roxlap-scene 0.3.0

Scene-graph layer for the roxlap voxel engine: many independent chunked voxel grids, each with f64 world position and Quat rotation.
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
//! Scene-level rendering — drives [`roxlap_core::opticast::opticast`]
//! across the grids of a [`Scene`].
//!
//! Two entry points:
//!
//! - [`render_scene_composed`] (recommended for multi-grid scenes):
//!   per grid, allocates a temporary framebuffer + zbuffer, runs
//!   opticast into the temp, then merges into the shared output via
//!   per-pixel min-z. Correctly composites overlapping grid output.
//! - [`render_scene`] (single-grid trusting caller): writes every
//!   grid directly into the shared rasterizer. For single-grid
//!   scenes this matches a direct opticast call byte-for-byte; for
//!   multi-grid it's last-grid-wins (sky writes from grid B
//!   overwrite grid A's hits). Useful for tests / single-grid
//!   sanity checks.
//!
//! ## S4B.2.e: Approach B multi-chunk dispatch
//!
//! Both APIs route per-grid rendering through
//! [`crate::Grid::chunk_xy_backing`] → [`roxlap_core::ChunkGrid`] →
//! [`roxlap_core::GridView::from_chunk_grid`] → [`opticast`].
//! `opticast`'s prelude looks up the camera's chunk via
//! [`roxlap_core::GridView::chunk_at_xy`]; the grouscan column-step
//! swaps the active per-chunk `(slab_buf, column_offsets)` when
//! rays cross a chunk-XY boundary. The combined-world stitch
//! (Approach C, S4.0..S4.2) is no longer in the render path — the
//! lighting bake still uses it until S4B.4 lands a per-chunk bake.
//!
//! Per-grid rotation (S5) and per-grid LOD (S6) plug in at the
//! same dispatch point: rotate the world camera into grid-local
//! before the chunk-grid lookup, then dispatch coarse / fine /
//! billboard based on grid-camera distance.

// `fb` / `zb` (framebuffer / zbuffer) and the `_fb` / `_zb` suffixes
// throughout this module are voxlap-canonical pairs — drilling them
// apart with longer names just hurts readability.
#![allow(clippy::similar_names)]

use glam::DVec3;
use roxlap_core::opticast::{opticast, OpticastOutcome, OpticastSettings};
use roxlap_core::rasterizer::ScratchPool;
use roxlap_core::scalar_rasterizer::ScalarRasterizer;
use roxlap_core::sky::Sky;
use roxlap_core::Camera;

use crate::billboard::{self, BillboardCache, DEFAULT_RESOLUTION as BILLBOARD_RESOLUTION};
use crate::lod::Lod;
use crate::{GridTransform, Scene, CHUNK_SIZE_XY};

/// Sentinel colour stamped into a `render_sky = false` grid's
/// temporary framebuffer wherever the rasterizer would have drawn
/// sky. After opticast, [`render_scene_composed`] walks the temp
/// buffer and resets `temp_zb` to [`f32::INFINITY`] for any pixel
/// still carrying this value — those pixels then always lose
/// [`compose_into`]'s min-z test and the underlying grid's sky
/// (or another grid's hit) wins.
///
/// Alpha byte is `0x00`. Voxlap voxel slabs carry an alpha-encoded
/// shade in `[0x00, 0x80]`, but a `0x00` alpha **with this exact
/// RGB pattern** is exceedingly unlikely to occur on a real hit
/// (the lit-voxel path produces alpha ≥ 0x40 in practice). Bit
/// pattern is also visually distinct (cyan-ish neon) if anything
/// ever leaks through to the screen, making the bug obvious.
const SKY_MASK_SENTINEL: u32 = 0x00_DE_AD_BE;

/// Project a world-space [`Camera`] into a grid's local frame:
/// translate by `-transform.origin`, then apply
/// `transform.rotation.inverse()` to the position and the
/// orthonormal basis (`right` / `down` / `forward`).
///
/// Identity rotation collapses to pure translation, byte-identical
/// to the pre-S5 path (`DQuat::IDENTITY * v == v`). For a rotated
/// grid the rasterizer still sees an axis-aligned chunk grid —
/// rotation is invisible below this layer per PORTING-SCENE.md § S5.
///
/// The basis is rotated as a free vector (no translation
/// component); position is rotated about the grid origin.
fn world_camera_to_grid_local(camera: &Camera, transform: &GridTransform) -> Camera {
    let inv = transform.rotation.inverse();
    let world_offset = DVec3::from_array(camera.pos) - transform.origin;
    let local_pos = inv * world_offset;
    let local_right = inv * DVec3::from_array(camera.right);
    let local_down = inv * DVec3::from_array(camera.down);
    let local_forward = inv * DVec3::from_array(camera.forward);
    Camera {
        pos: local_pos.to_array(),
        right: local_right.to_array(),
        down: local_down.to_array(),
        forward: local_forward.to_array(),
    }
}

/// Outcome of a [`render_scene`] / [`render_scene_composed`] call.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RenderOutcome {
    /// At least one grid produced a render.
    Rendered {
        /// Number of grids whose opticast pass returned
        /// [`OpticastOutcome::Rendered`].
        grids_drawn: usize,
    },
    /// No grid rendered. Either the scene was empty or every
    /// per-grid opticast call returned
    /// [`OpticastOutcome::SkippedCameraInSolid`].
    Empty,
}

/// Render every grid in `scene` directly into `(fb, zb)` — no
/// per-grid temp buffer, no compose merge. For multi-grid scenes
/// this is last-grid-wins (later grids' opticast writes overwrite
/// earlier grids' pixels indiscriminately, including sky), so it's
/// only correct for single-grid scenes.
///
/// Use this when you have one grid and want the byte-stable
/// matches-direct-opticast property — the test suite uses it as a
/// sanity check that the combined-world stitch + render harness
/// doesn't drift vs. a raw [`opticast`] call.
///
/// Caller pre-fills `fb` with the desired sky colour and `zb` with
/// any value (typically `0.0` matching the per-chunk renderer's
/// convention or `f32::INFINITY` for compose-friendly init); the
/// rasterizer overwrites both per pixel that gets a hit.
#[allow(clippy::too_many_arguments)]
pub fn render_scene(
    fb: &mut [u32],
    zb: &mut [f32],
    pitch_pixels: usize,
    width: u32,
    height: u32,
    pool: &mut ScratchPool,
    scene: &mut Scene,
    camera: &Camera,
    settings: &OpticastSettings,
    sky: Option<&Sky>,
) -> RenderOutcome {
    debug_assert_eq!(fb.len(), zb.len());
    let pixel_count = (width as usize) * (height as usize);
    debug_assert_eq!(fb.len(), pixel_count);

    let mut grids_drawn = 0usize;
    for (_id, grid) in scene.grids_mut() {
        // S4B.2.e: Approach B render path. World → grid-local
        // camera transform doesn't need a voxel-offset adjustment
        // anymore — Approach B's chunks live at their signed
        // (chx, chy) indices and `chunk_at_xy` handles negative-
        // index lookups natively.
        //
        // S5.0: per-grid arbitrary rotation. The local camera is
        // built by `world_camera_to_grid_local` — translation +
        // inverse-rotation of the basis. Identity rotation keeps
        // this byte-identical to the pre-S5 translate-only form.
        let Some(backing) = grid.chunk_xyz_backing() else {
            // Empty grid (no populated chz=0 chunks) — skip.
            continue;
        };
        let local_cam = world_camera_to_grid_local(camera, &grid.transform);
        let cg = roxlap_core::ChunkGrid {
            chunks: &backing.chunks,
            origin_chunk_xy: backing.origin_chunk_xy,
            origin_chunk_z: backing.origin_chunk_z,
            chunks_x: backing.chunks_x,
            chunks_y: backing.chunks_y,
            chunks_z: backing.chunks_z,
        };
        let grid_view = roxlap_core::GridView::from_chunk_grid(&cg, CHUNK_SIZE_XY);
        let outcome = {
            let mut rasterizer = ScalarRasterizer::new(fb, zb, pitch_pixels, grid_view);
            if let Some(sky_ref) = sky {
                rasterizer = rasterizer.with_sky(sky_ref);
            }
            opticast(&mut rasterizer, pool, &local_cam, settings, grid_view)
        };
        if outcome == OpticastOutcome::Rendered {
            grids_drawn += 1;
        }
    }
    if grids_drawn == 0 {
        RenderOutcome::Empty
    } else {
        RenderOutcome::Rendered { grids_drawn }
    }
}

/// Per-pixel "min-z wins" merge of `(temp_fb, temp_zb)` into
/// `(shared_fb, shared_zb)`.
///
/// Voxlap's z-buffer convention: `z` = perpendicular distance from
/// camera; **smaller `z` = closer to camera**. This helper picks
/// the closer pixel per slot. Sky pixels emerge with a large `z`
/// (`scratch.skycast.dist`, set to `gxmax` or `i32::MAX` per
/// `phase_startsky`) so they always lose to any hit's finite
/// distance.
///
/// `temp_fb` / `temp_zb` are read-only inputs; both must have the
/// same length as `shared_fb` / `shared_zb` (debug-asserted).
pub fn compose_into(
    shared_fb: &mut [u32],
    shared_zb: &mut [f32],
    temp_fb: &[u32],
    temp_zb: &[f32],
) {
    debug_assert_eq!(shared_fb.len(), shared_zb.len());
    debug_assert_eq!(shared_fb.len(), temp_fb.len());
    debug_assert_eq!(shared_fb.len(), temp_zb.len());
    for i in 0..shared_fb.len() {
        if temp_zb[i] < shared_zb[i] {
            shared_fb[i] = temp_fb[i];
            shared_zb[i] = temp_zb[i];
        }
    }
}

/// Render every grid in `scene` with per-grid temporary buffers +
/// z-buffer composition. The canonical multi-grid scene render
/// path.
///
/// Algorithm:
/// 1. Caller pre-fills `fb` with the desired sky colour and `zb`
///    with [`f32::INFINITY`] (so any rendered pixel wins the
///    initial composition).
/// 2. For each grid, allocate a temporary `(temp_fb, temp_zb)` of
///    the same size, pre-fill them with sky / `INFINITY`, and run
///    [`opticast`] into them via a [`ScalarRasterizer`] over the
///    temporary buffers AND the grid's combined-world view (S4.0).
/// 3. Merge the temporary buffers into the shared `(fb, zb)` via
///    [`compose_into`] — closer pixels (smaller `z`) win.
///
/// Pixel correctness across overlapping grids: sky pixels emerge
/// with `z` = `gxmax` / `i32::MAX` (a very large value), so they
/// always lose to any hit. Hits compete on actual perpendicular
/// distance — the closer grid's surface is what gets composited.
///
/// `pitch_pixels` is the framebuffer's row stride in pixels (×4 for
/// bytes). `width` × `height` must equal `fb.len()` /
/// `zb.len()`. `sky` is the optional textured sky resource the
/// rasterizer threads through to `phase_startsky`; `None` ⇒ solid
/// `pool.skycast` fill.
///
/// **Heap allocation per call:** two `Vec` allocations per grid (a
/// temp framebuffer and zbuffer). For repeated frame rendering an
/// owned scratch struct that pre-allocates these is the obvious
/// optimisation; deferred until profiling shows it matters.
#[allow(clippy::too_many_arguments)]
pub fn render_scene_composed(
    fb: &mut [u32],
    zb: &mut [f32],
    pitch_pixels: usize,
    width: u32,
    height: u32,
    pool: &mut ScratchPool,
    scene: &mut Scene,
    camera: &Camera,
    settings: &OpticastSettings,
    sky_color: u32,
    sky: Option<&Sky>,
) -> RenderOutcome {
    debug_assert_eq!(fb.len(), zb.len());
    let pixel_count = (width as usize) * (height as usize);
    debug_assert_eq!(fb.len(), pixel_count);

    let mut grids_drawn = 0usize;
    let mut temp_fb = vec![sky_color; pixel_count];
    let mut temp_zb = vec![f32::INFINITY; pixel_count];

    for (_id, grid) in scene.grids_mut() {
        // S6.0/S6.1: per-grid LOD tier dispatch. The picker keys
        // off the grid's `lod_thresholds` and the world-space
        // camera. Default thresholds are `always_near` so every
        // grid lands on `Lod::Near` and the framebuffer stays
        // byte-identical to the pre-S6 path.
        //
        // S6.1: `Mid` applies the grid's `mid_mip_levels` /
        // `mid_mip_scan_dist` overrides (if `Some`) on top of the
        // base settings, biasing the grid into coarser mips. With
        // both `None`, Mid renders identically to Near (graceful
        // degrade — callers opt into the Mid plumbing via
        // `LodThresholds::from_radius_with_mid_mip`).
        //
        // S6.3: `Far` skips the opticast path entirely — render
        // dispatches into the billboard impostor blit (below). The
        // LOD enum is computed before `chunk_xyz_backing` because
        // the Far branch needs `&mut grid` for the lazy cache
        // populate, which conflicts with the `&grid` lifetime
        // backing's tied to.
        let lod = grid.select_lod(DVec3::from_array(camera.pos));

        if lod == Lod::Far {
            // S6.3: Far-tier billboard blit.
            //
            // Empty grids have nothing to impostor; skip without
            // touching `billboards` so a later edit + Far re-entry
            // still builds a fresh cache.
            if grid.chunks.is_empty() {
                continue;
            }
            // Lazy populate: cleared by edits (see `edit.rs`),
            // rebuilt on first Far entry after each edit cycle.
            if grid.billboards.is_none() {
                let cache = BillboardCache::build(grid, BILLBOARD_RESOLUTION);
                grid.billboards = Some(cache);
            }
            // Grid bounds + world-space centre. Rotation preserves
            // length, so `bounds.radius` is the world-space radius.
            let bounds = billboard::grid_bounds(grid);
            let centre_world = grid.transform.origin + grid.transform.rotation * bounds.centre;
            // Query direction = unit vector from grid centre TO
            // camera, in grid-local space (snapshots' `view_dir`s
            // live in that frame).
            let cam_pos = DVec3::from_array(camera.pos);
            let centre_to_cam_world = cam_pos - centre_world;
            let ctc_len = centre_to_cam_world.length();
            if !ctc_len.is_finite() || ctc_len < 1e-9 {
                // Camera essentially at grid centre — pick_nearest
                // is ill-defined. Skip; a future frame at a
                // resolvable pose will render normally.
                continue;
            }
            let query_dir_world = centre_to_cam_world / ctc_len;
            let query_dir_local = grid.transform.rotation.inverse() * query_dir_world;
            // Cache is guaranteed Some here (populated above).
            let cache = grid.billboards.as_ref().unwrap();
            // pick_nearest only returns None for empty caches;
            // we just built a 26-snapshot cache so unwrap is safe.
            let snapshot = cache
                .pick_nearest(query_dir_local)
                .expect("billboard cache populated above");
            billboard::billboard_blit_into(
                fb,
                zb,
                pitch_pixels,
                width,
                height,
                snapshot,
                centre_world,
                bounds.radius,
                camera,
                settings,
            );
            grids_drawn += 1;
            continue;
        }

        // S4B.2.e: Approach B render path. See `render_scene`'s
        // body for the camera transform + ChunkGrid construction
        // commentary; the only difference is this writes to
        // (temp_fb, temp_zb) and composes via `compose_into`.
        // S5.0: per-grid rotation flows via the shared helper.
        let Some(backing) = grid.chunk_xyz_backing() else {
            continue;
        };
        // S5.2-followup: per-grid sky opt-out. Grids with
        // `render_sky = false` (e.g. a rotating ship) must not
        // contribute sky pixels — the grid-local sky lookup
        // rotates with the grid and visibly fights the world's
        // sky during compose. Implementation: stamp a sentinel
        // colour into temp_fb everywhere the rasterizer would
        // paint sky, then walk the buffer post-opticast and
        // mark sentinel pixels as `INFINITY` in temp_zb so
        // [`compose_into`]'s min-z test always drops them.
        let owns_sky = grid.render_sky;
        let local_sky_color = if owns_sky {
            sky_color
        } else {
            SKY_MASK_SENTINEL
        };
        if !owns_sky {
            // Override the pool's skycast colour just for this
            // grid so the solid-fill sky path stamps the sentinel.
            // Restored after the grid's compose. `dist = 0` mirrors
            // the caller's typical setup; the rasterizer's prelude
            // overwrites the dist field with `gxmax` or `i32::MAX`
            // anyway, so the dist arg is cosmetic here.
            pool.set_skycast(SKY_MASK_SENTINEL as i32, 0);
        }

        // Reset temp to sky / INFINITY so each grid starts fresh.
        // The reset cost is O(pixels) per grid; for small grid counts
        // this is negligible vs the opticast work.
        temp_fb.fill(local_sky_color);
        temp_zb.fill(f32::INFINITY);

        let local_cam = world_camera_to_grid_local(camera, &grid.transform);
        let cg = roxlap_core::ChunkGrid {
            chunks: &backing.chunks,
            origin_chunk_xy: backing.origin_chunk_xy,
            origin_chunk_z: backing.origin_chunk_z,
            chunks_x: backing.chunks_x,
            chunks_y: backing.chunks_y,
            chunks_z: backing.chunks_z,
        };
        let grid_view = roxlap_core::GridView::from_chunk_grid(&cg, CHUNK_SIZE_XY);

        // Build the per-grid settings by layering three opt-in
        // overrides on top of the caller's `settings`:
        //
        //   1. (S6.1) `lod_thresholds.mid_mip_levels` /
        //      `mid_mip_scan_dist` — applied iff `lod == Mid`.
        //      Biases the grid into coarser mips via the existing
        //      multi-mip path. None ⇒ Mid degrades to Near's
        //      settings (graceful).
        //   2. (S5.2-followup) `Grid::mip_levels_override` — global
        //      per-grid cap applied at ALL tiers. Preserves the
        //      ship anti-axis-aligned-beam workaround through Mid
        //      tier (so a rotating ship pinned at mip-0 stays at
        //      mip-0 even when distant).
        //
        // Layer order: Mid overrides first, then global cap. Both
        // mip_levels overrides are clamped to `[1, base.mip_levels]`
        // since the base is the maximum the renderer can use
        // (chunk's `chunk_mips`-min logic inside scalar_rasterizer
        // applies further per-chunk).
        let per_grid_settings;
        let active_settings = {
            let base_mip_levels = settings.mip_levels;
            let base_mip_scan = settings.mip_scan_dist;
            let lod_mip_levels = match lod {
                Lod::Mid => grid.lod_thresholds.mid_mip_levels,
                Lod::Near | Lod::Far => None,
            };
            let lod_mip_scan = match lod {
                Lod::Mid => grid.lod_thresholds.mid_mip_scan_dist,
                Lod::Near | Lod::Far => None,
            };
            let global_mip_cap = grid.mip_levels_override;
            let needs_override =
                lod_mip_levels.is_some() || lod_mip_scan.is_some() || global_mip_cap.is_some();
            if needs_override {
                // Resolve mip_levels: start with base, apply LOD
                // override (clamped to base), then apply global cap.
                let mut mip_levels =
                    lod_mip_levels.map_or(base_mip_levels, |n| n.clamp(1, base_mip_levels));
                if let Some(cap) = global_mip_cap {
                    mip_levels = mip_levels.min(cap.clamp(1, base_mip_levels));
                }
                // Resolve mip_scan_dist: LOD override clamps to
                // `min(base, override)` — the override only makes
                // transitions kick in CLOSER, never farther. The
                // renderer floors at 4 internally so we don't
                // bottom-clamp here.
                let mip_scan_dist = lod_mip_scan.map_or(base_mip_scan, |d| base_mip_scan.min(d));
                per_grid_settings = OpticastSettings {
                    mip_levels,
                    mip_scan_dist,
                    ..*settings
                };
                &per_grid_settings
            } else {
                settings
            }
        };

        let outcome = {
            let mut rasterizer =
                ScalarRasterizer::new(&mut temp_fb, &mut temp_zb, pitch_pixels, grid_view);
            // Sky texture is suppressed for `!owns_sky` grids so
            // the textured-sky branch doesn't bypass the sentinel;
            // only the solid-fill path stamps `skycast.col`.
            if owns_sky {
                if let Some(sky_ref) = sky {
                    rasterizer = rasterizer.with_sky(sky_ref);
                }
            }
            opticast(
                &mut rasterizer,
                pool,
                &local_cam,
                active_settings,
                grid_view,
            )
        };

        if !owns_sky {
            // Mask sentinel pixels so compose drops them. One linear
            // sweep of the temp framebuffer; sentinel pixels become
            // `INFINITY` in temp_zb (= always lose min-z).
            for (px, z) in temp_fb.iter().zip(temp_zb.iter_mut()) {
                if *px == SKY_MASK_SENTINEL {
                    *z = f32::INFINITY;
                }
            }
            // Restore the pool's sky colour so subsequent grids
            // (and the next frame) see the caller's value.
            pool.set_skycast(sky_color as i32, 0);
        }

        if outcome == OpticastOutcome::Rendered {
            compose_into(fb, zb, &temp_fb, &temp_zb);
            grids_drawn += 1;
        }
    }

    if grids_drawn == 0 {
        RenderOutcome::Empty
    } else {
        RenderOutcome::Rendered { grids_drawn }
    }
}

#[cfg(test)]
#[allow(clippy::float_cmp)]
mod tests {
    use super::*;
    use crate::{GridTransform, Scene, CHUNK_SIZE_XY};
    use glam::{DVec3, IVec3};
    use roxlap_core::opticast::{opticast as core_opticast, OpticastSettings};
    use roxlap_core::rasterizer::ScratchPool;
    use roxlap_core::scalar_rasterizer::ScalarRasterizer;
    use roxlap_core::{Camera, Engine};

    const XRES: u32 = 320;
    const YRES: u32 = 200;

    /// Build a single-grid scene at the given world origin with a
    /// recognisable shape inside its chunk (0, 0, 0): a 16-voxel
    /// box plus a 6-radius sphere. Returns `(scene, grid_id)`.
    fn build_one_grid_scene(world_origin: DVec3) -> (Scene, crate::GridId) {
        let mut scene = Scene::new();
        let id = scene.add_grid(GridTransform::at(world_origin));
        let grid = scene.grid_mut(id).unwrap();
        // Box covering [40..56]³ in chunk-local coords.
        grid.set_rect(
            IVec3::new(40, 40, 40),
            IVec3::new(55, 55, 55),
            Some(0x80_88_88_88),
        );
        // Sphere at (80, 80, 80) radius 6.
        grid.set_sphere(IVec3::new(80, 80, 80), 6, Some(0x80_22_aa_22));
        (scene, id)
    }

    fn camera_at(pos: [f64; 3]) -> Camera {
        // Look +y axis; voxlap z-down convention. Right-handed:
        // right × down == forward.
        Camera {
            pos,
            right: [-1.0, 0.0, 0.0],
            down: [0.0, 0.0, 1.0],
            forward: [0.0, 1.0, 0.0],
        }
    }

    /// Spin up an engine + `ScratchPool` + framebuffers ready for
    /// one `opticast` / `render_scene` pass. `pool_vsid` should
    /// cover the largest grid's combined vsid.
    fn render_setup(pool_vsid: u32) -> (Engine, ScratchPool, Vec<u32>, Vec<f32>) {
        let engine = Engine::new();
        let mut pool = ScratchPool::new(XRES, YRES, pool_vsid);
        let sky = engine.sky_color();
        let sky_col_i = i32::from_ne_bytes(sky.to_ne_bytes());
        pool.set_skycast(sky_col_i, 0);
        let fog_col_i = i32::from_ne_bytes(engine.fog_color().to_ne_bytes());
        pool.set_fog(fog_col_i, engine.fog_max_scan_dist());
        pool.set_treat_z_max_as_air(true);
        let pixel_count = (XRES as usize) * (YRES as usize);
        let framebuffer = vec![sky; pixel_count];
        let zbuffer = vec![0.0f32; pixel_count];
        (engine, pool, framebuffer, zbuffer)
    }

    /// Render `scene` via [`render_scene`] (single-grid no-compose
    /// path) and return the resulting framebuffer.
    fn render_via_scene(scene: &mut Scene, camera: &Camera) -> Vec<u32> {
        let (_engine, mut pool, mut fb, mut zb) = render_setup(CHUNK_SIZE_XY);
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let outcome = render_scene(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            scene,
            camera,
            &settings,
            None,
        );
        assert_eq!(outcome, RenderOutcome::Rendered { grids_drawn: 1 });
        fb
    }

    /// Render the same chunk as a direct opticast call, with the
    /// camera already in grid-local frame. The reference output
    /// for the round-trip test.
    fn render_via_direct_opticast(scene: &Scene, local_camera: &Camera) -> Vec<u32> {
        let (_engine, mut pool, mut fb, mut zb) = render_setup(CHUNK_SIZE_XY);
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let grid = scene.grids().next().unwrap().1;
        let chunk = grid.chunk(IVec3::ZERO).unwrap();
        let grid_view = roxlap_core::GridView::from_single_vxl(chunk);
        let mut rasterizer = ScalarRasterizer::new(&mut fb, &mut zb, XRES as usize, grid_view);
        let _ = core_opticast(
            &mut rasterizer,
            &mut pool,
            local_camera,
            &settings,
            grid_view,
        );
        drop(rasterizer);
        fb
    }

    // ---- S5.0: world_camera_to_grid_local helper ----

    /// Identity rotation: pos translates by `-origin`; basis is
    /// untouched. This is the byte-identical-to-pre-S5 contract.
    #[test]
    fn world_camera_to_grid_local_identity_rotation_translates_pos_only() {
        let camera = Camera {
            pos: [110.0, 220.0, 330.0],
            right: [1.0, 0.0, 0.0],
            down: [0.0, 0.0, 1.0],
            forward: [0.0, 1.0, 0.0],
        };
        let transform = GridTransform::at(DVec3::new(100.0, 200.0, 300.0));
        let local = super::world_camera_to_grid_local(&camera, &transform);
        // Basis must be bit-for-bit unchanged for the identity case.
        assert_eq!(local.right, camera.right);
        assert_eq!(local.down, camera.down);
        assert_eq!(local.forward, camera.forward);
        // Pos translates by `-origin`.
        for (got, want) in local.pos.iter().zip([10.0, 20.0, 30.0].iter()) {
            assert!((got - want).abs() < 1e-12, "pos got={got} want={want}");
        }
    }

    /// 90° rotation about +Z: grid-local `+x` aligns with world `+y`.
    /// World camera at `(0, 10, 0)` looking world `+y` lives in
    /// grid-local at `(10, 0, 0)` looking grid-local `+x`.
    #[test]
    fn world_camera_to_grid_local_90deg_z_rotates_basis_and_pos() {
        use glam::DQuat;
        let camera = Camera {
            pos: [0.0, 10.0, 0.0],
            right: [1.0, 0.0, 0.0],
            down: [0.0, 0.0, 1.0],
            forward: [0.0, 1.0, 0.0],
        };
        let transform = GridTransform {
            origin: DVec3::ZERO,
            rotation: DQuat::from_rotation_z(std::f64::consts::FRAC_PI_2),
        };
        let local = super::world_camera_to_grid_local(&camera, &transform);
        // World +y == grid-local +x.
        let approx_eq =
            |a: [f64; 3], b: [f64; 3]| a.iter().zip(b.iter()).all(|(x, y)| (x - y).abs() < 1e-9);
        assert!(
            approx_eq(local.pos, [10.0, 0.0, 0.0]),
            "pos={:?} expected ~(10, 0, 0)",
            local.pos
        );
        // World +x (right) maps to grid-local -y.
        assert!(
            approx_eq(local.right, [0.0, -1.0, 0.0]),
            "right={:?} expected ~(0, -1, 0)",
            local.right
        );
        // World +z (down) is unchanged — it's the rotation axis.
        assert!(
            approx_eq(local.down, [0.0, 0.0, 1.0]),
            "down={:?} expected ~(0, 0, 1)",
            local.down
        );
        // World +y (forward) maps to grid-local +x.
        assert!(
            approx_eq(local.forward, [1.0, 0.0, 0.0]),
            "forward={:?} expected ~(1, 0, 0)",
            local.forward
        );
    }

    /// Basis orthonormality + handedness both survive the
    /// inverse-rotation transform. Property: any unit-quaternion
    /// conjugation preserves the input basis's orthonormality AND
    /// its handedness (rotations are orientation-preserving).
    #[test]
    fn world_camera_to_grid_local_preserves_basis_orthonormality() {
        use glam::DQuat;
        // Right-handed voxlap basis (`right × down == forward`):
        // looking +y, right = -x makes the cross product land on +y.
        let camera = Camera {
            pos: [3.0, -5.0, 7.0],
            right: [-1.0, 0.0, 0.0],
            down: [0.0, 0.0, 1.0],
            forward: [0.0, 1.0, 0.0],
        };
        let transform = GridTransform {
            origin: DVec3::new(1.0, 2.0, 3.0),
            rotation: DQuat::from_axis_angle(glam::DVec3::new(0.3, 0.8, 0.5).normalize(), 0.7),
        };
        let local = super::world_camera_to_grid_local(&camera, &transform);
        let r = DVec3::from_array(local.right);
        let d = DVec3::from_array(local.down);
        let f = DVec3::from_array(local.forward);
        // Norms ≈ 1.
        for v in [r, d, f] {
            assert!(
                (v.length_squared() - 1.0).abs() < 1e-12,
                "basis vec {v:?} not unit length"
            );
        }
        // Orthogonality.
        assert!(r.dot(d).abs() < 1e-12, "right·down = {}", r.dot(d));
        assert!(r.dot(f).abs() < 1e-12, "right·forward = {}", r.dot(f));
        assert!(d.dot(f).abs() < 1e-12, "down·forward = {}", d.dot(f));
        // Right-handed: right × down == forward (voxlap convention).
        let cross = r.cross(d);
        assert!(
            (cross - f).length() < 1e-12,
            "right×down={cross:?} forward={f:?}"
        );
    }

    // ---- S5.1: rotated-grid render correctness ----

    /// Build a single-grid scene at the given transform with a
    /// marker box near one corner of chunk (0, 0, 0). Returns the
    /// scene and the marker colour. Picking a single chunk + small
    /// box keeps the test compact while still exercising the gline
    /// + grouscan path through the rotated frame.
    fn build_one_grid_marker_scene(transform: GridTransform) -> (Scene, crate::GridId, u32) {
        let mut scene = Scene::new();
        let id = scene.add_grid(transform);
        let grid = scene.grid_mut(id).unwrap();
        // Bright marker box at chunk-local (40..56, 40..56, 40..56).
        grid.set_rect(
            IVec3::new(40, 40, 40),
            IVec3::new(55, 55, 55),
            Some(0x80_55_aa_22), // distinctive green
        );
        (scene, id, 0x80_55_aa_22)
    }

    /// Pin S5.1's central equivalence: rotating both the grid and the
    /// camera by the SAME rotation around the grid's origin must
    /// leave the rendered framebuffer unchanged — the grid-local
    /// camera pose collapses to the same values in both scenarios.
    ///
    /// We use `DQuat::from_xyzw(0.0, 0.0, 1.0, 0.0)`, the
    /// 180°-around-Z unit quaternion. This rotation acts on vectors
    /// as `(x, y, z) → (-x, -y, z)`, which only multiplies f64
    /// components by 0 or ±1 — bit-exact under glam's standard quat
    /// conjugation formula. Other angles (e.g. 90°) would introduce
    /// sub-1e-15 noise from sin/cos, breaking byte-identity at
    /// chunk / voxel boundaries.
    #[test]
    fn s5_1_180deg_z_rotated_grid_byte_identical_to_axis_aligned() {
        use glam::DQuat;
        // Right-handed voxlap basis (right × down == forward).
        let axis_aligned_camera = Camera {
            pos: [40.0, -20.0, 50.0],
            right: [-1.0, 0.0, 0.0],
            down: [0.0, 0.0, 1.0],
            forward: [0.0, 1.0, 0.0],
        };
        // R_z(180°): (x, y, z) → (-x, -y, z).
        let rotated_camera = Camera {
            pos: [-40.0, 20.0, 50.0],
            right: [1.0, 0.0, 0.0],
            down: [0.0, 0.0, 1.0],
            forward: [0.0, -1.0, 0.0],
        };
        // Sanity: prove the exact-arithmetic rotation lands on the
        // baseline. If glam ever changes its quat*vec formula in a
        // way that loses exactness here, the next two assertions
        // catch it before the framebuffer comparison.
        let q = DQuat::from_xyzw(0.0, 0.0, 1.0, 0.0);
        let rot_pos = q * DVec3::from_array(axis_aligned_camera.pos);
        let rot_fwd = q * DVec3::from_array(axis_aligned_camera.forward);
        assert_eq!(rot_pos.to_array(), rotated_camera.pos);
        assert_eq!(rot_fwd.to_array(), rotated_camera.forward);

        let (mut scene_a, _, _) = build_one_grid_marker_scene(GridTransform::identity());
        let fb_a = render_via_scene(&mut scene_a, &axis_aligned_camera);

        let (mut scene_b, _, _) = build_one_grid_marker_scene(GridTransform {
            origin: DVec3::ZERO,
            rotation: q,
        });
        let fb_b = render_via_scene(&mut scene_b, &rotated_camera);

        assert_eq!(
            fb_a, fb_b,
            "rotating both grid and camera by R about the grid origin must leave the framebuffer unchanged"
        );
    }

    /// 45° smoke test: rotated grid renders to something non-trivial
    /// without panicking. No equivalence assertion (45° quat math is
    /// approximate at f64 level; that path is exercised structurally,
    /// not bit-exactly). Camera is placed at a fixed world pose where
    /// — under the rotation — the marker box stays inside the view
    /// frustum.
    #[test]
    fn s5_1_45deg_z_rotated_grid_renders_marker() {
        use glam::DQuat;
        let rotation = DQuat::from_rotation_z(std::f64::consts::FRAC_PI_4);
        let (mut scene, _, marker) = build_one_grid_marker_scene(GridTransform {
            origin: DVec3::ZERO,
            rotation,
        });

        // World position of the marker's centre. Grid-local
        // (47.5, 47.5, 47.5) → world `rotation * (47.5, 47.5, 47.5)`.
        // R_z(45°): (47.5, 47.5, 47.5) → (0, 67.18, 47.5) (the x/y
        // components combine into a single +y vector at √2 * 47.5).
        let marker_world = rotation * DVec3::new(47.5, 47.5, 47.5);
        // Camera 80 units south of the marker on the world Y axis,
        // looking +y at the same z. RH basis.
        let camera = Camera {
            pos: [marker_world.x, marker_world.y - 80.0, marker_world.z],
            right: [-1.0, 0.0, 0.0],
            down: [0.0, 0.0, 1.0],
            forward: [0.0, 1.0, 0.0],
        };

        let (_engine, mut pool, mut fb, mut zb) = render_setup(CHUNK_SIZE_XY);
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let outcome = render_scene(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            None,
        );
        assert_eq!(outcome, RenderOutcome::Rendered { grids_drawn: 1 });
        let marker_count = fb.iter().filter(|&&p| p == marker).count();
        assert!(
            marker_count > 50,
            "45°-rotated marker box should be visible — got {marker_count} marker pixels"
        );
    }

    // ---- S5.2-followup: per-grid render_sky opt-out ----

    /// Two-grid scene where grid B sits behind grid A along +y;
    /// grid A is opaque only in the centre of the framebuffer, so
    /// the camera's view through grid A is mostly "ray miss". When
    /// `A.render_sky = false`, the pixels around A's silhouette
    /// must remain whatever grid B (or the shared pre-fill)
    /// painted — NOT A's grid-local sky colour. This pins the
    /// sentinel-mask path: without it, A's sky would write into
    /// the composed framebuffer wherever its sky-z happened to win
    /// the min-z race with B's sky-z.
    #[test]
    fn render_sky_false_drops_grid_sky_pixels() {
        use crate::{GridId, GridTransform};

        // Grid B (far, sky owner) — a wide floor of distinct
        // colour spanning chunk-local x/y so most rays land on it.
        let mut scene = Scene::new();
        let _b_id: GridId = scene.add_grid(GridTransform::at(DVec3::new(0.0, 600.0, 0.0)));
        // Find grid B's id (HashMap iteration; we only just added
        // one grid, so its id is whichever the iterator yields).
        let b_id = scene.grids().next().unwrap().0;
        scene.grid_mut(b_id).unwrap().set_rect(
            IVec3::new(0, 0, 100),
            IVec3::new(127, 127, 110),
            Some(0x80_22_88_22), // green floor
        );

        // Grid A (near, sky disabled) — a SMALL marker box that
        // covers only a fraction of the screen. Most pixels of A's
        // local render are sky.
        let a_id = scene.add_grid(GridTransform::at(DVec3::new(0.0, 200.0, 0.0)));
        scene.grid_mut(a_id).unwrap().set_rect(
            IVec3::new(60, 60, 60),
            IVec3::new(67, 67, 67),
            Some(0x80_aa_22_22), // red cube
        );
        scene.grid_mut(a_id).unwrap().render_sky = false;

        let unique_sky: u32 = 0xFF_AB_CD_EF;
        let (_engine, mut pool, _) = make_composed_pool(CHUNK_SIZE_XY);
        let mut fb = vec![unique_sky; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        let camera = camera_at([64.0, 0.0, 100.0]);
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let outcome = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            unique_sky,
            None,
        );
        assert_eq!(outcome, RenderOutcome::Rendered { grids_drawn: 2 });

        // The sentinel must never appear in the composed output —
        // every sentinel pixel must have been masked out before
        // compose. If any leak through, the test catches it.
        let leaked = fb
            .iter()
            .filter(|&&p| p == super::SKY_MASK_SENTINEL)
            .count();
        assert_eq!(
            leaked, 0,
            "SKY_MASK_SENTINEL leaked into composed framebuffer ({leaked} pixels)"
        );
        // Grid A's hit (red cube) must still render — render_sky=false
        // only affects sky pixels, not hits.
        let red_count = fb.iter().filter(|&&p| p == 0x80_aa_22_22).count();
        assert!(
            red_count > 0,
            "red cube from sky-disabled grid A is missing — render_sky=false should only mask sky"
        );
        // Grid B's floor must be visible past grid A's silhouette
        // (the sky-disabled grid doesn't hide B's render).
        let green_count = fb.iter().filter(|&&p| p == 0x80_22_88_22).count();
        assert!(
            green_count > 0,
            "grid B's floor invisible — grid A's masked sky may have overwritten it"
        );
    }

    /// Identity-rotation, single-grid scene with `render_sky = false`
    /// must produce a sentinel-free framebuffer. Sanity test for the
    /// trivial 1-grid case (no second grid to compose against).
    #[test]
    fn render_sky_false_single_grid_no_sentinel_leak() {
        let (mut scene, id, _) = build_one_grid_marker_scene(GridTransform::identity());
        scene.grid_mut(id).unwrap().render_sky = false;
        let unique_sky: u32 = 0xFF_12_34_56;
        let (_engine, mut pool, _) = make_composed_pool(CHUNK_SIZE_XY);
        let mut fb = vec![unique_sky; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        let camera = camera_at([64.0, 0.0, 64.0]);
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let outcome = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            unique_sky,
            None,
        );
        assert_eq!(outcome, RenderOutcome::Rendered { grids_drawn: 1 });
        let leaked = fb
            .iter()
            .filter(|&&p| p == super::SKY_MASK_SENTINEL)
            .count();
        assert_eq!(leaked, 0, "SKY_MASK_SENTINEL leaked ({leaked} pixels)");
        // Pixels that would have been the grid's sky now show
        // through to the pre-fill (unique_sky).
        let prefill_count = fb.iter().filter(|&&p| p == unique_sky).count();
        assert!(
            prefill_count > 0,
            "no pre-fill pixels survived — render_sky=false should leave non-hit pixels untouched"
        );
    }

    #[test]
    fn render_scene_at_origin_matches_direct_opticast() {
        // Grid at world origin → grid-local camera == world camera.
        // Single 1-chunk grid: combined view's bytes are byte-identical
        // to the chunk's own column data (slng-walk equivalence), so
        // render_scene must produce the same framebuffer as a direct
        // opticast on the chunk.
        let (mut scene, _) = build_one_grid_scene(DVec3::ZERO);
        let cam = camera_at([64.0, 0.0, 64.0]);
        let via_scene = render_via_scene(&mut scene, &cam);
        let via_direct = render_via_direct_opticast(&scene, &cam);
        assert_eq!(
            via_scene, via_direct,
            "render_scene with single 1-chunk grid at origin should match direct opticast"
        );
    }

    #[test]
    fn render_scene_translated_grid_matches_grid_local_opticast() {
        // Grid at world (1000, 2000, 3000). World camera at
        // (1064, 2000, 3064) — grid-local (64, 0, 64). render_scene
        // should produce the same output as a direct opticast call
        // with grid-local camera.
        let world_origin = DVec3::new(1000.0, 2000.0, 3000.0);
        let (mut scene, _) = build_one_grid_scene(world_origin);
        let world_cam = camera_at([1064.0, 2000.0, 3064.0]);
        let local_cam = camera_at([64.0, 0.0, 64.0]);
        let via_scene = render_via_scene(&mut scene, &world_cam);
        let via_direct = render_via_direct_opticast(&scene, &local_cam);
        assert_eq!(
            via_scene, via_direct,
            "render_scene of translated grid should match opticast with grid-local camera"
        );
    }

    #[test]
    fn empty_scene_returns_empty_outcome() {
        let mut scene = Scene::new();
        let (_engine, mut pool, mut fb, mut zb) = render_setup(CHUNK_SIZE_XY);
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let outcome = render_scene(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera_at([0.0, 0.0, 0.0]),
            &settings,
            None,
        );
        assert_eq!(outcome, RenderOutcome::Empty);
    }

    // ---- S3.1 / S4.0: render_scene_composed + 2-grid composition ----

    /// Build a 2-grid scene with two distinguishable boxes placed
    /// side-by-side in world space along the camera's right axis.
    /// Each grid holds one chunk (`(0, 0, 0)`) containing a single
    /// 16-voxel box with a uniquely-coloured surface so the
    /// composited framebuffer is partitionable by colour.
    fn build_two_grid_side_by_side() -> (Scene, u32, u32) {
        let mut scene = Scene::new();
        // Grid 0 at world (0, 200, 0): box centred chunk-local (64, 64, 100).
        let g0 = scene.add_grid(GridTransform::at(DVec3::new(0.0, 200.0, 0.0)));
        scene.grid_mut(g0).unwrap().set_rect(
            IVec3::new(56, 56, 92),
            IVec3::new(71, 71, 107),
            Some(0x80_88_22_22), // dark red
        );
        // Grid 1 at world (200, 200, 0): box centred chunk-local (64, 64, 100).
        let _g1 = scene.add_grid(GridTransform::at(DVec3::new(200.0, 200.0, 0.0)));
        // Borrow-checker dance: re-borrow grid 1 mutably.
        let g1_id = scene
            .grids()
            .filter(|(id, _)| *id != g0)
            .map(|(id, _)| id)
            .next()
            .unwrap();
        scene.grid_mut(g1_id).unwrap().set_rect(
            IVec3::new(56, 56, 92),
            IVec3::new(71, 71, 107),
            Some(0x80_22_22_88), // dark blue
        );
        (scene, 0x80_88_22_22, 0x80_22_22_88)
    }

    fn make_composed_pool(pool_vsid: u32) -> (Engine, ScratchPool, u32) {
        let engine = Engine::new();
        let mut pool = ScratchPool::new(XRES, YRES, pool_vsid);
        let sky_color = engine.sky_color();
        let sky_col_i = i32::from_ne_bytes(sky_color.to_ne_bytes());
        pool.set_skycast(sky_col_i, 0);
        let fog_col_i = i32::from_ne_bytes(engine.fog_color().to_ne_bytes());
        pool.set_fog(fog_col_i, engine.fog_max_scan_dist());
        pool.set_treat_z_max_as_air(true);
        (engine, pool, sky_color)
    }

    fn pixel_count(width: u32, height: u32) -> usize {
        (width as usize) * (height as usize)
    }

    #[test]
    fn compose_into_takes_smaller_z() {
        let mut shared_fb = vec![0xff_ff_ff_ff_u32; 4];
        let mut shared_zb = vec![10.0f32; 4];
        let temp_fb = [0xaa_aa_aa_aa, 0x11_22_33_44, 0x55_66_77_88, 0xde_ad_be_ef];
        let temp_zb = [5.0f32, 20.0, 10.0, f32::INFINITY];
        compose_into(&mut shared_fb, &mut shared_zb, &temp_fb, &temp_zb);
        // i=0: 5 < 10 → take temp.
        assert_eq!(shared_fb[0], 0xaa_aa_aa_aa);
        assert_eq!(shared_zb[0], 5.0);
        // i=1: 20 > 10 → keep shared.
        assert_eq!(shared_fb[1], 0xff_ff_ff_ff);
        assert_eq!(shared_zb[1], 10.0);
        // i=2: 10 == 10 → keep shared (`<` not `<=`).
        assert_eq!(shared_fb[2], 0xff_ff_ff_ff);
        // i=3: INFINITY > 10 → keep shared.
        assert_eq!(shared_fb[3], 0xff_ff_ff_ff);
    }

    #[test]
    fn render_scene_composed_two_grids_both_visible() {
        // Camera positioned to see both grids' boxes. Grid 0's box
        // at world (~64, ~264, ~100); grid 1's box at world
        // (~264, ~264, ~100). Camera at world (160, 100, 100)
        // looking +y centres both in view.
        let (mut scene, red, blue) = build_two_grid_side_by_side();
        let (_engine, mut pool, sky_color) = make_composed_pool(CHUNK_SIZE_XY);
        let mut fb = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];

        let camera = camera_at([160.0, 100.0, 100.0]);
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let outcome = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        assert_eq!(outcome, RenderOutcome::Rendered { grids_drawn: 2 });

        // Both colours should appear somewhere in the framebuffer.
        let red_count = fb.iter().filter(|&&p| p == red).count();
        let blue_count = fb.iter().filter(|&&p| p == blue).count();
        assert!(
            red_count > 0,
            "no red pixels: grid 0 (red box) not visible after compose"
        );
        assert!(
            blue_count > 0,
            "no blue pixels: grid 1 (blue box) not visible after compose"
        );
    }

    #[test]
    fn render_scene_composed_grid_a_in_front_of_grid_b() {
        // Two grids stacked along +y so grid A (closer) occludes
        // grid B (farther). After composition only grid A's colour
        // should appear on the overlap.
        let mut scene = Scene::new();
        let g_a = scene.add_grid(GridTransform::at(DVec3::new(0.0, 50.0, 0.0)));
        scene.grid_mut(g_a).unwrap().set_rect(
            IVec3::new(56, 56, 92),
            IVec3::new(71, 71, 107),
            Some(0x80_aa_00_00), // red
        );
        let _g_b = scene.add_grid(GridTransform::at(DVec3::new(0.0, 200.0, 0.0)));
        let g_b_id = scene
            .grids()
            .filter(|(id, _)| *id != g_a)
            .map(|(id, _)| id)
            .next()
            .unwrap();
        scene.grid_mut(g_b_id).unwrap().set_rect(
            IVec3::new(56, 56, 92),
            IVec3::new(71, 71, 107),
            Some(0x80_00_00_aa), // blue
        );

        let (_engine, mut pool, sky_color) = make_composed_pool(CHUNK_SIZE_XY);
        let mut fb = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];

        // Camera at (64, -10, 100) looking +y — both boxes line up
        // along the camera's forward axis.
        let camera = camera_at([64.0, -10.0, 100.0]);
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let outcome = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        assert_eq!(outcome, RenderOutcome::Rendered { grids_drawn: 2 });

        // Red (closer grid) should be visible. Blue (farther grid)
        // may peek around the edges but the central pixels should
        // be red where both boxes project.
        let red_count = fb.iter().filter(|&&p| p == 0x80_aa_00_00).count();
        assert!(
            red_count > 0,
            "expected red pixels (closer box should win z-test)"
        );

        // Reverse the registration order (force grid B drawn first)
        // and verify that's irrelevant — composition is commutative.
        let mut scene2 = Scene::new();
        let g_b2 = scene2.add_grid(GridTransform::at(DVec3::new(0.0, 200.0, 0.0)));
        scene2.grid_mut(g_b2).unwrap().set_rect(
            IVec3::new(56, 56, 92),
            IVec3::new(71, 71, 107),
            Some(0x80_00_00_aa),
        );
        let g_a2 = scene2.add_grid(GridTransform::at(DVec3::new(0.0, 50.0, 0.0)));
        scene2.grid_mut(g_a2).unwrap().set_rect(
            IVec3::new(56, 56, 92),
            IVec3::new(71, 71, 107),
            Some(0x80_aa_00_00),
        );

        let mut fb2 = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb2 = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        let outcome2 = render_scene_composed(
            &mut fb2,
            &mut zb2,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene2,
            &camera,
            &settings,
            sky_color,
            None,
        );
        assert_eq!(outcome2, RenderOutcome::Rendered { grids_drawn: 2 });
        assert_eq!(
            fb, fb2,
            "composition should be order-independent — same scene in different add order should produce identical output"
        );
    }

    // ---- S6.1: Mid-tier mip overrides ----

    /// Build a multi-mip-friendly grid: solid floor spanning the
    /// whole chunk at z=100..254 + `generate_mips(3)`. This is the
    /// same setup `vxl_generate_mips_on_set_voxel_chunk_renders`
    /// uses and is known to render at `mip_levels = 3,
    /// mip_scan_dist = 32`.
    ///
    /// Returns `(scene, grid_id)`. The Mid test sets the camera
    /// inside the chunk so chunk-local rays reach the floor at
    /// short distances; that lets the Mid override use
    /// `mip_scan_dist = 16` without busting the ray budget
    /// (`mip_scan_dist * 2^(mip_levels-1) = 16 * 4 = 64` covers the
    /// distance from camera to floor).
    fn build_mip_visible_grid(world_origin: DVec3) -> (Scene, crate::GridId) {
        let mut scene = Scene::new();
        let id = scene.add_grid(GridTransform::at(world_origin));
        let grid = scene.grid_mut(id).unwrap();
        // Solid floor across the entire chunk at z=100..254.
        grid.set_rect(
            IVec3::new(0, 0, 100),
            IVec3::new(127, 127, 254),
            Some(0x80_88_88_88),
        );
        // Build the per-chunk mip ladder so `gmipnum` can grow past 1.
        grid.chunk_mut(IVec3::ZERO).unwrap().generate_mips(3);
        (scene, id)
    }

    /// FNV-1a 64-bit hash of the framebuffer bytes.
    fn fb_hash(fb: &[u32]) -> u64 {
        let mut h: u64 = 0xcbf2_9ce4_8422_2325;
        for px in fb {
            for b in px.to_le_bytes() {
                h ^= u64::from(b);
                h = h.wrapping_mul(0x0000_0100_0000_01b3);
            }
        }
        h
    }

    /// Render `scene` via composed path with `mip_levels = 3,
    /// mip_scan_dist = 32` — same values the working
    /// `vxl_generate_mips_on_set_voxel_chunk_renders` test uses.
    /// Returns the framebuffer.
    fn render_with_multi_mip(scene: &mut Scene, camera: &Camera) -> Vec<u32> {
        let (_engine, mut pool, sky_color) = make_composed_pool(CHUNK_SIZE_XY);
        let mut fb = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        let mut settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        settings.mip_levels = 3;
        settings.mip_scan_dist = 32;
        let outcome = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            scene,
            camera,
            &settings,
            sky_color,
            None,
        );
        assert_eq!(outcome, RenderOutcome::Rendered { grids_drawn: 1 });
        fb
    }

    /// Mid-tier with explicit mip overrides must produce a different
    /// framebuffer than Near-tier rendering of the same scene. Loose
    /// test — checks hash inequality and that the Mid render still
    /// has some non-sky pixels (sanity that the renderer didn't bail).
    #[test]
    fn s6_1_mid_overrides_produce_different_framebuffer_than_near() {
        // Camera at grid origin + a bit inside the chunk, looking +y.
        let camera = camera_at([64.0, 0.0, 64.0]);

        // Scene A: default thresholds → Near tier → renderer uses
        // base settings (mip_levels=3, mip_scan_dist=32).
        let (mut scene_a, _) = build_mip_visible_grid(DVec3::ZERO);
        let fb_near = render_with_multi_mip(&mut scene_a, &camera);

        // Scene B: thresholds force Mid tier + mip overrides. We
        // cap mip_levels at 1 (no multi-mip) to guarantee a visible
        // pixel difference vs Near's mip-1/2 transitions. This is
        // the inverse of the typical "Mid = coarser" use case but
        // is the most reliable way to demonstrate that the override
        // path actually fires; production callers would more
        // commonly leave mip_levels at base and lower mip_scan_dist.
        let (mut scene_b, b_id) = build_mip_visible_grid(DVec3::ZERO);
        scene_b.grid_mut(b_id).unwrap().lod_thresholds = crate::LodThresholds {
            // r_near = 0 → any nonzero distance lands in Mid or Far.
            r_near: 0.0,
            r_mid: f64::INFINITY,
            mid_mip_levels: Some(1),
            mid_mip_scan_dist: None,
        };
        // Sanity: confirm the picker actually returns Mid for this pose.
        let lod = scene_b
            .grid(b_id)
            .unwrap()
            .select_lod(DVec3::from_array(camera.pos));
        assert_eq!(lod, Lod::Mid, "expected Mid tier for forced thresholds");
        let fb_mid = render_with_multi_mip(&mut scene_b, &camera);

        // Both renders must contain non-sky pixels (the override
        // didn't bust the renderer).
        let (_engine, _, sky_color) = make_composed_pool(CHUNK_SIZE_XY);
        let non_sky_near = fb_near.iter().filter(|&&p| p != sky_color).count();
        let non_sky_mid = fb_mid.iter().filter(|&&p| p != sky_color).count();
        assert!(
            non_sky_near > 100,
            "Near render too sparse ({non_sky_near})"
        );
        assert!(non_sky_mid > 100, "Mid render too sparse ({non_sky_mid})");

        // Hash must differ — the Mid override changed mip_levels
        // from 3 to 1, which changes mip transitions and so changes
        // pixels.
        let h_near = fb_hash(&fb_near);
        let h_mid = fb_hash(&fb_mid);
        assert_ne!(
            h_near, h_mid,
            "Mid tier with mid_mip_levels=Some(1) must differ from Near (h_near={h_near:016x})"
        );
    }

    /// Mid tier with `mid_mip_levels = None` AND
    /// `mid_mip_scan_dist = None` must produce a byte-identical
    /// framebuffer to Near. This is the graceful-degrade contract
    /// — callers can opt into the Mid plumbing without committing
    /// to a mip override and stay byte-stable.
    #[test]
    fn s6_1_mid_without_overrides_byte_identical_to_near() {
        let camera = camera_at([64.0, 0.0, 64.0]);

        // Scene A: default thresholds → Near.
        let (mut scene_a, _) = build_mip_visible_grid(DVec3::ZERO);
        let fb_near = render_with_multi_mip(&mut scene_a, &camera);

        // Scene B: thresholds force Mid but no mip overrides set.
        let (mut scene_b, b_id) = build_mip_visible_grid(DVec3::ZERO);
        scene_b.grid_mut(b_id).unwrap().lod_thresholds = crate::LodThresholds {
            r_near: 0.0,
            r_mid: f64::INFINITY,
            mid_mip_levels: None,
            mid_mip_scan_dist: None,
        };
        let lod = scene_b
            .grid(b_id)
            .unwrap()
            .select_lod(DVec3::from_array(camera.pos));
        assert_eq!(lod, Lod::Mid);
        let fb_mid = render_with_multi_mip(&mut scene_b, &camera);

        // Byte-identical: Mid with no overrides degrades cleanly.
        assert_eq!(
            fb_near, fb_mid,
            "Mid with both overrides=None must byte-match Near"
        );
    }

    /// `mip_levels_override` (the global per-grid cap) must compose
    /// with the Mid override: the effective `mip_levels` should be
    /// `min(mid_override, global_cap)`. Tests that the ship
    /// anti-axis-aligned-beam workaround survives Mid tier.
    ///
    /// We pin this by checking that a grid with `mip_levels_override
    /// = Some(1)` (mip-0 only — ship workaround) AND Mid-tier
    /// `mid_mip_levels = Some(4)` renders the same as a grid with
    /// just `mip_levels_override = Some(1)` at Near tier. Both
    /// resolve to `mip_levels = 1` (no multi-mip), so both must
    /// produce the same framebuffer.
    #[test]
    fn s6_1_global_mip_cap_survives_mid_tier() {
        let camera = camera_at([64.0, 0.0, 64.0]);

        // Scene A: Near tier + global cap=1.
        let (mut scene_a, a_id) = build_mip_visible_grid(DVec3::ZERO);
        scene_a.grid_mut(a_id).unwrap().mip_levels_override = Some(1);
        let fb_a = render_with_multi_mip(&mut scene_a, &camera);

        // Scene B: Mid tier + global cap=1 + Mid override=4. Global
        // cap (1) should win since it's the tighter floor on
        // `min(global_cap, mid_override)`.
        let (mut scene_b, b_id) = build_mip_visible_grid(DVec3::ZERO);
        scene_b.grid_mut(b_id).unwrap().mip_levels_override = Some(1);
        scene_b.grid_mut(b_id).unwrap().lod_thresholds = crate::LodThresholds {
            r_near: 0.0,
            r_mid: f64::INFINITY,
            mid_mip_levels: Some(4),
            // mip_scan_dist override left None so we isolate the
            // mip_levels resolution path.
            mid_mip_scan_dist: None,
        };
        let fb_b = render_with_multi_mip(&mut scene_b, &camera);

        assert_eq!(
            fb_a, fb_b,
            "global mip_levels_override should clamp Mid override (ship workaround survives Mid tier)"
        );
    }

    // ---- S6.3: Far-tier billboard blit ----

    /// Force Far tier via `r_near = 0, r_mid = 0`: any non-zero
    /// camera-to-grid distance lands on `Lod::Far`. Renders a small
    /// grid at world (0, 200, 0) with default-radius thresholds
    /// turned all-Far. The composed framebuffer must contain
    /// non-sky pixels from the impostor blit.
    #[test]
    fn s6_3_far_tier_blits_non_sky_pixels() {
        let (mut scene, id) = build_one_grid_scene(DVec3::new(0.0, 200.0, 0.0));
        scene.grid_mut(id).unwrap().lod_thresholds = crate::LodThresholds {
            r_near: 0.0,
            r_mid: 0.0,
            mid_mip_levels: None,
            mid_mip_scan_dist: None,
        };

        let camera = camera_at([64.0, 0.0, 100.0]);
        let (_engine, mut pool, sky_color) = make_composed_pool(CHUNK_SIZE_XY);
        let mut fb = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let outcome = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        assert_eq!(outcome, RenderOutcome::Rendered { grids_drawn: 1 });

        // Sanity: picker actually picked Far.
        let lod = scene
            .grid(id)
            .unwrap()
            .select_lod(DVec3::from_array(camera.pos));
        assert_eq!(lod, Lod::Far);

        // Impostor must paint at least some non-sky pixels.
        let non_sky = fb.iter().filter(|&&p| p != sky_color).count();
        assert!(
            non_sky > 0,
            "Far-tier render produced no non-sky pixels — billboard blit not firing"
        );
    }

    /// Lazy populate: cache starts `None`, becomes `Some` after the
    /// first Far render.
    #[test]
    fn s6_3_far_render_lazily_populates_cache() {
        let (mut scene, id) = build_one_grid_scene(DVec3::new(0.0, 200.0, 0.0));
        scene.grid_mut(id).unwrap().lod_thresholds = crate::LodThresholds {
            r_near: 0.0,
            r_mid: 0.0,
            mid_mip_levels: None,
            mid_mip_scan_dist: None,
        };
        assert!(scene.grid(id).unwrap().billboards.is_none());

        let camera = camera_at([64.0, 0.0, 100.0]);
        let (_engine, mut pool, sky_color) = make_composed_pool(CHUNK_SIZE_XY);
        let mut fb = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let _ = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        let cache = scene
            .grid(id)
            .unwrap()
            .billboards
            .as_ref()
            .expect("Far render should have populated billboards");
        assert_eq!(cache.len(), 26);
    }

    /// Edit invalidates the cache; a subsequent Far render rebuilds.
    #[test]
    fn s6_3_edit_invalidates_then_far_render_rebuilds() {
        let (mut scene, id) = build_one_grid_scene(DVec3::new(0.0, 200.0, 0.0));
        scene.grid_mut(id).unwrap().lod_thresholds = crate::LodThresholds {
            r_near: 0.0,
            r_mid: 0.0,
            mid_mip_levels: None,
            mid_mip_scan_dist: None,
        };
        let camera = camera_at([64.0, 0.0, 100.0]);
        let (_engine, mut pool, sky_color) = make_composed_pool(CHUNK_SIZE_XY);
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);

        // First Far render → cache built.
        let mut fb1 = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb1 = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        let _ = render_scene_composed(
            &mut fb1,
            &mut zb1,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        assert!(scene.grid(id).unwrap().billboards.is_some());

        // Edit invalidates.
        scene
            .grid_mut(id)
            .unwrap()
            .set_voxel(IVec3::new(70, 70, 70), Some(0x80_aa_aa_22));
        assert!(scene.grid(id).unwrap().billboards.is_none());

        // Second Far render rebuilds.
        let mut fb2 = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb2 = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        let _ = render_scene_composed(
            &mut fb2,
            &mut zb2,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        assert!(scene.grid(id).unwrap().billboards.is_some());
    }

    /// Hybrid scene: one Near grid + one Far grid. Both must render
    /// visibly; the Far grid via blit, the Near grid via opticast.
    /// Sanity check that the two paths cohabit one
    /// `render_scene_composed` call.
    #[test]
    fn s6_3_near_and_far_grids_in_same_scene() {
        let mut scene = Scene::new();
        // Grid A: stays Near (default thresholds). Solid box at
        // world (-30..-20, 190..210, 50..70).
        let a_id = scene.add_grid(GridTransform::at(DVec3::new(-100.0, 200.0, 0.0)));
        scene.grid_mut(a_id).unwrap().set_rect(
            IVec3::new(70, 0, 50),
            IVec3::new(85, 15, 70),
            Some(0x80_22_88_22), // green
        );
        // Grid B: forced Far. Box at world (~100, 200, 100).
        let b_id = scene.add_grid(GridTransform::at(DVec3::new(100.0, 200.0, 0.0)));
        scene.grid_mut(b_id).unwrap().set_rect(
            IVec3::new(0, 0, 80),
            IVec3::new(20, 20, 110),
            Some(0x80_aa_22_22), // red
        );
        scene.grid_mut(b_id).unwrap().lod_thresholds = crate::LodThresholds {
            r_near: 0.0,
            r_mid: 0.0,
            mid_mip_levels: None,
            mid_mip_scan_dist: None,
        };

        let camera = camera_at([0.0, 0.0, 80.0]);
        // Confirm A is Near, B is Far for this pose.
        assert_eq!(
            scene
                .grid(a_id)
                .unwrap()
                .select_lod(DVec3::from_array(camera.pos)),
            Lod::Near
        );
        assert_eq!(
            scene
                .grid(b_id)
                .unwrap()
                .select_lod(DVec3::from_array(camera.pos)),
            Lod::Far
        );

        let (_engine, mut pool, sky_color) = make_composed_pool(CHUNK_SIZE_XY);
        let mut fb = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let outcome = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        assert_eq!(outcome, RenderOutcome::Rendered { grids_drawn: 2 });

        // Each grid should contribute visible pixels.
        let non_sky = fb.iter().filter(|&&p| p != sky_color).count();
        assert!(
            non_sky > 20,
            "hybrid scene produced too few non-sky pixels ({non_sky}); one tier may have failed"
        );
    }

    /// Empty grid at Far tier: skipped silently (no panic, no
    /// allocation), `billboards` stays `None`.
    #[test]
    fn s6_3_empty_grid_at_far_is_skipped() {
        let mut scene = Scene::new();
        let id = scene.add_grid(GridTransform::at(DVec3::new(100.0, 200.0, 0.0)));
        scene.grid_mut(id).unwrap().lod_thresholds = crate::LodThresholds {
            r_near: 0.0,
            r_mid: 0.0,
            mid_mip_levels: None,
            mid_mip_scan_dist: None,
        };

        let camera = camera_at([0.0, 0.0, 100.0]);
        let (_engine, mut pool, sky_color) = make_composed_pool(CHUNK_SIZE_XY);
        let mut fb = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let outcome = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        // No grids contributed.
        assert_eq!(outcome, RenderOutcome::Empty);
        // Cache must NOT have been built for an empty grid.
        assert!(scene.grid(id).unwrap().billboards.is_none());
        // Framebuffer unchanged.
        assert!(fb.iter().all(|&p| p == sky_color));
    }

    // ---- S6.0: LOD picker wired but every tier falls through to Near ----

    /// Threshold-invariance: a grid rendered with the S6 derived
    /// thresholds (`from_radius` of the actual bounding sphere) must
    /// produce a framebuffer byte-identical to the same grid with
    /// default `always_near` thresholds, because S6.0 takes the
    /// `Near` arm of the match for all three tiers. This is the
    /// regression test for the S6.0 contract.
    #[test]
    fn render_scene_composed_lod_threshold_invariance() {
        // Scene A: default thresholds (always_near).
        let (mut scene_a, _a_id) = build_one_grid_scene(DVec3::new(0.0, 200.0, 0.0));
        let cam = camera_at([64.0, 0.0, 100.0]);
        let (_engine, mut pool, sky_color) = make_composed_pool(CHUNK_SIZE_XY);
        let mut fb_a = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb_a = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let outcome_a = render_scene_composed(
            &mut fb_a,
            &mut zb_a,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene_a,
            &cam,
            &settings,
            sky_color,
            None,
        );
        assert_eq!(outcome_a, RenderOutcome::Rendered { grids_drawn: 1 });

        // Scene B: thresholds derived from the grid's bounding
        // radius. At this camera distance the grid lands on Mid or
        // Far; if S6.0 ever stops falling through to Near, this test
        // catches the divergence.
        let (mut scene_b, b_id) = build_one_grid_scene(DVec3::new(0.0, 200.0, 0.0));
        let radius = scene_b.grid(b_id).unwrap().bounding_radius();
        assert!(
            radius > 0.0,
            "bounding_radius should be > 0 for a populated grid"
        );
        scene_b.grid_mut(b_id).unwrap().lod_thresholds = crate::LodThresholds::from_radius(radius);
        // Sanity: the camera is far enough that the picker no longer
        // returns Near (otherwise the invariance test would be vacuous).
        let lod = scene_b
            .grid(b_id)
            .unwrap()
            .select_lod(DVec3::from_array(cam.pos));
        assert_ne!(
            lod,
            Lod::Near,
            "camera should land in Mid or Far for derived thresholds — got {lod:?}",
        );

        let mut fb_b = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb_b = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        let outcome_b = render_scene_composed(
            &mut fb_b,
            &mut zb_b,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene_b,
            &cam,
            &settings,
            sky_color,
            None,
        );
        assert_eq!(outcome_b, RenderOutcome::Rendered { grids_drawn: 1 });

        // Byte-identity is the S6.0 contract — Mid/Far still take
        // the Near arm.
        assert_eq!(
            fb_a, fb_b,
            "S6.0 framebuffer must be byte-identical regardless of LOD thresholds"
        );
    }

    #[test]
    fn render_scene_composed_empty_scene_returns_empty() {
        let mut scene = Scene::new();
        let (_engine, mut pool, sky_color) = make_composed_pool(CHUNK_SIZE_XY);
        let mut fb = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        let camera = camera_at([0.0, 0.0, 0.0]);
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let outcome = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        assert_eq!(outcome, RenderOutcome::Empty);
        // fb should be unchanged (still all sky).
        assert!(fb.iter().all(|&p| p == sky_color));
    }

    /// FNV-1a 64-bit hash. Same offset/prime as the
    /// `roxlap-oracle::fnv1a64` helper used by the wasm-render
    /// goldens; pinning a render hash here is the same flavour of
    /// regression catch.
    fn fnv1a64(data: &[u8]) -> u64 {
        let mut h: u64 = 0xcbf2_9ce4_8422_2325;
        for &b in data {
            h ^= u64::from(b);
            h = h.wrapping_mul(0x0000_0100_0000_01b3);
        }
        h
    }

    // ---- S4.0 cross-chunk smoke test ----

    /// Two-chunk-wide grid: a recognisable shape spans the chunk
    /// boundary at `virtual_x = 128`. The render must not have a
    /// horizontal seam line at the boundary.
    #[test]
    fn render_scene_two_chunk_x_grid_no_seam() {
        let mut scene = Scene::new();
        let id = scene.add_grid(GridTransform::at(DVec3::new(0.0, 200.0, 0.0)));
        let g = scene.grid_mut(id).unwrap();
        // 100-voxel-tall stripe spanning x=[120..136] across the
        // x=128 chunk seam at z=200, y=[60..68]. After bake-free
        // render, every column in the stripe paints the same colour
        // at the same z; a seam at x=128 would show as missing
        // pixels in the column at virtual_x=128 / 129 / ...
        g.set_rect(
            IVec3::new(120, 60, 200),
            IVec3::new(136, 67, 215),
            Some(0x80_aa_55_22),
        );
        // Sanity: ensure both chunks were materialised.
        assert_eq!(g.chunk_count(), 2);

        // Render with a camera positioned to look at the stripe
        // straight on. Stripe at world (120..136, 260..268, 200..215).
        // Camera at (128, 100, 207) looking +y centres on it.
        let (_engine, mut pool, sky_color) = make_composed_pool(2 * CHUNK_SIZE_XY);
        let mut fb = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        let camera = camera_at([128.0, 100.0, 207.0]);
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let outcome = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        assert_eq!(outcome, RenderOutcome::Rendered { grids_drawn: 1 });

        // Stripe colour should appear in roughly the centre of the
        // framebuffer. A chunk-edge seam would manifest as a thin
        // sky-coloured vertical line splitting the stripe in two.
        let stripe = 0x80_aa_55_22;
        let stripe_count = fb.iter().filter(|&&p| p == stripe).count();
        assert!(
            stripe_count > 200,
            "stripe rendered too few pixels ({stripe_count}) — chunks may not be stitching"
        );

        // Walk the centre row left-to-right looking for a sky-pixel
        // gap inside a stripe run. A gap 1+ pixels wide flags a
        // chunk-edge seam.
        let centre_y = (YRES / 2) as usize;
        let row_start = centre_y * (XRES as usize);
        let row = &fb[row_start..row_start + (XRES as usize)];
        let mut in_stripe = false;
        let mut seam_gaps = 0usize;
        for &px in row {
            if px == stripe {
                in_stripe = true;
            } else if in_stripe && px == sky_color {
                // Stripe ended; if we re-enter it on this row that's
                // a seam.
                if row.iter().skip_while(|&&p| p != px).any(|&p| p == stripe) {
                    // Look ahead for any further stripe pixel.
                    seam_gaps += 1;
                }
                in_stripe = false;
            }
        }
        // We allow seam_gaps to count the legitimate "stripe ended,
        // didn't restart" transition once; more than that means
        // multiple disjoint runs on the row → seam.
        assert!(
            seam_gaps <= 1,
            "centre row has {seam_gaps} disjoint stripe runs — expected 1 (chunk-edge seam suspected)"
        );
    }

    /// Pin the byte-exact FNV-1a64 of a 2-chunk render. Catches
    /// any drift in the cross-chunk stitch / opticast path.
    /// S4B.5: regression test for the cf-halving + column-step
    /// interaction at chunk-vsid (=128) under multi-mip rendering.
    /// Prior to the fix in `grouscan.rs:phase_after_delete_kept_presync`
    /// the single-chunk column-step recomputed `ixy_sptr_col_idx`
    /// from `cy * vsid + cx`, mapping the post-remiporend mip-N
    /// sub-table index back into mip-0's range. The next mip
    /// transition then underflowed at
    /// `state.ixy_sptr_col_idx - mip_base_offsets[old_mip]`.
    ///
    /// `mip_scan_dist=32` chosen so the 3-mip depth ladder
    /// (32→64→128 PREC scan budgets) reaches the floor 36 voxels
    /// away at mip-1 or mip-2 — exercising the post-transition
    /// rendering path that was broken pre-fix.
    #[test]
    fn vxl_generate_mips_on_set_voxel_chunk_renders() {
        let mut grid = crate::Grid::new(GridTransform::identity());
        // Solid floor at z=100..254 across the entire chunk —
        // looks like the oracle test's terrain.
        grid.set_rect(
            IVec3::new(0, 0, 100),
            IVec3::new(127, 127, 254),
            Some(0x80_88_88_88),
        );
        let chunk = grid.chunks.get_mut(&IVec3::ZERO).unwrap();
        chunk.generate_mips(3);
        let (_engine, mut pool, sky_color) = make_composed_pool(CHUNK_SIZE_XY);
        let mut fb = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        let camera = camera_at([64.0, 0.0, 64.0]);
        let mut settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        settings.mip_levels = 3;
        settings.mip_scan_dist = 32;
        let grid_view = roxlap_core::GridView::from_single_vxl(&chunk);
        let mut rasterizer = ScalarRasterizer::new(&mut fb, &mut zb, XRES as usize, grid_view);
        let _ = core_opticast(&mut rasterizer, &mut pool, &camera, &settings, grid_view);
        drop(rasterizer);
        let non_sky = fb.iter().filter(|&&p| p != sky_color).count();
        assert!(
            non_sky > 0,
            "Vxl::generate_mips on a set_voxel-built chunk should render to something non-sky (got {non_sky})"
        );
    }

    /// Mip-0 preservation when mips are generated on the combined
    /// view but `mip_levels = 1` in the rasterizer's settings.
    /// Confirms `generate_mips` only APPENDS data — mip-0
    /// prefix is unchanged.
    #[test]
    fn render_with_mips_present_still_renders_mip0() {
        let mut scene = Scene::new();
        let id = scene.add_grid(GridTransform::at(DVec3::ZERO));
        scene.grid_mut(id).unwrap().set_rect(
            IVec3::new(40, 40, 40),
            IVec3::new(55, 55, 55),
            Some(0x80_88_88_88),
        );
        // S4B.4.a: force mip-1..mip-2 generation on the single
        // chunk directly (the Grid's combined-view cache API was
        // removed). The chunk's own Vxl::generate_mips builds its
        // own mip tables and the renderer happens to render through
        // them via Approach B's chunk_at_xy lookup.
        {
            let grid = scene.grid_mut(id).unwrap();
            let chunk = grid.chunks.get_mut(&IVec3::ZERO).unwrap();
            chunk.generate_mips(3);
        }

        let (_engine, mut pool, sky_color) = make_composed_pool(CHUNK_SIZE_XY);
        let mut fb = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        let camera = camera_at([64.0, 0.0, 64.0]);
        // mip_scan_dist huge → renderer never transitions past mip-0
        // so this test pins mip-0 correctness only.
        let mut settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        settings.mip_scan_dist = 100_000;
        let outcome = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        assert_eq!(outcome, RenderOutcome::Rendered { grids_drawn: 1 });
        let non_sky = fb.iter().filter(|&&p| p != sky_color).count();
        assert!(
            non_sky > 0,
            "render of single-grid scene with mips present rendered all-sky: mip-0 may be corrupted by generate_mips"
        );
    }

    #[test]
    fn render_scene_two_chunk_x_grid_hash_is_stable() {
        // Frozen 2026-05-10 at S4.0 landing on x86_64.
        const GOLDEN: u64 = 0x215e_d66d_7359_4725;
        // Same scene shape as `render_scene_two_chunk_x_grid_no_seam`
        // — kept distinct so the hash assertion doesn't share its
        // setup with the structural seam check.
        let mut scene = Scene::new();
        let id = scene.add_grid(GridTransform::at(DVec3::new(0.0, 200.0, 0.0)));
        scene.grid_mut(id).unwrap().set_rect(
            IVec3::new(120, 60, 200),
            IVec3::new(136, 67, 215),
            Some(0x80_aa_55_22),
        );
        let (_engine, mut pool, sky_color) = make_composed_pool(2 * CHUNK_SIZE_XY);
        let mut fb = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        let camera = camera_at([128.0, 100.0, 207.0]);
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let outcome = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        assert_eq!(outcome, RenderOutcome::Rendered { grids_drawn: 1 });

        let bytes: Vec<u8> = fb.iter().flat_map(|p| p.to_ne_bytes()).collect();
        let hash = fnv1a64(&bytes);
        if GOLDEN == SENTINEL {
            // First-run capture mode — print the hash so the
            // developer can paste it into GOLDEN above.
            eprintln!("render_scene_two_chunk_x_grid_hash_is_stable: capture hash = 0x{hash:016x}");
            panic!("GOLDEN is the SENTINEL placeholder — paste 0x{hash:016x} into GOLDEN above");
        }
        assert_eq!(
            hash, GOLDEN,
            "2-chunk render hash drifted: expected 0x{GOLDEN:016x}, got 0x{hash:016x}"
        );
    }

    /// Sentinel for first-run hash capture in
    /// [`render_scene_two_chunk_x_grid_hash_is_stable`]. Replace
    /// `GOLDEN`'s definition with the printed value once captured.
    const SENTINEL: u64 = 0xDEAD_BEEF_DEAD_BEEF;

    /// S4B.2.c.3: render a 2-chunk x-stripe scene via Approach B
    /// (multi-chunk GridView + direct opticast). Validates the full
    /// chain — `Grid::chunk_xy_backing` → `ChunkGrid` →
    /// `GridView::from_chunk_grid` → opticast prelude
    /// `recompute_camera_chunk` → `camera_chunk_air_gap` lookup →
    /// gline's chunk-aware seed → grouscan's chunk-swap column-step.
    ///
    /// Geometry: a floor in chunk (0, 0) at grid-local
    /// `(0..127, 0..127, 200..205)` plus a recognisable box in
    /// chunk (1, 0) at `(160..170, 50..60, 150..165)`. Camera in
    /// chunk (0, 0) looking +x so rays cross into chunk (1, 0) and
    /// must trigger the cross-chunk DDA. (Camera in chunk (1, 0) is
    /// blocked by the in_bounds_xy check that still uses the per-
    /// chunk vsid; full grid-AABB in_bounds gets revisited later.)
    ///
    /// Hash-pinned. Non-sky pixel count is the primary correctness
    /// signal — if the cross-chunk DDA were broken, only the floor
    /// in chunk (0, 0) would render.
    #[test]
    fn approach_b_renders_two_chunk_x_stripe_via_chunk_grid() {
        const SENTINEL_B: u64 = 0xDEAD_BEEF_DEAD_BEEF;
        // Frozen 2026-05-11 on x86_64 — Approach B's first
        // multi-chunk render (S4B.2.c.3). Refreeze when changing
        // the rasterizer; the cross-chunk DDA stays validated by
        // the `floor_count` + `box_count` assertions above.
        const GOLDEN_B: u64 = 0x5ee1_e81c_66a8_d1f1;

        let mut scene = Scene::new();
        let id = scene.add_grid(GridTransform::identity());
        let g = scene.grid_mut(id).unwrap();
        // Floor across chunk (0, 0) so rays looking +x always have
        // a hit before they exit the grid AABB.
        g.set_rect(
            IVec3::new(0, 0, 200),
            IVec3::new(127, 127, 205),
            Some(0x80_44_44_aa),
        );
        // Recognisable box deep in chunk (1, 0) — only visible if
        // the cross-chunk DDA fires.
        g.set_rect(
            IVec3::new(160, 50, 150),
            IVec3::new(170, 60, 165),
            Some(0x80_aa_55_22),
        );
        assert_eq!(g.chunk_count(), 2);

        // Build the multi-chunk GridView.
        let backing = g.chunk_xyz_backing().expect("at least one chunk populated");
        assert_eq!(backing.chunks_x, 2);
        assert_eq!(backing.chunks_y, 1);
        assert_eq!(backing.origin_chunk_xy, [0, 0]);
        let cg = roxlap_core::ChunkGrid {
            chunks: &backing.chunks,
            origin_chunk_xy: backing.origin_chunk_xy,
            origin_chunk_z: backing.origin_chunk_z,
            chunks_x: backing.chunks_x,
            chunks_y: backing.chunks_y,
            chunks_z: backing.chunks_z,
        };
        let grid_view = roxlap_core::GridView::from_chunk_grid(&cg, CHUNK_SIZE_XY);

        // Camera in chunk (0, 0) looking +x toward chunk (1, 0).
        // Voxlap z-down basis: right × down == forward.
        let camera = Camera {
            pos: [10.0, 64.0, 160.0],
            right: [0.0, 1.0, 0.0],
            down: [0.0, 0.0, 1.0],
            forward: [1.0, 0.0, 0.0],
        };
        let (_engine, mut pool, mut fb, mut zb) = render_setup(2 * CHUNK_SIZE_XY);
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let mut rasterizer = ScalarRasterizer::new(&mut fb, &mut zb, XRES as usize, grid_view);
        let outcome = core_opticast(&mut rasterizer, &mut pool, &camera, &settings, grid_view);
        drop(rasterizer);
        assert_eq!(outcome, OpticastOutcome::Rendered);

        // Hits BOTH the floor (chunk 0, 0) AND the box (chunk 1, 0).
        let floor_count = fb.iter().filter(|&&p| p == 0x80_44_44_aa).count();
        let box_count = fb.iter().filter(|&&p| p == 0x80_aa_55_22).count();
        assert!(
            floor_count > 1000,
            "floor not visible — only {floor_count} floor pixels (single-chunk path?)"
        );
        assert!(
            box_count > 50,
            "box in chunk (1, 0) not visible — only {box_count} box pixels — cross-chunk DDA may have failed to fire"
        );

        // Hash-pin the output. Refreeze when changing the rasterizer.
        let bytes: Vec<u8> = fb.iter().flat_map(|p| p.to_ne_bytes()).collect();
        let hash = fnv1a64(&bytes);
        if GOLDEN_B == SENTINEL_B {
            eprintln!("approach_b_renders_two_chunk_x_stripe_via_chunk_grid: capture hash = 0x{hash:016x}");
            panic!(
                "GOLDEN_B is the SENTINEL placeholder — paste 0x{hash:016x} into GOLDEN_B above"
            );
        }
        assert_eq!(
            hash, GOLDEN_B,
            "Approach B 2-chunk render hash drifted: expected 0x{GOLDEN_B:016x}, got 0x{hash:016x}"
        );
    }

    /// S4B.2.d: multi-chunk camera that sits **past** the first
    /// chunk's vsid (i.e., inside chunk (1, 0)). Validates that
    /// `recompute_in_bounds_xy` against the grid AABB recognises
    /// the camera as in-bounds — and that the seed path looks up
    /// chunk (1, 0)'s column via `chunk_at_xy(camera_chunk_idx)`
    /// instead of returning the OOB-XY bedrock placeholder.
    ///
    /// Scene shape: a 2-chunk x-stripe with a floor in chunk (1, 0)
    /// (where the camera sits) and the recognisable box in chunk
    /// (0, 0). The camera looks `-x` so rays cross from chunk
    /// (1, 0) back into chunk (0, 0). Tests the OTHER direction of
    /// cross-chunk DDA + the in-bounds AABB fix together.
    #[test]
    fn approach_b_camera_in_chunk_1_0_renders_neighbour() {
        let mut scene = Scene::new();
        let id = scene.add_grid(GridTransform::identity());
        let g = scene.grid_mut(id).unwrap();
        // Floor under the camera in chunk (1, 0).
        g.set_rect(
            IVec3::new(128, 0, 200),
            IVec3::new(255, 127, 205),
            Some(0x80_44_44_aa),
        );
        // Box deep in chunk (0, 0) — only visible if the camera in
        // chunk (1, 0) is recognised as in-bounds AND the
        // cross-chunk DDA fires westward.
        g.set_rect(
            IVec3::new(20, 50, 150),
            IVec3::new(30, 60, 165),
            Some(0x80_aa_55_22),
        );
        assert_eq!(g.chunk_count(), 2);

        let backing = g.chunk_xyz_backing().expect("populated");
        let cg = roxlap_core::ChunkGrid {
            chunks: &backing.chunks,
            origin_chunk_xy: backing.origin_chunk_xy,
            origin_chunk_z: backing.origin_chunk_z,
            chunks_x: backing.chunks_x,
            chunks_y: backing.chunks_y,
            chunks_z: backing.chunks_z,
        };
        let grid_view = roxlap_core::GridView::from_chunk_grid(&cg, CHUNK_SIZE_XY);
        let (aabb_min, aabb_max) = grid_view.aabb_xy();
        assert_eq!(aabb_min, [0, 0]);
        assert_eq!(aabb_max, [256, 128]);

        // Camera deep in chunk (1, 0): world (200, 64, 160). Past
        // the single-chunk vsid=128 OOB cutoff but inside the
        // multi-chunk AABB. Look -x toward chunk (0, 0).
        let camera = Camera {
            pos: [200.0, 64.0, 160.0],
            right: [0.0, -1.0, 0.0],
            down: [0.0, 0.0, 1.0],
            forward: [-1.0, 0.0, 0.0],
        };
        let (_engine, mut pool, mut fb, mut zb) = render_setup(2 * CHUNK_SIZE_XY);
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let mut rasterizer = ScalarRasterizer::new(&mut fb, &mut zb, XRES as usize, grid_view);
        let outcome = core_opticast(&mut rasterizer, &mut pool, &camera, &settings, grid_view);
        drop(rasterizer);
        assert_eq!(outcome, OpticastOutcome::Rendered);

        let floor_count = fb.iter().filter(|&&p| p == 0x80_44_44_aa).count();
        let box_count = fb.iter().filter(|&&p| p == 0x80_aa_55_22).count();
        assert!(
            floor_count > 1000,
            "floor under camera in chunk (1, 0) not visible — only {floor_count} floor pixels — in_bounds_xy fix may not have taken effect"
        );
        assert!(
            box_count > 50,
            "box in chunk (0, 0) not visible — only {box_count} box pixels — westward cross-chunk DDA failed"
        );
    }

    /// S4B.6.c: stacked-grid scaffold — camera in chz=1 (= world
    /// z=256..511) of a 2-chunk-tall grid should render its own
    /// chunk's terrain. Verifies cf seed + slab-byte reads + chunk-
    /// XY swaps all use world-z consistently.
    ///
    /// Cross-chunk look-down (= camera in chz=0 sees terrain in
    /// chz=1) needs cf z range extension at air-gap-lookup time;
    /// that's a follow-up to S4B.6.c.
    #[test]
    fn stacked_two_chunk_z_camera_in_chz1_sees_own_chunk_floor() {
        let mut scene = Scene::new();
        let id = scene.add_grid(GridTransform::at(DVec3::ZERO));
        let g = scene.grid_mut(id).unwrap();
        // chz=0: all-air (materialised so chunk_xyz_backing enumerates).
        g.ensure_chunk(IVec3::new(0, 0, 0));
        // chz=1: floor at local z=50 (= world z=306).
        g.set_rect(
            IVec3::new(60, 60, 306),
            IVec3::new(72, 72, 310),
            Some(0x80_33_66_99),
        );
        assert!(g.chunk(IVec3::new(0, 0, 1)).is_some());

        let (_engine, mut pool, sky_color) = make_composed_pool(2 * CHUNK_SIZE_XY);
        let mut fb = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        pool.set_treat_z_max_as_air(true);
        // Camera at world (66, 66, 280) — directly above the
        // floor at world z=306. Look STRAIGHT DOWN (z increases =
        // down in voxlap z-down).
        let camera = Camera {
            pos: [66.0, 66.0, 280.0],
            right: [1.0, 0.0, 0.0],
            down: [0.0, 1.0, 0.0],
            forward: [0.0, 0.0, 1.0],
        };
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let outcome = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        assert_eq!(outcome, RenderOutcome::Rendered { grids_drawn: 1 });
        let floor_count = fb.iter().filter(|&&p| p == 0x80_33_66_99).count();
        assert!(
            floor_count > 100,
            "camera at chz=1 with floor in same chunk should see it — got {floor_count} floor pixels"
        );
    }

    /// S4B.6.e: cross-chunk look-down. Camera in chz=0's all-air
    /// chunk should see chz=1's floor below it. This was deferred
    /// from S4B.6.c because the cf seed's z range capped at the
    /// camera-chunk's bedrock (world z=255); S4B.6.e extends the
    /// air-gap walk in `camera_chunk_air_gap` to step into the
    /// next chunk down when the camera's column is all-air-bedrock,
    /// and the rasterizer routes state.column / slab_buf to the
    /// chunk holding the real floor via `seed_chunk_z`.
    #[test]
    fn stacked_two_chunk_z_camera_in_chz0_sees_chz1_floor() {
        let mut scene = Scene::new();
        let id = scene.add_grid(GridTransform::at(DVec3::ZERO));
        let g = scene.grid_mut(id).unwrap();
        // chz=0: all-air. Materialised so chunk_xyz_backing
        // enumerates it.
        g.ensure_chunk(IVec3::new(0, 0, 0));
        // chz=1: floor at world z=306..310 (= local z=50..54).
        g.set_rect(
            IVec3::new(60, 60, 306),
            IVec3::new(72, 72, 310),
            Some(0x80_77_aa_44),
        );
        assert!(g.chunk(IVec3::new(0, 0, 1)).is_some());

        let (_engine, mut pool, sky_color) = make_composed_pool(2 * CHUNK_SIZE_XY);
        let mut fb = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        pool.set_treat_z_max_as_air(true);
        // Camera at world (66, 66, 100) — in chz=0's all-air
        // chunk. Look STRAIGHT DOWN (z+) toward chz=1's floor at
        // world z=306.
        let camera = Camera {
            pos: [66.0, 66.0, 100.0],
            right: [1.0, 0.0, 0.0],
            down: [0.0, 1.0, 0.0],
            forward: [0.0, 0.0, 1.0],
        };
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let outcome = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        assert_eq!(outcome, RenderOutcome::Rendered { grids_drawn: 1 });
        let floor_count = fb.iter().filter(|&&p| p == 0x80_77_aa_44).count();
        assert!(
            floor_count > 50,
            "camera in chz=0 air-gap should see chz=1 floor via cross-chunk look-down — got {floor_count} floor pixels"
        );
    }

    /// S4B.6.l KNOWN LIMITATION (pre-S4B.6.l fix): camera at chz=0
    /// with all-air-bedrock at the camera's own XY column
    /// (seed_chz=1 via cross-chunk look-down). A DIFFERENT XY column
    /// has chz=0 content (= a distant mountain entirely inside
    /// chz=0). State.current_chunk_z gets pinned to 1 at seed time
    /// and the chunk-XY swap reads chz=1 chunks across the DDA, so
    /// the chz=0 mountain is invisible. This test pins the limitation
    /// — it currently asserts mountain_count == 0 to fail loudly
    /// (= the limitation has been fixed) once cf-splitting at chz
    /// boundaries lands.
    #[test]
    #[ignore = "S4B.6.l: known limitation — needs cf-splitting at chz boundaries"]
    fn stacked_chz0_distant_mountain_visible_from_chz0_camera() {
        let mut scene = Scene::new();
        let id = scene.add_grid(GridTransform::at(DVec3::ZERO));
        let g = scene.grid_mut(id).unwrap();
        // chz=0 mountain at a column DISTANT from the camera —
        // entirely in chz=0 (world z=100..200), so chz=1 at the
        // same XY is all-air-bedrock.
        g.set_rect(
            IVec3::new(100, 100, 100),
            IVec3::new(124, 124, 200),
            Some(0x80_aa_55_22), // distinct brown
        );
        // chz=1 hills filling the floor at world z=336..360 across
        // the chunk EXCEPT a hole around the mountain XY (so the
        // mountain doesn't sit on a green tower).
        g.set_rect(
            IVec3::new(0, 0, 336),
            IVec3::new(128, 128, 360),
            Some(0x80_22_88_44),
        );
        g.set_rect(IVec3::new(100, 100, 336), IVec3::new(124, 124, 360), None);
        // Materialise chz=0 + chz=1 (chz=0 has the mountain; chz=1
        // has the hills).
        assert!(g.chunk(IVec3::new(0, 0, 0)).is_some());
        assert!(g.chunk(IVec3::new(0, 0, 1)).is_some());

        let (_engine, mut pool, sky_color) = make_composed_pool(CHUNK_SIZE_XY);
        let mut fb = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        pool.set_treat_z_max_as_air(true);
        // Camera at (40, 40, 60) — chz=0 air, FAR from the mountain
        // XY (100..124, 100..124). Yaw=π/4 (look toward +x+y =
        // mountain direction), pitch=0.72 rad (≈ 41° down) so the
        // ray bisecting the screen aims at the chz=0 mountain centre
        // ≈ (112, 112, 150).
        let (sy, cy) = (std::f64::consts::FRAC_PI_4).sin_cos();
        let (sp, cp) = 0.72_f64.sin_cos();
        let camera = Camera {
            pos: [40.0, 40.0, 60.0],
            right: [-sy, cy, 0.0],
            down: [-cy * sp, -sy * sp, cp],
            forward: [cy * cp, sy * cp, sp],
        };
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let outcome = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        assert_eq!(outcome, RenderOutcome::Rendered { grids_drawn: 1 });
        let mountain_count = fb.iter().filter(|&&p| p == 0x80_aa_55_22).count();
        let hill_count = fb.iter().filter(|&&p| p == 0x80_22_88_44).count();
        eprintln!("chz0-distant-mountain: mountain_chz0={mountain_count} hill_chz1={hill_count}");
        // chz=1 hills are reachable via seed-time cross-chunk
        // look-down.
        assert!(
            hill_count > 50,
            "expected chz=1 hills via cross-chunk look-down — got {hill_count}"
        );
        // The proper-fix assertion: chz=0 distant mountain SHOULD be
        // visible. Currently fails — pins the limitation.
        assert!(
            mountain_count > 50,
            "expected chz=0 distant mountain visible — got {mountain_count} (S4B.6.l limitation)"
        );
    }

    /// S4B.6.h: mid-render chunk-Z handoff. Camera column has
    /// content in chz=0 (= a mountain at the camera's XY) so
    /// seed-time cross-chunk look-down does NOT fire — seed_chz=0.
    /// As rays DDA across the scene, they visit XY columns where
    /// chz=0 is all-air-bedrock. Mid-render handoff should swap
    /// state to chz=1's column at those XY positions and reveal
    /// hill content sitting under the camera's chz=0 layer.
    ///
    /// This is the "tall mountains breaching chunk-Z boundary"
    /// case the demo aims for.
    #[test]
    fn mid_render_handoff_reveals_chz1_hills_under_mountain_camera() {
        let mut scene = Scene::new();
        let id = scene.add_grid(GridTransform::at(DVec3::ZERO));
        let g = scene.grid_mut(id).unwrap();
        // chz=0: a small "mountain peak" at the camera's XY.
        // Mountain at world z=150..200 — solid block.
        g.set_rect(
            IVec3::new(60, 60, 150),
            IVec3::new(72, 72, 200),
            Some(0x80_88_44_22), // brown mountain
        );
        // chz=1: hills at world z=336..360 across the WHOLE chunk
        // (so DDA rays hit them when chz=0 is air).
        g.set_rect(
            IVec3::new(0, 0, 336),
            IVec3::new(128, 128, 360),
            Some(0x80_22_88_44), // green hills
        );
        // Carve a hole in chz=1's hill at the mountain's footprint
        // so the mountain doesn't appear to "float" on green.
        g.set_rect(IVec3::new(60, 60, 336), IVec3::new(72, 72, 360), None);
        assert!(g.chunk(IVec3::new(0, 0, 0)).is_some());
        assert!(g.chunk(IVec3::new(0, 0, 1)).is_some());

        let (_engine, mut pool, sky_color) = make_composed_pool(2 * CHUNK_SIZE_XY);
        let mut fb = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        pool.set_treat_z_max_as_air(true);
        // Camera at world (66, 66, 100) — directly above the
        // mountain peak (at z=150). Camera column has the
        // mountain in chz=0. Look straight down.
        let camera = Camera {
            pos: [66.0, 66.0, 100.0],
            right: [1.0, 0.0, 0.0],
            down: [0.0, 1.0, 0.0],
            forward: [0.0, 0.0, 1.0],
        };
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let outcome = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        assert_eq!(outcome, RenderOutcome::Rendered { grids_drawn: 1 });
        let mountain_count = fb.iter().filter(|&&p| p == 0x80_88_44_22).count();
        let hill_count = fb.iter().filter(|&&p| p == 0x80_22_88_44).count();
        // Verify the hills render at approximately the correct
        // world-z by sampling the z-buffer at hill pixels. Camera
        // at z=100 looking straight down; hills at world z=336.
        // Expected depth = 236 for directly-below pixels. If
        // state.z1 stays stuck at the mountain peak's z=150 the
        // hills would render with depth ≈ 50 → orders of magnitude
        // off.
        let mut hill_depths: Vec<f32> = fb
            .iter()
            .zip(zb.iter())
            .filter_map(|(&p, &d)| if p == 0x80_22_88_44 { Some(d) } else { None })
            .collect();
        hill_depths.sort_by(|a, b| a.partial_cmp(b).unwrap());
        let median_hill_depth = hill_depths[hill_depths.len() / 2];
        eprintln!(
            "mid-render handoff: mountain={mountain_count} hill={hill_count} median_hill_depth={median_hill_depth:.1}"
        );
        assert!(
            mountain_count > 50,
            "should see mountain peak via chz=0 — got {mountain_count} mountain pixels"
        );
        assert!(
            hill_count > 50,
            "should see chz=1 hills via mid-render handoff — got {hill_count} hill pixels"
        );
        assert!(
            (median_hill_depth - 236.0).abs() < 80.0,
            "hill median depth should be ≈236 (camera→z=336); got {median_hill_depth:.1} — state.z1 may be stale at the mountain peak's z"
        );
    }

    /// S4B.6.g: cross-chunk look-down under multi-mip. Same scene
    /// as `stacked_two_chunk_z_camera_in_chz0_sees_chz1_floor` but
    /// with `mip_levels=2, mip_scan_dist=16` so the rasterizer
    /// transitions to mip-1 well within the chz=1 terrain. Locks in
    /// the slab_z_at mip-N offset fix (= `chunk_world_z_base >>
    /// gmipcnt`). Pre-fix produced a green / brown "wall in a circle
    /// around the camera" because mip-1 rendered the floor at
    /// world-z ≈ 178 instead of 306.
    #[test]
    fn stacked_two_chunk_z_camera_in_chz0_sees_chz1_floor_multi_mip() {
        let mut scene = Scene::new();
        let id = scene.add_grid(GridTransform::at(DVec3::ZERO));
        let g = scene.grid_mut(id).unwrap();
        g.ensure_chunk(IVec3::new(0, 0, 0));
        g.set_rect(
            IVec3::new(60, 60, 306),
            IVec3::new(72, 72, 310),
            Some(0x80_77_aa_44),
        );
        assert!(g.chunk(IVec3::new(0, 0, 1)).is_some());

        let (_engine, mut pool, sky_color) = make_composed_pool(2 * CHUNK_SIZE_XY);
        let mut fb = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        pool.set_treat_z_max_as_air(true);
        let camera = Camera {
            pos: [66.0, 66.0, 100.0],
            right: [1.0, 0.0, 0.0],
            down: [0.0, 1.0, 0.0],
            forward: [0.0, 0.0, 1.0],
        };
        let mut settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        settings.mip_levels = 2;
        settings.mip_scan_dist = 16;
        let outcome = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        assert_eq!(outcome, RenderOutcome::Rendered { grids_drawn: 1 });
        let floor_count = fb.iter().filter(|&&p| p == 0x80_77_aa_44).count();
        assert!(
            floor_count > 50,
            "multi-mip cross-chunk look-down should still see chz=1 floor — got {floor_count} floor pixels"
        );
    }

    /// S4B.6.d: 3-chunk-tall stack stresses the widened gylookup
    /// (`(chunks_z * 512) >> mip + 4` per mip). Pre-S4B.6.d, gylookup
    /// was hardcoded at `(512 >> mip) + 4`, which would OOB or alias
    /// for any z > 511. This test renders a floor at world z=562
    /// (= chz=2, local z=50) with the camera at world z=540, looking
    /// straight down. Multi-mip is on so we exercise the mip slide
    /// path in `phase_remiporend` that scales `advance` by chunks_z.
    #[test]
    fn stacked_three_chunk_z_camera_in_chz2_sees_own_chunk_floor_multi_mip() {
        let mut scene = Scene::new();
        let id = scene.add_grid(GridTransform::at(DVec3::ZERO));
        let g = scene.grid_mut(id).unwrap();
        // Materialise chz=0 + chz=1 so chunk_xyz_backing enumerates
        // the full stack.
        g.ensure_chunk(IVec3::new(0, 0, 0));
        g.ensure_chunk(IVec3::new(0, 0, 1));
        // chz=2: floor at world z=562..566 (= local z=50..54).
        g.set_rect(
            IVec3::new(60, 60, 562),
            IVec3::new(72, 72, 566),
            Some(0x80_aa_55_22),
        );
        assert!(g.chunk(IVec3::new(0, 0, 2)).is_some());

        let (_engine, mut pool, sky_color) = make_composed_pool(2 * CHUNK_SIZE_XY);
        let mut fb = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        pool.set_treat_z_max_as_air(true);
        let camera = Camera {
            pos: [66.0, 66.0, 540.0],
            right: [1.0, 0.0, 0.0],
            down: [0.0, 1.0, 0.0],
            forward: [0.0, 0.0, 1.0],
        };
        // Multi-mip on to exercise the gylookup-slide path.
        let mut settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        settings.mip_levels = 2;
        settings.mip_scan_dist = 16;
        let outcome = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        assert_eq!(outcome, RenderOutcome::Rendered { grids_drawn: 1 });
        let floor_count = fb.iter().filter(|&&p| p == 0x80_aa_55_22).count();
        assert!(
            floor_count > 100,
            "camera at chz=2 with floor in same chunk should see it — got {floor_count} floor pixels"
        );
    }

    // ---- S7.4: render integration with streaming ----

    /// Floor-stamping generator for S7.4 render tests. Produces a
    /// 10-voxel-thick floor at the bottom of every chunk it
    /// generates (chunk-local `z = 230..239`, all xy). Visible as
    /// a green stripe along the bottom of the framebuffer when
    /// the camera looks +y across populated chunks.
    #[derive(Debug)]
    struct FloorGenerator;

    impl crate::ChunkGenerator for FloorGenerator {
        fn generate(&self, _chunk_idx: IVec3) -> roxlap_formats::vxl::Vxl {
            // Lean on `Grid::ensure_chunk` for the empty-chunk
            // builder, then carve a floor via `set_rect`. Detach
            // the chunk from the temporary grid and return it.
            let mut tmp = crate::Grid::new(GridTransform::identity());
            tmp.ensure_chunk(IVec3::ZERO);
            let mut vxl = tmp.chunks.remove(&IVec3::ZERO).unwrap();
            #[allow(clippy::cast_possible_wrap)]
            roxlap_formats::edit::set_rect(
                &mut vxl,
                glam::IVec3::new(0, 0, 230).into(),
                glam::IVec3::new((CHUNK_SIZE_XY - 1) as i32, (CHUNK_SIZE_XY - 1) as i32, 239)
                    .into(),
                Some(0x80_22_aa_22),
            );
            vxl
        }
    }

    #[test]
    fn render_scene_composed_unpumped_streaming_grid_renders_all_sky() {
        // S7.4(a): a grid with a generator + active stream radius
        // but no pump_streaming call has zero chunks. The render
        // walks the grid (chunk_xyz_backing returns None for an
        // empty chunk map → grid is skipped), framebuffer stays
        // sky.
        use std::sync::Arc;
        let mut scene = Scene::new();
        let id = scene.add_grid(GridTransform::at(DVec3::ZERO));
        let g = scene.grid_mut(id).unwrap();
        g.set_generator(Some(Arc::new(FloorGenerator)));
        g.stream_radius = crate::StreamRadius::new(300.0, 600.0);
        assert!(g.chunks.is_empty(), "no pump yet → no chunks");

        let (_engine, mut pool, sky_color) = make_composed_pool(CHUNK_SIZE_XY);
        let mut fb = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        // Camera at (64, -100, 200) looking +y so it would see
        // chunks ahead once they exist.
        let camera = camera_at([64.0, -100.0, 200.0]);
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let _ = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        // Empty grid path skips opticast → framebuffer untouched.
        assert!(
            fb.iter().all(|&p| p == sky_color),
            "unpumped streaming grid must render as all sky"
        );
    }

    #[test]
    fn render_scene_composed_picks_up_streamed_chunks_after_sync_pump() {
        // S7.4(a): once the streaming pump installs chunks, the
        // next render shows them. Using pump_streaming_sync for
        // deterministic timing — pump_streaming (async) lands
        // the same way modulo a frame of latency.
        use std::sync::Arc;
        let mut scene = Scene::new();
        let id = scene.add_grid(GridTransform::at(DVec3::ZERO));
        let g = scene.grid_mut(id).unwrap();
        g.set_generator(Some(Arc::new(FloorGenerator)));
        // Cover chunks ahead of the camera (y=0, y=128, y=256).
        g.stream_radius = crate::StreamRadius::new(300.0, 600.0);

        // Render BEFORE pump: zero floor pixels.
        let (_engine, mut pool, sky_color) = make_composed_pool(CHUNK_SIZE_XY);
        let mut fb = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        let camera = camera_at([64.0, -100.0, 200.0]);
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let _ = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        let pre_floor = fb.iter().filter(|&&p| p == 0x80_22_aa_22).count();
        assert_eq!(pre_floor, 0, "pre-pump frame has no streamed chunks");

        // Pump synchronously — `world_pos` matches the camera so
        // chunks ahead of it (within r_active = 300) stream in.
        scene.pump_streaming_sync(DVec3::new(64.0, -100.0, 200.0));
        let g = scene.grid(id).unwrap();
        assert!(
            !g.chunks.is_empty(),
            "pump should have streamed at least one chunk"
        );

        // Render AFTER pump: the floor should now be visible. Reset
        // the framebuffer to sky first.
        fb.iter_mut().for_each(|p| *p = sky_color);
        zb.iter_mut().for_each(|z| *z = f32::INFINITY);
        let outcome = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        assert_eq!(outcome, RenderOutcome::Rendered { grids_drawn: 1 });
        let post_floor = fb.iter().filter(|&&p| p == 0x80_22_aa_22).count();
        assert!(
            post_floor > 100,
            "post-pump frame should show the streamed floor — got {post_floor} green pixels"
        );
    }

    #[test]
    fn render_scene_composed_partial_streaming_renders_pending_chunks_as_air() {
        // S7.4(a): mixed state — some r_active chunks are
        // materialised, others are still pending (not in
        // `chunks`). The render must treat pending chunks as
        // implicit-air. Verified by stamping one chunk via the
        // generator + skipping the others, then confirming the
        // framebuffer has fewer floor pixels than the
        // fully-pumped baseline.
        use std::sync::Arc;
        let mut scene = Scene::new();
        let id = scene.add_grid(GridTransform::at(DVec3::ZERO));
        let g = scene.grid_mut(id).unwrap();
        g.set_generator(Some(Arc::new(FloorGenerator)));
        // r_active must be set so the later pump_streaming_sync
        // sanity-check actually streams more chunks in. Kept at
        // 300 so the resulting chunks_z stack is ≤ 3 — opticast's
        // `gylookup` table multiplies `chunks_z * 512 * PREC` and
        // overflows i32 at chunks_z ≥ 4 (pre-existing limit, not
        // S7.4 scope to fix).
        g.stream_radius = crate::StreamRadius::new(300.0, 600.0);

        // Materialise ONLY chunk (0, 0, 0) manually via the
        // sync helper — leave (0, 1, 0), (0, 2, 0) absent.
        let installed = g.ensure_chunk_generated(IVec3::ZERO);
        assert!(installed, "manual install of one chunk");
        assert_eq!(g.chunks.len(), 1);
        // Make sure (0, 1, 0), (0, 2, 0) are NOT present.
        assert!(g.chunk(IVec3::new(0, 1, 0)).is_none());
        assert!(g.chunk(IVec3::new(0, 2, 0)).is_none());

        let (_engine, mut pool, sky_color) = make_composed_pool(CHUNK_SIZE_XY);
        let mut fb = vec![sky_color; pixel_count(XRES, YRES)];
        let mut zb = vec![f32::INFINITY; pixel_count(XRES, YRES)];
        // Camera inside chunk (0, 0, 0); looking +y means the
        // floor of (0, 0, 0) gets rendered until the ray walks
        // off the chunk into implicit-air space at y=128. No
        // floor pixels past that distance.
        let camera = camera_at([64.0, 32.0, 200.0]);
        let settings = OpticastSettings::for_oracle_framebuffer(XRES, YRES);
        let _ = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        let floor_pixels = fb.iter().filter(|&&p| p == 0x80_22_aa_22).count();
        // Visible floor inside chunk (0,0,0); pending neighbours
        // contribute nothing. The number isn't pinned exactly —
        // it just needs to be non-zero (we have content) and
        // less than what a fully-streamed scene would produce.
        assert!(
            floor_pixels > 0,
            "should see at least some floor from the loaded chunk"
        );
        // Sanity: stream the missing chunks; verify the floor
        // pixel count goes up.
        scene.pump_streaming_sync(DVec3::new(64.0, 32.0, 200.0));
        assert!(scene.grid(id).unwrap().chunk_count() >= 2);
        fb.iter_mut().for_each(|p| *p = sky_color);
        zb.iter_mut().for_each(|z| *z = f32::INFINITY);
        let _ = render_scene_composed(
            &mut fb,
            &mut zb,
            XRES as usize,
            XRES,
            YRES,
            &mut pool,
            &mut scene,
            &camera,
            &settings,
            sky_color,
            None,
        );
        let floor_pixels_full = fb.iter().filter(|&&p| p == 0x80_22_aa_22).count();
        assert!(
            floor_pixels_full > floor_pixels,
            "fully-streamed scene should show more floor than partial: \
             partial={floor_pixels} full={floor_pixels_full}"
        );
    }
}