File size: 10,147 Bytes
8ca7ba0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
"""Carry verified source articulation graphs into the delivered house."""
import json
from pathlib import Path
import sys


def transfer_baked_surface(source_stage,native_stage,source_root,native_root):
    """Copy baked material/UVs by verified world-space face correspondence.

    Native points, topology, rigid bodies and collisions remain untouched.
    A failed or ambiguous correspondence is an export failure, not a fallback.
    """
    import numpy as np
    from scipy.spatial import cKDTree
    from pxr import Gf,Sdf,Usd,UsdGeom,UsdShade,UsdPhysics,Vt
    source_cache=UsdGeom.XformCache();native_cache=UsdGeom.XformCache()
    def points(stage_cache,p):
        xf=stage_cache.GetLocalToWorldTransform(p)
        return np.array([list(xf.Transform(Gf.Vec3d(v))) for v in UsdGeom.Mesh(p).GetPointsAttr().Get()])
    candidates=[]
    for p in Usd.PrimRange(source_stage.GetPrimAtPath(source_root)):
        if p.IsA(UsdGeom.Mesh):
            xyz=points(source_cache,p)
            if len(xyz):candidates.append((p,xyz,xyz.min(0),xyz.max(0)))
    records=[]
    for p in Usd.PrimRange(native_stage.GetPrimAtPath(native_root)):
        if not p.IsA(UsdGeom.Mesh) or UsdGeom.Imageable(p).ComputePurpose()=='guide':continue
        xyz=points(native_cache,p);matches=[]
        if not len(xyz):continue
        for q,coords,lo,hi in candidates:
            if max(abs(xyz.min(0)-lo).max(),abs(xyz.max(0)-hi).max())>.001:continue
            distance,ids=cKDTree(coords).query(xyz)
            reverse=cKDTree(xyz).query(coords)[0]
            error=max(float(distance.max()),float(reverse.max()))
            if error<=.001:matches.append((q,ids,error))
        if len(matches)!=1:raise ValueError('Baked/native visual correspondence is not unique: '+str(p.GetPath())+' '+str(len(matches)))
        q,ids,error=matches[0];sm=UsdGeom.Mesh(q);nm=UsdGeom.Mesh(p)
        shadow=q.GetAttribute('primvars:doNotCastShadows')
        if shadow and shadow.Get() is not None:p.CreateAttribute('primvars:doNotCastShadows',Sdf.ValueTypeNames.Bool).Set(shadow.Get())
        UsdGeom.Imageable(p).CreateVisibilityAttr(UsdGeom.Imageable(q).ComputeVisibility())
        physics_material=UsdShade.MaterialBindingAPI(p).ComputeBoundMaterial('physics')[0]
        if physics_material and physics_material.GetPrim().HasAPI(UsdPhysics.MaterialAPI):
            p.CreateRelationship('material:binding:physics').SetTargets([physics_material.GetPath()])
        coords=points(source_cache,q);tree=cKDTree(coords)
        canonical={i:min(tree.query_ball_point(v,1e-5)) for i,v in enumerate(coords)}
        ids=np.asarray([canonical[int(i)] for i in ids])
        src_idx=list(sm.GetFaceVertexIndicesAttr().Get());src_counts=list(sm.GetFaceVertexCountsAttr().Get())
        faces=[];offset=0;by_vertex={}
        for face,count in enumerate(src_counts):
            corners=list(range(offset,offset+count));verts={canonical[src_idx[k]] for k in corners};faces.append((verts,corners))
            for v in verts:by_vertex.setdefault(v,[]).append(face)
            offset+=count
        dst_idx=list(nm.GetFaceVertexIndicesAttr().Get());dst_counts=list(nm.GetFaceVertexCountsAttr().Get());corner_map=[];face_map=[];offset=0
        for count in dst_counts:
            mapped=[int(ids[v]) for v in dst_idx[offset:offset+count]];members=set(mapped)
            selected=sorted({f for v in members for f in by_vertex.get(v,[]) if faces[f][0].issubset(members)})
            if not selected:raise ValueError('Native face has no baked source correspondence')
            for v in mapped:
                choices=[k for f in selected for k in faces[f][1] if canonical[src_idx[k]]==v]
                if not choices:raise ValueError('Native UV corner has no source correspondence')
                corner_map.append(choices[0])
            face_map.append(selected);offset+=count
        uv_names=[]
        for uv in UsdGeom.PrimvarsAPI(q).GetPrimvars():
            if uv.GetTypeName() not in (Sdf.ValueTypeNames.TexCoord2fArray,Sdf.ValueTypeNames.Float2Array):continue
            values=uv.ComputeFlattened()
            if values is None:continue
            interpolation=uv.GetInterpolation()
            if interpolation=='faceVarying':mapped=[values[k] for k in corner_map]
            elif interpolation in ('vertex','varying'):mapped=[values[src_idx[k]] for k in corner_map]
            else:raise ValueError('Unsupported baked UV interpolation: '+str(interpolation))
            target=UsdGeom.PrimvarsAPI(p).CreatePrimvar(uv.GetPrimvarName(),uv.GetTypeName(),'faceVarying');target.Set(Vt.Vec2fArray(mapped));target.GetIndicesAttr().Clear();uv_names.append(uv.GetPrimvarName())
        base=UsdShade.MaterialBindingAPI(q).ComputeBoundMaterial()[0]
        source_materials=[str(base.GetPath()) if base else None]*len(faces)
        for subset in UsdGeom.Subset.GetAllGeomSubsets(sm):
            material=UsdShade.MaterialBindingAPI(subset.GetPrim()).ComputeBoundMaterial()[0]
            if material:
                for index in subset.GetIndicesAttr().Get():source_materials[index]=str(material.GetPath())
        physical_faces=[str(physics_material.GetPath()) if physics_material and physics_material.GetPrim().HasAPI(UsdPhysics.MaterialAPI) else None]*len(dst_counts)
        for subset in UsdGeom.Subset.GetAllGeomSubsets(nm):
            bound=UsdShade.MaterialBindingAPI(subset.GetPrim()).ComputeBoundMaterial('physics')[0]
            if bound and bound.GetPrim().HasAPI(UsdPhysics.MaterialAPI):
                for face in subset.GetIndicesAttr().Get():physical_faces[face]=str(bound.GetPath())
        groups={}
        for index,selected in enumerate(face_map):
            materials={source_materials[f] for f in selected}
            if len(materials)!=1 or None in materials:raise ValueError('Ambiguous baked face material')
            groups.setdefault((next(iter(materials)),physical_faces[index]),[]).append(index)
        # Block inherited source bindings/subsets when installing the baked skin.
        for subset in UsdGeom.Subset.GetAllGeomSubsets(nm):subset.GetPrim().SetActive(False)
        for i,((material,physical),indices) in enumerate(sorted(groups.items(),key=lambda item:str(item[0]))):
            if len(groups)==1:target=p
            else:
                subset=UsdGeom.Subset.Define(native_stage,str(p.GetPath())+'/RHGBaked_'+str(i));subset.CreateElementTypeAttr('face');subset.CreateFamilyNameAttr('materialBind');subset.CreateIndicesAttr(indices);target=subset.GetPrim()
            UsdShade.MaterialBindingAPI.Apply(target);target.CreateRelationship('material:binding').SetTargets([Sdf.Path(material)])
            if physical:target.CreateRelationship('material:binding:physics').SetTargets([Sdf.Path(physical)])
        records.append(dict(native_mesh=str(p.GetPath()),baked_mesh=str(q.GetPath()),world_geometry_error_m=error,uv_names=uv_names,materials=sorted({v[0] for v in groups}),physical_materials_preserved=sorted({v[1] for v in groups if v[1]}),native_geometry_modified=False))
    return records


def author_native(stage, source, output, paths, shared):
    from pxr import Sdf, Usd, UsdGeom, UsdPhysics
    from .rparena_v16 import material_assets, sha
    helpers=Path(__file__).resolve().parents[2]/'scripts/internal/scene_generation/real_assets'
    sys.path.insert(0,str(helpers))
    from native_scene_contract import validate
    check=validate(source)
    if not check['passed']:
        raise ValueError('Source native articulation gate is incomplete: '+str(check))
    receipt=json.loads((source/'native_articulation_verification.json').read_text())
    bindings=receipt.get('bindings',[])
    if not bindings:
        return dict(source_receipt_sha256=sha(source/'native_articulation_verification.json'),
                    instances=[],body_paths=[],joint_count=0)
    original=Usd.Stage.Open(str(source/receipt['active_runtime']))
    flat=original.Flatten()
    layer=Sdf.Layer.CreateNew(str(output/'native.usdc'))
    native=Usd.Stage.Open(layer)
    world=UsdGeom.Xform.Define(native,'/World').GetPrim();native.SetDefaultPrim(world)
    if not Sdf.CopySpec(flat,'/World/Native',layer,'/World/Native'):
        raise ValueError('Missing verified /World/Native subtree')
    layer.Save()
    textures=material_assets(native,output/'native.usdc',output,shared)
    records=[];bodies=[];joints=[]
    for binding in bindings:
        entity=binding['entity_id'];path=binding['instance']
        prim=native.GetPrimAtPath(path)
        if not prim:raise ValueError('Missing native instance: '+entity)
        movable=[p for p in Usd.PrimRange(prim) if p.IsA(UsdPhysics.Joint)
                 and not p.IsA(UsdPhysics.FixedJoint) and UsdPhysics.Joint(p).GetJointEnabledAttr().Get()]
        if len(movable)!=binding['movable_joint_count']:
            raise ValueError('Native joint denominator changed: '+entity)
        old=paths[entity]
        surfaces=transfer_baked_surface(stage,native,old,path) if (output/'baked-material-delivery.json').exists() else []
        native.OverridePrim(old).SetActive(False)
        paths[entity]=path
        owned=[str(p.GetPath()) for p in Usd.PrimRange(prim) if p.HasAPI(UsdPhysics.RigidBodyAPI)]
        bodies.extend(owned);joints.extend(str(p.GetPath()) for p in movable)
        records.append(dict(entity_id=entity,instance=path,disabled_static_prim=old,
                            movable_joint_count=len(movable),body_paths=owned,
                            source_sha256=binding['source_sha256']))
        records[-1]['baked_surface_transfer']=surfaces
    if len(joints)!=receipt['native_joint_denominator']:
        raise ValueError('Native joint total changed')
    layer.Save()
    stage.GetRootLayer().subLayerPaths.insert(0,'native.usdc')
    return dict(source_receipt_sha256=sha(source/'native_articulation_verification.json'),
                source_runtime_sha256=sha(source/receipt['active_runtime']),instances=records,
                body_paths=bodies,joint_paths=joints,joint_count=len(joints),texture_assets=textures,
                validation_scope='source_gate_preserved; delivered_stage_requires_physical_validation')