main
John Lauer Batch hero geometry from 23568 to 370 primitives without changing triangle positions or part layers 01e6506
"""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))