animsmith-core 0.5.0

Engine-agnostic data model, sampling, measurements, and checks for the animsmith animation-clip linter
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
//! The loader-facing layer: clips, tracks, and the skeleton before metric
//! resampling or repair. The glTF loader preserves authored animation
//! values; the FBX loader normalizes scene coordinates and bakes takes to
//! linear TRS tracks. Mechanical checks (NaN, quaternion flips, key
//! density, …) read this layer; semantic checks read the sampled layer
//! built from it (see [`crate::sample`]).

use glam::{Mat3, Mat4, Quat, Vec3};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};

/// Stable machine-readable reason a positive-uniform affine linear part failed
/// classification.
///
/// Core consumers map these typed facts into their own domain-specific
/// diagnostics rather than sharing a broad operation error enum.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AffineDomainViolation {
    /// The linear part's axis lengths are not equal (non-uniform scale).
    NonUniformScale,
    /// The linear part's axes are not mutually orthogonal (shear).
    Sheared,
    /// The linear part has a negative determinant (reflection).
    Reflected,
    /// The linear part is singular or near-singular.
    Singular,
    /// The linear part contains a non-finite component.
    NonFinite,
}

/// Tolerances supplied by one caller of
/// [`classify_positive_uniform_affine`].
///
/// The classifier deliberately owns no global policy: Appendix D scale
/// planning uses its versioned `f64` policy, while skinned bind-pose
/// canonicalization retains its established `1e-4` acceptance band.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct PositiveUniformAffineTolerance {
    pub(crate) equal_axis: f64,
    pub(crate) relative_orthogonality: f64,
    pub(crate) singular_determinant_relative: f64,
}

/// Policy-neutral geometric facts for one affine linear part.
///
/// Every derived operation widens the source `f32` columns to `f64` first.
/// Callers deliberately apply their own tolerance and precedence policies to
/// this one fact record: strict positive-uniform operations reject a domain
/// violation, while measurement retains finite descriptive evidence.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct AffineGeometryFacts {
    pub(crate) axis_lengths: [f64; 3],
    pub(crate) mean_axis_length: f64,
    pub(crate) determinant: f64,
    pub(crate) axis_length_product: f64,
    /// Widened dot products in XY, XZ, YZ order.
    pub(crate) cross_axis_dots: [f64; 3],
}

impl AffineGeometryFacts {
    /// Derive the complete finite fact record, or reject it atomically.
    ///
    /// The scalar triple product's operation order is part of the established
    /// Appendix D classifier behavior and must not be replaced with an f32
    /// determinant or a differently associated f64 expansion.
    pub(crate) fn from_linear(linear: Mat3) -> Result<Self, AffineDomainViolation> {
        if !linear.is_finite() {
            return Err(AffineDomainViolation::NonFinite);
        }
        let columns = [
            linear.x_axis.as_dvec3(),
            linear.y_axis.as_dvec3(),
            linear.z_axis.as_dvec3(),
        ];
        let axis_lengths = affine_axis_lengths(linear);
        let mean_axis_length = average_affine_axis_length(axis_lengths);
        let determinant = columns[2].dot(columns[0].cross(columns[1]));
        let axis_length_product = axis_lengths[0] * axis_lengths[1] * axis_lengths[2];
        let cross_axis_dots = [
            columns[0].dot(columns[1]),
            columns[0].dot(columns[2]),
            columns[1].dot(columns[2]),
        ];
        if axis_lengths.iter().any(|value| !value.is_finite())
            || !mean_axis_length.is_finite()
            || !determinant.is_finite()
            || !axis_length_product.is_finite()
            || cross_axis_dots.iter().any(|value| !value.is_finite())
        {
            return Err(AffineDomainViolation::NonFinite);
        }
        Ok(Self {
            axis_lengths,
            mean_axis_length,
            determinant,
            axis_length_product,
            cross_axis_dots,
        })
    }

    /// Whether every axis lies within a symmetric mean-relative band.
    ///
    /// Comparing every value to the mean removes the privileged-X behavior
    /// of pairwise-from-X tests. The longer-operand base keeps the predicate
    /// symmetric around the mean, and `<=` makes the boundary inclusive.
    pub(crate) fn has_equal_axis_lengths(self, relative_tolerance: f64) -> bool {
        values_equal_to_mean(
            &self.axis_lengths,
            self.mean_axis_length,
            relative_tolerance,
        )
    }
}

/// Whether every finite value lies within a symmetric relative band around
/// `mean`, using the longer operand as the relative base.
pub(crate) fn values_equal_to_mean(values: &[f64], mean: f64, relative_tolerance: f64) -> bool {
    values
        .iter()
        .all(|&value| (value - mean).abs() <= relative_tolerance * mean.abs().max(value.abs()))
}

/// Classify an affine linear part as an orientation-preserving positive
/// uniform scale and return its common factor.
///
/// Inputs widen to `f64` before every derived calculation. This preserves the
/// Appendix D scale classifier's boundary behaviour; callers choose the
/// tolerance policy appropriate to their separate contract.
pub(crate) fn classify_positive_uniform_affine(
    linear: Mat3,
    tolerance: PositiveUniformAffineTolerance,
) -> Result<f64, AffineDomainViolation> {
    let facts = AffineGeometryFacts::from_linear(linear)?;
    if facts.mean_axis_length <= 0.0 {
        return Err(AffineDomainViolation::Singular);
    }

    // Check singularity before the shape facts. A degenerate basis that is
    // also non-uniform or sheared is still singular, which keeps the
    // independently named rejection classes deterministic.
    // Expand the scalar triple product from the widened columns. Calling
    // `Mat3::determinant` here would perform the derived arithmetic in f32
    // before widening and moves the singular boundary.
    if facts.determinant.abs()
        <= tolerance.singular_determinant_relative * facts.axis_length_product
    {
        return Err(AffineDomainViolation::Singular);
    }
    // This is a relative band with no unit floor: a floor would become an
    // absolute tolerance for sub-unit transforms. The longer-operand base
    // keeps the comparison symmetric, and `>` makes the boundary inclusive.
    if !facts.has_equal_axis_lengths(tolerance.equal_axis) {
        return Err(AffineDomainViolation::NonUniformScale);
    }

    // Scale the dot-product band by the square of the common factor. As with
    // the axis band, equality is accepted and only a value beyond it rejects.
    let orthogonality_tolerance =
        tolerance.relative_orthogonality * facts.mean_axis_length * facts.mean_axis_length;
    if facts
        .cross_axis_dots
        .iter()
        .any(|dot| dot.abs() > orthogonality_tolerance)
    {
        return Err(AffineDomainViolation::Sheared);
    }
    if facts.determinant < 0.0 {
        return Err(AffineDomainViolation::Reflected);
    }
    Ok(facts.mean_axis_length)
}

/// The three column lengths of a linear part, widened to `f64` first.
///
/// The positive-uniform classifier and the scale proof's observed-factor
/// witness both use this helper so that their factor is one shared quantity.
pub(crate) fn affine_axis_lengths(linear: Mat3) -> [f64; 3] {
    [
        linear.x_axis.as_dvec3().length(),
        linear.y_axis.as_dvec3().length(),
        linear.z_axis.as_dvec3().length(),
    ]
}

/// The arithmetic-mean common factor represented by three affine axis
/// lengths.
///
/// The finite widened inputs are summed in ascending order so this shared
/// factor does not depend on an affine matrix's authored column order.
pub(crate) fn average_affine_axis_length(lengths: [f64; 3]) -> f64 {
    let mut ascending = lengths;
    ascending.sort_by(f64::total_cmp);
    (ascending[0] + ascending[1] + ascending[2]) / 3.0
}

#[cfg(test)]
pub(crate) mod affine_test_fixtures {
    use super::{Mat3, Vec3};

    /// A finite diagonal basis intentionally between the two callers' equal
    /// axis bands: Appendix D rejects it, while skinned canonicalization's
    /// established `1e-4` policy accepts it.
    pub(crate) fn tolerance_divergence_basis() -> Mat3 {
        Mat3::from_diagonal(Vec3::new(1.0, 1.000_05, 1.0))
    }

    /// A nearly orthogonal basis whose only non-zero cross-axis dot product
    /// lies between the two callers' orthogonality bands.
    pub(crate) fn orthogonality_tolerance_divergence_basis() -> Mat3 {
        Mat3::from_cols(Vec3::X, Vec3::new(5.0e-5, 1.0, 0.0), Vec3::Z)
    }

    /// All signed column orders of the exact Appendix D v6 mean fixture.
    ///
    /// Odd permutations negate their first column, preserving orientation
    /// without changing any axis length.
    pub(crate) fn appendix_d_v6_mean_permutations() -> [Mat3; 6] {
        let columns = [
            Vec3::new(
                f32::from_bits(0x3f0e_8cbb),
                f32::from_bits(0x3f26_fbbe),
                f32::from_bits(0x3f21_9bc7),
            ),
            Vec3::new(
                f32::from_bits(0x3d9c_b415),
                f32::from_bits(0x3e92_d82b),
                f32::from_bits(0x3f82_e85d),
            ),
            Vec3::new(
                f32::from_bits(0x3f14_5226),
                f32::from_bits(0x3e9e_e50d),
                f32::from_bits(0x3f56_817c),
            ),
        ];
        [
            Mat3::from_cols(columns[0], columns[1], columns[2]),
            Mat3::from_cols(-columns[0], columns[2], columns[1]),
            Mat3::from_cols(-columns[1], columns[0], columns[2]),
            Mat3::from_cols(columns[1], columns[2], columns[0]),
            Mat3::from_cols(columns[2], columns[0], columns[1]),
            Mat3::from_cols(-columns[2], columns[1], columns[0]),
        ]
    }
}

/// Index into [`Skeleton::bones`].
pub type BoneId = usize;

/// Node-local TRS transform.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Transform {
    /// Translation in scene units.
    pub translation: Vec3,
    /// Orientation relative to the parent node.
    pub rotation: Quat,
    /// Non-uniform local scale.
    pub scale: Vec3,
}

impl Transform {
    /// The identity transform: zero translation, identity rotation, and
    /// unit scale.
    pub const IDENTITY: Self = Self {
        translation: Vec3::ZERO,
        rotation: Quat::IDENTITY,
        scale: Vec3::ONE,
    };

    /// Convert this TRS transform to a matrix using glam's
    /// scale-rotation-translation order.
    pub fn to_mat4(&self) -> Mat4 {
        Mat4::from_scale_rotation_translation(self.scale, self.rotation, self.translation)
    }
}

impl Default for Transform {
    fn default() -> Self {
        Self::IDENTITY
    }
}

/// One skeleton node/bone in parent-before-child order.
#[derive(Debug, Clone)]
pub struct Bone {
    /// Bone/node name as authored or normalized by the loader.
    pub name: String,
    /// Parent bone index; `None` means this is a root bone.
    pub parent: Option<BoneId>,
    /// Rest pose, node-local. Whether this or the inverse-bind-derived
    /// rest is authoritative is a `bind-pose` check concern.
    pub rest: Transform,
    /// Inverse bind matrix from a skin, when one references this bone.
    pub inverse_bind: Option<Mat4>,
}

/// Bones in topological order: a bone's parent always precedes it.
/// Loaders are responsible for establishing this invariant.
#[derive(Debug, Clone, Default)]
pub struct Skeleton {
    /// Bones in topological order.
    pub bones: Vec<Bone>,
}

impl Skeleton {
    /// Name of the bone at `id`.
    ///
    /// # Panics
    ///
    /// Panics if `id` is not a valid index into [`Skeleton::bones`].
    pub fn bone_name(&self, id: BoneId) -> &str {
        &self.bones[id].name
    }
}

/// Structural failure composing [`Skeleton`] rest-local transforms into
/// world matrices, returned by [`world_rest_matrices`].
///
/// This is deliberately generic over the eventual caller-facing error: every
/// caller of [`world_rest_matrices`] maps one of these two structural facts
/// into its own typed error variant rather than sharing an error enum across
/// module boundaries.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum WorldMatrixError {
    /// The node's local or accumulated world transform has a non-finite
    /// component.
    NonFiniteTransform {
        /// The node with the non-finite transform.
        node: BoneId,
    },
    /// The node's parent is not earlier in [`Skeleton::bones`], so the
    /// skeleton is not in the required parent-before-child order.
    InvalidParent {
        /// The node with an invalid parent.
        node: BoneId,
        /// The invalid parent index.
        parent: BoneId,
    },
}

/// Compose every [`Bone::rest`] local transform in `skeleton` into a
/// parent-before-child world matrix, shared by every module that needs plain
/// rest-world FK (skin bind-pose canonicalization, static mesh baking, and
/// scale planning/proof).
///
/// `skeleton.bones` order is trusted as parent-before-child, matching
/// [`Skeleton`]'s documented invariant; a parent index that is not strictly
/// less than its child's is reported as [`WorldMatrixError::InvalidParent`]
/// rather than assumed.
pub(crate) fn world_rest_matrices(skeleton: &Skeleton) -> Result<Vec<Mat4>, WorldMatrixError> {
    let mut worlds = Vec::with_capacity(skeleton.bones.len());
    for (node, bone) in skeleton.bones.iter().enumerate() {
        let local = bone.rest.to_mat4();
        if !mat4_is_finite(local) {
            return Err(WorldMatrixError::NonFiniteTransform { node });
        }
        let world = match bone.parent {
            Some(parent) if parent < node => worlds[parent] * local,
            Some(parent) => return Err(WorldMatrixError::InvalidParent { node, parent }),
            None => local,
        };
        if !mat4_is_finite(world) {
            return Err(WorldMatrixError::NonFiniteTransform { node });
        }
        worlds.push(world);
    }
    Ok(worlds)
}

/// Compose rest-world matrices for a partial-evidence consumer.
///
/// Unlike [`world_rest_matrices`], this deliberately preserves a slot for
/// every bone and makes only the malformed chain unavailable. Measurement
/// uses that behaviour to retain finite evidence from unrelated roots.
pub(crate) fn tolerant_world_rest_matrices(skeleton: &Skeleton) -> Vec<Option<Mat4>> {
    let mut worlds = Vec::with_capacity(skeleton.bones.len());
    for bone in &skeleton.bones {
        let local = bone.rest.to_mat4();
        let world = match bone.parent {
            Some(parent) => worlds
                .get(parent)
                .copied()
                .flatten()
                .map(|parent_world| parent_world * local),
            None => Some(local),
        }
        .filter(|matrix| mat4_is_finite(*matrix));
        worlds.push(world);
    }
    worlds
}

pub(crate) fn mat4_is_finite(matrix: Mat4) -> bool {
    matrix.to_cols_array().into_iter().all(f32::is_finite)
}

/// Animated property targeted by a [`Track`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Property {
    /// Local translation channel.
    Translation,
    /// Local rotation channel.
    Rotation,
    /// Local scale channel.
    Scale,
}

impl Property {
    /// Stable snake-case name used in diagnostics and serialized
    /// metadata.
    pub fn as_str(self) -> &'static str {
        match self {
            Property::Translation => "translation",
            Property::Rotation => "rotation",
            Property::Scale => "scale",
        }
    }
}

/// Interpolation mode for a [`Track`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Interpolation {
    /// Linear interpolation between key values.
    Linear,
    /// Hold the previous key until the next key.
    Step,
    /// glTF cubic spline: `values` holds `[in-tangent, value, out-tangent]`
    /// triplets per keyframe. Use [`Track::value_index`] to address the
    /// value elements.
    CubicSpline,
}

/// Storage for a track's key values.
#[derive(Debug, Clone)]
pub enum TrackValues {
    /// Translation or scale values.
    Vec3s(Vec<Vec3>),
    /// Rotation values.
    Quats(Vec<Quat>),
}

impl TrackValues {
    /// Number of stored values, including tangents for cubic-spline
    /// tracks.
    pub fn len(&self) -> usize {
        match self {
            TrackValues::Vec3s(v) => v.len(),
            TrackValues::Quats(v) => v.len(),
        }
    }

    /// Whether there are no stored values.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// One animated property of one bone.
#[derive(Debug, Clone)]
pub struct Track {
    /// Bone index targeted by this track.
    pub bone: BoneId,
    /// Property animated on the target bone.
    pub property: Property,
    /// Interpolation mode used between keys.
    pub interpolation: Interpolation,
    /// Keyframe times in seconds. Same length as the keyframe count
    /// (tangent elements in cubic tracks do not add times).
    pub times: Vec<f32>,
    /// Key values, with cubic-spline tracks storing tangent triplets.
    pub values: TrackValues,
}

impl Track {
    /// Number of keyframes.
    pub fn key_count(&self) -> usize {
        self.times.len()
    }

    /// Index into `values` of keyframe `k`'s value element (skips
    /// tangents for cubic tracks).
    pub fn value_index(&self, k: usize) -> usize {
        match self.interpolation {
            Interpolation::CubicSpline => 3 * k + 1,
            _ => k,
        }
    }

    /// Keyframe `k`'s value, for Vec3 tracks.
    pub fn key_vec3(&self, k: usize) -> Option<Vec3> {
        match &self.values {
            TrackValues::Vec3s(v) => v.get(self.value_index(k)).copied(),
            TrackValues::Quats(_) => None,
        }
    }

    /// Keyframe `k`'s value, for rotation tracks.
    pub fn key_quat(&self, k: usize) -> Option<Quat> {
        match &self.values {
            TrackValues::Quats(v) => v.get(self.value_index(k)).copied(),
            TrackValues::Vec3s(_) => None,
        }
    }

    /// First key time, or `0.0` for an empty track.
    pub fn start_time(&self) -> f32 {
        self.times.first().copied().unwrap_or(0.0)
    }

    /// Last key time, or `0.0` for an empty track.
    pub fn end_time(&self) -> f32 {
        self.times.last().copied().unwrap_or(0.0)
    }
}

/// One animation clip targeting the document skeleton.
#[derive(Debug, Clone)]
pub struct Clip {
    /// Clip name, used as the key in measurement maps and config
    /// expectations.
    pub name: String,
    /// Clip length in seconds (max sampler end time across tracks).
    pub duration_s: f64,
    /// Animated tracks belonging to this clip.
    pub tracks: Vec<Track>,
}

/// Loader-provided provenance for a [`Document`].
#[derive(Debug, Clone, Default)]
pub struct SourceInfo {
    /// Source path, when the loader was given one.
    pub path: Option<String>,
    /// Source format label such as `"glb"` or `"fbx"`.
    pub format: Option<String>,
}

/// A loaded file: one skeleton, any number of clips targeting it, and
/// the scene assets (meshes, materials, and textures) that rode in alongside
/// them.
/// `assets` is default-empty: the check catalog judges animation and
/// ignores it, but the load/write round-trip carries it so `transform`
/// and `convert` preserve geometry instead of silently dropping it.
#[derive(Debug, Clone, Default)]
pub struct Document {
    /// Skeleton shared by every clip.
    pub skeleton: Skeleton,
    /// Animation clips targeting [`Document::skeleton`].
    pub clips: Vec<Clip>,
    /// Meshes, materials, and textures carried by the loaded scene.
    pub assets: SceneAssets,
    /// Optional source provenance.
    pub source: SourceInfo,
}

/// A structural invariant violated by [`validate_document_shape`].
///
/// Validation is a snapshot, not a durable guarantee: [`Document`] and its
/// nested fields are publicly mutable. Strict operations that rely on this
/// full shape must validate again at each public boundary.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum DocumentShapeError {
    /// A bone's local rest transform or its composed rest-world transform is
    /// non-finite.
    #[error("node {node} has a non-finite rest transform")]
    NonFiniteSkeletonRest {
        /// The affected skeleton node.
        node: BoneId,
    },
    /// A bone's parent does not precede it in parent-before-child order.
    #[error("node {node} has invalid parent {parent}")]
    InvalidSkeletonParent {
        /// The affected skeleton node.
        node: BoneId,
        /// The invalid parent index.
        parent: BoneId,
    },
    /// The source-node projection declares one source node identity twice.
    #[error("source skeleton declares duplicate source node index {source_node_index}")]
    DuplicateSourceNodeIndex {
        /// The duplicated source-node index.
        source_node_index: usize,
    },
    /// The source-skin projection declares one source skin identity twice.
    #[error("source skeleton declares duplicate source skin index {source_skin_index}")]
    DuplicateSourceSkinIndex {
        /// The duplicated source-skin index.
        source_skin_index: usize,
    },
    /// A complete source-node projection contradicts the normalized skeleton.
    #[error(
        "source node {source_node_index} contradicts the document skeleton's parent chain ({violation})"
    )]
    SourceProjection {
        /// The source node whose projection failed.
        source_node_index: usize,
        /// The typed projection failure.
        violation: SourceProjectionViolation,
    },
    /// A clip declares the same target `(node, property)` more than once.
    #[error("clip {clip_index} declares duplicate {property:?} tracks for node {node}")]
    DuplicateClipTrack {
        /// Index into [`Document::clips`].
        clip_index: usize,
        /// The duplicated target node.
        node: BoneId,
        /// The duplicated animated property.
        property: Property,
    },
    /// A track is malformed for its target, interpolation, or value storage.
    #[error("clip {clip_index} track for node {node} has an invalid shape ({violation})")]
    TrackShape {
        /// Index into [`Document::clips`].
        clip_index: usize,
        /// The track's target node.
        node: BoneId,
        /// The typed track-shape failure.
        violation: TrackShapeViolation,
    },
    /// A mesh instance has an invalid reference or inverse-bind payload.
    #[error("mesh instance {instance_index} is invalid ({violation})")]
    MeshInstanceShape {
        /// Index into [`SceneAssets::instances`].
        instance_index: usize,
        /// The typed mesh-instance failure.
        violation: MeshInstanceShapeViolation,
    },
    /// A bone-level inverse-bind matrix is non-finite.
    #[error("node {node} has a non-finite inverse-bind matrix")]
    NonFiniteBoneInverseBind {
        /// The affected skeleton node.
        node: BoneId,
    },
}

/// The way a complete source-node projection contradicts the skeleton.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum SourceProjectionViolation {
    /// A projected bone index is outside [`Skeleton::bones`].
    #[error("projected_bone_out_of_range")]
    ProjectedBoneOutOfRange,
    /// Two source-node rows project to the same normalized bone.
    #[error("two_source_nodes_project_to_one_bone")]
    TwoSourceNodesProjectToOneBone,
    /// An ancestor walk names a source node absent from the projection table.
    #[error("parent_source_node_is_missing")]
    ParentSourceNodeMissing,
    /// An ancestor walk through unprojected rows does not terminate.
    #[error("cyclic_unprojected_source_parent_chain")]
    CyclicUnprojectedSourceParentChain,
    /// The nearest projected source ancestor differs from the bone parent.
    #[error("projection_and_skeleton_parents_differ")]
    NearestProjectedParentMismatch,
    /// A projected bone has an unprojected direct skeleton child.
    #[error("projected_bone_has_an_unprojected_skeleton_child")]
    ProjectedBoneHasUnprojectedSkeletonChild,
}

/// The way a clip track is malformed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum TrackShapeViolation {
    /// The target bone index is outside [`Skeleton::bones`].
    #[error("bone_index_out_of_range")]
    BoneIndexOutOfRange,
    /// The track has no keyframe times.
    #[error("empty_times")]
    EmptyTimes,
    /// At least one keyframe time is not finite.
    #[error("non_finite_time")]
    NonFiniteTime,
    /// Keyframe times are not strictly increasing.
    #[error("times_not_strictly_increasing")]
    TimesNotStrictlyIncreasing,
    /// Stored value count disagrees with the interpolation's key count.
    #[error("value_count_mismatch")]
    ValueCountMismatch,
    /// The value storage does not match the targeted property.
    #[error("value_type_mismatches_property")]
    ValueTypeMismatchesProperty,
    /// At least one stored value is not finite.
    #[error("non_finite_value")]
    NonFiniteValue,
}

/// The way a mesh instance is malformed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum MeshInstanceShapeViolation {
    /// The instance node index is outside [`Skeleton::bones`].
    #[error("node_index_out_of_range")]
    NodeIndexOutOfRange,
    /// The mesh index is outside [`SceneAssets::meshes`].
    #[error("mesh_index_out_of_range")]
    MeshIndexOutOfRange,
    /// A skin joint index is outside [`Skeleton::bones`].
    #[error("skin_joint_out_of_range")]
    SkinJointOutOfRange,
    /// A non-empty inverse-bind array has a different length from skin joints.
    #[error("skin_ibm_count_mismatch")]
    SkinInverseBindCountMismatch,
    /// An instance inverse-bind matrix is not finite.
    #[error("non_finite_inverse_bind")]
    NonFiniteSkinInverseBind,
}

// --- Scene assets (meshes/materials) -----------------------------------
//
// The geometry half of a [`Document`]. Populated by both format loaders and
// emitted by the writer, so a full conversion preserves geometry. Primitives
// may be indexed already; [`Primitive::weld`] can index unindexed exact
// duplicates without collapsing authored seams.

/// One triangle-list primitive sharing a material. Attribute arrays may be
/// indexed already; [`Primitive::weld`] dedupes an unindexed primitive into
/// indexed form.
///
/// Additional glTF skin-influence attribute sets are intentionally metadata
/// only. The primary four influences remain in [`Self::joints`] and
/// [`Self::weights`]; consumers can use this metadata to apply their own
/// policy without the core assuming how additional influences are evaluated.
#[derive(Debug, Clone, Default)]
pub struct Primitive {
    /// Index into [`SceneAssets::materials`].
    pub material: Option<usize>,
    /// Triangle indices into the attribute arrays; empty = unindexed.
    pub indices: Vec<u32>,
    /// Vertex positions in scene units.
    pub positions: Vec<Vec3>,
    /// Same length as `positions`, or empty.
    pub normals: Vec<Vec3>,
    /// Same length as `positions`, or empty.
    pub uvs: Vec<[f32; 2]>,
    /// Indices into an owning instance's skin-joint list; empty if unskinned.
    pub joints: Vec<[u16; 4]>,
    /// Skinning weights parallel to [`Primitive::joints`].
    pub weights: Vec<[f32; 4]>,
    /// Declared non-primary skin-influence attribute sets.
    ///
    /// Each entry records whether the glTF primitive had `JOINTS_n` and/or
    /// `WEIGHTS_n` for `n >= 1`. Entries are sorted by
    /// [`AdditionalInfluenceSet::set_index`].
    pub additional_influence_sets: Vec<AdditionalInfluenceSet>,
}

/// Presence metadata for one non-primary glTF skin-influence attribute set.
///
/// A set may contain only one side because source assets can declare
/// `JOINTS_n` and `WEIGHTS_n` independently. This type deliberately does not
/// retain the corresponding per-vertex values: the core model's skinning
/// semantics remain the primary `JOINTS_0` / `WEIGHTS_0` set.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AdditionalInfluenceSet {
    /// glTF attribute-set number (`n >= 1`).
    pub set_index: u32,
    /// Whether `JOINTS_n` was declared.
    pub joints_present: bool,
    /// Whether `WEIGHTS_n` was declared.
    pub weights_present: bool,
}

/// One source mesh definition, independent of any node that instances it.
#[derive(Debug, Clone, Default)]
pub struct MeshAsset {
    /// Mesh name.
    pub name: String,
    /// Stable index of this definition in the source format.
    ///
    /// glTF permits several nodes to instance one mesh definition. Loaders
    /// preserve that distinction through [`SceneAssets::instances`].
    pub source_mesh_index: usize,
    /// Triangle-list primitives belonging to this mesh.
    pub primitives: Vec<Primitive>,
}

/// One node instance of a source [`MeshAsset`] definition.
#[derive(Debug, Clone, Default)]
pub struct MeshInstance {
    /// Index of the source-format node that owns this mesh instance.
    pub source_node_index: usize,
    /// The node this mesh hangs off in the core skeleton.
    pub node: BoneId,
    /// Index into [`SceneAssets::meshes`] of the instanced definition.
    pub mesh: usize,
    /// Skin joints in cluster order. Empty = unskinned.
    pub skin_joints: Vec<BoneId>,
    /// Per-joint inverse bind matrices, parallel to `skin_joints`
    /// (glTF convention: joint-bind-world⁻¹ × geometry-to-world, all
    /// in the converted scene space). Falls back to the bones'
    /// `inverse_bind` when empty.
    pub skin_ibms: Vec<Mat4>,
}

/// One declared source scene and its root nodes.
#[derive(Debug, Clone, Default)]
pub struct SceneAsset {
    /// Index of this scene in the source-format scene array.
    pub source_scene_index: usize,
    /// Authored scene name, when the source format provides one.
    pub name: Option<String>,
    /// Root nodes belonging to this scene, represented as core bone ids.
    pub roots: Vec<BoneId>,
}

/// Whether a loader supplied source-node and source-skin identity evidence.
///
/// The skeleton used by sampling is deliberately format-neutral and is ordered
/// for parent-before-child FK. Source formats can use a different stable node
/// order, so this coverage flag keeps an empty source table from being
/// mistaken for a source file with no nodes or skins.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SourceSkeletonCoverage {
    /// The loader cannot provide source-node and source-skin identity facts.
    #[default]
    Unavailable,
    /// The source-node and source-skin tables describe the loaded input.
    /// Source nodes with [`SourceNodeAsset::bone`] form the downward-closed
    /// projection consumed by strict operations.
    Complete,
}

/// The source-projected local-rest representation of one source node.
///
/// glTF permits either decomposed TRS properties or a matrix. Keeping this
/// representation separate from [`Bone::rest`] avoids presenting a lossy
/// matrix decomposition as though it were authored TRS evidence. For glTF the
/// value is the authored node member. A loader whose format semantics require
/// coordinate, helper-node, or inheritance normalization may instead project
/// that documented source-side result; its format-specific capability
/// inventory must make the distinction explicit. In particular, the FBX
/// loader records ufbx's adjusted/compensated TRS here and never claims it is
/// the raw FBX transform stack.
#[derive(Debug, Clone)]
pub enum SourceNodeLocalRest {
    /// Source-declared or format-normalized translation, rotation, and scale.
    Trs {
        /// Local translation in scene units.
        translation: Vec3,
        /// Local orientation relative to the parent node.
        rotation: Quat,
        /// Local non-uniform scale.
        scale: Vec3,
    },
    /// Source-declared or format-normalized column-major 4×4 local transform.
    Matrix(Mat4),
}

/// One source-side node with stable loader identity facts.
///
/// For a direct format projection this is an authored node. A loader that
/// normalizes helper or inheritance semantics may also include generated
/// source-side nodes, provided its capability inventory records that boundary.
///
/// Marked `#[non_exhaustive]` because this projection grows as loaders learn
/// to carry more source-native identity (`bone` was the most recent
/// addition): out-of-crate embedders construct it through
/// [`SourceNodeAsset::new`] and assign the optional facts they have, so a
/// later field cannot break their build. The sibling source-asset structs in
/// this module are not yet marked; they are stable in a way this one has
/// already demonstrated it is not.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SourceNodeAsset {
    /// Stable index in the loader's complete source-side node table.
    pub source_node_index: usize,
    /// Source-projected node name, when present.
    pub name: Option<String>,
    /// Source-side node-table index of the projected parent, when any.
    pub parent_source_node_index: Option<usize>,
    /// Source scenes that name this projected node as a root, in source-scene order.
    pub scene_root_indices: Vec<usize>,
    /// Source-projected local-rest representation.
    pub local_rest: SourceNodeLocalRest,
    /// The core [`BoneId`] this source node normalized to, when the loader
    /// retained it as an independent normalized node.
    ///
    /// `None` means this source row has no independent [`Skeleton`] bone. A
    /// loader may have dropped an unreachable node, or it may have folded a
    /// static connector's authored local rest into the next projected node.
    /// The row remains authoritative source identity and local-rest evidence
    /// under [`SourceSkeletonCoverage::Complete`]. Format-neutral consumers
    /// that need to resolve a raw source-node selector (for example
    /// [`crate::scale::ScaleOperation::RestBindUniformScale`]'s
    /// `source_root_node_index`/skin joints) into the normalized
    /// [`Skeleton`] must use this field rather than assuming source-node
    /// order equals bone order.
    ///
    /// With [`SourceSkeletonCoverage::Complete`] coverage, the `Some` rows
    /// must form a downward-closed, nearest-projected-parent-preserving
    /// projection into the normalized skeleton. Unprojected source rows may
    /// occur between projected ancestors; [`validate_document_shape`]
    /// verifies that relation.
    pub bone: Option<BoneId>,
}

impl SourceNodeAsset {
    /// One source node identified by its stable source-array index and its
    /// source-projected local rest — the two facts every loader necessarily has.
    ///
    /// Every remaining fact ([`Self::name`], [`Self::parent_source_node_index`],
    /// [`Self::scene_root_indices`], [`Self::bone`]) starts absent and is
    /// assigned through the public fields. This is the only way to build the
    /// value outside `animsmith-core`, since the type is `#[non_exhaustive]`.
    pub fn new(source_node_index: usize, local_rest: SourceNodeLocalRest) -> Self {
        Self {
            source_node_index,
            name: None,
            parent_source_node_index: None,
            scene_root_indices: Vec::new(),
            local_rest,
            bone: None,
        }
    }
}

/// Read status for a source skin's inverse-bind declaration.
///
/// glTF supplies this through an accessor. Other formats may supply an
/// equivalent ordered declaration (for example, FBX cluster bind matrices)
/// that the loader projects into target coordinates. Format-specific
/// capability evidence must distinguish projected values from exact source
/// payload preservation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SourceInverseBindAccessorStatus {
    /// The skin did not declare inverse-bind matrices.
    #[default]
    Absent,
    /// The declaration was readable and had at least one matrix per declared joint.
    Available,
    /// The source declared a count-zero inverse-bind payload.
    EmptyAccessor,
    /// The declaration was readable but has fewer matrices than declared joints.
    CountMismatch,
    /// The source declared bind matrices that the loader could not read.
    Unreadable,
}

/// Read-side evidence for one source skin inverse-bind declaration.
#[derive(Debug, Clone, Default)]
pub struct SourceInverseBindAccessor {
    /// Whether the source bind declaration was absent, complete, or malformed.
    pub status: SourceInverseBindAccessorStatus,
    /// Declared source matrix count, or `None` when no matrices were declared.
    pub declared_count: Option<usize>,
    /// Matrices in declared joint order when they were readable.
    ///
    /// glTF retains raw accessor values. A format loader may instead retain a
    /// documented coordinate-normalized projection of the source bind
    /// declaration. This may contain non-finite values from a parseable binary
    /// accessor or equivalent source structure.
    /// Measurement serialization must classify those values rather than emit
    /// non-finite JSON numbers.
    pub matrices: Vec<Mat4>,
}

/// One source node that declares use of a source skin.
#[derive(Debug, Clone)]
pub struct SourceSkinAttachment {
    /// Stable node-array index of the attachment node.
    pub source_node_index: usize,
    /// Stable source mesh-definition index, when the node declares a mesh.
    ///
    /// This remains present even when the current core mesh importer skips the
    /// definition (for example, because it has no triangle-list primitive).
    pub source_mesh_index: Option<usize>,
}

/// One source skin definition, kept separate from bone-level convenience data.
#[derive(Debug, Clone, Default)]
pub struct SourceSkinAsset {
    /// Stable skin-array index in the source format.
    pub source_skin_index: usize,
    /// Authored skin name, when present.
    pub name: Option<String>,
    /// Explicitly declared skeleton root, when present; never inferred.
    pub skeleton_root_source_node_index: Option<usize>,
    /// Source joints in declared skin-slot order.
    pub joint_source_node_indices: Vec<usize>,
    /// Source inverse-bind declaration evidence for this skin.
    ///
    /// glTF retains exact accessor values. Other loaders may retain a
    /// documented coordinate-normalized projection, as described by
    /// [`SourceInverseBindAccessor`].
    pub inverse_bind_accessor: SourceInverseBindAccessor,
    /// Source nodes that reference this skin, in source-node order.
    pub attachments: Vec<SourceSkinAttachment>,
}

/// Source-node and source-skin evidence carried beside normalized scene assets.
#[derive(Debug, Clone, Default)]
pub struct SourceSkeletonAssets {
    /// Whether these source tables are complete for the loaded input.
    pub coverage: SourceSkeletonCoverage,
    /// Source nodes in stable source-node order.
    pub nodes: Vec<SourceNodeAsset>,
    /// Source skins in stable source-skin order.
    pub skins: Vec<SourceSkinAsset>,
}

/// An embedded texture: raw encoded image bytes (glTF embeds the file
/// as-is, no decoding).
#[derive(Debug, Clone)]
pub struct TextureAsset {
    /// Encoded image bytes.
    pub bytes: Vec<u8>,
    /// "image/png" or "image/jpeg".
    pub mime: String,
}

/// A normal-map texture and the scalar applied to its X/Y components.
///
/// Keeping the scale beside the texture makes the glTF normal-texture state
/// atomic: a scale cannot accidentally survive after its texture is removed.
#[derive(Debug, Clone)]
pub struct NormalTextureAsset {
    /// Embedded encoded normal-map image.
    pub texture: TextureAsset,
    /// Scalar multiplier for the decoded tangent-space X/Y components.
    pub scale: f32,
}

/// An occlusion texture and the scalar applied to its sampled value.
///
/// Keeping the strength beside the texture makes the glTF occlusion-texture
/// state atomic: a strength cannot accidentally survive after its texture is
/// removed.
#[derive(Debug, Clone)]
pub struct OcclusionTextureAsset {
    /// Embedded encoded occlusion texture.
    pub texture: TextureAsset,
    /// Scalar multiplier for the sampled occlusion value.
    pub strength: f32,
}

/// PBR material factors plus optional embedded glTF texture slots.
#[derive(Debug, Clone)]
pub struct MaterialAsset {
    /// Material name.
    pub name: String,
    /// Multiplied with the texture when one is present (set to white
    /// by the FBX loader in that case, matching exporter convention).
    pub base_color: [f32; 4],
    /// Metallic factor.
    pub metallic: f32,
    /// Roughness factor.
    pub roughness: f32,
    /// Embedded base-color texture, if one was loaded.
    pub base_color_texture: Option<TextureAsset>,
    /// Embedded tangent-space normal texture, if one was loaded.
    pub normal_texture: Option<NormalTextureAsset>,
    /// Embedded metallic-roughness texture, if one was loaded.
    ///
    /// glTF stores roughness in green and metallic in blue.
    pub metallic_roughness_texture: Option<TextureAsset>,
    /// Embedded occlusion texture, if one was loaded.
    pub occlusion_texture: Option<OcclusionTextureAsset>,
}

/// Whether source material-resource inspection covers the whole input.
///
/// This sidecar is deliberately separate from writer-facing [`MaterialAsset`]
/// values. A loader may preserve materials for writing while declining to
/// inspect resource provenance or decode image metadata.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MaterialResourceCoverage {
    /// The loader inspected its complete documented source material-resource
    /// domain. Format-specific documentation defines which binding slots that
    /// domain includes.
    Complete,
    /// The loader cannot provide source resource evidence.
    #[default]
    Unavailable,
}

/// A material texture slot with stable source-format meaning.
///
/// Declaration order is the stable wire order used by material-resource
/// measurements.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MaterialTextureSlot {
    /// Base-color texture.
    BaseColor,
    /// Tangent-space normal texture.
    Normal,
    /// Combined metallic-roughness texture.
    MetallicRoughness,
    /// Occlusion texture.
    Occlusion,
    /// Emissive texture.
    Emissive,
}

/// One source material-to-texture binding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SourceMaterialTextureBinding {
    /// Material slot in stable semantic order.
    pub slot: MaterialTextureSlot,
    /// Stable source texture index.
    pub texture_index: usize,
}

/// One source material definition, independent of writer-facing material data.
#[derive(Debug, Clone, Default)]
pub struct SourceMaterialAsset {
    /// Stable source material index.
    pub material_index: usize,
    /// Authored name, when present.
    pub name: Option<String>,
    /// Source texture bindings, sorted by [`SourceMaterialTextureBinding::slot`].
    pub texture_bindings: Vec<SourceMaterialTextureBinding>,
}

/// One source texture definition.
#[derive(Debug, Clone, Default)]
pub struct SourceTextureAsset {
    /// Stable source texture index.
    pub texture_index: usize,
    /// Authored name, when present.
    pub name: Option<String>,
    /// Stable source image index referenced by this texture.
    pub image_index: usize,
}

/// How an image payload was declared by its source format.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ImageSourceKind {
    /// Bytes embedded directly in a container record.
    Embedded,
    /// Bytes encoded in a data URI.
    DataUri,
    /// A relative or otherwise external resource reference.
    External,
}

/// Image container format recognized by inspection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ImageContainerFormat {
    /// PNG image data.
    Png,
    /// JPEG image data.
    Jpeg,
}

/// Decoded image color representation reported by inspection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DecodedImageColorType {
    /// Single-channel, 8-bit luminance.
    L8,
    /// Luminance plus alpha, 8-bit channels.
    La8,
    /// RGB, 8-bit channels.
    Rgb8,
    /// RGBA, 8-bit channels.
    Rgba8,
    /// Single-channel, 16-bit luminance.
    L16,
    /// Luminance plus alpha, 16-bit channels.
    La16,
    /// RGB, 16-bit channels.
    Rgb16,
    /// RGBA, 16-bit channels.
    Rgba16,
}

/// Why source-image inspection could not produce decoded metadata.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ImageUnavailableReason {
    /// The source does not make the image payload available to the loader.
    SourceUnavailable,
    /// A data URI could not be parsed or decoded.
    InvalidDataUri,
    /// The image container is not supported for inspection.
    UnsupportedContainer,
    /// Supported image bytes could not be decoded.
    DecodeFailed,
    /// Inspection declined the resource because it exceeded a resource limit.
    ResourceLimit,
}

/// Result of bounded source-image inspection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SourceImageInspection {
    /// Decoded metadata was available without retaining decoded pixels.
    Available {
        /// Pixel width.
        width: u32,
        /// Pixel height.
        height: u32,
        /// Number of decoded channels.
        channel_count: u8,
        /// Decoded color representation.
        color_type: DecodedImageColorType,
    },
    /// Inspection could not provide decoded metadata.
    Unavailable {
        /// Stable unavailability reason.
        reason: ImageUnavailableReason,
    },
}

/// One source image definition and bounded inspection result.
#[derive(Debug, Clone)]
pub struct SourceImageAsset {
    /// Stable source image index.
    pub image_index: usize,
    /// Authored name, when present.
    pub name: Option<String>,
    /// Source declaration kind.
    pub source_kind: ImageSourceKind,
    /// MIME type declared by the source, when present.
    pub declared_mime_type: Option<String>,
    /// Detected container format, when recognisable.
    pub detected_container: Option<ImageContainerFormat>,
    /// Bounded image-inspection result.
    pub inspection: SourceImageInspection,
}

/// Read-only source material-resource evidence carried beside scene assets.
#[derive(Debug, Clone, Default)]
pub struct MaterialResourceAssets {
    /// Whether the source resource lists are complete.
    pub coverage: MaterialResourceCoverage,
    /// Source materials in source order.
    pub materials: Vec<SourceMaterialAsset>,
    /// Source textures in source order.
    pub textures: Vec<SourceTextureAsset>,
    /// Source images in source order.
    pub images: Vec<SourceImageAsset>,
}

impl Primitive {
    /// Dedupe identical corners into indexed triangles. Exact
    /// bit-equality only — no tolerance welding, so seams authored via
    /// split normals/UVs are preserved.
    pub fn weld(&mut self) {
        if !self.indices.is_empty() || self.positions.is_empty() {
            return;
        }
        let corner_key = |i: usize| -> Vec<u8> {
            let mut key = Vec::with_capacity(64);
            let mut push_f32s = |vals: &[f32]| {
                for v in vals {
                    key.extend_from_slice(&v.to_le_bytes());
                }
            };
            push_f32s(&self.positions[i].to_array());
            if let Some(n) = self.normals.get(i) {
                push_f32s(&n.to_array());
            }
            if let Some(uv) = self.uvs.get(i) {
                push_f32s(uv);
            }
            if let Some(w) = self.weights.get(i) {
                push_f32s(w);
            }
            if let Some(j) = self.joints.get(i) {
                for v in j {
                    key.extend_from_slice(&v.to_le_bytes());
                }
            }
            key
        };
        let mut seen: std::collections::HashMap<Vec<u8>, u32> = std::collections::HashMap::new();
        let mut indices = Vec::with_capacity(self.positions.len());
        let mut positions = Vec::new();
        let mut normals = Vec::new();
        let mut uvs = Vec::new();
        let mut joints = Vec::new();
        let mut weights = Vec::new();
        for i in 0..self.positions.len() {
            let index = *seen.entry(corner_key(i)).or_insert_with(|| {
                positions.push(self.positions[i]);
                if let Some(n) = self.normals.get(i) {
                    normals.push(*n);
                }
                if let Some(uv) = self.uvs.get(i) {
                    uvs.push(*uv);
                }
                if let Some(j) = self.joints.get(i) {
                    joints.push(*j);
                }
                if let Some(w) = self.weights.get(i) {
                    weights.push(*w);
                }
                (positions.len() - 1) as u32
            });
            indices.push(index);
        }
        self.indices = indices;
        self.positions = positions;
        self.normals = normals;
        self.uvs = uvs;
        self.joints = joints;
        self.weights = weights;
    }
}

/// Mesh definitions, their node instances, scenes, and materials carried
/// alongside animation data.
#[derive(Debug, Clone, Default)]
pub struct SceneAssets {
    /// Mesh definitions in source order, including definitions without a node
    /// instance.
    pub meshes: Vec<MeshAsset>,
    /// Node instances of the mesh definitions, in source node order.
    pub instances: Vec<MeshInstance>,
    /// Materials referenced by mesh primitives.
    pub materials: Vec<MaterialAsset>,
    /// Read-only source material, texture, and image evidence for measurement.
    /// Writer-facing material slots remain in [`Self::materials`].
    pub material_resources: MaterialResourceAssets,
    /// Declared source scenes in source order.
    pub scenes: Vec<SceneAsset>,
    /// Source scene index selected by default, when one was declared.
    pub default_scene: Option<usize>,
    /// Source-node and source-skin identity evidence for skeleton measurements.
    ///
    /// This is intentionally separate from the normalized [`Skeleton`] and
    /// from [`MeshInstance::skin_ibms`]: a source node order need not match
    /// FK order, and one joint can have different inverse binds in different
    /// source skins.
    pub source_skeleton: SourceSkeletonAssets,
}

/// Validate the enumerated structural snapshot strict document operations
/// rely on.
///
/// This is a snapshot only: [`Document`] is publicly mutable, so a successful
/// call does not certify a document against later mutation. Any strict
/// operation that relies on this full shape must rerun validation at its own
/// public boundary.
/// Tolerant analysis APIs may intentionally accept documents this rejects and
/// preserve the valid evidence they can read. This function does not validate
/// operation-specific capability, affine, closure, proof, or payload
/// invariants such as primitive skinning shape and base positions.
///
/// # Errors
///
/// Returns a typed [`DocumentShapeError`] for the first violation in stable
/// validation order: skeleton rest/topology, source identity/projection,
/// tracks, instances, then bone-level inverse binds.
pub fn validate_document_shape(document: &Document) -> Result<(), DocumentShapeError> {
    validate_skeleton_rest(&document.skeleton)?;
    validate_source_skeleton_identity(&document.assets.source_skeleton)?;
    validate_source_projection(document)?;
    validate_clip_tracks(document)?;
    validate_mesh_instances(document)?;
    validate_bone_inverse_binds(&document.skeleton)
}

fn validate_skeleton_rest(skeleton: &Skeleton) -> Result<(), DocumentShapeError> {
    world_rest_matrices(skeleton)
        .map(|_| ())
        .map_err(|error| match error {
            WorldMatrixError::NonFiniteTransform { node } => {
                DocumentShapeError::NonFiniteSkeletonRest { node }
            }
            WorldMatrixError::InvalidParent { node, parent } => {
                DocumentShapeError::InvalidSkeletonParent { node, parent }
            }
        })
}

fn validate_source_skeleton_identity(
    source_skeleton: &SourceSkeletonAssets,
) -> Result<(), DocumentShapeError> {
    let mut seen_nodes = BTreeSet::new();
    for node in &source_skeleton.nodes {
        if !seen_nodes.insert(node.source_node_index) {
            return Err(DocumentShapeError::DuplicateSourceNodeIndex {
                source_node_index: node.source_node_index,
            });
        }
    }
    let mut seen_skins = BTreeSet::new();
    for skin in &source_skeleton.skins {
        if !seen_skins.insert(skin.source_skin_index) {
            return Err(DocumentShapeError::DuplicateSourceSkinIndex {
                source_skin_index: skin.source_skin_index,
            });
        }
    }
    Ok(())
}

/// Validate the identity relation a `Complete` source projection claims.
///
/// Projected rows must be injective, preserve each bone's nearest projected
/// ancestor, and be downward-closed in the normalized skeleton. Unprojected
/// source rows may remain between projected ancestors, and unrelated
/// unprojected roots remain legal; totality is not required. Non-`Complete`
/// rows are not identity evidence and are deliberately ignored.
///
/// The rule is load-bearing for consumers such as scale that select a rewrite
/// domain through source-node ancestry but apply and prove it through
/// [`Skeleton::bones`]. Without agreement, a normalized child can sit outside
/// the selected source closure while its parent moves, leaving its displaced
/// world rest outside every declared proof walk.
fn validate_source_projection(document: &Document) -> Result<(), DocumentShapeError> {
    let source_skeleton = &document.assets.source_skeleton;
    if source_skeleton.coverage != SourceSkeletonCoverage::Complete {
        return Ok(());
    }

    let bones = &document.skeleton.bones;
    let mut bone_of_source = BTreeMap::new();
    let mut source_of_bone = BTreeMap::new();
    let mut skeleton_parents = Vec::with_capacity(source_skeleton.nodes.len());
    for node in &source_skeleton.nodes {
        let Some(bone) = node.bone else {
            continue;
        };
        let skeleton_parent = bones
            .get(bone)
            .ok_or(DocumentShapeError::SourceProjection {
                source_node_index: node.source_node_index,
                violation: SourceProjectionViolation::ProjectedBoneOutOfRange,
            })?
            .parent;
        if source_of_bone
            .insert(bone, node.source_node_index)
            .is_some()
        {
            return Err(DocumentShapeError::SourceProjection {
                source_node_index: node.source_node_index,
                violation: SourceProjectionViolation::TwoSourceNodesProjectToOneBone,
            });
        }
        bone_of_source.insert(node.source_node_index, bone);
        skeleton_parents.push((node, skeleton_parent));
    }

    let by_source_index: BTreeMap<_, _> = source_skeleton
        .nodes
        .iter()
        .map(|node| (node.source_node_index, node))
        .collect();
    let unprojected_rows = source_skeleton.nodes.len() - bone_of_source.len();
    // Cache only successful suffix resolutions. A malformed suffix still
    // fails on the first projected row that reaches it, preserving that row
    // as the error owner; a later row is never visited after the error.
    let mut resolved_unprojected = BTreeMap::<usize, Option<BoneId>>::new();
    for (node, skeleton_parent) in skeleton_parents {
        let mut cursor = node.parent_source_node_index;
        let mut unresolved_suffix = Vec::new();
        let projected_parent = loop {
            let Some(parent_source_node_index) = cursor else {
                break None;
            };
            if let Some(&bone) = bone_of_source.get(&parent_source_node_index) {
                break Some(bone);
            }
            if let Some(&projected_parent) = resolved_unprojected.get(&parent_source_node_index) {
                break projected_parent;
            }
            let parent = by_source_index.get(&parent_source_node_index).ok_or(
                DocumentShapeError::SourceProjection {
                    source_node_index: node.source_node_index,
                    violation: SourceProjectionViolation::ParentSourceNodeMissing,
                },
            )?;
            unresolved_suffix.push(parent_source_node_index);
            if unresolved_suffix.len() > unprojected_rows {
                return Err(DocumentShapeError::SourceProjection {
                    source_node_index: node.source_node_index,
                    violation: SourceProjectionViolation::CyclicUnprojectedSourceParentChain,
                });
            }
            cursor = parent.parent_source_node_index;
        };
        for source_node_index in unresolved_suffix {
            resolved_unprojected.insert(source_node_index, projected_parent);
        }
        if projected_parent != skeleton_parent {
            return Err(DocumentShapeError::SourceProjection {
                source_node_index: node.source_node_index,
                violation: SourceProjectionViolation::NearestProjectedParentMismatch,
            });
        }
    }

    for (bone, child) in bones.iter().enumerate() {
        if source_of_bone.contains_key(&bone) {
            continue;
        }
        if let Some(parent) = child.parent
            && let Some(&source_node_index) = source_of_bone.get(&parent)
        {
            return Err(DocumentShapeError::SourceProjection {
                source_node_index,
                violation: SourceProjectionViolation::ProjectedBoneHasUnprojectedSkeletonChild,
            });
        }
    }
    Ok(())
}

fn validate_clip_tracks(document: &Document) -> Result<(), DocumentShapeError> {
    let bone_count = document.skeleton.bones.len();
    for (clip_index, clip) in document.clips.iter().enumerate() {
        let mut seen = Vec::with_capacity(clip.tracks.len());
        for track in &clip.tracks {
            if track.bone >= bone_count {
                return Err(DocumentShapeError::TrackShape {
                    clip_index,
                    node: track.bone,
                    violation: TrackShapeViolation::BoneIndexOutOfRange,
                });
            }
            if seen.contains(&(track.bone, track.property)) {
                return Err(DocumentShapeError::DuplicateClipTrack {
                    clip_index,
                    node: track.bone,
                    property: track.property,
                });
            }
            seen.push((track.bone, track.property));
            validate_track_shape(clip_index, track)?;
        }
    }
    Ok(())
}

pub(crate) fn validate_track_shape(
    clip_index: usize,
    track: &Track,
) -> Result<(), DocumentShapeError> {
    let violation = if track.times.is_empty() {
        Some(TrackShapeViolation::EmptyTimes)
    } else if track.times.iter().any(|time| !time.is_finite()) {
        Some(TrackShapeViolation::NonFiniteTime)
    } else if track.times.windows(2).any(|times| times[0] >= times[1]) {
        Some(TrackShapeViolation::TimesNotStrictlyIncreasing)
    } else {
        let expected_values = match track.interpolation {
            Interpolation::CubicSpline => track.times.len().checked_mul(3),
            Interpolation::Linear | Interpolation::Step => Some(track.times.len()),
        };
        if expected_values != Some(track.values.len()) {
            Some(TrackShapeViolation::ValueCountMismatch)
        } else if !matches!(
            (&track.values, track.property),
            (
                TrackValues::Vec3s(_),
                Property::Translation | Property::Scale
            ) | (TrackValues::Quats(_), Property::Rotation)
        ) {
            Some(TrackShapeViolation::ValueTypeMismatchesProperty)
        } else if match &track.values {
            TrackValues::Vec3s(values) => values.iter().any(|value| !value.is_finite()),
            TrackValues::Quats(values) => values.iter().any(|value| !value.is_finite()),
        } {
            Some(TrackShapeViolation::NonFiniteValue)
        } else {
            None
        }
    };
    violation.map_or(Ok(()), |violation| {
        Err(DocumentShapeError::TrackShape {
            clip_index,
            node: track.bone,
            violation,
        })
    })
}

fn validate_mesh_instances(document: &Document) -> Result<(), DocumentShapeError> {
    let bone_count = document.skeleton.bones.len();
    let mesh_count = document.assets.meshes.len();
    for (instance_index, instance) in document.assets.instances.iter().enumerate() {
        let violation = if instance.node >= bone_count {
            Some(MeshInstanceShapeViolation::NodeIndexOutOfRange)
        } else if instance.mesh >= mesh_count {
            Some(MeshInstanceShapeViolation::MeshIndexOutOfRange)
        } else if instance
            .skin_joints
            .iter()
            .any(|&joint| joint >= bone_count)
        {
            Some(MeshInstanceShapeViolation::SkinJointOutOfRange)
        } else if !instance.skin_ibms.is_empty()
            && instance.skin_ibms.len() != instance.skin_joints.len()
        {
            Some(MeshInstanceShapeViolation::SkinInverseBindCountMismatch)
        } else if instance.skin_ibms.iter().any(|ibm| !mat4_is_finite(*ibm)) {
            Some(MeshInstanceShapeViolation::NonFiniteSkinInverseBind)
        } else {
            None
        };
        if let Some(violation) = violation {
            return Err(DocumentShapeError::MeshInstanceShape {
                instance_index,
                violation,
            });
        }
    }
    Ok(())
}

fn validate_bone_inverse_binds(skeleton: &Skeleton) -> Result<(), DocumentShapeError> {
    for (node, bone) in skeleton.bones.iter().enumerate() {
        if let Some(inverse_bind) = bone.inverse_bind
            && !mat4_is_finite(inverse_bind)
        {
            return Err(DocumentShapeError::NonFiniteBoneInverseBind { node });
        }
    }
    Ok(())
}

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

    #[test]
    fn property_serde_uses_the_stable_trs_vocabulary() {
        assert_eq!(
            serde_json::to_value([Property::Translation, Property::Rotation, Property::Scale,])
                .expect("properties serialize"),
            serde_json::json!(["translation", "rotation", "scale"])
        );
        assert_eq!(
            serde_json::from_value::<Vec<Property>>(serde_json::json!([
                "translation",
                "rotation",
                "scale"
            ]))
            .expect("properties deserialize"),
            [Property::Translation, Property::Rotation, Property::Scale,]
        );
    }

    fn bone(parent: Option<BoneId>) -> Bone {
        Bone {
            name: "bone".into(),
            parent,
            rest: Transform::IDENTITY,
            inverse_bind: None,
        }
    }

    fn one_bone_document() -> Document {
        Document {
            skeleton: Skeleton {
                bones: vec![bone(None)],
            },
            ..Document::default()
        }
    }

    fn source_node(
        source_node_index: usize,
        parent_source_node_index: Option<usize>,
        bone: Option<BoneId>,
    ) -> SourceNodeAsset {
        SourceNodeAsset {
            source_node_index,
            name: None,
            parent_source_node_index,
            scene_root_indices: Vec::new(),
            local_rest: SourceNodeLocalRest::Trs {
                translation: Vec3::ZERO,
                rotation: Quat::IDENTITY,
                scale: Vec3::ONE,
            },
            bone,
        }
    }

    fn valid_track() -> Track {
        Track {
            bone: 0,
            property: Property::Translation,
            interpolation: Interpolation::Linear,
            times: vec![0.0],
            values: TrackValues::Vec3s(vec![Vec3::ZERO]),
        }
    }

    fn track_document(track: Track) -> Document {
        let mut document = one_bone_document();
        document.clips.push(Clip {
            name: "clip".into(),
            duration_s: 0.0,
            tracks: vec![track],
        });
        document
    }

    fn instance_document() -> Document {
        let mut document = one_bone_document();
        document.assets.meshes.push(MeshAsset::default());
        document.assets.instances.push(MeshInstance {
            node: 0,
            mesh: 0,
            ..MeshInstance::default()
        });
        document
    }

    #[test]
    fn document_shape_validation_accepts_a_complete_projection_with_an_unprojected_intermediate() {
        let mut document = Document {
            skeleton: Skeleton {
                bones: vec![bone(None), bone(Some(0))],
            },
            assets: SceneAssets {
                source_skeleton: SourceSkeletonAssets {
                    coverage: SourceSkeletonCoverage::Complete,
                    nodes: vec![
                        source_node(10, None, Some(0)),
                        source_node(11, Some(10), None),
                        source_node(12, Some(11), Some(1)),
                    ],
                    ..SourceSkeletonAssets::default()
                },
                meshes: vec![MeshAsset::default()],
                instances: vec![MeshInstance {
                    node: 1,
                    mesh: 0,
                    skin_joints: vec![0, 1],
                    skin_ibms: vec![Mat4::IDENTITY, Mat4::IDENTITY],
                    ..MeshInstance::default()
                }],
                ..SceneAssets::default()
            },
            ..Document::default()
        };
        document.clips.push(Clip {
            name: "clip".into(),
            duration_s: 0.0,
            tracks: vec![valid_track()],
        });

        assert_eq!(validate_document_shape(&document), Ok(()));
    }

    #[test]
    fn shared_unprojected_parent_suffix_preserves_each_projected_parent() {
        const CONNECTORS: usize = 64;
        const PROJECTED_CHILDREN: usize = 64;

        let mut nodes = Vec::with_capacity(1 + CONNECTORS + PROJECTED_CHILDREN);
        nodes.push(source_node(0, None, Some(0)));
        for source_node_index in 1..=CONNECTORS {
            nodes.push(source_node(
                source_node_index,
                Some(source_node_index - 1),
                None,
            ));
        }
        for child in 0..PROJECTED_CHILDREN {
            nodes.push(source_node(
                1 + CONNECTORS + child,
                Some(CONNECTORS),
                Some(1 + child),
            ));
        }
        let document = Document {
            skeleton: Skeleton {
                bones: std::iter::once(bone(None))
                    .chain((0..PROJECTED_CHILDREN).map(|_| bone(Some(0))))
                    .collect(),
            },
            assets: SceneAssets {
                source_skeleton: SourceSkeletonAssets {
                    coverage: SourceSkeletonCoverage::Complete,
                    nodes,
                    ..SourceSkeletonAssets::default()
                },
                ..SceneAssets::default()
            },
            ..Document::default()
        };

        assert_eq!(validate_document_shape(&document), Ok(()));
        let mut mismatched = document.clone();
        mismatched.skeleton.bones[PROJECTED_CHILDREN].parent = None;
        assert_eq!(
            validate_document_shape(&mismatched),
            Err(DocumentShapeError::SourceProjection {
                source_node_index: CONNECTORS + PROJECTED_CHILDREN,
                violation: SourceProjectionViolation::NearestProjectedParentMismatch,
            })
        );
    }

    #[test]
    fn document_shape_validation_has_an_analytic_error_for_every_variant() {
        let projection_error =
            |source_node_index, violation| DocumentShapeError::SourceProjection {
                source_node_index,
                violation,
            };
        let track_error = |node, violation| DocumentShapeError::TrackShape {
            clip_index: 0,
            node,
            violation,
        };
        let instance_error = |violation| DocumentShapeError::MeshInstanceShape {
            instance_index: 0,
            violation,
        };

        let mut non_finite_rest = one_bone_document();
        non_finite_rest.skeleton.bones[0].rest.translation.x = f32::NAN;
        let overflowed_rest_world = Document {
            skeleton: Skeleton {
                bones: vec![
                    Bone {
                        rest: Transform {
                            scale: Vec3::splat(f32::MAX),
                            ..Transform::IDENTITY
                        },
                        ..bone(None)
                    },
                    Bone {
                        rest: Transform {
                            translation: Vec3::splat(2.0),
                            ..Transform::IDENTITY
                        },
                        ..bone(Some(0))
                    },
                ],
            },
            ..Document::default()
        };
        let self_parent = Document {
            skeleton: Skeleton {
                bones: vec![bone(Some(0))],
            },
            ..Document::default()
        };
        let forward_parent = Document {
            skeleton: Skeleton {
                bones: vec![bone(Some(1)), bone(None)],
            },
            ..Document::default()
        };
        let far_parent = Document {
            skeleton: Skeleton {
                bones: vec![bone(Some(99))],
            },
            ..Document::default()
        };
        let duplicate_node = Document {
            assets: SceneAssets {
                source_skeleton: SourceSkeletonAssets {
                    nodes: vec![
                        source_node(9, None, None),
                        source_node(10, None, None),
                        source_node(9, None, None),
                    ],
                    ..SourceSkeletonAssets::default()
                },
                ..SceneAssets::default()
            },
            ..Document::default()
        };
        let duplicate_skin = Document {
            assets: SceneAssets {
                source_skeleton: SourceSkeletonAssets {
                    skins: vec![
                        SourceSkinAsset {
                            source_skin_index: 4,
                            ..SourceSkinAsset::default()
                        },
                        SourceSkinAsset {
                            source_skin_index: 5,
                            ..SourceSkinAsset::default()
                        },
                        SourceSkinAsset {
                            source_skin_index: 4,
                            ..SourceSkinAsset::default()
                        },
                    ],
                    ..SourceSkeletonAssets::default()
                },
                ..SceneAssets::default()
            },
            ..Document::default()
        };
        let complete_projection = |nodes| SceneAssets {
            source_skeleton: SourceSkeletonAssets {
                coverage: SourceSkeletonCoverage::Complete,
                nodes,
                ..SourceSkeletonAssets::default()
            },
            ..SceneAssets::default()
        };
        let out_of_range_projection = Document {
            skeleton: Skeleton {
                bones: vec![bone(None)],
            },
            assets: complete_projection(vec![source_node(10, None, Some(1))]),
            ..Document::default()
        };
        let non_injective_projection = Document {
            skeleton: Skeleton {
                bones: vec![bone(None)],
            },
            assets: complete_projection(vec![
                source_node(10, None, Some(0)),
                source_node(11, None, Some(0)),
            ]),
            ..Document::default()
        };
        let missing_projection_parent = Document {
            skeleton: Skeleton {
                bones: vec![bone(None), bone(Some(0))],
            },
            assets: complete_projection(vec![source_node(11, Some(99), Some(1))]),
            ..Document::default()
        };
        // Exactly one unprojected row lies between projected child 11 and the
        // genuinely missing parent 99. The strict `> unprojected_rows` guard
        // must preserve the missing-parent classification; `>=` reports a
        // cycle at this exact boundary instead.
        let missing_projection_parent_at_cycle_bound = Document {
            skeleton: Skeleton {
                bones: vec![bone(None), bone(Some(0))],
            },
            assets: complete_projection(vec![
                source_node(10, None, Some(0)),
                source_node(11, Some(12), Some(1)),
                source_node(12, Some(99), None),
            ]),
            ..Document::default()
        };
        let cyclic_unprojected_parent = Document {
            skeleton: Skeleton {
                bones: vec![bone(None), bone(Some(0))],
            },
            assets: complete_projection(vec![
                source_node(11, Some(12), Some(1)),
                source_node(12, Some(12), None),
            ]),
            ..Document::default()
        };
        let cyclic_unprojected_parent_pair = Document {
            skeleton: Skeleton {
                bones: vec![bone(None), bone(Some(0))],
            },
            assets: complete_projection(vec![
                source_node(11, Some(12), Some(1)),
                source_node(12, Some(13), None),
                source_node(13, Some(12), None),
            ]),
            ..Document::default()
        };
        let mismatched_nearest_parent = Document {
            skeleton: Skeleton {
                bones: vec![bone(None), bone(Some(0))],
            },
            assets: complete_projection(vec![
                source_node(10, None, Some(0)),
                source_node(11, None, Some(1)),
            ]),
            ..Document::default()
        };
        let unprojected_child = Document {
            skeleton: Skeleton {
                bones: vec![bone(None), bone(Some(0))],
            },
            assets: complete_projection(vec![source_node(10, None, Some(0))]),
            ..Document::default()
        };

        let duplicate_track = {
            let track = valid_track();
            let mut document = track_document(track.clone());
            document.clips[0].tracks.push(Track {
                property: Property::Scale,
                ..valid_track()
            });
            document.clips[0].tracks.push(track);
            document
        };
        let mut boundary_out_of_range_track = valid_track();
        boundary_out_of_range_track.bone = 1;
        let mut far_out_of_range_track = valid_track();
        far_out_of_range_track.bone = 99;
        let empty_track = Track {
            times: Vec::new(),
            values: TrackValues::Vec3s(Vec::new()),
            ..valid_track()
        };
        let non_finite_later_time = Track {
            times: vec![0.0, f32::NAN],
            values: TrackValues::Vec3s(vec![Vec3::ZERO, Vec3::ZERO]),
            ..valid_track()
        };
        let unordered_times = Track {
            times: vec![1.0, 0.0],
            values: TrackValues::Vec3s(vec![Vec3::ZERO, Vec3::ZERO]),
            ..valid_track()
        };
        let equal_times = Track {
            times: vec![0.0, 0.0],
            values: TrackValues::Vec3s(vec![Vec3::ZERO, Vec3::ZERO]),
            ..valid_track()
        };
        let wrong_linear_value_count = Track {
            values: TrackValues::Vec3s(Vec::new()),
            ..valid_track()
        };
        let excess_linear_value_count = Track {
            values: TrackValues::Vec3s(vec![Vec3::ZERO, Vec3::ZERO]),
            ..valid_track()
        };
        let wrong_step_value_count = Track {
            interpolation: Interpolation::Step,
            times: vec![0.0, 1.0],
            values: TrackValues::Vec3s(vec![Vec3::ZERO]),
            ..valid_track()
        };
        let excess_step_value_count = Track {
            interpolation: Interpolation::Step,
            values: TrackValues::Vec3s(vec![Vec3::ZERO, Vec3::ZERO]),
            ..valid_track()
        };
        let wrong_cubic_value_count = Track {
            interpolation: Interpolation::CubicSpline,
            times: vec![0.0, 1.0],
            values: TrackValues::Vec3s(vec![Vec3::ZERO; 4]),
            ..valid_track()
        };
        let excess_cubic_value_count = Track {
            interpolation: Interpolation::CubicSpline,
            values: TrackValues::Vec3s(vec![Vec3::ZERO; 4]),
            ..valid_track()
        };
        let wrong_translation_value_type = Track {
            values: TrackValues::Quats(vec![Quat::IDENTITY]),
            ..valid_track()
        };
        let wrong_scale_value_type = Track {
            property: Property::Scale,
            values: TrackValues::Quats(vec![Quat::IDENTITY]),
            ..valid_track()
        };
        let wrong_rotation_value_type = Track {
            property: Property::Rotation,
            values: TrackValues::Vec3s(vec![Vec3::ZERO]),
            ..valid_track()
        };
        let non_finite_value = Track {
            values: TrackValues::Vec3s(vec![Vec3::splat(f32::NAN)]),
            ..valid_track()
        };

        let mut bad_instance_node = instance_document();
        bad_instance_node.assets.instances[0].node = 1;
        let mut far_instance_node = instance_document();
        far_instance_node.assets.instances[0].node = 99;
        let mut bad_instance_mesh = instance_document();
        bad_instance_mesh.assets.instances[0].mesh = 1;
        let mut far_instance_mesh = instance_document();
        far_instance_mesh.assets.instances[0].mesh = 99;
        let mut bad_instance_joint = instance_document();
        bad_instance_joint.assets.instances[0].skin_joints = vec![1];
        let mut far_instance_joint = instance_document();
        far_instance_joint.assets.instances[0].skin_joints = vec![99];
        let mut bad_instance_count = instance_document();
        bad_instance_count.assets.instances[0].skin_joints = vec![0];
        bad_instance_count.assets.instances[0].skin_ibms = vec![Mat4::IDENTITY, Mat4::IDENTITY];
        let mut short_instance_count = instance_document();
        short_instance_count.skeleton.bones.push(bone(Some(0)));
        short_instance_count.assets.instances[0].skin_joints = vec![0, 1];
        short_instance_count.assets.instances[0].skin_ibms = vec![Mat4::IDENTITY];
        let mut bad_instance_ibm = instance_document();
        bad_instance_ibm.assets.instances[0].skin_joints = vec![0];
        bad_instance_ibm.assets.instances[0].skin_ibms =
            vec![Mat4::from_cols_array(&[f32::NAN; 16])];
        let mut bad_bone_ibm = one_bone_document();
        bad_bone_ibm.skeleton.bones[0].inverse_bind = Some(Mat4::from_cols_array(&[f32::NAN; 16]));

        let cases = vec![
            (
                "non-finite rest",
                non_finite_rest,
                DocumentShapeError::NonFiniteSkeletonRest { node: 0 },
            ),
            (
                "non-finite composed rest world",
                overflowed_rest_world,
                DocumentShapeError::NonFiniteSkeletonRest { node: 1 },
            ),
            (
                "self parent",
                self_parent,
                DocumentShapeError::InvalidSkeletonParent { node: 0, parent: 0 },
            ),
            (
                "forward parent",
                forward_parent,
                DocumentShapeError::InvalidSkeletonParent { node: 0, parent: 1 },
            ),
            (
                "far parent",
                far_parent,
                DocumentShapeError::InvalidSkeletonParent {
                    node: 0,
                    parent: 99,
                },
            ),
            (
                "duplicate source node",
                duplicate_node,
                DocumentShapeError::DuplicateSourceNodeIndex {
                    source_node_index: 9,
                },
            ),
            (
                "duplicate source skin",
                duplicate_skin,
                DocumentShapeError::DuplicateSourceSkinIndex {
                    source_skin_index: 4,
                },
            ),
            (
                "projected bone range",
                out_of_range_projection,
                projection_error(10, SourceProjectionViolation::ProjectedBoneOutOfRange),
            ),
            (
                "projection injectivity",
                non_injective_projection,
                projection_error(
                    11,
                    SourceProjectionViolation::TwoSourceNodesProjectToOneBone,
                ),
            ),
            (
                "missing projection parent",
                missing_projection_parent,
                projection_error(11, SourceProjectionViolation::ParentSourceNodeMissing),
            ),
            (
                "missing projection parent at cycle bound",
                missing_projection_parent_at_cycle_bound,
                projection_error(11, SourceProjectionViolation::ParentSourceNodeMissing),
            ),
            (
                "cyclic projection parent",
                cyclic_unprojected_parent,
                projection_error(
                    11,
                    SourceProjectionViolation::CyclicUnprojectedSourceParentChain,
                ),
            ),
            (
                "cyclic projection parent pair",
                cyclic_unprojected_parent_pair,
                projection_error(
                    11,
                    SourceProjectionViolation::CyclicUnprojectedSourceParentChain,
                ),
            ),
            (
                "nearest projection parent",
                mismatched_nearest_parent,
                projection_error(
                    11,
                    SourceProjectionViolation::NearestProjectedParentMismatch,
                ),
            ),
            (
                "projection downward closure",
                unprojected_child,
                projection_error(
                    10,
                    SourceProjectionViolation::ProjectedBoneHasUnprojectedSkeletonChild,
                ),
            ),
            (
                "duplicate track",
                duplicate_track,
                DocumentShapeError::DuplicateClipTrack {
                    clip_index: 0,
                    node: 0,
                    property: Property::Translation,
                },
            ),
            (
                "track bone range boundary",
                track_document(boundary_out_of_range_track),
                track_error(1, TrackShapeViolation::BoneIndexOutOfRange),
            ),
            (
                "track bone range far",
                track_document(far_out_of_range_track),
                track_error(99, TrackShapeViolation::BoneIndexOutOfRange),
            ),
            (
                "empty track",
                track_document(empty_track),
                track_error(0, TrackShapeViolation::EmptyTimes),
            ),
            (
                "non-finite time",
                track_document(non_finite_later_time),
                track_error(0, TrackShapeViolation::NonFiniteTime),
            ),
            (
                "unordered times",
                track_document(unordered_times),
                track_error(0, TrackShapeViolation::TimesNotStrictlyIncreasing),
            ),
            (
                "equal times",
                track_document(equal_times),
                track_error(0, TrackShapeViolation::TimesNotStrictlyIncreasing),
            ),
            (
                "linear value count",
                track_document(wrong_linear_value_count),
                track_error(0, TrackShapeViolation::ValueCountMismatch),
            ),
            (
                "linear excess value count",
                track_document(excess_linear_value_count),
                track_error(0, TrackShapeViolation::ValueCountMismatch),
            ),
            (
                "step value count",
                track_document(wrong_step_value_count),
                track_error(0, TrackShapeViolation::ValueCountMismatch),
            ),
            (
                "step excess value count",
                track_document(excess_step_value_count),
                track_error(0, TrackShapeViolation::ValueCountMismatch),
            ),
            (
                "cubic value count",
                track_document(wrong_cubic_value_count),
                track_error(0, TrackShapeViolation::ValueCountMismatch),
            ),
            (
                "cubic excess value count",
                track_document(excess_cubic_value_count),
                track_error(0, TrackShapeViolation::ValueCountMismatch),
            ),
            (
                "translation value type",
                track_document(wrong_translation_value_type),
                track_error(0, TrackShapeViolation::ValueTypeMismatchesProperty),
            ),
            (
                "scale value type",
                track_document(wrong_scale_value_type),
                track_error(0, TrackShapeViolation::ValueTypeMismatchesProperty),
            ),
            (
                "rotation value type",
                track_document(wrong_rotation_value_type),
                track_error(0, TrackShapeViolation::ValueTypeMismatchesProperty),
            ),
            (
                "non-finite value",
                track_document(non_finite_value),
                track_error(0, TrackShapeViolation::NonFiniteValue),
            ),
            (
                "instance node boundary",
                bad_instance_node,
                instance_error(MeshInstanceShapeViolation::NodeIndexOutOfRange),
            ),
            (
                "instance node far",
                far_instance_node,
                instance_error(MeshInstanceShapeViolation::NodeIndexOutOfRange),
            ),
            (
                "instance mesh boundary",
                bad_instance_mesh,
                instance_error(MeshInstanceShapeViolation::MeshIndexOutOfRange),
            ),
            (
                "instance mesh far",
                far_instance_mesh,
                instance_error(MeshInstanceShapeViolation::MeshIndexOutOfRange),
            ),
            (
                "instance joint boundary",
                bad_instance_joint,
                instance_error(MeshInstanceShapeViolation::SkinJointOutOfRange),
            ),
            (
                "instance joint far",
                far_instance_joint,
                instance_error(MeshInstanceShapeViolation::SkinJointOutOfRange),
            ),
            (
                "instance ibm count excess",
                bad_instance_count,
                instance_error(MeshInstanceShapeViolation::SkinInverseBindCountMismatch),
            ),
            (
                "instance ibm count short",
                short_instance_count,
                instance_error(MeshInstanceShapeViolation::SkinInverseBindCountMismatch),
            ),
            (
                "instance ibm finite",
                bad_instance_ibm,
                instance_error(MeshInstanceShapeViolation::NonFiniteSkinInverseBind),
            ),
            (
                "bone ibm finite",
                bad_bone_ibm,
                DocumentShapeError::NonFiniteBoneInverseBind { node: 0 },
            ),
        ];
        for (name, document, expected) in cases {
            assert_eq!(validate_document_shape(&document), Err(expected), "{name}");
        }
    }

    #[test]
    fn document_shape_finiteness_checks_every_stored_component() {
        for component in 0..3 {
            let mut translation = Vec3::ZERO.to_array();
            translation[component] = f32::NAN;
            let mut document = one_bone_document();
            document.skeleton.bones[0].rest.translation = Vec3::from_array(translation);
            assert_eq!(
                validate_document_shape(&document),
                Err(DocumentShapeError::NonFiniteSkeletonRest { node: 0 }),
                "rest translation component {component}"
            );

            let mut scale = Vec3::ONE.to_array();
            scale[component] = f32::NAN;
            let mut document = one_bone_document();
            document.skeleton.bones[0].rest.scale = Vec3::from_array(scale);
            assert_eq!(
                validate_document_shape(&document),
                Err(DocumentShapeError::NonFiniteSkeletonRest { node: 0 }),
                "rest scale component {component}"
            );

            let mut value = Vec3::ZERO.to_array();
            value[component] = f32::NAN;
            let document = track_document(Track {
                values: TrackValues::Vec3s(vec![Vec3::from_array(value)]),
                ..valid_track()
            });
            assert_eq!(
                validate_document_shape(&document),
                Err(DocumentShapeError::TrackShape {
                    clip_index: 0,
                    node: 0,
                    violation: TrackShapeViolation::NonFiniteValue,
                }),
                "track Vec3 component {component}"
            );
        }

        for component in 0..4 {
            let mut rotation = Quat::IDENTITY.to_array();
            rotation[component] = f32::NAN;
            let mut document = one_bone_document();
            document.skeleton.bones[0].rest.rotation = Quat::from_array(rotation);
            assert_eq!(
                validate_document_shape(&document),
                Err(DocumentShapeError::NonFiniteSkeletonRest { node: 0 }),
                "rest rotation component {component}"
            );

            let document = track_document(Track {
                property: Property::Rotation,
                values: TrackValues::Quats(vec![Quat::from_array(rotation)]),
                ..valid_track()
            });
            assert_eq!(
                validate_document_shape(&document),
                Err(DocumentShapeError::TrackShape {
                    clip_index: 0,
                    node: 0,
                    violation: TrackShapeViolation::NonFiniteValue,
                }),
                "track quaternion component {component}"
            );
        }

        for key in 0..3 {
            let mut times = vec![0.0, 1.0, 2.0];
            times[key] = f32::NAN;
            let document = track_document(Track {
                times,
                values: TrackValues::Vec3s(vec![Vec3::ZERO; 3]),
                ..valid_track()
            });
            assert_eq!(
                validate_document_shape(&document),
                Err(DocumentShapeError::TrackShape {
                    clip_index: 0,
                    node: 0,
                    violation: TrackShapeViolation::NonFiniteTime,
                }),
                "track time {key}"
            );
        }

        for component in 0..16 {
            let mut columns = Mat4::IDENTITY.to_cols_array();
            columns[component] = f32::NAN;
            let inverse_bind = Mat4::from_cols_array(&columns);

            let mut instance_document = instance_document();
            instance_document.assets.instances[0].skin_joints = vec![0];
            instance_document.assets.instances[0].skin_ibms = vec![inverse_bind];
            assert_eq!(
                validate_document_shape(&instance_document),
                Err(DocumentShapeError::MeshInstanceShape {
                    instance_index: 0,
                    violation: MeshInstanceShapeViolation::NonFiniteSkinInverseBind,
                }),
                "instance inverse-bind component {component}"
            );

            let mut bone_document = one_bone_document();
            bone_document.skeleton.bones[0].inverse_bind = Some(inverse_bind);
            assert_eq!(
                validate_document_shape(&bone_document),
                Err(DocumentShapeError::NonFiniteBoneInverseBind { node: 0 }),
                "bone inverse-bind component {component}"
            );
        }
    }

    #[test]
    fn document_shape_rejects_duplicate_tracks_for_every_property() {
        let tracks = [
            (Property::Translation, TrackValues::Vec3s(vec![Vec3::ZERO])),
            (Property::Scale, TrackValues::Vec3s(vec![Vec3::ONE])),
            (Property::Rotation, TrackValues::Quats(vec![Quat::IDENTITY])),
        ];

        for (property, values) in tracks {
            let track = Track {
                property,
                values,
                ..valid_track()
            };
            let mut document = track_document(track.clone());
            document.clips[0].tracks.push(track);

            assert_eq!(
                validate_document_shape(&document),
                Err(DocumentShapeError::DuplicateClipTrack {
                    clip_index: 0,
                    node: 0,
                    property,
                }),
                "duplicate {property:?} track"
            );
        }
    }

    #[test]
    fn document_shape_rejects_infinite_times_quaternions_and_inverse_binds() {
        for non_finite in [f32::INFINITY, f32::NEG_INFINITY] {
            let document = track_document(Track {
                times: vec![non_finite],
                values: TrackValues::Vec3s(vec![Vec3::ZERO]),
                ..valid_track()
            });
            assert_eq!(
                validate_document_shape(&document),
                Err(DocumentShapeError::TrackShape {
                    clip_index: 0,
                    node: 0,
                    violation: TrackShapeViolation::NonFiniteTime,
                }),
                "track time {non_finite}"
            );

            let document = track_document(Track {
                property: Property::Rotation,
                values: TrackValues::Quats(vec![Quat::from_xyzw(non_finite, 0.0, 0.0, 1.0)]),
                ..valid_track()
            });
            assert_eq!(
                validate_document_shape(&document),
                Err(DocumentShapeError::TrackShape {
                    clip_index: 0,
                    node: 0,
                    violation: TrackShapeViolation::NonFiniteValue,
                }),
                "track quaternion {non_finite}"
            );

            let mut columns = Mat4::IDENTITY.to_cols_array();
            columns[0] = non_finite;
            let inverse_bind = Mat4::from_cols_array(&columns);
            let mut document = instance_document();
            document.assets.instances[0].skin_joints = vec![0];
            document.assets.instances[0].skin_ibms = vec![inverse_bind];
            assert_eq!(
                validate_document_shape(&document),
                Err(DocumentShapeError::MeshInstanceShape {
                    instance_index: 0,
                    violation: MeshInstanceShapeViolation::NonFiniteSkinInverseBind,
                }),
                "instance inverse bind {non_finite}"
            );

            let mut document = one_bone_document();
            document.skeleton.bones[0].inverse_bind = Some(inverse_bind);
            assert_eq!(
                validate_document_shape(&document),
                Err(DocumentShapeError::NonFiniteBoneInverseBind { node: 0 }),
                "bone inverse bind {non_finite}"
            );
        }
    }

    #[test]
    fn document_shape_checks_mesh_and_joint_references_on_later_instances() {
        let later_instance = MeshInstance {
            node: 0,
            mesh: 0,
            ..MeshInstance::default()
        };

        let mut document = instance_document();
        document.assets.instances.push(later_instance.clone());
        document.assets.instances[1].mesh = 1;
        assert_eq!(
            validate_document_shape(&document),
            Err(DocumentShapeError::MeshInstanceShape {
                instance_index: 1,
                violation: MeshInstanceShapeViolation::MeshIndexOutOfRange,
            })
        );

        let mut document = instance_document();
        document.assets.instances.push(later_instance);
        document.assets.instances[1].skin_joints = vec![1];
        assert_eq!(
            validate_document_shape(&document),
            Err(DocumentShapeError::MeshInstanceShape {
                instance_index: 1,
                violation: MeshInstanceShapeViolation::SkinJointOutOfRange,
            })
        );
    }

    #[test]
    fn document_shape_finds_duplicates_that_do_not_involve_the_first_item() {
        let mut document = Document::default();
        document.assets.source_skeleton.skins = [4, 5, 5]
            .into_iter()
            .map(|source_skin_index| SourceSkinAsset {
                source_skin_index,
                ..SourceSkinAsset::default()
            })
            .collect();
        assert_eq!(
            validate_document_shape(&document),
            Err(DocumentShapeError::DuplicateSourceSkinIndex {
                source_skin_index: 5,
            })
        );

        let scale_track = Track {
            property: Property::Scale,
            values: TrackValues::Vec3s(vec![Vec3::ONE]),
            ..valid_track()
        };
        let mut document = track_document(valid_track());
        document.clips[0].tracks.push(scale_track.clone());
        document.clips[0].tracks.push(scale_track);
        assert_eq!(
            validate_document_shape(&document),
            Err(DocumentShapeError::DuplicateClipTrack {
                clip_index: 0,
                node: 0,
                property: Property::Scale,
            })
        );
    }

    #[test]
    fn document_shape_checks_later_tracks_and_inverse_binds() {
        let mut document = track_document(valid_track());
        document.clips[0].tracks.push(Track {
            property: Property::Scale,
            times: Vec::new(),
            values: TrackValues::Vec3s(Vec::new()),
            ..valid_track()
        });
        assert_eq!(
            validate_document_shape(&document),
            Err(DocumentShapeError::TrackShape {
                clip_index: 0,
                node: 0,
                violation: TrackShapeViolation::EmptyTimes,
            })
        );

        let scale_track = Track {
            property: Property::Scale,
            values: TrackValues::Vec3s(vec![Vec3::ONE]),
            ..valid_track()
        };
        let mut document = track_document(valid_track());
        document.clips.push(Clip {
            name: "later".into(),
            duration_s: 0.0,
            tracks: vec![scale_track.clone(), scale_track],
        });
        assert_eq!(
            validate_document_shape(&document),
            Err(DocumentShapeError::DuplicateClipTrack {
                clip_index: 1,
                node: 0,
                property: Property::Scale,
            })
        );

        let mut document = track_document(valid_track());
        document.clips.push(Clip {
            name: "later".into(),
            duration_s: 0.0,
            tracks: vec![Track {
                property: Property::Scale,
                times: Vec::new(),
                values: TrackValues::Vec3s(Vec::new()),
                ..valid_track()
            }],
        });
        assert_eq!(
            validate_document_shape(&document),
            Err(DocumentShapeError::TrackShape {
                clip_index: 1,
                node: 0,
                violation: TrackShapeViolation::EmptyTimes,
            })
        );

        let mut columns = Mat4::IDENTITY.to_cols_array();
        columns[15] = f32::NAN;
        let non_finite_inverse_bind = Mat4::from_cols_array(&columns);

        let mut document = instance_document();
        document.skeleton.bones.push(bone(Some(0)));
        document.assets.instances[0].skin_joints = vec![0, 1];
        document.assets.instances[0].skin_ibms = vec![Mat4::IDENTITY, non_finite_inverse_bind];
        assert_eq!(
            validate_document_shape(&document),
            Err(DocumentShapeError::MeshInstanceShape {
                instance_index: 0,
                violation: MeshInstanceShapeViolation::NonFiniteSkinInverseBind,
            })
        );

        let mut document = instance_document();
        document.assets.instances.push(MeshInstance {
            node: 0,
            mesh: 0,
            skin_joints: vec![0],
            skin_ibms: vec![non_finite_inverse_bind],
            ..MeshInstance::default()
        });
        assert_eq!(
            validate_document_shape(&document),
            Err(DocumentShapeError::MeshInstanceShape {
                instance_index: 1,
                violation: MeshInstanceShapeViolation::NonFiniteSkinInverseBind,
            })
        );

        let mut document = instance_document();
        document.assets.instances.push(MeshInstance {
            node: 0,
            mesh: 0,
            skin_joints: vec![0],
            skin_ibms: vec![Mat4::IDENTITY, Mat4::IDENTITY],
            ..MeshInstance::default()
        });
        assert_eq!(
            validate_document_shape(&document),
            Err(DocumentShapeError::MeshInstanceShape {
                instance_index: 1,
                violation: MeshInstanceShapeViolation::SkinInverseBindCountMismatch,
            })
        );

        let mut document = one_bone_document();
        document.skeleton.bones.push(Bone {
            inverse_bind: Some(non_finite_inverse_bind),
            ..bone(Some(0))
        });
        assert_eq!(
            validate_document_shape(&document),
            Err(DocumentShapeError::NonFiniteBoneInverseBind { node: 1 })
        );
    }

    #[test]
    fn document_shape_violation_names_remain_machine_stable() {
        let source_projection = [
            (
                SourceProjectionViolation::ProjectedBoneOutOfRange,
                "projected_bone_out_of_range",
            ),
            (
                SourceProjectionViolation::TwoSourceNodesProjectToOneBone,
                "two_source_nodes_project_to_one_bone",
            ),
            (
                SourceProjectionViolation::ParentSourceNodeMissing,
                "parent_source_node_is_missing",
            ),
            (
                SourceProjectionViolation::CyclicUnprojectedSourceParentChain,
                "cyclic_unprojected_source_parent_chain",
            ),
            (
                SourceProjectionViolation::NearestProjectedParentMismatch,
                "projection_and_skeleton_parents_differ",
            ),
            (
                SourceProjectionViolation::ProjectedBoneHasUnprojectedSkeletonChild,
                "projected_bone_has_an_unprojected_skeleton_child",
            ),
        ];
        for (violation, expected) in source_projection {
            assert_eq!(violation.to_string(), expected);
        }

        let track = [
            (
                TrackShapeViolation::BoneIndexOutOfRange,
                "bone_index_out_of_range",
            ),
            (TrackShapeViolation::EmptyTimes, "empty_times"),
            (TrackShapeViolation::NonFiniteTime, "non_finite_time"),
            (
                TrackShapeViolation::TimesNotStrictlyIncreasing,
                "times_not_strictly_increasing",
            ),
            (
                TrackShapeViolation::ValueCountMismatch,
                "value_count_mismatch",
            ),
            (
                TrackShapeViolation::ValueTypeMismatchesProperty,
                "value_type_mismatches_property",
            ),
            (TrackShapeViolation::NonFiniteValue, "non_finite_value"),
        ];
        for (violation, expected) in track {
            assert_eq!(violation.to_string(), expected);
        }

        let instance = [
            (
                MeshInstanceShapeViolation::NodeIndexOutOfRange,
                "node_index_out_of_range",
            ),
            (
                MeshInstanceShapeViolation::MeshIndexOutOfRange,
                "mesh_index_out_of_range",
            ),
            (
                MeshInstanceShapeViolation::SkinJointOutOfRange,
                "skin_joint_out_of_range",
            ),
            (
                MeshInstanceShapeViolation::SkinInverseBindCountMismatch,
                "skin_ibm_count_mismatch",
            ),
            (
                MeshInstanceShapeViolation::NonFiniteSkinInverseBind,
                "non_finite_inverse_bind",
            ),
        ];
        for (violation, expected) in instance {
            assert_eq!(violation.to_string(), expected);
        }
    }

    #[test]
    fn tolerant_world_rests_keep_unrelated_partial_evidence() {
        let skeleton = Skeleton {
            bones: vec![
                bone(None),
                bone(Some(99)),
                Bone {
                    rest: Transform {
                        translation: Vec3::X,
                        ..Transform::IDENTITY
                    },
                    ..bone(None)
                },
                Bone {
                    rest: Transform {
                        translation: Vec3::Y,
                        ..Transform::IDENTITY
                    },
                    ..bone(Some(2))
                },
                bone(Some(1)),
            ],
        };

        let worlds = tolerant_world_rest_matrices(&skeleton);
        assert_eq!(worlds.len(), 5);
        assert_eq!(worlds[0], Some(Mat4::IDENTITY));
        assert_eq!(worlds[1], None, "the malformed parent is unavailable");
        assert_eq!(worlds[2], Some(Mat4::from_translation(Vec3::X)));
        assert_eq!(
            worlds[3],
            Some(Mat4::from_translation(Vec3::new(1.0, 1.0, 0.0))),
            "a finite independent chain remains measurable"
        );
        assert_eq!(
            worlds[4], None,
            "a child of unavailable evidence is unavailable"
        );
    }

    #[test]
    fn shared_affine_classifier_respects_distinct_caller_tolerances() {
        let equal_axis_basis = affine_test_fixtures::tolerance_divergence_basis();
        let strict = PositiveUniformAffineTolerance {
            equal_axis: 1.0e-5,
            relative_orthogonality: 1.0e-5,
            singular_determinant_relative: 1.0e-6,
        };
        let loose = PositiveUniformAffineTolerance {
            equal_axis: 1.0e-4,
            relative_orthogonality: 1.0e-4,
            singular_determinant_relative: 0.0,
        };

        assert_eq!(
            classify_positive_uniform_affine(equal_axis_basis, strict),
            Err(AffineDomainViolation::NonUniformScale),
            "the stricter caller rejects this equal-axis difference"
        );
        assert!(
            classify_positive_uniform_affine(equal_axis_basis, loose).is_ok(),
            "the looser caller accepts this equal-axis difference"
        );

        let orthogonality_basis = affine_test_fixtures::orthogonality_tolerance_divergence_basis();
        assert_eq!(
            classify_positive_uniform_affine(orthogonality_basis, strict),
            Err(AffineDomainViolation::Sheared),
            "the stricter caller rejects this cross-axis dot product"
        );
        assert!(
            classify_positive_uniform_affine(orthogonality_basis, loose).is_ok(),
            "the looser caller accepts this cross-axis dot product"
        );
    }

    #[test]
    fn shared_affine_classifier_pins_its_symmetric_f64_formula() {
        let policy = PositiveUniformAffineTolerance {
            equal_axis: 1.0e-5,
            relative_orthogonality: 1.0e-5,
            singular_determinant_relative: 1.0e-6,
        };

        // Exact binary32 lengths whose mean is exactly 99_999 in binary64.
        // The longest-axis deviation is exactly 1: accepted only when the
        // relative base is max(mean, axis), then refused one binary32 ulp
        // farther out.
        let on_long_edge = Mat3::from_diagonal(Vec3::new(99_998.5, 99_998.5, 100_000.0));
        assert_eq!(
            classify_positive_uniform_affine(on_long_edge, policy),
            Ok(99_999.0)
        );
        let short = 99_998.5;
        let long = 100_000.0 + 0.007_812_5;
        for diagonal in [
            Vec3::new(long, short, short),
            Vec3::new(short, long, short),
            Vec3::new(short, short, long),
        ] {
            assert_eq!(
                classify_positive_uniform_affine(Mat3::from_diagonal(diagonal), policy),
                Err(AffineDomainViolation::NonUniformScale)
            );
        }

        // A one-sided comparison would miss the uniquely short axis. At this
        // exact binary32 step the short-axis deviation is outside the band,
        // while each longer axis remains inside it.
        let short = 1.0 - 2.0_f32.powi(-16);
        for diagonal in [
            Vec3::new(short, 1.0, 1.0),
            Vec3::new(1.0, short, 1.0),
            Vec3::new(1.0, 1.0, short),
        ] {
            assert_eq!(
                classify_positive_uniform_affine(Mat3::from_diagonal(diagonal), policy),
                Err(AffineDomainViolation::NonUniformScale)
            );
        }

        // Only binary64 dot-product arithmetic places this basis outside the
        // orthogonality band; binary32 rounds the deciding dot back inside.
        let c0 = Vec3::new(0.12792248, -0.99066633, -0.047073245);
        let c1 = Vec3::new(-0.34637994, -0.00016034879, -0.93809813);
        let c2 = Vec3::new(0.92933476, 0.13630849, -0.3431568);
        assert!((c1.dot(c2) as f64).abs() < 1.0e-5);
        assert!(c1.as_dvec3().dot(c2.as_dvec3()).abs() > 1.0e-5);
        assert_eq!(
            classify_positive_uniform_affine(Mat3::from_cols(c0, c1, c2), policy),
            Err(AffineDomainViolation::Sheared)
        );

        // Orthogonality is sign-independent; dropping abs() accepts the
        // negative case while leaving the positive fixture green.
        for shear in [2.0_f32.powi(-15), -2.0_f32.powi(-15)] {
            let basis = Mat3::from_cols(Vec3::X, Vec3::new(shear, 1.0, 0.0), Vec3::Z);
            assert_eq!(
                classify_positive_uniform_affine(basis, policy),
                Err(AffineDomainViolation::Sheared)
            );
        }
    }

    #[test]
    fn affine_axis_mean_is_ascending_and_column_order_invariant() {
        // This is the audited counterexample. These are the widened lengths
        // of three exact binary32 columns; their authored-order sum changes
        // by one binary64 ulp when the columns are cycled. The canonical
        // ascending association is the lower result.
        let lengths = [
            f64::from_bits(0x3ff1_09e7_e000_022c),
            f64::from_bits(0x3ff1_09ec_6000_0eb5),
            f64::from_bits(0x3ff1_09fa_e000_3cde),
        ];
        let expected = f64::from_bits(0x3ff1_09ef_b555_6f3f);
        let ascending = (lengths[0] + lengths[1] + lengths[2]) / 3.0;
        let descending = (lengths[2] + lengths[1] + lengths[0]) / 3.0;
        assert_eq!(expected.to_bits(), 0x3ff1_09ef_b555_6f3f);
        assert_eq!(ascending.to_bits(), expected.to_bits());
        assert_eq!(descending.to_bits(), 0x3ff1_09ef_b555_6f40);
        for order in [
            [0, 1, 2],
            [0, 2, 1],
            [1, 0, 2],
            [1, 2, 0],
            [2, 0, 1],
            [2, 1, 0],
        ] {
            assert_eq!(
                average_affine_axis_length(order.map(|index| lengths[index])),
                expected,
                "axis order {order:?}"
            );
        }

        // The association is observable even for exactly representable
        // dyadic inputs: adding the two small terms first retains them,
        // while adding either to `2^53` loses both. This catches replacing
        // the canonical sort with a different fixed input order.
        let dyadic = [2.0_f64.powi(53), 1.0, 1.0];
        let ascending = (dyadic[1] + dyadic[2] + dyadic[0]) / 3.0;
        let descending = (dyadic[0] + dyadic[1] + dyadic[2]) / 3.0;
        assert_ne!(ascending, descending);
        assert_eq!(average_affine_axis_length(dyadic), ascending);

        // The same exact binary32 columns exercise the classifier. Every
        // permutation below preserves orientation: odd column permutations
        // negate one column, which leaves lengths unchanged and restores the
        // determinant's sign. The equal-axis boundary must consequently
        // reject the same geometry in all six authored axis orders.
        let permutations = affine_test_fixtures::appendix_d_v6_mean_permutations();
        let expected_length_bits = lengths.map(f64::to_bits);
        assert_eq!(
            affine_axis_lengths(permutations[0]).map(f64::to_bits),
            expected_length_bits
        );
        let tolerance = PositiveUniformAffineTolerance {
            equal_axis: 1.0e-5,
            relative_orthogonality: 1.0e-5,
            singular_determinant_relative: 1.0e-6,
        };
        for (permutation, linear) in permutations.into_iter().enumerate() {
            assert!(
                linear
                    .x_axis
                    .as_dvec3()
                    .cross(linear.y_axis.as_dvec3())
                    .dot(linear.z_axis.as_dvec3())
                    > 0.0,
                "orientation for permutation {permutation}"
            );
            assert_eq!(
                average_affine_axis_length(affine_axis_lengths(linear)).to_bits(),
                expected.to_bits(),
                "mean for permutation {permutation}"
            );
            assert_eq!(
                classify_positive_uniform_affine(linear, tolerance),
                Err(AffineDomainViolation::NonUniformScale),
                "classification for permutation {permutation}"
            );
        }
    }

    #[test]
    fn shared_affine_classifier_pins_f64_determinant_arithmetic() {
        // These exact binary32 columns make the f32 scalar triple product
        // land above the same threshold that the product of widened columns
        // lands below. The remaining bands are deliberately loose so only
        // singularity arithmetic decides the result.
        let linear = Mat3::from_cols(
            Vec3::new(
                f32::from_bits(0x3ff3_5574),
                f32::from_bits(0x3f0e_fa3c),
                0.0,
            ),
            Vec3::new(
                f32::from_bits(0x3ff5_5e17),
                f32::from_bits(0x3f10_2c31),
                0.0,
            ),
            Vec3::Z,
        );
        let columns = [
            linear.x_axis.as_dvec3(),
            linear.y_axis.as_dvec3(),
            linear.z_axis.as_dvec3(),
        ];
        let determinant_f64 = columns[2].dot(columns[0].cross(columns[1]));
        let determinant_f32 = f64::from(linear.determinant());
        let lengths = affine_axis_lengths(linear);
        let threshold = (determinant_f64 + determinant_f32) / 2.0;
        assert!(determinant_f64 < threshold);
        assert!(determinant_f32 > threshold);

        assert_eq!(
            classify_positive_uniform_affine(
                linear,
                PositiveUniformAffineTolerance {
                    equal_axis: 10.0,
                    relative_orthogonality: 10.0,
                    singular_determinant_relative: threshold
                        / (lengths[0] * lengths[1] * lengths[2]),
                },
            ),
            Err(AffineDomainViolation::Singular)
        );

        // Every derived determinant operand must stay widened as well. A
        // binary32 axis-product intermediate overflows on this otherwise
        // finite, positive, exactly uniform basis and falsely calls it
        // singular under Appendix D's non-zero relative threshold.
        let large_uniform = 2.0e19_f32;
        assert_eq!(
            classify_positive_uniform_affine(
                Mat3::from_diagonal(Vec3::splat(large_uniform)),
                PositiveUniformAffineTolerance {
                    equal_axis: 1.0e-5,
                    relative_orthogonality: 1.0e-5,
                    singular_determinant_relative: 1.0e-6,
                },
            ),
            Ok(f64::from(large_uniform))
        );
    }

    #[test]
    fn affine_geometry_facts_pin_every_widened_field_and_slot() {
        let linear = Mat3::from_cols(
            Vec3::new(1.0, 2.0, 3.0),
            Vec3::new(4.0, 5.0, 6.0),
            Vec3::new(7.0, 8.0, 10.0),
        );

        let facts = AffineGeometryFacts::from_linear(linear).expect("finite widened facts");
        assert_eq!(
            facts.axis_lengths.map(f64::to_bits),
            [
                0x400d_eeea_1168_3f49,
                0x4021_8cc8_21d6_d3e3,
                0x402d_3064_dcc8_ae67,
            ]
        );
        assert_eq!(facts.mean_axis_length.to_bits(), 0x4022_12f7_d653_30b4);
        assert_eq!(facts.determinant.to_bits(), 0xc008_0000_0000_0000);
        assert_eq!(facts.axis_length_product.to_bits(), 0x407d_f2e3_88f2_1b01);
        assert_eq!(
            facts.cross_axis_dots.map(f64::to_bits),
            [
                0x4040_0000_0000_0000,
                0x404a_8000_0000_0000,
                0x4060_0000_0000_0000,
            ],
            "cross-axis slots are XY, XZ, YZ"
        );
    }

    #[test]
    fn affine_geometry_facts_widen_every_dot_product_before_multiplying() {
        let x = Vec3::new(
            f32::from_bits(0x3ff3_5574),
            f32::from_bits(0x3f0e_fa3c),
            0.0,
        );
        let y = Vec3::new(
            f32::from_bits(0x3ff5_5e17),
            f32::from_bits(0x3f10_2c31),
            0.0,
        );
        let widened_dot = x.as_dvec3().dot(y.as_dvec3());
        let f32_then_widened = f64::from(x.dot(y));

        for (slot, linear) in [
            (0, Mat3::from_cols(x, y, Vec3::Z)),
            (1, Mat3::from_cols(x, Vec3::Z, y)),
            (2, Mat3::from_cols(Vec3::Z, x, y)),
        ] {
            let facts = AffineGeometryFacts::from_linear(linear).expect("finite widened facts");
            assert_eq!(facts.cross_axis_dots[slot], widened_dot);
            assert_ne!(
                facts.cross_axis_dots[slot], f32_then_widened,
                "dot slot {slot} must multiply and add in f64, not widen an f32 result"
            );
        }
    }

    #[test]
    fn weld_preserves_uv_seams_at_shared_positions() {
        let mut primitive = Primitive {
            positions: vec![Vec3::ZERO, Vec3::ZERO, Vec3::ZERO],
            uvs: vec![[0.0, 0.0], [1.0, 0.0], [0.0, 0.0]],
            ..Primitive::default()
        };

        primitive.weld();

        assert_eq!(primitive.positions.len(), 2);
        let reconstructed_corners = primitive
            .indices
            .iter()
            .map(|&index| {
                let index = index as usize;
                (primitive.positions[index], primitive.uvs[index])
            })
            .collect::<Vec<_>>();
        assert_eq!(
            reconstructed_corners,
            vec![
                (Vec3::ZERO, [0.0, 0.0]),
                (Vec3::ZERO, [1.0, 0.0]),
                (Vec3::ZERO, [0.0, 0.0]),
            ]
        );
    }
}