crcbl-render 0.7.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
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
//! The frame milestones 3, 4 and 5 draw: a lit mesh into an HDR target, then a
//! tonemap into whatever the caller is presenting to.
//!
//! ```text
//! ┌ cull ───────────┐ ┌ draw-args ──────┐ ┌ forward ──────────┐ ┌ tonemap ──────┐
//! │ instances ─────▶│ │ visible ───────▶│ │ scene-color Clear │ │ reads it      │
//! │ visible list    │ │ per-bucket runs │ │ scene-depth Clear │ │ writes the    │
//! │ + a GPU count   │ │ + indirect args │ │ one indirect call │ │ target        │
//! │                 │ │ + a draw count  │ │ per bucket        │ │               │
//! └─────────────────┘ └─────────────────┘ └───────────────────┘ └───────────────┘
//! ```
//!
//! Two passes and one graph. Everything that makes them ordered, everything that
//! transitions `scene-color` from a colour attachment into a sampled texture,
//! and everything that returns the target to [`ResourceState::Present`] is
//! computed by [`crate::graph`] — **there is not one hand-written barrier in
//! this file, or anywhere above the seam.**
//!
//! # Scope
//!
//! Stage 2's ladder rungs 3–5, and nothing beyond:
//!
//! * **3** — depth-tested spinning mesh, perspective camera in a uniform buffer.
//! * **4** — one directional light (in `mesh.slang`). The rung's own wording is
//!   "Lambert+Blinn"; what shipped is Lambert plus a Cook-Torrance GGX lobe over
//!   a glTF metallic-roughness row, which is that rung's "real material model"
//!   arriving early rather than a different rung.
//! * **5** — orthographic mode, which is [`Camera::projection`] and *nothing
//!   else*: no second pipeline, no branch in this file, no shader permutation.
//!
//! Explicitly not here: bindless at scale (P3), shadows and real post (P7),
//! material authoring (topic 37), asset loading (P9). The mesh is a constant in
//! `crcbl-shaders` because rung 3 says "hardcoded cube/sphere".
//!
//! What *is* here since 2026-08 is [`crate::material_table`]: §3.2's material
//! table, holding **both** halves of "texture indices + factors", with
//! [`mesh::GpuInstance::material`] selecting a row. Three rows are resident and
//! two of them exist to be seen: [`scene::DEMO_TINTED`] differs from the default
//! row in its factor and its roughness, and [`scene::DEMO_TEXTURED`] in its
//! base-colour page layer alone. Which rows those are is [`crate::scene::demo`]'s
//! to say, and so is why the shading factor rides on that row rather than on a
//! fourth.
//!
//! The page is the texture side, and it is one `D2Array` image rather than an
//! array of descriptors — `BindingModel::ArrayPages` rather than `Bindless`.
//! That is the whole of the binding-model decision §3.2 leaves open, taken
//! here because a layer index needs nothing of a device where a descriptor
//! array needs `Features::DESCRIPTOR_INDEXING`, which `crcbl-mtl` withdraws. So
//! there is one lookup, one layout and one artifact rather than a permutation,
//! and a device that reports the feature runs the same declaration. What
//! bindless buys later is capacity, not a second path — see [`crate::scene::PageDesc`]
//! and the layout entry for binding 7.
//!
//! What *was* on that list until 2026-08 is GPU culling and the indirect draw
//! count, and both are here now: [`crate::draw_gen`] runs `cull.slang` and
//! `draw_gen.slang` in front of this pass, and the draws below come out of the
//! arguments they wrote. See that module for what a bucket is and why the
//! arguments are per bucket rather than per surviving instance.
//!
//! # The CPU records a fixed number of draws
//!
//! One per bucket, whatever the scene holds — topic 03's
//! headline goal, "10 objects and 10,000 objects record roughly the same
//! commands". Adding an object is an instance in the pool and nothing else;
//! removing one is [`InstancePool::remove`] and nothing else. Neither changes a
//! single command this file records, because what varies — how many instances a
//! bucket draws, and which — is written by a compute pass into a buffer the
//! draw reads.
//!
//! Which *call* those draws are is the one branch: [`GeometryPath::IndirectCount`]
//! takes the count from GPU memory too, and [`GeometryPath::IndirectPerBatch`] —
//! Metal, whose API has multi-draw-indirect and no GPU-side count — reads each
//! bucket's one argument structure unconditionally and leans on its instance
//! count being zero.
//!
//! What *is* here, since 2026-08, is [`crate::mesh_pool`]: the cube is the first
//! resident of the global vertex and index pools rather than owning two buffers
//! of its own, so it is `{base_vertex, base_index, index_count}` like everything
//! P7 will draw. Same geometry, different residence.
//!
//! And since the same month, [`crate::instance_pool`]: the cube's model matrix
//! is a `GpuInstance` in a storage buffer rather than a field of the frame's
//! uniform block, uploaded by delta. It holds the same matrix `begin_frame` used
//! to write into the uniform, which is why the golden images did not move.
//!
//! # A second resident, and how it finds its own vertices
//!
//! A pool whose only mesh is at base vertex 0 cannot tell a base vertex that
//! works from one that is silently cancelled out, and `mesh.slang`'s header
//! shows the four targets disagreeing about exactly that: the SPIR-V subtracts
//! `BaseVertex` back out of `SV_VertexID`, so the pool's base — passed through
//! `draw_indexed`'s own argument — reached the shader as zero, while WGSL and
//! MSL kept it. The same disagreement covers `SV_InstanceID`, which is what
//! [`crate::sprite_pass`] paid for first.
//!
//! So **every draw this pass records passes zero for both of its bases**, and
//! the real ones arrive as data. The base vertex comes from
//! [`MeshPool`]'s mesh table, indexed by the drawn instance's
//! [`mesh::GpuInstance::mesh`] — so it is resolved per instance, by the GPU,
//! and one draw could cover instances of different meshes. The instance comes
//! from the bucket's run of survivors, walked with `SV_InstanceID`, which counts
//! from zero on every target *because* the first instance is zero. All a draw
//! says for itself is which word holds its run's start — the start is the GPU's,
//! per frame — in a [`mesh::DrawConstants`] block reached through a dynamic
//! offset: one block per bucket, written once at build.
//!
//! That is what makes the pool's *second* resident,
//! [`mesh::pyramid_vertices`], draw its own geometry rather than the cube's.
//!
//! The pyramid is in the pools from `new` but has no *instance* until a caller
//! places one with [`ForwardRenderer::add_instance`] — an instance in the pool
//! is an object in the scene now that culling decides what draws. The frame the
//! samples draw is still the cube alone, which is why their golden images did
//! not move either.
//!
//! # A third resident, and how it finds its own clusters
//!
//! The same argument one layer down. A mesh that fits **one** cluster cannot
//! tell a per-cluster offset that works from one that is lost, and the cube and
//! the pyramid fit one each — 24 and 16 vertices against a bound of 64. So the
//! pool's third resident is [`mesh::open_box_vertices`], five clusters of one
//! flat face each, four of them at a `Meshlet::vertex_offset` that is not zero.
//! It is [`crate::cluster_pool`]'s counterpart to what the pyramid is for
//! [`crate::mesh_pool`], and it is what §3.5's per-cluster culling will need
//! before a surviving-cluster count can mean anything.
//!
//! It arrives on the pyramid's terms exactly: resident from `new`, in the scene
//! only when a caller places it, so no golden moved for it either.
//!
//! # Uniforms are a ring, and they have to be
//!
//! The camera spins, so the uniform block is rewritten every frame — and the
//! previous frame may still be reading it. One buffer would be a
//! read-after-write hazard *across* submissions, which is precisely what
//! `CRCBL_VK_SYNC_VALIDATION=1` exists to find and precisely what
//! stage 2 called its headline risk. So there
//! is one uniform buffer and one bind group per frame in flight, and
//! [`ForwardRenderer::begin_frame`] rotates them.

use crcbl_hal::{
    BindGroupDesc, BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
    BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BufferDesc, BufferHandle,
    BufferUsage, ColorTargetState, CompareOp, CullMode, DepthBias, DepthStencilState, Device,
    DeviceCaps, Features, FilterMode, Format, GeometryPath, GraphicsPipelineDesc,
    GraphicsPipelineHandle, HalError, ImageDesc, ImageHandle, ImageSubresourceRange, ImageType,
    ImageUsage, ImageViewDesc, ImageViewHandle, ImageViewType, LoadOp, MemoryLocation,
    MeshPipelineDesc, MultisampleState, PipelineLayoutDesc, PipelineLayoutHandle, PolygonMode,
    PrimitiveState, QueueHandle, Rect2d, ResourceState, SampleType, SamplerAddressMode,
    SamplerDesc, SamplerHandle, ShaderEntry, ShaderModuleDesc, ShaderModuleHandle, ShaderStages,
    StoreOp, Viewport, check_portable_storage_buffers,
};
use crcbl_shaders::meshlet::MeshClusters;
use crcbl_shaders::probe_gather::PunctualProducer;
use crcbl_shaders::{
    MESH, MESH_CLUSTER, Stage, TONEMAP, contact_shadows, dfg, level_select, ltc, mesh, ssao, ssr,
    tonemap,
};
use glam::{Mat4, Quat, Vec3};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use crate::camera::{Atmosphere, Camera, DirectionalLight, Fog, Sky};
use crate::cluster_pool::{ClusterPool, ClusterRange, PooledMesh};
use crate::contact_shadows::ContactShadows;
use crate::counters::FrameCounters;
use crate::cull::Frustum;
use crate::cull_stats::CullStatsRing;
use crate::debug_draw::DebugDraw;
use crate::draw_gen::{DrawGen, DrawGenDesc, FrameCull, GeneratedDraws};
use crate::effects::{EffectRequest, RenderEffects};
use crate::graph::{
    BufferId, ImageId, ImportedBuffer, ImportedImage, InitialClaim, PassBuilder, RenderGraph,
};
// Renamed on the way in, because [`crate::light_grid::Grid`] already holds the
// bare name here and means the froxel grid — the collision [`crate::grid`]'s
// header predicted.
use crate::atlas_view::AtlasView;
use crate::bloom::Bloom;
use crate::cmaa2::Cmaa2;
use crate::exposure::{Exposure, ExposureAdaptation, ExposureBuffers};
use crate::fxaa::Fxaa;
use crate::grass::{Grass, GrassFrame, GrassScene};
use crate::grid::{Grid as GroundGrid, GridStyle};
use crate::hiz::Hiz;
use crate::instance_pool::{InstanceHandle, InstancePool, InstancePoolDesc, InstancePoolError};
use crate::light::{Light, sun_row};
use crate::light_grid::{FROXEL_CAPACITY, FrameView, Grid, LightGrid, LightGridDesc};
use crate::material_table::{MaterialTable, MaterialTableDesc};
use crate::mesh_pool::{MeshHandle, MeshPool, MeshPoolDesc, MeshPoolError, MeshUpload};
use crate::occlusion_cull::{OcclusionCulling, OcclusionPyramid};
use crate::probe::{ProbeTable, ProbeTableDesc};
use crate::probe_gather::{ProbeGather, ProbeGatherDesc, RsmImages, RsmTargets};
use crate::rsm;
use crate::scene::{self, Geometry, InstanceDesc, PageKind, ProbeUpdate, SceneDesc};
use crate::shadow::{self, Cascades};
use crate::skinning::{SkinRange, SkinnedMesh, Skinning, SkinningError};
use crate::sky_pass::SkyPass;
use crate::ssao::{Ssao, cached_group};
use crate::ssr::{Ssr, SsrEnvironment, SsrImages};
use crate::stack::CameraStack;
use crate::texture::{
    UploadedTexture, upload_texture, upload_texture_layers, upload_texture_mip_layers,
};
use crate::transient::TransientPool;
use crate::upscale::Upscale;
use crate::volumetric::{FroxelBuffers, Medium, Volumetric, VolumetricImages, VolumetricReads};
use crate::water::{Water, WaterBodies, WaterFrame, WaterImages, WaterInputs};
use crcbl_shaders::atmosphere::{SKY_VIEW_BUILD_ROWS, SkyView, SkyViewBuild};

mod bucket_draws;
mod frame_prepare;
mod pages;
mod shadow_inputs;
mod view;

use pages::{PageBindings, RetiredPage, upload_page};

pub use shadow_inputs::{FRAME_UNIFORMS_READERS, UniformsField, UniformsReader};

use bucket_draws::{BucketDraws, EmitTail, RegionStep};

use view::{FramePasses, Overlays, TonemapPipeline, View, ViewInputs, ViewOutput};
pub use view::{
    FrameTargets, MAX_VIEWS, ViewBackground, ViewDesc, ViewId, ViewLighting, ViewMask, ViewTarget,
};

/// The clear behind the mesh, in **linear** light.
///
/// The scene target is `Rgba16Float`, so this is a linear value and the tonemap
/// pass plus the swapchain's sRGB encode are what turn it into pixels. Writing a
/// display-referred colour here would come out visibly paler, which is the
/// classic HDR-pipeline mistake and worth a sentence rather than a surprise.
pub const SCENE_CLEAR: [f32; 4] = [0.012, 0.016, 0.030, 1.0];

/// How many frames of uniform buffers to keep. Matches the frame loop's
/// frames-in-flight.
pub const FRAMES_IN_FLIGHT: usize = 2;

// The UI pass this renderer draws its HUD through keeps a ring of its own,
// built at `crcbl_frame`'s default depth; held equal here, where both are in
// scope, so the HUD cannot fall a frame behind the ring it shares a submit with.
const _: () = assert!(crcbl_frame::ui_pass::FRAMES_IN_FLIGHT == FRAMES_IN_FLIGHT);

/// The darkest exposure [`ForwardRenderer::set_exposure`] will accept: **five
/// stops below** [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`].
///
/// The floor exists so that the control cannot be driven somewhere it cannot be
/// driven back from. The operator clamps its own *output* to `[0, 1]`, so an
/// unclamped input has two dead ends: far enough down and every pixel rounds to
/// the same black byte, far enough up and every pixel saturates to white — and
/// in both the picture stops carrying the information a user would need to see
/// which way to go. Five stops is well inside either: it is a sixteenth of the
/// scene's brightness, dark but plainly still a picture, and it is the range a
/// camera's exposure-compensation dial covers.
pub const EXPOSURE_MIN: f32 = 1.0 / 32.0;

/// The brightest exposure [`ForwardRenderer::set_exposure`] will accept: **five
/// stops above** [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`], for
/// [`EXPOSURE_MIN`]'s reason.
pub const EXPOSURE_MAX: f32 = 32.0;

/// The default has to be reachable from both ends of the range, or a control
/// that steps by a ratio starts somewhere it can only leave in one direction.
const _: () = assert!(
    EXPOSURE_MIN > 0.0
        && EXPOSURE_MIN < crcbl_shaders::tonemap::DEFAULT_EXPOSURE
        && EXPOSURE_MAX > crcbl_shaders::tonemap::DEFAULT_EXPOSURE
);

/// The format the frame's depth buffer is created with, taken from the
/// description that creates it rather than written down a second time.
///
/// Read by [`ForwardRenderer::set_ground_grid`], whose pipeline is built for a
/// depth attachment before there is a frame to ask. The extent is irrelevant to
/// a format, which is why any is passed.
pub(crate) const SCENE_DEPTH_FORMAT: Format = crate::targets::scene_depth((1, 1)).format;

/// The format the frame's HDR scene target is created with, taken from the
/// description that creates it rather than written down a second time.
///
/// Read by [`crate::debug_draw`], whose pipeline blends into whichever image the
/// chain of HDR passes ended with — every one of them is a
/// [`crate::targets::scene_color`]. The extent is irrelevant to a format,
/// which is why any is passed.
pub(crate) const SCENE_COLOR_FORMAT: Format = crate::targets::scene_color((1, 1)).format;

/// The format §3.2's base-colour page is created with.
///
/// **`Rgba8UnormSrgb`, and that is the colour-space decision** — the argument
/// for it is at the `upload_texture_mip_layers` call inside
/// [`ForwardRenderer::with_scene`]. Named rather than spelled twice because
/// [`ForwardRenderer::base_color_page_import`] has to declare the same format
/// the image was created with, and a barrier naming a format the image is not in
/// picks the wrong aspects.
const BASE_COLOR_PAGE_FORMAT: Format = Format::Rgba8UnormSrgb;

/// The format topic 43 §2's **normal** page is
/// created with.
///
/// **`Rgba8Unorm`, and the missing `Srgb` is the whole decision.**
/// Topic 44's rung 2 argues it: a base-colour texel is a
/// colour and glTF defines it as sRGB-encoded, so the format above is what makes
/// the sampler decode it; a normal texel is a *number* — three components of a
/// direction, stored as `n * 0.5 + 0.5` — and pushing it through the sRGB
/// transfer curve is wrong by a gamma. What that looks like is not an error but
/// a surface that leans further off vertical than the author drew, which is why
/// the mistake survives review everywhere it is made.
///
/// `the_page_formats_split_colour_from_number` is the whole guard, and it is
/// worth having because the four constants sit a few lines apart and the wrong
/// one compiles.
const NORMAL_PAGE_FORMAT: Format = Format::Rgba8Unorm;

/// The format topic 43 §2's **metallic-roughness-
/// occlusion** page is created with.
///
/// **`Rgba8Unorm`, and the missing `Srgb` is the same decision
/// [`NORMAL_PAGE_FORMAT`] argues.** An occlusion, a roughness and a metalness
/// are numbers rather than colours — glTF 2.0 §3.9.2 and §3.9.5 define them as
/// linear factors — and a surface shaded through an sRGB decode of them is
/// smoother and shinier than the author drew, which is a failure that survives
/// review because it looks like a choice.
///
/// A separate constant from [`NORMAL_PAGE_FORMAT`] rather than a reuse of it,
/// for [`LTC_SIZE_U32`]'s reason: the two stand for different facts, and a day
/// one of them wanted a different format should be an edit here rather than a
/// search for which callers of a shared name meant which page.
const MRO_PAGE_FORMAT: Format = Format::Rgba8Unorm;

/// The format topic 43 §2's **emissive** page is
/// created with.
///
/// **`Rgba8UnormSrgb`, and it is the base-colour page's decision rather than
/// the normal page's.** An emissive texel is a colour: glTF 2.0 §3.9.4 defines
/// `emissiveTexture` as sRGB-encoded exactly as it defines `baseColorTexture`,
/// and `GpuMaterial::emissive` beside it is a linear radiance, so the format is
/// what puts the two in one space before they are multiplied.
///
/// A separate constant from [`BASE_COLOR_PAGE_FORMAT`] for the reason above it,
/// and `the_page_formats_split_colour_from_number` is the guard that the four
/// do not drift into one another.
const EMISSIVE_PAGE_FORMAT: Format = Format::Rgba8UnormSrgb;

/// What the renderer needs of a [`PageKind`] to create and fill its image.
///
/// Written here rather than in [`crate::scene`] because the two answers are the
/// device's: the format is the one [`base_color_page_import`] and
/// [`normal_page_import`] have to declare, and the filter is the one
/// [`crate::mip`] builds the chain with. A kind added by
/// topic 43 §2's rung 3 is a new arm in each.
///
/// [`base_color_page_import`]: ForwardRenderer::base_color_page_import
/// [`normal_page_import`]: ForwardRenderer::normal_page_import
impl PageKind {
    /// The format this kind's image is created with.
    ///
    /// The sRGB in one and its absence in the other is the whole colour-space
    /// decision — see [`BASE_COLOR_PAGE_FORMAT`] and [`NORMAL_PAGE_FORMAT`],
    /// which is where each is argued.
    const fn format(self) -> Format {
        match self {
            Self::BaseColor => BASE_COLOR_PAGE_FORMAT,
            Self::Normal => NORMAL_PAGE_FORMAT,
            Self::MetallicRoughnessOcclusion => MRO_PAGE_FORMAT,
            Self::Emissive => EMISSIVE_PAGE_FORMAT,
        }
    }

    /// Every mip level below `level0`, built on the host with this kind's own
    /// filter.
    ///
    /// [`crate::mip::normal_chain`] averages the decoded vectors plainly and
    /// renormalises, where [`crate::mip::chain`] decodes an sRGB curve and
    /// weights by alpha. A normal map mipped through the colour filter leans
    /// further off vertical at every level than the map it was built from, and
    /// nothing in a frame reports it.
    fn chain(self, level0: &[u8], extent: u32) -> Vec<Vec<u8>> {
        match self {
            Self::BaseColor | Self::Emissive => crate::mip::chain(level0, extent),
            Self::Normal => crate::mip::normal_chain(level0, extent),
            Self::MetallicRoughnessOcclusion => crate::mip::linear_chain(level0, extent),
        }
    }

    /// The device label this kind's image is created under.
    const fn upload_label(self) -> &'static str {
        match self {
            Self::BaseColor => "material base colour",
            Self::Normal => "material normals",
            Self::MetallicRoughnessOcclusion => "material metallic-roughness-occlusion",
            Self::Emissive => "material emissive",
        }
    }
}

/// The one texel a page **nothing names** is created with.
///
/// [`crate::texture::upload_texture_mip_layers`] refuses a zero-layer image, and
/// every bind group of the mesh layout has to fill both page bindings whether or
/// not the description carried either page — so a [`PageKind`] with no layers
/// gets a 1×1 single-layer image in its own format instead of an `extent²` one
/// nobody samples. That is the whole of what row (d) bought back:
/// `apps/alcove`, `apps/sundial` and `apps/quarry` name no page at all, and
/// every scene in the tree that has no normal map used to carry a full neutral
/// layer and a third again for its chain.
///
/// **Magenta, and it is never sampled for its value.** A material naming no page
/// carries [`GpuMaterial::NO_PAGE`](mesh::GpuMaterial::NO_PAGE):
/// `mesh.slang`'s `base_color_texel` discards the fetch with a select and
/// returns the literal `1.0`, and `shading_normal_of` returns before it fetches
/// at all. So nothing should ever read this — and the value is chosen so that if
/// something does, the frame says so in a colour no lit surface in this engine
/// produces. White would blend into every untextured surface and black would
/// read as a shadow; both are failures a golden could pass.
const PAGE_PLACEHOLDER_TEXEL: [u8; 4] = [0xFF, 0x00, 0xFF, 0xFF];

/// The format the motion-vector target is created with: two channels of half
/// float, topic 43 §9's third colour attachment.
///
/// **Named here rather than in [`crate::targets::motion`]**, on
/// [`crate::graph`]'s other format-owning descriptions' terms: the description
/// and
/// [`MeshModules::COLOR_TARGETS`] have to agree, and the pass that builds the
/// pipeline is the one that owns the answer.
///
/// # The convention the target holds, so a consumer never has to guess it
///
/// **Current minus previous, in texture coordinates, `+y` down.** A pass
/// holding the previous frame reads its history at `uv - motion`, and a surface
/// travelling right and down the screen has both components positive.
/// `mesh.slang`'s `motion_vector` is where the mapping is written out and this
/// is the same sentence on the host side, because the first consumer will read
/// one of the two and not both.
///
/// # Two channels and half float
///
/// A motion vector is a screen-space offset and has no third component. Half
/// float rather than a normalised integer because the value is signed and
/// unbounded — an object crossing the frame in one frame is a motion past `1.0`
/// — and because the interesting magnitudes are small: a surface moving a
/// tenth of a pixel is the case a temporal filter is most sensitive to, and
/// eight or even sixteen unsigned bits over a `-1..1` range would quantise it
/// into rest. It is also the format `crcbl_hal::Format::Rg16Float`'s own doc
/// names motion vectors as the use for.
pub(crate) const MOTION_FORMAT: Format = Format::Rg16Float;

/// Which picture the colour pass draws instead of the shaded one.
///
/// The engine's debug views, as one value rather than as independent booleans,
/// because they are not independent: every one of them rides in a single lane of
/// the frame's uniform block and the shaders test the thresholds outermost
/// first, so a renderer with two of them set draws exactly one.
/// [`ForwardRenderer::debug_view`] is where that order lives, and this is what it
/// answers with — so a menu row, a debug panel and the picture cannot disagree
/// about which view is on.
///
/// **The declaration order is not the precedence** — each view was appended as
/// it arrived, and [`ForwardRenderer::debug_view`] is the one place the order is
/// decided. The sentinels in
/// [`FrameUniforms`](crcbl_shaders::mesh::FrameUniforms) ascend with it, though:
/// see its `HEATMAP_VIEW_ON`, and the shaders test the outermost threshold
/// first.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DebugView {
    /// The lit picture. What every frame draws unless a caller asked otherwise.
    #[default]
    Shaded,
    /// Each cluster shaded by the projected screen-space error the LOD
    /// selection judged it on — [`ForwardRenderer::set_heatmap`].
    Heatmap,
    /// Each cluster tinted by the DAG level it was decimated to —
    /// [`ForwardRenderer::set_lod_view`].
    LodTint,
    /// World-space surface normals — [`ForwardRenderer::set_normals_view`].
    Normals,
    /// The ambient-occlusion channel alone, as grey —
    /// [`ForwardRenderer::set_occlusion_view`].
    AmbientOcclusion,
    /// The motion vector each fragment wrote, stretched and centred on grey —
    /// [`ForwardRenderer::set_motion_view`].
    Motion,
    /// The bent direction the occlusion channel carries beside its scalar, as
    /// `n * 0.5 + 0.5` — [`ForwardRenderer::set_bent_normal_view`]. **Wins over
    /// every other view.**
    BentNormal,
    /// The sun's cascades and the lit tiles beside them — the `D32Float` shadow
    /// atlas itself, letterboxed over the finished frame with a border round
    /// every occupied slot — [`ForwardRenderer::set_atlas_view`].
    ///
    /// **The one view that is a pass rather than a branch in `mesh.slang`**, and
    /// therefore the one whose lane is the off sentinel: the colour pass draws
    /// the shaded picture exactly as it always did and `crate::atlas_view`
    /// replaces it afterwards. That module's header is where the placement is
    /// argued.
    ///
    /// It resolves **below every view above and above [`Self::Cascades`]** — see
    /// [`ForwardRenderer::debug_view`].
    ShadowAtlas,
    /// The shaded picture tinted by the cascade each sun-lit fragment's shadow
    /// was sampled from, with the cross-fade band drawn as the blend of the two
    /// — [`ForwardRenderer::set_cascade_view`].
    ///
    /// **Loses to every other view**, and it is the only one that does. The views
    /// above draw something *instead of* the shaded picture; this one draws the
    /// shaded picture and multiplies it, so there is nothing left for it to
    /// modulate as soon as one of them is on. See
    /// [`ForwardRenderer::debug_view`].
    Cascades,
}

impl DebugView {
    /// What a panel row or a summary line calls it.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::Shaded => "shaded",
            Self::Heatmap => "heatmap",
            Self::LodTint => "lod tint",
            Self::Normals => "normals",
            Self::AmbientOcclusion => "ambient occlusion",
            Self::Motion => "motion",
            Self::BentNormal => "bent normal",
            Self::ShadowAtlas => "shadow atlas",
            Self::Cascades => "cascades",
        }
    }
}

// Mesh-only resources follow the complete common fragment binding range.
// Metal assigns dense native indices by resource-table order, so inserting a
// mesh-only buffer before lights/probes would shift the layout away from the
// independently compiled fragment stage. Sparse logical bindings cost no slots.
const CLUSTERS_BINDING: u32 = 32;
const CLUSTER_VERTICES_BINDING: u32 = 33;
const CLUSTER_CORNERS_BINDING: u32 = 34;
const CLUSTER_DRAW_ARGS_BINDING: u32 = 35;
const CLUSTER_CULL_BINDING: u32 = 36;
const CLUSTER_CULL_STATS_BINDING: u32 = 37;
const CLUSTER_SELECT_BINDING: u32 = 38;
const CLUSTER_SELECTION_BINDING: u32 = 39;
const CLUSTER_GROUP_STATE_BINDING: u32 = 40;

/// The shared fragment shader's shadow atlas slot. Historical logical gaps
/// remain reserved so the raster shader bindings stay unchanged.
const SHADOW_ATLAS_BINDING: u32 = 15;

/// The bind-group slot the shadow atlas's **comparison** sampler is bound to.
const SHADOW_SAMPLER_BINDING: u32 = 16;

/// The bind-group slot the base-colour page is bound to.
///
/// Named because [`ForwardRenderer::replace_page`] rewrites it in every group
/// of the mesh layout, as it does each page's binding — see
/// `pages::page_binding`.
const BASE_COLOR_PAGE_BINDING: u32 = 7;

/// The bind-group slot the base-colour page's sampler is bound to.
///
/// Named because it is an entry [`ForwardRenderer::set_anisotropy`] rewrites
/// in every group of the mesh layout: a sampler is a resource a group holds by
/// handle, so a new sampler is a new group, and the rebuild finds the entry by
/// this number.
const PAGE_SAMPLER_BINDING: u32 = 8;

/// The shared fragment shader's light list. Both shader modules declare it
/// before mesh-only buffers so native buffer index 7 is common to both stages.
const LIGHT_LIST_BINDING: u32 = 20;

/// The bind-group slot the froxel grid is read through.
const LIGHT_GRID_BINDING: u32 = 21;

/// The fragment shader's screen-space occlusion texture. Mesh-only additions
/// are buffers, so this resource does not shift their native argument table.
const AMBIENT_OCCLUSION_BINDING: u32 = 22;

/// The shared irradiance probe table, native buffer 9 in both shader modules.
/// `mesh_cluster.slang` mirrors it before its own buffers to preserve the prefix.
const PROBE_TABLE_BINDING: u32 = 23;

/// The mesh path's packed `DrawGen` table, read for the screen-error heatmap.
/// Its logical binding stays 24; after the shared fragment buffer prefix it is
/// native buffer 10. The raster path does not declare this storage buffer.
const LEVEL_GROUP_TABLE_BINDING: u32 = 24;

/// The bind-group slot the split-sum `DFG` table is fetched through — how much
/// of the light arriving at a GGX lobe that lobe hands back.
///
/// No mirror is needed in `mesh_cluster.slang`: that module adds only buffers
/// after the shared prefix. The fragment shader's `specular_dfg` remains at
/// native texture 3, following `ambient_occlusion` at texture 2.
///
/// **An image rather than a storage buffer, and that is forced.** The table is
/// 4096 pairs and a buffer would carry it exactly; but the raster path's layout
/// is at the WebGPU storage-buffer ceiling in its *vertex* stage, and Slang's
/// Metal backend materialises every global into every entry point — so a row
/// bound to the fragment stage alone would be a global the vertex stage names
/// and nothing fills. See [`crcbl_hal::check_portable_storage_buffers`] and
/// binding 7's `geometry` visibility.
const SPECULAR_DFG_BINDING: u32 = 25;

/// The bind-group slot §2's normal page is sampled through.
///
/// **Appended past [`SPECULAR_DFG_BINDING`], never inserted**, for
/// [`PROBE_TABLE_BINDING`]'s reason exactly: `crcbl-mtl` gives a resource the
/// next index in its Metal argument table by counting the same-table entries of
/// this layout, and Slang numbers a stage's arguments by declaration order, so
/// the two agree only while both ascend. No mirror is needed in
/// `mesh_cluster.slang`, which adds only buffers after the shared prefix.
///
/// **No sampler of its own.** The page is read through
/// [`PAGE_SAMPLER_BINDING`]'s sampler, the same trilinear anisotropic one the
/// base-colour page uses, because it is sampled at the same UV over an image of
/// the same extent. A second sampler would be a second layout entry, a second
/// index in Metal's sampler argument table, and a second thing
/// [`ForwardRenderer::set_anisotropy`] has to rebuild — for a filter that would
/// be identical.
const NORMAL_PAGE_BINDING: u32 = 26;

/// The bind-group slot topic 44's rung 5 reads its linearly
/// transformed cosine table through.
///
/// **Appended past [`NORMAL_PAGE_BINDING`], never inserted**, for that
/// constant's reason exactly: `crcbl-mtl` gives a resource the next index in its
/// Metal argument table by counting the same-table entries of this layout, and
/// Slang numbers a stage's arguments by declaration order, so the two agree only
/// while both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it
/// needs no mirror there and no index anything already owns moves.
///
/// **No sampler**, like the table two rows below it: four `Load`s and a bilinear
/// blend written out in the shader, because a hardware filter's weights are
/// fixed-function arithmetic four rasterisers compute independently and these
/// goldens are compared across all four.
const LTC_TABLE_BINDING: u32 = 27;

/// The bind-group slot topic 45's contact-shadow channel is
/// read through.
///
/// **Appended past [`LTC_TABLE_BINDING`], never inserted**, for that constant's
/// reason exactly: `crcbl-mtl` gives a resource the next index in its Metal
/// argument table by counting the same-table entries of this layout, and Slang
/// numbers a stage's arguments by declaration order, so the two agree only while
/// both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it needs
/// no mirror there and no index anything already owns moves.
///
/// **No sampler**, like the occlusion channel: `mesh.slang`'s `contact_at` is a
/// clamped `Load` at `SV_Position.xy`, and the channel is exactly the size of
/// the frame on every pass that computed one.
const CONTACT_SHADOW_BINDING: u32 = 28;

/// The bind-group slot the irradiance probes' per-probe
/// visibility maps are read through: one `Rg32Float` layer per probe.
///
/// **Appended past [`CONTACT_SHADOW_BINDING`], never inserted**, for that
/// constant's reason exactly: `crcbl-mtl` gives a resource the next index in its
/// Metal argument table by counting the same-table entries of this layout, and
/// Slang numbers a stage's arguments by declaration order, so the two agree only
/// while both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it
/// needs no mirror there and no index anything already owns moves —
/// `msl/mesh.metal` puts it at `texture(7)`, the next free index of that table.
///
/// **A texture rather than a storage buffer, and that is forced**: the raster
/// path's vertex stage is already at every storage buffer a WebGPU device
/// guarantees, which is the same reason [`SPECULAR_DFG_BINDING`] is an image.
///
/// **No sampler**, like the occlusion channel and both cooked tables:
/// `mesh.slang`'s `probe_moments` is four clamped `Load`s and a blend written
/// out, because a hardware filter's weights are fixed-function arithmetic four
/// rasterisers compute independently — and because `Rg32Float` is not a
/// filterable format on WebGPU without an optional feature.
const PROBE_VISIBILITY_BINDING: u32 = 29;

/// The bind-group slot topic 43 §2's packed
/// **metallic-roughness-occlusion** page is sampled through.
///
/// **Appended past [`PROBE_VISIBILITY_BINDING`], never inserted**, for
/// [`NORMAL_PAGE_BINDING`]'s reason exactly: `crcbl-mtl` gives a resource the
/// next index in its Metal argument table by counting the same-table entries of
/// this layout, and Slang numbers a stage's arguments by declaration order, so
/// the two agree only while both ascend. No mirror is needed in
/// `mesh_cluster.slang`, which adds only buffers after the shared prefix.
///
/// **No sampler of its own**, for [`NORMAL_PAGE_BINDING`]'s reason: the page is
/// read at the same UV over an image of the same shape as the base-colour one,
/// so it goes through [`PAGE_SAMPLER_BINDING`]'s sampler and adds no entry to
/// Metal's sampler argument table.
const MRO_PAGE_BINDING: u32 = 30;

/// The bind-group slot topic 43 §2's **emissive**
/// page is sampled through.
///
/// **Appended past [`MRO_PAGE_BINDING`], never inserted**, for that constant's
/// reason exactly, and it shares [`PAGE_SAMPLER_BINDING`]'s sampler on the same
/// terms. `mesh_cluster.slang` adds only buffers after these textures, so it needs no
/// mirror there and no index anything already owns moves.
const EMISSIVE_PAGE_BINDING: u32 = 31;

/// [`crcbl_shaders::dfg::DFG_SIZE`] as an image extent.
///
/// The table is square, and its size is a compile-time constant, so the
/// conversion belongs here rather than as a fallible one at the upload.
const DFG_SIZE_U32: u32 = dfg::DFG_SIZE as u32;

/// [`crcbl_shaders::ltc::LTC_SIZE`] as an image extent.
///
/// The same number as [`DFG_SIZE_U32`], and a separate constant rather than a
/// reuse of it: `crcbl_shaders::ltc`'s `the_grid_is_the_dfg_table_s_grid` is
/// what says the two tables are the same square, and each upload naming its own
/// module is what would make a day they were not into a compile error here
/// rather than a stretched image.
const LTC_SIZE_U32: u32 = ltc::LTC_SIZE as u32;

/// The `Rgba8Unorm` texel that occludes nothing and steers nothing.
///
/// What [`ForwardRenderer::ambient_occlusion_placeholder`] holds, and therefore
/// what `mesh.slang` reads on a frame drawing without
/// [`RenderEffects::AMBIENT_OCCLUSION`].
///
/// **`r` is `0xFF`, which is `1.0`**: the shading multiplies its ambient by
/// this and the term is untouched. Any other value would be a silent global
/// ambient scale.
///
/// **`gba` are [`ssao::BENT_NORMAL_NONE`], which decodes to a zero-length
/// direction** — the sentinel the occlusion chain writes wherever it has no
/// bent direction to report, and which `mesh.slang`'s `bent_normal_at` answers
/// with the fragment's own shading normal. So "no occlusion pass ran" and "no
/// direction at this pixel" are one case with one answer, and a frame drawn
/// with the effect off is the frame this renderer drew before the channel was
/// widened. Encoding a direction here instead would tilt every ambient term in
/// such a frame towards one world axis.
const AMBIENT_OCCLUSION_NONE: [u8; 4] = [
    0xFF,
    ssao::BENT_NORMAL_NONE,
    ssao::BENT_NORMAL_NONE,
    ssao::BENT_NORMAL_NONE,
];

/// The `R8Unorm` texel the sun reaches unobstructed: `1.0`, which is `0xFF`.
///
/// What [`ForwardRenderer::contact_shadow_placeholder`] holds, and therefore
/// what `mesh.slang` reads on a frame drawing without
/// [`RenderEffects::CONTACT_SHADOWS`] — it multiplies `sun_visibility` by this
/// and the cascades have the last word alone. Any other value would be a silent
/// global scale on the sun.
///
/// The same byte as [`AMBIENT_OCCLUSION_NONE`]'s first and a constant of its
/// own, for the reason [`LTC_SIZE_U32`] is not [`DFG_SIZE_U32`]: the two
/// placeholders stand for different facts, and a day one of them wanted a
/// different value should be an edit here rather than a search for which
/// callers of a shared name meant which thing.
const CONTACT_SHADOW_NONE: u8 = 0xFF;

/// The one `Rg32Float` texel that occludes nothing: a mean distance of
/// [`probe_visibility::FAR`](crcbl_shaders::probe_visibility::FAR) and its
/// square.
///
/// What [`ForwardRenderer::probe_visibility_placeholder`] holds, and therefore
/// what `mesh.slang` reads on a frame drawn before anything was captured or with
/// `r_probe_visibility` off. No surface in any scene is further away than that,
/// so `probe_weight` answers one for every probe and every fragment, and the
/// grid is the unweighted trilinear blend it was before this rung — which is
/// what makes the off position bit-identical rather than merely close.
///
/// Any *smaller* value would be a silent occluder: every probe in every scene
/// would read as being behind a wall, and the whole grid would collapse onto
/// `PROBE_OCCLUDED_WEIGHT`.
fn probe_visibility_none() -> [u8; crcbl_shaders::probe_visibility::TEXEL_BYTES] {
    let mut texel = [0u8; crcbl_shaders::probe_visibility::TEXEL_BYTES];
    let far = crcbl_shaders::probe_visibility::FAR;
    texel[..4].copy_from_slice(&far.to_le_bytes());
    texel[4..].copy_from_slice(&(far * far).to_le_bytes());
    texel
}

/// The reversed-Z far plane, in the two places that have to agree about it.
///
/// `ssao.slang` leaves early at exactly this depth because the unprojection there
/// divides by a `clip.w` an infinite reversed-Z projection takes to zero. The
/// shader cannot include the seam and `crcbl-shaders` does not depend on it, so
/// the mirror is checked here — which is the only place both names are in scope.
const _: () = assert!(crcbl_hal::depth::CLEAR == crcbl_shaders::ssao::DEPTH_FAR);

/// How many buckets a resident mesh occupies, which is **not the same on every
/// geometry path** — the one place in this renderer the two differ in shape
/// rather than in the call they record.
///
/// A flat mesh is one bucket either way. A DAG is one bucket on
/// [`EmitTail::Mesh`]: a bucket is a mesh's run of clusters, and the point of
/// topic 25's per-cluster selection is that one dispatch covers
/// several levels at once, so the run is every level's clusters end to end and
/// the bucket's mesh id is level 0's.
///
/// On the two indirect tails a DAG is one bucket **per level**, because there
/// the same plan takes a uniform cut and a level is drawn as an ordinary index
/// range: a DAG's levels are separate mesh table entries, `draw_gen.slang`
/// selects one per instance, and a bucket is what an indexed draw of one index
/// range *is*. See [`ForwardRenderer::level_buckets`].
const fn buckets_for(levels: usize, emit: EmitTail) -> usize {
    if emit.is_mesh() { 1 } else { levels }
}

/// Every material mode this renderer routes a draw by, and the order the bucket
/// table lays its per-mode runs of every mesh's levels down in.
///
/// [`GpuMaterial::mode`](mesh::GpuMaterial::mode)'s whole range, which is why
/// the routing is total rather than checked: a row's mode is
/// `flags & GpuMaterial::MODE_MASK`, that mask is the alpha-mask bit and the
/// double-sided one, and the four combinations of them are these — so no
/// material can carry a mode that is not in this list and no instance can
/// scatter into a bucket that does not exist. Widening the mask means adding the
/// mode here **and** giving it a depth pipeline in
/// [`ForwardRenderer::depth_partitions`] in the same change — the two are the
/// producer and the consumer of one list.
///
/// **A scene emits a twin per mode its own materials carry**, not one per
/// entry here: two materials of two modes are two twins whichever two they are,
/// and only a scene actually holding all four pays for four. The build below is
/// where that filter is, and this module's
/// `an_all_opaque_scene_keeps_one_bucket_per_mesh_level` is what holds it.
const DEPTH_MODES: [u32; 4] = [
    0,
    mesh::GpuMaterial::ALPHA_MODE_MASK,
    mesh::GpuMaterial::DOUBLE_SIDED,
    mesh::GpuMaterial::ALPHA_MODE_MASK | mesh::GpuMaterial::DOUBLE_SIDED,
];

/// A pipeline and its [`CullMode::None`] twin: the two objects a pass binds to
/// draw single-sided and double-sided buckets of one frame.
///
/// **A pipeline rather than a per-draw state, because no backend seam exposes
/// dynamic cull mode** — and `crcbl_hal::CommandEncoder::set_stencil_reference`
/// is the precedent for why one would not be added: a raster state a recorded
/// stream carried per draw is a state every backend has to be able to change
/// between two indirect calls, and the portable answer to "this draw rasterises
/// differently" is a second pipeline. Which draws take which is
/// [`ForwardRenderer::sided_partitions`].
///
/// Four passes need the pair — the colour pass, the two depth-only ones and the
/// reflective shadow map — so it is a type rather than eight fields, and the
/// twins are built together so a renderer can never hold one without the other.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct SidedPipelines {
    /// [`CullMode::Back`]: every bucket whose material is single-sided, which is
    /// every bucket of every scene that does not use `doubleSided`.
    single: GraphicsPipelineHandle,
    /// [`CullMode::None`]: the buckets whose material carries
    /// [`GpuMaterial::DOUBLE_SIDED`](mesh::GpuMaterial::DOUBLE_SIDED).
    ///
    /// Built on every scene rather than only on one that has such a material,
    /// for [`MeshModules::depth_masked_pipeline`]'s stated reason: the modules
    /// are released inside `build` and a pipeline built later would need them
    /// back, which is a second shader compilation.
    double: GraphicsPipelineHandle,
}

/// The pixel budget topic 25's descent compares a group's projected
/// error against, unless a caller sets another with
/// [`ForwardRenderer::set_lod_error_budget`].
///
/// One pixel, because that is what the metric is *for*: a level's error is how
/// far its simplification may have moved the surface, so a budget of a pixel is
/// the point at which a level change stops being something a viewer can see.
/// The plan's "correct thresholds make pops sub-pixel by definition" is this
/// number.
const LOD_ERROR_BUDGET: f32 = 1.0;

/// Bytes one bucket's draw-constant block occupies, whichever of the two blocks
/// it holds.
///
/// The larger of [`mesh::DRAW_CONSTANTS_SIZE`] and
/// [`CLUSTER_DRAW_CONSTANTS_SIZE`](crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE),
/// because which one a bucket holds is the geometry path's decision and the
/// buffer, its dynamic stride and the range the bind group names are all fixed
/// before that decision reaches them.
///
/// **The bound range is the half that bites.** A range sized for the smaller
/// block leaves the larger one's tail outside it, and a uniform read past the
/// bound range is not a fault — it is a zero. Sized at sixteen bytes, the mesh
/// path's `group_stride` read back as zero and every instance descended against
/// instance zero's LOD state.
const DRAW_CONSTANTS_BLOCK: u64 =
    if mesh::DRAW_CONSTANTS_SIZE > crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE {
        mesh::DRAW_CONSTANTS_SIZE as u64
    } else {
        crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE as u64
    };

/// How far below the budget an already-expanded group is held before it
/// collapses again — topic 25's "switch-up and switch-down differ",
/// as a fraction of [`LOD_ERROR_BUDGET`].
///
/// A ratio and not an offset because the band has to scale with the budget: a
/// fixed number of pixels is most of a one-pixel budget and none of a fifty-pixel
/// one. A fifth of the budget is a deadband a camera has to move decisively out
/// of, and one a camera drifting along a boundary never leaves — which is the
/// flicker the plan is about. `crcbl_shaders::cluster_select::LodBudgets` is the
/// pair this produces, and a ratio of one is that type's `sharp`: no band, and
/// the setting that shows the band is what stops the flicker.
const LOD_HOLD_RATIO: f32 = 0.8;

/// How much larger than the camera's the pixel budget a shadow cascade selects
/// under is — topic 25's "**Shadow LOD bias**: shadow-pass culling
/// selects +1/+2 coarser levels — casters are cheap where it never shows".
///
/// # A budget factor, because a level is not a parameter of the rule
///
/// The descent compares a group's projected error to a pixel budget; it never
/// names a level. So "one or two levels coarser" is an *intent*, and the budget
/// that produces it is the setting — and the two do not convert, because how far
/// apart two levels' errors are is a property of the mesh. The committed dunes
/// DAG is the demonstration: the step from one level's error to the next is
/// several times larger in the middle of that hierarchy than at its base, and
/// across its top levels there is no step at all — they report one error and are
/// never separately selected by any budget. A bias expressed in levels would
/// mean something different at each of those. `cook-clusters` prints the per
/// level errors it built.
///
/// Four, then, is two doublings of the budget: enough that a caster is drawn
/// coarser than the same object is in the colour pass, and small enough to stay
/// inside what a shadow hides. What hides it is that a shadow edge is filtered —
/// the atlas is read through a comparison sampler with linear filtering, so an
/// edge arrives already spread over neighbouring texels — and that the atlas
/// quantises every caster to [`shadow::TILE`] texels per cascade before anything
/// samples it.
///
/// # Why one number, applied to the whole pass
///
/// **A cut is a cover only while expansion is monotone up the DAG**, and this
/// scaling is what keeps it so. Multiplying both budgets by one positive
/// constant leaves the rule in
/// [`crcbl_shaders::cluster_select`]'s form with different constants in it, and
/// that module's induction turns on the projected error being monotone up the
/// DAG rather than on what the constants are — so the shadow pass's cut is a
/// cover for exactly the reason the camera's is. A bias that varied by cluster,
/// by group, by level or by cascade would not be: two groups on one branch would
/// be judged against different budgets, and a child expanding under an
/// unexpanded parent is a hole.
///
/// Being larger than one also makes the shadow pass's expanded set a **subset**
/// of the colour pass's, since the two now select from one eye at one scale: a
/// group over `k` times the budget is over the budget. So the shadow cut is
/// never finer than the camera's anywhere, which is the property
/// `crcbl-vk`'s `the_shadow_cascades_select_coarser_than_the_camera` reads back
/// and asserts.
pub const SHADOW_LOD_BIAS: f32 = 4.0;

/// How many culls the shadow atlas needs: one per cascade and **one per shadowed
/// light**, whatever kind of light it is.
///
/// Topic 18's fourth decision, as a number. A point light's six faces share the
/// light's sphere — which is what a cull tests against — so they share one
/// [`DrawGen`] and its visible set, and the six draws differ in a matrix and a
/// viewport. Six generators per light would be six copies of
/// [`TileBuffers::group_state`], which is where the cost of one is written down.
const SHADOW_CULLS: usize = shadow::CASCADES + shadow::LIGHT_SLOTS;

/// How many shadow *views* there are: one per cascade, and one per face of every
/// light slot.
///
/// A view is what has a matrix, so it is what has a frame-block copy, a bind
/// group and a cut of its own — while a *tile* is where a view lands in the
/// atlas and a *cull* is which visible set it draws. The three were one number
/// until a light could own six tiles.
///
/// Every slot carries [`shadow::POINT_FACES`] views whether the light in it is a
/// point or a spot, because a bind group names its buffers when it is created
/// and the kind of light holding a slot changes per frame. A spot uses face 0's
/// view and the other five are never recorded — they cost a uniform buffer and a
/// descriptor each, which is nothing beside the [`DrawGen`] a second *cull*
/// would cost.
const SHADOW_VIEWS: usize = shadow::CASCADES + shadow::LIGHT_SLOTS * shadow::POINT_FACES;

/// Cascade 0's view, which is the one the irradiance probes'
/// reflective shadow map is drawn through.
///
/// **A cascade is its own view index**, which is what `add_shadow_pass`'s view
/// list pushes; [`shadow_view`] numbers a *light slot's* faces and starts past
/// [`shadow::CASCADES`], so it is not the function to reach for here.
const CASCADE_ZERO_VIEW: usize = 0;

const _: () = assert!(
    CASCADE_ZERO_VIEW < shadow::CASCADES,
    "cascade 0's view has to be one of the cascades' own, not a light slot's"
);

/// Which view is face `face` of light slot `slot`.
const fn shadow_view(slot: usize, face: usize) -> usize {
    shadow::CASCADES + slot * shadow::POINT_FACES + face
}

/// Which cull light slot `slot` draws from.
const fn shadow_cull(slot: usize) -> usize {
    shadow::CASCADES + slot
}

/// One punctual shadow face this frame draws into the punctual reflective
/// shadow map, and everything both halves of the updater need of it.
///
/// The irradiance probes' punctual producer. It carries no
/// matrix and no visible set: a face's transform is already in the uniform block
/// [`ForwardRenderer::shadow_groups`] binds, and its draws are the ones its
/// slot's cull generated for the atlas — which is what makes this rung cost no
/// second cull and no second matrix.
#[derive(Clone, Copy, Debug)]
struct PunctualFace {
    /// Which shadow view this face is — [`shadow_view`]'s answer, and the index
    /// of the bind group whose block holds that face's own `view_proj`.
    view: usize,
    /// Which of the frame's shadow culls generated its draws — [`shadow_cull`]'s
    /// answer for the slot this face belongs to.
    cull: usize,
    /// Which face of its light this is, and so — where the light's cull tagged
    /// its casters by face — which draw region it draws.
    face: usize,
    /// Where it lands in the punctual map — [`rsm::punctual_tile`], which is the
    /// rectangle the pass sets its viewport to *and* the one the gather reads
    /// this face's texels out of.
    tile: shadow::TileRect,
    /// The light this is a face of, as the gather weighs its texels.
    producer: PunctualProducer,
}

/// The draw region face `face` of a light draws: its own region where the
/// light's cull tagged casters by face, and region 0 — every survivor — where it
/// did not. See [`crcbl_shaders::draw_gen::FACE_REGION_BASE`].
fn face_region(by_face: bool, face: usize) -> u32 {
    if by_face {
        crcbl_shaders::draw_gen::FACE_REGION_BASE
            + u32::try_from(face).unwrap_or_else(|_| unreachable!("a light has six faces"))
    } else {
        0
    }
}

/// One light's row in the gather's producer table, for the face standing at
/// `tile`.
///
/// **Built out of the light's own row**, which is the one place a light becomes
/// numbers — so the falloff, the cone and the colour the bounce is weighed by
/// are the very ones `mesh.slang` weighs the same light's direct term by, rather
/// than a second reading of the same fields that could round or widen
/// differently. [`Light::row`](crate::light::Light::row) is handed [`None`]
/// because a producer occludes through nothing: the gather gates a texel with
/// the probe's own visibility map, not with the light's.
fn producer_row(light: &Light, tile: shadow::TileRect) -> PunctualProducer {
    let row = light.row(None);
    PunctualProducer {
        position: [row.position[0], row.position[1], row.position[2]],
        radius: row.position[3],
        color: [row.color[0], row.color[1], row.color[2]],
        cos_outer: row.direction[3],
        axis: [row.direction[0], row.direction[1], row.direction[2]],
        cos_inner: row.cos_inner,
        origin: [tile.x, tile.y],
        side: tile.side,
        kind: row.kind,
    }
}

const _: () = assert!(
    SHADOW_CULLS == shadow::GROUPS,
    "a cull is a cadence group: `shadow::Cadence` schedules what this file \
     dispatches, and two different counts would schedule a group nothing draws"
);

/// Vertices in the over-sized triangle `mesh.slang`'s `depthClearVertexMain`
/// generates from `SV_VertexID`. No geometry is bound.
const TILE_CLEAR_VERTICES: u32 = 3;

const _: () = assert!(
    crcbl_shaders::mesh::SHADOW_ATLAS_CLEAR_DEPTH == crcbl_hal::depth::CLEAR,
    "the stage that resets one tile writes a depth the attachment's own clear \
     does not, so a held tile and a cleared one would answer differently where \
     nothing was drawn"
);

/// Narrows the shadow pass's viewport and scissor to one tile of the atlas.
///
/// The rectangle the allocator handed out — the same one the fragment stage
/// samples through, out of [`shadow::Selection`]. The graph set a viewport over
/// the whole atlas before the pass body ran, and this is what narrows it: the
/// same clip-space matrix mapped into a different part of the image, and for a
/// point light six different matrices into six of them off one visible set.
///
/// A function rather than the two calls inline, because the tile clear and the
/// draws that follow it walk the same tiles and a viewport set one way for one
/// of them would clear a rectangle nothing draws into.
fn set_shadow_tile(encoder: &mut dyn crcbl_hal::CommandEncoder, tile: shadow::TileRect) {
    let rect = Rect2d {
        x: i32::try_from(tile.x).unwrap_or(i32::MAX),
        y: i32::try_from(tile.y).unwrap_or(i32::MAX),
        width: tile.side,
        height: tile.side,
    };
    encoder.set_viewport(&Viewport {
        x: rect.x as f32,
        y: rect.y as f32,
        width: rect.width as f32,
        height: rect.height as f32,
        ..Viewport::from_size(rect.width, rect.height)
    });
    encoder.set_scissor(&rect);
}

/// What the last executed graph left the renderer-owned import `image` in, as an
/// [`ImportedImage::initial`].
///
/// **[`ResourceState::Undefined`] is the answer to an empty ledger, not a
/// fallback around one.** The ledger records what a graph *executed*, so nothing
/// recorded means nothing has run against this image on this pool — a freshly
/// created image before its first frame, and an image whose pool has been
/// through [`TransientPool::destroy`] — and `Undefined` is what an image no
/// barrier has moved is in. It is also the only declaration that lets the
/// incoming barrier hand the image a layout at all: every other state names an
/// old layout the image is not in.
///
/// The reason this is a lookup and not a field the renderer advances: a graph is
/// built, then compiled, and [`RenderGraph::compile`] can refuse it. A field
/// stepped forward while the passes were declared would have moved for a frame
/// that never reached the GPU, and the next frame's declaration — now wrong —
/// has no ledger entry to contradict it, so [`InitialClaim::Tracked`] would pass
/// it through. One source of truth is what removes that gap rather than
/// narrowing it.
fn imported_state(pool: &TransientPool, image: ImageHandle) -> ResourceState {
    pool.imported_image_use(image)
        .unwrap_or(ResourceState::Undefined)
}

/// The passes [`ForwardRenderer::add_passes`] records itself: the shadow
/// atlas's, the two reflective shadow maps, the depth prepass, the forward pass,
/// the debug draw layer, the tonemap, the ground grid and the
/// culling-statistics copy — plus [`Ssao::MAX_PASSES`], [`Ssr::PASSES`],
/// [`ProbeGather::PASSES`], [`Bloom::MAX_PASSES`], [`Exposure::PASSES`],
/// [`POST_TONEMAP_PASSES`] and [`Upscale::PASSES`] beside them.
///
/// [`AtlasView::PASSES`] has no term of its own and is inside
/// [`POST_TONEMAP_PASSES`] instead, which is where that is argued: the atlas
/// viewer and the resolve are never both recorded.
///
/// The reflective shadow maps and [`ProbeGather::PASSES`] are counted on the
/// ground grid's terms: all three are off unless a scene's
/// [`ProbeUpdate`] asks for them, and a bound short
/// of the frame that does ask would silently stop timing its last pass. The
/// punctual map is a pass whether or not the frame has a punctual light to draw
/// into it — see `ForwardRenderer::add_shadow_pass`, where the clear is what the
/// gather reads on a frame that lights none.
///
/// Every other pass in the frame belongs to a [`DrawGen`] or to the
/// [`LightGrid`], which is why this is the only count written here rather than
/// derived — see [`ForwardRenderer::MAX_PASSES`]. The copy is counted even
/// though a device that refused the readback records one fewer: this is a
/// ceiling, and one that came up short would silently stop timing the last pass
/// of every frame. It is the **all-effects-on** count for the same reason: a
/// frame that switched one off records fewer, and a bound that tracked the
/// toggles would have to be re-sized whenever they moved.
///
/// The ground grid is counted on the same terms, even though it is off by
/// default and is not a [`RenderEffects`] bit: a caller that switches it on
/// records one more pass, and a bound short of that would silently stop timing
/// the last pass of every frame it drew. The render-scale upscale is the second
/// of those — see [`ForwardRenderer::set_render_scale`], which is `1.0` and
/// therefore absent until a caller moves it. The debug draw layer is the third,
/// and [`DebugDraw::MAX_PASSES`] is its own ceiling.
///
/// **The bloom, Hi-Z and occlusion terms are ceilings where the others are
/// counts**: a chain's length is a function of the target's extent — see
/// [`crate::bloom`] and [`crate::hiz`] — and the occlusion pair's is a function
/// of [`crate::ssao::r_ssao_blur_passes`], while this constant is read before
/// either an extent or a console is known. The frame that lands on
/// it is a large one with bloom switched on; every smaller frame records fewer,
/// exactly as a frame with a free shadow slot does.
const RENDER_PASSES: u32 = 8
    // The occlusion cull's late depth prepass and its farthest pyramid, on the
    // ground grid's terms: off unless a caller switches the cull on.
    + 1
    + OcclusionPyramid::PASSES
    + DebugDraw::MAX_PASSES
    + ProbeGather::PASSES
    + Ssao::MAX_PASSES
    + ContactShadows::PASSES
    + Hiz::PASSES
    + Ssr::PASSES
    + Volumetric::PASSES
    + Water::PASSES
    + Grass::PASSES
    + Exposure::PASSES
    + Bloom::MAX_PASSES
    + POST_TONEMAP_PASSES
    + Upscale::PASSES;

/// What the frame's one resolve slot costs at its widest: the larger of the two
/// antialiasing tiers.
///
/// **The larger and not the sum**, because the two are never both recorded —
/// [`RenderEffects::CMAA2`] carries that in writing and
/// [`ForwardRenderer::add_passes`] is where the choice is made. So this is the
/// all-effects-on count as well as the ceiling, which is the property
/// [`RENDER_PASSES`] needs from every term it adds up.
///
/// [`ForwardRenderer::add_passes`]: ForwardRenderer::add_passes
const RESOLVE_PASSES: u32 = if Fxaa::PASSES > Cmaa2::PASSES {
    Fxaa::PASSES
} else {
    Cmaa2::PASSES
};

/// What the frame's one **post-tonemap** slot costs at its widest: the resolve
/// above, or [`crate::atlas_view`]'s pass, which replaces the picture instead of
/// filtering it.
///
/// **The larger and not the sum**, on [`RESOLVE_PASSES`]' terms and for a
/// reason of the same shape: [`ForwardRenderer::resolved_effects`] takes *both*
/// antialiasing tiers off for every debug view, and the atlas viewer records
/// only on the frame [`ForwardRenderer::debug_view`] resolved to
/// [`DebugView::ShadowAtlas`] — which is a debug view. So a frame that draws the
/// atlas resolves nothing, a frame that resolves is not drawing the atlas, and
/// neither can be short of this. `the_pass_bound_is_the_widest_frame_the_renderer_records`
/// is what holds the arithmetic to a frame that was actually recorded.
const POST_TONEMAP_PASSES: u32 = if RESOLVE_PASSES > AtlasView::PASSES {
    RESOLVE_PASSES
} else {
    AtlasView::PASSES
};

/// Draws a full-screen pass records: the over-sized triangle, drawn once.
///
/// The smallest fraction of the target extent a frame may be drawn at.
///
/// A quarter in each dimension, which is a sixteenth of the pixels — below that
/// the internal frame is small enough that a Catmull-Rom reconstruction of it
/// stops being a picture of the scene and starts being a picture of the filter,
/// and the Hi-Z pyramid and the bloom chain both run out of levels. Every
/// engine's resolution slider bottoms out somewhere; this is where this one
/// does, and [`ForwardRenderer::set_render_scale`] clamps to it rather than
/// refusing, so a settings slider cannot hand the renderer a frame it cannot
/// draw.
pub const MIN_RENDER_SCALE: f32 = 0.25;

/// The anisotropy the base-colour page is sampled with where the device grants
/// [`Features::SAMPLER_ANISOTROPY`].
///
/// Eight, which is topic 43's filtering rung's
/// default and the figure current engines default their own slider to: past it
/// the footprint's long axis is already sampled finely enough that sixteen is
/// invisible at a grazing angle and costs the same again in fetches. A device
/// whose [`Limits::max_sampler_anisotropy`](crcbl_hal::Limits) is lower gets
/// that limit instead — [`ForwardRenderer::anisotropy_for`] is the clamp — and a
/// device without the feature gets one, which is the value that turns it off.
pub const DEFAULT_ANISOTROPY: f32 = 8.0;

/// Named rather than written into [`ForwardRenderer::counters`]'s arithmetic,
/// because these are the only draws in this file whose instance and triangle
/// counts the CPU knows exactly — everything else here goes through an indirect
/// call.
const FULLSCREEN_DRAWS: u64 = 1;

/// How many full-screen passes a frame drawing `effects` at `extent` records:
/// the tonemap, always, and each switched-on effect's passes beside it.
///
/// **A function of the frame rather than a constant**, since
/// topic 48's toggles: it was the tonemap alone, then
/// five, and either written down is a number that stops matching the frame. The
/// tonemap is the one that is not conditional — a frame has to reach the
/// swapchain.
///
/// **`extent` is here because the bloom chain's length depends on it** — see
/// [`crate::bloom`] — where the two pairs above are the same two passes at every
/// size. A frame too small for even one chain level records none of them, which
/// is the same arithmetic as the toggle being off. It is the **internal** render
/// extent for the same reason: that is the extent every one of these passes runs
/// at.
///
/// `upscaling` is not a [`RenderEffects`] bit and could not be one — it is a
/// resolution, not an effect — so it arrives as its own argument, on the ground
/// grid's terms. It is false on every frame at full render scale, which is the
/// frame this function counted before the knob existed.
///
/// `ssao_blurs` arrives the same way and for the same reason: it is a console
/// variable rather than an effect bit, and it is the caller's job to read it
/// **once** for the frame. Reading it here as well would be a second read that
/// a command landing between the two could disagree with, and the disagreement
/// would be a counter describing a frame that was not recorded.
fn fullscreen_passes(
    effects: RenderEffects,
    extent: (u32, u32),
    upscaling: bool,
    ssao_blurs: u32,
) -> u64 {
    let mut passes = 1;
    if upscaling {
        passes += Upscale::PASSES as u64;
    }
    if effects.contains(RenderEffects::AMBIENT_OCCLUSION) {
        passes += u64::from(Ssao::passes(ssao_blurs));
    }
    if effects.contains(RenderEffects::CONTACT_SHADOWS) {
        passes += u64::from(ContactShadows::PASSES);
    }
    if effects.contains(RenderEffects::REFLECTIONS) {
        // The march's pair, and the pyramid it climbs — which is as long as the
        // extent allows and is zero on a frame too small to halve once, so this
        // term is the only one here that is not a constant per effect.
        passes += Ssr::PASSES as u64 + u64::from(crate::hiz::levels_for(extent));
    }
    if effects.contains(RenderEffects::BLOOM) {
        passes += u64::from(Bloom::passes_for(extent));
    }
    // **One resolve slot, and the higher tier takes it.** Both bits set is a
    // frame with CMAA2's passes and no FXAA pass at all, which is what
    // [`RenderEffects::CMAA2`] means by the two never both running — so this is
    // an `else if` rather than two independent terms.
    //
    // **[`Cmaa2::FULLSCREEN_PASSES`] and not [`Cmaa2::PASSES`]**: what this
    // function counts is full-screen *draws*, and two of that tier's three
    // passes are compute dispatches. [`crate::exposure`]'s three are left out
    // of this arithmetic for the same reason.
    if effects.contains(RenderEffects::CMAA2) {
        passes += Cmaa2::FULLSCREEN_PASSES;
    } else if effects.contains(RenderEffects::ANTIALIASING) {
        passes += Fxaa::PASSES as u64;
    }
    if effects.contains(RenderEffects::VOLUMETRIC_FOG) {
        // **[`Volumetric::COMPOSITE_PASSES`], not [`Volumetric::PASSES`].** The
        // scatter and the column scan are compute dispatches; what this
        // function counts is full-screen *draws*, and only the composite is
        // one. An atmosphere runs the composite without the effect, and the
        // caller adds that one — it is not an effect bit.
        passes += u64::from(Volumetric::COMPOSITE_PASSES);
    }
    // [`RenderEffects::AUTO_EXPOSURE`] adds none, and that is the whole of its
    // entry here: all three of its passes are compute dispatches, and the
    // exposure they measure reaches the picture through the tonemap's own draw.
    passes
}

/// The budget an **orthographic** camera selects under: one no group satisfies,
/// so every group expands and the base level is drawn whole.
///
/// The metric divides a projected error by the distance to the group's sphere,
/// and an orthographic projection has no such falloff — see
/// [`Projection::pixels_per_unit`], which is where the trade is written down.
/// Drawing the finest level is the conservative answer and the honest one; a
/// distance term invented for a projection that has none would be neither.
///
/// [`Projection::pixels_per_unit`]: crate::camera::Projection::pixels_per_unit
const LOD_BUDGET_NONE: f32 = f32::NEG_INFINITY;

/// Where a skinned object is, and what it draws: [`InstanceDesc`] with a
/// [`SkinnedMesh`] where the description's mesh index would be.
///
/// The mesh is a reservation rather than an index because a skinned draw is not
/// only a mesh — it also names a *run of the vertex pool* the skinning dispatch
/// fills, and which of the reservation's two runs that is changes every frame.
/// [`ForwardRenderer::begin_skinned_frame`] is what keeps it current, so nothing
/// here carries a parity.
#[derive(Clone, Copy, Debug)]
pub struct SkinnedInstanceDesc<'a> {
    /// The region this object is drawn out of, from
    /// [`ForwardRenderer::reserve_skinned`].
    pub mesh: &'a SkinnedMesh,
    /// Which [`SceneDesc::materials`] row it shades through, exactly as
    /// [`InstanceDesc::material`].
    pub material: usize,
    /// Where it is: a model matrix, on [`InstanceDesc::transform`]'s terms.
    ///
    /// The joints are **not** in it — a palette carries each joint's global
    /// transform times its inverse bind matrix, and this is what puts the
    /// deformed mesh in the world. See
    /// [`SkinRange::palette`](crate::skinning::SkinRange::palette).
    pub transform: Mat4,
}

/// The sky-view LUT a frame is drawn from, and everything taken out of it.
///
/// **The two projections are cached beside the LUT rather than taken per
/// frame**, which is what makes a frame under a sun that has not moved do no
/// host LUT work at all: both are functions of the LUT alone, and the LUT only
/// changes when [`ForwardRenderer::refresh_sky_view`] swaps a finished build
/// in. [`crate::sky_pass`] still encodes [`SkyView::rows`] and its aerial LUT's
/// rows per frame, because those are writes into the frame's own ring slots
/// rather than projections.
#[derive(Clone, Debug)]
struct PresentedSky {
    /// The normalised sun and viewpoint the LUT was marched for, which is what
    /// [`ForwardRenderer::refresh_sky_view`] compares this frame's atmosphere
    /// against.
    parameters: crcbl_shaders::atmosphere::Atmosphere,
    /// The marched LUT: what [`crate::sky_pass`] uploads and the background
    /// samples.
    view: SkyView,
    /// [`SkyView::gradient_fit`], which `ssr.slang` reflects with and the sky
    /// pass's block carries.
    gradient: crcbl_shaders::sky::SkyGradient,
    /// [`SkyView::irradiance`], which is the frame block's L1 ambient term.
    irradiance: crcbl_shaders::probe::GpuProbe,
}

impl PresentedSky {
    /// Takes both projections from a LUT that has just been marched.
    fn new(parameters: crcbl_shaders::atmosphere::Atmosphere, view: SkyView) -> Self {
        Self {
            parameters,
            gradient: view.gradient_fit(),
            irradiance: view.irradiance(),
            view,
        }
    }
}

/// What [`ForwardRenderer::begin_frame`] fitted for the whole frame, kept so a
/// secondary view begun after it writes its blocks against the same sun, light
/// rows and shadow matrices the primary camera's were written against.
///
/// Everything here is decided by the primary camera and drawn once: the rows
/// carry the shadow tiles the primary camera's selection handed out, and the
/// cascades are fitted to its frustum. A secondary view samples the maps those
/// passes drew — `docs/plan/29-fp-rendering.md`'s "shadow maps reused".
#[derive(Clone, Debug)]
struct FrameScene {
    light: DirectionalLight,
    rows: Vec<crcbl_shaders::light::GpuLight>,
    cascades: Cascades,
    shadow_view_proj: [[f32; 16]; shadow::CASCADES],
    light_view_proj: [[f32; 16]; shadow::LIGHT_TILES],
    atlas_rects: [[f32; 4]; shadow::TILES],
}

/// The bucket and level tables a scene's generators are all built from, kept
/// so [`ForwardRenderer::create_view`] can build one more after `build` has
/// returned.
#[derive(Debug)]
struct DrawTables {
    bucket_meshes: Vec<u32>,
    bucket_clusters: Vec<u32>,
    bucket_cluster_bases: Vec<u32>,
    mesh_levels: Vec<level_select::MeshLevels>,
    level_groups: Vec<level_select::LevelGroup>,
    level_meshes: Vec<u32>,
    instance_capacity: u32,
    light_capacity: u32,
}

/// The primary frame attachments an overlay may use before antialiasing and
/// render-scale reconstruction.
///
/// `display` is the display-space image the tonemap and post-tonemap overlays
/// have written. `depth` is the matching internal scene depth image, retained
/// as a read-only attachment for depth-tested overlays. Both have
/// `internal_extent` dimensions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ForwardOverlayTargets {
    pub display: ImageId,
    pub depth: ImageId,
    pub internal_extent: (u32, u32),
}

/// Everything the forward frame owns, created once.
#[derive(Debug)]
pub struct ForwardRenderer {
    // Geometry: the global pools, and the meshes resident in them. Each
    // range is resolved once, at build, and `MeshPool::mesh` only hands one out
    // for a mesh whose upload has completed — so there is no way to reach a
    // draw below with a mesh the GPU has not received.
    pool: MeshPool,
    /// The dynamic offset of each bucket's [`mesh::DrawConstants`] block, in
    /// [`SceneDesc::meshes`] order. Its length is the bucket count, which
    /// [`buckets_for`] says is a property of the path as well as of the scene.
    ///
    /// **The whole of what the CPU still says per draw.** Everything else a
    /// draw needs — how many instances, which indices, which vertices — is in
    /// the arguments the GPU wrote or in a table it resolves them through.
    bucket_constants: Vec<u32>,
    /// What one draw region adds to a bucket's offsets — the same for every
    /// generator this renderer built, because they share one bucket table.
    region_step: RegionStep,
    /// The material mode of each bucket, in the same order — the copy the
    /// **passes** read, where `DrawGen`'s copy is the one the GPU scatters
    /// against.
    ///
    /// What it is for: the depth prepass and the shadow atlas partition their
    /// call list on it and bind a pipeline per partition, so an opaque mesh in a
    /// scene with a cutout in it keeps the vertex-only stage. See
    /// [`ForwardRenderer::depth_partitions`].
    ///
    /// All zeroes for a scene whose materials are all opaque — every demo and
    /// every golden in this tree — which is exactly one bucket per mesh and one
    /// partition, byte for byte the stream they recorded before modes existed.
    bucket_modes: Vec<u32>,

    // The instance array, and the objects' places in it. Nothing here is
    // rewritten per frame: the pool uploads what a caller changed and nothing
    // else, so a scene nobody moved costs no transfer at all.
    instances: InstancePool,
    /// The mesh table id of each description mesh's **level 0**, in
    /// [`SceneDesc::meshes`] order — what an [`InstanceDesc::mesh`] index
    /// resolves through.
    ///
    /// Level 0's and not the whole run, because that is the entry an instance
    /// carries: `cull.slang` reads a bounding box out of it and a DAG's coarser
    /// levels approximate the same surface inside the same box. The coarser
    /// entries are resident and no instance names one — a cluster reaches its
    /// own level's vertices through
    /// [`crcbl_shaders::cluster_select::ClusterSelect::vertex_base`], and the
    /// uniform cut reaches them through the bucket table.
    ///
    /// Kept rather than resolved per call because every write of an instance
    /// writes the whole record, and an instance that lost its mesh id would
    /// resolve to entry 0 — which is a mesh, and the wrong one.
    mesh_ids: Vec<u32>,
    /// Level 0's pool handle for each description mesh that can be skinned, in
    /// [`SceneDesc::meshes`] order, and [`None`] for the ones that cannot — see
    /// [`ResidentMesh::skinnable`].
    ///
    /// What [`ForwardRenderer::reserve_skinned`] resolves an
    /// [`InstanceDesc::mesh`] index through. Kept rather than looked up, because
    /// there is no way back from a table id to the handle that owns it: an id is
    /// a bare index and a [`MeshHandle`] is generational.
    skinnable_meshes: Vec<Option<MeshHandle>>,
    /// Every object [`ForwardRenderer::add_skinned_instance`] placed, with the
    /// two base vertices it alternates between.
    ///
    /// The list [`ForwardRenderer::begin_skinned_frame`] walks to point each one
    /// at the half of its region *this* frame's dispatch fills. Entries whose
    /// instance has gone stale are dropped as it walks, so
    /// [`ForwardRenderer::remove_instance`] needs to know nothing about
    /// skinning.
    skinned_instances: Vec<SkinnedInstance>,

    /// §3.2's material table, and the rows in it.
    ///
    /// One buffer shared by every frame's bind group, not a ring — see
    /// [`crate::material_table`], which is where that decision lives.
    materials: MaterialTable,
    /// The table row of each description material, in [`SceneDesc::materials`]
    /// order — what an [`InstanceDesc::material`] index resolves through.
    ///
    /// Kept for the reason [`ForwardRenderer::mesh_ids`] is: a `set` writes the
    /// whole record, and an instance that lost its material id would name row 0
    /// by accident, which is a material and only *happens* to be the untinted
    /// one.
    material_ids: Vec<u32>,
    /// Topic 50's irradiance grid, row by row.
    ///
    /// One buffer shared by every frame's bind group, like the material table
    /// and for a stronger version of its reason: a probe is written when the
    /// scene is made resident and there is no call that rewrites one. See
    /// [`crate::probe`].
    probes: ProbeTable,
    /// Where those rows are, which rides in the frame block rather than in a
    /// buffer of its own — a fragment needs it before it knows which row to
    /// fetch.
    ///
    /// Kept rather than re-derived because [`SceneDesc`] is read once, at build.
    /// [`ProbeVolume::default`](crcbl_shaders::probe::ProbeVolume::default) is a
    /// grid of nothing, which is what a description with no probes leaves here
    /// and what makes the whole feature add zero.
    probe_volume: crcbl_shaders::probe::ProbeVolume,
    /// §3.2's texture side: one `D2Array` image whose layers the material rows
    /// index. One page, bound once, for every material — see the module docs on
    /// why this is [`ArrayPages`](crcbl_hal::BindingModel::ArrayPages) and not
    /// a bindless descriptor array.
    base_color_page: UploadedTexture,
    /// §2's second page: one `D2Array` image of tangent-space normals, whose
    /// layers [`GpuMaterial::normal_texture`](mesh::GpuMaterial::normal_texture)
    /// indexes.
    ///
    /// The base-colour page's own shape at [`NORMAL_PAGE_BINDING`], sampled
    /// through the same UV and the same sampler, and **created linear** — see
    /// [`NORMAL_PAGE_FORMAT`]. Its extent is its own: a description sizes each
    /// [`PageKind`] separately, so a 512² normal page beside a 2048²
    /// base-colour one is what the caller wrote and what this holds.
    normal_page: UploadedTexture,
    /// §2's third page: one `D2Array` image of glTF's packed occlusion,
    /// roughness and metallic, whose layers
    /// [`metallic_roughness_occlusion_texture`](mesh::GpuMaterial::metallic_roughness_occlusion_texture)
    /// indexes.
    ///
    /// The normal page's own shape at [`MRO_PAGE_BINDING`], sampled through the
    /// same UV and the same sampler, and **created linear** — see
    /// [`MRO_PAGE_FORMAT`].
    mro_page: UploadedTexture,
    /// §2's fourth page: one `D2Array` image of emitted radiance, whose layers
    /// [`emissive_texture`](mesh::GpuMaterial::emissive_texture) indexes.
    ///
    /// The base-colour page's own shape at [`EMISSIVE_PAGE_BINDING`], and
    /// **created sRGB** rather than linear, because an emissive texel is a
    /// colour — see [`EMISSIVE_PAGE_FORMAT`].
    emissive_page: UploadedTexture,
    /// Each [`PageKind`]'s image size in texels, as a width and a height,
    /// indexed by [`PageKind::index`].
    ///
    /// Square, because [`PageDesc`](crate::scene::PageDesc) carries one extent
    /// per kind rather than a rectangle. `(1, 1)` for a kind the description
    /// named no layer of, which is the placeholder's extent and not the
    /// description's — see [`PAGE_PLACEHOLDER_TEXEL`]. Kept rather than
    /// re-derived because [`add_passes`](Self::add_passes) declares both pages
    /// to the graph and an [`ImportedImage`] names an extent, and the
    /// description they came from is the caller's, read once at build.
    page_extents: [(u32, u32); PageKind::ALL.len()],
    /// The sampler the page is read through.
    base_color_sampler: SamplerHandle,
    /// The anisotropy [`ForwardRenderer::base_color_sampler`] was created
    /// with, after [`set_anisotropy`](ForwardRenderer::set_anisotropy)'s clamp.
    anisotropy: f32,
    /// How many layers each [`PageKind`]'s page holds, indexed by
    /// [`PageKind::index`] — zero for a kind the description named none of.
    ///
    /// What [`replace_page`](ForwardRenderer::replace_page) holds a
    /// replacement to, so every material row's layer number goes on naming the
    /// same texture.
    page_layers: [usize; PageKind::ALL.len()],
    /// `[frame]`: the page sampler and the four page views that slot's
    /// mesh-layout groups name.
    ///
    /// A slot moves onto [`ForwardRenderer::page_bindings`] at its own
    /// `begin_frame` and not before — see [`ForwardRenderer::adopt_pages`] —
    /// so this is what says which slots still name a sampler
    /// [`set_anisotropy`](ForwardRenderer::set_anisotropy) replaced or a page
    /// [`replace_page`](ForwardRenderer::replace_page) did.
    slot_pages: Vec<PageBindings>,
    /// Page samplers and pages replaced while some slot may still name them.
    /// Each is destroyed as the last slot naming it moves off, or at
    /// [`destroy`](ForwardRenderer::destroy).
    retired_pages: Vec<RetiredPage>,

    /// Draw calls the last [`ForwardRenderer::add_passes`] recorded — see
    /// [`ForwardRenderer::counters`], which is the only thing that reads it.
    ///
    /// Kept rather than recomputed because the shadow pass's share is the number
    /// of **occupied** tiles, which [`ForwardRenderer::add_shadow_pass`] works
    /// out from topic 45's tile allocation and nothing outside
    /// it can restate without becoming the second copy that drifts.
    recorded_draws: u64,
    /// Which call the forward pass records — the device's [`GeometryPath`],
    /// resolved once.
    emit: EmitTail,
    /// The most buckets one call of the geometry passes draws, or `None` where
    /// they record a call per bucket — [`EmitTail::range_limit`], resolved at
    /// build with [`emit`](Self::emit) and for its reason.
    range_limit: Option<u32>,
    /// §3.5's clusters, and **only on [`EmitTail::Mesh`]**: the two indirect
    /// tails draw the same geometry out of the index pool and read none of
    /// this. `None` is therefore the ordinary state on most devices rather than
    /// a failure, and it is also what makes a fall-through impossible — see
    /// [`ForwardRenderer::geometry_path`].
    clusters: Option<ClusterPool>,
    /// Whether the mesh pipeline was built with §3.5's amplification stage in
    /// front of it — see [`ForwardRenderer::culls_clusters`], which is where
    /// what it means is written down.
    culls_clusters: bool,
    /// Where each description mesh's clusters are in
    /// [`ForwardRenderer::clusters`] — every level of it, as one run, in
    /// [`SceneDesc::meshes`] order. Empty off the mesh path, where there is no
    /// cluster pool at all. See [`ForwardRenderer::cluster_range`].
    mesh_clusters: Vec<ClusterRange>,
    /// The bucket each level of each description mesh draws through, finest
    /// first, in [`SceneDesc::meshes`] order — and empty on the mesh path. See
    /// [`ForwardRenderer::level_buckets`].
    ///
    /// **The run for the scene's first material mode**, which is `OPAQUE`
    /// wherever the scene has an opaque material at all: the table is every
    /// mesh's levels once per mode the scene holds, mode by mode, and this
    /// names a mesh's levels in the first of those runs. See
    /// [`ForwardRenderer::bucket_modes`].
    mesh_level_buckets: Vec<Vec<u32>>,
    /// The pixel budget topic 25's descent compares a group's
    /// projected error against. [`LOD_ERROR_BUDGET`] until
    /// [`ForwardRenderer::set_lod_error_budget`] says otherwise.
    lod_error_budget: f32,
    /// How far below that an expanded group is held before it collapses again.
    /// [`LOD_HOLD_RATIO`] until
    /// [`ForwardRenderer::set_lod_hold_ratio`] says otherwise.
    lod_hold_ratio: f32,
    /// The same three numbers the shadow cascades selected under, which is
    /// [`ForwardRenderer::lod_params`] with both budgets scaled by
    /// [`SHADOW_LOD_BIAS`] and the same pixels-per-unit.
    ///
    /// Kept beside the camera's for its reason: a reader comparing the two cuts
    /// takes both pairs from here rather than re-deriving the bias, which would
    /// be comparing two copies of one arithmetic instead of two selections.
    shadow_lod_params: [f32; 3],

    /// The lights a caller set beside the sun, as
    /// [`ForwardRenderer::set_lights`] was handed them.
    ///
    /// Kept rather than converted on the way in, because a row is the *frame's*
    /// artefact: the sun arrives per frame at
    /// [`begin_frame`](ForwardRenderer::begin_frame) and is row 0, so the list a
    /// frame uploads cannot be assembled until then.
    extra_lights: Vec<Light>,

    /// One [`mesh::DrawConstants`] block per draw, a device dynamic-offset
    /// alignment apart. Shared by every frame's bind group rather than ringed,
    /// because nothing rewrites it after `build`: a mesh's base vertex and an
    /// object's instance index are decided when the pools allocate them.
    draw_constants: BufferHandle,
    /// The camera's resources and history — see [`view`], which is where the
    /// line between a camera's state and the scene's is drawn.
    primary: View,
    /// Every secondary view [`ForwardRenderer::create_view`] built, indexed by
    /// [`ViewId::index`] less one — a free id is `None`.
    views: Vec<Option<View>>,
    /// The tables a view's generator is built from — see [`DrawTables`].
    draw_tables: DrawTables,
    /// Counts every [`begin_frame`](ForwardRenderer::begin_frame), so a view can
    /// say which frame it was last begun for — see [`View::begun`].
    frame_serial: u64,
    /// The frame the last `begin_frame` opened, for
    /// [`begin_view`](ForwardRenderer::begin_view). `None` before the first.
    frame_scene: Option<FrameScene>,
    /// Which frame-in-flight slot is current. Set from
    /// [`InstancePool::begin_frame`]'s return rather than counted here, so the
    /// uniform ring and the instance ring cannot drift apart.
    frame: usize,

    mesh_layout: BindGroupLayoutHandle,
    mesh_pipeline_layout: PipelineLayoutHandle,
    mesh_pipeline: SidedPipelines,
    /// [`ForwardRenderer::mesh_pipeline`] again in
    /// [`PolygonMode::Line`], for
    /// [`set_wireframe`](ForwardRenderer::set_wireframe).
    ///
    /// [`None`] until a caller first switches the view on — the ground grid's
    /// arrangement exactly, and for its reason: a second pipeline compiled at
    /// build would be paid for by every sample, golden and headless run that
    /// never asks for a wireframe, which is all of them. Once built it is kept,
    /// because switching the view off is
    /// [`ForwardRenderer::wireframe_on`] and not a release.
    ///
    /// **A pair, like the pipeline it replaces**, because [`PolygonMode::Line`]
    /// does not disable culling: a single-sided wireframe drawn over a
    /// double-sided bucket would leave a surface out of the debug view that the
    /// shaded frame beside it draws, which is a view of the document that
    /// disagrees with the document.
    wireframe_pipeline: Option<SidedPipelines>,
    /// Whether [`add_passes`](ForwardRenderer::add_passes) drives the forward
    /// pass through [`ForwardRenderer::wireframe_pipeline`]. **`false` by
    /// default**: a wireframe is a tool's view of a document, and every sample
    /// and every golden image predates it.
    wireframe_on: bool,
    /// The occlusion and small-feature culls a caller asked for — see
    /// [`set_occlusion_culling`](ForwardRenderer::set_occlusion_culling).
    occlusion_culling: OcclusionCulling,
    /// Whether a point light's six faces cull separately — see
    /// [`set_point_face_culls`](ForwardRenderer::set_point_face_culls).
    point_face_culls: bool,
    /// What a test asked every shadow view's uploaded block to be rewritten
    /// with — see
    /// [`set_shadow_view_tamper`](ForwardRenderer::set_shadow_view_tamper).
    /// [`None`] outside a test.
    shadow_view_tamper: Option<fn(&mut mesh::FrameUniforms)>,
    /// Whether [`begin_frame`](ForwardRenderer::begin_frame) writes
    /// [`FrameUniforms::NORMALS_VIEW_ON`] into the frame block, which makes
    /// `mesh.slang`'s fragment stage draw world-space normals instead of shading
    /// — see [`set_normals_view`](ForwardRenderer::set_normals_view).
    ///
    /// **`false` by default**, on [`ForwardRenderer::wireframe_on`]'s terms
    /// exactly: it is a tool's view of a document, and every sample and every
    /// golden image predates it.
    ///
    /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
    normals_view: bool,

    /// The exponential height fog the colour pass composites over its
    /// radiance — see [`set_fog`](ForwardRenderer::set_fog).
    ///
    /// **[`Fog::NONE`] by default**, on [`normals_view`](Self::normals_view)'s
    /// terms: a caller who never asks for fog draws the frame this renderer
    /// drew before the feature existed, and exactly that frame — the shader's
    /// composite is an identity at zero density rather than an interpolation
    /// that nearly is.
    fog: Fog,

    /// The gradient sky whose irradiance the colour pass adds to the ambient
    /// term — see [`set_sky`](ForwardRenderer::set_sky).
    ///
    /// **[`Sky::NONE`] by default**, on [`fog`](Self::fog)'s terms: a black
    /// gradient projects to coefficients that are all zero, so the three dot
    /// products the fragment stage adds are zero and no frame drawn before a
    /// sky existed moves.
    sky: Sky,
    /// The atmosphere that **replaces** [`Self::sky`] when a caller sets one —
    /// see [`set_atmosphere`](ForwardRenderer::set_atmosphere).
    ///
    /// `None` by default, so a renderer nobody calls that on is the renderer it
    /// was.
    atmosphere: Option<Atmosphere>,
    /// The marched sky-view LUT this renderer is drawing, with the parameters
    /// it was marched for and the projections taken from it.
    ///
    /// **Cached against the parameters rather than rebuilt per frame**, because
    /// the march is tens of milliseconds of CPU and the sun in most frames has
    /// not moved. The stored parameters are the *normalised* ones the shader
    /// crate takes, so a caller handing over the same sun spelled two lengths
    /// does not force a rebuild.
    ///
    /// This is the LUT a frame is **drawn from**, which is not the one being
    /// marched: see [`Self::sky_view_build`].
    sky_view: Option<PresentedSky>,
    /// The march in flight, when the sun has moved away from
    /// [`Self::sky_view`]'s.
    ///
    /// [`ForwardRenderer::refresh_sky_view`] steps it
    /// [`SKY_VIEW_BUILD_ROWS`] rows per frame and swaps it into
    /// [`Self::sky_view`] when it finishes.
    ///
    /// **The host side is where the double buffer is**: the LUT being drawn and
    /// the LUT being marched are these two fields, and [`crate::sky_pass`]'s
    /// device ring is untouched. Putting the stripe on the device instead would
    /// mean writing part of a ring slot per frame, and that ring's slots are
    /// written whole precisely because each is a frame in flight — a partial
    /// write would have to track, per slot, which rows of *which* sun that slot
    /// already holds, which is bookkeeping the host copy does not need at all.
    sky_view_build: Option<SkyViewBuild>,

    /// Whether the colour pass tints each cluster by its DAG level instead of
    /// shading — see [`set_lod_view`](ForwardRenderer::set_lod_view).
    ///
    /// **Wins over [`normals_view`](Self::normals_view) when both are set**,
    /// because one uniform lane carries both switches and the fragment stage
    /// tests the LOD threshold first. `crcbl_shaders`'
    /// `the_lod_view_threshold_lies_above_the_normals_view` is what keeps that
    /// order true.
    lod_view: bool,

    /// Whether the colour pass shades each cluster by the projected error the
    /// LOD selection judged it on, instead of shading it or tinting it — see
    /// [`set_heatmap`](ForwardRenderer::set_heatmap).
    ///
    /// **Wins over both [`lod_view`](Self::lod_view) and
    /// [`normals_view`](Self::normals_view)**, on the same terms and for the same
    /// reason: one uniform lane carries all three switches and the shaders test
    /// the outermost threshold first. `crcbl_shaders`'
    /// `the_heatmap_view_threshold_lies_above_the_lod_view` is what keeps that
    /// order true, and
    /// `the_three_debug_views_resolve_in_one_order_however_they_are_set` is what
    /// holds this side to it.
    heatmap: bool,

    /// Whether the colour pass draws the ambient-occlusion channel as grey
    /// instead of shading — see
    /// [`set_occlusion_view`](ForwardRenderer::set_occlusion_view).
    ///
    /// **Wins over every other view**, on [`heatmap`](Self::heatmap)'s terms and
    /// for its reason: one uniform lane, outermost threshold first.
    /// `crcbl_shaders`' `the_occlusion_view_threshold_lies_above_the_heatmap` is
    /// what keeps that order true, and
    /// `the_debug_views_resolve_in_one_order_however_they_are_set` is what holds
    /// this side to it.
    occlusion_view: bool,

    /// Whether the colour pass draws the motion vector instead of shading — see
    /// [`set_motion_view`](ForwardRenderer::set_motion_view).
    ///
    /// **Wins over every other view**, on [`occlusion_view`](Self::occlusion_view)'s
    /// terms and for its reason: one uniform lane, outermost threshold first.
    /// `crcbl_shaders`' `the_motion_view_threshold_lies_above_the_occlusion_view`
    /// is what keeps that order true, and
    /// `the_debug_views_resolve_in_one_order_however_they_are_set` is what holds
    /// this side to it.
    motion_view: bool,
    /// Whether the colour pass draws the occlusion channel's bent direction
    /// instead of shading — see
    /// [`set_bent_normal_view`](ForwardRenderer::set_bent_normal_view).
    ///
    /// **Wins over every other view**, on [`motion_view`](Self::motion_view)'s
    /// terms: it is the outermost sentinel in the lane, and
    /// `crcbl_shaders`' `the_bent_normal_view_threshold_lies_above_the_motion_view`
    /// is what holds the shader's branch order to it.
    bent_normal_view: bool,

    /// Whether the colour pass tints the shaded picture by the cascade each
    /// sun-lit fragment's shadow was sampled from — see
    /// [`set_cascade_view`](ForwardRenderer::set_cascade_view).
    ///
    /// **Loses to every other view**, which is the opposite of every field
    /// above and for the reason [`DebugView::Cascades`] carries: every one of them
    /// replaces the shaded picture and this one multiplies it, so a frame drawing
    /// any of them has nothing for this tint to reach. `crcbl_shaders`'
    /// `the_cascade_view_threshold_lies_below_every_replacing_view` is what
    /// holds the shader to the same order, from the other end of the lane.
    cascade_view: bool,

    /// Whether the frame draws the shadow atlas over the finished picture — see
    /// [`set_atlas_view`](ForwardRenderer::set_atlas_view).
    ///
    /// **Not a lane of the frame block**, unlike every field above: this view is
    /// a pass rather than a branch in `mesh.slang`, so what reads this is
    /// [`ForwardRenderer::add_passes`] deciding whether to record
    /// [`crate::atlas_view`]'s. It resolves below every replacing view and above
    /// [`cascade_view`](Self::cascade_view) — see
    /// [`ForwardRenderer::debug_view`].
    atlas_view: bool,

    /// Where [`begin_frame`](ForwardRenderer::begin_frame) projects
    /// topic 25's selection from, when that is not the camera's own
    /// eye — see
    /// [`set_frozen_selection_eye`](ForwardRenderer::set_frozen_selection_eye).
    ///
    /// **[`None`] is not a position, it is "follow the camera"**, and it is what
    /// every frame the engine has drawn so far did: the eye handed to
    /// [`DrawGen::begin_frame`] is `camera.eye`, byte for byte, so a caller that
    /// never sets this writes the parameter block it wrote before this field
    /// existed.
    ///
    /// **Not a [`DebugView`]**, and deliberately: the three views are one
    /// picture chosen between, while this is a change to what the *selection*
    /// answers and leaves the picture's choice alone. A reviewer freezing the
    /// cut and then reading it off the LOD tint is the combination the feature
    /// exists for, so the two cannot be alternatives.
    frozen_selection_eye: Option<Vec3>,

    /// Topic 18's shadow atlas: one `D32Float` image holding
    /// [`shadow::TILES`] square tiles in a fixed grid — the sun's cascades
    /// first, then one per shadowed light.
    ///
    /// Owned here rather than created by the graph per frame, because its
    /// extent is a **quality setting and not a window size** — nothing about it
    /// changes on a resize, so a transient would be re-created for no reason
    /// and could not be read back by a test that does not own the graph.
    shadow_atlas: ImageHandle,
    shadow_atlas_view: ImageViewHandle,
    /// A 1×1 depth image that exists so the depth-only pipeline's bind group can
    /// fill [`SHADOW_ATLAS_BINDING`] without naming the atlas it is writing.
    ///
    /// Both halves of that sentence are forced:
    ///
    /// * **The slot has to be filled.** Slang's Metal backend materialises every
    ///   global into every entry point — `msl/mesh.metal`'s `vertexMain` takes
    ///   `shadow_atlas [[texture(1)]]` whether it reads it or not — so a
    ///   depth-only pipeline sharing this layout still declares the argument. A
    ///   layout with the slot removed would break Metal alone, on a runner this
    ///   team cannot debug on, which is the trap binding 6's comment already
    ///   records.
    /// * **It cannot be the atlas.** WebGPU refuses a texture that is a render
    ///   attachment and a bind-group resource in the same pass, and the shadow
    ///   pass is exactly that pass.
    ///
    /// Nothing samples it: the shadow pipeline has no fragment stage. It is
    /// brought into the graph beside the atlas so its layout transition is the
    /// graph's like every other, rather than a hand-written barrier.
    shadow_placeholder: ImageHandle,
    shadow_placeholder_view: ImageViewHandle,
    /// The **comparison** sampler the atlas is read through — hardware PCF.
    shadow_sampler: SamplerHandle,
    /// The depth-only pipeline every tile is rendered with — and, driven with
    /// the camera's own draws, the depth prepass's: `mesh.slang`'s
    /// `depthVertexMain` where the geometry comes from a vertex stage, the same
    /// geometry stage as [`ForwardRenderer::mesh_pipeline`] where it comes from
    /// a mesh one, and no fragment stage in either case.
    shadow_pipeline: SidedPipelines,
    /// The same two passes' pipeline for the buckets whose material mode cuts
    /// an alpha mask: `vertexMain` and `depthMaskedFragmentMain` — see
    /// [`MeshModules::depth_masked_pipeline`].
    ///
    /// Built on every scene rather than only on one that has a masked material,
    /// for [`ForwardRenderer::rsm_pipeline`]'s reason: the modules are released
    /// inside `build` and a pipeline built later would need them back, which is
    /// a second shader compilation. Which buckets are drawn with it is
    /// [`ForwardRenderer::depth_partitions`], and it is a **partition of one
    /// frame's draws** rather than a choice for the whole frame.
    depth_masked_pipeline: SidedPipelines,
    /// The pipeline that resets one tile of the atlas before it is redrawn, on a
    /// frame that is keeping some of the others — see
    /// [`MeshModules::depth_clear_pipeline`], which is where the whole argument
    /// for it lives.
    shadow_clear_pipeline: GraphicsPipelineHandle,
    /// The irradiance probes' reflective shadow map — see
    /// [`MeshModules::rsm_pipeline`]. Built on every scene and bound only by a
    /// frame whose volume asked for [`ProbeUpdate::EveryFrame`].
    rsm_pipeline: SidedPipelines,
    /// The compute pass that reads that map into the probe rows, and [`None`]
    /// for every scene whose volume is [`ProbeUpdate::Authored`] — which is the
    /// whole of what the default costs such a scene: no pipeline, no buffers, no
    /// pass and no frame time.
    probe_gather: Option<ProbeGather>,
    /// Whether cascade 0's view block and cull parameters were written for the
    /// frame being recorded, so the reflective shadow map can be drawn from
    /// them.
    ///
    /// Not [`ForwardRenderer::shadow_group_redrawn`], which is a claim about the
    /// *atlas*: a frame drawing without
    /// [`RenderEffects::SHADOWS`](crate::effects::RenderEffects::SHADOWS) fits
    /// cascade 0 for the map and writes no tile, and overloading that flag would
    /// report a cascade as redrawn when nothing drew it.
    rsm_cull_ready: bool,
    /// What the scene said fills the probe rows.
    ///
    /// Read by [`ForwardRenderer::begin_frame`] — which keeps cascade 0 off the
    /// shadow atlas's static-cache hold when the updater is on, because the map
    /// is that cascade's own draws — and by the pass recording below.
    probe_update: ProbeUpdate,
    /// How far cascade 0 reached on the frame being recorded, which is the
    /// radius of the sphere it was fitted to — `crate::rsm::texel_area` is what
    /// reads it.
    ///
    /// Written by [`ForwardRenderer::begin_frame`] beside the cascade matrices
    /// themselves, rather than recomputed at pass-record time: a frame that
    /// scaled its gather by one cascade's footprint while drawing the map
    /// through another's would be a bounce that is uniformly wrong, and nothing
    /// in the frame could see it.
    cascade_reach: f32,
    /// The sun's colour premultiplied by its intensity, this frame.
    ///
    /// The reflective shadow map holds albedo rather than flux — `RsmOutput` in
    /// `mesh.slang` argues why — so this is what the gather multiplies by, and it
    /// is read off the same [`DirectionalLight`] the cascades were fitted to.
    /// The sun's *direction* is not carried beside it: the gather needs none, on
    /// `probe_gather.slang`'s own derivation.
    sun_color: Vec3,
    /// One cull and draw-argument pass **per cascade and per shadowed light**,
    /// which is topic 18's "one cull dispatch per cascade against the same
    /// instance/geometry pools" with a shadowed light counting as a cascade does.
    ///
    /// A whole [`DrawGen`] rather than just its cull half: the shadow pass emits
    /// the same indirect call the colour pass does, so it needs the same
    /// arguments, and there is no "cull only" constructor to reach for. The cost
    /// is that each duplicates the clear and draw-argument pipelines and
    /// [`DrawGen`]'s own per-instance state — see
    /// [`TileBuffers::group_state`], which is where that price is written down,
    /// and [`SHADOW_CULLS`], which is why a point light has one of these rather
    /// than six.
    ///
    /// **Indexed by cull**: `0..shadow::CASCADES` are the sun's and
    /// [`shadow_cull`] is where a light slot's is.
    shadow_draws: Vec<DrawGen>,
    /// `[frame][view]`: a copy of the frame block whose `view_proj` **is** that
    /// view's matrix, so the depth-only pipeline runs the unmodified vertex and
    /// mesh stages rather than a second transform path.
    shadow_uniforms: Vec<Vec<BufferHandle>>,
    /// Empty between frame preparations, with capacity retained for assembly.
    shadow_prepare_views: Vec<(usize, usize, mesh::FrameUniforms)>,
    /// Empty between frame preparations, with capacity retained for frusta.
    shadow_prepare_culls: Vec<(usize, Frustum)>,
    /// `[frame][view]`: the mesh layout again, reading that view's uniforms and
    /// the survivors of the cull its slot owns.
    shadow_groups: Vec<Vec<BindGroupHandle>>,
    /// `[frame][view]`: the cut that view's amplification stage chose, one word
    /// per resident cluster — and empty where there is no such stage.
    ///
    /// **A buffer per view rather than the camera's**, unlike every other
    /// resource these passes share: the colour pass is recorded last and writes
    /// [`ForwardRenderer::cluster_selection`] over whatever a view left in it,
    /// so a view writing there leaves nothing behind to read. Without one of
    /// these the shadow pass's descent is unobservable — which is the state
    /// [`SHADOW_LOD_BIAS`] arrived in, and it is what a bias nothing can measure
    /// would have stayed in.
    shadow_selection: Vec<Vec<BufferHandle>>,
    /// Which of [`ForwardRenderer::extra_lights`] holds each shadow slot, where
    /// in the atlas's light region its tiles are, and the memory that keeps that
    /// answer from flickering.
    ///
    /// Re-run every [`ForwardRenderer::begin_frame`] and read by
    /// [`ForwardRenderer::add_shadow_pass`], which records a cull for each
    /// occupied slot and a viewport per face it has, and nothing at all for the
    /// free ones — so an unheld tile keeps the reversed-Z clear, which reads as
    /// "nothing stored, fully lit" wherever anything did sample it.
    shadow_lights: shadow::Selection,
    /// `[group]`: everything that group's maps would be drawn from, as
    /// [`ForwardRenderer::shadow_group_record`] spells it.
    ///
    /// Kept only to tell one frame's answer from the last one's: it is compared
    /// and then replaced, and what travels from there is the number below.
    ///
    /// **Per group rather than per atlas**, since the cadence rung: a group is a
    /// cascade or a light slot's whole run of tiles, and holding one map while
    /// redrawing another is the whole of what that rung buys.
    shadow_group_inputs: Vec<Vec<u8>>,
    /// `[group]`: a number that moves whenever that group's entry of
    /// [`ForwardRenderer::shadow_group_inputs`] does, and never comes back to a
    /// value it has had.
    ///
    /// So "the image already holds this" is one integer comparison, which is
    /// what lets the pass body below carry the answer out of the graph.
    shadow_group_id: Vec<u64>,
    /// `[group]`: how many instance writes that group's cull could have seen,
    /// over the renderer's life — the per-group stand-in for
    /// [`InstancePool::revision`] in
    /// [`ForwardRenderer::shadow_group_record`], moved by
    /// [`ForwardRenderer::note_caster_writes`].
    shadow_group_writes: Vec<u64>,
    /// `[element]`: where each element of the instance array could draw into a
    /// shadow map, as of the last [`ForwardRenderer::note_caster_writes`] —
    /// which is what a write's *before* is read from. Grows to the highest
    /// element written; an element past its end has never been written and is
    /// [`shadow_inputs::CasterFootprint::Nowhere`].
    shadow_footprints: Vec<shadow_inputs::CasterFootprint>,
    /// The live elements whose mesh has a DAG, and so whose level the selection
    /// eye chooses — the ones that put the eye into a light group's record.
    shadow_dag_elements: std::collections::BTreeSet<u32>,
    /// Scratch for [`InstancePool::take_written`], kept so a frame that moved
    /// an instance does not allocate its list.
    shadow_written: Vec<u32>,
    /// This frame's written elements' footprints, before and after the write,
    /// from [`ForwardRenderer::note_caster_writes`] for
    /// [`shadow_inputs::shadow_groups_reached`]. Empty on a frame nothing was
    /// written in.
    shadow_moved: Vec<(
        shadow_inputs::CasterFootprint,
        shadow_inputs::CasterFootprint,
    )>,
    /// The number given to the shadow pass this renderer recorded last.
    ///
    /// Moves once per recorded pass, so the body below can say *which* pass ran
    /// with one integer.
    shadow_pass_id: u64,
    /// The [`ForwardRenderer::shadow_pass_id`] of the last shadow pass that
    /// **ran**, written by that pass's own body.
    ///
    /// By the body rather than by the call that recorded it, and that is the
    /// whole of why this is shared state rather than a plain field: a frame
    /// whose graph was refused — or built and dropped — recorded a pass that
    /// never executed, so the image still holds whatever the frame before it
    /// left there. `a_refused_frame_leaves_the_shadow_atlas_where_it_was` is
    /// that case, and it is the same boundary [`TransientPool`]'s ledger of
    /// imported images uses for the same reason.
    ///
    /// Zero until a pass has run, and the ids start above it, so the first frame
    /// of all draws.
    shadow_pass_ran: Arc<AtomicU64>,
    /// What the shadow pass recorded last would leave the image holding, if its
    /// body ran.
    ///
    /// Taken and applied by the next [`ForwardRenderer::begin_frame`], which is
    /// the only place that can tell whether it did — see
    /// [`ForwardRenderer::shadow_pass_ran`].
    shadow_pending: Option<ShadowCommit>,
    /// `[group]`: the id, the centre that group's maps were projected from and
    /// how far they reach, as the record the **image** holds describes them.
    ///
    /// The id is what says a map is out of date. The centre and reach are what
    /// say it is about somewhere else: a map whose own centre has moved further
    /// than its own reach covers ground it was never drawn for, and holding
    /// that is worse than a shadow that lags — see
    /// [`ForwardRenderer::shadow_cadence_reset`].
    shadow_group_held: Vec<(u64, Vec3, f32)>,
    /// `[group]`: whether this frame redraws that group's maps.
    ///
    /// Frozen by [`ForwardRenderer::begin_frame`] for
    /// [`ForwardRenderer::frame_effects`]' reason: this call decides it and
    /// `add_passes` acts on it, and a value that moved between them would skip
    /// a cull whose draws were recorded, or the other way about.
    shadow_group_redrawn: Vec<bool>,
    /// Where every atlas slot's map was laid out on the frame the **image** was
    /// drawn from, so a frame can tell whether the texels it is keeping still
    /// describe the layout it is about to sample through.
    ///
    /// A layout that has moved is what makes a frame clear the whole attachment
    /// and redraw every group: a tile left over from a different layout is
    /// texels nothing this frame can account for. Promoted beside
    /// [`ForwardRenderer::shadow_group_held`].
    ///
    /// [`None`] until a pass has drawn, which is **not** the layout a frame
    /// with shadows off produces: an image no pass has touched holds undefined
    /// memory rather than a clear, so the first frame of all has to write one
    /// whatever it is asked for.
    shadow_atlas_layout: Option<Vec<shadow::TileRect>>,
    /// Whether any map this frame samples is one an earlier frame drew, rather
    /// than one this frame did.
    ///
    /// The cadence's own readback — see
    /// [`ForwardRenderer::shadow_atlas_cached`], which is this for the whole
    /// atlas.
    shadow_atlas_cached: bool,
    /// Whether this frame ignored the cadence because some map's region moved
    /// out from under it — see [`ForwardRenderer::shadow_cadence_reset`].
    shadow_cadence_reset: bool,
    /// How many tiles this frame redraws — see
    /// [`ForwardRenderer::shadow_faces_redrawn`].
    shadow_faces_redrawn: u32,
    /// A shadow cadence the caller pinned, or [`None`] to take the console's.
    ///
    /// [`ForwardRenderer::set_effect_request`]'s shape at this knob and for its
    /// reason: `shadow::r_shadow_cadence` and `shadow::r_shadow_faces` are
    /// process-global, and an application that wants a tier's own pair — or a
    /// test that wants a frame nothing else in the process can move — needs one
    /// that is not.
    shadow_cadence_request: Option<shadow::Cadence>,
    /// Whether this frame's shadow pass clears the whole attachment, rather
    /// than loading it and resetting only the tiles it redraws.
    ///
    /// Frozen beside [`ForwardRenderer::shadow_group_redrawn`] and for its
    /// reason: the decision is `begin_frame`'s and the recording is
    /// `add_shadow_pass`'s, and a value that moved between them would load an
    /// attachment whose tiles nothing had reset.
    shadow_atlas_clears: bool,
    /// How many frames have been opened, which is what the cadence is keyed to.
    ///
    /// **Monotonic, unlike [`ForwardRenderer::frame`]**, which is the index of
    /// the frame in flight and wraps every [`FRAMES_IN_FLIGHT`]. A schedule
    /// keyed to that would repeat every few frames and bound nothing.
    shadow_frame: u64,
    /// Whether this frame dispatches skinning, and so rewrites part of the
    /// vertex pool the shadow pass draws from.
    ///
    /// The atlas's one **always redraw**: a skinned caster's vertices are
    /// produced by a compute pass into the pool, so there is nothing on the
    /// host to compare a frame's geometry against — the palette a caller hands
    /// over is not the vertices, and the vertices are never read back. Set by
    /// [`ForwardRenderer::begin_skinned_frame`], which is the only call that
    /// can make it true, and cleared by [`ForwardRenderer::begin_frame`], which
    /// dispatches none.
    frame_skins: bool,

    /// Topic 03 §3.6's one permitted readback: the camera cull's statistics, on
    /// a delayed ring — see [`crate::cull_stats`], which is where the shape and
    /// the latency are argued.
    ///
    /// **The camera's cull only.** [`ForwardRenderer::shadow_draws`] each have a
    /// statistics buffer of their own and none of them is read: a cascade's
    /// survivor count is a different question about a different frustum, and
    /// added into this one it would produce a number larger than the pool holds.
    ///
    /// [`None`] on a device that would not give out the buffers, which is what
    /// makes the counters row degrade to `indirect` rather than fail.
    cull_stats: Option<CullStatsRing>,

    tonemap_layout: BindGroupLayoutHandle,
    tonemap_pipeline_layout: PipelineLayoutHandle,
    tonemap_pipeline: GraphicsPipelineHandle,
    sampler: SamplerHandle,
    /// The multiplier the tonemap pass applies before its clamp — see
    /// [`set_exposure`](ForwardRenderer::set_exposure).
    ///
    /// Always within [`EXPOSURE_MIN`]`..=`[`EXPOSURE_MAX`], because the setter is
    /// the only thing that writes it and it clamps.
    exposure: f32,
    /// How far auto-exposure may move in one frame — see
    /// [`set_exposure_adaptation`](ForwardRenderer::set_exposure_adaptation).
    ///
    /// [`None`] until a caller says otherwise, and that is the whole distance in
    /// one frame: the picture the pass drew before adaptation existed.
    exposure_adaptation: Option<ExposureAdaptation>,
    /// Which operator the tonemap pass runs — see
    /// [`set_tonemap_curve`](ForwardRenderer::set_tonemap_curve).
    ///
    /// [`TonemapCurve::Aces`](crcbl_shaders::tonemap::TonemapCurve::Aces) until
    /// a caller says otherwise: this renderer shades in linear HDR, so the
    /// filmic roll-off is what a view that has said nothing wants. A
    /// display-referred view — a 2D sample, or a fixture whose assertions
    /// predict a code value — asks for
    /// [`TonemapCurve::Clamp`](crcbl_shaders::tonemap::TonemapCurve::Clamp),
    /// which is the identity on `0..=1`.
    tonemap_curve: tonemap::TonemapCurve,

    /// The format the tonemap pipeline was built for. A swapchain format change
    /// needs a new pipeline, which is why it is remembered rather than assumed.
    target_format: Format,

    /// A 1×1 `R8Unorm` image holding [`AMBIENT_OCCLUSION_NONE`], so a group of
    /// the mesh layout can fill [`AMBIENT_OCCLUSION_BINDING`] without naming an
    /// occlusion image that does not exist yet.
    ///
    /// [`ForwardRenderer::shadow_placeholder`]'s argument, one binding along.
    /// The shadow pass and the depth prepass name it and never sample it — a
    /// depth-only pipeline has no fragment stage — and **the forward pass names
    /// it too on a frame drawing without [`RenderEffects::AMBIENT_OCCLUSION`]**,
    /// where it is the whole of that effect's off-switch. An AO-on frame binds
    /// the occlusion pair's blurred output instead.
    ///
    /// **It is white because that is the value that occludes nothing**, which is
    /// what makes it an honest stand-in for "no occlusion was computed" rather
    /// than decoration. That it *reads* as white is `mesh.slang`'s doing: the
    /// binding is fetched with a `Load`, and a `Load` past a 1×1 image's one
    /// texel is zero on every backend, so the shader clamps the coordinate to the
    /// image's extent. See [`add_passes`](ForwardRenderer::add_passes).
    ///
    /// It is uploaded rather than cleared, so it is in
    /// [`ResourceState::ShaderRead`] from the moment it exists and no pass has to
    /// declare it to give it a layout.
    ambient_occlusion_placeholder: UploadedTexture,
    /// A 1×1 `R8Unorm` image holding [`CONTACT_SHADOW_NONE`], so a group of the
    /// mesh layout can fill [`CONTACT_SHADOW_BINDING`] without naming a
    /// contact-shadow image that does not exist yet.
    ///
    /// [`ForwardRenderer::ambient_occlusion_placeholder`]'s argument, one
    /// binding along and with one difference worth stating: an unclamped `Load`
    /// past this one's single texel would cost the frame its **sun**, not its
    /// ambient. `mesh.slang`'s `contact_at` is what clamps it.
    contact_shadow_placeholder: UploadedTexture,
    /// A 1×1×1 `Rg32Float` image holding [`probe_visibility_none`], so a group
    /// of the mesh layout can fill [`PROBE_VISIBILITY_BINDING`] before anything
    /// has been captured — and so the console switch has something to name when
    /// the maps are turned off.
    ///
    /// [`ForwardRenderer::ambient_occlusion_placeholder`]'s argument, with the
    /// same clamp on the shader's side: `mesh.slang`'s `probe_moments` clamps
    /// against `GetDimensions`, so all four of its taps land on this image's one
    /// texel and every probe reads as unobstructed.
    probe_visibility_placeholder: UploadedTexture,
    /// The captured maps, one `Rg32Float` layer per probe — `None` until
    /// [`ForwardRenderer::capture_probe_visibility`] has run, which is every
    /// frame drawn by a caller that never calls it.
    probe_visibility: Option<UploadedTexture>,
    /// The scene's static triangles, kept for that capture and for nothing else.
    ///
    /// Empty for a description that reserved no probes, which is what makes the
    /// retention cost of this rung zero for every caller that does not use it —
    /// see [`crate::probe_visibility`].
    probe_occluders: crate::probe_visibility::Occluders,
    /// The split-sum `DFG` table as an `Rgba8Unorm` image — binding
    /// [`SPECULAR_DFG_BINDING`], read by multi-scatter energy compensation and
    /// by every area light's specular term.
    ///
    /// Uploaded once from `crcbl_shaders::dfg::pair_texels` and never written
    /// again: it is a property of the GGX lobe rather than of a scene, a view or
    /// a frame. Unlike [`ForwardRenderer::ambient_occlusion_placeholder`] beside
    /// it this is not a stand-in for anything — there is no path on which the
    /// table is absent, because there is no path on which the lobe is.
    specular_dfg: UploadedTexture,
    /// The linearly transformed cosine fit as an `Rgba16Float` image — binding
    /// [`LTC_TABLE_BINDING`], and the whole of an area light's specular shape.
    ///
    /// Uploaded once from `crcbl_shaders::ltc::texels`, on the table above it's
    /// terms exactly and for the same reason: it is a property of the lobe, and
    /// it is bound on every path because Slang's Metal backend materialises
    /// every global into every entry point.
    ltc_table: UploadedTexture,
    /// `[frame][view]`: the entries [`ForwardRenderer::shadow_groups`] was built
    /// from.
    ///
    /// Kept for one rebuild only: the pages' and their sampler's, which
    /// [`ForwardRenderer::adopt_pages`] performs on every group of the mesh
    /// layout a slot holds — [`View::prepass_group_entries`]' reason.
    shadow_group_entries: Vec<Vec<Vec<BindGroupEntry>>>,

    /// The ground grid's pipeline and uniform ring — see [`crate::grid`].
    ///
    /// [`None`] until a caller first switches it on with
    /// [`set_ground_grid`](ForwardRenderer::set_ground_grid), which is what
    /// keeps a sample that never asks for a grid from building a pipeline and a
    /// ring of blocks for a pass it does not record. Once built it is kept —
    /// switching the grid off is [`ForwardRenderer::ground_grid_on`] and not a
    /// release, because releasing a uniform ring the frames in flight may still
    /// be reading is exactly what the ring exists to prevent.
    ground_grid: Option<GroundGrid>,
    /// Whether [`add_passes`](ForwardRenderer::add_passes) records the ground
    /// grid's pass. **`false` by default**: the grid is a tool's chrome, and
    /// every sample and every golden image predates it.
    ground_grid_on: bool,

    /// The debug draw layer's immediate-mode buffer and its pass — see
    /// [`crate::debug_draw`].
    ///
    /// Always present and empty by default, because appending to it is what a
    /// system does and the buffer is a `Vec`; the pipeline and the rings inside
    /// it are what stay unbuilt until a frame has both a segment and
    /// [`crate::debug_draw::r_debug_draw`] switched on.
    debug_draw: DebugDraw,

    /// The shadow atlas viewer — see [`crate::atlas_view`]. It draws on no frame
    /// but the one [`debug_view`](Self::debug_view) resolved to
    /// [`DebugView::ShadowAtlas`], which is none until a caller calls
    /// [`set_atlas_view`](Self::set_atlas_view).
    atlas_viewer: AtlasView,
    /// How large the internal render target is as a fraction of the extent a
    /// caller hands `begin_frame` — see [`set_render_scale`](Self::set_render_scale).
    render_scale: f32,

    /// The three layers a caller supplies — see [`crate::effects`].
    effect_request: EffectRequest,
    /// The fourth layer: what this device can draw, which clamps last and
    /// absolutely.
    ///
    /// **Every effect, and that is a fact about the effects rather than an
    /// unfinished clamp.** Topic 18 says so of the occlusion pair in as many
    /// words — "there is no device fact to gate on … inventing a capability that
    /// is really a performance opinion is what topic 39 exists to prevent" — and
    /// the reflection pair's module says it of itself. The shadow atlas is a
    /// `D32Float` image and a depth-only pass, which is not something a device
    /// that got this far can be missing either: one too small for the atlas
    /// fails to *build* this renderer rather than degrading past it.
    ///
    /// So the clamp is real and its rule set is empty. The first rule arrives
    /// with the ray-traced variants of these same three effects, which
    /// [`LightingPath`](crcbl_hal::LightingPath) selects and which nothing
    /// builds yet.
    device_effects: RenderEffects,
    /// What the frame [`begin_frame`](ForwardRenderer::begin_frame) opened
    /// draws, resolved once there.
    ///
    /// **Frozen for the frame on purpose.** `begin_frame` skips a shadow cull's
    /// parameter write when shadows are off and
    /// [`add_passes`](ForwardRenderer::add_passes) skips its dispatch; a request
    /// changed between the two would dispatch a cull whose counters nothing
    /// zeroed, which is a plausible frame drawn off last frame's numbers.
    frame_effects: RenderEffects,
    /// How many blur passes the frame [`begin_frame`](ForwardRenderer::begin_frame)
    /// opened runs over the raw occlusion channel — [`crate::ssao::blur_passes`],
    /// read once there.
    ///
    /// **Frozen for the frame on [`ForwardRenderer::frame_effects`]'s terms.**
    /// [`add_passes`](ForwardRenderer::add_passes) both counts the frame's
    /// full-screen triangles and records its passes, and a console command
    /// landing between the two reads would leave `counters` describing a frame
    /// that was never submitted.
    frame_ssao_blurs: u32,
    /// Full-screen passes the last [`add_passes`](ForwardRenderer::add_passes)
    /// recorded, which is what [`counters`](ForwardRenderer::counters) reports
    /// as submitted beside the pool's instances.
    ///
    /// Stored rather than re-derived from [`ForwardRenderer::frame_effects`]:
    /// `counters` describes the frame that *was* recorded, and a request set
    /// after it would otherwise change the count of a frame already submitted.
    recorded_fullscreen: u64,

    /// Whether the last [`add_passes`](ForwardRenderer::add_passes) recorded the
    /// debug draw layer's pass, as the one direct draw it costs.
    ///
    /// Separate from [`ForwardRenderer::recorded_fullscreen`] because it is not
    /// a full-screen triangle: it is one line-list draw of every segment this
    /// frame appended. Both are direct draws of one instance, which is what
    /// [`ForwardRenderer::direct_draws`] adds up.
    recorded_debug_draw: u64,
    /// How many tiles of the shadow atlas the last
    /// [`add_passes`](ForwardRenderer::add_passes) reset with a draw rather
    /// than with the attachment's own clear.
    ///
    /// Zero on every frame that clears the whole attachment, which is every
    /// frame until the cadence is switched on — see
    /// [`MeshModules::depth_clear_pipeline`]. One over-sized triangle of one
    /// instance each, so it joins the full-screen draws rather than the
    /// indirect ones.
    recorded_tile_clears: u64,
    /// `docs/plan/55-water.md`'s bodies of water, meshed, and the ring of
    /// buffers every view draws them from — see [`crate::water`]. Empty until
    /// [`set_water`](ForwardRenderer::set_water), and an empty set records no
    /// pass.
    water: WaterBodies,
    /// The surface draws the last [`add_passes`](ForwardRenderer::add_passes)
    /// recorded for the primary camera: one indexed draw per body, each of one
    /// instance, so they join the direct draws on the debug draw layer's terms.
    recorded_water_draws: u64,
    /// `docs/plan/57-grass.md`'s field, its device resources and the ring of
    /// retirements a replaced one leaves — see [`crate::grass`]. Empty until
    /// [`set_grass`](ForwardRenderer::set_grass), and an empty field records no
    /// pass.
    grass: GrassScene,
    /// The wind block every view writes into its own ring — see
    /// [`set_wind`](ForwardRenderer::set_wind). Calm until a caller sets one.
    wind: crcbl_shaders::wind::WindParams,
    /// The grass draws the last [`add_passes`](ForwardRenderer::add_passes)
    /// recorded for the primary camera: one per tile slot per look the field
    /// draws.
    ///
    /// **Not among the direct draws**, unlike the water surface's: every one of
    /// them is an indirect call whose instance count lives in a buffer a
    /// dispatch wrote, so the CPU knows how many *calls* it submitted and
    /// nothing about how many blades came out of them.
    recorded_grass_draws: u64,
}

/// What a partly-built [`ForwardRenderer`] has to give back.
///
/// `new` creates a dozen objects with `?` between them, and the seam's
/// `destroy_*` is explicit — so a failure half way through used to leak
/// everything created before it. The recorder's leak assertions cover the happy
/// path; this covers the other one.
#[derive(Debug, Default)]
struct Rollback {
    buffers: Vec<BufferHandle>,
    bind_groups: Vec<BindGroupHandle>,
    bind_group_layouts: Vec<BindGroupLayoutHandle>,
    pipeline_layouts: Vec<PipelineLayoutHandle>,
    pipelines: Vec<GraphicsPipelineHandle>,
    samplers: Vec<SamplerHandle>,
    /// The shadow atlas and its placeholder, which are created here rather than
    /// uploaded — so unlike [`Rollback::textures`] they are a plain handle each,
    /// with their views beside them.
    images: Vec<ImageHandle>,
    image_views: Vec<ImageViewHandle>,
    /// Uploaded images, which own a view each and so cannot be rolled back as
    /// one list of handles.
    textures: Vec<UploadedTexture>,
    /// The geometry pool, which owns two buffers, a semaphore and anything
    /// still staged — so it cannot be rolled back as a list of handles.
    pool: Option<MeshPool>,
    /// The instance pool, which owns one buffer per frame in flight.
    instances: Option<InstancePool>,
    /// The material table, which owns one buffer.
    materials: Option<MaterialTable>,
    /// The irradiance probe table, which owns one buffer.
    probes: Option<ProbeTable>,
    /// The irradiance probes' updater, which owns one pipeline,
    /// one layout and a ring of blocks — and only exists for a scene whose
    /// volume asked to be updated.
    probe_gather: Option<ProbeGather>,
    /// The cull and draw-argument passes, which own two pipelines and a ring of
    /// buffers each — and which clean themselves up on their own failure path,
    /// so this only carries one that was built.
    draws: Option<DrawGen>,
    /// One more of the same per shadow-atlas tile — a `Vec` rather than an
    /// `Option`, because a failure part way through the tiles has to release the
    /// ones already built.
    shadow_draws: Vec<DrawGen>,
    /// The cluster buffers, which own three buffers and are built on the
    /// mesh-shader path alone.
    clusters: Option<ClusterPool>,
    /// Topic 18's light list and froxel grid, which own a pipeline and a ring of
    /// three buffers — and which clean themselves up on their own failure path,
    /// so this only carries one that was built.
    lights: Option<LightGrid>,
    /// Topic 46's occlusion pair, which owns two
    /// pipelines, two layouts and a ring of blocks.
    ssao: Option<Ssao>,
    /// Topic 45's contact-shadow march, which owns one
    /// pipeline, one layout and a ring of blocks.
    contact_shadows: Option<ContactShadows>,
    /// Topic 47's depth pyramid, which owns one
    /// pipeline, one layout and a ring of blocks per level.
    hiz: Option<Hiz>,
    /// Topic 03 §3.3's farthest-depth pyramid,
    /// which owns one pipeline, one layout and — once a frame culled — a chain
    /// of level images.
    occlusion_pyramid: Option<OcclusionPyramid>,
    /// Topic 47's reflection march, which owns one
    /// pipeline, one layout and a ring of blocks.
    ssr: Option<Ssr>,
    /// The froxel volume, which owns three
    /// pipelines, two layouts and two rings of buffers.
    volumetric: Option<Volumetric>,
    /// Topic 43 §6's auto-exposure, which owns three
    /// pipelines, one layout and three rings of buffers.
    exposure: Option<Exposure>,
    /// Topic 48's bloom chain, which owns three
    /// pipelines, two layouts, a sampler and a ring of blocks.
    bloom: Option<Bloom>,
    /// The cheap antialiasing tier, which owns one
    /// pipeline, one layout, a sampler and a ring of blocks.
    fxaa: Option<Fxaa>,
    /// The higher antialiasing tier, which owns
    /// four compute pipelines, one graphics pipeline, two layouts and a ring of
    /// blocks.
    cmaa2: Option<Cmaa2>,
    upscale: Option<Upscale>,
    /// The background pass, which owns one pipeline, one layout and a ring of
    /// blocks and groups.
    sky_pass: Option<SkyPass>,
    /// The water surface's two pipelines, their layouts and a ring of blocks.
    water: Option<Water>,
    /// The grass passes' pipelines, their layouts and their rings of
    /// blocks.
    grass: Option<Grass>,
    /// The shadow atlas viewer, which owns one pipeline, one layout and a ring
    /// of blocks and groups.
    atlas_viewer: Option<AtlasView>,
    /// The camera, once [`View::build`] has made it whole — released as one,
    /// by [`View::destroy`].
    primary: Option<View>,
}

impl Rollback {
    /// Releases everything, in the same dependency order as
    /// [`ForwardRenderer::destroy`].
    fn run(self, device: &dyn Device) {
        if let Some(view) = self.primary {
            view.destroy(device);
        }
        for texture in self.textures {
            texture.destroy(device);
        }
        for handle in self.samplers {
            device.destroy_sampler(handle);
        }
        for handle in self.image_views {
            device.destroy_image_view(handle);
        }
        for handle in self.images {
            device.destroy_image(handle);
        }
        for handle in self.pipelines {
            device.destroy_graphics_pipeline(handle);
        }
        for handle in self.pipeline_layouts {
            device.destroy_pipeline_layout(handle);
        }
        for handle in self.bind_groups {
            device.destroy_bind_group(handle);
        }
        for handle in self.bind_group_layouts {
            device.destroy_bind_group_layout(handle);
        }
        for handle in self.buffers {
            device.destroy_buffer(handle);
        }
        if let Some(clusters) = self.clusters {
            clusters.destroy(device);
        }
        for draws in self.shadow_draws {
            draws.destroy(device);
        }
        if let Some(lights) = self.lights {
            lights.destroy(device);
        }
        if let Some(atlas_viewer) = self.atlas_viewer {
            atlas_viewer.destroy(device);
        }
        if let Some(grass) = self.grass {
            grass.destroy(device);
        }
        if let Some(water) = self.water {
            water.destroy(device);
        }
        if let Some(sky_pass) = self.sky_pass {
            sky_pass.destroy(device);
        }
        if let Some(upscale) = self.upscale {
            upscale.destroy(device);
        }
        if let Some(cmaa2) = self.cmaa2 {
            cmaa2.destroy(device);
        }
        if let Some(fxaa) = self.fxaa {
            fxaa.destroy(device);
        }
        if let Some(bloom) = self.bloom {
            bloom.destroy(device);
        }
        if let Some(exposure) = self.exposure {
            exposure.destroy(device);
        }
        if let Some(volumetric) = self.volumetric {
            volumetric.destroy(device);
        }
        if let Some(ssr) = self.ssr {
            ssr.destroy(device);
        }
        if let Some(occlusion_pyramid) = self.occlusion_pyramid {
            occlusion_pyramid.destroy(device);
        }
        if let Some(hiz) = self.hiz {
            hiz.destroy(device);
        }
        if let Some(contact_shadows) = self.contact_shadows {
            contact_shadows.destroy(device);
        }
        if let Some(ssao) = self.ssao {
            ssao.destroy(device);
        }
        if let Some(draws) = self.draws {
            draws.destroy(device);
        }
        // Before the table, because its bind groups name that table's rows.
        if let Some(gather) = self.probe_gather {
            gather.destroy(device);
        }
        if let Some(table) = self.probes {
            table.destroy(device);
        }
        if let Some(table) = self.materials {
            table.destroy(device);
        }
        if let Some(pool) = self.instances {
            pool.destroy(device);
        }
        if let Some(pool) = self.pool {
            pool.destroy(device);
        }
    }
}

/// What every bind group of the mesh layout names identically.
///
/// Split from [`MeshGroup`] rather than folded into it because the split *is*
/// the claim: a resource here cannot differ between the colour pass's group and
/// a cascade's, and one there must be looked at.
struct SharedBindings<'a> {
    vertices: BufferHandle,
    draw_constants: BufferHandle,
    mesh_table: BufferHandle,
    materials: BufferHandle,
    /// Bindings [`BASE_COLOR_PAGE_BINDING`], [`NORMAL_PAGE_BINDING`],
    /// [`MRO_PAGE_BINDING`] and [`EMISSIVE_PAGE_BINDING`] — the four material
    /// pages, every one read through the sampler at [`PAGE_SAMPLER_BINDING`]
    /// beside them — as this frame slot names them, which is what
    /// [`ForwardRenderer::adopt_pages`] moves one slot at a time.
    pages: PageBindings,
    /// `Some` on [`GeometryPath::MeshShader`] and on no other path, which is
    /// what decides whether the mesh-only bindings exist at all.
    clusters: Option<&'a ClusterPool>,
    shadow_sampler: SamplerHandle,
    /// Bindings [`LIGHT_LIST_BINDING`] and [`LIGHT_GRID_BINDING`], this frame's
    /// slots of the light ring.
    ///
    /// Shared rather than per-group, unlike the instance array beside them, and
    /// that is the claim: **a cascade shades nothing**, so it reads the same
    /// list and the same grid the colour pass does — the depth-only pipeline
    /// simply never looks. Two buffers per pass would be two clustering
    /// dispatches for one camera.
    lights: BufferHandle,
    light_grid: BufferHandle,
    /// Binding [`PROBE_TABLE_BINDING`], **this frame's slot** of the irradiance
    /// grid's ring.
    ///
    /// Shared across the *groups of one frame* rather than across frames, which
    /// is the light list's arrangement exactly: a cascade shades nothing, so it
    /// reads the same rows the colour pass does and the depth-only pipeline
    /// simply never looks. What it is not is shared across the ring — see
    /// [`crate::probe`] for why the table is per-frame at all.
    probes: BufferHandle,
    /// Binding [`LEVEL_GROUP_TABLE_BINDING`], `DrawGen`'s packed table buffer.
    ///
    /// Shared rather than per-group for the probe grid's reason exactly: the
    /// regions are written when a mesh becomes resident and never per frame, so
    /// a cascade and the colour pass read the same words. What varies between
    /// them is the *budget* the mesh stage projects against, and that rides in
    /// each pass's own frame block.
    tables: BufferHandle,
    /// Binding [`SPECULAR_DFG_BINDING`], the split-sum `DFG` pair — see
    /// [`ForwardRenderer::specular_dfg`].
    ///
    /// Shared rather than per-group for the probe grid's reason and more
    /// strongly: it is cooked into the binary, uploaded once at build and
    /// identical for every view this engine will ever draw. A cascade names it
    /// and never looks.
    specular_dfg: ImageViewHandle,
    /// Binding [`LTC_TABLE_BINDING`], the area lights' fit — see
    /// [`ForwardRenderer::ltc_table`]. Shared for the table above it's reason.
    ltc_table: ImageViewHandle,
}

/// The half of a mesh-layout bind group that differs between the colour pass and
/// each shadow cascade.
///
/// One description for both, so the two cannot drift: a cascade's group is the
/// colour pass's with six resources swapped, and swapping the wrong five of them
/// is a shadow map rendered from the camera — which looks like a shadow map.
struct MeshGroup {
    /// Binding 0. The colour pass's frame block, or a cascade's copy whose
    /// `view_proj` is that cascade's matrix.
    uniforms: BufferHandle,
    /// Binding 2. This frame's slot of the instance ring.
    instances: BufferHandle,
    /// Binding 5. Whose survivors this group draws.
    runs: BufferHandle,
    /// Binding 12, on the mesh path: the same survivors' indirect arguments,
    /// read as data.
    args: BufferHandle,
    /// Binding 13, where there is an amplification stage: the frustum it culls
    /// clusters against.
    cull_params: BufferHandle,
    /// Binding 14, likewise: what it counts survivors into.
    cull_stats: BufferHandle,
    /// Binding 18, likewise: the cut the descent chose, one word per resident
    /// cluster. `None` exactly where there is no amplification stage, which is
    /// where the layout has no CLUSTER_SELECTION_BINDING either.
    ///
    /// **A buffer per pass**, not one shared: the colour pass is recorded last,
    /// so a cascade writing the camera's would leave nothing of its own to read.
    /// See [`ForwardRenderer::shadow_selection`].
    cluster_selection: Option<BufferHandle>,
    /// Binding 19, likewise: topic 25's hysteresis state, which the
    /// draw-argument pass wrote this frame and this one only reads.
    ///
    /// **A buffer per pass** as well, because the colour pass and a cascade
    /// judge the same groups under different budgets — see
    /// [`TileBuffers::group_state`].
    group_state: Option<BufferHandle>,
    /// Binding [`SHADOW_ATLAS_BINDING`]. The atlas for the pass that reads it,
    /// and the placeholder for the pass that writes it — see
    /// [`ForwardRenderer::shadow_placeholder`], which is where that is argued.
    shadow_map: ImageViewHandle,
    /// Binding [`AMBIENT_OCCLUSION_BINDING`]. The blurred occlusion channel for
    /// a forward pass that computed one, and the white placeholder everywhere
    /// else — see [`ForwardRenderer::ambient_occlusion_placeholder`].
    ///
    /// **Every group built at `build` names the placeholder**, including the
    /// camera's: the occlusion image may be a graph transient whose view exists
    /// only at execute time, so the camera's group is rebuilt against whatever
    /// the frame bound inside the forward pass and cached — the shape
    /// [`View::tonemap_groups`] already has.
    ambient_occlusion: ImageViewHandle,
    /// Binding [`CONTACT_SHADOW_BINDING`]. The contact-shadow channel for a
    /// forward pass that marched one, and the white placeholder everywhere else
    /// — see [`ForwardRenderer::contact_shadow_placeholder`].
    ///
    /// [`MeshGroup::ambient_occlusion`]'s terms exactly, including that every
    /// group built at `build` names the placeholder.
    contact_shadow: ImageViewHandle,
    /// Binding [`PROBE_VISIBILITY_BINDING`]. The captured per-probe visibility
    /// maps for the camera's pass, and the one-texel placeholder everywhere
    /// else — see [`ForwardRenderer::probe_visibility_placeholder`].
    ///
    /// [`MeshGroup::ambient_occlusion`]'s terms, with one difference: the image
    /// is not a graph transient but an ordinary uploaded texture, so what makes
    /// this a per-frame swap is the console switch and whether a capture has
    /// happened yet — neither of which is known at `build`.
    probe_visibility: ImageViewHandle,
}

impl MeshGroup {
    fn entries(&self, shared: &SharedBindings<'_>) -> Vec<BindGroupEntry> {
        let mut entries = vec![
            BindGroupEntry {
                binding: 0,
                array_index: 0,
                resource: BindingResource::whole_buffer(self.uniforms),
            },
            BindGroupEntry {
                binding: 1,
                array_index: 0,
                resource: BindingResource::whole_buffer(shared.vertices),
            },
            BindGroupEntry {
                binding: 2,
                array_index: 0,
                // **This frame's slot of the instance ring, not a shared
                // buffer.** Binding one buffer here for every group would undo
                // the ring and reintroduce the cross-submission
                // read-after-write hazard it exists to prevent.
                resource: BindingResource::whole_buffer(self.instances),
            },
            BindGroupEntry {
                binding: 3,
                array_index: 0,
                // **One block, not the whole buffer.** The binding is dynamic,
                // so the bind's offset is added on top of this one and both
                // Vulkan and WebGPU require `offset + dynamic + size` to stay
                // inside the buffer — bound whole, the very first non-zero
                // dynamic offset would be out of range.
                resource: BindingResource::Buffer {
                    buffer: shared.draw_constants,
                    offset: 0,
                    size: DRAW_CONSTANTS_BLOCK,
                },
            },
            BindGroupEntry {
                binding: 4,
                array_index: 0,
                // The same table in every group, unlike the instance array
                // above it: the pool writes an entry when a mesh is uploaded or
                // freed, neither of which happens between frames here.
                resource: BindingResource::whole_buffer(shared.mesh_table),
            },
            BindGroupEntry {
                binding: 5,
                array_index: 0,
                // Whose cull this group draws from. This is the binding a
                // cascade's group differs in most consequentially: it is what
                // makes the shadow pass draw what the *light* can see rather
                // than what the camera can.
                resource: BindingResource::whole_buffer(self.runs),
            },
            BindGroupEntry {
                binding: 6,
                array_index: 0,
                resource: BindingResource::whole_buffer(shared.materials),
            },
            BindGroupEntry {
                binding: BASE_COLOR_PAGE_BINDING,
                array_index: 0,
                // **One entry, `array_index: 0`**, because the page is one
                // image and the layer is chosen in the shader. A bindless array
                // would be one entry per texture at ascending array indices,
                // which is the write path `BindGroupEntry`'s own docs describe
                // and the one this pass does not take.
                resource: BindingResource::ImageView(
                    shared.pages.views[PageKind::BaseColor.index()],
                ),
            },
            BindGroupEntry {
                binding: PAGE_SAMPLER_BINDING,
                array_index: 0,
                resource: BindingResource::Sampler(shared.pages.sampler),
            },
        ];
        if let Some(clusters) = shared.clusters {
            entries.extend([
                BindGroupEntry {
                    binding: CLUSTERS_BINDING,
                    array_index: 0,
                    // The same three buffers in every group, on the mesh table's
                    // terms: clusters are written when the pool is built and
                    // never again.
                    resource: BindingResource::whole_buffer(clusters.clusters()),
                },
                BindGroupEntry {
                    binding: CLUSTER_VERTICES_BINDING,
                    array_index: 0,
                    resource: BindingResource::whole_buffer(clusters.vertices()),
                },
                BindGroupEntry {
                    binding: CLUSTER_CORNERS_BINDING,
                    array_index: 0,
                    resource: BindingResource::whole_buffer(clusters.corners()),
                },
                BindGroupEntry {
                    binding: CLUSTER_DRAW_ARGS_BINDING,
                    array_index: 0,
                    // **Arguments read as data.** The mesh path records no
                    // indirect draw at all; what it wants out of this buffer is
                    // the one word only the GPU knows — how many instances
                    // survived into each bucket.
                    resource: BindingResource::whole_buffer(self.args),
                },
            ]);
        }
        // Both mesh entry points retain these native buffer arguments even
        // when no amplification stage reads them.
        if shared.clusters.is_some() {
            entries.extend([
                BindGroupEntry {
                    binding: CLUSTER_CULL_BINDING,
                    array_index: 0,
                    resource: BindingResource::whole_buffer(self.cull_params),
                },
                BindGroupEntry {
                    binding: CLUSTER_CULL_STATS_BINDING,
                    array_index: 0,
                    resource: BindingResource::whole_buffer(self.cull_stats),
                },
            ]);
        }
        entries.push(BindGroupEntry {
            binding: SHADOW_ATLAS_BINDING,
            array_index: 0,
            resource: BindingResource::ImageView(self.shadow_map),
        });
        entries.push(BindGroupEntry {
            binding: SHADOW_SAMPLER_BINDING,
            array_index: 0,
            resource: BindingResource::Sampler(shared.shadow_sampler),
        });
        // Mesh-only buffers are sorted after the common fragment prefix below.
        if let Some(clusters) = shared.clusters {
            entries.push(BindGroupEntry {
                binding: CLUSTER_SELECT_BINDING,
                array_index: 0,
                // Bound with the geometry rather than with the cull, because
                // `vertex_base` *is* geometry: it is which level of a DAG a
                // cluster's vertices live in, and both mesh entry points resolve
                // a vertex through it.
                resource: BindingResource::whole_buffer(clusters.selection()),
            });
        }
        if let Some(selection) = self.cluster_selection {
            entries.push(BindGroupEntry {
                binding: CLUSTER_SELECTION_BINDING,
                array_index: 0,
                resource: BindingResource::whole_buffer(selection),
            });
        }
        if let Some(state) = self.group_state {
            entries.push(BindGroupEntry {
                binding: CLUSTER_GROUP_STATE_BINDING,
                array_index: 0,
                resource: BindingResource::whole_buffer(state),
            });
        }
        // Topic 18's pair, on every path and in every group — see the layout,
        // which has no configuration that omits them either.
        entries.push(BindGroupEntry {
            binding: LIGHT_LIST_BINDING,
            array_index: 0,
            resource: BindingResource::whole_buffer(shared.lights),
        });
        entries.push(BindGroupEntry {
            binding: LIGHT_GRID_BINDING,
            array_index: 0,
            resource: BindingResource::whole_buffer(shared.light_grid),
        });
        // Shared fragment textures and probes retain their raster bindings.
        entries.push(BindGroupEntry {
            binding: AMBIENT_OCCLUSION_BINDING,
            array_index: 0,
            resource: BindingResource::ImageView(self.ambient_occlusion),
        });
        // And the irradiance grid past it — see [`PROBE_TABLE_BINDING`].
        entries.push(BindGroupEntry {
            binding: PROBE_TABLE_BINDING,
            array_index: 0,
            resource: BindingResource::whole_buffer(shared.probes),
        });
        // Group records are present on both mesh paths, matching the layout.
        if shared.clusters.is_some() {
            entries.push(BindGroupEntry {
                binding: LEVEL_GROUP_TABLE_BINDING,
                array_index: 0,
                resource: BindingResource::whole_buffer(shared.tables),
            });
        }
        // The DFG texture is read by the fragment stage of every path.
        entries.push(BindGroupEntry {
            binding: SPECULAR_DFG_BINDING,
            array_index: 0,
            resource: BindingResource::ImageView(shared.specular_dfg),
        });
        // And §2's normal page above that, on the same ascending terms — see
        // [`NORMAL_PAGE_BINDING`]. Unconditional and `array_index: 0` for
        // binding 7's reason: one image, and the layer is chosen in the shader.
        entries.push(BindGroupEntry {
            binding: NORMAL_PAGE_BINDING,
            array_index: 0,
            resource: BindingResource::ImageView(shared.pages.views[PageKind::Normal.index()]),
        });
        // And the area lights' table above that, on the same ascending terms —
        // see [`LTC_TABLE_BINDING`].
        entries.push(BindGroupEntry {
            binding: LTC_TABLE_BINDING,
            array_index: 0,
            resource: BindingResource::ImageView(shared.ltc_table),
        });
        // And the contact-shadow channel above that, last of the set and on the
        // same ascending terms — see [`CONTACT_SHADOW_BINDING`].
        entries.push(BindGroupEntry {
            binding: CONTACT_SHADOW_BINDING,
            array_index: 0,
            resource: BindingResource::ImageView(self.contact_shadow),
        });
        // And the probe visibility maps above that, on the same ascending terms
        // — see [`PROBE_VISIBILITY_BINDING`].
        entries.push(BindGroupEntry {
            binding: PROBE_VISIBILITY_BINDING,
            array_index: 0,
            resource: BindingResource::ImageView(self.probe_visibility),
        });
        // And §2's other two pages above that, last of the set and on the same
        // ascending terms — see [`MRO_PAGE_BINDING`] and
        // [`EMISSIVE_PAGE_BINDING`]. Unconditional and `array_index: 0` for the
        // normal page's reason: one image apiece, and the layer is chosen in
        // the shader.
        entries.push(BindGroupEntry {
            binding: MRO_PAGE_BINDING,
            array_index: 0,
            resource: BindingResource::ImageView(
                shared.pages.views[PageKind::MetallicRoughnessOcclusion.index()],
            ),
        });
        entries.push(BindGroupEntry {
            binding: EMISSIVE_PAGE_BINDING,
            array_index: 0,
            resource: BindingResource::ImageView(shared.pages.views[PageKind::Emissive.index()]),
        });
        entries.sort_by_key(|entry| entry.binding);
        entries
    }
}

/// The two `ArrayPages` images every group of the mesh layout names, as the
/// graph knows them.
///
/// One value rather than two arguments because the two travel together
/// everywhere: every pass that declares one declares the other, and a pass
/// handed them the wrong way round would order a caller's copy into the wrong
/// image — which is a barrier bug, and therefore one that reproduces on one
/// backend and not the others.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct MaterialPages {
    /// §3.2's base-colour page — [`ForwardRenderer::base_color_page_import`].
    base_color: ImageId,
    /// §2's normal page — [`ForwardRenderer::normal_page_import`].
    normal: ImageId,
    /// §2's metallic-roughness-occlusion page —
    /// [`ForwardRenderer::mro_page_import`].
    mro: ImageId,
    /// §2's emissive page — [`ForwardRenderer::emissive_page_import`].
    emissive: ImageId,
}

/// Everything [`ForwardRenderer::add_shadow_pass`] declares and does not write,
/// as the graph knows it.
///
/// One value rather than an argument apiece for [`MaterialPages`]' reason, and
/// the list grew past what an argument list should be the moment the probe rows
/// joined it: each of these is in every cascade's bind group and read by no
/// cascade, so what the pass does with them is one thing — declare them, so the
/// graph can order whoever writes them against these draws.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ShadowReads {
    /// The occlusion placeholder every cascade's group stands the real channel
    /// in for — [`ForwardRenderer::ambient_occlusion_placeholder`].
    occlusion_placeholder: ImageId,
    /// §3.2's and §2's pages, which the cascades name and never sample.
    pages: MaterialPages,
    /// The skinned vertex region, where a frame has one — the cascades pull the
    /// same geometry the colour pass does.
    skinned: Option<BufferId>,
    /// This frame's slot of the probe ring — see [`crate::probe`].
    probes: BufferId,
}

/// What the mesh pass's bind-group layout is called.
///
/// Named rather than written twice because a test asserts on it: the layout's
/// *binding numbers* are what `crcbl-mtl` turns into Metal argument-table
/// indices by counting, so `the_mesh_layout_declares_the_same_bindings_with_and_without_a_task_stage`
/// has to find this one layout among the recorder's.
const MESH_LAYOUT_LABEL: &str = "mesh frame";

/// Imports a buffer a pass both reads and writes, carried from one frame on
/// its slot to the next: it arrives in the state the previous frame that used
/// the slot left it in, and that is the state it is declared to leave in.
///
/// A record of the cut or a statistics sink, which a pass writes and the next
/// frame on the same slot writes again — a barrier naming `Undefined` as its
/// source would carry no source scope and order this frame's write against
/// nothing.
fn import_read_write(graph: &mut RenderGraph<'_>, label: &str, buffer: BufferHandle) -> BufferId {
    graph.import_buffer(
        label,
        ImportedBuffer {
            buffer,
            initial: ResourceState::ShaderReadWrite,
            final_state: ResourceState::ShaderReadWrite,
        },
    )
}

/// Declares the buffers a geometry pass reads to find its draws.
///
/// The other half of [`BucketDraws`]: what the *graph* has to be told, where that
/// struct is what the encoder is told. Three passes declare exactly this set, and
/// the seam calls the barrier it produces the single most important one in a
/// GPU-driven frame — its absence produces "sometimes nothing draws".
///
/// A caller with a cluster-selection buffer of its own appends it; that is the
/// one declaration that differs between the colour pass, a cascade and the depth
/// prepass.
fn read_draw_sources<'g, 'a>(
    pass: PassBuilder<'g, 'a>,
    draws: &GeneratedDraws,
    emit: EmitTail,
) -> PassBuilder<'g, 'a> {
    // The buffers the draws come out of. Declaring them is what makes the graph
    // transition them out of the compute pass's `ShaderReadWrite`.
    let pass = pass.read_buffer(draws.runs_id);
    if emit.is_mesh() {
        // **The same arguments, read as data rather than executed**, which is
        // what the stages use to bound the run of surviving instances they index.
        // The per-bucket draw *counts* are not read at all, because nothing here
        // is a draw whose count could come from memory.
        //
        // The dispatch *extents* are a real indirect read — one structure per
        // bucket, written by the same pass. They are in a **different buffer**
        // from the arguments above and that separation is load-bearing: a
        // resource is in exactly one state per pass and these two are in
        // different ones. They share a buffer with the counts instead, which
        // this path does not read at all — see [`GeneratedDraws::counts`].
        let pass = pass
            .read_buffer(draws.args_id)
            .use_buffer(draws.counts_id, ResourceState::IndirectArgument);
        // The amplification stage counts its survivors into the culling
        // statistics, which the draw-argument pass read a moment ago — so this
        // is a write-after-read the graph has to order, and declaring it is
        // the whole of how it learns to.
        //
        // Topic 25's hysteresis state is read here and written by
        // the draw-argument pass a moment ago. Declaring it is what orders the
        // two — and what puts it back into `ShaderReadWrite` at the end of the
        // graph, which is where the next frame's draw-argument pass expects to
        // find it.
        //
        // **Declared on the whole mesh path, not only where there is an
        // amplification stage**, because that is where the bind group now
        // names both — see the layout, which is where the Metal argument-table
        // arithmetic that forced it is argued. A buffer bound writable and
        // never transitioned is a descriptor in the wrong resource state, which
        // is what the graph exists to prevent.
        pass.use_buffer(draws.visible_count_id, ResourceState::ShaderReadWrite)
            .read_buffer(draws.group_state_id)
    } else {
        pass.use_buffer(draws.args_id, ResourceState::IndirectArgument)
            .use_buffer(draws.counts_id, ResourceState::IndirectArgument)
    }
}

/// What one [`MeshDesc`](crate::scene::MeshDesc) became once it was resident.
///
/// One of these per description mesh, in description order — so a mesh's index
/// here is its index there, which is what lets the bucket table, the level
/// tables and the cluster pool all be filled in by walking one list.
struct ResidentMesh {
    /// This mesh's table ids, finest first: one entry for a flat mesh, one per
    /// level for a DAG. Never empty.
    ///
    /// Every level is its own vertex range and so its own table entry. Level 0's
    /// id is the one the *instance* carries and the one the cull pass reads a
    /// bounding box out of; the coarser ones are named by the bucket table on a
    /// path that takes a uniform cut, and by nothing at all on the mesh path,
    /// where a cluster reaches its own level through
    /// [`vertex_bases`](Self::vertex_bases) instead.
    levels: Vec<u32>,
    /// Per level, how far that level's vertices start past level 0's — so a flat
    /// mesh's single entry is zero.
    ///
    /// What [`crcbl_shaders::cluster_select::ClusterSelect::vertex_base`] holds,
    /// and the whole of what makes a DAG drawable from one instance: the mesh
    /// stage adds this to the instance's own `base_vertex`, so a cut spanning
    /// three levels reads three different vertex ranges out of one pool.
    vertex_bases: Vec<u32>,
    /// Level 0's pool handle, for a mesh that can be **skinned** — and [`None`]
    /// for a [`Geometry::Dag`].
    ///
    /// A DAG is refused because its coarser levels are separate vertex runs no
    /// skinning dispatch writes: an instance drawn out of a skinned region
    /// resolves every level through [`vertex_bases`](Self::vertex_bases) added
    /// to the region's base, which for anything but level 0 is memory the
    /// dispatch never touched.
    skinnable: Option<MeshHandle>,
}

impl ResidentMesh {
    /// The table id an instance of this mesh carries: **level 0's**, whatever
    /// the geometry path, because it is the entry `cull.slang` reads a bounding
    /// box out of and the coarser levels approximate the same surface inside the
    /// same box.
    fn id(&self) -> u32 {
        self.levels[0]
    }
}

/// One skinned object the renderer re-points every frame: the instance, and the
/// base vertex it draws out of under each parity.
///
/// The bases are copied out of the [`SkinnedMesh`] rather than borrowed from it,
/// so placing an object does not tie the renderer's lifetime to the caller's
/// reservation — the renderer never needs the region again, only the two
/// numbers.
#[derive(Clone, Copy, Debug)]
struct SkinnedInstance {
    handle: InstanceHandle,
    /// Indexed by parity, in [`crate::skinning::SkinnedRegion::base`]'s
    /// indexing — so the half a frame of parity `p` draws out of is
    /// `bases[p & 1]` and the half the frame before it filled is
    /// `bases[(p ^ 1) & 1]`, which is
    /// [`SkinnedRegion::previous_base`](crate::skinning::SkinnedRegion::previous_base)'s
    /// answer for the same `p`.
    bases: [u32; 2],
    /// Whether a frame has already pointed this entry at a half of the region
    /// it now names.
    ///
    /// **What makes the previous base meaningful.** The half a frame did not
    /// write holds whatever its reservation came with until a dispatch fills
    /// it, so an object's first frame out of a region has no previous
    /// deformation to point at — naming that half would give it a motion vector
    /// against undefined vertices. Such an entry is put at rest instead, which
    /// is the rule [`InstancePool::insert`](crate::instance_pool::InstancePool::insert)
    /// applies to `previous_transform` for the same reason: a spawn did not
    /// travel from anywhere.
    pointed: bool,
}

/// The two base vertices an object drawn out of `mesh` alternates between, in
/// [`SkinnedInstance::bases`]' indexing.
fn skinned_bases(mesh: &SkinnedMesh) -> [u32; 2] {
    [mesh.region().base(0), mesh.region().base(1)]
}

/// One shadow cull's per-frame buffers, read out of its [`DrawGen`] before that
/// generator is handed to the rollback.
struct TileBuffers {
    runs: Vec<BufferHandle>,
    args: Vec<BufferHandle>,
    cull_params: Vec<BufferHandle>,
    cull_stats: Vec<BufferHandle>,
    /// This cull's own hysteresis state, and not the camera's.
    ///
    /// A shadow view selects from the camera's eye at the camera's scale, like
    /// the colour pass, but under budgets [`SHADOW_LOD_BIAS`] times as large — so
    /// it reaches a different answer for the same group, and an answer carried
    /// between frames needs somewhere of its own to be carried. Sharing the
    /// camera's buffer would be two rules writing one history and each undoing
    /// the other's band every frame.
    ///
    /// One per cull rather than one for the shadow pass, even though every one of
    /// them selects identically: each cull is its own [`DrawGen`], and one buffer
    /// between them would be several dispatches writing one element with nothing
    /// ordering them.
    ///
    /// **This is what a cull costs that is not a dispatch.** It is
    /// [`Capacities::instances`](crate::scene::Capacities::instances) × the
    /// resident group count words of device-local
    /// memory, held for the renderer's whole life whether anything is drawn
    /// through it or not, and it is the reason [`shadow::LIGHT_SLOTS`] is a
    /// budget rather than "however many lights the scene has" — and the reason a
    /// point light's six faces share one of these rather than owning six.
    group_state: BufferHandle,
}

impl ForwardRenderer {
    /// Builds both pipelines and makes [`scene::demo`] resident.
    ///
    /// [`ForwardRenderer::with_scene`] with the engine's own description, and
    /// nothing else — so the frame this draws is the one the golden suite has
    /// always compared, and every existing caller is untouched.
    ///
    /// `target_format` must be the format the tonemap pass will render into —
    /// dynamic rendering checks pipeline and attachment formats against each
    /// other at pass-begin time, not at creation.
    ///
    /// # Errors
    ///
    /// [`HalError`], on [`ForwardRenderer::with_scene`]'s terms.
    pub fn new(
        device: &dyn Device,
        queue: QueueHandle,
        target_format: Format,
    ) -> Result<Self, HalError> {
        Self::with_scene(device, queue, target_format, &scene::demo())
    }

    /// Builds both pipelines and makes `scene` resident.
    ///
    /// Everything in the description is created here and never grows: the
    /// geometry pools, the cluster pool, the material table, the page, the
    /// instance array and the bucket table are all sized and filled once. See
    /// [`crate::scene`] for why that split is where the seam is, and for the
    /// four places a description's *order* decides what the frame looks like.
    ///
    /// `target_format` must be the format the tonemap pass will render into —
    /// dynamic rendering checks pipeline and attachment formats against each
    /// other at pass-begin time, not at creation.
    ///
    /// # No description is too small
    ///
    /// One mesh and one material row is a scene, and so is
    /// [`scene::demo`]'s four and three. Nothing on this type names a
    /// description entry by position any more — the five `set_*` demo wrappers
    /// that did are gone, and [`ForwardRenderer::add_instance`] takes the mesh
    /// and the row a caller wrote its **own** description in.
    ///
    /// # Errors
    ///
    /// [`HalError::InvalidDescriptor`] if the description cannot be made
    /// resident as written: a page layer that is not its kind's extent's worth of
    /// RGBA8, a page kind holding layers at no extent, a material row naming a
    /// layer that kind's page has not got, a DAG carrying a vertex array for anything but each of its
    /// levels, a cluster array with a read outside itself in it (see
    /// [`MeshClusters::check`]), or more vertices, indices, mesh table entries or
    /// material rows than [`SceneDesc::capacities`] reserves — that last naming the pool, the
    /// capacity and what the description needs, because the answer to it is to
    /// raise the number. Every one of those is settled **before the first device
    /// object exists**, so a refusal leaks nothing.
    ///
    /// [`HalError`] otherwise, from any seam call — including the geometry a
    /// pool refuses for itself, such as vertex bytes that are not a whole number
    /// of vertices. A backend that cannot build a pipeline says so here rather
    /// than drawing nothing later, and a failure part-way through releases
    /// everything already created, so a caller that retries or exits leaves
    /// nothing behind.
    pub fn with_scene(
        device: &dyn Device,
        queue: QueueHandle,
        target_format: Format,
        scene: &SceneDesc<'_>,
    ) -> Result<Self, HalError> {
        Self::with_scene_serviced(device, queue, target_format, scene, &mut || {})
    }

    /// [`ForwardRenderer::with_scene`], calling `service` between the steps of
    /// the build so the thread running it can keep its window alive.
    ///
    /// # What it is for: a build on the thread that owns the window
    ///
    /// The build needs the device, so it runs on whichever thread holds it —
    /// for a game that is the loop thread, which also owns the window, and a
    /// desktop marks a window hung when its thread takes no message for a few
    /// seconds (see `crcbl_shell::Shell::keep_alive`). A game passes
    /// `&mut || shell.keep_alive()` here and the window keeps answering for the
    /// whole build.
    ///
    /// # Where it is called
    ///
    /// Where the time is, which was measured rather than guessed. With a cold
    /// driver shader cache — a player's first launch, or the first after a
    /// driver update — **pipeline creation is most of the build**. Measured in
    /// 2026-09 on an RX 7900 XTX, release, building one glTF scene: 2.2 to 2.4 s
    /// on Vulkan and 1.9 to 2.2 s on D3D12 cold against 0.25 s warm, while the
    /// mesh and page uploads took about 0.1 s either way. So `service` runs
    /// after every mesh upload (each level of a DAG), after every page layer's
    /// mip chain and each page's upload, after each of the camera's
    /// post-processing subsystems, before every mesh-pass and grass pipeline,
    /// and between the build's other phases.
    ///
    /// **The longest gap left is one pipeline**, and a pipeline cannot be
    /// split: on that scene, cold, it was the forward pass's colour pipeline
    /// at 0.31 s on Vulkan and 0.36 s on D3D12, where the build without calls
    /// had been one gap of 2 s. Warm, the longest was about 0.04 s. A machine
    /// eight times slower under contention still calls back inside the five
    /// seconds Windows allows.
    ///
    /// `service` sees nothing of the build and cannot touch the renderer or the
    /// scene. Whatever reaches the window meanwhile — input, a resize, a close
    /// request — is the caller's to keep for later, as
    /// `crcbl_shell::Shell::keep_alive` does.
    ///
    /// # Errors
    ///
    /// [`ForwardRenderer::with_scene`]'s, on its terms: a failure part-way
    /// through releases everything already created.
    pub fn with_scene_serviced(
        device: &dyn Device,
        queue: QueueHandle,
        target_format: Format,
        scene: &SceneDesc<'_>,
        service: &mut dyn FnMut(),
    ) -> Result<Self, HalError> {
        Self::build_on_path(
            device,
            queue,
            target_format,
            scene,
            device.preferred_geometry_path(),
            service,
        )
    }

    /// Builds exactly the requested geometry tail, independently of the device's
    /// performance preference. Capabilities remain available to other callers.
    ///
    /// # Errors
    ///
    /// Returns [`HalError::UnsupportedFeatures`] before creating device objects
    /// when the requested tail lacks its required feature. Other failures follow
    /// [`Self::with_scene`]'s rollback contract.
    pub fn with_scene_on_path(
        device: &dyn Device,
        queue: QueueHandle,
        target_format: Format,
        scene: &SceneDesc<'_>,
        geometry_path: GeometryPath,
    ) -> Result<Self, HalError> {
        Self::build_on_path(
            device,
            queue,
            target_format,
            scene,
            geometry_path,
            &mut || {},
        )
    }

    /// The body of [`Self::with_scene_on_path`] and
    /// [`Self::with_scene_serviced`], calling `service` where the latter
    /// documents.
    fn build_on_path(
        device: &dyn Device,
        queue: QueueHandle,
        target_format: Format,
        scene: &SceneDesc<'_>,
        geometry_path: GeometryPath,
        service: &mut dyn FnMut(),
    ) -> Result<Self, HalError> {
        let required = match geometry_path {
            GeometryPath::MeshShader => crcbl_hal::Features::MESH_SHADER,
            GeometryPath::IndirectCount => crcbl_hal::Features::DRAW_INDIRECT_COUNT,
            GeometryPath::IndirectPerBatch => crcbl_hal::Features::empty(),
        };
        let missing = required.difference(device.caps().features);
        if !missing.is_empty() {
            return Err(HalError::UnsupportedFeatures { missing });
        }
        let mut rollback = Rollback::default();
        match Self::build(
            device,
            queue,
            target_format,
            scene,
            geometry_path,
            &mut rollback,
            service,
        ) {
            Ok(renderer) => Ok(renderer),
            Err(error) => {
                rollback.run(device);
                Err(error)
            }
        }
    }

    /// Everything `build` needs to be true of a description, checked **before
    /// the first device object exists**.
    ///
    /// That placement is the whole design of this function. `build` hands the
    /// geometry pool and the material table to the rollback and creates a dozen
    /// objects with `?` between them; a check that ran part way down that list
    /// would be a new early exit on the wrong side of a handover, and a rejected
    /// description would leak two device-local buffers. Run from the top of
    /// `build`, a refusal costs nothing to unwind because nothing was made.
    ///
    /// # Errors
    ///
    /// [`HalError::InvalidDescriptor`] naming the entry that is wrong and what
    /// is wrong with it.
    fn check_scene(scene: &SceneDesc<'_>) -> Result<(), HalError> {
        let refuse = |what: String| Err(HalError::InvalidDescriptor(what));
        // A renderer draws meshes, and every table below is sized from them:
        // with none, the mesh table's sizing has no level to take a maximum
        // of. A scene that draws only the sky is one with meshes and no
        // instances.
        if scene.meshes.is_empty() {
            return refuse(
                "a scene description needs at least one mesh; one with meshes and no \
                 instances draws only the sky"
                    .to_owned(),
            );
        }
        // Every layer's length against its own kind's extent, and layers at no
        // extent at all. Checked by the type that owns the page rather than
        // here, because that is where a page can be built wrong and where the
        // check can be made to fail; see `PageDesc::check`.
        scene.page.check()?;
        // The probe grid's counts against the rows it carries, which is what
        // bounds the shader's fetch. Checked by the type that owns the grid, on
        // `PageDesc::check`'s terms exactly — see `ProbeGrid::check`.
        scene.probes.check()?;
        // A row naming a layer the page does not have is an out-of-range sample,
        // which nothing below the seam reports.
        //
        // **A column carrying `NO_PAGE` is exempt**, and it is the only exempt
        // value: it is a sentinel rather than an index — `0xFFFF`, one past
        // `mesh::MAX_PAGE_LAYER`, so no page can grow to hold it — and the
        // fragment stage never reads a page for it. Exempting it here is what
        // lets a material name no texture without the page having to carry a
        // layer for it to point at — or, since row (d), having to exist at all.
        //
        // **Per kind**, because the kinds are separate images with separate
        // layer lists and separate extents: a row pointed at a base-colour layer
        // number would pass a check that only counted one of them and then
        // sample past the end of the other image.
        for (row, material) in scene.materials.iter().enumerate() {
            for kind in PageKind::ALL {
                let names = match kind {
                    PageKind::BaseColor => material.base_color_texture,
                    PageKind::Normal => material.normal_texture,
                    PageKind::MetallicRoughnessOcclusion => {
                        material.metallic_roughness_occlusion_texture
                    }
                    PageKind::Emissive => material.emissive_texture,
                };
                if names == mesh::GpuMaterial::NO_PAGE {
                    continue;
                }
                let have = scene.page.layers(kind).len();
                if names as usize >= have {
                    return refuse(format!(
                        "material row {row} samples {} page layer {names}, and that page \
                         has {have}",
                        kind.label()
                    ));
                }
            }
        }

        for (index, desc) in scene.meshes.iter().enumerate() {
            let Geometry::Dag { levels, dag, .. } = &desc.geometry else {
                continue;
            };
            // Zipped together at upload and again at
            // `ClusterDag::selection_records`, so a short list would silently
            // leave a level's clusters reading the level below's vertices.
            if levels.len() != dag.levels.len() {
                return refuse(format!(
                    "mesh {index} ({}) carries {} vertex array(s) for a DAG of {} level(s)",
                    desc.label,
                    levels.len(),
                    dag.levels.len()
                ));
            }
            for (depth, (bytes, level)) in levels.iter().zip(&dag.levels).enumerate() {
                let want = level.positions.len() * mesh::VERTEX_STRIDE;
                if bytes.len() != want {
                    return refuse(format!(
                        "mesh {index} ({}) level {depth} carries {} vertex byte(s) for {} \
                         position(s), which is {want}",
                        desc.label,
                        bytes.len(),
                        level.positions.len()
                    ));
                }
            }
        }

        // **Every read the mesh stage makes from a cluster array lands inside
        // it.** Checked by the type that owns the arrays, on `PageDesc::check`'s
        // terms exactly — see `MeshClusters::check`, which is where the reason
        // it cannot be checked below the seam is argued. Both variants carry
        // the same type beside a vertex count, so both are checked the same way.
        for (index, desc) in scene.meshes.iter().enumerate() {
            let levels: Vec<(usize, &MeshClusters)> = match &desc.geometry {
                Geometry::Flat {
                    vertices, clusters, ..
                } => vec![(vertices.len() / mesh::VERTEX_STRIDE, clusters)],
                Geometry::Dag { dag, .. } => dag
                    .levels
                    .iter()
                    .map(|level| (level.positions.len(), &level.clusters))
                    .collect(),
            };
            for (depth, (vertices, clusters)) in levels.into_iter().enumerate() {
                if let Err(fault) = clusters.check(vertices) {
                    return refuse(format!(
                        "mesh {index} ({}) level {depth} {fault}",
                        desc.label
                    ));
                }
            }
        }

        // **Capacity, summed over the whole description**, which is the one
        // refusal no pool can make for itself. `MeshPool` and `MaterialTable`
        // do refuse their own overflow, but they refuse it part way through
        // filling something that already exists, and the pair of numbers
        // [`MeshPoolError::PoolExhausted`](crate::mesh_pool::MeshPoolError::PoolExhausted)
        // carries to tell fragmentation from a full pool says nothing *here*:
        // the pool was created empty a few lines below, nothing has been freed
        // in it, so its free list is one block and the largest block and the
        // total are the same number. At build the answer is always "raise this
        // capacity", so it is said by name and before anything is created.
        let mut vertices: u64 = 0;
        let mut indices: u64 = 0;
        for desc in &scene.meshes {
            match &desc.geometry {
                Geometry::Flat {
                    vertices: bytes,
                    indices: list,
                    ..
                } => {
                    // Bytes that are not a whole number of vertices are the
                    // pool's to refuse, and it refuses before it allocates.
                    vertices += (bytes.len() / mesh::VERTEX_STRIDE) as u64;
                    indices += list.len() as u64;
                }
                Geometry::Dag { levels, dag, .. } => {
                    for bytes in levels {
                        vertices += (bytes.len() / mesh::VERTEX_STRIDE) as u64;
                    }
                    for level in &dag.levels {
                        // The call the upload itself makes, so the two cannot
                        // disagree about what a level costs.
                        indices += level.indices().len() as u64;
                    }
                }
            }
        }
        let entries: u64 = scene
            .meshes
            .iter()
            .map(|desc| desc.geometry.levels() as u64)
            .sum();
        for (pool, needed, capacity) in [
            ("vertex pool", vertices, scene.capacities.vertices),
            ("index pool", indices, scene.capacities.indices),
            ("mesh table", entries, scene.capacities.meshes),
            (
                "material table",
                scene.materials.len() as u64,
                scene.capacities.materials,
            ),
            (
                "probe table",
                scene.probes.probes.len() as u64,
                scene.capacities.probes,
            ),
        ] {
            if needed > u64::from(capacity) {
                return refuse(format!(
                    "the {pool} holds {capacity} and the description needs {needed}"
                ));
            }
        }
        Ok(())
    }

    /// The body of [`ForwardRenderer::with_scene`], recording what it has
    /// created into `rollback` as it goes and calling `service` where
    /// [`ForwardRenderer::with_scene_serviced`] documents.
    fn build(
        device: &dyn Device,
        queue: QueueHandle,
        target_format: Format,
        scene: &SceneDesc<'_>,
        geometry_path: GeometryPath,
        rollback: &mut Rollback,
        service: &mut dyn FnMut(),
    ) -> Result<Self, HalError> {
        // Before anything exists, so a refused description leaks nothing — see
        // `check_scene`, which is where that placement is argued.
        Self::check_scene(scene)?;

        // Resolved before anything is created, because it decides the *shape*
        // of what is created — the bind group layout, which pipeline kind the
        // pass builds, and what a bucket's constant block says. A device on the
        // mesh path never builds the raster pipeline and a device on either
        // indirect tail never builds the mesh one, which is what makes "the
        // frame came out of the mesh stage" a fact about the object graph
        // rather than a claim about a branch.
        let emit = EmitTail::from_path(geometry_path);
        // And whether that tail draws a range of buckets per call, which only
        // changes what the passes record — the constant blocks carry the words
        // both shapes read — so it decides nothing about what is created.
        let range_limit = emit.range_limit(&device.caps());
        // **A second capability, asked separately.** `Features::TASK_SHADER` is
        // not implied by `MESH_SHADER`, so §3.5's per-cluster cull is an
        // amplification stage this renderer builds where the device has one and
        // leaves out where it does not — and a device without it keeps drawing
        // through `mesh_cluster.slang`'s un-amplified `meshMain`, which culls
        // nothing and emits every cluster. Same picture, more work.
        let culls_clusters = emit.is_mesh()
            && device
                .caps()
                .features
                .contains(crcbl_hal::Features::TASK_SHADER);

        let (pool, residents) = Self::build_geometry(device, queue, scene, service)?;
        // What an `InstanceDesc::mesh` index resolves through: one id per
        // description mesh, in description order, and each of them that mesh's
        // **level 0** whatever the path — because it is the entry the cull pass
        // reads a bounding box out of, and a DAG's coarser levels approximate
        // the same surface inside the same box.
        let mesh_ids: Vec<u32> = residents.iter().map(ResidentMesh::id).collect();
        // The scene's own triangles, kept for the probe-visibility capture and
        // for nothing else — and kept at all only when the description reserves
        // a probe, so a scene without one pays no memory for this rung. Taken
        // here because `scene` is the caller's and is read once.
        let probe_occluders = crate::probe_visibility::Occluders::from_scene(scene, &mesh_ids);
        // The same list one level down: what a caller reserving a skinned region
        // names its mesh with. Read here beside the ids rather than from
        // `residents` later, because the descriptions this came from are the
        // caller's and are read once.
        let skinnable_meshes: Vec<Option<MeshHandle>> =
            residents.iter().map(|mesh| mesh.skinnable).collect();
        // The handles are `Copy`, so they can be read out before the pool
        // becomes the rollback's — which it must be before the first `?` below,
        // or a failed pipeline would leak two device-local buffers. The index
        // pool is not named here at all: it is bound at draw time rather than
        // descriptor-written, so only the vertex pool and the mesh table reach a
        // bind group.
        let vertices = pool.vertex_buffer();
        let mesh_table = pool.table_buffer();
        rollback.pool = Some(pool);

        // §3.2's texture side, before the table that indexes it: a material row
        // is written with a layer number, so the layer has to exist to be named.
        //
        // **One loop over [`PageKind::ALL`]**, because the kinds differ only in
        // three answers the kind itself owns — its format, its mip filter and
        // its device label — and everything else about creating a page is the
        // same code. Two hand-written copies were what let the normal page be
        // created through the colour page's filter for as long as nobody
        // compared the two, and rung 3 adds two more kinds to get wrong.
        //
        // **`Rgba8UnormSrgb` on the base-colour page, `Rgba8Unorm` on the
        // normal page, and that is the colour-space decision.** A base-colour
        // description's texels are sRGB-encoded, which is what glTF defines a
        // base-colour texture to be, so the format is what makes the sampler
        // decode them — and `mesh.slang` then multiplies a linear texel by a
        // linear `base_color` and lights in linear, exactly as it did before
        // there was a texture. A normal texel is a *number* and nothing decodes
        // it. See `PageKind::format`, and topic 44's rung 2.
        //
        // Every layer's length against its kind's extent was settled by
        // `check_scene` above, before this device object existed.
        //
        // **Every layer goes up with its mip chain**, built here on the host by
        // [`crate::mip`] — topic 43's filtering rung.
        // The chain is what a trilinear sampler needs to stop shimmering on a
        // minified surface, and it is built at upload rather than by a compute
        // pass because the page's format is what decodes it and a host chain is
        // the same bytes on every backend.
        //
        // **A kind with no layers takes one texel.** `upload_texture_mip_layers`
        // refuses a zero-layer image and every bind group has to fill both page
        // bindings, so a page nothing names is created 1×1 in its own format
        // holding [`PAGE_PLACEHOLDER_TEXEL`] — which the shader never reads,
        // and which is magenta so that a frame says so if it ever does.
        //
        // The upload itself is [`upload_page`], shared with
        // [`ForwardRenderer::replace_page`] so a page reloaded under a running
        // renderer is built exactly as this one was. A layer's chain is host
        // work proportional to its texels, so a page of many large layers is
        // serviced one layer at a time.
        let mut pages: [Option<UploadedTexture>; PageKind::ALL.len()] = [None; PageKind::ALL.len()];
        let mut page_extents = [(1, 1); PageKind::ALL.len()];
        let mut page_layers = [0; PageKind::ALL.len()];
        for kind in PageKind::ALL {
            let layers = scene.page.layers(kind);
            let (page, extent) = upload_page(
                device,
                queue,
                kind,
                scene.page.extent(kind),
                layers,
                service,
            )?;
            rollback.textures.push(page);
            page_extents[kind.index()] = (extent, extent);
            page_layers[kind.index()] = layers.len();
            pages[kind.index()] = Some(page);
            service();
        }
        let [
            Some(base_color_page),
            Some(normal_page),
            Some(mro_page),
            Some(emissive_page),
        ] = pages
        else {
            unreachable!("the loop above fills a slot for every PageKind::ALL entry");
        };

        // The page's sampler at the device's default — see `create_page_sampler`
        // for what it filters, and `set_anisotropy` for how a caller moves it.
        let anisotropy = Self::anisotropy_for(&device.caps());
        let base_color_sampler = Self::create_page_sampler(device, anisotropy)?;
        rollback.samplers.push(base_color_sampler);
        // What every slot's groups are built naming, and what each moves off
        // only at its own frame — see `ForwardRenderer::adopt_pages`.
        let page_bindings = PageBindings {
            sampler: base_color_sampler,
            views: [
                base_color_page.view,
                normal_page.view,
                mro_page.view,
                emissive_page.view,
            ],
        };

        // The material table, before the instances: an instance is written with
        // the material id it carries, so the row has to exist to be named.
        let (materials, material_ids) = Self::build_materials(device, scene)?;
        let material_buffer = materials.buffer();
        rollback.materials = Some(materials);

        // Topic 50's irradiance grid: the table is created here once, and
        // `crate::probe_gather`'s compute pass rewrites its rows every frame —
        // see [`crate::probe`]. **Created even for a description with no probes**, because
        // every group of this layout has to fill [`PROBE_TABLE_BINDING`] and the
        // honest filler for "no probes were authored" is the zeroed row the
        // shader's clamp lands on.
        let probe_table = ProbeTable::new(
            device,
            queue,
            &ProbeTableDesc {
                label: Some("forward"),
                capacity: scene.capacities.probes,
                frames: FRAMES_IN_FLIGHT,
            },
        )?;
        // Into the rollback before it is filled, so a copy that fails releases
        // the buffers rather than leaking them.
        rollback.probes = Some(probe_table);
        let probe_table = rollback.probes.as_ref().expect("just stored");
        probe_table.fill(device, queue, &scene.probes.probes)?;
        // Read out here, like the instance ring's below and for the same
        // reason: the handles are `Copy`, and the loop that builds the bind
        // groups mutates the rollback the table now lives in.
        let probe_buffers: Vec<BufferHandle> = (0..FRAMES_IN_FLIGHT)
            .map(|frame| probe_table.buffer(frame))
            .collect();
        // The irradiance probes' updater, built **only** for a
        // description that asked for it. A volume left at
        // [`ProbeUpdate::Authored`] gets no pipeline, no buffers and no pass, so
        // the default really is the frame every scene drew before this landed.
        let probe_gather = match scene.probes.update {
            ProbeUpdate::Authored => None,
            ProbeUpdate::EveryFrame => Some(ProbeGather::new(
                device,
                &ProbeGatherDesc {
                    label: Some("forward probes"),
                    volume: scene.probes.volume,
                    probes: &probe_buffers,
                },
            )?),
        };
        rollback.probe_gather = probe_gather;
        let probe_gather = rollback.probe_gather.take();
        service();

        // **Empty.** Every object in the scene arrives through
        // [`ForwardRenderer::add_instance`], including the demo scene's cube: a
        // renderer that inserted one of its description's meshes here would put
        // an object in a caller's frame that the caller never asked for.
        let instances = InstancePool::new(
            device,
            &InstancePoolDesc {
                label: Some("forward instances"),
                capacity: scene.capacities.instances,
                frames_in_flight: FRAMES_IN_FLIGHT,
            },
        )?;
        // Same handle-then-hand-over dance as the geometry pool above: the
        // buffers are `Copy` and are read out before the pool becomes the
        // rollback's, which it must be before the first `?` below — after which
        // nothing needs the pool again until `begin_frame`.
        let instance_buffers: Vec<BufferHandle> = instances.buffers().to_vec();
        rollback.instances = Some(instances);

        // The two compute passes, and the buffers the draws come out of. Built
        // here rather than beside the pipelines below because the mesh bind
        // group names one of its buffers, so it has to exist first.
        //
        // The bucket table, and the one place its order is decided.
        //
        // **Built by walking the description**, which is what makes a duplicate
        // structurally impossible rather than refused: every bucket's mesh id is
        // the id of the description mesh it came from, and two description
        // meshes are two uploads with two table entries however alike their
        // geometry is. That matters because `draw_gen.slang`'s scatter takes the
        // *first* bucket whose mesh id matches, so a second bucket naming one
        // mesh would never draw anything at all.
        //
        // One bucket per mesh, except for two things. A DAG is one bucket where
        // an amplification stage picks its cut per cluster and one per level
        // where the cull pass picks a uniform one — see [`buckets_for`]. And the
        // whole run is repeated once per **material mode** the scene holds, so
        // an instance's mode picks a bucket exactly as its mesh does; see
        // [`ForwardRenderer::bucket_modes`].
        //
        // **Mode-major: every mesh's run for one mode, then the next mode's.**
        // A mode picks the pipeline a pass binds, so this makes each pipeline's
        // partition — [`ForwardRenderer::depth_partitions`] and
        // [`ForwardRenderer::sided_partitions`] — one contiguous run of
        // buckets, which a device with a draw index records as one ranged call
        // rather than a call per bucket — and which the mesh tail behind a
        // task stage must have, because it draws each partition as one flat
        // call of its run. `DEPTH_MODES` order makes a sided partition one run
        // too: opaque sits beside masked, and double-sided beside both.
        //
        // **Once per mode the scene holds, not once per mode that exists.** A
        // scene whose materials are all opaque gets exactly the table it always
        // had — same length, same order, same bytes — so the twin costs nothing
        // where nothing is masked, which is every demo and every golden here. A
        // bucket is not free: every pass records one indirect call per bucket
        // per view, and every generator holds its run start.
        let scene_modes: Vec<u32> = {
            let held: Vec<u32> = DEPTH_MODES
                .into_iter()
                .filter(|mode| {
                    scene
                        .materials
                        .iter()
                        .any(|material| material.mode() == *mode)
                })
                .collect();
            // A description with no materials at all still needs a bucket per
            // mesh, or nothing it holds can be drawn.
            if held.is_empty() {
                vec![DEPTH_MODES[0]]
            } else {
                held
            }
        };
        // One mode's run: every description mesh's levels, in description
        // order. `bucket_bases` is where each mesh starts within it, so the
        // tables below can be filled in mesh by mesh rather than by re-deriving
        // the arithmetic; mode slot `s` of the mesh is `s` runs further on.
        let mut mode_run: Vec<u32> = Vec::new();
        let mut bucket_bases: Vec<usize> = Vec::with_capacity(residents.len());
        for resident in &residents {
            bucket_bases.push(mode_run.len());
            mode_run
                .extend_from_slice(&resident.levels[..buckets_for(resident.levels.len(), emit)]);
        }
        let mut bucket_meshes: Vec<u32> = Vec::with_capacity(mode_run.len() * scene_modes.len());
        // The mode each of those buckets draws, in step with it.
        let mut bucket_modes: Vec<u32> = Vec::with_capacity(bucket_meshes.capacity());
        for mode in &scene_modes {
            bucket_meshes.extend_from_slice(&mode_run);
            bucket_modes.extend(std::iter::repeat_n(*mode, mode_run.len()));
        }
        let bucket_count = u32::try_from(bucket_meshes.len())
            .unwrap_or_else(|_| unreachable!("a table of a few buckets"));

        // Topic 25's selection tables, and the one thing that
        // decides whether `draw_gen.slang` takes a uniform cut at all.
        //
        // Every mesh id gets an entry, because the shader indexes this with
        // `GpuInstance::mesh` and an instance can name any of them; the default
        // is `MeshLevels::FLAT` pointing at a level run that is the mesh itself,
        // so a mesh with no hierarchy resolves back to itself with no branch.
        // **A DAG keeps that default on the mesh path**, which is how a device
        // already descending it per cluster avoids a second, coarser cut on top
        // of it — the suppression is data rather than a branch in the shader.
        //
        // **Sized by the mesh table's capacity, not by the meshes resident in
        // it**, because that is the invariant `draw_gen.slang`'s
        // `mesh_levels_of` states and indexes on: "every entry an instance can
        // name is filled". The read is unbounded and an instance's mesh id is a
        // bare table index, so a table sized to the description alone is an
        // out-of-range read of whatever the packer laid down next for any id the
        // description did not fill. What it finds there decides the frame: zeros
        // resolve to mesh 0 and draw another mesh's geometry, and a live
        // `group_count` sends `select_level`'s loop over a count no allocation
        // backs, which on radv is a hard GPU recovery rather than a wrong
        // picture. That is not a hypothetical: it is what a skinned instance
        // naming an alias entry did until 2026-08, before it learned to name its
        // source mesh instead.
        let table_len = usize::try_from(scene.capacities.meshes)
            .unwrap_or(usize::MAX)
            .max(
                usize::try_from(
                    residents
                        .iter()
                        .flat_map(|resident| resident.levels.iter().copied())
                        .max()
                        .unwrap_or_else(|| {
                            unreachable!("check_scene refused an empty description")
                        })
                        + 1,
                )
                .unwrap_or_else(|_| unreachable!("a table of a few meshes")),
            );
        let mut level_meshes: Vec<u32> = (0..table_len)
            .map(|id| u32::try_from(id).unwrap_or_else(|_| unreachable!("bounded by table_len")))
            .collect();
        let mut mesh_levels: Vec<level_select::MeshLevels> = level_meshes
            .iter()
            .map(|&id| level_select::MeshLevels {
                first_level: id,
                ..level_select::MeshLevels::FLAT
            })
            .collect();
        // Every DAG's groups end to end, in description order, and where each
        // one's run starts. `ClusterSelect` records name a group by its index in
        // *this* array — see `ClusterDag::selection_records`' `first_group` — so
        // several DAGs concatenate without `crcbl-shaders` knowing they did.
        let mut level_groups: Vec<level_select::LevelGroup> = Vec::new();
        let mut first_groups: Vec<u32> = Vec::with_capacity(residents.len());
        for (index, desc) in scene.meshes.iter().enumerate() {
            first_groups.push(
                u32::try_from(level_groups.len())
                    .unwrap_or_else(|_| unreachable!("a few dozen groups per DAG")),
            );
            let Geometry::Dag { dag, .. } = &desc.geometry else {
                continue;
            };
            let groups = dag.level_groups();
            let id = residents[index].id();
            mesh_levels[id as usize] = level_select::MeshLevels {
                first_group: first_groups[index],
                group_count: u32::try_from(groups.len())
                    .unwrap_or_else(|_| unreachable!("a DAG of a few dozen groups")),
                // **The mesh path suppresses the uniform cut with a top level of
                // zero, not with a group count of zero**, and the difference is
                // the hysteresis state: `draw_gen.slang` judges every group it is
                // given whatever level it answers, and the amplification stage
                // reads those answers. A record naming no groups would leave the
                // state untouched and every cluster of the patch collapsed. A
                // top level of zero makes the level loop's minimum unreachable,
                // so the instance routes to the mesh it already names — which is
                // level 0.
                first_level: if emit.is_mesh() {
                    id
                } else {
                    u32::try_from(level_meshes.len())
                        .unwrap_or_else(|_| unreachable!("a table of a few meshes"))
                },
                top_level: if emit.is_mesh() {
                    0
                } else {
                    u32::try_from(residents[index].levels.len() - 1)
                        .unwrap_or_else(|_| unreachable!("a DAG of a few levels"))
                },
            };
            level_groups.extend(groups);
            if !emit.is_mesh() {
                level_meshes.extend_from_slice(&residents[index].levels);
            }
        }

        // §3.5's clusters, on the path that reads them and on no other. The
        // records are `crcbl-shaders`' — cooked, because the builder is
        // `crcbl-scene`'s and the renderer must not depend on that crate — and
        // they arrive in bucket-mesh order so a bucket's range is its own
        // index. See `crate::cluster_pool`.
        //
        // Before the draw generation below rather than after it, because the
        // per-bucket cluster counts are the x extent of each bucket's mesh
        // dispatch and that pass writes the argument structure carrying them.
        let mut bucket_clusters = vec![0u32; bucket_meshes.len()];
        let mut bucket_cluster_bases = vec![0u32; bucket_meshes.len()];
        let mut mesh_clusters: Vec<ClusterRange> = Vec::new();
        if emit.is_mesh() {
            // A flat mesh is one pool entry and its clusters carry
            // `ClusterSelect::ALWAYS`, so the descent draws them from every
            // camera; a DAG is **one entry per level**, laid end to end.
            let mut cooked: Vec<PooledMesh> = Vec::with_capacity(residents.len());
            // Where each description mesh's entries start, on `bucket_bases`'
            // terms — the two differ exactly where a DAG's levels are one bucket
            // and several entries.
            let mut entry_bases: Vec<usize> = Vec::with_capacity(residents.len());
            for (index, desc) in scene.meshes.iter().enumerate() {
                entry_bases.push(cooked.len());
                match &desc.geometry {
                    Geometry::Flat { clusters, .. } => {
                        cooked.push(PooledMesh::without_lod(clusters.clone()));
                    }
                    Geometry::Dag { dag, .. } => {
                        let selection = dag
                            .selection_records(&residents[index].vertex_bases, first_groups[index]);
                        for (level, records) in dag.levels.iter().zip(selection) {
                            cooked.push(PooledMesh {
                                clusters: level.clusters.clone(),
                                selection: records,
                            });
                        }
                    }
                }
            }

            let clusters = ClusterPool::new(device, "forward", &cooked)?;
            let range = |entry: usize| {
                clusters
                    .range(entry)
                    .unwrap_or_else(|| unreachable!("one range per entry, in order"))
            };
            // **A DAG's levels are one run, not one per bucket.** `concatenate`
            // lays the entries down in the order it was given them, so the
            // levels are contiguous: the bucket starts where level 0 does and
            // reaches to the end of the last level. That is what lets one
            // dispatch cover a cut spanning several of them — and it is why a
            // flat mesh, whose one entry is the whole sum, needs no second case.
            mesh_clusters.reserve(residents.len());
            for (index, resident) in residents.iter().enumerate() {
                let entry = entry_bases[index];
                let base = range(entry).base;
                let count: u32 = (entry..entry + resident.levels.len())
                    .map(|entry| range(entry).count)
                    .sum();
                // **Every one of this mesh's buckets, not only the first.** A
                // mode twin draws the same geometry, so it dispatches over the
                // same clusters; a twin left at zero launches no workgroup and
                // its instances vanish from the frame. One bucket per mode here,
                // because the mesh path takes `buckets_for` of one, each a whole
                // mode's run past the one before.
                for slot in 0..scene_modes.len() {
                    let bucket = slot * mode_run.len() + bucket_bases[index];
                    bucket_cluster_bases[bucket] = base;
                    bucket_clusters[bucket] = count;
                }
                mesh_clusters.push(ClusterRange { base, count });
            }

            rollback.clusters = Some(clusters);
            service();
        }

        // One ring per shadow view, indexed `[view][frame]`: topic 25's
        // observable, one word per resident cluster holding the cut the descent
        // chose — see `ForwardRenderer::shadow_selection` for why a view cannot
        // share the camera's, which [`View::build`] allocates beside its cull.
        //
        // Allocated on the whole mesh path rather than only where there is an
        // amplification stage to write them, because the layout declares
        // CLUSTER_SELECTION_BINDING there — see the layout, which is where that is argued.
        let mut tile_selection: Vec<Vec<BufferHandle>> = Vec::new();
        if emit.is_mesh() {
            let count = rollback
                .clusters
                .as_ref()
                .unwrap_or_else(|| unreachable!("the mesh path implies a cluster pool"))
                .count();
            let mut ring = |label: &str| -> Result<Vec<BufferHandle>, HalError> {
                let mut buffers = Vec::with_capacity(instance_buffers.len());
                for frame in 0..instance_buffers.len() {
                    let buffer = device.create_buffer(&BufferDesc {
                        label: Some(&format!("{label} {frame}")),
                        size: u64::from(count) * 4,
                        usage: BufferUsage::STORAGE.union(BufferUsage::TRANSFER_SRC),
                        memory: MemoryLocation::DeviceLocal,
                    })?;
                    rollback.buffers.push(buffer);
                    buffers.push(buffer);
                }
                Ok(buffers)
            };
            for view in 0..SHADOW_VIEWS {
                tile_selection.push(ring(&format!("shadow selection {view}"))?);
            }
        }

        // --- the mesh pass ---
        //
        // No `BindingFlags` anywhere: this layout is legal on **both** tiers,
        // because a lit mesh is not a Tier A feature. The bindless shape — a
        // trailing `VARIABLE_COUNT | PARTIALLY_BOUND | UPDATE_AFTER_BIND`
        // texture array — is topic 03's, at P3.
        // **Which stage pulls the geometry**, and the only thing the two shapes
        // of this layout disagree about for bindings 0 to 8. `ShaderStages::MESH`
        // is outside `GRAPHICS` and `ALL`, so it is named rather than implied,
        // and every backend refuses a layout carrying it on a device without
        // `Features::MESH_SHADER` — which is exactly the device that never
        // reaches this arm.
        //
        // **`TASK` joins it when there is an amplification stage**, and the
        // union is deliberately over every binding rather than the eight
        // `taskMain` actually reads. Slang's Metal backend materialises every
        // global in every entry point of a module — the argument bindings 6 to
        // 8 already carry — so a layout that named only the task stage's own
        // reads would be a layout `msl/mesh_cluster.metal` disagrees with, on a
        // runner this team cannot debug on.
        let geometry = match (emit.is_mesh(), culls_clusters) {
            (true, true) => ShaderStages::MESH.union(ShaderStages::TASK),
            (true, false) => ShaderStages::MESH,
            (false, _) => ShaderStages::VERTEX,
        };
        let mut mesh_entries = vec![
            BindGroupLayoutEntry {
                binding: 0,
                visibility: geometry.union(ShaderStages::FRAGMENT),
                kind: BindingKind::UniformBuffer { dynamic: false },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 1,
                // **Both stages, and here it is the FRAGMENT half that needs
                // saying** — binding 6 and 7 are the mirror image, where the
                // fragment stage plainly reads the row and the vertex half is
                // the one Slang forces. Slang's Metal backend materialises
                // every module global into every entry point, so
                // `msl/mesh.metal`'s `fragmentMain` takes this buffer whether
                // its body dereferences it or not — and Metal's debug layer
                // answers a declared-but-unbound fragment argument with
                // `missing Buffer binding at index N`, once per draw. Vulkan,
                // D3D12 and WebGPU all accept a visibility wider than the
                // shader's reads, so naming FRAGMENT costs them nothing but the
                // entry itself.
                //
                // **It does not cost a redundant bind on Metal either**, and
                // that is what makes it safe rather than a trade: `crcbl-mtl`
                // consults `MTLPipelineOption::BindingInfo` reflection and
                // issues the fragment-stage bind only where `MTLBinding::isUsed`
                // says the compiled function kept the argument. This entry is
                // the permission; the reflection is the decision.
                visibility: geometry.union(ShaderStages::FRAGMENT),
                kind: BindingKind::StorageBuffer {
                    // The shader says `StructuredBuffer`, not
                    // `RWStructuredBuffer`, so this is the truth rather than a
                    // hint — and it is what lets the graph merge read-after-read.
                    read_only: true,
                    dynamic: false,
                    stride: size_of::<u32>() as u32,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 2,
                // Both stages, for binding 1's reason exactly.
                visibility: geometry.union(ShaderStages::FRAGMENT),
                kind: BindingKind::StorageBuffer {
                    // `StructuredBuffer` again: the vertex stage reads its
                    // instance and writes nothing. The *host* writes this one
                    // every frame, which is a mapped write rather than a shader
                    // one and does not make it read-write here.
                    read_only: true,
                    dynamic: false,
                    stride: crcbl_shaders::mesh::INSTANCE_STRIDE as u32,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 3,
                // Both stages, for binding 1's reason exactly.
                visibility: geometry.union(ShaderStages::FRAGMENT),
                // `dynamic: true`, and it is the whole mechanism: it is what
                // lets a draw say where its run of instances starts without
                // `draw_indexed`'s own base instance, which the module docs and
                // `mesh.slang`'s header explain the targets disagree about.
                // Same shape, for the same reason, as `crate::sprite_pass`'s.
                kind: BindingKind::UniformBuffer { dynamic: true },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 4,
                // Both stages, for binding 1's reason exactly.
                visibility: geometry.union(ShaderStages::FRAGMENT),
                kind: BindingKind::StorageBuffer {
                    // The mesh table. `StructuredBuffer` again — the vertex
                    // stage looks its mesh up and writes nothing — and one
                    // buffer shared by every frame's group, because unlike the
                    // instance array nothing rewrites it between frames.
                    read_only: true,
                    dynamic: false,
                    stride: crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u32,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 5,
                // Both stages, for binding 1's reason exactly.
                visibility: geometry.union(ShaderStages::FRAGMENT),
                kind: BindingKind::StorageBuffer {
                    // The per-bucket runs of surviving instances. Read-only
                    // here and written by the draw-argument pass, which is a
                    // different bind group and a different pass — the graph is
                    // what orders the two.
                    read_only: true,
                    dynamic: false,
                    stride: size_of::<u32>() as u32,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 6,
                // **Both stages, and the union is not belt-and-braces.** The
                // fragment stage is where `mesh.slang` now reads the table, so
                // it plainly needs it — a pipeline layout that leaves it out is
                // refused outright by wgpu and reported as
                // `VUID-VkGraphicsPipelineCreateInfo-layout-07988` by Vulkan.
                // The vertex half has to stay because Slang's Metal backend
                // materialises every global in every entry point: `vertexMain`
                // in `msl/mesh.metal` still takes `materials [[buffer(6)]]`
                // whether it reads it or not, so dropping VERTEX would break
                // Metal alone, on a runner this team cannot debug on.
                visibility: geometry.union(ShaderStages::FRAGMENT),
                kind: BindingKind::StorageBuffer {
                    // The material table. One buffer in every frame's group,
                    // like the mesh table above and unlike the instance ring:
                    // a material is written when it is created, not per frame.
                    read_only: true,
                    dynamic: false,
                    stride: crcbl_shaders::mesh::MATERIAL_STRIDE as u32,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: BASE_COLOR_PAGE_BINDING,
                // Both stages, for binding 6's reason exactly: the fragment
                // stage samples it, and Slang's Metal backend materialises
                // every global in every entry point — `vertexMain` in
                // `msl/mesh.metal` takes the texture whether it reads it or
                // not, so a layout without VERTEX would break Metal alone.
                visibility: geometry.union(ShaderStages::FRAGMENT),
                // **`D2Array`, and the layout is where wgpu wants to hear it.**
                // The other three backends read the dimension off the bound
                // view and never consult this; WebGPU compares the two at
                // pipeline creation and refuses the pair, which is what a
                // layout claiming `D2` over an array view got — "expects
                // dimension = D2, but given a view with dimension = D2Array".
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2Array,
                    sample_type: SampleType::Float,
                },
                // **`count: 1`, and this is the binding-model decision.** One
                // `D2Array` image whose *layers* the material rows index is
                // `BindingModel::ArrayPages`; an array of `count` descriptors
                // indexed per fragment would be `Bindless` and would need
                // `Features::DESCRIPTOR_INDEXING`, which `crcbl-mtl` withdraws.
                // So this layout is legal on every device, exactly as the six
                // buffers above are, and no `BindingFlags` appear anywhere in
                // this file yet.
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: PAGE_SAMPLER_BINDING,
                visibility: geometry.union(ShaderStages::FRAGMENT),
                kind: BindingKind::Sampler { comparison: false },
                count: 1,
                flags: BindingFlags::empty(),
            },
        ];
        if emit.is_mesh() {
            // §3.5's four extra reads, and only on the path that has them.
            // Adding them unconditionally would make every device declare four
            // buffers `mesh.slang` does not name — and WebGPU, which checks a
            // bind group against its layout entry for entry, would then need
            // four buffers created for a path that never reads them.
            //
            // `read_only: true` on all four, which is the truth rather than a
            // hint: the mesh stage indexes them and writes nothing, and it is
            // what lets the graph merge read-after-read.
            //
            // Four different element types, so four strides, in binding order:
            // the clusters (`Meshlet`), the cluster vertex and corner pools
            // (`uint` each), and the per-cluster draw arguments
            // (`DrawIndexedArgs`, the indirect layout every API agrees on).
            let cluster_strides = [
                crcbl_shaders::meshlet::MESHLET_STRIDE as u32,
                size_of::<u32>() as u32,
                size_of::<u32>() as u32,
                crcbl_hal::indirect::DRAW_INDEXED_ARGS_BYTES as u32,
            ];
            mesh_entries.extend(
                (CLUSTERS_BINDING..=CLUSTER_DRAW_ARGS_BINDING)
                    .zip(cluster_strides)
                    .map(|(binding, stride)| {
                        BindGroupLayoutEntry {
                            binding,
                            // **Not the fragment stage.** These four are the geometry
                            // stage's alone, and `mesh_cluster.slang` has no fragment entry
                            // point of its own to materialise them into — its fragment
                            // stage is `mesh.slang`'s, which does not declare mesh-only
                            // buffers.
                            visibility: geometry,
                            kind: BindingKind::StorageBuffer {
                                read_only: true,
                                dynamic: false,
                                stride,
                            },
                            count: 1,
                            flags: BindingFlags::empty(),
                        }
                    }),
            );
        }
        // Both mesh entry points retain these declarations. Omitting unused
        // task buffers would shift later native buffer indices on the plain
        // mesh path, so the layout includes them on both paths.
        if emit.is_mesh() {
            mesh_entries.push(BindGroupLayoutEntry {
                binding: CLUSTER_CULL_BINDING,
                visibility: geometry,
                // **The same block the instance cull reads**, not a copy: one
                // camera, one frustum, and no way for the two rejections to
                // disagree about which. `dynamic: false` because there is one
                // block per frame rather than one per bucket.
                kind: BindingKind::UniformBuffer { dynamic: false },
                count: 1,
                flags: BindingFlags::empty(),
            });
            mesh_entries.push(BindGroupLayoutEntry {
                binding: CLUSTER_CULL_STATS_BINDING,
                visibility: geometry,
                kind: BindingKind::StorageBuffer {
                    // **The one writable binding this pass has.** The stage adds
                    // to a counter, so `read_only: false` is the truth rather
                    // than a hint, and it is what makes the graph order this
                    // write after the draw-argument pass's read of the same
                    // buffer.
                    read_only: false,
                    dynamic: false,
                    stride: size_of::<u32>() as u32,
                },
                count: 1,
                flags: BindingFlags::empty(),
            });
        }
        // Topic 18's cascades, read by the fragment stage and declared last —
        // above `mesh_cluster.slang`'s range rather than inside it, for the
        // reason `SHADOW_ATLAS_BINDING` gives.
        //
        // Both carry `geometry` in their visibility beside `FRAGMENT`, for
        // binding 7's reason exactly: Slang's Metal backend materialises every
        // global into every entry point, and `msl/mesh.metal`'s `vertexMain`
        // takes `shadow_atlas [[texture(1)]]` and `shadow_sampler
        // [[sampler(1)]]` whether it reads them or not.
        mesh_entries.push(BindGroupLayoutEntry {
            binding: SHADOW_ATLAS_BINDING,
            visibility: geometry.union(ShaderStages::FRAGMENT),
            kind: BindingKind::SampledImage {
                view_type: ImageViewType::D2,
                // **`Depth`, and this is the field the seam grew for this
                // pass.** WebGPU will only bind a `D32Float` view through a
                // depth sample type, and its shader side agrees — the WGSL
                // artifact declares `texture_depth_2d`. The other three
                // backends take the interpretation off the view's format and
                // never read this.
                sample_type: SampleType::Depth,
            },
            count: 1,
            flags: BindingFlags::empty(),
        });
        mesh_entries.push(BindGroupLayoutEntry {
            binding: SHADOW_SAMPLER_BINDING,
            visibility: geometry.union(ShaderStages::FRAGMENT),
            // The sampler-side twin of the line above: `sampler_comparison` in
            // the WGSL, `SamplerComparisonState` in the HLSL, and a
            // `compareEnable` on the Vulkan sampler object. The layout has to
            // say so on WebGPU and cannot on the other three.
            kind: BindingKind::Sampler { comparison: true },
            count: 1,
            flags: BindingFlags::empty(),
        });
        // DAG geometry and selection state, in the mesh-only binding range.
        if emit.is_mesh() {
            mesh_entries.push(BindGroupLayoutEntry {
                binding: CLUSTER_SELECT_BINDING,
                visibility: geometry,
                // Read-only and read by **both** mesh entry points, unlike the
                // pair below: a cluster's `vertex_base` is which level of a DAG
                // its geometry lives in, which an un-amplified stage needs just
                // as much as an amplified one.
                kind: BindingKind::StorageBuffer {
                    read_only: true,
                    dynamic: false,
                    stride: crcbl_shaders::cluster_select::CLUSTER_SELECT_STRIDE as u32,
                },
                count: 1,
                flags: BindingFlags::empty(),
            });
        }
        // Both on the whole mesh path, for the two above's reason exactly: the
        // amplification stage is the only writer and the only reader, and the
        // Metal argument table counts entries rather than reading binding
        // numbers.
        if emit.is_mesh() {
            mesh_entries.push(BindGroupLayoutEntry {
                binding: CLUSTER_SELECTION_BINDING,
                visibility: geometry,
                kind: BindingKind::StorageBuffer {
                    // The second writable binding: the amplification stage
                    // records the cut it chose, one word per resident cluster.
                    read_only: false,
                    dynamic: false,
                    stride: size_of::<u32>() as u32,
                },
                count: 1,
                flags: BindingFlags::empty(),
            });
            mesh_entries.push(BindGroupLayoutEntry {
                binding: CLUSTER_GROUP_STATE_BINDING,
                visibility: geometry,
                kind: BindingKind::StorageBuffer {
                    // Topic 25's hysteresis state, and read-only
                    // here: the draw-argument pass is its only writer, which is
                    // what lets a stage with one workgroup per cluster use a
                    // decision that has to survive a frame.
                    read_only: true,
                    dynamic: false,
                    stride: size_of::<u32>() as u32,
                },
                count: 1,
                flags: BindingFlags::empty(),
            });
        }

        // The shared fragment light list and froxel grid are bound on every
        // path and in every group, unlike the four
        // conditional ranges above: `mesh.slang`'s fragment stage reads them
        // whatever geometry produced the primitive, so there is no configuration
        // in which the layout can omit them.
        //
        // `geometry` joins `FRAGMENT` in the visibility for binding 7's reason
        // exactly: Slang's Metal backend materialises every global into every
        // entry point, so the vertex and mesh stages take these buffers whether
        // they read them or not.
        mesh_entries.push(BindGroupLayoutEntry {
            binding: LIGHT_LIST_BINDING,
            visibility: geometry.union(ShaderStages::FRAGMENT),
            kind: BindingKind::StorageBuffer {
                read_only: true,
                dynamic: false,
                stride: crcbl_shaders::light::LIGHT_STRIDE as u32,
            },
            count: 1,
            flags: BindingFlags::empty(),
        });
        mesh_entries.push(BindGroupLayoutEntry {
            binding: LIGHT_GRID_BINDING,
            visibility: geometry.union(ShaderStages::FRAGMENT),
            kind: BindingKind::StorageBuffer {
                // **Read-only here**, and written by the clustering pass through
                // a layout of its own. The graph is what orders the two.
                read_only: true,
                dynamic: false,
                stride: size_of::<u32>() as u32,
            },
            count: 1,
            flags: BindingFlags::empty(),
        });
        // Topic 46's occlusion channel, last of the set
        // — see [`AMBIENT_OCCLUSION_BINDING`] on why last is structural rather
        // than tidy.
        //
        // `geometry` beside `FRAGMENT` for binding 7's reason exactly, and
        // `msl/mesh.metal` is the proof rather than the theory: its `vertexMain`
        // takes `ambient_occlusion [[texture(2)]]` whether it reads it or not.
        mesh_entries.push(BindGroupLayoutEntry {
            binding: AMBIENT_OCCLUSION_BINDING,
            visibility: geometry.union(ShaderStages::FRAGMENT),
            kind: BindingKind::SampledImage {
                view_type: ImageViewType::D2,
                // **`Float`, unlike the shadow atlas above.** This one is an
                // ordinary `R8Unorm` colour image and the WGSL artifact declares
                // `texture_2d<f32>` for it; `Depth` here would be a layout
                // claiming a depth format the view does not have.
                sample_type: SampleType::Float,
            },
            count: 1,
            flags: BindingFlags::empty(),
        });
        // The irradiance grid, past the occlusion channel — see
        // [`PROBE_TABLE_BINDING`] on why the list only ever grows at its top.
        //
        // `geometry` beside `FRAGMENT` for binding 7's reason exactly, and
        // `msl/mesh.metal` is again the proof rather than the theory: its
        // `vertexMain` takes `probes [[buffer(9)]]` whether it reads it or not.
        mesh_entries.push(BindGroupLayoutEntry {
            binding: PROBE_TABLE_BINDING,
            visibility: geometry.union(ShaderStages::FRAGMENT),
            kind: BindingKind::StorageBuffer {
                // **Read-only, and it stays read-only when the updater lands.**
                // The rows are device-local now — see [`crate::probe`], which is
                // where that is argued — so the seam no longer forces this;
                // what forces it is that the shading path does not write a
                // probe and this layout has no headroom to pretend otherwise.
                // The raster path is at the WebGPU per-stage storage-buffer
                // ceiling already, which the check at the end of the layout
                // holds it to, so `read_only: false` here would buy a write
                // nothing performs at the price of a binding budget there is
                // none of. The irradiance probes' gather is a
                // compute pass with a layout of its own, and that is where the
                // writable binding of these rows belongs.
                read_only: true,
                dynamic: false,
                stride: crcbl_shaders::probe::PROBE_STRIDE as u32,
            },
            count: 1,
            flags: BindingFlags::empty(),
        });
        if emit.is_mesh() {
            // DAG group records follow the common buffer prefix; the
            // remaining mesh-only buffers are sorted after them below.
            //
            // **Conditional like the mesh-only bindings**, and not for tidiness:
            // the raster path's layout is at the WebGPU storage-buffer ceiling
            // already, so a row bound unconditionally would be a renderer that
            // cannot be built in a browser. The mesh path's own reads sit outside
            // that count because `ShaderStages::MESH` is not one of the three
            // stages it sums.
            mesh_entries.push(BindGroupLayoutEntry {
                binding: LEVEL_GROUP_TABLE_BINDING,
                // Only the geometry stage reads this table: the
                // heatmap's colour is chosen where the cluster is known, and
                // `mesh.slang`'s fragment stage — which is this pipeline's —
                // does not declare this buffer.
                visibility: geometry,
                kind: BindingKind::StorageBuffer {
                    // Read-only and read by **both** mesh entry points, like
                    // CLUSTER_SELECT_BINDING: an un-amplified stage draws through the same
                    // `emit_cluster`, so a row present for one and absent for the
                    // other is a descriptor read out of an empty slot.
                    read_only: true,
                    dynamic: false,
                    stride: size_of::<u32>() as u32,
                },
                count: 1,
                flags: BindingFlags::empty(),
            });
        }

        // The `DFG` table, above everything — see [`SPECULAR_DFG_BINDING`].
        //
        // `geometry` beside `FRAGMENT` for binding 7's reason exactly: Slang's
        // Metal backend materialises every global into every entry point, so
        // `msl/mesh.metal`'s `vertexMain` takes `specular_dfg [[texture(3)]]`
        // whether it reads it or not.
        mesh_entries.push(BindGroupLayoutEntry {
            binding: SPECULAR_DFG_BINDING,
            visibility: geometry.union(ShaderStages::FRAGMENT),
            kind: BindingKind::SampledImage {
                view_type: ImageViewType::D2,
                // `Float`, as the occlusion channel above: an `Rgba8Unorm`
                // colour image, declared `texture_2d<f32>` by the WGSL artifact.
                sample_type: SampleType::Float,
            },
            count: 1,
            flags: BindingFlags::empty(),
        });

        // §2's normal page, above everything — see [`NORMAL_PAGE_BINDING`].
        //
        // `geometry` beside `FRAGMENT` for binding 7's reason exactly: Slang's
        // Metal backend materialises every global into every entry point, so
        // `msl/mesh.metal`'s `vertexMain` takes the page whether it samples it
        // or not. **A sampled image and not a storage buffer**, which costs this
        // layout nothing at the WebGPU ceiling checked below — that limit counts
        // storage buffers, and this row is a texture.
        mesh_entries.push(BindGroupLayoutEntry {
            binding: NORMAL_PAGE_BINDING,
            visibility: geometry.union(ShaderStages::FRAGMENT),
            kind: BindingKind::SampledImage {
                view_type: ImageViewType::D2Array,
                // `Float`: an `Rgba8Unorm` image, declared
                // `texture_2d_array<f32>` by the WGSL artifact — the same
                // sample type the sRGB base-colour page reports, since both
                // decode to floats.
                sample_type: SampleType::Float,
            },
            count: 1,
            flags: BindingFlags::empty(),
        });
        // The area lights' table, above the page — see [`LTC_TABLE_BINDING`].
        //
        // `geometry` beside `FRAGMENT` for the two rows above it's reason.
        // `Float` because `Rgba16Float` is a filterable sampled format on every
        // target this engine opens, and the WGSL artifact declares it
        // `texture_2d<f32>` — the shader only ever `Load`s it, but the layout
        // has to say what the module declared.
        mesh_entries.push(BindGroupLayoutEntry {
            binding: LTC_TABLE_BINDING,
            visibility: geometry.union(ShaderStages::FRAGMENT),
            kind: BindingKind::SampledImage {
                view_type: ImageViewType::D2,
                sample_type: SampleType::Float,
            },
            count: 1,
            flags: BindingFlags::empty(),
        });
        // Topic 45's contact-shadow channel, last of the set —
        // see [`CONTACT_SHADOW_BINDING`] on why last is structural rather than
        // tidy.
        //
        // `geometry` beside `FRAGMENT` and `Float` for the occlusion channel's
        // reasons exactly: it is the same `R8Unorm` shape, and Slang's Metal
        // backend materialises every global into every entry point whether that
        // stage reads it or not.
        mesh_entries.push(BindGroupLayoutEntry {
            binding: CONTACT_SHADOW_BINDING,
            visibility: geometry.union(ShaderStages::FRAGMENT),
            kind: BindingKind::SampledImage {
                view_type: ImageViewType::D2,
                sample_type: SampleType::Float,
            },
            count: 1,
            flags: BindingFlags::empty(),
        });
        // The irradiance probes' per-probe visibility maps, last
        // of the set — see [`PROBE_VISIBILITY_BINDING`] on why last is
        // structural.
        //
        // `D2Array` has to be *declared*, not merely bound: WebGPU compares the
        // dimension a layout entry claims against the view handed to it at
        // pipeline creation, which is the normal page's own note.
        // `UnfilterableFloat` for the same reason and measured the same way: the
        // image is `Rg32Float`, which is unfilterable without WebGPU's
        // `float32-filterable`, and this slot declared `Float` made Chromium
        // refuse the whole mesh bind group — "None of the supported sample types
        // (UnfilterableFloat) ... match the expected sample types (Float)" —
        // which took every 3D demo's frame to black. Reading it only with `Load`
        // does not lift that: the check is on the layout against the view's
        // format, not on how the shader gets at it.
        mesh_entries.push(BindGroupLayoutEntry {
            binding: PROBE_VISIBILITY_BINDING,
            visibility: geometry.union(ShaderStages::FRAGMENT),
            kind: BindingKind::SampledImage {
                view_type: ImageViewType::D2Array,
                sample_type: SampleType::UnfilterableFloat,
            },
            count: 1,
            flags: BindingFlags::empty(),
        });
        // §2's other two pages, last of the set — see [`MRO_PAGE_BINDING`] and
        // [`EMISSIVE_PAGE_BINDING`] on why last is structural rather than tidy.
        //
        // `geometry` beside `FRAGMENT`, `D2Array` and `Float` are the normal
        // page's three answers exactly, and for its reasons: Slang's Metal
        // backend materialises every global into every entry point, WebGPU
        // compares the declared dimension against the bound view, and both
        // images are `Rgba8Unorm`-family formats that decode to filterable
        // floats.
        for binding in [MRO_PAGE_BINDING, EMISSIVE_PAGE_BINDING] {
            mesh_entries.push(BindGroupLayoutEntry {
                binding,
                visibility: geometry.union(ShaderStages::FRAGMENT),
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2Array,
                    sample_type: SampleType::Float,
                },
                count: 1,
                flags: BindingFlags::empty(),
            });
        }
        mesh_entries.sort_by_key(|entry| entry.binding);
        let mesh_desc = BindGroupLayoutDesc {
            label: Some(MESH_LAYOUT_LABEL),
            entries: &mesh_entries,
        };
        // **This layout is at the guaranteed limit with no headroom on the
        // raster path, in both raster stages**: the vertex stage takes every
        // storage buffer a WebGPU device promises, and since bindings 1 to 5
        // gained FRAGMENT visibility for Metal's debug layer the fragment stage
        // takes the same number. A ninth in either is a renderer that cannot be
        // built in a browser or on SwiftShader, so it fails here rather than at
        // somebody else's `createPipelineLayout` — see
        // [`crcbl_hal::check_portable_storage_buffers`], which also says why the
        // mesh path's extra reads are outside the count.
        // `Some("mesh")`, which is the *pipeline* layout's label, not
        // `mesh_desc.label` — the error text reads "pipeline layout {label}
        // binds …", so naming the bind group layout there sends the reader to
        // the wrong object.
        check_portable_storage_buffers(Some("mesh"), &[&mesh_desc])?;
        let mesh_layout = device.create_bind_group_layout(&mesh_desc)?;
        rollback.bind_group_layouts.push(mesh_layout);

        // A dynamic offset must be a multiple of the device's alignment, and one
        // block has to fit inside one stride. Read from the device rather than
        // assumed, exactly as `crate::sprite_pass` does: 256 on WebGPU, 64 on a
        // typical desktop Vulkan driver.
        //
        // One stride for both blocks, sized for the larger — see
        // [`DRAW_CONSTANTS_BLOCK`]. Which of the two a bucket's block holds is
        // decided below.
        let alignment = device.caps().limits.min_uniform_buffer_offset_alignment;
        let draw_stride =
            u32::try_from(DRAW_CONSTANTS_BLOCK.next_multiple_of(alignment)).map_err(|_| {
                HalError::InvalidDescriptor(format!(
                    "min_uniform_buffer_offset_alignment is {alignment}, which no dynamic \
                         offset can express"
                ))
            })?;
        let draw_constants = device.create_buffer(&BufferDesc {
            label: Some("mesh draw constants"),
            // A block per bucket per draw region: a region's draws name their
            // own run starts, and the mesh path's block names the region's
            // argument structure. See `crcbl_shaders::draw_gen::DRAW_REGIONS`.
            size: u64::from(draw_stride)
                * u64::from(bucket_count)
                * u64::from(crcbl_shaders::draw_gen::DRAW_REGIONS),
            usage: BufferUsage::UNIFORM,
            memory: MemoryLocation::HostUpload,
        })?;
        rollback.buffers.push(draw_constants);
        // --- the shadow map's own resources ---
        //
        // Before the bind groups, because every one of them names the atlas or
        // the placeholder standing in for it.
        let (atlas_width, atlas_height) = shadow::atlas_extent();
        let shadow_atlas = device.create_image(&ImageDesc {
            label: Some("shadow atlas"),
            image_type: ImageType::D2,
            format: Format::D32Float,
            extent: crcbl_hal::Extent3d::d2(atlas_width, atlas_height),
            mip_levels: 1,
            samples: 1,
            // `TRANSFER_SRC` so a test can copy the cascades back and check
            // that something was written into them. A shadow map that stayed at
            // its clear value produces a frame that looks entirely plausible —
            // everything is lit — so the readback is the only thing that can
            // tell a working pass from one that drew nothing.
            usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT
                .union(ImageUsage::SAMPLED)
                .union(ImageUsage::TRANSFER_SRC),
        })?;
        rollback.images.push(shadow_atlas);
        let shadow_atlas_view = device.create_image_view(&ImageViewDesc {
            label: Some("shadow atlas"),
            image: shadow_atlas,
            view_type: ImageViewType::D2,
            format: Format::D32Float,
            range: ImageSubresourceRange::all(Format::D32Float),
        })?;
        rollback.image_views.push(shadow_atlas_view);

        let shadow_placeholder = device.create_image(&ImageDesc {
            label: Some("shadow placeholder"),
            image_type: ImageType::D2,
            format: Format::D32Float,
            extent: crcbl_hal::Extent3d::d2(1, 1),
            mip_levels: 1,
            samples: 1,
            usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT.union(ImageUsage::SAMPLED),
        })?;
        rollback.images.push(shadow_placeholder);
        let shadow_placeholder_view = device.create_image_view(&ImageViewDesc {
            label: Some("shadow placeholder"),
            image: shadow_placeholder,
            view_type: ImageViewType::D2,
            format: Format::D32Float,
            range: ImageSubresourceRange::all(Format::D32Float),
        })?;
        rollback.image_views.push(shadow_placeholder_view);

        // The occlusion placeholder, beside the shadow one and for the same
        // reason: every group of this layout has to fill
        // [`AMBIENT_OCCLUSION_BINDING`], and most of them are built before the
        // graph has an occlusion image to name.
        //
        // **Uploaded rather than cleared**, unlike the depth placeholder above,
        // and the four bytes are the whole point — see
        // [`AMBIENT_OCCLUSION_NONE`], which is where each of them is argued.
        // Left undefined this would be a random ambient scale *and* a random
        // direction to steer it along, on any frame that fell back to it.
        let ambient_occlusion_placeholder = upload_texture(
            device,
            queue,
            "ssao placeholder",
            Format::Rgba8Unorm,
            1,
            1,
            &AMBIENT_OCCLUSION_NONE,
        )?;
        rollback.textures.push(ambient_occlusion_placeholder);

        // The contact-shadow placeholder, beside the occlusion one and on its
        // terms exactly: every group of this layout has to fill
        // [`CONTACT_SHADOW_BINDING`], and most of them are built before the graph
        // has a contact-shadow image to name. `0xFF` is `1.0` through `R8Unorm`,
        // so a fragment that reads this one is a fragment the sun reaches
        // unobstructed.
        let contact_shadow_placeholder = upload_texture(
            device,
            queue,
            "contact shadow placeholder",
            Format::R8Unorm,
            1,
            1,
            &[CONTACT_SHADOW_NONE],
        )?;
        rollback.textures.push(contact_shadow_placeholder);

        // The probe-visibility placeholder, on the two above it's terms: every
        // group of this layout has to fill [`PROBE_VISIBILITY_BINDING`], and
        // nothing has been captured when they are built. One texel of
        // [`probe_visibility_none`], which no surface is further away than, so a
        // probe read through it keeps all of its weight.
        let probe_visibility_placeholder = upload_texture_layers(
            device,
            queue,
            "probe visibility placeholder",
            Format::Rg32Float,
            1,
            1,
            &[&probe_visibility_none()],
        )?;
        rollback.textures.push(probe_visibility_placeholder);

        // The split-sum `DFG` table, uploaded once and read by every frame this
        // renderer will draw — `crcbl_shaders::dfg` is where it is integrated,
        // committed and encoded, and `SPECULAR_ALBEDO_BINDING` is where it lands.
        //
        // **Cooked bytes rather than a computed image**: the integrator
        // importance-samples a lobe, which is `sin`, `cos` and a `powf`, and this
        // engine's goldens are compared across four backends with no tolerance.
        // Baking here would be four slightly different tables.
        let specular_dfg = upload_texture(
            device,
            queue,
            "dfg table",
            // Two bytes of fixed point per channel, high byte first — see
            // `crcbl_shaders::dfg::PAIR_TEXEL_BYTES`, which argues why this is
            // not the `Rg16Float` the format's own doc anticipated.
            Format::Rgba8Unorm,
            DFG_SIZE_U32,
            DFG_SIZE_U32,
            &dfg::pair_texels(),
        )?;
        rollback.textures.push(specular_dfg);

        // The area lights' fit, beside it and on its terms — cooked bytes for
        // the same reason, and `Rgba16Float` rather than fixed point because
        // these are matrix entries rather than shares of arriving light.
        // `crcbl_shaders::ltc::LTC_TEXEL_BYTES` argues the format.
        let ltc_table = upload_texture(
            device,
            queue,
            "ltc table",
            Format::Rgba16Float,
            LTC_SIZE_U32,
            LTC_SIZE_U32,
            &ltc::texels(),
        )?;
        rollback.textures.push(ltc_table);
        service();

        // **A comparison sampler, and that is the PCF.** Each
        // `SampleCmpLevelZero` returns the filtered fraction of four texels that
        // passed the test, so the shader's 3×3 kernel is nine hardware-bilinear
        // comparisons rather than nine raw fetches it averages itself.
        //
        // `Greater` for the engine's reversed-Z, exactly as the depth *test*
        // is: the receiver survives when it is nearer the light than whatever
        // the map stored. `SamplerDesc::compare` carries the same warning.
        //
        // Clamped on every axis so a receiver just outside a cascade's box
        // reads the edge rather than wrapping into the opposite corner — the
        // shader's own bounds check is what actually handles that case, and this
        // is the second line of defence one texel wide.
        let shadow_sampler = device.create_sampler(&SamplerDesc {
            label: Some("shadow comparison"),
            mag_filter: FilterMode::Linear,
            min_filter: FilterMode::Linear,
            mip_filter: FilterMode::Nearest,
            address_mode: [SamplerAddressMode::ClampToEdge; 3],
            compare: Some(crcbl_hal::CompareOp::Greater),
            ..SamplerDesc::default()
        })?;
        rollback.samplers.push(shadow_sampler);

        // --- the camera ---
        //
        // Everything the camera's picture needs of its own, built against the
        // scene resources above — see [`view`], which is where the line between
        // the two is drawn. Into the rollback whole as soon as it exists, so a
        // failure further down releases it with everything else.
        let slot_pages = vec![page_bindings; instance_buffers.len()];
        rollback.primary = Some(View::build(
            device,
            queue,
            &ViewInputs {
                id: ViewId::PRIMARY,
                effects: RenderEffects::all(),
                background: ViewBackground::Scene,
                lighting: ViewLighting::Scene,
                target_format,
                emit,
                instances: &instance_buffers,
                mesh_table,
                bucket_meshes: &bucket_meshes,
                bucket_modes: &bucket_modes,
                bucket_clusters: &bucket_clusters,
                bucket_cluster_bases: &bucket_cluster_bases,
                mesh_levels: &mesh_levels,
                level_groups: &level_groups,
                level_meshes: &level_meshes,
                instance_capacity: scene.capacities.instances,
                light_capacity: scene.capacities.lights,
                clusters: rollback.clusters.as_ref(),
                task_lanes: view::task_lanes(culls_clusters),
                mesh_layout,
                vertices,
                draw_constants,
                materials: material_buffer,
                pages: &slot_pages,
                probes: &probe_buffers,
                specular_dfg: specular_dfg.view,
                ltc_table: ltc_table.view,
                shadow_map: shadow_atlas_view,
                shadow_sampler,
                ambient_occlusion: ambient_occlusion_placeholder.view,
                contact_shadow: contact_shadow_placeholder.view,
                probe_visibility: probe_visibility_placeholder.view,
            },
            service,
        )?);
        let primary = rollback.primary.as_ref().expect("just stored");

        // Written here and never again: **which word holds** a bucket's run
        // start is fixed by the bucket table and the capacity, and both are
        // fixed at build. What varies per frame is where the run starts and how
        // much of it is filled, and the GPU writes both — the start into that
        // word, the count into the bucket's indirect arguments. See
        // `mesh.slang`'s header for why the block names a word rather than
        // carrying the start.
        //
        // Taken from the camera's generator and bound for every generator's
        // draws: the shadow culls and every secondary view are built from the
        // same table and the same capacity, so `bucket_start_word` answers the
        // same for all of them.
        let draws = &primary.draws;
        let mut bucket_constants = vec![0u32; bucket_meshes.len()];
        // **Every draw region's copy**, region 0's at the offsets
        // `bucket_constants` records and each further region a bucket count of
        // strides behind the one before: a region's draw reads its own run
        // start and — on the mesh path — its own argument structure, and the
        // two are the only words a region changes. See
        // `crcbl_shaders::draw_gen::DRAW_REGIONS`.
        for (region, (bucket, index)) in
            (0..crcbl_shaders::draw_gen::DRAW_REGIONS).flat_map(|region| {
                (0..bucket_count).map(move |bucket| (region, (bucket, bucket as usize)))
            })
        {
            let offset = (region * bucket_count + bucket) * draw_stride;
            if region == 0 {
                bucket_constants[index] = offset;
            }
            let start_at = draws.region_start_word(region, bucket);
            // The mesh path's block says three more things — where this
            // bucket's mesh's clusters are, how many it has, and which element
            // of the indirect arguments holds its instance count — because a
            // dispatch carries none of them and a `draw_indexed_indirect` does
            // not need them. All three are fixed when the bucket table is,
            // exactly like `start_at`.
            let block = if emit.is_mesh() {
                crcbl_shaders::meshlet::ClusterDrawConstants {
                    start_at,
                    cluster_base: bucket_cluster_bases[index],
                    cluster_count: bucket_clusters[index],
                    // The region's argument structure, which is where this
                    // region's instance count is.
                    bucket: region * bucket_count + bucket,
                    // The same number the draw-argument pass indexes the state
                    // with, taken from the object that owns the buffer rather
                    // than recomputed from the group table — the two indexing it
                    // differently is a cluster reading another instance's
                    // decision.
                    group_stride: draws.group_stride(),
                    // Where the group records are in the table buffer, from the
                    // object that packed it — the screen-error heatmap's one
                    // input that is not already in the frame block. Taken from
                    // `DrawGen` rather than recomputed here for `group_stride`'s
                    // reason: two spellings of one offset is an overlay reading
                    // another region's words as a group.
                    level_groups_at: draws.table_offsets().level_groups_at,
                    // The same two numbers again as words of that buffer,
                    // which is where a draw that is not the first of a ranged
                    // call reads them — `mesh_cluster.slang`'s "One call for
                    // a range of buckets". This bucket's, not the region's
                    // argument structure's: the tables hold one word a bucket.
                    cluster_base_at: draws.table_offsets().bucket_cluster_bases_at + bucket,
                    cluster_count_at: draws.table_offsets().bucket_clusters_at + bucket,
                    // Where this bucket's task chunks start in this region,
                    // and where the region's end: what a flat call binding
                    // this block searches between — `mesh_cluster.slang`'s
                    // `taskMain`.
                    chunk_starts_at: draws.chunk_start_word(region, bucket),
                    chunk_starts_end: draws.chunk_start_word(region, bucket_count),
                }
                .to_bytes()
                .to_vec()
            } else {
                // **The bucket's mesh, which is not always the drawn instance's.**
                // A uniform cut selects one of a DAG's levels and each level is
                // a mesh table entry of its own, so this is what says which
                // geometry the draw's index range belongs to; the instance goes
                // on naming level 0. See `mesh::DrawConstants::mesh`.
                mesh::DrawConstants {
                    start_at,
                    mesh: bucket_meshes[index],
                    mesh_at: draws.bucket_mesh_word(bucket),
                }
                .to_bytes()
                .to_vec()
            };
            device.write_buffer(draw_constants, u64::from(offset), &block)?;
        }

        let region_step = RegionStep {
            constants: bucket_count * draw_stride,
            args: draws.args_region_offset(1),
            counts: draws.counts_region_offset(1),
        };

        // §3.3's cull, once per cascade and once per shadowed light. Each gets
        // its own `DrawGen` and therefore its own frustum, survivor list and
        // indirect arguments — which is what "one cull dispatch per cascade
        // against the same instance/geometry pools" means, and why the instance
        // ring and the mesh table below are the same handles the camera's cull
        // was given.
        //
        // **One per light rather than one per tile**, which is topic 18's fourth
        // decision and what `SHADOW_CULLS` is: a point light's six faces cull
        // against the light's sphere once and draw that one visible set through
        // six matrices.
        //
        // **Built for every slot, including the ones no light may ever hold.** A
        // generator's buffers are sized by the instance capacity rather than by
        // the scene, so building one on demand would mean allocating device
        // memory inside `begin_frame` — and a frame that cannot allocate is a
        // frame that cannot draw. The unused ones cost memory and no dispatch:
        // `add_shadow_pass` records passes for the occupied slots alone.
        for cull in 0..SHADOW_CULLS {
            // Into the rollback as each is built, on the same terms as the
            // camera's: a failure two culls in has to release the first one,
            // and the rollback is the only thing that knows about it.
            let label = if cull < shadow::CASCADES {
                format!("shadow cascade {cull}")
            } else {
                format!("shadow light {}", cull - shadow::CASCADES)
            };
            let draws = DrawGen::new(
                device,
                queue,
                &DrawGenDesc {
                    label: Some(&label),
                    instances: &instance_buffers,
                    mesh_table,
                    bucket_meshes: &bucket_meshes,
                    bucket_modes: &bucket_modes,
                    bucket_clusters: &bucket_clusters,
                    bucket_cluster_bases: &bucket_cluster_bases,
                    mesh_levels: &mesh_levels,
                    level_groups: &level_groups,
                    level_meshes: &level_meshes,
                    instance_capacity: scene.capacities.instances,
                    // No view's: a shadow map is drawn from everything resident
                    // that casts, so an instance a camera hides still casts its
                    // shadow and one `set_instance_casts_shadow` turned off does
                    // not — on every geometry path, since this is the cull they
                    // all draw from. The reflective shadow maps draw these same
                    // survivors, so such an instance bounces no light either.
                    hidden_view: mesh::GpuInstance::CASTS_NO_SHADOW,
                    // A light slot may hold a point light, whose six faces cull
                    // separately into six regions of the one generator; a
                    // cascade never does.
                    mode: if cull < shadow::CASCADES {
                        crcbl_shaders::draw_gen::DrawMode::Plain
                    } else {
                        crcbl_shaders::draw_gen::DrawMode::Faces
                    },
                    task_lanes: view::task_lanes(culls_clusters),
                },
            )?;
            rollback.shadow_draws.push(draws);
            service();
        }
        // The handles are `Copy` and are read out here for the same reason the
        // camera's are above: the pool they came from is the rollback's now.
        let tile_buffers: Vec<TileBuffers> = rollback
            .shadow_draws
            .iter()
            .map(|draws| TileBuffers {
                runs: (0..instance_buffers.len())
                    .map(|frame| draws.runs(frame))
                    .collect(),
                args: (0..instance_buffers.len())
                    .map(|frame| draws.args(frame))
                    .collect(),
                cull_params: (0..instance_buffers.len())
                    .map(|frame| draws.cull_params(frame))
                    .collect(),
                cull_stats: (0..instance_buffers.len())
                    .map(|frame| draws.visible_count(frame))
                    .collect(),
                group_state: draws.group_state(),
            })
            .collect();

        let mut shadow_uniforms = Vec::with_capacity(FRAMES_IN_FLIGHT);
        let mut shadow_groups = Vec::with_capacity(FRAMES_IN_FLIGHT);
        let mut shadow_selection = Vec::with_capacity(FRAMES_IN_FLIGHT);
        let mut shadow_group_entries = Vec::with_capacity(FRAMES_IN_FLIGHT);
        for (frame, &slot_instances) in instance_buffers.iter().enumerate() {
            // Everything a group of this layout names that is the same in all of
            // this frame's — the camera's list and table buffers included, which
            // a shadow view binds because the layout declares them and reads
            // nothing of. The per-group half is what `MeshGroup` below varies,
            // and the two exist so the colour pass's group and the shadow pass's
            // are one description rather than two that agree today.
            let shared = SharedBindings {
                vertices,
                draw_constants,
                mesh_table,
                materials: material_buffer,
                pages: page_bindings,
                clusters: rollback.clusters.as_ref(),
                shadow_sampler,
                lights: primary.lights.lights(frame),
                light_grid: primary.lights.grid(frame),
                probes: probe_buffers[frame],
                tables: primary.draws.tables(),
                specular_dfg: specular_dfg.view,
                ltc_table: ltc_table.view,
            };

            // The same layout again, once per shadow view, differing in exactly
            // the things a view is: which matrix, and which cull's survivors.
            //
            // **The view's own uniforms and the cull's shared buffers**, which
            // is the whole of what a point light's six faces are: one visible
            // set, six matrices. `shadow_cull` is the map from a view to the
            // generator behind it, and it is a compile-time one because a bind
            // group names its buffers when it is created — where a face's *tile*
            // is decided per frame and reaches the device as a viewport.
            let mut frame_shadow_uniforms = Vec::with_capacity(SHADOW_VIEWS);
            let mut frame_shadow_groups = Vec::with_capacity(SHADOW_VIEWS);
            let mut frame_shadow_selection = Vec::with_capacity(SHADOW_VIEWS);
            let mut frame_shadow_entries = Vec::with_capacity(SHADOW_VIEWS);
            for view in 0..SHADOW_VIEWS {
                let buffers = &tile_buffers[if view < shadow::CASCADES {
                    view
                } else {
                    shadow_cull((view - shadow::CASCADES) / shadow::POINT_FACES)
                }];
                let tile_uniforms = device.create_buffer(&BufferDesc {
                    label: Some("shadow view uniforms"),
                    size: mesh::FRAME_UNIFORMS_SIZE as u64,
                    usage: BufferUsage::UNIFORM,
                    memory: MemoryLocation::HostUpload,
                })?;
                rollback.buffers.push(tile_uniforms);
                let entries = MeshGroup {
                    uniforms: tile_uniforms,
                    instances: slot_instances,
                    runs: buffers.runs[frame],
                    args: buffers.args[frame],
                    // The amplification stage culls clusters against whatever
                    // frustum is in this block, and against
                    // `frame.camera_position` — which in a view's copy is the
                    // *light*. So the per-cluster cull rejects what faces away
                    // from the light, which is the right question for a shadow
                    // map and the wrong one to have asked with the camera's
                    // frustum.
                    cull_params: buffers.cull_params[frame],
                    cull_stats: buffers.cull_stats[frame],
                    // **This view's own**, and not the colour pass's: that pass
                    // is recorded last and would write over it. See
                    // `ForwardRenderer::shadow_selection`.
                    cluster_selection: tile_selection.get(view).map(|ring| ring[frame]),
                    // Its cull's — see `TileBuffers::group_state`, which is
                    // where that budget is argued.
                    group_state: emit.is_mesh().then_some(buffers.group_state),
                    shadow_map: shadow_placeholder_view,
                    // A cascade shades nothing — the pipeline has no fragment
                    // stage — so this slot exists only because Metal
                    // materialises every global into every entry point.
                    ambient_occlusion: ambient_occlusion_placeholder.view,
                    contact_shadow: contact_shadow_placeholder.view,
                    probe_visibility: probe_visibility_placeholder.view,
                }
                .entries(&shared);
                let group = device.create_bind_group(&BindGroupDesc {
                    label: Some("shadow view"),
                    layout: mesh_layout,
                    entries: &entries,
                    variable_count: None,
                })?;
                rollback.bind_groups.push(group);
                frame_shadow_uniforms.push(tile_uniforms);
                frame_shadow_groups.push(group);
                frame_shadow_entries.push(entries);
                frame_shadow_selection.extend(tile_selection.get(view).map(|ring| ring[frame]));
            }
            shadow_uniforms.push(frame_shadow_uniforms);
            shadow_groups.push(frame_shadow_groups);
            shadow_group_entries.push(frame_shadow_entries);
            shadow_selection.push(frame_shadow_selection);
            service();
        }

        let mesh_set_layouts = [mesh_layout];
        let mesh_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
            label: Some("mesh"),
            bind_group_layouts: &mesh_set_layouts,
            // The camera goes in the uniform buffer above rather than here:
            // `Features::PUSH_CONSTANTS` is absent on Tier B and the seam is
            // explicit that the substitute is a data-layout decision. So this
            // file needs no tier branch at all — it has been on Tier B's shape
            // since P1, and `crate::ui_pass` is where the split actually bites.
            push_constants: None,
        })?;
        rollback.pipeline_layouts.push(mesh_pipeline_layout);

        // The colour pass's pipeline and its depth-only twin, out of one set of
        // modules — see [`MeshModules`], which is where the two shapes and the
        // reasons for them live. Both are created before either is unwrapped and
        // the modules are released between, so a failing creation leaks nothing.
        //
        // **Each shape is built twice, once per material side** — see
        // [`SidedPipelines`], which is where the cull modes and the reason for a
        // pipeline rather than a per-draw state live. The shadow tile clear is
        // the one exception: its triangle comes out of `SV_VertexID` and it
        // already culls nothing.
        //
        // **`service` before every one of them**: on a cold driver cache each is
        // a shader compilation, and this batch is the build's longest run of
        // them — see [`ForwardRenderer::with_scene_serviced`].
        let modules = MeshModules::new(device, emit, culls_clusters)?;
        let mesh_results = MeshModules::sided(|cull| {
            service();
            modules.color_pipeline(
                device,
                mesh_pipeline_layout,
                PolygonMode::Fill,
                cull,
                "forward",
            )
        });
        let shadow_results = MeshModules::sided(|cull| {
            service();
            modules.depth_pipeline(device, mesh_pipeline_layout, cull)
        });
        // And its cutout twin, which a frame whose material table masks alpha is
        // recorded with instead — see [`MeshModules::depth_masked_pipeline`].
        let depth_masked_results = MeshModules::sided(|cull| {
            service();
            modules.depth_masked_pipeline(device, mesh_pipeline_layout, cull)
        });
        // And the one that resets a tile, which the cadence rung needs and the
        // attachment's load operation cannot express — see
        // [`MeshModules::depth_clear_pipeline`].
        service();
        let shadow_clear_result = modules.depth_clear_pipeline(device, mesh_pipeline_layout);
        // And the irradiance probes' reflective shadow map, built
        // from the same modules and the same layout — see
        // [`MeshModules::rsm_pipeline`]. Built on every scene rather than only
        // on one whose probes ask to be updated: the modules are released a line
        // below and a pipeline built later would need them back, which is a
        // second shader compilation for a field a `ProbeGrid` decides.
        let rsm_results = MeshModules::sided(|cull| {
            service();
            modules.rsm_pipeline(device, mesh_pipeline_layout, cull)
        });
        modules.destroy(device);
        // Register every successful creation before propagating any error.
        // Results later in this batch may own pipelines even when the first
        // result failed; dropping an unvisited Result does not release a HAL
        // handle. The outer rollback owns all of them until build succeeds.
        for pipeline in mesh_results
            .iter()
            .chain(&shadow_results)
            .chain(&depth_masked_results)
            .chain(std::iter::once(&shadow_clear_result))
            .chain(&rsm_results)
            .flatten()
        {
            rollback.pipelines.push(*pipeline);
        }
        let into_sided = |results: [Result<GraphicsPipelineHandle, HalError>; 2]|
         -> Result<SidedPipelines, HalError> {
            let [single, double] = results;
            Ok(SidedPipelines { single: single?, double: double? })
        };
        let mesh_pipeline = into_sided(mesh_results)?;
        let shadow_pipeline = into_sided(shadow_results)?;
        let depth_masked_pipeline = into_sided(depth_masked_results)?;
        let shadow_clear_pipeline = shadow_clear_result?;
        let rsm_pipeline = into_sided(rsm_results)?;

        // --- the tonemap pass ---
        let tonemap_entries = [
            BindGroupLayoutEntry {
                binding: 0,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2,
                    sample_type: SampleType::Float,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 1,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::Sampler { comparison: false },
                count: 1,
                flags: BindingFlags::empty(),
            },
            // The exposure — see [`set_exposure`](Self::set_exposure). A uniform
            // buffer rather than a push constant, which is [`crate::ui_pass`]'s
            // decision restated: WebGPU has no push constants at all, so a range
            // here would split this pass into a tier A and a tier B form —
            // two layouts, two buffers and, because one Slang entry point reads
            // either a `[[vk::push_constant]]` block or a `[[vk::binding]]`ed
            // one and never both, a second copy of `tonemap.slang`. Four bytes
            // once a frame do not buy that.
            //
            // `FRAGMENT` alone, and the artifact agrees: `spirv/tonemap.spv`
            // lists `%params` in the fragment `OpEntryPoint`'s interface and not
            // in the vertex one, because the vertex stage generates three
            // corners out of `SV_VertexID` and reads nothing.
            BindGroupLayoutEntry {
                binding: 2,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::UniformBuffer { dynamic: false },
                count: 1,
                flags: BindingFlags::empty(),
            },
            // The measured exposure — see [`crate::exposure`]. **Bound on every
            // frame, whether or not anything measured**, because a binding that
            // comes and goes is a second pipeline layout and a second group
            // cache keyed on which one is live, to save four bytes. The block
            // above carries the switch that decides whether the shader reads it.
            BindGroupLayoutEntry {
                binding: 3,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::StorageBuffer {
                    // Written by `exposure.slang`'s reduce and read here —
                    // `StructuredBuffer` in this shader, which is the truth
                    // rather than a hint.
                    read_only: true,
                    dynamic: false,
                    stride: size_of::<u32>() as u32,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
        ];
        let tonemap_desc = BindGroupLayoutDesc {
            label: Some("tonemap scene"),
            entries: &tonemap_entries,
        };
        check_portable_storage_buffers(Some("tonemap"), &[&tonemap_desc])?;
        let tonemap_layout = device.create_bind_group_layout(&tonemap_desc)?;
        rollback.bind_group_layouts.push(tonemap_layout);
        let tonemap_set_layouts = [tonemap_layout];
        let tonemap_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
            label: Some("tonemap"),
            bind_group_layouts: &tonemap_set_layouts,
            push_constants: None,
        })?;
        rollback.pipeline_layouts.push(tonemap_pipeline_layout);
        let tonemap_vertex = entry(&TONEMAP, Stage::Vertex)?;
        let tonemap_fragment = entry(&TONEMAP, Stage::Fragment)?;
        let tonemap_module = device.create_shader_module(&ShaderModuleDesc {
            label: Some("tonemap.slang"),
            spirv: TONEMAP.spirv(),
            wgsl: TONEMAP.wgsl(),
            msl: TONEMAP.msl(),
            // A container per entry point, for the reason the mesh module above
            // gives.
            dxil: &TONEMAP.dxil_containers(),
        })?;
        let tonemap_targets = [ColorTargetState::opaque(target_format)];
        let tonemap_pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
            label: Some("tonemap"),
            layout: tonemap_pipeline_layout,
            vertex: ShaderEntry {
                module: tonemap_module,
                entry_point: tonemap_vertex,
            },
            fragment: Some(ShaderEntry {
                module: tonemap_module,
                entry_point: tonemap_fragment,
            }),
            // The full-screen triangle is deliberately oversized, so two of its
            // vertices are outside the viewport and its winding is not worth
            // reasoning about. `CullMode::None` is the honest setting.
            primitive: PrimitiveState::default(),
            depth_stencil: None,
            multisample: MultisampleState::default(),
            color_targets: &tonemap_targets,
        });
        device.destroy_shader_module(tonemap_module);
        let tonemap_pipeline = tonemap_pipeline?;
        rollback.pipelines.push(tonemap_pipeline);
        service();

        // Nearest, not linear: see `tonemap.slang` on why a 1:1 blit must not
        // leave a golden image depending on two rasterisers agreeing about
        // texel-centre arithmetic.
        let sampler = device.create_sampler(&SamplerDesc {
            label: Some("tonemap scene"),
            mag_filter: FilterMode::Nearest,
            min_filter: FilterMode::Nearest,
            mip_filter: FilterMode::Nearest,
            address_mode: [SamplerAddressMode::ClampToEdge; 3],
            ..SamplerDesc::default()
        })?;
        rollback.samplers.push(sampler);

        // --- the shadow atlas viewer ---
        //
        // Built last, so `Rollback::run` releases it first. It writes the
        // caller's target rather than a transient — it replaces the picture the
        // tonemap put there, which is [`crate::atlas_view`]'s argument — and it
        // records on no frame but the one that resolved
        // [`DebugView::ShadowAtlas`].
        rollback.atlas_viewer = Some(AtlasView::new(
            device,
            instance_buffers.len(),
            target_format,
            Self::build_fullscreen,
        )?);
        service();

        Ok(Self {
            pool: rollback
                .pool
                .take()
                .unwrap_or_else(|| unreachable!("the pool was placed in the rollback above")),
            bucket_constants,
            region_step,
            bucket_modes,
            instances: rollback
                .instances
                .take()
                .unwrap_or_else(|| unreachable!("the pool was placed in the rollback above")),
            mesh_ids,
            skinnable_meshes,
            skinned_instances: Vec::new(),
            materials: rollback
                .materials
                .take()
                .unwrap_or_else(|| unreachable!("the table was placed in the rollback above")),
            material_ids,
            probes: rollback
                .probes
                .take()
                .unwrap_or_else(|| unreachable!("the table was placed in the rollback above")),
            probe_volume: scene.probes.volume,
            base_color_page,
            normal_page,
            mro_page,
            emissive_page,
            page_extents,
            page_layers,
            base_color_sampler,
            anisotropy,
            // Every slot's groups were just built naming these.
            slot_pages: vec![page_bindings; FRAMES_IN_FLIGHT],
            retired_pages: Vec::new(),
            // No frame has been recorded yet, and the counters say so rather
            // than reporting the count a frame *would* have.
            recorded_draws: 0,
            emit,
            range_limit,
            clusters: rollback.clusters.take(),
            culls_clusters,
            draw_constants,
            mesh_clusters,
            // One entry per description mesh, each holding one bucket per level,
            // where the cull pass takes a uniform cut — and nothing at all where
            // the amplification stage takes a per-cluster one. Read off the
            // bucket table that was actually built rather than re-derived from
            // the path.
            mesh_level_buckets: if emit.is_mesh() {
                Vec::new()
            } else {
                residents
                    .iter()
                    .enumerate()
                    .map(|(index, resident)| {
                        let base = bucket_bases[index];
                        (base..base + resident.levels.len())
                            .map(|bucket| {
                                u32::try_from(bucket)
                                    .unwrap_or_else(|_| unreachable!("a table of a few buckets"))
                            })
                            .collect()
                    })
                    .collect()
            },
            lod_error_budget: LOD_ERROR_BUDGET,
            lod_hold_ratio: LOD_HOLD_RATIO,
            // Overwritten by the first `begin_frame`, which is the only thing
            // that can know the viewport.
            shadow_lod_params: [0.0, 0.0, 0.0],
            extra_lights: Vec::new(),
            primary: rollback
                .primary
                .take()
                .unwrap_or_else(|| unreachable!("the camera was placed in the rollback above")),
            views: Vec::new(),
            draw_tables: DrawTables {
                bucket_meshes,
                bucket_clusters,
                bucket_cluster_bases,
                mesh_levels,
                level_groups,
                level_meshes,
                instance_capacity: scene.capacities.instances,
                light_capacity: scene.capacities.lights,
            },
            frame_serial: 0,
            frame_scene: None,
            frame: 0,
            mesh_layout,
            mesh_pipeline_layout,
            mesh_pipeline,
            // Off, and unbuilt, on the ground grid's terms below: the wireframe
            // view is opt-in, so a caller that never asks for one draws the
            // frame it drew before `set_wireframe` existed.
            wireframe_pipeline: None,
            wireframe_on: false,
            occlusion_culling: OcclusionCulling::OFF,
            point_face_culls: true,
            shadow_view_tamper: None,
            // Off, on the line above's terms: the normals view is opt-in, so a
            // caller that never asks for one draws the frame it drew before
            // `set_normals_view` existed. It builds nothing, so there is no
            // second field here.
            normals_view: false,
            // Off on the same terms, and "off" here is a density of zero: the
            // shader's composite is exactly the identity there, so a caller who
            // never calls `set_fog` gets the frame byte for byte.
            fog: Fog::NONE,
            sky: Sky::NONE,
            atmosphere: None,
            sky_view: None,
            sky_view_build: None,
            lod_view: false,
            heatmap: false,
            occlusion_view: false,
            motion_view: false,
            bent_normal_view: false,
            cascade_view: false,
            atlas_view: false,
            // Following the camera, on the line above's terms: the selection eye
            // is the camera's until a caller pins it, so a renderer nobody calls
            // `set_frozen_selection_eye` on hands `begin_frame` exactly what it
            // handed before this field existed.
            frozen_selection_eye: None,
            shadow_atlas,
            shadow_atlas_view,
            shadow_placeholder,
            shadow_placeholder_view,
            shadow_sampler,
            shadow_pipeline,
            depth_masked_pipeline,
            shadow_clear_pipeline,
            rsm_pipeline,
            probe_gather,
            probe_update: scene.probes.update,
            // Overwritten by the first `begin_frame`, which is the only reader's
            // only source. Zero is the honest placeholder: no cascade has been
            // fitted yet, and a gather recorded against it would scale by zero
            // rather than by a number nobody chose.
            cascade_reach: 0.0,
            // Nothing has been fitted before the first `begin_frame`.
            rsm_cull_ready: false,
            sun_color: Vec3::ZERO,
            shadow_draws: std::mem::take(&mut rollback.shadow_draws),
            shadow_uniforms,
            shadow_prepare_views: Vec::new(),
            shadow_prepare_culls: Vec::new(),
            shadow_groups,
            shadow_selection,
            shadow_lights: shadow::Selection::default(),
            // Nothing has drawn the atlas, so the first frame draws every group
            // whatever it is asked for — which is also what gives the image a
            // defined content before anything samples it. A record is never
            // empty, so the first frame's is a change and takes every id past
            // the zero below it.
            shadow_group_inputs: vec![Vec::new(); SHADOW_CULLS],
            shadow_group_id: vec![0; SHADOW_CULLS],
            shadow_group_writes: vec![0; SHADOW_CULLS],
            shadow_footprints: Vec::new(),
            shadow_dag_elements: std::collections::BTreeSet::new(),
            shadow_written: Vec::new(),
            shadow_moved: Vec::new(),
            shadow_pass_id: 0,
            shadow_pass_ran: Arc::new(AtomicU64::new(0)),
            shadow_pending: None,
            // A reach of zero, so every centre on the first frame is further
            // from what the image holds than the nothing it holds reaches —
            // which is the reset that frame should be.
            shadow_group_held: vec![(0, Vec3::ZERO, 0.0); SHADOW_CULLS],
            shadow_group_redrawn: vec![false; SHADOW_CULLS],
            shadow_atlas_layout: None,
            shadow_atlas_cached: false,
            shadow_cadence_reset: false,
            shadow_faces_redrawn: 0,
            shadow_cadence_request: None,
            shadow_atlas_clears: true,
            shadow_frame: 0,
            frame_skins: false,
            // [`FRAMES_IN_FLIGHT`], the number every other ring here is sized
            // by, so a slot has been through the whole loop before it is read.
            // `culls_clusters` rather than the device's feature bits: what
            // decides whether the cluster word is a count is whether *this
            // renderer* built an amplification stage.
            cull_stats: CullStatsRing::new(device, FRAMES_IN_FLIGHT, culls_clusters),
            tonemap_layout,
            tonemap_pipeline_layout,
            tonemap_pipeline,
            sampler,
            // The value `tonemap.slang`'s `EXPOSURE` constant held, so a
            // renderer nobody has called `set_exposure` on writes the frame it
            // wrote before the block existed.
            exposure: tonemap::DEFAULT_EXPOSURE,
            exposure_adaptation: None,
            // And the filmic roll-off over it: this renderer shades in linear
            // HDR, so a view that has asked for nothing gets the operator that
            // range was shaded for.
            tonemap_curve: tonemap::TonemapCurve::Aces,
            target_format,
            ambient_occlusion_placeholder,
            contact_shadow_placeholder,
            probe_visibility_placeholder,
            // Nothing has been captured, so every frame drawn before
            // `capture_probe_visibility` reads the placeholder and weighs every
            // probe at one — which is the frame this renderer drew before the
            // maps existed.
            probe_visibility: None,
            probe_occluders,
            specular_dfg,
            ltc_table,
            shadow_group_entries,
            // Off, and unbuilt: the grid is opt-in, so a caller that never asks
            // for one draws the frame it drew before this module existed.
            ground_grid: None,
            ground_grid_on: false,
            // Empty, and unbuilt: nothing has appended a segment, so this
            // renderer records the frame it recorded before the layer existed.
            debug_draw: DebugDraw::default(),
            atlas_viewer: rollback
                .atlas_viewer
                .take()
                .unwrap_or_else(|| unreachable!("the viewer was placed in the rollback above")),
            // Full resolution, which is the frame every caller of this type drew
            // before there was a knob — see [`Self::set_render_scale`].
            render_scale: 1.0,
            // The default stack the view wants, no quality clamp and no
            // override, which resolves to every effect this device permits but
            // the lens one — the frame every caller of this type drew before
            // there were toggles. See [`RenderEffects::DEFAULT_STACK`].
            effect_request: EffectRequest::default(),
            device_effects: RenderEffects::all(),
            frame_effects: RenderEffects::DEFAULT_STACK,
            // What the switch says today, so a renderer built and never opened
            // still describes the frame it would draw. `begin_frame` reads it
            // again for the frame it opens.
            frame_ssao_blurs: crate::ssao::blur_passes(),
            // No frame has been recorded yet, on `recorded_draws`' terms.
            recorded_fullscreen: 0,
            // No frame has been recorded yet, on `recorded_fullscreen`'s terms.
            recorded_debug_draw: 0,
            recorded_tile_clears: 0,
            // No bodies, so no pass: the frame every caller of this type drew
            // before water existed. Nothing is allocated until a body is set.
            water: WaterBodies::new(FRAMES_IN_FLIGHT),
            recorded_water_draws: 0,
            // No field, so no pass: the frame every caller of this type drew
            // before grass existed. The two calm wind layers are one texel
            // each and are what makes a field with no weather set still.
            grass: GrassScene::new(device, queue, FRAMES_IN_FLIGHT)?,
            wind: crcbl_shaders::wind::WindParams::default(),
            recorded_grass_draws: 0,
        })
    }

    /// Builds a full-screen-triangle pipeline out of `shader`'s vertex and
    /// fragment entry points.
    ///
    /// One helper because every post pass in this crate wants the same
    /// pipeline — the tonemap's, `ssao`'s, `ssao-blur`'s, `ssr`'s and the rest —
    /// differing in the module, the layout and the target format alone. The
    /// tonemap's stays written out where it is: it is the one that carries the
    /// *why* of the shape, and this is the shape repeated.
    ///
    /// The module is destroyed before the pipeline result is unwrapped, so a
    /// failing creation leaks nothing.
    ///
    /// # Errors
    ///
    /// [`HalError`] from the manifest lookup, the module or the pipeline.
    fn build_fullscreen(
        device: &dyn Device,
        label: &str,
        shader: &crcbl_shaders::Shader,
        layout: PipelineLayoutHandle,
        color_targets: &[ColorTargetState],
    ) -> Result<GraphicsPipelineHandle, HalError> {
        Self::build_fullscreen_with(device, label, shader, layout, color_targets, None)
    }

    /// [`Self::build_fullscreen`] for a pass that **depth-tests** what it draws
    /// against an attachment it does not write.
    ///
    /// The state is [`DepthStencilState::equal_depth_read_only`], whose
    /// [`CompareOp::GreaterOrEqual`] is the reversed-Z pair for "the fragment's
    /// depth must equal what is already there". One caller, [`crate::sky_pass`],
    /// which emits its triangle at the far plane so that the test selects
    /// exactly the pixels no geometry covered — see that module.
    ///
    /// # Errors
    ///
    /// [`HalError`] from the manifest lookup, the module or the pipeline.
    fn build_tested_fullscreen(
        device: &dyn Device,
        label: &str,
        shader: &crcbl_shaders::Shader,
        layout: PipelineLayoutHandle,
        color_targets: &[ColorTargetState],
        depth_format: Format,
    ) -> Result<GraphicsPipelineHandle, HalError> {
        Self::build_fullscreen_with(
            device,
            label,
            shader,
            layout,
            color_targets,
            Some(DepthStencilState::equal_depth_read_only(depth_format)),
        )
    }

    /// The body of the two above, which differ in their depth state and in
    /// nothing else.
    ///
    /// # Errors
    ///
    /// [`HalError`] from the manifest lookup, the module or the pipeline.
    fn build_fullscreen_with(
        device: &dyn Device,
        label: &str,
        shader: &crcbl_shaders::Shader,
        layout: PipelineLayoutHandle,
        color_targets: &[ColorTargetState],
        depth_stencil: Option<DepthStencilState>,
    ) -> Result<GraphicsPipelineHandle, HalError> {
        let vertex = entry(shader, Stage::Vertex)?;
        let fragment = entry(shader, Stage::Fragment)?;
        let module = device.create_shader_module(&ShaderModuleDesc {
            label: Some(shader.source()),
            spirv: shader.spirv(),
            wgsl: shader.wgsl(),
            msl: shader.msl(),
            // A container per entry point, for the reason the mesh module gives.
            dxil: &shader.dxil_containers(),
        })?;
        let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
            label: Some(label),
            layout,
            vertex: ShaderEntry {
                module,
                entry_point: vertex,
            },
            fragment: Some(ShaderEntry {
                module,
                entry_point: fragment,
            }),
            // The triangle is deliberately oversized, so two of its vertices are
            // outside the viewport and its winding is not worth reasoning about.
            primitive: PrimitiveState::default(),
            depth_stencil,
            multisample: MultisampleState::default(),
            color_targets,
        });
        device.destroy_shader_module(module);
        pipeline
    }

    /// Builds a full-screen-triangle pipeline that writes a **depth**
    /// attachment and no colour one.
    ///
    /// [`Self::build_fullscreen`]'s shape with the two halves of that swapped:
    /// no colour target at all, and a depth state whose comparison always
    /// passes so every texel of the destination takes the value the fragment
    /// computed. The reversed-Z [`CompareOp::Greater`] every geometry pipeline
    /// in this file uses would be wrong here — this pass is not depth-testing
    /// anything, it is writing a reduction, and a test against the target's
    /// undefined contents would drop texels at random.
    ///
    /// Two callers, [`crate::hiz`] and [`crate::occlusion_cull`], and it stays
    /// a method rather than moving there because the module and the
    /// destroy-before-unwrap above are this file's, and both take it in exactly
    /// as `crate::ssao` takes the sibling.
    ///
    /// **The entry points are named**, unlike the sibling's: `hiz.slang` has a
    /// fragment stage per pyramid, and a stage looked up by kind would be
    /// ambiguous.
    ///
    /// # Errors
    ///
    /// [`HalError`] from the module or the pipeline.
    fn build_depth_fullscreen(
        device: &dyn Device,
        label: &str,
        shader: &crcbl_shaders::Shader,
        vertex: &str,
        fragment: &str,
        layout: PipelineLayoutHandle,
        format: Format,
    ) -> Result<GraphicsPipelineHandle, HalError> {
        let module = device.create_shader_module(&ShaderModuleDesc {
            label: Some(shader.source()),
            spirv: shader.spirv(),
            wgsl: shader.wgsl(),
            msl: shader.msl(),
            dxil: &shader.dxil_containers(),
        })?;
        let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
            label: Some(label),
            layout,
            vertex: ShaderEntry {
                module,
                entry_point: vertex,
            },
            fragment: Some(ShaderEntry {
                module,
                entry_point: fragment,
            }),
            primitive: PrimitiveState::default(),
            depth_stencil: Some(DepthStencilState {
                format,
                depth_write: true,
                depth_compare: CompareOp::Always,
                stencil: None,
                bias: DepthBias::default(),
            }),
            multisample: MultisampleState::default(),
            color_targets: &[],
        });
        device.destroy_shader_module(module);
        pipeline
    }

    /// Creates the geometry pool and makes every mesh of `scene` resident in it.
    ///
    /// Separate from [`ForwardRenderer::build`] because it is **self-cleaning**:
    /// the pool is not the rollback's until this has returned, so a failure
    /// between creating it and flushing the last upload releases it here.
    fn build_geometry(
        device: &dyn Device,
        queue: QueueHandle,
        scene: &SceneDesc<'_>,
        service: &mut dyn FnMut(),
    ) -> Result<(MeshPool, Vec<ResidentMesh>), HalError> {
        let mut pool = MeshPool::new(
            device,
            &MeshPoolDesc {
                label: Some("forward geometry"),
                vertex_capacity: scene.capacities.vertices,
                index_capacity: scene.capacities.indices,
                mesh_capacity: scene.capacities.meshes,
            },
        )?;
        match Self::residents(device, queue, &mut pool, scene, service) {
            Ok(residents) => Ok((pool, residents)),
            Err(error) => {
                pool.destroy(device);
                Err(error)
            }
        }
    }

    /// Creates the material table and fills it with `scene`'s rows, returning it
    /// and the id of each.
    ///
    /// Self-cleaning for the same reason [`ForwardRenderer::build_geometry`] is:
    /// the table is not the rollback's until this has returned.
    fn build_materials(
        device: &dyn Device,
        scene: &SceneDesc<'_>,
    ) -> Result<(MaterialTable, Vec<u32>), HalError> {
        let mut materials = MaterialTable::new(
            device,
            &MaterialTableDesc {
                label: Some("forward"),
                capacity: scene.capacities.materials,
            },
        )?;
        match Self::material_rows(device, &mut materials, &scene.materials) {
            Ok(ids) => Ok((materials, ids)),
            Err(error) => {
                materials.destroy(device);
                Err(error)
            }
        }
    }

    /// Inserts `rows` **in order** and returns the id of each.
    ///
    /// Split out of [`ForwardRenderer::build_materials`] only so the table can
    /// be released on a failure without the borrow that filling it takes, which
    /// is the same shape [`ForwardRenderer::residents`] has.
    ///
    /// **In order, because row 0 is not this function's to choose**: it is what
    /// [`mesh::GpuInstance::default`] names, so it is what an instance written
    /// without a material id shades with. Inserting a description's rows in any
    /// other order would move that row under every caller — see
    /// [`SceneDesc::materials`], which is where it is a caller's decision.
    fn material_rows(
        device: &dyn Device,
        materials: &mut MaterialTable,
        rows: &[mesh::GpuMaterial],
    ) -> Result<Vec<u32>, HalError> {
        let mut ids = Vec::with_capacity(rows.len());
        for row in rows {
            let handle = materials.insert(device, row)?;
            // The id is asked for rather than assumed, because the number an
            // instance carries is this one and nothing else knows it.
            ids.push(materials.index(handle).ok_or_else(|| {
                HalError::Backend(
                    "a material inserted into an empty table did not resolve".to_string(),
                )
            })?);
        }
        Ok(ids)
    }

    /// Uploads every mesh of `scene` and returns their mesh ids — **only** once
    /// the transfers have completed.
    ///
    /// The calls are §3.1's upload path in order: the copies are recorded and
    /// submitted against timeline values, [`MeshPool::flush`] is what makes those
    /// values pass, and [`MeshPool::mesh`] is what refuses to hand out a range
    /// before they have.
    ///
    /// **In description order**, which is what makes a mesh's table id a
    /// property of the description rather than of this loop — the second mesh
    /// uploaded is the pool's first resident at a non-zero base vertex, which is
    /// what the module docs call the one thing that can tell a working base
    /// vertex from a cancelled one.
    ///
    /// A DAG is **one upload per level**. Every level was decimated separately,
    /// so a coarser level's vertices are wherever the collapses put them and
    /// belong to no vertex of the level below — a DAG is several vertex ranges,
    /// and the pool suballocates in vertices, so several ranges means several
    /// uploads. Level 0 goes first, so every other level starts past it and the
    /// offsets a cluster carries are non-negative; that is checked rather than
    /// assumed, because the pool's free list makes no promise about where a mesh
    /// lands.
    fn residents(
        device: &dyn Device,
        queue: QueueHandle,
        pool: &mut MeshPool,
        scene: &SceneDesc<'_>,
        service: &mut dyn FnMut(),
    ) -> Result<Vec<ResidentMesh>, HalError> {
        let mut uploaded: Vec<Vec<crate::mesh_pool::MeshHandle>> =
            Vec::with_capacity(scene.meshes.len());
        for desc in &scene.meshes {
            match &desc.geometry {
                Geometry::Flat {
                    vertices,
                    indices,
                    uv_range,
                    flags,
                    ..
                } => {
                    uploaded.push(vec![pool.upload(
                        device,
                        queue,
                        &MeshUpload {
                            label: &desc.label,
                            vertices,
                            indices,
                            uv_range: *uv_range,
                            flags: *flags,
                        },
                    )?]);
                    service();
                }
                Geometry::Dag {
                    levels,
                    dag,
                    uv_range,
                    flags,
                } => {
                    let mut handles = Vec::with_capacity(levels.len());
                    for (depth, (vertices, level)) in levels.iter().zip(&dag.levels).enumerate() {
                        handles.push(pool.upload(
                            device,
                            queue,
                            &MeshUpload {
                                label: &format!("{} level {depth}", desc.label),
                                vertices,
                                indices: &level.indices(),
                                // Level 0's range for every level, which is the
                                // one the mesh path reads whichever level it
                                // draws — see `Geometry::Dag::uv_range`.
                                uv_range: *uv_range,
                                // And the description's flags for every level,
                                // for the same reason: the levels are one
                                // surface, so a tangent frame either describes
                                // all of them or none.
                                flags: *flags,
                            },
                        )?);
                        service();
                    }
                    uploaded.push(handles);
                }
            }
        }

        pool.flush(device)?;
        service();
        // The table index is the only number that leaves here — where the
        // geometry actually is reaches the GPU through the mesh table, and the
        // draw arguments are built from that table by a shader. `MeshPool::mesh`
        // is still asked, because it is the call that refuses a mesh whose
        // upload has not completed, and an id for a mesh that is not there yet
        // would be a draw of nothing.
        let resolve = |handle| match (pool.mesh(handle), pool.table_index(handle)) {
            (Some(_), Some(id)) => Ok(id),
            _ => Err(MeshPoolError::NotResident { handle }),
        };
        let base_vertex = |handle| match pool.mesh(handle) {
            Some(range) => Ok(range.base_vertex),
            None => Err(MeshPoolError::NotResident { handle }),
        };

        let mut residents = Vec::with_capacity(uploaded.len());
        for (desc, handles) in scene.meshes.iter().zip(&uploaded) {
            // **Relative to level 0's base**, because that is the base the
            // instance resolves through its mesh id and the one the stage adds
            // this on top of. A level that landed *below* level 0 would make the
            // sum wrap, so it is refused here rather than drawn as another
            // mesh's vertices. A flat mesh is one level and reads zero.
            let level_zero = base_vertex(handles[0])?;
            let mut vertex_bases = Vec::with_capacity(handles.len());
            for (depth, &handle) in handles.iter().enumerate() {
                let base = base_vertex(handle)?;
                vertex_bases.push(base.checked_sub(level_zero).ok_or_else(|| {
                    HalError::InvalidDescriptor(format!(
                        "{} level {depth} landed at vertex {base}, below level 0's \
                         {level_zero}, so its clusters cannot name their own geometry",
                        desc.label
                    ))
                })?);
            }
            residents.push(ResidentMesh {
                levels: handles
                    .iter()
                    .map(|&handle| resolve(handle))
                    .collect::<Result<_, _>>()?,
                vertex_bases,
                // Matched on the description rather than counted off `handles`,
                // so a DAG decimated to a single level is still refused: what
                // makes a mesh skinnable is that every draw of it reads one
                // vertex run, and that is a property of the geometry rather than
                // of how many levels it happened to arrive with.
                skinnable: matches!(desc.geometry, Geometry::Flat { .. }).then(|| handles[0]),
            });
        }
        Ok(residents)
    }

    /// Rotates to the next frame's uniform buffer and instance buffer, writes
    /// this frame's camera and light into the first, and uploads whatever
    /// changed into the second.
    ///
    /// Must be called once per frame, before [`ForwardRenderer::add_passes`].
    /// Separate from `add_passes` because the write happens on the CPU and the
    /// passes are recorded on the GPU timeline: fusing them would hide the ring
    /// rotation inside a function whose name says nothing about it.
    ///
    /// **It moves nothing.** Every object's transform is the caller's, written
    /// through [`ForwardRenderer::set_instance`] whenever it changes, so the
    /// transfer this records is [`InstancePool::begin_frame`]'s delta and a
    /// frame in which nothing moved uploads no instance bytes at all. The
    /// sandbox's spinning cube is one 80-byte write a frame because the sandbox
    /// spins it; a still scene is free.
    ///
    /// It also writes this frame's **cull parameters** — the camera's frustum,
    /// extracted from the very same view-projection the uniform block carries,
    /// so the pass that decides what is on screen and the pass that draws it
    /// cannot be looking at two different cameras — and zeroes the counters the
    /// two compute passes only ever add to. See [`crate::draw_gen`] on why those
    /// zeroes come from the host.
    ///
    /// # Errors
    ///
    /// [`HalError`] if the uniform buffer, the instance buffer or any of the
    /// draw-generation buffers could not be written.
    pub fn begin_frame(
        &mut self,
        device: &dyn Device,
        camera: &Camera,
        light: &DirectionalLight,
        extent: (u32, u32),
    ) -> Result<(), HalError> {
        // The instance pool owns the ring, so its slot is the frame index the
        // uniform buffer and the bind group below are picked with.
        self.frame = self.instances.rotate();
        self.frame_skins = false;
        self.instances.flush(device)?;
        self.begin_frame_body(device, camera, light, extent)
    }

    /// [`begin_frame`](Self::begin_frame) for a frame that **skins**: the same
    /// call with the skinning plan folded into it.
    ///
    /// It does four things in the one order that is correct, which is why it is
    /// a call and not a note in someone's docs:
    ///
    /// 1. rotates the instance ring, so the frame slot exists;
    /// 2. hands that slot and `ranges` to `skinning`, which validates them,
    ///    uploads the palettes and **moves the ping-pong** — the only place the
    ///    parity ever moves;
    /// 3. points every object placed by
    ///    [`add_skinned_instance`](Self::add_skinned_instance) at the half of its
    ///    region the parity now names;
    /// 4. uploads the instance delta, so those bases are the ones this frame
    ///    draws.
    ///
    /// Do those three and four in the other order and the objects carry the
    /// previous frame's half — a character posed one frame late, every frame,
    /// with nothing to report it. A caller never sees a parity or a table id, and
    /// so cannot get that wrong.
    ///
    /// Build `ranges` with [`SkinnedMesh::skin_range`], one per reserved region
    /// this frame animates. A frame with **no** skinned object still calls this
    /// with an empty slice — see [`Skinning::begin_frame`], whose slot would
    /// otherwise re-dispatch whichever frame last used it.
    ///
    /// [`add_skinned_passes`](Self::add_skinned_passes) is the other half, and
    /// the one that orders the dispatch before the draws.
    ///
    /// # Errors
    ///
    /// Whatever [`Skinning::begin_frame`] refuses — a joint index past its
    /// palette, a binding count that is not the region's vertex count, more than
    /// the pass was built for — and [`SkinningError::Hal`] for anything the seam
    /// refused, this renderer's own uniform and instance writes included.
    ///
    /// # Panics
    ///
    /// If `skinning` was not built with at least [`FRAMES_IN_FLIGHT`] frames:
    /// its rings are indexed by this renderer's frame slot, and
    /// [`Skinning::begin_frame`] refuses a slot it has no buffers for.
    pub fn begin_skinned_frame(
        &mut self,
        device: &dyn Device,
        skinning: &mut Skinning,
        ranges: &[SkinRange<'_>],
        camera: &Camera,
        light: &DirectionalLight,
        extent: (u32, u32),
    ) -> Result<(), SkinningError> {
        self.frame = self.instances.rotate();
        // An empty plan dispatches nothing — see [`Skinning::begin_frame`] — so
        // it leaves the vertex pool where it was, and the shadow atlas with it.
        self.frame_skins = !ranges.is_empty();
        skinning.begin_frame(device, self.frame, ranges)?;
        self.point_skinned_instances(skinning.parity());
        self.instances.flush(device)?;
        self.begin_frame_body(device, camera, light, extent)?;
        Ok(())
    }

    /// Whether this frame records the irradiance probes' two
    /// updater passes.
    ///
    /// The scene's own answer and the console's together: the volume decides
    /// whether the feature applies at all — see [`ProbeUpdate`], which is where
    /// the reason it is not an effect bit lives — and `r_probe_bounce` is the
    /// on/off pair a pricing run reads the two passes' cost off with everything
    /// else held still.
    ///
    /// **It is not the whole condition.** The map is cascade 0's own draws, so
    /// the pass is recorded only where that cascade is being drawn too — see
    /// `add_shadow_pass`, which is where the rest of it is.
    fn probe_update_runs(&self) -> bool {
        self.probe_update == ProbeUpdate::EveryFrame && rsm::enabled()
    }

    /// The six side-plane sets a point light's face culls test, or `None` for
    /// a light that is not a point — or with the face culls switched off, which
    /// is one cull against the light's box drawn into all six faces.
    ///
    /// `faces` are the light's face matrices in face order, the ones its tiles
    /// render through.
    fn point_face_planes(&self, light: &Light, faces: &[Mat4]) -> Option<crate::cull::FacePlanes> {
        if !self.point_face_culls || !matches!(light, Light::Point(_)) {
            return None;
        }
        let matrices: [Mat4; shadow::POINT_FACES] = faces.try_into().ok()?;
        Some(crate::cull::face_planes(&matrices))
    }

    /// Every punctual shadow face this frame draws into the punctual reflective
    /// shadow map, in the order the pass draws them and the producer table lists
    /// them.
    ///
    /// **One list for both halves of the updater**, and that is the point:
    /// `add_shadow_pass` sets a viewport from a face's
    /// [`tile`](PunctualFace::tile) and the gather reads that same rectangle out
    /// of the matching producer row, so a face the pass drew and a row the
    /// gather walked have to be the same face. Building the two from separate
    /// filters is two things that can drift, and the drift would be a light
    /// bouncing another light's map.
    ///
    /// **The occupied slots this frame redraws**, which is the same set
    /// `add_shadow_pass` gives the atlas: a face's transform is a shadow view's
    /// block and its draws are a shadow cull's, and
    /// [`Self::begin_frame_body`](Self::begin_frame) writes neither for a slot
    /// it is holding.
    ///
    /// # Every occupied tile, and no budget of its own
    ///
    /// The producers are exactly the atlas's occupied faces — up to
    /// [`shadow::LIGHT_SLOTS`] lights and [`shadow::LIGHT_TILES`] tiles between
    /// them — rather than the highest-ranked light or some smaller count.
    ///
    /// **Because the budget already exists and is spent.**
    /// [`shadow::Selection`] has ranked these lights by projected screen
    /// influence and handed out every tile there is; a second budget on top
    /// would rank the same lights again, differently, and produce a light that
    /// casts a shadow and lends no bounce. That is a difference no picture shows
    /// — the same argument [`Self::shadow_lights`] makes about a map's size —
    /// and it is the kind of quiet inconsistency the two halves of one light are
    /// worst placed to have.
    ///
    /// It is affordable at the extent that was chosen for it:
    /// `apps/lantern` lights seven faces, and
    /// [`PUNCTUAL_RSM_SIDE`](crcbl_shaders::probe_gather::PUNCTUAL_RSM_SIDE)
    /// carries the sweep that priced them.
    ///
    /// **Empty where shadows are off**, for that same reason — a punctual face
    /// *is* a shadow view. The sun's half is not, which is what
    /// `updater_drives_cascade_zero` exists for: switching shadows off keeps the
    /// sun's bounce and loses every punctual one, rather than switching the
    /// whole updater off with them.
    fn punctual_faces(&self) -> Vec<PunctualFace> {
        if !self.probe_update_runs() {
            return Vec::new();
        }
        // A frame with the shadows switched off draws no atlas, so no group of
        // it is *redrawn* — and `begin_frame_body`'s `updater_drives_cascade_zero`
        // branch has still written every one of these views and dispatched every
        // one of these culls, for this pass to draw through.
        let updater_drives = !self.frame_effects.contains(RenderEffects::SHADOWS);
        let mut faces = Vec::new();
        for (slot, held) in self.shadow_lights.slots().iter().enumerate() {
            let Some(held) = *held else {
                continue;
            };
            if !updater_drives && !self.shadow_group_redrawn[shadow_cull(slot)] {
                continue;
            }
            let Some(light) = self.extra_lights.get(held.light) else {
                continue;
            };
            // A spot draws face 0 alone and a point light all six, each through
            // its own matrix into its own tile — `shadow::tile_span` is the same
            // function `Selection` allocated the run with, so a face here and a
            // tile there cannot disagree about how many there are.
            for face in 0..shadow::tile_span(light) {
                let tile = rsm::punctual_tile(held.base + face);
                faces.push(PunctualFace {
                    view: shadow_view(slot, face),
                    cull: shadow_cull(slot),
                    face,
                    tile,
                    producer: producer_row(light, tile),
                });
            }
        }
        faces
    }

    /// Puts an object in the scene and returns the handle that names it.
    ///
    /// An instance in the pool **is** an object in the scene: the frame records
    /// a fixed number of draws and the cull pass decides which instances they
    /// walk, so adding one costs a slot in an array and not a command. It is
    /// drawn from the next [`ForwardRenderer::begin_frame`], which is what
    /// uploads it.
    ///
    /// # The index it lands at is not decoration
    ///
    /// `draw_gen.slang` keys topic 25's hysteresis state by the
    /// instance's **array index**, at `instance_index * group_stride`, and
    /// `mesh_cluster.slang`'s amplification stage reads the same address. So the
    /// record of which of a DAG's groups an object had expanded belongs to the
    /// *slot*, not to the object — and a slot that [`remove_instance`] freed is
    /// handed to the next `add_instance`, which inherits it. What that costs is
    /// one frame selected against a history that is not this object's, and the
    /// next frame's own judgement replaces it; it is never a wrong picture,
    /// because every group is judged afresh whatever the state said.
    ///
    /// That inheritance is inert while the scene holds **one** instance of a DAG
    /// mesh, which is every frame the engine has drawn so far — one instance's
    /// run has no previous occupant, and a flat mesh's
    /// [`MeshLevels`](level_select::MeshLevels) record names no groups at all, so
    /// nothing indexes the state for it. It stops being inert the moment an
    /// application places a second.
    ///
    /// [`remove_instance`]: ForwardRenderer::remove_instance
    ///
    /// # A DAG mesh needs a device that can choose a level
    ///
    /// One device shape cannot draw a [`Geometry::Dag`] mesh: a mesh stage with
    /// **no** amplification stage in front of it emits every cluster of the
    /// bucket, which for a DAG is every level at once — several overlapping
    /// copies of one surface. This does not refuse it, because it has no
    /// vocabulary for that refusal; a caller placing a DAG asks
    /// [`ForwardRenderer::selects_levels`] first, and places it only where that
    /// says yes. A flat mesh is unaffected on every path.
    ///
    /// # Errors
    ///
    /// [`InstancePoolError::PoolFull`] when the instance pool is full. It never
    /// grows — [`Capacities::instances`](crate::scene::Capacities::instances) is
    /// what a caller sizes it with.
    ///
    /// # Panics
    ///
    /// If [`InstanceDesc::mesh`] or [`InstanceDesc::material`] is past the end of
    /// the description this renderer was built from. Both are indices a caller
    /// wrote against a description it holds, so an out-of-range one is a mistake
    /// in the calling code rather than a condition the frame can be in — and the
    /// alternative is an object silently drawn as some other mesh, in some other
    /// colour.
    pub fn add_instance(
        &mut self,
        desc: &InstanceDesc,
    ) -> Result<InstanceHandle, InstancePoolError> {
        let instance = self.gpu_instance(desc);
        self.instances.insert(&instance)
    }

    /// Rewrites the object `handle` names — its mesh, its material and its
    /// transform, all three.
    ///
    /// A stale handle — one [`ForwardRenderer::remove_instance`] retired — writes
    /// nothing, rather than overwriting whatever took its slot.
    ///
    /// Takes effect at the next [`ForwardRenderer::begin_frame`], which uploads
    /// the element and nothing else: an object that did not move costs no
    /// transfer at all.
    ///
    /// # Panics
    ///
    /// On [`ForwardRenderer::add_instance`]'s terms, for the same reason.
    pub fn set_instance(&mut self, handle: InstanceHandle, desc: &InstanceDesc) {
        let mut instance = self.gpu_instance(desc);
        instance.flags |= self.kept_flags(handle);
        self.instances.set(handle, &instance);
    }

    /// The bits of `handle`'s record a rewrite of it keeps: its hidden views
    /// and whether it casts — see [`ForwardRenderer::set_instance_views`] and
    /// [`ForwardRenderer::set_instance_casts_shadow`]. Zero for a stale
    /// handle, whose rewrite writes nothing anyway.
    fn kept_flags(&self, handle: InstanceHandle) -> u32 {
        self.instances.get(handle).map_or(0, |record| {
            record.flags
                & (mesh::GpuInstance::HIDDEN_VIEWS_MASK | mesh::GpuInstance::CASTS_NO_SHADOW)
        })
    }

    /// Sets whether `handle` casts a shadow. Every instance starts casting.
    ///
    /// **Every shadow map and nothing else**: an instance that casts none is
    /// rejected by the cull of the sun's cascades and of every shadowed light,
    /// on every geometry path, so it lands in no tile of the atlas — and in no
    /// reflective shadow map, which draws those same culls' survivors, so it
    /// bounces no light into the probes either. Every camera still draws it,
    /// and it still receives the shadows the rest of the scene casts.
    ///
    /// What a model drawn for an icon wants, placed where the scene's sun can
    /// see it: see [`ViewBackground::Transparent`] and
    /// [`set_instance_views`](Self::set_instance_views).
    ///
    /// A change redraws every shadow map whose cull the instance could be kept
    /// by, because it is a write [`InstancePool::take_written`] names. Not a
    /// move, on
    /// [`set_instance_views`](Self::set_instance_views)' terms, and a stale
    /// handle is ignored.
    pub fn set_instance_casts_shadow(&mut self, handle: InstanceHandle, casts: bool) {
        if let Some(record) = self.instances.get(handle) {
            let flags = if casts {
                record.flags & !mesh::GpuInstance::CASTS_NO_SHADOW
            } else {
                record.flags | mesh::GpuInstance::CASTS_NO_SHADOW
            };
            self.instances.set_flags(handle, flags);
        }
    }

    /// Whether `handle` casts a shadow, or `None` for a stale handle.
    #[must_use]
    pub fn instance_casts_shadow(&self, handle: InstanceHandle) -> Option<bool> {
        self.instances
            .get(handle)
            .map(|record| record.flags & mesh::GpuInstance::CASTS_NO_SHADOW == 0)
    }

    /// Takes the object `handle` names back out of the scene, freeing its slot.
    ///
    /// **A removal is a cleared live bit, not a skipped draw**, because the frame
    /// no longer records a draw per object: `cull.slang` asks whether an instance
    /// is live before it reads anything else, so removing an object and culling
    /// it off screen take the same path out of the frame. An instance left in the
    /// pool would be drawn wherever its transform put it.
    ///
    /// A stale handle removes nothing. Takes effect at the next
    /// [`ForwardRenderer::begin_frame`], on
    /// [`ForwardRenderer::set_instance`]'s terms.
    pub fn remove_instance(&mut self, handle: InstanceHandle) {
        self.instances.remove(handle);
    }

    /// Captures a visibility map for every probe, from the static geometry
    /// standing in the scene right now.
    ///
    /// The probe visibility rung: each probe records how far
    /// away the nearest surface is in every direction, and `mesh.slang`'s
    /// `probe_irradiance` then weighs each of a fragment's eight probes by
    /// whether it can *see* that fragment — so a probe on the far side of a wall
    /// contributes nothing and a room stops lighting the room next door.
    /// This crate's own `probe_capture` module is the pass, `probe_visibility`
    /// is the geometry it draws, and [`crcbl_shaders::probe_visibility`] is the
    /// format.
    ///
    /// # Call it once, after the scene's walls are placed
    ///
    /// **A description carries no instances** — [`SceneDesc`] is meshes,
    /// materials, a page and the probe rows, and the objects arrive afterwards
    /// through [`ForwardRenderer::add_instance`] — so there is nothing for a
    /// capture inside [`ForwardRenderer::with_scene`] to be about. This is the
    /// call that has the room in it, and an application makes it once its static
    /// geometry is placed.
    ///
    /// A caller that never makes it draws exactly the frame this renderer drew
    /// before the maps existed: every group names the one-texel placeholder,
    /// which no surface is further away than, and every probe keeps all of its
    /// weight.
    ///
    /// **It is a capture of geometry and not a bake of light.** Nothing about
    /// the lights is recorded, every one of them still moves, and the rows the
    /// probes carry are untouched.
    ///
    /// # What it sees, and what it does not
    ///
    /// Every instance live in the pool when it is called, at the transform it
    /// then has, rasterised from its mesh's level-0 triangles into six 90°
    /// faces per probe. Objects that move
    /// afterwards keep the occlusion they had here, which is the accepted limit
    /// this technique has everywhere it is used — a probe volume is about the
    /// walls. Recapturing after a wall moves is this call again.
    ///
    /// **The device must be idle.** The previous capture's image is released
    /// here, and a frame in flight may still be reading it.
    ///
    /// # Errors
    ///
    /// [`HalError`] from the capture. The previous maps are kept on the failing
    /// path, so a renderer that has captured once and then failed goes on
    /// drawing with what it had.
    pub fn capture_probe_visibility(
        &mut self,
        device: &dyn Device,
        queue: QueueHandle,
    ) -> Result<(), HalError> {
        let placed: Vec<crate::probe_visibility::Occluder> = self
            .instances
            .live()
            .into_iter()
            .map(|record| crate::probe_visibility::Occluder {
                mesh: record.mesh,
                transform: Mat4::from_cols_array(&record.transform),
            })
            .collect();
        let Some(uploaded) = crate::probe_capture::capture(
            device,
            queue,
            &self.probe_volume,
            &self.probe_occluders,
            &placed,
        )?
        else {
            // No probes, or nothing placed for a map to be about. Leaving the
            // placeholder bound is the honest answer, and it is what a scene
            // with no probes has always read.
            return Ok(());
        };
        // The cached groups name the view this replaces, so they go before it
        // does — a bind group outliving the image it names is a validation
        // error on every backend that checks, and a use-after-free on the ones
        // that do not.
        for slot in &mut self.primary.screen_channel_groups {
            if let Some((_, stale)) = slot.take() {
                device.destroy_bind_group(stale);
            }
        }
        if let Some(previous) = self.probe_visibility.replace(uploaded) {
            previous.destroy(device);
        }
        Ok(())
    }

    /// Re-centres the irradiance clipmap on `point` by whole probe steps, and
    /// captures the probes the step exposed.
    ///
    /// The irradiance probes' scrolling: each level moves a whole
    /// number of its own probe spacings towards `point`, so the probes that stay
    /// inside it stand exactly where they stood and go on being addressed at the
    /// rows they already had — and only the slabs the step brought in are
    /// captured. Answers how many rows that was, which is **zero for the
    /// ordinary frame**: the point has to travel half a probe spacing before the
    /// nearest whole step changes at all.
    ///
    /// [`ProbeVolume::follow`](crcbl_shaders::probe::ProbeVolume::follow) is the
    /// rule and `exposed` beside it is the invalidation; this is the two of them
    /// plus the device work they imply — the visibility maps of the exposed
    /// rows, and the position table the reflective-shadow-map gather reads.
    ///
    /// # A volume authored to cover its whole world does not move
    ///
    /// The steps are the ones that centre a level on `point`, and a caller whose
    /// volume is already the world it is in wants none of them — so a caller
    /// passes the point it wants the *centre* at rather than the camera outright
    /// when the two differ. `apps/lantern` and `apps/shard` are that case and
    /// their own modules say so.
    ///
    /// # A step stalls, and a frame that does not step costs a comparison
    ///
    /// The recapture is [`ForwardRenderer::capture_probe_visibility`]'s pass
    /// over fewer rows, and it waits on [`Device::wait_idle`] exactly as that
    /// one does — so a step drains the device before it rewrites anything and
    /// leaves it drained. That is a stall, and it is why the probe records price a step
    /// separately from a frame. A call that steps nothing returns before the
    /// wait, so the ordinary frame pays a rounding per level and per axis and
    /// nothing else.
    ///
    /// It may therefore be called from a frame loop, but **not after**
    /// [`ForwardRenderer::begin_frame`] has been called for the frame being
    /// recorded: the header it moves is the one that frame's uniform block has
    /// already been written from.
    ///
    /// A renderer that has never captured re-centres the header and captures
    /// nothing: there is no image to write slabs into, every group still names
    /// the placeholder, and the first
    /// [`ForwardRenderer::capture_probe_visibility`] covers the scrolled volume
    /// whole.
    ///
    /// # It moves the geometry and not the light
    ///
    /// What a step re-captures is the *visibility* of the probes it exposed,
    /// which is what the maps are about. The **rows** are not touched, so under
    /// [`ProbeUpdate::Authored`] a probe
    /// that a step brought in keeps the irradiance the probe that left had —
    /// authored for somewhere else. A volume that scrolls therefore wants
    /// [`ProbeUpdate::EveryFrame`], whose
    /// gather refills every row from the scene each frame and has no such gap;
    /// `docs/backlog.md` carries what an authored one would need instead.
    ///
    /// # Errors
    ///
    /// [`HalError`] from the recapture or from the position rewrite. The volume
    /// keeps the steps it had on either failing path, so a renderer that could
    /// not capture a slab does not go on drawing with rows about somewhere else.
    pub fn follow_probe_volume(
        &mut self,
        device: &dyn Device,
        queue: QueueHandle,
        point: [f32; 3],
    ) -> Result<u32, HalError> {
        let mut moved = self.probe_volume;
        let rows = moved.follow(point);
        if rows.is_empty() && moved.steps == self.probe_volume.steps {
            return Ok(0);
        }
        // **Before anything is written**, so a caller may make this call from
        // its frame loop: the layers the recapture rewrites and the position
        // table beside them are read by whatever frames are still in flight, and
        // neither is a ring. A frame that does not step never reaches this line,
        // which is what keeps the ordinary frame free of it.
        device.wait_idle()?;
        if let Some(captured) = &self.probe_visibility {
            let placed: Vec<crate::probe_visibility::Occluder> = self
                .instances
                .live()
                .into_iter()
                .map(|record| crate::probe_visibility::Occluder {
                    mesh: record.mesh,
                    transform: Mat4::from_cols_array(&record.transform),
                })
                .collect();
            crate::probe_capture::recapture(
                device,
                queue,
                &moved,
                &self.probe_occluders,
                &placed,
                &rows,
                captured.image,
            )?;
        }
        // After the capture, so a volume whose slabs could not be drawn keeps
        // the header its maps are about.
        if let Some(gather) = &self.probe_gather {
            gather.rewrite_positions(device, &moved)?;
        }
        self.probe_volume = moved;
        Ok(u32::try_from(rows.len()).unwrap_or(u32::MAX))
    }

    /// Where the irradiance clipmap stands right now — the header the frame
    /// block carries, [`ForwardRenderer::follow_probe_volume`]'s scroll
    /// included.
    #[must_use]
    pub const fn probe_volume(&self) -> crcbl_shaders::probe::ProbeVolume {
        self.probe_volume
    }

    /// `draws` split by the **whole** material mode, each partition under the
    /// depth-only pipeline that honours it — what the depth prepass and every
    /// shadow view record instead of one call list under one pipeline.
    ///
    /// Four pipelines for [`DEPTH_MODES`]' four values, which is what makes the
    /// split total: the opaque buckets are drawn with
    /// [`shadow_pipeline`](Self::shadow_pipeline) — `depthVertexMain` and no
    /// fragment stage — the masked ones with
    /// [`depth_masked_pipeline`](Self::depth_masked_pipeline), which can
    /// `discard`, and each of those has a [`CullMode::None`] twin for the
    /// buckets whose material is double-sided. A scene with one cutout in it
    /// pays a fragment stage for that mesh's draws and for no others; before
    /// this it paid for the whole frame, which on lavapipe roughly doubled the
    /// prepass and added two thirds to the shadow pass.
    ///
    /// **Both depth passes and not just the atlas.** A double-sided plate whose
    /// back face the prepass culled writes no depth there, so the colour pass's
    /// `GreaterOrEqual` test against it rejects the fragment and the surface is
    /// missing from the frame; and a cascade that culled it casts no shadow.
    fn depth_partitions(&self, draws: &BucketDraws) -> Vec<BucketDraws> {
        self.partitions(
            draws,
            mesh::GpuMaterial::MODE_MASK,
            &[
                (DEPTH_MODES[0], self.shadow_pipeline.single),
                (DEPTH_MODES[1], self.depth_masked_pipeline.single),
                (DEPTH_MODES[2], self.shadow_pipeline.double),
                (DEPTH_MODES[3], self.depth_masked_pipeline.double),
            ],
        )
    }

    /// `draws` split by the material's **side** alone, each partition under the
    /// matching half of `pipelines` — what the colour pass and the two
    /// reflective shadow maps record.
    ///
    /// Two partitions where [`depth_partitions`](Self::depth_partitions) has
    /// four, and the difference is the whole of what these passes do not care
    /// about: their pipelines carry a fragment stage either way and cut the
    /// alpha mask inside it, so a masked bucket and an opaque one are the same
    /// draw here. What they cannot express inside the stage is the cull mode.
    fn sided_partitions(&self, draws: &BucketDraws, pipelines: SidedPipelines) -> Vec<BucketDraws> {
        self.partitions(
            draws,
            mesh::GpuMaterial::DOUBLE_SIDED,
            &[
                (0, pipelines.single),
                (mesh::GpuMaterial::DOUBLE_SIDED, pipelines.double),
            ],
        )
    }

    /// Resolves a description's mesh and material indices into the table ids the
    /// GPU reads.
    ///
    /// The whole record every time, because [`InstancePool::set`] writes the
    /// whole record: an instance that lost either id would name entry 0 of that
    /// table, which is a mesh and a material rather than an absence.
    fn gpu_instance(&self, desc: &InstanceDesc) -> mesh::GpuInstance {
        mesh::GpuInstance {
            transform: desc.transform.to_cols_array(),
            mesh: self.mesh_ids[desc.mesh],
            material: self.material_ids[desc.material],
            flags: self.material_mode_bits(desc.material),
            ..mesh::GpuInstance::default()
        }
    }

    /// The material mode of description material `material`, in the bits an
    /// instance record carries it in.
    ///
    /// **Read out of the table rather than out of the description**, because the
    /// table is what a `set` would move and the row is what the shader shades
    /// through. It is the other half of the record's routing key: `draw_gen`
    /// buckets an instance by [`mesh`](mesh::GpuInstance::mesh) and by this,
    /// which is how a masked material costs a fragment stage in the depth passes
    /// for its own mesh alone.
    ///
    /// The mode is captured **here**, when the record is written — see
    /// [`GpuInstance::MATERIAL_MODE_SHIFT`](mesh::GpuInstance::MATERIAL_MODE_SHIFT)
    /// for what that means for a material rewritten afterwards.
    fn material_mode_bits(&self, material: usize) -> u32 {
        self.materials.mode(self.material_ids[material]) << mesh::GpuInstance::MATERIAL_MODE_SHIFT
    }

    // --- skinning: reserving the region, placing the object, ordering the
    // dispatch ---

    /// The vertex pool every mesh here is resident in — what
    /// [`SkinningDesc::vertices`](crate::skinning::SkinningDesc::vertices)
    /// takes.
    ///
    /// The skinning pass reads a bind pose out of this buffer and writes the
    /// deformed vertices back into another run of it, which is what makes a
    /// skinned draw an ordinary draw. It must be *this* pool's buffer: a
    /// [`Skinning`] built against any other writes vertices no draw here can
    /// reach.
    #[must_use]
    pub const fn vertex_buffer(&self) -> BufferHandle {
        self.pool.vertex_buffer()
    }

    /// Where that pool's **attribute** region begins, in words — what
    /// [`SkinningDesc::attribute_base`](crate::skinning::SkinningDesc::attribute_base)
    /// takes.
    ///
    /// The buffer holds two streams, so a pass that writes it needs the
    /// boundary as well as the handle; a [`Skinning`] built with the wrong one
    /// writes a mesh's attributes over another mesh's positions. See
    /// [`MeshPool::attribute_base`](crate::MeshPool::attribute_base).
    #[must_use]
    pub const fn attribute_base(&self) -> u32 {
        self.pool.attribute_base()
    }

    /// Reserves a skinned region for description mesh `mesh`.
    ///
    /// The whole of what a caller needs to skin something, in one value: hand
    /// [`SkinnedMesh::skin_range`] a palette and a set of bindings to get the
    /// frame's [`SkinRange`], hand the result to
    /// [`begin_skinned_frame`](Self::begin_skinned_frame), and place it with
    /// [`add_skinned_instance`](Self::add_skinned_instance). The bases and the
    /// parity never have to be spelled by the caller at all — see
    /// [`crate::skinning::SkinnedMesh`], where the ping-pong lives.
    ///
    /// **The mesh keeps its own entry and the region takes none**, so the same
    /// description mesh can be drawn skinned through this and in its bind pose
    /// through [`add_instance`](Self::add_instance) in the same frame, both
    /// resolving through the one table entry it already had.
    ///
    /// Give it back with [`release_skinned`](Self::release_skinned).
    ///
    /// # Errors
    ///
    /// Whatever [`SkinnedMesh::reserve`] refuses: a vertex pool with no room for
    /// both halves. **Two vertex runs per skinned primitive** is what a scene's
    /// [`Capacities`](crate::scene::Capacities) has to have been sized for.
    ///
    /// # Panics
    ///
    /// If `mesh` is past the end of the description this renderer was built
    /// from, on [`add_instance`](Self::add_instance)'s terms — and if it names a
    /// [`Geometry::Dag`], which cannot be drawn out of a skinned region at all.
    /// A DAG is refused rather than skinned wrongly: its coarser levels are
    /// separate vertex runs no dispatch writes, so a cut that descended past
    /// level 0 would draw whatever the pool happened to be holding there.
    pub fn reserve_skinned(&mut self, mesh: usize) -> Result<SkinnedMesh, MeshPoolError> {
        let source = self.skinnable_meshes[mesh].unwrap_or_else(|| {
            panic!(
                "description mesh {mesh} is a Geometry::Dag, whose coarser levels are vertex \
                 runs no skinning dispatch writes; only a flat mesh can be skinned"
            )
        });
        SkinnedMesh::reserve(&mut self.pool, source)
    }

    /// Gives `skinned`'s region back to the vertex pool.
    ///
    /// The device must not still be drawing it: this records no barrier, on
    /// [`SkinnedMesh::release`]'s terms. Objects placed through it are **not**
    /// removed — [`remove_instance`](Self::remove_instance) is what does that,
    /// and an instance left behind goes on drawing its source mesh's geometry
    /// out of vertices the pool has handed back. Remove the objects first.
    pub fn release_skinned(&mut self, skinned: SkinnedMesh) {
        skinned.release(&mut self.pool);
    }

    /// Places a skinned object in the scene.
    ///
    /// [`add_instance`](Self::add_instance) with a reserved region in place of a
    /// description mesh. The renderer keeps the object in a list of its own and
    /// **re-points it every [`begin_skinned_frame`](Self::begin_skinned_frame)**
    /// at the half of the region that frame's dispatch fills, so the parity is
    /// never something a caller writes.
    ///
    /// A skinned object driven by plain [`begin_frame`](Self::begin_frame) is
    /// therefore left pointing wherever it last was, which after the first frame
    /// is the pose of the frame before — the reason the two entry points are
    /// separate calls rather than a flag.
    ///
    /// # Errors
    ///
    /// [`InstancePoolError::PoolFull`], on
    /// [`add_instance`](Self::add_instance)'s terms.
    ///
    /// # Panics
    ///
    /// If [`SkinnedInstanceDesc::material`] is past the end of the description
    /// this renderer was built from, on
    /// [`add_instance`](Self::add_instance)'s terms.
    pub fn add_skinned_instance(
        &mut self,
        desc: &SkinnedInstanceDesc<'_>,
    ) -> Result<InstanceHandle, InstancePoolError> {
        // Parity zero, and it never reaches the GPU as such: the instance pool
        // uploads by delta at `begin_skinned_frame`, which re-points every entry
        // of the list below before it flushes. What this writes is the rest of
        // the record.
        let instance = self.skinned_gpu_instance(desc, 0);
        let handle = self.instances.insert(&instance)?;
        self.skinned_instances.push(SkinnedInstance {
            handle,
            bases: skinned_bases(desc.mesh),
            pointed: false,
        });
        Ok(handle)
    }

    /// Rewrites the skinned object `handle` names — its region, its material and
    /// its transform.
    ///
    /// [`set_instance`](Self::set_instance) for an object placed by
    /// [`add_skinned_instance`](Self::add_skinned_instance), and the call a
    /// character's transform changes through. A stale handle writes nothing.
    ///
    /// Passing a handle this renderer has never seen skinned adopts it: the
    /// object joins the re-pointed list from here on. That is what lets a caller
    /// swap a bind-pose instance over to a region without removing and replacing
    /// it.
    ///
    /// # Panics
    ///
    /// On [`add_skinned_instance`](Self::add_skinned_instance)'s terms.
    pub fn set_skinned_instance(&mut self, handle: InstanceHandle, desc: &SkinnedInstanceDesc<'_>) {
        let mut instance = self.skinned_gpu_instance(desc, 0);
        instance.flags |= self.kept_flags(handle);
        if !self.instances.set(handle, &instance) {
            return;
        }
        let bases = skinned_bases(desc.mesh);
        match self
            .skinned_instances
            .iter_mut()
            .find(|entry| entry.handle == handle)
        {
            // **A different region is a fresh entry.** The half this object has
            // never been drawn out of holds whatever its reservation came with,
            // so the next pointing owes it rest rather than a previous
            // deformation — see [`SkinnedInstance::pointed`]. The pair of bases
            // is what "different" means here: two calls naming one region give
            // the same two runs, so rewriting an object's material or transform
            // is not a change of region.
            Some(entry) => {
                entry.pointed &= entry.bases == bases;
                entry.bases = bases;
            }
            None => self.skinned_instances.push(SkinnedInstance {
                handle,
                bases,
                pointed: false,
            }),
        }
    }

    /// A skinned object's record, at one parity — [`gpu_instance`](Self::gpu_instance)
    /// with the region's base vertex carried in the record and the bit that says
    /// to read it.
    ///
    /// The mesh id is the **source** mesh's, not a second entry's, so the bucket
    /// this instance is scattered into, the levels it selects through and the
    /// box it is culled against are the ones the undeformed mesh already had.
    fn skinned_gpu_instance(
        &self,
        desc: &SkinnedInstanceDesc<'_>,
        parity: u32,
    ) -> mesh::GpuInstance {
        let base_vertex = desc.mesh.region().base(parity);
        mesh::GpuInstance {
            transform: desc.transform.to_cols_array(),
            mesh: desc.mesh.mesh_id(),
            material: self.material_ids[desc.material],
            // The override bit **and** the material mode: a skinned instance is
            // routed by the same key as a rigid one, so a skinned cutout lands
            // in its mesh's masked bucket rather than in the opaque twin.
            flags: mesh::GpuInstance::BASE_VERTEX_OVERRIDE | self.material_mode_bits(desc.material),
            base_vertex,
            // At rest, which is what a record this call writes has to be: the
            // object has not been drawn out of this region yet, so the other
            // half holds whatever its reservation came with. A frame that runs
            // [`point_skinned_instances`](Self::point_skinned_instances) is
            // what starts pointing this at the half before.
            previous_base_vertex: base_vertex,
            ..mesh::GpuInstance::default()
        }
    }

    /// Points every skinned object at the half of its region a frame of this
    /// parity fills **and at the half the frame before it filled**, and forgets
    /// the ones whose instance has gone.
    ///
    /// Called between the instance ring's rotation and its upload, which is the
    /// whole reason those two are separate calls — see
    /// [`InstancePool::rotate`](crate::instance_pool::InstancePool::rotate).
    ///
    /// The second base is what a skinned fragment's motion vector is subtracted
    /// against — see
    /// [`GpuInstance::previous_base_vertex`](mesh::GpuInstance::previous_base_vertex).
    /// **A region this frame's `ranges` left out was not skinned this frame**,
    /// so the half this points at as the current one already holds an earlier
    /// frame's pose. That is pre-existing — it is what a caller driving a
    /// skinned object through plain [`begin_frame`](Self::begin_frame) gets, and
    /// it predates this second base — and the previous half is then no worse off
    /// than the current one.
    fn point_skinned_instances(&mut self, parity: u32) {
        let Self {
            instances,
            skinned_instances,
            ..
        } = self;
        skinned_instances.retain_mut(|entry| {
            // `SkinnedRegion::base`'s indexing and `SkinnedRegion::previous_base`'s,
            // applied to the entry's own copy of the pair — see
            // [`SkinnedInstance::bases`].
            let base_vertex = entry.bases[(parity & 1) as usize];
            let previous_base_vertex = if entry.pointed {
                entry.bases[((parity ^ 1) & 1) as usize]
            } else {
                // Nothing has been written into the other half for this object,
                // so it is put at rest — see [`SkinnedInstance::pointed`].
                base_vertex
            };
            entry.pointed = true;
            // The two bases and nothing else: the transform, the material and
            // the mesh the caller last set survive, and so does the transform
            // the record moved *from* — which
            // [`InstancePool::set`](crate::instance_pool::InstancePool::set)
            // would overwrite with this frame's, leaving a skinned object's own
            // travel out of the motion target. See
            // [`InstancePool::set_bases`](crate::instance_pool::InstancePool::set_bases).
            // Its answer is also what says the instance is still there, so an
            // object a caller removed drops out of the list here.
            instances.set_bases(entry.handle, base_vertex, previous_base_vertex)
        });
    }

    /// The lights in the frame **beside the sun**, which
    /// [`begin_frame`](Self::begin_frame) still takes on its own.
    ///
    /// Topic 44's light list, minus its first row: the
    /// sun is row 0 of every frame's list and the ones set here follow it, in
    /// the order given. That order is the one a froxel keeps a prefix of when it
    /// runs out of budget — see [`ForwardRenderer::light_capacity`] and the
    /// overflow counter beside it — so it is a caller's lever and not an
    /// accident.
    ///
    /// The sun keeps a parameter of its own because it is the light that owns
    /// the ambient term and the shadow cascades, neither of which a [`Light`]
    /// has. What it stopped being is a special case in the *shader*, which is
    /// what the list bought.
    ///
    /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
    /// what uploads the rows.
    ///
    /// # Panics
    ///
    /// If there are more lights than [`ForwardRenderer::light_capacity`] leaves
    /// room for once the sun has its row. Refused rather than truncated: a light
    /// missing from the list is missing from every froxel, and **no counter in
    /// the frame would report it** — the overflow counter counts what a froxel's
    /// budget refused, which is a different number.
    pub fn set_lights(&mut self, lights: &[Light]) {
        assert!(
            lights.len() < self.primary.lights.capacity() as usize,
            "{} lights beside the sun, in a list of {}",
            lights.len(),
            self.primary.lights.capacity()
        );
        self.extra_lights.clear();
        self.extra_lights.extend_from_slice(lights);
    }

    /// Rows the light list holds, the sun's included.
    #[must_use]
    pub const fn light_capacity(&self) -> u32 {
        self.primary.lights.capacity()
    }

    /// This frame's froxel grid, as [`begin_frame`](Self::begin_frame) sized it
    /// from the viewport and the camera.
    ///
    /// Exposed for the reason [`lod_params`](Self::lod_params) is: a test that
    /// wants to know which froxel a point was shaded out of has to use the grid
    /// the frame really used, and re-deriving it would be a second copy of the
    /// arithmetic rather than a reading of the first.
    #[must_use]
    pub const fn grid(&self) -> Grid {
        self.primary.grid
    }

    /// `frame`'s froxel grid buffer, for a test copying out what the clustering
    /// pass decided.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    #[must_use]
    pub fn light_grid_buffer(&self, frame: usize) -> BufferHandle {
        self.primary.lights.grid(frame)
    }

    /// The pixel budget the descent compares a group's projected error against.
    ///
    /// One pixel until this is called — see the constant this crate keeps it
    /// in. Larger is coarser: a group
    /// projecting *over* the budget is expanded and its children are drawn, so
    /// raising it stops the descent higher up the DAG.
    ///
    /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
    /// what writes it into the frame block.
    pub const fn set_lod_error_budget(&mut self, budget: f32) {
        self.lod_error_budget = budget;
    }

    /// The budget this renderer selects under unless
    /// [`set_lod_error_budget`](Self::set_lod_error_budget) says otherwise, and
    /// the ratio the hold budget sits at below whichever one is in force.
    ///
    /// Public because a test that drives a camera across a level boundary has to
    /// know where the boundary is, and where it is depends on both numbers —
    /// re-deriving either in the test would be a second copy to drift.
    pub const LOD_ERROR_BUDGET: f32 = LOD_ERROR_BUDGET;
    /// See [`LOD_ERROR_BUDGET`](Self::LOD_ERROR_BUDGET).
    pub const LOD_HOLD_RATIO: f32 = LOD_HOLD_RATIO;

    /// How far below the budget an already-expanded group is held before it
    /// collapses again — topic 25's hysteresis, as a fraction of
    /// the budget.
    ///
    /// [`LOD_HOLD_RATIO`](Self::LOD_HOLD_RATIO) until this is called. **A ratio
    /// of one removes the band**, which makes the two budgets equal and the
    /// previous frame's answer stop mattering — the setting a test uses to show
    /// that the band is what stops a drifting camera flickering, on the same
    /// code path and one number apart.
    ///
    /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
    /// what writes it into the two params blocks.
    pub const fn set_lod_hold_ratio(&mut self, ratio: f32) {
        self.lod_hold_ratio = ratio;
    }

    /// What the last [`begin_frame`](Self::begin_frame) handed the descent:
    /// pixels per unit at one unit from the eye, and the pixel budget.
    ///
    /// Pixels per unit at one unit from the eye, the budget an unexpanded group
    /// starts expanding over, and the budget an expanded one is held down to.
    ///
    /// What `ClusterDag::expand` takes, so a caller reading
    /// [`cluster_selection`](Self::cluster_selection) back can run the same
    /// frames host-side rather than re-deriving the numbers from the camera and
    /// hoping they agree. `[0.0, 0.0, 0.0]` before the first frame.
    #[must_use]
    pub const fn lod_params(&self) -> [f32; 3] {
        self.primary.lod_params
    }

    /// The same three numbers the **shadow cascades** selected under, which is
    /// [`lod_params`](Self::lod_params) with both budgets multiplied by
    /// [`SHADOW_LOD_BIAS`] — topic 25's shadow LOD bias, as the
    /// parameters it actually reaches the GPU as.
    ///
    /// The pixels-per-unit is the camera's, unchanged, because the cascades
    /// select from the camera's eye at the camera's scale; see
    /// [`begin_frame`](Self::begin_frame). `[0.0, 0.0, 0.0]` before the first
    /// frame.
    #[must_use]
    pub const fn shadow_lod_params(&self) -> [f32; 3] {
        self.shadow_lod_params
    }

    /// Where description mesh `mesh`'s clusters are in the cluster pool — every
    /// level of it, as one run — or `None` off the mesh path, where there is no
    /// cluster pool at all.
    ///
    /// The base a reader adds a `(level, cluster)` to in order to index
    /// [`cluster_selection`](Self::cluster_selection): the levels are laid down
    /// finest first and contiguously, so level `d` cluster `c` is at
    /// `base + (clusters of levels below d) + c`. A flat mesh is one level, so
    /// its run is its clusters and `c` indexes it directly.
    ///
    /// # Panics
    ///
    /// If `mesh` is past the end of the description this renderer was built
    /// from, on [`add_instance`](Self::add_instance)'s terms.
    #[must_use]
    pub fn cluster_range(&self, mesh: usize) -> Option<ClusterRange> {
        (!self.mesh_clusters.is_empty()).then(|| self.mesh_clusters[mesh])
    }

    /// The buffer `frame`'s amplification stage recorded its chosen cut into:
    /// one `u32` per resident cluster, `1` where the cluster was drawn.
    ///
    /// `None` where there is no amplification stage, which is every device that
    /// reports no [`Features::TASK_SHADER`] and every non-mesh geometry path.
    ///
    /// **This is topic 25's observable and nothing in the frame
    /// reads it.** A frame whose every cluster came from one level is a
    /// plausible picture and matches any golden blessed from it, so a golden
    /// cannot show per-cluster selection happening at all; this can. It is
    /// `TRANSFER_SRC`, and copying it out is the caller's to record.
    ///
    /// [`Features::TASK_SHADER`]: crcbl_hal::Features::TASK_SHADER
    #[must_use]
    pub fn cluster_selection(&self, frame: usize) -> Option<BufferHandle> {
        self.primary.cluster_selection.get(frame).copied()
    }

    /// The same, for `cascade`'s shadow pass: the cut that cascade's
    /// amplification stage chose this frame.
    ///
    /// **The shadow LOD bias' observable.** A budget the cascades merely *were
    /// passed* is a parameter; the cut they reached under it is the behaviour,
    /// and this is the only thing that carries it out of a frame — the colour
    /// pass overwrites [`cluster_selection`](Self::cluster_selection) after the
    /// cascades have run. Indexed and read exactly as that buffer is, through
    /// [`cluster_range`](Self::cluster_range).
    ///
    /// `None` where there is no amplification stage, and where `cascade` is not
    /// one of [`shadow::CASCADES`].
    #[must_use]
    pub fn shadow_selection(&self, frame: usize, cascade: usize) -> Option<BufferHandle> {
        self.shadow_selection
            .get(frame)
            .and_then(|cascades| cascades.get(cascade))
            .copied()
    }

    /// The buckets description mesh `mesh`'s levels draw through, finest first —
    /// element `d` is level `d`'s bucket, and it is empty on the mesh path.
    ///
    /// **This is the uniform cut's observable**, and it is the indirect
    /// arguments rather than a buffer of its own: `draw_gen.slang` scatters an
    /// instance into the bucket for the level it selected, so exactly one of
    /// these buckets comes out of a frame with a non-zero instance count and
    /// which one it is *is* the chosen level. A reader takes
    /// [`DrawGen::args_offset`](crate::draw_gen::DrawGen::args_offset) of each
    /// and looks at
    /// [`DrawIndexedArgs::instance_count`](crcbl_shaders::draw_gen::DrawIndexedArgs::instance_count).
    ///
    /// Empty on [`GeometryPath::MeshShader`], where a mesh is one bucket and the
    /// level is chosen per cluster instead — see
    /// [`cluster_selection`](Self::cluster_selection), which is that path's
    /// observable.
    ///
    /// **These are the buckets of the scene's first material mode** — `OPAQUE`
    /// in any scene that has an opaque material, since the table is every
    /// mesh's levels once per mode the scene holds, mode by mode in
    /// `DEPTH_MODES` order. An instance of another mode selects the same level
    /// and lands in that level's bucket in its own mode's run, which this does
    /// not name; every scene in this tree that reads this accessor is all
    /// opaque, so "exactly one of these has a non-zero instance count" holds for
    /// them as it always did.
    ///
    /// # Panics
    ///
    /// If `mesh` is past the end of the description this renderer was built
    /// from, on [`add_instance`](Self::add_instance)'s terms.
    #[must_use]
    pub fn level_buckets(&self, mesh: usize) -> &[u32] {
        if self.mesh_level_buckets.is_empty() {
            return &[];
        }
        &self.mesh_level_buckets[mesh]
    }

    /// `frame`'s indirect draw arguments, [`crcbl_shaders::draw_gen::DRAW_ARGS_SIZE`]
    /// bytes per bucket — what a reader of
    /// [`level_buckets`](Self::level_buckets) copies out.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this renderer was built with.
    #[must_use]
    pub fn draw_args(&self, frame: usize) -> BufferHandle {
        self.primary.draws.args(frame)
    }

    /// `frame`'s survivor list for the primary camera and the culling
    /// statistics beside it — `cull.slang`'s entries, tags and all, in the first
    /// [`DrawGen::visible_capacity`](crate::DrawGen::visible_capacity) words of
    /// the first buffer, and their count in word
    /// [`INSTANCE_SURVIVOR_WORD`](crcbl_shaders::cull::INSTANCE_SURVIVOR_WORD)
    /// of the second — for a test holding the GPU's occlusion verdicts against
    /// [`crate::cull`]'s oracle. The first buffer holds the routes and runs
    /// behind the list; see [`crate::draw_gen`].
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this renderer was built with.
    #[must_use]
    pub fn camera_cull_buffers(&self, frame: usize) -> (BufferHandle, BufferHandle) {
        (
            self.primary.draws.visible(frame),
            self.primary.draws.visible_count(frame),
        )
    }

    /// What the primary camera's cull reads, as the oracle in [`crate::cull`]
    /// takes it: every instance slot the pool has handed out, and the whole mesh
    /// table — both decoded from the host's own copies of what was uploaded.
    #[must_use]
    pub fn cull_records(&self) -> (Vec<mesh::GpuInstance>, Vec<mesh::GpuMesh>) {
        (self.instances.records(), self.pool.table_entries())
    }

    /// The generator behind shadow cull `cull` — a cascade's below
    /// [`shadow::CASCADES`], a light slot's after —
    /// for a test reading back what a point light's face culls kept.
    ///
    /// # Panics
    ///
    /// If `cull` is not one of the renderer's shadow culls.
    #[must_use]
    pub fn shadow_generator(&self, cull: usize) -> &DrawGen {
        &self.shadow_draws[cull]
    }

    /// The primary camera's farthest-depth pyramid — every level's image, view
    /// and extent, level 1 first — or empty before a frame culled by occlusion.
    ///
    /// For a test reading a level back: the images carry `TRANSFER_SRC` for
    /// exactly that, and they hold the last frame's early depth once that frame
    /// has finished.
    #[must_use]
    pub fn occlusion_pyramid(&self) -> Vec<(crcbl_hal::ImageHandle, ImageViewHandle, (u32, u32))> {
        self.primary.occlusion_pyramid.level_images()
    }

    /// The most passes [`add_passes`](Self::add_passes) adds to one frame.
    ///
    /// [`DrawGen::MAX_PASSES`] per cull — the camera's, and one per shadow cull
    /// beside it — plus [`LightGrid::MAX_PASSES`] for the froxel grid and the
    /// passes that draw. **A ceiling, not a count**: a frame whose shadow slots
    /// are not all filled runs fewer culls, which is what makes a free tile
    /// free.
    ///
    /// Derived rather than written down, because a number written down is one
    /// that stops matching the frame the day a pass is added — which is exactly
    /// how the samples' hand-picked `8` came to time the first eight passes of a
    /// fourteen-pass frame. A caller sizing
    /// [`PassTimers`](crate::timing::PassTimers) wants
    /// [`MAX_TIMED_PASSES`](crate::timing::MAX_TIMED_PASSES), which adds this to
    /// what the overlay renderers record.
    pub const MAX_PASSES: u32 = DrawGen::MAX_PASSES * (1 + SHADOW_CULLS as u32)
        + DrawGen::LATE_PASSES
        + LightGrid::MAX_PASSES
        + RENDER_PASSES;

    /// Adds the forward and tonemap passes to `graph`, rendering into `target`,
    /// and returns the HDR scene target they went through.
    ///
    /// `target` is normally the imported swapchain image. Everything else — the
    /// HDR scene colour, the depth buffer, and every barrier between them — is
    /// the graph's.
    ///
    /// The returned [`ImageId`] is the `Rgba16Float` frame the tonemap read:
    /// the scene colour **with the screen-space reflections already added**, not
    /// the target the forward pass wrote. A caller that wants to add a pass of
    /// its own after the tonemap — a debug overlay, or a readback proving the
    /// HDR range is real — declares a read of it and the graph works out the
    /// transition, exactly as it does for the tonemap.
    ///
    /// The two are the same description and different images, which is the
    /// design's off-switch as data rather than as a branch: a frame with
    /// [`RenderEffects::REFLECTIONS`] off adds neither pass, returns the forward
    /// pass's own id, and is bit-identical.
    ///
    /// # Which passes this adds is [`effects`](Self::effects)
    ///
    /// Resolved by the [`begin_frame`](Self::begin_frame) that opened this frame
    /// and read here — see [`crate::effects`] for the four layers and for what
    /// each toggle removes. Every effect is on by default, which is the frame
    /// every caller drew before the toggles existed.
    ///
    /// A switched-off effect is **fewer passes and one different bound
    /// descriptor**, never a shader permutation: the shadow atlas keeps its
    /// reversed-Z clear and reads as fully lit, the occlusion binding falls back
    /// to the renderer's white 1×1, and the reflection pair simply is not there.
    ///
    /// # The ground grid comes last, and after the tonemap
    ///
    /// [`set_ground_grid`](Self::set_ground_grid) is what puts it in the frame,
    /// and it is off by default. When it is on, its pass is added **after** the
    /// tonemap and writes `target` rather than the HDR scene colour, depth-tested
    /// against the scene depth: the grid is reference chrome, and a grid drawn
    /// before the tonemap would be exposed and tonemapped like geometry, so its
    /// colour would move with how bright the scene is. See [`crate::grid`].
    ///
    /// # `pool` is where the shadow atlas's incoming state comes from
    ///
    /// It must be the same pool the caller is about to
    /// [`compile`](RenderGraph::compile) and
    /// [`execute`](crate::CompiledGraph::execute) against, because the atlas and
    /// its placeholder are imports this renderer owns across frames and the
    /// pool's ledger is the record of what the last executed graph left them in
    /// — [`TransientPool::imported_image_use`], with [`None`] read as
    /// [`ResourceState::Undefined`]. Reading it here rather than carrying a
    /// field of our own is what keeps the declaration and the audit
    /// ([`InitialClaim::Tracked`]) one answer instead of two that drift: a frame
    /// whose `compile` fails is a frame that never ran, and a field advanced at
    /// build time would already have moved on without it.
    pub fn add_passes<'a>(
        &'a mut self,
        graph: &mut RenderGraph<'a>,
        pool: &TransientPool,
        target: ImageId,
        extent: (u32, u32),
    ) -> ImageId {
        self.add_frame_passes(
            graph,
            pool,
            FrameTargets::primary(target, extent, None),
            |_, _| {},
        )
    }

    /// [`add_passes`](Self::add_passes) for a frame that **skins**: the same
    /// frame with `skinning`'s dispatch in front of every pass that draws.
    ///
    /// # This takes the pass rather than its [`BufferId`], and that is the point
    ///
    /// [`Skinning::add_pass`] hands back the id of the vertex pool so that a
    /// mesh pass can declare a read of it and be ordered after the dispatch. The
    /// obvious seam is therefore an id parameter here — and it is the wrong one,
    /// because every way of getting it wrong is silent. A caller can pass the id
    /// of a *different* import, add the skinning pass after this one, or not add
    /// it at all, and in each case the graph orders nothing, the draws read the
    /// region before the compute write has been made visible, and what comes out
    /// is a mesh that flickers between two poses on hardware and looks perfect
    /// under a validation layer.
    ///
    /// So this takes the [`Skinning`] and **adds the pass itself**, first, with
    /// this renderer's own frame slot, and declares the read on the three passes
    /// that pull vertices out of the pool — the shadow atlas, the depth prepass
    /// and the forward pass. There is no order for a caller to get right,
    /// because there is only one call.
    ///
    /// A frame whose [`begin_skinned_frame`](Self::begin_skinned_frame) was
    /// handed no ranges adds no dispatch and no declarations, and is the frame
    /// [`add_passes`](Self::add_passes) would have built.
    ///
    /// # It records one pass more than [`MAX_PASSES`](Self::MAX_PASSES)
    ///
    /// That constant is the bound on [`add_passes`](Self::add_passes) and stays
    /// so; the skinning dispatch is [`Skinning::MAX_PASSES`], and
    /// [`MAX_TIMED_PASSES`](crate::timing::MAX_TIMED_PASSES) — what a caller
    /// sizes [`PassTimers`](crate::PassTimers) with — already sums the two.
    pub fn add_skinned_passes<'a>(
        &'a mut self,
        graph: &mut RenderGraph<'a>,
        pool: &TransientPool,
        target: ImageId,
        extent: (u32, u32),
        skinning: &Skinning,
    ) -> ImageId {
        self.add_frame_passes(
            graph,
            pool,
            FrameTargets::primary(target, extent, Some(skinning)),
            |_, _| {},
        )
    }

    /// [`add_skinned_passes`](Self::add_skinned_passes) with one game-owned
    /// overlay inserted after the display-space frame is complete and before
    /// antialiasing or render-scale reconstruction.
    ///
    /// The callback receives the display target and its matching scene depth
    /// attachment at the internal render extent. It may add graph passes that
    /// sample `display` and attach `depth` read-only; it must leave both images
    /// in states its declarations name. The forward renderer continues with its
    /// existing resolve and upscale passes after the callback returns.
    pub fn add_skinned_passes_with_overlay<'a, F>(
        &'a mut self,
        graph: &mut RenderGraph<'a>,
        pool: &TransientPool,
        target: ImageId,
        extent: (u32, u32),
        skinning: &Skinning,
        overlay: F,
    ) -> ImageId
    where
        F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
    {
        self.add_frame_passes(
            graph,
            pool,
            FrameTargets::primary(target, extent, Some(skinning)),
            overlay,
        )
    }

    /// [`add_skinned_passes_with_overlay`](Self::add_skinned_passes_with_overlay)
    /// for a frame that also draws secondary views — see
    /// [`create_view`](Self::create_view).
    ///
    /// **The scene's passes are recorded once**: one skinning dispatch (where
    /// `skinning` is `Some`), one shadow atlas, one probe gather. Then each view
    /// in `views` records its own cull, clustering and frame into its own
    /// target, and the primary camera's frame into `target` comes last — so
    /// `overlay` may read a view's target, which is already drawn by then.
    ///
    /// Every view named must have been begun this frame by
    /// [`begin_view`](Self::begin_view).
    ///
    /// # Panics
    ///
    /// If a [`ViewTarget`] in [`FrameTargets::views`] names [`ViewId::PRIMARY`],
    /// a view this renderer did not build, a view not begun this frame, or a
    /// view twice.
    pub fn add_passes_with_views<'a, F>(
        &'a mut self,
        graph: &mut RenderGraph<'a>,
        pool: &TransientPool,
        frame: FrameTargets<'_>,
        overlay: F,
    ) -> ImageId
    where
        F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
    {
        self.add_frame_passes(graph, pool, frame, overlay)
    }

    /// The body of every `add_*passes` entry point, which differ in their
    /// arguments and in nothing else.
    fn add_frame_passes<'a, F>(
        &'a mut self,
        graph: &mut RenderGraph<'a>,
        pool: &TransientPool,
        frame: FrameTargets<'_>,
        overlay: F,
    ) -> ImageId
    where
        F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
    {
        let FrameTargets {
            target,
            extent,
            skinning,
            views,
        } = frame;
        // **From here down `extent` is the extent the frame is *drawn* at**,
        // which is the caller's at a render scale of `1.0` and smaller below it.
        // Every use of it in this function sizes a transient, and every one of
        // those transients belongs to the internal frame; `target` is the only
        // thing here at the caller's extent, and it is an id whose image already
        // knows how big it is. `begin_frame_body` shadows it the same way and
        // for the same reason, so the two halves of a frame cannot disagree.
        //
        // `upscaling` is derived from the two extents rather than from the scale
        // itself, which is what makes it exact: a target small enough that the
        // scaled extent rounds back onto it adds no pass, because there would be
        // nothing for the pass to do.
        let target_extent = extent;
        let extent = self.internal_extent(target_extent);
        let upscaling = extent != target_extent;
        let frame = self.frame;
        let instance_count = self.instances.slot_count();
        let emit = self.emit;

        // Every secondary view the caller asked for, checked before anything of
        // theirs is recorded: a view that does not exist, or one nothing began
        // this frame, would draw out of blocks written for some other frame.
        let secondary: Vec<(ViewTarget, (u32, u32))> = views
            .iter()
            .map(|view| {
                assert!(
                    view.view != ViewId::PRIMARY,
                    "the primary camera draws into the target `add_passes_with_views` takes, \
                     not into a `ViewTarget`"
                );
                let built = self
                    .views
                    .get(view.view.index() - 1)
                    .and_then(Option::as_ref)
                    .unwrap_or_else(|| panic!("{:?} is not a view this renderer built", view.view));
                assert_eq!(
                    built.begun, self.frame_serial,
                    "{:?} was not begun this frame; call `begin_view` after `begin_frame`",
                    view.view
                );
                assert!(
                    views.iter().filter(|other| other.view == view.view).count() == 1,
                    "{:?} was named twice in one frame",
                    view.view
                );
                (*view, self.view_extent(built.background, view.extent))
            })
            .collect();

        // **The skinning dispatch, before anything else is added.** It imports
        // the vertex pool and hands back that node's id; every pass below that
        // pulls vertices declares a read of it, and the graph is what turns the
        // two declarations into the barrier between the compute write and the
        // draws. `None` is a frame with nothing to skin, which adds no pass and
        // declares nothing — see `Skinning::add_pass`.
        let skinned = skinning.and_then(|skinning| skinning.add_pass(graph, frame));

        // The camera's cull dispatch and the draw-argument dispatch, and the
        // light clustering after them — before anything draws, and before the
        // shadow atlas, which is where they always ran. See [`View::add_cull`].
        let cull = self.primary.add_cull(graph, pool, frame, instance_count);

        // Topic 25's record of each cascade's cut. Each is written by
        // exactly one mesh pass, so what the graph orders here is this frame's
        // write against the next frame's use of the same slot. Each arrives in
        // the state the previous frame left it in, which is the one declared as
        // final.
        let tile_selection: Vec<BufferId> = self
            .shadow_selection
            .get(self.frame)
            .into_iter()
            .flatten()
            .enumerate()
            .map(|(tile, &buffer)| {
                import_read_write(graph, &format!("shadow-selection-{tile}"), buffer)
            })
            .collect();

        // **This frame's slot of the probe ring**, which is the buffer every
        // one of this frame's bind groups names — see [`crate::probe`] for why
        // there is more than one. Imported in `ShaderRead` and handed back in
        // it: the build's staging copy left it there and no pass in the frame
        // writes it yet.
        let probe_buffer = self.probes.buffer(frame);
        let probe_table = graph.import_buffer(
            "probes",
            ImportedBuffer {
                buffer: probe_buffer,
                initial: ResourceState::ShaderRead,
                final_state: ResourceState::ShaderRead,
            },
        );

        // The occlusion placeholder, imported once and read by every pass whose
        // bind group names it: the shadow pass's views, the depth prepass's copy
        // of the camera's group, and — on a frame drawing without
        // `RenderEffects::AMBIENT_OCCLUSION` — the forward pass itself. It was
        // uploaded at build, so it is already in `ShaderRead` and the graph has
        // nothing to transition; declaring it is what keeps that true if a later
        // pass wants it in some other state.
        let occlusion_placeholder = graph.import_image(
            "ssao-placeholder",
            ImportedImage {
                image: self.ambient_occlusion_placeholder.image,
                view: self.ambient_occlusion_placeholder.view,
                format: Format::R8Unorm,
                extent: (1, 1),
                initial: ResourceState::ShaderRead,
                claim: InitialClaim::Tracked,
                final_state: ResourceState::ShaderRead,
            },
        );

        // The contact-shadow placeholder, imported beside the occlusion one and
        // on its terms exactly: every group of the mesh layout names this
        // binding, and on a frame drawing without `RenderEffects::CONTACT_SHADOWS`
        // it is what the forward pass binds.
        let contact_placeholder = graph.import_image(
            "contact-shadows-placeholder",
            ImportedImage {
                image: self.contact_shadow_placeholder.image,
                view: self.contact_shadow_placeholder.view,
                format: Format::R8Unorm,
                extent: (1, 1),
                initial: ResourceState::ShaderRead,
                claim: InitialClaim::Tracked,
                final_state: ResourceState::ShaderRead,
            },
        );

        // §3.2's base-colour page, in every bind group of `mesh_layout` and so
        // read by all three of the passes that draw geometry. Like the
        // placeholder above it is already in `ShaderRead` and the graph has
        // nothing to transition on a frame nothing writes it — **the
        // declaration is for the frames something does**. A caller that copies a
        // render-to-texture view into one of its layers imports the same handle,
        // gets this same id back (`RenderGraph::import_image`), and the graph
        // then has an edge to order its write against these reads. Without the
        // declaration there is no such edge: the page is bound out of a
        // descriptor the graph never hears about, and a copy scheduled anywhere
        // but the tail of the frame leaves it in `TransferDst` for the passes
        // that sample it.
        let base_color_page =
            graph.import_image(Self::BASE_COLOR_PAGE_LABEL, self.base_color_page_import());
        // §2's normal page beside it, declared for exactly the reason above: it
        // is in every group of `mesh_layout` too, so a caller copying into one
        // of its layers needs the same edge against these draws.
        let normal_page = graph.import_image(Self::NORMAL_PAGE_LABEL, self.normal_page_import());
        // §2's other two pages beside them, declared for exactly the same
        // reason: both are in every group of `mesh_layout`, so a caller copying
        // into one of their layers needs the same edge against these draws.
        let mro_page = graph.import_image(Self::MRO_PAGE_LABEL, self.mro_page_import());
        let emissive_page =
            graph.import_image(Self::EMISSIVE_PAGE_LABEL, self.emissive_page_import());

        // What this frame draws, resolved by the `begin_frame` that opened it —
        // see [`crate::effects`]. Read once here so every conditional below is
        // about one value rather than about four reads of a field.
        let effects = self.frame_effects;
        // Read here for `effects`' reason and for one more: the passes below
        // borrow `self` field by field, and a `&self` method called between
        // them would borrow the whole of it.
        let draws_sky = self.draws_sky();
        // What the frame's water draws, or `None` for a frame with none — read
        // here for `draws_sky`'s reason, and the same value every view records
        // from.
        let water = self.water.frame(self.frame);
        // The same, for the grass field: read here for `draws_sky`'s reason,
        // and the same value every view records from.
        let grass = self.grass.frame();
        // Whether this frame ends by drawing the shadow atlas over itself — the
        // resolved view rather than the switch, so a caller who left the atlas
        // up and then asked for normals gets normals. Read here for
        // `draws_sky`'s reason exactly: `debug_view` takes `&self`.
        let draws_atlas_view = self.debug_view() == DebugView::ShadowAtlas;

        let pages = MaterialPages {
            base_color: base_color_page,
            normal: normal_page,
            mro: mro_page,
            emissive: emissive_page,
        };
        let (shadow_atlas, shadow_draws, shadow_tile_clears, rsm_images) = self.add_shadow_pass(
            graph,
            pool,
            &tile_selection,
            ShadowReads {
                occlusion_placeholder,
                pages,
                skinned,
                probes: probe_table,
            },
        );

        // The wireframe twin where a caller switched the view on, and `None`
        // everywhere else — see `set_wireframe`. Written on `ground_grid`'s
        // terms, and the `filter` is what keeps "switched on" from outrunning
        // "built": the field is only `Some` after a build that succeeded.
        //
        // The depth prepass below takes the depth-only pipeline and is untouched
        // by this, which is the half that makes a wireframe frame legible: the
        // occlusion pair still reads solid depth. **It is also what makes this
        // one variable rather than two**: the colour pass's depth attachment
        // branches on it as well, because a wireframe is not the geometry the
        // prepass drew — see `MeshModules::color_depth_stencil`.
        let wireframe = self.wireframe_pipeline.filter(|_| self.wireframe_on);
        let bucket_draws = BucketDraws {
            // Replaced per partition below, in both passes that draw this list —
            // see [`ForwardRenderer::sided_partitions`] and
            // [`ForwardRenderer::depth_partitions`]. The field is what the
            // partitions inherit everything else from.
            pipeline: self.mesh_pipeline.single,
            layout: self.mesh_pipeline_layout,
            indices: self.pool.index_buffer(),
            emit,
            calls: self
                .bucket_constants
                .iter()
                .enumerate()
                .map(|(bucket, constant_offset)| {
                    let bucket = u32::try_from(bucket)
                        .unwrap_or_else(|_| unreachable!("a fixed table of a few buckets"));
                    (
                        *constant_offset,
                        self.primary.draws.args_offset(bucket),
                        self.primary.draws.count_offset(bucket),
                        self.primary.draws.mesh_args_offset(bucket),
                    )
                })
                .collect(),
            region_step: self.region_step,
            // Packed per partition, where the partition's buckets are known.
            ranges: None,
            flat: None,
        };

        // Every draw this frame records: the shadow pass's, one per bucket — or
        // per range of buckets, or per partition behind a task stage — in
        // **each** of the depth prepass and the forward pass, and one full-screen
        // triangle per full-screen pass. Assigned before the passes below borrow
        // the fields they need, so it is the count for the frame being built
        // rather than the one before it — and off this frame's resolved effects
        // rather than off a constant, so a switched-off effect's triangle is not
        // counted as submitted.
        //
        // The ground grid is added on top rather than folded into
        // `fullscreen_passes`: it is not a [`RenderEffects`] bit and is not
        // resolved by the toggle order — it is a caller's opt-in, off by
        // default — so what decides it is the field and not this frame's
        // effects.
        self.recorded_fullscreen = fullscreen_passes(effects, extent, upscaling, self.frame_ssao_blurs)
                + u64::from(self.ground_grid().is_some() && !draws_atlas_view)
                + if draws_sky { SkyPass::PASSES } else { 0 }
                // The composite on an atmosphere frame whose fog effect is off,
                // on the sky's terms: it is there for the air in front of the
                // scene, which the atmosphere decides and no effect bit does.
                // With the effect on, `fullscreen_passes` already counted it.
                + if self.primary.frame_aerial
                    && !effects.contains(RenderEffects::VOLUMETRIC_FOG)
                {
                    u64::from(Volumetric::COMPOSITE_PASSES)
                } else {
                    0
                }
                // The water copy's triangle, on the sky's terms: content rather
                // than an effect bit, so the bodies decide it.
                + if water.is_some() { Water::FULLSCREEN_PASSES } else { 0 }
                // The atlas viewer, on the ground grid's terms: not an effect
                // bit and not resolved by the toggle order, so what decides it
                // is the debug view and not this frame's effects. It *replaces*
                // the tonemap `fullscreen_passes` counted and the grid above —
                // see `View::add_passes` — so its passes stand in for the one.
                + if draws_atlas_view {
                    u64::from(AtlasView::PASSES) - 1
                } else {
                    0
                };
        // The debug draw layer's own call, on the ground grid's terms: not an
        // effect bit, and decided by whether this frame's slot has a segment in
        // it. One direct draw of one instance covering every segment appended,
        // which is why it joins the full-screen triangles rather than the
        // indirect draws — `counters` counts both as submitted *and* drawn,
        // because the CPU knows what they cover.
        self.recorded_debug_draw = u64::from(self.debug_draw.records_pass(self.frame));
        // The shadow pass's tile resets, on the same terms: one over-sized
        // triangle of one instance per tile it redrew, and none at all on a
        // frame that cleared the whole attachment — see
        // [`MeshModules::depth_clear_pipeline`].
        self.recorded_tile_clears = shadow_tile_clears;
        // One indexed draw per body the frame's water holds.
        self.recorded_water_draws = water
            .as_ref()
            .map_or(0, |water: &WaterFrame| water.draws.len() as u64);
        // One indirect draw per tile slot the frame's field holds, per look it
        // draws.
        self.recorded_grass_draws = grass.as_ref().map_or(0, |grass: &GrassFrame| {
            u64::from(grass.slots) * u64::from(grass.draws_per_slot())
        });
        // The late depth prepass is a third list of calls, on a frame whose
        // camera culls in two phases.
        let camera_passes: u64 = if self.primary.draws.frame_mode(frame)
            == crcbl_shaders::draw_gen::DrawMode::Occlusion
        {
            3
        } else {
            2
        };
        let prepass_partitions = self.depth_partitions(&bucket_draws);
        // And the colour pass's own split, which is by **side** alone: its
        // pipeline has a fragment stage either way, so an alpha mask is nothing
        // it has to route around and a cull mode is. The wireframe twin pair
        // substitutes for the shaded one here exactly as the single pipeline
        // used to.
        let color_partitions =
            self.sided_partitions(&bucket_draws, wireframe.unwrap_or(self.mesh_pipeline));
        // Off the partitions the passes below record, because where a call
        // draws a range of buckets the two splits pack into different numbers
        // of ranges — see [`BucketDraws::call_count`].
        let calls = |partitions: &[BucketDraws]| -> u64 {
            partitions.iter().map(BucketDraws::call_count).sum()
        };
        self.recorded_draws = shadow_draws
            + (camera_passes - 1) * calls(&prepass_partitions)
            + calls(&color_partitions)
            + self.recorded_grass_draws
            + self.direct_draws();

        // --- the probe gather ---
        //
        // The irradiance probes' updater, second half: the map
        // the pass above drew, read into every row of the table. **Here rather
        // than beside that pass** because the write is `&mut` — the group naming
        // the map's transient views is cached across frames, and a group naming a
        // transient cannot be built where the others are; see
        // [`crate::ssao::cached_group`].
        //
        // It is before the depth prepass and the forward pass, which is the
        // ordering that matters: both declare a read of these rows, so the graph
        // barriers this write against them.
        //
        // Which map layer a row is weighed against is the row's own index, so
        // the view is resolved exactly as the drawing passes resolve it — the
        // placeholder until `capture_probe_visibility` has run, and off entirely
        // where `r_probe_visibility` is off. A gather against the placeholder
        // occludes nothing, which is the honest answer for a scene that never
        // captured.
        let probe_visibility_view = match &self.probe_visibility {
            Some(captured) if crate::probe_visibility::enabled() => captured.view,
            _ => self.probe_visibility_placeholder.view,
        };
        let frame = self.frame;
        if let Some((gather, images)) = self.probe_gather.as_mut().zip(rsm_images) {
            gather.add_pass(graph, frame, images, probe_visibility_view, probe_table);
        }

        let passes = FramePasses {
            slot: frame,
            emit,
            target_format: self.target_format,
            ssao_blurs: self.frame_ssao_blurs,
            draws_sky,
            water,
            grass,
            skinned,
            probe_buffer,
            probe_table,
            occlusion_placeholder,
            contact_placeholder,
            pages,
            shadow_atlas,
            probe_visibility: probe_visibility_view,
            mesh_layout: self.mesh_layout,
            wireframe,
            prepass_partitions,
            color_partitions,
            tonemap: TonemapPipeline {
                sampler: self.sampler,
                layout: self.tonemap_layout,
                pipeline_layout: self.tonemap_pipeline_layout,
                pipeline: self.tonemap_pipeline,
            },
        };
        // From here the frame is borrowed field by field, because every view's
        // passes hold its own caches for the life of the graph.
        let Self {
            primary,
            views: built,
            debug_draw,
            ground_grid,
            ground_grid_on,
            atlas_viewer,
            cull_stats,
            ..
        } = self;

        // **Every secondary view before the primary camera's frame**, so a pass
        // the primary records — an overlay compositing a scope's picture onto
        // the lens it is seen through — reads a view that is already drawn. Each
        // records its whole frame straight through: its own cull, its own
        // clustering, and every pass the primary records after them, against the
        // atlas and the probe rows the scene passes above left behind.
        for (index, slot) in built.iter_mut().enumerate() {
            let Some((view_target, view_extent)) = secondary
                .iter()
                .find(|(view, _)| view.view.index() == index + 1)
            else {
                continue;
            };
            let view = slot
                .as_mut()
                .unwrap_or_else(|| unreachable!("checked against the built views above"));
            let view_cull = view.add_cull(graph, pool, frame, instance_count);
            view.add_passes(
                graph,
                &passes,
                view_cull,
                ViewOutput {
                    target: view_target.target,
                    target_extent: view_target.extent,
                    extent: *view_extent,
                },
                Overlays::default(),
                |_, _| {},
            );
        }

        // The statistics buffer's id, read before the cull moves into the pass
        // recording below: the copy that reads it is the frame's last pass.
        let stats_id = cull.generated.visible_count_id;
        let tonemapped = primary.add_passes(
            graph,
            &passes,
            cull,
            ViewOutput {
                target,
                target_extent,
                extent,
            },
            Overlays {
                debug_draw: Some(debug_draw),
                ground_grid: ground_grid.as_ref().filter(|_| *ground_grid_on),
                atlas_viewer: draws_atlas_view.then_some(atlas_viewer),
            },
            overlay,
        );

        // **Last, and that is the point.** Three passes add to the statistics
        // buffer — the cull dispatch, the light grid's overflow counter and the
        // amplification stage inside the forward pass — so a copy scheduled any
        // earlier would take a total the frame had not finished writing. The
        // graph puts it in `TransferSrc` for this and back into the state the
        // next frame on this slot imports it in; there is not a barrier written
        // here.
        if let Some(stats) = cull_stats.as_mut() {
            stats.add_copy_pass(graph, stats_id);
        }

        tonemapped
    }

    /// Adds the cull dispatches and the depth-only pass that fill the shadow
    /// atlas, and returns the atlas as the graph knows it.
    ///
    /// Every tile is one viewport of one render pass. A pass per tile would be
    /// one clear of the same image and one more barrier per tile, and the graph
    /// would have to be told each of them only touches part of it — where one
    /// pass with a viewport per tile is what a shadow *atlas* is for in the first
    /// place.
    ///
    /// **Only the occupied tiles get a cull and a viewport.** The cascades
    /// always are; a light tile is occupied when
    /// [`shadow::Selection`] gave it to a light. A free one keeps the
    /// reversed-Z clear the pass wrote, which is `0.0` — "nothing stored, as far
    /// away as depth goes" — so anything that did sample it would come back
    /// fully lit rather than fully shadowed.
    ///
    /// # With [`RenderEffects::SHADOWS`] off, every tile is a free one
    ///
    /// That is the whole switch, and it is the same mechanism a free tile
    /// already had rather than a second one: no cull is dispatched and no
    /// viewport is drawn, the pass records its clear and nothing else, and every
    /// comparison against the atlas comes back fully lit. The pass itself stays
    /// on the frame that switches it off — it is what *writes* that clear, and a
    /// frame that skipped it would leave the atlas holding the last frame that
    /// did draw into it, or undefined memory on the first frame of all.
    ///
    /// # A cached atlas records nothing at all
    ///
    /// Topic 45's static-caching rung. When
    /// [`ForwardRenderer::shadow_atlas_cached`] says the image already holds
    /// what this frame would draw, this adds **no cull and no pass**: the atlas
    /// is imported so the passes that sample it have an edge to the resource,
    /// and it keeps the contents an earlier frame left in it. That is why the
    /// image is a persistent one with a tracked ledger entry rather than a
    /// transient — nothing else in the frame can alias it, so what it holds is
    /// what the last pass to write it wrote.
    ///
    /// # Per group, and what pays for the tiles it keeps
    ///
    /// Topic 45's cadence rung. A **group** — a cascade, or a
    /// light slot's whole run of tiles — is redrawn or held on its own, and
    /// [`ForwardRenderer::shadow_group_redrawn`] is what says which. A frame
    /// that holds nothing clears the whole attachment, which is the recording
    /// that shipped before the rung; a frame that holds something **loads** the
    /// attachment instead and resets each tile it redraws with
    /// [`MeshModules::depth_clear_pipeline`], which is the portable statement of
    /// a clear bounded to one tile.
    ///
    /// The attachment's own [`LoadOp::Clear`] cannot serve there: it covers
    /// every tile including the ones being kept, and the region-bounded
    /// alternatives are not portable — Metal's load action and WebGPU's
    /// `loadOp` have no render area to bound them, so a clear that covered part
    /// of the image on Vulkan and all of it on Metal would be a held tile that
    /// survives on one backend and is erased on another.
    fn add_shadow_pass(
        &self,
        graph: &mut RenderGraph<'_>,
        pool: &TransientPool,
        selection: &[BufferId],
        reads: ShadowReads,
    ) -> (ImageId, u64, u64, Option<RsmImages>) {
        let shadows = self.frame_effects.contains(RenderEffects::SHADOWS);
        let (atlas_width, atlas_height) = shadow::atlas_extent();
        let atlas = graph.import_image(
            "shadow-atlas",
            ImportedImage {
                image: self.shadow_atlas,
                view: self.shadow_atlas_view,
                format: Format::D32Float,
                extent: (atlas_width, atlas_height),
                // What the previous executed frame left it in — `Undefined` on
                // the first, which is what makes the graph give it a layout at
                // all.
                initial: imported_state(pool, self.shadow_atlas),
                // The renderer keeps this image across frames, so the pool's
                // ledger is the record of what happened to it and the line above
                // is that record read back rather than a second copy of it.
                claim: InitialClaim::Tracked,
                final_state: ResourceState::ShaderRead,
            },
        );
        // The cached frame's whole answer: the image above and nothing that
        // touches it. It is already in `ShaderRead` — the frame that drew it
        // handed it back that way — so the graph has no transition to make, and
        // the passes that sample it read the maps an earlier frame left there.
        if self.shadow_atlas_cached {
            // **And no reflective shadow map either**, which cannot happen while
            // the updater is on: `begin_frame` keeps cascade 0 off the hold in
            // exactly that case, so a frame reaching here has nothing to draw
            // the map from. See `probe_update_runs`.
            return (atlas, 0, 0, None);
        }
        let placeholder = graph.import_image(
            "shadow-placeholder",
            ImportedImage {
                image: self.shadow_placeholder,
                view: self.shadow_placeholder_view,
                format: Format::D32Float,
                extent: (1, 1),
                // **Its own ledger entry, not the atlas's.** The two move
                // together today — both are imported by this function on every
                // frame and both are handed back in `ShaderRead` — so one lookup
                // would answer both, and that is exactly the coincidence a
                // second declared state here stops depending on.
                initial: imported_state(pool, self.shadow_placeholder),
                claim: InitialClaim::Tracked,
                final_state: ResourceState::ShaderRead,
            },
        );

        // Which light slots have a light this frame, resolved once: a slot's
        // cull is dispatched and its faces are drawn together or not at all, and
        // `begin_frame` filled that generator's parameters under exactly this
        // condition.
        //
        // **And only the ones this frame redraws**, since the cadence rung: a
        // held slot keeps the texels it has, so recording its cull and its
        // draws would be the same picture at the full price.
        let occupied: Vec<(usize, shadow::Assignment, &Light)> = self
            .shadow_lights
            .slots()
            .iter()
            .enumerate()
            .filter(|_| shadows)
            .filter(|(slot, _)| self.shadow_group_redrawn[shadow_cull(*slot)])
            .filter_map(|(slot, held)| {
                let held = (*held)?;
                Some((slot, held, self.extra_lights.get(held.light)?))
            })
            .collect();

        // One cull dispatch per cascade and per occupied slot, before the pass
        // that draws from them — **not one per tile**, which is topic 18's
        // fourth decision: a point light's six faces draw one visible set.
        let cascades: Vec<usize> = if shadows {
            (0..shadow::CASCADES)
                .filter(|cascade| self.shadow_group_redrawn[*cascade])
                .collect()
        } else {
            Vec::new()
        };
        // **Cascade 0's cull, on a frame that is not drawing it into the
        // atlas.** `begin_frame` fits it whenever the updater is on, shadows or
        // no shadows — see `rsm_cull_ready` — so this is the case where the map
        // is drawn and the atlas keeps its clear. Chained **last**, because the
        // occupied slots' entries are indexed by `cascades.len() + index` a few
        // lines below and an insertion before them would hand a light's draws to
        // the wrong viewport.
        let rsm_only_cull = self.rsm_cull_ready && !cascades.contains(&0);
        // The punctual producer's faces, which are also the light slots'
        // atlas views — see `punctual_faces`, the one list both halves of the
        // updater walk.
        let punctual = self.punctual_faces();
        // And their culls on a frame that is not drawing the atlas, which
        // `occupied` is empty on for the same reason `cascades` is. Deduplicated
        // because a point light's six faces draw one visible set, and chained
        // **after** the entries `views` indexes positionally below.
        let punctual_only_culls: Vec<usize> = if shadows {
            Vec::new()
        } else {
            punctual
                .iter()
                .map(|face| face.cull)
                .collect::<std::collections::BTreeSet<_>>()
                .into_iter()
                .collect()
        };
        let generated: Vec<(usize, GeneratedDraws)> = cascades
            .iter()
            .copied()
            .chain(occupied.iter().map(|(slot, _, _)| shadow_cull(*slot)))
            .chain(rsm_only_cull.then_some(0))
            .chain(punctual_only_culls)
            .map(|cull| {
                (
                    cull,
                    self.shadow_draws[cull].add_passes(
                        graph,
                        self.frame,
                        self.instances.slot_count(),
                    ),
                )
            })
            .collect();

        // What the pass body records, in order: which view's bind group, which
        // rectangle of the atlas its viewport covers, and which of the culls
        // above it draws from. Paired rather than positional, because the free
        // slots are missing from every one of these lists and a bare index into
        // one would hand a light's draws to the wrong viewport the moment one
        // slot is free and a later one is not.
        //
        // **The rectangle rather than the slot**, resolved here: the body runs
        // in a closure that outlives this borrow, and asking the selection for
        // it there would be a second reading of an allocation that has to be the
        // one the frame block was written from.
        //
        // **And which draw region of that cull**: region 0, every survivor, for
        // a cascade and a spot; and for a point light whose cull tagged its
        // casters by face, the region of the face being drawn — see
        // `set_point_face_culls`.
        let mut views: Vec<(usize, shadow::TileRect, usize, u32)> = cascades
            .iter()
            .enumerate()
            .map(|(position, cascade)| {
                (
                    *cascade,
                    self.shadow_lights.atlas_rect(*cascade),
                    position,
                    0,
                )
            })
            .collect();
        for (index, (slot, held, light)) in occupied.iter().enumerate() {
            // A spot draws face 0 alone; a point light draws all six, each
            // through its own matrix into its own tile. `shadow::tile_span` is
            // the same function `Selection` allocated the run with, so a face
            // here and a tile there cannot disagree about how many there are.
            let by_face = self.shadow_draws[shadow_cull(*slot)].frame_mode(self.frame)
                == crcbl_shaders::draw_gen::DrawMode::Faces;
            for face in 0..shadow::tile_span(light) {
                views.push((
                    shadow_view(*slot, face),
                    self.shadow_lights
                        .atlas_rect(shadow::light_tile(held.base + face)),
                    cascades.len() + index,
                    face_region(by_face, face),
                ));
            }
        }

        let mut pass = graph
            .add_render_pass("shadow")
            // **Stored, unlike the scene's depth.** This is the one depth buffer
            // in the engine that something downstream reads, which is what
            // `PassBuilder::clear_depth`'s docs said would need a `StoreOp` the
            // day a prepass existed.
            .depth(
                atlas,
                // **Loaded on a frame that is keeping a tile**, which is the
                // cadence rung's whole seam: a clear here covers the image, so
                // the tiles this frame *does* redraw are reset one at a time by
                // the pipeline below instead. A frame keeping nothing clears,
                // which is what shipped.
                if self.shadow_atlas_clears {
                    LoadOp::Clear
                } else {
                    LoadOp::Load
                },
                StoreOp::Store,
                crcbl_hal::ClearValue {
                    depth: crcbl_hal::depth::CLEAR,
                    ..crcbl_hal::ClearValue::default()
                },
            )
            // Declared so the graph gives it a shader-read layout: it is in
            // every cascade's bind group, standing in for the atlas this pass is
            // writing. See `ForwardRenderer::shadow_placeholder`.
            .read_image(placeholder)
            // Likewise, and it is in every one of those groups too — see
            // `ForwardRenderer::ambient_occlusion_placeholder`. Nothing samples
            // it here either: the depth-only pipeline has no fragment stage.
            .read_image(reads.occlusion_placeholder)
            // And §3.2's page, which `mesh_layout` names in every group — a
            // cascade's included. See `ForwardRenderer::base_color_page_import`
            // for what the declaration buys a caller that writes the page.
            .read_image(reads.pages.base_color)
            // And §2's other three pages beside it, in those same groups and
            // sampled by no cascade — see
            // `ForwardRenderer::normal_page_import`.
            .read_image(reads.pages.normal)
            .read_image(reads.pages.mro)
            .read_image(reads.pages.emissive)
            // And the probe rows, which are in those groups too and which no
            // cascade reads — declared on the placeholder's and the pages'
            // terms, plus one of their own: the rows are device-local and a copy
            // destination so the irradiance probes' gather can
            // write them, and a pass that binds a buffer it has not declared is
            // one the graph cannot order that write against.
            .read_buffer(reads.probes);
        // Each tile's mesh pass records the cut it descended to, into a buffer
        // of its own — see `ForwardRenderer::shadow_selection`. Empty where
        // there is no amplification stage to descend anything.
        //
        // Declared for every tile rather than for the occupied ones: the state
        // is what the buffer is *in*, which does not depend on whether this
        // frame happened to write it, and a free tile's buffer still has to
        // arrive in the state the next frame's import claims.
        for &buffer in selection {
            pass = pass.use_buffer(buffer, ResourceState::ShaderReadWrite);
        }
        // The skinned vertices this pass may pull, and the reason it is declared
        // here as well as on the colour passes: a cascade draws the same
        // geometry out of the same pool, so a shadow that fell before the
        // dispatch was visible would be cast by the previous pose — a shadow
        // that does not match its caster, on a frame whose picture is otherwise
        // right.
        if let Some(vertices) = reads.skinned {
            pass = pass.read_buffer(vertices);
        }
        for (_, draws) in &generated {
            pass = read_draw_sources(pass, draws, self.emit);
        }

        let groups = self.shadow_groups[self.frame].clone();
        // **What the reflective shadow map is drawn from**, read out here rather
        // than reconstructed by the caller: cascade 0's bind group — whose
        // uniform block already holds that cascade's `view_proj`, which is what
        // "reusing cascade 0's matrix" means — and the `GeneratedDraws` its cull
        // produced a moment ago. Both are `Copy`, so recording a second pass
        // from them costs no second cull and no second matrix.
        //
        // [`None`] on a frame that is not drawing cascade 0 at all: shadows off,
        // or a `r_shadow_cadence` past one that held the group anyway. The rows
        // then keep what the last gather wrote — see [`ProbeUpdate::EveryFrame`],
        // which says so.
        let cascade_zero: Option<(BindGroupHandle, GeneratedDraws)> = self
            .rsm_cull_ready
            .then(|| {
                generated
                    .iter()
                    .find(|(cull, _)| *cull == 0)
                    .map(|(_, draws)| (groups[CASCADE_ZERO_VIEW], *draws))
            })
            .flatten();
        // **What the punctual reflective shadow map is drawn from**, resolved
        // here for `cascade_zero`'s reason and on its terms: each face's own
        // bind group — whose uniform block already holds that face's
        // `view_proj` — and the `GeneratedDraws` its slot's cull produced a
        // moment ago. Both are `Copy`, so the second pass costs no second cull
        // and no second matrix.
        //
        // Found by cull id rather than by position, so this list and the atlas's
        // cannot be knocked out of step by a slot the other one skipped.
        //
        // And the face's draw region, on the atlas's terms: a point light whose
        // cull tagged its casters draws each face from that face's region.
        let punctual_views: Vec<(BindGroupHandle, shadow::TileRect, GeneratedDraws, u32)> =
            punctual
                .iter()
                .filter_map(|face| {
                    let (_, draws) = generated.iter().find(|(cull, _)| *cull == face.cull)?;
                    let by_face = self.shadow_draws[face.cull].frame_mode(self.frame)
                        == crcbl_shaders::draw_gen::DrawMode::Faces;
                    Some((
                        groups[face.view],
                        face.tile,
                        *draws,
                        face_region(by_face, face.face),
                    ))
                })
                .collect();
        // The culls those faces draw from, **once each**: a point light's six
        // faces draw one visible set, so declaring a face's sources would
        // declare the same buffers six times in one pass.
        let punctual_sources: Vec<GeneratedDraws> = punctual
            .iter()
            .map(|face| face.cull)
            .collect::<std::collections::BTreeSet<_>>()
            .into_iter()
            .filter_map(|cull| {
                let (_, draws) = generated.iter().find(|(candidate, _)| *candidate == cull)?;
                Some(*draws)
            })
            .collect();
        let bucket_draws = BucketDraws {
            // Replaced per partition below; the field is what the tile clears
            // and the reflective shadow map inherit, and neither binds it.
            pipeline: self.shadow_pipeline.single,
            layout: self.mesh_pipeline_layout,
            indices: self.pool.index_buffer(),
            emit: self.emit,
            calls: self
                .bucket_constants
                .iter()
                .enumerate()
                .map(|(bucket, constant_offset)| {
                    let bucket = u32::try_from(bucket)
                        .unwrap_or_else(|_| unreachable!("a fixed table of a few buckets"));
                    (
                        *constant_offset,
                        self.primary.draws.args_offset(bucket),
                        self.primary.draws.count_offset(bucket),
                        self.primary.draws.mesh_args_offset(bucket),
                    )
                })
                .collect(),
            region_step: self.region_step,
            // Packed per partition, where the partition's buckets are known.
            ranges: None,
            flat: None,
        };
        // Kept back for the reflective shadow map below, which is the same
        // per-bucket call list under a different pipeline — the depth prepass
        // plays exactly this trick with the camera's. Cloned before the pass
        // body takes the original.
        let bucket_calls = bucket_draws.clone();
        // The atlas's own split by material mode: an opaque bucket's tile is
        // drawn with no fragment stage in a scene that has a cutout in it. Every
        // view draws every partition — one call per bucket, per range of
        // buckets, or behind a task stage one flat call, per view, under a
        // pipeline per mode.
        let tile_partitions = self.depth_partitions(&bucket_draws);

        // Counted off the two loops the body below runs, before it takes them:
        // every partition's calls per occupied view. `ForwardRenderer::counters`
        // is what reports it, and reading it back off the same `Vec`s is what
        // makes it move when the tile allocation does.
        let recorded = views.len() as u64
            * tile_partitions
                .iter()
                .map(BucketDraws::call_count)
                .sum::<u64>();
        // And the tile resets beside them, which are direct draws of one
        // instance rather than indirect ones: a frame that cleared the whole
        // attachment records none, and a frame that loaded it records one per
        // tile it redraws.
        let clears = if self.shadow_atlas_clears {
            0
        } else {
            views.len() as u64
        };

        // What the image will hold once this body has run, carried into it so
        // that *recording* the pass is not what claims the atlas was drawn — see
        // [`ForwardRenderer::shadow_atlas_drawn`].
        let ran = Arc::clone(&self.shadow_pass_ran);
        let pass_id = self.shadow_pass_id;
        // The tiles this pass redraws have to be reset before anything is drawn
        // into them, and on a frame that loaded the attachment there is nothing
        // else that will — see [`MeshModules::depth_clear_pipeline`]. A frame
        // that cleared has already had every tile reset by the attachment, so
        // this is `None` and the recording is the one that shipped.
        let clear = (!self.shadow_atlas_clears).then_some(self.shadow_clear_pipeline);
        // **The reset draw has to bind a group, and only a browser says so.**
        // `MeshModules::depth_clear_pipeline` builds this pipeline from
        // `mesh_pipeline_layout`, so its layout declares group 0 whether or not
        // the one triangle's vertex shader reads a byte of it — and WebGPU
        // refuses a draw with any group the *layout* declares left unset, where
        // Vulkan and the others only care about what the shader dereferences. An
        // unbound reset therefore fails no native run and rejects the whole
        // browser frame: `No bind group set at group index 0` arrives when the
        // encoder is finished, so every pass recorded after it is thrown away
        // with it and the canvas stays at the clear colour.
        //
        // Any bucket's offset does: the block is what the mesh draws index and
        // this draw reads none of it, so what matters is that the offset is one
        // the layout accepts rather than which bucket it names.
        let clear_layout = bucket_draws.layout;
        let clear_offset = bucket_draws
            .calls
            .first()
            .map_or(0, |(constant_offset, ..)| *constant_offset);
        pass.execute(move |ctx| {
            ran.store(pass_id, Ordering::Relaxed);
            let encoder = ctx.encoder();
            if let Some(clear) = clear {
                encoder.bind_graphics_pipeline(clear);
                for (view, tile, _, _) in &views {
                    set_shadow_tile(encoder, *tile);
                    encoder.bind_group(0, groups[*view], &[clear_offset], clear_layout);
                    encoder.draw(0..TILE_CLEAR_VERTICES, 0..1);
                }
            }
            for partition in &tile_partitions {
                partition.open(encoder);
                for (view, tile, cull, region) in &views {
                    set_shadow_tile(encoder, *tile);
                    partition.record_region(encoder, groups[*view], &generated[*cull].1, *region);
                }
            }
        });

        // --- the reflective shadow map ---
        //
        // The irradiance probes' updater, first half, recorded
        // here because this is where cascade 0's bind group and its
        // already-generated draws are. **A pass of its own at its own extent**,
        // and [`crate::rsm`]'s header argues why it cannot ride the atlas above:
        // one colour attachment there spans the whole 3072² image for data only
        // one 768² tile is read from, and it would give all fourteen light tiles
        // a fragment stage.
        //
        // No viewport is set: the graph opens a pass with a full-target viewport
        // and scissor already, and every attachment here is the map's own square.
        let Some((cascade_group, cascade_draws)) = cascade_zero else {
            return (atlas, recorded, clears, None);
        };
        let extent = rsm::extent();
        let sun = RsmTargets {
            albedo: graph.create_image("rsm-albedo", rsm::albedo_target(extent)),
            normal: graph.create_image("rsm-normal", rsm::normal_target(extent)),
            world: graph.create_image("rsm-world", rsm::world_target(extent)),
        };
        // Its own depth, cleared and discarded: it resolves which surface a
        // texel of the map holds and nothing reads it afterwards.
        let rsm_depth = graph.create_image("rsm-depth", rsm::depth_target(extent));
        let mut rsm = graph
            .add_render_pass("rsm")
            // **Cleared, and the world target's clear is load-bearing**: `w` is
            // the coverage flag `RsmOutput::world` writes, so a texel the pass
            // draws nothing into reads back zero there and the gather skips it.
            // Without the clear the world origin would stand in for every part
            // of the cascade the geometry does not cover.
            .clear_color(sun.albedo, [0.0; 4])
            .clear_color(sun.normal, [0.0; 4])
            .clear_color(sun.world, [0.0; 4])
            .clear_depth(rsm_depth)
            // The same declarations the cascade above makes, for the same
            // reason: every group of the mesh layout names these, and this pass
            // binds one of those groups. Unlike the cascade, this one has a
            // fragment stage — so the pages really are sampled here.
            .read_image(placeholder)
            .read_image(reads.occlusion_placeholder)
            .read_image(reads.pages.base_color)
            .read_image(reads.pages.normal)
            .read_image(reads.pages.mro)
            .read_image(reads.pages.emissive)
            .read_buffer(reads.probes);
        if let Some(vertices) = reads.skinned {
            rsm = rsm.read_buffer(vertices);
        }
        // Cascade 0's cluster-selection buffer, which the mesh path's stages
        // write — declared on the atlas pass's terms, and only for the one view
        // this pass draws.
        if let Some(&buffer) = selection.get(CASCADE_ZERO_VIEW) {
            rsm = rsm.use_buffer(buffer, ResourceState::ShaderReadWrite);
        }
        rsm = read_draw_sources(rsm, &cascade_draws, self.emit);
        // Split by side, on the colour pass's terms: this stage cuts the alpha
        // mask itself, so the only thing it cannot say inside the fragment stage
        // is which faces the rasteriser keeps.
        let rsm_partitions = self.sided_partitions(&bucket_calls, self.rsm_pipeline);
        let rsm_recorded: u64 = rsm_partitions.iter().map(BucketDraws::call_count).sum();
        rsm.execute(move |ctx| {
            let encoder = ctx.encoder();
            for partition in &rsm_partitions {
                partition.open(encoder);
                partition.record(encoder, cascade_group, &cascade_draws);
            }
        });

        // --- the punctual reflective shadow map ---
        //
        // The irradiance probes' punctual producer: the same
        // pipeline and the same per-bucket call list as the pass above, under
        // one viewport per shadowed light face instead of one whole map. A spot
        // is a tile and a point light is six, which is `shadow::tile_span` — so
        // this is the atlas pass's own view loop drawn into a second, much
        // smaller set of targets.
        //
        // **Recorded whether or not the frame lights a punctual face**, unlike
        // the map above. The clear is a legitimate answer — a frame with no
        // shadowed punctual light has no punctual bounce, and the coverage flag
        // in `w` says so at every texel — and a pass that came and went with the
        // lights would be a pass list that changes shape with the scene, which
        // is what `RENDER_PASSES` and every timing reader are written against.
        let punctual_extent = rsm::punctual_extent();
        let punctual_targets = RsmTargets {
            albedo: graph.create_image("rsm-punctual-albedo", rsm::albedo_target(punctual_extent)),
            normal: graph.create_image("rsm-punctual-normal", rsm::normal_target(punctual_extent)),
            world: graph.create_image("rsm-punctual-world", rsm::world_target(punctual_extent)),
        };
        let punctual_depth =
            graph.create_image("rsm-punctual-depth", rsm::depth_target(punctual_extent));
        let mut punctual_pass = graph
            .add_render_pass("rsm-punctual")
            // Cleared on the map above's terms, and the world target's clear is
            // load-bearing for its reason as well as for one of this map's own:
            // the tiles the cascades would hold are drawn into by nothing at
            // all, and a coverage flag of zero is what keeps the gather out of
            // them.
            .clear_color(punctual_targets.albedo, [0.0; 4])
            .clear_color(punctual_targets.normal, [0.0; 4])
            .clear_color(punctual_targets.world, [0.0; 4])
            .clear_depth(punctual_depth)
            .read_image(placeholder)
            .read_image(reads.occlusion_placeholder)
            .read_image(reads.pages.base_color)
            .read_image(reads.pages.normal)
            .read_image(reads.pages.mro)
            .read_image(reads.pages.emissive)
            .read_buffer(reads.probes);
        if let Some(vertices) = reads.skinned {
            punctual_pass = punctual_pass.read_buffer(vertices);
        }
        // Each face's own cluster-selection buffer, which the mesh path's stages
        // write — declared on the atlas pass's terms, and only for the views
        // this pass draws.
        for face in &punctual {
            if let Some(&buffer) = selection.get(face.view) {
                punctual_pass = punctual_pass.use_buffer(buffer, ResourceState::ShaderReadWrite);
            }
        }
        for draws in &punctual_sources {
            punctual_pass = read_draw_sources(punctual_pass, draws, self.emit);
        }
        let punctual_partitions = self.sided_partitions(&bucket_calls, self.rsm_pipeline);
        let punctual_recorded = punctual_views.len() as u64
            * punctual_partitions
                .iter()
                .map(BucketDraws::call_count)
                .sum::<u64>();
        punctual_pass.execute(move |ctx| {
            let encoder = ctx.encoder();
            // The partition is **outside** the view loop, on the shadow atlas's
            // terms: one pipeline bind covers every face of that side.
            for partition in &punctual_partitions {
                partition.open(encoder);
                for (group, tile, draws, region) in &punctual_views {
                    set_shadow_tile(encoder, *tile);
                    partition.record_region(encoder, *group, draws, *region);
                }
            }
        });

        let images = RsmImages {
            sun,
            punctual: punctual_targets,
        };
        (
            atlas,
            recorded + rsm_recorded + punctual_recorded,
            clears,
            Some(images),
        )
    }

    /// Which lights hold the atlas's light tiles this frame, and where each
    /// map was laid out.
    ///
    /// **The observable topic 45's priority rung otherwise has
    /// none for.** A map's *size* leaves no trace in the picture that a golden
    /// can hold anyone to: a light demoted to a quarter of a cell draws a
    /// slightly softer shadow, which is a perfectly plausible frame and one a
    /// re-bless accepts. [`Selection::atlas_rect`](crate::shadow::Selection)
    /// off this is what says which level the allocator actually handed out, and
    /// `crates/crcbl/tests/mesh_e2e/shadow_tiles.rs` is what reads it.
    ///
    /// Named for the selection's own subject rather than for its type, because
    /// [`Self::shadow_selection`] above is a *buffer* — the cut a cascade
    /// descended to — and two accessors of one name is a caller reaching for
    /// the wrong one.
    ///
    /// It is this frame's answer, written by [`Self::begin_frame`]: before the
    /// first frame every slot is free.
    /// Whether this frame took the shadow atlas as an earlier frame left it,
    /// rather than drawing it again.
    ///
    /// Topic 45's static-caching rung, read back. True means
    /// this frame recorded **no** shadow cull and no shadow pass, and every map
    /// sampled through [`Self::shadow_lights`]'s rectangles is the one the last
    /// frame that did draw put there — so a caller comparing two frames' pass
    /// lists, draw counts or GPU timings has to know which of them redrew.
    ///
    /// Decided by [`Self::begin_frame`] out of everything each group of the
    /// atlas is a function of — see `ForwardRenderer::shadow_group_record` —
    /// and it answers `false` before the first frame, because no frame has been
    /// opened and so none of them has held anything.
    ///
    /// **Whole-atlas, and since the cadence rung a frame can be neither.** A
    /// frame that redraws one map and holds another answers `false` here and
    /// `false` from [`Self::shadow_slot_redrawn`] for the maps it held; the two
    /// together are what say which.
    #[must_use]
    pub const fn shadow_atlas_cached(&self) -> bool {
        self.shadow_atlas_cached
    }

    /// Whether this frame redrew cascade `cascade`'s map, rather than keeping
    /// the one an earlier frame put there.
    ///
    /// Topic 45's cadence rung, read back. **The observable
    /// that rung otherwise has none for**: a held map draws a shadow lagging its
    /// caster by a frame or two, which is a perfectly plausible picture and one
    /// a golden accepts — so nothing but this distinguishes a cadence that is
    /// working from one that is not running at all.
    ///
    /// `false` for a `cascade` past [`shadow::CASCADES`] and before the first
    /// frame, which is the same answer for the same reason: no map was drawn
    /// there.
    #[must_use]
    pub fn shadow_cascade_redrawn(&self, cascade: usize) -> bool {
        cascade < shadow::CASCADES && self.shadow_group_redrawn[cascade]
    }

    /// Whether this frame redrew the maps of light slot `slot` —
    /// [`shadow::Selection::slots`]' index — rather than keeping the ones an
    /// earlier frame put there.
    ///
    /// [`Self::shadow_cascade_redrawn`]'s answer for the light region, and a
    /// point light's [`shadow::POINT_FACES`] faces answer together: they cull
    /// once and draw one visible set, so they are redrawn or held as one.
    #[must_use]
    pub fn shadow_slot_redrawn(&self, slot: usize) -> bool {
        slot < shadow::LIGHT_SLOTS && self.shadow_group_redrawn[shadow_cull(slot)]
    }

    /// How many tiles of the atlas this frame redrew.
    ///
    /// What [`shadow::r_shadow_faces`] is spent in, read back — so a test can
    /// say the budget bound rather than that it was configured. A cascade costs
    /// one and a point light's cube costs [`shadow::POINT_FACES`].
    #[must_use]
    pub const fn shadow_faces_redrawn(&self) -> u32 {
        self.shadow_faces_redrawn
    }

    /// Pins the shadow cadence for this renderer, or hands it back to the
    /// console.
    ///
    /// [`Self::set_effect_request`]'s shape at this knob:
    /// [`shadow::r_shadow_cadence`] and [`shadow::r_shadow_faces`] are
    /// process-global, so they are the *default* rather than the only answer —
    /// an application drawing two views at two qualities, or a test that needs a
    /// frame nothing else in the process can move, pins its own.
    ///
    /// [`None`] hands it back, which is what a renderer starts at.
    ///
    /// Read once per [`Self::begin_frame`], on `ForwardRenderer::frame_effects`'
    /// terms: this call decides it and `add_passes` acts on it.
    pub const fn set_shadow_cadence(&mut self, cadence: Option<shadow::Cadence>) {
        self.shadow_cadence_request = cadence;
    }

    /// Whether this frame ignored the cadence for at least one map because the
    /// region that map covers had moved out from under it.
    ///
    /// Topic 45's "a moving light or camera cut resets it",
    /// made precise: a map is *reset* rather than merely out of date when the
    /// centre it is projected from has moved further than the map's own reach —
    /// a light further than its own radius, or a cascade's eye further than the
    /// sphere that cascade was fitted to. Holding such a map is not a shadow
    /// that lags; it is a shadow of somewhere else.
    ///
    /// A frame whose atlas was **relaid** — a light gained, lost or resized a
    /// tile, or shadows were switched on or off — answers `true` as well, and
    /// that frame redraws every map it has: the only clear this seam can make
    /// covers the whole image, so there is nothing left to hold.
    #[must_use]
    pub const fn shadow_cadence_reset(&self) -> bool {
        self.shadow_cadence_reset
    }

    #[must_use]
    pub const fn shadow_lights(&self) -> &shadow::Selection {
        &self.shadow_lights
    }

    /// The shadow atlas, for a caller that wants to read it back.
    ///
    /// **The observable this whole slice can otherwise hide behind.** A shadow
    /// pass that renders nothing leaves every texel at
    /// [`depth::CLEAR`](crcbl_hal::depth::CLEAR) and produces a frame in which
    /// everything is lit — which is a perfectly plausible picture and matches
    /// any golden blessed from it. Copying this image back and finding a texel
    /// that is not the clear value is what distinguishes the two.
    ///
    /// It is created with
    /// [`ImageUsage::TRANSFER_SRC`](crcbl_hal::ImageUsage::TRANSFER_SRC) for
    /// exactly that, and its extent is [`shadow::atlas_extent`].
    #[must_use]
    pub const fn shadow_atlas(&self) -> crcbl_hal::ImageHandle {
        self.shadow_atlas
    }

    /// The view [`shadow_atlas`](Self::shadow_atlas) is bound and imported
    /// through, for a reader importing the atlas into a graph of its own.
    #[must_use]
    pub const fn shadow_atlas_view(&self) -> ImageViewHandle {
        self.shadow_atlas_view
    }

    /// The base-colour page every material row samples through
    /// [`GpuMaterial::base_color_texture`](crcbl_shaders::mesh::GpuMaterial::base_color_texture),
    /// as the image and the view [`crate::texture`] uploaded.
    ///
    /// **What a render-to-texture view copies into.** A second camera drawing
    /// into an image is only half of a monitor: the surface that *shows* it
    /// samples a page layer, and nothing above this crate can name the image
    /// that layer lives in.
    ///
    /// A caller that wants to *write* it wants
    /// [`base_color_page_import`](Self::base_color_page_import) instead: the
    /// graph can only order a copy against the draws that sample the page while
    /// both are declared, and the two declarations have to agree field for
    /// field. This one is the raw handles, for a caller that binds or reads them
    /// outside a graph.
    ///
    /// It is created with
    /// [`ImageUsage::TRANSFER_DST`](crcbl_hal::ImageUsage::TRANSFER_DST),
    /// because the upload that filled it is a copy, so a per-frame copy into it
    /// needs no new usage flag. Its extent is
    /// [`PageDesc::extent`](crate::scene::PageDesc::extent) of
    /// [`PageKind::BaseColor`] squared and it has one layer per
    /// [`PageDesc::layers`](crate::scene::PageDesc::layers) entry of that kind;
    /// the description is the caller's, so the caller already knows both. A
    /// description naming no base-colour layer gets a 1×1 placeholder instead —
    /// see this module's `PAGE_PLACEHOLDER_TEXEL`.
    #[must_use]
    pub const fn base_color_page(&self) -> UploadedTexture {
        self.base_color_page
    }

    /// What [`add_passes`](Self::add_passes) names the base-colour page in the
    /// graph.
    ///
    /// [`RenderGraph::import_image`] keeps the label of whichever import ran
    /// first, so a caller importing the page too passes this rather than a
    /// string of its own — otherwise every barrier record and
    /// [`dump`](crate::CompiledGraph::dump) line would name the page differently
    /// depending on which subsystem got there first.
    pub const BASE_COLOR_PAGE_LABEL: &'static str = "base-colour-page";

    /// The base-colour page **as this renderer declares it to a graph**.
    ///
    /// [`add_passes`](Self::add_passes) imports exactly this value under
    /// [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL) and declares a read
    /// of it on every pass whose bind group names the page, so a caller that
    /// writes the page — a render-to-texture view copied into one layer — gets
    /// the graph to order its write against those draws.
    ///
    /// **A caller that writes it imports this value rather than one of its
    /// own.** [`RenderGraph::import_image`] hands the second importer the id the
    /// first got, which is what puts the write and the reads on one state
    /// tracker, and it does that only while the two declarations agree in every
    /// field — a disagreement is [`GraphError::ImportDeclarationConflict`] at
    /// [`compile`](RenderGraph::compile). Reading the declaration off the
    /// renderer that owns the page is what makes them one answer instead of two
    /// constants that have to be kept equal by hand.
    ///
    /// [`InitialClaim::Tracked`] with [`ResourceState::ShaderRead`] both ways:
    /// [`crate::texture`] leaves an uploaded page in that state, and the
    /// trailing barrier the `final_state` asks for puts it back there at the end
    /// of every frame — so the pool's ledger and this declaration are the same
    /// answer, which is what `Tracked` has the graph check.
    ///
    /// [`GraphError::ImportDeclarationConflict`]: crate::graph::GraphError::ImportDeclarationConflict
    #[must_use]
    pub const fn base_color_page_import(&self) -> ImportedImage {
        ImportedImage {
            image: self.base_color_page.image,
            view: self.base_color_page.view,
            format: BASE_COLOR_PAGE_FORMAT,
            extent: self.page_extents[PageKind::BaseColor.index()],
            initial: ResourceState::ShaderRead,
            claim: InitialClaim::Tracked,
            final_state: ResourceState::ShaderRead,
        }
    }

    /// Topic 43 §2's **normal** page, the raw handles.
    ///
    /// [`base_color_page`](Self::base_color_page)'s counterpart, on every one of
    /// its terms: one `D2Array` image, one layer per
    /// [`PageDesc::layers`](crate::scene::PageDesc::layers) entry of
    /// [`PageKind::Normal`], at **that kind's own extent**, and created with
    /// [`ImageUsage::TRANSFER_DST`](crcbl_hal::ImageUsage::TRANSFER_DST) so a
    /// per-frame copy into a layer needs no new usage flag. What it is *not* is
    /// the same format: it is `Rgba8Unorm`, where the base-colour page is
    /// `Rgba8UnormSrgb`, and topic 44's rung 2 is where that
    /// is argued.
    #[must_use]
    pub const fn normal_page(&self) -> UploadedTexture {
        self.normal_page
    }

    /// What [`add_passes`](Self::add_passes) names the normal page in the graph,
    /// on [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
    pub const NORMAL_PAGE_LABEL: &'static str = "normal-page";

    /// The normal page **as this renderer declares it to a graph**, on
    /// [`base_color_page_import`](Self::base_color_page_import)'s terms exactly
    /// — including that a caller writing a layer imports *this* value rather
    /// than one of its own, so the write and the draws land on one state
    /// tracker.
    #[must_use]
    pub const fn normal_page_import(&self) -> ImportedImage {
        ImportedImage {
            image: self.normal_page.image,
            view: self.normal_page.view,
            format: NORMAL_PAGE_FORMAT,
            extent: self.page_extents[PageKind::Normal.index()],
            initial: ResourceState::ShaderRead,
            claim: InitialClaim::Tracked,
            final_state: ResourceState::ShaderRead,
        }
    }

    /// Topic 43 §2's packed
    /// **metallic-roughness-occlusion** page, the raw handles.
    ///
    /// [`normal_page`](Self::normal_page)'s counterpart, on every one of its
    /// terms and at the same `Rgba8Unorm` format: a layer of it is glTF's
    /// occlusion, roughness and metallic in `r`, `g` and `b`, which are numbers
    /// rather than a colour — see this module's `MRO_PAGE_FORMAT`.
    #[must_use]
    pub const fn mro_page(&self) -> UploadedTexture {
        self.mro_page
    }

    /// What [`add_passes`](Self::add_passes) names the
    /// metallic-roughness-occlusion page in the graph, on
    /// [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
    pub const MRO_PAGE_LABEL: &'static str = "metallic-roughness-occlusion-page";

    /// The metallic-roughness-occlusion page **as this renderer declares it to a
    /// graph**, on [`base_color_page_import`](Self::base_color_page_import)'s
    /// terms exactly.
    #[must_use]
    pub const fn mro_page_import(&self) -> ImportedImage {
        ImportedImage {
            image: self.mro_page.image,
            view: self.mro_page.view,
            format: MRO_PAGE_FORMAT,
            extent: self.page_extents[PageKind::MetallicRoughnessOcclusion.index()],
            initial: ResourceState::ShaderRead,
            claim: InitialClaim::Tracked,
            final_state: ResourceState::ShaderRead,
        }
    }

    /// Topic 43 §2's **emissive** page, the raw
    /// handles.
    ///
    /// [`base_color_page`](Self::base_color_page)'s counterpart down to the
    /// format: an emissive texel is a colour, so this image is
    /// `Rgba8UnormSrgb` and the sampler decodes it — see this module's
    /// `EMISSIVE_PAGE_FORMAT`.
    #[must_use]
    pub const fn emissive_page(&self) -> UploadedTexture {
        self.emissive_page
    }

    /// What [`add_passes`](Self::add_passes) names the emissive page in the
    /// graph, on [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
    pub const EMISSIVE_PAGE_LABEL: &'static str = "emissive-page";

    /// The emissive page **as this renderer declares it to a graph**, on
    /// [`base_color_page_import`](Self::base_color_page_import)'s terms exactly.
    #[must_use]
    pub const fn emissive_page_import(&self) -> ImportedImage {
        ImportedImage {
            image: self.emissive_page.image,
            view: self.emissive_page.view,
            format: EMISSIVE_PAGE_FORMAT,
            extent: self.page_extents[PageKind::Emissive.index()],
            initial: ResourceState::ShaderRead,
            claim: InitialClaim::Tracked,
            final_state: ResourceState::ShaderRead,
        }
    }

    /// The model matrix for a cube spinning at `seconds` into the run.
    ///
    /// Two axes at incommensurable rates, so the animation never repeats and
    /// every face comes into view — which is what makes "the cube is spinning"
    /// observable rather than a claim about a matrix.
    #[must_use]
    pub fn spin(seconds: f32) -> Mat4 {
        Mat4::from_quat(
            Quat::from_axis_angle(Vec3::Y, seconds * 0.9)
                * Quat::from_axis_angle(Vec3::X, seconds * 0.55),
        )
    }

    /// The format the tonemap pass renders into.
    #[must_use]
    pub const fn target_format(&self) -> Format {
        self.target_format
    }

    /// Switches the infinite ground grid on with `style`, or off with [`None`].
    ///
    /// **Off by default.** Every sample and every golden image predates the
    /// grid, so a renderer nobody has called this on records exactly the passes
    /// it always did — see [`crate::grid`] for what the pass is and
    /// [`add_passes`](Self::add_passes) for where in the frame it lands.
    ///
    /// The first `Some` builds the pipeline and the uniform ring; later calls
    /// only replace the style, and a `None` leaves both built. Releasing them
    /// here would mean releasing blocks the frames in flight may still be
    /// reading, so they are released by [`destroy`](Self::destroy) alone — the
    /// one call that already requires an idle device.
    ///
    /// # Errors
    ///
    /// [`HalError`] if the grid's pipeline or its blocks could not be created.
    /// Nothing is left switched on when that happens: the grid stays as it was.
    pub fn set_ground_grid(
        &mut self,
        device: &dyn Device,
        style: Option<GridStyle>,
    ) -> Result<(), HalError> {
        let Some(style) = style else {
            self.ground_grid_on = false;
            return Ok(());
        };
        let grid = match self.ground_grid.as_mut() {
            Some(grid) => grid,
            None => {
                // Built for the tonemap's target and the scene depth, because
                // those are the two attachments the pass is given — see
                // `add_passes`. Both are pipeline state, so a renderer whose
                // target format changed would need a new `Grid`; nothing in this
                // crate changes it after `build`, and `target_format` is kept
                // for exactly that reason.
                let grid = GroundGrid::new(
                    device,
                    self.primary.uniforms.len(),
                    self.target_format,
                    SCENE_DEPTH_FORMAT,
                )?;
                self.ground_grid.insert(grid)
            }
        };
        grid.set_style(style);
        self.ground_grid_on = true;
        Ok(())
    }

    /// The debug draw layer's immediate-mode buffer, to append to.
    ///
    /// The UI's debug item 5 (`docs/notes/tooling.md`): any system appends lines, boxes,
    /// spheres and frusta during the frame, and
    /// [`begin_frame`](Self::begin_frame) uploads and clears what is there — so
    /// a segment lives exactly the frame it was appended in and nothing has to
    /// be un-appended. See [`crate::debug_draw`] for where the pass lands and
    /// for the console switch that has to be on before anything is drawn.
    ///
    /// **Appending is free while the layer is off**, but building the geometry
    /// is the caller's: a system whose overlay costs something to compute asks
    /// [`DebugDraw::enabled`] first.
    pub fn debug_draw(&mut self) -> &mut DebugDraw {
        &mut self.debug_draw
    }

    /// How the ground grid is drawn, or [`None`] where it is switched off.
    ///
    /// The read-back half of [`set_ground_grid`](Self::set_ground_grid), and the
    /// observable a test asking "is the grid on" wants: a renderer that built
    /// the grid and then switched it off answers [`None`], because what it draws
    /// is what the question is about.
    #[must_use]
    pub fn ground_grid(&self) -> Option<&GridStyle> {
        self.ground_grid
            .as_ref()
            .filter(|_| self.ground_grid_on)
            .map(GroundGrid::style)
    }

    /// Whether this frame adds [`crate::sky_pass`]'s background pass.
    ///
    /// [`Sky::NONE`] with no atmosphere is the value a renderer nobody called
    /// [`set_sky`](Self::set_sky) or
    /// [`set_atmosphere`](Self::set_atmosphere) on holds, and it is checked
    /// here rather than left to the shader for the reason [`crate::sky_pass`]
    /// gives: a black gradient drawn over [`SCENE_CLEAR`] would *change* those
    /// frames, where adding no pass leaves them exactly as they were.
    fn draws_sky(&self) -> bool {
        self.sky != Sky::NONE || self.atmosphere.is_some()
    }

    /// Brings [`Self::sky_view`] up to the sun this frame has, a stripe of rows
    /// per frame.
    ///
    /// Called once per [`Self::begin_frame`]. The comparison is on the
    /// normalised parameters rather than on the [`Atmosphere`] a caller handed
    /// over, so re-setting the same sun spelled a different length is not a
    /// rebuild — and a caller that sets the same value every frame, which is
    /// the ordinary shape of a scene's update, pays the comparison and nothing
    /// else.
    ///
    /// # The first LUT is marched whole; every later one is marched in stripes
    ///
    /// A renderer that has no LUT has no sky to draw, so the first march after
    /// [`set_atmosphere`](Self::set_atmosphere) runs to completion inside this
    /// call and a caller that draws a single frame gets that frame's sky. After
    /// that there is always a finished LUT to show, so a sun that moved starts
    /// a [`SkyViewBuild`] and this steps it [`SKY_VIEW_BUILD_ROWS`] rows per
    /// frame — the frames in between keep drawing the LUT the last completed
    /// march produced, and no frame pays the whole march.
    ///
    /// # A sun that moves again restarts the march rather than finishing it
    ///
    /// The build in flight is kept only while its own sun is still the one the
    /// caller wants; a sun that moved during it is a new build from row zero,
    /// because finishing the old one would swap in a LUT for a sun that is
    /// already wrong and then immediately start marching again. **A sun that
    /// moves every frame therefore never completes a build and goes on showing
    /// the last one it finished** — a sky frozen at the sun it last caught up
    /// with, rather than a sky that stutters at whatever the march last passed.
    /// That is the trade this makes: the frame cost is bounded and the sky
    /// lags, where the whole-march rebuild it replaced had the sky exact and
    /// the frame cost unbounded. A caller that wants the sky exact stops the
    /// sun on a value and leaves it there: the march then completes, and the
    /// frames it takes are `SKY_VIEW_HEIGHT` over [`SKY_VIEW_BUILD_ROWS`].
    ///
    /// **The aerial-perspective LUT is marched in the same steps** — see
    /// [`SkyViewBuild`] — so the air in front of the scene arrives on the same
    /// frame as the sky and lags the sun by the same frames, never a sun apart
    /// from it. A change of [`Atmosphere::km_per_unit`] alone is a new march
    /// on the same terms, since it is part of the parameters compared.
    fn refresh_sky_view(&mut self) {
        let Some(atmosphere) = self.atmosphere else {
            self.sky_view = None;
            self.sky_view_build = None;
            return;
        };
        let parameters = atmosphere.parameters();
        if self
            .sky_view
            .as_ref()
            .is_some_and(|presented| presented.parameters == parameters)
        {
            self.sky_view_build = None;
            return;
        }
        if self.sky_view.is_none() {
            self.sky_view_build = None;
            self.sky_view = Some(PresentedSky::new(parameters, SkyView::build(&parameters)));
            return;
        }
        let mut build = match self.sky_view_build.take() {
            Some(build) if build.atmosphere() == parameters => build,
            _ => SkyViewBuild::start(&parameters),
        };
        if build.step(SKY_VIEW_BUILD_ROWS) {
            self.sky_view = Some(PresentedSky::new(parameters, build.finish()));
        } else {
            self.sky_view_build = Some(build);
        }
    }

    /// Sets the multiplier the tonemap pass applies before its clamp, clamped
    /// into [`EXPOSURE_MIN`]`..=`[`EXPOSURE_MAX`].
    ///
    /// **The default is [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`]**, which is
    /// the value `tonemap.slang` held as a compile-time constant until this
    /// became a runtime one — so a renderer nobody calls this on draws the frame
    /// it always drew, and every golden image is untouched.
    ///
    /// It takes effect on the next
    /// [`begin_frame`](Self::begin_frame), which is what writes the block: a
    /// frame already recorded reads the value it was recorded with.
    ///
    /// **The clamp is here rather than at the call site** so that no caller can
    /// reach a picture it cannot get back from, and so that a control which
    /// steps by reading this back and setting a multiple of it — which is what
    /// [`exposure`](Self::exposure) is for — cannot wind up past the end and
    /// then need as many presses to come back.
    pub const fn set_exposure(&mut self, exposure: f32) {
        // `max` then `min` rather than `f32::clamp`: `clamp` propagates a NaN,
        // and a NaN reaching the block is a frame of NaN pixels with no key to
        // press to get out of it. `f32::max` returns the bound instead, so a NaN
        // lands on `EXPOSURE_MIN` — dark, and one press from being bright again.
        self.exposure = exposure.max(EXPOSURE_MIN).min(EXPOSURE_MAX);
    }

    /// How far auto-exposure may travel toward its measurement in one frame.
    ///
    /// **[`None`] is the whole distance**, which is what a renderer nobody
    /// calls this on does and what the pass did before adaptation existed — so
    /// no golden moved when this arrived. A view that wants the roll asks, and
    /// asks *every frame*, because [`ExposureAdaptation`] carries that frame's
    /// own delta: this crate has no clock, and the frame time lives where the
    /// frame loop is.
    ///
    /// It takes effect on the next [`begin_frame`](Self::begin_frame), which is
    /// what writes the block, and it does nothing at all on a frame that did not
    /// ask for [`RenderEffects::AUTO_EXPOSURE`] — the passes that read it are
    /// the ones that bit adds.
    pub const fn set_exposure_adaptation(&mut self, adaptation: Option<ExposureAdaptation>) {
        self.exposure_adaptation = adaptation;
    }

    /// What [`set_exposure_adaptation`](Self::set_exposure_adaptation) was last
    /// handed.
    #[must_use]
    pub const fn exposure_adaptation(&self) -> Option<ExposureAdaptation> {
        self.exposure_adaptation
    }

    /// Which operator the tonemap pass runs on the exposed scene colour.
    ///
    /// **The ACES fit by default**, because this renderer shades in linear HDR
    /// and the roll-off is what that range is for. What a caller asks *for* here
    /// is therefore usually the other one: `tonemap.slang`'s clamp is the
    /// identity on `0..=1`, so display-referred content reaches the swapchain
    /// exactly, and a fixture that predicts a code value from a host model of
    /// the shading needs the frame to stay scene-referred. Every 2D sample in
    /// this tree draws through `crate::sprite_pass` and `crate::ui_pass`
    /// instead, so none of them reaches this pass at all.
    ///
    /// It takes effect on the next [`begin_frame`](Self::begin_frame), for
    /// [`set_exposure`](Self::set_exposure)'s reason: the block is written
    /// there, and a frame already recorded reads the value it was recorded
    /// with.
    ///
    /// **There is nothing to refuse and no `supports_` probe beside it.** The
    /// selector is a lane of a uniform block read by a branch every device
    /// already runs, so unlike the wireframe there is no second pipeline for a
    /// device to decline to build.
    pub const fn set_tonemap_curve(&mut self, curve: tonemap::TonemapCurve) {
        self.tonemap_curve = curve;
    }

    /// The operator in force, on [`exposure`](Self::exposure)'s terms: the
    /// value the next frame will be drawn with.
    #[must_use]
    pub const fn tonemap_curve(&self) -> tonemap::TonemapCurve {
        self.tonemap_curve
    }

    /// How large the internal render target is as a fraction of the extent
    /// [`begin_frame`](Self::begin_frame) is handed, clamped to
    /// `MIN_RENDER_SCALE..=1.0`.
    ///
    /// **This is the largest performance knob this renderer has.** Every pass
    /// before the upscale costs what its extent costs, so a scale of `0.7` is
    /// roughly half the shading work of `1.0`; the UI is composited onto the
    /// target afterwards at native resolution, so text stays sharp while the 3D
    /// frame gets cheap. `docs/notes/rendering.md` (_What the deleted
    /// 48-post-processing plan left behind_) is where that trade is written down.
    ///
    /// **`1.0` is not a special case with a fast path, it is the absence of the
    /// feature.** At full scale the internal extent *is* the caller's, the post
    /// chain writes the target directly, and no upscale pass is recorded — which
    /// is what makes a renderer nobody has called this on draw the frame it drew
    /// before the knob existed, bit for bit.
    ///
    /// **Above `1.0` is clamped away rather than supported.** Supersampling
    /// wants a box or Lanczos reduction and `upscale.slang` is a Catmull-Rom
    /// *reconstruction*; running it as a minification filter would alias, which
    /// is the opposite of what a caller asking for it wants. A non-finite scale
    /// is clamped to `1.0` for the same reason a `NaN` extent would be refused:
    /// the failure it produces is a zero-sized target somewhere downstream.
    ///
    /// Takes effect on the next [`begin_frame`](Self::begin_frame), on
    /// [`set_exposure`](Self::set_exposure)'s terms exactly — a frame already
    /// recorded is drawn at the scale it was recorded with.
    pub fn set_render_scale(&mut self, scale: f32) {
        self.render_scale = if scale.is_finite() {
            scale.clamp(MIN_RENDER_SCALE, 1.0)
        } else {
            1.0
        };
    }

    /// The render scale in force, after the clamp
    /// [`set_render_scale`](Self::set_render_scale) applied.
    ///
    /// The read-back half, on [`exposure`](Self::exposure)'s terms.
    #[must_use]
    pub const fn render_scale(&self) -> f32 {
        self.render_scale
    }

    /// The anisotropy the base-colour page is sampled with, in force from the
    /// next [`begin_frame`](Self::begin_frame).
    ///
    /// Topic 43's filtering rung, the player's half:
    /// [`anisotropy_for`](Self::anisotropy_for) is what a renderer nobody has
    /// called this on samples with, and this is what a settings row moves it
    /// to. Clamped to `1.0..=max_sampler_anisotropy` where the device was
    /// granted [`Features::SAMPLER_ANISOTROPY`] and to exactly `1.0` where it
    /// was not — the row can turn the filter off or push it to the device's
    /// ceiling, and nothing it asks reaches a `create_sampler` that would
    /// refuse it. A value that is not a number is the default, on
    /// [`set_render_scale`](Self::set_render_scale)'s terms.
    ///
    /// **A sampler is a resource a bind group holds by handle**, so a new
    /// anisotropy is a new sampler, and every group of the mesh layout has to
    /// be rebuilt to name it. That happens per frame slot, at the slot's own
    /// `begin_frame`, which is the moment the ring guarantees the slot's
    /// previous submission has retired — the guarantee every host write in
    /// that call already leans on — so a frame in flight goes on naming the
    /// sampler it was recorded with, and the replaced sampler is destroyed once
    /// no slot names it. This call creates the sampler and nothing else, and
    /// asking for the anisotropy already in force creates nothing.
    ///
    /// # Errors
    ///
    /// `create_sampler`'s, and the renderer is unchanged — the sampler in force
    /// stays in force.
    pub fn set_anisotropy(&mut self, device: &dyn Device, anisotropy: f32) -> Result<(), HalError> {
        let caps = device.caps();
        let ceiling = if caps.features.contains(Features::SAMPLER_ANISOTROPY) {
            caps.limits.max_sampler_anisotropy
        } else {
            1.0
        };
        let wanted = if anisotropy.is_finite() {
            anisotropy.clamp(1.0, ceiling)
        } else {
            Self::anisotropy_for(&caps)
        };
        // Bit-equal rather than within an epsilon: both sides came out of the
        // same clamp, and a row that lands on the value in force must not
        // rebuild every group for it.
        if wanted.to_bits() == self.anisotropy.to_bits() {
            return Ok(());
        }
        let sampler = Self::create_page_sampler(device, wanted)?;
        self.retired_pages
            .push(RetiredPage::Sampler(std::mem::replace(
                &mut self.base_color_sampler,
                sampler,
            )));
        self.anisotropy = wanted;
        Ok(())
    }

    /// The anisotropy in force, after the clamp
    /// [`set_anisotropy`](Self::set_anisotropy) applied.
    ///
    /// The read-back half, on [`render_scale`](Self::render_scale)'s terms.
    #[must_use]
    pub const fn anisotropy(&self) -> f32 {
        self.anisotropy
    }

    /// The anisotropy the base-colour page's sampler is created with on a
    /// device of `caps`: [`DEFAULT_ANISOTROPY`] clamped to
    /// [`Limits::max_sampler_anisotropy`](crcbl_hal::Limits) where
    /// [`Features::SAMPLER_ANISOTROPY`] was granted, and `1.0` where it was
    /// not.
    ///
    /// **Granted, not supported.** The feature is optional at every open site
    /// — [`Features::GPU_DRIVEN`] does not carry it — and a device opened
    /// without asking refuses a sampler above one even on hardware that has
    /// it, which is the shape every backend's `create_sampler` documents. So
    /// the question is what this device was opened *with*, and a caller that
    /// wants the plan's default has to name the feature beside the others it
    /// asks for. `crcbl-webgpu` withholds the feature and reports a ceiling of
    /// one, so a browser samples isotropically until `docs/backlog.md`'s
    /// ceiling decision is taken.
    #[must_use]
    pub fn anisotropy_for(caps: &DeviceCaps) -> f32 {
        if caps.features.contains(Features::SAMPLER_ANISOTROPY) {
            DEFAULT_ANISOTROPY.min(caps.limits.max_sampler_anisotropy)
        } else {
            1.0
        }
    }

    /// The base-colour page's sampler at `anisotropy`, which the caller has
    /// already held to the device — [`anisotropy_for`](Self::anisotropy_for)
    /// at build, [`set_anisotropy`](Self::set_anisotropy)'s clamp after.
    ///
    /// **Trilinear over the whole chain, anisotropic where the device is** —
    /// topic 43's filtering rung: a minified surface
    /// reads the level its footprint matches instead of shimmering through
    /// level 0, a magnified one blends four texels instead of stepping between
    /// them, and a surface at a grazing angle keeps its detail along the long
    /// axis of its footprint rather than blurring to the short one. A second
    /// sampler object rather than sharing the tonemap's, so a capture names
    /// each for what it filters.
    ///
    /// **`Repeat`, not `ClampToEdge`**, and that is what `mesh.slang`'s
    /// `TILING_PHYSICAL` needs: a physical UV runs to `world_extent /
    /// tile_metres`, past `0..1` on any face wider than one tile, and only a
    /// wrapping address mode makes the page tile across it rather than
    /// smearing its edge row. `TILING_AUTHORED` is unaffected — its UV is the
    /// vertex's, which the meshes author inside `0..1`, so a wrapped and a
    /// clamped read return the same nearest texel for it.
    fn create_page_sampler(
        device: &dyn Device,
        anisotropy: f32,
    ) -> Result<SamplerHandle, HalError> {
        device.create_sampler(&SamplerDesc {
            label: Some("material base colour"),
            mag_filter: FilterMode::Linear,
            min_filter: FilterMode::Linear,
            mip_filter: FilterMode::Linear,
            address_mode: [SamplerAddressMode::Repeat; 3],
            anisotropy,
            ..SamplerDesc::default()
        })
    }

    /// The extent a frame handed `target` is actually drawn at.
    ///
    /// Rounds rather than truncates, and floors at one texel in each dimension:
    /// a zero here would reach a transient image description, and an image of
    /// zero extent is a device error rather than a small frame. A caller who
    /// minimised the window already hands a zero extent through, and that path
    /// is unchanged — `max(1)` on a zero is one either way.
    fn internal_extent(&self, target: (u32, u32)) -> (u32, u32) {
        if self.render_scale >= 1.0 {
            return target;
        }
        let scale = f64::from(self.render_scale);
        (
            ((f64::from(target.0) * scale).round() as u32).max(1),
            ((f64::from(target.1) * scale).round() as u32).max(1),
        )
    }

    /// The exposure in force, after the clamp
    /// [`set_exposure`](Self::set_exposure) applied.
    ///
    /// The read-back half, on [`ground_grid`](Self::ground_grid)'s terms: what a
    /// caller wants is the number the frame is drawn with, not the one it asked
    /// for — which is also what makes a multiplicative step land on the end of
    /// the range rather than run past it.
    #[must_use]
    pub const fn exposure(&self) -> f32 {
        self.exposure
    }

    /// Whether `device` can draw the wireframe view at all.
    ///
    /// The question [`set_wireframe`](Self::set_wireframe) answers with an
    /// error, asked **before** anything is switched on — so an application can
    /// tell its user that this device has no wireframe rather than binding a key
    /// that fails, and can say so once at start-up instead of on every press.
    /// WebGPU has no line fill mode at all, so the browser is the case this
    /// exists for and not a hypothetical.
    ///
    /// An associated function rather than a method: it is a fact about the
    /// device, and a caller wants it before it has decided anything.
    #[must_use]
    pub fn supports_wireframe(device: &dyn Device) -> bool {
        device.caps().supports(Features::POLYGON_MODE_LINE)
    }

    /// Asks every camera's cull to drop what is hidden or too small to see —
    /// topic 03 §3.3's occlusion cull and its
    /// small-feature test. See [`crate::occlusion_cull`].
    ///
    /// [`OcclusionCulling::occlusion`] **changes no pixel**: the first phase
    /// guesses from the previous frame's depth, the second tests every rejected
    /// instance against this frame's, and only the second's rejections are
    /// dropped. [`OcclusionCulling::small_feature_pixels`] does change pixels,
    /// and is off unless a threshold is named.
    ///
    /// Taken from the next [`begin_frame`](Self::begin_frame), and combined with
    /// the `r_occlusion_cull` and `r_small_feature_px` console switches — either
    /// side turning a cull on turns it on. A wireframe frame culls by the frustum
    /// alone, because a wireframe shows the edges a depth test would hide.
    pub fn set_occlusion_culling(&mut self, culling: OcclusionCulling) {
        self.occlusion_culling = culling;
    }

    /// Whether a point light's shadow cull tags each caster with the faces of
    /// its cube it reaches, so each face draws only those — **on** by default.
    ///
    /// Off is the cull this replaced: one test against the light's box, and
    /// every caster in it drawn into all six faces for the rasteriser to clip.
    /// The two write the same atlas, texel for texel — the six faces' pyramids
    /// tile the box, so a caster a face drops has no texel in that face's tile —
    /// and the switch exists so a test can hold them against each other and a
    /// price can be read off both.
    pub fn set_point_face_culls(&mut self, on: bool) {
        self.point_face_culls = on;
    }

    /// **A test hook**: from the next [`begin_frame`](Self::begin_frame),
    /// rewrites every block the shadow atlas's depth pass is fed with `tamper`
    /// on its way to the GPU, or stops doing so with [`None`] — the default,
    /// and the only value a frame outside a test runs under.
    ///
    /// Applied **after** the atlas cache has read the blocks, so the rewrite is
    /// invisible to the decision whether to redraw a map and visible only to the
    /// depth pass that draws it. That is what makes it a probe of the shaders:
    /// `crcbl`'s `mesh_e2e` `shadow_block_reads` draws the atlas with each
    /// [`UniformsReader::ColourOnly`] entry of [`FRAME_UNIFORMS_READERS`]
    /// perturbed through here and holds the depth to the untampered frame's, bit
    /// for bit. It reaches the atlas's views alone — not the probe updater's
    /// shadows-off writes, which draw nothing into the atlas.
    pub fn set_shadow_view_tamper(&mut self, tamper: Option<fn(&mut mesh::FrameUniforms)>) {
        self.shadow_view_tamper = tamper;
    }

    /// What [`set_occlusion_culling`](Self::set_occlusion_culling) last asked
    /// for, before the console switches and the wireframe are applied.
    #[must_use]
    pub const fn occlusion_culling(&self) -> OcclusionCulling {
        self.occlusion_culling
    }

    /// The culls the next frame runs: [`occlusion_culling`](Self::occlusion_culling)
    /// with the console switches applied, and nothing on a wireframe frame.
    #[must_use]
    pub fn resolved_occlusion_culling(&self) -> OcclusionCulling {
        if self.wireframe_on {
            return OcclusionCulling::OFF;
        }
        let console_pixels = crate::occlusion_cull::r_small_feature_px.get_f32();
        OcclusionCulling {
            occlusion: self.occlusion_culling.occlusion
                || crate::occlusion_cull::r_occlusion_cull.get_bool(),
            small_feature_pixels: self
                .occlusion_culling
                .small_feature_pixels
                .or((console_pixels > 0.0).then_some(console_pixels)),
        }
    }

    /// Draws the scene's triangles as lines, or goes back to filling them.
    ///
    /// **Off by default.** Every sample and every golden image predates the
    /// view, so a renderer nobody has called this on records exactly the frame
    /// it always did.
    ///
    /// # What it is, and what it is not
    ///
    /// The **colour pass** alone changes fill mode. The depth prepass and the
    /// shadow cascades keep drawing filled triangles, because they are what the
    /// occlusion pair and the shadow lookups read and depth drawn as lines is
    /// depth with holes in it. So a wireframe frame is the same geometry, the
    /// same shading and the same lights, rasterised as edges: what was inside a
    /// triangle becomes the clear colour, and what was on its edge stays lit.
    ///
    /// # It is built on the first `true`
    ///
    /// The pipeline is compiled here rather than beside the filled one at
    /// [`with_scene`](Self::with_scene), and that is the trade this
    /// call makes: one pipeline compile on the first press — a hitch, in a view
    /// the user just asked for — against a second compile in the start-up of
    /// every sample, golden run and headless test that never asks for one. Later
    /// calls only flip the switch, and a `false` leaves the pipeline built, for
    /// [`set_ground_grid`](Self::set_ground_grid)'s reason: releasing something
    /// the frames in flight may still be recording against is what
    /// [`destroy`](Self::destroy) — which already requires an idle device — is
    /// for.
    ///
    /// # Errors
    ///
    /// [`HalError::UnsupportedFeatures`] naming
    /// [`Features::POLYGON_MODE_LINE`](crcbl_hal::Features::POLYGON_MODE_LINE)
    /// when `on` is `true` on a device that has not got it — ask
    /// [`supports_wireframe`](Self::supports_wireframe) first. Refused rather
    /// than quietly filled: a caller who asked for a wireframe and got a solid
    /// frame back with no error has no way to tell that from a wireframe of a
    /// solid-looking model.
    ///
    /// [`HalError`] from the pipeline otherwise. **Nothing is left switched on
    /// when either happens**: the view stays as it was.
    pub fn set_wireframe(&mut self, device: &dyn Device, on: bool) -> Result<(), HalError> {
        if !on {
            self.wireframe_on = false;
            return Ok(());
        }
        if self.wireframe_pipeline.is_none() {
            if !Self::supports_wireframe(device) {
                return Err(HalError::UnsupportedFeatures {
                    missing: Features::POLYGON_MODE_LINE,
                });
            }
            let modules = MeshModules::new(device, self.emit, self.culls_clusters)?;
            let [single, double] = MeshModules::sided(|cull| {
                modules.color_pipeline(
                    device,
                    self.mesh_pipeline_layout,
                    PolygonMode::Line,
                    cull,
                    "wireframe",
                )
            });
            modules.destroy(device);
            // **Both or neither.** A caller that got one twin back would draw a
            // frame missing every double-sided surface and nothing would say
            // so; released here rather than kept, because `destroy` is what
            // releases what this field holds and it holds nothing yet.
            let pipelines = match (single, double) {
                (Ok(single), Ok(double)) => SidedPipelines { single, double },
                (Ok(built), Err(error)) | (Err(error), Ok(built)) => {
                    device.destroy_graphics_pipeline(built);
                    return Err(error);
                }
                (Err(error), Err(_)) => return Err(error),
            };
            self.wireframe_pipeline = Some(pipelines);
        }
        self.wireframe_on = true;
        Ok(())
    }

    /// Whether the colour pass draws lines instead of filled triangles.
    ///
    /// The read-back half of [`set_wireframe`](Self::set_wireframe), and the
    /// observable a test asking "is this frame a wireframe" wants: a renderer
    /// that built the pipeline and then switched it off answers `false`, because
    /// what it draws is what the question is about.
    #[must_use]
    pub const fn wireframe(&self) -> bool {
        self.wireframe_on
    }

    /// Draws each surface's **world-space** normal instead of shading it, so a
    /// modeller can see whether the normals a document carries are sane.
    ///
    /// **Off by default**, on [`set_wireframe`](Self::set_wireframe)'s terms: it
    /// is a tool's view of a document, and every sample and every golden image
    /// predates it. It takes effect on the next
    /// [`begin_frame`](Self::begin_frame), which is what writes the block.
    ///
    /// # What the colours mean
    ///
    /// The conventional encoding, `n * 0.5 + 0.5` into RGB: +X reads red, +Y
    /// green, +Z blue, and a face whose winding was inverted reads the
    /// **complement** of the colour it should have. A missing or degenerate
    /// normal reads as whatever the vertex data actually holds rather than as the
    /// plausible shading a light would have given it, which is the point.
    ///
    /// # World space, not view space
    ///
    /// The two diagnose different things and this one is world space, so a face
    /// keeps its colour while the camera orbits: "is this face inverted" is then
    /// something a modeller *sees*, instead of inferring it from a picture that
    /// re-colours whenever they move. View-space normals answer the other
    /// question — is this normal smooth, is this seam split — by re-colouring on
    /// purpose, and they are not a thing this block could express anyway: it
    /// carries `view_proj` and no separate view matrix, so there is no rotation in
    /// the shader to take a normal into eye space with.
    ///
    /// # It builds nothing and adds no pass
    ///
    /// Unlike the wireframe, which needs a second pipeline and so a device that
    /// can build one: this is one lane of the frame's uniform block — see
    /// [`FrameUniforms::NORMALS_VIEW_ON`] — read by a branch in the fragment
    /// stage every device already runs. There is nothing to refuse and nothing to
    /// release, which is why it cannot fail and there is no `supports_` probe
    /// beside it.
    ///
    /// The tonemap still applies: at
    /// [`DEFAULT_EXPOSURE`](crcbl_shaders::tonemap::DEFAULT_EXPOSURE) its operator
    /// is the identity on `0..=1` and the encoded normal reaches the swapchain
    /// exactly, and at any other exposure the picture is scaled per channel — so
    /// which channel dominates a face never changes, but a caller reading exact
    /// values wants [`set_exposure`](Self::set_exposure) left alone.
    ///
    /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
    pub const fn set_normals_view(&mut self, on: bool) {
        self.normals_view = on;
    }

    /// Sets the exponential height fog the colour pass composites over every
    /// shaded surface.
    ///
    /// Topic 43 §4's cheapest large win: distance
    /// reads as distance, a valley fills while a hilltop stays clear, and it
    /// costs four numbers in a block every pipeline already binds.
    ///
    /// # It adds no pass and cannot fail
    ///
    /// On [`set_normals_view`](Self::set_normals_view)'s terms exactly — two
    /// rows of the frame's uniform block, read by arithmetic in the fragment
    /// stage every device already runs. There is nothing to build, so there is
    /// nothing to refuse and no `supports_` probe beside it.
    ///
    /// # Off is exactly off
    ///
    /// [`Fog::NONE`] is the default and a zero density is an *exact* identity,
    /// not an approximate one: the optical depth is zero, its transmittance is
    /// exactly one, and `mesh.slang` composites as `lit * t + fog * (1 - t)`
    /// rather than as a `lerp`, which at `t == 1` would return
    /// `fog + (lit - fog)` and lose the low bits of an HDR radiance far from
    /// the fog colour. So this feature moves no frame it is not switched on
    /// for.
    ///
    /// # What it does not fog
    ///
    /// The screen-space reflections `ssr_blur.slang` adds **after** this pass,
    /// which arrive unfogged onto an already-fogged surface — see
    /// `docs/backlog.md`. Fog is applied where the radiance is finished, and
    /// the reflection composite is one pass later.
    pub const fn set_fog(&mut self, fog: Fog) {
        self.fog = fog;
    }

    /// Lights the scene with a gradient sky, on top of whatever ambient and
    /// irradiance grid it already has.
    ///
    /// Topic 43 §8's rung. [`Sky`] is three
    /// radiances — zenith, horizon, ground — and what reaches a surface is that
    /// gradient projected onto the L1 basis the probe grid already uses, so a
    /// surface facing up receives the sky and one facing down the ground's
    /// bounce. Three colours, no extra pass.
    ///
    /// # It adds no pass and cannot fail
    ///
    /// On [`set_fog`](Self::set_fog)'s terms exactly — three rows of the
    /// frame's uniform block and three dot products in a fragment stage every
    /// device already runs. Nothing to build, so nothing to refuse and no
    /// `supports_` probe beside it.
    ///
    /// # Off is exactly off
    ///
    /// [`Sky::NONE`] is the default and a black gradient projects to every
    /// coefficient zero — each is a product with a zero factor — so the
    /// fragment stage adds `max(0, 0)` and the ambient sum is the one it was
    /// before this existed, bit for bit.
    ///
    /// # What it does not do
    ///
    /// **Draw anything.** The background is still the scene target's clear
    /// colour, and a scene lit by a sky it cannot see is what this rung leaves
    /// behind until the pass that draws the gradient lands. The environment
    /// `ssr.slang` falls back to on a missed ray is still the probe grid's, so
    /// a mirror under a sky still reflects whatever the probes hold.
    pub const fn set_sky(&mut self, sky: Sky) {
        self.sky = sky;
    }

    /// Replaces the gradient with Hillaire's atmosphere, or `None` to put the
    /// gradient back.
    ///
    /// Topic 43 §8. A frame with an atmosphere takes
    /// it for all three of the things a sky is: the background the sky pass
    /// draws, the L1 ambient term `mesh.slang` adds, and the environment
    /// `ssr.slang` falls back to when a ray hits nothing. The
    /// [`Sky`] a caller may also have set is not read on those frames.
    ///
    /// # What it costs
    ///
    /// **A march on the host, not on the device.** The first
    /// [`begin_frame`](Self::begin_frame) after this is called marches
    /// [`crcbl_shaders::atmosphere::SkyView`] whole, which is tens of
    /// milliseconds of CPU — a renderer with no LUT has no sky, so that one is
    /// paid where it is asked for. Every later move of the sun is marched
    /// [`SKY_VIEW_BUILD_ROWS`] rows per frame with the last finished LUT still
    /// drawn, so no frame after the first pays the whole march;
    /// `refresh_sky_view` is where that is written down, including what a sun
    /// that moves *every* frame gets. A frame whose
    /// sun has not moved costs the comparison that finds nothing to do and
    /// nothing else: the LUT's two projections are cached beside it. The device
    /// pays four buffer loads and a blend, which is what the gradient pays.
    ///
    /// # Off is exactly off
    ///
    /// `None` is the default, and a renderer nobody calls this on writes the
    /// same block, adds the same passes and draws the same frame it did before
    /// this existed — `sky.slang`'s arm is
    /// [`crcbl_shaders::sky::ATMOSPHERE_OFF`], which is exactly zero.
    ///
    /// # What it does not do
    ///
    /// **Draw the sun.** The LUT holds the scattered sky and not the disc, as
    /// the paper's does; the sun itself is the [`DirectionalLight`] the forward
    /// pass already shades with, and pointing the two the same way is the
    /// caller's job.
    ///
    /// **Put the air in front of a surface.** That is the paper's third LUT and
    /// this engine's froxel column, and neither reads this.
    pub fn set_atmosphere(&mut self, atmosphere: Option<Atmosphere>) {
        self.atmosphere = atmosphere;
    }

    /// The bodies of water every view draws — `docs/plan/55-water.md`'s rung 1,
    /// and this crate's `water` module for how.
    ///
    /// Replaces whatever was set before. Each body is meshed here, by
    /// [`crcbl_water::surface_mesh`], and the result is uploaded to each frame
    /// slot as that slot next begins, so the call touches no device and a frame
    /// still in flight keeps the buffers it was submitted with.
    ///
    /// # Off is exactly off
    ///
    /// An empty slice is the default, and a renderer with no bodies records no
    /// water pass at all: the frame it draws is the one it drew before this
    /// existed, bit for bit. Water is content, not a
    /// [`RenderEffects`] bit, on [`set_sky`](Self::set_sky)'s terms.
    ///
    /// # Errors
    ///
    /// [`crcbl_water::BodyError`] for the first body that cannot be meshed —
    /// too few points, a non-finite coordinate, an outline that crosses itself,
    /// a negative coefficient — and then **nothing is replaced**: the bodies set
    /// before this call go on drawing.
    pub fn set_water(
        &mut self,
        bodies: &[crcbl_water::WaterBody],
    ) -> Result<(), crcbl_water::BodyError> {
        self.water.set(bodies)
    }

    /// The bodies of water this renderer draws, as they were last set.
    #[must_use]
    pub fn water(&self) -> &[crcbl_water::WaterBody] {
        self.water.bodies()
    }

    /// The field of grass every view draws — `docs/plan/57-grass.md`'s rungs G1
    /// and G3, and this crate's `grass` module for how.
    ///
    /// Replaces whatever was set before. The field's ground, cover map, blade
    /// table and per-tile blocks are uploaded here, and the buffers a dispatch
    /// writes are created here; a field replaced while a frame is in flight
    /// leaves its resources alive until the ring has come round, so the call is
    /// safe at any point between frames.
    ///
    /// # Off is exactly off
    ///
    /// [`None`] is the default, and a renderer with no field records no grass
    /// pass at all: the frame it draws is the one it drew before this existed,
    /// bit for bit. Grass is content, not a [`RenderEffects`] bit, on
    /// [`set_water`](Self::set_water)'s terms.
    ///
    /// # Errors
    ///
    /// [`crate::grass::SetError::Field`] for a description the field itself
    /// refuses — no tiles, a zero texel scale, an empty blade table — and then
    /// **nothing is replaced**: the field set before this call goes on drawing.
    /// [`crate::grass::SetError::Hal`] for a seam call that failed, on the same
    /// terms.
    pub fn set_grass(
        &mut self,
        device: &dyn Device,
        queue: QueueHandle,
        field: Option<&crate::grass::GrassField>,
    ) -> Result<(), crate::grass::SetError> {
        self.grass.set(device, queue, field)
    }

    /// The field of grass this renderer draws, as it was last set.
    #[must_use]
    pub fn grass(&self) -> Option<&crate::grass::GrassField> {
        self.grass.field()
    }

    /// The two buffers the grass generation pass writes, or [`None`] for a
    /// renderer with no field.
    ///
    /// What `crcbl`'s `render_e2e` copies back to check the placement blade by
    /// blade and to read each slot's instance count, on
    /// [`froxel_buffers`](Self::froxel_buffers)' terms — see
    /// [`crate::grass::GrassBuffers`] for the layout. They hold whatever the
    /// last frame that generated left there, which for a field nobody has drawn
    /// yet is undefined rather than empty.
    #[must_use]
    pub fn grass_buffers(&self) -> Option<crate::grass::GrassBuffers> {
        self.grass.buffers()
    }

    /// The two authored wind layers `docs/plan/56-wind.md`'s decision 1 names,
    /// as the GPU copy of the field samples them.
    ///
    /// [`None`] restores the calm placeholder: one texel of no deflection and
    /// one of zero intensity, which is what makes a field with no weather set
    /// stand still. A replaced pair waits for the ring exactly as a replaced
    /// field does.
    ///
    /// # Errors
    ///
    /// [`crate::grass::WindLayerError`] for a layer that is not four bytes a
    /// texel of the grid it came with, or a seam call that failed.
    pub fn set_wind_layers(
        &mut self,
        device: &dyn Device,
        queue: QueueHandle,
        layers: Option<&crate::grass::WindLayers>,
    ) -> Result<(), crate::grass::WindLayerError> {
        self.grass.set_wind_layers(device, queue, layers)
    }

    /// The wind's uniform block for the frames from here on —
    /// `crcbl_wind::WindField::gpu_params`, which is where the authoritative
    /// `f64` formula is narrowed to `f32`.
    ///
    /// Everything in it is camera-relative or already wrapped, so a caller
    /// writes it once per frame from the field's own state and never from a
    /// world-scale coordinate. The default is a base speed of zero, which is
    /// calm.
    pub const fn set_wind(&mut self, params: crcbl_shaders::wind::WindParams) {
        self.wind = params;
    }

    /// The wind block this renderer writes, as it was last set.
    #[must_use]
    pub const fn wind(&self) -> crcbl_shaders::wind::WindParams {
        self.wind
    }

    /// The atmosphere this renderer draws, if it has one.
    #[must_use]
    pub const fn atmosphere(&self) -> Option<Atmosphere> {
        self.atmosphere
    }

    /// Draws each cluster tinted by the DAG level it was decimated to, instead
    /// of shading it.
    ///
    /// **The picture cluster LOD's whole claim rests on**: one mesh spanning
    /// several levels across its own surface is a statement a test can assert
    /// and nobody can see, and this is what makes it visible. The mesh path
    /// tints per cluster; the two indirect paths select one level per instance
    /// and have no per-cluster level at all, so they draw one flat grey — which
    /// is the comparison rather than a shortfall.
    ///
    /// Costs what [`set_normals_view`](Self::set_normals_view) costs: one lane
    /// of the frame's uniform block, read by a branch every device already runs.
    /// Nothing to build, nothing to refuse, nothing to release.
    ///
    /// **Wins over the normals view when both are on**, because the two share a
    /// lane and the fragment stage tests this one first.
    pub const fn set_lod_view(&mut self, on: bool) {
        self.lod_view = on;
    }

    /// Whether the colour pass tints clusters by their DAG level.
    ///
    /// **What was asked for, not what is drawn.** The three debug views share
    /// one lane and resolve in one order, so a renderer with this and
    /// [`set_heatmap`](Self::set_heatmap) both on draws the heatmap and still
    /// answers `true` here — the caller's setting is what a caller's toggle has
    /// to read back, and [`debug_view`](Self::debug_view) is what says which one
    /// the frame actually took.
    #[must_use]
    pub const fn lod_view(&self) -> bool {
        self.lod_view
    }

    /// Shades each cluster by the **projected screen-space error** the LOD
    /// selection judged it on, instead of shading it.
    ///
    /// The LOD tint's sibling, and the other half of topic 25's
    /// pair: [`set_lod_view`](Self::set_lod_view) answers "which level am I
    /// looking at", and this answers "how close to the budget is this, and where
    /// is the selection about to switch". The number is the one
    /// `draw_gen.slang`'s `group_is_expanded` compared against the budget — a
    /// cluster's *producing* group's error, projected from this frame's eye at
    /// this frame's pixels per unit.
    ///
    /// # What the colours mean
    ///
    /// A ramp that climbs in luminance from a cold floor to white, with a hue
    /// break at each of the two budgets: the hold budget where the hysteresis
    /// band starts, and the expand budget at the top, which is white. So the two
    /// budgets draw themselves as contour lines across the surface, and
    /// "brighter is closer to switching" reads even in a greyscale screenshot.
    /// `mesh_cluster.slang`'s `HEAT_UNDER_LOW` carries the ramp in full, and
    /// `crcbl_shaders`' `the_heatmap_ramp_climbs_in_luminance` is what holds it
    /// to being readable as an ordering.
    ///
    /// A cluster nothing simplified — the original surface, at the bottom of the
    /// DAG — costs exactly zero and takes the ramp's floor.
    ///
    /// # Mesh path only, and that is the capability rather than a shortfall
    ///
    /// A per-cluster error exists only where selection is per cluster.
    /// [`GeometryPath::IndirectCount`] and [`GeometryPath::IndirectPerBatch`]
    /// choose one level per *instance*, so there is no per-cluster number for
    /// them to shade by and `mesh.slang`'s vertex stage writes the same flat grey
    /// the LOD tint gets. Standing the two beside each other is the comparison.
    ///
    /// # It builds nothing and adds no pass
    ///
    /// One lane of the frame's uniform block, on
    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly — plus one
    /// storage-buffer read in the mesh stage, which the mesh path's layout
    /// already carries. Nothing to build, nothing to refuse, nothing to release.
    ///
    /// **Wins over both the LOD tint and the normals view when several are on**;
    /// see [`debug_view`](Self::debug_view), which is that order stated once.
    ///
    /// [`GeometryPath::IndirectCount`]: crcbl_hal::GeometryPath::IndirectCount
    /// [`GeometryPath::IndirectPerBatch`]: crcbl_hal::GeometryPath::IndirectPerBatch
    pub const fn set_heatmap(&mut self, on: bool) {
        self.heatmap = on;
    }

    /// Whether the colour pass shades clusters by their projected error.
    ///
    /// **What was asked for, not what is drawn**, on
    /// [`lod_view`](Self::lod_view)'s terms.
    #[must_use]
    pub const fn heatmap(&self) -> bool {
        self.heatmap
    }

    /// Draws the ambient-occlusion channel alone, as grey, instead of shading.
    ///
    /// One is white and fully occluded is black — the buffer the forward pass
    /// multiplies its ambient term by, shown as itself. **This is how the AO
    /// ladder — GTAO against the eight-tap hemisphere — is compared at all:** a
    /// composited frame shows occlusion times albedo times ambient, and a
    /// difference in the first is not separable from a difference in the other
    /// two by looking at the result.
    ///
    /// # What it draws with occlusion switched off
    ///
    /// White, everywhere. A frame without
    /// [`RenderEffects::AMBIENT_OCCLUSION`] binds a 1×1 white image in place of
    /// a computed channel, and this view shows that image rather than pretending
    /// to a channel nothing computed — "no occlusion was computed" and "nothing
    /// occludes here" are the same value to the shading, and the view does not
    /// get to disagree with the shading about it.
    ///
    /// # It builds nothing and adds no pass
    ///
    /// One lane of the frame's uniform block, on
    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly. Unlike the
    /// tint and the heatmap it needs nothing from the geometry stage, so it
    /// draws on every [`GeometryPath`] rather than on
    /// the mesh-shader one alone.
    ///
    /// **Wins over every other view when several are on**; see
    /// [`debug_view`](Self::debug_view), which is that order stated once.
    pub const fn set_occlusion_view(&mut self, on: bool) {
        self.occlusion_view = on;
    }

    /// Whether the colour pass draws the occlusion channel instead of shading.
    ///
    /// **What was asked for, not what is drawn**, on
    /// [`lod_view`](Self::lod_view)'s terms.
    #[must_use]
    pub const fn occlusion_view(&self) -> bool {
        self.occlusion_view
    }

    /// Draws each fragment's motion vector instead of shading it.
    ///
    /// The two components are stretched by
    /// [`MOTION_VIEW_SCALE`](crcbl_shaders::mesh::MOTION_VIEW_SCALE) and centred
    /// on grey, into red and green, with blue left at zero. A pixel at rest is
    /// grey in both channels to within one half-float step —
    /// [`MOTION_VIEW_SCALE`](crcbl_shaders::mesh::MOTION_VIEW_SCALE) says why
    /// not exactly — and a surface travelling right and down the screen
    /// brightens both.
    ///
    /// # It is the motion-vector target's only reader today
    ///
    /// The forward pass writes a motion vector into a third colour attachment on
    /// every frame — see [`crate::targets::motion`] — and no pass reads it
    /// yet; TAA (`docs/backlog.md`) is the first that will. This
    /// view is therefore what says the subtraction behind it is the right one,
    /// which is why it exists ahead of a consumer.
    ///
    /// # It builds nothing and adds no pass
    ///
    /// One lane of the frame's uniform block, on
    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
    /// the occlusion view it needs nothing from the geometry stage that a
    /// shaded frame does not already produce — so it draws on every
    /// [`GeometryPath`].
    ///
    /// **Wins over every other view when several are on**; see
    /// [`debug_view`](Self::debug_view), which is that order stated once.
    pub const fn set_motion_view(&mut self, on: bool) {
        self.motion_view = on;
    }

    /// Whether the colour pass draws the motion vector instead of shading.
    ///
    /// **What was asked for, not what is drawn**, on
    /// [`lod_view`](Self::lod_view)'s terms.
    #[must_use]
    pub const fn motion_view(&self) -> bool {
        self.motion_view
    }

    /// Draws the occlusion channel's **bent direction** instead of shading.
    ///
    /// The three channels beside the visibility scalar, passed through as the
    /// colour: the conventional `n * 0.5 + 0.5`, so +X reads red, +Y green and
    /// +Z blue, which is the mapping
    /// [`set_normals_view`](Self::set_normals_view) already uses for a surface
    /// normal. A fragment the occlusion pass had no direction for reads as the
    /// mid grey the zero sentinel encodes to.
    ///
    /// # What it is for
    ///
    /// The bent direction is what the ambient term is sampled *along*, and a
    /// composited frame cannot show it: ambient times albedo times a
    /// direction-dependent irradiance is one colour, and a direction that is
    /// subtly wrong looks like a lighting choice. This draws the direction
    /// alone, which is how a corner that leans the wrong way out of its own
    /// wall is a thing a reviewer sees rather than infers.
    ///
    /// # What it draws with occlusion switched off
    ///
    /// Mid grey, everywhere. A frame without
    /// [`RenderEffects::AMBIENT_OCCLUSION`] binds a 1×1 placeholder holding
    /// [`BENT_NORMAL_NONE`](crcbl_shaders::ssao::BENT_NORMAL_NONE) in those
    /// three channels, and this view shows that image rather than pretending to
    /// a direction nothing computed — which is the same answer the shading
    /// takes, since `mesh.slang` reads that sentinel as "use the shading
    /// normal".
    ///
    /// # It builds nothing and adds no pass
    ///
    /// One lane of the frame's uniform block, on
    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
    /// the occlusion view it needs nothing from the geometry stage — so it
    /// draws on every [`GeometryPath`].
    ///
    /// **Wins over every other view when several are on**; see
    /// [`debug_view`](Self::debug_view), which is that order stated once.
    pub const fn set_bent_normal_view(&mut self, on: bool) {
        self.bent_normal_view = on;
    }

    /// Whether the colour pass draws the bent direction instead of shading.
    ///
    /// **What was asked for, not what is drawn**, on
    /// [`lod_view`](Self::lod_view)'s terms.
    #[must_use]
    pub const fn bent_normal_view(&self) -> bool {
        self.bent_normal_view
    }

    /// Tints the shaded picture by the **cascade** each sun-lit fragment's
    /// shadow was sampled from.
    ///
    /// Topic 45's eighth decision made the cascade switch a
    /// band rather than a step, and this is the picture that band is judged in:
    /// each fragment's shading multiplied by
    /// [`CASCADE_TINTS`](crcbl_shaders::mesh::CASCADE_TINTS) of the cascade it
    /// selected, and inside the band by the *blend* of the two — the same weight
    /// the visibility itself was mixed with. So the boundary reads as a
    /// gradient, and a seam where two cascades disagree shows up as a step in
    /// the gradient rather than as a ring somebody has to already suspect.
    ///
    /// # It keeps the shaded picture, which is why it loses to every other view
    ///
    /// Every other view replaces the frame; this one multiplies it, so the geometry
    /// stays readable underneath and the shadow the cascades produced is still
    /// in the picture being coloured. That is also what puts it last in
    /// [`debug_view`](Self::debug_view)'s order: with a replacing view on there
    /// is no shading left for a tint to reach.
    ///
    /// # What it draws where no cascade covers a fragment
    ///
    /// Nothing at all —
    /// [`CASCADE_TINT_NONE`](crcbl_shaders::mesh::CASCADE_TINT_NONE) is white.
    /// A surface facing away from the sun and one past the last cascade's reach
    /// are both that, because neither was sampled through a cascade, and a
    /// frame drawn without [`RenderEffects::SHADOWS`](crate::RenderEffects::SHADOWS) is
    /// white everywhere for the same reason. Colouring those would be inventing
    /// a cascade for a pixel no map covers.
    ///
    /// # It builds nothing and adds no pass
    ///
    /// One lane of the frame's uniform block, on
    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
    /// the occlusion view it needs nothing from the geometry stage — so it draws
    /// on every [`GeometryPath`].
    pub const fn set_cascade_view(&mut self, on: bool) {
        self.cascade_view = on;
    }

    /// Whether the colour pass tints the picture by the sun's cascades.
    ///
    /// **What was asked for, not what is drawn**, on
    /// [`lod_view`](Self::lod_view)'s terms — and here that gap is the usual
    /// case rather than the corner one: this view loses to every other one, so a
    /// renderer with any of them also on answers `true` here and draws that one.
    #[must_use]
    pub const fn cascade_view(&self) -> bool {
        self.cascade_view
    }

    /// Draws the **shadow atlas itself** over the finished frame: the
    /// `D32Float` image `crate::shadow` budgets, letterboxed at its own aspect,
    /// each texel's stored depth as a grey and a border round every occupied
    /// slot.
    ///
    /// Sundial's atlas viewer, and the answer to a
    /// question no other view can be asked: which slot holds which map, and
    /// which slots hold nothing. A tile that was never rendered into, or
    /// rendered at the wrong viewport, lights a scene *fully* — so the frame it
    /// produces is plausible and every golden blessed from it passes. Here it is
    /// a rectangle that is visibly empty.
    ///
    /// # It is a pass, and it is the only debug view that is
    ///
    /// Every other view rides in one lane of the frame's uniform block and is a
    /// branch in `mesh.slang`, because every other view is a function of the
    /// fragment being shaded. The atlas is not: it is one image the whole frame
    /// shares. So this switch adds `crate::atlas_view`'s full-screen pass to
    /// the frame instead — after the tonemap, in display space, for that
    /// module's reason — and the frame block is byte-identical either way.
    ///
    /// # Where it resolves, and what it costs when it is off
    ///
    /// Below every replacing view and above
    /// [`set_cascade_view`](Self::set_cascade_view)'s tint — see
    /// [`debug_view`](Self::debug_view), which is that order stated once. A
    /// frame that resolved anything else records **no pass**, no pipeline bind
    /// and no block read, which is what makes the off position bit-identical on
    /// `crate::sky_pass`'s terms.
    pub const fn set_atlas_view(&mut self, on: bool) {
        self.atlas_view = on;
    }

    /// Whether the frame draws the shadow atlas over the picture.
    ///
    /// **What was asked for, not what is drawn**, on
    /// [`lod_view`](Self::lod_view)'s terms: a renderer with a replacing view
    /// also on answers `true` here and draws that one.
    #[must_use]
    pub const fn atlas_view(&self) -> bool {
        self.atlas_view
    }

    /// Pins the eye topic 25's selection is projected from, so the
    /// cut stops following the camera.
    ///
    /// [`None`] is the default and means "the camera's own eye", which is what
    /// every frame before this existed did. `Some(eye)` selects detail for a
    /// viewer standing at `eye` while the frame is still drawn, culled and lit
    /// from wherever the camera actually is.
    ///
    /// # What it is for
    ///
    /// Per-cluster LOD is only checkable from somewhere other than the point
    /// that chose it. Looked at from the selecting eye, a cut that is far too
    /// coarse and a cut that is exactly right produce the same silhouette —
    /// that is what a screen-space error budget *means* — so the one viewpoint
    /// where a wrong cut cannot be seen is the viewpoint every unfrozen frame is
    /// judged from. Pin the eye and fly away from it, and the boundaries between
    /// levels become geometry a reviewer can walk up to and look at edge-on.
    ///
    /// # Only the selection freezes
    ///
    /// The frame has three places a viewer position is read, and this moves
    /// exactly one of them:
    ///
    /// * **the selection** — `draw_gen.slang`'s `select_level`, which reads
    ///   `DrawGenParams::camera_position` and is the only thing that decides the
    ///   cut. It writes the group hysteresis state that the mesh path's
    ///   amplification stage then descends, so freezing this one field freezes
    ///   the cut on the per-cluster path and the two indirect paths alike. This
    ///   is what moves.
    /// * **the frustum culls** — `cull.slang`'s instance test and
    ///   `mesh_cluster.slang`'s per-cluster one, whose planes are extracted from
    ///   the frame's own view-projection and never read a camera position at
    ///   all. Unaffected, and it has to be: a frame culled against a frustum the
    ///   reviewer has flown out of would draw nothing.
    /// * **the normal cone** — `mesh_cluster.slang`'s `cluster_survives`, which
    ///   reads [`FrameUniforms::camera_position`] and asks which way a cluster
    ///   faces *relative to the viewer*. That question is about the eye the
    ///   picture is drawn from, not the eye it was selected for; frozen, a
    ///   reviewer who flew round to the other side of the face would have every
    ///   cluster now facing them rejected for facing away from a viewpoint
    ///   nobody is standing at. It stays live.
    ///
    /// The split is not new. `DrawGenParams::camera_position` and
    /// [`FrameUniforms::camera_position`] are already separate fields carrying
    /// different values on a shadow cascade — that one holds the sun while this
    /// one stays the camera, because detail is denominated in the camera's
    /// pixels and facing is asked about the light. This freezes the same seam
    /// from the other side, and needs no new binding, no new shader input and no
    /// shader change of any kind.
    ///
    /// # It freezes the cascades' selection too
    ///
    /// [`begin_frame`](Self::begin_frame) hands the same eye to every shadow
    /// cascade's draw generator, because a cascade selects detail for the
    /// *camera* — see [`SHADOW_LOD_BIAS`]. A frozen camera cut over a live
    /// shadow cut would be a shadow silhouette sliding under a fixed one, which
    /// is a difference in the picture that belongs to neither.
    ///
    /// # The heatmap reads the live eye, and says so
    ///
    /// [`set_heatmap`](Self::set_heatmap) shades a cluster by its producing
    /// group's projected error, computed in the mesh stage from
    /// [`FrameUniforms::camera_position`] — the eye that stays live. So under a
    /// frozen selection the two overlays answer different questions: the cut is
    /// the one chosen at the pinned eye, and the heat is what the error would be
    /// if it were chosen from here now. That is readable — flying towards the
    /// face brightens the clusters the frozen cut is not refining, which is the
    /// selection's sensitivity made visible — but it does mean the ramp's
    /// contours stop coinciding with the level boundaries while frozen.
    /// [`set_lod_view`](Self::set_lod_view) is the overlay that composes
    /// unconditionally: a cluster's level is a property of the cut and of
    /// nothing else.
    ///
    /// Carrying the pinned eye into the mesh stage as well would need a second
    /// position in the frame block, which is a new shader input in every backend
    /// for one overlay's benefit; `docs/backlog.md` holds that trade-off.
    ///
    /// [`FrameUniforms::camera_position`]: crcbl_shaders::mesh::FrameUniforms::camera_position
    pub const fn set_frozen_selection_eye(&mut self, eye: Option<Vec3>) {
        self.frozen_selection_eye = eye;
    }

    /// Where the selection is pinned, or [`None`] while it follows the camera.
    ///
    /// The read-back half of
    /// [`set_frozen_selection_eye`](Self::set_frozen_selection_eye), and what a
    /// debug panel says "frozen at" out of — "frozen" without the position is a
    /// row nobody can act on.
    #[must_use]
    pub const fn frozen_selection_eye(&self) -> Option<Vec3> {
        self.frozen_selection_eye
    }

    /// Which of the debug views the next frame will actually draw.
    ///
    /// **The one place the precedence is decided**, and every other statement of
    /// it in this crate reads it back from here. The switches ride in one float
    /// lane of the frame block — see
    /// [`FrameUniforms::HEATMAP_VIEW_ON`](crcbl_shaders::mesh::FrameUniforms::HEATMAP_VIEW_ON)
    /// — and the shaders test the outermost threshold first, so a sentinel for
    /// an outer view clears every threshold below it. Resolving here rather than
    /// letting each caller guess is what stops "which view is on" being answered
    /// differently by a menu row, a debug panel and the picture.
    #[must_use]
    pub const fn debug_view(&self) -> DebugView {
        if self.bent_normal_view {
            DebugView::BentNormal
        } else if self.motion_view {
            DebugView::Motion
        } else if self.occlusion_view {
            DebugView::AmbientOcclusion
        } else if self.heatmap {
            DebugView::Heatmap
        } else if self.lod_view {
            DebugView::LodTint
        } else if self.normals_view {
            DebugView::Normals
        } else if self.atlas_view {
            // **Below every view above it, and above the tint below.**
            //
            // Below, because every branch before this one is a question about
            // the *picture* — a cluster's error, a surface's normal, the
            // occlusion channel — and this one is not a picture of the scene at
            // all. A caller who left the atlas up and then asked for normals has
            // asked to look at the frame again, and the frame is what the branch
            // above draws; the atlas is one keystroke away and is not lost by
            // being deferred to.
            //
            // Above, because the cascade tint multiplies the shaded picture and
            // this replaces it: a tint on a frame the atlas overwrote would be a
            // tint on the atlas, which is a colour standing for nothing.
            DebugView::ShadowAtlas
        } else if self.cascade_view {
            // **Innermost, and the only view that sits below the others rather
            // than above them.** Every branch before this one draws something
            // *instead of* the shaded picture and returns before the shading; a
            // cascade tint is a multiply on that shading, so there is nothing
            // for it to modulate while one of them is showing and a caller with
            // both on has asked for the picture the outer one draws. The lane
            // says the same thing from the other end — the cascade sentinel is
            // negative, so it clears none of the shaders' thresholds — and
            // `crcbl_shaders`'
            // `the_cascade_view_threshold_lies_below_every_replacing_view` is
            // what holds that half.
            DebugView::Cascades
        } else {
            DebugView::Shaded
        }
    }

    /// [`debug_view`](Self::debug_view) as the value the frame block's lane
    /// carries.
    const fn debug_view_lane(&self) -> f32 {
        match self.debug_view() {
            DebugView::BentNormal => mesh::FrameUniforms::BENT_NORMAL_VIEW_ON,
            DebugView::Motion => mesh::FrameUniforms::MOTION_VIEW_ON,
            DebugView::AmbientOcclusion => mesh::FrameUniforms::OCCLUSION_VIEW_ON,
            DebugView::Heatmap => mesh::FrameUniforms::HEATMAP_VIEW_ON,
            DebugView::LodTint => mesh::FrameUniforms::LOD_VIEW_ON,
            DebugView::Normals => mesh::FrameUniforms::NORMALS_VIEW_ON,
            DebugView::Cascades => mesh::FrameUniforms::CASCADE_VIEW_ON,
            // **The off sentinel, and it is not an omission.** This view is a
            // pass rather than a branch in `mesh.slang` — see
            // [`crate::atlas_view`] — so the colour pass draws exactly the
            // shaded picture it always drew and the pass afterwards replaces it.
            // A lane of its own would be a threshold no shader tests.
            DebugView::ShadowAtlas | DebugView::Shaded => mesh::FrameUniforms::NORMALS_VIEW_OFF,
        }
    }

    /// Whether the colour pass draws world-space normals instead of shading.
    ///
    /// The read-back half of [`set_normals_view`](Self::set_normals_view), on
    /// [`wireframe`](Self::wireframe)'s terms: what it draws is what the question
    /// is about.
    #[must_use]
    pub const fn normals_view(&self) -> bool {
        self.normals_view
    }

    /// The cull and draw-argument passes, and the buffers they produce.
    ///
    /// What a caller reads the culling statistics out of — topic 03 §3.6's
    /// delayed readback ring is [`DrawGen::visible_count`] — and what
    /// `crcbl-vk`'s end-to-end suite copies back to check the generated
    /// arguments against the draws this pass used to record itself.
    #[must_use]
    pub const fn draws(&self) -> &DrawGen {
        &self.primary.draws
    }

    /// `frame`'s auto-exposure measurement: the bins the histogram pass filled
    /// and the exposure the reduce wrote out of them.
    ///
    /// What `crcbl`'s `mesh_e2e` copies back to check the histogram bin by bin
    /// against `crcbl_shaders::exposure`, on [`draws`](Self::draws)' terms — see
    /// [`ExposureBuffers`]. Both hold whatever the last frame that measured left
    /// there, so a frame drawn without
    /// [`RenderEffects::AUTO_EXPOSURE`](crate::RenderEffects::AUTO_EXPOSURE)
    /// hands back the frame before it rather than nothing.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this renderer was built with.
    #[must_use]
    pub fn exposure_buffers(&self, frame: usize) -> ExposureBuffers {
        self.primary.auto_exposure.buffers(frame)
    }

    /// `frame`'s froxel column: the buffers the froxel volume's
    /// three passes write, and the block they read.
    ///
    /// What `crcbl`'s `mesh_e2e` copies back to check the column froxel by
    /// froxel against `crcbl_shaders::volumetric`, on
    /// [`draws`](Self::draws)' terms — see [`FroxelBuffers`].
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this renderer was built with.
    #[must_use]
    pub fn froxel_buffers(&self, frame: usize) -> FroxelBuffers {
        self.primary.volumetric.buffers(frame)
    }

    /// The three layers a caller supplies to the toggle resolution order — see
    /// [`crate::effects`].
    ///
    /// Read back rather than only written, so a caller changing one layer does
    /// not have to remember the other two: take this, edit the field it owns,
    /// hand it back to [`set_effect_request`](Self::set_effect_request).
    #[must_use]
    pub const fn effect_request(&self) -> EffectRequest {
        self.effect_request
    }

    /// Replaces all three requested layers, and resolves them at the next
    /// [`begin_frame`](Self::begin_frame).
    ///
    /// **The frame in flight does not move.** `begin_frame` freezes what it
    /// resolved and [`add_passes`](Self::add_passes) records that, because the
    /// two halves of a frame have to agree about which culls were parametrised:
    /// `begin_frame` skips a shadow cull's parameter write when shadows are off
    /// and `add_passes` skips its dispatch, and a request landing between the two
    /// would dispatch a cull against numbers nothing zeroed.
    pub const fn set_effect_request(&mut self, request: EffectRequest) {
        self.effect_request = request;
    }

    /// Replaces the **camera** layer with what `stack` asks for, and leaves the
    /// other three where they are.
    ///
    /// The file half of [`crate::stack`] reaching the renderer: a view that has
    /// a render stack writes it here, and the player's `[engine.video]` clamp,
    /// the antialiasing rung they picked and any programmatic override are
    /// untouched — which is the property that makes the four layers four rather
    /// than one. A caller that wants to move more than this layer builds an
    /// [`EffectRequest`] and uses
    /// [`set_effect_request`](Self::set_effect_request).
    ///
    /// **The frame in flight does not move**, on `set_effect_request`'s terms
    /// and for its reason: this writes the request and
    /// [`begin_frame`](Self::begin_frame) is what resolves it.
    pub const fn set_camera_stack(&mut self, stack: &CameraStack) {
        self.effect_request.camera = stack.compile();
    }

    /// What the frame the last [`begin_frame`](Self::begin_frame) opened draws.
    ///
    /// The resolved set, not a layer: every effect in it has survived the
    /// camera's stack, the player's quality clamp, any programmatic override and
    /// the device — which is the one question a test asking "did this frame have
    /// shadows in it" wants answered.
    ///
    /// [`RenderEffects::all`] before the first frame, which is what a renderer
    /// nobody has changed would draw.
    #[must_use]
    pub const fn effects(&self) -> RenderEffects {
        self.frame_effects
    }

    /// What a frame begun **now** would draw: the whole order applied to the
    /// current request.
    ///
    /// [`effects`](Self::effects)' question one frame earlier, and the one a
    /// caller reporting its own configuration wants — a debug panel built at
    /// startup has no frame behind it yet, and printing what the last one drew
    /// would print a default.
    ///
    /// **A debug view takes the antialiasing resolve off** — either tier of it
    /// — whatever the four layers said. Those views are readouts rather than
    /// pictures — a pixel's colour *is* the cluster's projected error or its
    /// DAG level, read back against a legend — and a filter that blends two
    /// clusters' shades invents a ramp position no cluster occupies.
    /// `apps/quarry`'s heatmap and LOD tests are the consumers that count a
    /// frame's distinct colours.
    #[must_use]
    pub fn resolved_effects(&self) -> RenderEffects {
        let resolved = self.effect_request.resolve(self.device_effects);
        if matches!(self.debug_view(), DebugView::Shaded) {
            resolved
        } else {
            // **Both tiers**, because the slot is what a readout cannot have
            // rather than one filter in particular.
            resolved.difference(RenderEffects::ANTIALIASING.union(RenderEffects::CMAA2))
        }
    }

    /// Which tonemap operator the next frame runs:
    /// [`tonemap_curve`](Self::tonemap_curve)'s answer for a shaded frame, and
    /// the clamp for a readout.
    ///
    /// **[`resolved_effects`](Self::resolved_effects)' argument, applied to the
    /// operator instead of to the resolve.** A debug view's pixels *are* data —
    /// an encoded normal, an occlusion channel, a cascade's colour code — and a
    /// curve is a monotone remapping of every one of them. `apps/alcove`'s
    /// `--bent-view` reads a normal back and compares it against the geometry's
    /// own, which under ACES is 49 code values out; the clamp is the identity on
    /// `0..=1`, so it is the operator that leaves a readout readable. A caller
    /// that wants a curved readout has none, deliberately: there is no reading
    /// it would make easier.
    #[must_use]
    pub const fn resolved_tonemap_curve(&self) -> tonemap::TonemapCurve {
        if matches!(self.debug_view(), DebugView::Shaded) {
            self.tonemap_curve
        } else {
            tonemap::TonemapCurve::Clamp
        }
    }

    /// Which effects this **device** permits, which is the fourth layer and
    /// clamps last.
    ///
    /// Every one of them today — see [`ForwardRenderer::device_effects`], which
    /// is where that is argued per effect rather than asserted.
    #[must_use]
    pub const fn device_effects(&self) -> RenderEffects {
        self.device_effects
    }

    /// Which [`GeometryPath`] this renderer was **built for** — not what the
    /// device reports, but what it actually built.
    ///
    /// The device may prefer a path below its capability ceiling when a higher
    /// one uses emulation. This reports the preference actually built, rather
    /// than the ceiling: [`GeometryPath::MeshShader`] here means
    /// `build` created a mesh pipeline out of `mesh_cluster.slang` and its
    /// cluster buffers, and created **no** raster pipeline for the pass to fall
    /// back to. So a frame this renderer drew came out of a mesh stage, and a
    /// silent degradation is not a state it has — which is the claim a golden
    /// image on its own could never make, because a fall-through draws the same
    /// picture.
    #[must_use]
    pub const fn geometry_path(&self) -> GeometryPath {
        match self.emit {
            EmitTail::Mesh => GeometryPath::MeshShader,
            EmitTail::Count => GeometryPath::IndirectCount,
            EmitTail::PerBatch => GeometryPath::IndirectPerBatch,
        }
    }

    /// Whether this renderer **built** §3.5's per-cluster cull — an
    /// amplification stage in front of the mesh stage, rejecting a surviving
    /// instance's back-facing and off-screen clusters.
    ///
    /// `false` on the two indirect tails, which draw index ranges and have no
    /// stage to put it in, and on a device with `Features::MESH_SHADER` and no
    /// `Features::TASK_SHADER` — a real and supported state, not a degradation:
    /// that device draws every cluster of every surviving instance and the
    /// picture is the same one.
    ///
    /// The instance cull runs on every path either way, and is unaffected by
    /// this.
    ///
    /// It is asked of the renderer rather than of the device for
    /// [`ForwardRenderer::geometry_path`]'s reason: this reports what was
    /// built, so `true` means
    /// [`DrawGen::visible_count`](crate::draw_gen::DrawGen::visible_count)'s
    /// cluster word is a number the frame produced rather than the zero the
    /// clearing pass left.
    #[must_use]
    pub const fn culls_clusters(&self) -> bool {
        self.culls_clusters
    }

    /// Whether this renderer can choose **which level** of a
    /// [`Geometry::Dag`] mesh an object is drawn at, and therefore whether
    /// [`ForwardRenderer::add_instance`] may be given one at all.
    ///
    /// Topic 25's selection happens in the amplification stage where
    /// there is one, and in the cull pass where the tail is indirect and a level
    /// is an ordinary index range. **One device shape has neither**: a mesh stage
    /// with [`Features::MESH_SHADER`](crcbl_hal::Features::MESH_SHADER) and no
    /// [`Features::TASK_SHADER`](crcbl_hal::Features::TASK_SHADER) draws through
    /// `mesh_cluster.slang`'s un-amplified `meshMain`, which emits every cluster
    /// of the bucket — and a DAG's bucket is every level end to end, so the frame
    /// is several overlapping copies of one surface. That is a real and supported
    /// device state rather than a degradation, so this reports it instead of
    /// refusing to build.
    ///
    /// A [`Geometry::Flat`] mesh is one level and is unaffected: its clusters
    /// carry [`ClusterSelect::ALWAYS`] and every path draws it from every camera,
    /// which is why this is asked only before placing a DAG.
    ///
    /// Asked of the renderer rather than of the device for
    /// [`ForwardRenderer::culls_clusters`]' reason: it reports what was built.
    ///
    /// [`ClusterSelect::ALWAYS`]: crcbl_shaders::cluster_select::ClusterSelect::ALWAYS
    #[must_use]
    pub const fn selects_levels(&self) -> bool {
        !self.emit.is_mesh() || self.culls_clusters
    }

    /// Which frame-in-flight slot the last [`ForwardRenderer::begin_frame`]
    /// rotated to, which is the slot every per-frame buffer is indexed by.
    #[must_use]
    pub const fn frame(&self) -> usize {
        self.frame
    }

    /// What the last [`add_passes`](Self::add_passes) recorded, and what it
    /// cannot know.
    ///
    /// Zero draws until a frame has been built: this reports what was recorded,
    /// not what a frame would record.
    ///
    /// # The triangles are [`None`] here, on every geometry path
    ///
    /// Every draw this renderer records except the full-screen passes' and the
    /// debug draw layer's is **indirect**:
    /// the instance count and the index range live in the argument buffer
    /// `draw_gen.slang` wrote, so the CPU records the call and learns nothing
    /// about what it covered. That is true of
    /// [`GeometryPath::MeshShader`] and of
    /// both indirect tails alike — the three differ in which call is recorded,
    /// not in who decides the counts — so
    /// [`FrameCounters::triangles`](crate::counters::FrameCounters::triangles)
    /// is [`None`] whatever the device supports. Nothing counts a triangle on
    /// the GPU either, and a cluster count times a nominal triangles-per-cluster
    /// would read as authoritative and be neither.
    ///
    /// # The instances drawn come back off the GPU, a few frames late
    ///
    /// [`FrameCounters::drawn`](crate::counters::FrameCounters::drawn) is
    /// `cull.slang`'s survivor count, off [`crate::cull_stats`]'s delayed ring,
    /// plus the frame's direct draws — the ones here whose instance the CPU
    /// knows about, and the ones that are also in
    /// [`instances`](crate::counters::FrameCounters::instances). So the pair is
    /// comparable: the same quantity submitted and kept.
    ///
    /// **The camera's cull alone.** The shadow culls test other frustums and
    /// their survivors are counted into buffers of their own; adding them here
    /// would give a "drawn" larger than "submitted" on any frame with a shadow
    /// in it.
    ///
    /// It is [`None`] — the row says `indirect` — for the first few frames of a
    /// renderer's life, while the ring has not come round, and for good on a
    /// device that would not give out a readback.
    /// [`cull_frame`](crate::counters::FrameCounters::cull_frame) is which frame
    /// the number is about whenever there is one.
    ///
    /// [`FrameCounters::instances`](crate::counters::FrameCounters::instances)
    /// is known and is the plan's "submitted" half: the live instances
    /// [`add_passes`](Self::add_passes) hands the cull dispatches, plus the
    /// frame's direct draws — every full-screen pass's triangle and the debug
    /// draw layer's line list.
    #[must_use]
    pub fn counters(&self) -> FrameCounters {
        if self.recorded_draws == 0 {
            return FrameCounters::default();
        }
        let stats = self.cull_stats();
        let direct = self.direct_draws();
        FrameCounters {
            draws: self.recorded_draws,
            instances: self.instances.len() as u64 + direct,
            // Each direct draw is submitted and drawn, and none of them is in
            // the cull's count — they are draws of one instance, added on both
            // sides so the two halves of the row measure the same thing. Off the
            // frame that *was* recorded rather than off a constant, so a frame
            // with an effect switched off does not count a triangle it never
            // submitted.
            // Less what the occlusion cull's second phase rejected, which were
            // survivors of the frustum and were not drawn.
            drawn: stats
                .map(|stats| stats.instances.saturating_sub(stats.occlusion.late_rejects) + direct),
            triangles: None,
            // The survivors alone: the panel row is "clusters drawn", and the
            // frustum and cone rejection counts beside them are a different
            // question — `CullStats::clusters` carries all three for a caller
            // that wants the split, which `apps/quarry`'s own panel row is.
            clusters: stats
                .and_then(|stats| stats.clusters)
                .map(|cull| cull.survivors),
            cull_frame: stats.map(|stats| stats.frame),
        }
    }

    /// The draws this renderer records **directly** — the ones whose instance
    /// the CPU knows about, as opposed to the indirect calls whose counts live
    /// in a buffer a shader wrote.
    ///
    /// Every full-screen pass's over-sized triangle, plus the debug draw
    /// layer's line list on a frame that has one. One instance each, which is
    /// why [`counters`](Self::counters) adds this to both halves of its
    /// submitted/drawn pair.
    fn direct_draws(&self) -> u64 {
        self.recorded_fullscreen * FULLSCREEN_DRAWS
            + self.recorded_debug_draw
            + self.recorded_tile_clears
            + self.recorded_water_draws
    }

    /// What the camera's cull kept, on the frame the ring has reached.
    ///
    /// Topic 03 §3.6's one permitted readback, and [`None`] until it has come
    /// round — see [`crate::cull_stats`] for the latency and for what makes it
    /// free of any wait. [`counters`](Self::counters) is where this reaches the
    /// panel; it is exposed on its own because the frame number and the cluster
    /// word are both things a test asserts about directly.
    #[must_use]
    pub fn cull_stats(&self) -> Option<crate::cull_stats::CullStats> {
        self.cull_stats.as_ref().and_then(CullStatsRing::latest)
    }

    /// Describes the imported swapchain image the frame ends in.
    ///
    /// A helper rather than something every caller writes, because getting
    /// `initial`/`final_state` wrong is exactly the hand-written barrier this
    /// slice removed: an acquired image's contents are undefined, and the
    /// compositor may only be handed one in [`ResourceState::Present`].
    #[must_use]
    pub fn present_target(
        image: crcbl_hal::ImageHandle,
        view: ImageViewHandle,
        format: Format,
        extent: (u32, u32),
    ) -> ImportedImage {
        ImportedImage {
            image,
            view,
            format,
            extent,
            initial: ResourceState::Undefined,
            // The acquire's semaphore, not a barrier, is what orders this frame
            // after the last use of the image — which is what makes `Undefined`
            // honest here and what makes it uncheckable. See `InitialClaim`.
            claim: InitialClaim::Acquired,
            final_state: ResourceState::Present,
        }
    }

    /// Releases everything, in dependency order. The device must be idle.
    pub fn destroy(self, device: &dyn Device) {
        if let Some(stats) = self.cull_stats {
            stats.destroy(device);
        }
        // The cameras first: their groups name the scene's buffers, pages and
        // atlas below, and they own nothing the scene's groups name.
        for view in self.views.into_iter().flatten() {
            view.destroy(device);
        }
        self.primary.destroy(device);
        // After every view, whose grass and water groups name these buffers.
        self.grass.destroy(device);
        self.water.destroy(device);
        device.destroy_sampler(self.sampler);
        device.destroy_graphics_pipeline(self.tonemap_pipeline);
        device.destroy_pipeline_layout(self.tonemap_pipeline_layout);
        device.destroy_bind_group_layout(self.tonemap_layout);

        for pipelines in [
            self.shadow_pipeline,
            self.depth_masked_pipeline,
            self.rsm_pipeline,
        ] {
            device.destroy_graphics_pipeline(pipelines.single);
            device.destroy_graphics_pipeline(pipelines.double);
        }
        device.destroy_graphics_pipeline(self.shadow_clear_pipeline);
        for groups in self.shadow_groups {
            for group in groups {
                device.destroy_bind_group(group);
            }
        }
        for buffers in self.shadow_uniforms {
            for buffer in buffers {
                device.destroy_buffer(buffer);
            }
        }
        for buffers in self.shadow_selection {
            for buffer in buffers {
                device.destroy_buffer(buffer);
            }
        }
        for draws in self.shadow_draws {
            draws.destroy(device);
        }
        device.destroy_sampler(self.shadow_sampler);
        device.destroy_image_view(self.shadow_atlas_view);
        device.destroy_image(self.shadow_atlas);
        device.destroy_image_view(self.shadow_placeholder_view);
        device.destroy_image(self.shadow_placeholder);

        if let Some(grid) = self.ground_grid {
            grid.destroy(device);
        }
        // Nothing to release on a renderer nobody drew a segment through — see
        // [`crate::debug_draw`], whose pipeline is built on first use.
        self.debug_draw.destroy(device);
        self.atlas_viewer.destroy(device);
        self.ambient_occlusion_placeholder.destroy(device);
        self.contact_shadow_placeholder.destroy(device);
        self.probe_visibility_placeholder.destroy(device);
        if let Some(captured) = self.probe_visibility {
            captured.destroy(device);
        }
        self.specular_dfg.destroy(device);
        self.ltc_table.destroy(device);
        self.normal_page.destroy(device);
        self.mro_page.destroy(device);
        self.emissive_page.destroy(device);

        device.destroy_graphics_pipeline(self.mesh_pipeline.single);
        device.destroy_graphics_pipeline(self.mesh_pipeline.double);
        // The one place the wireframe pair is released — `set_wireframe(.., false)`
        // deliberately is not, because this call is the one that requires an
        // idle device.
        if let Some(pipelines) = self.wireframe_pipeline {
            device.destroy_graphics_pipeline(pipelines.single);
            device.destroy_graphics_pipeline(pipelines.double);
        }
        device.destroy_pipeline_layout(self.mesh_pipeline_layout);
        device.destroy_bind_group_layout(self.mesh_layout);
        self.base_color_page.destroy(device);
        device.destroy_sampler(self.base_color_sampler);
        for retired in self.retired_pages {
            retired.destroy(device);
        }
        device.destroy_buffer(self.draw_constants);
        if let Some(clusters) = self.clusters {
            clusters.destroy(device);
        }
        // Before the probe table, because its bind groups name that table's
        // rows — the same ordering the light grid is under above.
        if let Some(gather) = self.probe_gather {
            gather.destroy(device);
        }
        self.probes.destroy(device);
        self.materials.destroy(device);
        self.instances.destroy(device);
        self.pool.destroy(device);
    }
}

/// What the shadow pass a frame recorded would leave the image holding, held
/// until the frame after can say whether its body ran.
///
/// Topic 45's static-caching rung, per group: recording a pass
/// is not drawing one, so nothing here is believed until
/// [`ForwardRenderer::shadow_pass_ran`] carries this [`ShadowCommit::id`] back
/// out of the graph.
#[derive(Clone, Debug)]
struct ShadowCommit {
    /// The [`ForwardRenderer::shadow_pass_id`] the body publishes.
    id: u64,
    /// `[group]`: what the group's entry of
    /// [`ForwardRenderer::shadow_group_held`] becomes for every group the pass
    /// redraws, and [`None`] for the groups it holds.
    groups: Vec<Option<(u64, Vec3, f32)>>,
    /// The layout the pass draws under, where it clears the whole attachment —
    /// and [`None`] where it loads, because a loading pass leaves every tile it
    /// does not redraw exactly as it found it.
    layout: Option<Vec<shadow::TileRect>>,
}

/// The shader modules a mesh pipeline is built from, with its entry points
/// already resolved.
///
/// **A type rather than a run of locals in `build`** because there are now two
/// callers: `build`, which makes the colour pipeline and its depth-only twin,
/// and [`ForwardRenderer::set_wireframe`], which makes the colour pipeline again
/// in [`PolygonMode::Line`] long after `build` released its modules. The
/// alternative was a second copy of a descriptor that names two modules, their
/// entry points, the colour targets and a depth state — the pair that drifts.
///
/// Short-lived: created, used to build pipelines, and [`MeshModules::destroy`]ed
/// in the same function. A module is not needed once the pipeline exists.
struct MeshModules {
    /// `mesh.slang`'s module — the vertex stage on the indirect path, and the
    /// fragment stage on both.
    mesh: ShaderModuleHandle,
    /// `vertexMain`, unused on the mesh-shader path.
    vertex: &'static str,
    /// `depthVertexMain`, which [`MeshModules::depth_pipeline`] takes in
    /// [`MeshModules::vertex`]'s place: the same transform off stream 0 of the
    /// vertex pool and no attribute region at all. Unused on the mesh-shader
    /// path, where the geometry stage is `mesh_cluster.slang`'s either way.
    depth_vertex: &'static str,
    /// `depthClearVertexMain`, which [`MeshModules::depth_clear_pipeline`]
    /// builds the tile clear from: three corners off `SV_VertexID` and no input
    /// at all, so it resets one tile of the atlas without reading a vertex.
    ///
    /// **The same stage on every path**, unlike the two above: a device with a
    /// mesh stage still has a vertex stage, and a clear that produced no
    /// geometry is a primitive, not a cluster.
    depth_clear_vertex: &'static str,
    fragment: &'static str,
    /// `depthMaskedFragmentMain`, which [`MeshModules::depth_masked_pipeline`]
    /// puts *behind* [`MeshModules::vertex`] — the alpha mask and no target at
    /// all.
    ///
    /// **The same stage on both paths**, unlike the two vertex entry points
    /// above: it reads `mesh.slang`'s own `VertexOutput`, which is what
    /// `vertexMain` writes on the raster path and what `mesh_cluster.slang`'s
    /// mesh stage writes on the mesh one. So the cutout is one comparison in one
    /// place rather than one per geometry path.
    depth_masked_fragment: &'static str,
    /// `rsmFragmentMain`, which [`MeshModules::rsm_pipeline`] takes in
    /// [`MeshModules::fragment`]'s place: the same geometry stage, three targets
    /// describing the surface rather than shading it.
    ///
    /// **The reason the shaded stage above is looked up by name.** A module with
    /// two fragment entry points has no unambiguous one, which is what `entry`
    /// answers `None` for.
    rsm_fragment: &'static str,
    /// `mesh_cluster.slang`'s, on the mesh-shader path alone.
    cluster: Option<ClusterStages>,
}

/// The geometry half of a mesh-shader pipeline: `mesh_cluster.slang`'s module
/// and the stages taken out of it.
struct ClusterStages {
    /// The module the mesh stage is built from, and the one the task stage is,
    /// which are **two modules rather than one**.
    ///
    /// `mesh_cluster.slang` compiles to a combined module carrying every entry
    /// point and to one module per stage, and these are the per-stage ones. A
    /// module holding a task entry point and its mesh partner carries two
    /// `TaskPayloadWorkgroupEXT` variables — the task writes one, the mesh stage
    /// reads the other — and an NVIDIA driver then delivers a payload of zeroes,
    /// which draws cluster 0 of instance slot 0 of every bucket and nothing
    /// else. See `crcbl_shaders::EntryPoint`.
    mesh_module: ShaderModuleHandle,
    /// The task stage's own module, on the same terms. [`None`] exactly when
    /// [`task`](Self::task) is.
    task_module: Option<ShaderModuleHandle>,
    /// Which of the module's two mesh entry points this path builds — the
    /// amplified one where the device has a task stage to feed it.
    mesh: &'static str,
    /// §3.5's per-cluster cull, where the device has the stage to run it in.
    /// [`None`] is not a degradation: `meshMain` draws the same picture out of
    /// the same clusters, having rejected none of them, which is what a device
    /// with [`Features::MESH_SHADER`](crcbl_hal::Features::MESH_SHADER) and no
    /// [`Features::TASK_SHADER`](crcbl_hal::Features::TASK_SHADER) gets.
    task: Option<&'static str>,
}

impl MeshModules {
    /// **Three targets, one fragment stage.** `mesh.slang`'s `FragmentOutput`
    /// writes the shaded colour, then topic 47's
    /// reflectivity channel, then topic 43 §9's motion
    /// vector — and both pipeline shapes name that same entry point, so each
    /// target is one more element of this array and not a second pipeline, a
    /// second entry point or a new interpolant. The refusal the AO section
    /// records was about the depth prepass, which has no fragment stage and no
    /// colour target at all; it does not reach this array.
    ///
    /// Element order is `SV_Target` order, and each format is the one the
    /// matching `TransientImageDesc` creates: a pipeline built for a format the
    /// attachment is not in is a validation error on WebGPU and a silent
    /// reinterpretation elsewhere.
    const COLOR_TARGETS: [ColorTargetState; 3] = [
        ColorTargetState::opaque(Format::Rgba16Float),
        ColorTargetState::opaque(Format::Rgba8Unorm),
        ColorTargetState::opaque(MOTION_FORMAT),
    ];

    /// **Three targets again, and a different three.** `mesh.slang`'s
    /// `RsmOutput` writes the surface's diffuse albedo, its world normal encoded
    /// `n * 0.5 + 0.5`, and its world position with a coverage flag in `w` —
    /// which is what the irradiance probes' gather needs of a
    /// texel and nothing more.
    ///
    /// Element order is `SV_Target` order and each format is the one the
    /// matching description in [`crate::rsm`] creates: a pipeline built for a
    /// format the attachment is not in is a validation error on WebGPU and a
    /// silent reinterpretation elsewhere. `the_targets_carry_the_formats_the_shader_writes`
    /// in that module is the other half of the pair.
    const RSM_TARGETS: [ColorTargetState; 3] = [
        ColorTargetState::opaque(Format::Rgba16Float),
        ColorTargetState::opaque(Format::Rgba8Unorm),
        ColorTargetState::opaque(Format::Rgba32Float),
    ];

    /// Invocations per mesh workgroup, which is `mesh_cluster.slang`'s
    /// `[numthreads(THREADS, 1, 1)]` — and `THREADS` is
    /// `MAX_CLUSTER_VERTICES`, one lane per vertex a cluster can hold.
    ///
    /// Taken from the crate that owns the shader source rather than written
    /// out, as
    /// [`MeshPipelineDesc::mesh_workgroup_size`](crcbl_hal::MeshPipelineDesc::mesh_workgroup_size)
    /// requires: only Metal reads this field, so a literal that disagreed with
    /// the shader would launch the wrong number of threads on one backend and
    /// nowhere else.
    const MESH_WORKGROUP_SIZE: [u32; 3] =
        [crcbl_shaders::meshlet::MAX_CLUSTER_VERTICES as u32, 1, 1];

    /// Invocations per task workgroup: `taskMain` is
    /// `[numthreads(TASK_LANES, 1, 1)]`, one lane per (cluster, instance slot)
    /// pair of its chunk. Taken from the crate that owns the shader, on
    /// [`MESH_WORKGROUP_SIZE`](Self::MESH_WORKGROUP_SIZE)'s terms.
    const TASK_WORKGROUP_SIZE: [u32; 3] = [crcbl_shaders::meshlet::TASK_LANES, 1, 1];

    /// Loads whichever modules `emit` needs and resolves their entry points.
    ///
    /// # Errors
    ///
    /// [`HalError::ShaderCompilation`] if the committed manifest names no such
    /// entry point, and [`HalError`] from either module. A failure after the
    /// first module was created releases it rather than leaking it.
    fn new(device: &dyn Device, emit: EmitTail, culls_clusters: bool) -> Result<Self, HalError> {
        // Entry points resolved before the module exists: a manifest that
        // disagreed with the SPIR-V would otherwise fail inside the descriptor
        // literal, with the module already created and nothing holding it.
        //
        // **The vertex stage is named rather than looked up by stage**, for
        // `mesh_cluster.slang`'s reason below: since the depth-only stage landed
        // this module has two vertex entry points, and a stage lookup answers
        // `None` for two matches. Which of the two a pipeline names is the whole
        // of what the split-stream vertex pool bought.
        let vertex = named_entry(&MESH, "vertexMain", Stage::Vertex)?;
        let depth_vertex = named_entry(&MESH, "depthVertexMain", Stage::Vertex)?;
        let depth_clear_vertex = named_entry(&MESH, "depthClearVertexMain", Stage::Vertex)?;
        // **Named rather than looked up by stage, on the vertex entry points'
        // terms exactly.** Since the irradiance probes' updater
        // landed, this module has *two* fragment entry points — the shaded one
        // and `rsmFragmentMain` — and `entry` answers `None` for two matches, so
        // a stage lookup here refuses the build outright with "exposes no
        // unambiguous Fragment entry point".
        let fragment = named_entry(&MESH, "fragmentMain", Stage::Fragment)?;
        let depth_masked_fragment = named_entry(&MESH, "depthMaskedFragmentMain", Stage::Fragment)?;
        let rsm_fragment = named_entry(&MESH, "rsmFragmentMain", Stage::Fragment)?;
        // **Named rather than looked up by stage**, because the module has two
        // mesh entry points and a stage lookup would refuse an ambiguous one —
        // see `named_entry`. Which of the two this names is the whole of the
        // amplification decision.
        let cluster_stages = emit
            .is_mesh()
            .then(|| {
                let mesh = named_entry(
                    &MESH_CLUSTER,
                    if culls_clusters {
                        "amplifiedMeshMain"
                    } else {
                        "meshMain"
                    },
                    Stage::Mesh,
                )?;
                let task = culls_clusters
                    .then(|| named_entry(&MESH_CLUSTER, "taskMain", Stage::Task))
                    .transpose()?;
                Ok::<_, HalError>((mesh, task))
            })
            .transpose()?;

        let mesh = device.create_shader_module(&ShaderModuleDesc {
            label: Some("mesh.slang"),
            spirv: MESH.spirv(),
            wgsl: MESH.wgsl(),
            msl: MESH.msl(),
            // **Both containers, and still one module.** A DXIL container holds
            // exactly one entry point, so this is a list where its three
            // neighbours are single artifacts; the backend that consumes it
            // picks the container named by the stage it is building. Nothing
            // here branches on a backend, and the three that ignore DXIL see
            // the same module they always did.
            dxil: &MESH.dxil_containers(),
        })?;
        let cluster = match cluster_stages {
            None => None,
            Some((cluster_mesh, task)) => {
                // **The mesh stage's module is `mesh_cluster.slang`; the
                // fragment stage's is still `mesh.slang`'s.** A pipeline takes a
                // module per stage, so the shading — Lambert, the GGX lobe, the
                // material row, the page sample — is the same code both paths
                // run rather than a copy that agrees today.
                // `mesh_cluster.slang`'s header carries the argument, and its
                // `VertexOutput` is what the two agree through.
                // **One module per stage, each carrying that stage's own
                // SPIR-V.** Only the SPIR-V differs between them: MSL is one
                // artifact per source whatever the stage, and a DXIL container
                // is already per entry point, so both are handed over unchanged
                // and the backends that read them see what they always did.
                let stage_module = |entry_point: &str| {
                    device.create_shader_module(&ShaderModuleDesc {
                        label: Some("mesh_cluster.slang"),
                        // The combined module where this stage has none of its
                        // own, which is every stage of every other shader.
                        spirv: MESH_CLUSTER
                            .spirv_for(entry_point)
                            .unwrap_or_else(|| MESH_CLUSTER.spirv()),
                        // `None`, and it is the whole reason this is a second
                        // file: WGSL cannot express a mesh stage at all.
                        wgsl: MESH_CLUSTER.wgsl(),
                        msl: MESH_CLUSTER.msl(),
                        dxil: &MESH_CLUSTER.dxil_containers(),
                    })
                };
                let mesh_module = match stage_module(cluster_mesh) {
                    Ok(module) => module,
                    Err(error) => {
                        device.destroy_shader_module(mesh);
                        return Err(error);
                    }
                };
                let task_module = match task.map(stage_module).transpose() {
                    Ok(module) => module,
                    Err(error) => {
                        device.destroy_shader_module(mesh);
                        device.destroy_shader_module(mesh_module);
                        return Err(error);
                    }
                };
                Some(ClusterStages {
                    mesh_module,
                    task_module,
                    mesh: cluster_mesh,
                    task,
                })
            }
        };
        Ok(Self {
            mesh,
            vertex,
            depth_vertex,
            depth_clear_vertex,
            fragment,
            depth_masked_fragment,
            rsm_fragment,
            cluster,
        })
    }

    /// The rasteriser state every pipeline shape here shares, because the only
    /// things that differ between them are which stage produces the geometry and
    /// which side of it survives.
    ///
    /// [`CullMode::Back`] is what a single-sided bucket asks for, and it has
    /// been on from the first mesh. The cube's winding is asserted by
    /// `crcbl-shaders`' own tests, so a face that vanished would be a *test*
    /// failure rather than a debugging session — and a mesh drawn without
    /// culling would let a winding mistake survive into P7's geometry pool. The
    /// mesh stage emits its corner triples in the index buffer's own order, so
    /// the winding it produces is the same one.
    ///
    /// [`CullMode::None`] is what a double-sided bucket asks for — glTF 2.0
    /// §3.9.6's first half — and the twin built with it is the only way a back
    /// face reaches `mesh.slang` at all. See [`SidedPipelines`].
    fn primitive(polygon_mode: PolygonMode, cull_mode: CullMode) -> PrimitiveState {
        PrimitiveState {
            cull_mode,
            polygon_mode,
            ..PrimitiveState::default()
        }
    }

    /// What a pipeline built with `cull` adds to its label, so a capture and
    /// `crcbl_hal::null`'s recorder tell a [`SidedPipelines::double`] twin from
    /// the [`SidedPipelines::single`] it was built beside.
    ///
    /// Empty for the culling modes, because those pipelines' labels are the ones
    /// every existing capture and every test lookup already names.
    fn side_label(cull: CullMode) -> &'static str {
        match cull {
            CullMode::None => " double-sided",
            CullMode::Front | CullMode::Back => "",
        }
    }

    /// Both sides of one pipeline shape, single-sided first, **created and not
    /// yet unwrapped**.
    ///
    /// The results rather than the pair, because that is the discipline `build`
    /// keeps for every pipeline it makes: everything is created while the
    /// modules are alive, the modules are released once, and only then is each
    /// successful result handed to rollback before any error is propagated. A
    /// helper that unwrapped here would have to drop a handle it had already
    /// created when its twin failed, and nothing would ever destroy it.
    fn sided(
        mut build: impl FnMut(CullMode) -> Result<GraphicsPipelineHandle, HalError>,
    ) -> [Result<GraphicsPipelineHandle, HalError>; 2] {
        [build(CullMode::Back), build(CullMode::None)]
    }

    /// Milestone 3's depth test, and the seam's default is already reversed-Z:
    /// `Greater` against `D32Float`, writes on. The clear value that agrees with
    /// it comes from the graph (`PassBuilder::clear_depth`), and the projection
    /// matrix that agrees with **both** comes from [`crate::camera`].
    fn depth_stencil() -> Option<DepthStencilState> {
        Some(DepthStencilState::default())
    }

    /// The colour pass's depth state, which is not the same shape as
    /// [`MeshModules::depth_stencil`] because the depth prepass has already
    /// drawn this geometry.
    ///
    /// **Filled: [`DepthStencilState::equal_depth_read_only`], so the shading is
    /// paid for once per pixel.** The prepass runs the same draws through
    /// `depthVertexMain` — or, on the mesh path, through the very same geometry
    /// stage — so the depth already in the attachment is this pass's own answer,
    /// and a `GreaterOrEqual` test with writes off keeps exactly the fragments
    /// that would have won the write. What it removes is the clustered-forward
    /// shading of every fragment a nearer one goes on to cover.
    ///
    /// **Lines: the writing default, because a wireframe is not the geometry the
    /// prepass drew.** [`PolygonMode::Line`] rasterises the triangle's edges,
    /// and an edge pixel's depth is interpolated along the line rather than
    /// across the face, so testing it for equality against a filled prepass
    /// rejects most of the wireframe. That frame keeps the pass shape this pass
    /// had before the prepass existed — see the colour pass's depth attachment,
    /// which branches on the same condition.
    fn color_depth_stencil(polygon_mode: PolygonMode) -> Option<DepthStencilState> {
        match polygon_mode {
            PolygonMode::Fill => Some(DepthStencilState::equal_depth_read_only(Format::D32Float)),
            _ => Self::depth_stencil(),
        }
    }

    /// The colour pass's pipeline, filled or wireframe, culling back faces or
    /// nothing.
    ///
    /// `label` names the caller — `"forward"` for the frame's own, `"wireframe"`
    /// for [`ForwardRenderer::set_wireframe`]'s — and [`MeshModules::side_label`]
    /// names the side, so a capture tells all four apart.
    fn color_pipeline(
        &self,
        device: &dyn Device,
        layout: PipelineLayoutHandle,
        polygon_mode: PolygonMode,
        cull: CullMode,
        label: &str,
    ) -> Result<GraphicsPipelineHandle, HalError> {
        let primitive = Self::primitive(polygon_mode, cull);
        let depth_stencil = Self::color_depth_stencil(polygon_mode);
        let side = Self::side_label(cull);
        let fragment = Some(ShaderEntry {
            module: self.mesh,
            entry_point: self.fragment,
        });
        match self.cluster.as_ref() {
            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
                label: Some(&format!("{label}{side} mesh cluster")),
                layout,
                task: cluster
                    .task
                    .zip(cluster.task_module)
                    .map(|(entry_point, module)| ShaderEntry {
                        module,
                        entry_point,
                    }),
                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
                mesh: ShaderEntry {
                    module: cluster.mesh_module,
                    entry_point: cluster.mesh,
                },
                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
                fragment,
                primitive,
                depth_stencil,
                multisample: MultisampleState::default(),
                color_targets: &Self::COLOR_TARGETS,
            }),
            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
                label: Some(&format!("{label}{side} mesh")),
                layout,
                vertex: ShaderEntry {
                    module: self.mesh,
                    entry_point: self.vertex,
                },
                fragment,
                primitive,
                depth_stencil,
                multisample: MultisampleState::default(),
                color_targets: &Self::COLOR_TARGETS,
            }),
        }
    }

    /// The depth-only twin of [`MeshModules::color_pipeline`], built out of the
    /// same modules and the same layout: no fragment stage, no colour target,
    /// and a vertex stage that fetches stream 0 of the vertex pool alone.
    ///
    /// **The transform is identical and the fetch is not, which is the point.**
    /// Topic 18 asks for a shadow pass "identical on every `GeometryPath` —
    /// depth pass plus whatever emit tail the device selected", and what makes
    /// that work is a frame block whose `view_proj` is the cascade's matrix
    /// rather than a second transform path: a cascade that disagreed with the
    /// colour pass about where a vertex is would produce shadows that do not
    /// line up with their casters, which is indistinguishable from a bias
    /// problem. `depthVertexMain` is that same clip position written the same
    /// way, with everything the discarded varyings needed — the attribute
    /// region and the previous frame's position — left unread;
    /// topic 43 §2 split the pool for exactly this
    /// pass, and this is where it is spent.
    ///
    /// **The mesh-shader path still runs the colour pipeline's geometry
    /// stage.** `mesh_cluster.slang` emits one `VertexOutput`, so a depth-only
    /// mesh stage is a second entry point in that module and its own rung; a
    /// device with a mesh stage goes on reading whole vertices here.
    ///
    /// Always [`PolygonMode::Fill`]: it fills the shadow atlas and the depth
    /// prepass, and depth drawn as lines is depth with holes in it — which the
    /// occlusion pair would read as geometry that is not there.
    fn depth_pipeline(
        &self,
        device: &dyn Device,
        layout: PipelineLayoutHandle,
        cull: CullMode,
    ) -> Result<GraphicsPipelineHandle, HalError> {
        let primitive = Self::primitive(PolygonMode::Fill, cull);
        let side = Self::side_label(cull);
        match self.cluster.as_ref() {
            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
                label: Some(&format!("shadow cascade{side} mesh cluster")),
                layout,
                task: cluster
                    .task
                    .zip(cluster.task_module)
                    .map(|(entry_point, module)| ShaderEntry {
                        module,
                        entry_point,
                    }),
                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
                mesh: ShaderEntry {
                    module: cluster.mesh_module,
                    entry_point: cluster.mesh,
                },
                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
                fragment: None,
                primitive,
                depth_stencil: Self::depth_stencil(),
                multisample: MultisampleState::default(),
                color_targets: &[],
            }),
            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
                label: Some(&format!("shadow cascade{side}")),
                layout,
                vertex: ShaderEntry {
                    module: self.mesh,
                    entry_point: self.depth_vertex,
                },
                fragment: None,
                primitive,
                depth_stencil: Self::depth_stencil(),
                multisample: MultisampleState::default(),
                color_targets: &[],
            }),
        }
    }

    /// [`MeshModules::depth_pipeline`] with an alpha mask in it: the same depth
    /// state and the same absent colour targets, `depthMaskedFragmentMain`
    /// behind the geometry stage, and [`MeshModules::vertex`] in
    /// [`MeshModules::depth_vertex`]'s place.
    ///
    /// Topic 43 §3's cutout, in the two passes that
    /// write depth without shading. A masked instance drawn through the pipeline
    /// above writes its full silhouette: it occludes itself through the hole it
    /// can see through, and it casts the shadow of a leaf that has none.
    ///
    /// **The vertex stage is the colour pass's, and it has to be.** A cutout
    /// needs the UV, which lives in the attribute region `depthVertexMain`
    /// exists not to read — so this stage reads a whole vertex, exactly as
    /// [`MeshModules::rsm_pipeline`] does beside it and for the same reason.
    /// What that buys is one fragment entry point for both geometry paths: the
    /// mesh path already emits `mesh.slang`'s `VertexOutput`, so the mask is
    /// compared in one place rather than once per path.
    ///
    /// **Which draws are recorded with it is the bucket's own material mode**,
    /// not the frame's — see [`ForwardRenderer::depth_partitions`]. A scene that
    /// masks nothing has no bucket in this partition, records through the
    /// pipeline above with no fragment stage anywhere, and costs exactly what it
    /// cost before this one existed; a scene that masks one mesh pays the
    /// fragment stage for that mesh's draws alone.
    fn depth_masked_pipeline(
        &self,
        device: &dyn Device,
        layout: PipelineLayoutHandle,
        cull: CullMode,
    ) -> Result<GraphicsPipelineHandle, HalError> {
        let primitive = Self::primitive(PolygonMode::Fill, cull);
        let side = Self::side_label(cull);
        let fragment = Some(ShaderEntry {
            module: self.mesh,
            entry_point: self.depth_masked_fragment,
        });
        match self.cluster.as_ref() {
            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
                label: Some(&format!("shadow cascade masked{side} mesh cluster")),
                layout,
                task: cluster
                    .task
                    .zip(cluster.task_module)
                    .map(|(entry_point, module)| ShaderEntry {
                        module,
                        entry_point,
                    }),
                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
                mesh: ShaderEntry {
                    module: cluster.mesh_module,
                    entry_point: cluster.mesh,
                },
                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
                fragment,
                primitive,
                depth_stencil: Self::depth_stencil(),
                multisample: MultisampleState::default(),
                color_targets: &[],
            }),
            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
                label: Some(&format!("shadow cascade masked{side}")),
                layout,
                vertex: ShaderEntry {
                    module: self.mesh,
                    entry_point: self.vertex,
                },
                fragment,
                primitive,
                depth_stencil: Self::depth_stencil(),
                multisample: MultisampleState::default(),
                color_targets: &[],
            }),
        }
    }

    /// The reflective shadow map's pipeline: the colour pipeline's geometry
    /// stage, `rsmFragmentMain` in the shaded stage's place, and
    /// [`MeshModules::RSM_TARGETS`] in [`MeshModules::COLOR_TARGETS`]'s.
    ///
    /// The irradiance probes' updater draws the sun's near
    /// cascade a second time through this — see [`crate::rsm`], which owns the
    /// attachments, and `ForwardRenderer::add_shadow_pass`, which records the
    /// pass out of that cascade's own bind group and its own already-generated
    /// draws.
    ///
    /// **[`MeshModules::vertex`] and not [`MeshModules::depth_vertex`]**, unlike
    /// the cascade this rides beside: a fragment stage that writes a world
    /// position, a normal and an albedo needs the varyings `depthVertexMain`
    /// exists to leave unread. On the mesh path it is the very same geometry
    /// stage the colour pass runs, for the reason `depth_pipeline` gives.
    ///
    /// **Its own depth, written**, rather than the colour pass's read-only
    /// equality test: nothing has drawn this view's depth before it, and the
    /// pass is what decides which surface a texel of the map holds.
    fn rsm_pipeline(
        &self,
        device: &dyn Device,
        layout: PipelineLayoutHandle,
        cull: CullMode,
    ) -> Result<GraphicsPipelineHandle, HalError> {
        let primitive = Self::primitive(PolygonMode::Fill, cull);
        let side = Self::side_label(cull);
        let fragment = Some(ShaderEntry {
            module: self.mesh,
            entry_point: self.rsm_fragment,
        });
        match self.cluster.as_ref() {
            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
                label: Some(&format!("rsm{side} mesh cluster")),
                layout,
                task: cluster
                    .task
                    .zip(cluster.task_module)
                    .map(|(entry_point, module)| ShaderEntry {
                        module,
                        entry_point,
                    }),
                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
                mesh: ShaderEntry {
                    module: cluster.mesh_module,
                    entry_point: cluster.mesh,
                },
                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
                fragment,
                primitive,
                depth_stencil: Self::depth_stencil(),
                multisample: MultisampleState::default(),
                color_targets: &Self::RSM_TARGETS,
            }),
            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
                label: Some(&format!("rsm{side}")),
                layout,
                vertex: ShaderEntry {
                    module: self.mesh,
                    entry_point: self.vertex,
                },
                fragment,
                primitive,
                depth_stencil: Self::depth_stencil(),
                multisample: MultisampleState::default(),
                color_targets: &Self::RSM_TARGETS,
            }),
        }
    }

    /// The pipeline that resets one tile of the shadow atlas, so a pass can keep
    /// some tiles and redraw others.
    ///
    /// Topic 45's cadence rung needs a tile cleared on its own,
    /// and the attachment's [`LoadOp`] cannot do it — a clear there covers the
    /// whole image, and the region-bounded forms are not portable. This is the
    /// portable statement of the same thing: `mesh.slang`'s
    /// `depthClearVertexMain` covers the viewport the shadow pass has already
    /// set over the tile, and the depth state below writes
    /// [`depth::CLEAR`](crcbl_hal::depth) over whatever was there.
    ///
    /// **[`CompareOp::Always`] and writes on**, which is the pair that makes it a
    /// clear rather than a draw: the tile holds the previous frame's depths, and
    /// under the engine's [`CompareOp::Greater`] a clear value of zero would
    /// fail against every one of them and leave the tile exactly as it was.
    ///
    /// **[`CullMode::None`]**, unlike [`MeshModules::primitive`]: the triangle
    /// is generated from `SV_VertexID` rather than wound by an artist, so a
    /// culling rule meant for scene geometry would decide whether the clear
    /// happens at all.
    ///
    /// **A vertex pipeline on every path**, including the mesh-shader one: a
    /// device with a mesh stage still has a vertex stage, and the clear has no
    /// clusters to descend.
    fn depth_clear_pipeline(
        &self,
        device: &dyn Device,
        layout: PipelineLayoutHandle,
    ) -> Result<GraphicsPipelineHandle, HalError> {
        device.create_graphics_pipeline(&GraphicsPipelineDesc {
            label: Some("shadow tile clear"),
            // The mesh layout, so binding this pipeline in the middle of the
            // shadow pass does not disturb the bind group the draws around it
            // are recorded with. The stage reads none of it.
            layout,
            vertex: ShaderEntry {
                module: self.mesh,
                entry_point: self.depth_clear_vertex,
            },
            fragment: None,
            primitive: PrimitiveState {
                cull_mode: CullMode::None,
                polygon_mode: PolygonMode::Fill,
                ..PrimitiveState::default()
            },
            depth_stencil: Some(DepthStencilState {
                depth_compare: CompareOp::Always,
                ..DepthStencilState::default()
            }),
            multisample: MultisampleState::default(),
            color_targets: &[],
        })
    }

    /// Releases every module. The pipelines built from them stay valid.
    fn destroy(self, device: &dyn Device) {
        device.destroy_shader_module(self.mesh);
        if let Some(cluster) = self.cluster {
            device.destroy_shader_module(cluster.mesh_module);
            if let Some(task) = cluster.task_module {
                device.destroy_shader_module(task);
            }
        }
    }
}

/// The entry point for `stage`, or an error naming the shader.
///
/// Unreachable in practice — `crcbl-shaders`' own tests assert both modules
/// expose both stages — but the alternative is an `expect` in engine code.
fn entry(shader: &crcbl_shaders::Shader, stage: Stage) -> Result<&'static str, HalError> {
    shader.entry_point(stage).ok_or_else(|| {
        HalError::ShaderCompilation(format!(
            "{}.slang exposes no unambiguous {stage:?} entry point; the committed SPIR-V and its \
             manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix",
            shader.name()
        ))
    })
}

/// The entry point called `name`, checked to be `stage`'s.
///
/// [`entry`] cannot serve `mesh_cluster.slang`: it has **two** mesh entry
/// points — one behind the amplification stage and one without it — and a
/// lookup by stage answers `None` for two matches rather than picking one, for
/// the good reason that picking one would draw the wrong geometry.
///
/// The stage is still checked rather than taken on trust: a name that resolved
/// to the wrong stage would be a pipeline built with an amplification stage in
/// its mesh slot, and the failure would arrive as a driver error rather than as
/// this sentence.
pub(crate) fn named_entry(
    shader: &crcbl_shaders::Shader,
    name: &'static str,
    stage: Stage,
) -> Result<&'static str, HalError> {
    let found = shader
        .entry_points()
        .iter()
        .find(|entry| entry.name() == name && entry.stage() == stage);
    found.map(crcbl_shaders::EntryPoint::name).ok_or_else(|| {
        HalError::ShaderCompilation(format!(
            "{}.slang exposes no {stage:?} entry point called `{name}`; the committed SPIR-V and \
             its manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix",
            shader.name()
        ))
    })
}

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

    use super::*;
    use crate::effects::{Antialiasing, EffectOverride};
    use crate::scene::{
        DEMO_CUBE, DEMO_DUNES, DEMO_OPEN_BOX, DEMO_PYRAMID, DEMO_TEXTURED, DEMO_TINTED,
        DEMO_UNTINTED,
    };
    use crcbl_hal::null::{Event, NullInstance, ObjectKind, Recorder};
    use crcbl_hal::{DeviceDesc, DrawIndirect, Features, Instance, QueueKind};

    #[test]
    fn refused_mesh_color_pipelines_release_successful_depth_pipelines() {
        let recorder = Recorder::new();
        let mut limits = crcbl_hal::Limits::desktop();
        limits.max_color_attachments = 2;
        let features = Features::COMPUTE | Features::MESH_SHADER;
        let instance = NullInstance::new(crcbl_hal::DeviceCaps { features, limits })
            .with_recorder(recorder.clone());
        let device = instance
            .create_device(&DeviceDesc {
                label: None,
                adapter: crcbl_hal::AdapterId(0),
                required_features: features,
                optional_features: Features::empty(),
                compatible_surface: None,
            })
            .unwrap();
        let queue = device.queue(QueueKind::Graphics).unwrap();
        let before = recorder.total_live_objects();
        let error = ForwardRenderer::with_scene_on_path(
            device.as_ref(),
            queue,
            Format::Rgba8UnormSrgb,
            &scene::demo(),
            GeometryPath::MeshShader,
        )
        .expect_err("three-target color pipelines must be refused");
        assert!(
            error
                .to_string()
                .contains("3 colour targets exceeds max_color_attachments 2"),
            "{error}"
        );
        assert!(
            recorder.events().iter().any(|event| matches!(
                event,
                Event::Created {
                    kind: ObjectKind::GraphicsPipeline,
                    ..
                }
            )),
            "the refusal must exercise cleanup of successful pipelines"
        );
        assert_eq!(
            recorder.total_live_objects(),
            before,
            "partial pipeline construction leaked resources"
        );
        recorder.assert_valid();
    }

    #[test]
    fn exact_geometry_path_overrides_preference_and_default_keeps_it() {
        let recorder = Recorder::new();
        let instance = NullInstance::gpu_driven()
            .with_geometry_preference(GeometryPath::IndirectPerBatch)
            .with_recorder(recorder.clone());
        let device = instance
            .create_device(&DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)))
            .unwrap();
        let queue = device.queue(QueueKind::Graphics).unwrap();
        assert_eq!(device.caps().geometry_path(), GeometryPath::IndirectCount);
        let default = ForwardRenderer::with_scene(
            device.as_ref(),
            queue,
            Format::Rgba8UnormSrgb,
            &scene::demo(),
        )
        .unwrap();
        assert_eq!(default.geometry_path(), GeometryPath::IndirectPerBatch);
        default.destroy(device.as_ref());
        recorder.clear();
        let mut exact = ForwardRenderer::with_scene_on_path(
            device.as_ref(),
            queue,
            Format::Rgba8UnormSrgb,
            &scene::demo(),
            GeometryPath::IndirectCount,
        )
        .unwrap();
        assert_eq!(exact.geometry_path(), GeometryPath::IndirectCount);
        let rendered = frame(device.as_ref(), &mut exact, queue);
        let commands = commands_in_pass(&recorder, "forward");
        assert!(commands.iter().any(|command| matches!(
            command,
            crcbl_hal::null::Command::DrawIndexedIndirectCount(_)
        )));
        assert!(
            !commands
                .iter()
                .any(|command| matches!(command, crcbl_hal::null::Command::DrawIndexedIndirect(_)))
        );
        rendered.finish(device.as_ref(), exact);
    }

    /// **A device with a draw index draws a range of buckets per call, and one
    /// without it a call per bucket** — both indirect tails, read off the
    /// recorded stream of a whole frame.
    ///
    /// The ranged frame records one bind and one multi-draw per range in the
    /// depth prepass, whose draws together cover every bucket exactly once,
    /// and no count draw anywhere; the per-bucket frame records the call per
    /// bucket it always did. Both frames' counters are what they recorded.
    #[test]
    fn a_draw_index_puts_the_geometry_passes_on_a_call_per_range() {
        use crcbl_hal::null::Command;

        for path in [GeometryPath::IndirectCount, GeometryPath::IndirectPerBatch] {
            for ranged in [false, true] {
                let optional = if ranged {
                    Features::GPU_DRIVEN | Features::DRAW_INDEX
                } else {
                    DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)).optional_features
                };
                let (recorder, device, queue) = open_with(optional);
                let mut renderer = ForwardRenderer::with_scene_on_path(
                    device.as_ref(),
                    queue,
                    Format::Rgba8UnormSrgb,
                    &scene::demo(),
                    path,
                )
                .expect("the demo scene builds");
                assert_eq!(renderer.range_limit.is_some(), ranged, "{path:?}");
                let buckets = renderer.bucket_modes.len();
                assert!(buckets > 1, "one bucket packs into one call either way");
                let rendered = frame(device.as_ref(), &mut renderer, queue);

                let commands = commands_in_pass(&recorder, "depth-prepass");
                let binds = commands
                    .iter()
                    .filter(|command| matches!(command, Command::BindGroup { slot: 0, .. }))
                    .count();
                let draws: Vec<u32> = commands
                    .iter()
                    .filter_map(|command| match command {
                        Command::DrawIndexedIndirect(draw) => Some(draw.draw_count),
                        Command::DrawIndexedIndirectCount(draw) => {
                            assert!(!ranged, "{path:?}: a ranged pass records no count draw");
                            assert_eq!(draw.max_draw_count, 1);
                            Some(1)
                        }
                        _ => None,
                    })
                    .collect();
                assert_eq!(binds, draws.len(), "{path:?}: one bind per call");
                assert_eq!(
                    draws.iter().sum::<u32>() as usize,
                    buckets,
                    "{path:?}: every bucket drawn once"
                );
                if ranged {
                    assert!(
                        draws.len() < buckets,
                        "{path:?}: {draws:?} is a call per bucket over {buckets} buckets"
                    );
                } else {
                    assert_eq!(draws, vec![1; buckets], "{path:?}");
                }
                assert!(
                    !recorder
                        .commands()
                        .iter()
                        .any(|command| ranged
                            && matches!(command, Command::DrawIndexedIndirectCount(_))),
                    "{path:?}: a ranged frame records no count draw"
                );
                assert_eq!(
                    renderer.counters().draws,
                    recorded_draws(&recorder) as u64,
                    "{path:?}, ranged {ranged}"
                );
                rendered.finish(device.as_ref(), renderer);
                recorder.assert_valid();
            }
        }
    }

    /// **A scene holding every material mode draws each pipeline's buckets as
    /// one ranged call**, because the bucket table is numbered mode-major: the
    /// depth prepass records one call per depth pipeline and the colour pass
    /// one per sided pipeline, on both indirect tails.
    ///
    /// Numbered mesh by mesh, the same scene alternates modes bucket by bucket
    /// and every partition's runs are one bucket long, so the prepass would
    /// record a call per bucket — the counts below are what tell the two
    /// numberings apart, and the sums are what say every bucket still drew.
    #[test]
    fn every_mode_partition_of_a_ranged_frame_is_one_call() {
        use crcbl_hal::null::Command;
        use crcbl_shaders::mesh::GpuMaterial;

        let scene = {
            let mut scene = crate::scene::demo();
            while scene.materials.len() < 4 {
                scene.materials.push(GpuMaterial::UNTINTED);
            }
            let rows = [
                0,
                GpuMaterial::ALPHA_MODE_MASK,
                GpuMaterial::DOUBLE_SIDED,
                GpuMaterial::MODE_MASK,
            ];
            for (row, flags) in scene.materials.iter_mut().zip(rows) {
                row.flags = flags;
            }
            scene
        };
        for path in [GeometryPath::IndirectCount, GeometryPath::IndirectPerBatch] {
            let (recorder, device, queue) = open_with(Features::GPU_DRIVEN | Features::DRAW_INDEX);
            let mut renderer = ForwardRenderer::with_scene_on_path(
                device.as_ref(),
                queue,
                Format::Rgba8UnormSrgb,
                &scene,
                path,
            )
            .expect("the four-mode demo builds");
            assert!(renderer.range_limit.is_some(), "{path:?}");
            let buckets = renderer.bucket_modes.len();
            let per_mode = buckets / DEPTH_MODES.len();
            assert_eq!(
                per_mode * DEPTH_MODES.len(),
                buckets,
                "{path:?}: four twins"
            );
            assert!(
                per_mode > 1,
                "{path:?}: a mode of one bucket is one call under either numbering"
            );
            let rendered = frame(device.as_ref(), &mut renderer, queue);

            let draws = |label: &str| -> Vec<u32> {
                commands_in_pass(&recorder, label)
                    .iter()
                    .filter_map(|command| match command {
                        Command::DrawIndexedIndirect(draw) => Some(draw.draw_count),
                        _ => None,
                    })
                    .collect()
            };
            let prepass = draws("depth-prepass");
            assert_eq!(
                prepass,
                vec![u32::try_from(per_mode).expect("a few buckets"); DEPTH_MODES.len()],
                "{path:?}: one call per depth pipeline, each a whole mode"
            );
            let forward = draws("forward");
            assert_eq!(
                forward,
                vec![u32::try_from(2 * per_mode).expect("a few buckets"); 2],
                "{path:?}: one call per sided pipeline, each two adjacent modes"
            );
            rendered.finish(device.as_ref(), renderer);
            recorder.assert_valid();
        }
    }

    /// **Behind an amplification stage the mesh tail records one flat call per
    /// partition, and without one a range of buckets per call on a device with
    /// a draw index and a call per bucket without** — read off the recorded
    /// stream of a whole frame.
    ///
    /// The flat calls are [`flat_dispatch_calls`]: one structure each, the
    /// colour pass's sided segments in region 0, under the segment's first
    /// bucket's block — whatever the bucket count, and whether or not the
    /// device granted a draw index, which the flat call does not read. Without
    /// the stage the colour pass's calls, unrolled a structure at a time, are
    /// exactly the per-bucket dispatches [`mesh_dispatch_calls`] names — every
    /// bucket's own extents, each once. Either way the counters are what the
    /// frame recorded.
    #[test]
    fn the_mesh_tail_records_a_flat_call_per_partition_behind_a_task_stage() {
        use crcbl_hal::null::Command;

        // `None` is the demo scene; `Some(n)` is `n` copies of its cube, one
        // bucket each, in one material mode — so one run of `n` buckets.
        for cubes in [None, Some(4), Some(33)] {
            for task in [Features::TASK_SHADER, Features::empty()] {
                for ranged in [false, true] {
                    let case = format!("{cubes:?} cubes, {task:?}, ranged {ranged}");
                    let recorder = Recorder::new();
                    let optional = if ranged {
                        task | Features::DRAW_INDEX
                    } else {
                        task
                    };
                    let (device, queue) = open_mesh_path(&recorder, optional);
                    let mut scene = scene::demo();
                    if let Some(cubes) = cubes {
                        scene.meshes = vec![scene.meshes[DEMO_CUBE].clone(); cubes as usize];
                        scene.capacities.meshes = cubes;
                        scene.capacities.vertices =
                            cubes * crcbl_shaders::mesh::CUBE_VERTEX_COUNT as u32;
                        scene.capacities.indices =
                            cubes * crcbl_shaders::mesh::CUBE_INDEX_COUNT as u32;
                    }
                    let mut renderer = ForwardRenderer::with_scene_on_path(
                        device.as_ref(),
                        queue,
                        Format::Rgba8UnormSrgb,
                        &scene,
                        GeometryPath::MeshShader,
                    )
                    .expect("the mesh renderer builds");
                    assert_eq!(renderer.range_limit.is_some(), ranged, "{case}");
                    assert_eq!(renderer.culls_clusters(), !task.is_empty(), "{case}");
                    let buckets = renderer.bucket_constants.len();
                    assert!(buckets > 1, "one bucket packs into one call either way");
                    let rendered = frame(device.as_ref(), &mut renderer, queue);

                    let commands = commands_in_pass(&recorder, "forward");
                    let bound: Vec<u32> = commands
                        .iter()
                        .filter_map(|command| match command {
                            Command::BindGroup {
                                slot: 0,
                                dynamic_offsets,
                                ..
                            } => Some(dynamic_offsets[0]),
                            _ => None,
                        })
                        .collect();
                    let calls: Vec<DrawIndirect> = commands
                        .iter()
                        .filter_map(|command| match command {
                            Command::DrawMeshTasksIndirect(draw) => Some(*draw),
                            Command::DrawMeshTasks { .. }
                            | Command::DrawIndexedIndirect(_)
                            | Command::DrawIndexedIndirectCount(_) => {
                                panic!("{case}: the mesh tail recorded {command:?}")
                            }
                            _ => None,
                        })
                        .collect();
                    assert_eq!(bound.len(), calls.len(), "{case}: one bind per call");
                    assert!(
                        calls
                            .iter()
                            .all(|call| call.stride
                                == crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32),
                        "{case}: one structure a bucket, or a flat call's one"
                    );
                    if task.is_empty() {
                        // Each call a structure at a time: what a call per
                        // bucket would have recorded for the buckets it
                        // stands for.
                        let mut unrolled: Vec<DrawIndirect> = calls
                            .iter()
                            .flat_map(|call| {
                                (0..call.draw_count).map(|draw| DrawIndirect {
                                    offset: call.offset + u64::from(draw) * u64::from(call.stride),
                                    draw_count: 1,
                                    ..*call
                                })
                            })
                            .collect();
                        unrolled.sort_by_key(|draw| draw.offset);
                        assert_eq!(
                            unrolled,
                            mesh_dispatch_calls(&renderer),
                            "{case}: every bucket's own extents, each once"
                        );
                        let counts: Vec<u32> = calls.iter().map(|call| call.draw_count).collect();
                        match (ranged, cubes) {
                            (false, _) => assert_eq!(counts, vec![1; buckets], "{case}"),
                            (true, Some(cubes)) => assert_eq!(counts, vec![cubes], "{case}"),
                            (true, None) => assert!(
                                calls.len() < buckets,
                                "{case}: {counts:?} is a call per bucket over {buckets} buckets"
                            ),
                        }
                    } else {
                        let (expected, firsts) = flat_dispatch_calls(
                            &renderer,
                            crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED,
                        );
                        assert_eq!(calls, expected, "{case}: one flat call per sided partition");
                        assert_eq!(
                            bound,
                            firsts
                                .iter()
                                .map(|&bucket| renderer.bucket_constants[bucket as usize])
                                .collect::<Vec<_>>(),
                            "{case}: each under its segment's first bucket's block"
                        );
                    }
                    assert_eq!(
                        renderer.counters().draws,
                        recorded_draws(&recorder) as u64,
                        "{case}"
                    );
                    rendered.finish(device.as_ref(), renderer);
                    recorder.assert_valid();
                }
            }
        }
    }

    /// **Draw `d` of a ranged mesh call reads the words bucket `first + d`'s own
    /// block carries**, in every draw region.
    ///
    /// The host half of `mesh_cluster.slang`'s "One call for a range of
    /// buckets": a ranged call binds its first bucket's block alone, and the
    /// SPIR-V stages add the draw index to its `start_at` and `bucket` and to
    /// the two table words it names. So each bucket's block has to sit one word
    /// past the one before in all four, and the table words have to hold the
    /// bucket's own cluster base and count — read out of the bytes that reached
    /// the device, since a block written wrong leaves the renderer's fields
    /// right.
    #[test]
    fn a_mesh_block_names_the_words_a_ranged_draw_reads() {
        let recorder = Recorder::new();
        let (device, queue) = open_mesh_path(&recorder, Features::TASK_SHADER);
        let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
            .expect("the mesh renderer builds");
        let blocks = recorder
            .buffer_bytes(renderer.draw_constants)
            .expect("the blocks are live");
        let tables = recorder
            .buffer_bytes(renderer.primary.draws.tables())
            .expect("the tables are live");
        let word = |bytes: &[u8], at: usize| {
            u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four bytes"))
        };
        let buckets = renderer.bucket_constants.len();
        assert!(buckets > 1, "a range needs two buckets to step between");
        let bucket_count = u32::try_from(buckets).expect("a few buckets");
        let stride = renderer.bucket_constants[1] - renderer.bucket_constants[0];
        let block = |region: u32, bucket: u32| {
            let at = ((region * bucket_count + bucket) * stride) as usize;
            let field = |index: usize| word(&blocks, at + index * 4);
            crcbl_shaders::meshlet::ClusterDrawConstants {
                start_at: field(0),
                cluster_base: field(1),
                cluster_count: field(2),
                bucket: field(3),
                group_stride: field(4),
                level_groups_at: field(5),
                cluster_base_at: field(6),
                cluster_count_at: field(7),
                chunk_starts_at: field(8),
                chunk_starts_end: field(9),
            }
        };
        let mut bases = Vec::new();
        for region in 0..crcbl_shaders::draw_gen::DRAW_REGIONS {
            let first = block(region, 0);
            for bucket in 0..bucket_count {
                let own = block(region, bucket);
                assert_eq!(
                    word(&tables, own.cluster_base_at as usize * 4),
                    own.cluster_base,
                    "region {region} bucket {bucket}: the base word holds the base"
                );
                assert_eq!(
                    word(&tables, own.cluster_count_at as usize * 4),
                    own.cluster_count,
                    "region {region} bucket {bucket}: the count word holds the count"
                );
                // What draw `bucket` of a call bound at bucket 0's block reads
                // — and a flat call's workgroup that found bucket `bucket` by
                // searching the chunk starts from bucket 0's word to the
                // region's end.
                assert_eq!(
                    (
                        first.start_at + bucket,
                        first.bucket + bucket,
                        first.cluster_base_at + bucket,
                        first.cluster_count_at + bucket,
                        first.group_stride,
                        first.level_groups_at,
                        first.chunk_starts_at + bucket,
                        first.chunk_starts_end,
                    ),
                    (
                        own.start_at,
                        own.bucket,
                        own.cluster_base_at,
                        own.cluster_count_at,
                        own.group_stride,
                        own.level_groups_at,
                        own.chunk_starts_at,
                        own.chunk_starts_end,
                    ),
                    "region {region} bucket {bucket}"
                );
                assert_eq!(
                    own.chunk_starts_at,
                    crcbl_shaders::draw_gen::chunk_start_word(
                        renderer.primary.draws.visible_capacity(),
                        bucket_count,
                        region,
                        bucket,
                    ),
                    "region {region} bucket {bucket}: the word draw_gen writes its chunks' start into"
                );
                assert_eq!(
                    own.chunk_starts_end - own.chunk_starts_at,
                    bucket_count - bucket,
                    "region {region} bucket {bucket}: the search ends at the region's end word"
                );
                if region == 0 {
                    bases.push(own.cluster_base);
                }
            }
        }
        assert!(
            bases.windows(2).any(|pair| pair[0] != pair[1]),
            "the buckets' meshes start at different clusters, so a range reading its \
             first bucket's base for every draw would be seen: {bases:?}"
        );
        renderer.destroy(device.as_ref());
        recorder.assert_valid();
    }

    #[test]
    fn exact_geometry_path_builds_supported_tails_and_refuses_missing_features_without_allocating()
    {
        for features in [
            Features::GPU_DRIVEN,
            Features::COMPUTE | Features::MESH_SHADER,
        ] {
            let recorder = Recorder::new();
            let instance = NullInstance::new(crcbl_hal::DeviceCaps {
                features,
                limits: crcbl_hal::Limits::desktop(),
            })
            .with_recorder(recorder.clone());
            let device = instance
                .create_device(&DeviceDesc {
                    label: None,
                    adapter: crcbl_hal::AdapterId(0),
                    required_features: Features::COMPUTE,
                    optional_features: features,
                    compatible_surface: None,
                })
                .expect("null device opens");
            let queue = device.queue(QueueKind::Graphics).unwrap();
            for (path, required) in [
                (GeometryPath::IndirectPerBatch, Features::empty()),
                (GeometryPath::IndirectCount, Features::DRAW_INDIRECT_COUNT),
                (GeometryPath::MeshShader, Features::MESH_SHADER),
            ] {
                recorder.clear();
                let result = ForwardRenderer::with_scene_on_path(
                    device.as_ref(),
                    queue,
                    Format::Rgba8UnormSrgb,
                    &scene::demo(),
                    path,
                );
                if features.contains(required) {
                    let renderer = result.expect("supported exact tail builds");
                    assert_eq!(renderer.geometry_path(), path);
                    renderer.destroy(device.as_ref());
                } else {
                    assert!(
                        matches!(result, Err(HalError::UnsupportedFeatures { missing }) if missing == required)
                    );
                    assert!(
                        recorder.events().is_empty(),
                        "unsupported selection must not touch device objects"
                    );
                }
                recorder.assert_valid();
            }
        }
    }

    pub(super) fn open() -> (Recorder, Box<dyn Device>, QueueHandle) {
        open_with(DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)).optional_features)
    }

    /// [`open`] asking for `optional_features` instead of
    /// [`DeviceDesc::for_adapter`]'s.
    ///
    /// The null preset *has* more than the default request asks for, and a
    /// granted feature set is the intersection of the two — so this is how a test
    /// reaches a device with something the ordinary one lacks. What it exists for
    /// is [`Features::POLYGON_MODE_LINE`]: with the default request, `open`'s
    /// device has no line fill mode, which is the other half of the wireframe
    /// pair of tests below.
    fn open_with(optional_features: Features) -> (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 {
                optional_features,
                ..DeviceDesc::for_adapter(adapter.id)
            })
            .expect("the null backend always opens");
        let queue = device.queue(QueueKind::Graphics).expect("always present");
        (recorder, device, queue)
    }

    /// Puts one of [`scene::demo`]'s meshes in the frame the way a caller does.
    ///
    /// **Insertion order is what the caller decides**, and it is load-bearing:
    /// the slot an object lands in is topic 25's hysteresis key. So
    /// every test below places its objects in the order the frame used to hold
    /// them — the cube first, wherever there is one.
    fn place_demo(
        renderer: &mut ForwardRenderer,
        mesh: usize,
        material: usize,
        transform: Mat4,
    ) -> InstanceHandle {
        renderer
            .add_instance(&InstanceDesc {
                mesh,
                material,
                transform,
            })
            .expect("a pool of thousands has room for a handful of objects")
    }

    /// [`scene::demo`]'s cube, placed **first** so it takes the pool slot it has
    /// always had.
    ///
    /// `begin_frame` used to write this object for every caller; the tests below
    /// that are about a frame with something in it place it themselves now.
    pub(super) fn place_cube(renderer: &mut ForwardRenderer, transform: Mat4) -> InstanceHandle {
        place_demo(renderer, DEMO_CUBE, DEMO_UNTINTED, transform)
    }

    /// The whole renderer builds and tears down against a backend with no
    /// driver, which is what makes it testable on every CI leg.
    #[test]
    fn the_forward_renderer_builds_and_leaks_nothing() {
        let (recorder, device, queue) = open();
        let before = recorder.total_live_objects();
        let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
            .expect("the null backend accepts every descriptor");
        assert_eq!(renderer.target_format(), Format::Rgba8UnormSrgb);
        assert!(recorder.total_live_objects() > before);
        renderer.destroy(device.as_ref());
        assert_eq!(
            recorder.total_live_objects(),
            before,
            "every object created must be destroyed"
        );
        recorder.assert_valid();
    }

    /// The uniform ring really rotates, or a spinning cube is a
    /// read-after-write hazard across submissions.
    #[test]
    fn the_uniform_ring_rotates() {
        let (_, device, queue) = open();
        let mut renderer =
            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
        let camera = Camera::default();
        let light = DirectionalLight::default();

        let mut seen = Vec::new();
        for _ in 0..FRAMES_IN_FLIGHT * 2 {
            renderer
                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
                .expect("write");
            seen.push(renderer.primary.uniforms[renderer.frame]);
        }
        assert_ne!(
            seen[0], seen[1],
            "consecutive frames must not share a buffer"
        );
        assert_eq!(seen[0], seen[FRAMES_IN_FLIGHT], "and the ring must wrap");
        renderer.destroy(device.as_ref());
    }

    /// **The tonemap's block is a ring too, and it carries the exposure the
    /// caller set.**
    ///
    /// The bytes are the observable rather than the field, because the field is
    /// what a renderer that never wired the block up would also have: the claim
    /// is that the number reaches the buffer `tonemap.slang` reads, and only the
    /// null recorder's write log can say so.
    ///
    /// The default is checked first — a renderer nobody has called
    /// [`ForwardRenderer::set_exposure`] on writes the value the shader's
    /// `EXPOSURE` constant held, under
    /// [`ForwardRenderer::set_tonemap_curve`]'s own default.
    #[test]
    fn the_tonemap_block_holds_the_exposure_and_rotates_with_the_frame() {
        let (recorder, device, queue) = open();
        let mut renderer =
            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
        let camera = Camera::default();
        let light = DirectionalLight::default();

        renderer
            .begin_frame(device.as_ref(), &camera, &light, (64, 48))
            .expect("write");
        assert_eq!(
            recorder
                .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
                .expect("begin_frame wrote the block"),
            crcbl_shaders::tonemap::TonemapParams {
                exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
                curve: crcbl_shaders::tonemap::TonemapCurve::Aces,
                auto_exposure: false,
                coverage_alpha: false,
            }
            .to_bytes(),
            "an untouched renderer must write the exposure the constant used to hold, \
             under the operator this renderer starts on",
        );

        // A value that is neither the default nor a bound, so a block left at
        // either would fail.
        renderer.set_exposure(3.5);
        let mut slots = Vec::new();
        for _ in 0..FRAMES_IN_FLIGHT * 2 {
            renderer
                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
                .expect("write");
            slots.push(renderer.primary.tonemap_uniforms[renderer.frame]);
            assert_eq!(
                recorder
                    .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
                    .expect("begin_frame wrote the block"),
                crcbl_shaders::tonemap::TonemapParams {
                    exposure: 3.5,
                    curve: crcbl_shaders::tonemap::TonemapCurve::Aces,
                    auto_exposure: false,
                    coverage_alpha: false,
                }
                .to_bytes(),
                "the frame's own block must carry the exposure in force",
            );
        }
        assert_ne!(
            slots[0], slots[1],
            "consecutive frames must not share a block"
        );
        assert_eq!(slots[0], slots[FRAMES_IN_FLIGHT], "and the ring must wrap");

        renderer.destroy(device.as_ref());
    }

    /// **The curve reaches the block, and a caller can move it off the
    /// default.**
    ///
    /// The selector is a lane of the same ring the exposure rides in, and a lane
    /// nothing wrote would read as
    /// [`TonemapCurve::Clamp`](crcbl_shaders::tonemap::TonemapCurve::Clamp)
    /// whatever a caller asked for — a setter that compiles, a frame that looks
    /// right, and a curve that never runs. Since the renderer now *starts* on
    /// the fit, that failure would read as a working default, so the check runs
    /// in both directions: the untouched block carries the fit, and asking for
    /// the clamp changes the bytes on every frame of the ring.
    #[test]
    fn the_tonemap_block_carries_the_curve_a_caller_selected() {
        use crcbl_shaders::tonemap::TonemapCurve;

        let (recorder, device, queue) = open();
        let mut renderer =
            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
        let camera = Camera::default();
        let light = DirectionalLight::default();

        assert_eq!(
            renderer.tonemap_curve(),
            TonemapCurve::Aces,
            "a renderer nobody configured must run the operator the goldens were blessed under",
        );
        renderer
            .begin_frame(device.as_ref(), &camera, &light, (64, 48))
            .expect("write");
        let by_default = recorder
            .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
            .expect("begin_frame wrote the block");

        renderer.set_tonemap_curve(TonemapCurve::Clamp);
        assert_eq!(renderer.tonemap_curve(), TonemapCurve::Clamp);
        for _ in 0..FRAMES_IN_FLIGHT * 2 {
            renderer
                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
                .expect("write");
            let written = recorder
                .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
                .expect("begin_frame wrote the block");
            assert_eq!(
                written,
                crcbl_shaders::tonemap::TonemapParams {
                    exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
                    curve: TonemapCurve::Clamp,
                    auto_exposure: false,
                    coverage_alpha: false,
                }
                .to_bytes(),
                "every frame of the ring must carry the selected curve",
            );
            assert_ne!(
                written, by_default,
                "and it must differ from the block a default renderer writes",
            );
        }

        // **A readout runs the clamp whatever was selected**, and the selection
        // survives it: the caller's curve is still the caller's, the frame's is
        // the identity, and the shaded frame after gets the curve back. Asked of
        // the fit, which is the selection a readout has something to lose under.
        renderer.set_tonemap_curve(TonemapCurve::Aces);
        renderer.set_normals_view(true);
        assert_eq!(renderer.tonemap_curve(), TonemapCurve::Aces);
        assert_eq!(renderer.resolved_tonemap_curve(), TonemapCurve::Clamp);
        renderer
            .begin_frame(device.as_ref(), &camera, &light, (64, 48))
            .expect("write");
        assert_eq!(
            recorder
                .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
                .expect("begin_frame wrote the block"),
            crcbl_shaders::tonemap::TonemapParams {
                exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
                curve: TonemapCurve::Clamp,
                auto_exposure: false,
                coverage_alpha: false,
            }
            .to_bytes(),
            "a debug view's block must carry the clamp, since its pixels are data",
        );
        renderer.set_normals_view(false);
        assert_eq!(renderer.resolved_tonemap_curve(), TonemapCurve::Aces);

        renderer.destroy(device.as_ref());
    }

    /// **The exposure is clamped where it is set**, so no caller can reach a
    /// frame it cannot get back from.
    ///
    /// Each case is a different way of leaving the range, and the NaN one is the
    /// reason [`ForwardRenderer::set_exposure`] does not use `f32::clamp`: that
    /// propagates a NaN into the block, which is a frame of NaN pixels with no
    /// key to press to escape it.
    #[test]
    fn the_exposure_setter_clamps_to_a_range_a_caller_can_come_back_from() {
        let (_, device, queue) = open();
        let mut renderer =
            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
        assert!(
            (renderer.exposure() - crcbl_shaders::tonemap::DEFAULT_EXPOSURE).abs() < f32::EPSILON,
            "the default is {}",
            renderer.exposure(),
        );

        for (asked, expected) in [
            (2.0, 2.0),
            (EXPOSURE_MAX * 4.0, EXPOSURE_MAX),
            (f32::INFINITY, EXPOSURE_MAX),
            (EXPOSURE_MIN / 4.0, EXPOSURE_MIN),
            (0.0, EXPOSURE_MIN),
            (-8.0, EXPOSURE_MIN),
            (f32::NEG_INFINITY, EXPOSURE_MIN),
            (f32::NAN, EXPOSURE_MIN),
        ] {
            renderer.set_exposure(asked);
            assert!(
                (renderer.exposure() - expected).abs() < f32::EPSILON,
                "{asked} was clamped to {}, not {expected}",
                renderer.exposure(),
            );
        }

        renderer.destroy(device.as_ref());
    }

    /// **The debug views resolve in one order, however they are set.**
    ///
    /// Every one of them rides in one float lane and the shaders test the
    /// outermost threshold first, so a renderer with two switches on draws
    /// exactly one picture — and which one has to be a rule rather than
    /// whichever branch a caller's setter happened to run last. Every
    /// combination of the switches is walked, because a precedence written as an
    /// `if` chain is right for most of them by accident: a chain in the wrong
    /// order agrees with this one on every combination where at most one switch
    /// is set.
    ///
    /// **The two innermost views are the exception the walk is worth most for.**
    /// [`DebugView::Cascades`] keeps the shaded picture rather than replacing
    /// it, so it resolves *last* and its sentinel runs the other way down the
    /// lane; [`DebugView::ShadowAtlas`] resolves just above it and carries the
    /// *off* sentinel, because it is a pass rather than a branch. Every
    /// combination where either is set beside a replacing view is a combination
    /// an order written any other way answers differently, and there is no
    /// single-switch case that could tell them apart.
    ///
    /// [`ForwardRenderer::debug_view`] is asserted beside the lane, so the value
    /// a panel reads back and the value the shader branches on cannot drift —
    /// they are the same function.
    #[test]
    fn the_debug_views_resolve_in_one_order_however_they_are_set() {
        // `w` of the second `float4` of the block — the lane
        // `the_normals_view_moves_the_ambients_last_lane_and_no_other_byte`
        // spells out, and for its reason.
        const AMBIENT_W: usize = 64 + 16 + 12;

        let (recorder, device, queue) = open();
        let mut renderer =
            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
        let camera = Camera::default();
        let light = DirectionalLight::default();

        for bent in [false, true] {
            for motion in [false, true] {
                for occlusion in [false, true] {
                    for heatmap in [false, true] {
                        for lod in [false, true] {
                            for normals in [false, true] {
                                for (atlas, cascades) in
                                    [false, true].into_iter().flat_map(|atlas| {
                                        [false, true].map(|cascades| (atlas, cascades))
                                    })
                                {
                                    renderer.set_bent_normal_view(bent);
                                    renderer.set_motion_view(motion);
                                    renderer.set_occlusion_view(occlusion);
                                    renderer.set_heatmap(heatmap);
                                    renderer.set_lod_view(lod);
                                    renderer.set_normals_view(normals);
                                    renderer.set_atlas_view(atlas);
                                    renderer.set_cascade_view(cascades);
                                    let set = format!(
                                        "bent={bent} motion={motion} occlusion={occlusion} \
                                 heatmap={heatmap} lod={lod} normals={normals} \
                                 atlas={atlas} cascades={cascades}"
                                    );
                                    // Each switch reads back what it was set to, whatever
                                    // the others are: a caller's toggle is about the
                                    // caller's setting, and only `debug_view` is about the
                                    // picture.
                                    assert_eq!(renderer.bent_normal_view(), bent);
                                    assert_eq!(renderer.motion_view(), motion);
                                    assert_eq!(renderer.occlusion_view(), occlusion);
                                    assert_eq!(renderer.heatmap(), heatmap);
                                    assert_eq!(renderer.lod_view(), lod);
                                    assert_eq!(renderer.normals_view(), normals);
                                    assert_eq!(renderer.atlas_view(), atlas);
                                    assert_eq!(renderer.cascade_view(), cascades);

                                    let expected = if bent {
                                        DebugView::BentNormal
                                    } else if motion {
                                        DebugView::Motion
                                    } else if occlusion {
                                        DebugView::AmbientOcclusion
                                    } else if heatmap {
                                        DebugView::Heatmap
                                    } else if lod {
                                        DebugView::LodTint
                                    } else if normals {
                                        DebugView::Normals
                                    } else if atlas {
                                        // **Below every replacing view above and
                                        // above the tint below**, which is the
                                        // half of this order no single-switch
                                        // case reaches: with a replacing view
                                        // also set the frame is that view's, and
                                        // with the tint also set the frame is the
                                        // atlas.
                                        DebugView::ShadowAtlas
                                    } else if cascades {
                                        // **Last, which is the half of this order a
                                        // chain in any other arrangement would get
                                        // right by accident.** The cascade tint is a
                                        // multiply on the shaded picture, so every
                                        // combination that also names a replacing
                                        // view has to resolve to *that* view — and
                                        // those are exactly the combinations an
                                        // `if cascades` written one line higher
                                        // would answer differently.
                                        DebugView::Cascades
                                    } else {
                                        DebugView::Shaded
                                    };
                                    assert_eq!(renderer.debug_view(), expected, "{set}");

                                    renderer
                                        .begin_frame(device.as_ref(), &camera, &light, (64, 48))
                                        .expect("write");
                                    let block = recorder
                                        .buffer_bytes(renderer.primary.uniforms[renderer.frame])
                                        .expect("begin_frame wrote the block");
                                    let sentinel = match expected {
                                        DebugView::BentNormal => {
                                            mesh::FrameUniforms::BENT_NORMAL_VIEW_ON
                                        }
                                        DebugView::Motion => mesh::FrameUniforms::MOTION_VIEW_ON,
                                        DebugView::AmbientOcclusion => {
                                            mesh::FrameUniforms::OCCLUSION_VIEW_ON
                                        }
                                        DebugView::Heatmap => mesh::FrameUniforms::HEATMAP_VIEW_ON,
                                        DebugView::LodTint => mesh::FrameUniforms::LOD_VIEW_ON,
                                        DebugView::Normals => mesh::FrameUniforms::NORMALS_VIEW_ON,
                                        DebugView::Cascades => mesh::FrameUniforms::CASCADE_VIEW_ON,
                                        // **The atlas view carries the *off*
                                        // sentinel**, which is what makes this
                                        // assertion say something rather than
                                        // restate `debug_view_lane`: the colour
                                        // pass draws the shaded picture and
                                        // `crate::atlas_view`'s pass replaces
                                        // it, so a lane of its own here would be
                                        // a threshold no shader tests.
                                        DebugView::ShadowAtlas | DebugView::Shaded => {
                                            mesh::FrameUniforms::NORMALS_VIEW_OFF
                                        }
                                    };
                                    assert_eq!(
                                        &block[AMBIENT_W..AMBIENT_W + 4],
                                        &sentinel.to_le_bytes(),
                                        "{set} resolved to {expected:?}, and the lane says otherwise"
                                    );
                                    // And the resolve comes off for every one of them:
                                    // these frames are read back as data, so their colours
                                    // have to stay the ones the shader wrote — see
                                    // `resolved_effects`. The whole slot rather than one
                                    // tier of it, because which tier the default carries
                                    // is not what this is about.
                                    assert_eq!(
                                        renderer.effects().intersects(Antialiasing::SLOT),
                                        expected == DebugView::Shaded,
                                        "{set}"
                                    );
                                }
                            }
                        }
                    }
                }
            }
        }

        renderer.destroy(device.as_ref());
    }

    /// **The atlas viewer records one pass, and only on the frame it is the view
    /// showing.**
    ///
    /// The mechanism no other check in this file can see. Every other debug view
    /// is a lane of the frame block, so
    /// [`the_debug_views_resolve_in_one_order_however_they_are_set`] observes it
    /// by reading four bytes; this one is a *pass*, and "the pass was recorded"
    /// is a claim about the command stream and about nothing else. A switch that
    /// resolved correctly and recorded nothing would satisfy every other
    /// assertion in this module and draw the frame unchanged.
    ///
    /// Three arms, and the third is the one that makes the first two mean
    /// something:
    ///
    /// * off — no pass at all, which is what makes the off position
    ///   bit-identical for every golden in this workspace;
    /// * on — the pass, with the full-screen triangle in it;
    /// * on **beside a replacing view** — no pass, because
    ///   [`ForwardRenderer::debug_view`] resolved to that view and the atlas is
    ///   not what this frame draws. That is the half a `self.atlas_view` read at
    ///   the recording site would get wrong while passing both arms above.
    ///
    /// [`the_debug_views_resolve_in_one_order_however_they_are_set`]: fn@the_debug_views_resolve_in_one_order_however_they_are_set
    /// **The shadow atlas viewer replaces the tonemap and the ground grid, and
    /// the draw count follows.**
    ///
    /// The viewer fills every display pixel with a `DontCare` load, so a
    /// tonemapped frame or a grid recorded under it is stored and discarded.
    /// The pass counts go red if either comes back; the counter goes red if
    /// `counters` still charges the frame for the triangles it no longer
    /// records.
    #[test]
    fn the_atlas_viewer_replaces_the_display_passes_and_the_count_follows() {
        let (recorder, device, queue) = open();
        let mut renderer =
            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
        renderer
            .set_ground_grid(device.as_ref(), Some(GridStyle::default()))
            .expect("the null backend builds every pipeline");
        renderer.set_atlas_view(true);
        assert_eq!(renderer.debug_view(), DebugView::ShadowAtlas);

        let viewing = frame(device.as_ref(), &mut renderer, queue);
        let opened = |label: &str| {
            recorder
                .commands()
                .iter()
                .filter(|command| {
                    matches!(command.opens_pass(), Some((_, Some(recorded))) if recorded == label)
                })
                .count()
        };
        assert_eq!(opened(crate::atlas_view::LABEL), 1);
        assert_eq!(opened("tonemap"), 0, "the viewer discards the tonemap");
        assert_eq!(opened("grid"), 0, "and the grid drawn over it");
        assert_eq!(
            renderer.counters().draws,
            recorded_draws(&recorder) as u64,
            "the counter charges the frame for exactly the draws it recorded"
        );
        viewing.finish(device.as_ref(), renderer);
    }

    #[test]
    fn the_atlas_viewer_records_its_pass_only_when_it_is_the_view_showing() {
        use crcbl_hal::null::Command;

        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        let (camera, sun) = (Camera::default(), DirectionalLight::default());

        // How many times the viewer's pass was opened since `from`, which is
        // where the previous arm's commands ended.
        let opened = |from: usize| {
            recorder.commands()[from..]
                .iter()
                .filter(|command| {
                    matches!(
                        command.opens_pass(),
                        Some((_, Some(recorded))) if recorded == crate::atlas_view::LABEL
                    )
                })
                .count()
        };

        let shaded = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
        assert_eq!(
            opened(0),
            0,
            "a frame drawing the shaded picture recorded the atlas viewer's pass"
        );
        let after_shaded = recorder.commands().len();
        shaded.release(device);

        renderer.set_atlas_view(true);
        assert_eq!(renderer.debug_view(), DebugView::ShadowAtlas);
        let viewing = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
        assert_eq!(
            opened(after_shaded),
            1,
            "the atlas viewer is on and its pass was not recorded exactly once"
        );
        // And what it recorded is the over-sized triangle and nothing else: a
        // pass that bound a pipeline and drew no vertices would open above and
        // leave the frame the tonemap wrote.
        let drawn: Vec<(u32, u32)> = commands_in_pass(&recorder, crate::atlas_view::LABEL)
            .into_iter()
            .filter_map(|command| match command {
                Command::Draw {
                    vertices,
                    instances,
                } => Some((
                    vertices.end - vertices.start,
                    instances.end - instances.start,
                )),
                _ => None,
            })
            .collect();
        assert_eq!(drawn, vec![(crate::atlas_view::FULLSCREEN_VERTICES, 1)]);
        let after_viewing = recorder.commands().len();
        viewing.release(device);

        // The switch left on, and a replacing view asked for over the top of it.
        renderer.set_normals_view(true);
        assert_eq!(
            renderer.debug_view(),
            DebugView::Normals,
            "the atlas view does not lose to a replacing view, so the arm below asks nothing"
        );
        let normals = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
        assert_eq!(
            opened(after_viewing),
            0,
            "the frame resolved to the normals view and still recorded the atlas viewer's \
             pass over the top of it"
        );
        normals.release(device);

        renderer.destroy(device);
    }

    /// **The heatmap moves the ambient's last lane and no other byte**, and
    /// switching it off puts the block back.
    ///
    /// The normals view's assertion below, for the outermost of the three: the
    /// overlay costs one lane, so every golden image ever blessed is untouched
    /// by the feature existing. The `lod_params` row the heatmap reads is
    /// written every frame whether it is on or not — it is the numbers the
    /// selection used — so this compares two frames of the *same* camera and
    /// budget, where that row is equal on both sides and any byte outside the
    /// lane is a real difference.
    #[test]
    fn the_heatmap_moves_the_ambients_last_lane_and_no_other_byte() {
        const AMBIENT_W: usize = 64 + 16 + 12;

        // Held for the whole comparison, and it is not this check's own knob:
        // `r_shadow_filter` and `r_shadow_split` land in the block's
        // `shadow_filter` row on every `begin_frame`, and the filter checks in
        // this module move them under this lock while `cargo test` runs the
        // module's checks as threads of one process. Two frames read either side
        // of such a move differ at that row, which is outside every lane below —
        // one run in twelve, measured 2026-09-04.
        let _filter = shadow_filter_switch();
        let (recorder, device, queue) = open();
        let mut renderer =
            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
        let camera = Camera::default();
        let light = DirectionalLight::default();
        let block = |renderer: &mut ForwardRenderer| -> Vec<u8> {
            renderer
                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
                .expect("write");
            recorder
                .buffer_bytes(renderer.primary.uniforms[renderer.frame])
                .expect("begin_frame wrote the block")
        };

        assert!(
            !renderer.heatmap(),
            "the heatmap has to be off in a renderer nobody has asked",
        );
        let shaded = block(&mut renderer);
        assert_eq!(
            &shaded[AMBIENT_W..AMBIENT_W + 4],
            &mesh::FrameUniforms::NORMALS_VIEW_OFF.to_le_bytes(),
            "an untouched renderer must write the value every golden image was blessed with",
        );

        renderer.set_heatmap(true);
        let heatmap = block(&mut renderer);
        assert_eq!(
            &heatmap[AMBIENT_W..AMBIENT_W + 4],
            &mesh::FrameUniforms::HEATMAP_VIEW_ON.to_le_bytes(),
            "the switch has to reach the lane the mesh stage branches on",
        );
        let outside: Vec<usize> = shaded
            .iter()
            .zip(heatmap.iter())
            .enumerate()
            .filter(|(at, (was, now))| was != now && !(AMBIENT_W..AMBIENT_W + 4).contains(at))
            .map(|(at, _)| at)
            .collect();
        assert!(
            outside.is_empty(),
            "the frame block changed at {outside:?}, which is outside the heatmap's own lane",
        );

        renderer.set_heatmap(false);
        assert_eq!(
            block(&mut renderer),
            shaded,
            "switching the view off has to put the block back, not just stop reporting it",
        );

        renderer.destroy(device.as_ref());
    }

    /// **The normals view moves one lane of the frame block and nothing else.**
    ///
    /// The mechanism, at the level a null device can observe it: which bytes of
    /// the buffer `mesh.slang` reads changed. A field on the renderer would say
    /// only that a flag moved; the block is what the shader actually branches on.
    ///
    /// Four claims, and each rules out a different way of passing wrongly:
    ///
    /// * an untouched renderer writes [`FrameUniforms::NORMALS_VIEW_OFF`] — which
    ///   is what makes every golden image untouched by this feature;
    /// * switching on writes [`FrameUniforms::NORMALS_VIEW_ON`] into the lane the
    ///   shader reads, at the offset `std140` puts it at rather than at one this
    ///   test picked;
    /// * **those four bytes are the only ones that moved**, so the switch did not
    ///   come at the cost of the ambient colour beside it or of any matrix;
    /// * and switching off puts the block back exactly, so the view is a toggle
    ///   rather than a one-way door.
    ///
    /// [`FrameUniforms::NORMALS_VIEW_OFF`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_OFF
    /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
    #[test]
    fn the_normals_view_moves_the_ambients_last_lane_and_no_other_byte() {
        // `w` of the second `float4` of the block: one `float4x4`, one `float4`,
        // then three floats of ambient colour. Spelled as the sum rather than as
        // `92` so that a member arriving before it is a compile-time question
        // about `FrameUniforms`' own layout and not a silent read of a matrix.
        const AMBIENT_W: usize = 64 + 16 + 12;

        // Held for the whole comparison, and it is not this check's own knob:
        // `r_shadow_filter` and `r_shadow_split` land in the block's
        // `shadow_filter` row on every `begin_frame`, and the filter checks in
        // this module move them under this lock while `cargo test` runs the
        // module's checks as threads of one process. Two frames read either side
        // of such a move differ at that row, which is outside every lane below —
        // one run in twelve, measured 2026-09-04.
        let _filter = shadow_filter_switch();
        let (recorder, device, queue) = open();
        let mut renderer =
            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
        let camera = Camera::default();
        let light = DirectionalLight::default();
        let block = |renderer: &mut ForwardRenderer| -> Vec<u8> {
            renderer
                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
                .expect("write");
            recorder
                .buffer_bytes(renderer.primary.uniforms[renderer.frame])
                .expect("begin_frame wrote the block")
        };

        assert!(
            !renderer.normals_view(),
            "the normals view has to be off in a renderer nobody has asked",
        );
        let shaded = block(&mut renderer);
        assert_eq!(
            &shaded[AMBIENT_W..AMBIENT_W + 4],
            &mesh::FrameUniforms::NORMALS_VIEW_OFF.to_le_bytes(),
            "an untouched renderer must write the value every golden image was blessed with",
        );

        renderer.set_normals_view(true);
        assert!(renderer.normals_view());
        let normals = block(&mut renderer);
        assert_eq!(
            &normals[AMBIENT_W..AMBIENT_W + 4],
            &mesh::FrameUniforms::NORMALS_VIEW_ON.to_le_bytes(),
            "the switch has to reach the lane the fragment stage branches on",
        );
        // The bytes that moved, and they all have to be inside the lane — not
        // *all* of the lane, because `0.0f` and `1.0f` share their two low bytes
        // and an equality against the whole range would be a test about IEEE 754
        // rather than about the block.
        let outside: Vec<usize> = shaded
            .iter()
            .zip(normals.iter())
            .enumerate()
            .filter(|(at, (was, now))| was != now && !(AMBIENT_W..AMBIENT_W + 4).contains(at))
            .map(|(at, _)| at)
            .collect();
        assert!(
            outside.is_empty(),
            "the frame block changed at {outside:?}, which is outside the normals view's own lane",
        );

        renderer.set_normals_view(false);
        assert!(!renderer.normals_view());
        assert_eq!(
            block(&mut renderer),
            shaded,
            "switching the view off has to put the block back, not just stop reporting it",
        );

        renderer.destroy(device.as_ref());
    }

    /// **A frame uploads the instances a caller moved, and a frame nobody moved
    /// anything in uploads nothing at all.**
    ///
    /// The second half is the stronger claim and it is the one that needed the
    /// cube to become an ordinary instance: `begin_frame` used to take the
    /// cube's transform as an argument and write it into the pool every frame,
    /// so that slot was dirty in every ring slot forever and a motionless scene
    /// paid a spinning one's transfer. The bytes were identical, so no golden
    /// image could ever have shown it — the recorder's write log is the only
    /// place the difference is visible.
    ///
    /// The pyramid is here so that "only the one that moved" is a claim about a
    /// choice: with one instance in the array, uploading it and uploading
    /// everything are the same event.
    #[test]
    fn only_the_instance_that_moved_is_uploaded() {
        let (recorder, device, queue) = open();
        let mut renderer =
            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
        let instance_buffers = renderer.instances.buffers().to_vec();
        let cube = place_cube(&mut renderer, Mat4::IDENTITY);
        place_demo(
            &mut renderer,
            DEMO_PYRAMID,
            DEMO_UNTINTED,
            Mat4::from_translation(Vec3::X),
        );

        // Both instances are dirty in *every* slot when they are inserted, so
        // the first frames upload both however well delta upload works. The ring
        // has to be walked right through before an upload is evidence about the
        // delta rather than about initialisation.
        let frame = |renderer: &mut ForwardRenderer| {
            renderer
                .begin_frame(
                    device.as_ref(),
                    &Camera::default(),
                    &DirectionalLight::default(),
                    (64, 48),
                )
                .expect("write");
        };
        for _ in 0..FRAMES_IN_FLIGHT {
            frame(&mut renderer);
        }
        let instance_writes = |from: usize| -> Vec<(u64, usize)> {
            recorder
                .events()
                .into_iter()
                .skip(from)
                .filter_map(|event| match event {
                    crcbl_hal::null::Event::BufferWritten {
                        buffer,
                        offset,
                        len,
                    } if instance_buffers.contains(&buffer) => Some((offset, len)),
                    _ => None,
                })
                .collect()
        };

        let before = recorder.events().len();
        frame(&mut renderer);
        assert_eq!(
            instance_writes(before),
            [],
            "a frame in which nothing moved must upload no instance bytes at all"
        );

        let before = recorder.events().len();
        let model = ForwardRenderer::spin(1.25);
        renderer.set_instance(
            cube,
            &InstanceDesc {
                mesh: DEMO_CUBE,
                material: DEMO_UNTINTED,
                transform: model,
            },
        );
        frame(&mut renderer);
        assert_eq!(
            renderer
                .instances
                .get(cube)
                .expect("the cube is live")
                .transform,
            model.to_cols_array(),
            "the model matrix must land in the instance, not the uniform block"
        );
        let cube_at = u64::from(renderer.instances.index(cube).expect("the cube is live"))
            * crcbl_shaders::mesh::INSTANCE_STRIDE as u64;
        assert_eq!(
            instance_writes(before),
            [(cube_at, crcbl_shaders::mesh::INSTANCE_STRIDE)],
            "a steady-state frame must upload exactly the one instance that changed"
        );

        renderer.destroy(device.as_ref());
        recorder.assert_valid();
    }

    /// **An object takes one pool slot, a rewrite keeps it, and a removal gives
    /// it back for the next object to reuse.**
    ///
    /// The three-call bookkeeping every caller of the instance API depends on,
    /// checked on the pool rather than on the recorder. A `set_instance` that
    /// inserted instead would take a fresh slot per call — the pool exhausted in
    /// a few thousand frames of a caller that writes a transform per frame, which
    /// is what every sample does — and every slot it abandoned would stay
    /// **live**, so the frame would draw a copy of the object at each transform
    /// it had ever been given. Neither is something a golden image would show
    /// until the pool ran out.
    ///
    /// `only_the_instance_that_moved_is_uploaded` is the delta half of this and
    /// reads the recorder; this is the bookkeeping half and reads the pool, which
    /// is where an abandoned slot would still be counted.
    ///
    /// Run over every mesh of [`scene::demo`], because the DAG is the one whose
    /// slot carries topic 25's hysteresis state — the reuse below is
    /// exactly what [`ForwardRenderer::add_instance`] documents as inheriting a
    /// previous occupant's expanded groups.
    #[test]
    fn an_object_takes_one_slot_and_a_removal_gives_it_back() {
        for mesh in [DEMO_CUBE, DEMO_PYRAMID, DEMO_OPEN_BOX, DEMO_DUNES] {
            let (recorder, device, queue) = open();
            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
                .expect("built");
            // The null backend takes an indirect tail, so the DAG is placeable
            // here; the arm that cannot select a level refuses before an
            // application ever calls this.
            assert!(
                renderer.selects_levels(),
                "an indirect tail chooses a level for every mesh, DAG included"
            );
            // What the pool holds before anything is placed, which is nothing: a
            // renderer places no object of its own any more.
            let resident = renderer.instances.len();
            assert_eq!(resident, 0, "a fresh renderer holds no objects");

            let first = Mat4::from_translation(Vec3::new(1.0, 2.0, 3.0));
            let handle = place_demo(&mut renderer, mesh, DEMO_UNTINTED, first);
            assert_eq!(
                renderer.instances.len(),
                resident + 1,
                "mesh {mesh}: add_instance takes one slot"
            );

            // The rewrite is the whole test: the same handle, the same slot
            // count, and the new transform in it.
            let second = Mat4::from_translation(Vec3::new(-4.0, 5.0, -6.0));
            renderer.set_instance(
                handle,
                &InstanceDesc {
                    mesh,
                    material: DEMO_UNTINTED,
                    transform: second,
                },
            );
            assert_eq!(
                renderer.instances.len(),
                resident + 1,
                "mesh {mesh}: set_instance must rewrite its instance, not insert a second"
            );
            assert_eq!(
                renderer.instances.slot_count(),
                u32::try_from(resident + 1).expect("a handful of instances"),
                "mesh {mesh}: set_instance must not have reached past the slot it holds"
            );
            assert_eq!(
                renderer
                    .instances
                    .get(handle)
                    .unwrap_or_else(|| panic!("mesh {mesh}: the instance is live"))
                    .transform,
                second.to_cols_array(),
                "mesh {mesh}: set_instance must have written the second transform"
            );

            // And a removal gives the slot back, so a caller toggling an object
            // is not a leak either.
            renderer.remove_instance(handle);
            assert_eq!(
                renderer.instances.len(),
                resident,
                "mesh {mesh}: remove_instance must free the slot rather than hide the object"
            );
            place_demo(&mut renderer, mesh, DEMO_UNTINTED, first);
            assert_eq!(
                renderer.instances.slot_count(),
                u32::try_from(resident + 1).expect("a handful of instances"),
                "mesh {mesh}: the object after a removal must reuse the freed slot"
            );

            renderer.destroy(device.as_ref());
            recorder.assert_valid();
        }
    }

    /// **The description resolves to the ids the renderer used to hand itself**:
    /// one table entry per description mesh, in description order, with the DAG
    /// occupying one per level after them — and every level's vertex base
    /// measured from level 0's, which is zero.
    ///
    /// Upload order is what decides a mesh id, and `cull.slang` reads a bounding
    /// box out of the entry the *instance* names. So a description walked in
    /// another order, or a DAG whose levels landed among the flat meshes, would
    /// leave every instance naming a mesh that is not its own: the cube culled
    /// against the pyramid's box, the dunes patch drawn as an open box. Every
    /// one of those is a frame that still looks like a frame.
    ///
    /// The bases are asserted against the table bytes rather than against
    /// `ResidentMesh`, because the table is what the GPU reads.
    #[test]
    fn the_description_resolves_to_the_ids_it_was_written_in() {
        let (recorder, device, queue) = open();
        let renderer =
            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");

        assert_eq!(
            renderer.mesh_ids,
            [0, 1, 2, 3],
            "the four description meshes take the first four table entries, in order"
        );

        // The DAG's coarser levels follow level 0, so a cut that spans them
        // reads entries the flat meshes never occupied.
        let scene = scene::demo();
        let Geometry::Dag { dag, .. } = &scene.meshes[DEMO_DUNES].geometry else {
            panic!("the demo description's fourth mesh is the DAG");
        };
        let level_ids: Vec<u32> = (0..dag.levels.len())
            .map(|level| renderer.mesh_ids[DEMO_DUNES] + level as u32)
            .collect();
        assert!(
            level_ids
                .iter()
                .all(|&id| id > renderer.mesh_ids[DEMO_OPEN_BOX]),
            "every dunes level is past the flat residents: {level_ids:?}"
        );

        // **Level 0 is at the pool's own first vertex**, which is what makes
        // every `ClusterSelect::vertex_base` a non-negative offset from it — the
        // sum the mesh stage forms with the instance's own base.
        let entries: Vec<crcbl_shaders::mesh::GpuMesh> = level_ids
            .iter()
            .map(|&id| mesh_entry(&recorder, &renderer, id))
            .collect();
        let level_zero = entries[0].base_vertex;
        assert_eq!(
            level_zero,
            mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_OPEN_BOX]).base_vertex
                + crcbl_shaders::mesh::OPEN_BOX_VERTEX_COUNT as u32,
            "the DAG starts where the last flat resident ends"
        );
        let bases: Vec<u32> = entries
            .iter()
            .map(|entry| {
                entry
                    .base_vertex
                    .checked_sub(level_zero)
                    .expect("a level below level 0 would wrap the offset a cluster carries")
            })
            .collect();
        assert_eq!(
            bases[0], 0,
            "level 0 is the base every other is measured from"
        );
        assert!(
            bases.windows(2).all(|pair| pair[0] < pair[1]),
            "each level starts past the one below it: {bases:?}"
        );

        renderer.destroy(device.as_ref());
        recorder.assert_valid();
    }

    /// **A description that is not [`scene::demo`]: five meshes and two DAGs.**
    ///
    /// [`ForwardRenderer::with_scene`] is written for any mesh count and any
    /// number of DAGs, and until this nothing had put either through it — every
    /// golden image and every end-to-end run is `scene::demo()`, whose four
    /// meshes hold one DAG between them.
    ///
    /// What only a second DAG exercises is the **concatenation**: `level_groups`
    /// is every DAG's groups laid end to end and a DAG reaches its own run
    /// through the `first_group` offset handed to `ClusterDag::selection_records`,
    /// which is zero for the first one and therefore invisible while there is
    /// only one. A second DAG whose records still named the first's groups would
    /// descend a hierarchy belonging to another surface — a cut that is a
    /// plausible picture and matches no assertion the CPU makes about the frame.
    ///
    /// On the mesh path, because that is where the offset is *used*: an indirect
    /// tail takes a uniform cut and builds no [`ClusterSelect`] records at all.
    ///
    /// [`ClusterSelect`]: crcbl_shaders::cluster_select::ClusterSelect
    #[test]
    fn a_second_dag_reaches_its_own_groups_and_not_the_first_s() {
        use crcbl_shaders::cluster_select::{CLUSTER_SELECT_STRIDE, ClusterSelect};

        let recorder = Recorder::new();
        let (device, queue) = open_mesh_path(&recorder, Features::TASK_SHADER);

        // The engine has one DAG, so a second one is a second copy of it. That
        // is the whole point: two DAGs whose *groups* are alike is the case
        // where reaching the wrong run still produces a cut, and so the case a
        // frame comparison could never catch.
        let mut scene = scene::demo();
        let mut again = scene.meshes[DEMO_DUNES].clone();
        again.label = "dunes again".into();
        scene.meshes.push(again);
        // Room for the second copy. Doubling rather than measuring, because the
        // number that matters is that the description carries its own sizes at
        // all — see `Capacities`, which is the caller's to choose.
        scene.capacities.vertices *= 2;
        scene.capacities.indices *= 2;
        let second_dag = scene.meshes.len() - 1;

        let Geometry::Dag { dag, .. } = &scene.meshes[DEMO_DUNES].geometry else {
            panic!("the demo description's fourth mesh is the DAG");
        };
        let levels = dag.levels.len();
        let groups = dag.level_groups().len();
        assert!(groups > 0, "a DAG with no groups would select nothing");

        let mut renderer =
            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
                .expect("a five-mesh description with two DAGs is one this can make resident");

        // Every level of both is its own table entry, laid down in description
        // order, so the second DAG's level 0 is a whole hierarchy past the
        // first's.
        assert_eq!(
            renderer.mesh_ids.len(),
            scene.meshes.len(),
            "one id per description mesh, whatever the count"
        );
        assert_eq!(
            renderer.mesh_ids[second_dag],
            renderer.mesh_ids[DEMO_DUNES] + levels as u32,
            "the second DAG's level 0 starts past every level of the first"
        );

        // **The hysteresis state is per instance per resident group**, and
        // `group_stride` is what says how many groups that is. One DAG made this
        // number a single hierarchy's; two is what tells a stride that sums from
        // one that took the first answer it found.
        assert_eq!(
            renderer.primary.draws.group_stride(),
            u32::try_from(groups * 2).expect("a few dozen groups per DAG"),
            "every resident DAG's groups are in the stride, not just the first's"
        );

        // The records themselves: which group each cluster produces and which
        // contains it, as the amplification stage reads them.
        let clusters = renderer
            .clusters
            .as_ref()
            .expect("the mesh path builds a cluster pool");
        let selection = recorder
            .buffer_bytes(clusters.selection())
            .expect("the selection records are live");
        // Entries are laid down in description order, a flat mesh taking one and
        // a DAG one per level — so the second DAG's start a hierarchy past the
        // first's, which start past the three flat residents.
        let first_entry = DEMO_DUNES;
        let record = |entry: usize| -> Vec<ClusterSelect> {
            let range = clusters.range(entry).expect("one range per entry");
            (range.base..range.base + range.count)
                .map(|cluster| {
                    let at = cluster as usize * CLUSTER_SELECT_STRIDE;
                    ClusterSelect::from_bytes(
                        selection[at..at + CLUSTER_SELECT_STRIDE]
                            .try_into()
                            .expect("one whole record"),
                    )
                })
                .collect()
        };
        // The named group of every record that has one, per DAG — and the count,
        // because a comparison over an empty set is a check that cannot fail.
        let named = |base: usize| -> Vec<u32> {
            (base..base + levels)
                .flat_map(record)
                .flat_map(|select| {
                    let producer = (select.flags & ClusterSelect::HAS_PRODUCER != 0)
                        .then_some(select.producer_group);
                    let container = (select.flags & ClusterSelect::HAS_CONTAINER != 0)
                        .then_some(select.container_group);
                    producer.into_iter().chain(container)
                })
                .collect()
        };
        let boundary = u32::try_from(groups).expect("a few dozen groups per DAG");
        let first = named(first_entry);
        let second = named(first_entry + levels);
        assert!(
            !first.is_empty() && first.len() == second.len(),
            "the two copies must name the same number of groups: {} against {}",
            first.len(),
            second.len()
        );
        assert!(
            first.iter().all(|&group| group < boundary),
            "the first DAG's records stay inside its own run: {first:?}"
        );
        assert!(
            second
                .iter()
                .all(|&group| (boundary..boundary * 2).contains(&group)),
            "the second DAG's records must name the groups past the first's, and \
             `first_group` is the only thing that puts them there: {second:?}"
        );

        // And both are placeable through the runtime API, which is what a
        // description of a shape no `set_*` method names is *for*.
        let place = |renderer: &mut ForwardRenderer, mesh: usize, x: f32| {
            renderer
                .add_instance(&InstanceDesc {
                    mesh,
                    material: DEMO_UNTINTED,
                    transform: Mat4::from_translation(Vec3::new(x, 0.0, 0.0)),
                })
                .expect("the pool has room")
        };
        let near = place(&mut renderer, DEMO_DUNES, -64.0);
        let far = place(&mut renderer, second_dag, 64.0);
        let index = |handle| {
            renderer
                .instances
                .index(handle)
                .expect("a just-added instance is live")
        };
        assert_ne!(
            index(near),
            index(far),
            "two instances take two slots, and the index is the hysteresis key"
        );
        assert_eq!(
            renderer.instances.get(far).expect("live").mesh,
            renderer.mesh_ids[second_dag],
            "an InstanceDesc's mesh index resolves through the description, not through \
             a table id the caller cannot know"
        );

        renderer.destroy(device.as_ref());
        recorder.assert_valid();
    }

    /// **A description the renderer cannot make resident is refused before the
    /// first device object exists**, so a rejection leaks nothing.
    ///
    /// `build` hands the geometry pool and the material table to the rollback
    /// and then creates a dozen objects with `?` between them. A check that ran
    /// part way down that list would be a new early exit on the wrong side of a
    /// handover, and the pool would go with it — which is exactly the leak
    /// `Rollback` exists to prevent and which
    /// `the_forward_renderer_builds_and_leaks_nothing` cannot see, because it
    /// only walks the happy path.
    ///
    /// Each arm below is a *different* refusal, so a check that stopped running
    /// would show up as one arm leaking rather than as all of them — and each
    /// names a fragment of the message it must be refused *with*, or an arm
    /// would pass on some other check's answer.
    /// **A description with no meshes is refused by name**, before anything
    /// is created, rather than reaching the mesh table's sizing with nothing
    /// to size it from.
    #[test]
    fn a_scene_with_no_meshes_is_refused_by_name() {
        let (recorder, device, queue) = open();
        let before = recorder.total_live_objects();
        let mut scene = scene::demo();
        scene.meshes.clear();
        let error =
            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
                .expect_err("a scene of no meshes must be refused");
        assert!(
            error.to_string().contains("at least one mesh"),
            "the refusal says what is missing: {error}"
        );
        assert_eq!(
            recorder.total_live_objects(),
            before,
            "the refusal created something"
        );
    }

    #[test]
    fn a_refused_description_creates_nothing_at_all() {
        /// One way of writing a description the renderer cannot build, and the
        /// words that say it was this refusal rather than another.
        type Break = (&'static str, fn(&mut SceneDesc<'static>), &'static str);

        let cases: [Break; 9] = [
            (
                "a row naming a layer the page has not got",
                |scene| {
                    scene.materials[DEMO_TEXTURED].base_color_texture = 7;
                },
                "material row 2 samples base-colour page layer 7",
            ),
            // And the same on the two kinds rung 3 added, because `check_scene`
            // reads a different column of the row for each: a check written per
            // kind is only worth what its arms cover, and a column nobody broke
            // here could be read out of the wrong material field for ever.
            // `demo` names no layer of either, so any index at all is past the
            // end.
            (
                "a row naming a packed-page layer the page has not got",
                |scene| {
                    scene.materials[DEMO_TEXTURED].metallic_roughness_occlusion_texture = 3;
                },
                "material row 2 samples metallic-roughness-occlusion page layer 3",
            ),
            (
                "a row naming an emissive layer the page has not got",
                |scene| {
                    scene.materials[DEMO_TEXTURED].emissive_texture = 3;
                },
                "material row 2 samples emissive page layer 3",
            ),
            // The one page refusal a caller can actually spell: `push_layer`
            // takes bytes it cannot measure against the extent.
            (
                "a page layer of the wrong length",
                |scene| {
                    scene.page = scene::PageDesc::empty();
                    scene
                        .page
                        .set_extent(PageKind::BaseColor, scene::PAGE_EXTENT);
                    scene.page.push_layer(PageKind::BaseColor, vec![0x00; 4]);
                    scene.materials[DEMO_TEXTURED].base_color_texture = scene::CHECKER_LAYER;
                },
                "base-colour page layer 0 carries 4 bytes",
            ),
            (
                "a DAG level with no vertices",
                |scene| {
                    let Geometry::Dag { levels, .. } = &mut scene.meshes[DEMO_DUNES].geometry
                    else {
                        panic!("the demo description's fourth mesh is the DAG");
                    };
                    levels.pop();
                },
                "vertex array(s) for a DAG of",
            ),
            // The four capacities, each of which is a pool a caller sized and
            // a description outgrew. Written as a capacity the description is
            // too large for rather than as a description too large for the
            // default, because that is the shape of the mistake: the numbers on
            // `Capacities` are the ones an application picks.
            (
                "more vertices than the pool holds",
                |scene| {
                    scene.capacities.vertices = 1;
                },
                "the vertex pool holds 1 and the description needs",
            ),
            (
                "more indices than the pool holds",
                |scene| {
                    scene.capacities.indices = 1;
                },
                "the index pool holds 1 and the description needs",
            ),
            (
                "more meshes than the table holds",
                |scene| {
                    scene.capacities.meshes = 1;
                },
                "the mesh table holds 1 and the description needs",
            ),
            (
                "more material rows than the table holds",
                |scene| {
                    scene.capacities.materials = 2;
                },
                "the material table holds 2 and the description needs 3",
            ),
        ];

        for (what, break_it, says) in cases {
            let (recorder, device, queue) = open();
            let before = recorder.total_live_objects();
            let mut scene = scene::demo();
            break_it(&mut scene);
            let error =
                ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
                    .expect_err(&format!("{what} must be refused"));
            assert!(
                matches!(error, HalError::InvalidDescriptor(_)),
                "{what} must be refused as an invalid descriptor, not as {error:?}"
            );
            assert!(
                error.to_string().contains(says),
                "{what} must be refused with a message saying so, and this one says {error}"
            );
            assert_eq!(
                recorder.total_live_objects(),
                before,
                "{what} was refused after something had been created, and the rollback \
                 is the only thing that could have released it"
            );
            recorder.assert_valid();
        }

        // **And the refusal that is not free**, which is the half of the
        // handover every arm above walks past: `check_scene` settles what the
        // whole description says, and what one mesh's *bytes* say is the pool's,
        // which only sees them one upload at a time. Vertex bytes that are not a
        // whole number of vertices reach `MeshPool::upload` — so the third of
        // the four meshes is refused with the pool created, two device-local
        // buffers in it and the first two meshes already staged into them.
        // `build_geometry` is what releases that, and it can only do so because
        // the pool is not the rollback's until it has returned.
        let (recorder, device, queue) = open();
        let before = recorder.total_live_objects();
        // So the count below is this build's and not `open`'s.
        recorder.clear();
        let mut scene = scene::demo();
        let Geometry::Flat { vertices, .. } = &mut scene.meshes[DEMO_OPEN_BOX].geometry else {
            panic!("the demo description's third mesh is flat");
        };
        vertices.to_mut().push(0);
        let error =
            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
                .expect_err("a mesh of part of a vertex must be refused");
        assert!(
            error.to_string().contains("is not a whole number of"),
            "the pool's own refusal reaches the caller with its numbers, and this \
             one says {error}"
        );
        assert!(
            recorder
                .events()
                .iter()
                .any(|event| matches!(event, crcbl_hal::null::Event::Created { .. })),
            "this arm is evidence about the rollback only if the refusal came after \
             something had been created"
        );
        assert_eq!(
            recorder.total_live_objects(),
            before,
            "a mesh refused part way through the list left the geometry pool behind, \
             which is exactly what `build_geometry` being self-cleaning is for"
        );
        recorder.assert_valid();
    }

    /// **The one capacity a description cannot be checked against, and the one
    /// an application is expected to handle while it runs.**
    ///
    /// Every other number on [`scene::Capacities`] sizes something the
    /// description fills once, so `check_scene` refuses an over-large one before
    /// a device object exists. Objects are placed at any point in a renderer's
    /// life, so the only honest answer for that one is the error
    /// [`ForwardRenderer::add_instance`] returns — and it returns
    /// [`InstancePoolError`] rather than a [`HalError`], so the capacity and
    /// what is in it survive to the caller that chose them.
    ///
    /// It also gives [`Capacities::instances`](scene::Capacities::instances) a
    /// value of its own rather than the default, which is what makes the pool
    /// fillable at all: a renderer that ignored the number the description
    /// carries and reserved the default would draw every frame in the tree
    /// identically and refuse nothing here.
    #[test]
    fn a_full_instance_pool_reaches_the_application_that_sized_it() {
        let (recorder, device, queue) = open();
        let mut scene = scene::demo();
        scene.capacities.instances = 2;
        let mut renderer =
            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
                .expect("a scene with room for two objects builds");
        let place = |renderer: &mut ForwardRenderer| {
            renderer.add_instance(&InstanceDesc {
                mesh: DEMO_CUBE,
                material: DEMO_UNTINTED,
                transform: Mat4::IDENTITY,
            })
        };
        place(&mut renderer).expect("the first of two");
        place(&mut renderer).expect("the second of two");
        let error = place(&mut renderer).expect_err("a third object has no slot to go in");
        assert!(
            matches!(
                error,
                InstancePoolError::PoolFull {
                    capacity: 2,
                    in_use: 2
                }
            ),
            "a full pool must reach the caller as a full pool, with the capacity it \
             chose; this arrived as {error}"
        );
        renderer.destroy(device.as_ref());
        recorder.assert_valid();
    }

    /// **One mesh and one material row is a scene, and it draws.**
    ///
    /// The floor is gone. `with_scene` used to refuse anything shorter than
    /// [`scene::demo`] — four meshes and three rows — because the five `set_*`
    /// demo wrappers named those entries by position, and the renderer's own
    /// `dunes_clusters` and `dunes_level_buckets` indexed the description at
    /// `DEMO_DUNES` besides. So an application's own description was not merely
    /// refused: with the check removed it would have panicked out of `build`.
    ///
    /// A frame is recorded rather than only a build, because that is where the
    /// positional indexing was: the bucket table, the cluster ranges and the
    /// draw-argument blocks are all one-per-description-mesh, and a renderer that
    /// still assumed four would come apart here rather than at `with_scene`.
    #[test]
    fn a_description_smaller_than_the_demo_is_a_scene() {
        use std::borrow::Cow;

        let scene = SceneDesc {
            meshes: vec![scene::MeshDesc {
                label: Cow::Borrowed("the only mesh"),
                geometry: Geometry::Flat {
                    vertices: Cow::Owned(crcbl_shaders::mesh::cube_vertex_bytes()),
                    uv_range: crcbl_shaders::mesh::demo_uv_range(),
                    indices: Cow::Owned(crcbl_shaders::mesh::cube_indices()),
                    clusters: crcbl_shaders::meshlet::cube_clusters(),
                    flags: 0,
                },
            }],
            materials: vec![mesh::GpuMaterial::UNTINTED],
            page: scene::PageDesc::empty(),
            probes: scene::ProbeGrid::default(),
            capacities: scene::Capacities::default(),
        };
        assert!(
            scene.meshes.len() < scene::demo().meshes.len()
                && scene.materials.len() < scene::demo().materials.len(),
            "this description must be smaller than the demo's in both, or it says nothing \
             about the floor"
        );

        let (recorder, device, queue) = open();
        let mut renderer =
            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
                .expect("one mesh and one row is a description the renderer can hold");
        assert_eq!(
            renderer.mesh_ids,
            [0],
            "the one description mesh takes the one table entry"
        );
        assert_eq!(
            renderer.bucket_constants.len(),
            1,
            "one bucket per description mesh, and there is one"
        );
        renderer
            .add_instance(&InstanceDesc {
                mesh: 0,
                material: 0,
                transform: Mat4::IDENTITY,
            })
            .expect("an empty pool has room for the only object");
        let recorded = frame(device.as_ref(), &mut renderer, queue);
        assert_eq!(
            commands_in_pass(&recorder, "forward")
                .into_iter()
                .filter(|command| matches!(
                    command,
                    crcbl_hal::null::Command::DrawIndexedIndirectCount(_)
                ))
                .count(),
            1,
            "a one-mesh scene records the one bucket's indirect call"
        );
        recorded.finish(device.as_ref(), renderer);
    }

    /// **A description that exactly fills what it reserved is built, not
    /// refused.**
    ///
    /// The other side of the capacity check, and the side nothing else in the
    /// tree can fail on: every other scene reserves far more than it holds, so a
    /// comparison written `>=` instead of `>` would pass the whole suite and
    /// refuse only the application that had sized its pools exactly right.
    ///
    /// The two capacities asserted here are the two a caller can size without
    /// re-deriving anything the renderer knows: one mesh table entry per
    /// [`Geometry::levels`], which is what that method is documented to answer,
    /// and one row per material. The four rows share one comparison, so they
    /// stand or fall together.
    #[test]
    fn a_description_that_exactly_fits_its_capacities_is_built() {
        let (recorder, device, queue) = open();
        let mut scene = scene::demo();
        scene.capacities.meshes = scene
            .meshes
            .iter()
            .map(|desc| u32::try_from(desc.geometry.levels()).expect("a few levels"))
            .sum();
        scene.capacities.materials =
            u32::try_from(scene.materials.len()).expect("a few material rows");
        let renderer =
            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
                .expect("a description that fits exactly is not too large for itself");
        renderer.destroy(device.as_ref());
        recorder.assert_valid();
    }

    /// **The level tables cover every mesh-table slot an instance can name**,
    /// not only the slots the description filled.
    ///
    /// `draw_gen.slang`'s `mesh_levels_of` reads `gen.mesh_levels_at + mesh *
    /// MESH_LEVELS_WORDS` with no bound, and says in its own doc comment that
    /// "every entry an instance can name is filled". An instance's mesh id is a
    /// bare table index, so a table sized to the description alone makes that
    /// read land in whatever the packer put next for any slot the description
    /// left empty.
    ///
    /// Growing the capacity by a known number of slots grows the tables buffer
    /// by exactly what those slots occupy: one `MeshLevels` record and one
    /// `level_meshes` word each. The arithmetic is the assertion, so nothing
    /// here is a number to keep in step by hand.
    #[test]
    fn the_level_tables_cover_every_slot_the_mesh_table_has() {
        const EXTRA: u32 = 4;

        let sized = |extra: u32| {
            let (recorder, device, queue) = open();
            let mut scene = scene::demo();
            scene.capacities.meshes += extra;
            let renderer =
                ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
                    .expect("a description with room to spare");
            let size = recorder
                .buffer_bytes(renderer.primary.draws.tables())
                .expect("the table buffer is live")
                .len();
            renderer.destroy(device.as_ref());
            recorder.assert_valid();
            size
        };

        let grown = sized(EXTRA) - sized(0);
        let want = EXTRA as usize * (crcbl_shaders::level_select::MESH_LEVELS_STRIDE + 4);
        assert_eq!(
            grown, want,
            "{EXTRA} more table slots must add {EXTRA} more selection records and {EXTRA} more \
             level words, and added {grown} bytes"
        );
    }

    /// The property the whole arrangement exists for: the pool's second
    /// resident is **not** at base vertex zero, so a frame containing it is a
    /// frame that fails if the base is lost between the pool and the shader.
    ///
    /// Read out of the **mesh table** rather than out of a renderer field,
    /// because the table is where a generated draw's index range comes from:
    /// `draw_gen.slang` builds every argument structure out of these bytes and
    /// nothing on the CPU is consulted.
    ///
    /// Without this the pass is back where it started — one mesh, base 0, and a
    /// base-vertex bug that no picture can show.
    #[test]
    fn the_second_mesh_lands_past_the_first() {
        let (recorder, device, queue) = open();
        let renderer =
            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
        let cube = mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_CUBE]);
        let pyramid = mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_PYRAMID]);

        assert_eq!(cube.base_vertex, 0, "the cube is first");
        assert_eq!(
            pyramid.base_vertex as usize,
            crcbl_shaders::mesh::CUBE_VERTEX_COUNT,
            "the pyramid must start where the cube ends, or the pools are not \
             suballocating at all"
        );
        assert_eq!(
            pyramid.index_count as usize,
            crcbl_shaders::mesh::PYRAMID_INDEX_COUNT,
            "and the entry carries the whole range, which is what the draw-argument \
             pass builds its arguments out of"
        );
        // And the two buckets read different constant blocks, or both would walk
        // the same run of instances.
        assert_ne!(
            renderer.bucket_constants[DEMO_CUBE], renderer.bucket_constants[DEMO_PYRAMID],
            "each bucket needs a block of its own"
        );
        renderer.destroy(device.as_ref());
    }

    /// **Each bucket's block points at that bucket's own run**, and the runs do
    /// not overlap.
    ///
    /// This is what replaced "the block names an instance": a draw covers
    /// however many instances survived culling, so what it can say for itself is
    /// only where to find its slice of the survivors. Two buckets naming one
    /// start word would draw each other's objects — with the *right* geometry,
    /// because the index range comes from the arguments, which is exactly the
    /// kind of plausible wrong picture a golden image struggles with.
    ///
    /// Read out of the bytes that reached the device rather than out of the
    /// renderer's own fields, because the failure is a block written wrong and
    /// the field would still be right.
    #[test]
    fn each_bucket_walks_its_own_run_of_survivors() {
        let (recorder, device, queue) = open();
        let renderer =
            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
        let blocks = recorder
            .buffer_bytes(renderer.draw_constants)
            .expect("the blocks are live");
        let start_word_at = |offset: u32| {
            let at = offset as usize;
            u32::from_le_bytes(blocks[at..at + 4].try_into().expect("four bytes"))
        };

        let draws = &renderer.primary.draws;
        let cube = start_word_at(renderer.bucket_constants[DEMO_CUBE]);
        let pyramid = start_word_at(renderer.bucket_constants[DEMO_PYRAMID]);
        // **Behind the survivors, their routes and the runs**, which share the
        // buffer: a block naming a word inside the runs would have the draw read
        // an instance index as its start, and one inside the survivor list or
        // the routes a start that is the same instances in a different order, or
        // a bucket number — both of which draw a plausible picture.
        assert_eq!(
            cube,
            draws.runs_at() + draws.visible_capacity(),
            "the first bucket's start word is the first word past one capacity of runs"
        );
        assert_eq!(
            pyramid,
            cube + (DEMO_PYRAMID - DEMO_CUBE) as u32,
            "and the second's is a word later — a start per bucket, not a run per bucket"
        );
        assert_eq!(
            cube,
            draws.bucket_start_word(DEMO_CUBE as u32),
            "the block carries what `DrawGen::bucket_start_word` says, because a reader \
             copying a run back uses that accessor and the shader uses this block"
        );
        renderer.destroy(device.as_ref());
    }

    /// **An instance's record carries its material's mode**, in the bits
    /// `draw_gen.slang` routes by.
    ///
    /// The host half of the per-bucket split, and the half no picture and no
    /// pipeline bind can show: the bucket table can be perfectly twinned and
    /// every partition bound to the right pipeline while every instance still
    /// answers mode zero, in which case the masked twins are empty, the cutout
    /// partition draws nothing, and a cutout casts a solid shadow. The record is
    /// where that is decided.
    ///
    /// Both directions, so the check is shown to discriminate: the opaque
    /// instance's mode bits have to be **clear**, or a writer that set them
    /// unconditionally would satisfy a one-sided assertion. And the two records
    /// are asserted to differ in `flags` and nothing else, so this is about the
    /// mode rather than about two unrelated instances.
    #[test]
    fn an_instances_record_carries_its_materials_mode() {
        let masked_scene = {
            let mut scene = crate::scene::demo();
            scene.materials[DEMO_TINTED].flags = crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK;
            scene
        };
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &masked_scene)
                .expect("the null backend accepts the demo description");
        let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
        let opaque = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
        let masked = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TINTED, at);

        let record = |handle: InstanceHandle| {
            renderer
                .instances
                .get(handle)
                .expect("the instance was inserted and is live")
        };
        let opaque = record(opaque);
        let masked = record(masked);
        assert_eq!(
            opaque.material_mode(),
            0,
            "an opaque material's instance carries no mode bits, or every instance in the tree \
             routes to a cutout bucket"
        );
        assert_eq!(
            masked.material_mode(),
            crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK,
            "and a masked material's instance carries its mode, or it scatters into the opaque \
             twin and the depth passes write its full silhouette"
        );
        assert_eq!(
            mesh::GpuInstance {
                flags: opaque.flags,
                material: opaque.material,
                ..masked
            },
            opaque,
            "the two records differ in the mode bits and the material id and in nothing else"
        );

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

    /// **A scene whose materials are all opaque gets exactly the bucket table
    /// it had before material modes existed** — one bucket per (mesh, level),
    /// and no twin.
    ///
    /// The zero-cost half of the per-bucket split, and the one a null device can
    /// state exactly. A bucket is not free: every pass records one indirect call
    /// per bucket per view, and every generator holds a run start per bucket. So
    /// a table that twinned unconditionally would double the recorded draws of
    /// every demo and every golden in this tree, none of which mask anything.
    ///
    /// The oracle is [`level_buckets`](ForwardRenderer::level_buckets), which is
    /// built from a mesh's own level count rather than from the table's length —
    /// so a build that emitted a twin per mesh has more buckets than levels and
    /// this says so. And the twinned scenes below are asserted to be exactly as
    /// many times as long as they hold modes, or the comparison would pass on a
    /// renderer that had stopped twinning at all.
    ///
    /// # A twin per mode the scene **holds**, not per mode that exists
    ///
    /// [`DEPTH_MODES`] has four entries and a bucket is not free — every pass
    /// records one indirect call per bucket — so the rule that matters is which
    /// values the description's own materials carry. Two rows of two modes are
    /// two twins whichever two they are, and the pair below says so both ways:
    /// three modes across three rows is three, and three rows collapsed onto two
    /// *values* is two even though between them they set both mode bits.
    #[test]
    fn an_all_opaque_scene_keeps_one_bucket_per_mesh_level() {
        use crcbl_shaders::mesh::GpuMaterial;

        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        // The uniform-cut path, where a DAG is one bucket per level. The mesh
        // path folds a DAG into one bucket and reports no level buckets at all,
        // which would leave the oracle below empty.
        assert!(
            !renderer.emit.is_mesh(),
            "this preset built a mesh-shader path, whose level buckets are empty"
        );
        let levels: usize = (0..crate::scene::demo().meshes.len())
            .map(|mesh| renderer.level_buckets(mesh).len())
            .sum();
        assert!(levels > 0, "the demo has meshes, so it has levels");
        assert_eq!(
            renderer.bucket_constants.len(),
            levels,
            "an all-opaque scene's bucket table is one bucket per (mesh, level) and no mode \
             twin: {levels} level(s) against {} bucket(s)",
            renderer.bucket_constants.len()
        );
        assert_eq!(
            renderer.bucket_modes,
            vec![0; levels],
            "and every one of them draws the OPAQUE mode"
        );
        let opaque_meshes = renderer.draw_tables.bucket_meshes.clone();
        let opaque_level_buckets: Vec<Vec<u32>> = (0..crate::scene::demo().meshes.len())
            .map(|mesh| renderer.level_buckets(mesh).to_vec())
            .collect();
        renderer.destroy(device);
        recorder.assert_valid();

        // Every arrangement worth stating, as the modes its material rows carry
        // and the number of twins that has to produce. The demo has three rows;
        // a fourth is appended where four distinct modes are wanted, which
        // nothing instances and which therefore changes nothing but the mode
        // set.
        for (rows, modes, what) in [
            (
                vec![GpuMaterial::ALPHA_MODE_MASK, 0, 0],
                2,
                "one masked row beside two opaque ones",
            ),
            (
                vec![GpuMaterial::DOUBLE_SIDED, 0, 0],
                2,
                "one double-sided row beside two opaque ones",
            ),
            (
                vec![GpuMaterial::ALPHA_MODE_MASK, GpuMaterial::DOUBLE_SIDED, 0],
                3,
                "a masked row, a double-sided one and an opaque one",
            ),
            (
                vec![
                    GpuMaterial::ALPHA_MODE_MASK,
                    GpuMaterial::DOUBLE_SIDED,
                    GpuMaterial::ALPHA_MODE_MASK,
                ],
                2,
                "three rows carrying two mode values between them — both mode bits are set \
                 somewhere and neither row is opaque, so a rule counting bits rather than \
                 values would say three",
            ),
            (
                vec![
                    0,
                    GpuMaterial::ALPHA_MODE_MASK,
                    GpuMaterial::DOUBLE_SIDED,
                    GpuMaterial::MODE_MASK,
                ],
                4,
                "one row of each mode, which is the only arrangement that pays for four",
            ),
        ] {
            let scene = {
                let mut scene = crate::scene::demo();
                while scene.materials.len() < rows.len() {
                    scene.materials.push(GpuMaterial::UNTINTED);
                }
                for (row, flags) in scene.materials.iter_mut().zip(&rows) {
                    row.flags = *flags;
                }
                scene
            };
            let (recorder, device, queue) = open();
            let device = device.as_ref();
            let twinned =
                ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &scene)
                    .expect("the null backend accepts the demo description");
            assert_eq!(
                twinned.bucket_constants.len(),
                modes * levels,
                "{what}: {modes} mode(s) over {levels} level(s) is {} bucket(s), and the table \
                 has {}",
                modes * levels,
                twinned.bucket_constants.len()
            );
            // The modes present, as a set — which is the claim, since the order
            // is `DEPTH_MODES`' and the count above already pins the length.
            let held: std::collections::BTreeSet<u32> =
                twinned.bucket_modes.iter().copied().collect();
            let want: std::collections::BTreeSet<u32> = rows.iter().copied().collect();
            assert_eq!(
                held, want,
                "{what}: the table twins the modes its materials carry and no others"
            );
            for mode in &held {
                assert_eq!(
                    twinned
                        .bucket_modes
                        .iter()
                        .filter(|held| *held == mode)
                        .count(),
                    levels,
                    "{what}: every mode present gets every mesh's levels once"
                );
            }
            // **Mode-major**: each held mode is one contiguous run of the
            // all-opaque table, in `DEPTH_MODES` order, so a pipeline's
            // partition is one range of buckets.
            let held_in_order: Vec<u32> = DEPTH_MODES
                .into_iter()
                .filter(|mode| held.contains(mode))
                .collect();
            assert_eq!(
                twinned.bucket_modes,
                held_in_order
                    .iter()
                    .flat_map(|mode| std::iter::repeat_n(*mode, levels))
                    .collect::<Vec<_>>(),
                "{what}: every bucket of one mode is contiguous, modes in DEPTH_MODES order"
            );
            assert_eq!(
                twinned.draw_tables.bucket_meshes,
                opaque_meshes.repeat(held_in_order.len()),
                "{what}: each mode's run is the all-opaque table, mesh by mesh"
            );
            for (mesh, opaque) in opaque_level_buckets.iter().enumerate() {
                assert_eq!(
                    twinned.level_buckets(mesh),
                    opaque.as_slice(),
                    "{what}: mesh {mesh}'s level buckets are the first mode's run"
                );
            }
            // And the `(mesh, mode) → bucket` lookup the scatter routes through
            // sends every key to its mode's run, at the mesh's own offset.
            let lookup = crcbl_shaders::draw_gen::bucket_lookup(
                &twinned.draw_tables.bucket_meshes,
                &twinned.bucket_modes,
            )
            .expect("a small lookup");
            for (slot, mode) in held_in_order.iter().enumerate() {
                for (offset, mesh) in opaque_meshes.iter().enumerate() {
                    let key = 1 + (*mesh * crcbl_shaders::draw_gen::MATERIAL_MODES + *mode);
                    assert_eq!(
                        lookup[key as usize] as usize,
                        slot * levels + offset,
                        "{what}: mesh {mesh} in mode {mode}"
                    );
                }
            }
            twinned.destroy(device);
            recorder.assert_valid();
        }
    }

    /// **The two pyramids differ in exactly one field, and it is the material
    /// id — which names a row holding a different colour and a different
    /// roughness.**
    ///
    /// The whole of what §3.2's table buys, stated as the two things that have
    /// to be true at once. Placed at the *same* transform, so "differ only in
    /// material" is literal rather than nearly: same mesh id, same matrix, same
    /// flags, and a `GpuInstance` comparison that would fail on any other
    /// field. And the ids they carry name rows the device actually holds —
    /// asserted on the bytes in the buffer, because a table the renderer agrees
    /// with itself about is not a table a shader can read.
    ///
    /// The two rows are asserted to differ, or the pair would be evidence of
    /// nothing: two instances naming two rows of the same colour draw the same
    /// picture whether or not either id was ever used.
    #[test]
    fn the_two_pyramids_differ_only_in_their_material() {
        let (recorder, device, queue) = open();
        let mut renderer =
            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
        let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
        let plain_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
        let tinted_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TINTED, at);

        let instance = |handle: InstanceHandle| {
            renderer
                .instances
                .get(handle)
                .expect("the instance was inserted and is live")
        };
        let plain = instance(plain_handle);
        let tinted = instance(tinted_handle);
        assert_ne!(
            plain.material, tinted.material,
            "the two pyramids must not share a material row"
        );
        assert_eq!(
            mesh::GpuInstance {
                material: tinted.material,
                ..plain
            },
            tinted,
            "the two instances must differ in the material id and in nothing else"
        );

        let bytes = recorder
            .buffer_bytes(renderer.materials.buffer())
            .expect("the table is live");
        let row = |index: u32| {
            let at = index as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
            mesh::GpuMaterial::from_bytes(
                bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
                    .try_into()
                    .expect("one row"),
            )
        };
        assert_eq!(
            row(plain.material),
            mesh::GpuMaterial::UNTINTED,
            "the plain pyramid's row must be the factor that changes nothing"
        );
        assert_eq!(
            row(tinted.material),
            mesh::GpuMaterial {
                base_color: scene::PYRAMID_TINT,
                roughness: scene::PYRAMID_ROUGHNESS,
                ..mesh::GpuMaterial::UNTINTED
            },
            "the tinted pyramid's row must be the tint and the tighter lobe"
        );
        // The shading half of that row, on its own: a roughness equal to the
        // neutral row's would leave `crcbl`'s render e2e comparing one lobe
        // against itself, and that test would go green on a shader that had
        // never read the column.
        assert_ne!(
            row(plain.material).roughness,
            row(tinted.material).roughness,
            "the two rows must differ in roughness, or the highlight the render e2e measures \
             is not attributable to the material"
        );
        assert_ne!(
            row(plain.material),
            row(tinted.material),
            "two rows holding the same colour would make the pair prove nothing"
        );
        // And the tint is the *only* thing that differs between them: a row that
        // also changed its page layer would make this pair evidence about two
        // columns at once, which is what the third pyramid exists to avoid.
        assert_eq!(
            row(plain.material).base_color_texture,
            row(tinted.material).base_color_texture,
            "the factor pair must sample the same page layer"
        );

        // And the second pyramid leaves the frame the way the first does: the
        // instance is removed, not a draw skipped.
        renderer.remove_instance(tinted_handle);
        assert!(
            renderer.instances.get(tinted_handle).is_none(),
            "the instance must be given back, or an object nobody asked for stays in the scene"
        );

        renderer.destroy(device.as_ref());
    }

    /// **The same claim one column along: the plain and textured pyramids
    /// differ in exactly one field, and the rows it names differ in exactly one
    /// column — the base-colour page layer.**
    ///
    /// [`the_two_pyramids_differ_only_in_their_material`]'s argument for §3.2's
    /// *texture indices* rather than its *factors*. The factors of the two rows
    /// are asserted **equal** here, which is the half that makes the pair
    /// evidence about the texture at all: a textured row that also carried a
    /// tint would draw a different picture for a reason the frame could not
    /// distinguish from the tinted pyramid's.
    ///
    /// The layer numbers are asserted against the page the renderer actually
    /// uploaded, so a row naming a layer that does not exist is caught here
    /// rather than as an out-of-range sample on a device.
    #[test]
    fn the_textured_pyramid_differs_only_in_its_page_layer() {
        let (recorder, device, queue) = open();
        let mut renderer =
            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
        let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
        let plain_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
        let textured_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TEXTURED, at);

        let instance = |handle: InstanceHandle| {
            renderer
                .instances
                .get(handle)
                .expect("the instance was inserted and is live")
        };
        let plain = instance(plain_handle);
        let textured = instance(textured_handle);
        assert_ne!(
            plain.material, textured.material,
            "the two pyramids must not share a material row"
        );
        assert_eq!(
            mesh::GpuInstance {
                material: textured.material,
                ..plain
            },
            textured,
            "the two instances must differ in the material id and in nothing else"
        );

        let bytes = recorder
            .buffer_bytes(renderer.materials.buffer())
            .expect("the table is live");
        let row = |index: u32| {
            let at = index as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
            mesh::GpuMaterial::from_bytes(
                bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
                    .try_into()
                    .expect("one row"),
            )
        };
        assert_eq!(
            row(plain.material).base_color,
            row(textured.material).base_color,
            "the texture pair must share a factor, or the pair is evidence about both columns"
        );
        assert_eq!(
            row(plain.material).base_color_texture,
            mesh::GpuMaterial::NO_PAGE
        );
        assert_eq!(
            row(textured.material).base_color_texture,
            scene::CHECKER_LAYER
        );
        assert_ne!(
            row(plain.material),
            row(textured.material),
            "two rows naming the same layer would make the pair prove nothing"
        );
        // The layer that number names is a layer the page has, and it is not
        // one flat colour — a checker of one repeated texel would pass every
        // assertion above and draw the picture the untextured row draws.
        let page = scene::demo().page;
        let layers = page.layers(PageKind::BaseColor);
        assert!(
            (scene::CHECKER_LAYER as usize) < layers.len(),
            "layer {} is past the end of a {}-layer page, which is an out-of-range sample \
             nothing below the seam would report",
            scene::CHECKER_LAYER,
            layers.len()
        );
        let checker = &layers[scene::CHECKER_LAYER as usize];
        assert!(
            checker
                .as_chunks::<4>()
                .0
                .iter()
                .any(|texel| texel != &checker[..4]),
            "a flat checker layer would shade the textured row exactly as the untextured \
             one shades, and the pair would prove nothing"
        );

        renderer.remove_instance(textured_handle);
        assert!(
            renderer.instances.get(textured_handle).is_none(),
            "the instance must be given back, or an object nobody asked for stays in the scene"
        );

        renderer.destroy(device.as_ref());
    }

    /// **A [`PageKind`] nothing names costs one texel**, not `extent² × 4` bytes
    /// and a third again for its chain.
    ///
    /// This is what row (d) bought, and it is the half of it no picture can
    /// show: the frame a scene with no normal map draws is byte-identical either
    /// way, because `mesh.slang` returns before it fetches. What changes is the
    /// image the renderer created, and the copies into it are where that is
    /// visible. `crcbl/tests/mesh_e2e/normal_map.rs`'s
    /// `no_normal_map_returns_the_surface_normal_exactly_and_the_neutral_texel_does_not`
    /// is the device-side half saying the frame did not move.
    ///
    /// [`scene::demo`] is the scene: every one of its rows carries
    /// [`NO_PAGE`](mesh::GpuMaterial::NO_PAGE) in the normal column, and it is
    /// the description every golden in this tree is a variation of.
    ///
    /// # Sabotage
    ///
    /// The empty-kind arm of the upload loop uploading a full 64² neutral layer
    /// and its chain instead of the placeholder — the shape this replaced. Red
    /// on 2026-09-06 with `"a description with no normal map must upload the
    /// one-texel placeholder, and this copied 7 level(s) at [Extent3d { width:
    /// 64, height: 64, depth_or_layers: 1 }, … ] — a burned neutral layer costs
    /// extent² × 4 bytes and a third again for its chain, on every scene in the
    /// tree"`.
    #[test]
    fn a_page_kind_nothing_names_costs_one_texel() {
        use crcbl_hal::null::Command;

        let scene = scene::demo();
        assert!(
            scene
                .materials
                .iter()
                .all(|row| row.normal_texture == mesh::GpuMaterial::NO_PAGE),
            "a row naming a normal layer would make the description one that *does* name \
             the page, and this test would be about the other case"
        );
        assert!(
            scene.page.layers(PageKind::Normal).is_empty()
                && scene.page.extent(PageKind::BaseColor) > 1,
            "the description must name no normal layer while naming base-colour ones, or \
             a placeholder-sized copy says nothing about which page it landed in"
        );

        let (recorder, device, queue) = open();
        let renderer =
            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
                .expect("a description naming no normal page is one this can make resident");

        let copies: Vec<crcbl_hal::BufferImageCopy> = recorder
            .commands()
            .into_iter()
            .filter_map(|command| match command {
                Command::CopyBufferToImage(copy) if copy.image == renderer.normal_page.image => {
                    Some(copy)
                }
                _ => None,
            })
            .collect();
        let extents: Vec<crcbl_hal::Extent3d> =
            copies.iter().map(|copy| copy.image_extent).collect();
        assert_eq!(
            extents,
            vec![crcbl_hal::Extent3d::d2(1, 1)],
            "a description with no normal map must upload the one-texel placeholder, and \
             this copied {} level(s) at {extents:?} — a burned neutral layer costs \
             extent² × 4 bytes and a third again for its chain, on every scene in the tree",
            copies.len()
        );

        // The placeholder is one layer, and the graph declaration says so: a
        // caller importing this page to write a layer of its own would get
        // `ImportDeclarationConflict` against an extent that was not 1×1.
        assert_eq!(
            renderer.normal_page_import().extent,
            (1, 1),
            "the declaration names the placeholder's extent, not the base-colour page's"
        );
        renderer.destroy(device.as_ref());
    }

    /// **A page and a material table that are the caller's own, not
    /// [`scene::demo`]'s**: a different extent per kind, more layers than the
    /// demo page holds, a normal page the demo does not have at all, and rows
    /// past the three the demo writes.
    ///
    /// Every other scene in the tree is `scene::demo()` — with a mesh appended,
    /// at most — so until this nothing had put an app-supplied *layer* or an
    /// app-supplied *row* through [`ForwardRenderer::with_scene`] at all. A
    /// build that uploaded the demo's two layers and stopped, or that inserted
    /// its three rows and stopped, would leave every golden byte-identical and
    /// pass every other assertion in this module: the demo scene cannot tell a
    /// table filled from the description from one filled up to the description's
    /// third row.
    ///
    /// Read off the recorder rather than off the description, because the
    /// description is the input. The copies are what reached the image and the
    /// table buffer is what the shader indexes, and neither is a restatement of
    /// what was handed in.
    #[test]
    fn an_app_page_and_table_reach_the_device_whole() {
        use crcbl_hal::null::Command;

        /// Not [`scene::PAGE_EXTENT`], so an extent that had been compiled in
        /// rather than read off the page shows up as a copy of the wrong size.
        const APP_EXTENT: u32 = 4;

        /// **Not [`APP_EXTENT`]**, which is the whole of what row (d)'s per-kind
        /// extent bought: a renderer that still sized the normal page from the
        /// base-colour page's number would copy this layer at 4² and the copy
        /// list below would say so.
        const APP_NORMAL_EXTENT: u32 = 2;
        let layer_bytes = APP_EXTENT as usize * APP_EXTENT as usize * 4;

        // Three base-colour layers, each flat and each a value of its own: a
        // build that uploaded one layer twice, or that stopped short, is a
        // different sequence of copies. Then one normal layer at the other
        // extent, which the demo scene has no page for at all.
        let mut page = scene::PageDesc::empty();
        page.set_extent(PageKind::BaseColor, APP_EXTENT);
        page.set_extent(PageKind::Normal, APP_NORMAL_EXTENT);
        let app_layers: Vec<u32> = [0x11_u8, 0x22, 0x33]
            .into_iter()
            .map(|value| page.push_layer(PageKind::BaseColor, vec![value; layer_bytes]))
            .collect();
        let app_normal = page.push_layer(
            PageKind::Normal,
            scene::PageDesc::NEUTRAL_NORMAL
                .repeat(APP_NORMAL_EXTENT as usize * APP_NORMAL_EXTENT as usize),
        );

        let mut scene = scene::demo();
        scene.page = page;
        // One row per appended layer, and each with a factor of its own as well,
        // so a row that landed at another row's id is not a row that happens to
        // look like it. The last of them names the normal layer too, so the
        // table carries a row through both pages.
        for (nth, &layer) in app_layers.iter().enumerate() {
            let shade = 0.25 * (nth as f32 + 1.0);
            let last = nth + 1 == app_layers.len();
            scene.materials.push(mesh::GpuMaterial {
                base_color: [shade, shade, shade, 1.0],
                base_color_texture: layer,
                normal_texture: if last {
                    app_normal
                } else {
                    mesh::GpuMaterial::NO_PAGE
                },
                ..mesh::GpuMaterial::UNTINTED
            });
        }
        assert!(
            scene.materials.len() > scene::demo().materials.len()
                && scene.page.layers(PageKind::BaseColor).len()
                    > scene::demo().page.layers(PageKind::BaseColor).len(),
            "the description under test must exceed the demo's in both, or this is a \
             demo test wearing another name"
        );
        assert_eq!(
            scene::demo().page.extent(PageKind::Normal),
            0,
            "the demo scene must name no normal page, or the normal copies below are \
             evidence about the demo's page rather than the caller's"
        );

        let (recorder, device, queue) = open();
        let mut renderer =
            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
                .expect("a page and a table of the caller's own are ones this can make resident");

        // The page, layer by layer. Filtered by image because the build uploads
        // the ambient-occlusion placeholder through the same path.
        let copies: Vec<crcbl_hal::BufferImageCopy> = recorder
            .commands()
            .into_iter()
            .filter_map(|command| match command {
                Command::CopyBufferToImage(copy)
                    if copy.image == renderer.base_color_page.image =>
                {
                    Some(copy)
                }
                _ => None,
            })
            .collect();
        // Every layer goes up with its chain — three levels for this extent —
        // so the copies are layer-major, level-minor, each at its level's own
        // extent.
        let levels = crcbl_hal::Extent3d::d2(APP_EXTENT, APP_EXTENT)
            .full_mip_levels(crcbl_hal::ImageType::D2);
        assert_eq!(levels, 3, "a 4² page has three levels down to one texel");
        let layer_count = u32::try_from(scene.page.layers(PageKind::BaseColor).len())
            .expect("a page of a few layers");
        assert_eq!(
            copies
                .iter()
                .map(|copy| (
                    copy.image_subresource.base_layer,
                    copy.image_subresource.mip
                ))
                .collect::<Vec<(u32, u32)>>(),
            (0..layer_count)
                .flat_map(|layer| (0..levels).map(move |level| (layer, level)))
                .collect::<Vec<(u32, u32)>>(),
            "every level of every layer the description carries must be copied into the page, \
             in order"
        );
        assert!(
            copies.iter().all(|copy| {
                let side = crate::mip::level_extent(APP_EXTENT, copy.image_subresource.mip);
                copy.image_extent == crcbl_hal::Extent3d::d2(side, side)
            }),
            "the page is the extent the caller wrote, not the demo's, halved per level: \
             {copies:?}"
        );

        // The normal page, at **its own** extent. One layer, two levels for a
        // 2² image, and every copy sized from `APP_NORMAL_EXTENT` — a renderer
        // that carried one extent for both kinds would put this layer up at 4².
        let normal_copies: Vec<crcbl_hal::BufferImageCopy> = recorder
            .commands()
            .into_iter()
            .filter_map(|command| match command {
                Command::CopyBufferToImage(copy) if copy.image == renderer.normal_page.image => {
                    Some(copy)
                }
                _ => None,
            })
            .collect();
        let normal_levels = crcbl_hal::Extent3d::d2(APP_NORMAL_EXTENT, APP_NORMAL_EXTENT)
            .full_mip_levels(crcbl_hal::ImageType::D2);
        assert_eq!(
            normal_copies
                .iter()
                .map(|copy| (
                    copy.image_subresource.base_layer,
                    copy.image_subresource.mip,
                    copy.image_extent
                ))
                .collect::<Vec<(u32, u32, crcbl_hal::Extent3d)>>(),
            (0..normal_levels)
                .map(|level| {
                    let side = crate::mip::level_extent(APP_NORMAL_EXTENT, level);
                    (0, level, crcbl_hal::Extent3d::d2(side, side))
                })
                .collect::<Vec<(u32, u32, crcbl_hal::Extent3d)>>(),
            "the normal page is the extent the caller wrote for *that* kind, halved per \
             level: {normal_copies:?}"
        );
        assert_eq!(
            renderer.normal_page_import().extent,
            (APP_NORMAL_EXTENT, APP_NORMAL_EXTENT),
            "the graph declaration names the normal page's own extent, or a caller \
             importing it to write a layer gets ImportDeclarationConflict"
        );
        assert_eq!(
            renderer.base_color_page_import().extent,
            (APP_EXTENT, APP_EXTENT),
            "and the base-colour declaration names its own, which is a different number"
        );

        // The table, row by row, out of the buffer `mesh.slang` indexes.
        let bytes = recorder
            .buffer_bytes(renderer.materials.buffer())
            .expect("the table is live");
        let row = |id: u32| {
            let at = id as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
            mesh::GpuMaterial::from_bytes(
                bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
                    .try_into()
                    .expect("one row"),
            )
        };
        assert_eq!(
            renderer.material_ids.len(),
            scene.materials.len(),
            "one id per description row, whatever the count"
        );
        for (index, wrote) in scene.materials.iter().enumerate() {
            assert_eq!(
                &row(renderer.material_ids[index]),
                wrote,
                "description row {index} must be the row its id names"
            );
        }

        // And a caller can place an object through a row only its own
        // description has, which is the whole point of the rows being the
        // caller's.
        let last = scene.materials.len() - 1;
        let handle = renderer
            .add_instance(&InstanceDesc {
                mesh: DEMO_CUBE,
                material: last,
                transform: Mat4::IDENTITY,
            })
            .expect("an empty pool of thousands has room for one object");
        assert_eq!(
            renderer
                .instances
                .get(handle)
                .expect("a just-added instance is live")
                .material,
            renderer.material_ids[last],
            "an InstanceDesc's material index resolves through the description, not \
             through a table id the caller cannot know"
        );

        renderer.destroy(device.as_ref());
        recorder.assert_valid();
    }

    /// **The frame records two compute dispatches and exactly one indirect draw
    /// per bucket — whatever is in the scene.**
    ///
    /// The property topic 03 opens with, checked on the recorded command stream:
    /// adding the pyramid adds an instance and changes no command. A pass that
    /// had kept a draw per object would record one command here and two there,
    /// which is what this used to assert and what the indirect path replaced.
    ///
    /// It also pins the arguments each call names: bucket `n` reads the `n`-th
    /// argument structure and the `n`-th count, at the stride every API fixed.
    /// Two calls pointing at one structure is a frame that draws one object
    /// twice.
    #[test]
    fn the_frame_records_one_indirect_call_per_bucket_whatever_the_scene_holds() {
        use crcbl_hal::null::Command;

        for pyramid in [None, Some(Mat4::from_translation(Vec3::X))] {
            let (recorder, device, queue) = open();
            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
                .expect("built");
            // The cube in both scenes, so the difference between them is the
            // pyramid alone. It also keeps both frames non-empty, and an empty
            // one would be a weaker comparison than this claims: `cull`'s
            // dispatch covers no workgroups when the pool is empty, and the pass
            // records nothing rather than a dispatch of zero — see
            // [`DrawGen::add_passes`].
            place_cube(&mut renderer, Mat4::IDENTITY);
            if let Some(at) = pyramid {
                place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
            }
            let frame = frame(device.as_ref(), &mut renderer, queue);

            let stride = crcbl_shaders::draw_gen::DRAW_ARGS_SIZE as u32;
            let expected: Vec<(u32, u64, u64)> = (0..renderer.bucket_constants.len())
                .map(|bucket| {
                    (
                        renderer.bucket_constants[bucket],
                        bucket as u64 * u64::from(stride),
                        bucket as u64 * 4,
                    )
                })
                .collect();

            // The dynamic offset last bound before each draw, paired with the
            // offsets that draw read its arguments and its count from.
            let mut offset = None;
            let mut seen: Vec<(u32, u64, u64)> = Vec::new();
            let mut dispatches = 0;
            for command in recorder.commands() {
                if matches!(command, Command::Dispatch { .. }) {
                    dispatches += 1;
                }
            }
            for command in commands_in_pass(&recorder, "forward") {
                match command {
                    Command::BindGroup {
                        slot: 0,
                        dynamic_offsets,
                        ..
                    } => offset = dynamic_offsets.first().copied(),
                    Command::DrawIndexedIndirectCount(draw) => {
                        assert_eq!(draw.stride, stride, "sizeof(VkDrawIndexedIndirectCommand)");
                        assert_eq!(
                            draw.max_draw_count, 1,
                            "one argument structure per bucket, so one is the ceiling"
                        );
                        seen.push((
                            offset.expect("a draw is preceded by its constant block"),
                            draw.args_offset,
                            draw.count_offset,
                        ));
                    }
                    Command::DrawIndexed { .. } => {
                        panic!("the forward pass must not record a CPU-counted draw any more")
                    }
                    _ => {}
                }
            }
            assert_eq!(
                dispatches,
                DrawGen::DISPATCHES as usize * (1 + shadow::CASCADES) + 1 + RESOLVE_DISPATCHES,
                "the clearing pass, the cull pass and the draw-argument pass's three, in \
                 front of the draws — once for the camera and once per shadow cascade — plus \
                 topic 18's one clustering dispatch, which is the camera's alone because a \
                 cascade shades nothing, plus the resolve's own"
            );
            assert_eq!(
                seen, expected,
                "with pyramid = {pyramid:?}, the pass must record one indirect call per \
                 bucket, each pointing at its own arguments, its own count and its own \
                 block"
            );

            frame.finish(device.as_ref(), renderer);
        }
    }

    /// **The two `GeometryPath` arms record different calls and nothing else
    /// differs.**
    ///
    /// A device with a GPU-side count takes it from GPU memory; one without —
    /// Metal, whose API has multi-draw-indirect and no count buffer — reads each
    /// bucket's one argument structure unconditionally. Same buckets, same
    /// arguments, same block: the tail is the only thing that moves, which is
    /// what topic 03 means by "the lesser path is
    /// a constraint on data layout, not a separate renderer".
    ///
    /// Both presets are run here rather than only the one this machine has,
    /// because the arm a device never selects is the arm nothing tests.
    #[test]
    fn each_geometry_path_records_its_own_indirect_call() {
        use crcbl_hal::null::Command;

        for (preset, path, counted) in [
            (
                NullInstance::gpu_driven(),
                GeometryPath::IndirectCount,
                true,
            ),
            (
                NullInstance::portable(),
                GeometryPath::IndirectPerBatch,
                false,
            ),
        ] {
            let recorder = Recorder::new();
            let instance = preset.with_recorder(recorder.clone());
            let adapter = instance.adapters().remove(0);
            assert_eq!(
                instance
                    .adapter_caps(adapter.id)
                    .expect("the null backend describes its adapter")
                    .geometry_path(),
                path,
                "the preset must select the path this arm is about"
            );
            // `DeviceDesc::for_adapter` requires a timeline semaphore, which the
            // portable preset does not have; the forward pass does not need one
            // either, so this asks for what it uses. The optional set matters:
            // a device is opened with the features it *asked* for, and the path
            // is derived from those rather than from the adapter's.
            let device = instance
                .create_device(&DeviceDesc {
                    label: None,
                    adapter: adapter.id,
                    required_features: Features::COMPUTE,
                    optional_features: Features::GPU_DRIVEN,
                    compatible_surface: None,
                })
                .expect("the null backend always opens");
            assert_eq!(
                device.caps().geometry_path(),
                path,
                "and the opened device still selects it"
            );
            let queue = device.queue(QueueKind::Graphics).expect("always present");
            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
                .expect("built");
            let frame = frame(device.as_ref(), &mut renderer, queue);

            let mut counted_calls = 0;
            let mut per_batch_calls = 0;
            for command in commands_in_pass(&recorder, "forward") {
                match command {
                    Command::DrawIndexedIndirectCount(_) => counted_calls += 1,
                    Command::DrawIndexedIndirect(draw) => {
                        assert_eq!(
                            draw.draw_count, 1,
                            "one argument structure per bucket, read unconditionally"
                        );
                        per_batch_calls += 1;
                    }
                    _ => {}
                }
            }
            let buckets = renderer.bucket_constants.len();
            let (expected_counted, expected_per_batch) =
                if counted { (buckets, 0) } else { (0, buckets) };
            assert_eq!(
                (counted_calls, per_batch_calls),
                (expected_counted, expected_per_batch),
                "{path:?} must record one call of its own kind per bucket and none of the other"
            );

            frame.finish(device.as_ref(), renderer);
        }
    }

    /// Serialises the two checks that move
    /// [`r_debug_draw`](crate::debug_draw::r_debug_draw), and puts it back
    /// afterwards.
    ///
    /// A [`ConVar`](crcbl_console::ConVar) is process-global by design, and
    /// `cargo test` runs a crate's tests as threads of *one* process: two checks
    /// that move the switch are then two writers to one cell, which shows up as
    /// a flake rather than as a failure anybody can read.
    /// `crcbl::debug_view::for_test` is the same shape one crate up and there
    /// for the same reason; this one is smaller because nothing outside these
    /// two tests ever writes the cell.
    fn debug_draw_switch() -> DebugDrawSwitch {
        let guard = DEBUG_DRAW_SWITCH
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let switch = DebugDrawSwitch { _guard: guard };
        switch.set(false);
        switch
    }

    /// What [`debug_draw_switch`] hands back: the switch is this thread's until
    /// it drops, and it goes back off when it does.
    struct DebugDrawSwitch {
        _guard: std::sync::MutexGuard<'static, ()>,
    }

    impl DebugDrawSwitch {
        /// Moves the switch.
        fn set(&self, on: bool) {
            crate::debug_draw::r_debug_draw
                .set(&crcbl_console::Value::Bool(on))
                .expect("`r_debug_draw` is a writable bool");
        }
    }

    impl Drop for DebugDrawSwitch {
        fn drop(&mut self) {
            // Off at both ends, so a check that panicked mid-way does not hand
            // the next holder a switched-on layer.
            self.set(false);
        }
    }

    /// [`debug_draw_switch`]'s lock.
    ///
    /// **First of the two**, when a test takes this and [`ssao_blur_switch`]
    /// both — see that function for what the opposite order cost.
    static DEBUG_DRAW_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// Takes `r_ssao_blur_passes` for this thread and puts it back at its
    /// default when the guard drops.
    ///
    /// [`debug_draw_switch`]'s shape exactly, for its reason: a plain
    /// `cargo test` run shares one process between tests, and a variable this
    /// one left moved is a frame the next test did not ask for.
    ///
    /// **Every test whose assertion depends on the shape of a frame takes this,
    /// not only the one that moves the count.** The variable is a process
    /// global and `cargo test` runs this module's tests on threads that share
    /// it, so a frame built while
    /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`] holds two blurs
    /// carries an `ssao-blur-2` pass, a full-screen triangle and a pipeline bind
    /// that the test building it never asked for. Taking the guard both
    /// serialises against that test and pins the count for the frames this one
    /// builds.
    ///
    /// Two shapes need it, and the second is easy to miss. A test comparing a
    /// frame against a **literal pass list** breaks whenever the count is two.
    /// A test comparing **two frames it built itself** — a difference in draws,
    /// an equality between pass lists, a "one pass longer" claim — breaks only
    /// when the count *moves between them*, which is a narrower window and why
    /// this reproduced at roughly one run in eight rather than every run.
    ///
    /// Both were established by experiment on 2026-09-01 rather than by
    /// reading: pinning the count at two reddens the first shape, and making
    /// `crate::ssao::blur_passes` alternate reddens the second.
    ///
    /// **A test taking this and [`debug_draw_switch`] takes that one first.**
    /// These are two plain mutexes with no ordering between them, so two tests
    /// acquiring both in opposite orders deadlock — which is not a hazard this
    /// comment is guessing at: adding the guard to the two debug-draw tests
    /// above their existing one did exactly that on 2026-09-01, and turned a
    /// 0.2 second suite into one that had not finished in ten minutes. It is
    /// invisible in a single-threaded run, where the same suite passes in a
    /// second, so `--test-threads=1` is not a check for it.
    ///
    /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`]: fn@a_second_occlusion_blur_is_a_pass_the_frame_records
    pub(super) fn ssao_blur_switch() -> SsaoBlurSwitch {
        let guard = SSAO_BLUR_SWITCH
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let switch = SsaoBlurSwitch { _guard: guard };
        switch.set(1);
        switch
    }

    /// What [`ssao_blur_switch`] hands back.
    pub(super) struct SsaoBlurSwitch {
        _guard: std::sync::MutexGuard<'static, ()>,
    }

    impl SsaoBlurSwitch {
        /// Asks for `passes` of them.
        fn set(&self, passes: i64) {
            crate::ssao::r_ssao_blur_passes
                .set(&crcbl_console::Value::Int(passes))
                .expect("`r_ssao_blur_passes` is a writable int in range");
        }
    }

    impl Drop for SsaoBlurSwitch {
        fn drop(&mut self) {
            // Back to the shipping count at both ends, so a check that panicked
            // mid-way does not hand the next holder a three-pass frame.
            self.set(1);
        }
    }

    /// [`ssao_blur_switch`]'s lock.
    static SSAO_BLUR_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// Takes `r_ssao_split` for this thread and puts it back when the guard
    /// drops.
    ///
    /// [`ssao_blur_switch`]'s shape exactly, for its reason. The seam is what
    /// makes the occlusion chain record its second march, so a test about the
    /// widest frame a renderer can produce has to hold this as well as the blur
    /// count — see `crate::ssao`'s `r_ssao_split`.
    pub(super) fn ssao_split_switch() -> SsaoSplitSwitch {
        let guard = SSAO_SPLIT_SWITCH
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let switch = SsaoSplitSwitch { _guard: guard };
        switch.set(0.0);
        switch
    }

    /// What [`ssao_split_switch`] hands back.
    pub(super) struct SsaoSplitSwitch {
        _guard: std::sync::MutexGuard<'static, ()>,
    }

    impl SsaoSplitSwitch {
        /// Asks for a seam at `at`, or for none at zero.
        fn set(&self, at: f32) {
            crate::ssao::r_ssao_split
                .set(&crcbl_console::Value::Float(at))
                .expect("`r_ssao_split` is a writable float in range");
        }
    }

    impl Drop for SsaoSplitSwitch {
        fn drop(&mut self) {
            // Back to the default at both ends, so a check that panicked
            // mid-way does not hand the next holder a comparing frame.
            self.set(0.0);
        }
    }

    /// [`ssao_split_switch`]'s lock.
    static SSAO_SPLIT_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// Takes `r_shadow_filter` and `r_shadow_split` for this thread and puts
    /// them both back at their defaults when the guard drops.
    ///
    /// [`ssao_split_switch`]'s shape, with two variables under one lock because
    /// they are read into one row of one block — `crate::shadow::FILTER_SWITCH`
    /// is where that is argued, and why the lock lives there rather than beside
    /// this function: `crate::shadow`'s own tests move the same two.
    fn shadow_filter_switch() -> ShadowFilterSwitch {
        let guard = crate::shadow::FILTER_SWITCH
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let switch = ShadowFilterSwitch { _guard: guard };
        switch.reset();
        switch
    }

    /// What [`shadow_filter_switch`] hands back.
    struct ShadowFilterSwitch {
        _guard: std::sync::MutexGuard<'static, ()>,
    }

    impl ShadowFilterSwitch {
        /// Asks for `filter` on the near side of the seam.
        fn filter(&self, filter: shadow::Filter) {
            crate::shadow::r_shadow_filter
                .set(&crcbl_console::Value::Enum(filter.label()))
                .expect("`r_shadow_filter` is a writable enum in the set");
        }

        /// Asks for a seam at `at`, or for none at zero.
        fn seam(&self, at: f32) {
            crate::shadow::r_shadow_split
                .set(&crcbl_console::Value::Float(at))
                .expect("`r_shadow_split` is a writable float in range");
        }

        /// Asks for `texels` of constant bias.
        fn bias(&self, texels: f32) {
            crate::shadow::r_shadow_bias
                .set(&crcbl_console::Value::Float(texels))
                .expect("`r_shadow_bias` is a writable float in range");
        }

        /// Asks for `texels` of normal offset.
        fn offset(&self, texels: f32) {
            crate::shadow::r_shadow_normal_offset
                .set(&crcbl_console::Value::Float(texels))
                .expect("`r_shadow_normal_offset` is a writable float in range");
        }

        /// Back to the frame every golden was blessed as.
        fn reset(&self) {
            self.filter(shadow::shipped_filter());
            self.seam(0.0);
            self.bias(shipped_float(&crate::shadow::r_shadow_bias));
            self.offset(shipped_float(&crate::shadow::r_shadow_normal_offset));
        }
    }

    /// The float `var` declares as its default — what a frame nobody typed at
    /// is drawn with, read off the variable rather than written down here.
    fn shipped_float(var: &crcbl_console::ConVar) -> f32 {
        match var.default() {
            crcbl_console::Value::Float(shipped) => *shipped,
            other => panic!("`{}` defaults to {other:?}, not to a float", var.name()),
        }
    }

    impl Drop for ShadowFilterSwitch {
        fn drop(&mut self) {
            // Back to the defaults at both ends, so a check that panicked
            // mid-way does not hand the next holder a comparing frame.
            self.reset();
        }
    }

    /// Takes `r_ssao_slices` for this thread and puts it back at its default
    /// when the guard drops.
    ///
    /// [`ssao_blur_switch`]'s shape exactly, for its reason: a plain
    /// `cargo test` run shares one process between tests, and a variable this
    /// one left moved is a frame the next test did not ask for.
    fn ssao_slice_switch() -> SsaoSliceSwitch {
        let guard = SSAO_SLICE_SWITCH
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let switch = SsaoSliceSwitch { _guard: guard };
        switch.set(i64::from(ssao::SLICE_COUNT_DEFAULT));
        switch
    }

    /// What [`ssao_slice_switch`] hands back.
    struct SsaoSliceSwitch {
        _guard: std::sync::MutexGuard<'static, ()>,
    }

    impl SsaoSliceSwitch {
        /// Asks each pixel for `slices` of them.
        fn set(&self, slices: i64) {
            crate::ssao::r_ssao_slices
                .set(&crcbl_console::Value::Int(slices))
                .expect("`r_ssao_slices` is a writable int in range");
        }
    }

    impl Drop for SsaoSliceSwitch {
        fn drop(&mut self) {
            // Back to the shipping count at both ends, so a check that panicked
            // mid-way does not hand the next holder a four-slice frame — which
            // is a frame every golden in this workspace was blessed without.
            self.set(i64::from(ssao::SLICE_COUNT_DEFAULT));
        }
    }

    /// [`ssao_slice_switch`]'s lock.
    static SSAO_SLICE_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// Takes `r_ssao_technique` for this thread and puts it back at its default
    /// when the guard drops.
    ///
    /// [`ssao_blur_switch`]'s shape exactly, for its reason — and this one moves
    /// a **pipeline** rather than a lane of a uniform block, so a frame that
    /// picked it up from another thread's test gathers through a shader that
    /// test never selected.
    ///
    /// **Its lock lives in `crate::ssao`** rather than beside this function, and
    /// it is the one switch here whose does: `ssao`'s own
    /// `the_seams_other_side_is_the_technique_that_ships` moves the same
    /// variable, and a second mutex would serialise neither against the other.
    /// See `crate::ssao::TECHNIQUE_SWITCH` for where it sits in the order.
    fn ssao_technique_switch() -> SsaoTechniqueSwitch {
        let guard = crate::ssao::TECHNIQUE_SWITCH
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let switch = SsaoTechniqueSwitch { _guard: guard };
        switch.set(shipped_technique_name());
        switch
    }

    /// The technique name the chain ships, and the one
    /// [`ssao_technique_switch`] restores.
    ///
    /// **Read off the variable rather than written down**, which is
    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]'s
    /// rule about the slice count and for its reason: which value ships is a
    /// thing that moves, and a test naming the wrong one would be comparing the
    /// shipped configuration against itself.
    ///
    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]: fn@the_comparison_seam_marches_twice_over_columns_that_tile_the_gather
    fn shipped_technique_name() -> &'static str {
        match crate::ssao::r_ssao_technique.default() {
            crcbl_console::Value::Enum(name) => name,
            other => panic!("`r_ssao_technique` defaults to {other:?}, not to a technique name"),
        }
    }

    /// A name from the variable's own set that is **not** the one it ships.
    ///
    /// [`shipped_technique_name`]'s clause from the other side: the tests below
    /// need a technique to move the console to, and picking it out of the
    /// declared set is what keeps them from naming one the variable does not
    /// offer — or, if a third arrived, from silently going on comparing the
    /// same two.
    fn other_technique_name() -> &'static str {
        let crcbl_console::Kind::Enum(names) = crate::ssao::r_ssao_technique.kind() else {
            panic!("`r_ssao_technique` is an enum variable");
        };
        let ships = shipped_technique_name();
        names
            .iter()
            .copied()
            .find(|name| *name != ships)
            .expect("`r_ssao_technique` offers a technique other than the one it ships")
    }

    /// What [`ssao_technique_switch`] hands back.
    struct SsaoTechniqueSwitch {
        _guard: std::sync::MutexGuard<'static, ()>,
    }

    impl SsaoTechniqueSwitch {
        /// Asks for the gather `name` selects.
        fn set(&self, name: &'static str) {
            crate::ssao::r_ssao_technique
                .set(&crcbl_console::Value::Enum(name))
                .expect("`r_ssao_technique` is a writable enum in the set");
        }
    }

    impl Drop for SsaoTechniqueSwitch {
        fn drop(&mut self) {
            // Back to what ships at both ends, so a check that panicked mid-way
            // does not hand the next holder a frame gathered through the cheap
            // tier — which is a frame no golden in this workspace was blessed
            // on.
            self.set(shipped_technique_name());
        }
    }

    /// Every draw the recorded stream holds, whichever call recorded it.
    ///
    /// Not scoped to a pass, unlike [`commands_in_pass`]: what
    /// [`ForwardRenderer::counters`] claims is a count over the *whole* frame, so
    /// the thing to compare it against is the whole frame.
    fn recorded_draws(recorder: &Recorder) -> usize {
        use crcbl_hal::null::Command;

        recorder
            .commands()
            .into_iter()
            .filter(|command| {
                matches!(
                    command,
                    Command::Draw { .. }
                        | Command::DrawIndexed { .. }
                        | Command::DrawIndirect(_)
                        | Command::DrawIndexedIndirect(_)
                        | Command::DrawIndirectCount(_)
                        | Command::DrawIndexedIndirectCount(_)
                        | Command::DrawMeshTasks { .. }
                        | Command::DrawMeshTasksIndirect(_)
                )
            })
            .count()
    }

    /// **The draw count is what the frame recorded, and the two GPU-side
    /// counters are `None` rather than a guess.**
    ///
    /// Both halves matter and both are checked here against something that
    /// moves. The draws are compared with the recorded stream, so a count that
    /// forgot the shadow pass's share or the tonemap's triangle fails. The
    /// instances are read before and after a pyramid is put in the pool, so a
    /// counter wired to a constant — or to the pool's *capacity*, which does not
    /// move — fails too.
    ///
    /// `drawn` and `triangles` are asserted [`None`] **on the frames this test
    /// runs**, which are inside [`CULL_STATS_FLOOR`]: nothing has come
    /// back off the GPU yet, and a `drawn` that was `Some` here would be a
    /// number invented before any readback landed. That is the assertion that
    /// catches the tempting version of this method: an instance count taken from
    /// the pool and reported as "drawn" would read as a culling win of exactly
    /// zero on every frame, which is the number the whole cull exists to change.
    /// What happens once the ring *has* come round is the test below.
    #[test]
    fn the_forward_counters_are_the_recorded_draws_and_admit_what_they_cannot_know() {
        let _blurs = ssao_blur_switch();
        let (recorder, device, queue) = open();
        let mut renderer =
            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");

        // Before any frame: nothing recorded, and said as a known zero.
        assert_eq!(renderer.counters(), FrameCounters::default());

        let first = frame(device.as_ref(), &mut renderer, queue);
        let counters = renderer.counters();
        assert_eq!(
            counters.draws,
            recorded_draws(&recorder) as u64,
            "the counter and the frame's recorded draws disagree",
        );
        // Derived from what the frame resolved rather than from a constant, so
        // this is still the every-effect frame's count and would follow a frame
        // that switched one off.
        let fullscreen = fullscreen_passes(
            renderer.effects(),
            TEST_EXTENT,
            false,
            renderer.frame_ssao_blurs,
        ) * FULLSCREEN_DRAWS;
        assert!(
            counters.draws > fullscreen,
            "a frame that recorded only its full-screen passes drew no scene",
        );
        assert_eq!(
            counters.instances,
            renderer.instances.len() as u64 + fullscreen,
        );
        assert_eq!(
            counters.drawn, None,
            "the ring has not come round, so there is no survivor count yet",
        );
        assert_eq!(counters.cull_frame, None, "and no frame to stamp it with");
        assert_eq!(counters.triangles, None);
        first.release(device.as_ref());

        // A second scene: one more instance in the pool, and the counter moves
        // with it. The draws do not — one call per bucket whatever the scene
        // holds is what §3.3 is about, and this is where that shows.
        place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, Mat4::IDENTITY);
        recorder.clear();
        let second = frame(device.as_ref(), &mut renderer, queue);
        let richer = renderer.counters();
        assert_eq!(
            richer.instances,
            counters.instances + 1,
            "an instance added to the pool must move the counter",
        );
        assert_eq!(
            richer.draws, counters.draws,
            "the recorded call count is independent of what the scene holds",
        );
        assert_eq!(richer.draws, recorded_draws(&recorder) as u64);

        second.finish(device.as_ref(), renderer);
    }

    /// **Once the ring has come round, `drawn` is a number and it says which
    /// frame it is from.**
    ///
    /// The other half of the test above: `indirect` while the readback is in
    /// flight, a count afterwards, and a `cull_frame` naming a frame several
    /// behind the one just recorded. The null backend executes no copy, so the
    /// *value* here is the full-screen passes' own draws and nothing else — what the cull
    /// really kept is asserted against a real GPU, in the umbrella crate's
    /// `tests/draw_gen_e2e/`, where a scene is culled on purpose.
    ///
    /// The frame number is the assertion with teeth here: a ring that read the
    /// slot it had just written would report the frame it is on, and a
    /// `cull_frame` left at `None` would put a latent number on the panel with
    /// nothing to say how old it is.
    #[test]
    fn the_culling_counters_arrive_a_few_frames_late_and_say_which_frame() {
        let (_recorder, device, queue) = open();
        let mut renderer =
            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");

        let mut frames = Vec::new();
        for _ in 0..CULL_STATS_FLOOR {
            frames.push(frame(device.as_ref(), &mut renderer, queue));
            assert_eq!(
                renderer.counters().drawn,
                None,
                "no readback has even been polled yet, so there is nothing back",
            );
        }

        frames.push(frame(device.as_ref(), &mut renderer, queue));
        let counters = renderer.counters();
        assert_eq!(
            counters.drawn,
            Some(
                fullscreen_passes(
                    renderer.effects(),
                    TEST_EXTENT,
                    false,
                    renderer.frame_ssao_blurs,
                ) * FULLSCREEN_DRAWS,
            ),
            "the survivor count the null backend produced is zero, plus one instance per \
             full-screen pass — which is on both sides of the row",
        );
        assert_eq!(
            counters.cull_frame,
            Some(1),
            "the report is the frame whose copy answered, not the frame just recorded",
        );
        assert_eq!(renderer.cull_stats().expect("a readback answered").frame, 1,);

        for frame in frames {
            frame.release(device.as_ref());
        }
        renderer.destroy(device.as_ref());
    }

    /// The frames a culling counter cannot possibly have arrived in.
    ///
    /// Two: the copy is recorded on one frame and the readback for it requested
    /// on the next, so the earliest frame that can poll anything is the third.
    /// A device that answers its first poll — the null backend, and every native
    /// one — reports there; a browser answers later, which is why this is a
    /// floor rather than a latency. See [`crate::cull_stats`].
    const CULL_STATS_FLOOR: usize = 2;

    /// **A light that takes a shadow tile moves the draw count**, because the
    /// shadow pass records one call per bucket per occupied view.
    ///
    /// The observable a `recorded_draws` comparison alone would miss: a
    /// `counters` that counted only the colour pass and the tonemap agrees with
    /// nothing here, and one that hard-coded the cascades agrees with the first
    /// frame and not the second.
    #[test]
    fn a_light_that_takes_a_shadow_tile_moves_the_draw_count() {
        let (recorder, device, queue) = open();
        let mut renderer =
            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");

        let dark = frame(device.as_ref(), &mut renderer, queue);
        let without = renderer.counters().draws;
        assert_eq!(without, recorded_draws(&recorder) as u64);
        dark.release(device.as_ref());

        renderer.set_lights(&[shadowable_spot(0.0)]);
        recorder.clear();
        let lit = frame(device.as_ref(), &mut renderer, queue);
        let with = renderer.counters().draws;
        assert!(
            with > without,
            "a shadow-casting light adds a view and therefore draws: {with} against {without}",
        );
        assert_eq!(
            with,
            recorded_draws(&recorder) as u64,
            "and the counter still matches the stream",
        );
        lit.finish(device.as_ref(), renderer);
    }

    /// Opens a null device offering `optional` on top of the mesh path, and
    /// asserts it really selected that path.
    ///
    /// Asked for rather than merely reported, because a device grants what it
    /// enabled: leaving mesh shaders out of the optional set opens a device on
    /// an indirect tail and tests nothing.
    ///
    /// The adapter has [`Features::DRAW_INDEX`] too, which a device is granted
    /// only where `optional` asks for it — so a test that does not gets the
    /// mesh tail's call per bucket.
    fn open_mesh_path(recorder: &Recorder, optional: Features) -> (Box<dyn Device>, QueueHandle) {
        let caps = crcbl_hal::DeviceCaps {
            features: Features::GPU_DRIVEN
                | Features::MESH_SHADER
                | Features::TASK_SHADER
                | Features::DRAW_INDEX,
            limits: crcbl_hal::Limits::desktop(),
        };
        let instance = NullInstance::new(caps).with_recorder(recorder.clone());
        let adapter = instance.adapters().remove(0);
        assert_eq!(
            instance
                .adapter_caps(adapter.id)
                .expect("the null backend describes its adapter")
                .geometry_path(),
            GeometryPath::MeshShader,
            "a device with mesh shaders selects them, which is the case this is about"
        );
        let device = instance
            .create_device(&DeviceDesc {
                label: None,
                adapter: adapter.id,
                required_features: Features::COMPUTE,
                optional_features: Features::GPU_DRIVEN | Features::MESH_SHADER | optional,
                compatible_surface: None,
            })
            .expect("the null backend always opens");
        assert_eq!(
            device.caps().geometry_path(),
            GeometryPath::MeshShader,
            "and the opened device still selects it"
        );
        let queue = device.queue(QueueKind::Graphics).expect("always present");
        (device, queue)
    }

    /// **The four material pages are created with the format their contents
    /// call for, and it is only a *colour* that is sRGB.**
    ///
    /// Topic 44's rung 2 calls this the classic PBR bug and
    /// says why it survives review: a base-colour texel and an emissive one are
    /// sRGB-encoded *colours*, which is what glTF defines them as, and a normal
    /// texel and a packed occlusion-roughness-metallic one are *numbers* — so
    /// decoding either of those through the sRGB curve is wrong by a gamma and
    /// looks merely like a surface bumpier or shinier than the author drew.
    /// Nothing in a frame reports it, no golden comparison can name it, and the
    /// four constants sit a few lines apart with the wrong one compiling.
    ///
    /// So this is the whole guard, and it is three claims rather than one: that
    /// each constant is the one it should be, that
    /// [`PageKind::format`] — which is what the upload loop actually calls —
    /// answers with it, and, the half that would otherwise be a check that
    /// cannot fail, that the format each page is *created* with is the format
    /// its `ImportedImage` declares. A declaration naming a format the image is
    /// not in picks the wrong aspects in a barrier.
    #[test]
    fn the_page_formats_split_colour_from_number() {
        assert_eq!(BASE_COLOR_PAGE_FORMAT, Format::Rgba8UnormSrgb);
        assert_eq!(EMISSIVE_PAGE_FORMAT, Format::Rgba8UnormSrgb);
        assert_eq!(NORMAL_PAGE_FORMAT, Format::Rgba8Unorm);
        assert_eq!(MRO_PAGE_FORMAT, Format::Rgba8Unorm);
        // Through the dispatch the upload loop actually calls, rather than the
        // constants alone: one loop creates every image now, and a `format` arm
        // pointed at the wrong constant is the way that loop gets it wrong.
        assert_eq!(PageKind::BaseColor.format(), BASE_COLOR_PAGE_FORMAT);
        assert_eq!(PageKind::Normal.format(), NORMAL_PAGE_FORMAT);
        assert_eq!(
            PageKind::MetallicRoughnessOcclusion.format(),
            MRO_PAGE_FORMAT
        );
        assert_eq!(PageKind::Emissive.format(), EMISSIVE_PAGE_FORMAT);
        assert_ne!(
            BASE_COLOR_PAGE_FORMAT, NORMAL_PAGE_FORMAT,
            "a normal page created sRGB decodes every texel through a gamma it never had"
        );
        assert_ne!(
            EMISSIVE_PAGE_FORMAT, MRO_PAGE_FORMAT,
            "a packed roughness page created sRGB shades every surface smoother than authored"
        );

        let (recorder, device, queue) = open();
        let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
            .expect("the forward renderer builds on the null backend");
        assert_eq!(
            renderer.base_color_page_import().format,
            BASE_COLOR_PAGE_FORMAT
        );
        assert_eq!(renderer.normal_page_import().format, NORMAL_PAGE_FORMAT);
        assert_eq!(renderer.mro_page_import().format, MRO_PAGE_FORMAT);
        assert_eq!(renderer.emissive_page_import().format, EMISSIVE_PAGE_FORMAT);
        // And they really are four images, not one bound four times — which is
        // the other way a page could be "linear" and still be sampled through
        // the sRGB one.
        let created = [
            renderer.base_color_page(),
            renderer.normal_page(),
            renderer.mro_page(),
            renderer.emissive_page(),
        ];
        for (at, page) in created.iter().enumerate() {
            for other in &created[at + 1..] {
                assert_ne!(page.image, other.image, "two page kinds share one image");
                assert_ne!(page.view, other.view, "two page kinds share one view");
            }
        }
        // The labels come off the recorder rather than off the handles, so this
        // is evidence about what the device was asked to create.
        let images: Vec<String> = recorder
            .events()
            .into_iter()
            .filter_map(|event| match event {
                Event::Created {
                    kind: ObjectKind::Image,
                    label: Some(label),
                } => Some(label),
                _ => None,
            })
            .collect();
        for kind in PageKind::ALL {
            let page = kind.upload_label();
            assert!(
                images.iter().any(|label| label == page),
                "no image was created for the {page} page, and it is {images:?} that were"
            );
        }
        renderer.destroy(device.as_ref());
    }

    /// Compare native argument indices from the shipped entry points with the
    /// actual renderer layout. A shared fragment buffer must have the same index
    /// even when geometry introduces additional resources in another module.
    #[test]
    fn mesh_pipeline_buffers_match_native_shader_arguments() {
        for optional in [Features::TASK_SHADER, Features::empty()] {
            let recorder = Recorder::new();
            let (device, queue) = open_mesh_path(&recorder, optional);
            let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
                .expect("the mesh renderer builds");
            let (_, entries) = recorder
                .bind_group_layouts_created()
                .into_iter()
                .find(|(label, _)| label.as_deref() == Some(MESH_LAYOUT_LABEL))
                .expect("the actual mesh layout");
            let mut buffers: Vec<_> = entries
                .iter()
                .filter(|entry| {
                    matches!(
                        entry.kind,
                        BindingKind::UniformBuffer { .. } | BindingKind::StorageBuffer { .. }
                    )
                })
                .collect();
            buffers.sort_by_key(|entry| entry.binding);
            assert_eq!(buffers.len(), 20, "the native buffer budget is unchanged");
            for (source, shader, names) in [
                (
                    include_str!("../../crcbl-shaders/shaders/mesh.slang"),
                    &MESH,
                    &["fragmentMain"][..],
                ),
                (
                    include_str!("../../crcbl-shaders/shaders/mesh_cluster.slang"),
                    &MESH_CLUSTER,
                    &["meshMain", "taskMain", "amplifiedMeshMain"][..],
                ),
            ] {
                let declarations: Vec<_> = source.lines().collect();
                let bindings: Vec<_> = declarations
                    .windows(2)
                    .filter_map(|lines| {
                        let binding = lines[0]
                            .trim()
                            .strip_prefix("[[vk::binding(")?
                            .split(',')
                            .next()?
                            .parse::<u32>()
                            .ok()?;
                        // The name is the last word before the D3D12 register.
                        let name = lines[1]
                            .split(" D3D12_REGISTER(")
                            .next()?
                            .split_whitespace()
                            .last()?
                            .trim_end_matches(';');
                        Some((name, binding))
                    })
                    .collect();
                for name in names {
                    let signature = shader
                        .msl()
                        .expect("committed native shader")
                        .lines()
                        .find(|line| line.starts_with("[[") && line.contains(&format!(" {name}(")))
                        .expect("native entry signature");
                    let mut checked = 0;
                    for argument in signature.split(", ") {
                        let Some((declaration, tail)) = argument.split_once(" [[buffer(") else {
                            continue;
                        };
                        let native: usize = tail.split(')').next().unwrap().parse().unwrap();
                        let variable = declaration.split_whitespace().last().unwrap();
                        let variable = variable.rsplit_once('_').map_or(variable, |(base, _)| base);
                        let binding = bindings
                            .iter()
                            .find(|(candidate, _)| *candidate == variable)
                            .unwrap_or_else(|| panic!("unknown {name} buffer {variable}"))
                            .1;
                        let expected = buffers
                            .iter()
                            .position(|entry| entry.binding == binding)
                            .expect("shader binding exists in the renderer layout");
                        assert_eq!(
                            native, expected,
                            "{name}: {variable}, logical binding {binding}, native shader vs global layout"
                        );
                        checked += 1;
                    }
                    assert!(
                        checked >= 10,
                        "entry parsing must cover the complete buffer interface"
                    );
                }
            }
            renderer.destroy(device.as_ref());
        }
    }

    #[test]
    fn the_mesh_layout_declares_the_same_bindings_with_and_without_a_task_stage() {
        let mut declared: Vec<Vec<(u32, BindingKind)>> = Vec::new();
        for optional in [Features::TASK_SHADER, Features::empty()] {
            let recorder = Recorder::new();
            let (device, queue) = open_mesh_path(&recorder, optional);
            let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
                .expect("the forward renderer builds on both device shapes");
            assert_eq!(
                renderer.culls_clusters(),
                optional.contains(Features::TASK_SHADER),
                "the two arms must actually differ, or this compares a device with itself"
            );
            let (label, entries) = recorder
                .bind_group_layouts_created()
                .into_iter()
                .find(|(label, _)| label.as_deref() == Some(MESH_LAYOUT_LABEL))
                .expect("the mesh pass declares its layout by name");
            assert_eq!(label.as_deref(), Some(MESH_LAYOUT_LABEL));
            declared.push(
                entries
                    .iter()
                    .map(|entry| (entry.binding, entry.kind))
                    .collect(),
            );
        }

        let [amplified, plain] = declared
            .try_into()
            .unwrap_or_else(|_| unreachable!("two arms were run"));
        assert_eq!(
            amplified, plain,
            "the mesh layout's bindings changed with the task stage, which moves every Metal \
             argument-table index above the difference"
        );
        // These mesh declarations remain present without a task stage.
        for binding in [
            CLUSTER_CULL_BINDING,
            CLUSTER_CULL_STATS_BINDING,
            CLUSTER_SELECT_BINDING,
            CLUSTER_SELECTION_BINDING,
            CLUSTER_GROUP_STATE_BINDING,
        ] {
            assert!(
                plain.iter().any(|(number, _)| *number == binding),
                "binding {binding} is declared by mesh_cluster.slang and must be in the layout"
            );
        }
        // Logical gaps consume no native slots. The complete shader union must
        // remain sorted, and every mesh-only buffer follows the fragment prefix.
        let numbers: Vec<u32> = plain.iter().map(|(binding, _)| *binding).collect();
        let expected: Vec<u32> = (0..=8).chain(15..=16).chain(20..=40).collect();
        assert_eq!(
            numbers, expected,
            "the complete sparse shader binding union"
        );
    }

    /// **`Features::TASK_SHADER` is what decides whether §3.5's per-cluster cull
    /// is built, and a device without it still draws.**
    ///
    /// The two capabilities are separate, and the adapter above offers both — so
    /// asking for one and not the other is a device state a real driver has and
    /// this can reach. Neither arm is a skip:
    ///
    /// * With the task stage, the renderer builds the amplification stage and
    ///   [`ForwardRenderer::culls_clusters`] says so. The null backend refuses a
    ///   task stage on a device without the flag, so an arm that computed this
    ///   wrongly would fail to build rather than pass quietly. It records one
    ///   flat call per partition — [`flat_dispatch_calls`].
    /// * Without it, the renderer builds `meshMain` — the un-amplified entry
    ///   point — and draws every cluster of every surviving instance, one
    ///   indirect dispatch per bucket reading its own extents.
    #[test]
    fn the_task_stage_is_built_only_where_the_device_has_one() {
        use crcbl_hal::null::Command;

        for (optional, expected) in [(Features::TASK_SHADER, true), (Features::empty(), false)] {
            let recorder = Recorder::new();
            let (device, queue) = open_mesh_path(&recorder, optional);
            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
                .expect("the forward renderer builds on both device shapes");
            assert_eq!(
                device.caps().supports(Features::TASK_SHADER),
                expected,
                "the device must actually differ between the arms, or both test the same thing"
            );
            assert_eq!(
                renderer.culls_clusters(),
                expected,
                "the amplification stage is built exactly where the device has one"
            );
            assert_eq!(
                renderer.geometry_path(),
                GeometryPath::MeshShader,
                "both arms are the mesh path; only the stage in front of it differs"
            );

            let frame = frame(device.as_ref(), &mut renderer, queue);
            // After the frame, because the buffer named is the slot the frame
            // rotated to — asking before it names the previous slot's ring
            // entry and the comparison is against a buffer nothing drew from.
            let expected = if expected {
                flat_dispatch_calls(&renderer, crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED).0
            } else {
                mesh_dispatch_calls(&renderer)
            };

            let dispatched: Vec<DrawIndirect> = commands_in_pass(&recorder, "forward")
                .into_iter()
                .filter_map(|command| match command {
                    Command::DrawMeshTasksIndirect(draw) => Some(draw),
                    _ => None,
                })
                .collect();
            assert_eq!(
                dispatched, expected,
                "a flat call per partition behind the stage, and a dispatch per bucket reading \
                 its own extents without it"
            );

            frame.finish(device.as_ref(), renderer);
        }
    }

    /// The flat calls a pass splitting the bucket table by the material-mode
    /// bits `key` records behind a task stage, in region 0, in partition order
    /// — one per segment the table holds buckets of — and each segment's first
    /// bucket, whose block the call binds.
    ///
    /// The offsets from [`crcbl_shaders::draw_gen::flat_args_word`] over the
    /// camera generator's own region count rather than from
    /// `DrawGen::flat_args_offset`, for [`mesh_dispatch_calls`]' reason.
    fn flat_dispatch_calls(renderer: &ForwardRenderer, key: u32) -> (Vec<DrawIndirect>, Vec<u32>) {
        let stride = crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32;
        let buckets = u32::try_from(renderer.bucket_constants.len()).expect("a few buckets");
        let regions = renderer.primary.draws.mode().regions();
        let segments = crcbl_shaders::draw_gen::flat_segments(&renderer.bucket_modes);
        let values: Vec<u32> = if key == crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED {
            vec![0, key]
        } else {
            DEPTH_MODES.to_vec()
        };
        values
            .into_iter()
            .filter(|value| {
                renderer
                    .bucket_modes
                    .iter()
                    .any(|mode| mode & key == *value)
            })
            .map(|value| {
                let segment = crcbl_shaders::draw_gen::flat_segment(key, value)
                    .expect("a split every pass makes");
                (
                    DrawIndirect {
                        args: renderer.primary.draws.mesh_args(renderer.frame),
                        offset: u64::from(crcbl_shaders::draw_gen::flat_args_word(
                            buckets, regions, 0, segment, 0,
                        )) * 4,
                        draw_count: 1,
                        stride,
                    },
                    segments[segment as usize].0,
                )
            })
            .unzip()
    }

    /// The [`DrawIndirect`] the mesh path must record for each bucket, in bucket
    /// order.
    ///
    /// Built from the buffer the draw-argument pass writes and the stride the
    /// APIs fixed, so a test comparing against it is asserting that the call
    /// reads *this frame's* arguments at *this bucket's* offset — the two ways
    /// an indirect dispatch goes wrong while still dispatching something.
    ///
    /// **The offsets are multiplied out here rather than asked of
    /// [`DrawGen::mesh_args_offset`]**, which is the difference between a
    /// comparison and a tautology: an offset function that returned zero for
    /// every bucket would agree with itself, and three calls onto one structure
    /// is a frame that draws one bucket's geometry three times.
    fn mesh_dispatch_calls(renderer: &ForwardRenderer) -> Vec<DrawIndirect> {
        let stride = crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32;
        // The extents share a buffer with the one draw count per bucket that
        // precedes them, so every offset is that far in. Written out from the
        // bucket count here rather than taken from `DrawGen::mesh_args_offset`,
        // for the reason above: a base of zero is exactly the mistake this
        // comparison exists to catch, and it would agree with itself.
        let counts_bytes = renderer.bucket_constants.len() as u64 * 4;
        (0..renderer.bucket_constants.len())
            .map(|bucket| DrawIndirect {
                args: renderer.primary.draws.mesh_args(renderer.frame),
                offset: counts_bytes + bucket as u64 * u64::from(stride),
                draw_count: 1,
                stride,
            })
            .collect()
    }

    /// **A device selecting [`GeometryPath::MeshShader`] draws through a mesh
    /// pipeline, and records no indirect draw and no index-buffer bind at all.**
    ///
    /// The three halves are one claim. That it dispatched says the path is
    /// wired; that it recorded *no* `DrawIndexedIndirect` of either kind says it
    /// did not quietly fall through to a tail that draws the same picture; and
    /// that it bound no index buffer says the geometry really came out of the
    /// cluster records rather than out of the index pool. Until 2026-08 this
    /// device degraded and logged that it had, which is exactly the shape —
    /// "not implemented" arriving as a passing frame — the three together rule
    /// out.
    ///
    /// **The extents are not here to be checked, and that is the point.** They
    /// are three words the draw-argument pass writes, so what this can pin is
    /// the call reading *this* bucket's structure out of *this* frame's buffer
    /// — and the CPU-side half of the x extent, the per-bucket cluster table
    /// the host uploaded, which the null backend keeps the bytes of. What the
    /// GPU then makes of it needs a GPU: `crcbl-vk`'s
    /// `the_mesh_dispatch_extent_is_the_culled_instance_count` reads the
    /// arguments back.
    #[test]
    fn a_mesh_shader_device_draws_through_a_mesh_pipeline() {
        use crcbl_hal::null::Command;

        let recorder = Recorder::new();
        let caps = crcbl_hal::DeviceCaps {
            features: Features::GPU_DRIVEN | Features::MESH_SHADER,
            limits: crcbl_hal::Limits::desktop(),
        };
        let instance = NullInstance::new(caps).with_recorder(recorder.clone());
        let adapter = instance.adapters().remove(0);
        assert_eq!(
            instance
                .adapter_caps(adapter.id)
                .expect("the null backend describes its adapter")
                .geometry_path(),
            GeometryPath::MeshShader,
            "a device with mesh shaders selects them, which is the case this is about"
        );
        let device = instance
            .create_device(&DeviceDesc {
                label: None,
                adapter: adapter.id,
                required_features: Features::COMPUTE,
                // Asked for, because a device reports what it enabled: leaving
                // mesh shaders out of the optional set would open a device that
                // selects an indirect path outright and test nothing.
                optional_features: Features::GPU_DRIVEN | Features::MESH_SHADER,
                compatible_surface: None,
            })
            .expect("the null backend always opens");
        assert_eq!(
            device.caps().geometry_path(),
            GeometryPath::MeshShader,
            "and the opened device still selects it"
        );
        let queue = device.queue(QueueKind::Graphics).expect("always present");
        let mut renderer =
            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
        assert_eq!(
            renderer.geometry_path(),
            GeometryPath::MeshShader,
            "the renderer must have *built* the mesh path, not merely been offered it"
        );
        let frame = frame(device.as_ref(), &mut renderer, queue);
        let expected = mesh_dispatch_calls(&renderer);
        // The table is written once at build, into a host-visible buffer the
        // null backend keeps the bytes of — so it is readable whether or not a
        // shader ever ran. It shares that buffer with the four other tables the
        // draw-argument pass reads, so the region has to be cut out at the
        // offset the renderer told the shader about rather than at zero.
        let table_bytes = recorder
            .buffer_bytes(renderer.primary.draws.tables())
            .expect("the table buffer is one of this recorder's buffers");
        let clusters_at = renderer.primary.draws.table_offsets().bucket_clusters_at as usize * 4;
        let clusters: Vec<u32> = table_bytes[clusters_at..]
            .as_chunks::<4>()
            .0
            .iter()
            .take(renderer.bucket_constants.len())
            .map(|word| u32::from_le_bytes(*word))
            .collect();

        let mut dispatched = Vec::new();
        let mut index_binds = 0;
        for command in commands_in_pass(&recorder, "forward") {
            match command {
                Command::DrawMeshTasksIndirect(draw) => dispatched.push(draw),
                Command::DrawMeshTasks { .. } => panic!(
                    "the mesh path recorded a CPU-sized dispatch, which is the extent \
                     the instance cull is supposed to have taken over"
                ),
                Command::DrawIndexedIndirectCount(_) | Command::DrawIndexedIndirect(_) => {
                    panic!(
                        "the mesh path recorded an indirect draw, which is the silent \
                         fall-through this test exists to rule out"
                    )
                }
                Command::BindIndexBuffer { .. } => index_binds += 1,
                _ => {}
            }
        }
        assert_eq!(
            dispatched, expected,
            "one indirect dispatch per bucket, each reading its own argument structure \
             out of this frame's buffer"
        );
        assert_eq!(
            clusters.len(),
            renderer.bucket_constants.len(),
            "one x extent per bucket: {clusters:?}"
        );
        assert!(
            clusters.iter().all(|&count| count > 0),
            "a bucket with no clusters dispatches nothing, whatever the arguments say: \
             {clusters:?}"
        );
        // **The x extents are not all the same number**, which is what makes
        // the table a statement about each bucket's own mesh. Two
        // single-cluster meshes would let a table hard-coded to one cluster
        // pass; the open box is five, one per face.
        assert_eq!(
            clusters[DEMO_OPEN_BOX] as usize,
            crcbl_shaders::mesh::OPEN_BOX_FACES.len(),
            "the open box dispatches one workgroup per face, and that is the only \
             resident whose cluster count is not one: {clusters:?}"
        );
        assert_eq!(
            index_binds, 0,
            "a mesh pipeline has no index buffer; binding one would mean the geometry \
             came from the index pool after all"
        );

        frame.finish(device.as_ref(), renderer);
    }

    /// **The cull pass is told the camera the frame is drawn with**, and how
    /// many array elements to walk.
    ///
    /// Both halves fail silently: a frustum from a different aspect ratio culls
    /// geometry that is on screen, and an instance count short of the pool's
    /// high-water mark stops testing the instances above a freed slot. Neither
    /// is visible in a picture until something disappears from an edge.
    #[test]
    fn the_cull_pass_gets_this_frame_s_camera_and_every_occupied_slot() {
        let (recorder, device, queue) = open();
        let mut renderer =
            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
        // The cube first and the pyramid above it, because the second half of
        // this test frees the lower slot and asks what the walk still covers.
        let cube = place_cube(&mut renderer, Mat4::IDENTITY);
        place_demo(
            &mut renderer,
            DEMO_PYRAMID,
            DEMO_UNTINTED,
            Mat4::from_translation(Vec3::X),
        );

        let camera = Camera {
            eye: Vec3::new(1.6, 1.2, 2.2),
            ..Camera::default()
        };
        let extent = (256u32, 192u32);
        renderer
            .begin_frame(
                device.as_ref(),
                &camera,
                &DirectionalLight::default(),
                extent,
            )
            .expect("write");

        let aspect = extent.0 as f32 / extent.1 as f32;
        let expected = crate::cull::Frustum::from_view_projection(camera.view_projection(aspect));
        let written = recorder
            .buffer_bytes(renderer.primary.draws.cull_params(renderer.frame))
            .expect("this frame's cull parameters are live");
        assert_eq!(
            &written[..crcbl_shaders::cull::PARAMS_SIZE],
            &crcbl_shaders::cull::Params {
                planes: expected.planes.map(|plane| plane.to_array()),
                instance_count: 2,
                capacity: scene::Capacities::default().instances,
                hidden_view: ViewId::PRIMARY.hidden_bit(),
                ..crcbl_shaders::cull::Params::default()
            }
            .to_bytes()[..],
            "the cull block must carry this frame's own frustum, the pool's whole \
             occupied range, and the visible list's capacity"
        );

        // And the high-water mark is what is written, not the live count: remove
        // the cube and the pyramid above it still has to be tested.
        renderer.remove_instance(cube);
        renderer
            .begin_frame(
                device.as_ref(),
                &camera,
                &DirectionalLight::default(),
                extent,
            )
            .expect("write");
        let written = recorder
            .buffer_bytes(renderer.primary.draws.cull_params(renderer.frame))
            .expect("live");
        assert_eq!(
            u32::from_le_bytes(written[96..100].try_into().expect("four bytes")),
            2,
            "one live instance, two occupied slots — a walk of one would never \
             reach the pyramid"
        );

        renderer.destroy(device.as_ref());
        recorder.assert_valid();
    }

    /// **Every counter both compute passes add to is zeroed by a pass of its
    /// own, before either of them runs.**
    ///
    /// The two shaders only ever increment, so a counter carrying the previous
    /// frame's total makes a bucket's argument structure claim more instances
    /// than its run holds — which draws whatever the run's stale tail happens to
    /// name.
    ///
    /// # This once read the bytes back, and no longer can
    ///
    /// It used to poison every counter with `0xAB` and assert `begin_frame`
    /// had written zeroes over them — the poison being the whole test, because
    /// the null backend runs no shader and a counter nothing wrote reads as the
    /// zero it was created with. The counters are device-local now, so nothing
    /// on the host writes them and [`Recorder::buffer_bytes`] holds nothing for
    /// them: the zero is a dispatch inside the frame, and a backend that runs no
    /// shader cannot observe it at all.
    ///
    /// So the poison moved to where a shader actually runs — `crcbl-vk`'s
    /// `draw_gen` end-to-end fills them with a sentinel and reads back the
    /// generated arguments — and what is checkable *here* is the schedule: that
    /// the frame contains the clearing pass, that it writes exactly those
    /// buffers, and that the graph orders the two accumulating passes after it.
    /// Each of the counts below goes red if a buffer is dropped from the
    /// clearing pass, and the pass list goes red if the pass leaves the frame.
    #[test]
    fn every_frame_starts_from_zeroed_counters() {
        let (recorder, device, queue) = open();
        let mut renderer =
            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
        place_cube(&mut renderer, Mat4::IDENTITY);
        let imported = swapchain_image(device.as_ref());
        // Twice round the ring, because a slot cleared only on its first use is
        // exactly the failure this is about.
        for round in 0..FRAMES_IN_FLIGHT * 2 {
            renderer
                .begin_frame(
                    device.as_ref(),
                    &Camera::default(),
                    &DirectionalLight::default(),
                    (64, 48),
                )
                .expect("write");
            let mut graph = crate::RenderGraph::new(queue);
            let target = graph.import_image("target", imported);
            let pool = crate::TransientPool::new();
            renderer.add_passes(&mut graph, &pool, target, (64, 48));
            let compiled = graph.compile(&pool).expect("a legal frame");

            let clear = &compiled.passes()[0];
            assert_eq!(
                clear.label(),
                "clear-counters",
                "round {round}: the zero has to be written before anything adds to it"
            );
            let barriers = &clear.barriers().buffers;
            assert_eq!(
                barriers.len(),
                3,
                "round {round}: the survivor count, the draw arguments, and the buffer \
                 holding both the draw counts and the mesh-dispatch arguments, and \
                 nothing else: {barriers:?}"
            );
            assert!(
                barriers
                    .iter()
                    .all(|barrier| barrier.to == ResourceState::ShaderReadWrite),
                "round {round}: every one of them is written by this pass: {barriers:?}"
            );
            // The ones the frame leaves as indirect arguments are the two a
            // driver reads; the survivor count rests in a shader read. That
            // split is what names them without a handle to compare.
            assert_eq!(
                barriers
                    .iter()
                    .filter(|barrier| barrier.from == ResourceState::IndirectArgument)
                    .count(),
                2,
                "round {round}: out of the state a draw read them in: {barriers:?}"
            );

            let after = |label: &str| {
                compiled
                    .passes()
                    .iter()
                    .find(|pass| pass.label() == label)
                    .unwrap_or_else(|| panic!("round {round}: no `{label}` pass"))
                    .barriers()
                    .buffers
                    .iter()
                    .filter(|barrier| {
                        barrier.from == ResourceState::ShaderReadWrite
                            && barrier.to == ResourceState::ShaderReadWrite
                    })
                    .count()
            };
            assert_eq!(
                after("cull"),
                1,
                "round {round}: the survivor count reaches the cull pass's atomic behind a \
                 barrier on the write that zeroed it"
            );
            assert_eq!(
                after("draw-args"),
                4,
                "round {round}: and so do the draw arguments and the buffer holding the \
                 draw counts beside the mesh-dispatch arguments — plus the survivor list, \
                 which the cull pass has just written and this pass reads through the same \
                 descriptor it scatters the runs into, and `docs/notes/rendering.md`'s \
                 hysteresis state, which the clearing pass does *not* zero and which is \
                 behind the same kind of barrier for the opposite reason: it is the one \
                 buffer here carrying a value out of the previous frame, so what it needs \
                 ordering against is that frame rather than this one's clear"
            );
            // **And the prefix sum and the scatter behind barriers of their own**,
            // on every buffer the stage before them wrote. This is what orders
            // them on a device that runs undeclared commands in any order — see
            // `DrawGen::add_passes` — and what three dispatches in one pass
            // silently lacked.
            for label in ["draw-starts", "draw-scatter"] {
                assert_eq!(
                    after(label),
                    4,
                    "round {round}: `{label}` reads what the pass before it wrote, so every \
                     buffer they share is ordered behind a barrier"
                );
            }

            // The compiled graph borrows the renderer's pass bodies, so it has
            // to go before the next frame borrows the renderer again.
            drop(compiled);
        }
        renderer.destroy(device.as_ref());
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// **A frame with no instances leaves out every generator's cull and
    /// scatter passes**, and keeps the clear and the two stages that write each
    /// bucket's arguments.
    ///
    /// An empty pass is not a harmless no-op on Metal: the backend opens an
    /// encoder for every graph pass and strict validation rejects ending one
    /// with no work — see `DrawGen::add_passes`. Each count below goes red if
    /// an empty pass comes back, or if a pass a zero-draw frame needs drops out.
    #[test]
    fn a_frame_with_no_instances_omits_the_empty_draw_generation_passes() {
        let (recorder, device, queue) = open();
        let mut renderer =
            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
        renderer
            .begin_frame(
                device.as_ref(),
                &Camera::default(),
                &DirectionalLight::default(),
                (64, 48),
            )
            .expect("write");
        let imported = swapchain_image(device.as_ref());
        let mut graph = crate::RenderGraph::new(queue);
        let target = graph.import_image("target", imported);
        let pool = crate::TransientPool::new();
        renderer.add_passes(&mut graph, &pool, target, (64, 48));
        let compiled = graph.compile(&pool).expect("a legal frame");

        let count = |label: &str| {
            compiled
                .passes()
                .iter()
                .filter(|pass| pass.label() == label)
                .count()
        };
        // The camera's generator and one per shadow cascade.
        let generators = 1 + shadow::CASCADES;
        for label in ["clear-counters", "draw-args", "draw-starts"] {
            assert_eq!(
                count(label),
                generators,
                "`{label}` still has work with nothing to draw: the clear erases the \
                 previous frame's counts and the argument stages write zero draws"
            );
        }
        for label in ["cull", "draw-scatter"] {
            assert_eq!(
                count(label),
                0,
                "`{label}` has no workgroups to dispatch with no instances"
            );
        }

        drop(compiled);
        renderer.destroy(device.as_ref());
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// **The graph transitions the generated arguments into
    /// [`ResourceState::IndirectArgument`] before the draws read them**, and the
    /// runs into a shader read.
    ///
    /// The seam calls this the single most important barrier in a GPU-driven
    /// frame and says its absence produces "sometimes nothing draws" — which is
    /// exactly the failure a golden image on one driver would not catch. It is
    /// asserted on the compiled graph, which is pure and needs no device.
    #[test]
    fn the_graph_barriers_the_arguments_into_place_before_the_draws() {
        let _blurs = ssao_blur_switch();
        let (recorder, device, queue) = open();
        let mut renderer =
            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
        place_cube(&mut renderer, Mat4::IDENTITY);
        renderer
            .begin_frame(
                device.as_ref(),
                &Camera::default(),
                &DirectionalLight::default(),
                (64, 48),
            )
            .expect("write");

        let imported = swapchain_image(device.as_ref());
        let mut graph = crate::RenderGraph::new(queue);
        let target = graph.import_image("target", imported);
        let pool = crate::TransientPool::new();
        renderer.add_passes(&mut graph, &pool, target, (64, 48));
        let compiled = graph.compile(&pool).expect("a legal frame");

        let passes: Vec<String> = compiled
            .passes()
            .iter()
            .map(|pass| pass.label().to_string())
            .collect();
        // The camera's five compute passes and topic 18's clustering dispatch,
        // then five per shadow cascade, then the depth-only pass they feed and
        // the colour pass that samples it.
        //
        // **The clustering pass is after the camera's clearing dispatch**, and
        // that is the ordering the overflow counter depends on: the clearing
        // pass zeroes the statistics word this one adds to, and both declare
        // the same buffer, so the graph is what puts the barrier between them.
        let mut expected: Vec<String> = Vec::new();
        for cascade in 0..=shadow::CASCADES {
            expected.extend(
                [
                    "clear-counters",
                    "cull",
                    "draw-args",
                    "draw-starts",
                    "draw-scatter",
                ]
                .into_iter()
                .map(str::to_string),
            );
            if cascade == 0 {
                expected.push("light-cluster".to_string());
            }
        }
        // And the culling-statistics copy **last**, after every pass that adds
        // to the buffer it reads — the cull dispatch, the clustering pass and
        // the amplification stage inside the colour pass.
        expected.extend(
            [
                "shadow",
                "depth-prepass",
                "ssao",
                "ssao-blur",
                // The reconstruction that ends the occlusion chain, between the
                // blur it reads and the pass that binds what it wrote — see
                // [`crate::ssao`]'s header on why the first two run smaller than
                // the frame and this one does not.
                "ssao-upsample",
                "forward",
                // The pyramid the march climbs, between the pass that wrote
                // level 0 and the pass that reads the chain. Two levels at this
                // extent, written out for the reason `crate::bloom`'s chain is
                // in the toggle test below: a table generated from
                // `crate::hiz::levels_for` could not fail.
                "hiz-1",
                "hiz-2",
                "ssr",
                "ssr-blur",
                "tonemap",
                // The resolve `RenderEffects::DEFAULT_STACK` carries, which is
                // CMAA2's three rather than FXAA's one —
                // `each_effect_toggle_removes_exactly_the_passes_it_owns` is
                // where the swap between the two tiers is pinned.
                "cmaa2-edges",
                "cmaa2-shapes",
                "cmaa2-apply",
                "cull-stats-readback",
            ]
            .into_iter()
            .map(str::to_string),
        );
        assert_eq!(
            passes, expected,
            "each cull's five compute passes come first, and in that order"
        );

        // **The depth prepass, not the colour pass**, and that is what says the
        // prepass really is the first thing to draw from the camera's cull: it is
        // where the draw buffers leave the compute pass's writes. The colour pass
        // below then needs none of these, because they are already in the state it
        // wants — which is the assertion after it.
        let prepass = compiled
            .passes()
            .iter()
            .find(|pass| pass.label() == "depth-prepass")
            .expect("the pass list above");
        let into_indirect = prepass
            .barriers()
            .buffers
            .iter()
            .filter(|barrier| barrier.to == ResourceState::IndirectArgument)
            .count();
        assert_eq!(
            into_indirect,
            2,
            "the arguments and the count, out of the compute pass's writes and into \
             the state a draw reads them in: {:?}",
            prepass.barriers().buffers
        );
        assert!(
            prepass.barriers().buffers.iter().any(|barrier| {
                barrier.from == ResourceState::ShaderReadWrite
                    && barrier.to == ResourceState::ShaderRead
            }),
            "and the runs, which the vertex stage reads: {:?}",
            prepass.barriers().buffers
        );

        let forward = compiled
            .passes()
            .iter()
            .find(|pass| pass.label() == "forward")
            .expect("the pass list above");
        assert!(
            forward
                .barriers()
                .buffers
                .iter()
                .all(|barrier| barrier.to != ResourceState::IndirectArgument),
            "the prepass draws from the same arguments, so the colour pass finds them \
             already in the state it wants — a barrier here would mean something between \
             the two put them back: {:?}",
            forward.barriers().buffers
        );
        // What the colour pass *does* still have to be given: the froxel grid,
        // which no earlier pass reads.
        assert!(
            forward.barriers().buffers.iter().any(|barrier| {
                barrier.from == ResourceState::ShaderReadWrite
                    && barrier.to == ResourceState::ShaderRead
            }),
            "and the froxel grid, which its fragment stage reads: {:?}",
            forward.barriers().buffers
        );

        let draw_args = compiled
            .passes()
            .iter()
            .find(|pass| pass.label() == "draw-args")
            .expect("the pass list above");
        assert!(
            draw_args.barriers().buffers.iter().any(|barrier| {
                barrier.from == ResourceState::ShaderReadWrite
                    && barrier.to == ResourceState::ShaderRead
            }),
            "and the visible list is ordered after the cull pass wrote it: {:?}",
            draw_args.barriers().buffers
        );

        // The compiled graph borrows the renderer's pass bodies, so it has to go
        // before the renderer does.
        drop(compiled);
        renderer.destroy(device.as_ref());
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// One more frame than the uniform ring is deep, so at least one lap both
    /// reuses a slot and follows a lap that already sampled the atlas.
    const SHADOW_LAPS: usize = FRAMES_IN_FLIGHT + 1;

    /// **Every frame's first barrier on the shadow atlas names what the previous
    /// frame left it in**, and the same for its placeholder.
    ///
    /// # Why this cannot be read off one frame
    ///
    /// The atlas is neither a transient nor a swapchain image. The pool never
    /// hands one out and has no description to size it from, and no acquire
    /// semaphore sits between one frame's use of it and the next — so
    /// [`ForwardRenderer::add_passes`] *declares* it, and the declaration is what
    /// makes the transition true.
    ///
    /// What it declares is [`imported_state`], the pool's record of what the
    /// last graph to *execute* left the image in, so [`InitialClaim::Tracked`]
    /// can only ever find the two agreeing for this one import — deliberately,
    /// because a declaration and an audit reading one value cannot drift apart
    /// the way a renderer-held copy of it could. The audit still has teeth
    /// elsewhere in this frame: `ssao-placeholder` and `probes` declare a
    /// constant, and `the_guard_still_catches_an_engine_import_that_lies` is
    /// what shows it fires on those.
    ///
    /// So neither mechanism says anything about the barriers on either side of
    /// the declaration — whether the frame that ran actually reached the state
    /// the ledger now claims, and whether the next frame's first barrier comes
    /// out of it — which is what the stream below is for.
    ///
    /// Declaring [`ResourceState::Undefined`] on a frame after the first is the
    /// failure this catches. It expands to `srcStageMask = NONE,
    /// srcAccessMask = NONE` (`crcbl_vk::conv::state_masks`), so the transition
    /// into the depth-only pass's attachment state orders against nothing — while
    /// the previous frame's colour pass is still sampling the very same image.
    /// Vulkan reports it as `SYNC-HAZARD-WRITE-AFTER-READ` with
    /// `read_barriers: 0`; every other backend resolves it however the driver
    /// likes.
    ///
    /// # Why the command stream is the observable
    ///
    /// Nothing above the seam can see a wrong declaration: the frame still
    /// renders, the golden still matches, and no state is ever read back. So this
    /// replays the recorded stream with a tracker, which is the same check a
    /// validation layer performs and needs no GPU at all — the shape
    /// `crcbl::screenshot`'s
    /// `every_readback_barrier_declares_the_state_the_image_is_actually_in` uses.
    /// One difference: `Undefined` is **not** waved through after the first
    /// touch. It is true for a swapchain image because the acquire's semaphore
    /// makes it true, and there is no such semaphore here.
    #[test]
    fn the_shadow_atlas_enters_each_frame_in_the_state_the_last_one_left_it() {
        use crcbl_hal::null::Command;

        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        let atlas = renderer.shadow_atlas();
        let placeholder = renderer.shadow_placeholder;
        let mut pool = crate::TransientPool::new();
        let imported = swapchain_image(device);
        let mut recorded = Vec::with_capacity(SHADOW_LAPS);

        for lap in 0..SHADOW_LAPS {
            renderer
                .begin_frame(
                    device,
                    &Camera::default(),
                    // **A different sun each lap**, so every lap redraws the
                    // atlas: this is a test about the barrier a frame that
                    // writes the image declares, and a lap that cached would
                    // record no pass and no transition at all. See
                    // [`moving_sun`].
                    &moving_sun(u32::try_from(lap).expect("a handful of laps")),
                    (64, 48),
                )
                .expect("write");
            let mut graph = crate::RenderGraph::new(queue);
            let target = graph.import_image("target", imported);
            renderer.add_passes(&mut graph, &pool, target, (64, 48));
            let compiled = graph.compile(&pool).expect("a legal frame");
            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
                label: Some("shadow lap"),
                queue,
            });
            compiled
                .execute(device, &mut pool, encoder.as_mut(), None)
                .expect("the graph executed");
            recorded.push(encoder.finish().expect("recording succeeded"));
        }

        // The two images the renderer owns across frames. A transient's state is
        // the pool's business and the fake swapchain image's is the acquire's, so
        // neither belongs in here.
        let mut tracked = [
            (atlas, ResourceState::Undefined),
            (placeholder, ResourceState::Undefined),
        ];
        let mut atlas_writes = 0usize;
        let mut named = 0usize;
        for command in recorder.commands() {
            let Command::Barrier { images, .. } = command else {
                continue;
            };
            for barrier in images {
                let Some((_, state)) = tracked
                    .iter_mut()
                    .find(|(handle, _)| *handle == barrier.image)
                else {
                    continue;
                };
                assert_eq!(
                    barrier.from, *state,
                    "a barrier declared {:?} -> {:?} on an image the frame before it left in \
                     {:?}. `Undefined` carries no source scope, so a transition declaring it \
                     orders against nothing and the previous frame's sampled read is still in \
                     flight underneath it.",
                    barrier.from, barrier.to, *state
                );
                if barrier.image == atlas && barrier.to == ResourceState::DepthStencilWrite {
                    atlas_writes += 1;
                }
                *state = barrier.to;
                named += 1;
            }
        }

        // Both halves of the loop above are silent on an empty stream, so the
        // shape it walked is asserted rather than assumed: one transition into
        // the depth-only pass's attachment state per lap, the last one included.
        assert_eq!(
            atlas_writes, SHADOW_LAPS,
            "{named} barrier(s) named the atlas or its placeholder across {SHADOW_LAPS} laps, \
             {atlas_writes} of them taking the atlas into DepthStencilWrite — every lap moved \
             the sun, so every lap redraws the atlas, and anything else means the loop above \
             asserted on a stream that does not contain the transition it is about"
        );
        let (_, ended) = tracked[0];
        assert_eq!(
            ended,
            ResourceState::ShaderRead,
            "the import promises to hand the atlas back in the state the next frame declares"
        );

        renderer.destroy(device);
        for commands in recorded {
            device.destroy_command_buffer(commands);
        }
        pool.destroy(device);
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// A renderer with a shadowed spot beside the sun's cascades and a caster
    /// for both to draw, which is the smallest scene the atlas cache has
    /// anything to say about: without a light tile the only maps are the
    /// cascades, and without a caster every tile is a clear.
    fn shadow_cache_scene(
        device: &dyn Device,
        queue: QueueHandle,
    ) -> (ForwardRenderer, InstanceHandle) {
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        // Pinned, on `set_shadow_cadence`'s own terms: the console's two limits
        // are process-global and `the_console_moves_both_limits` holds them at
        // a four-frame hold and three faces a frame for the length of its
        // check. A cache test reading the console inside that window reports
        // "did not settle" — seen in the wild on 2026-09-04, and reproduced by
        // holding both limits at those values inside the arm's own process,
        // which the pin makes harmless.
        renderer.set_shadow_cadence(Some(shadow::Cadence::EVERY_FRAME));
        let cube = place_cube(&mut renderer, Mat4::IDENTITY);
        renderer.set_lights(&[shadowable_spot(-1.0)]);
        (renderer, cube)
    }

    /// Draws one frame and answers whether it drew the shadow atlas, **read two
    /// ways that have to agree**.
    ///
    /// [`ForwardRenderer::shadow_atlas_cached`] is the renderer's own claim and
    /// the recorded stream is what the device was actually told; either on its
    /// own would be satisfied by a renderer that reported one thing and did the
    /// other, which is precisely the failure a cache has. `seen` is the cursor
    /// into the cumulative recorder, so each call reads its own frame.
    fn drew_the_atlas(
        recorder: &Recorder,
        seen: &mut usize,
        device: &dyn Device,
        renderer: &mut ForwardRenderer,
        queue: QueueHandle,
        camera: &Camera,
        sun: &DirectionalLight,
    ) -> bool {
        let drawn = frame_seen_from(device, renderer, queue, camera, sun);
        let claimed = renderer.shadow_atlas_cached();
        let commands = recorder.commands();
        let opened = commands[*seen..].iter().any(|command| {
            command
                .opens_pass()
                .is_some_and(|(_, label)| label == Some("shadow"))
        });
        *seen = commands.len();
        drawn.release(device);
        assert_eq!(
            opened,
            !claimed,
            "the renderer reports cached = {claimed} and its frame {} a pass labelled `shadow`",
            if opened { "opened" } else { "opened no" }
        );
        opened
    }

    #[test]
    fn shadow_preparation_retains_empty_scratch_after_redraw_and_cached_frames() {
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let (mut renderer, _) = shadow_cache_scene(device, queue);
        let camera = Camera::default();
        let sun = DirectionalLight::default();
        let mut seen = 0;
        assert!(drew_the_atlas(
            &recorder,
            &mut seen,
            device,
            &mut renderer,
            queue,
            &camera,
            &sun
        ));
        let capacity = (
            renderer.shadow_prepare_views.capacity(),
            renderer.shadow_prepare_culls.capacity(),
        );
        assert!(capacity.0 >= SHADOW_VIEWS && capacity.1 >= SHADOW_CULLS);
        assert!(renderer.shadow_prepare_views.is_empty());
        assert!(renderer.shadow_prepare_culls.is_empty());
        for _ in 0..FRAMES_IN_FLIGHT {
            assert!(!drew_the_atlas(
                &recorder,
                &mut seen,
                device,
                &mut renderer,
                queue,
                &camera,
                &sun
            ));
            assert!(renderer.shadow_prepare_views.is_empty());
            assert!(renderer.shadow_prepare_culls.is_empty());
            assert_eq!(
                (
                    renderer.shadow_prepare_views.capacity(),
                    renderer.shadow_prepare_culls.capacity()
                ),
                capacity
            );
        }
        for (step, view) in [0, 1, shadow_view(0, 0)].into_iter().enumerate() {
            // The spot moves for its own view and the camera for the cascades',
            // which are fitted to it: a moved spot alone is no input of theirs.
            renderer.set_lights(&[shadowable_spot(-2.0 - step as f32)]);
            let camera = Camera {
                eye: camera.eye + Vec3::X * 0.1 * (step + 1) as f32,
                ..camera
            };
            let slot = (renderer.frame + 1) % FRAMES_IN_FLIGHT;
            let short = device
                .create_buffer(&BufferDesc {
                    label: Some("refused shadow scratch test upload"),
                    size: std::mem::size_of::<f32>() as u64,
                    usage: BufferUsage::UNIFORM,
                    memory: MemoryLocation::HostUpload,
                })
                .unwrap();
            let original = std::mem::replace(&mut renderer.shadow_uniforms[slot][view], short);
            let before = recorder.buffer_bytes(short).unwrap();
            let result = renderer.begin_frame(device, &camera, &sun, TEST_EXTENT);
            renderer.shadow_uniforms[slot][view] = original;
            assert!(
                matches!(result, Err(HalError::InvalidDescriptor(ref cause)) if cause.contains("exceeds")),
                "observe a refused shadow uniform: {result:?}"
            );
            assert_eq!(recorder.buffer_bytes(short).unwrap(), before);
            assert!(!recorder.events().iter().any(
                |event| matches!(event, Event::BufferWritten { buffer, .. } if *buffer == short)
            ));
            assert!(renderer.shadow_prepare_views.is_empty());
            assert!(renderer.shadow_prepare_culls.is_empty());
            assert_eq!(
                (
                    renderer.shadow_prepare_views.capacity(),
                    renderer.shadow_prepare_culls.capacity()
                ),
                capacity
            );
            let refused_inputs = renderer.shadow_group_inputs.clone();
            device.destroy_buffer(short);
            recorder.assert_valid();
            assert!(drew_the_atlas(
                &recorder,
                &mut seen,
                device,
                &mut renderer,
                queue,
                &camera,
                &sun
            ));
            assert_eq!(renderer.shadow_group_inputs, refused_inputs);
            assert!(renderer.shadow_prepare_views.is_empty());
            assert!(renderer.shadow_prepare_culls.is_empty());
            assert_eq!(
                (
                    renderer.shadow_prepare_views.capacity(),
                    renderer.shadow_prepare_culls.capacity()
                ),
                capacity
            );
            assert!(!drew_the_atlas(
                &recorder,
                &mut seen,
                device,
                &mut renderer,
                queue,
                &camera,
                &sun
            ));
        }
        renderer.destroy(device);
        recorder.assert_valid();
        assert_eq!(recorder.total_live_objects(), 0);
    }

    /// **A frame over a scene nothing moved in does not draw the shadow atlas
    /// again**, and what it saves is the whole of the atlas's work.
    ///
    /// Topic 45's static-caching rung, and the observable it
    /// otherwise has none for: the map a cached frame samples is byte for byte
    /// the map the frame before it sampled, so no golden image and no readback
    /// can tell the two frames apart. The recorded command stream can — and the
    /// dispatch count is the half that says the *culls* went with the pass,
    /// rather than the frame still paying for the draws it decided not to
    /// record.
    #[test]
    fn a_frame_over_a_still_scene_does_not_draw_the_shadow_atlas_again() {
        use crcbl_hal::null::Command;

        // The blur count is a process-global console variable, and the frame's
        // draw count below includes the full-screen triangle each blur records
        // — so a concurrent test holding `r_ssao_blur_passes` at two would move
        // it under this one. Held rather than merely read, which is the
        // convention that variable's own test set.
        let _blurs = ssao_blur_switch();
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let (mut renderer, _) = shadow_cache_scene(device, queue);
        let camera = Camera::default();
        let sun = DirectionalLight::default();

        let mut seen = 0usize;
        let dispatches = |recorder: &Recorder, from: usize| {
            recorder.commands()[from..]
                .iter()
                .filter(|command| matches!(command, Command::Dispatch { .. }))
                .count()
        };

        let at = seen;
        assert!(
            drew_the_atlas(
                &recorder,
                &mut seen,
                device,
                &mut renderer,
                queue,
                &camera,
                &sun
            ),
            "the first frame of all has to draw the atlas: nothing has put anything in it"
        );
        let first = dispatches(&recorder, at);
        let drawing_draws = renderer.counters().draws;
        let buckets = renderer.bucket_constants.len() as u64;
        assert!(
            renderer.shadow_lights().base_of(0).is_some(),
            "the spot must hold a run for the count below to include a light slot's cull"
        );
        // The camera's own draw generation and topic 18's clustering dispatch,
        // plus a generation per cascade and one for the spot's slot.
        assert_eq!(
            first,
            DrawGen::DISPATCHES as usize * (2 + shadow::CASCADES) + 1 + RESOLVE_DISPATCHES,
            "the drawing frame did not record the culls this test is about skipping"
        );

        for round in 0..3 {
            let at = seen;
            assert!(
                !drew_the_atlas(
                    &recorder,
                    &mut seen,
                    device,
                    &mut renderer,
                    queue,
                    &camera,
                    &sun
                ),
                "round {round} redrew an atlas nothing had changed"
            );
            assert_eq!(
                dispatches(&recorder, at),
                DrawGen::DISPATCHES as usize + 1 + RESOLVE_DISPATCHES,
                "round {round} kept a shadow cull it had no pass to feed"
            );
            assert_eq!(
                drawing_draws - renderer.counters().draws,
                (shadow::CASCADES + 1) as u64 * buckets,
                "round {round}: the frame's own draw count did not lose exactly the atlas's \
                 calls — one per bucket per cascade, and one per bucket for the spot's tile"
            );
        }

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

    /// A cadence that holds every map one rung down for a frame, with the whole
    /// atlas's worth of tiles to spend.
    ///
    /// Pinned through [`ForwardRenderer::set_shadow_cadence`] rather than set on
    /// the console: [`shadow::r_shadow_cadence`] is process-global and the
    /// shadow pass is in every frame's pass list, so a test that moved it would
    /// change the frame every other test in this module draws.
    const HOLD_TWO: shadow::Cadence = shadow::Cadence {
        hold: 2,
        faces: shadow::TILES,
    };

    /// How the shadow pass loaded its depth attachment, over the commands from
    /// `from` on, and [`None`] where the frame recorded no such pass.
    ///
    /// **The observable the tile clear otherwise has none for.** A frame that
    /// kept a tile and a frame that redrew every one of them sample maps that
    /// may be identical, so nothing in the picture separates them; this is the
    /// declaration that says which the device was told.
    fn shadow_pass_depth_load(recorder: &Recorder, from: usize) -> Option<LoadOp> {
        use crcbl_hal::null::Command;

        recorder.commands()[from..].iter().find_map(|command| {
            let Command::BeginRenderPass {
                label,
                depth_stencil_attachment,
                ..
            } = command
            else {
                return None;
            };
            if label.as_deref() != Some("shadow") {
                return None;
            }
            depth_stencil_attachment
                .as_ref()
                .map(|attachment| attachment.depth_load)
        })
    }

    /// Direct draws recorded inside the shadow pass, over the commands from
    /// `from` on — which is one per tile the pass reset itself, the atlas's
    /// geometry being drawn indirectly.
    fn tile_clears_in_the_shadow_pass(recorder: &Recorder, from: usize) -> usize {
        use crcbl_hal::null::Command;

        let mut inside = false;
        let mut clears = 0;
        for command in &recorder.commands()[from..] {
            if let Some((_, label)) = command.opens_pass() {
                inside = label == Some("shadow");
                continue;
            }
            if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
                inside = false;
                continue;
            }
            if inside && matches!(command, Command::Draw { .. }) {
                clears += 1;
            }
        }
        clears
    }

    /// **The far cascade is redrawn every second frame and the near one every
    /// frame**, on a scene where the eye moves and so every map is out of date.
    ///
    /// Topic 45's cadence rung, and the observable it otherwise
    /// has none for: a held map draws a shadow one frame behind its caster,
    /// which is a plausible picture and one a golden accepts.
    ///
    /// The eye moves by a fraction of a cascade's own reach, so no frame is a
    /// reset — that is asserted rather than assumed, because a reset would make
    /// every frame redraw everything and this test would pass by having
    /// switched the cadence off.
    #[test]
    fn the_far_cascade_is_held_on_the_frames_between_its_turns() {
        let _blurs = ssao_blur_switch();
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let (mut renderer, _) = shadow_cache_scene(device, queue);
        let sun = DirectionalLight::default();
        renderer.set_shadow_cadence(Some(HOLD_TWO));

        const FRAMES: usize = 8;
        let mut near = 0;
        let mut far = 0;
        for step in 0..FRAMES {
            #[expect(
                clippy::cast_precision_loss,
                reason = "a handful of frames, and the step is what is wanted"
            )]
            let camera = Camera {
                eye: Camera::default().eye + Vec3::X * 0.05 * step as f32,
                ..Camera::default()
            };
            let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
            assert_eq!(
                renderer.shadow_cadence_reset(),
                step == 0,
                "frame {step}: only the first frame has an atlas to lay out, and a reset \
                 after it would redraw everything and leave nothing for the cadence to hold"
            );
            near += usize::from(renderer.shadow_cascade_redrawn(0));
            far += usize::from(renderer.shadow_cascade_redrawn(1));
            drawn.release(device);
        }
        assert_eq!(
            near, FRAMES,
            "the near cascade is fitted to the eye and is on the top rung: every frame"
        );
        assert_eq!(
            far,
            FRAMES / 2,
            "the far cascade is one rung down, so every second frame"
        );

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

    /// **A frame that keeps a tile loads the attachment and resets the tiles it
    /// redraws itself**, and a frame that keeps none clears it — which is what
    /// shipped.
    ///
    /// The half of the cadence a redraw count cannot see: holding a tile is only
    /// worth anything if the tile survives, and the one clear this seam has
    /// covers the whole image. A frame that loaded and reset nothing would draw
    /// into tiles still holding the last frame's depths, and under reversed-Z a
    /// caster that moved away would go on occluding.
    #[test]
    fn a_frame_that_keeps_a_tile_loads_the_attachment_and_resets_the_rest() {
        let _blurs = ssao_blur_switch();
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let (mut renderer, _) = shadow_cache_scene(device, queue);
        let sun = DirectionalLight::default();

        // The first frame lays the atlas out, so it clears and redraws
        // everything whatever the console says.
        let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
        first.release(device);
        assert_eq!(
            shadow_pass_depth_load(&recorder, 0),
            Some(LoadOp::Clear),
            "the frame that lays the atlas out has nothing to keep"
        );
        assert_eq!(
            tile_clears_in_the_shadow_pass(&recorder, 0),
            0,
            "and so resets no tile of its own"
        );

        renderer.set_shadow_cadence(Some(HOLD_TWO));
        let mut seen = recorder.commands().len();
        let mut loaded = 0;
        for step in 1..4 {
            #[expect(
                clippy::cast_precision_loss,
                reason = "a handful of frames, and the step is what is wanted"
            )]
            let camera = Camera {
                eye: Camera::default().eye + Vec3::X * 0.05 * step as f32,
                ..Camera::default()
            };
            let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
            let load = shadow_pass_depth_load(&recorder, seen).expect("a shadow pass");
            let clears = tile_clears_in_the_shadow_pass(&recorder, seen);
            let faces = renderer.shadow_faces_redrawn() as usize;
            if load == LoadOp::Load {
                loaded += 1;
                assert_eq!(
                    clears, faces,
                    "frame {step} loaded the attachment and reset {clears} of the {faces} \
                     tiles it redrew"
                );
                assert!(
                    faces < shadow::TILES,
                    "frame {step} loaded an attachment while redrawing every tile"
                );
            } else {
                assert_eq!(
                    clears, 0,
                    "frame {step} cleared the attachment and reset {clears} tiles again"
                );
            }
            seen = recorder.commands().len();
            drawn.release(device);
        }
        assert!(
            loaded > 0,
            "no frame kept a tile, so nothing here is about the load path"
        );

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

    /// A point light costs the budget every face it draws, not one.
    ///
    /// **The half of the budget its name is about.** `shadow_faces_redrawn` is
    /// a sum over the groups a frame redrew of the maps each of them owns, and
    /// a point light owns [`shadow::POINT_FACES`] of them. Every other check
    /// here is built on the sun and a spot, which own one map each — so a face
    /// count that answered `1` for every group would satisfy all of them, and
    /// did: collapsing it passed the whole of `crcbl-render` and the mesh e2e
    /// suite. This is what binds on the difference.
    #[test]
    fn a_point_light_costs_the_budget_every_face_it_draws() {
        let _blurs = ssao_blur_switch();
        let (_recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        let _cube = place_cube(&mut renderer, Mat4::IDENTITY);
        renderer.set_lights(&[shadowable_point(-1.0)]);
        let sun = DirectionalLight::default();

        // Every group is forced on the first frame — the image has held none of
        // them — so this counts what a full redraw actually costs.
        renderer.set_shadow_cadence(Some(shadow::Cadence::EVERY_FRAME));
        let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
        first.release(device);
        let point_faces = u32::try_from(shadow::POINT_FACES).expect("a handful of faces");
        assert!(
            renderer.shadow_lights().base_of(0).is_some(),
            "the point must hold a run of tiles, or there is no multi-face group to count"
        );
        assert!(
            renderer.shadow_faces_redrawn() >= point_faces,
            "a frame that redrew a point light's whole cube reported {} faces, fewer than the \
             {point_faces} it owns — so the budget is counting groups rather than the maps they \
             draw, and a cube would slip past a budget of one",
            renderer.shadow_faces_redrawn()
        );
    }

    /// **A frame never redraws more tiles than the budget allows**, and every
    /// map still gets its turn.
    ///
    /// The starvation half is what makes this more than an inequality: a
    /// schedule that spent the budget on the same maps every frame would satisfy
    /// the bound and never draw the rest at all.
    #[test]
    fn the_face_budget_bounds_a_frame_and_starves_no_map() {
        let _blurs = ssao_blur_switch();
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let (mut renderer, _) = shadow_cache_scene(device, queue);
        let sun = DirectionalLight::default();

        let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
        first.release(device);
        assert!(
            renderer.shadow_lights().base_of(0).is_some(),
            "the spot must hold a run, or the budget has only the cascades to bind on"
        );

        // One tile a frame: the two cascades and the spot's map cannot all fit,
        // so something is held on every frame of the run below.
        const BUDGET: u32 = 1;
        renderer.set_shadow_cadence(Some(shadow::Cadence {
            hold: 1,
            faces: BUDGET as usize,
        }));
        const FRAMES: usize = 12;
        let mut drew = [0usize; 3];
        for step in 1..=FRAMES {
            #[expect(
                clippy::cast_precision_loss,
                reason = "a handful of frames, and the step is what is wanted"
            )]
            let camera = Camera {
                eye: Camera::default().eye + Vec3::X * 0.02 * step as f32,
                ..Camera::default()
            };
            // The spot drifts too: its map is not fitted to the camera, so a
            // moving eye alone leaves it up to date and asking for nothing.
            #[expect(
                clippy::cast_precision_loss,
                reason = "a handful of frames, and the step is what is wanted"
            )]
            renderer.set_lights(&[shadowable_spot(-1.0 + 0.01 * step as f32)]);
            let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
            assert!(
                renderer.shadow_faces_redrawn() <= BUDGET,
                "frame {step} redrew {} tiles against a budget of {BUDGET}",
                renderer.shadow_faces_redrawn()
            );
            drew[0] += usize::from(renderer.shadow_cascade_redrawn(0));
            drew[1] += usize::from(renderer.shadow_cascade_redrawn(1));
            drew[2] += usize::from(renderer.shadow_slot_redrawn(0));
            drawn.release(device);
        }
        for (map, count) in drew.iter().enumerate() {
            assert!(
                *count > 0,
                "map {map} was never redrawn in {FRAMES} frames under a budget of \
                 {BUDGET}: {drew:?}"
            );
        }

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

    /// **A light that jumps further than its own radius resets the cadence**,
    /// and one that drifts inside it does not.
    ///
    /// Topic 45's "a moving light or camera cut resets it",
    /// made precise: a map whose centre has moved past the map's own reach is
    /// not a frame out of date, it is about somewhere else — so it is redrawn on
    /// the frame that notices rather than when its turn comes round. Both arms,
    /// because a reset that fired on every move would be the cadence switched
    /// off.
    #[test]
    fn a_light_that_jumps_past_its_own_radius_resets_the_cadence() {
        let _blurs = ssao_blur_switch();
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let (mut renderer, _) = shadow_cache_scene(device, queue);
        let sun = DirectionalLight::default();
        let camera = Camera::default();
        // The coarsest hold there is, so a redraw of the spot's map on the
        // frames below is the reset and not its turn.
        renderer.set_shadow_cadence(Some(shadow::Cadence {
            hold: 8,
            faces: shadow::TILES,
        }));

        let mut settle = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
        settle.release(device);
        for _ in 0..2 {
            settle = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
            settle.release(device);
        }
        assert!(
            !renderer.shadow_cadence_reset(),
            "the scene has settled, so nothing is about somewhere else"
        );

        // A drift well inside the light's own radius: out of date, not moved.
        renderer.set_lights(&[shadowable_spot(-1.0 + 0.5)]);
        let drifted = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
        drifted.release(device);
        assert!(
            !renderer.shadow_cadence_reset(),
            "a light that moved a sixteenth of its radius is a map a frame out of date"
        );

        // And a jump past it. `shadowable_spot`'s radius is what the reach is
        // taken from, so this is a light standing where its own map says
        // nothing.
        renderer.set_lights(&[shadowable_spot(-1.0 + 40.0)]);
        let jumped = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
        jumped.release(device);
        assert!(
            renderer.shadow_cadence_reset(),
            "a light that jumped five times its own radius must not hold its map"
        );
        assert!(
            renderer.shadow_slot_redrawn(0),
            "and the reset is only a reset if the map is actually redrawn"
        );

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

    /// **A console knob about *sampling* the atlas does not redraw it.**
    ///
    /// `r_shadow_filter` and `r_shadow_split` decide how the colour pass reads
    /// a map, and `r_shadow_bias` and `r_shadow_normal_offset` how far from a
    /// receiver it reads — and not one byte of what the depth pass writes into
    /// it is any of theirs. Yet the
    /// shadow views' blocks are the frame's block spread, and the cache record
    /// is those blocks' bytes — so until the views zeroed the row, a person
    /// typing `r_shadow_filter box` redrew every map in the atlas for nothing,
    /// and in this crate's own test process the filter tests moving that cell
    /// redrew the atlas under `each_thing_the_atlas_is_drawn_from_redraws_it`
    /// once in every five or six workspace runs on 2026-09-04. Holding the lock
    /// here is what makes the move below the only one in flight.
    #[test]
    fn a_moved_shadow_filter_leaves_a_still_atlas_alone() {
        let switch = shadow_filter_switch();
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let (mut renderer, _) = shadow_cache_scene(device, queue);
        let camera = Camera::default();
        let sun = DirectionalLight::default();
        let mut seen = 0usize;
        assert!(
            drew_the_atlas(
                &recorder,
                &mut seen,
                device,
                &mut renderer,
                queue,
                &camera,
                &sun
            ),
            "the first frame of all draws the atlas"
        );
        assert!(
            !drew_the_atlas(
                &recorder,
                &mut seen,
                device,
                &mut renderer,
                queue,
                &camera,
                &sun
            ),
            "a still second frame has to hold it, or the move below proves nothing"
        );

        switch.filter(shadow::Filter::Box);
        switch.seam(0.5);
        assert!(
            !drew_the_atlas(
                &recorder,
                &mut seen,
                device,
                &mut renderer,
                queue,
                &camera,
                &sun
            ),
            "`r_shadow_filter` and `r_shadow_split` moved and the atlas was drawn again: a \
             sampling knob reached the record of what the maps were drawn from"
        );

        // The bias pair sits in a different row of the same block, and the
        // second row it reaches is `Cascades::params`, which is rebuilt every
        // frame — so this is the arm that says the *whole* row is kept out of
        // the record rather than the one lane the filter is in.
        switch.bias(8.0);
        switch.offset(8.0);
        assert!(
            !drew_the_atlas(
                &recorder,
                &mut seen,
                device,
                &mut renderer,
                queue,
                &camera,
                &sun
            ),
            "`r_shadow_bias` and `r_shadow_normal_offset` moved and the atlas was drawn again: \
             the bias row reached the record of what the maps were drawn from"
        );

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

    /// **Every input the atlas is drawn from redraws it**, one at a time.
    ///
    /// The half that stops "cached everything, for ever" from passing every
    /// assertion above. Each arm moves exactly one thing and asserts the next
    /// frame draws again — and then holds still and asserts it stops, so an arm
    /// cannot pass by having broken the cache outright.
    ///
    /// The camera is in here because it is not obvious: a shadow map is drawn
    /// from a light, not from the eye. But a cascade is fitted to the camera's
    /// own frustum, and every shadow cull selects a DAG's detail at the camera's
    /// pixels — `SHADOW_LOD_BIAS` — so a moved eye is a different cascade, and a
    /// different light map wherever a DAG is in the light's cull.
    /// `shadow_reach`'s tests are the other half: what a moved eye or a moved
    /// caster must *not* redraw.
    ///
    /// `settles` is how many still frames it takes to go quiet again, and it is
    /// two for exactly one arm: `InstancePool`'s carry-forward puts a moved
    /// instance's `previous_transform` back at rest on the frame *after* the
    /// move, and that is a write, which is a change this record cannot tell
    /// from any other. See `InstancePool::take_written`, which says so.
    #[test]
    fn each_thing_the_atlas_is_drawn_from_redraws_it() {
        let camera = Camera::default();
        let sun = DirectionalLight::default();
        let moved_camera = Camera {
            eye: camera.eye + Vec3::X * 4.0,
            ..camera
        };
        type Change = fn(&mut ForwardRenderer, InstanceHandle);
        let arms: [(&str, Change, &Camera, &DirectionalLight, usize); 4] = [
            (
                "a caster moved",
                |renderer, cube| {
                    renderer.set_instance(
                        cube,
                        &InstanceDesc {
                            mesh: DEMO_CUBE,
                            material: DEMO_UNTINTED,
                            transform: Mat4::from_translation(Vec3::X),
                        },
                    );
                },
                &camera,
                &sun,
                2,
            ),
            (
                "a caster removed",
                |renderer, cube| renderer.remove_instance(cube),
                &camera,
                &sun,
                1,
            ),
            (
                "the light moved",
                |renderer, _| renderer.set_lights(&[shadowable_spot(1.5)]),
                &camera,
                &sun,
                1,
            ),
            ("the camera moved", |_, _| {}, &moved_camera, &sun, 1),
        ];

        for (what, change, camera, sun, settles) in arms {
            let (recorder, device, queue) = open();
            let device = device.as_ref();
            let (mut renderer, cube) = shadow_cache_scene(device, queue);
            let mut seen = 0usize;
            // Two frames, so the atlas is drawn and then held: the arm's own
            // assertion is about a frame that would otherwise have cached.
            for round in 0..2 {
                let drew = drew_the_atlas(
                    &recorder,
                    &mut seen,
                    device,
                    &mut renderer,
                    queue,
                    &Camera::default(),
                    &DirectionalLight::default(),
                );
                assert_eq!(
                    drew,
                    round == 0,
                    "{what}: the still frames before the change did not settle"
                );
            }

            change(&mut renderer, cube);
            assert!(
                drew_the_atlas(
                    &recorder,
                    &mut seen,
                    device,
                    &mut renderer,
                    queue,
                    camera,
                    sun
                ),
                "{what} and the atlas was not drawn again"
            );
            // And it goes quiet again in exactly `settles` frames, so the arm
            // cannot pass by having broken the cache rather than by having
            // invalidated it — and a change that started redrawing for ever
            // fails here rather than going unnoticed.
            for round in 0..settles {
                assert_eq!(
                    drew_the_atlas(
                        &recorder,
                        &mut seen,
                        device,
                        &mut renderer,
                        queue,
                        camera,
                        sun
                    ),
                    round + 1 < settles,
                    "{what}: the still frames after the change did not settle in {settles}"
                );
            }

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

    /// **A frame with a skinned object in it always redraws the atlas**, and
    /// that is a limit written down rather than a gap.
    ///
    /// A skinned caster's vertices are produced by a compute dispatch into the
    /// pool, so there is nothing on the host to compare: the palette a caller
    /// hands over is not the geometry, and the geometry is never read back. The
    /// honest answer is to redraw, and the dishonest one is a map of a pose the
    /// character has left.
    #[test]
    fn a_frame_with_a_skinned_object_never_caches_the_atlas() {
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut fixture = SkinnedFixture::build(device, queue);
        fixture.renderer.set_lights(&[shadowable_spot(-1.0)]);
        let imported = swapchain_image_at(device, TEST_EXTENT);
        let mut pool = crate::TransientPool::new();

        // The same palette and the same plan every lap, so nothing a host-side
        // comparison could see has moved.
        for lap in 0..3 {
            fixture.begin(device);
            let mut graph = crate::RenderGraph::new(queue);
            let target = graph.import_image("target", imported);
            fixture.renderer.add_skinned_passes(
                &mut graph,
                &pool,
                target,
                TEST_EXTENT,
                &fixture.skinning,
            );
            let compiled = graph.compile(&pool).expect("a legal frame");
            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
                label: Some("skinned lap"),
                queue,
            });
            compiled
                .execute(device, &mut pool, encoder.as_mut(), None)
                .expect("the graph executed");
            device.destroy_command_buffer(encoder.finish().expect("recording succeeded"));
            assert!(
                !fixture.renderer.shadow_atlas_cached(),
                "lap {lap} held a shadow map of a pose no host-side comparison can vouch for"
            );
        }

        fixture.destroy(device);
        pool.destroy(device);
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// **Switching the shadows off clears the atlas once, and then holds the
    /// clear**, which is the same cache answering a frame that draws nothing.
    ///
    /// The switched-off frame is not itself a cached frame: the pass has to run
    /// to write the reversed-Z clear that makes every comparison come back lit,
    /// and the image holds the last drawn maps until it does. What *is* cached
    /// is every frame after it, and the record for a switched-off frame is
    /// deliberately blind to the camera and the casters, because nothing about
    /// them reaches an atlas nothing draws into.
    #[test]
    fn switching_the_shadows_off_clears_the_atlas_once_and_then_holds_it() {
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let (mut renderer, cube) = shadow_cache_scene(device, queue);
        let camera = Camera::default();
        let sun = DirectionalLight::default();
        let mut seen = 0usize;

        assert!(
            drew_the_atlas(
                &recorder,
                &mut seen,
                device,
                &mut renderer,
                queue,
                &camera,
                &sun
            ),
            "the first frame draws the maps"
        );
        renderer.set_effect_request(EffectRequest {
            programmatic: EffectOverride::none().force(RenderEffects::SHADOWS, Some(false)),
            ..EffectRequest::default()
        });
        assert!(
            drew_the_atlas(
                &recorder,
                &mut seen,
                device,
                &mut renderer,
                queue,
                &camera,
                &sun
            ),
            "the frame that switched the shadows off has to run the pass that clears the maps \
             out of the image"
        );
        assert!(
            !drew_the_atlas(
                &recorder,
                &mut seen,
                device,
                &mut renderer,
                queue,
                &camera,
                &sun
            ),
            "a second switched-off frame cleared an atlas that was already clear"
        );
        // And nothing about the scene reaches a frame that draws no map: the
        // caster moves and the atlas is still the clear it was.
        renderer.set_instance(
            cube,
            &InstanceDesc {
                mesh: DEMO_CUBE,
                material: DEMO_UNTINTED,
                transform: Mat4::from_translation(Vec3::X),
            },
        );
        assert!(
            !drew_the_atlas(
                &recorder,
                &mut seen,
                device,
                &mut renderer,
                queue,
                &camera,
                &sun
            ),
            "a caster moved with the shadows off, and the frame cleared the atlas over again"
        );

        renderer.set_effect_request(EffectRequest::default());
        assert!(
            drew_the_atlas(
                &recorder,
                &mut seen,
                device,
                &mut renderer,
                queue,
                &camera,
                &sun
            ),
            "switching the shadows back on has to draw the maps the clear replaced"
        );

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

    /// **A frame the graph refuses leaves the shadow atlas where it was.**
    ///
    /// [`RenderGraph::compile`] returns a [`Result`], so a frame can be
    /// described in full and then thrown away, and
    /// [`CompiledGraph::execute`](crate::CompiledGraph::execute) — the only
    /// thing that writes the pool's ledger — never runs. That is the case a
    /// renderer-held `ResourceState`, stepped forward while the passes were
    /// declared, gets wrong: it would already say [`ResourceState::ShaderRead`]
    /// for an image no barrier has touched, and [`InitialClaim::Tracked`] cannot
    /// object, because with nothing recorded there is nothing to contradict. The
    /// guard would be silent on precisely the drift it exists to find, which is
    /// why [`imported_state`] reads the ledger instead of a second copy of it.
    ///
    /// The observable is the first barrier the *next* frame records on the
    /// atlas. `Undefined -> DepthStencilWrite` is the transition an image
    /// nothing has written needs; `ShaderRead -> DepthStencilWrite` names an old
    /// layout the image was never in, which is a layout mismatch on every
    /// backend and a discarded image on some.
    #[test]
    fn a_refused_frame_leaves_the_shadow_atlas_where_it_was() {
        use crcbl_hal::null::Command;

        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        let atlas = renderer.shadow_atlas();
        let placeholder = renderer.shadow_placeholder;
        let mut pool = crate::TransientPool::new();
        let imported = swapchain_image(device);

        // The refused frame: every pass a real frame declares, and beside them
        // one transient nothing reads or writes. `compile` answers
        // `UnusedTransient` and the whole description — the shadow atlas's
        // import included — is dropped without a command being recorded.
        renderer
            .begin_frame(
                device,
                &Camera::default(),
                &DirectionalLight::default(),
                (64, 48),
            )
            .expect("write");
        {
            let mut graph = crate::RenderGraph::new(queue);
            let target = graph.import_image("target", imported);
            renderer.add_passes(&mut graph, &pool, target, (64, 48));
            graph.create_image("orphan", crate::targets::scene_color((64, 48)));
            let refused = graph
                .compile(&pool)
                .expect_err("a transient no pass declares");
            assert!(
                matches!(refused, crate::GraphError::UnusedTransient { .. }),
                "the frame has to be refused for the reason this test is about — a graph that \
                 compiled would go on to execute and the ledger would be written after all: \
                 {refused:?}"
            );
        }
        assert_eq!(
            pool.imported_image_use(atlas),
            None,
            "nothing executed, so the ledger has nothing to say about the atlas — this is the \
             emptiness `InitialClaim::Tracked` cannot check against"
        );

        // And the frame after it, which does run.
        renderer
            .begin_frame(
                device,
                &Camera::default(),
                &DirectionalLight::default(),
                (64, 48),
            )
            .expect("write");
        let mut graph = crate::RenderGraph::new(queue);
        let target = graph.import_image("target", imported);
        renderer.add_passes(&mut graph, &pool, target, (64, 48));
        let compiled = graph.compile(&pool).expect("a legal frame");
        let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
            label: Some("frame after a refusal"),
            queue,
        });
        compiled
            .execute(device, &mut pool, encoder.as_mut(), None)
            .expect("the graph executed");
        let commands = encoder.finish().expect("recording succeeded");

        // The first barrier each of the two images gets. Only the refused frame
        // ran before this one and it recorded nothing, so these are the frame's
        // opening transitions.
        let mut opened: Vec<(crcbl_hal::ImageHandle, ResourceState, ResourceState)> = Vec::new();
        for command in recorder.commands() {
            let Command::Barrier { images, .. } = command else {
                continue;
            };
            for barrier in images {
                if barrier.image != atlas && barrier.image != placeholder {
                    continue;
                }
                if opened.iter().any(|(image, _, _)| *image == barrier.image) {
                    continue;
                }
                opened.push((barrier.image, barrier.from, barrier.to));
            }
        }
        for (image, from, to) in &opened {
            assert_eq!(
                *from,
                ResourceState::Undefined,
                "a barrier declared {from:?} -> {to:?} on an image the refused frame never gave a \
                 layout to. The declaration is what makes the transition true, so one that has \
                 moved on without an executed frame behind it names a source scope and an old \
                 layout the image was never in — and the ledger is empty, so nothing refuses it \
                 either. Image {image:?}"
            );
        }
        // The loop above is silent on an empty list and on a short one, and a
        // wrong declaration shortens it: an image declared in the state it is
        // wanted in needs no transition, so it drops out of the stream
        // altogether rather than appearing with the wrong source.
        assert_eq!(
            opened.len(),
            2,
            "the atlas and its placeholder are both imported every frame and both are wanted in a \
             state they are not in, so both have to be barriered: {opened:?}"
        );
        assert!(
            opened
                .iter()
                .any(|(image, _, to)| *image == atlas && *to == ResourceState::DepthStencilWrite),
            "and the atlas's is the shadow pass taking it as a depth attachment: {opened:?}"
        );

        renderer.destroy(device);
        device.destroy_command_buffer(commands);
        pool.destroy(device);
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// **The import audit still refuses an engine site whose declaration is
    /// wrong**, now that the shadow atlas's is read out of the same ledger it is
    /// checked against.
    ///
    /// That pair is deliberately circular and this test is what keeps it from
    /// swallowing the guard whole: `shadow-atlas` and `shadow-placeholder` say
    /// what [`imported_state`] just read, so [`InitialClaim::Tracked`] can only
    /// ever find them agreeing — their safety comes from there being one answer
    /// rather than from the check. Every *other* import in the frame declares a
    /// constant, and `ssao-placeholder` is the one this drives a ledger entry
    /// away from: uploaded into [`ResourceState::ShaderRead`] at build and
    /// declared so on every frame, so a graph that leaves it somewhere else is a
    /// declaration the next `compile` has to refuse.
    #[test]
    fn the_guard_still_catches_an_engine_import_that_lies() {
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        let mut pool = crate::TransientPool::new();
        let imported = swapchain_image(device);
        let occlusion = renderer.ambient_occlusion_placeholder.image;

        // A graph of this test's own, which moves the renderer's occlusion
        // placeholder somewhere `add_passes` does not expect. Same image handle,
        // so the entry it leaves in the ledger is the one the next `compile`
        // reads for `ssao-placeholder`.
        let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
            label: Some("move the placeholder"),
            queue,
        });
        {
            let mut graph = crate::RenderGraph::new(queue);
            let moved = graph.import_image(
                "moved-placeholder",
                ImportedImage {
                    image: occlusion,
                    view: renderer.ambient_occlusion_placeholder.view,
                    format: Format::Rgba8Unorm,
                    extent: (1, 1),
                    initial: ResourceState::ShaderRead,
                    claim: InitialClaim::Tracked,
                    final_state: ResourceState::TransferSrc,
                },
            );
            graph
                .add_copy_pass("read the placeholder")
                .use_image(moved, ResourceState::TransferSrc)
                .execute(|_| {});
            graph
                .compile(&pool)
                .expect("a legal frame")
                .execute(device, &mut pool, encoder.as_mut(), None)
                .expect("the graph executed");
        }
        let commands = encoder.finish().expect("recording succeeded");
        assert_eq!(
            pool.imported_image_use(occlusion),
            Some(ResourceState::TransferSrc),
            "the ledger has to have moved for the frame below to have anything to disagree with"
        );

        renderer
            .begin_frame(
                device,
                &Camera::default(),
                &DirectionalLight::default(),
                (64, 48),
            )
            .expect("write");
        let mut graph = crate::RenderGraph::new(queue);
        let target = graph.import_image("target", imported);
        renderer.add_passes(&mut graph, &pool, target, (64, 48));
        let refused = graph
            .compile(&pool)
            .expect_err("`ssao-placeholder` declares a constant the ledger no longer agrees with");
        let crate::GraphError::ImportStateMismatch {
            resource,
            declared,
            left,
        } = &refused
        else {
            panic!("the audit has to name the import it refused, not merely fail: {refused:?}");
        };
        assert_eq!(resource, "ssao-placeholder");
        assert_eq!(*declared, ResourceState::ShaderRead);
        assert_eq!(*left, ResourceState::TransferSrc);

        renderer.destroy(device);
        device.destroy_command_buffer(commands);
        pool.destroy(device);
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// Compiles one frame and names the passes it turned out to be, in order.
    ///
    /// Compiled and not executed: what a pass costs is not the question here,
    /// only which of them the frame declared. Names rather than a count since
    /// the toggles landed — a count says a frame lost two passes and a list says
    /// *which* two, which is the difference between "the switch did something"
    /// and "the switch did the thing it is for".
    fn passes_in_a_frame(
        device: &dyn Device,
        queue: QueueHandle,
        renderer: &mut ForwardRenderer,
        imported: ImportedImage,
        pool: &crate::TransientPool,
        extent: (u32, u32),
    ) -> Vec<String> {
        renderer
            .begin_frame(
                device,
                &Camera::default(),
                &DirectionalLight::default(),
                extent,
            )
            .expect("write");
        let mut graph = crate::RenderGraph::new(queue);
        let target = graph.import_image("target", imported);
        renderer.add_passes(&mut graph, pool, target, extent);
        graph
            .compile(pool)
            .expect("a legal frame")
            .passes()
            .iter()
            .map(|pass| pass.label().to_string())
            .collect()
    }

    /// A spot at `x` that [`shadow::Selection`] will give a tile: finite, a
    /// radius, a direction and a cone well inside the widest one allowed.
    /// A shadowed point light, which is [`shadow::POINT_FACES`] maps rather
    /// than one.
    ///
    /// The spot beside it is one tile and one face, so a scene built only from
    /// spots cannot tell a budget counting **faces** from one counting groups —
    /// which is what this exists to give a check something to bind on.
    fn shadowable_point(x: f32) -> Light {
        Light::Point(crate::light::PointLight {
            position: Vec3::new(x, 2.0, 0.0),
            radius: 8.0,
            color: Vec3::ONE,
            fill: false,
        })
    }

    fn shadowable_spot(x: f32) -> Light {
        Light::Spot(crate::light::SpotLight {
            position: Vec3::new(x, 2.0, 0.0),
            radius: 8.0,
            color: Vec3::ONE,
            direction: -Vec3::Y,
            inner_angle: 0.3,
            outer_angle: 0.6,
            fill: false,
        })
    }

    /// The page's anisotropy is the plan's default clamped to the device, and
    /// one on a device that was not granted the feature — whatever its limit
    /// says.
    ///
    /// The last arm is the one worth having: `gate_limits_on_features` narrows
    /// a declined feature's limit on `crcbl-vk`, but a backend that did not
    /// would report sixteen beside an absent feature, and a clamp that read the
    /// limit alone would ask for a sampler the device refuses.
    #[test]
    fn the_anisotropy_is_the_default_clamped_to_what_the_device_granted() {
        let caps = |features: Features, max_sampler_anisotropy: f32| DeviceCaps {
            features,
            limits: crcbl_hal::Limits {
                max_sampler_anisotropy,
                ..crcbl_hal::Limits::desktop()
            },
        };
        let granted = Features::SAMPLER_ANISOTROPY;
        assert!(
            (ForwardRenderer::anisotropy_for(&caps(granted, 16.0)) - DEFAULT_ANISOTROPY).abs()
                < f32::EPSILON,
            "a device above the default gets the default"
        );
        assert!(
            (ForwardRenderer::anisotropy_for(&caps(granted, 4.0)) - 4.0).abs() < f32::EPSILON,
            "a device below the default gets its own limit"
        );
        assert!(
            (ForwardRenderer::anisotropy_for(&caps(Features::empty(), 16.0)) - 1.0).abs()
                < f32::EPSILON,
            "a device that was not granted the feature gets one, whatever its limit says"
        );
    }

    /// A new anisotropy is a new sampler, and every slot moves onto it at its
    /// own frame — the old one living until the last slot has left it.
    ///
    /// Counted on the null recorder rather than looked at: the sampler count
    /// rises by one at the call, holds through every slot's frame but the
    /// last, and falls back there, while the live group count never moves at
    /// all — every rebuilt group replaced one. A rebuild that leaked, one that
    /// destroyed a group a slot in flight still held, and one that never
    /// happened each move one of those counts; a second lap of the ring
    /// creating any group at all would be a rebuild that did not know it was
    /// done.
    #[test]
    fn a_new_anisotropy_moves_each_slot_at_its_own_frame_and_retires_the_old() {
        let (recorder, device, queue) =
            open_with(Features::GPU_DRIVEN.union(Features::SAMPLER_ANISOTROPY));
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        assert!(
            (renderer.anisotropy() - DEFAULT_ANISOTROPY).abs() < f32::EPSILON,
            "a renderer nobody has called the setter on samples at the default"
        );
        let samplers = recorder.live_objects(ObjectKind::Sampler);
        let groups = recorder.live_objects(ObjectKind::BindGroup);
        let groups_created = || {
            recorder
                .events()
                .iter()
                .filter(|event| {
                    matches!(
                        event,
                        Event::Created {
                            kind: ObjectKind::BindGroup,
                            ..
                        }
                    )
                })
                .count()
        };

        renderer
            .set_anisotropy(device, DEFAULT_ANISOTROPY)
            .expect("the device allows it");
        assert_eq!(
            recorder.live_objects(ObjectKind::Sampler),
            samplers,
            "the value in force creates nothing"
        );

        renderer
            .set_anisotropy(device, 4.0)
            .expect("the device allows it");
        assert!((renderer.anisotropy() - 4.0).abs() < f32::EPSILON);
        assert_eq!(
            recorder.live_objects(ObjectKind::Sampler),
            samplers + 1,
            "the new sampler stands beside the one every slot still names"
        );
        assert_eq!(
            recorder.live_objects(ObjectKind::BindGroup),
            groups,
            "no group moves until its slot's frame"
        );

        for round in 0..FRAMES_IN_FLIGHT {
            renderer
                .begin_frame(
                    device,
                    &Camera::default(),
                    &DirectionalLight::default(),
                    (64, 48),
                )
                .expect("write");
            let expected = if round + 1 < FRAMES_IN_FLIGHT {
                samplers + 1
            } else {
                samplers
            };
            assert_eq!(
                recorder.live_objects(ObjectKind::Sampler),
                expected,
                "round {round}: the replaced sampler lives until the last slot has left it"
            );
            assert_eq!(
                recorder.live_objects(ObjectKind::BindGroup),
                groups,
                "round {round}: every rebuilt group replaced one"
            );
        }
        let created = groups_created();
        for _ in 0..FRAMES_IN_FLIGHT {
            renderer
                .begin_frame(
                    device,
                    &Camera::default(),
                    &DirectionalLight::default(),
                    (64, 48),
                )
                .expect("write");
        }
        assert_eq!(
            groups_created(),
            created,
            "a slot already on the sampler in force rebuilds nothing"
        );

        // The clamp: the device's ceiling above it, off below one, the default
        // for a value that is not a number.
        let ceiling = device.caps().limits.max_sampler_anisotropy;
        renderer
            .set_anisotropy(device, ceiling * 4.0)
            .expect("clamped to what the device allows");
        assert!((renderer.anisotropy() - ceiling).abs() < f32::EPSILON);
        renderer
            .set_anisotropy(device, 0.0)
            .expect("one is the value that turns it off");
        assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
        renderer
            .set_anisotropy(device, f32::NAN)
            .expect("the default is a sampler the device allows");
        assert!((renderer.anisotropy() - DEFAULT_ANISOTROPY).abs() < f32::EPSILON);

        recorder.assert_valid();
        renderer.destroy(device);
        assert_eq!(
            recorder.live_objects(ObjectKind::Sampler),
            0,
            "the samplers no slot ever adopted went with the renderer"
        );
    }

    /// A device without the feature samples isotropically whatever is asked:
    /// the ceiling is one, so the clamp lands on the value already in force and
    /// no sampler is created that `create_sampler` would refuse.
    #[test]
    fn a_device_without_the_feature_keeps_the_page_isotropic_whatever_is_asked() {
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        assert!(
            !device
                .caps()
                .features
                .contains(Features::SAMPLER_ANISOTROPY),
            "the default request does not name the feature"
        );
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
        let samplers = recorder.live_objects(ObjectKind::Sampler);

        renderer
            .set_anisotropy(device, DEFAULT_ANISOTROPY)
            .expect("asks for nothing the device lacks");
        assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
        assert_eq!(recorder.live_objects(ObjectKind::Sampler), samplers);
        renderer.destroy(device);
    }

    /// The knob clamps to the range it documents, in both directions and on a
    /// value that is neither.
    ///
    /// **The `NaN` arm is the one worth having.** A slider that divided by a
    /// zero, or a settings file that carried a nonsense string, reaches this
    /// with a value that fails every comparison it is put through — so a naive
    /// `clamp` would keep it, `internal_extent` would multiply by it, and the
    /// `as u32` below would produce a zero extent and a device error a long way
    /// from here.
    #[test]
    fn the_render_scale_is_clamped_to_the_range_it_documents() {
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");

        assert!(
            (renderer.render_scale() - 1.0).abs() < f32::EPSILON,
            "a renderer nobody has called the setter on draws at full scale"
        );

        renderer.set_render_scale(0.5);
        assert!((renderer.render_scale() - 0.5).abs() < f32::EPSILON);

        // Above one is supersampling, which this filter is the wrong one for.
        renderer.set_render_scale(2.0);
        assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);

        renderer.set_render_scale(0.01);
        assert!((renderer.render_scale() - MIN_RENDER_SCALE).abs() < f32::EPSILON);

        renderer.set_render_scale(f32::NAN);
        assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);
        renderer.set_render_scale(f32::INFINITY);
        assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);

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

    /// The internal extent is the target rounded, never zero, and is the target
    /// itself at full scale.
    ///
    /// **The floor is not decoration.** A transient image of zero extent is a
    /// device error rather than a small frame, and a 4×3 target at the minimum
    /// scale is exactly the arithmetic that would produce one.
    #[test]
    fn the_internal_extent_rounds_and_never_reaches_zero() {
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");

        assert_eq!(
            renderer.internal_extent((1920, 1080)),
            (1920, 1080),
            "full scale is the absence of the feature, not a resize by one"
        );

        renderer.set_render_scale(0.5);
        assert_eq!(renderer.internal_extent((1920, 1080)), (960, 540));

        // Rounds rather than truncating: 1920 * 0.7 is 1344, and 1080 * 0.7 is
        // 756 — both exact — so a target that does *not* divide evenly is what
        // shows the rounding. 1281 * 0.7 = 896.7.
        renderer.set_render_scale(0.7);
        assert_eq!(renderer.internal_extent((1281, 1080)), (897, 756));

        renderer.set_render_scale(MIN_RENDER_SCALE);
        assert_eq!(renderer.internal_extent((4, 3)), (1, 1));
        assert_eq!(
            renderer.internal_extent((0, 0)),
            (1, 1),
            "a minimised window is the caller's zero extent, and this may not \
             pass it through as one"
        );

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

    /// **The upscale is a pass below full scale and is not there above it**, and
    /// the frame is otherwise the same list.
    ///
    /// This is the observable the knob is: everything else about it — the
    /// clamps, the rounding — is arithmetic that could be right while the frame
    /// went on being drawn at the caller's extent. What says the feature works
    /// is that the pass appears, that it appears **last**, and that switching it
    /// off leaves the frame that was there before it existed.
    #[test]
    fn the_upscale_is_the_last_pass_and_only_below_full_scale() {
        let _blurs = ssao_blur_switch();
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        let imported = swapchain_image_at(device, TEST_EXTENT);
        let pool = crate::TransientPool::new();

        let full = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
        assert!(
            !full.contains(&"upscale".to_string()),
            "a frame at full scale has no upscale in it: {full:?}"
        );

        renderer.set_render_scale(0.5);
        let scaled = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
        assert_eq!(
            scaled.iter().filter(|label| *label == "upscale").count(),
            1,
            "a scaled frame records exactly one upscale: {scaled:?}"
        );
        // Last of the passes that draw. The statistics copy is genuinely after
        // it and says so — see the comment on `add_copy_pass`'s placement.
        let upscale = scaled
            .iter()
            .position(|label| label == "upscale")
            .expect("the assertion above");
        let tonemap = scaled
            .iter()
            .position(|label| label == "tonemap")
            .expect("every frame tonemaps");
        assert!(
            upscale > tonemap,
            "the upscale carries what the post chain ended with: {scaled:?}"
        );

        // **The pyramid gets shorter, and that is the evidence the rest of the
        // frame really is smaller.** Everything above this is about the last
        // pass; a knob that added an upscale while going on rendering at the
        // caller's extent would pass every one of those assertions and save
        // nothing. `crate::hiz`'s chain is as long as the extent allows, so the
        // level count is a number read out of the frame that can only be the
        // internal extent's.
        let levels = |passes: &[String]| {
            passes
                .iter()
                .filter(|label| label.starts_with("hiz-"))
                .count()
        };
        let internal = renderer.internal_extent(TEST_EXTENT);
        assert_eq!(levels(&full), crate::hiz::levels_for(TEST_EXTENT) as usize);
        assert_eq!(levels(&scaled), crate::hiz::levels_for(internal) as usize);
        assert!(
            levels(&scaled) < levels(&full),
            "at this extent the halved frame has to lose a level, or this \
             assertion is not looking at anything: {scaled:?}"
        );

        // And nothing else moved: an upscale is a pass added to the frame, not a
        // frame rebuilt around one. The pyramid is the one part that is a
        // function of the extent, so it is compared by the count above and
        // dropped from the list here.
        let without_hiz = |passes: &[String]| -> Vec<String> {
            passes
                .iter()
                .filter(|label| !label.starts_with("hiz-") && *label != "upscale")
                .cloned()
                .collect()
        };
        assert_eq!(
            without_hiz(&scaled),
            without_hiz(&full),
            "the scaled frame is the full-scale frame, one pass longer and one \
             pyramid shorter"
        );

        renderer.set_render_scale(1.0);
        let back = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
        assert_eq!(
            back, full,
            "the knob goes back, which is what a settings slider does"
        );

        renderer.destroy(device);
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// **A skinned-frame overlay receives the display and depth images at the
    /// internal extent, before either resolve reconstructs the target.**
    ///
    /// The callback's own pass attaches the display and depth it received. That
    /// makes matching dimensions a graph invariant rather than a comparison of
    /// numbers the callback could have been handed without ever using the
    /// images; changing either id to a target-sized image makes compilation
    /// refuse the mismatched attachments.
    #[test]
    fn an_overlay_uses_the_internal_display_and_depth_before_the_resolves() {
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut fixture = SkinnedFixture::build(device, queue);
        fixture.renderer.set_render_scale(0.5);
        fixture.renderer.set_effect_request(EffectRequest {
            antialiasing: Some(Antialiasing::Fxaa),
            ..EffectRequest::default()
        });
        fixture.begin(device);
        let internal_extent = fixture.renderer.internal_extent(TEST_EXTENT);

        let imported = swapchain_image_at(device, TEST_EXTENT);
        let mut pool = crate::TransientPool::new();
        {
            let mut graph = crate::RenderGraph::new(queue);
            let target = graph.import_image("target", imported);
            let mut received = None;
            fixture.renderer.add_skinned_passes_with_overlay(
                &mut graph,
                &pool,
                target,
                TEST_EXTENT,
                &fixture.skinning,
                |graph, targets| {
                    received = Some(targets);
                    graph
                        .add_render_pass("overlay-probe")
                        .color(
                            targets.display,
                            LoadOp::Load,
                            StoreOp::Store,
                            crcbl_hal::ClearValue::default(),
                        )
                        .depth_read(targets.depth)
                        .execute(|_| {});
                },
            );
            let received = received.expect("the overlay callback runs while the frame is built");
            assert_eq!(
                received.internal_extent, internal_extent,
                "the overlay receives the extent its display and depth attachments have"
            );

            let compiled = graph.compile(&pool).expect("the shared attachments match");
            let labels: Vec<&str> = compiled.passes().iter().map(|pass| pass.label()).collect();
            let overlay = labels
                .iter()
                .position(|label| *label == "overlay-probe")
                .expect("the callback's pass is part of the frame");
            let fxaa = labels
                .iter()
                .position(|label| *label == "fxaa")
                .expect("the requested resolve is part of the frame");
            let upscale = labels
                .iter()
                .position(|label| *label == "upscale")
                .expect("the half-scale frame reconstructs its target");
            assert!(
                overlay < fxaa && overlay < upscale,
                "the overlay must write display before its resolve and upscale: {labels:?}"
            );
        }

        fixture.destroy(device);
        pool.destroy(device);
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// **[`ForwardRenderer::MAX_PASSES`] bounds the frame, and lands on it.**
    ///
    /// It is what a caller sizes [`PassTimers`](crate::PassTimers) with, so both
    /// halves matter: a bound under the widest frame times part of it and drops
    /// the rest, and a bound well over it buys query sets nothing ever writes.
    /// A shadowable spot per light slot fills every one of them, which is the
    /// most culls a frame can run and so the widest frame there is — it must land
    /// exactly on the constant, and the frame with no shadowed light at all must
    /// be short of it by exactly the culls those slots would have added.
    ///
    /// The ground grid is switched on for **both** frames, because the widest
    /// frame is the one that has it: it is off by default and not a
    /// [`RenderEffects`] bit, so nothing else here would put its pass in. The
    /// debug draw layer is on for both frames for the same reason, and it needs
    /// a segment appended before each rather than one switch, because
    /// [`begin_frame`](ForwardRenderer::begin_frame) clears its buffer.
    ///
    /// **And the frames are drawn at [`WIDEST_EXTENT`] rather than at
    /// [`TEST_EXTENT`], with every effect forced on and the render scale off
    /// full.** The bloom chain's length is a function of the extent the frame is
    /// drawn at — see [`crate::bloom`] — so the widest frame this renderer
    /// records is a *large* one, and a bound checked against a 64×48 frame would
    /// sit six passes above what that frame runs and this assertion would have
    /// to be a `<=`. It is an `==` on purpose: a bound well over the widest
    /// frame buys query sets nothing writes, and only an exact comparison
    /// notices.
    ///
    /// **The render scale is what makes those two requirements compose.** The
    /// upscale is a pass only below full scale, and below full scale the chain
    /// runs at the *internal* extent — so a frame with both is one whose
    /// internal extent is the longest chain's, and whose target is larger than
    /// that. Halving a target of 2048×1024 is what arranges it, and the two
    /// assertions below check the arrangement rather than trusting it.
    ///
    /// [`WIDEST_EXTENT`]: fn@the_pass_bound_is_the_widest_frame_the_renderer_records
    #[test]
    fn the_pass_bound_is_the_widest_frame_the_renderer_records() {
        /// The extent whose bloom chain is the longest [`crate::bloom`] will
        /// build: six halvings of 512 leave sixteen by eight, which is still at
        /// or above that module's floor. The widest frame is drawn at this,
        /// which is why it is the internal one and not the target.
        const WIDEST_INTERNAL: (u32, u32) = (1024, 512);
        /// Half, so the frame records an upscale and draws at
        /// [`WIDEST_INTERNAL`].
        const WIDEST_SCALE: f32 = 0.5;
        /// The caller's extent: twice [`WIDEST_INTERNAL`] in each dimension.
        const WIDEST_EXTENT: (u32, u32) = (WIDEST_INTERNAL.0 * 2, WIDEST_INTERNAL.1 * 2);

        let (recorder, device, queue) = open();
        let device = device.as_ref();
        // **A scene whose probes ask to be updated**, because the widest frame
        // is the one with every pass in it and
        // the irradiance probes' two are recorded by a volume
        // rather than by an effect bit — the ground grid's argument exactly. A
        // renderer built on the demo's empty grid records neither, and the bound
        // would then be checked against a frame that could not reach it.
        let mut scene = scene::demo();
        scene.capacities.probes = 1;
        scene.probes = scene::ProbeGrid {
            volume: crcbl_shaders::probe::ProbeVolume {
                origin: [0.0; 3],
                inv_spacing: [1.0; 3],
                counts: [1, 1, 1],
                levels: 1,
                steps: crcbl_shaders::probe::ProbeSteps::default(),
            },
            probes: vec![crcbl_shaders::probe::GpuProbe::ZERO],
            update: ProbeUpdate::EveryFrame,
        };
        let mut renderer =
            ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &scene)
                .expect("built");
        // A maximum-width graph must include actual instances to cull.
        place_cube(&mut renderer, Mat4::IDENTITY);
        renderer
            .set_ground_grid(device, Some(GridStyle::default()))
            .expect("the null backend builds every pipeline");
        // **And the occlusion cull**, whose late prepass, farthest pyramid and
        // three late compute passes are the ground grid's kind of pass: off
        // unless a caller asks, and in the widest frame when one does.
        renderer.set_occlusion_culling(OcclusionCulling {
            occlusion: true,
            small_feature_pixels: None,
        });
        // **A body of water**, on the ground grid's terms: content rather than
        // an effect bit, so the widest frame is one a caller gave water to, and
        // `Water::PASSES` is in the bound for it.
        renderer
            .set_water(&[crcbl_water::WaterBody {
                outline: vec![[-1.0, -1.0], [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0]],
                level: 0.0,
                medium: crcbl_water::Medium {
                    absorption: [0.4, 0.1, 0.05],
                    scattering: [0.01, 0.01, 0.01],
                },
            }])
            .expect("a square meshes");
        // **A field of grass**, on the water body's terms exactly: content
        // rather than an effect bit, so the widest frame is one a caller gave a
        // field to and `Grass::PASSES` is in the bound for it.
        renderer
            .set_grass(
                device,
                queue,
                Some(
                    &crate::grass::GrassField::new(
                        [1, 1],
                        4.0,
                        [-2.0, -2.0],
                        50.0,
                        crate::grass::Heightfield {
                            texels: [4, 4],
                            metres_per_texel: 1.0,
                            origin: [-2.0, -2.0],
                            heights: vec![0.0; 16],
                        },
                        crate::grass::CoverMap {
                            texels: [4, 4],
                            metres_per_texel: 1.0,
                            origin: [-2.0, -2.0],
                            cover: vec![[255, 0]; 16],
                        },
                        // A shell row and a mesh blade row, so the widest
                        // frame records every look's draw the grass pass has.
                        [
                            crate::grass::BladeLook::Shells,
                            crate::grass::BladeLook::Blades,
                        ]
                        .map(|look| crate::grass::BladeType {
                            root_color: [0.05, 0.1, 0.02],
                            tip_color: [0.3, 0.5, 0.1],
                            height: 0.3,
                            half_width: 0.03,
                            height_spread: 0.3,
                            width_spread: 0.2,
                            look,
                            style: crate::grass::BladeStyle::PLAIN,
                            shape: crate::grass::BladeShape::STRAIGHT,
                            clumping: crate::grass::Clumping::NONE,
                        })
                        .to_vec(),
                    )
                    .expect("a real field"),
                ),
            )
            .expect("the null backend uploads every map");
        renderer.set_render_scale(WIDEST_SCALE);
        assert_eq!(
            renderer.internal_extent(WIDEST_EXTENT),
            WIDEST_INTERNAL,
            "the scale has to take the target to the extent whose chain is the \
             longest one, or the bound below is checked against a frame that \
             could not reach it"
        );
        // **Both post effects forced on.** Neither is in the default camera
        // stack — see [`RenderEffects::DEFAULT_STACK`], which leaves the lens out
        // for one reason and the resolve out for another — and the widest frame
        // is the one that has every effect in it, the ground grid's argument
        // exactly.
        renderer.set_effect_request(EffectRequest {
            programmatic: EffectOverride::none().force(OUTSIDE_THE_DEFAULT, Some(true)),
            ..EffectRequest::default()
        });
        let imported = swapchain_image_at(device, WIDEST_EXTENT);
        let mut pool = crate::TransientPool::new();

        // The debug draw layer on for both frames below, because it is a pass
        // the bound counts and no effect bit switches on — the ground grid's
        // argument again. A segment before each, since `begin_frame` clears the
        // buffer: the layer is immediate mode.
        let switch = debug_draw_switch();
        switch.set(true);
        // And the occlusion pair's second blur, for exactly that reason: it is a
        // pass [`Ssao::MAX_PASSES`] counts and no effect bit switches on, so a
        // frame at the shipping count comes one short of the bound and this test
        // would be asserting the bound against a frame that could not reach it.
        let blurs = ssao_blur_switch();
        blurs.set(i64::from(Ssao::MAX_BLUR_PASSES));
        // And the comparison seam, which is the occlusion chain's other
        // conditional pass — see `crate::ssao`'s `r_ssao_split`. Held for the
        // same reason the blur count is: the bound counts a frame that compares,
        // so a frame that does not could never reach it.
        let split = ssao_split_switch();
        split.set(0.5);
        renderer
            .debug_draw()
            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
        let bare =
            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, WIDEST_EXTENT).len();
        assert_eq!(
            crate::bloom::mips_for(WIDEST_INTERNAL),
            crate::bloom::MAX_MIPS,
            "the widest frame has to be one whose chain is the longest one there \
             is, or the bound below is checked against a frame that could not \
             reach it"
        );
        assert!(
            bare < ForwardRenderer::MAX_PASSES as usize,
            "a frame with no shadowed light runs {bare} passes, which is already the \
             bound of {} — then the bound does not cover the slots this scene left free",
            ForwardRenderer::MAX_PASSES
        );

        // One spot per slot, spaced so no two of them share an influence — the
        // list has to fill every slot or the bound below is checked against a
        // frame that could not reach it.
        #[expect(
            clippy::cast_precision_loss,
            reason = "a handful of slots, and the value is only a position"
        )]
        let spots: Vec<Light> = (0..shadow::LIGHT_SLOTS)
            .map(|slot| shadowable_spot(1.0 + slot as f32))
            .collect();
        renderer.set_lights(&spots);
        renderer
            .debug_draw()
            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
        let widest =
            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, WIDEST_EXTENT).len();
        assert_eq!(
            renderer.shadow_lights.slots().iter().flatten().count(),
            shadow::LIGHT_SLOTS,
            "the spots must actually hold every slot, or this is the bare frame again \
             under another name"
        );
        assert_eq!(
            widest,
            ForwardRenderer::MAX_PASSES as usize,
            "the widest frame is what the bound is for"
        );
        assert_eq!(
            widest - bare,
            DrawGen::MAX_PASSES as usize * shadow::LIGHT_SLOTS,
            "a filled slot costs a cull's passes and nothing else"
        );

        renderer.destroy(device);
        pool.destroy(device);
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// **A toggle reaches the recorded frame, and takes exactly its own passes
    /// with it.**
    ///
    /// The observable is the compiled pass list, because the thing that could
    /// otherwise be true is that the switch is stored and read by nothing: a
    /// renderer holding `SHADOWS` clear and recording every shadow cull anyway
    /// draws a frame that looks right, reports the right effect set, and has not
    /// switched anything off.
    ///
    /// So each arm compares the whole list rather than its length. Two passes
    /// fewer is satisfied by removing the wrong two, and it is satisfied by a
    /// frame that lost its tonemap.
    ///
    /// The shadow arm is the one that cannot be written by name — a cascade's
    /// cull passes are labelled exactly as the camera's are — so it is written as
    /// its two halves instead: the count moves by a cull's worth per cascade and
    /// per filled light slot, and everything from the `shadow` pass onwards is
    /// unchanged. The `shadow` pass itself **stays**, because it is what writes
    /// the clear that reads as "fully lit".
    #[test]
    fn each_effect_toggle_removes_exactly_the_passes_it_owns() {
        let _blurs = ssao_blur_switch();
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        place_cube(&mut renderer, Mat4::IDENTITY);
        // One shadowed light beside the cascades, so the shadow arm below covers
        // a light slot's cull as well as a cascade's.
        renderer.set_lights(&[shadowable_spot(-1.0)]);
        let imported = swapchain_image(device);
        let mut pool = crate::TransientPool::new();

        // [`OUTSIDE_THE_DEFAULT`] forced on and then `off` forced off, on
        // [`frame_switching_off`]'s terms exactly: the default camera stack
        // leaves both of them out — see [`RenderEffects::DEFAULT_STACK`] — so a
        // control built on the default alone would have nothing for their arms
        // to remove. `force` clears the other side, so an arm whose `off` is one
        // of them still resolves to off.
        //
        // [`frame_switching_off`]: fn@frame_switching_off
        let without = |renderer: &mut ForwardRenderer, off: RenderEffects| {
            renderer.set_effect_request(EffectRequest {
                programmatic: EffectOverride::none()
                    .force(OUTSIDE_THE_DEFAULT, Some(true))
                    .force(off, Some(false)),
                ..EffectRequest::default()
            });
            passes_in_a_frame(device, queue, renderer, imported, &pool, TEST_EXTENT)
        };

        let all_on = without(&mut renderer, RenderEffects::empty());
        assert_eq!(
            renderer.effects(),
            RenderEffects::all(),
            "the control frame has to be the every-effect one"
        );
        assert_eq!(
            renderer.shadow_lights.slots().iter().flatten().count(),
            1,
            "the spot must actually hold a slot, or the shadow arm below is only about cascades"
        );

        // **None of the three leaves anything behind it**, and for the same
        // reason: nothing reads what it would have written. The occlusion pair's
        // reader binds the 1×1 white placeholder instead — `mesh.slang` clamps
        // its `Load` into it — and the reflection pair's and the chain's readers
        // both tonemap whatever image they would have read anyway.
        //
        // The chain's labels are written out rather than built from
        // `crate::bloom`'s arithmetic, because a table generated from the code
        // under test cannot fail: it is `TEST_EXTENT`'s two levels — two
        // downsamples, the one upsample between them, and the composite — and if
        // that extent moves this is the assertion that says so.
        for (off, gone) in [
            (
                RenderEffects::AMBIENT_OCCLUSION,
                ["ssao", "ssao-blur", "ssao-upsample"].as_slice(),
            ),
            (
                RenderEffects::CONTACT_SHADOWS,
                // One pass and no blur — `crate::contact_shadows`'s header says
                // why the occlusion pair's second pass has no counterpart here.
                ["contact-shadows"].as_slice(),
            ),
            (
                RenderEffects::REFLECTIONS,
                // **The pyramid goes with the march**, which is the whole of
                // what makes it an optimisation rather than a resource: it is
                // recorded on the frames that reflect and on no others. Two
                // levels at `TEST_EXTENT`, written out on the chain's terms
                // above.
                ["hiz-1", "hiz-2", "ssr", "ssr-blur"].as_slice(),
            ),
            (
                RenderEffects::BLOOM,
                [
                    "bloom-down-1",
                    "bloom-down-2",
                    "bloom-up-1",
                    "bloom-composite",
                ]
                .as_slice(),
            ),
            (
                RenderEffects::AUTO_EXPOSURE,
                // All three go together and the tonemap stays: the pass reads
                // the measurement only when the block says to, and the block
                // says so on exactly the frames these three ran on.
                ["exposure-clear", "exposure-histogram", "exposure-reduce"].as_slice(),
            ),
        ] {
            let labels = without(&mut renderer, off);
            assert_eq!(
                renderer.effects(),
                RenderEffects::all().difference(off),
                "{off:?}: the frame must have resolved to the set the request asked for"
            );
            // **The control frame has to contain what this arm removes**, and
            // that is not a restatement of the comparison below: the comparison
            // builds `expected` by filtering `gone` out of `all_on`, so an arm
            // naming a pass the control never recorded filters nothing, matches,
            // and passes whether the effect draws anything or not. Removing the
            // resolve pass entirely left this loop green until this assertion
            // existed.
            for label in gone {
                assert!(
                    all_on.iter().any(|recorded| recorded == label),
                    "{off:?}: the every-effect frame does not record `{label}`, so removing it \
                     below proves nothing: {all_on:#?}"
                );
            }
            let expected: Vec<String> = all_on
                .iter()
                .filter(|label| !gone.contains(&label.as_str()))
                .cloned()
                .collect();
            assert_eq!(
                labels, expected,
                "{off:?}: the frame must lose {gone:?}, gain nothing in their place, and keep \
                 every other pass"
            );
        }

        // **The two antialiasing tiers share one resolve slot**, so neither is
        // a plain removal and neither belongs in the loop above: switching
        // CMAA2 off while FXAA stays on swaps three passes for one rather than
        // losing three, and the loop's "gain nothing in their place" comparison
        // is exactly what that violates. Three frames say it instead.
        let both = all_on.clone();
        let cheap = without(&mut renderer, RenderEffects::CMAA2);
        let neither = without(
            &mut renderer,
            RenderEffects::CMAA2.union(RenderEffects::ANTIALIASING),
        );
        const CMAA2_PASSES: [&str; 3] = ["cmaa2-edges", "cmaa2-shapes", "cmaa2-apply"];
        let resolve_of = |labels: &[String]| -> Vec<String> {
            labels
                .iter()
                .filter(|label| *label == "fxaa" || CMAA2_PASSES.contains(&label.as_str()))
                .cloned()
                .collect()
        };
        let without_resolve = |labels: &[String]| -> Vec<String> {
            labels
                .iter()
                .filter(|label| *label != "fxaa" && !CMAA2_PASSES.contains(&label.as_str()))
                .cloned()
                .collect()
        };
        assert_eq!(
            resolve_of(&both),
            CMAA2_PASSES.map(str::to_string).to_vec(),
            "with both bits set the higher tier takes the slot and the cheap one \
             records nothing"
        );
        assert_eq!(
            resolve_of(&cheap),
            vec!["fxaa".to_string()],
            "with only the cheap bit set the slot is FXAA's"
        );
        assert!(
            resolve_of(&neither).is_empty(),
            "with neither bit set the frame has no resolve at all: {neither:#?}"
        );
        // And nothing else moved: the tiers swap in one slot rather than
        // rebuilding the frame around themselves.
        assert_eq!(without_resolve(&both), without_resolve(&cheap));
        assert_eq!(without_resolve(&both), without_resolve(&neither));
        // The slot is where the ordering argument puts it — directly after the
        // last pass that writes the display image, which at this extent is the
        // tonemap.
        for labels in [&both, &cheap] {
            let at = labels
                .iter()
                .position(|label| label == "tonemap")
                .expect("a frame has to reach the swapchain");
            assert_eq!(
                &labels[at + 1..=at + resolve_of(labels).len()],
                resolve_of(labels).as_slice(),
                "the resolve must follow the tonemap: {labels:#?}"
            );
        }

        let no_shadows = without(&mut renderer, RenderEffects::SHADOWS);
        assert_eq!(
            renderer.effects(),
            RenderEffects::all().difference(RenderEffects::SHADOWS),
        );
        assert_eq!(
            all_on.len() - no_shadows.len(),
            DrawGen::MAX_PASSES as usize * (shadow::CASCADES + 1),
            "shadows off must drop a cull's passes per cascade and per filled slot"
        );
        let from_the_atlas = |labels: &[String]| {
            let at = labels
                .iter()
                .position(|label| label == "shadow")
                .expect("the atlas pass is recorded whether or not anything draws into it");
            labels[at..].to_vec()
        };
        assert_eq!(
            from_the_atlas(&no_shadows),
            from_the_atlas(&all_on),
            "only the culls go: the atlas pass and everything after it are unchanged"
        );

        renderer.destroy(device);
        pool.destroy(device);
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// **The contact march is a pass a frame records only when it was asked
    /// for, and the mask it writes is what the forward pass then reads.**
    ///
    /// Two observables, because either alone is satisfied by a mistake the other
    /// one catches:
    ///
    /// * **The compiled pass list.** `contact-shadows` appears between the
    ///   prepass whose depth it marches and the forward pass that binds it, and
    ///   appears at all only on the frame that asked. The toggle test above
    ///   already says a frame loses this pass and nothing else; what is added
    ///   here is *where* it sits, which is the half a set comparison cannot see
    ///   — a march recorded after the pass that reads it compiles and draws a
    ///   mask nothing ever looks at.
    /// * **The forward pass's own barriers.** On the frame that marched, one
    ///   more image is transitioned into [`ResourceState::ShaderRead`] before
    ///   the forward pass opens than on the frame that did not — which is the
    ///   mask leaving the colour attachment it was written as. That is what says
    ///   the pass's output reaches the shading, rather than being written into a
    ///   transient and dropped while the shader goes on reading the 1×1
    ///   placeholder. The placeholder is imported in `ShaderRead` already and
    ///   needs no transition, so it contributes nothing to this count and the
    ///   difference is exactly the mask.
    ///
    /// [`RenderEffects::CONTACT_SHADOWS`] is out of the default camera stack
    /// while its re-bless is pending — see that constant — so the `on` frame has
    /// to force it and the `off` frame is what a view saying nothing draws.
    #[test]
    fn the_contact_march_is_recorded_only_when_asked_and_its_mask_reaches_the_forward_pass() {
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        let imported = swapchain_image(device);
        let mut pool = crate::TransientPool::new();

        let frame = |renderer: &mut ForwardRenderer, on: bool| -> (Vec<String>, usize) {
            renderer.set_effect_request(EffectRequest {
                programmatic: EffectOverride::none()
                    .force(RenderEffects::CONTACT_SHADOWS, Some(on)),
                ..EffectRequest::default()
            });
            renderer
                .begin_frame(
                    device,
                    &Camera::default(),
                    &DirectionalLight::default(),
                    TEST_EXTENT,
                )
                .expect("write");
            let mut graph = crate::RenderGraph::new(queue);
            let target = graph.import_image("target", imported);
            renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
            let compiled = graph.compile(&pool).expect("a legal frame");
            let labels: Vec<String> = compiled
                .passes()
                .iter()
                .map(|pass| pass.label().to_string())
                .collect();
            let readable = compiled
                .passes()
                .iter()
                .find(|pass| pass.label() == "forward")
                .expect("every frame draws its geometry")
                .barriers()
                .images
                .iter()
                .filter(|barrier| barrier.to == ResourceState::ShaderRead)
                .count();
            (labels, readable)
        };

        let (marched, marched_reads) = frame(&mut renderer, true);
        assert!(
            renderer.effects().contains(RenderEffects::CONTACT_SHADOWS),
            "the forced frame has to have resolved with the bit set"
        );
        let (bare, bare_reads) = frame(&mut renderer, false);
        assert!(
            !renderer.effects().contains(RenderEffects::CONTACT_SHADOWS),
            "and the control frame without it"
        );

        assert!(
            !bare.iter().any(|label| label == "contact-shadows"),
            "a frame that did not ask must record no march at all: {bare:#?}"
        );
        let at = |labels: &[String], wanted: &str| {
            labels
                .iter()
                .position(|label| label == wanted)
                .unwrap_or_else(|| panic!("no `{wanted}` pass in {labels:#?}"))
        };
        let march = at(&marched, "contact-shadows");
        assert!(
            march > at(&marched, "depth-prepass"),
            "the march reads the prepass's depth, so it cannot precede it: {marched:#?}"
        );
        assert!(
            march < at(&marched, "forward"),
            "and the forward pass binds what it wrote, so it cannot follow it: {marched:#?}"
        );

        assert_eq!(
            marched_reads,
            bare_reads + 1,
            "the forward pass has to take one more image into `ShaderRead` on the frame that \
             marched — the mask. Equal counts mean the pass wrote a transient the shading \
             never reads."
        );

        renderer.destroy(device);
        pool.destroy(device);
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// **The ground grid is off until a caller asks, and then it is the last
    /// pass of the frame — after the tonemap.**
    ///
    /// Three claims and each is a separate way to get this wrong. Off by default
    /// is what keeps every sample and every golden image where they were. *After
    /// the tonemap* is the placement decision: added a line earlier it would
    /// draw into the HDR scene colour and be tonemapped like geometry, which
    /// compiles, draws a grid, and gives it a colour that moves with the
    /// exposure. And switching it off again has to remove the pass, not merely
    /// stop reporting it.
    ///
    /// The whole list is compared rather than its length, for the reason the
    /// effect-toggle test gives: one more pass is satisfied by gaining the wrong
    /// one.
    #[test]
    fn the_ground_grid_is_opt_in_and_lands_after_the_tonemap() {
        let _blurs = ssao_blur_switch();
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        let imported = swapchain_image(device);
        let mut pool = crate::TransientPool::new();

        let off = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
        assert!(
            renderer.ground_grid().is_none(),
            "a renderer nobody asked has no grid"
        );
        assert!(
            !off.contains(&"grid".to_string()),
            "the grid must not be in a frame nobody asked for it in: {off:#?}"
        );

        renderer
            .set_ground_grid(device, Some(GridStyle::default()))
            .expect("the null backend builds every pipeline");
        assert_eq!(renderer.ground_grid(), Some(&GridStyle::default()));
        let on = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);

        let mut expected = off.clone();
        // The statistics copy is added after every render pass and stays last —
        // see `add_passes`. So the grid goes in front of it, which is directly
        // after the tonemap.
        let tonemap = expected
            .iter()
            .position(|label| label == "tonemap")
            .expect("a frame has to reach the swapchain");
        expected.insert(tonemap + 1, "grid".to_string());
        assert_eq!(
            on, expected,
            "the grid must be the one pass gained, and it must sit after the tonemap"
        );

        renderer
            .set_ground_grid(device, None)
            .expect("switching off builds nothing");
        assert!(renderer.ground_grid().is_none());
        assert_eq!(
            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
            off,
            "switching the grid off has to remove its pass, not just stop reporting it"
        );

        renderer.destroy(device);
        pool.destroy(device);
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// **A second occlusion blur is a pass the frame records, an image it takes
    /// out of the pool, and a triangle its counter reports** — or it is a switch
    /// that does nothing.
    ///
    /// `crcbl`'s `forward_e2e::occlusion` measures what the second blur is worth
    /// by driving the pipelines itself, so nothing there would notice that a
    /// real frame never records it. The three things below are what a frame has
    /// to do differently, and each of them fails silently on its own: a missing
    /// pass draws a slightly rougher picture, a missing image is a bind of the
    /// wrong one, and a counter short by one is a number nobody reads until it
    /// is quoted.
    ///
    /// **This test owns `r_ssao_blur_passes` for its duration**, through
    /// [`ssao_blur_switch`] and for [`debug_draw_switch`]'s reason.
    /// The id [`Ssao::add_passes`] hands back is the reconstruction's target,
    /// whichever blur ran into it.
    ///
    /// **The one thing about that chain no other check can see.** The pass list
    /// is identical either way, the graph accepts a written-and-never-read
    /// transient without complaint, and every golden is at one blur where the
    /// two blur answers coincide — so a frame bound to the wrong image draws
    /// something nobody would question, which is exactly what the function's
    /// own doc warns about. Verified 2026-08-31 by returning `blurred` from the
    /// two-blur arm: `crcbl-render`'s unit tests, the forward and mesh e2e
    /// suites and lantern's golden all stayed green.
    ///
    /// **Since the halving it is a second silent failure and a louder one.**
    /// Every working image is [`crate::ssao::half_extent`] of the frame, so a
    /// returned working id is not merely a rougher channel — it is an image a
    /// quarter of the size bound where `mesh.slang` reads at `SV_Position`,
    /// which its clamp turns into occlusion smeared over the top-left quarter of
    /// the frame rather than into an error.
    #[test]
    fn the_occlusion_id_handed_back_is_the_reconstruction_target() {
        let (_recorder, device, queue) = open();
        let device = device.as_ref();
        let mut ssao = Ssao::new(device, 1, ForwardRenderer::build_fullscreen).expect("built");
        let gathered = crate::ssao::half_extent(TEST_EXTENT);

        let one = {
            let mut graph = crate::RenderGraph::new(queue);
            let depth = graph.create_image("scene-depth", crate::targets::scene_depth(TEST_EXTENT));
            let raw = graph.create_image("ssao", crate::targets::ambient_occlusion(gathered));
            let blurred =
                graph.create_image("ssao-blurred", crate::targets::ambient_occlusion(gathered));
            let upsampled = graph.create_image(
                "ssao-upsampled",
                crate::targets::ambient_occlusion(TEST_EXTENT),
            );
            let got = ssao.add_passes(
                &mut graph,
                0,
                TEST_EXTENT,
                depth,
                crate::ssao::OcclusionImages {
                    raw,
                    blurred,
                    again: None,
                    upsampled,
                },
            );
            (got == upsampled, got == blurred || got == raw)
        };
        assert!(one.0, "one blur finishes in the reconstruction's image");
        assert!(
            !one.1,
            "and never in one of the half-extent images the chain worked in"
        );

        let two = {
            let mut graph = crate::RenderGraph::new(queue);
            let depth = graph.create_image("scene-depth", crate::targets::scene_depth(TEST_EXTENT));
            let raw = graph.create_image("ssao", crate::targets::ambient_occlusion(gathered));
            let blurred =
                graph.create_image("ssao-blurred", crate::targets::ambient_occlusion(gathered));
            let again = graph.create_image(
                "ssao-blurred-2",
                crate::targets::ambient_occlusion(gathered),
            );
            let upsampled = graph.create_image(
                "ssao-upsampled",
                crate::targets::ambient_occlusion(TEST_EXTENT),
            );
            let got = ssao.add_passes(
                &mut graph,
                0,
                TEST_EXTENT,
                depth,
                crate::ssao::OcclusionImages {
                    raw,
                    blurred,
                    again: Some(again),
                    upsampled,
                },
            );
            (got == upsampled, got == again || got == blurred)
        };
        assert!(
            two.0,
            "two blurs finish in the reconstruction's image as well, which is the id the forward \
             pass binds"
        );
        assert!(
            !two.1,
            "and not in a blur's own image -- a frame bound to one of those is a frame nobody \
             would question"
        );
    }

    /// **The gather runs at half the frame and the reconstruction runs at all
    /// of it** — or the halving is a description nobody rendered into.
    ///
    /// The pass list cannot see this: three passes with the right labels in the
    /// right order is exactly what a chain that halved nothing would record. The
    /// **render area** is where the halving is observable, and the graph derives
    /// it from each pass's colour attachment — so this is the check that the
    /// transients [`ForwardRenderer::add_passes`] created are the ones
    /// [`crate::ssao::half_extent`] sized, and that the reconstruction was given
    /// the frame-sized one.
    ///
    /// Neither mistake is an error anywhere else. Working images at the frame's
    /// extent are four times the march and a reconstruction reading the corner
    /// of its input; a frame-sized image handed to the march and a half-sized
    /// one to the forward pass is occlusion smeared over a quarter of the
    /// picture by `mesh.slang`'s clamp. Both are pictures.
    ///
    /// **This test owns `r_ssao_blur_passes` for its duration**, through
    /// [`ssao_blur_switch`] and for that function's second reason: it looks the
    /// occlusion chain's passes up by name, and a second blur arriving from
    /// another thread's switch is a pass this frame did not ask for.
    #[test]
    fn the_occlusion_chain_gathers_at_half_the_frame_and_reconstructs_at_all_of_it() {
        let _switch = ssao_blur_switch();

        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        let imported = swapchain_image(device);
        let mut pool = crate::TransientPool::new();
        renderer
            .begin_frame(
                device,
                &Camera::default(),
                &DirectionalLight::default(),
                TEST_EXTENT,
            )
            .expect("write");
        let mut graph = crate::RenderGraph::new(queue);
        let target = graph.import_image("target", imported);
        renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
        let compiled = graph.compile(&pool).expect("a legal frame");
        let area_of = |label: &str| {
            let pass = compiled
                .passes()
                .iter()
                .find(|pass| pass.label() == label)
                .unwrap_or_else(|| panic!("the frame records no `{label}` pass at all"));
            let area = pass.render_area();
            (area.width, area.height)
        };

        let gathered = crate::ssao::half_extent(TEST_EXTENT);
        assert_ne!(
            gathered, TEST_EXTENT,
            "the fixture extent has to halve to something else, or every assertion below holds \
             of a chain that halved nothing"
        );
        assert_eq!(
            area_of("ssao"),
            gathered,
            "the march has to run over the gather extent"
        );
        assert_eq!(
            area_of("ssao-blur"),
            gathered,
            "and so does the blur over what the march wrote"
        );
        assert_eq!(
            area_of("ssao-upsample"),
            TEST_EXTENT,
            "the reconstruction writes the channel `mesh.slang` reads at `SV_Position`, so it \
             runs at the frame's own extent"
        );

        drop(compiled);
        renderer.destroy(device);
        pool.destroy(device);
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// **The comparison seam records a second march, scissored to the columns
    /// the first one was kept off.**
    ///
    /// `crate::split`'s geometry, read off the encoder rather than off the code
    /// that drove it: two passes, and two `SetScissor` rectangles that tile the
    /// gather extent between them.
    ///
    /// **What this cannot see is which block each march bound.** The reference
    /// backend records a bind group as a handle and a layout, not as the
    /// resources behind it, so pointing both marches at one buffer leaves this
    /// test green — measured, by doing exactly that. The group inequality below
    /// is kept because it is free and would catch the two marches sharing a
    /// cache, which is a different fault; what covers the blocks is
    /// `crate::ssao`'s `the_seams_other_side_is_what_the_chain_ships`, and what
    /// is not covered at all is the wiring between them. `docs/backlog.md`
    /// carries that gap.
    ///
    /// **The control is the same frame without a seam**, and it is what makes
    /// the assertions mean anything: a chain that scissored unconditionally
    /// would satisfy every claim below and change every golden in the workspace,
    /// so the frame nobody asked to compare has to record one march and set no
    /// rectangle at all.
    ///
    /// Holds [`ssao_split_switch`] for [`ssao_blur_switch`]'s reason: the seam
    /// is process-wide state and a frame that picked one up from another
    /// thread's test is a frame with a pass this one did not ask for.
    #[test]
    fn the_comparison_seam_marches_twice_over_columns_that_tile_the_gather() {
        use crcbl_hal::null::Command;

        let _blurs = ssao_blur_switch();
        let split = ssao_split_switch();
        // Third, after the two above: the only other test that takes this one
        // takes it alone, so this is the whole order and there is no cycle in
        // it. Moved below, because two blocks holding the same scalars are
        // equal whatever the seam did.
        let slices = ssao_slice_switch();
        // The count the seam's far side reads, and one that is not it. Read off
        // the variable rather than written down: which end of the range ships
        // has changed once already, and a test naming the wrong end would be
        // comparing the shipped configuration against itself.
        let ships = match crate::ssao::r_ssao_slices.default() {
            crcbl_console::Value::Int(count) => *count,
            other => panic!("`r_ssao_slices` defaults to {other:?}, which is not a count"),
        };
        let moved = if ships == i64::from(ssao::SLICE_COUNT_MAX) {
            i64::from(ssao::SLICE_COUNT_DEFAULT)
        } else {
            i64::from(ssao::SLICE_COUNT_MAX)
        };
        assert_ne!(
            ships, moved,
            "the two slice counts this compares are one count, so the blocks below would differ \
             by nothing whatever the seam did"
        );
        slices.set(ships);

        let gathered = crate::ssao::half_extent(TEST_EXTENT);
        // One entry per march the frame recorded: the last rectangle that pass
        // left the scissor at, and the group it bound.
        //
        // **The last and not the only one.** The graph opens every pass with a
        // scissor over the whole render area, so a march that sets none of its
        // own still records one — which is why "did it scissor at all" is not
        // the question and "what did it end up cropped to" is.
        let marches = |recorder: &Recorder, from: usize| {
            let mut inside = false;
            let mut found: Vec<(crcbl_hal::Rect2d, crcbl_hal::BindGroupHandle)> = Vec::new();
            let mut rect = None;
            let mut group = None;
            for command in &recorder.commands()[from..] {
                if let Some((_, label)) = command.opens_pass() {
                    inside = matches!(label, Some("ssao" | "ssao-shipped"));
                    (rect, group) = (None, None);
                    continue;
                }
                if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
                    if let (true, Some(rect), Some(group)) = (inside, rect, group) {
                        found.push((rect, group));
                    }
                    inside = false;
                    continue;
                }
                if !inside {
                    continue;
                }
                match command {
                    Command::SetScissor(at) => rect = Some(*at),
                    Command::BindGroup { group: bound, .. } => group = Some(*bound),
                    _ => {}
                }
            }
            found
        };

        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");

        split.set(0.0);
        let alone = frame_seen_from(
            device,
            &mut renderer,
            queue,
            &Camera::default(),
            &DirectionalLight::default(),
        );
        let plain = marches(&recorder, 0);
        let after = recorder.commands().len();
        let (console, shipped) = renderer.primary.ssao.blocks(renderer.frame);
        let (uncompared_console, uncompared_shipped) = (
            recorder.buffer_bytes(console).expect("the console's block"),
            recorder.buffer_bytes(shipped).expect("the seam's block"),
        );
        alone.release(device);

        split.set(0.5);
        slices.set(moved);
        let frame = frame_seen_from(
            device,
            &mut renderer,
            queue,
            &Camera::default(),
            &DirectionalLight::default(),
        );
        let compared = marches(&recorder, after);
        let (console, shipped) = renderer.primary.ssao.blocks(renderer.frame);
        let (compared_console, compared_shipped) = (
            recorder.buffer_bytes(console).expect("the console's block"),
            recorder.buffer_bytes(shipped).expect("the seam's block"),
        );
        frame.finish(device, renderer);

        assert_eq!(
            plain.len(),
            1,
            "a frame comparing nothing recorded {} march(es); the seam is off, so there is one",
            plain.len()
        );
        assert_eq!(
            (
                plain[0].0.x,
                plain[0].0.y,
                plain[0].0.width,
                plain[0].0.height
            ),
            (0, 0, gathered.0, gathered.1),
            "a frame comparing nothing left its march cropped to something other than the whole \
             gather extent {gathered:?} — so the chain crops whether or not anybody asked it to, \
             and every golden in this workspace was blessed on a frame that does not"
        );

        assert_eq!(
            compared.len(),
            2,
            "a frame comparing two configurations recorded {} march(es)",
            compared.len()
        );
        let (left, right) = (compared[0].0, compared[1].0);
        assert_eq!(
            (left.x, left.y, right.y),
            (0, 0, 0),
            "both halves start at the top and the left one at the edge"
        );
        assert_eq!(
            i64::from(right.x),
            i64::from(left.width),
            "the second march starts where the first one ended, or a column is drawn twice"
        );
        assert_eq!(
            (left.width + right.width, left.height, right.height),
            (gathered.0, gathered.1, gathered.1),
            "the two rectangles have to cover the gather extent {gathered:?} exactly"
        );
        assert!(
            left.width < gathered.0 && right.width < gathered.0,
            "one half covers the whole extent, so the other draws over it and the seam is a \
             rectangle that crops nothing"
        );
        assert_ne!(
            compared[0].1, compared[1].1,
            "the two marches bound one group, so they cannot be reading two blocks"
        );

        // How far the reference backend can follow the far side. It will say
        // what bytes a buffer holds and it will not say which buffer a group
        // names, so the two together are "there are two blocks, and they differ
        // by the knob that was moved" — not "the right march read the right
        // one". Pointing both marches at one buffer still passes; see this
        // module's entry in `docs/backlog.md`.
        assert_eq!(
            uncompared_console, uncompared_shipped,
            "the console sat at its defaults and the two blocks still differ, so the seam's far \
             side is not this frame with the shipped scalars — it is another frame"
        );
        assert_ne!(
            compared_console, compared_shipped,
            "one slice count was moved off the shipped one and both blocks still hold the same \
             bytes, so a comparison shows the same picture twice"
        );

        recorder.assert_valid();
    }

    /// Every gather pipeline the frame bound, in the order the marches ran.
    ///
    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]'s
    /// `marches` closure asking the other question of the same stream: that one
    /// reads the scissor and the group, and this one reads the pipeline. Only
    /// the `ssao` and `ssao-shipped` passes are looked at, because every other
    /// pass in the chain binds a pipeline too and a filter over the whole stream
    /// would be counting blurs.
    ///
    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]: fn@the_comparison_seam_marches_twice_over_columns_that_tile_the_gather
    fn gathers_bound(recorder: &Recorder, from: usize) -> Vec<crcbl_hal::GraphicsPipelineHandle> {
        use crcbl_hal::null::Command;

        let mut inside = false;
        let mut found = Vec::new();
        for command in &recorder.commands()[from..] {
            if let Some((_, label)) = command.opens_pass() {
                inside = matches!(label, Some("ssao" | "ssao-shipped"));
                continue;
            }
            if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
                inside = false;
                continue;
            }
            if let (true, Command::BindGraphicsPipeline(pipeline)) = (inside, command) {
                found.push(*pipeline);
            }
        }
        found
    }

    /// **`r_ssao_technique` decides which shader the gather runs**, read off the
    /// pipeline the `ssao` pass bound.
    ///
    /// The observable `docs/backlog.md` says the uniform block cannot have. The
    /// reference backend records a bind group as a handle and a layout rather
    /// than as the resources behind it, so nothing can ask which *block* a march
    /// read — but a pipeline is recorded as itself, so which *technique* a march
    /// ran is a question this backend answers. `Ssao::gathers` is what names the
    /// two, so this is an equality against the pipeline built from each shader
    /// rather than an inequality that any two handles would satisfy.
    ///
    /// **The default arm is the load-bearing half.** A selector that read the
    /// wrong variable, or a `pipeline_for` whose arms were swapped, would still
    /// change the frame when the console moved; what would go with it is every
    /// golden in this workspace, which is blessed on the technique that ships.
    ///
    /// Holds [`ssao_blur_switch`] for its own reason and
    /// [`ssao_technique_switch`] third, after it and [`ssao_split_switch`] —
    /// see `crate::ssao::TECHNIQUE_SWITCH` on the order.
    #[test]
    fn the_occlusion_technique_picks_the_gathers_pipeline() {
        let _blurs = ssao_blur_switch();
        let _seam = ssao_split_switch();
        let technique = ssao_technique_switch();
        // The name to move to, taken out of the variable's own set — see
        // `other_technique_name`.
        let other = other_technique_name();

        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        let (ships, cheap) = renderer.primary.ssao.gathers();
        assert_ne!(
            ships, cheap,
            "the renderer built one gather pipeline for both techniques, so nothing below can \
             tell them apart"
        );

        let shipped = frame_seen_from(
            device,
            &mut renderer,
            queue,
            &Camera::default(),
            &DirectionalLight::default(),
        );
        let by_default = gathers_bound(&recorder, 0);
        let after = recorder.commands().len();
        shipped.release(device);

        technique.set(other);
        let moved_frame = frame_seen_from(
            device,
            &mut renderer,
            queue,
            &Camera::default(),
            &DirectionalLight::default(),
        );
        let moved = gathers_bound(&recorder, after);
        moved_frame.finish(device, renderer);

        assert_eq!(
            by_default,
            vec![ships],
            "a frame nobody has touched the console on gathered through something other than \
             `ssao.slang`'s pipeline, which is what every golden in this workspace was blessed on"
        );
        assert_eq!(
            moved,
            vec![cheap],
            "`r_ssao_technique {other}` left the frame gathering through the pipeline \
             it gathered through before, so the selector reaches nothing"
        );
        recorder.assert_valid();
    }

    /// **The comparison seam's two marches run two techniques**, which is what
    /// the seam was built for.
    ///
    /// Alcove's second milestone is SSAO and GTAO in
    /// one frame, and this is that claim as a pair of pipeline handles: with the
    /// technique moved the near side runs the cheap tier and the far side the
    /// one that ships, and with it at its default both marches run the same
    /// shader and the seam separates nothing.
    ///
    /// **The control is the frame at the default**, and it is what makes the
    /// first half mean anything: a far side that always ran `ssao.slang` would
    /// satisfy the inequality below whatever `shipped_technique` did, and a
    /// chain that had simply forgotten to pass the far side a pipeline of its
    /// own would too.
    #[test]
    fn the_comparison_seam_marches_through_two_techniques() {
        let _blurs = ssao_blur_switch();
        let seam = ssao_split_switch();
        let technique = ssao_technique_switch();
        let other = other_technique_name();

        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        let (ships, cheap) = renderer.primary.ssao.gathers();

        seam.set(0.5);
        let compared = frame_seen_from(
            device,
            &mut renderer,
            queue,
            &Camera::default(),
            &DirectionalLight::default(),
        );
        let one_technique = gathers_bound(&recorder, 0);
        let after = recorder.commands().len();
        compared.release(device);

        technique.set(other);
        let frame = frame_seen_from(
            device,
            &mut renderer,
            queue,
            &Camera::default(),
            &DirectionalLight::default(),
        );
        let two_techniques = gathers_bound(&recorder, after);
        frame.finish(device, renderer);

        assert_eq!(
            one_technique,
            vec![ships, ships],
            "a seam with the technique at its default has to march the shipped gather twice — \
             both sides read `shipped`'s configuration, and the picture is one technique either \
             side of a line"
        );
        assert_eq!(
            two_techniques,
            vec![cheap, ships],
            "with `r_ssao_technique {other}` the near side has to run the cheap tier \
             and the far side what ships; the far side follows the variable's *default*, exactly \
             as the four scalars do"
        );
        recorder.assert_valid();
    }

    /// **The frame block carries the console's shadow filter on the near side
    /// of the seam, the shipped one on the far side, and the column
    /// [`crate::split::halves`] counted.**
    ///
    /// [`the_comparison_seam_marches_through_two_techniques`]'s claim for the
    /// other seam, and it has to be a claim about *bytes* rather than about
    /// pass handles: the occlusion chain compares two pipelines and this
    /// compares two arms of one, so there is nothing in the pass list to look
    /// at. What a person sees is decided entirely by the row this asserts.
    ///
    /// **The frame at the default is the control**, and it is what makes the
    /// rest mean anything: a block that always wrote the shipped filter into
    /// both lanes would satisfy the third case's far side whatever
    /// `shipped_filter` did, and one that copied the near lane into the far one
    /// would satisfy the first two.
    ///
    /// The column is compared against `halves`' own answer rather than against
    /// a number written here, which is the seam module's whole point: a test
    /// that multiplied the fraction by the width itself would be a second
    /// opinion about the rounding, and the floor is exactly what that module's
    /// `the_seam_takes_the_floor_of_the_column_it_asks_for` exists to pin.
    ///
    /// [`the_comparison_seam_marches_through_two_techniques`]: fn@the_comparison_seam_marches_through_two_techniques
    #[test]
    fn the_frame_block_carries_a_shadow_filter_for_each_side_of_the_seam() {
        let switch = shadow_filter_switch();

        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");

        // The seam is counted over the extent the scene is *drawn* at, which is
        // what `SV_Position.x` is denominated in — not the caller's window.
        let internal = renderer.internal_extent(TEST_EXTENT);
        let (left, _) = crate::split::halves(internal, 0.5).expect("a seam down the middle");
        assert!(
            left.width > 0,
            "a seam with no columns on one side would make every assertion below hold of a \
             frame that compares nothing"
        );

        let ships = shadow::shipped_filter();
        let other = shadow::Filter::Box;
        assert_ne!(
            other.mode(),
            ships.mode(),
            "the filter this test moves the console to is the one that ships, so the seam it \
             asks for compares one kernel against itself"
        );

        let draw = |renderer: &mut ForwardRenderer| {
            renderer
                .begin_frame(
                    device,
                    &Camera::default(),
                    &DirectionalLight::default(),
                    TEST_EXTENT,
                )
                .expect("write");
            let bytes = recorder
                .buffer_bytes(renderer.primary.uniforms[renderer.frame])
                .expect("this frame's uniform block is live");
            let at = mesh::FRAME_UNIFORMS_SIZE - 16;
            core::array::from_fn(|lane| {
                u32::from_le_bytes(
                    bytes[at + lane * 4..at + lane * 4 + 4]
                        .try_into()
                        .expect("four bytes"),
                )
            })
        };

        let shipped: [u32; 4] = draw(&mut renderer);
        assert_eq!(
            shipped,
            [ships.mode(), ships.mode(), 0, 0],
            "a frame nobody has touched the console on must carry the shipped filter in both \
             lanes and no column, which is the row every golden in this workspace was blessed \
             under"
        );

        switch.filter(other);
        let unsplit: [u32; 4] = draw(&mut renderer);
        assert_eq!(
            unsplit,
            [other.mode(), other.mode(), 0, 0],
            "`r_shadow_filter {}` with no seam has to reach every pixel, so both lanes carry it",
            other.label()
        );

        switch.seam(0.5);
        let compared: [u32; 4] = draw(&mut renderer);
        assert_eq!(
            compared,
            [other.mode(), ships.mode(), left.width, 0],
            "a seam at 0.5 has to put the console's filter left of `halves`' column and the \
             shipped one right of it; the far side follows the variable's *default*, exactly \
             as the occlusion chain's does"
        );

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

    #[test]
    fn a_second_occlusion_blur_is_a_pass_the_frame_records() {
        let switch = ssao_blur_switch();

        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        let imported = swapchain_image(device);
        let pool = crate::TransientPool::new();

        let once = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
        let counted_once = renderer.counters().instances;
        assert!(
            once.contains(&"ssao-blur".to_string()),
            "the shipping frame has to blur once, or the arm below is about a frame with no \
             occlusion in it at all: {once:#?}"
        );
        assert!(
            !once.contains(&"ssao-blur-2".to_string()),
            "a frame nobody moved the switch for must record one blur: {once:#?}"
        );

        switch.set(2);
        let twice = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
        let counted_twice = renderer.counters().instances;
        assert!(
            twice.contains(&"ssao-blur-2".to_string()),
            "`r_ssao_blur_passes 2` must put a second blur in the frame: {twice:#?}"
        );
        assert_eq!(
            twice.len(),
            once.len() + 1,
            "the second blur is the only pass that may join the frame: {twice:#?}"
        );
        assert_eq!(
            counted_twice,
            counted_once + FULLSCREEN_DRAWS,
            "the frame recorded a full-screen triangle its counter did not report"
        );

        // The pass has to write somewhere the forward pass then reads, and the
        // graph is what would refuse a frame that bound an image nothing wrote.
        // `passes_in_a_frame` compiles rather than executes, so this is the
        // check that the third transient was requested at all.
        assert!(
            twice.iter().any(|pass| pass == "forward"),
            "the frame still has to reach its forward pass: {twice:#?}"
        );
        recorder.assert_valid();
    }

    /// Every host-written buffer at the end of a whole ring of frames, keyed by
    /// the handle written and holding what that handle last held.
    ///
    /// A whole ring rather than one frame, because the blocks a frame writes are
    /// themselves rings — a buffer per frame in flight, [`Ssao`]'s among them —
    /// so one frame touches one slot of each and two single-frame batches would
    /// be comparing different buffers. A ring writes every slot, so two batches'
    /// keys line up and a difference between them is a difference in *bytes*.
    ///
    /// Only the events this call appends are read, so a caller can take one
    /// batch after another off the same recorder.
    fn host_buffers_over_a_ring(
        recorder: &Recorder,
        device: &dyn Device,
        renderer: &mut ForwardRenderer,
        queue: QueueHandle,
    ) -> std::collections::BTreeMap<u64, Vec<u8>> {
        let from = recorder.events().len();
        for _ in 0..FRAMES_IN_FLIGHT {
            frame(device, renderer, queue).release(device);
        }
        recorder.events()[from..]
            .iter()
            .filter_map(|event| match event {
                Event::BufferWritten { buffer, .. } => Some(*buffer),
                _ => None,
            })
            .map(|buffer| {
                let bytes = recorder
                    .buffer_bytes(buffer)
                    .expect("the stream only names buffers this recorder created");
                (buffer.to_bits(), bytes)
            })
            .collect()
    }

    /// **`r_ssao_slices` reaches the block `ssao.slang` reads, on every frame of
    /// the ring, and moves nothing else in the frame.**
    ///
    /// The device test drives the two occlusion pipelines directly and
    /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`] moves the *blur*
    /// count, so until this the slice count was a variable with a `get_i64` and
    /// no evidence that a rendered frame ever carried it: `slice_count` could
    /// have returned its default unconditionally and every check in this
    /// workspace would still be green.
    ///
    /// So the observable is the bytes, taken off the null recorder's write log
    /// after a whole ring of frames at each setting and compared **by handle**.
    /// Two claims come out of that comparison and both are load-bearing:
    ///
    /// * **Some block moved** — every ring slot, in fact, which is what says the
    ///   count reaches the frame at all rather than only the slot the last frame
    ///   happened to land in.
    /// * **Every block that moved, moved only there.** A frame is a few dozen
    ///   host writes and the slice count has business with exactly one word of
    ///   one of them; a setting that perturbed a matrix, an instance or a shadow
    ///   view would be drawing a different frame for a reason nobody asked for,
    ///   and the "at least one differs" half alone would pass on it happily.
    ///
    /// **Holds every switch whose row is in a block it compares**, in the lock
    /// order: the two batches are compared byte for byte over every host
    /// buffer the frame writes, so any console row another test moves between
    /// them — the blur count, the seam, the technique, the shadow filter, or
    /// `crate::ssao`'s own mover of the params block — reads here as "some
    /// other write moving". [`ssao_technique_switch`] is the one that
    /// serialises against that mover.
    #[test]
    fn four_slices_reach_the_frame_the_shader_reads() {
        let _blurs = ssao_blur_switch();
        let _seam = ssao_split_switch();
        let switch = ssao_slice_switch();
        let _technique = ssao_technique_switch();
        let _filter = shadow_filter_switch();

        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");

        // A ring rendered before either batch is taken, because the two below
        // are compared by handle and the renderer's opening frame writes blocks
        // no later frame writes again: it fills a cold shadow atlas, so the
        // shadow views' uniform blocks and the draw-generation blocks of the
        // cascades that were drawn are written once and never again while the
        // cache holds. Those would be in the first batch and missing from the
        // second, and a key that is only in one of them is a difference this
        // test cannot say anything about.
        for _ in 0..FRAMES_IN_FLIGHT {
            frame(device, &mut renderer, queue).release(device);
        }
        let shipping = host_buffers_over_a_ring(&recorder, device, &mut renderer, queue);
        switch.set(i64::from(ssao::SLICE_COUNT_MAX));
        let asked = host_buffers_over_a_ring(&recorder, device, &mut renderer, queue);
        assert_eq!(
            shipping.keys().collect::<Vec<_>>(),
            asked.keys().collect::<Vec<_>>(),
            "the two batches must write the same buffers, or they are not comparable",
        );

        // Which bytes moving the count alone is allowed to move, asked of
        // `SsaoParams::to_bytes` rather than written here as an offset: the
        // block's layout is `crcbl_shaders::ssao`'s, and a field inserted ahead
        // of the count would leave a number spelled here pointing at the radius.
        let block_of = |slices| {
            ssao::SsaoParams {
                inv_proj: [0.0; 16],
                proj: [0.0; 16],
                inv_view: [0.0; 16],
                radius: 0.0,
                slices,
                intensity: ssao::INTENSITY_DEFAULT,
                bent_normals: crate::ssao::bent_normals(),
            }
            .to_bytes()
        };
        let at_shipping = block_of(ssao::SLICE_COUNT_DEFAULT);
        let at_max = block_of(ssao::SLICE_COUNT_MAX);
        let count_word: Vec<usize> = (0..ssao::PARAMS_SIZE)
            .filter(|at| at_shipping[*at] != at_max[*at])
            .collect();

        let mut moved = 0;
        for (handle, before) in &shipping {
            let after = &asked[handle];
            if before == after {
                continue;
            }
            moved += 1;
            let mut only_the_count = before.clone();
            for at in &count_word {
                assert_eq!(
                    before[*at], at_shipping[*at],
                    "buffer {handle} differs between the batches but did not go in holding the \
                     shipping slice count, so this is some other write moving",
                );
                only_the_count[*at] = at_max[*at];
            }
            assert_eq!(
                after, &only_the_count,
                "buffer {handle} moved somewhere other than the slice count's word: the setting \
                 is perturbing a block it has no business in",
            );
        }
        assert_eq!(
            moved, FRAMES_IN_FLIGHT,
            "`r_ssao_slices 4` must reach every slot of the occlusion ring; a count that moved \
             none of them is a console variable no rendered frame reads",
        );

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

    /// **The debug draw layer costs a frame nothing until something is appended
    /// *and* the console switch is on, and then it is the pass immediately
    /// before the tonemap.**
    ///
    /// Four claims, and each is a separate way to get this wrong.
    ///
    /// * **Off by default** is what keeps every golden image in the workspace
    ///   where it was blessed.
    /// * **A segment appended while the switch is off records nothing**, so a
    ///   system may append unconditionally.
    /// * **The switch on with an empty buffer records nothing either** — this is
    ///   the "costs nothing when empty" claim as a check rather than a sentence:
    ///   the compiled pass list is compared whole against the frame drawn before
    ///   the layer was switched on, so a pass that clears, blits or barriers
    ///   anything would show up here.
    /// * **Before the tonemap**, which is
    ///   `docs/plan/18-render-features.md`'s interaction rule and the opposite of
    ///   the ground grid above. Recorded a line later it would draw into the
    ///   display-space target and be free of the exposure, which compiles and
    ///   draws lines and is the wrong picture.
    ///
    /// And the fifth, which is what "immediate mode" means: the frame *after*
    /// the one that appended records nothing again, because
    /// [`ForwardRenderer::begin_frame`] cleared the buffer.
    ///
    /// The whole list is compared rather than its length, for the ground grid
    /// test's reason: one more pass is satisfied by gaining the wrong one.
    ///
    /// **This test owns `r_debug_draw` for its duration**, through
    /// [`debug_draw_switch`]: a plain `cargo test` run shares one process
    /// between tests, so the two checks here that move it have to take turns.
    /// `cargo nextest`, which CI runs, gives each a process of its own and needs
    /// none of it.
    #[test]
    fn the_debug_draw_layer_is_off_by_default_and_lands_before_the_tonemap() {
        let switch = debug_draw_switch();
        let _blurs = ssao_blur_switch();

        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        let imported = swapchain_image(device);
        let mut pool = crate::TransientPool::new();

        assert!(
            !crate::DebugDraw::enabled(),
            "the layer must be off before anything switches it on, or every claim below is \
             about a different default"
        );
        let off = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
        assert!(
            !off.contains(&"debug-draw".to_string()),
            "the layer must not be in a frame nobody switched it on for: {off:#?}"
        );

        renderer
            .debug_draw()
            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
        assert_eq!(
            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
            off,
            "a segment appended while the switch is off must record no pass"
        );

        switch.set(true);
        assert_eq!(
            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
            off,
            "the switch on with an empty buffer must record the frame the layer's absence would"
        );

        renderer
            .debug_draw()
            .aabb(-Vec3::ONE, Vec3::ONE, [0.0, 1.0, 0.0, 1.0]);
        let on = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
        let mut expected = off.clone();
        let tonemap = expected
            .iter()
            .position(|label| label == "tonemap")
            .expect("a frame has to reach the swapchain");
        expected.insert(tonemap, "debug-draw".to_string());
        assert_eq!(
            on, expected,
            "the layer must be the one pass gained, and it must sit before the tonemap"
        );

        assert_eq!(
            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
            off,
            "the buffer is immediate mode: the frame after the one that appended must record \
             nothing"
        );

        switch.set(false);
        renderer.destroy(device);
        pool.destroy(device);
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// **The debug draw layer's own call is counted in the frame's draws.**
    ///
    /// [`ForwardRenderer::counters`]' draw count is compared against the
    /// commands the null backend actually recorded, which is the same instrument
    /// `the_forward_counters_are_the_recorded_draws_and_admit_what_they_cannot_know`
    /// uses — so a layer whose line list was recorded and not counted fails here
    /// rather than quietly making every panel's draw row one short.
    ///
    /// Both directions are asserted: the frame that drew a segment records one
    /// more draw than the frame before it, *and* the counter moved by the same
    /// one. A count wired to a constant satisfies neither.
    ///
    /// It owns `r_debug_draw` for its duration, on
    /// `the_debug_draw_layer_is_off_by_default_and_lands_before_the_tonemap`'s
    /// terms.
    #[test]
    fn the_debug_draw_layers_call_is_counted_in_the_frames_draws() {
        let switch = debug_draw_switch();
        let _blurs = ssao_blur_switch();

        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");

        // A different sun in each of the two frames, so both of them redraw the
        // shadow atlas: the claim below is that the layer's own call is the one
        // draw the second frame gained, and a second frame that cached its
        // atlas would have lost the atlas's draws at the same time. See
        // [`moving_sun`].
        let quiet = frame_moving_the_sun(device, &mut renderer, queue, 0);
        let without = renderer.counters().draws;
        assert_eq!(
            without,
            recorded_draws(&recorder) as u64,
            "the counter and the frame's recorded draws disagree before the layer draws at all"
        );
        quiet.release(device);

        switch.set(true);
        renderer
            .debug_draw()
            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
        let drawn = frame_moving_the_sun(device, &mut renderer, queue, 1);
        let with = renderer.counters().draws;
        assert_eq!(
            with,
            without + 1,
            "the layer records one draw, so the count has to move by one"
        );
        assert_eq!(
            recorded_draws(&recorder) as u64,
            without + with,
            "the two frames' recorded draws and the two counts disagree, so the layer's call is \
             counted somewhere it was not recorded or recorded somewhere it was not counted"
        );

        switch.set(false);
        drawn.finish(device, renderer);
        recorder.assert_valid();
    }

    /// **The depth-only passes run the depth-only entry point, and the colour
    /// pass does not.**
    ///
    /// Topic 43 §2 split the vertex pool so a pass
    /// that wants a clip position and no more could fetch stream 0 alone, and
    /// [`MeshModules::depth_pipeline`] naming `mesh.slang`'s `depthVertexMain`
    /// is the whole of how that split is spent. **Nothing else in the tree sees
    /// it.** `crcbl_shaders::mesh`'s
    /// `the_depth_entry_point_fetches_the_position_stream_alone` reads the
    /// compiled artifact and would pass with the entry point built and unused;
    /// no golden moves, because the two stages compute the same clip position on
    /// purpose; the render graph records a legal frame either way; and the
    /// measured price says nothing — pointing this pipeline back at `vertexMain`
    /// cost the depth prepass about a tenth more on lavapipe and nothing to
    /// three figures on an RX 7900 XTX, measured 2026-08-31. So the wiring is
    /// asserted here, against the reference backend, which records the entry
    /// point a pipeline names precisely so this question has an answer.
    ///
    /// **Both halves, so the check is shown to discriminate.** A lookup that
    /// answered `depthVertexMain` for every pipeline would satisfy the first
    /// assertion alone, and the colour pipeline is the one that must *not* have
    /// moved. The labels are the descriptors' own and are what the two are told
    /// apart by, so a renamed pipeline fails at the `expect` rather than
    /// silently matching nothing.
    #[test]
    fn the_depth_pipeline_names_the_depth_only_vertex_stage_and_the_colour_one_does_not() {
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        // A mesh stage has no vertex entry point to name, and this whole rung is
        // about the raster arm — see [`MeshModules::depth_pipeline`]. The null
        // preset reports no `Features::MESH_SHADER`, so this is what it built;
        // asserted rather than assumed, because a preset that grew the feature
        // would leave every assertion below looking for pipelines that do not
        // exist.
        assert_ne!(
            renderer.geometry_path(),
            crcbl_hal::GeometryPath::MeshShader,
            "this device built a mesh-shader path, whose geometry stage names no vertex \
             entry point at all"
        );

        let pipelines = recorder.graphics_pipeline_vertex_entries();
        let entry_of = |label: &str| -> String {
            let found: Vec<&str> = pipelines
                .iter()
                .filter(|(name, _)| name.as_deref() == Some(label))
                .map(|(_, entry)| entry.as_str())
                .collect();
            assert_eq!(
                found.len(),
                1,
                "the renderer built {} pipeline(s) labelled `{label}`, out of {pipelines:?}",
                found.len()
            );
            found[0].to_owned()
        };

        assert_eq!(
            entry_of("shadow cascade"),
            "depthVertexMain",
            "the shadow atlas and the depth prepass share this pipeline, and it is the one \
             that reads the position stream alone"
        );
        assert_eq!(
            entry_of("forward mesh"),
            "vertexMain",
            "the colour pass needs every attribute the depth pass skips, so it is the entry \
             point that reads a whole vertex"
        );
        assert_eq!(
            entry_of("shadow cascade masked"),
            "vertexMain",
            "the cutout twin has to read a whole vertex: the UV it samples the mask from lives \
             in the attribute region `depthVertexMain` exists not to read"
        );

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

    /// **A masked material moves that mesh's depth draws onto the cutout
    /// pipeline, and moves nothing else.**
    ///
    /// The mechanism is which pipeline handle the recorded stream binds and
    /// which buckets' indirect calls follow each bind — the wireframe test's
    /// observable, for the same reason: a field saying a mode was read would
    /// prove the flag was read, not that the frame changed.
    ///
    /// Four claims, and each rules out a different way of passing wrongly:
    ///
    /// * a scene with nothing masked binds the vertex-only pipeline and
    ///   **never** the cutout one, which is the "an opaque frame costs what it
    ///   always did" claim at the level a null device can see it;
    /// * a scene with one masked row binds **both** in the depth prepass and
    ///   both in the shadow atlas — a per-frame choice binds one or the other,
    ///   never the pair;
    /// * the calls following each bind are exactly that mode's buckets, in
    ///   bucket order, read off the argument offsets the draws name. A split
    ///   that bound both pipelines and drew every bucket under each would
    ///   satisfy the claim above and double the frame's draws;
    /// * and folding the two handles together — then collapsing the runs of
    ///   equal binds the fold creates — leaves the two frames' bind streams
    ///   **equal**, so the colour pass, the tile clears and the reflective
    ///   shadow map are all where they were. A change that had also moved the
    ///   colour pass would satisfy the first three and fail this.
    ///
    /// The two scenes differ in one flags word and nothing else.
    #[test]
    fn a_masked_material_moves_its_own_meshs_depth_draws_onto_the_cutout_pipeline() {
        use crcbl_hal::null::Command;

        // The occlusion blur count is a process-global console variable and a
        // frame binds one pipeline per blur, so a concurrent test moving it
        // would put a bind in one of these frames and not the other — the
        // wireframe test's hazard exactly.
        let _blurs = ssao_blur_switch();

        let masked_scene = {
            let mut scene = crate::scene::demo();
            scene.materials[DEMO_UNTINTED].flags =
                crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK;
            scene
        };

        /// What one scene's frame reveals: the bucket count and each bucket's
        /// mode, how often each depth pipeline was bound, the (pipeline, bucket)
        /// pairs the depth prepass and the shadow atlas recorded, and the whole
        /// bind stream with the two depth handles folded into one.
        struct Recorded {
            modes: Vec<u32>,
            cutouts: usize,
            plains: usize,
            prepass: Vec<(bool, u32)>,
            atlas: Vec<(bool, u32)>,
            folded: Vec<GraphicsPipelineHandle>,
        }

        // One frame each, from two renderers rather than two frames from one:
        // a bucket table is fixed at build, and two builds keep the frames'
        // shadow-atlas state identical — both are a first frame.
        let bound = |scene: &crate::scene::SceneDesc<'_>| -> Recorded {
            let (recorder, device, queue) = open();
            let device = device.as_ref();
            let mut renderer =
                ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, scene)
                    .expect("the null backend accepts the demo description");
            place_cube(&mut renderer, Mat4::IDENTITY);
            let imported = swapchain_image(device);
            let mut pool = crate::TransientPool::new();
            renderer
                .begin_frame(
                    device,
                    &Camera::default(),
                    &DirectionalLight::default(),
                    (64, 48),
                )
                .expect("write");
            let mut graph = crate::RenderGraph::new(queue);
            let target = graph.import_image("target", imported);
            renderer.add_passes(&mut graph, &pool, target, (64, 48));
            let compiled = graph.compile(&pool).expect("a legal frame");
            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
                label: Some("alpha mask lap"),
                queue,
            });
            compiled
                .execute(device, &mut pool, encoder.as_mut(), None)
                .expect("the graph executed");
            encoder.finish().expect("recording succeeded");
            let plain = renderer.shadow_pipeline.single;
            let cutout = renderer.depth_masked_pipeline.single;
            assert_ne!(
                plain, cutout,
                "the two depth pipelines have to be two objects, or nothing below discriminates"
            );
            // Which bucket a draw is, recovered from the argument offset it
            // names — the offsets are the renderer's own accessor, so a call
            // pointing at the wrong bucket has no entry here at all.
            let bucket_of = |args_offset: u64| -> u32 {
                (0..u32::try_from(renderer.bucket_constants.len()).expect("a few buckets"))
                    .find(|bucket| renderer.primary.draws.args_offset(*bucket) == args_offset)
                    .unwrap_or_else(|| {
                        panic!("a draw read its arguments at {args_offset}, which is no bucket's")
                    })
            };
            // Per depth pass: the pipeline in force at each indirect call and
            // the bucket that call drew, in the order they were recorded.
            let pass_calls = |label: &str| -> Vec<(bool, u32)> {
                let mut current = None;
                let mut out = Vec::new();
                for command in commands_in_pass(&recorder, label) {
                    match command {
                        Command::BindGraphicsPipeline(handle) => current = Some(handle),
                        Command::DrawIndexedIndirectCount(draw) => {
                            let handle = current.expect("a draw follows a pipeline bind");
                            assert!(
                                handle == plain || handle == cutout,
                                "a depth pass drew under a pipeline that is neither depth one"
                            );
                            out.push((handle == cutout, bucket_of(draw.args_offset)));
                        }
                        _ => {}
                    }
                }
                out
            };
            let prepass = pass_calls("depth-prepass");
            let atlas = pass_calls("shadow");
            let binds: Vec<GraphicsPipelineHandle> = recorder
                .commands()
                .iter()
                .filter_map(|command| match command {
                    Command::BindGraphicsPipeline(handle) => Some(*handle),
                    _ => None,
                })
                .collect();
            let cutouts = binds.iter().filter(|handle| **handle == cutout).count();
            let plains = binds.iter().filter(|handle| **handle == plain).count();
            let mut folded: Vec<GraphicsPipelineHandle> = Vec::with_capacity(binds.len());
            for handle in binds {
                let handle = if handle == cutout { plain } else { handle };
                // The fold turns the masked frame's `plain, cutout` pair into
                // `plain, plain`; collapsing a run of equal binds is what makes
                // the two streams comparable without hiding a bind of anything
                // else, since no pass in either frame binds two *different*
                // pipelines that the fold could bring together.
                if folded.last() != Some(&handle) {
                    folded.push(handle);
                }
            }
            let modes = renderer.bucket_modes.clone();
            renderer.destroy(device);
            recorder.assert_valid();
            Recorded {
                modes,
                cutouts,
                plains,
                prepass,
                atlas,
                folded,
            }
        };

        let opaque = bound(&crate::scene::demo());
        let masked = bound(&masked_scene);

        assert_eq!(
            opaque.cutouts, 0,
            "a scene with nothing masked must never bind the cutout pipeline"
        );
        assert!(
            opaque.plains > 0,
            "a scene with nothing masked must bind the vertex-only pipeline, or the assertion \
             above is about a frame with no depth pass in it"
        );
        assert!(
            opaque.modes.iter().all(|mode| *mode == 0),
            "and every one of its buckets is opaque: {:?}",
            opaque.modes
        );
        assert_eq!(
            opaque.prepass.iter().filter(|(cutout, _)| *cutout).count(),
            0,
            "so no opaque draw is recorded under the cutout pipeline"
        );

        assert!(
            masked.cutouts > 0 && masked.plains > 0,
            "a masked scene must bind **both** depth pipelines — {} cutout and {} plain — or \
             the choice is still per frame",
            masked.cutouts,
            masked.plains
        );
        // What each depth pass should have recorded: every opaque bucket under
        // the plain pipeline in bucket order, then every masked one under the
        // cutout, which is the partition order `depth_partitions` lays down.
        let want: Vec<(bool, u32)> = [false, true]
            .into_iter()
            .flat_map(|cutout| {
                masked
                    .modes
                    .iter()
                    .enumerate()
                    .filter(move |(_, mode)| {
                        (**mode == crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK) == cutout
                    })
                    .map(move |(bucket, _)| (cutout, u32::try_from(bucket).expect("a few buckets")))
            })
            .collect();
        assert!(
            want.iter().any(|(cutout, _)| *cutout) && want.iter().any(|(cutout, _)| !*cutout),
            "the masked demo has to hold buckets of both modes, or this compares one partition \
             against itself: {:?}",
            masked.modes
        );
        assert_eq!(
            masked.prepass, want,
            "the depth prepass must record each bucket once, under the pipeline its own mode \
             asked for"
        );
        // The atlas draws every bucket once per occupied view, and the
        // partition is **outside** the view loop — one pipeline bind covers
        // every view of that mode — so its stream is each partition's bucket
        // list repeated once per view.
        let views = masked.atlas.len() / want.len();
        assert!(
            views > 0 && masked.atlas.len() % want.len() == 0,
            "the shadow atlas recorded {} calls over {} buckets, which is not a whole number \
             of views",
            masked.atlas.len(),
            want.len()
        );
        let mut atlas_want: Vec<(bool, u32)> = Vec::with_capacity(masked.atlas.len());
        for cutout in [false, true] {
            let partition: Vec<(bool, u32)> = want
                .iter()
                .copied()
                .filter(|(mode, _)| *mode == cutout)
                .collect();
            for _ in 0..views {
                atlas_want.extend_from_slice(&partition);
            }
        }
        assert_eq!(
            masked.atlas, atlas_want,
            "and every shadow view draws both partitions, each under its own pipeline"
        );

        assert_eq!(
            masked.folded, opaque.folded,
            "the frame gained or lost a pipeline bind beyond the cutout twin beside a plain one"
        );
    }

    /// **A double-sided material moves every pass's draws for its own buckets
    /// onto the `CullMode::None` twins, and moves nothing else.**
    ///
    /// [`a_masked_material_moves_its_own_meshs_depth_draws_onto_the_cutout_pipeline`]'s
    /// claim for glTF's other mode, and it is wider by construction: an alpha
    /// mask is cut inside a fragment stage, so only the two depth-only passes
    /// route around it, while a cull mode is a pipeline state and **every** pass
    /// that draws the surface has to route around it — the colour pass, both
    /// depth passes and the two reflective shadow maps.
    ///
    /// So this walks the whole recorded stream rather than two named passes:
    /// every render pass that recorded an indirect draw is read back as the
    /// (side, bucket) pairs it recorded, and each of the four claims below is
    /// about all of them at once.
    ///
    /// * a scene with nothing double-sided binds **no** cull-none twin
    ///   anywhere, which is the "an all-single-sided frame costs what it always
    ///   did" claim at the level a null device can see it;
    /// * a scene with one double-sided row binds a twin in every pass that
    ///   draws — a frame that had only routed the colour pass would satisfy
    ///   nothing below, and one that had only routed the depth passes would
    ///   draw a surface the prepass wrote no depth for;
    /// * the calls following each bind are exactly that side's buckets, in
    ///   bucket order. A split that bound both pipelines and drew every bucket
    ///   under each would satisfy the claim above and double the frame's draws;
    /// * and folding each twin onto the pipeline it is a twin of — then
    ///   collapsing the runs of equal binds the fold creates — leaves the two
    ///   frames' bind streams **equal**, so nothing else in the frame moved.
    ///
    /// The two scenes differ in one flags word and nothing else.
    ///
    /// [`a_masked_material_moves_its_own_meshs_depth_draws_onto_the_cutout_pipeline`]: fn@a_masked_material_moves_its_own_meshs_depth_draws_onto_the_cutout_pipeline
    #[test]
    fn a_double_sided_material_moves_every_passs_draws_onto_the_cull_none_twins() {
        use crcbl_hal::null::Command;

        // The occlusion blur count is a process-global console variable and a
        // frame binds one pipeline per blur — the masked test's hazard exactly.
        let _blurs = ssao_blur_switch();

        // **A scene whose probes ask to be updated**, because the reflective
        // shadow maps are recorded by a volume rather than by an effect bit —
        // and they are two of the five passes this claim is about. The demo's
        // empty grid records neither, which would leave the widest half of the
        // routing unchecked.
        let scene_with_probes = || {
            let mut scene = crate::scene::demo();
            scene.capacities.probes = 1;
            scene.probes = crate::scene::ProbeGrid {
                volume: crcbl_shaders::probe::ProbeVolume {
                    origin: [0.0; 3],
                    inv_spacing: [1.0; 3],
                    counts: [1, 1, 1],
                    levels: 1,
                    steps: crcbl_shaders::probe::ProbeSteps::default(),
                },
                probes: vec![crcbl_shaders::probe::GpuProbe::ZERO],
                update: ProbeUpdate::EveryFrame,
            };
            scene
        };
        let single_scene = scene_with_probes();
        let double_scene = {
            let mut scene = scene_with_probes();
            scene.materials[DEMO_UNTINTED].flags = crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED;
            scene
        };

        /// What one scene's frame reveals: each bucket's mode, how often a
        /// cull-none twin was bound at all, every drawing pass's (side, bucket)
        /// pairs in record order, and the whole bind stream with each twin
        /// folded onto the pipeline it twins.
        struct Recorded {
            modes: Vec<u32>,
            twins_bound: usize,
            passes: Vec<(String, Vec<(bool, u32)>)>,
            folded: Vec<GraphicsPipelineHandle>,
        }

        // One frame each, from two renderers rather than two frames from one, on
        // the masked test's terms: a bucket table is fixed at build, and two
        // builds keep both frames a first frame.
        let bound = |scene: &crate::scene::SceneDesc<'_>| -> Recorded {
            let (recorder, device, queue) = open();
            let device = device.as_ref();
            let mut renderer =
                ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, scene)
                    .expect("the null backend accepts the demo description");
            assert!(
                !renderer.emit.is_mesh(),
                "this preset built a mesh-shader path, whose draws carry no argument offset to \
                 recover a bucket from"
            );
            place_cube(&mut renderer, Mat4::IDENTITY);
            // **One shadowed spot**, so the punctual reflective shadow map has a
            // face to draw into: the pass is recorded on every frame but its
            // view loop is empty without one, and an empty loop records no draw
            // for the claim below to be about.
            renderer.set_lights(&[crate::Light::Spot(crate::SpotLight {
                position: Vec3::new(0.0, 2.0, 0.0),
                radius: 8.0,
                color: Vec3::splat(4.0),
                direction: Vec3::NEG_Y,
                inner_angle: 0.3,
                outer_angle: 0.6,
                fill: false,
            })]);
            let imported = swapchain_image(device);
            let mut pool = crate::TransientPool::new();
            renderer
                .begin_frame(
                    device,
                    &Camera::default(),
                    &DirectionalLight::default(),
                    (64, 48),
                )
                .expect("write");
            let mut graph = crate::RenderGraph::new(queue);
            let target = graph.import_image("target", imported);
            renderer.add_passes(&mut graph, &pool, target, (64, 48));
            let compiled = graph.compile(&pool).expect("a legal frame");
            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
                label: Some("double sided lap"),
                queue,
            });
            compiled
                .execute(device, &mut pool, encoder.as_mut(), None)
                .expect("the graph executed");
            encoder.finish().expect("recording succeeded");

            // Every twin and the pipeline it twins, so a bind can be reported as
            // a side and folded back. Asserted distinct, or nothing here
            // discriminates.
            let sided = [
                renderer.mesh_pipeline,
                renderer.shadow_pipeline,
                renderer.depth_masked_pipeline,
                renderer.rsm_pipeline,
            ];
            for pair in sided {
                assert_ne!(
                    pair.single, pair.double,
                    "a pipeline and its cull-none twin have to be two objects"
                );
            }
            let twin_of = |handle: GraphicsPipelineHandle| -> Option<GraphicsPipelineHandle> {
                sided
                    .iter()
                    .find(|pair| pair.double == handle)
                    .map(|pair| pair.single)
            };
            let bucket_of = |args_offset: u64| -> u32 {
                (0..u32::try_from(renderer.bucket_constants.len()).expect("a few buckets"))
                    .find(|bucket| renderer.primary.draws.args_offset(*bucket) == args_offset)
                    .unwrap_or_else(|| {
                        panic!("a draw read its arguments at {args_offset}, which is no bucket's")
                    })
            };

            let mut passes: Vec<(String, Vec<(bool, u32)>)> = Vec::new();
            let mut folded: Vec<GraphicsPipelineHandle> = Vec::new();
            let mut twins_bound = 0usize;
            let mut current: Option<GraphicsPipelineHandle> = None;
            let mut label: Option<String> = None;
            let mut calls: Vec<(bool, u32)> = Vec::new();
            let commands = recorder.commands();
            for command in &commands {
                match command {
                    Command::BeginRenderPass { label: name, .. } => {
                        label = name.clone();
                        calls = Vec::new();
                    }
                    Command::EndRenderPass => {
                        if !calls.is_empty() {
                            passes.push((
                                label.clone().expect("every pass here is labelled"),
                                std::mem::take(&mut calls),
                            ));
                        }
                    }
                    Command::BindGraphicsPipeline(handle) => {
                        current = Some(*handle);
                        if twin_of(*handle).is_some() {
                            twins_bound += 1;
                        }
                        // The fold turns a `single, double` pair into
                        // `single, single`; collapsing a run of equal binds is
                        // what makes the two streams comparable without hiding
                        // a bind of anything else.
                        let folded_handle = twin_of(*handle).unwrap_or(*handle);
                        if folded.last() != Some(&folded_handle) {
                            folded.push(folded_handle);
                        }
                    }
                    Command::DrawIndexedIndirectCount(draw) => {
                        let handle = current.expect("a draw follows a pipeline bind");
                        calls.push((twin_of(handle).is_some(), bucket_of(draw.args_offset)));
                    }
                    Command::DrawIndexedIndirect(draw) => {
                        let handle = current.expect("a draw follows a pipeline bind");
                        calls.push((twin_of(handle).is_some(), bucket_of(draw.offset)));
                    }
                    _ => {}
                }
            }
            let modes = renderer.bucket_modes.clone();
            renderer.destroy(device);
            pool.destroy(device);
            device.destroy_image_view(imported.view);
            device.destroy_image(imported.image);
            recorder.assert_valid();
            Recorded {
                modes,
                twins_bound,
                passes,
                folded,
            }
        };

        let single = bound(&single_scene);
        let double = bound(&double_scene);

        assert_eq!(
            single.twins_bound, 0,
            "a scene with nothing double-sided must never bind a cull-none twin"
        );
        // Named rather than counted, because the claim is that **every** pass
        // that draws the surface routes: a frame that had quietly stopped
        // recording one of them would satisfy a count and leave that pass's
        // routing unchecked for ever.
        let drawing: Vec<&str> = single
            .passes
            .iter()
            .map(|(name, _)| name.as_str())
            .collect();
        for pass in ["shadow", "depth-prepass", "forward", "rsm", "rsm-punctual"] {
            assert!(
                drawing.contains(&pass),
                "`{pass}` drew nothing in this frame, so its routing is unchecked: {drawing:?}"
            );
        }
        assert!(
            double.twins_bound > 0,
            "a double-sided scene must bind the cull-none twins"
        );
        assert_eq!(
            double
                .passes
                .iter()
                .map(|(name, _)| name)
                .collect::<Vec<_>>(),
            single
                .passes
                .iter()
                .map(|(name, _)| name)
                .collect::<Vec<_>>(),
            "the two frames must draw in the same passes, or they are not comparable"
        );

        // What each drawing pass should have recorded: every single-sided bucket
        // under the plain pipeline in bucket order, then every double-sided one
        // under the twin — the partition order `sided_partitions` lays down —
        // repeated once per view for a pass that draws several.
        let want: Vec<(bool, u32)> = [false, true]
            .into_iter()
            .flat_map(|twin| {
                double
                    .modes
                    .iter()
                    .enumerate()
                    .filter(move |(_, mode)| {
                        (**mode & crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED != 0) == twin
                    })
                    .map(move |(bucket, _)| (twin, u32::try_from(bucket).expect("a few buckets")))
            })
            .collect();
        assert!(
            want.iter().any(|(twin, _)| *twin) && want.iter().any(|(twin, _)| !*twin),
            "the double-sided demo has to hold buckets of both sides, or this compares one \
             partition against itself: {:?}",
            double.modes
        );
        for (name, calls) in &double.passes {
            let views = calls.len() / want.len();
            assert!(
                views > 0 && calls.len() % want.len() == 0,
                "`{name}` recorded {} call(s) over {} bucket(s), which is not a whole number of \
                 views",
                calls.len(),
                want.len()
            );
            // The partition is **outside** any view loop — one pipeline bind
            // covers every view of that side — so the stream is each partition's
            // bucket list repeated once per view.
            let mut expected: Vec<(bool, u32)> = Vec::with_capacity(calls.len());
            for twin in [false, true] {
                let partition: Vec<(bool, u32)> = want
                    .iter()
                    .copied()
                    .filter(|(side, _)| *side == twin)
                    .collect();
                for _ in 0..views {
                    expected.extend_from_slice(&partition);
                }
            }
            assert_eq!(
                *calls, expected,
                "`{name}` must record each bucket once per view, under the pipeline its own \
                 side asked for"
            );
        }

        assert_eq!(
            double.folded, single.folded,
            "the frame gained or lost a pipeline bind beyond a cull-none twin beside the \
             pipeline it twins"
        );
    }

    /// **The wireframe view swaps the colour pass's pipeline and nothing else.**
    ///
    /// The mechanism, at the level a null device can observe it: which pipeline
    /// handle each pass of the recorded stream binds. A field on the renderer
    /// would say only that a flag moved — this says the *frame* moved, and says
    /// which part of it did.
    ///
    /// Four claims, and each rules out a different way of passing wrongly:
    ///
    /// * the filled pipeline is bound on a frame nobody asked, and the wireframe
    ///   one does not exist;
    /// * switching on **removes** the filled pipeline from the stream — a second
    ///   pipeline that was built and never bound would still leave it there;
    /// * every other pipeline the frame binds is unchanged, so the depth prepass
    ///   and the shadow cascades are still filling triangles;
    /// * and switching off puts the stream back exactly, so the view is a toggle
    ///   rather than a one-way door.
    #[test]
    fn the_wireframe_view_swaps_the_colour_passs_pipeline_and_no_other() {
        use crcbl_hal::null::Command;

        // The pipelines a frame binds include one per occlusion blur, and the
        // blur count is a process-global console variable — so a concurrent
        // test holding `r_ssao_blur_passes` at two adds a bind to one of the
        // frames below and not to the others. It reddened this assertion on
        // 2026-08-31 under a workspace `cargo test`.
        let _blurs = ssao_blur_switch();
        let (recorder, device, queue) =
            open_with(Features::GPU_DRIVEN | Features::POLYGON_MODE_LINE);
        let device = device.as_ref();
        assert!(
            ForwardRenderer::supports_wireframe(device),
            "this test needs the line fill mode, and asked the device for it",
        );
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        place_demo(&mut renderer, DEMO_CUBE, DEMO_UNTINTED, Mat4::IDENTITY);
        let imported = swapchain_image(device);
        let mut pool = crate::TransientPool::new();

        // The pipelines one frame binds, in record order. Cumulative recorder,
        // so each call takes the tail its own frame added.
        let mut seen = 0usize;
        // A different sun each lap, so the shadow atlas is redrawn in every one
        // of them: the comparison below is "which pipelines did this frame
        // bind", and a lap that cached its atlas would bind the depth-only
        // pipeline one fewer time for a reason that has nothing to do with the
        // wireframe. See [`moving_sun`].
        let mut lap = 0u32;
        let mut pipelines_in_a_frame = |renderer: &mut ForwardRenderer, pool: &mut _| {
            lap += 1;
            renderer
                .begin_frame(device, &Camera::default(), &moving_sun(lap), (64, 48))
                .expect("write");
            let mut graph = crate::RenderGraph::new(queue);
            let target = graph.import_image("target", imported);
            renderer.add_passes(&mut graph, pool, target, (64, 48));
            let compiled = graph.compile(pool).expect("a legal frame");
            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
                label: Some("wireframe lap"),
                queue,
            });
            compiled
                .execute(device, pool, encoder.as_mut(), None)
                .expect("the graph executed");
            encoder.finish().expect("recording succeeded");
            let commands = recorder.commands();
            let bound: Vec<GraphicsPipelineHandle> = commands[seen..]
                .iter()
                .filter_map(|command| match command {
                    Command::BindGraphicsPipeline(handle) => Some(*handle),
                    _ => None,
                })
                .collect();
            seen = commands.len();
            bound
        };

        let filled = renderer.mesh_pipeline.single;
        let off = pipelines_in_a_frame(&mut renderer, &mut pool);
        assert!(
            off.contains(&filled),
            "a frame nobody asked has to bind the filled pipeline: {off:?}",
        );
        assert!(!renderer.wireframe());
        assert!(
            renderer.wireframe_pipeline.is_none(),
            "the wireframe pipeline must not be built until it is asked for",
        );

        renderer
            .set_wireframe(device, true)
            .expect("a device with the line fill mode builds it");
        assert!(renderer.wireframe());
        let lines = renderer
            .wireframe_pipeline
            .expect("switching on is what builds it")
            .single;
        let on = pipelines_in_a_frame(&mut renderer, &mut pool);
        assert!(
            !on.contains(&filled),
            "the colour pass still bound the filled pipeline: {on:?}",
        );
        assert_eq!(
            on.iter().filter(|handle| **handle == lines).count(),
            1,
            "the wireframe pipeline has to be bound exactly once — by the colour pass: {on:?}",
        );
        let substituted: Vec<GraphicsPipelineHandle> = on
            .iter()
            .map(|handle| if *handle == lines { filled } else { *handle })
            .collect();
        assert_eq!(
            substituted, off,
            "the frame gained or lost a pipeline bind beyond the colour pass's: {on:?} against \
             {off:?}",
        );

        renderer
            .set_wireframe(device, false)
            .expect("switching off builds nothing");
        assert!(!renderer.wireframe());
        assert_eq!(
            pipelines_in_a_frame(&mut renderer, &mut pool),
            off,
            "switching the view off has to put the filled pipeline back, not just stop reporting \
             it",
        );

        renderer.destroy(device);
        pool.destroy(device);
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// **The colour pass tests against the prepass's depth instead of clearing
    /// and rewriting it, so each pixel is shaded once** — and a wireframe frame
    /// does the opposite, because lines do not reproduce a filled prepass.
    ///
    /// Both halves have to hold together or the frame is wrong in one of two
    /// ways, so both are asserted here. The attachment alone read-only while the
    /// pipeline still wrote would be a pipeline writing to a read-only
    /// attachment; the pipeline alone on `GreaterOrEqual` against an attachment
    /// this pass had just *cleared* would reject every fragment and draw a black
    /// frame. Neither shows up as an error — the first is a validation message
    /// on one backend and undefined behaviour on the rest, the second is a
    /// picture — which is why the observable is read off the compiled graph and
    /// off the pipeline state rather than off a screenshot.
    #[test]
    fn the_colour_pass_shades_once_per_pixel_against_the_prepasss_depth() {
        let (recorder, device, queue) =
            open_with(Features::GPU_DRIVEN | Features::POLYGON_MODE_LINE);
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        place_demo(&mut renderer, DEMO_CUBE, DEMO_UNTINTED, Mat4::IDENTITY);
        let imported = swapchain_image(device);
        let mut pool = crate::TransientPool::new();

        // Each pass's depth attachment, off the graph's own dump: the label it
        // was declared under, and the `load`/`store`/`write` triple the backend
        // is handed. A pass with no depth attachment contributes nothing, which
        // is what makes the lookup below a search rather than an index.
        let depth_of = |renderer: &mut ForwardRenderer, pool: &mut _, label: &str| {
            renderer
                .begin_frame(
                    device,
                    &Camera::default(),
                    &DirectionalLight::default(),
                    (64, 48),
                )
                .expect("write");
            let mut graph = crate::RenderGraph::new(queue);
            let target = graph.import_image("target", imported);
            renderer.add_passes(&mut graph, pool, target, (64, 48));
            let dump = graph.compile(pool).expect("a legal frame").dump();
            let mut pass = String::new();
            let mut found = None;
            for line in dump.lines() {
                if let Some(rest) = line.split(" pass \"").nth(1) {
                    pass = rest.trim_end_matches('"').to_string();
                    if let Some((name, _)) = pass.split_once('"') {
                        pass = name.to_string();
                    }
                }
                if pass == label
                    && let Some(at) = line.find("depth load=")
                {
                    // Without the slot note the dump appends: which physical
                    // image the transient landed on is aliasing's business, not
                    // this assertion's.
                    let role = &line[at..];
                    let role = role.split_once(" [").map_or(role, |(head, _)| head);
                    found = Some(role.trim().to_string());
                }
            }
            found.unwrap_or_else(|| panic!("no depth attachment on `{label}`:\n{dump}"))
        };

        assert_eq!(
            depth_of(&mut renderer, &mut pool, "depth-prepass"),
            "depth load=Clear store=Store write=yes",
            "the prepass is what puts the depth there, so it clears, writes and keeps it",
        );
        assert_eq!(
            depth_of(&mut renderer, &mut pool, "forward"),
            "depth load=Load store=Store write=no",
            "and the colour pass reads it: a clear here would throw away the prepass and \
             pay for the overdraw again, and a write would be a second pass writing the \
             same values",
        );
        assert_eq!(
            MeshModules::color_depth_stencil(PolygonMode::Fill),
            Some(DepthStencilState {
                format: Format::D32Float,
                depth_write: false,
                depth_compare: CompareOp::GreaterOrEqual,
                stencil: None,
                bias: DepthBias::default(),
            }),
            "and the pipeline agrees with the attachment: equality against the prepass, \
             reachable only through the `OrEqual` under reversed-Z",
        );

        renderer
            .set_wireframe(device, true)
            .expect("this device was asked for the line fill mode");
        assert_eq!(
            depth_of(&mut renderer, &mut pool, "forward"),
            "depth load=Clear store=Store write=yes",
            "a wireframe frame keeps the old shape: `PolygonMode::Line` interpolates depth \
             along the edge rather than across the face, so testing it against a filled \
             prepass rejects most of the wireframe — and *loading* that depth under the \
             writing default's `Greater` would reject all of it",
        );
        assert_eq!(
            MeshModules::color_depth_stencil(PolygonMode::Line),
            MeshModules::depth_stencil(),
            "which is the writing default, the same state the depth-only twin uses",
        );

        renderer.destroy(device);
        pool.destroy(device);
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// **A device with no line fill mode is refused, not quietly filled.**
    ///
    /// The failure this rules out is the silent one: a caller who binds a key to
    /// this, presses it, and gets the solid frame back with nothing anywhere
    /// saying why — which on a model whose silhouette hides its interior is
    /// indistinguishable from a wireframe that worked. WebGPU is the real device
    /// this happens on; `open`'s null device stands in for it, because
    /// [`DeviceDesc::for_adapter`] asks for
    /// [`Features::GPU_DRIVEN`] and nothing else.
    #[test]
    fn a_device_without_the_line_fill_mode_refuses_the_wireframe_rather_than_filling_it() {
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        assert!(
            !ForwardRenderer::supports_wireframe(device),
            "this device was not asked for the line fill mode, so it must not report it",
        );
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");

        let refused = renderer
            .set_wireframe(device, true)
            .expect_err("a device without the feature has to say so");
        assert!(
            matches!(
                refused,
                HalError::UnsupportedFeatures { missing } if missing == Features::POLYGON_MODE_LINE
            ),
            "the refusal has to name the feature to go and look up, and is {refused:?}",
        );
        assert!(
            !renderer.wireframe(),
            "a refused request must leave the view off rather than half on",
        );
        assert!(
            renderer.wireframe_pipeline.is_none(),
            "nothing may be left behind by a refusal",
        );
        // And switching *off* is still fine on such a device: it builds nothing.
        renderer
            .set_wireframe(device, false)
            .expect("switching off asks the device for nothing");

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

    /// The grid's own full-screen triangle is counted as submitted, and only
    /// while it is on.
    ///
    /// [`FrameCounters::instances`] is the "submitted" half of the debug panel's
    /// row, and every full-screen pass in the frame contributes one — so a grid
    /// that drew and was not counted makes that row disagree with the frame by
    /// exactly one triangle, silently.
    #[test]
    fn the_grids_triangle_is_counted_only_while_it_is_on() {
        let _blurs = ssao_blur_switch();
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        let imported = swapchain_image(device);
        let mut pool = crate::TransientPool::new();

        passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
        let off = renderer.counters();

        renderer
            .set_ground_grid(device, Some(GridStyle::default()))
            .expect("the null backend builds every pipeline");
        passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
        let on = renderer.counters();

        assert_eq!(
            on.draws - off.draws,
            FULLSCREEN_DRAWS,
            "the grid records exactly one draw"
        );
        assert_eq!(
            on.instances - off.instances,
            FULLSCREEN_DRAWS,
            "and exactly one submitted instance"
        );

        renderer.destroy(device);
        pool.destroy(device);
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// One frame on a device of its own, under an override switching `off`.
    ///
    /// **A device of its own per arm**, because a [`Recorder`] accumulates for a
    /// device's whole life: asking "did the atlas pass draw" of a recorder that
    /// has seen two frames answers about both of them, and the arm that matters
    /// most here is the one whose answer must be zero.
    ///
    /// Returns what the frame reported and what its atlas pass actually drew.
    fn frame_switching_off(off: RenderEffects) -> (FrameCounters, u64, usize) {
        use crcbl_hal::null::Command;

        let recorder = Recorder::new();
        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
        let adapter = instance.adapters().remove(0);
        let opened = instance
            .create_device(&DeviceDesc::for_adapter(adapter.id))
            .expect("the null backend always opens");
        let device = opened.as_ref();
        let queue = opened.queue(QueueKind::Graphics).expect("always present");
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        // A shadowed light beside the cascades, so the atlas pass has draws to
        // lose rather than being empty either way.
        renderer.set_lights(&[shadowable_spot(-1.0)]);
        // **[`OUTSIDE_THE_DEFAULT`] forced on, then `off` forced off.** The default
        // camera stack leaves both of them out — see
        // [`RenderEffects::DEFAULT_STACK`] — so a control frame built on the
        // default alone would be measuring three effects and calling it five,
        // and their arms below would be switching off something already off.
        // `force` clears the other side, so an arm whose `off` is one of them
        // still resolves to off.
        renderer.set_effect_request(EffectRequest {
            programmatic: EffectOverride::none()
                .force(OUTSIDE_THE_DEFAULT, Some(true))
                .force(off, Some(false)),
            ..EffectRequest::default()
        });

        let recorded = frame(device, &mut renderer, queue);
        assert_eq!(
            renderer.effects(),
            RenderEffects::all().difference(off),
            "the frame must have resolved to the set the request asked for"
        );
        let counters = renderer.counters();
        let instances = renderer.instances.len() as u64;
        let atlas_draws = commands_in_pass(&recorder, "shadow")
            .into_iter()
            .filter(|command| {
                matches!(
                    command,
                    Command::DrawIndexedIndirect(_)
                        | Command::DrawIndexedIndirectCount(_)
                        | Command::DrawMeshTasksIndirect(_)
                )
            })
            .count();
        assert_eq!(
            counters.draws,
            recorded_draws(&recorder) as u64,
            "the counter and the frame's own recorded stream must agree, whatever is switched off"
        );
        recorded.finish(device, renderer);
        recorder.assert_valid();
        (counters, instances, atlas_draws)
    }

    /// **A switched-off effect is work the frame did not record**, and a frame
    /// that still executes with the placeholder bound in place of what it lost.
    ///
    /// The other half of the pass-list test above, and the half a pass list
    /// cannot make: the `shadow` pass is still *there* with shadows off, so the
    /// question is whether it drew. That answer comes off the recorded command
    /// stream, which is a different instrument from `recorded_draws` — the number
    /// under test.
    ///
    /// Executed rather than only compiled, because the occlusion switch changes
    /// which image the forward pass has bound. A frame that declared a read of a
    /// transient it never created, or bound a view the graph never realised,
    /// fails here and compiles perfectly.
    #[test]
    fn a_switched_off_effect_is_work_the_frame_did_not_record() {
        let _blurs = ssao_blur_switch();
        let (control, instances, atlas_draws) = frame_switching_off(RenderEffects::empty());
        assert!(
            atlas_draws > 0,
            "with shadows on the atlas pass has to draw something, or turning it off means \
             nothing"
        );
        assert_eq!(
            control.instances,
            instances
                + fullscreen_passes(
                    RenderEffects::all(),
                    TEST_EXTENT,
                    false,
                    crate::ssao::blur_passes(),
                ) * FULLSCREEN_DRAWS,
            "the control frame submits one triangle per full-screen pass"
        );

        // Each pair is one full-screen triangle per pass, and the atlas is
        // untouched by either.
        for (off, fewer) in [
            (
                RenderEffects::AMBIENT_OCCLUSION,
                u64::from(Ssao::passes(crate::ssao::blur_passes())),
            ),
            // The contact march's one pass, and a constant rather than a
            // function of anything: it has no blur behind it and no chain.
            (
                RenderEffects::CONTACT_SHADOWS,
                u64::from(ContactShadows::PASSES),
            ),
            // The march's two passes and the reductions that feed them, which
            // is what makes this arm's number a function of the extent the way
            // the chain's below is.
            (
                RenderEffects::REFLECTIONS,
                u64::from(Ssr::PASSES) + u64::from(crate::hiz::levels_for(TEST_EXTENT)),
            ),
            // Not a constant, unlike the occlusion pair above: the chain's
            // length is a function of the extent, and this is what it is at
            // `TEST_EXTENT`.
            (
                RenderEffects::BLOOM,
                u64::from(Bloom::passes_for(TEST_EXTENT)),
            ),
        ] {
            let (counters, instances, atlas) = frame_switching_off(off);
            assert_eq!(
                counters.draws,
                control.draws - fewer * FULLSCREEN_DRAWS,
                "{off:?}: the frame must record one draw fewer per pass it did not add"
            );
            assert_eq!(
                counters.instances,
                instances
                    + fullscreen_passes(
                        RenderEffects::all().difference(off),
                        TEST_EXTENT,
                        false,
                        crate::ssao::blur_passes(),
                    ) * FULLSCREEN_DRAWS,
                "{off:?}: and must not report as submitted a triangle it never submitted"
            );
            assert_eq!(
                atlas, atlas_draws,
                "{off:?}: a screen-space effect must not touch the shadow atlas"
            );
        }

        // Shadows: the atlas pass survives and draws nothing at all, which is
        // the mechanism — a cleared reversed-Z atlas reads as fully lit.
        let (counters, _, atlas) = frame_switching_off(RenderEffects::SHADOWS);
        assert_eq!(
            atlas, 0,
            "with shadows off the atlas pass must record its clear and no draw"
        );
        assert_eq!(
            counters.draws,
            control.draws - atlas_draws as u64,
            "and the frame must record exactly the atlas pass's draws fewer"
        );
    }

    /// **Every pass the frame records gets a row in the report, except the ones
    /// that open no scope.**
    ///
    /// The observable the bound exists for: the samples' hand-picked capacity
    /// timed the first eight passes of a fourteen-pass frame and reported eight
    /// rows, which reads exactly like a frame that has eight passes. Sized from
    /// [`MAX_TIMED_PASSES`](crate::MAX_TIMED_PASSES), the report names every
    /// pass the graph compiled, in order — so a bound one short of the frame
    /// makes this list short too.
    ///
    /// A [`PassKind::Copy`](crate::graph::PassKind::Copy) is filtered out of the
    /// expectation rather than expected to be missing by accident. The seam
    /// takes a timestamp only where a pass opens and closes and a copy opens
    /// nothing, so `PassTimers` gives it no query pair and no row — a row
    /// reading 0.000 ms would be a measurement nobody made.
    #[test]
    fn every_pass_of_the_frame_gets_a_timing_row() {
        let _blurs = ssao_blur_switch();
        // And the comparison seam, so the frame this checks carries the
        // occlusion chain's second march: `docs/plan/ROADMAP.md`'s S4D row asks
        // for a *per-technique* cost, and what makes that true is this test's
        // own claim — every pass that opens a scope gets a row — applied to a
        // frame that compares. See `crate::ssao`'s `r_ssao_split`.
        let split = ssao_split_switch();
        split.set(0.5);
        let recorder = Recorder::new();
        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
        let adapter = instance.adapters().remove(0);
        // `TIMESTAMP_QUERY` is not part of `GPU_DRIVEN` — topic 10's browsers
        // may lack it — so a device that wants timers has to ask for it, and
        // `open` above, which uses `DeviceDesc::for_adapter`, does not.
        let opened = instance
            .create_device(&DeviceDesc {
                label: Some("timed frame"),
                adapter: adapter.id,
                required_features: Features::GPU_DRIVEN,
                optional_features: Features::TIMESTAMP_QUERY,
                compatible_surface: None,
            })
            .expect("the null backend always opens");
        let queue = opened.queue(QueueKind::Graphics).expect("always present");
        let device = opened.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        renderer.set_lights(&[shadowable_spot(-1.0), shadowable_spot(1.0)]);
        let mut timers = crate::PassTimers::new(device, FRAMES_IN_FLIGHT, crate::MAX_TIMED_PASSES)
            .expect("the tier A null adapter has timestamp queries");
        let imported = swapchain_image(device);
        let mut pool = crate::TransientPool::new();
        let mut recorded = Vec::new();
        let mut compiled_labels = Vec::new();

        // The ring is one slot longer than the frames in flight and resolves a
        // slot only when it comes round again, so the first frame's report is
        // that many frames behind it — see the [`timing`](crate::timing) docs.
        for _ in 0..FRAMES_IN_FLIGHT + 2 {
            renderer
                .begin_frame(
                    device,
                    &Camera::default(),
                    &DirectionalLight::default(),
                    (64, 48),
                )
                .expect("write");
            let mut graph = crate::RenderGraph::new(queue);
            let target = graph.import_image("target", imported);
            renderer.add_passes(&mut graph, &pool, target, (64, 48));
            let compiled = graph.compile(&pool).expect("a legal frame");
            if compiled_labels.is_empty() {
                compiled_labels = compiled
                    .passes()
                    .iter()
                    .filter(|pass| pass.kind() != crate::graph::PassKind::Copy)
                    .map(|pass| pass.label().to_string())
                    .collect();
            }
            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
                label: Some("timed frame"),
                queue,
            });
            compiled
                .execute(device, &mut pool, encoder.as_mut(), Some(&mut timers))
                .expect("the graph executed");
            recorded.push(encoder.finish().expect("recording succeeded"));
        }

        let reported: Vec<&str> = timers
            .latest()
            .passes
            .iter()
            .map(|timing| timing.label.as_str())
            .collect();
        // Anti-vacuity for the seam held above: a frame that did not compare
        // would satisfy the equality below and say nothing about a
        // per-technique cost, because there would be one technique in it.
        for label in ["ssao", "ssao-shipped"] {
            assert!(
                compiled_labels.iter().any(|pass| pass == label),
                "the frame compiled no `{label}` pass, so the seam did not reach it and this \
                 test says nothing about a comparison having a cost per side. Its passes: \
                 {compiled_labels:?}"
            );
        }
        assert_eq!(
            reported,
            compiled_labels,
            "the report must name every pass the frame compiled that opens a scope, in order \
             — {} of {} timed with a capacity of {}",
            reported.len(),
            compiled_labels.len(),
            timers.capacity()
        );

        timers.destroy(device);
        renderer.destroy(device);
        for commands in recorded {
            device.destroy_command_buffer(commands);
        }
        pool.destroy(device);
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// One mesh-table entry, decoded from the bytes that reached the device.
    fn mesh_entry(
        recorder: &Recorder,
        renderer: &ForwardRenderer,
        id: u32,
    ) -> crcbl_shaders::mesh::GpuMesh {
        let table = recorder
            .buffer_bytes(renderer.pool.table_buffer())
            .expect("the table is live");
        let at = id as usize * crcbl_shaders::mesh::MESH_ENTRY_STRIDE;
        crcbl_shaders::mesh::GpuMesh::from_bytes(
            table[at..at + crcbl_shaders::mesh::MESH_ENTRY_STRIDE]
                .try_into()
                .expect("one whole entry"),
        )
    }

    // --- skinning: the seam a caller draws a skinned mesh through -----------

    /// A renderer with [`scene::demo`]'s cube reserved for skinning, and a
    /// [`Skinning`] built against that renderer's own vertex pool.
    struct SkinnedFixture {
        renderer: ForwardRenderer,
        skinning: Skinning,
        skinned: SkinnedMesh,
        palette: Vec<Mat4>,
        bindings: Vec<crcbl_shaders::skinning::SkinBinding>,
    }

    impl SkinnedFixture {
        fn build(device: &dyn Device, queue: QueueHandle) -> Self {
            let mut renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb)
                .expect("the null backend accepts every descriptor");
            let skinned = renderer
                .reserve_skinned(DEMO_CUBE)
                .expect("a default pool has room for two halves of a cube");
            let skinning = Skinning::new(
                device,
                &crate::skinning::SkinningDesc {
                    label: Some("skinned fixture"),
                    frames: FRAMES_IN_FLIGHT,
                    ranges: 1,
                    joints: 1,
                    bindings: skinned.vertex_count(),
                    // The renderer's own pool, which is the whole of what makes
                    // the dispatch's output reachable by its draws.
                    vertices: renderer.vertex_buffer(),
                    attribute_base: renderer.attribute_base(),
                },
            )
            .expect("the null backend accepts every descriptor");
            let bindings = vec![
                crcbl_shaders::skinning::SkinBinding {
                    joints: [0; crcbl_shaders::skinning::JOINTS_PER_VERTEX],
                    weights: [1.0, 0.0, 0.0, 0.0],
                };
                skinned.vertex_count() as usize
            ];
            Self {
                renderer,
                skinning,
                skinned,
                palette: vec![Mat4::IDENTITY],
                bindings,
            }
        }

        /// One skinned frame's `begin_skinned_frame`, with this fixture's single
        /// range.
        fn begin(&mut self, device: &dyn Device) {
            let range = self.skinned.skin_range(&self.palette, &self.bindings);
            self.renderer
                .begin_skinned_frame(
                    device,
                    &mut self.skinning,
                    &[range],
                    &Camera::default(),
                    &DirectionalLight::default(),
                    TEST_EXTENT,
                )
                .expect("a legal skinning plan");
        }

        fn destroy(mut self, device: &dyn Device) {
            self.renderer.release_skinned(self.skinned);
            self.skinning.destroy(device);
            self.renderer.destroy(device);
        }
    }

    /// How many times the host wrote the mesh-table entry `id` names.
    fn table_writes(recorder: &Recorder, renderer: &ForwardRenderer, id: u32) -> usize {
        let table = renderer.pool.table_buffer();
        let at = u64::from(id) * crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u64;
        recorder
            .events()
            .into_iter()
            .filter(|event| {
                matches!(
                    event,
                    crcbl_hal::null::Event::BufferWritten { buffer, offset, .. }
                        if *buffer == table && *offset == at
                )
            })
            .count()
    }

    /// The record `handle` names, out of the ring buffer **this frame draws
    /// from** rather than out of the pool's host mirror.
    ///
    /// A mirror and a buffer that disagree is exactly the defect a re-pointing
    /// design can have, so every claim about a skinned instance's bases is read
    /// off the bytes a shader would.
    fn instance_record(
        recorder: &Recorder,
        renderer: &ForwardRenderer,
        handle: InstanceHandle,
    ) -> mesh::GpuInstance {
        let buffer = renderer.instances.buffers()[renderer.frame()];
        let bytes = recorder.buffer_bytes(buffer).expect("the ring is live");
        let index = renderer
            .instances
            .index(handle)
            .expect("the object is live") as usize;
        let at = index * mesh::INSTANCE_STRIDE;
        mesh::GpuInstance::from_bytes(
            bytes[at..at + mesh::INSTANCE_STRIDE]
                .try_into()
                .expect("one whole instance"),
        )
    }

    /// **A skinned primitive takes no mesh-table entry of its own, and nothing
    /// rewrites the one it draws through.**
    ///
    /// [`crate::mesh_pool`]'s table is one host-visible buffer rather than a ring
    /// precisely because nothing rewrites an entry between frames, so a design
    /// that re-pointed an entry at the half a frame writes would be wrong only
    /// on the frames that overlap — which is to say invisibly. What alternates
    /// instead is a field of the *instance*, and instances go through a ring.
    ///
    /// So a skinned object draws through the source mesh's own entry: the same
    /// id [`add_instance`](ForwardRenderer::add_instance) would give it, still
    /// carrying the bind pose's base vertex, still written exactly once after
    /// four skinned frames. That shared entry is also what lets one mesh be
    /// drawn skinned and unskinned in the same frame.
    #[test]
    fn a_skinned_mesh_takes_no_table_entry_and_rewrites_none() {
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut fixture = SkinnedFixture::build(device, queue);

        let bind_pose_id = fixture.renderer.mesh_ids[DEMO_CUBE];
        assert_eq!(
            fixture.skinned.mesh_id(),
            bind_pose_id,
            "a skinned instance names the mesh it was deformed from, so the bucket, the level \
             tables and the bounding box all resolve as the bind pose's"
        );

        let bind_pose = mesh_entry(&recorder, &fixture.renderer, bind_pose_id);
        assert_eq!(
            bind_pose.base_vertex,
            fixture.skinned.input_base(),
            "the entry goes on naming the bind pose the dispatch reads, not either half it \
             writes"
        );
        for parity in 0..2 {
            assert_ne!(
                fixture.skinned.region().base(parity),
                bind_pose.base_vertex,
                "half {parity} must not be the bind pose, which the kernel reads while it \
                 writes them"
            );
        }
        assert_ne!(
            fixture.skinned.region().base(0),
            fixture.skinned.region().base(1),
            "the two halves are separate reservations, or the ping-pong is one buffer"
        );

        // Counted before the frames rather than compared against a literal:
        // `MeshPool::new` clears the whole table with one write at offset zero,
        // which lands on this entry too, so the number here is the pool's
        // start-up and not this test's business. What the loop below has to
        // leave alone is whatever it is.
        let writes_before = table_writes(&recorder, &fixture.renderer, bind_pose_id);
        assert!(
            writes_before > 0,
            "the entry was written at least once before any frame ran, or the counter below \
             is counting nothing and the comparison after the frames is vacuous"
        );

        // Four frames, which is two of each parity: enough that a design
        // rewriting an entry per frame would have written four more times.
        let imported = swapchain_image_at(device, TEST_EXTENT);
        let mut pool = crate::TransientPool::new();
        for _ in 0..4 {
            fixture.begin(device);
            let mut graph = crate::RenderGraph::new(queue);
            let target = graph.import_image("target", imported);
            fixture.renderer.add_skinned_passes(
                &mut graph,
                &pool,
                target,
                TEST_EXTENT,
                &fixture.skinning,
            );
            graph.compile(&pool).expect("a legal frame");
        }

        assert_eq!(
            table_writes(&recorder, &fixture.renderer, bind_pose_id),
            writes_before,
            "entry {bind_pose_id} was written again by a skinned frame; the whole reason this \
             table is one buffer rather than a ring is that nothing rewrites an entry between \
             frames"
        );

        fixture.destroy(device);
        pool.destroy(device);
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// **A skinned object's recorded base vertex follows the parity of the frame
    /// it is drawn in**, and it carries the bit that makes a shader read it.
    ///
    /// The other half of the design: the table entry never moves, so what has to
    /// alternate is a field of the *instance* — and it has to alternate in the
    /// buffer the frame actually draws from, which is why this reads the
    /// instance ring's bytes rather than the host's mirror.
    ///
    /// Three claims, and the last two are what stop the first being vacuous. The
    /// base must be the one this frame's parity names; the record must carry
    /// [`GpuInstance::BASE_VERTEX_OVERRIDE`](mesh::GpuInstance::BASE_VERTEX_OVERRIDE),
    /// without which the raster stages read the mesh entry and the field is
    /// decoration; and two consecutive frames must have named **different**
    /// halves, without which a renderer ignoring the parity entirely would pass.
    #[test]
    fn a_skinned_draw_carries_the_base_the_frames_dispatch_filled() {
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut fixture = SkinnedFixture::build(device, queue);
        let handle = fixture
            .renderer
            .add_skinned_instance(&SkinnedInstanceDesc {
                mesh: &fixture.skinned,
                material: DEMO_UNTINTED,
                transform: Mat4::IDENTITY,
            })
            .expect("a pool of thousands has room for one object");

        let mut carried = Vec::new();
        for _ in 0..2 {
            fixture.begin(device);
            let parity = fixture.skinning.parity();
            let instance = instance_record(&recorder, &fixture.renderer, handle);
            assert_eq!(
                instance.base_vertex,
                fixture.skinned.region().base(parity),
                "the buffer this frame draws from must carry the base parity {parity} writes"
            );
            assert_eq!(
                instance.flags & mesh::GpuInstance::BASE_VERTEX_OVERRIDE,
                mesh::GpuInstance::BASE_VERTEX_OVERRIDE,
                "without the bit the raster stages resolve the mesh entry's base and this \
                 field is never read"
            );
            assert_eq!(
                instance.mesh, fixture.renderer.mesh_ids[DEMO_CUBE],
                "and the record still names the source mesh, which is what its bucket, its \
                 levels and its bounding box resolve through"
            );
            carried.push(instance.base_vertex);
        }
        assert_ne!(
            carried[0], carried[1],
            "two consecutive frames must have drawn different halves, or a renderer that \
             ignored the parity entirely would pass this"
        );

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

    /// **A skinned object's record names the half the frame before it filled**,
    /// and it starts at rest.
    ///
    /// The other half of a skinned motion vector. The base above is where a
    /// fragment *is*; this is where it *was*, and without it the geometry stages
    /// put the previous transform through this frame's deformed vertex — so a
    /// limb that swung reports the motion of the body it hangs off. See
    /// [`GpuInstance::previous_base_vertex`](mesh::GpuInstance::previous_base_vertex).
    ///
    /// Four claims, and the first and last are what stop the middle two being a
    /// restatement of the parity:
    ///
    /// * the **first** frame of a fresh object writes the base it draws out of,
    ///   because the other half holds whatever its reservation came with and a
    ///   motion vector against undefined vertices is worse than no motion;
    /// * the frames after it write
    ///   [`SkinnedRegion::previous_base`](crate::skinning::SkinnedRegion::previous_base),
    ///   which must also **differ** from the base they draw out of — a renderer
    ///   that wrote the current base into both lanes would satisfy every "it is
    ///   a legal base" reading of this and leave every skinned instance at rest;
    /// * and moving the object onto a **different region** puts it back at rest
    ///   for one frame, because the halves it now names are two runs it has
    ///   never been drawn out of.
    #[test]
    fn a_skinned_draw_carries_the_previous_half_and_starts_at_rest() {
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut fixture = SkinnedFixture::build(device, queue);
        let handle = fixture
            .renderer
            .add_skinned_instance(&SkinnedInstanceDesc {
                mesh: &fixture.skinned,
                material: DEMO_UNTINTED,
                transform: Mat4::IDENTITY,
            })
            .expect("a pool of thousands has room for one object");

        for frame in 1..=3u32 {
            fixture.begin(device);
            let parity = fixture.skinning.parity();
            let instance = instance_record(&recorder, &fixture.renderer, handle);
            assert_eq!(
                instance.base_vertex,
                fixture.skinned.region().base(parity),
                "frame {frame} must draw out of the half parity {parity} fills"
            );
            if frame == 1 {
                assert_eq!(
                    instance.previous_base_vertex, instance.base_vertex,
                    "a fresh object has no previous deformation, so its first frame owes rest \
                     rather than a half no dispatch has written"
                );
            } else {
                assert_eq!(
                    instance.previous_base_vertex,
                    fixture.skinned.region().previous_base(parity),
                    "frame {frame} must subtract against the half the frame before it filled"
                );
                assert_ne!(
                    instance.previous_base_vertex, instance.base_vertex,
                    "frame {frame} named one half twice, which is every skinned fragment at \
                     rest however far its surface moved"
                );
            }
        }

        // The same object, moved onto a region it has never been drawn out of:
        // both halves are runs no dispatch of this object's has filled, so the
        // rule that put the first frame at rest applies again.
        let second = fixture
            .renderer
            .reserve_skinned(DEMO_CUBE)
            .expect("a default pool has room for two more halves of a cube");
        assert_ne!(
            second.region().base(0),
            fixture.skinned.region().base(0),
            "the second reservation is the same two runs as the first, so nothing below is \
             about a change of region at all"
        );
        fixture.renderer.set_skinned_instance(
            handle,
            &SkinnedInstanceDesc {
                mesh: &second,
                material: DEMO_UNTINTED,
                transform: Mat4::IDENTITY,
            },
        );

        for frame in 1..=2u32 {
            fixture.begin(device);
            let parity = fixture.skinning.parity();
            let instance = instance_record(&recorder, &fixture.renderer, handle);
            assert_eq!(
                instance.base_vertex,
                second.region().base(parity),
                "frame {frame} after the move must draw out of the new region"
            );
            if frame == 1 {
                assert_eq!(
                    instance.previous_base_vertex, instance.base_vertex,
                    "the first frame on a new region owes rest, exactly as a fresh object does"
                );
            } else {
                assert_eq!(
                    instance.previous_base_vertex,
                    second.region().previous_base(parity),
                    "and the frame after it is subtracting against the new region's other half"
                );
            }
        }

        fixture.renderer.release_skinned(second);
        fixture.destroy(device);
        recorder.assert_valid();
    }

    /// **A skinned object that moves carries the transform it moved from**, and
    /// the frame after it is back at rest.
    ///
    /// The transform half of a skinned motion vector, and the half the
    /// per-frame re-point used to erase: it rewrote the record through
    /// [`InstancePool::set`], which fills the previous transform out of the
    /// record it overwrites — and that record already held this frame's
    /// transform, because
    /// [`set_skinned_instance`](ForwardRenderer::set_skinned_instance) had put
    /// it there. Every skinned instance then read `previous_transform ==
    /// transform` on every frame, so a character that walked contributed
    /// nothing to the motion target from the walk, only from its deformation.
    /// [`InstancePool::set_bases`] is what the re-point goes through instead.
    ///
    /// Both frames are the claim. Without the second, a re-point that wrote
    /// some *other* stale transform into the field would pass; and the second
    /// is the pool's own rest rule reaching a skinned object at all, which a
    /// re-point that kept enrolling the element every frame would suppress
    /// for ever.
    ///
    /// Read out of the ring buffer the frame draws from, on
    /// [`instance_record`]'s terms.
    #[test]
    fn a_skinned_instance_that_moves_carries_the_transform_it_moved_from() {
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut fixture = SkinnedFixture::build(device, queue);
        let handle = fixture
            .renderer
            .add_skinned_instance(&SkinnedInstanceDesc {
                mesh: &fixture.skinned,
                material: DEMO_UNTINTED,
                transform: Mat4::IDENTITY,
            })
            .expect("a pool of thousands has room for one object");

        // Two frames standing still, so the history the move is measured
        // against is a settled record rather than a fresh one.
        fixture.begin(device);
        fixture.begin(device);

        let moved = Mat4::from_translation(Vec3::new(5.0, 0.0, 0.0));
        fixture.renderer.set_skinned_instance(
            handle,
            &SkinnedInstanceDesc {
                mesh: &fixture.skinned,
                material: DEMO_UNTINTED,
                transform: moved,
            },
        );
        fixture.begin(device);
        let instance = instance_record(&recorder, &fixture.renderer, handle);
        assert_eq!(
            instance.transform,
            moved.to_cols_array(),
            "the frame that moved the object must draw it where it arrived"
        );
        assert_eq!(
            instance.previous_transform,
            Mat4::IDENTITY.to_cols_array(),
            "and it must say where from — a previous transform equal to the current one is \
             the re-point having overwritten the move"
        );

        fixture.begin(device);
        let settled = instance_record(&recorder, &fixture.renderer, handle);
        assert_eq!(
            settled.transform,
            moved.to_cols_array(),
            "nothing moved it again"
        );
        assert_eq!(
            settled.previous_transform, settled.transform,
            "so the frame after the move owes rest; a re-point that enrolled the element \
             every frame would keep it reporting the move for ever"
        );

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

    /// **The graph barriers the skinning dispatch's write before every pass that
    /// pulls vertices**, and it does so because `add_skinned_passes` added the
    /// dispatch itself rather than trusting a caller to.
    ///
    /// Pass order alone would not settle it — a dispatch that ran first and was
    /// never barriered is the exact defect, and it produces a correct-looking
    /// frame on a desktop driver. So the transition out of
    /// [`ResourceState::ShaderReadWrite`] is named: there must be exactly one,
    /// it must sit after the dispatch, and it must sit at or before the first of
    /// the three passes that draw.
    #[test]
    fn the_skinning_dispatch_is_barriered_before_every_pass_that_draws() {
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut fixture = SkinnedFixture::build(device, queue);
        place_cube(&mut fixture.renderer, Mat4::IDENTITY);
        fixture
            .renderer
            .add_skinned_instance(&SkinnedInstanceDesc {
                mesh: &fixture.skinned,
                material: DEMO_UNTINTED,
                transform: Mat4::IDENTITY,
            })
            .expect("room for one object");
        fixture.begin(device);

        let imported = swapchain_image_at(device, TEST_EXTENT);
        let mut pool = crate::TransientPool::new();
        let mut graph = crate::RenderGraph::new(queue);
        let target = graph.import_image("target", imported);
        // The same node `Skinning::add_pass` imports — one handle is one node —
        // so the barriers below can be named rather than guessed at.
        let vertices = graph.import_buffer(
            "vertex-pool",
            ImportedBuffer {
                buffer: fixture.renderer.vertex_buffer(),
                initial: ResourceState::ShaderRead,
                final_state: ResourceState::ShaderRead,
            },
        );
        fixture.renderer.add_skinned_passes(
            &mut graph,
            &pool,
            target,
            TEST_EXTENT,
            &fixture.skinning,
        );
        let compiled = graph.compile(&pool).expect("a legal frame");
        let labels: Vec<&str> = compiled
            .passes()
            .iter()
            .map(crate::graph::CompiledPass::label)
            .collect();

        let dispatch = labels
            .iter()
            .position(|label| *label == "skinning")
            .expect("add_skinned_passes adds the dispatch itself");
        let drawing: Vec<usize> = ["shadow", "depth-prepass", "forward"]
            .into_iter()
            .map(|wanted| {
                labels
                    .iter()
                    .position(|label| *label == wanted)
                    .unwrap_or_else(|| panic!("the frame draws through {wanted}: {labels:?}"))
            })
            .collect();
        for (label, at) in ["shadow", "depth-prepass", "forward"]
            .into_iter()
            .zip(&drawing)
        {
            assert!(
                dispatch < *at,
                "the dispatch is at {dispatch} and {label} at {at}: {labels:?}"
            );
        }

        // Each drawing pass declares the read for itself, and this is asserted
        // per pass rather than left to the single barrier below. The graph
        // transitions the region once, before the first reader, and a later
        // pass that never declared the read finds it already in the state it
        // wanted — so dropping the declaration from `forward` alone changes no
        // barrier and moves no label, and every assertion in this test still
        // passes. What it does drop is that pass's *dependency* on the
        // dispatch, which is the only thing keeping the two in this order.
        for (label, at) in ["shadow", "depth-prepass", "forward"]
            .into_iter()
            .zip(&drawing)
        {
            assert!(
                compiled.passes()[*at].reads_buffer(vertices),
                "{label} draws skinned vertices and must declare that it reads them, or \
                 nothing but declaration order keeps it after the dispatch"
            );
        }

        let released: Vec<usize> = compiled
            .passes()
            .iter()
            .enumerate()
            .filter(|(_, pass)| {
                pass.barriers().buffers.iter().any(|barrier| {
                    barrier.buffer == vertices
                        && barrier.from == ResourceState::ShaderReadWrite
                        && barrier.to == ResourceState::ShaderRead
                })
            })
            .map(|(at, _)| at)
            .collect();
        assert_eq!(
            released.len(),
            1,
            "exactly one transition out of the dispatch's write: {released:?} in {labels:?}"
        );
        let barrier = released[0];
        let first_draw = *drawing.iter().min().expect("three passes");
        assert!(
            dispatch < barrier && barrier <= first_draw,
            "the barrier is at {barrier}, the dispatch at {dispatch} and the first pass that \
             draws at {first_draw} — a draw that reads the region before the write is made \
             visible is the whole defect this seam exists to prevent"
        );

        drop(compiled);
        fixture.destroy(device);
        pool.destroy(device);
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// A frame with nothing to skin adds no dispatch and declares no read, and
    /// is the frame [`ForwardRenderer::add_passes`] would have built.
    #[test]
    fn a_frame_with_no_skinned_range_is_the_frame_add_passes_builds() {
        let _blurs = ssao_blur_switch();
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut fixture = SkinnedFixture::build(device, queue);
        place_cube(&mut fixture.renderer, Mat4::IDENTITY);

        let imported = swapchain_image_at(device, TEST_EXTENT);
        let pool = crate::TransientPool::new();
        let mut skinned_labels = Vec::new();
        for _ in 0..1 {
            fixture
                .renderer
                .begin_skinned_frame(
                    device,
                    &mut fixture.skinning,
                    &[],
                    &Camera::default(),
                    &DirectionalLight::default(),
                    TEST_EXTENT,
                )
                .expect("an empty plan is a legal one");
            let mut graph = crate::RenderGraph::new(queue);
            let target = graph.import_image("target", imported);
            fixture.renderer.add_skinned_passes(
                &mut graph,
                &pool,
                target,
                TEST_EXTENT,
                &fixture.skinning,
            );
            skinned_labels = graph
                .compile(&pool)
                .expect("a legal frame")
                .passes()
                .iter()
                .map(|pass| pass.label().to_string())
                .collect();
        }
        let plain = passes_in_a_frame(
            device,
            queue,
            &mut fixture.renderer,
            imported,
            &pool,
            TEST_EXTENT,
        );
        assert_eq!(
            skinned_labels, plain,
            "a frame with nothing to skin must cost the vertex pool no barrier at all"
        );

        fixture.destroy(device);
        let mut pool = pool;
        pool.destroy(device);
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// One frame recorded end to end: `begin_frame`, the graph, and an encoder
    /// the commands land in.
    ///
    /// Returned rather than cleaned up here because the caller reads the
    /// recorder afterwards, and everything below must outlive that.
    struct Frame {
        imported: ImportedImage,
        pool: crate::TransientPool,
        commands: crcbl_hal::CommandBufferHandle,
    }

    impl Frame {
        /// Releases the frame and the image it drew into, leaving the renderer
        /// alive for another one.
        fn release(self, device: &dyn Device) {
            device.destroy_command_buffer(self.commands);
            let mut pool = self.pool;
            pool.destroy(device);
            device.destroy_image_view(self.imported.view);
            device.destroy_image(self.imported.image);
        }

        /// Releases the frame, the renderer and the image it drew into.
        fn finish(self, device: &dyn Device, renderer: ForwardRenderer) {
            self.release(device);
            renderer.destroy(device);
        }
    }

    /// Everything one labelled pass recorded, and nothing any other pass did.
    ///
    /// **Every draw assertion below is scoped through this**, and the reason is
    /// topic 18: the frame now records the same indirect call the colour pass
    /// records once per shadow cascade as well, out of that cascade's own
    /// arguments. A test filtering the whole stream for `DrawIndexedIndirect`
    /// would see one per cascade as well as the colour pass's, and could not
    /// say which pass any of them belonged to — so "the forward pass records one
    /// call per bucket" would become a claim about a total, which a shadow pass
    /// recording the wrong thing could satisfy.
    /// The compute dispatches a default frame's **resolve** records, which
    /// every dispatch count in this module sees and none of them is about.
    ///
    /// `RenderEffects::DEFAULT_STACK` carries `CMAA2`, whose edge detect and
    /// shape classification are dispatches; its apply is a draw and does not
    /// count here. `each_effect_toggle_removes_exactly_the_passes_it_owns` is
    /// what pins the resolve's pass list itself, so a tier that grew a dispatch
    /// fails there first and arrives here as a second red rather than as a
    /// silent skew.
    const RESOLVE_DISPATCHES: usize = 2;

    fn commands_in_pass(
        recorder: &crcbl_hal::null::Recorder,
        label: &str,
    ) -> Vec<crcbl_hal::null::Command> {
        use crcbl_hal::null::Command;

        let mut inside = false;
        let mut out = Vec::new();
        for command in recorder.commands() {
            if let Some((_, recorded)) = command.opens_pass() {
                inside = recorded == Some(label);
                continue;
            }
            if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
                inside = false;
                continue;
            }
            if inside {
                out.push(command);
            }
        }
        assert!(!out.is_empty(), "no pass labelled `{label}` recorded work");
        out
    }

    /// The extent every helper frame in this module is drawn at.
    ///
    /// Named since the bloom chain, whose length is a function of it — see
    /// [`crate::bloom`] — so a test comparing a pass count against
    /// [`fullscreen_passes`] has to ask about the same size the frame was drawn
    /// at. Small on purpose: two chain levels is enough for every arm here, and
    /// [`the_pass_bound_is_the_widest_frame_the_renderer_records`] is the one
    /// test that needs a frame large enough for six.
    ///
    /// [`the_pass_bound_is_the_widest_frame_the_renderer_records`]: fn@the_pass_bound_is_the_widest_frame_the_renderer_records
    const TEST_EXTENT: (u32, u32) = (64, 48);

    /// The effects a caller has to ask for, because the default stack leaves
    /// them out — see [`RenderEffects::DEFAULT_STACK`].
    ///
    /// Named rather than written out at each of the three sites that force them
    /// on, because the point of those sites is "every effect there is" and the
    /// bug they exist to catch is a new effect joining the set and one site
    /// still measuring the old one while calling it the whole stack. They are
    /// held out of the default for different reasons — [`crate::effects`] gives
    /// each, and [`RenderEffects::CONTACT_SHADOWS`]'s is the only one that is a
    /// pending re-bless rather than a decision — and share only that a test
    /// wanting the widest frame must ask.
    ///
    /// **Named for what it is rather than for what most of it is**: the set held
    /// four post passes and a resolve when it was `POST_EFFECTS`, and the contact
    /// march is neither.
    const OUTSIDE_THE_DEFAULT: RenderEffects = RenderEffects::BLOOM
        .union(RenderEffects::ANTIALIASING)
        .union(RenderEffects::VOLUMETRIC_FOG)
        .union(RenderEffects::AUTO_EXPOSURE)
        .union(RenderEffects::CMAA2)
        .union(RenderEffects::CONTACT_SHADOWS);

    /// Every effect this renderer draws is either in the default stack or in
    /// [`OUTSIDE_THE_DEFAULT`].
    ///
    /// The guard on the three sites above: they force [`OUTSIDE_THE_DEFAULT`] on and
    /// call the result "every effect", which is only true while nothing else is
    /// held out. An effect added outside the default stack and not added
    /// here makes this red before it makes a pass-list assertion red — which is
    /// the useful order, since a pass list going red says a label moved and this
    /// says what actually happened.
    #[test]
    fn forcing_the_post_effects_on_reaches_every_effect_there_is() {
        assert_eq!(
            RenderEffects::DEFAULT_STACK.union(OUTSIDE_THE_DEFAULT),
            RenderEffects::all(),
            "an effect outside the default stack that no test forces on is an effect \
             the every-effect frames below have never drawn"
        );
    }

    /// The default sun, turned a little further round for each `lap`.
    ///
    /// Topic 45's static-caching rung means a second frame over
    /// a scene nothing moved in records **no shadow pass at all** — see
    /// [`ForwardRenderer::shadow_atlas_cached`]. That is the feature, and it is
    /// a difference that every A/B drawing two frames from one renderer would
    /// otherwise be measuring on top of the one it is about. Turning the sun is
    /// the smallest input the atlas depends on: the cascades are refitted, so
    /// the atlas is redrawn, and no pass, pipeline or draw of the frame moves
    /// with it.
    ///
    /// Lap zero is [`DirectionalLight::default`] exactly, so a test whose first
    /// frame is the ordinary one keeps the frame every other test draws.
    fn moving_sun(lap: u32) -> DirectionalLight {
        let sun = DirectionalLight::default();
        // A degree a lap, about the axis the default direction is not parallel
        // to. Small enough that every cascade still sees the scene, and large
        // enough that the snapped cascade origin actually moves.
        let turn = Mat4::from_rotation_y(
            f32::from(u16::try_from(lap).expect("a handful of laps")) * std::f32::consts::PI
                / 180.0,
        );
        DirectionalLight {
            direction: turn.transform_vector3(sun.direction).normalize(),
            ..sun
        }
    }

    /// [`frame`] drawn under [`moving_sun`], so this frame's shadow atlas is
    /// not the one the lap before it left in the image.
    fn frame_moving_the_sun(
        device: &dyn Device,
        renderer: &mut ForwardRenderer,
        queue: QueueHandle,
        lap: u32,
    ) -> Frame {
        frame_lit_by(device, renderer, queue, &moving_sun(lap))
    }

    fn frame(device: &dyn Device, renderer: &mut ForwardRenderer, queue: QueueHandle) -> Frame {
        frame_lit_by(device, renderer, queue, &DirectionalLight::default())
    }

    fn frame_lit_by(
        device: &dyn Device,
        renderer: &mut ForwardRenderer,
        queue: QueueHandle,
        sun: &DirectionalLight,
    ) -> Frame {
        frame_seen_from(device, renderer, queue, &Camera::default(), sun)
    }

    fn frame_seen_from(
        device: &dyn Device,
        renderer: &mut ForwardRenderer,
        queue: QueueHandle,
        camera: &Camera,
        sun: &DirectionalLight,
    ) -> Frame {
        renderer
            .begin_frame(device, camera, sun, TEST_EXTENT)
            .expect("write");
        let imported = swapchain_image(device);
        let mut graph = crate::RenderGraph::new(queue);
        let target = graph.import_image("target", imported);
        let mut pool = crate::TransientPool::new();
        renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
        let compiled = graph.compile(&pool).expect("a legal frame");
        let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
            label: Some("forward frame"),
            queue,
        });
        compiled
            .execute(device, &mut pool, encoder.as_mut(), None)
            .expect("the graph executed");
        let commands = encoder.finish().expect("recording succeeded");
        Frame {
            imported,
            pool,
            commands,
        }
    }

    /// A stand-in for the acquired swapchain image the frame normally ends in,
    /// at [`TEST_EXTENT`].
    fn swapchain_image(device: &dyn Device) -> ImportedImage {
        swapchain_image_at(device, TEST_EXTENT)
    }

    /// The same, at an extent of the caller's choosing.
    ///
    /// A frame's attachments must all be one size — the graph refuses a pass
    /// whose colour target and depth disagree — so a test drawing at anything
    /// but [`TEST_EXTENT`] has to import a target of that size too.
    pub(super) fn swapchain_image_at(device: &dyn Device, extent: (u32, u32)) -> ImportedImage {
        let format = Format::Rgba8UnormSrgb;
        let image = device
            .create_image(&crcbl_hal::ImageDesc {
                label: Some("fake swapchain image"),
                image_type: crcbl_hal::ImageType::D2,
                extent: crcbl_hal::Extent3d::d2(extent.0, extent.1),
                format,
                mip_levels: 1,
                samples: 1,
                usage: crcbl_hal::ImageUsage::COLOR_ATTACHMENT | crcbl_hal::ImageUsage::PRESENT,
            })
            .expect("an image");
        let view = device
            .create_image_view(&crcbl_hal::ImageViewDesc {
                label: Some("fake swapchain view"),
                image,
                view_type: crcbl_hal::ImageViewType::D2,
                format,
                range: crcbl_hal::ImageSubresourceRange::all(format),
            })
            .expect("a view");
        ForwardRenderer::present_target(image, view, format, extent)
    }

    /// The spin is a rotation: no scale, no shear, so the cube neither grows
    /// nor mirrors as it turns, and every mesh golden blessed at a `spin` is a
    /// picture of one cube.
    ///
    /// That is also what keeps those goldens insensitive to `mesh.slang`'s
    /// `normal_basis`. A matrix with orthonormal rows and a positive
    /// determinant is its own cofactor matrix, to within a rounding step, so
    /// the vertex stage writes the normals it wrote when it multiplied by the
    /// bare 3×3 — see [`crcbl_shaders::mesh::GpuInstance::transform`], which no
    /// longer requires a caller to be rigid at all.
    #[test]
    fn the_spin_matrix_stays_rigid() {
        for seconds in [0.0f32, 0.5, 3.25, 100.0] {
            let model = ForwardRenderer::spin(seconds);
            let basis = glam::Mat3::from_mat4(model);
            let product = basis * basis.transpose();
            for (row, expected) in [
                (product.x_axis, Vec3::X),
                (product.y_axis, Vec3::Y),
                (product.z_axis, Vec3::Z),
            ] {
                assert!(
                    (row - expected).length() < 1e-5,
                    "the spin at {seconds}s is not orthonormal: {product:?}"
                );
            }
            assert!((model.determinant() - 1.0).abs() < 1e-5, "at {seconds}s");
        }
        // And it actually moves.
        assert_ne!(ForwardRenderer::spin(0.0), ForwardRenderer::spin(1.0));
    }

    /// The swapchain import says what a swapchain image actually needs, which is
    /// the knowledge the hand-written barriers used to carry.
    #[test]
    fn the_present_target_starts_undefined_and_ends_presentable() {
        let mut pool: crcbl_core::Pool<u8> = crcbl_core::Pool::new();
        let image = pool.insert(0).cast();
        let view = pool.insert(0).cast();
        let imported =
            ForwardRenderer::present_target(image, view, Format::Bgra8UnormSrgb, (1280, 720));
        assert_eq!(imported.initial, ResourceState::Undefined);
        assert_eq!(imported.final_state, ResourceState::Present);
        assert_eq!(imported.extent, (1280, 720));
    }

    /// The scene target is `Rgba16Float`, and the depth target is the
    /// reversed-Z format. Both are locked decisions and both are cheap to pin.
    #[test]
    fn the_scene_targets_are_hdr_and_reversed_z() {
        let color = crate::targets::scene_color((64, 48));
        assert_eq!(color.format, Format::Rgba16Float);
        assert!(color.format.is_hdr_capable());
        assert!(color.usage.contains(crcbl_hal::ImageUsage::SAMPLED));

        let depth = crate::targets::scene_depth((64, 48));
        assert_eq!(depth.format, Format::D32Float);
        assert_eq!(
            DepthStencilState::default().depth_compare,
            crcbl_hal::CompareOp::Greater
        );
    }

    /// A sun ten degrees or so above the horizon, and one further round: two
    /// atmospheres whose LUTs are nowhere near each other, so a comparison
    /// between them cannot pass by the two skies being alike.
    ///
    /// Spelled as directions rather than as angles for
    /// `crcbl_shaders::atmosphere`'s reason — nothing here takes a `sin` of its
    /// own — and normalised by `Atmosphere::parameters` on the way in.
    const MOVED_SUN: Atmosphere = Atmosphere {
        sun_direction: Vec3::new(1.0, 0.2, 0.0),
        ..Atmosphere::NOON
    };

    /// [`MOVED_SUN`] again, further round and lower.
    const MOVED_AGAIN: Atmosphere = Atmosphere {
        sun_direction: Vec3::new(1.0, 0.05, 0.5),
        ..Atmosphere::NOON
    };

    /// Frames the striped march takes to cross the LUT.
    const MARCH_FRAMES: usize = crcbl_shaders::atmosphere::SKY_VIEW_HEIGHT / SKY_VIEW_BUILD_ROWS;

    /// The bytes the most recent sky-view LUT upload put on the device.
    ///
    /// `crate::sky_pass` writes the whole buffer at offset zero on every frame
    /// that has an atmosphere, into the slot that frame is using — so the last
    /// write to any of the ring's buffers is the LUT the frame just recorded
    /// would draw. That is the only place the presented LUT is observable: the
    /// renderer's own copy is what a test could assert about instead, and it
    /// would then be asserting about the thing rather than about what reached
    /// the device.
    fn presented_lut(recorder: &Recorder, luts: &[BufferHandle]) -> Vec<u8> {
        recorder
            .events()
            .into_iter()
            .rev()
            .find_map(|event| match event {
                crcbl_hal::null::Event::BufferWritten { buffer, .. } if luts.contains(&buffer) => {
                    recorder.buffer_bytes(buffer)
                }
                _ => None,
            })
            .expect("a frame with an atmosphere uploads a sky-view LUT")
    }

    /// A renderer with an atmosphere set and its first LUT marched, and the
    /// buffers that LUT reaches the device through.
    ///
    /// The three tests below all start here: the first march is synchronous, so
    /// one frame is what it takes to have a sky to be stale about.
    fn with_marched_atmosphere(
        device: &dyn Device,
        queue: QueueHandle,
        atmosphere: Atmosphere,
    ) -> (ForwardRenderer, Vec<BufferHandle>) {
        let mut renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb)
            .expect("the null backend builds a renderer");
        let luts = renderer.primary.sky_pass.luts().to_vec();
        renderer.set_atmosphere(Some(atmosphere));
        atmosphere_frame(&mut renderer, device);
        (renderer, luts)
    }

    /// One frame of the atmosphere tests: nothing is drawn, and `begin_frame`
    /// is what writes the blocks and steps the march.
    fn atmosphere_frame(renderer: &mut ForwardRenderer, device: &dyn Device) {
        renderer
            .begin_frame(
                device,
                &Camera::default(),
                &DirectionalLight::default(),
                (64, 48),
            )
            .expect("the frame's blocks are written");
    }

    /// A sun that moved is marched a stripe per frame, and every frame until it
    /// is finished still uploads the LUT of the sun before it.
    ///
    /// **The amortisation, from the device's side.** Before this, one
    /// `begin_frame` marched the whole LUT, so a scene that swept its sun paid
    /// tens of milliseconds of CPU in every frame. The claim now is three
    /// things at once, and only the middle one is about performance: the march
    /// advances by `SKY_VIEW_BUILD_ROWS` per frame, the bytes reaching the
    /// device meanwhile are the *previous* sun's rather than a half-marched
    /// sky, and the new sun's LUT arrives whole on the frame the march ends.
    ///
    /// **And the aerial-perspective LUT keeps the same pace**: it rides the
    /// same stripes, so it too uploads the previous sun's air on every frame
    /// of the march and the new sun's on the frame that ends it — the lag
    /// behind a moving sun is [`MARCH_FRAMES`] for both, and the two never
    /// reach the device a sun apart.
    #[test]
    fn a_moving_sun_is_marched_a_stripe_per_frame() {
        let (recorder, device, queue) = open();
        let (mut renderer, luts) =
            with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
        let aerials = renderer.primary.sky_pass.aerials().to_vec();

        let before_view = SkyView::build(&Atmosphere::NOON.parameters());
        let after_view = SkyView::build(&MOVED_SUN.parameters());
        let before = before_view.rows();
        let after = after_view.rows();
        let (air_before, air_after) = (before_view.aerial().rows(), after_view.aerial().rows());
        assert_ne!(
            before, after,
            "the two suns march to the same LUT, so nothing below distinguishes them"
        );
        assert_ne!(
            air_before, air_after,
            "the two suns march to the same air, so nothing below distinguishes them"
        );
        assert!(
            renderer.sky_view_build.is_none(),
            "the first march is synchronous, so no build is left in flight"
        );
        assert_eq!(
            presented_lut(&recorder, &luts),
            before,
            "the frame after `set_atmosphere` did not upload that sun's LUT"
        );
        assert_eq!(
            presented_lut(&recorder, &aerials),
            air_before,
            "the frame after `set_atmosphere` did not upload that sun's air"
        );

        renderer.set_atmosphere(Some(MOVED_SUN));
        for step in 1..MARCH_FRAMES {
            atmosphere_frame(&mut renderer, device.as_ref());
            assert_eq!(
                renderer
                    .sky_view_build
                    .as_ref()
                    .map(SkyViewBuild::rows_done),
                Some(step * SKY_VIEW_BUILD_ROWS),
                "frame {step} of the march is not a stripe further along than frame {} was",
                step - 1
            );
            assert_eq!(
                presented_lut(&recorder, &luts),
                before,
                "frame {step} of the march uploaded something other than the sky it is still \
                 drawing"
            );
            assert_eq!(
                presented_lut(&recorder, &aerials),
                air_before,
                "frame {step} of the march uploaded air other than the sky it is still drawing's"
            );
        }

        atmosphere_frame(&mut renderer, device.as_ref());
        assert!(
            renderer.sky_view_build.is_none(),
            "the march did not finish in the frames its own stripe says it takes"
        );
        assert_eq!(
            presented_lut(&recorder, &luts),
            after,
            "the frame that finished the march did not upload the new sun's LUT"
        );
        assert_eq!(
            presented_lut(&recorder, &aerials),
            air_after,
            "the frame that finished the march did not upload the new sun's air"
        );
    }

    /// An atmosphere adds the composite for its air whether or not the fog
    /// effect is on, and the block tells the composite which halves to read.
    ///
    /// **The seam between the two volumes, on the renderer's side.** Three
    /// frames of one renderer: no atmosphere and the default stack, which has
    /// no fog effect in it — no composite at all, the frame drawn before the
    /// air existed; an atmosphere and the same stack — the composite and
    /// nothing of the column, and a block saying so; and an atmosphere with
    /// the fog effect forced on — all three passes, and a block saying both.
    /// The counters are held to the frame on the second: the composite is a
    /// full-screen triangle, and a frame that drew it and did not count it
    /// makes the debug panel's row disagree with the frame by one.
    #[test]
    fn an_atmosphere_composites_its_air_with_or_without_the_fog_effect() {
        let _blurs = ssao_blur_switch();
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let mut renderer =
            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
        let blocks: Vec<BufferHandle> = (0..FRAMES_IN_FLIGHT)
            .map(|frame| renderer.primary.volumetric.buffers(frame).params)
            .collect();
        let imported = swapchain_image(device);
        let mut pool = crate::TransientPool::new();
        let block = |recorder: &Recorder| {
            let bytes: [u8; crcbl_shaders::volumetric::PARAMS_SIZE] =
                presented_lut(recorder, &blocks)
                    .try_into()
                    .expect("the block is its own size");
            crcbl_shaders::volumetric::VolumetricParams::from_bytes(&bytes)
        };
        let column = ["volumetric-scatter", "volumetric-integrate"];

        let bare = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
        let before = renderer.counters();
        assert!(
            !bare.iter().any(|pass| pass.starts_with("volumetric")),
            "a frame with neither fog nor an atmosphere records {bare:?}"
        );
        let off = block(&recorder);
        assert_eq!(
            off.aerial_params,
            [0.0, 0.0, 0.0, crcbl_shaders::sky::ATMOSPHERE_OFF],
            "a frame with no atmosphere writes something into the aerial row"
        );

        renderer.set_atmosphere(Some(Atmosphere::NOON));
        let air = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
        assert!(
            air.iter().any(|pass| pass == "volumetric-composite")
                && !air.iter().any(|pass| column.contains(&pass.as_str())),
            "an atmosphere with the fog effect off records {air:?}, where it should composite its \
             air and run nothing of the column"
        );
        let after = renderer.counters();
        assert_eq!(
            after.draws - before.draws,
            (SkyPass::PASSES + u64::from(Volumetric::COMPOSITE_PASSES)) * FULLSCREEN_DRAWS,
            "the atmosphere's two full-screen passes — the sky and the air — are not both counted"
        );
        let aerial_only = block(&recorder);
        let sun = Atmosphere::NOON.parameters().sun_direction;
        assert_eq!(
            aerial_only.aerial_params,
            [sun[0], sun[1], sun[2], crcbl_shaders::sky::ATMOSPHERE_ON],
            "the aerial row does not carry the atmosphere's sun and its switch"
        );
        assert_eq!(
            aerial_only.fog_params[3],
            crcbl_shaders::volumetric::LOCAL_COLUMN_OFF,
            "the block tells the composite to read a column no pass filled"
        );

        renderer.set_effect_request(EffectRequest {
            programmatic: EffectOverride::none().force(RenderEffects::VOLUMETRIC_FOG, Some(true)),
            ..EffectRequest::default()
        });
        let both = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
        assert!(
            column
                .iter()
                .chain(&["volumetric-composite"])
                .all(|name| both.iter().any(|pass| pass == name)),
            "an atmosphere with the fog effect on records {both:?}"
        );
        assert_eq!(
            block(&recorder).fog_params[3],
            crcbl_shaders::volumetric::LOCAL_COLUMN_ON,
            "the block tells the composite to skip a column the frame filled"
        );

        renderer.destroy(device);
        pool.destroy(device);
        device.destroy_image_view(imported.view);
        device.destroy_image(imported.image);
        recorder.assert_valid();
    }

    /// A sun that moves while a march is in flight restarts it from row zero.
    ///
    /// **The decision `refresh_sky_view` writes down**, and the reason a sun
    /// that moves every frame shows a frozen sky rather than a stuttering one:
    /// finishing a march for a sun that has already moved would swap in a LUT
    /// that is wrong on arrival. What is observable is the progress counter —
    /// a build that kept its rows would be two stripes along here rather than
    /// one — and the sun the build in flight names.
    #[test]
    fn a_sun_that_moves_mid_march_restarts_it() {
        let (recorder, device, queue) = open();
        let (mut renderer, luts) =
            with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
        let before = SkyView::build(&Atmosphere::NOON.parameters()).rows();

        renderer.set_atmosphere(Some(MOVED_SUN));
        atmosphere_frame(&mut renderer, device.as_ref());
        atmosphere_frame(&mut renderer, device.as_ref());
        assert_eq!(
            renderer
                .sky_view_build
                .as_ref()
                .map(SkyViewBuild::rows_done),
            Some(2 * SKY_VIEW_BUILD_ROWS),
            "two frames of marching did not leave two stripes marched"
        );

        renderer.set_atmosphere(Some(MOVED_AGAIN));
        atmosphere_frame(&mut renderer, device.as_ref());
        assert_eq!(
            renderer
                .sky_view_build
                .as_ref()
                .map(SkyViewBuild::rows_done),
            Some(SKY_VIEW_BUILD_ROWS),
            "the march kept the rows it had marched for a sun that has since moved"
        );
        assert_eq!(
            renderer
                .sky_view_build
                .as_ref()
                .map(SkyViewBuild::atmosphere),
            Some(MOVED_AGAIN.parameters()),
            "the build in flight is marching a sun the caller has moved away from"
        );
        assert_eq!(
            presented_lut(&recorder, &luts),
            before,
            "a restart uploaded something other than the last LUT that finished"
        );
    }

    /// A frame whose sun has not moved marches nothing and re-takes neither
    /// projection.
    ///
    /// **What `PresentedSky` is for.** `gradient_fit` and `irradiance` used to
    /// be taken from the LUT in every `begin_frame`, which is host work a still
    /// sun has no reason to pay. Both are now taken once, where the march
    /// finishes — so a sentinel written over the cached gradient survives a
    /// frame if and only if that frame took neither the march nor the
    /// projection again, and the same sentinel's bytes turn up in what the
    /// frame wrote, which is what says the cache is the thing being read.
    #[test]
    fn a_still_sun_marches_nothing_and_reprojects_nothing() {
        let (recorder, device, queue) = open();
        let (mut renderer, _luts) =
            with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);

        let sentinel = crcbl_shaders::sky::SkyGradient {
            zenith: [0.125, 0.25, 0.375],
            horizon: [0.5, 0.625, 0.75],
            ground: [0.875, 1.125, 1.375],
        };
        let presented = renderer
            .sky_view
            .as_mut()
            .expect("the first frame marched a LUT");
        assert_ne!(
            presented.gradient, sentinel,
            "the sentinel is what the real projection already returns, so it proves nothing"
        );
        presented.gradient = sentinel;

        let before = recorder.events().len();
        atmosphere_frame(&mut renderer, device.as_ref());
        assert_eq!(
            renderer
                .sky_view
                .as_ref()
                .map(|presented| presented.gradient),
            Some(sentinel),
            "a frame under a sun that has not moved re-took the projections"
        );
        assert!(
            renderer.sky_view_build.is_none(),
            "a frame under a sun that has not moved started a march"
        );

        let wanted: Vec<u8> = sentinel
            .rows()
            .iter()
            .flatten()
            .flat_map(|value| value.to_le_bytes())
            .collect();
        let used = recorder
            .events()
            .into_iter()
            .skip(before)
            .filter_map(|event| match event {
                crcbl_hal::null::Event::BufferWritten { buffer, .. } => {
                    recorder.buffer_bytes(buffer)
                }
                _ => None,
            })
            .any(|bytes| {
                bytes
                    .windows(wanted.len())
                    .any(|window| window == wanted.as_slice())
            });
        assert!(
            used,
            "the cached gradient reached no block this frame wrote, so the frame is not reading \
             the cache at all"
        );
    }

    /// **The frame block's ambient rows carry the marched LUT's own L1
    /// projection**, and not the three-band fit's.
    ///
    /// `begin_frame` writes [`PresentedSky::irradiance`] into
    /// [`FrameUniforms::sky_sh_r`] and the two rows beside it, and until this
    /// test nothing read them back. The only reader of those rows is arithmetic
    /// in `mesh.slang`'s fragment stage, and no frame in the tree draws a
    /// surface under an atmosphere — `crcbl`'s
    /// `an_atmosphere_frame_is_the_host_lut` puts no geometry in its scene at
    /// all — so `PresentedSky::new` handed `view.gradient_fit().irradiance()`
    /// instead, the three-band fit's projection rather than the LUT's, was a
    /// swap `docs/backlog.md` recorded passing every suite in the tree on
    /// 2026-09-06.
    ///
    /// **Both halves are needed and the second is the sabotage's.** The rows
    /// equalling the LUT's projection is the wiring; the rows *differing* from
    /// the fit's is what makes the equality a claim about which projection
    /// arrived rather than about two numbers that happen to agree. The
    /// `assert_ne` above them is the anti-vacuity: a sun for which the two
    /// projections coincide would make this test pass under the swap.
    ///
    /// [`FrameUniforms::sky_sh_r`]: crcbl_shaders::mesh::FrameUniforms::sky_sh_r
    #[test]
    fn an_atmosphere_writes_the_luts_own_ambient_term() {
        /// The three rows, as the little-endian bytes `FrameUniforms::to_bytes`
        /// puts in the block.
        fn rows(probe: &crcbl_shaders::probe::GpuProbe) -> Vec<u8> {
            [probe.sh_r, probe.sh_g, probe.sh_b]
                .iter()
                .flatten()
                .flat_map(|value| value.to_le_bytes())
                .collect()
        }

        let (recorder, device, queue) = open();
        let (renderer, _luts) = with_marched_atmosphere(device.as_ref(), queue, MOVED_SUN);

        let view = SkyView::build(&MOVED_SUN.parameters());
        let marched = rows(&view.irradiance());
        let fitted = rows(&view.gradient_fit().irradiance());
        assert_ne!(
            marched, fitted,
            "this sun's LUT and its three-band fit project to the same rows, so a block \
             carrying either would satisfy the check below and the swap it exists for would \
             pass"
        );

        let block = recorder
            .buffer_bytes(renderer.primary.uniforms[renderer.frame])
            .expect("a frame with an atmosphere writes its uniform block");
        let at = mesh::SKY_SH_R_OFFSET;
        assert_eq!(
            &block[at..at + marched.len()],
            marched.as_slice(),
            "the frame block's sky rows are not `SkyView::irradiance` of the LUT this frame \
             marched, so the ambient term the fragment stage evaluates comes from somewhere \
             else"
        );
        assert_ne!(
            &block[at..at + fitted.len()],
            fitted.as_slice(),
            "the frame block's sky rows are the gradient fit's projection — the LUT was \
             marched and then thrown away for the three-band approximation of it"
        );

        renderer.destroy(device.as_ref());
    }
}