← Commit history

Batch hero geometry from 23568 to 370 primitives without changing triangle positions or part layers

John Lauer ·01e65069c1 · ·parent 3562546
4 files changed +66
mechanical/side-fan-r1/batching-check.jsonadded+9
@@ -0,0 +1,9 @@+{+  "geometryAndNormalsExact": true,+  "nodesLayersTransformsExact": true,+  "materialsExact": true,+  "animationTargetsExact": true,+  "beforePrimitives": 23568,+  "afterPrimitives": 370,+  "scope": "Render batching only; no hardware qualification"+}
mechanical/side-fan-r1/side-fan-assembly.glb
⋯ 1 unchanged line ⋯
tools/batch_glb_primitives.pyadded+55
@@ -0,0 +1,55 @@+"""Batch primitives within each mesh/material; retain nodes, layers and animations."""+import copy,json,struct,sys+from pathlib import Path+import numpy as np+from glb_shape_helpers import read_glb,write_glb++def batch(g,blob):+ before=sum(len(m['primitives']) for m in g['meshes'])+ def read(ai):+  a=g['accessors'][ai];v=g['bufferViews'][a['bufferView']];dt={5126:'<f4',5125:'<u4',5123:'<u2',5121:'u1',5122:'<i2',5120:'i1'}[a['componentType']];n={'SCALAR':1,'VEC3':3,'VEC2':2,'VEC4':4}[a['type']];size=np.dtype(dt).itemsize+  arr = np.ndarray((a['count'],n),dtype=dt,buffer=blob,offset=v.get('byteOffset',0)+a.get('byteOffset',0),strides=(v.get('byteStride',size*n),size)).copy()+  if a.get('normalized'):+   info=np.iinfo(arr.dtype);arr=np.maximum(arr.astype(np.float32)/info.max,-1)+  return arr+ def add(arr,kind,ctype):+  blob.extend(b'\0'*(-len(blob)%4));off=len(blob);blob.extend(arr.tobytes());vi=len(g['bufferViews']);g['bufferViews'].append({'buffer':0,'byteOffset':off,'byteLength':arr.nbytes});a={'bufferView':vi,'componentType':ctype,'count':len(arr),'type':kind}+  if kind=='VEC3':a.update(min=arr.min(axis=0).tolist(),max=arr.max(axis=0).tolist())+  i=len(g['accessors']);g['accessors'].append(a);return i+ for m in g['meshes']:+  groups={}+  for p in m['primitives']:+   key=json.dumps({k:v for k,v in p.items() if k not in ['attributes','indices']},sort_keys=True)+str(sorted(p['attributes']))+   groups.setdefault(key,[]).append(p)+  out=[]+  for ps in groups.values():+   if len(ps)==1:out.extend(ps);continue+   attrs={k:[] for k in ps[0]['attributes']};indices=[];count=0+   for p in ps:+    for k,a in p['attributes'].items():attrs[k].append(read(a))+    ix=read(p['indices']).astype('<u4').reshape(-1)+count;indices.append(ix);count+=len(attrs['POSITION'][-1])+   p=copy.deepcopy(ps[0]);p['attributes']={k:add(np.concatenate(v).astype('<f4'),'VEC3',5126) for k,v in attrs.items()};p['indices']=add(np.concatenate(indices).astype('<u4'),'SCALAR',5125);out.append(p)+  m['primitives']=out+ # Repack only referenced views; removes superseded geometry without touching accessor ids.+ used=set()+ for m in g['meshes']:+  for p in m['primitives']:used.update(p['attributes'].values());used.add(p['indices'])+ for a in g.get('animations',[]):+  for s in a['samplers']:used.update([s['input'],s['output']])+ views={g['accessors'][a]['bufferView'] for a in used};new=bytearray()+ for i,v in enumerate(g['bufferViews']):+  if i in views:+   new.extend(b'\0'*(-len(new)%4));start=len(new);new.extend(blob[v.get('byteOffset',0):v.get('byteOffset',0)+v['byteLength']]);v['byteOffset']=start+  else:v.update(byteOffset=0,byteLength=0)+ # Drop unused accessors/views and remap all surviving references.+ amap={a:i for i,a in enumerate(sorted(used))};vmap={v:i for i,v in enumerate(sorted(views))}+ g['accessors']=[g['accessors'][a] for a in sorted(used)]+ for a in g['accessors']:a['bufferView']=vmap[a['bufferView']]+ g['bufferViews']=[g['bufferViews'][v] for v in sorted(views)]+ for m in g['meshes']:+  for p in m['primitives']:p['attributes']={k:amap[a] for k,a in p['attributes'].items()};p['indices']=amap[p['indices']]+ for a in g.get('animations',[]):+  for s in a['samplers']:s['input']=amap[s['input']];s['output']=amap[s['output']]+ return new,{'beforePrimitives':before,'afterPrimitives':sum(len(m['primitives']) for m in g['meshes'])}+if __name__=='__main__':+ p=Path(sys.argv[1]);g,b=read_glb(p);b,report=batch(g,b);write_glb(p,g,b);print(json.dumps(report))
tools/build_side_fan_candidate.py+2
@@ -119,6 +119,8 @@ for n,s,k in parts: g['asset']['extras']['scope']='Side fan cooling study, original nominal ATS sink model, reinforced carrier; not a released board or print design' from style_assembly_glb import style style(g)+from batch_glb_primitives import batch+blob, batching_report = batch(g,blob) write_glb(O/'side-fan-assembly.glb',g,blob);assy.save(str(O/'mechanical-candidate.step')) carrier=base for n,s,k in parts: