File size: 3,041 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import curation_paths as paths
import json,struct,os,hashlib,numpy as np,sys,xml.etree.ElementTree as ET
from multiprocessing import Pool
A=paths.A
CT={5126:np.float32}
def qmat(q):
    x,y,z,w=q; return np.array([[1-2*(y*y+z*z),2*(x*y-z*w),2*(x*z+y*w)],[2*(x*y+z*w),1-2*(x*x+z*z),2*(y*z-x*w)],[2*(x*z-y*w),2*(y*z+x*w),1-2*(x*x+y*y)]])
def nodemat(n):
    if "matrix" in n: return np.array(n["matrix"],dtype=float).reshape(4,4).T
    M=np.eye(4)
    t=n.get("translation",[0,0,0]); r=n.get("rotation",[0,0,0,1]); s=n.get("scale",[1,1,1])
    M[:3,:3]=qmat(r)@np.diag(s); M[:3,3]=t; return M
def read(path):
    b=open(path,"rb").read()
    if b[:4]!=b"glTF": raise ValueError("not_glb")
    off=12; js=None; binc=None
    while off<len(b):
        ln,ty=struct.unpack_from("<II",b,off); data=b[off+8:off+8+ln]
        if ty==0x4E4F534A: js=json.loads(data)
        elif ty==0x004E4942 and binc is None: binc=data
        off+=8+ln
    if "KHR_draco_mesh_compression" in json.dumps(js.get("extensionsUsed",[])) : raise ValueError("draco")
    pts=[]
    def posacc(i):
        a=js["accessors"][i]; bv=js["bufferViews"][a["bufferView"]]
        if a["componentType"]!=5126 or a["type"]!="VEC3": raise ValueError("pos_type")
        st=bv.get("byteStride",12); o=bv.get("byteOffset",0)+a.get("byteOffset",0); n=a["count"]
        arr=np.frombuffer(binc,dtype=np.uint8,count=(n-1)*st+12,offset=o)
        return np.lib.stride_tricks.as_strided(arr,shape=(n,12),strides=(st,1)).copy().view(np.float32).reshape(n,3).astype(float)
    def visit(ni,M):
        n=js["nodes"][ni]; M=M@nodemat(n)
        if "mesh" in n:
            for pr in js["meshes"][n["mesh"]]["primitives"]:
                P=posacc(pr["attributes"]["POSITION"]); pts.append(P@M[:3,:3].T+M[:3,3])
        for c in n.get("children",[]): visit(c,M)
    sc=js["scenes"][js.get("scene",0)]
    for ni in sc["nodes"]: visit(ni,np.eye(4))
    return np.concatenate(pts) if pts else None
def work(a):
    f=A+"/pc2/"+hashlib.md5(a["key"].encode()).hexdigest()+".npz"
    if os.path.exists(f): return 0
    P=[];err=""
    for p,sc in zip(a["paths"],a.get("scales") or [None]*len(a["paths"])):
        try:
            q=read(p)
            if q is not None: P.append(q*(np.array(sc) if sc else 1.0))
        except Exception as e: err=str(e)[:60]
    if not P: np.savez(f,key=a["key"],err=err or "no_mesh"); return 1
    P=np.concatenate(P); rng=np.random.default_rng(0)
    if len(P)>6000: P=P[rng.choice(len(P),6000,replace=False)]
    np.savez(f,key=a["key"],pts=P.astype(np.float32),err=err); return 0
if __name__=="__main__":
    os.makedirs(A+"/pc2",exist_ok=True)
    spec=json.load(open(A+"/pc_spec.json"))
    # attach urdf mesh scales
    for a in spec:
        if a["key"].startswith("U:"): a["scales"]=None
    with Pool(24) as p: r=p.map(work,spec,chunksize=8)
    import glob,collections as C
    c=C.Counter()
    for f in glob.glob(A+"/pc2/*.npz"):
        z=np.load(f,allow_pickle=True); c["pts" if "pts" in z.files else "fail:"+str(z["err"])]+=1
    print(dict(c))