File size: 59,620 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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
"""Export v16 scenes without changing the retired asset-first adapter."""
from __future__ import annotations

import argparse
from contextlib import contextmanager
import hashlib
import json
import math
import os
from pathlib import Path
import resource
import re
import shutil
import subprocess
import time
import traceback


def read(path):
    return json.loads(Path(path).read_text(encoding='utf-8'))


def write(path, value):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_suffix(path.suffix + '.tmp')
    temporary.write_text(json.dumps(value, indent=2, ensure_ascii=False) + '\n', encoding='utf-8')
    temporary.replace(path)


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


@contextmanager
def timed(records, name, output):
    started = time.time()
    row = dict(stage=name, started_at=started, status='running', gpu_s=None,
               gpu_accounting='未采样;不以 wall time 冒充 GPU·s')
    records.append(row)
    write(output / 'timing.json', records)
    try:
        yield row
        row['status'] = 'completed'
    except Exception as error:
        row.update(status='failed', error=str(error), traceback=traceback.format_exc())
        raise
    finally:
        row.update(wall_s=time.time() - started,
                   process_peak_rss_bytes=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * 1024,
                   children_peak_rss_bytes=resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss * 1024,
                   output_bytes=sum(path.stat().st_size for path in output.rglob('*') if path.is_file()))
        write(output / 'timing.json', records)


def material_assets(stage, source, package, shared):
    from pxr import Sdf, UsdUtils
    layers, assets, unresolved = UsdUtils.ComputeAllDependencies(str(source))
    if unresolved:
        raise ValueError('USD 引用未解析:' + str(unresolved))
    if len(layers) != 1:
        raise ValueError('视觉入口含多层 USD;须先明确各层变换和引用,禁止静默 flatten')
    copied = []
    for prim in stage.Traverse():
        for attribute in prim.GetAttributes():
            if attribute.GetTypeName() not in (Sdf.ValueTypeNames.Asset, Sdf.ValueTypeNames.AssetArray):
                continue
            value = attribute.Get()
            if value is None:
                continue
            values = list(value) if attribute.GetTypeName() == Sdf.ValueTypeNames.AssetArray else [value]
            replacements = []
            for item in values:
                if not item.path:
                    replacements.append(item)
                    continue
                path = Path(item.resolvedPath or str(source.parent / item.path)).resolve()
                if not path.is_file():
                    raise FileNotFoundError('材质缺失,需针对缺失材质烘焙:' + str(path))
                identity = sha(path)
                relative = 'assets/' + identity + path.suffix.lower()
                intern(path, package / relative, shared / (identity + path.suffix.lower()))
                replacements.append(Sdf.AssetPath(relative))
                copied.append(dict(source=str(path), path=relative, sha256=identity))
            attribute.Set(replacements if attribute.GetTypeName() == Sdf.ValueTypeNames.AssetArray else replacements[0])
    return copied


def intern(source, destination, cached):
    cached.parent.mkdir(parents=True, exist_ok=True)
    destination.parent.mkdir(parents=True, exist_ok=True)
    if destination.exists():
        if sha(destination) != sha(source):
            raise ValueError('目标已存在且内容不同:' + str(destination))
        return
    if not cached.exists():
        temporary = cached.with_name(cached.name + '.' + str(os.getpid()) + '.tmp')
        shutil.copyfile(source, temporary)
        try:
            os.link(temporary, cached)
        except FileExistsError:
            pass
        temporary.unlink()
    if sha(cached) != sha(source):
        raise ValueError('内容缓存身份不一致:' + str(cached))
    try:
        os.link(cached, destination)
    except OSError:
        shutil.copyfile(cached, destination)


def deduplicate_geometry(stage, package, shared):
    from pxr import Sdf, Usd, UsdGeom
    rows = []
    for prim in list(stage.Traverse()):
        if not prim.IsA(UsdGeom.Mesh) or prim.IsInstanceProxy():
            continue
        geometry = Usd.Stage.CreateInMemory()
        mesh = UsdGeom.Mesh.Define(geometry, '/Geometry')
        names = []
        for attribute in prim.GetAttributes():
            name = attribute.GetName()
            if name.startswith(('xformOp', 'material:', 'physics:', 'physx', 'rhg:', 'userProperties:')) or name in ('visibility', 'purpose'):
                continue
            if attribute.GetNumTimeSamples():
                raise ValueError('静态 v16 包不允许动画网格:' + str(prim.GetPath()))
            if attribute.HasAuthoredValueOpinion():
                target = mesh.GetPrim().CreateAttribute(name, attribute.GetTypeName(), attribute.IsCustom(), attribute.GetVariability())
                target.Set(attribute.Get())
                for key, value in attribute.GetAllMetadata().items():
                    if key not in ('typeName', 'custom', 'variability', 'default'):
                        target.SetMetadata(key, value)
                names.append(name)
        identity = hashlib.sha256(geometry.GetRootLayer().ExportToString().encode()).hexdigest()
        cached = shared / (identity + '.usdc')
        if not cached.exists():
            temporary = shared / (identity + '.' + str(os.getpid()) + '.usdc')
            geometry.GetRootLayer().Export(str(temporary))
            try:
                os.link(temporary, cached)
            except FileExistsError:
                pass
            temporary.unlink()
        destination = package / 'assets' / cached.name
        if not destination.exists():
            intern(cached, destination, cached)
        for name in names:
            prim.RemoveProperty(name)
        prim.GetReferences().AddReference('assets/' + cached.name, '/Geometry')
        rows.append(dict(prim_path=str(prim.GetPath()), geometry_content_sha256=identity,
                         file_sha256=sha(destination), bytes=destination.stat().st_size))
    return rows


def group_roots(stage, roots, name):
    from pxr import Usd, UsdGeom
    if not roots:
        raise ValueError('没有可分组的几何节点:' + name)
    parents = {path.GetParentPath() for path in roots}
    if len(parents) != 1:
        raise ValueError('实体几何跨越不同变换父节点,需显式处理:' + name)
    parent = next(iter(parents))
    group = parent.AppendChild(name)
    if stage.GetPrimAtPath(group):
        raise ValueError('分组节点冲突:' + str(group))
    UsdGeom.Xform.Define(stage, group)
    for path in roots:
        editor = Usd.NamespaceEditor(stage)
        editor.MovePrimAtPath(path, group.AppendChild(path.name))
        if not editor.CanApplyEdits():
            raise ValueError('USD namespace 编辑无法保留依赖:' + str(path))
        editor.ApplyEdits()
    return group


def entity_paths(stage, manifest):
    paths = {}
    for entity in manifest['entities']:
        identity = entity['entity_id']
        matches = []
        for prim in stage.Traverse():
            values = [prim.GetName()]
            values += [str(attribute.Get()) for attribute in prim.GetAttributes()
                       if attribute.GetName().endswith(('entity_id', 'object_name'))]
            if identity in values or any(identity in value for value in values):
                matches.append(prim.GetPath())
        roots = [path for path in matches if not any(path != parent and path.HasPrefix(parent) for parent in matches)]
        if not roots:
            raise ValueError(f'实体没有对应的 USD 几何:{identity}')
        paths[identity] = str(roots[0] if len(roots) == 1 else group_roots(stage, roots, 'rparena_entity_' + identity))
    return paths


def luna_scene_namespace(stage):
    """对齐冻结 Luna 驱动的碰撞路径约定,只改变节点路径。"""
    from pxr import UsdGeom
    world = stage.GetPrimAtPath('/World')
    if stage.GetPrimAtPath('/World/SceneSmith'):
        raise ValueError('源已有SceneSmith命名空间;需显式核对,禁止重复包裹')
    scene = group_roots(stage, [prim.GetPath() for prim in world.GetChildren()], 'SceneSmith')
    floors = [prim.GetPath() for prim in stage.GetPrimAtPath(scene).GetChildren()
              if prim.GetName().startswith(('floor__','floor_connection__'))]
    if not floors:
        raise ValueError('没有v16 floor__地板;不能伪造Luna地板绑定')
    shell = group_roots(stage, floors, 'shell_floor')
    floor = group_roots(stage, [prim.GetPath() for prim in stage.GetPrimAtPath(shell).GetChildren()], 'Cube')
    stage.GetRootLayer().Save()
    return dict(scene_root=str(scene), floor_path=str(floor),
                geometry_changed=False, driver_contract='frozen_luna_wheel_run_paths')


def luna_scene_entry(package, base):
    from pxr import Sdf, Usd, UsdGeom
    path = package / 'scenesmith/scene.usdc'
    path.parent.mkdir(parents=True, exist_ok=True)
    layer = Sdf.Layer.CreateNew(str(path))
    layer.subLayerPaths = [base]
    layer.defaultPrim = 'World'
    layer.Save()
    stage = Usd.Stage.Open(layer)
    UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
    UsdGeom.SetStageMetersPerUnit(stage, 1.0)
    stage.GetRootLayer().Save()
    return 'scenesmith/scene.usdc'


def mass_evidence(entity):
    candidates = [(entity, 'SceneManifest.entity')]
    for key in ('physics', 'physical_properties', 'metadata'):
        if isinstance(entity.get(key), dict):
            candidates.append((entity[key], 'SceneManifest.entity.' + key))
    for values, source in candidates:
        value = values.get('mass_kg')
        if isinstance(value, (float, int)) and not isinstance(value, bool) and math.isfinite(value) and value > 0:
            return float(value), source
    return None, '原始实体和物理元数据未提供质量;禁止臆造'


def author_physics(stage, output, manifest, episode, paths):
    from pxr import Gf, Sdf, Usd, UsdGeom, UsdPhysics
    layer = Sdf.Layer.CreateNew(str(output / 'physics.usda'))
    stage.GetRootLayer().subLayerPaths.insert(0, 'physics.usda')
    stage.SetEditTarget(layer)
    physics_scene = UsdPhysics.Scene.Define(stage, '/World/PhysicsScene')
    physics_scene.CreateGravityDirectionAttr(Gf.Vec3f(0, 0, -1))
    physics_scene.CreateGravityMagnitudeAttr(9.81)
    binding = episode.get('bindings', {}).get('pickup_object', {})
    pickup = binding.get('entity_id')
    entity = next((row for row in manifest['entities'] if row['entity_id'] == pickup), None)
    mass, source = mass_evidence(entity or {})
    if entity is None:
        raise ValueError('BenchmarkEpisode 缺少原生 pickup_object 绑定')
    root = stage.GetPrimAtPath(paths[pickup])
    if mass is not None:
        UsdPhysics.RigidBodyAPI.Apply(root).CreateRigidBodyEnabledAttr(True)
        UsdPhysics.MassAPI.Apply(root).CreateMassAttr(mass)
    excluded = []
    for prim in stage.Traverse():
        if prim.IsA(UsdGeom.Mesh):
            ancestor = prim
            hardware = False
            source_guide = False
            while ancestor and ancestor.GetPath() != Sdf.Path.absoluteRootPath:
                kind=ancestor.GetAttribute('rhg:kind')
                if kind and kind.Get()=='door_swing_keepout_v9':
                    source_guide=True
                    break
                if ancestor.GetName().startswith(('door_hinge_pin__','door_hinge_plate__','door_hinge_continuous_bridge__','door_leaf_hinge_strap__','door_leaf_detail__')):
                    hardware = True
                    break
                ancestor = ancestor.GetParent()
            if hardware or source_guide:
                UsdPhysics.CollisionAPI.Apply(prim).CreateCollisionEnabledAttr(False)
                excluded.append(str(prim.GetPath()))
                continue
            if 'pmp20_window_backdrop_' in str(prim.GetPath()):
                UsdPhysics.CollisionAPI.Apply(prim).CreateCollisionEnabledAttr(False)
                excluded.append(str(prim.GetPath()))
                continue
            UsdPhysics.CollisionAPI.Apply(prim).CreateCollisionEnabledAttr(True)
            dynamic = prim.GetPath().HasPrefix(root.GetPath()) and mass is not None
            UsdPhysics.MeshCollisionAPI.Apply(prim).CreateApproximationAttr('convexHull' if dynamic else 'none')
            prim.AddAppliedSchema('PhysxCollisionAPI')
            prim.CreateAttribute('physxCollision:contactOffset', Sdf.ValueTypeNames.Float).Set(0.001)
            prim.CreateAttribute('physxCollision:restOffset', Sdf.ValueTypeNames.Float).Set(0.0)
    layer.Save()
    stage.SetEditTarget(stage.GetRootLayer())
    return dict(pickup_entity_id=pickup, mass_kg=mass, mass_source=source,
                dynamic_authored=mass is not None,
                excluded_attachment_colliders=excluded,
                blockers=[] if mass is not None else ['native_mass_metadata_missing'])


def author_doors(stage, source, output, *, preserve_source_runtime=False):
    from pxr import Gf, Sdf, Usd, UsdGeom, UsdPhysics
    receipt = read(source / 'door_physics_verification.json')
    if receipt.get('schema') != 'rhg.house_door_gate.v1' or receipt.get('passed') is not True:
        raise ValueError('源门 PhysX 门控没有通过')
    expected = receipt.get('evidence_sha256', {})
    required = {'door_physics/input.json.gz','door_physics/mesh_sweep.json',
                'door_physics/runtime/report.json','door_physics/runtime/trace.json',
                'door_physics/runtime/articulated_scene.usdc'}
    if not required.issubset(expected):
        raise ValueError('源门控缺少完整证据集合')
    if sha(source / (source.name + '.blend')) != receipt.get('source_blend_sha256'):
        raise ValueError('源 blend 与门控通过时的身份不一致')
    for name, digest in expected.items():
        path = (source / name).resolve()
        if not path.is_relative_to(source) or sha(path) != digest:
            raise ValueError('门控证据缺失或已变化:' + name)
    import gzip
    payload = json.loads(gzip.decompress((source / 'door_physics/input.json.gz').read_bytes()))
    definitions = payload['doors']
    verified_runtime=Usd.Stage.Open(str(source/'door_physics/runtime/articulated_scene.usdc')) if preserve_source_runtime else None
    layer = Sdf.Layer.CreateNew(str(output / 'doors.usda'))
    stage.GetRootLayer().subLayerPaths.insert(0, 'doors.usda')
    stage.SetEditTarget(layer)
    results = []
    for definition_index,definition in enumerate(definitions):
        name = definition['leaf']
        objects = set(definition['moving_objects'])
        matches = [prim for prim in stage.Traverse() if prim.GetName() in objects]
        parents = [prim for prim in stage.Traverse() if prim.GetName() == 'door_hinge_joint__' + definition['door_id']]
        roots = parents if len(parents) == 1 and all(prim.GetPath().HasPrefix(parents[0].GetPath()) for prim in matches) else [prim for prim in matches if not any(prim != parent and prim.GetPath().HasPrefix(parent.GetPath()) for parent in matches)]
        found_names = {prim.GetName() for prim in matches}
        if found_names != objects:
            raise ValueError('源门的移动部件未完整导出:' + str(objects - found_names))
        body = roots[0] if len(roots) == 1 else stage.GetPrimAtPath(group_roots(stage, [prim.GetPath() for prim in roots], 'rparena_door_' + definition['door_id']))
        mass = definition.get('mass_kg')
        if not mass or not definition.get('mass_provenance'):
            raise ValueError('源门质量及来源缺失:' + name)
        UsdPhysics.RigidBodyAPI.Apply(body).CreateRigidBodyEnabledAttr(True)
        UsdPhysics.MassAPI.Apply(body).CreateMassAttr(mass)
        copied_physics={}
        if verified_runtime:
            verified_body=verified_runtime.GetPrimAtPath(f'/World/Doors/Door_{definition_index}')
            if not verified_body or verified_body.GetAttribute('physics:mass').Get()!=mass:
                raise ValueError('Verified door body identity differs from source definition')
            # Plain OpenUSD exporters may not have the PhysX schema plugin
            # loaded. GetAppliedSchemas then omits authored PhysX APIs even
            # though their attributes remain in the source layer.
            schemas=verified_body.GetMetadata('apiSchemas')
            for schema in schemas.GetAppliedItems() if schemas else []:
                if schema.startswith(('Physics','Physx')):body.AddAppliedSchema(schema)
            for attribute in verified_body.GetAuthoredAttributes():
                if attribute.GetName().startswith(('physics:','physxRigidBody:')):
                    body.CreateAttribute(attribute.GetName(),attribute.GetTypeName(),
                        custom=attribute.IsCustom(),variability=attribute.GetVariability()).Set(attribute.Get())
                    copied_physics[attribute.GetName()]=str(attribute.Get())
        for child in stage.Traverse():
            if child.IsA(UsdGeom.Mesh) and child.GetPath().HasPrefix(body.GetPath()):
                UsdPhysics.MeshCollisionAPI.Apply(child).CreateApproximationAttr('convexHull')
        joint = UsdPhysics.RevoluteJoint.Define(stage, '/World/RHGDoorJoints/' + definition['door_id'])
        joint.CreateAxisAttr('Z')
        joint.CreateBody1Rel().SetTargets([body.GetPath()])
        hinge = Gf.Vec3d(*definition['hinge_xyz_m'])
        transform = UsdGeom.XformCache().GetLocalToWorldTransform(body)
        local = transform.GetInverse().Transform(hinge)
        joint.CreateLocalPos0Attr(Gf.Vec3f(*hinge))
        joint.CreateLocalPos1Attr(Gf.Vec3f(*local))
        orientation = transform.ExtractRotationQuat()
        joint.CreateLocalRot0Attr(Gf.Quatf(1))
        joint.CreateLocalRot1Attr(Gf.Quatf(orientation.GetInverse()))
        sign = definition['opening_sign']
        authored = definition['authored_opening_deg']
        limits = sorted(sign * (angle - authored) for angle in definition['limits_deg'])
        joint.CreateLowerLimitAttr(limits[0])
        joint.CreateUpperLimitAttr(limits[1])
        joint.CreateCollisionEnabledAttr(False)
        drive = UsdPhysics.DriveAPI.Apply(joint.GetPrim(), 'angular')
        drive.CreateTypeAttr('force')
        drive.CreateStiffnessAttr(300.0)
        drive.CreateDampingAttr(80.0)
        drive.CreateMaxForceAttr(150.0)
        drive.CreateTargetPositionAttr(0.0)
        results.append(dict(door_id=definition['door_id'], body=str(body.GetPath()),
                            joint=str(joint.GetPath()), source_definition=definition,
                            preserved_source_body_physics=copied_physics,
                            acceptance='需要在新组合层重新执行开合,源门控不替代新验收'))
    layer.Save()
    stage.SetEditTarget(stage.GetRootLayer())
    return results


def same_support_destination(package, manifest, source, pickup, paths):
    """用实际 USD 顶面筛选同一长支撑面的新目标;不声称物理可达。"""
    from pxr import Gf, Usd, UsdGeom
    import numpy as np
    stage = Usd.Stage.Open(str(package / 'root.usda'))
    support = stage.GetPrimAtPath(paths[source['entity_id']])
    triangles = []
    transforms = UsdGeom.XformCache()
    for prim in Usd.PrimRange(support):
        if not prim.IsA(UsdGeom.Mesh):
            continue
        mesh = UsdGeom.Mesh(prim)
        transform = transforms.GetLocalToWorldTransform(prim)
        points = np.asarray([list(transform.Transform(Gf.Vec3d(*point)))
                             for point in mesh.GetPointsAttr().Get()], dtype=float)
        indices = list(mesh.GetFaceVertexIndicesAttr().Get())
        offset = 0
        for count in mesh.GetFaceVertexCountsAttr().Get():
            face = indices[offset:offset+count]
            offset += count
            for index in range(1, count-1):
                triangles.append(points[[face[0], face[index], face[index+1]]])
    if not triangles:
        return None
    vertices = np.asarray(triangles)
    a, b, c = vertices[:, 0], vertices[:, 1], vertices[:, 2]
    denominator = (b[:, 1]-c[:, 1])*(a[:, 0]-c[:, 0]) + (c[:, 0]-b[:, 0])*(a[:, 1]-c[:, 1])
    valid = np.abs(denominator) > 1e-10
    a, b, c, denominator = a[valid], b[valid], c[valid], denominator[valid]
    z = source['position_xyz_m'][2]
    def supported(x, y):
        u = ((b[:, 1]-c[:, 1])*(x-c[:, 0]) + (c[:, 0]-b[:, 0])*(y-c[:, 1])) / denominator
        v = ((c[:, 1]-a[:, 1])*(x-c[:, 0]) + (a[:, 0]-c[:, 0])*(y-c[:, 1])) / denominator
        height = u*a[:, 2] + v*b[:, 2] + (1-u-v)*c[:, 2]
        hit = height[(u >= -1e-7) & (v >= -1e-7) & (u+v <= 1+1e-7)]
        return bool(len(hit) and abs(float(hit.max())-z) <= .015)
    bounds = UsdGeom.BBoxCache(Usd.TimeCode.Default(), ['default', 'render']).ComputeWorldBound(support).ComputeAlignedBox()
    lower, upper = bounds.GetMin(), bounds.GetMax()
    # 12 cm 的物体包围半宽覆盖原生小物体及标准芥末瓶;不外推给更大物体。
    margin = .12
    candidates = []
    for x in np.arange(lower[0]+margin, upper[0]-margin+.001, .08):
        for y in np.arange(lower[1]+margin, upper[1]-margin+.001, .08):
            distance = math.dist([x, y], pickup['position_xyz_m'][:2])
            if distance < .5:
                continue
            if not all(supported(x+dx, y+dy) for dx, dy in ((0,0),(-margin,-margin),(-margin,margin),(margin,-margin),(margin,margin))):
                continue
            obstructed = False
            for entity in manifest['entities']:
                if entity['entity_id'] in (source['entity_id'], pickup['entity_id']):
                    continue
                box = entity.get('world_bbox_m')
                if box and box[0][2] < z+.30 and box[1][2] > z+.015 and box[0][0]-margin < x < box[1][0]+margin and box[0][1]-margin < y < box[1][1]+margin:
                    obstructed = True
                    break
            if not obstructed:
                candidates.append((distance, float(x), float(y)))
    if not candidates:
        return None
    distance, x, y = max(candidates)
    return {**source, 'anchor_id':source['anchor_id']+'::same_support_transfer',
            'position_xyz_m':[x, y, z], 'geometry_source':'USD_mesh_top_five_probe_points_and_entity_bbox_clearance',
            'derivation_evidence':{'transfer_xy_m':distance, 'footprint_half_width_m':margin,
                                   'maximum_object_height_m':.25, 'physical_reachability_verified':False}}


def luna_cases(package, manifest, episode, paths, physics, seeds, allow_same_support=False):
    pickup = episode['bindings']['pickup_object']
    entities = {row['entity_id']: row for row in manifest['entities']}
    target = entities[pickup['entity_id']]
    supports = [row for row in manifest['interaction_anchors']
                if row.get('kind') == 'place_on_top' and row['room_id'] == pickup['room_id']]
    if not supports:
        raise ValueError('任务房间没有测量支撑面')
    source = min(supports, key=lambda row: math.dist(row['position_xyz_m'][:2], pickup['position_xyz_m'][:2]))
    destination = episode['bindings'].get('placement_target', {})
    blockers = list(physics['blockers'])
    derivation = '保留 BenchmarkEpisode 同房间目标'
    if destination.get('room_id') != pickup['room_id'] or destination.get('entity_id') == source['entity_id']:
        candidates = [row for row in supports if row['entity_id'] != source['entity_id']
                      and 0.35 <= row['position_xyz_m'][2] <= 1.2]
        if not candidates:
            fallback = same_support_destination(package, manifest, source, pickup, paths) if allow_same_support else None
            dimensions = target.get('dimensions_m', target.get('source_dimensions_m'))
            if fallback and dimensions and max(dimensions[:2]) <= .24 and dimensions[2] <= .25:
                destination = fallback
                derivation = '按续跑授权在同一长支撑面转移至少0.5米;USD顶面五点及实体包围盒筛选,物理可达性待完整任务验证'
            else:
                blockers.append('no_distinct_same_room_support')
                derivation = '同房间目标不足;原绑定仅保留为不可执行诊断,不运行跨房间替代任务'
        else:
            destination = max(candidates, key=lambda row: math.dist(source['position_xyz_m'][:2], row['position_xyz_m'][:2]))
            derivation = '首测限定同房间,使用测量锚点派生新的放置任务;原任务保留'
    if not destination.get('entity_id'):
        raise ValueError('没有原始放置目标;禁止构造虚假任务实体')
    room = next(row for row in manifest['rooms'] if row['room_id'] == pickup['room_id'])
    x0, y0, x1, y1 = room['bounds_m']
    spawn = [(x0 + x1) / 2, (y0 + y1) / 2, 0.0]
    # These are nominal search hints, not collision or reachability certificates.
    # The native Luna consumer requires both keys before station search begins.
    pick_xy = pickup['position_xyz_m'][:2]
    place_xy = destination['position_xyz_m'][:2]
    pick_hint = [*spawn[:2], math.atan2(pick_xy[1]-spawn[1], pick_xy[0]-spawn[0])]
    place_hint_xy = [max(x0, min(x1, place_xy[0]+spawn[0]-pick_xy[0])),
                     max(y0, min(y1, place_xy[1]+spawn[1]-pick_xy[1]))]
    place_hint = [*place_hint_xy, math.atan2(place_xy[1]-place_hint_xy[1],
                                          place_xy[0]-place_hint_xy[0])]
    task_id = package.name + '-native-transfer'
    task_entities = [dict(entity_id=key, role='MANIPULATED' if key == pickup['entity_id'] else 'TARGET',
                          category=entity.get('category', entity.get('role')), required=True,
                          attributes={**entity, **({'parent_entity_id': source['entity_id']} if key == pickup['entity_id'] else {})})
                     for key, entity in entities.items()]
    write(package / 'manifests/task.json', dict(schema_version='1.0', task_id=task_id, entities=task_entities,
          goal_predicates=[dict(name='supported_by', subject=pickup['entity_id'], object=destination['entity_id'])],
          metadata=dict(room_dimensions_m=[x1-x0, y1-y0], pick=pickup, place=destination,
                        derivation=derivation, original_task_spec=episode['task_spec'],
                        original_bindings=episode['bindings'], original_success_conditions=episode.get('success_conditions'))))
    write(package / 'manifests/scene.json', dict(schema_version='1.0', scene_id=package.name,
          task_id=task_id, entity_prim_paths=paths, robot_prim_path='/World/RobotSpawnStub',
          runtime_robot_prim_path='/World/Luna/Robot', runtime='luna_wheel_run_mesh', generic_runtime_supported=False))
    write(package / 'manifests/episode.json', episode)
    dimensions = target.get('dimensions_m', target.get('source_dimensions_m'))
    records = []
    for seed in seeds:
        case = dict(case_id=f'{package.name}-native-s{seed}', seed=seed, group='development', split='development',
                    scene_contract_version='rhg-luna/1.0', scene_id=package.name, scene_path=str(package.resolve()),
                    source_task_id=task_id, entity_id=pickup['entity_id'], source_id=source['entity_id'],
                    destination_id=destination['entity_id'], source_surface_z_m=source['position_xyz_m'][2],
                    source_room_id=source['room_id'], destination_room_id=destination['room_id'],
                    destination_surface_z_m=destination['position_xyz_m'][2],
                    target_position_xy=pickup['position_xyz_m'][:2], destination_position_xy=destination['position_xyz_m'][:2],
                    navigation_bounds=[x0,x1,y0,y1], start_base=spawn, dimensions=dimensions,
                    pick_base=pick_hint, place_base=place_hint,
                    station_hints_physical_reachability_verified=False,
                    mass_kg=physics['mass_kg'], scene_mode='original', shape='original',
                    object_usd_path=str(package / 'root.usda'), object_prim_path=paths[pickup['entity_id']],
                    object_position_xyz_m=[*pickup['position_xyz_m'][:2], target.get('base_z_m', 0.0)],
                    object_kind='original', object_id=target.get('asset_id'), native_target_retained=True,
                    instruction='在同一房间抓取原生物体,抬升、保持、搬运、放置、释放、撤离并独立读回。',
                    runnable=not blockers, blockers=blockers, task_derivation=derivation,
                    destination_derivation_evidence=destination.get('derivation_evidence'),
                    destination_offset_xy=[0.,0.], object_offset_xy=[0.,0.])
        write(package / ('cases' if case['runnable'] else 'blocked-cases') / (case['case_id'] + '.json'), case)
        records.append(case)
    write(package / 'luna-case-status.json', dict(status='ready' if not blockers else 'blocked',
          reasons=blockers, native_physics=physics, cases=[row['case_id'] for row in records], physical_task_qualified=False))
    return records


def standard_control_cases(package, native_cases, template_path, shared):
    from pxr import Gf, Sdf, Usd, UsdGeom, UsdPhysics
    template = read(template_path)
    if template.get('object_kind') != 'real_mesh' or not template.get('real_mesh'):
        raise ValueError('标准物体对照必须来自已验证的 real_mesh case 配方')
    source = Path(template['mesh_usd_path']).resolve()
    geometry = Path(template['mesh_geometry_path']).resolve()
    if sha(source) != template['mesh_usd_sha256'] or sha(geometry) != template['mesh_geometry_sha256']:
        raise ValueError('标准物体配方的资产哈希变化')
    mass = template['mass_kg']
    if not isinstance(mass,(int,float)) or isinstance(mass,bool) or not math.isfinite(mass) or mass <= 0:
        raise ValueError('标准物体配方必须提供有效质量')
    original = Usd.Stage.Open(str(source))
    original.Flatten().Export(str(package / 'control-object.usdc'))
    asset = Usd.Stage.Open(str(package / 'control-object.usdc'))
    material_assets(asset, package / 'control-object.usdc', package, shared)
    asset.GetRootLayer().Save()
    relative_geometry = 'assets/' + sha(geometry) + '.npz'
    intern(geometry, package / relative_geometry, shared / Path(relative_geometry).name)
    controls = []
    for native in native_cases:
        case = dict(native)
        folder = package / 'controls' / str(native['seed'])
        folder.mkdir(parents=True)
        root = Sdf.Layer.CreateNew(str(folder / 'root.usda'))
        root.subLayerPaths = [luna_scene_entry(folder, '../../../root.usda')]
        root.Save()
        stage = Usd.Stage.Open(str(folder / 'root.usda'))
        stage.SetDefaultPrim(stage.GetPrimAtPath('/World'))
        UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
        UsdGeom.SetStageMetersPerUnit(stage, 1.0)
        # Luna's SimulationContext creates the GPU physics scene. Importing a
        # second scene breaks its single-scene DirectGPU view.
        stage.OverridePrim('/World/PhysicsScene').SetActive(False)
        stage.OverridePrim(native['object_prim_path']).SetActive(False)
        target = UsdGeom.Xform.Define(stage, '/World/G1MeshTarget')
        target.GetPrim().GetReferences().AddReference('../../control-object.usdc')
        dimensions = template['dimensions']
        position = [*native['target_position_xy'], native['source_surface_z_m'] + dimensions[2]/2 + 0.003]
        UsdGeom.Xformable(target).ClearXformOpOrder()
        UsdGeom.Xformable(target).AddTranslateOp().Set(Gf.Vec3d(*position))
        UsdPhysics.RigidBodyAPI.Apply(target.GetPrim()).CreateRigidBodyEnabledAttr(True)
        UsdPhysics.MassAPI.Apply(target.GetPrim()).CreateMassAttr(float(mass))
        # Preserve the verified object's authored collision decomposition. Enabling
        # its visual mesh as an extra hull would change the physical recipe.
        collision_parts = [prim for prim in Usd.PrimRange(target.GetPrim())
                           if prim.IsA(UsdGeom.Mesh) and prim.HasAPI(UsdPhysics.CollisionAPI)
                           and UsdPhysics.CollisionAPI(prim).GetCollisionEnabledAttr().Get() is not False]
        if not collision_parts:
            raise ValueError('标准物体配方没有已声明的碰撞部件')
        stage.GetRootLayer().Save()
        for name in ('scene.json','task.json','episode.json'):
            value = read(package / 'manifests' / name)
            if name == 'scene.json':
                value['entity_prim_paths'][native['entity_id']] = '/World/G1MeshTarget'
            if name == 'task.json':
                for entity in value['entities']:
                    if entity['entity_id'] == native['entity_id']:
                        entity['attributes'].update(asset_id=template['mesh_source_id'], mass_kg=mass,
                                                    dimensions_m=dimensions, control_template=str(template_path))
            write(folder / 'manifests' / name, value)
        blockers = [reason for reason in native['blockers'] if reason != 'native_mass_metadata_missing']
        if native.get('destination_derivation_evidence') and (max(dimensions[:2]) > .24 or dimensions[2] > .25):
            blockers.append('standard_object_exceeds_same_support_screen_dimensions')
        case.update(case_id=native['case_id'].replace('-native-', '-standard-control-'),
                    scene_path=str(folder), object_kind='real_mesh', real_mesh=True, dimensions=dimensions,
                    physics_scene_owner='luna_runtime',object_usd_path=str(folder/'root.usda'),
                    object_prim_path='/World/G1MeshTarget',object_position_xyz_m=position,
                    mass_kg=mass, mesh_source_id=template['mesh_source_id'],
                    object_id=template['object_id'], close_position=template['close_position'],
                    color=template.get('color',[.2,.4,.8]), color_name=template.get('color_name','authored_texture'),
                    mesh_usd_path=str(package / 'control-object.usdc'), mesh_usd_sha256=sha(package / 'control-object.usdc'),
                    mesh_geometry_path=str(package / relative_geometry), mesh_geometry_sha256=sha(geometry),
                    mesh_initial_root_position=position, mesh_initial_yaw_rad=0.0,
                    native_target_retained=False, parent_room_native_target_retained=False,
                    condition='standard_object_control', original_native_case_id=native['case_id'],
                    substitution_reason=native['blockers'], blockers=blockers, runnable=not blockers,
                    standard_object_provenance=dict(template_path=str(template_path), template_sha256=sha(template_path)))
        write(package / ('cases' if case['runnable'] else 'blocked-cases') / (case['case_id'] + '.json'), case)
        controls.append(case)
    return controls


def native_luna_entries(package, cases):
    from pxr import Sdf, Usd, UsdGeom
    for case in cases:
        folder = package/'native'/str(case['seed'])
        folder.mkdir(parents=True)
        root = Sdf.Layer.CreateNew(str(folder/'root.usda'))
        root.subLayerPaths = [luna_scene_entry(folder, '../../../root.usda')]
        root.Save()
        stage = Usd.Stage.Open(str(folder/'root.usda'))
        stage.SetDefaultPrim(stage.GetPrimAtPath('/World'))
        UsdGeom.SetStageUpAxis(stage, 'Z')
        UsdGeom.SetStageMetersPerUnit(stage, 1.0)
        stage.OverridePrim('/World/PhysicsScene').SetActive(False)
        stage.GetRootLayer().Save()
        for name in ('scene.json','task.json','episode.json'):
            write(folder/'manifests'/name, read(package/'manifests'/name))
        case.update(scene_path=str(folder),physics_scene_owner='luna_runtime')
        write(package/('cases' if case['runnable'] else 'blocked-cases')/(case['case_id']+'.json'),case)

def pinned_runtime_files(package):
    runtime={}
    if (package/'baked-material-delivery.json').exists():
        for name,dependency in read(package/'baked-material-delivery.json')['runtime_dependencies'].items():
            path=Path(dependency['path']).resolve()
            if name!='OmniSurface.mdl' or path.name!=name or not path.is_file() or sha(path)!=dependency['sha256']:
                raise ValueError('声明的内置 MDL 运行时依赖不匹配')
            runtime[path]=dependency['sha256']
    return runtime


def register_authored_luna_scene(package, folder):
    """登记新整屋的完整源图;不套用旧房间外观恢复或授予外观资格。"""
    from pxr import Usd, UsdGeom, UsdUtils
    entry = folder / 'root.usda'
    stage = Usd.Stage.Open(str(entry))
    meshes = [prim for prim in stage.Traverse() if prim.IsA(UsdGeom.Mesh)]
    evidence = dict(world_default_prim=str(stage.GetDefaultPrim().GetPath()) == '/World',
                    meter_units=UsdGeom.GetStageMetersPerUnit(stage) == 1.0,
                    z_up=UsdGeom.GetStageUpAxis(stage) == 'Z',
                    floor_present=bool(stage.GetPrimAtPath('/World/SceneSmith/shell_floor/Cube')),
                    wall_meshes=sum('wall' in str(prim.GetPath()).lower() for prim in meshes),
                    ceiling_meshes=sum('ceiling' in str(prim.GetPath()).lower() for prim in meshes),
                    mesh_count=len(meshes))
    if not all(evidence[key] for key in ('world_default_prim','meter_units','z_up','floor_present','wall_meshes','ceiling_meshes')):
        raise ValueError('新整屋登记缺少明确的轴向、单位或完整建筑外壳')
    layers, assets, unresolved = UsdUtils.ComputeAllDependencies(str(entry))
    if unresolved:
        raise ValueError('新整屋登记存在未解析依赖:'+str(unresolved))
    paths = {entry.resolve(), *(Path(layer.realPath).resolve() for layer in layers if layer.realPath),
             *(Path(str(asset)).resolve() for asset in assets),
             *(path.resolve() for path in (folder/'manifests').glob('*.json')),
             (package/'provenance.json').resolve()}
    runtime=pinned_runtime_files(package)
    if any(not path.is_file() or (not path.is_relative_to(package.resolve()) and path not in runtime) for path in paths):
        raise ValueError('新整屋登记依赖缺失或超出包目录')
    write(folder/'rhg-authored-scene.json', dict(schema='rparena.rhg-authored-full-scene/1',
          entry=str(entry.resolve()),entry_sha256=sha(entry),structural_evidence=evidence,
          input_sha256={str(path):sha(path) for path in sorted(paths)},
          runtime_dependency_sha256={str(path):value for path,value in runtime.items()},
          visual_qualification='unqualified_new_house',physical_task_qualified=False))

def export_scene(args):
    from pxr import Sdf, Usd, UsdGeom, Work
    Work.SetConcurrencyLimit(4)
    source = args.source.resolve()
    output = args.output.resolve()
    if not re.fullmatch(r'[a-z0-9]+(?:-[a-z0-9]+)*', args.scene_id) or not re.fullmatch(r'[a-z0-9]+(?:-[a-z0-9]+)*', output.name):
        raise ValueError('scene-id 和输出目录名必须符合 RPArena static-scene 标识格式')
    if output.exists():
        raise FileExistsError('输出必须为新目录:' + str(output))
    output.mkdir(parents=True)
    records = []
    try:
        manifest = read(source / 'SceneManifest.v16.json')
        episode = read(source / 'BenchmarkEpisode.v16.json')
        if manifest.get('schema') != 'robohousegen.SceneManifest.v16' or episode.get('schema') != 'robohousegen.BenchmarkEpisode.v16':
            raise ValueError('只接受 v16 的 SceneManifest 与 BenchmarkEpisode')
        generation_record = source.parent.parent / 'generation-timing.json'
        records.append(dict(stage='generation', status='measured' if generation_record.exists() else 'not_available',
                            evidence=read(generation_record) if generation_record.exists() else None))
        with timed(records, 'usd_export', output) as row:
            delivery_policy=getattr(args,'delivery_policy','source')
            if delivery_policy=='source' and args.reuse_package:
                raise ValueError('Source delivery requires fresh source conversion; legacy visual packages cannot be reused')
            if args.reuse_package:
                reuse = args.reuse_package.resolve()
                previous = read(reuse/'provenance.json')
                expected_sources = previous['source_sha256']
                if any(sha(source/name) != expected for name,expected in expected_sources.items()):
                    raise ValueError('复用包的源场景身份不同;禁止复用视觉资产')
                delivery = read(reuse/'delivery-manifest.json')
                for name,expected in delivery['files'].items():
                    path = (reuse/name).resolve()
                    if not path.is_relative_to(reuse) or not path.is_file() or sha(path) != expected:
                        raise ValueError('复用包交付文件缺失、越界或被修改:'+name)
                shared = args.shared_assets.resolve()
                for path in sorted((reuse/'assets').iterdir()):
                    if path.is_file():
                        intern(path,output/'assets'/path.name,shared/path.name)
                # The visual root is editable below; never hardlink it to the old run.
                shutil.copyfile(reuse/'visual.usdc',output/'visual.usdc')
                visual = reuse/'visual.usdc'
                row.update(visual_reuse='verified_package',reuse_package=str(reuse),
                           reuse_delivery_sha256=sha(reuse/'delivery-manifest.json'))
            else:
                visual = source / 'visual_scene_base.usd'
            transfer=None
            if delivery_policy=='source':
                transfer=getattr(args,'baked_transfer',None)
                reference=getattr(args,'source_reference',None)
                if transfer is None:
                    if not args.blender:raise ValueError('Default source delivery needs Blender for prepare/render/bake')
                    repo=Path(__file__).resolve().parents[2]
                    reference=output/'source-reference'
                    commands=[
                        [args.blender,'-b','-t','2','--python-exit-code','1','--python',str(repo/'scripts/render_delivery_reference.py'),'--','--source',str(source),'--output',str(reference)],
                        [args.blender,'-b','-t','2','--python-exit-code','1','--python',str(repo/'scripts/bake_delivery_scene.py'),'--','--reference',str(reference),'--output',str(output/'source-transfer')]]
                    if getattr(args,'window_scenery',None):commands[0]+=['--window-scenery',str(args.window_scenery)]
                    from .source_device import blender_environment
                    with blender_environment(output,getattr(args,'gpu',None)) as environment:
                        for index,command in enumerate(commands):
                            with (output/f'source-stage-{index}.log').open('x') as log:subprocess.run(command,check=True,stdout=log,stderr=subprocess.STDOUT,env=environment)
                    transfer=output/'source-transfer'
                if reference is None:raise ValueError('Baked delivery requires its saved Blender reference')
                receipt=read(transfer/'bake-receipt.json')
                if receipt['source_sha256']!=sha(reference/'source.blend') or receipt['geometry_max_error_m']>1e-6:
                    raise ValueError('Baked source identity or geometry changed')
                from .rparena_baked import verify_images
                parity=verify_images(transfer,reference,getattr(args,'texture_contract',None));write(output/'baked-source-parity.json',parity)
                # Keep the existing mean-error gate. Clarity has its own strict
                # verdict; retain it even when downstream diagnosis is needed.
                if not parity['mean_error_passed']:
                    raise ValueError('Baked Blender source differs beyond the original PMP20 5/255 contract; keep failed views')
                shutil.copyfile(reference/'source.blend',output/'source.blend')
                source_contract=read(reference/'source-delivery.json')
                if source_contract['display']!=receipt['source_display']:
                    raise ValueError('Source display changed after baking')
                source_contract['ocio_config']='colormanagement/config.ocio'
                write(output/'source-delivery.json',source_contract)
                rays=read(reference/'source-ray-visibility.json')
                if rays['source_blend_sha256']!=receipt['source_sha256']:
                    raise ValueError('Source ray visibility belongs to another Blender baseline')
                write(output/'source-ray-visibility.json',rays)
                shutil.copyfile(reference/'views.json',output/'reference-views.json')
                shutil.copytree(reference/'colormanagement',output/'colormanagement')
                visual=transfer/'visual.usdc'
            reusable = False
            if visual.exists():
                candidate = Usd.Stage.Open(str(visual))
                reusable = candidate is not None and all(all(count == 3 for count in UsdGeom.Mesh(prim).GetFaceVertexCountsAttr().Get())
                            for prim in candidate.Traverse() if prim.IsA(UsdGeom.Mesh))
                candidate = None
            if delivery_policy=='source' and not reusable:
                raise ValueError('Baked transfer must contain a triangulated, openable USD')
            if not reusable and not args.reuse_package:
                if not args.blender:
                    raise ValueError('缺少 stage4 USD;传 --blender 以复用 RHG stage4')
                repo = Path(__file__).resolve().parents[2]
                command = [args.blender, '--background', '--python-exit-code', '1', '--python',
                           str(repo / 'scripts/export_rparena_v16_visual.py'), '--', str(source)]
                with (output / 'usd-export.log').open('x') as log:
                    subprocess.run(command, stdout=log, stderr=subprocess.STDOUT, check=True)
                visual = source / 'visual_scene_rparena_triangles.usd'
            row['reused_stage4'] = reusable or bool(args.reuse_package)
            row['triangulation'] = 'verified_package_triangles' if args.reuse_package else 'stage4_native_triangles' if reusable else 'Blender_stage4_explicit_triangulation_for_frozen_Luna_collision_consumer'
            stage = Usd.Stage.Open(str(visual))
            if not stage or not stage.GetPrimAtPath('/World'):
                raise ValueError('stage4 USD 必须含 /World')
            if UsdGeom.GetStageUpAxis(stage) != 'Z' or abs(UsdGeom.GetStageMetersPerUnit(stage)-1) > 1e-9:
                raise ValueError('源场景必须为 Z-up、米制,禁止隐式缩放')
            stage.GetRootLayer().Export(str(output / 'visual.usdc'))
            stage = Usd.Stage.Open(str(output / 'visual.usdc'))
            stage.SetDefaultPrim(stage.GetPrimAtPath('/World'))
            if delivery_policy=='source':
                for prim in stage.Traverse():
                    if 'glass__window__' in str(prim.GetPath()) and prim.IsA(UsdGeom.Mesh):
                        UsdGeom.Imageable(prim).CreateVisibilityAttr(UsdGeom.Tokens.invisible)
            shared = args.shared_assets.resolve()
            shared.mkdir(parents=True, exist_ok=True)
            textures = material_assets(stage, visual, output, shared)
            if transfer is not None:
                from .rparena_baked import apply_baked
                baked=apply_baked(stage,transfer,output,shared)
                write(output/'baked-material-delivery.json',baked)
                from .texture_compression import compress_colors
                compression_policy=getattr(args,'texture_compression','auto')
                if compression_policy=='auto':compression_policy='bc7' if 'texture_budget' in receipt else 'preserve'
                compression=compress_colors(stage,output,shared,compression_policy)
                variants={}
                for item in compression['converted']:variants.setdefault(item['original'],{})[item['path']]=item
                textures=[dict(source=item['source'],path=variant['path'],sha256=variant['sha256'])
                          for item in textures for variant in (variants.get(item['path'],{item['path']:item})).values()]
                baked['texture_compression']=compression
                write(output/'baked-material-delivery.json',baked)
            if args.reuse_package:
                old_metadata = read(args.reuse_package/'manifest.json')
                namespace = old_metadata['luna_namespace']
                paths = old_metadata['entity_prim_paths']
                if not stage.GetPrimAtPath(namespace['floor_path']) or any(not stage.GetPrimAtPath(path) for path in paths.values()):
                    raise ValueError('复用视觉的 Luna 命名空间或实体映射不完整')
            else:
                namespace = luna_scene_namespace(stage)
                paths = entity_paths(stage, manifest)
        with timed(records, 'geometry_deduplication', output) as row:
            geometry = deduplicate_geometry(stage, output, shared)
            row.update(mesh_count=len(geometry), shared_asset_count=len({item['geometry_content_sha256'] for item in geometry}))
            compact = output / 'visual-compact.usdc'
            stage.GetRootLayer().Export(str(compact))
            compact.replace(output / 'visual.usdc')
        root = Sdf.Layer.CreateNew(str(output / 'root.usda'))
        root.subLayerPaths = [luna_scene_entry(output, '../visual.usdc')]
        root.Save()
        stage = Usd.Stage.Open(str(output / 'root.usda'))
        stage.SetDefaultPrim(stage.GetPrimAtPath('/World'))
        UsdGeom.SetStageUpAxis(stage, 'Z')
        UsdGeom.SetStageMetersPerUnit(stage, 1.0)
        with timed(records, 'physics_layers', output):
            physics = author_physics(stage, output, manifest, episode, paths)
            doors = author_doors(stage, source, output,preserve_source_runtime=delivery_policy=='source')
            native=dict(instances=[],body_paths=[],joint_count=0)
            if delivery_policy=='source':
                from .rparena_native import author_native
                native=author_native(stage,source,output,paths,shared)
                write(output/'native-articulation-delivery.json',native)
            stage.GetRootLayer().Save()
        with timed(records, 'metadata_and_luna_cases', output):
            cases = luna_cases(output, manifest, episode, paths, physics, args.seeds,
                               allow_same_support=args.allow_same_support)
            native_luna_entries(output, cases)
            controls = []
            if args.control_template:
                controls = standard_control_cases(output, cases, args.control_template.resolve(), shared)
            case_status = read(output / 'luna-case-status.json')
            case_status['standard_control_cases'] = [row['case_id'] for row in controls]
            case_status['runnable_case_count'] = sum(row['runnable'] for row in cases + controls)
            write(output / 'luna-case-status.json', case_status)
            write(output / 'SceneManifest.v16.json', manifest)
            write(output / 'BenchmarkEpisode.v16.json', episode)
            commit = args.rhg_commit or subprocess.check_output(['git','-C',str(Path(__file__).resolve().parents[2]),'rev-parse','HEAD'], text=True).strip()
            provenance = dict(rhg_commit=commit, source_run=str(source),
                              source_sha256={name:sha(source/name) for name in ('SceneManifest.v16.json','BenchmarkEpisode.v16.json',
                                             'composition_manifest.runtime.json',source.name+'.blend')},
                              adapter_sha256=sha(__file__), physical_task_qualified=False)
            write(output / 'provenance.json', provenance)
            write(output / 'manifest.json', dict(schema='rhg.rparena.v16/1', provenance=provenance,
                  rooms=manifest['rooms'], portals=manifest['portals'],
                  support_surfaces=[row for row in manifest['interaction_anchors'] if row['kind']=='place_on_top'],
                  entity_prim_paths=paths, luna_namespace=namespace, task=episode, doors=doors, physics=physics,
                  texture_assets=textures, geometry_assets=geometry,
                  baked_materials=[dict(object=r['object'],source_material=r['source_material'],
                    usd_material_name=r['usd_material_name'],channels=list(r['maps'])) for r in receipt['materials']] if transfer is not None else [],
                  material_delivery=baked if transfer is not None else None,native_articulations=native,
                  source_texture_acceptance=parity if transfer is not None else None,
                  baking_status='source_side_baked_after_saved_Blender_reference' if transfer is not None else 'legacy_control_unmodified_visual'))
            write(output / 'SCENE-DYNAMIC-ACTORS.json', dict(
                  source_manifest=str((output/'manifest.json').resolve()),
                  source_sha256=sha(output/'manifest.json'),
                  body_paths=[door['body'] for door in doors]+native['body_paths'],
                  physical_parameters_changed=False))
            write(output / 'plan.json', dict(source=dict(units_scale=1.0)))
            write(output / 'portability.json', dict(schema='rhg.portability/1', usd_relative_content_paths=True,
                  runtime_libraries='explicit installed SDK paths and SHA256; no external scene textures or geometry',
                  storage='包内 assets 使用内容哈希;同文件系统跨包硬链接共享,跨盘复制',
                  luna_case_paths='case 中保留当前运行绝对路径;迁移安装后需生成独立 case 副本并更新路径,不修改封存包', physical_acceptance='not_run'))
        register_authored_luna_scene(output, output)
        for folder in sorted([*(output/'controls').glob('*'),*(output/'native').glob('*')]):
            register_authored_luna_scene(output, folder)
        with timed(records, 'packaging', output):
            from pxr import UsdUtils
            layers, assets, unresolved = UsdUtils.ComputeAllDependencies(str(output / 'root.usda'))
            runtime=pinned_runtime_files(output)
            external = [str(path) for path in [*(layer.realPath for layer in layers), *assets]
                        if not Path(path).resolve().is_relative_to(output) and Path(path).resolve() not in runtime]
            if unresolved or external:
                raise ValueError('包不可迁移:' + str(dict(unresolved=list(unresolved), external=external)))
            metadata = dict(format='rparena-static-scene', schema_version='1.0', id=args.scene_id,
                            bundle_id=output.name, root_usd='root.usda', runtime_files=[], source=provenance,
                            acceptance=dict(appearance='not_run',physical_task_qualified=False),
                            rooms=manifest['rooms'], portals=manifest['portals'], entity_prim_paths=paths,
                            support_surfaces=[row for row in manifest['interaction_anchors'] if row['kind']=='place_on_top'])
            metadata['runtime_files'] = sorted([path.relative_to(output).as_posix() for path in output.rglob('*') if path.is_file()
                                                and path.name not in ('timing.json', 'usd-export.log')]+['rparena.scene.json'])
            write(output / 'rparena.scene.json', metadata)
        files = {path.relative_to(output).as_posix():sha(path) for path in output.rglob('*') if path.is_file()
                 and path.name not in ('delivery-manifest.json','checksums.sha256','timing.json','usd-export.log')}
        write(output / 'delivery-manifest.json',dict(scene_entry='root.usda', files=files,
              acceptance_status='not_run', runtime_dependencies=baked['runtime_dependencies'] if transfer is not None else {}))
        (output / 'checksums.sha256').write_text(''.join(f'{digest}  {name}\n' for name,digest in sorted(files.items())))
        write(output / 'export-result.json', dict(status='exported_unqualified', package=str(output),
              case_count=len(cases)+len(controls), native_case_count=len(cases),
              runnable_case_count=sum(row['runnable'] for row in cases+controls),
              blockers=sorted({reason for row in cases+controls for reason in row['blockers']}),
              physical_task_qualified=False))
        for name in ('rparena_installation', 'isaac_loading_acceptance'):
            records.append(dict(stage=name, status='not_run', wall_s=None, gpu_s=None,
                                peak_rss_bytes=None, output_bytes=None))
        write(output / 'timing.json', records)
    except Exception as error:
        write(output / 'export-result.json', dict(status='failed', error=str(error),traceback=traceback.format_exc()))
        raise


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('source', type=Path)
    parser.add_argument('--output', type=Path, required=True)
    parser.add_argument('--scene-id', required=True)
    parser.add_argument('--shared-assets', type=Path, required=True)
    parser.add_argument('--blender')
    parser.add_argument('--delivery-policy',choices=['source','legacy-control'],default='source')
    parser.add_argument('--window-scenery',type=Path)
    parser.add_argument('--baked-transfer',type=Path)
    parser.add_argument('--source-reference',type=Path)
    parser.add_argument('--texture-contract',type=Path,help='Frozen source/baked texture ROI and threshold contract')
    parser.add_argument('--texture-compression',choices=('auto','preserve','png','bc7'),default='auto',help='auto uses BC7 for budgeted scenes and preserves legacy controls; png is explicit PNG8 fallback; normals stay PNG')
    parser.add_argument('--gpu',help='Idle local GPU index/UUID for source rendering and baking; otherwise reserve an idle GPU')
    parser.add_argument('--reuse-package',type=Path,help='源场景四项哈希相同且交付文件全量核验后,复用已封存包的视觉资产;新建全部物理层、入口与元数据')
    parser.add_argument('--rhg-commit', help='非 Git 部署目录必须传入已核实的源提交;adapter 文件另外计算哈希')
    parser.add_argument('--control-template', type=Path, help='保留原生条件后,按已验证 case 的质量和资产创建标准物体对照')
    parser.add_argument('--allow-same-support', action='store_true', help='无第二支撑面时,按续跑授权用实际USD顶面筛选同支撑面至少0.5米转移')
    parser.add_argument('--seeds', type=int, nargs='+', default=[2026101801,2026101802,2026101803])
    args = parser.parse_args(argv)
    export_scene(args)
    return 0