File size: 15,455 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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
"""Deterministic native-joint inspection and packaging. No model or category inference."""
from __future__ import annotations

import hashlib
import json
import math
import shutil
from pathlib import Path
from typing import Any


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open('rb') as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b''):
            digest.update(block)
    return digest.hexdigest()


def inspect_native(path: Path) -> dict[str, Any]:
    from pxr import Usd, UsdGeom, UsdPhysics

    path = Path(path).resolve()
    stage = Usd.Stage.Open(str(path))
    if stage is None:
        raise ValueError(f'Cannot open native USD: {path}')
    joints, issues = [], []
    for prim in stage.Traverse():
        if not prim.IsA(UsdPhysics.Joint):
            continue
        joint = UsdPhysics.Joint(prim)
        kind = prim.GetTypeName()
        body0 = list(map(str, joint.GetBody0Rel().GetTargets()))
        body1 = list(map(str, joint.GetBody1Rel().GetTargets()))
        row = {'path': str(prim.GetPath()), 'type': kind, 'body0': body0, 'body1': body1,
               'enabled': bool(joint.GetJointEnabledAttr().Get()),
               'local_pos0': list(joint.GetLocalPos0Attr().Get()),
               'local_pos1': list(joint.GetLocalPos1Attr().Get())}
        for side in (0, 1):
            q = getattr(joint, f'GetLocalRot{side}Attr')().Get()
            row[f'local_rot{side}_wxyz'] = [float(q.GetReal()), *map(float, q.GetImaginary())]
        if len(body1) != 1 or len(body0) > 1 or any(not stage.GetPrimAtPath(p) for p in body0 + body1):
            issues.append('invalid_joint_bodies:' + row['path'])
        movable = kind in ('PhysicsRevoluteJoint', 'PhysicsPrismaticJoint')
        row['movable'] = movable
        if movable:
            typed = UsdPhysics.RevoluteJoint(prim) if kind == 'PhysicsRevoluteJoint' else UsdPhysics.PrismaticJoint(prim)
            lower, upper = float(typed.GetLowerLimitAttr().Get()), float(typed.GetUpperLimitAttr().Get())
            axis = str(typed.GetAxisAttr().Get())
            row.update(axis=axis, lower=lower if math.isfinite(lower) else None,
                       upper=upper if math.isfinite(upper) else None,
                       unit='degrees' if kind == 'PhysicsRevoluteJoint' else 'stage_units')
            if not all(map(math.isfinite, (lower, upper))) or lower >= upper or axis not in ('X', 'Y', 'Z'):
                issues.append('invalid_joint_limits_or_axis:' + row['path'])
            drive_name = 'angular' if kind == 'PhysicsRevoluteJoint' else 'linear'
            drive = UsdPhysics.DriveAPI(prim, drive_name)
            row['has_native_drive'] = bool(drive)
        elif kind != 'PhysicsFixedJoint':
            issues.append('unsupported_joint_type:' + row['path'])
        joints.append(row)
    movable_count = sum(j['movable'] and j['enabled'] for j in joints)
    units, up = UsdGeom.GetStageMetersPerUnit(stage), str(UsdGeom.GetStageUpAxis(stage))
    if movable_count and (abs(units - 1.) > 1e-8 or up != 'Z'):
        issues.append('requires_offline_metric_z_up_conversion')
    if not stage.GetDefaultPrim():
        issues.append('missing_default_prim')
    layers = {str(Path(layer.realPath).resolve()): sha256(Path(layer.realPath))
              for layer in stage.GetUsedLayers() if layer.realPath and Path(layer.realPath).is_file()}
    return {'schema': 'rhg.native_articulation.v1', 'source_path': str(path),
            'source_sha256': sha256(path), 'source_layer_sha256': layers,
            'default_prim': str(stage.GetDefaultPrim().GetPath()) if stage.GetDefaultPrim() else None,
            'meters_per_unit': units, 'up_axis': up, 'joints': joints,
            'movable_joint_count': movable_count, 'issues': issues,
            'status': 'native_ready_for_physics' if movable_count and not issues else
                      'native_requires_review' if movable_count else 'static_no_native_joints',
            'physics_qualified': False, 'llm_calls': 0, 'joint_generation': 'none_preserve_source'}


def prepare_native(path: Path, out: Path) -> dict[str, Any]:
    """Seal composed USD and local asset dependencies without rewriting joints."""
    from pxr import Sdf, Usd

    path, out = Path(path).resolve(), Path(out).resolve()
    if out.is_relative_to(path.parent):
        raise ValueError('Native preparation output must be outside the source directory')
    inspection = inspect_native(path)
    out.mkdir(parents=True, exist_ok=False)
    if inspection['status'] != 'native_ready_for_physics':
        (out / 'receipt.json').write_text(json.dumps(inspection, indent=2))
        return inspection
    # Articulated asset folders carry MDL-local textures as well as USD layers.
    # Keep their relative layout; independently renaming MDL files breaks imports.
    shutil.copytree(path.parent, out / 'source')
    stage = Usd.Stage.Open(str(out / 'source' / path.name))
    flattened = stage.Flatten()
    target = out / 'native.usdc'
    flattened.Export(str(target))
    packaged = Usd.Stage.Open(str(target))
    dependencies, unresolved = {}, set()

    def copy_asset(value):
        if not isinstance(value, Sdf.AssetPath) or not value.path:
            return value
        original = Path(value.resolvedPath or value.path)
        if not original.is_absolute():
            original = path.parent / original
        if not original.is_file():
            unresolved.add(value.path)
            return value
        digest = sha256(original)
        if original.is_relative_to(out):
            relative = original.relative_to(out)
            dependencies[str(relative)] = digest
            return Sdf.AssetPath(relative.as_posix())
        relative = Path('resources') / (digest + original.suffix)
        destination = out / relative
        destination.parent.mkdir(exist_ok=True)
        if not destination.exists():
            shutil.copyfile(original, destination)
        dependencies[str(relative)] = digest
        return Sdf.AssetPath(relative.as_posix())

    for prim in packaged.Traverse():
        for attr in prim.GetAttributes():
            value = attr.Get()
            if isinstance(value, Sdf.AssetPath):
                attr.Set(copy_asset(value))
            elif attr.GetTypeName() == Sdf.ValueTypeNames.AssetArray and value:
                attr.Set([copy_asset(item) for item in value])
    packaged.GetRootLayer().Save()
    dependencies.update({str(p.relative_to(out)): sha256(p) for p in (out / 'source').rglob('*') if p.is_file()})
    saved = inspect_native(target)
    if saved['joints'] != inspection['joints']:
        raise ValueError('Packaging changed native joint definitions')
    inspection.update(runtime_path='native.usdc', runtime_sha256=sha256(target),
                      resource_sha256=dependencies, unresolved_visual_assets=sorted(unresolved),
                      joint_definitions_preserved=True, physical_geometry='native_source_colliders')
    (out / 'receipt.json').write_text(json.dumps(inspection, indent=2))
    return inspection


def resolve_joint_frame(stage, joint, side, cache=None):
    """Resolve one frame using OpenUSD 25.11 parseUtils::_GetLocalPose rules.

    Direct schema access avoids the unstable bulk Python physics-parser callback.
    Reference: https://github.com/PixarAnimationStudios/OpenUSD/blob/v25.11/pxr/usd/usdPhysics/parseUtils.cpp
    """
    from pxr import Gf, UsdGeom, UsdPhysics
    cache = cache or UsdGeom.XformCache()
    position = Gf.Vec3f(getattr(joint, f'GetLocalPos{side}Attr')().Get())
    rotation = Gf.Quatf(getattr(joint, f'GetLocalRot{side}Attr')().Get()).GetNormalized()
    targets = getattr(joint, f'GetBody{side}Rel')().GetTargets()
    if not targets:
        return None, position, rotation
    if len(targets) != 1:
        raise ValueError('Ambiguous native joint relationship')
    target = stage.GetPrimAtPath(targets[0])
    if not target:
        raise ValueError('Missing native joint target: '+str(targets[0]))
    actor, collision = target, None
    while actor and actor != stage.GetPseudoRoot():
        if actor.HasAPI(UsdPhysics.RigidBodyAPI):
            break
        if actor.HasAPI(UsdPhysics.CollisionAPI):
            collision = actor
        actor = actor.GetParent()
    if not actor or actor == stage.GetPseudoRoot():
        actor = collision
    target_world = cache.GetLocalToWorldTransform(target)
    actor_world = cache.GetLocalToWorldTransform(actor) if actor else Gf.Matrix4d(1.)
    if target != actor:
        local = Gf.Matrix4d(1.)
        local.SetRotate(Gf.Quatd(rotation))
        local.SetTranslateOnly(Gf.Vec3d(position))
        relative = (local*target_world*actor_world.GetInverse()).RemoveScaleShear()
        position = Gf.Vec3f(relative.ExtractTranslation())
        rotation = Gf.Quatf(relative.ExtractRotationQuat()).GetNormalized()
    scale = Gf.Vec3f(Gf.Transform(actor_world if target != actor else target_world).GetScale())
    position = Gf.Vec3f(*(position[i]*scale[i] for i in range(3)))
    return str(actor.GetPath()) if actor else None, position, rotation


def bind_native(stage, path: Path, prim_path: str, matrix=None, anchor_frame_mode='authored_matrix') -> dict[str, Any]:
    """Reference the complete native graph. Rebase world-fixed anchors after placement."""
    from pxr import Gf, UsdGeom

    source = inspect_native(path)
    if source['status'] != 'native_ready_for_physics':
        raise ValueError('Asset lacks supported native joints: ' + str(path))
    root = UsdGeom.Xform.Define(stage, prim_path)
    root.GetPrim().GetReferences().AddReference(str(Path(path).resolve()))
    if matrix is not None:
        matrix=Gf.Matrix4d(matrix)
        basis=[[float(matrix[i][j]) for j in range(3)] for i in range(3)]
        if (abs(matrix.GetDeterminant()-1.)>1e-6 or
                any(abs(sum(basis[i][k]*basis[j][k] for k in range(3))-(1. if i==j else 0.))>1e-6
                    for i in range(3) for j in range(3))):
            raise ValueError('Native joints require rigid placement; pre-scale assets offline')
        root.AddTransformOp().Set(matrix)
    rebased = rebase_world_fixed_joints(stage, root.GetPrim(), anchor_frame_mode)
    return {'instance': prim_path, 'source_sha256': source['source_sha256'],
            'movable_joint_count': source['movable_joint_count'], 'rebased_world_fixed_joints': rebased,
            'joint_generation': 'none_preserve_source', 'anchor_frame_mode':anchor_frame_mode, 'llm_calls': 0}


def rebase_world_fixed_joints(stage, root_prim, anchor_frame_mode='authored_matrix') -> list[str]:
    """Keep native fixed bases at their placed poses, including nonzero local frames."""
    from pxr import Gf, Usd, UsdGeom, UsdPhysics
    cache = UsdGeom.XformCache()
    if anchor_frame_mode not in {'authored_matrix','rigid_pose'}:
        raise ValueError('Unknown native fixed-anchor frame mode')
    root_path = root_prim.GetPath()
    rebased = []
    for prim in Usd.PrimRange(root_prim):
        if not prim.IsA(UsdPhysics.Joint):
            continue
        joint = UsdPhysics.Joint(prim)
        for relationship in (joint.GetBody0Rel(), joint.GetBody1Rel()):
            if any(not target.HasPrefix(root_path) for target in relationship.GetTargets()):
                raise ValueError('Native joint escaped its instance: ' + str(prim.GetPath()))
        if prim.IsA(UsdPhysics.FixedJoint) and not joint.GetBody0Rel().GetTargets():
            body = stage.GetPrimAtPath(joint.GetBody1Rel().GetTargets()[0])
            local = Gf.Matrix4d(1.)
            local.SetRotate(Gf.Quatd(joint.GetLocalRot1Attr().Get()))
            local.SetTranslateOnly(Gf.Vec3d(joint.GetLocalPos1Attr().Get()))
            anchor = local * cache.GetLocalToWorldTransform(body)
            joint.GetLocalPos0Attr().Set(Gf.Vec3f(anchor.ExtractTranslation()))
            rotation = anchor.ExtractRotationQuat()
            if anchor_frame_mode == 'rigid_pose':
                world = cache.GetLocalToWorldTransform(body)
                basis = [Gf.Vec3d(*(float(world[i][j]) for j in range(3))) for i in range(3)]
                is_rigid = (abs(world.GetDeterminant()-1.)<1e-6 and
                    all(abs(Gf.Dot(basis[i],basis[j])-(1. if i==j else 0.))<1e-6
                        for i in range(3) for j in range(3)))
                if not is_rigid:
                    # Points retain scale, while joint rotations use the rigid
                    # orientation of the relationship target, as USD physics does.
                    rigid_world = Gf.Matrix4d(1.)
                    rigid_world.SetRotate(Gf.Transform(world).GetRotation())
                    rotation = (local*rigid_world).ExtractRotationQuat().GetNormalized()
            joint.GetLocalRot0Attr().Set(Gf.Quatf(rotation))
            rebased.append(str(prim.GetPath()))
    return rebased


def bind_from_catalog(stage, catalog_path: Path, asset_id: str, prim_path: str, matrix=None):
    """Online reuse of a sealed, motion-verified asset; never generate a joint online."""
    catalog_path=Path(catalog_path).resolve()
    catalog=json.loads(catalog_path.read_text())
    if catalog.get('schema')!='rhg.native_articulation_acceptance_catalog.v1' or not catalog.get('complete'):
        raise ValueError('Incomplete native-articulation catalog')
    rows=[r for r in catalog['records'] if r['asset_id']==asset_id]
    if len(rows)!=1 or rows[0].get('joint_motion_qualified') is not True:
        raise ValueError('Asset has no verified native-joint motion: '+asset_id)
    row=rows[0]
    def resolve(relative):
        path=(catalog_path.parent/relative).resolve()
        if not path.is_relative_to(catalog_path.parent):
            raise ValueError('Catalog path escapes its bundle')
        return path
    bundle=resolve(row['bundle']);receipt_path=bundle/'receipt.json'
    report_path=resolve(row['report'])
    if sha256(receipt_path)!=row['receipt_sha256'] or sha256(report_path)!=row['report_sha256']:
        raise ValueError('Native asset receipt changed')
    receipt=json.loads(receipt_path.read_text());report=json.loads(report_path.read_text())
    runtime=resolve(str(Path(row['bundle'])/receipt['runtime_path']))
    if (not report.get('passed') or report.get('negative_control') or report.get('diagnostic_only') or
            report.get('joint_denominator')!=row['movable_joint_count'] or
            report.get('source_sha256')!=row['source_sha256'] or
            report.get('runtime_sha256')!=receipt['runtime_sha256'] or
            sha256(runtime)!=receipt['runtime_sha256']):
        raise ValueError('Native asset motion acceptance mismatch')
    if (row.get('validation_protocol',{}).get('source_floor_contact_required') and
            not report.get('floor_contact_included')):
        raise ValueError('Native source qualification requires measured floor contact')
    for name,digest in receipt['resource_sha256'].items():
        dependency=resolve(str(Path(row['bundle'])/name))
        if sha256(dependency)!=digest:raise ValueError('Native asset dependency changed: '+name)
    for name,digest in report['evidence_sha256'].items():
        evidence=resolve(str(Path(row['report']).parent/name))
        if sha256(evidence)!=digest:raise ValueError('Native physics evidence changed: '+name)
    return bind_native(stage,runtime,prim_path,matrix,
        row.get('validation_protocol',{}).get('anchor_frame_mode','authored_matrix'))