File size: 99,244 Bytes
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc2b32a
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc2b32a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc2b32a
 
 
 
2bcbba2
 
 
 
 
 
fc2b32a
 
 
 
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc2b32a
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff86ab2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff86ab2
 
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff86ab2
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc2b32a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff86ab2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff86ab2
 
 
 
fc2b32a
 
 
 
 
2bcbba2
 
 
 
 
 
 
 
 
 
 
ff86ab2
 
 
 
fc2b32a
 
 
 
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
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
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
"""Export the scene's colliders and kinematic structure into a dataset.

Why
---
A recorded episode stores ``observation.state`` -- the whole scene's
generalised coordinates -- and contact patches keyed by Newton SHAPE INDEX.
Neither means anything without the geometry and the joint tree they refer to,
and ``meta/scene.json`` records only absolute paths to the USDs on the machine
that recorded it. Ship such a dataset and the recipient has numbers with no
object: the DexVerse assets are 7 GB behind a Hugging Face gate, and the paths
point at someone else's home directory.

This writes the geometry itself, taken from the Newton model that generated
the data rather than from the USD it was built from, so what a reader draws is
what the physics collided with:

    meta/assets/bodies.json   every rigid body: label, parent, its joint, and
                              WHICH SLICE of observation.state drives it
    meta/assets/shapes.json   every collider: label, body, primitive type,
                              scale, pose in the body frame, mesh file.
                              This is also the legend for `_shape_pair`.
    meta/assets/*.obj         one mesh per mesh-typed collider, in its own
                              local frame
    meta/assets/sources.json  where each asset CAME FROM: source USD, its
                              sha256, and the pose and scale it was spawned
                              with

With those, a consumer needs numpy alone: read a frame of
``observation.state``, walk ``bodies.json`` to get each body's world pose,
place each shape by its ``transform``, and the scene is rebuilt exactly.

The exported geometry is authoritative for the RECORDED CONTACTS -- it is what
Newton collided -- but it is not always the source asset. Scenery is imported
with ``approximation = convexHull``, graspable objects with ``none``, and
``tools/prepare_asset.py`` bakes scale and moves colliders on the way in. A
downstream task that wants the object's full-resolution visual mesh, its
materials, or its authored joint limits wants the ORIGINAL, which is what
``sources.json`` points at: path, size and sha256, so a recipient can fetch
the same asset and prove it is the same one. ``--copy-source-assets`` (on by
default) also packages those originals into the dataset as ``.usdz`` (USD
with every dependency pulled in), so nothing has to be fetched at all.
:data:`NON_REDISTRIBUTABLE` overrides it per asset for the ones that are not
ours to pass on.
"""

from __future__ import annotations

import json
import os
import re

import numpy as np


def _np(a):
    return np.asarray(a.numpy()) if hasattr(a, "numpy") else np.asarray(a)


def _xform(t) -> list[float]:
    """Newton transform -> [px, py, pz, qx, qy, qz, qw]."""
    v = np.asarray(t, dtype=np.float64).reshape(-1)
    return [float(x) for x in v[:7]]


def _write_obj(path: str, verts, faces, comment: str = "") -> int:
    with open(path, "w") as fh:
        if comment:
            fh.write(f"# {comment}\n")
        for p in verts:
            fh.write(f"v {p[0]:.6f} {p[1]:.6f} {p[2]:.6f}\n")
        for t in faces:
            fh.write(f"f {t[0] + 1} {t[1] + 1} {t[2] + 1}\n")
    return len(faces)


def _mesh_of(source):
    """(vertices, triangles) from whatever Newton hung on shape_source."""
    if source is None:
        return None
    v = getattr(source, "vertices", None)
    i = getattr(source, "indices", None)
    if v is None or i is None:
        return None
    v = np.asarray(v, dtype=np.float64).reshape(-1, 3)
    i = np.asarray(i, dtype=np.int64).reshape(-1, 3)
    if not len(v) or not len(i):
        return None
    return v, i


def _safe(name: str) -> str:
    keep = [c if (c.isalnum() or c in "-_.") else "_" for c in name]
    return "".join(keep).strip("_")[:80] or "shape"


def _sha256(path: str, cap: int = 512 << 20) -> str | None:
    import hashlib  # noqa: PLC0415
    try:
        h = hashlib.sha256()
        with open(path, "rb") as fh:
            while chunk := fh.read(1 << 20):
                h.update(chunk)
        return h.hexdigest()
    except OSError:
        return None


#: Kit's own MDL materials. A YCB asset via DexVerse binds OmniPBR.mdl by bare name; Kit
#: finds it on its MDL search path at render time, so it is never a file beside the asset,
#: and a package neither can nor needs to hold it. Any OTHER unresolved reference fails the
#: package: that one is a real missing file.
KIT_MDL = re.compile(r"^Omni(PBR|Surface|Glass|Hair|Volume|Emissive)\w*\.mdl$")


def write_usdz(src: str, dst: str) -> list[str]:
    """Package ``src`` with every layer and file it references as ``dst`` (.usdz).

    UsdUtils.CreateNewUsdzPackage aborts on an unresolved reference, and the YCB
    can, hammer and drill all reference Kit's OmniPBR.mdl, so their datasets
    recorded 2026-09..11 hold no source asset (check_dataset: "not packaged and not
    excused"). This writes the same package and leaves out only Kit's built-in
    materials (KIT_MDL), returned so the caller can record them. Raises on any
    other unresolved reference, or a dependency outside ``src``'s directory (its
    path inside the package would have to change). Written to a temporary name
    and renamed, so a failure never leaves a partial package."""
    from pxr import Usd, UsdUtils  # noqa: PLC0415
    layers, assets, unresolved = UsdUtils.ComputeAllDependencies(src)
    builtin = sorted({u for u in unresolved if KIT_MDL.match(os.path.basename(u))})
    missing = sorted(set(unresolved) - set(builtin))
    if missing:
        raise RuntimeError(f"unresolved references: {missing}")
    base = os.path.dirname(os.path.abspath(src))
    root = os.path.abspath(src)
    paths = [root] + sorted({os.path.abspath(lyr.realPath) for lyr in layers} - {root}) \
        + sorted({os.path.abspath(a) for a in assets})
    tmp = dst + ".partial"
    w = Usd.ZipFileWriter.CreateNew(tmp)
    try:
        for p in paths:                # the root layer first: it is the package's default layer
            rel = os.path.relpath(p, base)
            if rel.startswith(".."):
                raise RuntimeError(f"{p} is outside {base}")
            w.AddFile(p, rel.replace(os.sep, "/"))
        w.Save()
    except Exception:
        w.Discard()
        if os.path.exists(tmp):
            os.remove(tmp)
        raise
    os.replace(tmp, dst)
    return builtin


#: Assets whose BYTES never travel with a dataset, whatever ``copy`` says,
#: keyed by the reason a recipient is expected to obtain them themselves.
#: The hand is MANO-derived: its licence is not ours to pass on and the
#: official model is a registration away (README "The hand"), after which
#: tools/build_mano_hand.py rebuilds exactly the rig meta/rig/ describes.
#: Provenance -- path, size, sha256 -- is still recorded for these, so a
#: recipient can prove they rebuilt from the same file.
NON_REDISTRIBUTABLE = {
    "hand": "MANO-derived; download the official model from "
            "https://mano.is.tue.mpg.de and rebuild with "
            "tools/build_mano_hand.py (the rig it made is in meta/rig/)",
}


def _non_redistributable(name: str, src: str) -> str | None:
    """Why this asset's bytes must not be packaged, or None to package it."""
    why = NON_REDISTRIBUTABLE.get(name)
    if why:
        return why
    low = src.replace(os.sep, "/").lower()
    if "/mano" in low or "mano_hand" in low or "mano_rig" in low:
        return NON_REDISTRIBUTABLE["hand"]
    return None


def export_sources(scene: dict, out_dir: str, copy: bool = True,
                   quiet: bool = False) -> dict:
    """Record where each asset came from, and package it unless barred.

    Identity, not just a path: a recipient who fetches an asset themselves can
    check the sha256 and know they have the file this demo was recorded
    against, rather than a later revision of it.

    ``copy`` (the collector's --copy-source-assets, on by default) also writes
    the asset itself to ``source_assets/<name>.usdz``, so the dataset replays
    on a machine that has none of the source art. It never overrides
    :data:`NON_REDISTRIBUTABLE`: an asset on that list records its provenance
    and the reason its bytes stayed behind, and nothing else.
    """
    rows, packaged, total, failed, withheld = [], 0, 0, [], []
    for name, a in (scene or {}).items():
        if not isinstance(a, dict) or not a.get("usd"):
            continue
        src = str(a["usd"])
        rec = {"asset": name, "usd": src,
               "exists_at_record_time": os.path.exists(src),
               "bytes": os.path.getsize(src) if os.path.exists(src) else None,
               "sha256": _sha256(src) if os.path.exists(src) else None,
               "spawn": {k: a[k] for k in ("pos", "yaw_deg", "scale", "root",
                                           "mass_kg") if k in a},
               "package": None}
        bar = _non_redistributable(name, src)
        if bar:
            rec["not_packaged"] = bar
            withheld.append(name)
        if copy and not bar and os.path.exists(src):
            pkg_dir = os.path.join(out_dir, "source_assets")
            os.makedirs(pkg_dir, exist_ok=True)
            dst = os.path.join(pkg_dir, f"{_safe(name)}.usdz")
            ok = False
            try:
                builtin = write_usdz(src, dst)
                ok = True
                if builtin:
                    rec["package_omits"] = _omits_note(builtin)
            except Exception as exc:                     # noqa: BLE001
                rec["package_error"] = str(exc).strip()
            if ok:
                rec["package"] = os.path.relpath(dst, out_dir)
                packaged += 1
                total += os.path.getsize(dst)
            else:
                # 🔴 never a partial package: write_usdz writes to a temporary name
                # (the sink's old CreateNewUsdzPackage abort left 42 MB that opened
                # like a real package and was missing geometry)
                failed.append(name)
        rows.append(rec)
    if rows:
        with open(os.path.join(out_dir, "sources.json"), "w") as fh:
            json.dump({"note": ("Where each asset came from. The geometry in "
                                "this directory is what Newton COLLIDED; these "
                                "are the originals it was imported from, which "
                                "may differ (convexHull for scenery, baked "
                                "scale). Check sha256 before assuming a fetched "
                                "asset is the same file."),
                       "packaged": ("`package` is the asset's own files, under "
                                    "source_assets/, so this dataset replays "
                                    "without them being fetched. `not_packaged` "
                                    "says why an asset's bytes were withheld "
                                    "and how to obtain them; the scene still "
                                    "rebuilds without it from the colliders in "
                                    "this directory and usd/."),
                       "assets": rows}, fh, indent=1)
    if not quiet and rows:
        miss = [r["asset"] for r in rows if not r["exists_at_record_time"]]
        print(f"  asset provenance -> sources.json: {len(rows)} assets"
              + (f", {packaged} packaged as .usdz ({total / 1e6:.1f} MB)" if copy
                 else ", not packaged (--copy-source-assets to include them)")
              + (f"; {withheld} not ours to redistribute, provenance only"
                 if withheld else "")
              + (f"; ⚠️ missing at record time: {miss}" if miss else ""))
        if failed:
            print(f"     ⚠️  could not package {failed} — see package_error in "
                  f"sources.json (its path and sha256 are still recorded)")
    return {"assets": len(rows), "packaged": packaged, "bytes": total,
            "withheld": withheld}


def joint_couplings(model) -> list[dict]:
    """Record solver joint couplings separately from the kinematic body tree.

    Coefficients use solver coordinates (radians/metres). Joint labels, not
    indices, survive scene regrouping and USD re-import. An empty list means
    the model was checked; an absent manifest field means an older export.
    """
    labels = [str(x) for x in getattr(model, "joint_label", [])]
    out = []

    def add(kind, follower, leader, coefficients, enabled):
        follower, leader = int(follower), int(leader)
        if not (0 <= follower < len(labels) and 0 <= leader < len(labels)):
            raise ValueError(f"Cannot export {kind} coupling with joints {follower}, {leader}")
        out.append({"kind": kind, "follower": labels[follower], "leader": labels[leader],
                    "coefficients": [float(x) for x in coefficients], "enabled": bool(enabled)})

    def equality_field(name):
        values = _custom(model, "mujoco:equality_constraint_" + name)
        if values is None:
            legacy = getattr(model, "equality_constraint_" + name, None)
            values = _np(legacy) if legacy is not None else None
        return values

    # Modern Newton can retain an equality row AND its projected mimic.
    # Export the authoritative polynomial row only, not a duplicate constraint.
    kinds, targets = equality_field("target_kind"), equality_field("target")
    projected = {int(targets[i]) for i in range(len(kinds)) if int(kinds[i]) == 2} if kinds is not None else set()
    count = int(getattr(model, "constraint_mimic_count", 0))
    if count:
        arrays = {k: _np(getattr(model, "constraint_mimic_" + k))
                  for k in ("joint0", "joint1", "coef0", "coef1", "enabled")}
        for i in range(count):
            if i in projected:
                continue
            add("mimic", arrays["joint0"][i], arrays["joint1"][i],
                [arrays["coef0"][i], arrays["coef1"][i]], arrays["enabled"][i])
    types = equality_field("type")
    if types is not None:
        # EqType.JOINT is MuJoCo's stable numeric value 2. Body weld/connect
        # equalities are not joint couplings and must not be treated as one.
        arrays = {k: equality_field(k)
                  for k in ("joint1", "joint2", "polycoef", "enabled")}
        for i in (types if isinstance(types, dict) else range(len(types))):
            if int(types[i]) != 2:
                continue
            add("equality", arrays["joint1"][i], arrays["joint2"][i],
                arrays["polycoef"][i], arrays["enabled"][i])
            for field in ("solref", "solimp"):
                values = _custom(model, "mujoco:eq_" + field)
                if values is not None and (i in values if isinstance(values, dict) else i < len(values)):
                    out[-1][field] = [float(x) for x in values[i]]
    return out


def _voxels_by_label(shape_voxel, labels: list[str], quiet: bool = False) -> list:
    """The builder's (label, voxel) list re-indexed onto the model's shapes.

    Index for index when the two label lists agree, which is the normal case
    (finalize copies the builder's shapes in order). Otherwise by label, and
    only for labels the builder holds once: a voxel attached to the wrong
    shape is worse than none.
    """
    if [lb for lb, _ in shape_voxel] == list(labels):
        return [v for _, v in shape_voxel]
    seen: dict[str, list] = {}
    for lb, v in shape_voxel:
        seen.setdefault(lb, []).append(v)
    out = [seen[lb][0] if len(seen.get(lb, ())) == 1 else None for lb in labels]
    if not quiet:
        print(f"  ⚠️  shape voxels: builder and model shape lists differ "
              f"({len(shape_voxel)} vs {len(labels)}); matched "
              f"{sum(v is not None for v in out)} by label")
    return out


def export(model, out_dir: str, quiet: bool = False,
           shape_voxel: list[tuple[str, float | None]] | None = None) -> dict:
    """Write bodies.json, shapes.json and the mesh OBJs. Returns a summary.

    ``shape_voxel`` is the builder's ``shape_sdf_target_voxel_size`` as
    (shape label, voxel) per shape: Newton does not carry that array onto the
    finalized Model, so without it no shape records the voxel it was flagged
    with. It is used only where its labels line up with the model's.
    """
    os.makedirs(out_dir, exist_ok=True)
    from newton import GeoType  # noqa: PLC0415

    body_label = [str(x) for x in (getattr(model, "body_label", []) or [])]
    n_body = len(body_label)

    # --- bodies: parent, joint, and the observation.state slice -------------
    j_type = _np(model.joint_type)
    j_parent = _np(model.joint_parent)
    j_child = _np(model.joint_child)
    j_qstart = _np(model.joint_q_start)
    j_label = [str(x) for x in (getattr(model, "joint_label", []) or [])]
    j_Xp = _np(model.joint_X_p)
    j_Xc = _np(model.joint_X_c)
    n_q = int(getattr(model, "joint_coord_count", 0) or 0)
    # 🔴 THE AXIS OF A HINGE, which nothing recorded until an ARCTIC dataset
    # could not be rebuilt offline. A REVOLUTE joint's one coordinate is an
    # ANGLE, and an angle means nothing without the axis it turns about, so
    # tools/check_dataset.py and viz/blender could read the number and still
    # not place the body. Per-DOF in newton, so it is indexed through
    # joint_qd_start; both arrays are optional here because a dataset written
    # by an older build has neither and body_poses() falls back.
    j_axis = _np(getattr(model, "joint_axis", None)) \
        if getattr(model, "joint_axis", None) is not None else None
    j_dofstart = _np(getattr(model, "joint_qd_start", None)) \
        if getattr(model, "joint_qd_start", None) is not None else None
    # The travel of a single-DOF joint, in the coordinate's own SI unit (rad,
    # m), per DOF like the axis. A trainer that rebuilds the scene as USD
    # needs the stops the physics had (export_usd), and the model is the only
    # source that cannot disagree with the recording.
    j_lo = _np(getattr(model, "joint_limit_lower", None)) \
        if getattr(model, "joint_limit_lower", None) is not None else None
    j_hi = _np(getattr(model, "joint_limit_upper", None)) \
        if getattr(model, "joint_limit_upper", None) is not None else None

    # FIRST joint per child body wins. A closed chain authors a body with two
    # incoming joints (the 2F-140's inner knuckles: the pad joint from the
    # inner finger, then the knuckle joint from the base); the solver keeps
    # the first in its tree and drops the later one, whose coordinates then
    # never move. Last-wins named the dropped joint here and a reader placed
    # the knuckle from a slice that stays at zero.
    joint_of = {}
    for j in range(len(j_child)):
        joint_of.setdefault(int(j_child[j]), j)
    # 🔴 `name` is the last path segment and it is NOT unique. Two MANO hands
    # both call their knuckle Index1 and their root Wrist_Root, so a reader
    # that builds {name: index} keeps whichever hand came last -- and then
    # skins one hand from the other hand's bones, or attributes a contact to
    # the wrong hand, with nothing to show for it. `label` is the unique key
    # and always was; `unique_name` is that same guarantee in a form short
    # enough to plot with, and `side` says which hand a body belongs to (None
    # for everything that is not a hand).
    _short = [lbl.rsplit("/", 1)[-1] for lbl in body_label]
    _dup = {n for n in _short if _short.count(n) > 1}

    def _side_of(lbl: str):
        for s in ("left", "right"):
            if f"/Hand{s.capitalize()}/" in lbl or lbl.endswith(f"/Hand{s.capitalize()}"):
                return s
        return None

    def _unique(b: int) -> str:
        n = _short[b]
        if n not in _dup:
            return n
        s = _side_of(body_label[b])
        if s is not None:
            return f"{s}:{n}"
        # Not a hand: fall back to the parent segment, then to the index, so
        # this always returns something unique rather than something plausible.
        parts = body_label[b].split("/")
        cand = f"{parts[-2]}:{n}" if len(parts) > 1 else n
        return cand if _short.count(cand) == 0 else f"{n}#{b}"

    bodies = []
    for b in range(n_body):
        j = joint_of.get(b)
        entry = {
            "index": b,
            "label": body_label[b],
            "name": _short[b],
            "unique_name": _unique(b),
            "side": _side_of(body_label[b]),
            "parent": None,
            "joint": None,
        }
        if j is not None:
            q0 = int(j_qstart[j])
            q1 = int(j_qstart[j + 1]) if j + 1 < len(j_qstart) else n_q
            entry["parent"] = int(j_parent[j])
            entry["joint"] = {
                "index": int(j),
                "label": j_label[j] if j < len(j_label) else "",
                "type": _joint_type_name(int(j_type[j])),
                "state_slice": [q0, q1],
                "X_p": _xform(j_Xp[j]),
                "X_c": _xform(j_Xc[j]),
            }
            # Only for the single-DOF joints where it is the whole meaning of
            # the coordinate. FREE and BALL carry their own rotation.
            if j_axis is not None and (q1 - q0) == 1:
                d = int(j_dofstart[j]) if j_dofstart is not None and j < len(j_dofstart) else j
                if 0 <= d < len(j_axis):
                    entry["joint"]["axis"] = [float(v) for v in
                                              np.asarray(j_axis[d]).ravel()[:3]]
                if j_lo is not None and j_hi is not None and 0 <= d < min(len(j_lo), len(j_hi)):
                    entry["joint"]["limit"] = [float(j_lo[d]), float(j_hi[d])]
        for key, attr in (("mass", "body_mass"), ("com", "body_com")):
            arr = getattr(model, attr, None)
            if arr is not None:
                v = _np(arr)
                if b < len(v):
                    entry[key] = (float(v[b]) if np.ndim(v[b]) == 0
                                  else [float(x) for x in np.asarray(v[b]).reshape(-1)[:3]])
        # the inertia tensor the solver integrated (about the COM, body frame,
        # row-major 3x3): a vendored asset authors one, and a rebuilt scene
        # that lets the importer derive it from the mesh gets a different body
        inr = getattr(model, "body_inertia", None)
        if inr is not None:
            v = _np(inr)
            if b < len(v):
                entry["inertia"] = [float(x) for x in np.asarray(v[b]).reshape(-1)[:9]]
        gc = _custom(model, "mujoco:gravcomp")
        if gc is not None:
            v = gc.get(b) if isinstance(gc, dict) else (float(gc[b]) if b < len(gc) else None)
            if v is not None and float(v) != 0.0:
                entry["gravcomp"] = float(v)                      # MuJoCo gravity compensation (the nail's 1.0)
        bodies.append(entry)

    # --- shapes: geometry, pose in the body frame, and the pair legend ------
    s_body = _np(model.shape_body)
    s_type = _np(model.shape_type)
    s_scale = _np(model.shape_scale)
    s_xform = _np(model.shape_transform)
    s_label = [str(x) for x in (getattr(model, "shape_label", []) or [])]
    s_src = list(getattr(model, "shape_source", []) or [])
    try:
        from newton import ShapeFlags  # noqa: PLC0415
        s_flags = _np(model.shape_flags)
        hydro_bit = int(ShapeFlags.HYDROELASTIC)
        collide_bit = int(ShapeFlags.COLLIDE_SHAPES)
    except Exception:                                    # noqa: BLE001
        s_flags, hydro_bit, collide_bit = None, 0, 0

    # The contact material the physics used per shape: the hydroelastic
    # stiffness and the SDF voxel it was flagged with (both None when this
    # Newton keeps neither on the model). export_usd authors them on the
    # collider so a rebuilt scene needs no task file to recover them.
    s_kh = _np(getattr(model, "shape_material_kh", None)) \
        if getattr(model, "shape_material_kh", None) is not None else None
    s_vox = _np(getattr(model, "shape_sdf_target_voxel_size", None)) \
        if getattr(model, "shape_sdf_target_voxel_size", None) is not None else None
    if s_vox is None and shape_voxel:
        s_vox = _voxels_by_label(shape_voxel, s_label, quiet=quiet)

    shapes, n_mesh, n_tri = [], 0, 0
    for k in range(len(s_body)):
        b = int(s_body[k])
        label = s_label[k] if k < len(s_label) else f"shape_{k}"
        gt = int(s_type[k])
        try:
            tname = GeoType(gt).name
        except Exception:                                # noqa: BLE001
            tname = str(gt)
        rec = {
            "index": k,
            "label": label,
            "body": b,
            "body_label": body_label[b] if 0 <= b < n_body else None,
            "type": tname,
            "scale": [float(x) for x in np.asarray(s_scale[k]).reshape(-1)[:3]],
            "transform": _xform(s_xform[k]),
            "mesh": None,
        }
        if s_flags is not None and k < len(s_flags):
            rec["hydroelastic"] = bool(int(s_flags[k]) & hydro_bit)
            # a `visuals/` mesh is a shape too, drawn and never collided; the
            # flag is the only record of which shapes the solver could touch
            rec["collide"] = bool(int(s_flags[k]) & collide_bit)
        if s_kh is not None and k < len(s_kh):
            rec["kh"] = float(s_kh[k])
        if s_vox is not None and k < len(s_vox) and s_vox[k] is not None and float(s_vox[k]) > 0:
            rec["sdf_voxel"] = float(s_vox[k])
        m = _mesh_of(s_src[k] if k < len(s_src) else None)
        if m is not None:
            v, f = m
            fn = f"{k:03d}_{_safe(label.rsplit('/', 1)[-1])}.obj"
            n_tri += _write_obj(os.path.join(out_dir, fn), v, f,
                                f"{label} (Newton shape {k}, body {b})")
            rec["mesh"] = fn
            n_mesh += 1
        shapes.append(rec)

    meta = {
        "note": ("Geometry as the physics had it. Body poses come from "
                 "observation.state via bodies[].joint.state_slice; a shape "
                 "sits at body_pose * shape.transform. Analytic types carry "
                 "their size in `scale` (BOX: half-extents; SPHERE: radius; "
                 "CAPSULE/CYLINDER: radius, half-height). `name` is the last "
                 "path segment and REPEATS across two hands; key on `label` "
                 "or `unique_name`, and `side` says which hand a body is on."),
        "state_coords": n_q,
        "joint_couplings": joint_couplings(model),
        "bodies": bodies,
    }
    with open(os.path.join(out_dir, "bodies.json"), "w") as fh:
        json.dump(meta, fh, indent=1)
    with open(os.path.join(out_dir, "shapes.json"), "w") as fh:
        json.dump({"note": "index is the value used in the contact sidecar's "
                           "_shape_pair column",
                   "shapes": shapes}, fh, indent=1)
    size = sum(os.path.getsize(os.path.join(out_dir, f))
               for f in os.listdir(out_dir))
    out = {"bodies": n_body, "shapes": len(shapes), "meshes": n_mesh,
           "joint_couplings": len(meta["joint_couplings"]),
           "triangles": n_tri, "bytes": size}
    if not quiet:
        print(f"  scene geometry -> {out_dir}: {n_body} bodies, "
              f"{len(shapes)} shapes ({n_mesh} meshes, {n_tri} triangles), "
              f"{size / 1e6:.1f} MB")
    return out


# ------------------------------------------------------------ appearance ----
# What each shape LOOKED like -- colour, hidden, texture -- written into the
# dataset beside the geometry (viz/blender/usd_materials.save). The OBJs above
# are what the physics collided with and say nothing about looks; before this a
# reader recovered colours from the asset USDs scene.json names by absolute
# path, which exist on the recording machine only, so a shipped dataset drew
# every part of an object in one role colour (square_peg_socket's orange head,
# white tail, teal and purple socket frames all gone) and every scan untextured.

def _usd_materials():
    import sys  # noqa: PLC0415
    here = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                        "viz", "blender")
    if here not in sys.path:
        sys.path.insert(0, here)
    import usd_materials  # noqa: PLC0415
    return usd_materials


def export_appearance(assets_dir: str, stage, quiet: bool = False) -> dict:
    """At record time: every task shape's appearance read off the LIVE stage (a shape's label
    is its prim path there), which is what the operator saw -- the table and primitive objects
    included, which have no source file to read later."""
    um = _usd_materials()
    _, shapes = load(assets_dir)
    got = um.for_stage(stage, [s["label"] for s in shapes["shapes"]])
    return um.save(assets_dir, got, "live stage", quiet=quiet)


def _omits_note(builtin: list[str]) -> str:
    return (f"{', '.join(builtin)}: Kit's built-in material, found on Kit's MDL search path "
            "at render time, never a file beside the asset")


def _local_asset(recorded: str) -> str | None:
    """The recorded USD path on this machine: the same file under this checkout
    (rows recorded on machine 2 say /home/rickxu/..., on machine 1 /home/richardxu/...)."""
    if os.path.exists(recorded):
        return recorded
    m = re.search(r"/vr_teleop_pipeline[^/]*/(.+)$", recorded.replace(os.sep, "/"))
    here = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), m.group(1)) if m else None
    return here if here and os.path.exists(here) else None


def backfill_source_assets(root: str, dry_run: bool = False, quiet: bool = False) -> dict:
    """Package the source assets a recording could not, into an existing dataset.

    For every sources.json row with neither `package` nor `not_packaged` (the
    YCB can, hammer and drill, whose OmniPBR.mdl reference made the recorder's
    packaging fail: write_usdz), find the recorded USD in this checkout and
    package it -- ONLY if its sha256 equals the one recorded with the demos, so
    the dataset gains the very file it was recorded against, never a later
    revision. The row keeps its `package_error` as `package_error_at_record`
    and says when and how it was packaged. Nothing recorded is touched."""
    adir = os.path.join(root, "meta", "assets")
    sp = os.path.join(adir, "sources.json")
    out = {"packaged": [], "skipped": {}}
    if not os.path.exists(sp):
        return out
    with open(sp) as fh:
        doc = json.load(fh)
    changed = False
    for r in doc.get("assets") or []:
        if r.get("package") or r.get("not_packaged"):
            continue
        name = r["asset"]
        src = _local_asset(r.get("usd") or "")
        if not src:
            out["skipped"][name] = f"{r.get('usd')} not found in this checkout"
            continue
        if not r.get("sha256") or _sha256(src) != r["sha256"]:
            out["skipped"][name] = f"{src}: sha256 differs from the recorded one"
            continue
        dst = os.path.join(adir, "source_assets", f"{_safe(name)}.usdz")
        if not dry_run:
            os.makedirs(os.path.dirname(dst), exist_ok=True)
            builtin = write_usdz(src, dst)
            if "package_error" in r:
                r["package_error_at_record"] = r.pop("package_error")
            r["package"] = os.path.relpath(dst, adir)
            if builtin:
                r["package_omits"] = _omits_note(builtin)
            import datetime as _dt  # noqa: PLC0415
            r["packaged_after_recording"] = (
                f"{_dt.date.today().isoformat()} by tools/scene_assets.py --source-assets, from "
                f"{os.path.relpath(src, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))}"
                ", whose sha256 equals the one recorded here")
            changed = True
        out["packaged"].append(name)
    if changed:
        tmp = sp + ".tmp"
        with open(tmp, "w") as fh:
            json.dump(doc, fh, indent=1)
        os.replace(tmp, sp)        # a new file: a hard-linked copy elsewhere keeps its own
    if not quiet:
        print(f"  source assets: {'would package' if dry_run else 'packaged'} "
              f"{out['packaged'] or 'nothing'}"
              + "".join(f"\n    skipped {k}: {v}" for k, v in out["skipped"].items()))
    return out


def backfill_appearance(root: str, quiet: bool = False) -> dict:
    """For a dataset recorded before export_appearance: the same record rebuilt from the asset
    USDs meta/scene.json names, and for the table and primitive objects (which Isaac Lab makes
    with no file behind them) the colours the collector gave them -- tools/task_spec's
    TABLE_COLOR, and the recorded task.json's `color` or DEFAULT_COLOR.

    🔴 An asset whose file no longer hashes to what sources.json recorded is REFUSED: its
    parts may have been regenerated since (square_peg_socket's socket was, 2026-09-16), and
    colours read off a different file would be attached to the wrong shapes.
    """
    import sys  # noqa: PLC0415
    repo = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    if repo not in sys.path:
        sys.path.insert(0, repo)
    from tools import task_spec  # noqa: PLC0415
    um = _usd_materials()
    adir = os.path.join(root, "meta", "assets")
    _, shapes = load(adir)
    with open(os.path.join(root, "meta", "scene.json")) as fh:
        scene = json.load(fh)
    task = {}
    tp = os.path.join(root, "meta", "task.json")
    if os.path.exists(tp):
        with open(tp) as fh:
            task = json.load(fh)
    recorded = {}
    sp = os.path.join(adir, "sources.json")
    if os.path.exists(sp):
        with open(sp) as fh:
            recorded = {r["usd"]: r.get("sha256") for r in json.load(fh).get("assets", [])}
    stale = []
    assets = {}
    for name, a in (scene.get("assets") or {}).items():
        if not isinstance(a, dict) or not a.get("usd") or name in ("hand", "hands"):
            continue
        want = recorded.get(a["usd"])
        if want and _sha256(a["usd"]) != want:
            stale.append(name)
            continue
        assets[name] = a
    from_usd = um.for_scene({"assets": assets}, log=lambda *x: None)
    spec_obj = {o["name"]: o for o in task.get("objects", [])}
    target = next((o["name"] for o in task.get("objects", []) if o.get("role") == "target"), None)

    def primitive_rgb(grp):
        if grp == "Table":
            return tuple(task_spec.TABLE_COLOR)
        name = target if grp == "Object" else (grp[len("Prop_"):] if grp.startswith("Prop_") else None)
        o = spec_obj.get(name)
        if o is None or o.get("shape", "cuboid") in task_spec.USD_SHAPES:
            return None
        return tuple(float(c) for c in o.get("color", task_spec.DEFAULT_COLOR))

    by_group = {}
    for s in shapes["shapes"]:
        if um.recordable(s["label"]):
            grp, suffix = um._scene_group(s["label"])
            by_group.setdefault(grp, []).append((s["label"], suffix))
    got, missing = {}, []
    for grp, members in by_group.items():
        visual = {lab for lab, suf in members if "visual" in suf.lower()}
        for lab, suf in members:
            app = (from_usd.get(grp) or {}).get(suf)
            if app is None:
                rgb = primitive_rgb(grp)
                if rgb is None:
                    missing.append(lab)
                    continue
                # A primitive body's collider and its display mesh share one space; the
                # collector draws the display mesh, so that is the one a camera saw.
                app = um.Appearance(rgb=rgb, hidden=bool(visual) and lab not in visual)
            got[lab] = app
    out = um.save(adir, got, "asset USDs (backfill)", quiet=quiet)
    out.update(stale=stale, missing=missing)
    if os.path.isdir(os.path.join(adir, USD_DIR)):
        export_usd(adir, scene=scene, task=task or None, quiet=True)   # colours + guides from the record
    if not quiet and (stale or missing):
        if stale:
            print(f"     ⚠️  not read, the file changed since recording (sha256 vs sources.json): "
                  f"{stale}")
        if missing:
            print(f"     ⚠️  {len(missing)} shape(s) with no appearance: {missing[:4]}"
                  + (" …" if len(missing) > 4 else ""))
    return out


def task_shape_voxels(shapes: list[dict], task: dict, default: float) -> tuple[dict[int, float], dict]:
    """shape index -> the voxel the collector flagged it with, rebuilt from the task file.

    The same rule as collect_env.configure_model: only hydroelastic shapes get one; the
    object is the longest of ``/Object`` (the target) or ``/Prop_<name>`` found in the
    shape's BODY label, and its ``voxel_size`` (else the scene's ``default``) applies;
    then the longest ``voxel_size_parts`` key found in the shape's own label overrides
    it. The hands match no object and keep the default. Also returns which part keys
    matched nothing, as the collector warns about.
    """
    objs = task.get("objects") or []
    target = next((o["name"] for o in objs if o.get("role") == "target"), None)
    key = {o["name"]: "/Object" if o["name"] == target else f"/Prop_{o['name']}" for o in objs}
    vox = {key[o["name"]]: float(o.get("voxel_size", default)) for o in objs}
    parts = {key[o["name"]]: {str(k): float(v) for k, v in o["voxel_size_parts"].items()}
             for o in objs if o.get("voxel_size_parts")}
    out, hit = {}, {(k, p): 0 for k, ps in parts.items() for p in ps}
    for sh in shapes:
        if not sh.get("hydroelastic"):
            continue
        nm = sh.get("body_label") or ""
        vk = max((k for k in vox if k in nm), key=len, default=None)
        v = vox[vk] if vk else float(default)
        if vk in parts:
            pk = max((p for p in parts[vk] if p in sh["label"]), key=len, default=None)
            if pk is not None:
                v = parts[vk][pk]
                hit[(vk, pk)] += 1
        out[int(sh["index"])] = v
    return out, {"unmatched_parts": sorted(f"{k.lstrip('/')}:{p}" for (k, p), n in hit.items() if not n)}


def backfill_voxels(root: str, dry_run: bool = False, quiet: bool = False) -> dict:
    """Write ``sdf_voxel`` into meta/assets/shapes.json for a dataset recorded before the
    exporter had the builder's voxels (every dataset before 2026-10-25: Newton keeps the
    array on the builder, not the Model, so none was written).

    Rebuilt from the dataset's own meta/task.json and meta/scene.json -- the task file
    and scene the collector wrote alongside shapes.json, every session overwriting all
    three together -- with :func:`task_shape_voxels`. A shape that already has a voxel
    keeps it; a disagreement is reported, not overwritten. Each per-object number is
    checked against scene.json's ``sdf_voxel_size_per_object`` first, and a dataset
    where they differ is refused: its task.json is not the file the voxels came from.
    """
    adir = os.path.join(root, "meta", "assets")
    sp = os.path.join(adir, "shapes.json")
    with open(sp) as fh:
        doc = json.load(fh)
    with open(os.path.join(root, "meta", "scene.json")) as fh:
        phys = json.load(fh).get("physics") or {}
    with open(os.path.join(root, "meta", "task.json")) as fh:
        task = json.load(fh)
    default = float(phys["sdf_voxel_size"])
    want = phys.get("sdf_voxel_size_per_object") or {}
    have = {o["name"]: float(o.get("voxel_size", default)) for o in task.get("objects") or []}
    bad = {n: (want[n], have.get(n)) for n in want if have.get(n) is None or abs(want[n] - have[n]) > 1e-12}
    if bad:
        raise ValueError(f"{root}: meta/task.json disagrees with scene.json on {bad} "
                         f"(scene, task) -- not the task file this scene was built from")
    vox, rep = task_shape_voxels(doc["shapes"], task, default)
    written, kept, clash = 0, 0, []
    for sh in doc["shapes"]:
        v = vox.get(int(sh["index"]))
        if v is None:
            continue
        if sh.get("sdf_voxel") is not None:
            kept += 1
            if abs(float(sh["sdf_voxel"]) - v) > 1e-12:
                clash.append((sh["label"], sh["sdf_voxel"], v))
            continue
        sh["sdf_voxel"] = v
        written += 1
    by_value: dict[float, int] = {}
    for v in vox.values():
        by_value[v] = by_value.get(v, 0) + 1
    if written and not dry_run:
        doc["sdf_voxel_note"] = ("sdf_voxel backfilled by tools/scene_assets.py --voxels from "
                                 "meta/task.json (voxel_size, voxel_size_parts) and meta/scene.json "
                                 "(sdf_voxel_size), by the collector's matching rule; the TARGET "
                                 "voxel asked of Newton, as a fresh export records it")
        tmp = sp + ".tmp"
        with open(tmp, "w") as fh:
            json.dump(doc, fh, indent=1)
        os.replace(tmp, sp)
    out = {"written": written, "kept": kept, "clash": clash,
           "mm": {round(k * 1e3, 4): n for k, n in sorted(by_value.items())}, **rep}
    if not quiet:
        print(f"  sdf_voxel: {written} written{' (dry run)' if dry_run else ''}, {kept} already set; "
              f"shapes per voxel (mm): {out['mm']}")
        for c in clash:
            print(f"  ⚠️  {c[0]}: recorded {c[1]} but the task file gives {c[2]} -- left as recorded")
        for u in out["unmatched_parts"]:
            print(f"  ⚠️  voxel_size_parts {u} matched no collider")
    return out


def _joint_type_name(v: int) -> str:
    """Newton JointType name for a raw value, without importing the enum by a
    name that has moved between versions."""
    import newton  # noqa: PLC0415
    for holder in (getattr(newton, "JointType", None),):
        if holder is None:
            continue
        try:
            return holder(v).name
        except Exception:                                # noqa: BLE001
            for nm in dir(holder):
                if not nm.startswith("_") and int(getattr(holder, nm)) == v:
                    return nm
    return str(v)


# --------------------------------------------------------------- reading ----
def load(assets_dir: str):
    """(bodies, shapes) as plain dicts. Companion to `export`, numpy only."""
    with open(os.path.join(assets_dir, "bodies.json")) as fh:
        bodies = json.load(fh)
    with open(os.path.join(assets_dir, "shapes.json")) as fh:
        shapes = json.load(fh)
    return bodies, shapes


def weld_anchored(bodies: dict, ep_meta: dict | None, meta_dir: str | None = None) -> dict:
    """bodies.json with every world-welded root moved to THIS episode's anchor.

    A welded root's pose is not in observation.state (a fixed joint has no
    coordinates): FK takes it from the joint's X_p, and bodies.json holds the
    value the scene was BUILT with, while every episode randomizes the anchor
    and records it in episodes.jsonl. Without this a _fixed task's fixture is
    rebuilt at the build-time anchor, up to half a metre from where the
    episode had it (measured 2026-10-03: 36-57 cm on five _fixed datasets,
    0.0002 mm once anchored). ``meta_dir`` (the dataset's meta/) supplies
    scene.json, which names the target. The same rule as viz/replay.py's
    apply_weld_anchors, kept numpy-only for tools/check_dataset.py.
    """
    try:
        from tools.weld_anchor import episode_anchors
    except ImportError:
        from weld_anchor import episode_anchors
    scene = {}
    sp = os.path.join(meta_dir, "scene.json") if meta_dir else ""
    if sp and os.path.exists(sp):
        with open(sp) as fh:
            scene = json.load(fh)
    target = next((k for k, v in (scene.get("assets") or {}).items()
                   if isinstance(v, dict) and v.get("role") == "target"), None)
    welded = {}
    for b in bodies["bodies"]:
        j = b.get("joint") or {}
        if j.get("type") != "FIXED" or b.get("parent", -1) != -1:
            continue
        parts = [x for x in (b.get("label") or "").split("/") if x]
        seg = (parts[parts.index("env_0") + 1] if "env_0" in parts and
               parts.index("env_0") + 1 < len(parts) else (parts[-1] if parts else ""))
        welded[b["index"]] = (target or "Object") if seg == "Object" else (
            seg[len("Prop_"):] if seg.startswith("Prop_") else seg)
    if not welded:
        return bodies
    by_index = {b["index"]: b for b in bodies["bodies"]}
    nominal = {i: (tuple(by_index[i]["joint"]["X_p"][:3]), tuple(by_index[i]["joint"]["X_p"][3:7]))
               for i in welded}
    moves, _ = episode_anchors(ep_meta or {}, {n: i for i, n in welded.items()}, nominal)
    out = []
    for b in bodies["bodies"]:
        if b["index"] in moves:
            pos, rot = moves[b["index"]]
            b = dict(b, joint=dict(b["joint"], X_p=[*pos, *rot]))
        out.append(b)
    return {**bodies, "bodies": out}


def body_poses(bodies: dict, state: np.ndarray) -> dict[int, np.ndarray]:
    """World pose (7,) per body index for one `observation.state` row.

    Handles the joint types this pipeline records: FREE (7 coords, the pose
    itself), BALL (4, a quaternion), and fixed/absent (the parent's pose).
    Anything else is reported rather than silently mis-posed. Index -1 is the
    world frame, which is what a static shape's `body` field holds.
    """
    def mul(a, b):
        pa, qa = a[:3], a[3:7]
        pb, qb = b[:3], b[3:7]
        return np.concatenate([pa + _rot(qa, pb), _qmul(qa, qb)])

    ident = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0])
    # Body -1 is the WORLD: static colliders (the ground plane) hang off it,
    # and a shape that names it is already in world coordinates.
    out: dict[int, np.ndarray] = {-1: ident}
    for e in bodies["bodies"]:
        j = e.get("joint")
        parent = e.get("parent")
        base = out.get(parent, ident) if (parent is not None and parent >= 0) else ident
        if j is None:
            out[e["index"]] = base
            continue
        q0, q1 = j["state_slice"]
        seg = np.asarray(state[q0:q1], dtype=np.float64)
        t = j["type"].upper()
        Xp = np.asarray(j["X_p"], dtype=np.float64)
        Xc = np.asarray(j["X_c"], dtype=np.float64)
        if t == "FREE" and len(seg) >= 7:
            local = seg[:7]
            out[e["index"]] = local
            continue
        if t == "BALL" and len(seg) >= 4:
            rel = np.concatenate([np.zeros(3), seg[:4]])
        elif len(seg) == 0:
            rel = ident
        elif t in ("REVOLUTE", "PRISMATIC") and len(seg) == 1:
            # One coordinate, and it means nothing without the axis it acts
            # on. `axis` is recorded from newton's joint_axis for datasets
            # written after that was added; older ones (every ARCTIC dataset
            # collected before it) fall back to +Z, which is the axis this
            # pipeline's own importer authors -- tools/import_arctic_asset.py
            # writes a "Z" axis token and puts ARCTIC's (0,0,-1) into X_p/X_c
            # as a 180 degree flip, so the joint frame's +Z is correct there.
            # A dataset from some other source with a non-Z hinge and no
            # recorded axis would be placed wrongly, which is why the axis is
            # now written rather than assumed.
            ax = np.asarray(j.get("axis") or (0.0, 0.0, 1.0), dtype=np.float64)
            n = np.linalg.norm(ax)
            ax = ax / n if n else np.array([0.0, 0.0, 1.0])
            if t == "REVOLUTE":
                half = 0.5 * float(seg[0])
                rel = np.concatenate([np.zeros(3),
                                      ax * np.sin(half), [np.cos(half)]])
            else:
                rel = np.concatenate([ax * float(seg[0]), [0.0, 0.0, 0.0, 1.0]])
        else:
            raise ValueError(f"body {e['name']}: joint type {t} with "
                             f"{len(seg)} coords is not supported here")
        inv_c = np.concatenate([-_rot(_qconj(Xc[3:7]), Xc[:3]), _qconj(Xc[3:7])])
        out[e["index"]] = mul(mul(mul(base, Xp), rel), inv_c)
    return out


def _qmul(a, b):
    ax, ay, az, aw = a
    bx, by, bz, bw = b
    return np.array([aw * bx + ax * bw + ay * bz - az * by,
                     aw * by - ax * bz + ay * bw + az * bx,
                     aw * bz + ax * by - ay * bx + az * bw,
                     aw * bw - ax * bx - ay * by - az * bz])


def _qconj(q):
    return np.array([-q[0], -q[1], -q[2], q[3]])


def _rot(q, v):
    u, w = np.asarray(q[:3]), float(q[3])
    v = np.asarray(v, dtype=np.float64)
    return v + 2.0 * np.cross(u, np.cross(u, v) + w * v)


# ----------------------------------------------------------------- USD ------
# The spawnable form of the export above. bodies.json + shapes.json + OBJs are
# enough to REDRAW the scene with numpy, but a simulator (Isaac Lab) loads USD,
# and every consumer that rebuilt one from the JSON has re-implemented the same
# hundred lines -- and, before the JSON existed, re-imported the SOURCE assets
# through its own copy of the collector's staging and got the scale order or
# the seat height wrong. This writes the USD once, at record time, from the
# same manifest, so a downstream pipeline spawns exactly what the physics
# collided with and never prepares an asset.
#
#     meta/assets/usd/<Group>.usd    one file per body group: Table, Object (the
#                                    target, one or several links), Prop_<name>
#     meta/assets/usd/index.json     per group: role, kinematic, spawn pose,
#                                    links, joints, voxels -- what a spawner needs
#
# A group is the bodies that share the first path segment after env_<k>/. A
# single-link group is one rigid body; a multi-link group is an articulation
# rooted at the link with no parent in the group, its joints authored with the
# recorded frames, axis and limits. Every prim sits at its RECORDED path under
# the group (/Object/base/collisions/mesh_0/box), so a model built from the
# file labels its bodies and shapes as the recording did. The two hands are
# never exported: they are what a retargeting pipeline replaces.

USD_DIR = "usd"

#: importer upper limits (deg) per ARCTIC object (tools/import_arctic_asset.py
#: --upper-deg), the last fallback for a dataset recorded before bodies.json
#: carried `limit`
_UPPER_DEG = {"box": 110.0, "phone": 135.0, "microwave": 100.0, "laptop": 129.7,
              "notebook": 180.0, "ketchup": 164.5, "mixer": 96.4, "waffleiron": 120.0,
              "capsulemachine": 105.0, "espressomachine": 80.0}
_PRISMATIC_UPPER_M = 0.2


def _t_mul(a, b):
    a, b = np.asarray(a, float), np.asarray(b, float)
    return np.concatenate([a[:3] + _rot(a[3:7], b[:3]), _qmul(a[3:7], b[3:7])])


def _t_inv(a):
    a = np.asarray(a, float)
    q = _qconj(a[3:7])
    return np.concatenate([-_rot(q, a[:3]), q])


def _t_apply(a, v):
    a = np.asarray(a, float)
    return _rot(a[3:7], np.asarray(v, float)) + a[:3]


def _group_tail(label: str) -> str | None:
    import re  # noqa: PLC0415
    m = re.search(r"/env_\d+/(.*)$", label)
    return m.group(1) if m else None


def _joint_limit_fallback(joint: dict, group: str, oname: str | None, task: dict,
                          sources: dict, assets_dir: str) -> tuple[float, float, str]:
    """(lower, upper, where) in SI for a manifest without `limit`: the source
    asset as vendored (the joint prim by name), else the task file's explicit
    limits, else the importer's known upper angle, else a wide default."""
    o = next((o for o in (task.get("objects") or []) if o.get("name") == oname), {}) if oname else {}
    src = next((a for a in (sources.get("assets") or []) if a.get("asset") == oname), {})
    usd = src.get("usd")
    if usd and os.path.exists(usd):
        try:
            import math  # noqa: PLC0415

            from pxr import Usd, UsdPhysics  # noqa: PLC0415
            stage = Usd.Stage.Open(usd)
            for prim in stage.Traverse():
                if prim.GetPath().name != joint["name"]:
                    continue
                if prim.IsA(UsdPhysics.RevoluteJoint):
                    j = UsdPhysics.RevoluteJoint(prim)
                    return (math.radians(float(j.GetLowerLimitAttr().Get() or 0.0)),
                            math.radians(float(j.GetUpperLimitAttr().Get() or 0.0)), "source asset")
                if prim.IsA(UsdPhysics.PrismaticJoint):
                    j = UsdPhysics.PrismaticJoint(prim)
                    s = float(src.get("spawn", {}).get("scale", o.get("scale", 1.0)))
                    return (float(j.GetLowerLimitAttr().Get() or 0.0) * s,
                            float(j.GetUpperLimitAttr().Get() or 0.0) * s, "source asset")
        except Exception:                                # noqa: BLE001
            pass
    jn = dict(o.get("joint") or {})
    cfgs = {jn["name"]: jn} if jn.get("name") else {}
    for nm, sub in (jn.get("joints") or {}).items():
        cfgs[nm] = {**{k: v for k, v in jn.items() if k not in ("name", "joints")}, **(sub or {})}
    c = cfgs.get(joint["name"], jn)
    lo = float(c.get("limit_lower", c.get("lower", 0.0)))
    if joint["type"] == "REVOLUTE":
        import math  # noqa: PLC0415
        import re  # noqa: PLC0415
        if "limit_upper" in c or "upper" in c:
            return lo, math.radians(float(c.get("limit_upper", c.get("upper")))), "task file"
        m = re.search(r"--upper-deg\s+([0-9.]+)", o.get("_rebuild", "") or "")
        if m:
            return lo, math.radians(float(m.group(1))), "task file _rebuild"
        base = os.path.basename(o.get("usd", "")).replace("arctic_", "").split(".")[0]
        if base in _UPPER_DEG:
            return lo, math.radians(_UPPER_DEG[base]), "importer table"
        return lo, math.pi, "DEFAULT"
    if "limit_upper" in c or "upper" in c or "upper_m" in o:
        return lo, float(c.get("limit_upper", c.get("upper", o.get("upper_m")))), "task file"
    return lo, _PRISMATIC_UPPER_M, "DEFAULT"


def usd_groups(assets_dir: str, scene: dict | None = None, task: dict | None = None) -> list[dict]:
    """The non-hand body groups of an export, each with everything a USD and a
    spawner need. Pure manifest reading; no USD library."""
    bodies, shapes = load(assets_dir)
    couplings = bodies.get("joint_couplings")
    bodies, shapes = bodies["bodies"], shapes["shapes"]
    scene = scene or {}
    task = task or {}
    sources = {}
    sp = os.path.join(assets_dir, "sources.json")
    if os.path.exists(sp):
        with open(sp) as fh:
            sources = json.load(fh)
    by_index = {b["index"]: b for b in bodies}
    links: dict[str, list[dict]] = {}
    for b in bodies:
        if b.get("side") is not None or "/Hand" in b["label"]:
            continue                                   # the recording hand(s): replaced downstream
        tail = _group_tail(b["label"])
        if tail is None:
            continue                                   # /World/ground and the like
        grp = tail.split("/")[0]
        link = {"index": int(b["index"]), "name": tail.split("/")[-1], "tail": tail,
                "parent": int(b["parent"]) if b.get("parent") is not None else -1,
                "mass": float(b.get("mass", 0.0)), "com": [float(v) for v in (b.get("com") or [0, 0, 0])],
                "inertia": b.get("inertia"), "gravcomp": b.get("gravcomp"), "joint": b.get("joint") or {}, "shapes": []}
        for s in shapes:
            if s["body"] != b["index"] or s["type"] == "PLANE":
                continue
            if s["type"].upper() not in ("MESH", "CONVEX_MESH", "BOX"):
                raise NotImplementedError(f"{tail}: shape type {s['type']} is not exported as USD")
            link["shapes"].append(s)
        links.setdefault(grp, []).append(link)
    objs = {o["name"]: o for o in (task.get("objects") or [])}
    target = next((o["name"] for o in (task.get("objects") or []) if o.get("role") == "target"), None)
    rec_assets = scene.get("assets") or {}
    voxel_default = float((scene.get("physics") or {}).get("sdf_voxel_size",
                          (task.get("physics") or {}).get("voxel_size", 0.002)))
    out = []
    for grp, ls in links.items():
        idx = {l["index"] for l in ls}
        root = next(l for l in ls if l["parent"] not in idx)
        joints = []
        for l in ls:
            jt = str(l["joint"].get("type", "")).upper()
            if jt in ("REVOLUTE", "PRISMATIC") and l["parent"] in idx:
                joints.append({"parent": by_index[l["parent"]]["name"], "child": l["name"], "type": jt,
                               "X_p": l["joint"]["X_p"], "X_c": l["joint"]["X_c"],
                               "axis": l["joint"].get("axis", [0, 0, 1]),
                               "name": str(l["joint"].get("label", "joint")).rsplit("/", 1)[-1],
                               "label": l["joint"].get("label"),
                               "limit": l["joint"].get("limit")})
        if grp == "Table":
            oname, role = None, "table"
            tb = rec_assets.get("table") or scene.get("table") or {}
            pos = tb.get("pos") or (task.get("table") or {}).get("pos") or [0, 0, 0]
            spawn = [*map(float, pos), 0.0, 0.0, 0.0, 1.0]
            kin, voxel, parts = True, float(os.environ.get("VR_TABLE_VOXEL", 0.004)), {}
        else:
            oname = target if grp == "Object" else grp[len("Prop_"):] if grp.startswith("Prop_") else grp
            role = "target" if grp == "Object" else "prop"
            rec = rec_assets.get(oname, {})
            o = objs.get(oname, {})
            pos = rec.get("pos")
            if pos is None:
                raise RuntimeError(f"{assets_dir}: scene.json has no spawn pose for {oname}")
            spawn = [*map(float, pos), *map(float, rec.get("rot_xyzw") or [0, 0, 0, 1])]
            kin = bool(rec.get("fixed", o.get("fixed", o.get("fixed_base", False))))
            voxel = float(rec.get("voxel_size", o.get("voxel_size", voxel_default)))
            parts = {k: float(v) for k, v in (rec.get("voxel_size_parts") or o.get("voxel_size_parts") or {}).items()}
        # a root whose recorded joint is FIXED sat on a weld to the world (the nail
        # block, the threaded bolt): an articulation spawns with its root fixed,
        # a lone body as kinematic. `fixed` in scene.json is the kinematic flag
        # of a rigid prop (socket, jack); both are reported
        welded = str(root["joint"].get("type", "")).upper() == "FIXED"
        if welded and len(ls) == 1:
            kin = True
        for j in joints:
            if j["limit"] is None:
                lo, hi, where = _joint_limit_fallback(j, grp, oname, task, sources, assets_dir)
                j["limit"] = [lo, hi]
                j["limit_source"] = where
            else:
                j["limit_source"] = "recorded"
        out.append({"name": grp, "object_name": oname, "role": role, "links": ls, "root": root["name"],
                    "joints": joints, "kinematic": kin, "fixed_base": welded, "spawn_pose": spawn,
                    "voxel": voxel, "voxel_parts": parts})
    order = {"Table": 0, "Object": 1}
    owners = {j["label"]: g for g in out for j in g["joints"]}
    for g in out:
        g["joint_couplings"] = [] if couplings is not None else None
    for coupling in couplings or []:
        follower, leader = coupling["follower"], coupling["leader"]
        gf, gl = owners.get(follower), owners.get(leader)
        if gf is None and gl is None:
            # The scene export excludes the recorded hands. Other missing
            # endpoints indicate a constraint the USD cannot reproduce.
            if all("/Hand" in label for label in (follower, leader)):
                continue
            raise ValueError(f"Coupling endpoints absent from scene: {follower}, {leader}")
        if gf is None or gf is not gl:
            raise ValueError(f"Cross-group joint coupling cannot be exported as separate USDs: {follower}, {leader}")
        gf["joint_couplings"].append(coupling)
    return sorted(out, key=lambda g: (order.get(g["name"], 2), g["name"]))


def _box_mesh(half):
    h = np.asarray(half, dtype=np.float64)
    v = np.array([[sx, sy, sz] for sx in (-h[0], h[0]) for sy in (-h[1], h[1]) for sz in (-h[2], h[2])])
    f = np.array([[0, 1, 3], [0, 3, 2], [4, 6, 7], [4, 7, 5], [0, 4, 5], [0, 5, 1],
                  [2, 3, 7], [2, 7, 6], [0, 2, 6], [0, 6, 4], [1, 5, 7], [1, 7, 3]])
    return v, f


def _collides(s: dict) -> bool:
    """Did the solver collide this shape? The recorded flag when the export has it; for an older export the
    prim path: a `visuals/` scope or a `_visual` mesh is drawn only (the peg's and the socket's `visuals/`
    boxes never appear in the contact sidecar, only their `collisions/` twins do)."""
    if "collide" in s:
        return bool(s["collide"])
    tail = s["label"].split("/env_0/")[-1] if "/env_0/" in s["label"] else s["label"]
    return "/visuals/" not in f"/{tail}" and "visual" not in tail.rsplit("/", 1)[-1]


def _load_obj(path: str):
    v, f = [], []
    with open(path) as fh:
        for line in fh:
            if line.startswith("v "):
                v.append([float(x) for x in line.split()[1:4]])
            elif line.startswith("f "):
                idx = [int(t.split("/")[0]) - 1 for t in line.split()[1:]]
                for i in range(1, len(idx) - 1):
                    f.append([idx[0], idx[i], idx[i + 1]])
    return np.asarray(v, dtype=np.float64).reshape(-1, 3), np.asarray(f, dtype=np.int64).reshape(-1, 3)


def _write_group_usd(g: dict, assets_dir: str, out_dir: str, color) -> tuple[str, int]:
    import math  # noqa: PLC0415

    from pxr import Gf, Sdf, Usd, UsdGeom, UsdPhysics, Vt  # noqa: PLC0415
    path = os.path.join(out_dir, f"{g['name']}.usd")
    if os.path.exists(path):
        os.remove(path)
    stage = Usd.Stage.CreateNew(path)
    UsdGeom.SetStageMetersPerUnit(stage, 1.0)
    UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
    single = len(g["links"]) == 1
    root = UsdGeom.Xform.Define(stage, f"/{g['name']}")
    stage.SetDefaultPrim(root.GetPrim())
    Usd.ModelAPI(root.GetPrim()).SetKind("component")
    # rest pose of every link relative to the root link (q = 0), through the
    # recorded joint frames: X_root_link = X_root_parent * X_p * X_c^-1
    by_index = {l["index"]: l for l in g["links"]}
    rest = {g["root"]: np.array([0, 0, 0, 0, 0, 0, 1.0])}
    pending = [l for l in g["links"] if l["name"] != g["root"]]
    guard = 0
    while pending:
        l = pending.pop(0)
        pn = by_index[l["parent"]]["name"]
        if pn not in rest:
            pending.append(l)
            guard += 1
            if guard > 10 * len(g["links"]):
                raise RuntimeError(f"{g['name']}: link tree does not close")
            continue
        rest[l["name"]] = _t_mul(_t_mul(rest[pn], l["joint"]["X_p"]), _t_inv(l["joint"]["X_c"]))
    faces = 0
    # every prim at its RECORDED path (/Object/base/collisions/mesh_0/box), so the shapes and bodies of a model
    # built from this file carry the same labels as the recording's, and a record of the one can be diffed
    # against the other name by name (compare below)
    for l in g["links"]:
        prim_path = f"/{l['tail']}"
        for depth in range(2, len(prim_path.split("/"))):
            UsdGeom.Xform.Define(stage, "/".join(prim_path.split("/")[:depth]))
        link = UsdGeom.Xform.Define(stage, prim_path)
        p = rest[l["name"]]
        if not single and (np.linalg.norm(p[:3]) > 1e-9 or abs(p[6] - 1.0) > 1e-9):
            q = Gf.Quatd(float(p[6]), Gf.Vec3d(float(p[3]), float(p[4]), float(p[5])))
            M = Gf.Matrix4d().SetRotate(q)
            M.SetTranslateOnly(Gf.Vec3d(*map(float, p[:3])))
            link.AddTransformOp().Set(M)
        UsdPhysics.RigidBodyAPI.Apply(link.GetPrim())
        if not single and l["name"] == g["root"]:
            UsdPhysics.ArticulationRootAPI.Apply(link.GetPrim())
        if l.get("gravcomp"):
            link.GetPrim().CreateAttribute("mjc:gravcomp", Sdf.ValueTypeNames.Float).Set(float(l["gravcomp"]))   # read by Isaac Lab's Newton schema
        mass = UsdPhysics.MassAPI.Apply(link.GetPrim())
        mass.CreateMassAttr(float(l["mass"]))
        mass.CreateCenterOfMassAttr(Gf.Vec3f(*map(float, l["com"])))
        if l.get("inertia") is not None:
            # the recorded tensor as principal moments + axes (what MassAPI takes); an importer left to derive
            # one from the mesh would give the body a different one
            I = np.asarray(l["inertia"], dtype=np.float64).reshape(3, 3)
            w, V = np.linalg.eigh(0.5 * (I + I.T))
            if np.linalg.det(V) < 0:
                V[:, 2] = -V[:, 2]
            from scipy.spatial.transform import Rotation as _R  # noqa: PLC0415
            q = _R.from_matrix(V).as_quat()
            mass.CreateDiagonalInertiaAttr(Gf.Vec3f(*map(float, np.maximum(w, 0.0))))
            mass.CreatePrincipalAxesAttr(Gf.Quatf(float(q[3]), Gf.Vec3f(float(q[0]), float(q[1]), float(q[2]))))
        for s in l["shapes"]:
            kind = s["type"].upper()
            stail = _group_tail(s["label"]) or f"{l['tail']}/{_safe(s['label'].rsplit('/', 1)[-1])}"
            spath = "/" + stail
            for depth in range(len(prim_path.split("/")) + 1, len(spath.split("/"))):
                UsdGeom.Xform.Define(stage, "/".join(spath.split("/")[:depth]))
            # the shape in ITS OWN frame, placed by xformOps: the recorded pose in the link frame and the
            # recorded scale, so the model built from this file carries the same shape_transform and
            # shape_scale as the recording (baking them into the points changes neither the physics nor
            # the picture, but it is not the same record)
            if kind == "BOX":
                geom = UsdGeom.Cube.Define(stage, spath)
                geom.CreateSizeAttr(2.0)                                      # half-extents = size/2 * scale
            else:
                v, f = _load_obj(os.path.join(assets_dir, s["mesh"]))
                geom = UsdGeom.Mesh.Define(stage, spath)
                geom.CreatePointsAttr(Vt.Vec3fArray([Gf.Vec3f(*map(float, q)) for q in v]))
                geom.CreateFaceVertexCountsAttr(Vt.IntArray([3] * len(f)))
                geom.CreateFaceVertexIndicesAttr(Vt.IntArray([int(i) for tri in f for i in tri]))
                geom.CreateSubdivisionSchemeAttr(UsdGeom.Tokens.none)
                geom.CreateExtentAttr(Vt.Vec3fArray([Gf.Vec3f(*map(float, v.min(0))), Gf.Vec3f(*map(float, v.max(0)))]))
            t = np.asarray(s["transform"], dtype=np.float64)
            xf = UsdGeom.Xformable(geom)
            if np.linalg.norm(t[:3]) > 0:
                xf.AddTranslateOp().Set(Gf.Vec3d(*map(float, t[:3])))
            if abs(t[6] - 1.0) > 1e-12 or np.linalg.norm(t[3:6]) > 0:
                xf.AddOrientOp().Set(Gf.Quatf(float(t[6]), Gf.Vec3f(float(t[3]), float(t[4]), float(t[5]))))
            sc = np.asarray(s["scale"], dtype=np.float64)
            if kind == "BOX" or np.any(np.abs(sc - 1.0) > 1e-12):
                xf.AddScaleOp().Set(Gf.Vec3f(*map(float, sc)))
            # How the shape LOOKED when it was recorded (shapes[].appearance): its own colour, and
            # purpose `guide` for one no camera drew -- a collider behind the part it stands in for,
            # exactly as the source asset authored it. The role colour only where nothing was recorded.
            app = s.get("appearance") or {}
            geom.CreateDisplayColorAttr(Vt.Vec3fArray([Gf.Vec3f(*(app.get("rgb") or color))]))
            if app.get("hidden"):
                UsdGeom.Imageable(geom).CreatePurposeAttr(UsdGeom.Tokens.guide)
            visual = not _collides(s)
            prim = geom.GetPrim()
            prim.CreateAttribute("vr:shapeIndex", Sdf.ValueTypeNames.Int).Set(int(s["index"]))
            if visual:
                continue                                                      # a plain mesh: drawn, a shape the solver never collides
            UsdPhysics.CollisionAPI.Apply(prim)
            if kind != "BOX":
                # a CONVEX_MESH (a primitive cylinder's collider) was collided as its hull; everything else as-is
                UsdPhysics.MeshCollisionAPI.Apply(prim).CreateApproximationAttr("convexHull" if kind == "CONVEX_MESH" else "none")
            f = f if kind != "BOX" else np.zeros((12, 3))
            vox = float(s.get("sdf_voxel") or 0.0)
            if vox <= 0.0:                                                   # older export: the scene's values
                vox = g["voxel"]
                for frag, vv in sorted(g["voxel_parts"].items(), key=lambda kv: len(kv[0])):
                    if frag in s["label"].split("env_0/")[-1]:
                        vox = vv
            if kind != "CONVEX_MESH":
                # Newton refuses a convexHull approximation on a prim that also asks for an SDF; the voxel is set on
                # the builder at MODEL_INIT anyway (the collector never authored it on a prim)
                prim.CreateAttribute("newton:sdfTargetVoxelSize", Sdf.ValueTypeNames.Float).Set(float(vox))
            prim.CreateAttribute("vr:sdfVoxel", Sdf.ValueTypeNames.Float).Set(float(vox))
            prim.CreateAttribute("vr:hydroelastic", Sdf.ValueTypeNames.Bool).Set(bool(s.get("hydroelastic", False)))
            if s.get("kh") is not None:
                prim.CreateAttribute("vr:kh", Sdf.ValueTypeNames.Float).Set(float(s["kh"]))
            faces += len(f)
    joint_prims = {}
    for j in g["joints"]:
        cls = UsdPhysics.RevoluteJoint if j["type"] == "REVOLUTE" else UsdPhysics.PrismaticJoint
        tails = {l["name"]: l["tail"] for l in g["links"]}
        jp = cls.Define(stage, f"/{tails[j['parent']]}/{j['name']}")
        joint_prims[j.get("label")] = jp.GetPrim()
        jp.CreateBody0Rel().SetTargets([Sdf.Path(f"/{tails[j['parent']]}")])
        jp.CreateBody1Rel().SetTargets([Sdf.Path(f"/{tails[j['child']]}")])
        jp.CreateAxisAttr("XYZ"[int(np.argmax(np.abs(np.asarray(j["axis"], float))))])
        Xp, Xc = np.asarray(j["X_p"], float), np.asarray(j["X_c"], float)
        jp.CreateLocalPos0Attr(Gf.Vec3f(*map(float, Xp[:3])))
        jp.CreateLocalRot0Attr(Gf.Quatf(float(Xp[6]), Gf.Vec3f(*map(float, Xp[3:6]))))
        jp.CreateLocalPos1Attr(Gf.Vec3f(*map(float, Xc[:3])))
        jp.CreateLocalRot1Attr(Gf.Quatf(float(Xc[6]), Gf.Vec3f(*map(float, Xc[3:6]))))
        lo, hi = j["limit"]
        if j["type"] == "REVOLUTE":                                          # USD: degrees for a hinge, metres for a slide
            lo, hi = math.degrees(lo), math.degrees(hi)
        jp.CreateLowerLimitAttr(float(lo))
        jp.CreateUpperLimitAttr(float(hi))
    authored = set()
    for coupling in g.get("joint_couplings") or []:
        follower = joint_prims[coupling["follower"]]
        leader = joint_prims[coupling["leader"]]
        if follower.GetPath() in authored:
            raise ValueError(f"Multiple couplings on {follower.GetPath()} cannot be represented by joint APIs")
        authored.add(follower.GetPath())
        coefficients = coupling["coefficients"]
        equality = coupling["kind"] == "equality"
        if coupling["kind"] not in ("mimic", "equality") or len(coefficients) != (5 if equality else 2):
            raise ValueError(f"Invalid joint coupling: {coupling}")
        schemas = ["NewtonMimicAPI"] + (["MjcEqualityJointAPI"] if equality else [])
        # Author tokens even when the offline USD installation has not loaded
        # the Newton/MuJoCo schema plugins. GetAppliedSchemas loses unknown APIs.
        follower.SetMetadata("apiSchemas", Sdf.TokenListOp.CreateExplicit(schemas))
        follower.CreateRelationship("newton:mimicJoint").SetTargets([leader.GetPath()])
        offset = math.degrees(coefficients[0]) if follower.IsA(UsdPhysics.RevoluteJoint) else coefficients[0]
        follower.CreateAttribute("newton:mimicCoef0", Sdf.ValueTypeNames.Float).Set(float(offset))
        follower.CreateAttribute("newton:mimicCoef1", Sdf.ValueTypeNames.Float).Set(float(coefficients[1]))
        follower.CreateAttribute("newton:mimicEnabled", Sdf.ValueTypeNames.Bool).Set(bool(coupling["enabled"]))
        if equality:
            # Legacy Newton reads the MuJoCo aliases (offset already in SI),
            # whereas current Newton reads newton:mimicCoef0 in USD units.
            follower.CreateRelationship("mjc:target").SetTargets([leader.GetPath()])
            for k in (0, 1):
                follower.CreateAttribute(f"mjc:coef{k}", Sdf.ValueTypeNames.Double).Set(float(coefficients[k]))
            if "solref" in coupling:
                follower.CreateAttribute("mjc:solref", Sdf.ValueTypeNames.Double2).Set(Gf.Vec2d(*coupling["solref"]))
            if "solimp" in coupling:
                follower.CreateAttribute("mjc:solimp", Sdf.ValueTypeNames.DoubleArray).Set(coupling["solimp"])
            for k in range(2, 5):
                follower.CreateAttribute(f"mjc:coef{k}", Sdf.ValueTypeNames.Double).Set(float(coefficients[k]))
    stage.GetRootLayer().Save()
    return path, faces


def _body_manifest_sha256(assets_dir: str) -> str:
    """Content identity survives ZIP extraction and copying between machines."""
    import hashlib
    with open(os.path.join(assets_dir, "bodies.json"), "rb") as fh:
        return hashlib.sha256(fh.read()).hexdigest()


def export_usd(assets_dir: str, scene: dict | None = None, task: dict | None = None,
               out_dir: str | None = None, quiet: bool = False) -> dict:
    """Write <assets_dir>/usd/<Group>.usd for every non-hand body group of an
    export, and usd/index.json with what a spawner needs per group. Reads only
    the manifest, so it runs at record time right after export() and offline
    on any dataset that has one. Returns the index."""
    out_dir = out_dir or os.path.join(assets_dir, USD_DIR)
    os.makedirs(out_dir, exist_ok=True)
    if scene is None:
        p = os.path.join(os.path.dirname(assets_dir), "scene.json")
        scene = json.load(open(p)) if os.path.exists(p) else {}
    if task is None:
        p = os.path.join(os.path.dirname(assets_dir), "task.json")
        task = json.load(open(p)) if os.path.exists(p) else {}
    colors = {"table": (0.96, 0.96, 0.96), "target": (0.36, 0.56, 0.86), "prop": (0.80, 0.62, 0.40)}
    index = {"note": ("One USD per recorded body group, built from bodies.json / shapes.json / the OBJs: "
                      "the colliders the physics had, `approximation = none`, the recorded masses, COMs, "
                      "joints and limits. Spawn each at `spawn_pose` (world, xyzw); `kinematic`: a rigid body that "
                      "never moves; `fixed_base`: an articulation whose root was welded to the world. "
                      "Per collider: newton:sdfTargetVoxelSize, vr:hydroelastic, vr:kh, vr:shapeIndex "
                      "(the contact sidecar's shape index). The hands are not here."),
             "joint_couplings_version": 1,
             "source": os.path.relpath(os.path.join(assets_dir, "bodies.json"), out_dir),
             "source_mtime": os.path.getmtime(os.path.join(assets_dir, "bodies.json")),
             "source_sha256": _body_manifest_sha256(assets_dir),
             "groups": {}}
    n_faces = 0
    for g in usd_groups(assets_dir, scene, task):
        path, faces = _write_group_usd(g, assets_dir, out_dir, colors[g["role"]])
        n_faces += faces
        index["groups"][g["name"]] = {
            "usd": os.path.basename(path), "role": g["role"], "object_name": g["object_name"],
            "kinematic": g["kinematic"], "fixed_base": g["fixed_base"], "spawn_pose": g["spawn_pose"], "root": g["root"],
            "links": {l["name"]: {"mass": l["mass"], "com": l["com"], "body_index": l["index"],
                                  "shapes": [s["index"] for s in l["shapes"]]} for l in g["links"]},
            "joints": [{k: v for k, v in j.items()} for j in g["joints"]],
            "joint_couplings": g["joint_couplings"],
            "voxel": g["voxel"], "voxel_parts": g["voxel_parts"], "faces": faces}
        if not quiet:
            jl = ", ".join(f"{j['name']} [{j['limit'][0]:.3g}, {j['limit'][1]:.3g}] ({j['limit_source']})" for j in g["joints"])
            print(f"    {g['name']:18s} {g['role']:6s} {'kinematic' if g['kinematic'] else 'welded' if g['fixed_base'] else 'dynamic':9s} "
                  f"links={[l['name'] for l in g['links']]} faces={faces}" + (f" joints: {jl}" if jl else ""))
    with open(os.path.join(out_dir, "index.json"), "w") as fh:
        json.dump(index, fh, indent=1)
    if not quiet:
        unknown = [name for name, g in index["groups"].items() if g["joint_couplings"] is None]
        if unknown:
            print(f"  joint couplings unavailable in this older manifest ({', '.join(unknown)}); "
                  "--amend with a matching collector model record to recover them")
        print(f"  scene USD -> {out_dir}: {len(index['groups'])} groups, {n_faces} collider faces")
    return index


def amend_manifest(assets_dir: str, record: dict, quiet: bool = False) -> dict:
    """Fill the fields an older export never wrote -- bodies: inertia, joint limit; shapes: collide, kh,
    sdf_voxel -- from a physics record of the same task (collect_env.py --dump-model, i.e. the collector
    rebuilding the recorded task file with the recorded config), matched by label. Fields the manifest already
    has are kept. Returns the counts written; rewrites bodies.json / shapes.json in place with an `amended`
    note."""
    bp, sp = os.path.join(assets_dir, "bodies.json"), os.path.join(assets_dir, "shapes.json")
    with open(bp) as fh:
        bodies = json.load(fh)
    with open(sp) as fh:
        shapes = json.load(fh)
    n = {"inertia": 0, "gravcomp": 0, "limit": 0, "kh": 0, "sdf_voxel": 0}
    n["joint_couplings"] = 0
    if "joint_couplings" not in bodies and "joint_couplings" in record:
        bodies["joint_couplings"] = record["joint_couplings"]
        n["joint_couplings"] = 1  # also persist an explicitly empty list
    rb, rj, rs = record.get("bodies", {}), record.get("joints", {}), record.get("shapes", {})
    for b in bodies["bodies"]:
        tail = _tail_of(b["label"])
        if tail is None or b.get("side") is not None or "/Hand" in b["label"]:
            continue
        r = rb.get(tail)
        if r and "inertia" not in b and r.get("inertia_diag") is not None and r.get("inertia") is None:
            d = r["inertia_diag"]; b["inertia"] = [d[0], 0, 0, 0, d[1], 0, 0, 0, d[2]]; n["inertia"] += 1
        elif r and "inertia" not in b and r.get("inertia") is not None:
            b["inertia"] = r["inertia"]; n["inertia"] += 1
        if r and "gravcomp" not in b and r.get("mujoco:gravcomp"):
            b["gravcomp"] = float(r["mujoco:gravcomp"]); n["gravcomp"] += 1
        j = rj.get(tail)
        if j and b.get("joint") and "limit" not in b["joint"] and j.get("limit_lower") is not None:
            b["joint"]["limit"] = [j["limit_lower"], j["limit_upper"]]; n["limit"] += 1
    for sh in shapes["shapes"]:
        tail = _tail_of(sh["label"])
        r = rs.get(tail) if tail else None
        if not r:
            continue
        for k in ("kh", "sdf_voxel"):                  # never `collide`: a rebuild today may stage a visual as a
            if k not in sh and r.get(k) is not None and (k != "sdf_voxel" or float(r[k]) > 0):   # collider the recording did not have
                sh[k] = r[k]; n[k] += 1
    if any(n.values()):
        note = f"amended from a collector --dump-model record: {', '.join(f'{k} x{v}' for k, v in n.items() if v)}"
        bodies.setdefault("amended", []).append(note); shapes.setdefault("amended", []).append(note)
        with open(bp, "w") as fh:
            json.dump(bodies, fh, indent=1)
        with open(sp, "w") as fh:
            json.dump(shapes, fh, indent=1)
    if not quiet:
        print(f"  manifest amended: " + ", ".join(f"{k} x{v}" for k, v in n.items()) if any(n.values()) else "  manifest complete, nothing amended")
    return n


def usd_fresh(assets_dir: str) -> bool:
    """Check body-manifest content identity; retain mtime fallback for older exports."""
    p = os.path.join(assets_dir, USD_DIR, "index.json")
    src = os.path.join(assets_dir, "bodies.json")
    if not (os.path.exists(p) and os.path.exists(src)):
        return False
    try:
        with open(p) as fh:
            idx = json.load(fh)
        same_source = (idx["source_sha256"] == _body_manifest_sha256(assets_dir)
                       if "source_sha256" in idx else
                       abs(float(idx.get("source_mtime", -1)) - os.path.getmtime(src)) < 1e-6)
        return idx.get("joint_couplings_version") == 1 and same_source and all(
            os.path.exists(os.path.join(assets_dir, USD_DIR, g["usd"])) for g in idx["groups"].values())
    except (OSError, ValueError, KeyError):
        return False


# --------------------------------------------------------- comparison ------
# Is the scene a downstream simulator built THE scene? `physics_record` reads
# everything contact-relevant off a Newton model, keyed by the body/shape path
# after env_0/ so two models built from different USDs line up; `compare`
# diffs two such records. The collector writes its own with --dump-model, the
# retargeting pipeline writes one from its env and compares.

_SHAPE_ATTRS = ("shape_material_mu", "shape_material_mu_torsional", "shape_material_mu_rolling",
                "shape_material_kh", "shape_material_ke", "shape_material_kd", "shape_material_kf",
                "shape_material_ka", "shape_material_restitution", "shape_sdf_target_voxel_size",
                "shape_thickness", "shape_collision_group")
_JOINT_ATTRS = ("joint_friction", "joint_armature", "joint_limit_lower", "joint_limit_upper",
                "joint_limit_ke", "joint_limit_kd", "joint_target_ke", "joint_target_kd",
                "joint_effort_limit", "joint_velocity_limit")
_CUSTOM = ("mujoco:solref", "mujoco:solref_mode", "mujoco:geom_solimp", "mujoco:condim")   # per shape
_CUSTOM_DOF = ("mujoco:dof_passive_damping",)                                                 # per dof
_CUSTOM_BODY = ("mujoco:gravcomp",)                                                           # per body


def _custom(model, name: str):
    """A builder custom attribute as it survives on the model, whichever spelling this Newton uses."""
    ns, _, attr = name.partition(":")
    for cand in (lambda: getattr(getattr(model, ns), attr),
                 lambda: model.custom_attributes[name],
                 lambda: model.get_attribute(name),
                 lambda: getattr(model, name.replace(":", "_"))):
        try:
            v = cand()
        except Exception:                                # noqa: BLE001
            continue
        if v is None:
            continue
        vals = getattr(v, "values", v)
        if isinstance(vals, dict):
            return {int(k): (list(map(float, np.asarray(x).reshape(-1))) if np.ndim(x) else float(x)) for k, x in vals.items()}
        try:
            a = _np(vals)
        except Exception:                                # noqa: BLE001
            continue
        return a
    return None


def _tail_of(label: str) -> str | None:
    import re  # noqa: PLC0415
    m = re.search(r"/env_\d+/(.*)$", label)
    return m.group(1) if m else None


def _mesh_digest(source) -> dict | None:
    m = _mesh_of(source)
    if m is None:
        return None
    v, f = m
    return {"vertices": int(len(v)), "faces": int(len(f)),
            "bbox": [float(x) for x in np.concatenate([v.min(0), v.max(0)])],
            "centroid": [float(x) for x in v.mean(0)]}


def physics_record(model, hands: bool = False) -> dict:
    """{"shapes": {tail: {...}}, "bodies": {tail: {...}}, "joints": {tail: {...}}} of a model; hand bodies
    (a MANO rig, an end effector: any body whose label the exporter would tag with a side, or under
    /Hand*, /Gripper*, /HandLeft ...) are left out unless `hands`."""
    from newton import GeoType, ShapeFlags  # noqa: PLC0415
    body_label = [str(x) for x in (getattr(model, "body_label", []) or [])]
    s_label = [str(x) for x in (getattr(model, "shape_label", []) or [])]
    s_body = _np(model.shape_body); s_type = _np(model.shape_type); s_scale = _np(model.shape_scale)
    s_xform = _np(model.shape_transform); s_flags = _np(model.shape_flags)
    s_src = list(getattr(model, "shape_source", []) or [])
    attrs = {a: _np(getattr(model, a)) for a in _SHAPE_ATTRS if getattr(model, a, None) is not None}
    custom = {c: _custom(model, c) for c in _CUSTOM}
    custom_dof = {c: _custom(model, c) for c in _CUSTOM_DOF}
    custom_body = {c: _custom(model, c) for c in _CUSTOM_BODY}

    def is_hand(lbl: str) -> bool:
        t = _tail_of(lbl) or lbl
        head = t.split("/")[0]
        return head.startswith(("Hand", "Gripper", "HandLeft", "HandRight", "Robot")) or "/Hand" in lbl

    def pick(container, i):
        if container is None:
            return None
        if isinstance(container, dict):
            return container.get(i)
        if i < len(container):
            x = container[i]
            return [float(v) for v in np.asarray(x).reshape(-1)] if np.ndim(x) else float(x)
        return None

    shapes = {}
    for k in range(len(s_body)):
        b = int(s_body[k]); lbl = s_label[k] if k < len(s_label) else f"shape_{k}"
        tail = _tail_of(lbl)
        if tail is None or (not hands and is_hand(lbl)):
            continue
        rec = {"type": GeoType(int(s_type[k])).name, "scale": [float(x) for x in np.asarray(s_scale[k]).reshape(-1)[:3]],
               "transform": _xform(s_xform[k]), "body": _tail_of(body_label[b]) if 0 <= b < len(body_label) else None,
               "hydroelastic": bool(int(s_flags[k]) & int(ShapeFlags.HYDROELASTIC)),
               "collide": bool(int(s_flags[k]) & int(ShapeFlags.COLLIDE_SHAPES)),
               "mesh": _mesh_digest(s_src[k] if k < len(s_src) else None)}
        for a, arr in attrs.items():
            if k < len(arr):
                rec[a.replace("shape_material_", "").replace("shape_", "")] = pick(arr, k)
        for c, arr in custom.items():
            v = pick(arr, k)
            if v is not None:
                rec[c] = v
        shapes[tail] = rec
    bodies, joints = {}, {}
    j_type = _np(model.joint_type); j_parent = _np(model.joint_parent); j_child = _np(model.joint_child)
    j_label = [str(x) for x in (getattr(model, "joint_label", []) or [])]
    j_Xp = _np(model.joint_X_p); j_Xc = _np(model.joint_X_c)
    j_qd = _np(model.joint_qd_start) if getattr(model, "joint_qd_start", None) is not None else None
    j_axis = _np(model.joint_axis) if getattr(model, "joint_axis", None) is not None else None
    jattrs = {a: _np(getattr(model, a)) for a in _JOINT_ATTRS if getattr(model, a, None) is not None}
    dof_damp = custom_dof.get("mujoco:dof_passive_damping")
    mass = _np(model.body_mass); com = _np(model.body_com)
    inertia = _np(model.body_inertia) if getattr(model, "body_inertia", None) is not None else None
    for b, lbl in enumerate(body_label):
        tail = _tail_of(lbl)
        if tail is None or (not hands and is_hand(lbl)):
            continue
        bodies[tail] = {"mass": float(mass[b]), "com": [float(x) for x in np.asarray(com[b]).reshape(-1)[:3]],
                        "inertia": ([float(x) for x in np.asarray(inertia[b]).reshape(-1)[:9]] if inertia is not None else None)}
        for c, arr in custom_body.items():
            v = pick(arr, b)
            if v is not None:
                bodies[tail][c] = v
    for j in range(len(j_child)):
        c = int(j_child[j]); lbl = body_label[c] if 0 <= c < len(body_label) else ""
        tail = _tail_of(lbl)
        if tail is None or (not hands and is_hand(lbl)):
            continue
        jt = _joint_type_name(int(j_type[j]))
        rec = {"type": jt, "parent": _tail_of(body_label[int(j_parent[j])]) if 0 <= int(j_parent[j]) < len(body_label) else None,
               "X_p": _xform(j_Xp[j]), "X_c": _xform(j_Xc[j])}
        if jt in ("REVOLUTE", "PRISMATIC"):
            rec["name"] = (j_label[j] if j < len(j_label) else "").rsplit("/", 1)[-1]   # a FREE/FIXED joint's name is an auto index
        if jt in ("REVOLUTE", "PRISMATIC") and j_qd is not None:
            d = int(j_qd[j])
            if j_axis is not None and d < len(j_axis):
                rec["axis"] = [float(v) for v in np.asarray(j_axis[d]).reshape(-1)[:3]]
            for a, arr in jattrs.items():
                if d < len(arr):
                    rec[a.replace("joint_", "")] = pick(arr, d)
            v = pick(dof_damp, d)
            if v is not None:
                rec["passive_damping"] = v
        joints[tail] = rec
    return {"shapes": shapes, "bodies": bodies, "joints": joints, "joint_couplings": [c for c in joint_couplings(model)
                                             if hands or not (is_hand(c["follower"]) or is_hand(c["leader"]))]}


def manifest_record(assets_dir: str) -> dict:
    """The recording's own word on the scene, in physics_record's shape, for the fields the manifest carries:
    per shape type, scale, pose, mesh size/bounds, hydroelastic, collide (recorded, else the visuals/ convention),
    kh / sdf_voxel when recorded; per body mass, COM, inertia when recorded; per joint type, parent, frames,
    axis, name, limits when recorded. Everything else (solver material, condim, gains) is not in a manifest."""
    bodies, shapes = load(assets_dir)
    bodies, shapes = bodies["bodies"], shapes["shapes"]
    by_index = {b["index"]: b for b in bodies}
    out = {"shapes": {}, "bodies": {}, "joints": {}}
    for b in bodies:
        tail = _tail_of(b["label"])
        if tail is None or b.get("side") is not None or "/Hand" in b["label"]:
            continue
        rec = {"mass": float(b.get("mass", 0.0)), "com": [float(v) for v in (b.get("com") or [0, 0, 0])]}
        if b.get("inertia") is not None:
            rec["inertia"] = [float(v) for v in b["inertia"]]
        if b.get("gravcomp") is not None:
            rec["mujoco:gravcomp"] = float(b["gravcomp"])
        out["bodies"][tail] = rec
        j = b.get("joint") or {}
        if j:
            jr = {"type": str(j.get("type", "")).upper(),
                  "parent": _tail_of(by_index[b["parent"]]["label"]) if b.get("parent") is not None and b["parent"] in by_index else None,
                  "X_p": [float(v) for v in j["X_p"]], "X_c": [float(v) for v in j["X_c"]]}
            if jr["type"] in ("REVOLUTE", "PRISMATIC"):
                jr["name"] = str(j.get("label", "")).rsplit("/", 1)[-1]
                if j.get("axis") is not None:
                    jr["axis"] = [float(v) for v in j["axis"]]
                if j.get("limit") is not None:
                    jr["limit_lower"], jr["limit_upper"] = float(j["limit"][0]), float(j["limit"][1])
            out["joints"][tail] = jr
    for sh in shapes:
        tail = _tail_of(sh["label"])
        if tail is None or sh["type"] == "PLANE" or sh["body"] not in by_index:
            continue
        b = by_index[sh["body"]]
        if b.get("side") is not None or "/Hand" in b["label"]:
            continue
        rec = {"type": sh["type"].upper(), "scale": [float(v) for v in sh["scale"]], "transform": [float(v) for v in sh["transform"]],
               "body": _tail_of(b["label"]), "hydroelastic": bool(sh.get("hydroelastic", False)), "collide": _collides(sh), "mesh": None}
        if sh.get("mesh"):
            v, f = _load_obj(os.path.join(assets_dir, sh["mesh"]))
            rec["mesh"] = {"vertices": int(len(v)), "faces": int(len(f)),
                           "bbox": [float(x) for x in np.concatenate([v.min(0), v.max(0)])], "centroid": [float(x) for x in v.mean(0)]}
        for k in ("kh", "sdf_voxel"):
            if sh.get(k) is not None:
                rec[k] = float(sh[k])
        out["shapes"][tail] = rec
    return out


def merge_records(collector: dict, manifest: dict) -> dict:
    """The scene a downstream simulator must reproduce: the collector's record of the task as it builds it
    today, with every field the recording itself carries taken from the recording (the manifest wins where it
    speaks -- geometry, flags, masses, joints; the collector's record supplies what a manifest has no word on).
    A body or shape the manifest has and the collector no longer builds (or the reverse) is kept from the
    manifest only."""
    out = {}
    for section in ("bodies", "joints", "shapes"):
        c, m = collector.get(section, {}), manifest.get(section, {})
        sec = {}
        for k in set(c) | set(m):
            if k not in m:
                continue                                     # the recording did not have it
            rec = dict(c.get(k, {}))
            rec.update(m[k])
            sec[k] = rec
        out[section] = sec
    return out


def dump_record(model, path: str, hands: bool = False) -> dict:
    rec = physics_record(model, hands=hands)
    os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
    with open(path, "w") as fh:
        json.dump(rec, fh, indent=1)
    return rec


def compare(ref: dict, got: dict, tol: float = 1e-5, rel: float = 1e-4, ignore: tuple = (), colliding_only: bool = True) -> list[str]:
    """Human-readable differences of `got` against `ref`; empty when the two scenes are the same. With
    `colliding_only` a shape the reference never collides (a visual) is not compared: it has no physics."""
    out = []
    if colliding_only:
        ref = dict(ref); got = dict(got)
        vis = {k for k, v in ref.get("shapes", {}).items() if not v.get("collide", True)}
        ref["shapes"] = {k: v for k, v in ref.get("shapes", {}).items() if k not in vis}
        got["shapes"] = {k: v for k, v in got.get("shapes", {}).items() if v.get("collide", True) or k in ref["shapes"]}

    def same(a, b) -> bool:
        if isinstance(a, dict) and isinstance(b, dict):
            return set(a) == set(b) and all(same(a[k], b[k]) for k in a)
        if isinstance(a, (list, tuple)) and isinstance(b, (list, tuple)):
            return len(a) == len(b) and all(same(x, y) for x, y in zip(a, b))
        if isinstance(a, (int, float)) and isinstance(b, (int, float)) and not isinstance(a, bool) and not isinstance(b, bool):
            return abs(a - b) <= tol + rel * max(abs(a), abs(b))
        return a == b

    if "joint_couplings" in ref:
        def normalized(rows):
            out = []
            for coupling in rows or []:
                c = dict(coupling)
                for endpoint in ("follower", "leader"):
                    c[endpoint] = _tail_of(c[endpoint]) or c[endpoint]
                out.append(c)
            return sorted(out, key=lambda c: (c["follower"], c["leader"], c["kind"]))
        if "joint_couplings" not in got or not same(normalized(ref["joint_couplings"]), normalized(got["joint_couplings"])):
            out.append("joint_couplings: recorded constraints missing or different")

    for section in ("bodies", "joints", "shapes"):
        r, g = ref.get(section, {}), got.get(section, {})
        for k in sorted(set(r) - set(g)):
            out.append(f"{section}: {k} missing")
        for k in sorted(set(g) - set(r)):
            out.append(f"{section}: {k} EXTRA")
        for k in sorted(set(r) & set(g)):
            for f in sorted(set(r[k]) | set(g[k])):
                if f in ignore:
                    continue
                a, b = r[k].get(f), g[k].get(f)
                if a is None or b is None:
                    if a is not b:
                        out.append(f"{section}: {k}.{f}: recorded {a} vs {b}")
                    continue
                if not same(a, b):
                    def fmt(x):
                        return (f"[{', '.join(f'{v:.4g}' for v in x)}]" if isinstance(x, (list, tuple)) and x and isinstance(x[0], (int, float))
                                else f"{x:.6g}" if isinstance(x, float) else str(x))
                    out.append(f"{section}: {k}.{f}: recorded {fmt(a)} vs {fmt(b)}")
    return out


if __name__ == "__main__":
    import argparse

    ap = argparse.ArgumentParser(
        description="Write meta/assets/usd/<Group>.usd for recorded datasets (backfill for datasets recorded "
                    "before the collector wrote them; every new --record writes them itself).")
    ap.add_argument("roots", nargs="+", help="dataset roots (the directory that holds meta/)")
    ap.add_argument("--rebuild", action="store_true", help="rewrite even when usd/ is up to date")
    ap.add_argument("--appearance", action="store_true",
                    help="only (re)write what each shape looked like -- shapes[].appearance and "
                         "meta/assets/visual/ -- from the asset USDs, for datasets recorded before "
                         "the collector wrote it (backfill_appearance)")
    ap.add_argument("--voxels", action="store_true",
                    help="only write each hydroelastic shape's sdf_voxel into shapes.json, from the "
                         "dataset's own meta/task.json, for datasets whose export recorded none "
                         "(backfill_voxels)")
    ap.add_argument("--source-assets", action="store_true",
                    help="only package the source assets the recording could not (sources.json rows with "
                         "no `package`), from this checkout, when their sha256 matches "
                         "(backfill_source_assets)")
    ap.add_argument("--dry-run", action="store_true", help="with --voxels / --source-assets: report, write nothing")
    ap.add_argument("--amend", default=None, metavar="RECORD.json",
                    help="first fill the manifest's missing physics fields (inertia, joint limits, collide, kh, "
                         "sdf voxel) from this collect_env.py --dump-model record of the same task (one root)")
    a = ap.parse_args()
    if a.amend and len(a.roots) != 1:
        ap.error("--amend takes exactly one dataset root")
    for r in a.roots:
        adir = os.path.join(r, "meta", "assets")
        if not os.path.exists(os.path.join(adir, "bodies.json")):
            print(f"{r}: no meta/assets/bodies.json (recorded without the asset export), skipped")
            continue
        if a.voxels:
            print(f"{r}:")
            backfill_voxels(r, dry_run=a.dry_run)
            continue
        if a.source_assets:
            print(f"{r}:")
            backfill_source_assets(r, dry_run=a.dry_run)
            continue
        if a.appearance:
            print(f"{r}:")
            backfill_appearance(r)
            continue
        if a.amend:
            with open(a.amend) as fh:
                amend_manifest(adir, json.load(fh))
        if usd_fresh(adir) and not a.rebuild:
            print(f"{r}: usd/ up to date")
            continue
        print(f"{r}:")
        export_usd(adir)