threers 0.1.0

Drop-in three.js replacement for Rust and WebAssembly (wgpu) — THREE.* API, scene graph, PBR, post-fx, mesh BVH, CSG, an OpenSCAD front end with a watertight exact-CSG kernel, headless render, and native media codecs
Documentation
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
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
//! Writing geometry and scenes out as USD.
//!
//! The output is what `UsdGeomMesh` asks for and nothing more: points, face
//! counts, face indices, and whichever of normals and `primvars:st` the
//! geometry actually carries. Faces are written as the polygons the geometry
//! remembers ([`BufferGeometry::polygons`]) — a quad read from USD, OBJ or FBX
//! goes back out as a quad — and as triangles where it remembers none.
//! Triangles are never re-joined by guessing: two coplanar triangles that were
//! not one face stay two faces.

use crate::animation::{AnimationClip, KeyframeTrack, TrackTarget, TrackValues};
use crate::core::{BufferGeometry, ObjectArena, ObjectId, ObjectKind};
use crate::materials::Material;
use crate::textures::{Texture, TextureFormat, TextureWrap};

use super::parse::{Specifier, UsdLayer, UsdPrim, UsdProperty};
use super::value::UsdValue;
use super::write::layer_to_usda;

/// How the layer describes its own units. USD's default is metres.
#[derive(Debug, Clone)]
pub struct UsdExportOptions {
    /// `metersPerUnit`. 1.0 says the numbers are metres, 0.01 that they are
    /// centimetres — which is what most DCC tools and every `.usdz` from a
    /// phone actually contain.
    pub meters_per_unit: f32,
    /// `upAxis`, `Y` or `Z`.
    pub up_axis: char,
    /// The prim a reader should open by default.
    pub default_prim: String,
    /// How many time codes make a second when animation is exported. 24 is
    /// USD's own default and what every reader assumes when a layer is silent.
    pub time_codes_per_second: f32,
}

impl Default for UsdExportOptions {
    fn default() -> Self {
        Self {
            meters_per_unit: 1.0,
            up_axis: 'Y',
            default_prim: "Root".into(),
            time_codes_per_second: 24.0,
        }
    }
}

fn float_array(values: &[f32], stride: usize) -> UsdValue {
    UsdValue::Array(
        values
            .chunks_exact(stride)
            .map(|c| UsdValue::Tuple(c.iter().map(|v| UsdValue::Float(*v as f64)).collect()))
            .collect(),
    )
}

fn int_array(values: impl Iterator<Item = u32>) -> UsdValue {
    UsdValue::Array(values.map(|v| UsdValue::Int(v as i128)).collect())
}

fn uniform(mut p: UsdProperty) -> UsdProperty {
    p.uniform = true;
    p
}

fn attribute(type_name: &str, name: &str, value: UsdValue) -> UsdProperty {
    UsdProperty {
        qualifier: String::new(),
        name: name.into(),
        type_name: type_name.into(),
        uniform: false,
        relationship: false,
        value,
        metadata: Vec::new(),
    }
}

fn interpolated(mut p: UsdProperty, how: &str) -> UsdProperty {
    p.metadata
        .push(("interpolation".into(), UsdValue::Token(how.into())));
    p
}

/// A `UsdGeomMesh` prim for one geometry.
pub fn mesh_prim(g: &BufferGeometry, name: &str) -> UsdPrim {
    let positions = g
        .get_attribute("position")
        .map(|a| a.array.clone())
        .unwrap_or_default();
    let vertices = positions.len() / 3;
    let indices: Vec<u32> = match &g.index {
        Some(i) => i.to_vec(),
        // Unindexed geometry is already one vertex per corner.
        None => (0..vertices as u32).collect(),
    };
    let triangles = indices.len() / 3;

    // A face per polygon where the geometry remembers them and the outline can
    // be recovered, a face per triangle everywhere else; see the module note.
    let mut face_counts: Vec<u32> = Vec::with_capacity(triangles);
    let mut face_indices: Vec<u32> = Vec::with_capacity(triangles * 3);
    for corners in g.faces() {
        face_counts.push(corners.len() as u32);
        face_indices.extend_from_slice(&corners);
    }

    let mut properties = vec![
        attribute("point3f[]", "points", float_array(&positions, 3)),
        attribute(
            "int[]",
            "faceVertexCounts",
            int_array(face_counts.into_iter()),
        ),
        attribute(
            "int[]",
            "faceVertexIndices",
            int_array(face_indices.into_iter()),
        ),
    ];

    // `extent` is not decoration: a reader uses it to frame the asset without
    // touching the points, and Quick Look will not show a mesh that lacks one.
    if vertices > 0 {
        let mut lo = [f32::INFINITY; 3];
        let mut hi = [f32::NEG_INFINITY; 3];
        for p in positions.as_chunks::<3>().0 {
            for a in 0..3 {
                lo[a] = lo[a].min(p[a]);
                hi[a] = hi[a].max(p[a]);
            }
        }
        properties.push(attribute(
            "float3[]",
            "extent",
            UsdValue::Array(vec![
                UsdValue::Tuple(lo.iter().map(|v| UsdValue::Float(*v as f64)).collect()),
                UsdValue::Tuple(hi.iter().map(|v| UsdValue::Float(*v as f64)).collect()),
            ]),
        ));
    }

    if let Some(n) = g.get_attribute("normal") {
        properties.push(interpolated(
            attribute("normal3f[]", "normals", float_array(&n.array, 3)),
            "vertex",
        ));
    }
    // USD's fallback shading, which every tool that does not evaluate a shader
    // graph falls back to — `usdview` flat-shaded, thumbnailers, importers that
    // read geometry and skip materials. Without it a vertex-coloured mesh
    // exported from here arrived grey, and the colours were simply gone.
    if let Some(c) = g.get_attribute("color") {
        properties.push(interpolated(
            attribute(
                "color3f[]",
                "primvars:displayColor",
                float_array(&c.array, 3),
            ),
            "vertex",
        ));
    }
    if let Some(uv) = g.get_attribute("uv") {
        properties.push(interpolated(
            attribute("texCoord2f[]", "primvars:st", float_array(&uv.array, 2)),
            "vertex",
        ));
    }
    // Without this a reader is entitled to subdivide the mesh, which turns a
    // faceted model into a smooth approximation of itself.
    properties.push(UsdProperty {
        qualifier: String::new(),
        name: "subdivisionScheme".into(),
        type_name: "token".into(),
        uniform: true,
        relationship: false,
        value: UsdValue::Token("none".into()),
        metadata: Vec::new(),
    });

    UsdPrim {
        specifier: Specifier::Def,
        type_name: "Mesh".into(),
        name: sanitize(name),
        metadata: Vec::new(),
        properties,
        children: Vec::new(),
        variant_sets: Vec::new(),
    }
}

/// An image an exported material refers to, and the bytes to write for it.
///
/// A `.usda` refers to its textures by relative path, so these have to land
/// beside the layer for the reference to resolve. A `.usdz` carries them
/// instead, which is why [`scene_to_usdz`](super::scene_to_usdz) needs no help
/// and the text form does.
#[derive(Debug, Clone)]
pub struct ExportedTexture {
    /// The asset path written into the layer, relative to it.
    pub path: String,
    /// PNG-encoded pixels.
    pub data: Vec<u8>,
}

/// A texture's pixels as 8-bit RGBA.
///
/// `None` when there is nothing to write: a texture whose bytes live only on
/// the GPU (see `Texture::without_pixels`), or one held block-compressed,
/// which would have to be decoded first and is a different job. The material
/// still exports — it keeps its constant values and loses only the map.
fn rgba8(texture: &Texture) -> Option<Vec<u8>> {
    let count = (texture.width as usize).checked_mul(texture.height as usize)?;
    if count == 0 || (texture.data.is_empty() && texture.stream.is_none()) {
        return None;
    }
    let pixels = unflipped(texture, count)?;
    // An image file stores the top row first and USD samples with `v = 1` at
    // that row — verified by rendering a half-red, half-blue image and seeing
    // which half Hydra put on top. `flip_y` is this crate's flag for "the top
    // row is first", so a texture with it *off* is authored bottom-up and has
    // to be turned over on the way out or it arrives upside down. USD has no
    // flag to carry the distinction; the rows have to be right.
    if texture.flip_y {
        return Some(pixels);
    }
    let stride = texture.width as usize * 4;
    Some(
        pixels
            .chunks_exact(stride)
            .rev()
            .flatten()
            .copied()
            .collect(),
    )
}

/// The pixels as 8-bit RGBA in the order they are held.
fn unflipped(texture: &Texture, count: usize) -> Option<Vec<u8>> {
    match texture.format {
        // A video's frame as it is when exported.
        TextureFormat::Rgba8UnormSrgb | TextureFormat::Rgba8Unorm => {
            texture.pixels().get(..count * 4).map(<[u8]>::to_vec)
        }
        // Everything else through f32, block formats decoded first. One
        // channel becomes grey, so the written file says what the single
        // channel said however a reader samples it; two are red and green.
        // Floats above 1.0 clamp, which is a real loss and only reachable for
        // a map holding an HDR image.
        f => {
            let (w, h) = (texture.width, texture.height);
            let v =
                crate::textures::codec::texels_f32(f, texture.data.get(..f.data_len(w, h))?, w, h)?;
            let byte = |x: f32| (x.clamp(0.0, 1.0) * 255.0).round() as u8;
            let n = crate::textures::codec::decoded_format(f).channels();
            if v.len() < count * n {
                return None;
            }
            Some(
                (0..count)
                    .flat_map(|i| {
                        let t = &v[i * n..i * n + n];
                        match n {
                            1 => [byte(t[0]), byte(t[0]), byte(t[0]), 255],
                            2 => [byte(t[0]), byte(t[1]), 0, 255],
                            _ => [byte(t[0]), byte(t[1]), byte(t[2]), byte(t[3])],
                        }
                    })
                    .collect(),
            )
        }
    }
}

/// USD's name for a wrap mode.
fn wrap_name(wrap: TextureWrap) -> &'static str {
    match wrap {
        TextureWrap::Repeat => "repeat",
        TextureWrap::ClampToEdge => "clamp",
        TextureWrap::MirroredRepeat => "mirror",
    }
}

/// One `UsdUVTexture` an export has to write, and where it plugs in.
struct Slot<'a> {
    /// The shader prim's name, and the stem of the image file.
    name: &'static str,
    /// The surface input it drives, and that input's type.
    input: &'static str,
    type_name: &'static str,
    /// Which of the texture shader's outputs to take. `rgb` for colour and
    /// normals, `r` for the maps that are one channel of data.
    channel: &'static str,
    /// `sRGB` for colour, `raw` for data. A normal map read as sRGB is wrong
    /// in a way that looks like bad lighting rather than like a bug.
    color_space: &'static str,
    /// `sampled * scale + bias`. Only a normal map needs them, to turn `[0,1]`
    /// into `[-1,1]`, and leaving them off points every normal into the surface.
    scale: [f32; 4],
    bias: [f32; 4],
    texture: &'a Texture,
}

fn slot<'a>(
    name: &'static str,
    input: &'static str,
    type_name: &'static str,
    channel: &'static str,
    color_space: &'static str,
    texture: &'a Texture,
) -> Slot<'a> {
    Slot {
        name,
        input,
        type_name,
        channel,
        color_space,
        scale: [1.0; 4],
        bias: [0.0; 4],
        texture,
    }
}

/// Every map a material carries, as the texture shaders USD wants for them.
fn texture_slots(material: &Material) -> Vec<Slot<'_>> {
    let mut out = Vec::new();
    macro_rules! push {
        ($opt:expr, $name:literal, $input:literal, $ty:literal, $ch:literal, $cs:literal) => {
            if let Some(t) = $opt.as_deref() {
                out.push(slot($name, $input, $ty, $ch, $cs, t));
            }
        };
    }
    match material {
        Material::Standard(m) => {
            push!(
                m.map,
                "DiffuseTex",
                "inputs:diffuseColor",
                "color3f",
                "rgb",
                "sRGB"
            );
            push!(
                m.emissive_map,
                "EmissiveTex",
                "inputs:emissiveColor",
                "color3f",
                "rgb",
                "sRGB"
            );
            push!(
                m.roughness_map,
                "RoughnessTex",
                "inputs:roughness",
                "float",
                "r",
                "raw"
            );
            push!(
                m.metalness_map,
                "MetallicTex",
                "inputs:metallic",
                "float",
                "r",
                "raw"
            );
            push!(
                m.ao_map,
                "OcclusionTex",
                "inputs:occlusion",
                "float",
                "r",
                "raw"
            );
            push!(
                m.displacement_map,
                "DisplacementTex",
                "inputs:displacement",
                "float",
                "r",
                "raw"
            );
            if let Some(t) = m.normal_map.as_deref() {
                out.push(normal_slot(t));
            }
        }
        Material::Physical(m) => {
            push!(
                m.map,
                "DiffuseTex",
                "inputs:diffuseColor",
                "color3f",
                "rgb",
                "sRGB"
            );
            push!(
                m.emissive_map,
                "EmissiveTex",
                "inputs:emissiveColor",
                "color3f",
                "rgb",
                "sRGB"
            );
            push!(
                m.roughness_map,
                "RoughnessTex",
                "inputs:roughness",
                "float",
                "r",
                "raw"
            );
            push!(
                m.metalness_map,
                "MetallicTex",
                "inputs:metallic",
                "float",
                "r",
                "raw"
            );
            push!(
                m.ao_map,
                "OcclusionTex",
                "inputs:occlusion",
                "float",
                "r",
                "raw"
            );
            push!(
                m.displacement_map,
                "DisplacementTex",
                "inputs:displacement",
                "float",
                "r",
                "raw"
            );
            if let Some(t) = m.normal_map.as_deref() {
                out.push(normal_slot(t));
            }
        }
        Material::Basic(m) => {
            push!(
                m.map,
                "DiffuseTex",
                "inputs:diffuseColor",
                "color3f",
                "rgb",
                "sRGB"
            )
        }
        Material::Sprite(m) => {
            push!(
                m.map,
                "DiffuseTex",
                "inputs:diffuseColor",
                "color3f",
                "rgb",
                "sRGB"
            )
        }
        _ => {}
    }
    out
}

/// A normal map, which is the one slot with a scale and bias that matter.
fn normal_slot(texture: &Texture) -> Slot<'_> {
    Slot {
        scale: [2.0, 2.0, 2.0, 1.0],
        bias: [-1.0, -1.0, -1.0, 0.0],
        ..slot(
            "NormalTex",
            "inputs:normal",
            "normal3f",
            "rgb",
            "raw",
            texture,
        )
    }
}

fn tuple2(v: [f32; 2]) -> UsdValue {
    UsdValue::Tuple(v.iter().map(|c| UsdValue::Float(*c as f64)).collect())
}

fn token(name: &str, value: &str) -> UsdProperty {
    let mut p = attribute("token", name, UsdValue::Token(value.into()));
    p.uniform = true;
    p
}

/// A shader prim of the given `info:id`.
fn shader(name: &str, id: &str, mut properties: Vec<UsdProperty>) -> UsdPrim {
    properties.insert(0, token("info:id", id));
    UsdPrim {
        specifier: Specifier::Def,
        type_name: "Shader".into(),
        name: name.into(),
        metadata: Vec::new(),
        properties,
        children: Vec::new(),
        variant_sets: Vec::new(),
    }
}

/// A connection, which the writer spells by appending `.connect`.
fn connect(type_name: &str, name: &str, target: String) -> UsdProperty {
    attribute(type_name, name, UsdValue::Path(target))
}

/// What a material of this crate's becomes in `UsdPreviewSurface` terms.
///
/// USD has one surface shader, so every material has to arrive as some
/// setting of it. Most of them are a colour and a little more, and the
/// mapping is only interesting where it is lossy — which is recorded on each
/// arm of [`preview_surface`].
struct Preview {
    color: [f32; 3],
    roughness: f32,
    metallic: f32,
    emissive: [f32; 3],
    opacity: f32,
    /// Phong's specular colour, which needs `useSpecularWorkflow` alongside
    /// it. `None` for everything that works in the metallic workflow.
    specular: Option<[f32; 3]>,
    /// Index of refraction. `None` leaves USD's own default of 1.5 alone
    /// rather than restating it.
    ior: Option<f32>,
    /// Clear coat and its roughness, for the materials that have one.
    clearcoat: Option<(f32, f32)>,
    /// The alpha below which a fragment is discarded outright. USD's default
    /// is zero, meaning "blend", so only a material that actually cuts out
    /// says anything.
    opacity_threshold: f32,
}

/// Blinn-Phong's exponent as a GGX roughness.
///
/// The usual approximation, and exact at neither end, but it keeps the
/// distinction between a shininess of 5 and one of 200 — which mapping every
/// Phong material to a fixed roughness does not.
fn roughness_from_shininess(shininess: f32) -> f32 {
    (2.0 / (shininess.max(0.0) + 2.0)).sqrt().clamp(0.0, 1.0)
}

/// One of this crate's materials as a `UsdPreviewSurface` setting.
fn preview_surface(material: &Material) -> Preview {
    let rgb = |c: &crate::math::Color| [c.r, c.g, c.b];
    let plain = |color: [f32; 3], opacity: f32| Preview {
        color,
        roughness: 1.0,
        metallic: 0.0,
        emissive: [0.0; 3],
        opacity,
        specular: None,
        ior: None,
        clearcoat: None,
        opacity_threshold: 0.0,
    };
    match material {
        Material::Standard(s) => Preview {
            color: rgb(&s.color),
            roughness: s.roughness,
            metallic: s.metalness,
            emissive: rgb(&s.emissive),
            opacity: s.opacity,
            specular: None,
            ior: None,
            clearcoat: None,
            opacity_threshold: 0.0,
        },
        Material::Physical(p) => Preview {
            color: rgb(&p.color),
            roughness: p.roughness,
            metallic: p.metalness,
            emissive: rgb(&p.emissive),
            opacity: p.opacity,
            specular: None,
            // The two things a physical material has that a standard one does
            // not, and that USD's preview surface happens to have as well.
            ior: Some(p.ior),
            clearcoat: (p.clearcoat > 0.0).then_some((p.clearcoat, p.clearcoat_roughness)),
            opacity_threshold: 0.0,
        },
        // Unlit in this crate, and USD has no unlit preview surface. A fully
        // rough dielectric is the closest lit stand-in; the colour is what
        // matters and it is kept exactly.
        Material::Basic(b) => Preview {
            opacity_threshold: b.alpha_test,
            ..plain(rgb(&b.color), b.opacity)
        },
        Material::Lambert(l) => Preview {
            emissive: rgb(&l.emissive),
            ..plain(rgb(&l.color), l.opacity)
        },
        // The one arm with a real conversion in it: Phong's specular colour
        // and exponent become USD's specular workflow, which is what that
        // workflow is for.
        Material::Phong(p) => Preview {
            roughness: roughness_from_shininess(p.shininess),
            emissive: rgb(&p.emissive),
            specular: Some(rgb(&p.specular)),
            ..plain(rgb(&p.color), p.opacity)
        },
        // Banded shading is a look, not a surface, and nothing in USD
        // reproduces it. The colour survives and the banding does not.
        Material::Toon(t) => Preview {
            emissive: rgb(&t.emissive),
            ..plain(rgb(&t.color), t.opacity)
        },
        Material::Matcap(m) => plain(rgb(&m.color), m.opacity),
        Material::Sprite(s) => plain(rgb(&s.color), s.opacity),
        Material::Points(p) => plain(rgb(&p.color), p.opacity),
        Material::Line(l) => plain(rgb(&l.color), l.opacity),
        // A mirror is a smooth metal, which USD does have.
        Material::Mirror(m) => Preview {
            roughness: 0.0,
            metallic: 1.0,
            ..plain(rgb(&m.color), 1.0)
        },
        Material::Atmosphere(a) => plain(rgb(&a.color), 1.0),
        // Normal, Depth, Distance, Sky and a user's own shader are all
        // computed rather than coloured, so there is nothing to carry across
        // and a neutral surface is the honest result.
        Material::Normal(n) => plain([0.8; 3], n.opacity),
        Material::Depth(d) => plain([0.8; 3], d.opacity),
        Material::Distance(_) | Material::Sky(_) | Material::Shader(_) => plain([0.8; 3], 1.0),
    }
}

/// A `UsdPreviewSurface` material prim, with whatever textures it needs.
///
/// The textures come back rather than being written here, because where they
/// go depends on the form the layer is taking: beside a `.usda`, inside a
/// `.usdz`.
pub fn material_prim_with_textures(
    material: &Material,
    name: &str,
    root: &str,
) -> (UsdPrim, Vec<ExportedTexture>) {
    let mut prim = material_prim(material, name);
    let slots = texture_slots(material);
    if slots.is_empty() {
        return (prim, Vec::new());
    }
    let path = format!("{root}/{}", sanitize(name));
    let mut images = Vec::new();
    let mut nodes = Vec::new();
    let mut reader_used = false;

    for slot in slots {
        let Some(pixels) = rgba8(slot.texture) else {
            // Nothing writable — the constant value on the surface stands in.
            continue;
        };
        let file = format!("textures/{}_{}.png", sanitize(name), slot.name);
        images.push(ExportedTexture {
            path: file.clone(),
            data: crate::utils::png::encode_png(slot.texture.width, slot.texture.height, &pixels),
        });

        // A texture is sampled by a primvar, and a UV transform sits between
        // the two when there is one. `UsdTransform2d` takes degrees where this
        // crate keeps radians.
        let transform_needed = slot.texture.offset.x != 0.0
            || slot.texture.offset.y != 0.0
            || slot.texture.repeat.x != 1.0
            || slot.texture.repeat.y != 1.0
            || slot.texture.rotation != 0.0;
        let st_source = if transform_needed {
            let node = format!("{}Transform", slot.name);
            nodes.push(shader(
                &node,
                "UsdTransform2d",
                vec![
                    connect(
                        "float2",
                        "inputs:in",
                        format!("{path}/stReader.outputs:result"),
                    ),
                    attribute(
                        "float2",
                        "inputs:scale",
                        tuple2([slot.texture.repeat.x, slot.texture.repeat.y]),
                    ),
                    attribute(
                        "float2",
                        "inputs:translation",
                        tuple2([slot.texture.offset.x, slot.texture.offset.y]),
                    ),
                    attribute(
                        "float",
                        "inputs:rotation",
                        UsdValue::Float(slot.texture.rotation.to_degrees() as f64),
                    ),
                    attribute("float2", "outputs:result", UsdValue::None),
                ],
            ));
            format!("{path}/{node}.outputs:result")
        } else {
            format!("{path}/stReader.outputs:result")
        };
        reader_used = true;

        let mut properties = vec![
            attribute("asset", "inputs:file", UsdValue::Asset(file)),
            connect("float2", "inputs:st", st_source),
            token("inputs:wrapS", wrap_name(slot.texture.wrap_s)),
            token("inputs:wrapT", wrap_name(slot.texture.wrap_t)),
            token("inputs:sourceColorSpace", slot.color_space),
        ];
        if slot.scale != [1.0; 4] || slot.bias != [0.0; 4] {
            properties.push(attribute("float4", "inputs:scale", tuple4(slot.scale)));
            properties.push(attribute("float4", "inputs:bias", tuple4(slot.bias)));
        }
        let out_type = if slot.channel == "rgb" {
            "float3"
        } else {
            "float"
        };
        properties.push(attribute(
            out_type,
            &format!("outputs:{}", slot.channel),
            UsdValue::None,
        ));
        nodes.push(shader(slot.name, "UsdUVTexture", properties));

        // A connection is a *field* of one property, not a second property
        // beside it. Authoring both leaves two specs at the same path, which
        // the text form tolerates and the crate form refuses to open at all:
        // "ignoring invalid specs: spec <...inputs:diffuseColor> repeated".
        let surface = &mut prim.children[0].properties;
        surface.retain(|p| p.name != slot.input);
        surface.push(connect(
            slot.type_name,
            slot.input,
            format!("{path}/{}.outputs:{}", slot.name, slot.channel),
        ));
    }

    if reader_used {
        nodes.insert(
            0,
            shader(
                "stReader",
                "UsdPrimvarReader_float2",
                vec![
                    // A `token` here parses and then fails `usdchecker`: the
                    // shader definition says `string`, and the two are not
                    // interchangeable to a validator.
                    attribute("string", "inputs:varname", UsdValue::String("st".into())),
                    attribute("float2", "outputs:result", UsdValue::None),
                ],
            ),
        );
    }
    prim.children.extend(nodes);
    (prim, images)
}

/// A `UsdPreviewSurface` material prim.
pub fn material_prim(material: &Material, name: &str) -> UsdPrim {
    let Preview {
        color,
        roughness,
        metallic,
        emissive,
        opacity,
        specular,
        ior,
        clearcoat,
        opacity_threshold,
    } = preview_surface(material);
    let name = sanitize(name);
    let shader = UsdPrim {
        specifier: Specifier::Def,
        type_name: "Shader".into(),
        name: "Surface".into(),
        metadata: Vec::new(),
        properties: vec![
            UsdProperty {
                qualifier: String::new(),
                name: "info:id".into(),
                type_name: "token".into(),
                uniform: true,
                relationship: false,
                value: UsdValue::Token("UsdPreviewSurface".into()),
                metadata: Vec::new(),
            },
            attribute("color3f", "inputs:diffuseColor", tuple3(color)),
            attribute("color3f", "inputs:emissiveColor", tuple3(emissive)),
            attribute("float", "inputs:metallic", UsdValue::Float(metallic as f64)),
            attribute(
                "float",
                "inputs:roughness",
                UsdValue::Float(roughness as f64),
            ),
            attribute("float", "inputs:opacity", UsdValue::Float(opacity as f64)),
            attribute("token", "outputs:surface", UsdValue::None),
        ]
        .into_iter()
        .chain(specular.into_iter().flat_map(|s| {
            [
                attribute("int", "inputs:useSpecularWorkflow", UsdValue::Int(1)),
                attribute("color3f", "inputs:specularColor", tuple3(s)),
            ]
        }))
        .chain(
            ior.into_iter()
                .map(|v| attribute("float", "inputs:ior", UsdValue::Float(v as f64))),
        )
        .chain((opacity_threshold > 0.0).then(|| {
            attribute(
                "float",
                "inputs:opacityThreshold",
                UsdValue::Float(opacity_threshold as f64),
            )
        }))
        .chain(clearcoat.into_iter().flat_map(|(amount, rough)| {
            [
                attribute("float", "inputs:clearcoat", UsdValue::Float(amount as f64)),
                attribute(
                    "float",
                    "inputs:clearcoatRoughness",
                    UsdValue::Float(rough as f64),
                ),
            ]
        }))
        .collect(),
        children: Vec::new(),
        variant_sets: Vec::new(),
    };
    UsdPrim {
        specifier: Specifier::Def,
        type_name: "Material".into(),
        name: name.clone(),
        metadata: Vec::new(),
        properties: vec![UsdProperty {
            qualifier: String::new(),
            // Named without the suffix: the writer adds `.connect` because
            // the value is a path, and spelling it here too produced
            // `outputs:surface.connect.connect`, which USD will not parse.
            name: "outputs:surface".into(),
            type_name: "token".into(),
            uniform: false,
            relationship: false,
            value: UsdValue::Path(format!("/Root/{name}/Surface.outputs:surface")),
            metadata: Vec::new(),
        }],
        children: vec![shader],
        variant_sets: Vec::new(),
    }
}

fn tuple4(v: [f32; 4]) -> UsdValue {
    UsdValue::Tuple(v.iter().map(|n| UsdValue::Float(*n as f64)).collect())
}

fn tuple3(v: [f32; 3]) -> UsdValue {
    UsdValue::Tuple(v.iter().map(|c| UsdValue::Float(*c as f64)).collect())
}

/// A prim name USD will accept: identifiers only, and never empty.
///
/// USD prim names are C identifiers. A mesh called `wheel.001` — which is what
/// every DCC tool produces — is not one, and a reader rejects the whole layer
/// rather than the one prim, so this is not a detail worth leaving to chance.
/// The first triangle of each face [`mesh_prim`] writes, in face order — the
/// faces [`BufferGeometry::faces`] yields: a recovered polygon is one face,
/// anything else a face per triangle.
fn face_first_triangles(g: &BufferGeometry) -> Vec<usize> {
    let grouped = g.polygon_counts().is_some();
    let mut out = Vec::new();
    for range in g.polygon_ranges() {
        if grouped && range.len() > 1 && g.polygon_loop(range.clone()).is_some() {
            out.push(range.start);
        } else {
            out.extend(range);
        }
    }
    out
}

pub fn sanitize(name: &str) -> String {
    let mut out = String::new();
    for (i, c) in name.chars().enumerate() {
        let ok = c.is_ascii_alphanumeric() || c == '_';
        let leading_digit = i == 0 && c.is_ascii_digit();
        out.push(if ok && !leading_digit { c } else { '_' });
    }
    if out.is_empty() {
        out.push_str("Prim");
    }
    out
}

/// One geometry as a complete layer.
pub fn geometry_to_layer(g: &BufferGeometry, name: &str, options: &UsdExportOptions) -> UsdLayer {
    let root = UsdPrim {
        specifier: Specifier::Def,
        type_name: "Xform".into(),
        name: sanitize(&options.default_prim),
        metadata: Vec::new(),
        properties: Vec::new(),
        children: vec![mesh_prim(g, name)],
        variant_sets: Vec::new(),
    };
    UsdLayer {
        metadata: vec![
            (
                "defaultPrim".into(),
                UsdValue::String(sanitize(&options.default_prim)),
            ),
            (
                "metersPerUnit".into(),
                UsdValue::Float(options.meters_per_unit as f64),
            ),
            (
                "upAxis".into(),
                UsdValue::String(options.up_axis.to_string()),
            ),
        ],
        prims: vec![root],
    }
}

/// One geometry as a `.usda` document.
pub fn geometry_to_usda(g: &BufferGeometry, name: &str) -> String {
    layer_to_usda(&geometry_to_layer(g, name, &UsdExportOptions::default()))
}

/// A scene graph as a layer, hierarchy and materials included.
pub fn scene_to_layer(
    arena: &ObjectArena,
    roots: &[ObjectId],
    options: &UsdExportOptions,
) -> UsdLayer {
    scene_to_layer_placed(arena, roots, options, &mut Vec::new()).0
}

/// A scene graph as a layer, with the image files its materials refer to.
///
/// The layer names its textures by relative path, so writing it without these
/// beside it leaves every map dangling. [`scene_to_usdz`](super::scene_to_usdz)
/// packs them for you; this is for the text and crate forms, which have
/// nowhere to put them.
pub fn scene_to_layer_with_textures(
    arena: &ObjectArena,
    roots: &[ObjectId],
    options: &UsdExportOptions,
) -> (UsdLayer, Vec<ExportedTexture>) {
    scene_to_layer_placed(arena, roots, options, &mut Vec::new())
}

/// Materials and their images as an export accumulates them.
#[derive(Default)]
struct Materials {
    prims: Vec<UsdPrim>,
    textures: Vec<ExportedTexture>,
    /// The `Skeleton` and `SkelAnimation` prims morphed meshes bind their
    /// blend shapes through (see [`add_blend_shapes`]); placed under the
    /// root, which they make a `SkelRoot`.
    skel: Vec<UsdPrim>,
}

fn scene_to_layer_placed(
    arena: &ObjectArena,
    roots: &[ObjectId],
    options: &UsdExportOptions,
    placed: &mut Vec<(ObjectId, String)>,
) -> (UsdLayer, Vec<ExportedTexture>) {
    let root_path = format!("/{}", sanitize(&options.default_prim));
    let mut materials = Materials::default();
    let mut children: Vec<UsdPrim> = Vec::new();
    for (i, root) in roots.iter().enumerate() {
        if let Some(prim) = object_prim_at(arena, *root, i, &mut materials, &root_path, placed) {
            children.push(prim);
        }
    }
    let textures = std::mem::take(&mut materials.textures);
    children.extend(materials.prims);
    // UsdSkel only applies a binding under a `SkelRoot`.
    let root_type = if materials.skel.is_empty() {
        "Xform"
    } else {
        "SkelRoot"
    };
    children.extend(materials.skel);
    let root = UsdPrim {
        specifier: Specifier::Def,
        type_name: root_type.into(),
        name: sanitize(&options.default_prim),
        metadata: Vec::new(),
        properties: Vec::new(),
        children,
        variant_sets: Vec::new(),
    };
    let layer = UsdLayer {
        metadata: vec![
            (
                "defaultPrim".into(),
                UsdValue::String(sanitize(&options.default_prim)),
            ),
            (
                "metersPerUnit".into(),
                UsdValue::Float(options.meters_per_unit as f64),
            ),
            (
                "upAxis".into(),
                UsdValue::String(options.up_axis.to_string()),
            ),
        ],
        prims: vec![root],
    };
    (layer, textures)
}

/// A scene graph as a `.usda` document.
pub fn scene_to_usda(arena: &ObjectArena, roots: &[ObjectId]) -> String {
    layer_to_usda(&scene_to_layer(arena, roots, &UsdExportOptions::default()))
}

/// The same, recording where each object ended up so that a later pass can
/// attach animation to it by path.
fn relationship(name: &str, value: UsdValue) -> UsdProperty {
    UsdProperty {
        qualifier: String::new(),
        name: name.into(),
        type_name: String::new(),
        uniform: false,
        relationship: true,
        value,
        metadata: Vec::new(),
    }
}

/// A mesh's morph targets as UsdSkel blend shapes.
///
/// A `BlendShape` holds *offsets* from the base mesh — three.js's relative
/// targets — so absolute targets (`morph_targets_relative == false`) are
/// written as `target − base`. A target that moves only some vertices is
/// written sparse, with `pointIndices`. The exporter writes the geometry's
/// vertices as the mesh's `points` one for one, so offsets index the same
/// vertices the targets do.
///
/// UsdSkel applies blend shapes only through a skeleton binding under a
/// `SkelRoot`: the mesh takes `SkelBindingAPI`, `skel:blendShapes` (the
/// target names, which the weights are keyed by) and `skel:blendShapeTargets`
/// (the `BlendShape` prims, children of the mesh), and binds a joint-less
/// `Skeleton` whose `skel:animationSource` is a `SkelAnimation` carrying the
/// mesh's current influences as `blendShapeWeights`. The skeleton and the
/// animation are pushed onto `skel`, for the caller to place under the root,
/// which it then makes a `SkelRoot`. Positions only: a target set with no
/// position targets has nothing USD can hold.
fn add_blend_shapes(
    mesh: &crate::core::Mesh,
    prim: &mut UsdPrim,
    mesh_path: &str,
    root: &str,
    skel: &mut Vec<UsdPrim>,
) {
    use crate::core::BufferAttribute;
    let g = &mesh.geometry;
    let Some(base) = g.get_attribute("position") else {
        return;
    };
    let Some(targets) = g.morph_attributes.get("position").filter(|t| !t.is_empty()) else {
        return;
    };
    let vertices = base.count();
    let normal_targets = g.morph_attributes.get("normal").filter(|t| !t.is_empty());
    let base_normal = g.get_attribute("normal");
    // Component `k` of vertex `v`, zero past the item size or the array.
    let read = |a: &BufferAttribute, v: usize, k: usize| -> f32 {
        if k >= a.item_size {
            return 0.0;
        }
        a.array.get(v * a.item_size + k).copied().unwrap_or(0.0)
    };
    // Per-vertex offsets of a target from the base, three a vertex.
    let offsets = |target: &BufferAttribute, base: Option<&BufferAttribute>| -> Vec<f32> {
        let mut out = Vec::with_capacity(vertices * 3);
        for v in 0..vertices {
            for k in 0..3 {
                let from = match (g.morph_targets_relative, base) {
                    (false, Some(b)) => read(b, v, k),
                    _ => 0.0,
                };
                out.push(read(target, v, k) - from);
            }
        }
        out
    };

    let mut names: Vec<String> = Vec::new();
    let mut paths: Vec<UsdValue> = Vec::new();
    let mut prim_names: Vec<String> = Vec::new();
    for (t, target) in targets.iter().enumerate() {
        let mut name = g
            .morph_target_names
            .get(t)
            .filter(|n| !n.is_empty())
            .cloned()
            .unwrap_or_else(|| format!("target_{t}"));
        // Weights are matched to shapes by name, so two alike would share one.
        if names.contains(&name) {
            name = format!("{name}_{t}");
        }
        let mut shape_name = sanitize(&name);
        if prim_names.contains(&shape_name) || prim.children.iter().any(|c| c.name == shape_name) {
            shape_name = format!("{shape_name}_{t}");
        }
        let position = offsets(target, Some(base));
        let normal = normal_targets
            .and_then(|n| n.get(t))
            .map(|n| offsets(n, base_normal));
        // Sparse when the target leaves some vertices alone; dense when it
        // moves nothing at all, since a reader may drop an empty shape.
        let touched: Vec<u32> = (0..vertices)
            .filter(|&v| {
                let moved = |d: &[f32]| d[v * 3..v * 3 + 3].iter().any(|x| *x != 0.0);
                moved(&position) || normal.as_deref().is_some_and(moved)
            })
            .map(|v| v as u32)
            .collect();
        let sparse = !touched.is_empty() && touched.len() < vertices;
        let pick = |d: &[f32]| -> Vec<f32> {
            if sparse {
                touched
                    .iter()
                    .flat_map(|&v| d[v as usize * 3..v as usize * 3 + 3].to_vec())
                    .collect()
            } else {
                d.to_vec()
            }
        };
        let mut properties = vec![uniform(attribute(
            "vector3f[]",
            "offsets",
            float_array(&pick(&position), 3),
        ))];
        if let Some(n) = &normal {
            properties.push(uniform(attribute(
                "vector3f[]",
                "normalOffsets",
                float_array(&pick(n), 3),
            )));
        }
        if sparse {
            properties.push(uniform(attribute(
                "int[]",
                "pointIndices",
                int_array(touched.into_iter()),
            )));
        }
        prim.children.push(UsdPrim {
            specifier: Specifier::Def,
            type_name: "BlendShape".into(),
            name: shape_name.clone(),
            metadata: Vec::new(),
            properties,
            children: Vec::new(),
            variant_sets: Vec::new(),
        });
        paths.push(UsdValue::Path(format!("{mesh_path}/{shape_name}")));
        prim_names.push(shape_name);
        names.push(name);
    }

    let tokens = || UsdValue::Array(names.iter().map(|n| UsdValue::Token(n.clone())).collect());
    let k = skel.len() / 2;
    let skeleton_path = format!("{root}/MorphSkel_{k}");
    let animation_path = format!("{root}/MorphAnim_{k}");
    prim.properties
        .push(uniform(attribute("token[]", "skel:blendShapes", tokens())));
    prim.properties.push(relationship(
        "skel:blendShapeTargets",
        UsdValue::Array(paths),
    ));
    prim.properties
        .push(relationship("skel:skeleton", UsdValue::Path(skeleton_path)));
    match prim
        .metadata
        .iter_mut()
        .find(|(key, _)| key == "prepend apiSchemas")
    {
        Some((_, UsdValue::Array(schemas))) => {
            schemas.push(UsdValue::Token("SkelBindingAPI".into()))
        }
        _ => prim.metadata.push((
            "prepend apiSchemas".into(),
            UsdValue::Array(vec![UsdValue::Token("SkelBindingAPI".into())]),
        )),
    }

    let mut weights = mesh.morph_influences.clone();
    weights.resize(names.len(), 0.0);
    skel.push(UsdPrim {
        specifier: Specifier::Def,
        type_name: "Skeleton".into(),
        name: format!("MorphSkel_{k}"),
        metadata: vec![(
            "prepend apiSchemas".into(),
            UsdValue::Array(vec![UsdValue::Token("SkelBindingAPI".into())]),
        )],
        properties: vec![relationship(
            "skel:animationSource",
            UsdValue::Path(animation_path),
        )],
        children: Vec::new(),
        variant_sets: Vec::new(),
    });
    skel.push(UsdPrim {
        specifier: Specifier::Def,
        type_name: "SkelAnimation".into(),
        name: format!("MorphAnim_{k}"),
        metadata: Vec::new(),
        properties: vec![
            uniform(attribute("token[]", "blendShapes", tokens())),
            attribute(
                "float[]",
                "blendShapeWeights",
                UsdValue::Array(weights.iter().map(|w| UsdValue::Float(*w as f64)).collect()),
            ),
        ],
        children: Vec::new(),
        variant_sets: Vec::new(),
    });
}

fn object_prim_at(
    arena: &ObjectArena,
    id: ObjectId,
    ordinal: usize,
    materials: &mut Materials,
    parent: &str,
    placed: &mut Vec<(ObjectId, String)>,
) -> Option<UsdPrim> {
    let object = arena.get(id)?;
    let name = if object.name.is_empty() {
        format!("Node_{ordinal}")
    } else {
        object.name.clone()
    };

    let mut prim = match &object.kind {
        ObjectKind::Mesh(mesh) => {
            let mut prim = mesh_prim(&mesh.geometry, &name);
            let material_name = format!("Material_{}", materials.prims.len());
            let root = parent.split('/').take(2).collect::<Vec<_>>().join("/");
            let (material, images) =
                material_prim_with_textures(&mesh.material, &material_name, &root);
            materials.prims.push(material);
            materials.textures.extend(images);
            // Sidedness is a property of the *surface* in USD, not of the
            // material bound to it, so it goes on the mesh. USD's default is
            // single-sided, so only a double-sided material says anything.
            if mesh.material.side() == 2 {
                prim.properties.push(uniform(attribute(
                    "bool",
                    "doubleSided",
                    UsdValue::Bool(true),
                )));
            }
            // With no colour per vertex, the material's own colour stands in as
            // a constant, so the mesh is the right colour even to a reader that
            // never looks at the shader.
            if !prim
                .properties
                .iter()
                .any(|p| p.name == "primvars:displayColor")
            {
                let c = mesh.material.color();
                prim.properties.push(interpolated(
                    attribute(
                        "color3f[]",
                        "primvars:displayColor",
                        UsdValue::Array(vec![tuple3([c.r, c.g, c.b])]),
                    ),
                    "constant",
                ));
            }
            let opacity = mesh.material.opacity();
            if opacity < 1.0 {
                prim.properties.push(interpolated(
                    attribute(
                        "float[]",
                        "primvars:displayOpacity",
                        UsdValue::Array(vec![UsdValue::Float(opacity as f64)]),
                    ),
                    "constant",
                ));
            }
            prim.properties.push(UsdProperty {
                qualifier: String::new(),
                name: "material:binding".into(),
                type_name: String::new(),
                uniform: false,
                relationship: true,
                value: UsdValue::Path(format!("/Root/{}", sanitize(&material_name))),
                metadata: Vec::new(),
            });
            // A binding without the schema that defines it is what `usdchecker`
            // objects to, and some readers ignore the binding outright.
            prim.metadata.push((
                "prepend apiSchemas".into(),
                UsdValue::Array(vec![UsdValue::Token("MaterialBindingAPI".into())]),
            ));
            // A material array: a `GeomSubset` per group, in the
            // `materialBind` family, binding that group's material to the
            // faces its triangles make — what the reader turns back into
            // groups. The mesh's own binding (the first material) covers
            // whatever no group claims.
            if mesh.is_multi_material() {
                let face_of = face_first_triangles(&mesh.geometry);
                let mut subsets = Vec::new();
                for (k, g) in mesh.geometry.groups.iter().enumerate() {
                    let Some(m) = mesh.materials.get(g.material_index as usize) else {
                        continue;
                    };
                    let (lo, hi) = (g.start as usize, g.start as usize + g.count as usize);
                    let faces: Vec<u32> = face_of
                        .iter()
                        .enumerate()
                        .filter(|&(_, &t)| (lo..hi).contains(&(t * 3)))
                        .map(|(f, _)| f as u32)
                        .collect();
                    if faces.is_empty() {
                        continue;
                    }
                    let material_name = format!("Material_{}", materials.prims.len());
                    let (material, images) = material_prim_with_textures(m, &material_name, &root);
                    materials.prims.push(material);
                    materials.textures.extend(images);
                    subsets.push(UsdPrim {
                        specifier: Specifier::Def,
                        type_name: "GeomSubset".into(),
                        name: format!("Group_{k}"),
                        metadata: vec![(
                            "prepend apiSchemas".into(),
                            UsdValue::Array(vec![UsdValue::Token("MaterialBindingAPI".into())]),
                        )],
                        properties: vec![
                            uniform(attribute(
                                "token",
                                "elementType",
                                UsdValue::Token("face".into()),
                            )),
                            uniform(attribute(
                                "token",
                                "familyName",
                                UsdValue::Token("materialBind".into()),
                            )),
                            attribute("int[]", "indices", int_array(faces.into_iter())),
                            UsdProperty {
                                qualifier: String::new(),
                                name: "material:binding".into(),
                                type_name: String::new(),
                                uniform: false,
                                relationship: true,
                                value: UsdValue::Path(format!(
                                    "/Root/{}",
                                    sanitize(&material_name)
                                )),
                                metadata: Vec::new(),
                            },
                        ],
                        children: Vec::new(),
                        variant_sets: Vec::new(),
                    });
                }
                if !subsets.is_empty() {
                    prim.properties.push(uniform(attribute(
                        "token",
                        "subsetFamily:materialBind:familyType",
                        UsdValue::Token("nonOverlapping".into()),
                    )));
                    prim.children.extend(subsets);
                }
            }
            let mesh_path = format!("{parent}/{}", prim.name);
            add_blend_shapes(mesh, &mut prim, &mesh_path, &root, &mut materials.skel);
            prim
        }
        _ => UsdPrim {
            specifier: Specifier::Def,
            type_name: "Xform".into(),
            name: sanitize(&name),
            metadata: Vec::new(),
            properties: Vec::new(),
            children: Vec::new(),
            variant_sets: Vec::new(),
        },
    };

    // Transform, written as the three ops USD reads in this order.
    let p = object.position;
    let q = object.quaternion;
    let s = object.scale;
    let mut order = Vec::new();
    if p.length_sq() > 0.0 {
        prim.properties.push(attribute(
            "double3",
            "xformOp:translate",
            tuple3([p.x, p.y, p.z]),
        ));
        order.push(UsdValue::Token("xformOp:translate".into()));
    }
    if (q.w - 1.0).abs() > 1e-9 || q.x != 0.0 || q.y != 0.0 || q.z != 0.0 {
        // USD writes the real part first.
        prim.properties.push(attribute(
            "quatf",
            "xformOp:orient",
            UsdValue::Tuple(
                [q.w, q.x, q.y, q.z]
                    .iter()
                    .map(|v| UsdValue::Float(*v as f64))
                    .collect(),
            ),
        ));
        order.push(UsdValue::Token("xformOp:orient".into()));
    }
    if (s.x - 1.0).abs() > 1e-9 || (s.y - 1.0).abs() > 1e-9 || (s.z - 1.0).abs() > 1e-9 {
        prim.properties.push(attribute(
            "float3",
            "xformOp:scale",
            tuple3([s.x, s.y, s.z]),
        ));
        order.push(UsdValue::Token("xformOp:scale".into()));
    }
    if !order.is_empty() {
        prim.properties.push(UsdProperty {
            qualifier: String::new(),
            name: "xformOpOrder".into(),
            type_name: "token[]".into(),
            uniform: true,
            relationship: false,
            value: UsdValue::Array(order),
            metadata: Vec::new(),
        });
    }
    if !object.visible {
        prim.properties.push(UsdProperty {
            qualifier: String::new(),
            name: "visibility".into(),
            type_name: "token".into(),
            uniform: false,
            relationship: false,
            value: UsdValue::Token("invisible".into()),
            metadata: Vec::new(),
        });
    }

    let path = format!("{parent}/{}", prim.name);
    placed.push((id, path.clone()));
    for (i, child) in object.children.iter().enumerate() {
        if let Some(c) = object_prim_at(arena, *child, i, materials, &path, placed) {
            prim.children.push(c);
        }
    }
    Some(prim)
}

#[cfg(test)]
mod tests {

    /// A material array leaves as `GeomSubset`s, one per group, and comes
    /// back through the reader as the same groups over the same materials.
    #[test]
    fn material_groups_round_trip_as_geom_subsets() {
        use crate::core::{BufferAttribute, Mesh, Object3D, ObjectArena, ObjectKind};
        use crate::materials::{Material, StandardMaterial};
        use crate::math::Color;
        use std::sync::Arc;
        let mut g = BufferGeometry::new();
        g.set_attribute(
            "position",
            BufferAttribute::new(
                vec![
                    0., 0., 0., 1., 0., 0., 1., 1., 0., 0., 1., 0., 2., 0., 0., 2., 1., 0.,
                ],
                3,
            ),
        );
        g.set_index(vec![0, 1, 2, 0, 2, 3, 1, 4, 5, 1, 5, 2]);
        g.add_group(0, 6, 1).add_group(6, 6, 0);
        let red = Arc::new(Material::from(StandardMaterial::new(Color::new(
            1.0, 0.0, 0.0,
        ))));
        let blue = Arc::new(Material::from(StandardMaterial::new(Color::new(
            0.0, 0.0, 1.0,
        ))));
        let mut arena = ObjectArena::new();
        let mut o = Object3D::mesh(Mesh::with_materials(Arc::new(g), vec![red, blue]));
        o.name = "Strip".into();
        let id = arena.insert(o);
        let text = scene_to_usda(&arena, &[id]);
        assert_eq!(text.matches("def GeomSubset").count(), 2, "{text}");
        let scene = super::super::scene::to_scene(&super::super::parse::parse(&text).unwrap());
        let strip = scene
            .arena
            .nodes
            .values()
            .find(|n| n.name == "Strip")
            .expect("the mesh");
        let ObjectKind::Mesh(mesh) = &strip.kind else {
            panic!("a mesh")
        };
        let groups: Vec<(u32, u32)> = mesh
            .geometry
            .groups
            .iter()
            .map(|g| (g.start, g.count))
            .collect();
        assert_eq!(groups, [(0, 6), (6, 6)]);
        let colours: Vec<[f32; 3]> = mesh
            .materials
            .iter()
            .map(|m| {
                let c = m.color();
                [c.r, c.g, c.b]
            })
            .collect();
        // The first group (triangles 0-1) wore blue, the second red.
        assert_eq!(colours, [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0]]);
    }

    /// A morphed mesh: an indexed quad with two *absolute* position targets
    /// and their normal targets, posed at `[0.25, 0.5]`. Absolute so the
    /// export has to convert to USD's offsets rather than copy them.
    fn morphed_quad() -> (crate::core::ObjectArena, crate::core::ObjectId) {
        use crate::core::{BufferAttribute, Mesh, Object3D, ObjectArena};
        use crate::materials::{Material, StandardMaterial};
        let base = vec![0., 0., 0., 1., 0., 0., 1., 1., 0., 0., 1., 0.];
        let up = [0., 0., 1.0f32].repeat(4);
        let mut g = BufferGeometry::new();
        g.set_attribute("position", BufferAttribute::new(base.clone(), 3));
        g.set_attribute("normal", BufferAttribute::new(up.clone(), 3));
        g.set_index(vec![0, 1, 2, 0, 2, 3]);
        // Smile lifts the top edge only (a sparse target); Bulge pushes
        // every vertex out along z and tilts the normals.
        let mut smile = base.clone();
        smile[7] += 0.5;
        smile[10] += 0.5;
        let bulge: Vec<f32> = base
            .chunks(3)
            .flat_map(|p| [p[0], p[1], p[2] + 0.75])
            .collect();
        let tilted: Vec<f32> = [0.0, 0.6, 0.8f32].repeat(4);
        g.morph_targets_relative = false;
        g.morph_target_names = vec!["smile".into(), "bulge".into()];
        g.set_morph_attribute(
            "position",
            vec![
                BufferAttribute::new(smile, 3),
                BufferAttribute::new(bulge, 3),
            ],
        );
        g.morph_attributes.insert(
            "normal".into(),
            vec![BufferAttribute::new(up, 3), BufferAttribute::new(tilted, 3)],
        );
        let mut mesh = Mesh::new(g, Material::Standard(StandardMaterial::default()));
        mesh.morph_influences = vec![0.25, 0.5];
        let mut arena = ObjectArena::new();
        let mut o = Object3D::mesh(mesh);
        o.name = "Face".into();
        let id = arena.insert(o);
        (arena, id)
    }

    /// The posed triangle corners of a mesh, position and normal, sorted —
    /// the surface it draws, whatever indexing the reader chose.
    fn posed_corners(mesh: &crate::core::Mesh) -> Vec<[i64; 6]> {
        let g = mesh.posed_geometry();
        let p = &g.get_attribute("position").unwrap().array;
        let n = &g.get_attribute("normal").unwrap().array;
        let count = p.len() / 3;
        let order: Vec<usize> = match &g.index {
            Some(i) => i.iter().map(|&v| v as usize).collect(),
            None => (0..count).collect(),
        };
        let mut out: Vec<[i64; 6]> = order
            .iter()
            .map(|&v| {
                let q = |x: f32| (x * 1e4).round() as i64;
                [
                    q(p[v * 3]),
                    q(p[v * 3 + 1]),
                    q(p[v * 3 + 2]),
                    q(n[v * 3]),
                    q(n[v * 3 + 1]),
                    q(n[v * 3 + 2]),
                ]
            })
            .collect();
        out.sort();
        out.dedup();
        out
    }

    fn the_face(scene: &super::super::scene::UsdScene) -> &crate::core::Mesh {
        use crate::core::ObjectKind;
        let face = scene
            .arena
            .nodes
            .values()
            .find(|n| n.name == "Face")
            .expect("the mesh");
        let ObjectKind::Mesh(mesh) = &face.kind else {
            panic!("a plain mesh, not {:?}", std::mem::discriminant(&face.kind))
        };
        mesh
    }

    /// Morph targets leave as UsdSkel blend shapes — offsets from the base,
    /// bound through `skel:blendShapes` / `skel:blendShapeTargets` under a
    /// `SkelRoot`, with the current influences as the weights of the
    /// `SkelAnimation` the binding names — and come back as the same targets
    /// posed the same way, through both the text and the crate form.
    #[test]
    fn morph_targets_round_trip_as_blend_shapes() {
        use crate::core::ObjectKind;
        let (arena, id) = morphed_quad();
        let ObjectKind::Mesh(original) = &arena.get(id).unwrap().kind else {
            unreachable!()
        };
        let want = posed_corners(original);

        let text = scene_to_usda(&arena, &[id]);
        assert_eq!(text.matches("def BlendShape").count(), 2, "{text}");
        assert!(text.contains("def SkelRoot \"Root\""), "{text}");
        assert!(text.contains("skel:blendShapeTargets"), "{text}");
        assert!(text.contains("blendShapeWeights"), "{text}");
        // Smile touches two vertices, so it is written sparse.
        assert!(text.contains("pointIndices"), "{text}");

        let usdc = super::super::scene_to_usdc(&arena, &[id]);
        for (form, layer) in [
            (
                "usda",
                super::super::parse::parse(&text).expect("usda parses"),
            ),
            (
                "usdc",
                super::super::UsdLoader::parse_layer(&usdc).expect("usdc parses"),
            ),
            // The same document, re-authored as a crate by OpenUSD's own
            // `usdcat morph.usda -o morph_blend_shapes.usdc` — so the reader
            // is held to what USD writes, not only to this crate's writer.
            (
                "usdcat usdc",
                super::super::UsdLoader::parse_layer(include_bytes!(
                    "testdata/morph_blend_shapes.usdc"
                ))
                .expect("usdcat's crate parses"),
            ),
        ] {
            let scene = super::super::scene::to_scene(&layer);
            let mesh = the_face(&scene);
            assert_eq!(
                mesh.geometry.morph_target_names,
                ["smile", "bulge"],
                "{form}: target names"
            );
            assert_eq!(mesh.morph_influences, [0.25, 0.5], "{form}: influences");
            assert_eq!(
                mesh.morph_target_dictionary.get("bulge"),
                Some(&1),
                "{form}: dictionary"
            );
            assert_eq!(posed_corners(mesh), want, "{form}: posed surface");
            // Unposed too: the targets themselves, not just this one pose.
            let mut rest = mesh.clone();
            rest.morph_influences = vec![0.0, 1.0];
            let mut orig = original.clone();
            orig.morph_influences = vec![0.0, 1.0];
            assert_eq!(
                posed_corners(&rest),
                posed_corners(&orig),
                "{form}: bulge alone"
            );
            // No stray nodes for the shapes, the skeleton or the animation.
            for n in scene.arena.nodes.values() {
                assert!(
                    !["smile", "bulge", "Smile", "Bulge"].contains(&n.name.as_str())
                        && !n.name.starts_with("Morph"),
                    "{form}: a node {:?} for a skel prim",
                    n.name
                );
            }
        }
    }

    /// A connection is written once, not twice.
    ///
    /// The writer appends `.connect` because the value is a path, so the
    /// property must *not* be named with the suffix as well — doing both
    /// produced `outputs:surface.connect.connect`, which USD refuses to parse
    /// at all. The round-trip tests missed it because both sides of this crate
    /// agreed with each other; OpenUSD did not.
    #[test]
    fn a_connection_is_not_spelled_twice() {
        use crate::core::{Mesh, Object3D, ObjectArena};
        use crate::geometries::BoxGeometry;
        use crate::materials::{Material, StandardMaterial};

        let mut arena = ObjectArena::new();
        let id = arena.insert(Object3D::mesh(Mesh::new(
            BoxGeometry::new(1.0, 1.0, 1.0),
            Material::Standard(StandardMaterial::default()),
        )));
        let text = scene_to_usda(&arena, &[id]);

        assert!(
            !text.contains(".connect.connect"),
            "the suffix was written twice:\n{text}"
        );
        assert!(text.contains("outputs:surface.connect = <"), "{text}");

        // And it reads back as the attribute, not as a property with a dot in
        // its name — which is not a name USD can hold.
        let layer = super::super::parse::parse(&text).expect("what we wrote, USD can read");
        let material = layer.prim_at("/Root/Material_0").expect("the material");
        assert!(material.property("outputs:surface.connect").is_none());
        let surface = material
            .property("outputs:surface")
            .expect("the connection");
        assert!(
            matches!(surface.value, UsdValue::Path(_)),
            "{:?}",
            surface.value
        );
    }

    /// Animation written out and read back is the animation that went in.
    #[test]
    fn a_clip_round_trips_through_a_document() {
        use crate::animation::{AnimationClip, KeyframeTrack, TrackTarget};
        use crate::core::Object3D;
        use crate::math::{Quaternion, Vector3};

        let mut arena = ObjectArena::new();
        let mut object = Object3D::group();
        object.name = "Mover".into();
        let id = arena.insert(object);

        let clip = AnimationClip::new(
            "spin",
            2.0,
            vec![
                KeyframeTrack::vector(
                    id,
                    TrackTarget::Position,
                    vec![0.0, 1.0, 2.0],
                    vec![
                        Vector3::new(0.0, 0.0, 0.0),
                        Vector3::new(10.0, 0.0, 0.0),
                        Vector3::new(10.0, 10.0, 0.0),
                    ],
                ),
                KeyframeTrack::quaternion(
                    id,
                    TrackTarget::Quaternion,
                    vec![0.0, 2.0],
                    vec![
                        Quaternion::identity(),
                        Quaternion::from_axis_angle(Vector3::new(0.0, 0.0, 1.0), 1.0),
                    ],
                ),
            ],
        );

        let text = animated_scene_to_usda(&arena, &[id], &[clip]);
        let layer = super::super::parse::parse(&text).expect("what we wrote, we can read");

        // The layer says how fast it runs and how long it is.
        assert_eq!(layer.time_codes_per_second(), 24.0);
        assert_eq!(layer.time_range(), Some((0.0, 48.0)));

        let mover = layer.prim_at("/Root/Mover").expect("the animated prim");
        let translate = mover.value("xformOp:translate").unwrap();
        let samples = translate.samples().expect("animated");
        assert_eq!(samples.len(), 3);
        // Seconds became time codes.
        assert_eq!(samples[1].0, 24.0);
        assert_eq!(samples[2].1.flat_f32(), vec![10.0, 10.0, 0.0]);

        // An op that only exists because it is animated still has to be in the
        // order, or USD ignores it.
        let order = mover.value("xformOpOrder").unwrap().flat_tokens();
        assert!(order.contains(&"xformOp:translate"), "{order:?}");
        assert!(order.contains(&"xformOp:orient"), "{order:?}");
    }

    /// Out through the exporter and back in through the scene builder: the
    /// clip that comes back drives the same object the same way.
    #[test]
    fn a_clip_survives_the_whole_round_trip() {
        use crate::animation::{AnimationClip, KeyframeTrack, TrackTarget, TrackValues};
        use crate::core::Object3D;
        use crate::math::Vector3;

        let mut arena = ObjectArena::new();
        let mut object = Object3D::group();
        object.name = "Mover".into();
        let id = arena.insert(object);
        let clip = AnimationClip::new(
            "move",
            2.0,
            vec![KeyframeTrack::vector(
                id,
                TrackTarget::Position,
                vec![0.0, 2.0],
                vec![Vector3::new(0.0, 0.0, 0.0), Vector3::new(4.0, 0.0, 0.0)],
            )],
        );

        let text = animated_scene_to_usda(&arena, &[id], &[clip]);
        let layer = super::super::parse::parse(&text).unwrap();
        let scene = super::super::scene::to_scene(&layer);

        let back = scene.animations.first().expect("a clip came back");
        assert_eq!(back.duration, 2.0);
        let track = back
            .tracks
            .iter()
            .find(|t| matches!(t.target, TrackTarget::Position))
            .expect("a position track");
        assert_eq!(track.times, vec![0.0, 2.0]);
        let TrackValues::Vector(values) = &track.values else {
            panic!("expected vectors");
        };
        assert_eq!(values[1], Vector3::new(4.0, 0.0, 0.0));
    }

    /// A scene with no animation is written exactly as it was before, with no
    /// time metadata invented for it.
    #[test]
    fn a_static_scene_gains_no_timing() {
        use crate::core::Object3D;
        let mut arena = ObjectArena::new();
        let id = arena.insert(Object3D::group());
        let text = animated_scene_to_usda(&arena, &[id], &[]);
        assert!(!text.contains("timeCodesPerSecond"), "{text}");
        assert!(!text.contains("timeSamples"), "{text}");
    }
    use super::super::parse::parse;
    use super::super::scene::{mesh_geometry, to_scene};
    use super::*;
    use crate::core::{BufferAttribute, Mesh, Object3D};
    use crate::materials::StandardMaterial;
    use crate::math::{Color, Vector3};

    fn triangle() -> BufferGeometry {
        let mut g = BufferGeometry::new();
        g.set_attribute(
            "position",
            BufferAttribute::new(vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0], 3),
        );
        g.set_attribute(
            "uv",
            BufferAttribute::new(vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0], 2),
        );
        g.set_index(vec![0, 1, 2]);
        g
    }

    #[test]
    fn a_geometry_round_trips_through_usda() {
        let text = geometry_to_usda(&triangle(), "Tri");
        let layer = parse(&text).unwrap();
        let prim = layer.prim_at("/Root/Tri").unwrap();
        assert_eq!(prim.type_name, "Mesh");
        let back = mesh_geometry(prim).unwrap();
        assert_eq!(
            back.get_attribute("position").unwrap().array,
            triangle().get_attribute("position").unwrap().array
        );
        assert_eq!(back.index.clone().unwrap(), vec![0, 1, 2]);
        assert_eq!(back.get_attribute("uv").unwrap().array.len(), 6);
    }

    #[test]
    fn the_extent_is_written_and_is_the_bounding_box() {
        let layer = parse(&geometry_to_usda(&triangle(), "Tri")).unwrap();
        let extent = layer
            .prim_at("/Root/Tri")
            .unwrap()
            .value("extent")
            .unwrap()
            .flat_f32();
        assert_eq!(extent, vec![0.0, 0.0, 0.0, 1.0, 1.0, 0.0]);
    }

    #[test]
    fn names_that_are_not_identifiers_are_made_into_them() {
        assert_eq!(sanitize("wheel.001"), "wheel_001");
        assert_eq!(sanitize("2fast"), "_fast");
        assert_eq!(sanitize(""), "Prim");
        // And the result parses, which is the point of doing it.
        let text = geometry_to_usda(&triangle(), "wheel.001");
        assert!(parse(&text).unwrap().prim_at("/Root/wheel_001").is_some());
    }

    #[test]
    fn a_scene_keeps_its_hierarchy_and_transforms() {
        let mut arena = ObjectArena::new();
        let mut parent = Object3D::group();
        parent.name = "Parent".into();
        parent.position = Vector3::new(1.0, 2.0, 3.0);
        let parent_id = arena.insert(parent);

        let mut child = Object3D::mesh(Mesh::new(
            triangle(),
            StandardMaterial::new(Color::new(1.0, 0.0, 0.0)).into(),
        ));
        child.name = "Child".into();
        child.scale = Vector3::new(2.0, 2.0, 2.0);
        let child_id = arena.insert(child);
        arena.add_child(parent_id, child_id);

        let text = scene_to_usda(&arena, &[parent_id]);
        let layer = parse(&text).unwrap();
        let scene = to_scene(&layer);

        let root = scene.arena.get(scene.roots[0]).unwrap();
        // Root → Parent → Child, plus the material beside Parent.
        let parent = scene.arena.get(root.children[0]).unwrap();
        assert_eq!(parent.name, "Parent");
        assert!((parent.position.y - 2.0).abs() < 1e-6);
        let child = scene.arena.get(parent.children[0]).unwrap();
        assert_eq!(child.name, "Child");
        assert!((child.scale.x - 2.0).abs() < 1e-6);
    }

    /// Every material kind that has a colour exports with that colour.
    ///
    /// This existed as a grey `_` arm for a while: Lambert, Phong, Toon,
    /// Matcap, Sprite, Points, Line and Mirror all left as
    /// `(0.8, 0.8, 0.8)`, colour and opacity dropped. Nothing caught it,
    /// because the reader read back exactly the grey the writer wrote and the
    /// round-trip test agreed with itself. `usdcat` on an exported gallery is
    /// what showed it.
    #[test]
    fn every_coloured_material_exports_its_colour() {
        use crate::materials::{
            BasicMaterial, LambertMaterial, LineBasicMaterial, MatcapMaterial, MirrorMaterial,
            PhongMaterial, PhysicalMaterial, PointsMaterial, SpriteMaterial, ToonMaterial,
        };

        let red = Color::new(0.9, 0.2, 0.1);
        let kinds: Vec<(&str, Material)> = vec![
            (
                "lambert",
                LambertMaterial {
                    color: red,
                    ..Default::default()
                }
                .into(),
            ),
            (
                "phong",
                PhongMaterial {
                    color: red,
                    ..Default::default()
                }
                .into(),
            ),
            (
                "toon",
                ToonMaterial {
                    color: red,
                    ..Default::default()
                }
                .into(),
            ),
            (
                "matcap",
                MatcapMaterial {
                    color: red,
                    ..Default::default()
                }
                .into(),
            ),
            (
                "sprite",
                SpriteMaterial {
                    color: red,
                    ..Default::default()
                }
                .into(),
            ),
            (
                "points",
                PointsMaterial {
                    color: red,
                    ..Default::default()
                }
                .into(),
            ),
            (
                "line",
                LineBasicMaterial {
                    color: red,
                    ..Default::default()
                }
                .into(),
            ),
            (
                "mirror",
                MirrorMaterial {
                    color: red,
                    ..Default::default()
                }
                .into(),
            ),
            (
                "physical",
                PhysicalMaterial {
                    color: red,
                    ..Default::default()
                }
                .into(),
            ),
            ("basic", BasicMaterial::new(red).into()),
            ("standard", StandardMaterial::new(red).into()),
        ];
        for (label, material) in kinds {
            let prim = material_prim(&material, "M");
            let surface = &prim.children[0];
            let colour = surface
                .value("inputs:diffuseColor")
                .expect("a diffuse colour")
                .flat_f32();
            assert_eq!(
                colour,
                vec![0.9, 0.2, 0.1],
                "{label} lost its colour on the way out"
            );
        }
    }

    fn checker_texture() -> std::sync::Arc<crate::textures::Texture> {
        use crate::textures::{Texture, TextureFormat, TextureWrap};
        let mut t = Texture::new(
            2,
            2,
            TextureFormat::Rgba8UnormSrgb,
            vec![
                255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 0, 255,
            ],
        );
        t.wrap_s = TextureWrap::Repeat;
        t.wrap_t = TextureWrap::MirroredRepeat;
        std::sync::Arc::new(t)
    }

    fn child<'a>(prim: &'a UsdPrim, name: &str) -> &'a UsdPrim {
        prim.children
            .iter()
            .find(|c| c.name == name)
            .unwrap_or_else(|| panic!("no child {name}"))
    }

    /// A map exports as the shader network USD reads textures through.
    ///
    /// A `UsdPreviewSurface` cannot name a file itself: the image is a
    /// `UsdUVTexture`, the UVs come from a `UsdPrimvarReader_float2`, and the
    /// surface input is *connected* to the texture's output rather than
    /// holding a value. Writing the file path onto the surface would parse and
    /// mean nothing.
    #[test]
    fn a_map_exports_as_a_texture_network() {
        let mut m = StandardMaterial::new(Color::new(1.0, 1.0, 1.0));
        m.map = Some(checker_texture());
        let (prim, images) = material_prim_with_textures(&m.into(), "M", "/Root");

        assert_eq!(images.len(), 1);
        assert_eq!(images[0].path, "textures/M_DiffuseTex.png");
        assert!(images[0].data.starts_with(b"\x89PNG"), "a PNG was encoded");

        let texture = child(&prim, "DiffuseTex");
        assert_eq!(
            texture.value("info:id").unwrap().as_str(),
            Some("UsdUVTexture")
        );
        assert_eq!(
            texture.value("inputs:file").unwrap().as_str(),
            Some("textures/M_DiffuseTex.png")
        );
        assert_eq!(
            texture.value("inputs:wrapS").unwrap().as_str(),
            Some("repeat")
        );
        assert_eq!(
            texture.value("inputs:wrapT").unwrap().as_str(),
            Some("mirror")
        );
        assert_eq!(
            texture.value("inputs:sourceColorSpace").unwrap().as_str(),
            Some("sRGB")
        );

        let reader = child(&prim, "stReader");
        assert_eq!(
            reader.value("info:id").unwrap().as_str(),
            Some("UsdPrimvarReader_float2")
        );

        // The surface takes the connection, and the constant it replaces is
        // gone: two properties at one path is a spec USD refuses to open.
        let surface = child(&prim, "Surface");
        let diffuse: Vec<&UsdProperty> = surface
            .properties
            .iter()
            .filter(|p| p.name == "inputs:diffuseColor")
            .collect();
        assert_eq!(
            diffuse.len(),
            1,
            "one property, not a value and a connection"
        );
        assert_eq!(
            diffuse[0].value.as_str(),
            Some("/Root/M/DiffuseTex.outputs:rgb")
        );
    }

    /// A normal map carries the scale and bias that make it a normal map.
    ///
    /// Eight-bit pixels hold `[0,1]` and a normal is `[-1,1]`. Without
    /// `scale = (2,2,2,1)` and `bias = (-1,-1,-1,0)` every normal points into
    /// the surface, which reads as bad lighting rather than as a broken file.
    /// It is also `raw`, not `sRGB`.
    #[test]
    fn a_normal_map_carries_its_scale_and_bias() {
        let mut m = StandardMaterial::new(Color::new(1.0, 1.0, 1.0));
        m.normal_map = Some(checker_texture());
        let (prim, _) = material_prim_with_textures(&m.into(), "M", "/Root");
        let texture = child(&prim, "NormalTex");
        assert_eq!(
            texture.value("inputs:scale").unwrap().flat_f32(),
            vec![2.0, 2.0, 2.0, 1.0]
        );
        assert_eq!(
            texture.value("inputs:bias").unwrap().flat_f32(),
            vec![-1.0, -1.0, -1.0, 0.0]
        );
        assert_eq!(
            texture.value("inputs:sourceColorSpace").unwrap().as_str(),
            Some("raw")
        );
        // And it drives the surface's normal, not its colour.
        let surface = child(&prim, "Surface");
        assert!(surface.properties.iter().any(|p| p.name == "inputs:normal"));
    }

    /// A UV transform becomes a `UsdTransform2d`, in degrees.
    ///
    /// This crate keeps rotation in radians and USD's node takes degrees, so
    /// passing the number through unconverted turns a quarter turn into about
    /// one and a half degrees.
    #[test]
    fn a_uv_transform_becomes_a_transform_node_in_degrees() {
        use crate::math::Vector2;
        let mut texture = (*checker_texture()).clone();
        texture.repeat = Vector2::new(2.0, 3.0);
        texture.rotation = std::f32::consts::FRAC_PI_2;
        let mut m = StandardMaterial::new(Color::new(1.0, 1.0, 1.0));
        m.map = Some(std::sync::Arc::new(texture));
        let (prim, _) = material_prim_with_textures(&m.into(), "M", "/Root");

        let node = child(&prim, "DiffuseTexTransform");
        assert_eq!(
            node.value("info:id").unwrap().as_str(),
            Some("UsdTransform2d")
        );
        assert_eq!(
            node.value("inputs:scale").unwrap().flat_f32(),
            vec![2.0, 3.0]
        );
        let rotation = node.value("inputs:rotation").unwrap().flat_f32()[0];
        assert!(
            (rotation - 90.0).abs() < 1e-3,
            "{rotation} should be degrees"
        );

        // And the texture samples the transform rather than the reader.
        assert_eq!(
            child(&prim, "DiffuseTex")
                .value("inputs:st")
                .unwrap()
                .as_str(),
            Some("/Root/M/DiffuseTexTransform.outputs:result")
        );
    }

    /// A texture with no readable pixels leaves the constant value standing.
    ///
    /// A material whose bytes are on the GPU has nothing to write; dropping
    /// the map is right, and dropping the colour with it is not.
    #[test]
    fn a_texture_with_no_pixels_is_skipped_not_fatal() {
        use crate::textures::{Texture, TextureFormat};
        let mut m = StandardMaterial::new(Color::new(0.25, 0.5, 0.75));
        m.map = Some(std::sync::Arc::new(Texture::new(
            4,
            4,
            TextureFormat::Rgba8UnormSrgb,
            Vec::new(),
        )));
        let (prim, images) = material_prim_with_textures(&m.into(), "M", "/Root");
        assert!(images.is_empty());
        assert_eq!(
            child(&prim, "Surface")
                .value("inputs:diffuseColor")
                .unwrap()
                .flat_f32(),
            vec![0.25, 0.5, 0.75]
        );
    }

    /// A `.usdz` carries the images its layer names.
    ///
    /// The package format exists to be self-contained; one that refers to a
    /// `textures/` directory that travelled separately is a valid archive and
    /// a broken asset.
    #[test]
    fn a_usdz_packs_the_textures_its_materials_name() {
        use crate::core::{Mesh, Object3D, ObjectArena};
        let mut m = StandardMaterial::new(Color::new(1.0, 1.0, 1.0));
        m.map = Some(checker_texture());
        let mut arena = ObjectArena::new();
        let id = arena.insert(Object3D::mesh(Mesh::new(triangle(), m.into())));
        let bytes = super::super::scene_to_usdz(&arena, &[id], &[]);

        let archive = super::super::usdz::read(&bytes).expect("a readable archive");
        let names: Vec<&str> = archive.entries.iter().map(|e| e.name.as_str()).collect();
        assert!(
            names.contains(&"textures/Material_0_DiffuseTex.png"),
            "{names:?}"
        );
    }

    /// Only a double-sided material says anything about sidedness, and it
    /// says it on the mesh, where USD keeps it.
    #[test]
    fn double_sided_lands_on_the_mesh() {
        use crate::core::{Mesh, Object3D, ObjectArena};
        use crate::materials::LambertMaterial;
        for (side, expected) in [(0u32, false), (2, true)] {
            let m = LambertMaterial {
                side,
                ..Default::default()
            };
            let mut arena = ObjectArena::new();
            let id = arena.insert(Object3D::mesh(Mesh::new(triangle(), m.into())));
            let layer = scene_to_layer(&arena, &[id], &UsdExportOptions::default());
            let mesh = layer.prim_at("/Root/Node_0").expect("the mesh");
            assert_eq!(mesh.value("doubleSided").is_some(), expected, "side {side}");
        }
    }

    /// Index of refraction and clear coat come from a physical material and
    /// from nothing else, so a standard material does not restate USD's
    /// defaults back at it.
    #[test]
    fn ior_and_clearcoat_are_physical_only() {
        use crate::materials::PhysicalMaterial;
        let p = PhysicalMaterial {
            ior: 1.45,
            clearcoat: 0.8,
            clearcoat_roughness: 0.05,
            ..Default::default()
        };
        let surface = material_prim(&p.into(), "M").children[0].clone();
        assert_eq!(surface.value("inputs:ior").unwrap().flat_f32(), vec![1.45]);
        assert_eq!(
            surface.value("inputs:clearcoat").unwrap().flat_f32(),
            vec![0.8]
        );

        let plain = material_prim(
            &StandardMaterial::new(Color::new(1.0, 1.0, 1.0)).into(),
            "M",
        );
        assert!(plain.children[0].value("inputs:ior").is_none());
        assert!(plain.children[0].value("inputs:clearcoat").is_none());
    }

    /// Vertex colours survive, as USD's fallback shading.
    ///
    /// `primvars:displayColor` is what every tool that does not evaluate a
    /// shader graph falls back to. Without it a vertex-coloured mesh exported
    /// from here arrived grey and the colours were simply gone — the material
    /// carries one colour and a mesh may have one per vertex.
    #[test]
    fn vertex_colours_export_as_display_colour() {
        use crate::core::BufferAttribute;
        let mut g = triangle();
        g.set_attribute(
            "color",
            BufferAttribute::new(vec![1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], 3),
        );
        let layer = parse(&geometry_to_usda(&g, "M")).unwrap();
        let prim = layer.prim_at("/Root/M").unwrap();
        let property = prim.property("primvars:displayColor").expect("a colour");
        assert_eq!(
            property.value.flat_f32(),
            vec![1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]
        );
        assert_eq!(
            property.meta("interpolation").and_then(|v| v.as_str()),
            Some("vertex")
        );
    }

    /// With no colour per vertex, the material's colour stands in as a
    /// constant — so the mesh is right even to a reader that skips shading.
    #[test]
    fn a_material_colour_becomes_a_constant_display_colour() {
        use crate::core::{Mesh, Object3D, ObjectArena};
        let mut arena = ObjectArena::new();
        let id = arena.insert(Object3D::mesh(Mesh::new(
            triangle(),
            StandardMaterial::new(Color::new(0.25, 0.5, 0.75)).into(),
        )));
        let layer = parse(&scene_to_usda(&arena, &[id])).unwrap();
        let property = layer
            .prim_at("/Root/Node_0")
            .unwrap()
            .property("primvars:displayColor")
            .expect("a colour");
        assert_eq!(property.value.flat_f32(), vec![0.25, 0.5, 0.75]);
        assert_eq!(
            property.meta("interpolation").and_then(|v| v.as_str()),
            Some("constant")
        );
    }

    /// A constant display colour is not a vertex attribute.
    ///
    /// One value applies to the whole surface. Read as if it were per vertex,
    /// the first vertex gets the colour and every other one reads past the end
    /// of the array — which for a colour is black.
    #[test]
    fn a_constant_display_colour_does_not_become_vertex_colours() {
        use crate::loaders::usd::scene::to_scene;
        let mut arena = crate::core::ObjectArena::new();
        let id = arena.insert(crate::core::Object3D::mesh(crate::core::Mesh::new(
            triangle(),
            StandardMaterial::new(Color::new(0.25, 0.5, 0.75)).into(),
        )));
        let layer = parse(&scene_to_usda(&arena, &[id])).unwrap();
        let scene = to_scene(&layer);
        let root = scene.arena.get(scene.roots[0]).unwrap();
        let ObjectKind::Mesh(mesh) = &scene.arena.get(root.children[0]).unwrap().kind else {
            panic!("not a mesh");
        };
        assert!(
            mesh.geometry.get_attribute("color").is_none(),
            "a constant colour is the material's, not the vertices'"
        );
    }

    /// Vertex colours make the whole trip, out and back.
    #[test]
    fn vertex_colours_come_back() {
        use crate::core::BufferAttribute;
        use crate::loaders::usd::scene::to_scene;
        let mut g = triangle();
        let colours = vec![1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
        g.set_attribute("color", BufferAttribute::new(colours.clone(), 3));
        let mut arena = crate::core::ObjectArena::new();
        let id = arena.insert(crate::core::Object3D::mesh(crate::core::Mesh::new(
            g,
            StandardMaterial::new(Color::new(1.0, 1.0, 1.0)).into(),
        )));
        let layer = parse(&scene_to_usda(&arena, &[id])).unwrap();
        let scene = to_scene(&layer);
        let root = scene.arena.get(scene.roots[0]).unwrap();
        let ObjectKind::Mesh(mesh) = &scene.arena.get(root.children[0]).unwrap().kind else {
            panic!("not a mesh");
        };
        assert_eq!(
            mesh.geometry.get_attribute("color").expect("colours").array,
            colours
        );
    }

    /// A cutout material carries its threshold, and a blended one does not.
    #[test]
    fn an_alpha_test_becomes_an_opacity_threshold() {
        use crate::materials::BasicMaterial;
        let cutout = BasicMaterial {
            alpha_test: 0.5,
            ..BasicMaterial::new(Color::new(1.0, 1.0, 1.0))
        };
        let surface = material_prim(&cutout.into(), "M").children[0].clone();
        assert_eq!(
            surface.value("inputs:opacityThreshold").unwrap().flat_f32(),
            vec![0.5]
        );
        let blended = material_prim(&BasicMaterial::new(Color::new(1.0, 1.0, 1.0)).into(), "M");
        assert!(blended.children[0]
            .value("inputs:opacityThreshold")
            .is_none());
    }

    /// All three forms carry the same document, and none of them loses the
    /// pictures.
    ///
    /// `scene_to_usdc` used to hand back bytes referring to `textures/*.png`
    /// and drop the images on the floor, so a crate written from a textured
    /// scene was dangling by construction. The package carries them; the other
    /// two report them so they can be written alongside.
    #[test]
    fn every_form_keeps_the_textures() {
        use super::super::{UsdExport, UsdLoader};
        use crate::core::{Mesh, Object3D, ObjectArena};

        let material = StandardMaterial {
            map: Some(checker_texture()),
            ..StandardMaterial::new(Color::new(1.0, 1.0, 1.0))
        };
        let mut arena = ObjectArena::new();
        let id = arena.insert(Object3D::mesh(Mesh::new(triangle(), material.into())));
        let out = UsdExport::scene(&arena, &[id]);

        assert_eq!(out.textures.len(), 1, "the export knows about its image");
        assert_eq!(out.textures[0].path, "textures/Material_0_DiffuseTex.png");

        // Each form is the same document.
        let from_text = super::super::parse::parse(&out.usda()).unwrap();
        let from_crate = super::super::usdc::read(&out.usdc()).unwrap();
        for layer in [&from_text, &from_crate] {
            let shader = layer
                .prim_at("/Root/Material_0/DiffuseTex")
                .expect("the texture shader");
            assert_eq!(
                shader.value("inputs:file").unwrap().as_str(),
                Some("textures/Material_0_DiffuseTex.png")
            );
        }

        // And the package needs nothing beside it.
        let scene = UsdLoader::parse(&out.usdz()).expect("reads back");
        let ObjectKind::Mesh(mesh) = &scene
            .arena
            .get(scene.arena.get(scene.roots[0]).unwrap().children[0])
            .unwrap()
            .kind
        else {
            panic!("not a mesh");
        };
        let Material::Standard(back) = &*mesh.material else {
            panic!("{:?}", mesh.material)
        };
        assert!(back.map.is_some(), "the package carried its image");
    }

    /// A `.usda` written to disk with its images beside it reads back whole.
    ///
    /// This is what the package form gets for free and the other two have to
    /// be told: the layer names `textures/foo.png` relative to itself, so the
    /// file has to be there and the reader has to be told where "there" is.
    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn a_layer_written_to_disk_reads_back_with_its_images() {
        use super::super::{attach_textures_from_dir, UsdExport, UsdLoader};
        use crate::core::{Mesh, Object3D, ObjectArena};

        let material = StandardMaterial {
            map: Some(checker_texture()),
            ..StandardMaterial::new(Color::new(1.0, 1.0, 1.0))
        };
        let mut arena = ObjectArena::new();
        let id = arena.insert(Object3D::mesh(Mesh::new(triangle(), material.into())));
        let out = UsdExport::scene(&arena, &[id]);

        let dir = std::env::temp_dir().join(format!("threers_usd_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        for name in ["disk.usda", "disk.usdc"] {
            let path = dir.join(name);
            out.write_to(&path, &dir).expect("writes");
            assert!(
                dir.join("textures/Material_0_DiffuseTex.png").exists(),
                "the image landed beside {name}"
            );

            let bytes = std::fs::read(&path).unwrap();
            let mut scene = UsdLoader::parse(&bytes).expect("reads");
            // Before being told where to look, it reports what it wants.
            assert_eq!(
                scene.textures.iter().flat_map(|(_, r)| r).count(),
                1,
                "{name} should ask for its image"
            );
            assert_eq!(attach_textures_from_dir(&mut scene, &dir), 1, "{name}");

            let ObjectKind::Mesh(mesh) = &scene
                .arena
                .get(scene.arena.get(scene.roots[0]).unwrap().children[0])
                .unwrap()
                .kind
            else {
                panic!("not a mesh");
            };
            let Material::Standard(back) = &*mesh.material else {
                panic!("{:?}", mesh.material)
            };
            let map = back
                .map
                .as_ref()
                .unwrap_or_else(|| panic!("{name} lost its map"));
            assert_eq!(&map.data[..4], &[255, 0, 0, 255], "{name} pixels changed");
        }
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A path climbing out of the directory is not followed.
    ///
    /// The function was handed a directory, not the disk. A layer that names
    /// `../../etc/passwd` gets told no and keeps asking, rather than being
    /// quietly obliged.
    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn a_texture_path_does_not_escape_its_directory() {
        use super::super::{attach_textures_from_dir, UsdLoader};

        let dir = std::env::temp_dir().join(format!("threers_usd_esc_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("sub")).unwrap();
        // A real PNG, reachable only by climbing out of `sub`.
        std::fs::write(
            dir.join("secret.png"),
            crate::utils::png::encode_png(1, 1, &[9, 9, 9, 255]),
        )
        .unwrap();

        let text = r#"#usda 1.0

def Mesh "M" (
    prepend apiSchemas = ["MaterialBindingAPI"]
)
{
    int[] faceVertexCounts = [3]
    int[] faceVertexIndices = [0, 1, 2]
    rel material:binding = </Mat>
    point3f[] points = [(0, 0, 0), (1, 0, 0), (0, 1, 0)]
}

def Material "Mat"
{
    token outputs:surface.connect = </Mat/S.outputs:surface>

    def Shader "S"
    {
        uniform token info:id = "UsdPreviewSurface"
        color3f inputs:diffuseColor.connect = </Mat/T.outputs:rgb>
        token outputs:surface
    }

    def Shader "T"
    {
        uniform token info:id = "UsdUVTexture"
        asset inputs:file = @../secret.png@
        float3 outputs:rgb
    }
}
"#;
        let mut scene = UsdLoader::parse(text.as_bytes()).expect("reads");
        assert_eq!(
            attach_textures_from_dir(&mut scene, &dir.join("sub")),
            0,
            "a path climbing out was followed"
        );
        assert_eq!(
            scene.textures.iter().flat_map(|(_, r)| r).count(),
            1,
            "and it is still reported rather than dropped"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A JPEG texture loads like a PNG one, with the `jpeg` feature: the
    /// colour map arrives on the material instead of staying a request.
    /// Without the feature it stays a request, reported rather than dropped.
    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn a_jpeg_texture_is_attached() {
        use super::super::{attach_textures_from_dir, UsdLoader};

        let dir = std::env::temp_dir().join(format!("threers_usd_jpeg_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        // one copy named .png on purpose: the decoder goes by the bytes, not the name
        let jpeg = include_bytes!("../testdata/jpeg/rgb.jpg");
        std::fs::write(dir.join("pic.jpg"), jpeg).unwrap();
        std::fs::write(dir.join("misnamed.png"), jpeg).unwrap();

        for file in ["pic.jpg", "misnamed.png"] {
            let text = format!(
                r#"#usda 1.0

def Mesh "M" (
    prepend apiSchemas = ["MaterialBindingAPI"]
)
{{
    int[] faceVertexCounts = [3]
    int[] faceVertexIndices = [0, 1, 2]
    rel material:binding = </Mat>
    point3f[] points = [(0, 0, 0), (1, 0, 0), (0, 1, 0)]
}}

def Material "Mat"
{{
    token outputs:surface.connect = </Mat/S.outputs:surface>

    def Shader "S"
    {{
        uniform token info:id = "UsdPreviewSurface"
        color3f inputs:diffuseColor.connect = </Mat/T.outputs:rgb>
        token outputs:surface
    }}

    def Shader "T"
    {{
        uniform token info:id = "UsdUVTexture"
        asset inputs:file = @./{file}@
        float3 outputs:rgb
    }}
}}
"#
            );
            let mut scene = UsdLoader::parse(text.as_bytes()).expect("reads");
            let attached = attach_textures_from_dir(&mut scene, &dir);
            let pending = scene.textures.iter().flat_map(|(_, r)| r).count();
            if cfg!(feature = "jpeg") {
                assert_eq!((attached, pending), (1, 0), "{file}");
                let map = scene
                    .arena
                    .nodes
                    .iter()
                    .find_map(|(_, o)| match &o.kind {
                        crate::core::ObjectKind::Mesh(m) => match &*m.material {
                            crate::materials::Material::Standard(s) => s.map.clone(),
                            crate::materials::Material::Physical(p) => p.map.clone(),
                            _ => None,
                        },
                        _ => None,
                    })
                    .expect("a colour map on the mesh");
                assert_eq!((map.width, map.height), (16, 16), "{file}");
                assert_eq!(
                    map.format,
                    crate::textures::TextureFormat::Rgba8UnormSrgb,
                    "a colour map is sRGB"
                );
            } else {
                assert_eq!((attached, pending), (0, 1), "{file}");
            }
        }
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A `.usdz` can hold either form of layer, and carries images either way.
    #[test]
    fn a_package_holds_text_or_crate() {
        use super::super::{UsdExport, UsdzLayer};
        use crate::core::{Mesh, Object3D, ObjectArena};

        let material = StandardMaterial {
            map: Some(checker_texture()),
            ..StandardMaterial::new(Color::new(1.0, 1.0, 1.0))
        };
        let mut arena = ObjectArena::new();
        let id = arena.insert(Object3D::mesh(Mesh::new(triangle(), material.into())));
        let out = UsdExport::scene(&arena, &[id]);

        for (form, stem, magic) in [
            (UsdzLayer::Text, "scene.usda", &b"#usda"[..]),
            (UsdzLayer::Crate, "scene.usdc", &b"PXR-USDC"[..]),
        ] {
            let archive =
                super::super::usdz::read(&out.usdz_as(form, &[])).expect("a readable archive");
            let root = archive.entries.first().expect("a layer");
            assert_eq!(root.name, stem);
            assert!(root.data.starts_with(magic), "{stem} is the wrong form");
            assert!(
                archive
                    .entries
                    .iter()
                    .any(|e| e.name == "textures/Material_0_DiffuseTex.png"),
                "the image travelled with {stem}"
            );
        }
    }

    /// A bottom-up texture is turned over on the way out.
    ///
    /// `flip_y` is this crate's flag for "the top row is stored first", which
    /// is what an image file holds and what USD expects — Hydra puts a PNG's
    /// first row at `v = 1`. A `DataTexture` or a render target is authored
    /// bottom-up instead, and writing its rows verbatim into a PNG puts the
    /// picture upside down in every USD reader. Nothing in the format can
    /// carry the distinction, so the rows have to be right.
    #[test]
    fn a_bottom_up_texture_is_written_the_right_way_up() {
        use crate::textures::{Texture, TextureFormat};
        // Two rows, distinguishable: first row red, second blue.
        let pixels = vec![
            255, 0, 0, 255, 255, 0, 0, 255, 0, 0, 255, 255, 0, 0, 255, 255,
        ];
        let top_down = Texture::new(2, 2, TextureFormat::Rgba8UnormSrgb, pixels.clone());
        assert!(top_down.flip_y, "an image texture stores the top row first");

        let bottom_up = Texture {
            flip_y: false,
            ..Texture::new(2, 2, TextureFormat::Rgba8UnormSrgb, pixels)
        };

        let written = |texture: Texture| {
            let m = StandardMaterial {
                map: Some(std::sync::Arc::new(texture)),
                ..StandardMaterial::new(Color::new(1.0, 1.0, 1.0))
            };
            let (_, images) = material_prim_with_textures(&m.into(), "M", "/Root");
            crate::utils::png::decode_png(&images[0].data).unwrap().rgba
        };

        // Top-down goes out as it is: red first.
        assert_eq!(&written(top_down)[..4], &[255, 0, 0, 255]);
        // Bottom-up is reversed, so the row that was last is written first.
        assert_eq!(&written(bottom_up)[..4], &[0, 0, 255, 255]);
    }

    /// A `.usdz` comes back with its pictures, not with a list of them.
    ///
    /// The package format is required to be self-contained, so a reader that
    /// hands back "this material wants textures/foo.png" and stops is making
    /// the caller re-open an archive it already read. The pixels make the whole
    /// trip here: into RGBA, out as PNG, into the archive, and back.
    #[test]
    fn a_usdz_comes_back_with_its_textures_loaded() {
        use crate::core::{Mesh, Object3D, ObjectArena};
        use crate::textures::{TextureFormat, TextureWrap};

        let material = StandardMaterial {
            map: Some(checker_texture()),
            normal_map: Some(checker_texture()),
            ..StandardMaterial::new(Color::new(1.0, 1.0, 1.0))
        };
        let mut arena = ObjectArena::new();
        let mut object = Object3D::mesh(Mesh::new(triangle(), material.into()));
        object.name = "Quad".into();
        let id = arena.insert(object);

        let bytes = super::super::scene_to_usdz(&arena, &[id], &[]);
        let scene = super::super::UsdLoader::parse(&bytes).expect("reads back");

        let quad = scene
            .arena
            .get_objects_by_name(scene.roots[0], "Quad")
            .into_iter()
            .next()
            .expect("the quad");
        let ObjectKind::Mesh(mesh) = &scene.arena.get(quad).unwrap().kind else {
            panic!("not a mesh");
        };
        let Material::Standard(back) = &*mesh.material else {
            panic!("{:?}", mesh.material);
        };

        let map = back.map.as_ref().expect("the colour map came back");
        assert_eq!((map.width, map.height), (2, 2));
        // The exact pixels, not merely something of the right shape.
        assert_eq!(
            &map.data[..8],
            &[255, 0, 0, 255, 0, 255, 0, 255],
            "the pixels changed on the way"
        );
        // Wrap modes are authored per texture and have to survive too.
        assert_eq!(map.wrap_s, TextureWrap::Repeat);
        assert_eq!(map.wrap_t, TextureWrap::MirroredRepeat);
        assert_eq!(map.format, TextureFormat::Rgba8UnormSrgb);

        // A normal map is data, and reading it through an sRGB curve is the
        // classic way to get lighting that looks subtly wrong everywhere.
        let normal = back.normal_map.as_ref().expect("the normal map");
        assert_eq!(normal.format, TextureFormat::Rgba8Unorm);

        // And nothing is left for the caller to chase.
        assert!(
            scene.textures.iter().all(|(_, r)| r.is_empty()),
            "{:?}",
            scene.textures
        );
    }

    /// A `.usda` still reports what it cannot reach.
    ///
    /// The archive case is special because the bytes are in hand. A layer that
    /// names files beside itself has to keep asking, or a caller that *can*
    /// find them never learns they exist.
    #[test]
    fn a_usda_still_reports_the_textures_it_names() {
        use crate::core::{Mesh, Object3D, ObjectArena};
        use crate::loaders::usd::scene::to_scene;

        let material = StandardMaterial {
            map: Some(checker_texture()),
            ..StandardMaterial::new(Color::new(1.0, 1.0, 1.0))
        };
        let mut arena = ObjectArena::new();
        let id = arena.insert(Object3D::mesh(Mesh::new(triangle(), material.into())));
        let layer = parse(&scene_to_usda(&arena, &[id])).unwrap();
        let scene = to_scene(&layer);
        let asked: Vec<&str> = scene
            .textures
            .iter()
            .flat_map(|(_, r)| r.iter())
            .map(|r| r.file.as_str())
            .collect();
        assert_eq!(asked, ["textures/Material_0_DiffuseTex.png"]);
    }

    /// A physical material comes back physical, not flattened to standard.
    ///
    /// `ior` and `clearcoat` have no home on a standard material, so reading
    /// a file that authors them into one drops both. The importer builds a
    /// physical material when it sees either, which is the only way a physical
    /// material survives its own export.
    #[test]
    fn a_physical_material_survives_the_round_trip() {
        use crate::core::{Mesh, Object3D, ObjectArena};
        use crate::loaders::usd::scene::to_scene;
        use crate::materials::PhysicalMaterial;

        let source = PhysicalMaterial {
            color: Color::new(0.3, 0.7, 0.7),
            roughness: 0.1,
            ior: 1.45,
            clearcoat: 0.8,
            clearcoat_roughness: 0.05,
            side: 2,
            ..Default::default()
        };
        let mut arena = ObjectArena::new();
        let id = arena.insert(Object3D::mesh(Mesh::new(triangle(), source.into())));

        let layer = parse(&scene_to_usda(&arena, &[id])).unwrap();
        let scene = to_scene(&layer);
        let root = scene.arena.get(scene.roots[0]).unwrap();
        let mesh = scene.arena.get(root.children[0]).unwrap();
        let ObjectKind::Mesh(mesh) = &mesh.kind else {
            panic!("not a mesh");
        };
        let Material::Physical(back) = &*mesh.material else {
            panic!("came back as {:?}, not physical", mesh.material);
        };
        assert!((back.ior - 1.45).abs() < 1e-5, "{}", back.ior);
        assert!((back.clearcoat - 0.8).abs() < 1e-5);
        assert!((back.clearcoat_roughness - 0.05).abs() < 1e-5);
        assert!((back.roughness - 0.1).abs() < 1e-5);
        assert!((back.color.g - 0.7).abs() < 1e-5);
        assert_eq!(back.side, 2, "doubleSided did not come back");
    }

    /// A material with no physical inputs stays standard.
    ///
    /// The test above would pass just as well if every material came back
    /// physical, which would be its own kind of wrong.
    #[test]
    fn a_standard_material_stays_standard() {
        use crate::core::{Mesh, Object3D, ObjectArena};
        use crate::loaders::usd::scene::to_scene;

        let mut arena = ObjectArena::new();
        let id = arena.insert(Object3D::mesh(Mesh::new(
            triangle(),
            StandardMaterial::new(Color::new(0.2, 0.4, 0.6)).into(),
        )));
        let layer = parse(&scene_to_usda(&arena, &[id])).unwrap();
        let scene = to_scene(&layer);
        let root = scene.arena.get(scene.roots[0]).unwrap();
        let mesh = scene.arena.get(root.children[0]).unwrap();
        let ObjectKind::Mesh(mesh) = &mesh.kind else {
            panic!("not a mesh");
        };
        assert!(
            matches!(&*mesh.material, Material::Standard(_)),
            "{:?}",
            mesh.material
        );
    }

    /// Phong arrives as USD's specular workflow, exponent and all.
    ///
    /// Shininess is not roughness, and the two run opposite ways, so a fixed
    /// roughness would make every Phong material equally shiny. The default
    /// exponent of 30 is roughly a quarter rough; 200 is much smoother.
    #[test]
    fn phong_becomes_the_specular_workflow() {
        use crate::materials::PhongMaterial;
        let phong = PhongMaterial {
            color: Color::new(0.2, 0.3, 0.9),
            specular: Color::new(1.0, 1.0, 1.0),
            shininess: 30.0,
            ..Default::default()
        };

        let prim = material_prim(&phong.clone().into(), "M");
        let surface = &prim.children[0];
        assert_eq!(
            surface
                .value("inputs:useSpecularWorkflow")
                .unwrap()
                .flat_u32(),
            vec![1]
        );
        assert_eq!(
            surface.value("inputs:specularColor").unwrap().flat_f32(),
            vec![1.0, 1.0, 1.0]
        );
        // sqrt(2 / 32) = 0.25
        let rough = surface.value("inputs:roughness").unwrap().flat_f32()[0];
        assert!((rough - 0.25).abs() < 1e-6, "{rough}");

        let smoother = material_prim(
            &PhongMaterial {
                shininess: 200.0,
                ..phong.clone()
            }
            .into(),
            "M",
        )
        .children[0]
            .value("inputs:roughness")
            .unwrap()
            .flat_f32()[0];
        assert!(smoother < rough, "a higher exponent is a smoother surface");
    }

    /// A metallic workflow material says nothing about a specular one.
    #[test]
    fn only_phong_carries_the_specular_workflow() {
        let prim = material_prim(
            &StandardMaterial::new(Color::new(1.0, 1.0, 1.0)).into(),
            "M",
        );
        assert!(prim.children[0]
            .value("inputs:useSpecularWorkflow")
            .is_none());
    }

    #[test]
    fn a_material_survives_the_round_trip() {
        let mut arena = ObjectArena::new();
        let mut m = StandardMaterial::new(Color::new(0.2, 0.4, 0.6));
        m.roughness = 0.3;
        m.metalness = 0.8;
        let id = arena.insert(Object3D::mesh(Mesh::new(triangle(), m.into())));
        let layer = parse(&scene_to_usda(&arena, &[id])).unwrap();
        let scene = to_scene(&layer);
        let root = scene.arena.get(scene.roots[0]).unwrap();
        let mesh = scene.arena.get(root.children[0]).unwrap();
        match &mesh.kind {
            ObjectKind::Mesh(mesh) => match &*mesh.material {
                Material::Standard(s) => {
                    assert!((s.color.b - 0.6).abs() < 1e-6);
                    assert!((s.roughness - 0.3).abs() < 1e-6);
                    assert!((s.metalness - 0.8).abs() < 1e-6);
                }
                other => panic!("{other:?}"),
            },
            other => panic!("{other:?}"),
        }
    }

    #[test]
    fn unindexed_geometry_gets_an_index_written_for_it() {
        let mut g = BufferGeometry::new();
        g.set_attribute("position", BufferAttribute::new(vec![0.0; 18], 3));
        let layer = parse(&geometry_to_usda(&g, "M")).unwrap();
        let prim = layer.prim_at("/Root/M").unwrap();
        assert_eq!(
            prim.value("faceVertexCounts").unwrap().flat_u32(),
            vec![3, 3]
        );
        assert_eq!(
            prim.value("faceVertexIndices").unwrap().flat_u32(),
            vec![0, 1, 2, 3, 4, 5]
        );
    }

    /// Polygons survive a round trip, checked against OpenUSD both ways.
    ///
    /// `testdata/polygons.usdc` is `usdcat`'s binary form of
    /// `testdata/polygons.usda`: a quad, a triangle and a pentagon. Read here,
    /// it comes back as one polygon per face; written out again — text and
    /// crate — the faces are the authored ones, corner for corner. Where
    /// `usdcat` is installed it reads both of those files too, so the check
    /// is not just this crate's writer agreeing with its own reader.
    #[test]
    fn polygons_round_trip_against_usdcat() {
        const AUTHORED: &[u8] = include_bytes!("testdata/polygons.usdc");
        const COUNTS: [u32; 3] = [4, 3, 5];
        const INDICES: [u32; 12] = [0, 1, 2, 3, 1, 4, 2, 4, 5, 6, 7, 2];

        let layer = super::super::crate_read::read(AUTHORED).unwrap();
        let g = mesh_geometry(layer.prim_at("/Root/Faces").unwrap()).unwrap();
        assert_eq!(g.polygon_counts(), Some(&[2u32, 1, 3][..]));

        let text = geometry_to_usda(&g, "Faces");
        let crate_bytes = super::super::geometry_to_usdc(&g, "Faces");
        for layer in [
            parse(&text).unwrap(),
            super::super::crate_read::read(&crate_bytes).unwrap(),
        ] {
            let prim = layer.prim_at("/Root/Faces").unwrap();
            assert_eq!(prim.value("faceVertexCounts").unwrap().flat_u32(), COUNTS);
            assert_eq!(prim.value("faceVertexIndices").unwrap().flat_u32(), INDICES);
        }

        let usdcat = std::path::Path::new("/usr/bin/usdcat");
        if !usdcat.exists() {
            eprintln!("no usdcat; checked against this crate's reader only");
            return;
        }
        let dir = std::env::temp_dir().join(format!("threers-polygons-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let usda = dir.join("faces.usda");
        let usdc = dir.join("faces.usdc");
        std::fs::write(&usda, &text).unwrap();
        std::fs::write(&usdc, &crate_bytes).unwrap();
        for file in [&usda, &usdc] {
            let out = std::process::Command::new(usdcat)
                .arg(file)
                .output()
                .unwrap();
            assert!(
                out.status.success(),
                "{}",
                String::from_utf8_lossy(&out.stderr)
            );
            let flat = String::from_utf8_lossy(&out.stdout);
            assert!(
                flat.contains("int[] faceVertexCounts = [4, 3, 5]"),
                "{flat}"
            );
            assert!(
                flat.contains("int[] faceVertexIndices = [0, 1, 2, 3, 1, 4, 2, 4, 5, 6, 7, 2]"),
                "{flat}"
            );
        }
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A polygon whose triangles do not form one outline is written as its
    /// triangles, not as a guess.
    #[test]
    fn an_unrecoverable_polygon_is_written_as_triangles() {
        let mut g = BufferGeometry::new();
        let mut points = vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0];
        points.extend_from_slice(&[5.0, 0.0, 0.0, 6.0, 0.0, 0.0, 5.0, 1.0, 0.0]);
        g.set_attribute("position", BufferAttribute::new(points, 3));
        g.set_index(vec![0, 1, 2, 3, 4, 5]);
        g.set_polygons(vec![2]);
        assert_eq!(g.polygon_counts(), Some(&[2u32][..]));
        let layer = parse(&geometry_to_usda(&g, "M")).unwrap();
        let prim = layer.prim_at("/Root/M").unwrap();
        assert_eq!(
            prim.value("faceVertexCounts").unwrap().flat_u32(),
            vec![3, 3]
        );
    }
}

/// A scene graph with its animation, as a USD layer.
///
/// Every track becomes `timeSamples` on the transform op it drives, and the
/// layer gets the time metadata a player needs to know what the numbers mean.
/// Track times are seconds; USD counts in time codes, so they are multiplied
/// by the rate on the way out — which is the same conversion
/// [`to_scene`](super::scene::to_scene) undoes on the way in.
pub fn animated_scene_to_layer(
    arena: &ObjectArena,
    roots: &[ObjectId],
    clips: &[AnimationClip],
    options: &UsdExportOptions,
) -> UsdLayer {
    animated_scene_to_layer_with_textures(arena, roots, clips, options).0
}

/// A scene graph with its animation, and the image files its materials name.
pub fn animated_scene_to_layer_with_textures(
    arena: &ObjectArena,
    roots: &[ObjectId],
    clips: &[AnimationClip],
    options: &UsdExportOptions,
) -> (UsdLayer, Vec<ExportedTexture>) {
    let mut placed = Vec::new();
    let (mut layer, textures) = scene_to_layer_placed(arena, roots, options, &mut placed);
    let rate = options.time_codes_per_second.max(1.0) as f64;

    let mut last = 0.0f64;
    for clip in clips {
        for track in &clip.tracks {
            let Some((_, path)) = placed.iter().find(|(id, _)| *id == track.object) else {
                continue;
            };
            let Some(op) = sampled_track(track, rate) else {
                continue;
            };
            if let Some(time) = op.samples.last().map(|(t, _)| *t) {
                last = last.max(time);
            }
            let Some(prim) = prim_at_mut(&mut layer, path) else {
                continue;
            };
            set_op(
                prim,
                op.name,
                op.type_name,
                UsdValue::TimeSamples(op.samples),
            );
        }
        last = last.max((clip.duration as f64) * rate);
    }

    if last > 0.0 {
        layer
            .metadata
            .push(("timeCodesPerSecond".into(), UsdValue::Float(rate)));
        layer
            .metadata
            .push(("startTimeCode".into(), UsdValue::Float(0.0)));
        layer
            .metadata
            .push(("endTimeCode".into(), UsdValue::Float(last)));
    }
    (layer, textures)
}

/// A scene graph with its animation, as a `.usda` document.
pub fn animated_scene_to_usda(
    arena: &ObjectArena,
    roots: &[ObjectId],
    clips: &[AnimationClip],
) -> String {
    layer_to_usda(&animated_scene_to_layer(
        arena,
        roots,
        clips,
        &UsdExportOptions::default(),
    ))
}

/// A track expressed as the USD transform op it drives.
struct SampledOp {
    /// The op's attribute name, e.g. `xformOp:translate`.
    name: &'static str,
    /// The type USD expects that op to be authored as.
    type_name: &'static str,
    /// Times in time codes, not seconds.
    samples: Vec<(f64, UsdValue)>,
}

/// One track as the USD op it drives, with its times in time codes.
fn sampled_track(track: &KeyframeTrack, rate: f64) -> Option<SampledOp> {
    let time = |i: usize| track.times.get(i).map(|t| *t as f64 * rate).unwrap_or(0.0);
    match (&track.target, &track.values) {
        (TrackTarget::Position, TrackValues::Vector(values)) => Some(SampledOp {
            name: "xformOp:translate",
            type_name: "double3",
            samples: values
                .iter()
                .enumerate()
                .map(|(i, v)| (time(i), tuple3([v.x, v.y, v.z])))
                .collect(),
        }),
        (TrackTarget::Scale, TrackValues::Vector(values)) => Some(SampledOp {
            name: "xformOp:scale",
            type_name: "float3",
            samples: values
                .iter()
                .enumerate()
                .map(|(i, v)| (time(i), tuple3([v.x, v.y, v.z])))
                .collect(),
        }),
        (TrackTarget::Quaternion, TrackValues::Quaternion(values)) => Some(SampledOp {
            name: "xformOp:orient",
            type_name: "quatf",
            samples: values
                .iter()
                .enumerate()
                // USD writes the real part first.
                .map(|(i, q)| (time(i), tuple4([q.w, q.x, q.y, q.z])))
                .collect(),
        }),
        // Colour and morph tracks have no transform op to land on; a USD
        // layer can animate those, but not as part of the xform stack.
        _ => None,
    }
}

/// Replace an op's value, keeping `xformOpOrder` correct.
///
/// A prim exported from a static pose already carries the ops its transform
/// needed; animating one that was left out — a translate that happened to be
/// zero on the frame the scene was captured at — means adding it to the order
/// as well, or USD will ignore it.
fn set_op(prim: &mut UsdPrim, name: &str, type_name: &str, value: UsdValue) {
    match prim.properties.iter_mut().find(|p| p.name == name) {
        Some(existing) => existing.value = value,
        None => prim.properties.push(attribute(type_name, name, value)),
    }

    let ordered = prim
        .properties
        .iter()
        .any(|p| p.name == "xformOpOrder" && p.value.flat_tokens().contains(&name));
    if ordered {
        return;
    }
    match prim
        .properties
        .iter_mut()
        .find(|p| p.name == "xformOpOrder")
    {
        Some(order) => {
            if let UsdValue::Array(items) = &mut order.value {
                items.push(UsdValue::Token(name.into()));
            }
        }
        None => {
            let mut order = attribute(
                "token[]",
                "xformOpOrder",
                UsdValue::Array(vec![UsdValue::Token(name.into())]),
            );
            order.uniform = true;
            prim.properties.push(order);
        }
    }
}

fn prim_at_mut<'a>(layer: &'a mut UsdLayer, path: &str) -> Option<&'a mut UsdPrim> {
    let mut parts = path.trim_start_matches('/').split('/');
    let first = parts.next()?;
    let mut current = layer.prims.iter_mut().find(|p| p.name == first)?;
    for part in parts {
        current = current.children.iter_mut().find(|p| p.name == part)?;
    }
    Some(current)
}

#[cfg(test)]
mod external {
    use super::super::shade;
    use super::*;

    /// One mesh per material kind, in all three forms, for Apple's tools.
    ///
    /// The round-trip tests above run what this writes back through this
    /// crate's own reader, which proves the two agree and nothing more. This
    /// writes files for `usdchecker` to validate, `usdcat` to flatten, and
    /// `usdrecord` to try to shade.
    #[test]
    #[ignore = "writes files for external validation"]
    fn write_materials_for_openusd() {
        use crate::core::{BufferAttribute, BufferGeometry, Mesh, Object3D, ObjectArena};
        use crate::materials::{
            BasicMaterial, LambertMaterial, Material, PhongMaterial, PhysicalMaterial,
            StandardMaterial, ToonMaterial,
        };
        use crate::math::{Color, Vector3};

        fn quad() -> BufferGeometry {
            let mut g = BufferGeometry::new();
            g.set_attribute(
                "position",
                BufferAttribute::new(
                    vec![
                        -0.5, -0.5, 0.0, 0.5, -0.5, 0.0, 0.5, 0.5, 0.0, -0.5, 0.5, 0.0,
                    ],
                    3,
                ),
            );
            g.set_attribute("normal", BufferAttribute::new([0.0, 0.0, 1.0].repeat(4), 3));
            g.set_attribute(
                "uv",
                BufferAttribute::new(vec![0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0], 2),
            );
            g.set_index(vec![0, 1, 2, 0, 2, 3]);
            g
        }

        let dir = std::env::var("USD_OUT").unwrap_or_else(|_| "/tmp".into());

        let basic = BasicMaterial {
            opacity: 0.5,
            ..BasicMaterial::new(Color::new(0.9, 0.1, 0.1))
        };
        let lambert = LambertMaterial {
            color: Color::new(0.1, 0.8, 0.2),
            ..Default::default()
        };
        let phong = PhongMaterial {
            color: Color::new(0.2, 0.3, 0.9),
            specular: Color::new(1.0, 1.0, 1.0),
            ..Default::default()
        };
        let standard = StandardMaterial {
            roughness: 0.25,
            metalness: 0.9,
            emissive: Color::new(0.05, 0.0, 0.1),
            ..StandardMaterial::new(Color::new(0.8, 0.6, 0.1))
        };
        let physical = PhysicalMaterial {
            color: Color::new(0.3, 0.7, 0.7),
            roughness: 0.1,
            ior: 1.45,
            clearcoat: 0.8,
            clearcoat_roughness: 0.05,
            ..Default::default()
        };
        let toon = ToonMaterial {
            color: Color::new(0.7, 0.2, 0.7),
            side: 2,
            ..Default::default()
        };

        // A checkerboard and a flat normal map, so a render shows whether the
        // texture is sampled at all and whether the UVs are the right way up.
        use crate::textures::{Texture, TextureFormat, TextureWrap};
        use std::sync::Arc;
        let mut checker = Vec::new();
        for y in 0..64u32 {
            for x in 0..64u32 {
                let on = ((x / 8) + (y / 8)) % 2 == 0;
                let (r, g, b) = if on { (240, 240, 40) } else { (30, 30, 120) };
                checker.extend_from_slice(&[r, g, b, 255]);
            }
        }
        let map = Texture {
            wrap_s: TextureWrap::Repeat,
            wrap_t: TextureWrap::Repeat,
            ..Texture::new(64, 64, TextureFormat::Rgba8UnormSrgb, checker)
        };
        let normal = Texture::new(
            2,
            2,
            TextureFormat::Rgba8Unorm,
            [128, 128, 255, 255].repeat(4),
        );
        let textured = StandardMaterial {
            roughness: 0.9,
            map: Some(Arc::new(map)),
            normal_map: Some(Arc::new(normal)),
            ..StandardMaterial::new(Color::new(1.0, 1.0, 1.0))
        };

        let kinds: Vec<(&str, Material)> = vec![
            ("Basic", basic.into()),
            ("Lambert", lambert.into()),
            ("Phong", phong.into()),
            ("Standard", standard.into()),
            ("Physical", physical.into()),
            ("Toon", toon.into()),
            ("Textured", textured.into()),
        ];
        let mut arena = ObjectArena::new();
        let mut roots = Vec::new();
        for (i, (name, material)) in kinds.into_iter().enumerate() {
            let mut object = Object3D::mesh(Mesh::new(quad(), material));
            object.name = name.into();
            object.position = Vector3::new(i as f32 * 1.2 - 3.0, 0.0, 0.0);
            roots.push(arena.insert(object));
        }

        // One export, three forms — and `write_to` puts the images beside the
        // two that refer to them rather than carrying them.
        let out = super::super::UsdExport::scene(&arena, &roots);
        let base = std::path::Path::new(&dir);
        for name in ["materials.usda", "materials.usdc", "materials.usdz"] {
            out.write_to(base.join(name), base).expect("writes");
        }
        println!(
            "wrote materials.usda / .usdc / .usdz and {} texture(s) to {dir}",
            out.textures.len()
        );
    }

    /// Read a file back and check the materials survived whatever wrote it.
    ///
    /// Pointed at `usdcat`'s output for the gallery, this closes the loop
    /// through OpenUSD rather than through this crate's own reader: export,
    /// hand to Apple's tools, read back what they produced. A writer and a
    /// reader that only ever talk to each other agree on their own mistakes.
    #[test]
    #[ignore = "reads a file produced by OpenUSD"]
    fn read_materials_back_from_openusd() {
        use crate::loaders::usd::scene::to_scene;

        let path = std::env::var("USD_IN").expect("USD_IN=<a flattened gallery>");
        let text = std::fs::read_to_string(&path).expect("readable");
        let layer = super::super::parse::parse(&text).expect("parses");
        let scene = to_scene(&layer);

        let named = |want: &str| {
            let found = scene
                .arena
                .get_objects_by_name(scene.roots[0], want)
                .into_iter()
                .next()
                .unwrap_or_else(|| panic!("no object named {want}"));
            scene.arena.get(found).unwrap().clone()
        };
        let material_of = |object: &crate::core::Object3D| match &object.kind {
            ObjectKind::Mesh(mesh) => (*mesh.material).clone(),
            other => panic!("{other:?} is not a mesh"),
        };

        match material_of(&named("Physical")) {
            Material::Physical(p) => {
                assert!((p.ior - 1.45).abs() < 1e-4, "ior came back {}", p.ior);
                assert!((p.clearcoat - 0.8).abs() < 1e-4);
                assert!((p.clearcoat_roughness - 0.05).abs() < 1e-4);
                assert!((p.color.g - 0.7).abs() < 1e-4);
            }
            other => panic!("Physical came back as {other:?}"),
        }
        assert_eq!(material_of(&named("Toon")).side(), 2, "doubleSided lost");
        assert!(
            (material_of(&named("Lambert")).color().g - 0.8).abs() < 1e-4,
            "Lambert lost its colour"
        );

        // The textured one keeps its maps, as requests for the caller to load.
        let textured = shade::bound_material_path(&layer, "/Root/Textured")
            .and_then(|p| layer.prim_at(&p))
            .map(|p| shade::resolve(p, &layer))
            .expect("a bound material");
        let slots: Vec<_> = textured.textures.iter().map(|t| t.slot).collect();
        assert!(
            slots.contains(&shade::TextureSlot::BaseColor)
                && slots.contains(&shade::TextureSlot::Normal),
            "{slots:?}"
        );
        let normal = textured
            .textures
            .iter()
            .find(|t| t.slot == shade::TextureSlot::Normal)
            .unwrap();
        assert_eq!(normal.scale, [2.0, 2.0, 2.0, 1.0]);
        assert_eq!(normal.bias, [-1.0, -1.0, -1.0, 0.0]);
        assert_eq!(normal.color_space, "raw");
        println!("materials survived the trip through OpenUSD");
    }

    /// Write archives for Apple's `usdchecker --arkit` to judge.
    #[test]
    #[ignore = "writes files for external validation"]
    fn write_archives_for_arkit() {
        use super::super::{scene_to_usdz, UsdzEntry};
        use crate::core::{Mesh, Object3D, ObjectArena};
        use crate::geometries::{BoxGeometry, SphereGeometry};
        use crate::materials::{Material, StandardMaterial};

        let dir = std::env::var("USD_OUT").unwrap_or_else(|_| "/tmp".into());
        let mut arena = ObjectArena::new();
        let mut roots = Vec::new();
        for (i, geometry) in [
            BoxGeometry::new(1.0, 2.0, 3.0),
            SphereGeometry::new(1.0, 24, 12),
        ]
        .into_iter()
        .enumerate()
        {
            let mut object = Object3D::mesh(Mesh::new(
                geometry,
                Material::Standard(StandardMaterial::default()),
            ));
            object.name = format!("Part{i}");
            roots.push(arena.insert(object));
        }

        // A texture beside the layer, which is what a real archive carries.
        let png = include_bytes!("testdata/tiny.png").to_vec();
        let archive = scene_to_usdz(
            &arena,
            &roots,
            &[UsdzEntry {
                name: "textures/albedo.png".into(),
                data: png,
            }],
        );
        let path = format!("{dir}/arkit_scene.usdz");
        std::fs::write(&path, &archive).unwrap();
        println!("wrote {path} ({} bytes)", archive.len());
    }

    /// Write an animated document to disk so that OpenUSD's own tools can be
    /// pointed at it. Ignored by default: it needs a path, and the assertion
    /// that matters is made by `usdcat`, not by this process.
    #[test]
    #[ignore = "writes a file for external validation"]
    fn write_an_animated_document() {
        use crate::animation::{AnimationClip, KeyframeTrack, TrackTarget};
        use crate::core::Object3D;
        use crate::geometries::BoxGeometry;
        use crate::math::{Quaternion, Vector3};

        let mut arena = ObjectArena::new();
        let mut object = Object3D::mesh(crate::core::Mesh::new(
            BoxGeometry::new(1.0, 1.0, 1.0),
            crate::materials::Material::Standard(Default::default()),
        ));
        object.name = "Cube".into();
        let id = arena.insert(object);

        let clip = AnimationClip::new(
            "spin",
            2.0,
            vec![
                KeyframeTrack::vector(
                    id,
                    TrackTarget::Position,
                    vec![0.0, 1.0, 2.0],
                    vec![
                        Vector3::new(0.0, 0.0, 0.0),
                        Vector3::new(3.0, 2.0, 0.0),
                        Vector3::new(6.0, 0.0, 0.0),
                    ],
                ),
                KeyframeTrack::quaternion(
                    id,
                    TrackTarget::Quaternion,
                    vec![0.0, 2.0],
                    vec![
                        Quaternion::identity(),
                        Quaternion::from_axis_angle(
                            Vector3::new(0.0, 1.0, 0.0),
                            std::f32::consts::PI,
                        ),
                    ],
                ),
                KeyframeTrack::vector(
                    id,
                    TrackTarget::Scale,
                    vec![0.0, 1.0, 2.0],
                    vec![
                        Vector3::new(1.0, 1.0, 1.0),
                        Vector3::new(2.0, 2.0, 2.0),
                        Vector3::new(1.0, 1.0, 1.0),
                    ],
                ),
            ],
        );

        let text = animated_scene_to_usda(&arena, &[id], &[clip]);
        let path = std::env::var("USD_OUT").unwrap_or_else(|_| "/tmp/threers_anim.usda".into());
        std::fs::write(&path, text).unwrap();
        println!("wrote {path}");
    }
}