File size: 4,959 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import curation_paths as paths
import json,os,math,numpy as np,collections as C,itertools,sys,xml.etree.ElementTree as ET,sqlite3
sys.path.insert(0,paths.AUDIT_SCRIPTS)
from glbpts import read
from urdfunion import rpy,T
A=paths.A
def rots():
    out=[]
    for p in itertools.permutations(range(3)):
        for s in itertools.product((1,-1),repeat=3):
            M=np.zeros((3,3))
            for i in range(3): M[i,p[i]]=s[i]
            if np.linalg.det(M)>0: out.append(M)
    return out
R24=rots()
Cg=np.array([[1,0,0],[0,0,-1],[0,1,0]],float)       # glTF Y-up -> canonical Z-up (HSSD registry transform)
db=sqlite3.connect("file:"+paths.L+"/full_matrix_reviewed_compatibility_v3.sqlite3?mode=ro",uri=True)
upath={a:json.loads(rj).get("canonical_path") for a,rj in db.execute("select asset_id,record_json from assets where asset_id like 'hssd:urdf/%'")}
match=json.load(open(A+"/pc_match.json"))
good=[m for m in match if m.get("chamfer") is not None and m["chamfer"]<=0.005]
print("pairs with chamfer<=0.005:",len(good),"distinct urdf",len({m['urdf'] for m in good}),"distinct static",len({m['static'] for m in good}))
cache={}
def motions(uid):
    """return list of (kind, direction_in_urdf_root_frame, weight) at zero pose"""
    if uid in cache: return cache[uid]
    path=upath[uid]; root=ET.parse(path).getroot(); base=os.path.dirname(path)
    joints={}
    for j in root.findall("joint"):
        lm=j.find("limit"); ax=j.find("axis")
        joints[j.find("child").get("link")]=dict(parent=j.find("parent").get("link"),M=T(j.find("origin")),type=j.get("type"),
            axis=np.array([float(v) for v in ax.get("xyz").split()]) if ax is not None else None,
            lo=float(lm.get("lower")) if lm is not None and lm.get("lower") else 0.0,up=float(lm.get("upper")) if lm is not None and lm.get("upper") else 0.0)
    def world(l,g=0):
        if l not in joints or g>12: return np.eye(4)
        return world(joints[l]["parent"],g+1)@joints[l]["M"]
    links={l.get("name"):l for l in root.findall("link")}
    def link_pts(l):
        pts=[]; W=world(l)
        for v in links[l].findall("visual"):
            m=v.find("geometry/mesh")
            if m is None: continue
            f=os.path.join(base,m.get("filename"))
            if not os.path.exists(f): continue
            P=read(f)
            if P is None: continue
            P=P*np.array([float(x) for x in (m.get("scale") or "1 1 1").split()]); M=W@T(v.find("origin")); pts.append(P@M[:3,:3].T+M[:3,3])
        return np.concatenate(pts) if pts else None
    out=[]
    for child,j in joints.items():
        if j["type"] not in("prismatic","revolute") or j["axis"] is None: continue
        s=1.0 if abs(j["up"])>=abs(j["lo"]) and j["up"]!=0 else (-1.0 if j["lo"]!=0 else 0.0)
        if s==0: continue
        Wp=world(j["parent"])@j["M"]; a=Wp[:3,:3]@j["axis"]; a/=max(np.linalg.norm(a),1e-9)
        if j["type"]=="prismatic": out.append(("drawer",s*a,Wp[:3,3]))
        else:
            P=link_pts(child)
            if P is None: continue
            out.append(("door",(s*a,P.mean(0),Wp[:3,3]),None))
    cache[uid]=out; return out
def front_for(uid,M):
    votes=C.Counter(); n={"drawer":0,"door":0}
    for kind,d,h in motions(uid):
        if kind=="drawer": dc=Cg@(M@d)
        else:
            a,c,hp=d; r=c-hp; mv=np.cross(a,r)             # motion of the door centroid for positive opening
            if np.linalg.norm(mv)<1e-9: continue
            ac=Cg@(M@(a/np.linalg.norm(a)))
            if abs(ac[2])<0.7: continue                     # only vertical hinges
            dc=Cg@(M@mv)
        dc=np.array(dc,float); dc[2]=0
        if np.linalg.norm(dc)<0.5*np.linalg.norm(Cg@(M@(d if kind=="drawer" else mv))): continue   # mostly vertical motion
        k=("+" if (dc[0] if abs(dc[0])>abs(dc[1]) else dc[1])>0 else "-")+("X" if abs(dc[0])>abs(dc[1]) else "Y")
        votes[k]+=1; n[kind]+=1
    return votes,n
by_static=C.defaultdict(list)
for m in good:
    try: v,n=front_for(m["urdf"],R24[m["rot"]])
    except Exception as e: continue
    if not v: continue
    top,c=v.most_common(1)[0]
    by_static[m["static"]].append(dict(urdf=m["urdf"],axis=top,share=round(c/sum(v.values()),2),votes=dict(v),n=n,chamfer=m["chamfer"]))
out=[]
for s,L in by_static.items():
    ax=C.Counter(x["axis"] for x in L); top,c=ax.most_common(1)[0]
    out.append(dict(static=s,front_axis=top,n_urdf=len(L),agree=c/len(L),min_share=min(x["share"] for x in L),support=L))
json.dump(out,open(A+"/static_front_from_urdf.json","w"))
print("static assets with transferred front:",len(out))
print("axis distribution:",dict(C.Counter(o["front_axis"] for o in out)))
print("urdf-agreement: all-agree",sum(1 for o in out if o["agree"]==1.0),"; within-asset door/drawer consistency (min_share==1):",sum(1 for o in out if o["min_share"]==1.0))
print("with both drawer and door votes:",sum(1 for o in out if any(x["n"]["drawer"] and x["n"]["door"] for x in o["support"])))