crcbl-render 0.17.0

Crucible renderer: the 3D frame on crcbl-frame — meshes, materials, lights, effects
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
//! The skinning prepass: joint palettes and bind-pose vertices in, skinned
//! vertices written back into a transient region of the same vertex pool.
//!
//! ```text
//!  MeshPool ──reserve_vertices ×2──▶ SkinnedRegion { prev, current }
//!
//!  begin_frame ──▶ palettes[frame]      (one buffer, every range end to end)
//!              ──▶ bindings[frame]      (one buffer, every range end to end,
//!                                         rewritten only when they change)
//!              ──▶ params[frame][slot]  (one uniform block per range)
//!
//!  add_pass ──── compute "skinning"  vertex pool ──▶ vertex pool
//!                                         │ graph barrier
//!                    the caller's mesh pass ◀┘  ShaderRead
//! ```
//!
//! GPU skinning as the rules in `docs/notes/simulation.md` (_What the deleted
//! 17-animation plan left behind_) set it out, and the host side of
//! `crates/crcbl-shaders/shaders/skinning.slang`. The kernel is that file's;
//! everything here is what it cannot do for itself — allocate the region it
//! writes into, upload the palette it blends onto, and refuse the inputs it has
//! no way to reject.
//!
//! # What the pass writes is what the vertex stage pulls
//!
//! The one sentence the whole design hangs off, and the shader's header carries
//! it in full: a skinned draw is an ordinary draw whose base vertex names the
//! region this pass filled. That is why [`SkinnedRegion`] is a range of
//! [`crate::mesh_pool`]'s pool rather than a buffer of its own.
//!
//! Where the base comes from is **one branch, in the raster stages**: an
//! instance carrying
//! [`GpuInstance::BASE_VERTEX_OVERRIDE`](crcbl_shaders::mesh::GpuInstance::BASE_VERTEX_OVERRIDE)
//! takes it from its own record instead of from the mesh entry the draw
//! resolved. A skinned instance still names its **source** mesh for bucket
//! scattering and level selection. Cluster culling keeps every selected cluster
//! of a deforming instance, because the source spheres and normal cones no
//! longer describe the vertices that the skinning pass writes. Instance culling
//! keeps the whole instance too, unless its record carries a box of its own —
//! [`SkinnedInstanceDesc::bounds`](crate::SkinnedInstanceDesc::bounds) — which
//! the culls then test in place of the source mesh's. The renderer drops this
//! pass's dispatch for a region whose every object such a box puts out of
//! everything the frame draws — see
//! [`ForwardRenderer::set_skinning_culls`](crate::ForwardRenderer::set_skinning_culls).
//!
//! # The region is double-buffered, and the motion-vector pass reads the other half
//!
//! The animation plan's 2026-07-27 correction: "TAA motion vectors for
//! skinned meshes need previous-frame skinned **positions**, not just a previous
//! transform… the skinned-output pool region is double-buffered (prev/current
//! ping-pong) from day one — a pool-layout decision that is nearly free now and
//! a skinning-pipeline rewrite later."
//!
//! So [`SkinnedRegion`] reserves **two** runs and [`Skinning::begin_frame`]
//! alternates which one a frame writes. **What reads the other one is the
//! motion-vector pass**:
//! [`ForwardRenderer::point_skinned_instances`](crate::forward::ForwardRenderer)
//! writes its base into
//! [`GpuInstance::previous_base_vertex`](crcbl_shaders::mesh::GpuInstance::previous_base_vertex)
//! every frame, beside the current half's, and `mesh.slang`'s vertex stage and
//! `mesh_cluster.slang`'s `emit_cluster` take a fragment's previous clip
//! position from the vertex there. Subtracting the *current* deformed vertex
//! instead — which is what a record with no previous base leaves them doing —
//! gives a swinging limb the motion of the body it hangs off.
//!
//! The correction was followed ahead of that reader, and the alternative it
//! avoided was shipping a pass whose output has one home and then re-pointing
//! every bind group, every barrier and every draw that names it.
//!
//! # One dispatch per range, one bind group per range
//!
//! [`crcbl_shaders::skinning::Params`] describes exactly one contiguous run of
//! vertices, so a frame with three animated characters is three dispatches. Each
//! needs its own uniform block, so [`Skinning`] holds one params buffer and one
//! bind group per (frame, range) slot and [`SkinningDesc::ranges`] is how many
//! of those exist. The palette buffer, the skin-binding buffer and the vertex
//! pool are shared by all of them, and a range names its own start in each.
//!
//! The GPU-driven form — one dispatch over a table of ranges — is what §3.3's
//! other passes look like and is deliberately not here. It needs a range table
//! the shader can index, which is a second layout to pin against `slangc`, and
//! the kernel as committed reads one block.
//!
//! # Where a bad joint index is refused
//!
//! In [`Skinning::begin_frame`], by name, before anything is uploaded. The
//! shader clamps every index against the palette length, so a malformed asset
//! draws wrongly rather than reading past a storage buffer — but a clamp is a
//! containment, not a diagnosis, and `docs/backlog.md` records that
//! `crcbl-scene` cannot do better because a glTF primitive does not know its
//! skin at import time. This call does: it is handed the palette and the
//! bindings together, and it is the last place either is a Rust value. See
//! [`SkinningError::JointOutOfRange`].
//!
//! Every joint is checked when the bindings change. A frame handing over the
//! same bindings as the one before tests each range's palette length against
//! the highest joint that range was found to name, which refuses exactly what
//! the full scan would — and the scan then runs to name the vertex.
//!
//! # The oracle
//!
//! [`skin_vertex`] is this module's [`crate::cull::visible_instances`]: ordinary
//! Rust that computes what `computeMain` computes, so a test that reads the
//! pool back has something to compare against. Nothing in a frame calls it, and
//! that is the point of an oracle.
//!
//! **Nothing in this workspace executes the kernel yet.** `crcbl-render` depends
//! on `crcbl-hal` and no backend, so its own tests run against the null backend,
//! which records a dispatch and never runs one. The readback that proves the
//! kernel belongs beside the cull one in `crates/crcbl-vk/tests/vk_e2e/`, which
//! is where `crcbl_render::cull`'s oracle is already used that way.

use crcbl_hal::{
    BindGroupDesc, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutHandle, BufferDesc,
    BufferHandle, BufferUsage, ComputePipelineHandle, Device, HalError, MemoryLocation,
    PipelineLayoutDesc, PipelineLayoutHandle, ResourceState, check_portable_storage_buffers,
};
use crcbl_shaders::mesh::MeshVertex;
use crcbl_shaders::skinning::{
    JOINT_STRIDE, JOINTS_PER_VERTEX, PARAMS_SIZE, Params, SKIN_BINDING_STRIDE, SkinBinding,
    WORKGROUP_SIZE,
};
use crcbl_shaders::vertex::{QTangent, TangentFrame};
use glam::{Mat3, Mat4, Vec3, Vec4};

use crate::draw_gen::{UINT_STRIDE, bound, compute_pipeline, storage, uniform};
use crate::graph::{BufferId, ImportedBuffer, RenderGraph};
use crate::mesh_pool::{MeshHandle, MeshPool, MeshPoolError};

/// A skinned mesh's transient region of the vertex pool: two runs of the same
/// length, one written per frame and one holding the frame before it.
///
/// Reserved with [`SkinnedRegion::reserve`] and given back with
/// [`SkinnedRegion::release`]. Neither [`Clone`] nor [`Copy`], because a copy
/// is a second thing that would try to release the same two runs.
///
/// See the [module docs](self) for what each of the two runs is for.
#[derive(Debug)]
pub struct SkinnedRegion {
    /// The two runs' first vertices, indexed by a frame's parity.
    bases: [u32; 2],
    vertex_count: u32,
}

impl SkinnedRegion {
    /// Reserves both halves from `pool`.
    ///
    /// Two separate reservations rather than one run of `2 * vertex_count`: a
    /// fragmented pool can hold two halves where it has no single block for the
    /// pair, and nothing here needs the two to be adjacent.
    ///
    /// # Errors
    ///
    /// Whatever [`MeshPool::reserve_vertices`] refuses. A failure on the second
    /// half gives the first one back before it returns, so a refused
    /// reservation leaks no pool space.
    pub fn reserve(pool: &mut MeshPool, vertex_count: u32) -> Result<Self, MeshPoolError> {
        let first = pool.reserve_vertices(vertex_count)?;
        let second = match pool.reserve_vertices(vertex_count) {
            Ok(second) => second,
            Err(error) => {
                pool.release_vertices(first, vertex_count);
                return Err(error);
            }
        };
        Ok(Self {
            bases: [first, second],
            vertex_count,
        })
    }

    /// Gives both halves back to `pool`.
    ///
    /// The device must not be reading either of them: this is pool bookkeeping
    /// and records no barrier, exactly like [`MeshPool::free`].
    pub fn release(self, pool: &mut MeshPool) {
        for base in self.bases {
            pool.release_vertices(base, self.vertex_count);
        }
    }

    /// Vertices in each half, which is also the skinned mesh's vertex count.
    #[must_use]
    pub const fn vertex_count(&self) -> u32 {
        self.vertex_count
    }

    /// The half a frame of this parity writes — the run a draw of this mesh
    /// takes its base vertex from.
    ///
    /// `parity` is [`Skinning::parity`], the alternating bit of the frame most
    /// recently begun.
    #[must_use]
    pub const fn base(&self, parity: u32) -> u32 {
        self.bases[(parity & 1) as usize]
    }

    /// The other half: what the frame before this one skinned.
    ///
    /// **The half a motion vector is subtracted against** — see the
    /// [module docs](self).
    /// [`ForwardRenderer::point_skinned_instances`](crate::forward::ForwardRenderer)
    /// puts this number in every skinned instance's
    /// [`GpuInstance::previous_base_vertex`](crcbl_shaders::mesh::GpuInstance::previous_base_vertex),
    /// off its own copy of the two bases rather than through this call, because
    /// a placed object keeps the pair and not the region; this is where that
    /// indexing is defined and what a test compares against.
    #[must_use]
    pub const fn previous_base(&self, parity: u32) -> u32 {
        self.bases[((parity ^ 1) & 1) as usize]
    }

    /// Both halves' first vertices, in parity order: what tells two live
    /// regions apart, since the pool hands a run out again only once the
    /// region holding it has been released.
    #[must_use]
    pub(crate) const fn halves(&self) -> [u32; 2] {
        self.bases
    }
}

/// A resident mesh a draw can be pointed at the skinned output of: a
/// [`SkinnedRegion`], the mesh it was deformed from, and that mesh's own first
/// vertex.
///
/// ```text
///  source mesh ─┬─ region half 0   drawn on even frames
///               └─ region half 1   drawn on odd frames
/// ```
///
/// # The parity rides on the instance, not on the mesh table
///
/// [`SkinnedRegion::base`] alternates every frame, and an instance drawn out of
/// a region carries that base itself — see
/// [`GpuInstance::base_vertex`](crcbl_shaders::mesh::GpuInstance::base_vertex),
/// which the raster stages read in place of the mesh entry's when
/// [`GpuInstance::BASE_VERTEX_OVERRIDE`](crcbl_shaders::mesh::GpuInstance::BASE_VERTEX_OVERRIDE)
/// is set. So a frame's ping-pong is a write to the instance array, which
/// [`crate::instance_pool`] rings, and **no mesh-table entry is rewritten
/// between frames** — the property [`crate::mesh_pool`]'s module docs rest that
/// table's lack of a ring on.
///
/// [`mesh_id`](Self::mesh_id) is therefore the **source** mesh's id, one entry
/// and not two: the bucket `draw_gen.slang` scatters the instance into and the
/// level tables it indexes still belong to the source mesh. Culling must not
/// reject the deformed vertices using that mesh's undeformed bounds.
///
/// # It does not own the mesh
///
/// `source`'s vertices, indices and table entry are still the pool's. Freeing
/// that mesh while one of these is live leaves an instance naming an entry that
/// reads as the empty range, which draws nothing.
#[derive(Debug)]
pub struct SkinnedMesh {
    region: SkinnedRegion,
    /// The source mesh's table id: what
    /// [`GpuInstance::mesh`](crcbl_shaders::mesh::GpuInstance::mesh) holds for
    /// every instance drawn out of this region, under either parity.
    mesh: u32,
    /// The bind pose's first vertex — what [`SkinRange::input_base`] wants, kept
    /// here so the one call that needs it cannot be handed the skinned base by
    /// mistake.
    input_base: u32,
}

impl SkinnedMesh {
    /// Reserves a region as long as `source`'s vertex run.
    ///
    /// Nothing writes the region: it holds whatever its allocation came with
    /// until a [`Skinning`] dispatch fills it, exactly as
    /// [`MeshPool::reserve_vertices`] says. A draw out of it before that has
    /// happened is a draw of undefined vertices, which is what
    /// [`crate::forward::ForwardRenderer::add_skinned_passes`] exists to make
    /// impossible to record.
    ///
    /// # Errors
    ///
    /// [`MeshPoolError::NotResident`] if `source` is not a resident mesh of this
    /// pool, and whatever [`SkinnedRegion::reserve`] refuses — a pool with no
    /// room for both halves. **A failure gives back everything the earlier steps
    /// took**, so a refused reservation leaks no pool space.
    pub fn reserve(pool: &mut MeshPool, source: MeshHandle) -> Result<Self, MeshPoolError> {
        let range = pool
            .mesh(source)
            .ok_or(MeshPoolError::NotResident { handle: source })?;
        let vertex_count = pool
            .vertex_count(source)
            .ok_or(MeshPoolError::NotResident { handle: source })?;
        let region = SkinnedRegion::reserve(pool, vertex_count)?;
        Ok(Self {
            region,
            mesh: source.index(),
            input_base: range.base_vertex,
        })
    }

    /// Gives the region back.
    ///
    /// The device must not be reading either half: this records no barrier, on
    /// [`SkinnedRegion::release`]'s terms. It takes no table entry back, because
    /// it never took one — the source mesh's entry is the pool's and outlives
    /// this.
    pub fn release(self, pool: &mut MeshPool) {
        self.region.release(pool);
    }

    /// The region the dispatch writes and the draws read.
    #[must_use]
    pub const fn region(&self) -> &SkinnedRegion {
        &self.region
    }

    /// Vertices in each half, which is the bind pose's vertex count.
    #[must_use]
    pub const fn vertex_count(&self) -> u32 {
        self.region.vertex_count()
    }

    /// The bind pose's first vertex: [`SkinRange::input_base`].
    #[must_use]
    pub const fn input_base(&self) -> u32 {
        self.input_base
    }

    /// The mesh-table id an instance drawn out of this region carries — what
    /// [`GpuInstance::mesh`](crcbl_shaders::mesh::GpuInstance::mesh) holds.
    ///
    /// The **source** mesh's, and the same under either parity: what changes
    /// per frame is
    /// [`GpuInstance::base_vertex`](crcbl_shaders::mesh::GpuInstance::base_vertex),
    /// which [`SkinnedRegion::base`] answers for.
    #[must_use]
    pub const fn mesh_id(&self) -> u32 {
        self.mesh
    }

    /// This mesh's [`SkinRange`] for one frame, given the palette and the
    /// bindings.
    ///
    /// The only way to build one where `input_base` and `region` can disagree
    /// about which mesh they belong to, which is the mistake that would skin one
    /// primitive's vertices into another's region.
    #[must_use]
    pub const fn skin_range<'a>(
        &'a self,
        palette: &'a [Mat4],
        bindings: &'a [SkinBinding],
    ) -> SkinRange<'a> {
        SkinRange {
            input_base: self.input_base,
            region: &self.region,
            palette,
            bindings,
        }
    }
}

/// What a [`Skinning`] refuses to do.
#[derive(Debug, thiserror::Error)]
pub enum SkinningError {
    /// A skin binding names a joint the range's palette has not got.
    ///
    /// **The check `crcbl-scene` could not make.** A glTF primitive's
    /// `JOINTS_0` is validated at import against the attribute lengths and
    /// against nothing else, because a primitive does not know which skin will
    /// be applied to it; this call is handed the palette and the bindings
    /// together and can say. The shader clamps such an index rather than
    /// reading past the palette, so the containment is real either way — but a
    /// clamped index is a mesh that deforms wrongly with nothing to look at,
    /// and this names the vertex.
    #[error(
        "range {range}'s vertex {vertex} is bound to joint {joint} in slot {slot}, and its \
         palette holds {palette} — the shader would clamp it and the mesh would deform wrongly"
    )]
    JointOutOfRange {
        /// Which of the frame's ranges, in the order they were handed over.
        range: usize,
        /// The vertex within that range.
        vertex: usize,
        /// Which of the four joint slots of that vertex.
        slot: usize,
        /// The index it named.
        joint: u32,
        /// Matrices the range's palette actually holds.
        palette: usize,
    },
    /// A range's palette is empty.
    ///
    /// Refused here rather than left to
    /// [`Params::to_bytes`](crcbl_shaders::skinning::Params::to_bytes), which
    /// panics: the shader clamps against `joint_count - 1`, so an empty palette
    /// is every index in the buffer.
    #[error("range {range} has an empty joint palette, which the shader's index clamp would wrap")]
    EmptyPalette {
        /// Which of the frame's ranges.
        range: usize,
    },
    /// A range's skin bindings are not one per vertex of its region.
    ///
    /// They are parallel arrays — binding `i` describes bind-pose vertex `i` —
    /// so a short list would leave the tail of the mesh reading another range's
    /// bindings, and a long one is a caller that has the wrong region.
    #[error(
        "range {range} covers {vertices} vertices and was given {bindings} skin bindings; they \
         are parallel runs and must be the same length"
    )]
    BindingCountMismatch {
        /// Which of the frame's ranges.
        range: usize,
        /// Vertices in the range's region.
        vertices: u32,
        /// Bindings offered.
        bindings: usize,
    },
    /// More ranges, palette matrices or skin bindings than this pass was built
    /// for.
    ///
    /// Refused rather than truncated, for [`crate::light_grid`]'s reason: a
    /// character silently missing from the frame is what the capacity exists to
    /// prevent, and nothing downstream would report it.
    #[error(
        "this skinning pass holds {capacity} {what} and the frame asked for {asked}; raise \
         the renderer's skinning capacity rather than dropping a character, which no counter \
         would report"
    )]
    OverCapacity {
        /// `"ranges"`, `"palette matrices"` or `"skin bindings"`.
        what: &'static str,
        /// What the pass was built with.
        capacity: u32,
        /// What the frame needed.
        asked: u64,
    },
    /// Anything the seam refused.
    #[error(transparent)]
    Hal(#[from] HalError),
}

/// How large a [`Skinning`] is, and what it writes into.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SkinningDesc<'a> {
    /// Debug name; every buffer, group and pipeline is named after it.
    pub label: Option<&'a str>,
    /// How many frames in flight, and so how long every ring here is.
    pub frames: usize,
    /// Skinned ranges one frame can dispatch — one animated primitive each.
    ///
    /// A params buffer and a bind group exist per (frame, range), so this is a
    /// capacity rather than a hint.
    pub ranges: u32,
    /// Palette matrices the joint buffer holds, summed across every range of
    /// one frame.
    pub joints: u32,
    /// Skin bindings the binding buffer holds, likewise — which is the total
    /// **skinned** vertex count, not the vertex pool's capacity. See
    /// [`Params::binding_base`](crcbl_shaders::skinning::Params::binding_base).
    pub bindings: u32,
    /// The vertex pool this pass reads the bind pose from and writes the
    /// skinned vertices into: [`MeshPool::vertex_buffer`].
    ///
    /// One binding, read at one base and written at another — WebGPU forbids
    /// the same range appearing as a writable storage buffer and as anything
    /// else in one usage scope, so the two-view spelling is a
    /// `createBindGroup` failure in the browser rather than a matter of taste.
    pub vertices: BufferHandle,
    /// Where that pool's **attribute** region begins, in words:
    /// [`MeshPool::attribute_base`].
    ///
    /// The dispatch reads and writes both streams, and the boundary is the
    /// pool's capacity — which is why it arrives here rather than being derived:
    /// see `crcbl_shaders::skinning::Params::attribute_base`, the block lane it
    /// ends up in.
    ///
    /// [`MeshPool::attribute_base`]: crate::MeshPool::attribute_base
    pub attribute_base: u32,
}

/// One range the caller asks to be skinned this frame: one animated
/// primitive's bind pose, its region, its palette and its per-vertex bindings.
#[derive(Clone, Copy, Debug)]
pub struct SkinRange<'a> {
    /// First vertex of the **bind-pose** run in the pool —
    /// [`MeshRange::base_vertex`](crate::mesh_pool::MeshRange::base_vertex).
    pub input_base: u32,
    /// Where the skinned vertices go. Its
    /// [`vertex_count`](SkinnedRegion::vertex_count) is the dispatch's extent.
    pub region: &'a SkinnedRegion,
    /// This instance's joint palette — what
    /// [`crcbl_anim::Palette::matrices`] hands out: each joint's global
    /// transform times its inverse bind matrix, with the skinned node's own
    /// transform deliberately absent.
    ///
    /// [`crcbl_anim::Palette::matrices`]: https://docs.rs/crcbl-anim
    pub palette: &'a [Mat4],
    /// One entry per vertex of the bind-pose run, in the same order.
    pub bindings: &'a [SkinBinding],
}

/// The palette buffer, the skin-binding buffer, the per-range uniform blocks
/// and the compute pass over them.
#[derive(Debug)]
pub struct Skinning {
    /// `[frame]` — every range's palette, end to end.
    palettes: Vec<BufferHandle>,
    /// `[frame]` — every range's skin bindings, end to end.
    bindings: Vec<BufferHandle>,
    /// `[frame][range]` — one uniform block each.
    params: Vec<Vec<BufferHandle>>,
    /// `[frame][range]`, in the same order.
    groups: Vec<Vec<BindGroupHandle>>,
    /// `[frame]` — each range [`Skinning::begin_frame`] was last handed for
    /// that slot, in range order: its group count and the region it writes.
    active: Vec<Vec<Planned>>,
    layout: BindGroupLayoutHandle,
    pipeline_layout: PipelineLayoutHandle,
    pipeline: ComputePipelineHandle,
    vertices: BufferHandle,
    /// [`SkinningDesc::attribute_base`], carried into every block this pass
    /// writes.
    attribute_base: u32,
    range_capacity: u32,
    joint_capacity: u32,
    binding_capacity: u32,
    /// Frames [`Skinning::begin_frame`] has accepted. Its low bit is the
    /// ping-pong.
    frames_begun: u64,
    /// The skin bindings most recently passed validation, end to end, and what
    /// each range of them was checked to name — see [`Bindings`]. Kept even if
    /// a device write later fails that frame: they were valid, and the slots'
    /// generations say which of them still need writing.
    latest: Bindings,
    /// `[frame]` — the [`Bindings::generation`] that slot's binding buffer
    /// holds, or [`None`] for one it is not known to hold.
    uploaded: Vec<Option<u64>>,
}

/// One range of a slot's plan: what [`Skinning::add_pass`] dispatches for it.
#[derive(Clone, Copy, Debug)]
struct Planned {
    /// Workgroups the dispatch covers.
    groups: u32,
    /// The region it writes, as [`SkinnedRegion::halves`] names it.
    region: [u32; 2],
}

/// The skin bindings a [`Skinning`] last accepted, kept so a frame handing over
/// the same ones again is neither re-checked nor re-uploaded.
///
/// Bindings are a mesh's own vertex data and do not move from one frame to the
/// next, where the palette does. Comparing against this copy is one read of
/// each; what it saves is the joint scan, the serialisation and the write into
/// host-visible memory, every frame.
#[derive(Debug, Default)]
struct Bindings {
    /// Every range's bindings, end to end, in the order they were handed over.
    all: Vec<SkinBinding>,
    /// Per range: how many of `all` it covers, and the highest joint index any
    /// slot of them names — what [`SkinningError::JointOutOfRange`] tests a
    /// palette against, so an unchanged range is checked in one comparison.
    ranges: Vec<(usize, u32)>,
    /// Bumped whenever `all` changes; a slot whose
    /// [`Skinning::uploaded`] entry differs is re-uploaded.
    generation: u64,
}

impl Bindings {
    /// Whether `ranges` hand over exactly these bindings, range for range.
    fn matches(&self, ranges: &[SkinRange<'_>]) -> bool {
        if self.ranges.len() != ranges.len() {
            return false;
        }
        let mut at = 0;
        for (range, &(len, _)) in ranges.iter().zip(&self.ranges) {
            if range.bindings.len() != len || !same_bits(range.bindings, &self.all[at..at + len]) {
                return false;
            }
            at += len;
        }
        true
    }
}

/// Whether two binding runs are the same **bits**, which is what the buffer
/// holds — `f32`'s `==` calls `-0.0` and `0.0` equal and a `NaN` unequal to
/// itself, which would skip an upload that changes the buffer and repeat one
/// that does not.
fn same_bits(a: &[SkinBinding], b: &[SkinBinding]) -> bool {
    a.len() == b.len()
        && a.iter().zip(b).all(|(a, b)| {
            a.joints == b.joints && a.weights.map(f32::to_bits) == b.weights.map(f32::to_bits)
        })
}

/// The highest joint index any slot of `range`'s bindings names, or the first
/// one past its palette, refused by name.
///
/// **The check the shader cannot make and `crcbl-scene` could not make
/// either** — see [`SkinningError::JointOutOfRange`]. Every slot of every
/// vertex, including the ones carrying zero weight: the shader reads all four
/// matrices before it scales any of them, so a weightless slot naming a joint
/// past the palette is the same clamped read as a weighted one.
fn highest_joint(index: usize, range: &SkinRange<'_>) -> Result<u32, SkinningError> {
    let mut highest = 0;
    for (vertex, binding) in range.bindings.iter().enumerate() {
        for (slot, joint) in binding.joints.iter().enumerate() {
            if *joint as usize >= range.palette.len() {
                return Err(SkinningError::JointOutOfRange {
                    range: index,
                    vertex,
                    slot,
                    joint: *joint,
                    palette: range.palette.len(),
                });
            }
            highest = highest.max(*joint);
        }
    }
    Ok(highest)
}

impl Skinning {
    /// Builds every buffer, every bind group and the skinning pipeline.
    ///
    /// # Errors
    ///
    /// [`SkinningError::Hal`] if a resource could not be created, and
    /// [`HalError::InvalidDescriptor`] through it for a descriptor asking for
    /// no frames, no ranges, no joints or no bindings — a buffer of zero bytes
    /// is not a buffer on any backend the engine targets.
    pub fn new(device: &dyn Device, desc: &SkinningDesc<'_>) -> Result<Self, SkinningError> {
        if desc.frames == 0 || desc.ranges == 0 || desc.joints == 0 || desc.bindings == 0 {
            return Err(HalError::InvalidDescriptor(
                "a skinning pass needs at least one frame in flight, one range, one palette \
                 matrix and one skin binding"
                    .to_string(),
            )
            .into());
        }
        let label = desc.label.unwrap_or("skinning");

        let mut rollback = Rollback::default();
        let result = Self::build(device, desc, label, &mut rollback);
        if result.is_err() {
            rollback.run(device);
        }
        result
    }

    fn build(
        device: &dyn Device,
        desc: &SkinningDesc<'_>,
        label: &str,
        rollback: &mut Rollback,
    ) -> Result<Self, SkinningError> {
        // `skinning.slang`'s declaration order, which
        // `crcbl_shaders::skinning`'s bind-group table records and
        // `crcbl_shaders::declaration_order` holds the shader to. The vertex
        // pool is the one writable entry.
        let entries = [
            uniform(0),
            storage(1, true, crcbl_shaders::skinning::JOINT_STRIDE as u32),
            storage(2, true, crcbl_shaders::skinning::SKIN_BINDING_STRIDE as u32),
            storage(3, false, UINT_STRIDE),
        ];
        let layout_desc = BindGroupLayoutDesc {
            label: Some(label),
            entries: &entries,
        };
        check_portable_storage_buffers(Some(label), &[&layout_desc])?;
        let layout = device.create_bind_group_layout(&layout_desc)?;
        rollback.layouts.push(layout);
        let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
            label: Some(label),
            bind_group_layouts: &[layout],
            push_constants: None,
        })?;
        rollback.pipeline_layouts.push(pipeline_layout);
        let pipeline = compute_pipeline(
            device,
            label,
            &crcbl_shaders::SKINNING,
            pipeline_layout,
            WORKGROUP_SIZE,
        )?;
        rollback.pipelines.push(pipeline);

        let mut palettes = Vec::with_capacity(desc.frames);
        let mut bindings = Vec::with_capacity(desc.frames);
        let mut params = Vec::with_capacity(desc.frames);
        let mut groups = Vec::with_capacity(desc.frames);
        for frame in 0..desc.frames {
            let mut buffer = |name: &str, size: u64, usage| {
                let handle = device.create_buffer(&BufferDesc {
                    label: Some(&format!("{label} {name} {frame}")),
                    size,
                    usage,
                    // Host-uploaded and bound **read-only**, which is what keeps
                    // them off `crate::draw_gen`'s device-local rule: D3D12
                    // refuses an unordered-access view of an upload heap, not a
                    // shader resource view of one. The one buffer a shader
                    // writes here is the vertex pool, and `crate::mesh_pool`
                    // already makes that device-local.
                    memory: MemoryLocation::HostUpload,
                })?;
                rollback.buffers.push(handle);
                Ok::<_, HalError>(handle)
            };
            let palette = buffer(
                "palette",
                u64::from(desc.joints) * JOINT_STRIDE as u64,
                BufferUsage::STORAGE,
            )?;
            let skin = buffer(
                "bindings",
                u64::from(desc.bindings) * SKIN_BINDING_STRIDE as u64,
                BufferUsage::STORAGE,
            )?;

            let mut frame_params = Vec::with_capacity(desc.ranges as usize);
            let mut frame_groups = Vec::with_capacity(desc.ranges as usize);
            for range in 0..desc.ranges {
                let block = buffer(
                    &format!("params {range}"),
                    PARAMS_SIZE as u64,
                    BufferUsage::UNIFORM,
                )?;
                let group = device.create_bind_group(&BindGroupDesc {
                    label: Some(&format!("{label} {frame} {range}")),
                    layout,
                    entries: &[
                        bound(0, block),
                        bound(1, palette),
                        bound(2, skin),
                        bound(3, desc.vertices),
                    ],
                    // No binding here is an array, so nothing has a runtime
                    // length to declare.
                    variable_count: None,
                })?;
                rollback.groups.push(group);
                frame_params.push(block);
                frame_groups.push(group);
            }

            palettes.push(palette);
            bindings.push(skin);
            params.push(frame_params);
            groups.push(frame_groups);
        }

        Ok(Self {
            palettes,
            bindings,
            params,
            groups,
            active: vec![Vec::new(); desc.frames],
            layout,
            pipeline_layout,
            pipeline,
            vertices: desc.vertices,
            attribute_base: desc.attribute_base,
            range_capacity: desc.ranges,
            joint_capacity: desc.joints,
            binding_capacity: desc.bindings,
            frames_begun: 0,
            latest: Bindings::default(),
            uploaded: vec![None; desc.frames],
        })
    }

    /// Ranges one frame can dispatch.
    #[must_use]
    pub const fn range_capacity(&self) -> u32 {
        self.range_capacity
    }

    /// Palette matrices one frame's joint buffer holds, across every range.
    #[must_use]
    pub const fn joint_capacity(&self) -> u32 {
        self.joint_capacity
    }

    /// Skin bindings one frame's binding buffer holds, across every range.
    #[must_use]
    pub const fn binding_capacity(&self) -> u32 {
        self.binding_capacity
    }

    /// Which half of every [`SkinnedRegion`] the frame most recently begun
    /// writes.
    ///
    /// Zero before the first [`begin_frame`](Self::begin_frame), which names a
    /// half no dispatch has filled — there is nothing to draw yet either way.
    #[must_use]
    pub const fn parity(&self) -> u32 {
        (self.frames_begun % 2) as u32
    }

    /// Validates `ranges`, alternates the ping-pong, and uploads the palette,
    /// one uniform block per range, and the skin bindings **if this slot does
    /// not already hold them**.
    ///
    /// Call once per frame, before [`Skinning::add_pass`], against the frame
    /// slot the instance pool rotated to. A frame with no skinned meshes calls
    /// it with an empty slice, which clears the slot's plan — otherwise the
    /// pass would re-dispatch the ranges of whichever frame last used it.
    ///
    /// # The bindings are uploaded when they change, into every slot
    ///
    /// A mesh's bindings are its own vertex data, so a frame normally hands
    /// over the very ones the frame before it did. This keeps the last
    /// accepted set and compares against it: an unchanged set is neither
    /// re-checked joint by joint nor re-written. A changed one is checked in
    /// full and given a new generation, and each slot's binding buffer is
    /// rewritten the next time that slot begins a frame — once per slot, so
    /// every frame in flight reads the set it was handed, whichever slot it
    /// landed in.
    ///
    /// # Errors
    ///
    /// [`SkinningError::JointOutOfRange`], [`SkinningError::EmptyPalette`],
    /// [`SkinningError::BindingCountMismatch`] and
    /// [`SkinningError::OverCapacity`] for inputs the dispatch could not be
    /// built from, all of them checked **before** anything is written, so a
    /// refused frame leaves the slot's buffers alone; and
    /// [`SkinningError::Hal`] if a write failed, after which the slot
    /// dispatches nothing until a later frame succeeds on it.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    pub fn begin_frame(
        &mut self,
        device: &dyn Device,
        frame: usize,
        ranges: &[SkinRange<'_>],
    ) -> Result<(), SkinningError> {
        if let Some(shapes) = self.check(ranges)? {
            let latest = &mut self.latest;
            latest.all.clear();
            for range in ranges {
                latest.all.extend_from_slice(range.bindings);
            }
            latest.ranges = shapes;
            latest.generation = latest.generation.wrapping_add(1);
        }

        // Cleared before anything is written rather than replaced after: a
        // write that fails part-way would otherwise leave this slot dispatching
        // the *previous* frame's plan against uniform blocks half of which have
        // already been overwritten, which is a mesh skinned onto another
        // instance's palette. Nothing dispatched is the honest outcome.
        self.active[frame].clear();

        // The ping-pong, and the only place it moves: one step per frame that
        // was accepted, so `parity` alternates and the half a frame did not
        // write is the half the frame before it did.
        self.frames_begun = self.frames_begun.wrapping_add(1);
        let parity = self.parity();

        let joints: usize = ranges.iter().map(|range| range.palette.len()).sum();
        let mut palette_bytes = Vec::with_capacity(joints * JOINT_STRIDE);
        let mut binding_base = 0u32;
        let mut plan = Vec::with_capacity(ranges.len());
        for (slot, range) in ranges.iter().enumerate() {
            let vertex_count = range.region.vertex_count();
            let block = Params {
                vertex_count,
                input_base: range.input_base,
                output_base: range.region.base(parity),
                binding_base,
                joint_base: (palette_bytes.len() / JOINT_STRIDE) as u32,
                joint_count: range.palette.len() as u32,
                attribute_base: self.attribute_base,
            };
            // `to_bytes` panics on an overlap and on an empty palette. Neither
            // can happen here: `check` refused the empty palette by name, and
            // the two runs are separate `MeshPool` allocations, which the free
            // list never hands out twice. It is the backstop, not the check.
            device.write_buffer(self.params[frame][slot], 0, &block.to_bytes())?;

            write_palette(&mut palette_bytes, range.palette);
            // `check` held the total to the binding capacity, which is a `u32`.
            binding_base += vertex_count;
            plan.push(Planned {
                groups: vertex_count.div_ceil(WORKGROUP_SIZE),
                region: range.region.halves(),
            });
        }

        if !palette_bytes.is_empty() {
            device.write_buffer(self.palettes[frame], 0, &palette_bytes)?;
        }
        let generation = self.latest.generation;
        if self.uploaded[frame] != Some(generation) {
            // Forgotten first, so a write that fails leaves the slot due for
            // another rather than claiming bytes it may only half hold.
            self.uploaded[frame] = None;
            if !self.latest.all.is_empty() {
                let bytes: Vec<u8> = self
                    .latest
                    .all
                    .iter()
                    .flat_map(SkinBinding::to_bytes)
                    .collect();
                device.write_buffer(self.bindings[frame], 0, &bytes)?;
            }
            self.uploaded[frame] = Some(generation);
        }
        self.active[frame] = plan;
        Ok(())
    }

    /// Everything [`begin_frame`](Self::begin_frame) refuses, checked before it
    /// writes anything.
    ///
    /// Returns each range's binding count and highest joint when the bindings
    /// differ from [`Skinning::latest`], and [`None`] when they are the same —
    /// whose joints were checked when they were accepted, so only the palette
    /// lengths, which do move, are tested against them again.
    fn check(&self, ranges: &[SkinRange<'_>]) -> Result<Option<Vec<(usize, u32)>>, SkinningError> {
        let over = |what, capacity, asked| SkinningError::OverCapacity {
            what,
            capacity,
            asked,
        };
        if ranges.len() as u64 > u64::from(self.range_capacity) {
            return Err(over("ranges", self.range_capacity, ranges.len() as u64));
        }

        let mut shapes = (!self.latest.matches(ranges)).then(|| Vec::with_capacity(ranges.len()));
        let mut joints = 0u64;
        let mut bindings = 0u64;
        for (index, range) in ranges.iter().enumerate() {
            if range.palette.is_empty() {
                return Err(SkinningError::EmptyPalette { range: index });
            }
            let vertices = range.region.vertex_count();
            if range.bindings.len() as u64 != u64::from(vertices) {
                return Err(SkinningError::BindingCountMismatch {
                    range: index,
                    vertices,
                    bindings: range.bindings.len(),
                });
            }
            match shapes.as_mut() {
                Some(shapes) => shapes.push((range.bindings.len(), highest_joint(index, range)?)),
                // The same bindings with a shorter palette still have to be
                // refused, and by name: the scan that names the vertex runs
                // only once the one comparison says it will find one.
                None if self.latest.ranges[index].1 as usize >= range.palette.len() => {
                    highest_joint(index, range)?;
                }
                None => {}
            }
            joints += range.palette.len() as u64;
            bindings += range.bindings.len() as u64;
        }
        if joints > u64::from(self.joint_capacity) {
            return Err(over("palette matrices", self.joint_capacity, joints));
        }
        if bindings > u64::from(self.binding_capacity) {
            return Err(over("skin bindings", self.binding_capacity, bindings));
        }
        Ok(shapes)
    }

    /// How many passes [`add_pass`](Self::add_pass) adds to a frame.
    ///
    /// **At most one**, not exactly one: a frame whose
    /// [`begin_frame`](Self::begin_frame) was handed no ranges adds nothing,
    /// because a pass with an empty body would still cost the vertex pool two
    /// barriers it has no use for.
    pub const MAX_PASSES: u32 = 1;

    /// Adds the skinning pass to `graph` and returns the vertex pool's id, or
    /// [`None`] when this frame has nothing to skin.
    ///
    /// The id is what a caller declaring its own read of the pool must use: the
    /// graph orders this pass against a mesh pass only when both name the
    /// **same** buffer node, and importing the pool twice would be two
    /// resources it cannot order against each other. So a mesh pass drawing
    /// skinned geometry passes this id to
    /// [`PassBuilder::read_buffer`](crate::graph::PassBuilder::read_buffer),
    /// and must be added after this.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    pub fn add_pass(&self, graph: &mut RenderGraph<'_>, frame: usize) -> Option<BufferId> {
        self.add_pass_where(graph, frame, |_| true)
    }

    /// The regions slot `frame`'s plan writes, in range order, each as
    /// [`SkinnedRegion::halves`] names it.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    pub(crate) fn planned_regions(&self, frame: usize) -> impl Iterator<Item = [u32; 2]> + '_ {
        self.active[frame].iter().map(|planned| planned.region)
    }

    /// [`add_pass`](Self::add_pass) dispatching only the ranges whose region
    /// `keep` answers `true` for — the renderer's skinning cull, see
    /// `ForwardRenderer::cull_skinned_regions`. A plan `keep` empties adds no
    /// pass and returns [`None`], on `add_pass`'s terms.
    ///
    /// **The plan is left as it is**: the palettes and blocks were uploaded by
    /// [`begin_frame`](Self::begin_frame), the parity has moved, and a range
    /// dropped here leaves both halves of its region holding what they held.
    /// What a draw out of such a region then reads is the caller's to make
    /// impossible.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    pub(crate) fn add_pass_where(
        &self,
        graph: &mut RenderGraph<'_>,
        frame: usize,
        keep: impl Fn([u32; 2]) -> bool,
    ) -> Option<BufferId> {
        let dispatches: Vec<(BindGroupHandle, u32)> = self.active[frame]
            .iter()
            .enumerate()
            .filter(|(_, planned)| keep(planned.region))
            .map(|(slot, planned)| (self.groups[frame][slot], planned.groups))
            .collect();
        if dispatches.is_empty() {
            return None;
        }

        // The pool arrives in the state `MeshPool::upload` left it in and the
        // state every mesh pass reads it in, which are the same one.
        let pool = graph.import_buffer(
            "vertex-pool",
            ImportedBuffer {
                buffer: self.vertices,
                initial: ResourceState::ShaderRead,
                final_state: ResourceState::ShaderRead,
            },
        );
        let pipeline = self.pipeline;
        let layout = self.pipeline_layout;
        graph
            .add_compute_pass("skinning")
            // One declaration for one binding: the bind pose is read and the
            // skinned run is written through the same descriptor, so there is
            // no read-only half to declare separately.
            .use_buffer(pool, ResourceState::ShaderReadWrite)
            .execute(move |ctx| {
                let encoder = ctx.encoder();
                encoder.bind_compute_pipeline(pipeline);
                for (group, groups) in dispatches {
                    encoder.bind_group(0, group, &[], layout);
                    encoder.dispatch(groups, 1, 1);
                }
            });
        Some(pool)
    }

    /// Releases everything, in dependency order. The device must be idle.
    ///
    /// The vertex pool is **not** released here: it is
    /// [`crate::mesh_pool`]'s, and this pass only ever borrowed the handle.
    pub fn destroy(self, device: &dyn Device) {
        device.destroy_compute_pipeline(self.pipeline);
        device.destroy_pipeline_layout(self.pipeline_layout);
        for group in self.groups.into_iter().flatten() {
            device.destroy_bind_group(group);
        }
        device.destroy_bind_group_layout(self.layout);
        for buffer in self
            .palettes
            .into_iter()
            .chain(self.bindings)
            .chain(self.params.into_iter().flatten())
        {
            device.destroy_buffer(buffer);
        }
    }
}

/// What a failed [`Skinning::new`] has to give back, in the order it must.
#[derive(Default)]
struct Rollback {
    pipelines: Vec<ComputePipelineHandle>,
    pipeline_layouts: Vec<PipelineLayoutHandle>,
    groups: Vec<BindGroupHandle>,
    layouts: Vec<BindGroupLayoutHandle>,
    buffers: Vec<BufferHandle>,
}

impl Rollback {
    fn run(self, device: &dyn Device) {
        for pipeline in self.pipelines {
            device.destroy_compute_pipeline(pipeline);
        }
        for layout in self.pipeline_layouts {
            device.destroy_pipeline_layout(layout);
        }
        for group in self.groups {
            device.destroy_bind_group(group);
        }
        for layout in self.layouts {
            device.destroy_bind_group_layout(layout);
        }
        for buffer in self.buffers {
            device.destroy_buffer(buffer);
        }
    }
}

// --- the oracle ------------------------------------------------------------

/// The matrix `computeMain` blends before it transforms anything: the four
/// palette matrices scaled by the four weights and summed.
///
/// **Blended first, transformed once** — the shader's own order, and for a
/// normal it is not the same answer as transforming four times and blending the
/// results. The kernel's header carries that argument.
///
/// `joints` are clamped against `palette.len() - 1` exactly as the shader
/// clamps them, so this reproduces what a malformed asset actually draws rather
/// than what it meant to.
///
/// # Panics
///
/// If `palette` is empty, which is the clamp's `joint_count - 1` wrapping and
/// what [`Params::to_bytes`](crcbl_shaders::skinning::Params::to_bytes) refuses
/// on the buffer side.
#[must_use]
pub fn blend(palette: &[Mat4], binding: &SkinBinding) -> Mat4 {
    assert!(
        !palette.is_empty(),
        "a skinned vertex with an empty joint palette has nothing to blend onto, and the \
         shader's index clamp would wrap"
    );
    let last = palette.len() - 1;
    let mut blended = Mat4::ZERO;
    for slot in 0..JOINTS_PER_VERTEX {
        let joint = (binding.joints[slot] as usize).min(last);
        blended += palette[joint] * binding.weights[slot];
    }
    blended
}

/// The matrix that carries a normal through the linear part `basis` carries a
/// tangent through: the **cofactor** matrix, matching `normal_basis` in
/// `crates/crcbl-shaders/shaders/skinning.slang` term for term.
///
/// Row `i` is the cross product of the other two rows in cyclic order, which is
/// `det(basis)` times the inverse transpose. A normal is perpendicular to a
/// surface and only an angle-preserving transform carries a perpendicular the
/// way it carries a tangent, so the bare 3×3 is the wrong matrix the moment a
/// joint carries a non-uniform scale.
///
/// The cross-product form rather than `inverse().transpose() * determinant()`:
/// it is what the shader computes, and it is defined for a singular basis —
/// where the inverse is not, and where a blend of joints can genuinely land.
#[must_use]
pub fn normal_basis(basis: Mat3) -> Mat3 {
    let (first, second, third) = (basis.row(0), basis.row(1), basis.row(2));
    // The three cross products are the cofactor's *rows*, and `from_cols` takes
    // columns — so this builds the transpose and puts it back.
    Mat3::from_cols(second.cross(third), third.cross(first), first.cross(second)).transpose()
}

/// One vertex as `computeMain` writes it: the oracle a readback compares
/// against.
///
/// Ordinary Rust, and nothing in a frame calls it — [`crate::cull`]'s
/// [`visible_instances`](crate::cull::visible_instances) is the same shape for
/// the same reason. A dispatch that runs and writes a buffer nobody reads is
/// indistinguishable from one that does nothing.
///
/// Everything the kernel does, in the order it does it:
///
/// * the four palette matrices are blended by the four weights, **used exactly
///   as stored and never renormalised** — a set summing to 0.9 pulls its vertex
///   a tenth of the way to the palette's origin, which is the loudest failure
///   available and what the shader deliberately keeps;
/// * the position goes through the blended matrix;
/// * the normal goes through [`normal_basis`] of its linear part, and is
///   normalised **only if it is non-zero** — the shader's guard, whose fallback
///   is the bind-pose normal, because a `NaN` written into the pool is read
///   again by the shadow passes;
/// * the tangent goes through the **bare** linear part, because a tangent lies
///   in the surface where a normal is perpendicular to it, and is then
///   Gram-Schmidted against the posed normal — a quaternion is three axes at
///   right angles, and a shearing blend leaves the pair at some other one;
/// * the handedness is the bind pose's, carried rather than re-derived: it is
///   a property of the UV parameterisation, which no pose changes;
/// * `uv0`, `uv1` and `color` are copied through, because the destination is a
///   different range of the pool and a field left alone is a field holding
///   whatever the allocator last put there.
///
/// # Panics
///
/// If `palette` is empty — see [`blend`].
#[must_use]
pub fn skin_vertex(palette: &[Mat4], binding: &SkinBinding, vertex: &MeshVertex) -> MeshVertex {
    let blended = blend(palette, binding);
    let position = blended * Vec4::from((Vec3::from_array(vertex.position), 1.0));
    let bind_pose = vertex.qtangent.decode();
    let bind_normal = Vec3::from_array(bind_pose.normal);
    let bind_tangent = Vec3::from_array(bind_pose.tangent);

    let carried = normal_basis(Mat3::from_mat4(blended)) * bind_normal;
    let square_length = carried.dot(carried);
    let normal = if square_length > 0.0 {
        carried / square_length.sqrt()
    } else {
        bind_normal
    };
    let projected = {
        let moved = Mat3::from_mat4(blended) * bind_tangent;
        moved - normal * normal.dot(moved)
    };
    let square_length = projected.dot(projected);
    let tangent = if square_length > 0.0 {
        projected / square_length.sqrt()
    } else {
        bind_tangent
    };
    let handedness = Vec3::from_array(bind_pose.normal)
        .cross(bind_tangent)
        .dot(Vec3::from_array(bind_pose.bitangent));
    MeshVertex {
        position: [position.x, position.y, position.z],
        qtangent: QTangent::encode(TangentFrame {
            tangent: tangent.to_array(),
            bitangent: (normal.cross(tangent) * if handedness < 0.0 { -1.0 } else { 1.0 })
                .to_array(),
            normal: normal.to_array(),
        }),
        uv0: vertex.uv0,
        uv1: vertex.uv1,
        color: vertex.color,
    }
}

/// Appends `palette` to `out` as the shader reads it: each matrix's columns,
/// one after another, every `f32` little-endian.
///
/// A little-endian target's native bytes already are that, so each matrix
/// goes in as one slice rather than a float at a time; a big-endian target
/// swaps each float explicitly.
fn write_palette(out: &mut Vec<u8>, palette: &[Mat4]) {
    for matrix in palette {
        let columns = matrix.to_cols_array();
        #[cfg(target_endian = "little")]
        out.extend_from_slice(bytemuck::cast_slice(&columns));
        #[cfg(target_endian = "big")]
        for value in columns {
            out.extend_from_slice(&value.to_le_bytes());
        }
    }
}

// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use crcbl_shaders::vertex::UvRange;

    use crcbl_hal::null::{Command, Event, NullInstance, Recorder};
    use crcbl_hal::{CommandEncoderDesc, DeviceDesc, Instance, QueueHandle, QueueKind};
    use crcbl_shaders::mesh::VERTEX_STRIDE;

    use super::*;
    use crate::mesh_pool::{MeshPoolDesc, MeshUpload};
    use crate::transient::TransientPool;

    fn open() -> (Recorder, Box<dyn Device>, QueueHandle) {
        let recorder = Recorder::new();
        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
        let adapter = instance.adapters().remove(0);
        let device = instance
            .create_device(&DeviceDesc::for_adapter(adapter.id))
            .expect("the null backend always opens");
        let queue = device.queue(QueueKind::Graphics).expect("always present");
        (recorder, device, queue)
    }

    /// A pool wide enough for every reservation the tests below make, unless
    /// one is asking for the exhausted case on purpose.
    fn pool(device: &dyn Device, vertices: u32) -> MeshPool {
        MeshPool::new(
            device,
            &MeshPoolDesc {
                label: Some("skinning test"),
                vertex_capacity: vertices,
                index_capacity: 64,
                mesh_capacity: 4,
            },
        )
        .expect("the null backend accepts every descriptor")
    }

    /// A skinning pass over `pool`'s vertex buffer, sized for the frame the
    /// caller is about to build.
    fn skinning(
        device: &dyn Device,
        pool: &MeshPool,
        ranges: u32,
        joints: u32,
        bindings: u32,
    ) -> Skinning {
        Skinning::new(
            device,
            &SkinningDesc {
                label: Some("skinning test"),
                frames: 2,
                ranges,
                joints,
                bindings,
                vertices: pool.vertex_buffer(),
                attribute_base: pool.attribute_base(),
            },
        )
        .expect("the null backend accepts every descriptor")
    }

    /// `n` skin bindings, every vertex bound wholly to joint 0.
    fn rigid(n: usize) -> Vec<SkinBinding> {
        vec![
            SkinBinding {
                joints: [0; JOINTS_PER_VERTEX],
                weights: [1.0, 0.0, 0.0, 0.0],
            };
            n
        ]
    }

    /// Compiles and executes a one-pass graph over `frame`, so the recorder
    /// holds the commands the pass body really recorded.
    ///
    /// The encoder is **finished**, because the null backend buffers a command
    /// stream and hands it to the recorder there — a test that skipped it would
    /// read an empty command list and pass whatever the body did.
    fn run(
        recorder: &Recorder,
        device: &dyn Device,
        queue: QueueHandle,
        pass: &Skinning,
        frame: usize,
    ) {
        let mut transients = TransientPool::new();
        let mut graph = RenderGraph::new(queue);
        pass.add_pass(&mut graph, frame);
        let compiled = graph.compile(&transients).expect("a legal frame");
        let mut encoder = device.create_command_encoder(&CommandEncoderDesc {
            label: Some("skinning"),
            queue,
        });
        compiled
            .execute(device, &mut transients, encoder.as_mut(), None)
            .expect("the graph executed");
        let commands = encoder.finish().expect("a legal command stream");
        device.destroy_command_buffer(commands);
        // A dispatch outside a compute pass, a group bound to a dead object, a
        // binding wider than the device allows: the null backend records each
        // of those rather than refusing, so a test that never asked would pass
        // over a command stream Vulkan rejects.
        recorder.assert_valid();
    }

    /// Every `dispatch`'s group count, in the order they were recorded.
    fn dispatches(recorder: &Recorder) -> Vec<u32> {
        recorder
            .commands()
            .into_iter()
            .filter_map(|command| match command {
                Command::Dispatch { x, y, z } => {
                    assert_eq!((y, z), (1, 1), "the kernel is one-dimensional");
                    Some(x)
                }
                _ => None,
            })
            .collect()
    }

    /// The six words of a range's uniform block, read back out of the bytes
    /// that actually reached the buffer rather than mirrored from the inputs.
    fn params_of(recorder: &Recorder, pass: &Skinning, frame: usize, slot: usize) -> Params {
        let bytes = recorder
            .buffer_bytes(pass.params[frame][slot])
            .expect("the block is live");
        assert_eq!(bytes.len(), PARAMS_SIZE);
        let word = |at: usize| {
            u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four bytes of a word"))
        };
        Params {
            vertex_count: word(0),
            input_base: word(4),
            output_base: word(8),
            binding_base: word(12),
            joint_base: word(16),
            joint_count: word(20),
            attribute_base: word(24),
        }
    }

    // --- the drawable region -------------------------------------------------

    /// **Releasing a skinned mesh gives back the region**, and the space is
    /// reusable straight away.
    ///
    /// The second reservation is what says the vertices really came back rather
    /// than only that the free counter moved: a pool sized for one region and
    /// its source refuses the second reserve outright if the first leaked.
    #[test]
    fn releasing_a_skinned_mesh_returns_its_region() {
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut pool = pool(device, 64);
        const VERTICES: u32 = 8;
        let source = pool
            .upload(
                device,
                queue,
                &MeshUpload {
                    label: "source",
                    vertices: &vec![0u8; VERTICES as usize * VERTEX_STRIDE],
                    indices: &[0, 1, 2],
                    uv_range: UvRange::default(),
                    flags: 0,
                },
            )
            .expect("the pool has room");
        pool.flush(device).expect("the null backend completes it");
        let (free_before, _) = pool.vertex_space();

        let skinned = SkinnedMesh::reserve(&mut pool, source).expect("room for two halves");
        assert_eq!(
            skinned.vertex_count(),
            VERTICES,
            "each half is as long as the bind pose it deforms"
        );
        assert_eq!(
            skinned.input_base(),
            pool.mesh(source).expect("resident").base_vertex,
            "the range reads the bind pose where the pool put it"
        );
        assert_eq!(
            skinned.mesh_id(),
            source.index(),
            "a skinned instance names the mesh it was deformed from, so the bucket, the \
             level tables and the bounding box all resolve as the source's"
        );
        assert_eq!(
            pool.vertex_space().0,
            free_before - 2 * VERTICES,
            "two halves are taken, not one"
        );

        skinned.release(&mut pool);
        assert_eq!(
            pool.vertex_space().0,
            free_before,
            "the region goes back whole, and the free list coalesces it"
        );

        let again = SkinnedMesh::reserve(&mut pool, source).expect("the vertices came back");
        again.release(&mut pool);
        pool.destroy(device);
        recorder.assert_valid();
    }

    /// **A reservation takes no mesh-table entry**, so a pool whose table has no
    /// spare slot at all can still hold a skinned mesh.
    ///
    /// The table below has exactly one entry and the source mesh occupies it.
    /// Before 2026-08 this call took two more and a table of one refused it;
    /// what says the mechanism is gone rather than merely unused is that the
    /// reservation now succeeds here.
    #[test]
    fn a_reservation_needs_no_spare_table_entry() {
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut pool = MeshPool::new(
            device,
            &MeshPoolDesc {
                label: Some("no spare entry"),
                vertex_capacity: 64,
                index_capacity: 64,
                mesh_capacity: 1,
            },
        )
        .expect("the null backend accepts every descriptor");
        let source = pool
            .upload(
                device,
                queue,
                &MeshUpload {
                    label: "source",
                    vertices: &vec![0u8; 8 * VERTEX_STRIDE],
                    indices: &[0, 1, 2],
                    uv_range: UvRange::default(),
                    flags: 0,
                },
            )
            .expect("the pool has room");
        pool.flush(device).expect("the null backend completes it");

        let skinned = SkinnedMesh::reserve(&mut pool, source)
            .expect("a region is vertices, and the table is untouched");
        assert_eq!(
            skinned.mesh_id(),
            source.index(),
            "and the entry it draws through is the one the source already had"
        );
        skinned.release(&mut pool);

        pool.destroy(device);
        recorder.assert_valid();
    }

    /// A reservation the vertex pool has no room for leaks nothing.
    ///
    /// The half-and-then-refused path in [`SkinnedRegion::reserve`], reached
    /// through the call that wraps it: a pool with room for one half and not two
    /// must come back with its free list exactly as it was.
    #[test]
    fn a_refused_region_gives_back_the_half_it_took() {
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        const VERTICES: u32 = 8;
        let mut pool = MeshPool::new(
            device,
            &MeshPoolDesc {
                label: Some("room for one half"),
                vertex_capacity: 2 * VERTICES + VERTICES / 2,
                index_capacity: 64,
                mesh_capacity: 4,
            },
        )
        .expect("the null backend accepts every descriptor");
        let source = pool
            .upload(
                device,
                queue,
                &MeshUpload {
                    label: "source",
                    vertices: &vec![0u8; VERTICES as usize * VERTEX_STRIDE],
                    indices: &[0, 1, 2],
                    uv_range: UvRange::default(),
                    flags: 0,
                },
            )
            .expect("the pool has room");
        pool.flush(device).expect("the null backend completes it");
        let space = pool.vertex_space();

        let refused = SkinnedMesh::reserve(&mut pool, source);
        assert!(
            refused.is_err(),
            "the pool has room for one half of the region and not for two: {refused:?}"
        );
        assert_eq!(
            pool.vertex_space(),
            space,
            "a refused reservation leaks no pool space"
        );

        pool.destroy(device);
        recorder.assert_valid();
    }

    // --- the oracle ---------------------------------------------------------

    /// A vertex, distinct in every field so a copy landing in the wrong lane
    /// could not compare equal by accident.
    fn vertex(position: Vec3, normal: Vec3) -> MeshVertex {
        MeshVertex::from_normal(
            position.to_array(),
            normal.to_array(),
            [0.25, 0.5, 0.75, 1.0],
            [0.125, 0.375],
            &UvRange {
                scale: [1.0, 1.0],
                offset: [0.0, 0.0],
            },
        )
    }

    /// The normal a vertex's frame decodes to — what the tests below compare,
    /// since the record carries a quaternion rather than a normal.
    fn normal_of(vertex: &MeshVertex) -> Vec3 {
        Vec3::from_array(vertex.qtangent.decode().normal)
    }

    /// **A vertex whose weight is entirely on one joint is transformed
    /// exactly** — the kernel's own claim, and the one case where linear blend
    /// skinning owes an exact answer rather than an approximation.
    ///
    /// Exact equality rather than a tolerance, and it is not a lucky one: the
    /// blend is `M * 1.0` plus three `M * 0.0`, and adding a zero matrix to a
    /// finite one changes no bit.
    #[test]
    fn a_vertex_bound_wholly_to_one_joint_is_transformed_exactly() {
        let joint = Mat4::from_rotation_translation(
            glam::Quat::from_rotation_z(core::f32::consts::FRAC_PI_3),
            Vec3::new(2.0, -3.0, 0.5),
        );
        let palette = [Mat4::IDENTITY, joint];
        let binding = SkinBinding {
            joints: [1, 0, 0, 0],
            weights: [1.0, 0.0, 0.0, 0.0],
        };
        let bind_pose = vertex(Vec3::new(1.0, 2.0, 3.0), Vec3::Y);

        let skinned = skin_vertex(&palette, &binding, &bind_pose);

        let expected = joint * Vec4::new(1.0, 2.0, 3.0, 1.0);
        assert_eq!(
            skinned.position,
            [expected.x, expected.y, expected.z],
            "a rigidly bound vertex is the joint's transform of it and nothing else"
        );
        // A rotation is its own cofactor to within rounding, so the normal is
        // the rotated one; the tolerance is the normalise, not the blend.
        let want = Mat3::from_mat4(joint) * Vec3::Y;
        let got = normal_of(&skinned);
        for (got, want) in got.to_array().iter().zip(want.to_array()) {
            assert!(
                (got - want).abs() <= QTangent::MAX_COMPONENT_ERROR,
                "a rigidly bound normal is the joint's rotation of it: {got:?} against {want}"
            );
        }
        assert_eq!(skinned.color, bind_pose.color, "colour is copied through");
        assert_eq!(skinned.uv0, bind_pose.uv0, "uv is copied through");
        assert_eq!(skinned.uv1, bind_pose.uv1, "and the second set with it");
    }

    /// A vertex blended across two joints, against the value worked out by
    /// hand.
    ///
    /// Two pure translations and weights of a quarter and three quarters —
    /// both exact in binary, and both linear parts identity — so the blended
    /// matrix is the identity with `0.25 * t0 + 0.75 * t1` in its translation
    /// and the answer has no rounding in it at all.
    #[test]
    fn a_vertex_blended_across_two_joints_is_the_weighted_sum_of_both() {
        let palette = [
            Mat4::from_translation(Vec3::new(4.0, 0.0, 0.0)),
            Mat4::from_translation(Vec3::new(0.0, 8.0, 0.0)),
        ];
        let binding = SkinBinding {
            joints: [0, 1, 0, 0],
            weights: [0.25, 0.75, 0.0, 0.0],
        };
        let bind_pose = vertex(Vec3::new(1.0, 1.0, 1.0), Vec3::Z);

        let skinned = skin_vertex(&palette, &binding, &bind_pose);

        assert_eq!(
            skinned.position,
            [1.0 + 0.25 * 4.0, 1.0 + 0.75 * 8.0, 1.0],
            "a quarter of the first joint's translation and three quarters of the second's"
        );
        assert_eq!(
            skinned.qtangent, bind_pose.qtangent,
            "a blend of translations has an identity linear part, so the frame is unmoved — \
             and lane for lane, because the re-encode is the same arithmetic on the same frame"
        );
    }

    /// **A normal under a joint carrying a non-uniform scale goes through the
    /// cofactor matrix, and the bare 3×3 is a different vector.**
    ///
    /// The case the cofactor exists for: a scale of `(4, 1, 1)` stretches a
    /// 45° normal *toward* the stretched axis if it is carried like a tangent,
    /// and the surface's perpendicular tilts the other way. Both halves are
    /// asserted, because "it used the cofactor" is only evidence if the bare
    /// basis would have given something else.
    #[test]
    fn a_normal_under_a_non_uniform_scale_goes_through_the_cofactor_not_the_basis() {
        let scale = Mat4::from_scale(Vec3::new(4.0, 1.0, 1.0));
        let palette = [scale];
        let binding = SkinBinding {
            joints: [0, 0, 0, 0],
            weights: [1.0, 0.0, 0.0, 0.0],
        };
        let diagonal = Vec3::new(1.0, 1.0, 0.0).normalize();
        let skinned = skin_vertex(&palette, &binding, &vertex(Vec3::X, diagonal));

        // Cofactor of diag(4,1,1) is diag(1, 4, 4), so the normal tilts away
        // from x; the bare basis is diag(4,1,1) and tilts toward it.
        let through_cofactor = (Vec3::new(1.0, 4.0, 0.0)).normalize();
        let through_basis = (Vec3::new(4.0, 1.0, 0.0)).normalize();
        let got = normal_of(&skinned);
        assert!(
            (got - through_cofactor).length() <= QTangent::MAX_COMPONENT_ERROR,
            "{got:?} is not the cofactor's answer {through_cofactor:?}"
        );
        assert!(
            (got - through_basis).length() > 0.5,
            "the bare basis would have given {through_basis:?}, which is not far from {got:?} — \
             this test would pass with the wrong matrix"
        );
        assert!(
            (got.length() - 1.0).abs() <= QTangent::MAX_COMPONENT_ERROR,
            "the shader normalises, so the written normal is unit length"
        );
    }

    /// The cross-product form and the textbook one agree wherever the textbook
    /// one is defined.
    ///
    /// The shader is written in cross products because they are defined for a
    /// singular basis, where `inverse()` is not — so this is what says the two
    /// are the same matrix and not merely two plausible ones.
    #[test]
    fn the_cofactor_matches_the_inverse_transpose_scaled_by_the_determinant() {
        for basis in [
            Mat3::from_mat4(Mat4::from_scale(Vec3::new(2.0, 3.0, 0.5))),
            Mat3::from_rotation_y(0.7) * Mat3::from_diagonal(Vec3::new(1.0, 4.0, 0.25)),
            // A mirrored basis: negative determinant, which is the case
            // `graphitemaster/normals_revisited` is about.
            Mat3::from_diagonal(Vec3::new(-1.0, 2.0, 3.0)),
        ] {
            let textbook = basis.inverse().transpose() * basis.determinant();
            let cofactor = normal_basis(basis);
            for (got, want) in cofactor
                .to_cols_array()
                .iter()
                .zip(textbook.to_cols_array())
            {
                assert!(
                    (got - want).abs() < 1e-4,
                    "{cofactor:?} is not {textbook:?} for basis {basis:?}"
                );
            }
        }
    }

    /// A blend that collapses to nothing keeps the bind-pose normal rather
    /// than writing a `NaN` into the pool.
    ///
    /// The shader's guarded normalise, and it is guarded because the geometry
    /// it would poison is read again by the shadow passes: a `NaN` position
    /// makes triangles vanish rather than making anything report an error.
    #[test]
    fn a_blend_that_collapses_to_zero_keeps_the_bind_pose_normal() {
        let palette = [Mat4::IDENTITY];
        let binding = SkinBinding {
            joints: [0; JOINTS_PER_VERTEX],
            weights: [0.0; JOINTS_PER_VERTEX],
        };
        let bind_pose = vertex(Vec3::new(1.0, 2.0, 3.0), Vec3::Y);

        let skinned = skin_vertex(&palette, &binding, &bind_pose);

        assert_eq!(
            skinned.position,
            [0.0, 0.0, 0.0],
            "no weight at all puts the vertex at the palette's origin"
        );
        assert_eq!(
            skinned.qtangent, bind_pose.qtangent,
            "and the frame is the bind pose's, finite and already orthonormal"
        );
        assert!(
            normal_of(&skinned)
                .to_array()
                .iter()
                .all(|value| value.is_finite()),
            "nothing written into the vertex pool may be NaN"
        );
    }

    /// Weights that do not sum to one deflate their vertex toward the
    /// palette's origin, which is the failure the kernel deliberately keeps.
    ///
    /// Renormalising here would be this engine overruling
    /// `crcbl_scene::GltfPrimitive::weights`, which reports them as the file
    /// stored them so that a file whose weights do not sum is one whose author
    /// hears about it.
    #[test]
    fn weights_that_do_not_sum_to_one_deflate_the_vertex_rather_than_being_renormalised() {
        let palette = [Mat4::IDENTITY];
        let binding = SkinBinding {
            joints: [0; JOINTS_PER_VERTEX],
            weights: [0.9, 0.0, 0.0, 0.0],
        };
        let skinned = skin_vertex(
            &palette,
            &binding,
            &vertex(Vec3::new(10.0, 0.0, 0.0), Vec3::Y),
        );
        assert_eq!(
            skinned.position[0], 9.0,
            "a tenth of the way toward the origin, not renormalised back out to 10"
        );
    }

    /// A joint index past the palette is clamped the way the shader clamps it
    /// — so the oracle predicts what a malformed asset really draws, not what
    /// it meant to.
    #[test]
    fn a_joint_index_past_the_palette_is_clamped_the_way_the_shader_clamps_it() {
        let palette = [
            Mat4::from_translation(Vec3::X),
            Mat4::from_translation(Vec3::Y),
        ];
        let past = SkinBinding {
            joints: [99, 0, 0, 0],
            weights: [1.0, 0.0, 0.0, 0.0],
        };
        let last = SkinBinding {
            joints: [1, 0, 0, 0],
            weights: [1.0, 0.0, 0.0, 0.0],
        };
        let bind_pose = vertex(Vec3::ZERO, Vec3::Y);
        assert_eq!(
            skin_vertex(&palette, &past, &bind_pose).position,
            skin_vertex(&palette, &last, &bind_pose).position,
            "an out-of-range index resolves to the palette's last matrix"
        );
    }

    // --- the transient region ----------------------------------------------

    /// **The two halves alternate with the parity, and the one a frame does
    /// not write is the one the frame before it did.**
    ///
    /// This is the animation plan's 2026-07-27 correction as an
    /// assertion. A region that answered the same base for both parities would
    /// be a single-buffered one wearing the API of a double-buffered one, and
    /// nothing else in the tree would notice until TAA arrived.
    #[test]
    fn a_regions_two_halves_alternate_with_the_parity() {
        let (_recorder, device, _queue) = open();
        let mut pool = pool(device.as_ref(), 64);
        let region = SkinnedRegion::reserve(&mut pool, 8).expect("room for both halves");

        assert_ne!(
            region.base(0),
            region.base(1),
            "the two parities must name different runs, or the previous frame's skinned \
             positions are this frame's"
        );
        assert_eq!(region.base(0), region.previous_base(1));
        assert_eq!(region.base(1), region.previous_base(0));
        // The parity is a bit, so every even frame index is one half.
        assert_eq!(region.base(2), region.base(0));
        assert_eq!(region.base(3), region.base(1));
        assert_eq!(region.vertex_count(), 8);
    }

    /// Neither half overlaps the other, and neither overlaps the bind pose —
    /// which is the precondition
    /// [`Params::to_bytes`](crcbl_shaders::skinning::Params::to_bytes) panics
    /// on and which the allocator is what actually makes true.
    ///
    /// The bind pose here is a **real upload**, not a second reservation, so
    /// the claim is about the pool the renderer uses rather than about the free
    /// list in isolation.
    #[test]
    fn a_regions_halves_never_overlap_each_other_or_the_bind_pose() {
        let (_recorder, device, queue) = open();
        let mut pool = pool(device.as_ref(), 64);
        let count = 6u32;
        let handle = pool
            .upload(
                device.as_ref(),
                queue,
                &MeshUpload {
                    label: "bind pose",
                    vertices: &vec![0u8; count as usize * VERTEX_STRIDE],
                    indices: &[0, 1, 2],
                    uv_range: UvRange::default(),
                    flags: 0,
                },
            )
            .expect("room in both pools");
        pool.flush(device.as_ref()).expect("the null backend lands");
        let bind_pose = pool.mesh(handle).expect("resident").base_vertex;

        let region = SkinnedRegion::reserve(&mut pool, count).expect("room for both halves");
        let runs = [
            bind_pose..bind_pose + count,
            region.base(0)..region.base(0) + count,
            region.base(1)..region.base(1) + count,
        ];
        for (index, run) in runs.iter().enumerate() {
            for other in &runs[index + 1..] {
                assert!(
                    run.end <= other.start || other.end <= run.start,
                    "{run:?} overlaps {other:?}; one invocation would read a vertex another had \
                     already overwritten"
                );
            }
        }
        // And the block the pass would build from them is one `to_bytes`
        // accepts, on either parity.
        for parity in [0, 1] {
            let _ = Params {
                vertex_count: count,
                input_base: bind_pose,
                output_base: region.base(parity),
                binding_base: 0,
                joint_base: 0,
                joint_count: 1,
                attribute_base: 0,
            }
            .to_bytes();
        }
    }

    /// Releasing gives both halves back, so a pool that held one region can
    /// hold the next.
    #[test]
    fn a_released_region_gives_both_halves_back() {
        let (_recorder, device, _queue) = open();
        let mut pool = pool(device.as_ref(), 16);
        let before = pool.vertex_space();
        let region = SkinnedRegion::reserve(&mut pool, 8).expect("exactly fits");
        assert_eq!(pool.vertex_space().0, 0, "both halves are taken");
        region.release(&mut pool);
        assert_eq!(
            pool.vertex_space(),
            before,
            "everything is free again, and in one block"
        );
        SkinnedRegion::reserve(&mut pool, 8).expect("the space really came back");
    }

    /// A pool with room for one half and not two gives the first one back
    /// rather than leaking it.
    ///
    /// The half-allocated failure is the one a rollback is written for, and it
    /// is invisible without this: the reservation succeeds, the error is
    /// returned, and the pool is quietly smaller for the rest of the process.
    #[test]
    fn a_pool_with_room_for_one_half_gives_it_back_rather_than_leaking_it() {
        let (_recorder, device, _queue) = open();
        let mut pool = pool(device.as_ref(), 8);
        let before = pool.vertex_space();
        let error = SkinnedRegion::reserve(&mut pool, 6).expect_err("no room for twelve vertices");
        assert!(
            matches!(error, MeshPoolError::PoolExhausted { .. }),
            "{error} does not name the exhausted pool"
        );
        assert_eq!(
            pool.vertex_space(),
            before,
            "the first half must have gone back"
        );
    }

    /// A reservation of nothing is refused by its own name.
    #[test]
    fn a_region_of_no_vertices_is_refused() {
        let (_recorder, device, _queue) = open();
        let mut pool = pool(device.as_ref(), 8);
        let error = SkinnedRegion::reserve(&mut pool, 0).expect_err("no address to hand back");
        assert!(
            matches!(error, MeshPoolError::EmptyReservation),
            "{error} does not name the empty reservation"
        );
    }

    // --- the pass ------------------------------------------------------------

    /// **The dispatch covers every vertex and no more.**
    ///
    /// One invocation is one vertex and the division rounds up, so a count that
    /// is not a multiple of the workgroup size still gets a whole last group —
    /// whose tail the shader discards itself. A dispatch sized with a truncating
    /// divide skins a *prefix* of the mesh, which reads as a rigging mistake
    /// rather than as a dispatch that was too short.
    #[test]
    fn the_dispatch_covers_every_vertex_and_no_more() {
        for count in [1u32, 63, 64, 65, 127, 128, 200] {
            let (recorder, device, queue) = open();
            let mut pool = pool(device.as_ref(), count * 2 + 1);
            let region = SkinnedRegion::reserve(&mut pool, count).expect("room");
            let mut pass = skinning(device.as_ref(), &pool, 1, 2, count);
            let bindings = rigid(count as usize);
            pass.begin_frame(
                device.as_ref(),
                0,
                &[SkinRange {
                    input_base: 0,
                    region: &region,
                    palette: &[Mat4::IDENTITY, Mat4::IDENTITY],
                    bindings: &bindings,
                }],
            )
            .expect("a legal frame");
            run(&recorder, device.as_ref(), queue, &pass, 0);

            let groups = dispatches(&recorder);
            assert_eq!(groups.len(), 1, "one range is one dispatch");
            assert_eq!(
                groups[0],
                count.div_ceil(WORKGROUP_SIZE),
                "{count} vertices at {WORKGROUP_SIZE} per group"
            );
            assert!(
                u64::from(groups[0]) * u64::from(WORKGROUP_SIZE) >= u64::from(count),
                "{count} vertices need at least that many invocations, and {} groups give {}",
                groups[0],
                u64::from(groups[0]) * u64::from(WORKGROUP_SIZE)
            );
            pass.destroy(device.as_ref());
            region.release(&mut pool);
            pool.destroy(device.as_ref());
        }
    }

    /// Three ranges are three dispatches, in the order they were handed over,
    /// each against its own bind group.
    #[test]
    fn every_range_gets_its_own_dispatch_and_its_own_bind_group() {
        let (recorder, device, queue) = open();
        let mut pool = pool(device.as_ref(), 64);
        let counts = [1u32, 2, 3];
        let regions: Vec<SkinnedRegion> = counts
            .iter()
            .map(|count| SkinnedRegion::reserve(&mut pool, *count).expect("room"))
            .collect();
        let mut pass = skinning(device.as_ref(), &pool, 3, 6, 8);
        let bindings: Vec<Vec<SkinBinding>> =
            counts.iter().map(|count| rigid(*count as usize)).collect();
        let ranges: Vec<SkinRange<'_>> = (0..3)
            .map(|index| SkinRange {
                input_base: 32 + index as u32,
                region: &regions[index],
                palette: &[Mat4::IDENTITY, Mat4::IDENTITY],
                bindings: &bindings[index],
            })
            .collect();
        pass.begin_frame(device.as_ref(), 1, &ranges)
            .expect("a legal frame");
        run(&recorder, device.as_ref(), queue, &pass, 1);

        assert_eq!(dispatches(&recorder), vec![1, 1, 1], "three ranges");
        let bound: Vec<_> = recorder
            .commands()
            .into_iter()
            .filter_map(|command| match command {
                Command::BindGroup { group, .. } => Some(group),
                _ => None,
            })
            .collect();
        assert_eq!(
            bound, pass.groups[1],
            "each dispatch is preceded by that range's own group, in range order"
        );
    }

    /// **The uniform block names this frame's half**, and the next frame's
    /// names the other one.
    ///
    /// Read back out of the buffer the pass wrote rather than recomputed, so
    /// this is evidence about the upload and not about the plan repeating
    /// itself.
    #[test]
    fn the_params_block_names_this_frames_half_and_the_next_frames_names_the_other() {
        let (recorder, device, _queue) = open();
        let mut pool = pool(device.as_ref(), 64);
        let region = SkinnedRegion::reserve(&mut pool, 5).expect("room");
        let mut pass = skinning(device.as_ref(), &pool, 1, 3, 5);
        let bindings = rigid(5);
        let palette = [Mat4::IDENTITY; 3];

        let mut seen = Vec::new();
        for frame in [0usize, 1] {
            pass.begin_frame(
                device.as_ref(),
                frame,
                &[SkinRange {
                    input_base: 40,
                    region: &region,
                    palette: &palette,
                    bindings: &bindings,
                }],
            )
            .expect("a legal frame");
            let block = params_of(&recorder, &pass, frame, 0);
            assert_eq!(
                block,
                Params {
                    vertex_count: 5,
                    input_base: 40,
                    output_base: region.base(pass.parity()),
                    binding_base: 0,
                    joint_base: 0,
                    joint_count: 3,
                    attribute_base: pool.attribute_base(),
                }
            );
            seen.push(block.output_base);
        }
        assert_ne!(
            seen[0], seen[1],
            "two consecutive frames must write different halves of the region"
        );
    }

    /// A second range's bases are the first range's lengths, so the two
    /// dispatches read disjoint runs of the shared palette and binding buffers.
    ///
    /// One base serving both would make the second character read the first
    /// one's skin.
    #[test]
    fn each_ranges_palette_and_binding_bases_follow_the_range_before_it() {
        let (recorder, device, _queue) = open();
        let mut pool = pool(device.as_ref(), 64);
        let first = SkinnedRegion::reserve(&mut pool, 3).expect("room");
        let second = SkinnedRegion::reserve(&mut pool, 4).expect("room");
        let mut pass = skinning(device.as_ref(), &pool, 2, 5, 7);
        let (three, four) = (rigid(3), rigid(4));
        pass.begin_frame(
            device.as_ref(),
            0,
            &[
                SkinRange {
                    input_base: 50,
                    region: &first,
                    palette: &[Mat4::IDENTITY; 2],
                    bindings: &three,
                },
                SkinRange {
                    input_base: 54,
                    region: &second,
                    palette: &[Mat4::IDENTITY; 3],
                    bindings: &four,
                },
            ],
        )
        .expect("a legal frame");

        let first_block = params_of(&recorder, &pass, 0, 0);
        let second_block = params_of(&recorder, &pass, 0, 1);
        assert_eq!((first_block.joint_base, first_block.binding_base), (0, 0));
        assert_eq!(
            (second_block.joint_base, second_block.binding_base),
            (2, 3),
            "the second range starts where the first one's palette and bindings ended"
        );
        assert_eq!((first_block.joint_count, second_block.joint_count), (2, 3));
    }

    /// The palette and the skin bindings reach their buffers as the bytes the
    /// shader indexes: `to_cols_array` order at
    /// [`JOINT_STRIDE`](crcbl_shaders::skinning::JOINT_STRIDE), and
    /// [`SkinBinding::to_bytes`] at its own stride.
    #[test]
    fn the_uploaded_palette_and_bindings_are_the_bytes_the_shader_reads() {
        let (recorder, device, _queue) = open();
        let mut pool = pool(device.as_ref(), 32);
        let region = SkinnedRegion::reserve(&mut pool, 2).expect("room");
        let mut pass = skinning(device.as_ref(), &pool, 1, 2, 2);
        let palette = [
            Mat4::from_translation(Vec3::new(1.0, 2.0, 3.0)),
            Mat4::from_scale(Vec3::new(2.0, 4.0, 8.0)),
        ];
        let bindings = [
            SkinBinding {
                joints: [1, 0, 1, 0],
                weights: [0.5, 0.25, 0.125, 0.125],
            },
            SkinBinding {
                joints: [0, 1, 0, 1],
                weights: [1.0, 0.0, 0.0, 0.0],
            },
        ];
        pass.begin_frame(
            device.as_ref(),
            0,
            &[SkinRange {
                input_base: 8,
                region: &region,
                palette: &palette,
                bindings: &bindings,
            }],
        )
        .expect("a legal frame");

        let written = recorder
            .buffer_bytes(pass.palettes[0])
            .expect("the palette is live");
        for (index, matrix) in palette.iter().enumerate() {
            let want: Vec<u8> = matrix
                .to_cols_array()
                .iter()
                .flat_map(|value| value.to_le_bytes())
                .collect();
            assert_eq!(
                &written[index * JOINT_STRIDE..(index + 1) * JOINT_STRIDE],
                &want[..],
                "palette matrix {index} is not the columns the shader reads with no transpose"
            );
        }
        let written = recorder
            .buffer_bytes(pass.bindings[0])
            .expect("the binding buffer is live");
        for (index, binding) in bindings.iter().enumerate() {
            assert_eq!(
                &written[index * SKIN_BINDING_STRIDE..(index + 1) * SKIN_BINDING_STRIDE],
                &binding.to_bytes()[..],
                "skin binding {index} is not what the shader crate encodes"
            );
        }
    }

    /// How many host writes landed in each slot's binding buffer since the
    /// recorder was last cleared, in slot order.
    fn binding_writes(recorder: &Recorder, pass: &Skinning) -> Vec<usize> {
        let events = recorder.events();
        pass.bindings
            .iter()
            .map(|slot| {
                events
                    .iter()
                    .filter(|event| {
                        matches!(event, Event::BufferWritten { buffer, .. } if buffer == slot)
                    })
                    .count()
            })
            .collect()
    }

    /// Whether a slot's binding buffer starts with `bindings`, as the shader
    /// reads them.
    fn holds(recorder: &Recorder, pass: &Skinning, slot: usize, bindings: &[SkinBinding]) -> bool {
        let want: Vec<u8> = bindings.iter().flat_map(SkinBinding::to_bytes).collect();
        recorder
            .buffer_bytes(pass.bindings[slot])
            .is_some_and(|bytes| bytes[..want.len()] == want[..])
    }

    /// **Unchanged skin bindings are not uploaded again, and a change reaches
    /// every frame slot exactly once.**
    ///
    /// The bindings are a mesh's own vertex data, so re-sending them every
    /// frame was most of a skinned frame's host cost. More slots than the
    /// renderer's [`crate::forward::FRAMES_IN_FLIGHT`], so "every slot" is not
    /// satisfied by "this one and the other": a change written into only the
    /// slot that saw it leaves the next frame in flight skinning against the
    /// old set, which is a visible flicker every other frame and nothing else
    /// reports it.
    #[test]
    fn unchanged_bindings_are_not_uploaded_again_and_a_change_reaches_every_slot_once() {
        const FRAMES: usize = 3;
        const { assert!(FRAMES > crate::forward::FRAMES_IN_FLIGHT) };
        let (recorder, device, _queue) = open();
        let mut pool = pool(device.as_ref(), 32);
        let source = pool.reserve_vertices(4).expect("room");
        let region = SkinnedRegion::reserve(&mut pool, 4).expect("room");
        let mut pass = Skinning::new(
            device.as_ref(),
            &SkinningDesc {
                label: Some("skinning test"),
                frames: FRAMES,
                ranges: 1,
                joints: 2,
                bindings: 4,
                vertices: pool.vertex_buffer(),
                attribute_base: pool.attribute_base(),
            },
        )
        .expect("the null backend accepts every descriptor");
        let palette = [Mat4::IDENTITY; 2];
        let before = rigid(4);
        let mut after = rigid(4);
        after[2] = SkinBinding {
            joints: [1, 0, 0, 0],
            weights: [0.75, 0.25, 0.0, 0.0],
        };
        let mut frame = 0;
        let mut begin = |pass: &mut Skinning, bindings: &[SkinBinding]| {
            let slot = frame % FRAMES;
            frame += 1;
            pass.begin_frame(
                device.as_ref(),
                slot,
                &[SkinRange {
                    input_base: source,
                    region: &region,
                    palette: &palette,
                    bindings,
                }],
            )
            .expect("a legal frame");
            slot
        };

        // The first lap fills every slot, once each.
        for _ in 0..FRAMES {
            begin(&mut pass, &before);
        }
        assert_eq!(binding_writes(&recorder, &pass), [1; FRAMES]);

        // Steady frames write the palette and nothing of the bindings.
        recorder.clear();
        for _ in 0..2 * FRAMES {
            begin(&mut pass, &before);
        }
        assert_eq!(
            binding_writes(&recorder, &pass),
            [0; FRAMES],
            "a frame handing over the same bindings re-uploaded them"
        );
        let palette_writes = recorder
            .events()
            .iter()
            .filter(|event| {
                matches!(
                    event,
                    Event::BufferWritten { buffer, .. } if pass.palettes.contains(buffer)
                )
            })
            .count();
        assert_eq!(
            palette_writes,
            2 * FRAMES,
            "the pose still has to go up every frame, and the count above has to be able to \
             see a write"
        );

        // A change goes into each slot as that slot comes round, and only then.
        recorder.clear();
        for lap in 0..2 * FRAMES {
            let slot = begin(&mut pass, &after);
            assert_eq!(slot, lap % FRAMES, "the change lands at the start of a lap");
            assert!(
                holds(&recorder, &pass, slot, &after),
                "slot {slot} skinned frame {lap} after the change against the old bindings"
            );
            for later in lap + 1..FRAMES {
                assert!(
                    holds(&recorder, &pass, later % FRAMES, &before),
                    "slot {later} was written before it began a frame, while the device may still \
                     read it"
                );
            }
        }
        assert_eq!(
            binding_writes(&recorder, &pass),
            [1; FRAMES],
            "a change is one write into each slot, and then none"
        );
    }

    /// A change is a change of **bits**: a weight going from `0.0` to `-0.0`
    /// is a different buffer, which `f32`'s `==` would call the same.
    #[test]
    fn a_change_to_a_bindings_sign_of_zero_is_still_uploaded() {
        let (recorder, device, _queue) = open();
        let mut pool = pool(device.as_ref(), 32);
        let source = pool.reserve_vertices(1).expect("room");
        let region = SkinnedRegion::reserve(&mut pool, 1).expect("room");
        let mut pass = skinning(device.as_ref(), &pool, 1, 1, 1);
        let positive = rigid(1);
        let mut negative = rigid(1);
        negative[0].weights[3] = -0.0;
        for (frame, bindings) in [&positive, &negative].into_iter().enumerate() {
            pass.begin_frame(
                device.as_ref(),
                frame % 2,
                &[SkinRange {
                    input_base: source,
                    region: &region,
                    palette: &[Mat4::IDENTITY],
                    bindings,
                }],
            )
            .expect("a legal frame");
        }
        assert!(holds(&recorder, &pass, 1, &negative));
        assert!(holds(&recorder, &pass, 0, &positive));
    }

    /// **The joint check survives the bindings not changing.** They are
    /// checked in full only when they differ from the last set, so the same
    /// set handed over with a shorter palette must still be refused, and by
    /// the vertex that names the missing joint — and the refusal must not count
    /// as having accepted anything.
    #[test]
    fn unchanged_bindings_are_still_checked_against_a_shorter_palette() {
        let (recorder, device, _queue) = open();
        let mut pool = pool(device.as_ref(), 32);
        let source = pool.reserve_vertices(3).expect("room");
        let region = SkinnedRegion::reserve(&mut pool, 3).expect("room");
        let mut pass = skinning(device.as_ref(), &pool, 1, 4, 3);
        let mut bindings = rigid(3);
        bindings[2].joints[1] = 3;
        let begin = |pass: &mut Skinning, palette: &[Mat4]| {
            pass.begin_frame(
                device.as_ref(),
                0,
                &[SkinRange {
                    input_base: source,
                    region: &region,
                    palette,
                    bindings: &bindings,
                }],
            )
        };

        begin(&mut pass, &[Mat4::IDENTITY; 4]).expect("joint 3 of a four-joint palette");
        match begin(&mut pass, &[Mat4::IDENTITY; 2]) {
            Err(SkinningError::JointOutOfRange {
                range,
                vertex,
                slot,
                joint,
                palette,
            }) => assert_eq!((range, vertex, slot, joint, palette), (0, 2, 1, 3, 2)),
            other => panic!("{other:?} does not name the joint that is out of range"),
        }
        recorder.clear();
        begin(&mut pass, &[Mat4::IDENTITY; 4]).expect("joint 3 of a four-joint palette again");
        assert_eq!(
            binding_writes(&recorder, &pass),
            [0, 0],
            "the refused frame changed what the slot is known to hold"
        );
    }

    /// **A binding naming a joint the palette has not got is refused, loudly
    /// and by name.**
    ///
    /// The gap `docs/backlog.md` records: `crcbl-scene` cannot make this check
    /// because a glTF primitive does not know its skin at import, and the
    /// shader can only clamp. This call knows both, so it is where the refusal
    /// belongs — and the message has to name the vertex, or a rigger is left
    /// with "somewhere in this mesh".
    #[test]
    fn a_binding_naming_a_joint_the_palette_has_not_got_is_refused() {
        let (recorder, device, _queue) = open();
        let mut pool = pool(device.as_ref(), 32);
        let region = SkinnedRegion::reserve(&mut pool, 3).expect("room");
        let mut pass = skinning(device.as_ref(), &pool, 1, 2, 3);
        let mut bindings = rigid(3);
        // The third joint slot of the middle vertex, carrying no weight at all
        // — the shader reads all four matrices before it scales any of them, so
        // a weightless slot is the same clamped read as a weighted one.
        bindings[1].joints[2] = 7;

        let error = pass
            .begin_frame(
                device.as_ref(),
                0,
                &[SkinRange {
                    input_base: 0,
                    region: &region,
                    palette: &[Mat4::IDENTITY, Mat4::IDENTITY],
                    bindings: &bindings,
                }],
            )
            .expect_err("joint 7 of a two-joint palette");

        match error {
            SkinningError::JointOutOfRange {
                range,
                vertex,
                slot,
                joint,
                palette,
            } => assert_eq!((range, vertex, slot, joint, palette), (0, 1, 2, 7, 2)),
            other => panic!("{other} does not name the joint that is out of range"),
        }
        assert!(
            recorder
                .buffer_bytes(pass.params[0][0])
                .is_some_and(|bytes| bytes.iter().all(|byte| *byte == 0)),
            "a refused frame must not have written a uniform block"
        );
        assert!(
            pass.active[0].is_empty(),
            "and it must not have left a dispatch plan behind"
        );
    }

    /// The palette length is a range's own, not the buffer's: a joint index
    /// legal for a longer palette elsewhere in the frame is still refused here.
    #[test]
    fn a_joint_index_is_checked_against_its_own_ranges_palette() {
        let (_recorder, device, _queue) = open();
        let mut pool = pool(device.as_ref(), 32);
        let long = SkinnedRegion::reserve(&mut pool, 1).expect("room");
        let short = SkinnedRegion::reserve(&mut pool, 1).expect("room");
        let mut pass = skinning(device.as_ref(), &pool, 2, 6, 2);
        let mut named_three = rigid(1);
        named_three[0].joints[0] = 3;

        // Legal against a four-joint palette…
        pass.begin_frame(
            device.as_ref(),
            0,
            &[SkinRange {
                input_base: 0,
                region: &long,
                palette: &[Mat4::IDENTITY; 4],
                bindings: &named_three,
            }],
        )
        .expect("joint 3 of a four-joint palette");

        // …and refused against the two-joint one beside it.
        let error = pass
            .begin_frame(
                device.as_ref(),
                0,
                &[
                    SkinRange {
                        input_base: 0,
                        region: &long,
                        palette: &[Mat4::IDENTITY; 4],
                        bindings: &rigid(1),
                    },
                    SkinRange {
                        input_base: 1,
                        region: &short,
                        palette: &[Mat4::IDENTITY; 2],
                        bindings: &named_three,
                    },
                ],
            )
            .expect_err("joint 3 of a two-joint palette");
        assert!(
            matches!(error, SkinningError::JointOutOfRange { range: 1, .. }),
            "{error} blames the wrong range"
        );
    }

    /// An empty palette is refused here rather than left to the shader crate's
    /// panic, which is what would otherwise take the frame down.
    #[test]
    fn an_empty_palette_is_refused_rather_than_reaching_the_blocks_panic() {
        let (_recorder, device, _queue) = open();
        let mut pool = pool(device.as_ref(), 32);
        let region = SkinnedRegion::reserve(&mut pool, 1).expect("room");
        let mut pass = skinning(device.as_ref(), &pool, 1, 1, 1);
        let error = pass
            .begin_frame(
                device.as_ref(),
                0,
                &[SkinRange {
                    input_base: 0,
                    region: &region,
                    palette: &[],
                    bindings: &rigid(1),
                }],
            )
            .expect_err("no joints to blend onto");
        assert!(
            matches!(error, SkinningError::EmptyPalette { range: 0 }),
            "{error}"
        );
    }

    /// The skin bindings are parallel to the bind-pose run, so a list that is
    /// not one per vertex is refused rather than silently covering part of the
    /// mesh.
    #[test]
    fn a_binding_run_that_is_not_one_per_vertex_is_refused() {
        let (_recorder, device, _queue) = open();
        let mut pool = pool(device.as_ref(), 32);
        let region = SkinnedRegion::reserve(&mut pool, 4).expect("room");
        let mut pass = skinning(device.as_ref(), &pool, 1, 1, 8);
        for offered in [3usize, 5] {
            let error = pass
                .begin_frame(
                    device.as_ref(),
                    0,
                    &[SkinRange {
                        input_base: 0,
                        region: &region,
                        palette: &[Mat4::IDENTITY],
                        bindings: &rigid(offered),
                    }],
                )
                .expect_err("four vertices need four bindings");
            assert!(
                matches!(
                    error,
                    SkinningError::BindingCountMismatch {
                        vertices: 4,
                        bindings,
                        ..
                    } if bindings == offered
                ),
                "{error}"
            );
        }
    }

    /// Every capacity is refused by name rather than truncated: a character
    /// silently missing from the frame is what these bounds exist to prevent.
    #[test]
    fn a_frame_over_any_capacity_is_refused_and_names_which() {
        let (_recorder, device, _queue) = open();
        let mut pool = pool(device.as_ref(), 64);
        let region = SkinnedRegion::reserve(&mut pool, 2).expect("room");
        let two = rigid(2);
        let range = |palette: &'static [Mat4]| SkinRange {
            input_base: 0,
            region: &region,
            palette,
            bindings: &two,
        };
        const ONE: &[Mat4] = &[Mat4::IDENTITY];
        const THREE: &[Mat4] = &[Mat4::IDENTITY, Mat4::IDENTITY, Mat4::IDENTITY];

        let mut pass = skinning(device.as_ref(), &pool, 1, 8, 8);
        let error = pass
            .begin_frame(device.as_ref(), 0, &[range(ONE), range(ONE)])
            .expect_err("two ranges in a pass built for one");
        assert!(
            matches!(
                error,
                SkinningError::OverCapacity {
                    what: "ranges",
                    capacity: 1,
                    asked: 2
                }
            ),
            "{error}"
        );

        let mut pass = skinning(device.as_ref(), &pool, 2, 2, 8);
        let error = pass
            .begin_frame(device.as_ref(), 0, &[range(THREE)])
            .expect_err("three matrices in a buffer of two");
        assert!(
            matches!(
                error,
                SkinningError::OverCapacity {
                    what: "palette matrices",
                    capacity: 2,
                    asked: 3
                }
            ),
            "{error}"
        );

        let mut pass = skinning(device.as_ref(), &pool, 2, 8, 3);
        let error = pass
            .begin_frame(device.as_ref(), 0, &[range(ONE), range(ONE)])
            .expect_err("four bindings in a buffer of three");
        assert!(
            matches!(
                error,
                SkinningError::OverCapacity {
                    what: "skin bindings",
                    capacity: 3,
                    asked: 4
                }
            ),
            "{error}"
        );
    }

    /// A frame with nothing to skin adds no pass, so the vertex pool pays no
    /// barrier for a dispatch that would not have happened.
    ///
    /// And a slot whose previous frame *did* have ranges is cleared by the
    /// empty call rather than re-dispatching them, which is the failure the
    /// plan being per-slot state would otherwise produce.
    #[test]
    fn a_frame_with_nothing_to_skin_adds_no_pass_and_clears_the_slot() {
        let (recorder, device, queue) = open();
        let mut pool = pool(device.as_ref(), 32);
        let region = SkinnedRegion::reserve(&mut pool, 4).expect("room");
        let mut pass = skinning(device.as_ref(), &pool, 1, 1, 4);
        pass.begin_frame(
            device.as_ref(),
            0,
            &[SkinRange {
                input_base: 0,
                region: &region,
                palette: &[Mat4::IDENTITY],
                bindings: &rigid(4),
            }],
        )
        .expect("a legal frame");

        let mut graph = RenderGraph::new(queue);
        assert!(
            pass.add_pass(&mut graph, 0).is_some(),
            "a frame with a range has a pass"
        );

        pass.begin_frame(device.as_ref(), 0, &[])
            .expect("an empty frame is legal");
        recorder.clear();
        let mut graph = RenderGraph::new(queue);
        assert!(
            pass.add_pass(&mut graph, 0).is_none(),
            "a frame with no ranges adds nothing"
        );
        let compiled = graph.compile(&TransientPool::new()).expect("a legal frame");
        assert!(
            compiled.passes().is_empty(),
            "and the graph has no skinning pass in it"
        );
        run(&recorder, device.as_ref(), queue, &pass, 0);
        assert!(
            dispatches(&recorder).is_empty(),
            "nothing is dispatched for a frame with nothing to skin"
        );
    }

    /// The bind-group layout is the order `skinning.slang` declares its
    /// resources, and the vertex pool is the one writable entry.
    ///
    /// `crcbl_shaders::skinning` records the same table and holds the shader to
    /// it; this is the other half — a layout built against a different
    /// assignment binds the palette where the skin bindings belong, and every
    /// backend accepts it happily because both are read-only storage buffers.
    #[test]
    fn the_bind_group_layout_is_the_order_the_shader_declares() {
        let (recorder, device, _queue) = open();
        let pool = pool(device.as_ref(), 8);
        let pass = skinning(device.as_ref(), &pool, 1, 1, 1);
        let (_, entries) = recorder
            .bind_group_layouts_created()
            .into_iter()
            .find(|(label, _)| label.as_deref() == Some("skinning test"))
            .expect("the pass created its layout");
        assert_eq!(entries.len(), 4);
        assert!(matches!(
            entries[0].kind,
            crcbl_hal::BindingKind::UniformBuffer { .. }
        ));
        for (binding, read_only) in [(1usize, true), (2, true), (3, false)] {
            match entries[binding].kind {
                crcbl_hal::BindingKind::StorageBuffer { read_only: got, .. } => assert_eq!(
                    got, read_only,
                    "binding {binding} is the wrong kind of storage buffer"
                ),
                other => panic!("binding {binding} is {other:?}, not a storage buffer"),
            }
        }
        pass.destroy(device.as_ref());
    }

    /// Every object the pass created is released, and the vertex pool it
    /// borrowed is not.
    #[test]
    fn destroy_releases_everything_the_pass_made_and_nothing_it_borrowed() {
        let (recorder, device, _queue) = open();
        let pool = pool(device.as_ref(), 8);
        let borrowed = recorder.total_live_objects();
        let pass = skinning(device.as_ref(), &pool, 2, 4, 4);
        assert!(recorder.total_live_objects() > borrowed);
        pass.destroy(device.as_ref());
        assert_eq!(
            recorder.total_live_objects(),
            borrowed,
            "the pass released everything it made, and left the pool's buffers alone"
        );
        pool.destroy(device.as_ref());
        assert_eq!(
            recorder.total_live_objects(),
            0,
            "and the pool's own buffers were still there to release"
        );
    }

    /// A descriptor asking for no frames, ranges, joints or bindings is
    /// refused: a buffer of zero bytes is not a buffer on any backend the
    /// engine targets.
    #[test]
    fn a_descriptor_with_a_zero_in_it_is_refused() {
        let (_recorder, device, _queue) = open();
        let pool = pool(device.as_ref(), 8);
        let base = SkinningDesc {
            label: Some("zero"),
            frames: 1,
            ranges: 1,
            joints: 1,
            bindings: 1,
            vertices: pool.vertex_buffer(),
            attribute_base: pool.attribute_base(),
        };
        for desc in [
            SkinningDesc { frames: 0, ..base },
            SkinningDesc { ranges: 0, ..base },
            SkinningDesc { joints: 0, ..base },
            SkinningDesc {
                bindings: 0,
                ..base
            },
        ] {
            let error = Skinning::new(device.as_ref(), &desc).expect_err("a zero is refused");
            assert!(matches!(error, SkinningError::Hal(_)), "{error}");
        }
    }

    /// The float-at-a-time serialisation `write_palette` replaced, kept as the
    /// reference its bytes must equal.
    fn reference_palette(palette: &[Mat4]) -> Vec<u8> {
        let mut out = Vec::new();
        for matrix in palette {
            for value in matrix.to_cols_array() {
                out.extend_from_slice(&value.to_le_bytes());
            }
        }
        out
    }

    #[test]
    fn write_palette_matches_the_float_at_a_time_bytes() {
        // A fixed xorshift, so the values are arbitrary bit patterns (NaN
        // payloads and subnormals included) and the run is repeatable.
        let mut state = 0x9e37_79b9_7f4a_7c15u64;
        let mut next = || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            f32::from_bits(state as u32)
        };
        let edges = [
            -0.0,
            0.0,
            f32::from_bits(0x7fc0_0001),
            f32::from_bits(0xffa0_1234),
            f32::from_bits(1),
            f32::from_bits(0x807f_ffff),
            f32::INFINITY,
            f32::NEG_INFINITY,
            f32::MAX,
            f32::MIN_POSITIVE,
        ];
        let mut palette: Vec<Mat4> = (0..64)
            .map(|_| Mat4::from_cols_array(&std::array::from_fn(|_| next())))
            .collect();
        palette.push(Mat4::from_cols_array(&std::array::from_fn(|index| {
            edges[index % edges.len()]
        })));
        // Not symmetric, so a transpose cannot pass.
        palette.push(Mat4::from_cols_array(&std::array::from_fn(|index| {
            index as f32
        })));

        let mut written = vec![0xaa];
        write_palette(&mut written, &palette);
        assert_eq!(written[0], 0xaa, "write_palette appends, it does not clear");
        assert_eq!(written.len() - 1, palette.len() * JOINT_STRIDE);
        assert!(
            written[1..] == reference_palette(&palette)[..],
            "write_palette is not the float-at-a-time bytes"
        );
    }
}