roxlap-formats 0.1.1

Voxlap on-disk format parsers (.vxl, .kv6, .kvx, .kfa).
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
//! Voxel-edit primitives: column z-range buffer manipulation.
//!
//! Ported from voxlap5.c's column-edit helpers. Each column is
//! represented during edit processing as a flat `[i32]` "z-range
//! buffer" (`b2` in voxlap C):
//!
//! ```text
//! [top0, bot0, top1, bot1, ..., top_sentinel, bot_sentinel]
//! ```
//!
//! Each `(top_k, bot_k)` pair represents a contiguous SOLID region
//! `[top_k, bot_k)`. Voxlap's z-axis grows downward (z=0 is sky), so
//! `top_k < bot_k` and `bot_k` is exclusive. The list is terminated
//! by a sentinel pair whose `bot` is `>= MAXZDIM`; air gaps live
//! between adjacent slabs (`bot_k..top_{k+1}`).
//!
//! The buffer is owned by the caller; both helpers run in place and
//! assume the caller sized `b2` with enough tail capacity to absorb
//! the worst-case growth (one extra slab pair per `delslab` split,
//! never more for `insslab` — it can only collapse). voxlap C sizes
//! these via `SCPITCH * 3` slots; the Rust port inherits the
//! contract.
//!
//! These helpers are CD.1 of the cave-demo plan. CD.2+ wraps them in
//! `scum2_line` / `scum2_finish` and on-disk slab encode / decode.

#![allow(dead_code)] // CD.1 lands the helpers; CD.2+ wires them up.

/// Voxlap's `MAXZDIM` (voxlap5.h:10). World z is one byte → at most
/// 256 voxels tall.
pub const MAXZDIM: i32 = 256;

/// Carve voxels in `[y0, y1)` to air on the column `b2`.
///
/// Port of `delslab` (voxlap5.c:4231). `b2` is mutated in place.
///
/// - `y0 >= y1` is a no-op.
/// - `y1 >= MAXZDIM` is clamped to `MAXZDIM - 1` (matches C).
/// - `b2.is_empty()` returns early (matches the C null-pointer
///   guard).
///
/// In the worst case the carve splits a single solid slab in two,
/// growing the list by one pair. The caller is responsible for
/// sizing `b2` to absorb this. The helper does not allocate.
pub fn delslab(b2: &mut [i32], y0: i32, mut y1: i32) {
    if y1 >= MAXZDIM {
        y1 = MAXZDIM - 1;
    }
    if y0 >= y1 || b2.is_empty() {
        return;
    }
    let mut z = 0usize;
    while y0 >= b2[z + 1] {
        z += 2;
    }
    if y0 > b2[z] {
        if y1 < b2[z + 1] {
            // Carve sits strictly inside slab z: split it in two and
            // shift the rest of the list right by one pair to make
            // room.
            let mut i = z;
            while b2[i + 1] < MAXZDIM {
                i += 2;
            }
            while i > z {
                b2[i + 3] = b2[i + 1];
                b2[i + 2] = b2[i];
                i -= 2;
            }
            b2[z + 3] = b2[z + 1];
            b2[z + 1] = y0;
            b2[z + 2] = y1;
            return;
        }
        // y1 reaches into (or past) the bottom of slab z: shrink slab
        // z's bot to y0, then move on to handle slabs below.
        b2[z + 1] = y0;
        z += 2;
    }
    if y1 >= b2[z + 1] {
        // y1 spans through slab z (and possibly further). Find the
        // slab i that y1 lands in (above its bottom), adopt it as
        // the new slab z, and shift the tail back to close the gap.
        let mut i = z + 2;
        while y1 >= b2[i + 1] {
            i += 2;
        }
        let delta = i - z;
        b2[z] = b2[i];
        b2[z + 1] = b2[i + 1];
        while b2[i + 1] < MAXZDIM {
            i += 2;
            b2[i - delta] = b2[i];
            b2[i - delta + 1] = b2[i + 1];
        }
    }
    if y1 > b2[z] {
        // y1 falls inside slab z: clamp top.
        b2[z] = y1;
    }
}

/// Insert solid voxels in `[y0, y1)` on the column `b2`.
///
/// Port of `insslab` (voxlap5.c:4259). Mirrors the shape of
/// [`delslab`]: walks `b2` to find where `[y0, y1)` lands and either
/// inserts a fresh slab into an air gap or merges with adjacent
/// slabs.
///
/// - `y0 >= y1` is a no-op.
/// - `b2.is_empty()` returns early (matches the C null-pointer
///   guard).
/// - Unlike `delslab`, `insslab` does **not** clamp `y1` against
///   `MAXZDIM`; voxlap relies on the caller for that. A `y1` value
///   `>= MAXZDIM` collapses the column into a single solid slab
///   that acts as the sentinel.
pub fn insslab(b2: &mut [i32], y0: i32, y1: i32) {
    if y0 >= y1 || b2.is_empty() {
        return;
    }
    let mut z = 0usize;
    while y0 > b2[z + 1] {
        z += 2;
    }
    if y1 < b2[z] {
        // [y0, y1) lives entirely in the air gap above slab z.
        // Shift slabs [z..=last] right by one pair, then drop the
        // new slab into slot z.
        let mut i = z;
        while b2[i + 1] < MAXZDIM {
            i += 2;
        }
        loop {
            b2[i + 3] = b2[i + 1];
            b2[i + 2] = b2[i];
            if i == z {
                break;
            }
            i -= 2;
        }
        b2[z + 1] = y1;
        b2[z] = y0;
        return;
    }
    if y0 < b2[z] {
        // [y0, y1) overlaps the top of slab z: extend the top up.
        b2[z] = y0;
    }
    if y1 >= b2[z + 2] && b2[z + 1] < MAXZDIM {
        // The insert reaches into slab z+2 (or further); merge slabs
        // z..i into a single slab, where i is the last slab whose
        // top is at or below y1.
        let mut i = z + 2;
        while y1 >= b2[i + 2] && b2[i + 1] < MAXZDIM {
            i += 2;
        }
        let delta = i - z;
        b2[z + 1] = b2[i + 1];
        while b2[i + 1] < MAXZDIM {
            i += 2;
            b2[i - delta] = b2[i];
            b2[i - delta + 1] = b2[i + 1];
        }
    }
    if y1 > b2[z + 1] {
        // y1 reaches past the bottom of slab z: extend the bot down.
        b2[z + 1] = y1;
    }
}

/// Decode a column's slab bytes into the `b2` z-range buffer.
///
/// Port of `expandrle` (voxlap5.c:4131). Walks the slab chain, writes
/// `[top0, bot0, top1, bot1, ..., MAXZDIM_sentinel]` into `uind`.
/// `uind` MUST be sized to hold every solid run plus the sentinel pair
/// — voxlap allocates `MAXZDIM` slots, which is the worst-case bound
/// (one slab per z value).
///
/// The `if (v[3] >= v[1]) continue` branch handles a degenerate slab
/// where ceiling-z is at or below floor-z (no air gap above this
/// slab); voxlap merges it implicitly into the previous solid run by
/// skipping the slab in `uind`.
pub fn expandrle(slab: &[u8], uind: &mut [i32]) {
    uind[0] = i32::from(slab[1]);
    let mut i = 2usize;
    let mut v = 0usize;
    while slab[v] != 0 {
        v += usize::from(slab[v]) * 4;
        if slab[v + 3] >= slab[v + 1] {
            continue;
        }
        uind[i - 1] = i32::from(slab[v + 3]);
        uind[i] = i32::from(slab[v + 1]);
        i += 2;
    }
    uind[i - 1] = MAXZDIM;
}

/// One color-lookup record: original column's color for `z` in
/// `[z_start, z_end)`. Built from a column's slab bytes by
/// [`build_color_table`].
#[derive(Debug)]
struct ColorRange<'s> {
    z_start: i32,
    z_end: i32,
    /// Colors for `[z_start, z_end)`, BGRA, 4 bytes per voxel,
    /// ordered by `z`. Length `(z_end - z_start) * 4`.
    colors: &'s [u8],
}

/// Build the `tbuf2` color-lookup table for a column. Voxlap's
/// initial loop in `compilerle` (voxlap5.c:4163-4174). For each slab
/// emits a floor-color range and (for non-first slabs) a ceiling-
/// color range. Sentinel-terminated by a record at `z_start = MAXZDIM`.
fn build_color_table(slab: &[u8]) -> Vec<ColorRange<'_>> {
    let mut ranges = Vec::new();
    let mut v = 0usize;
    loop {
        let z_start = i32::from(slab[v + 1]);
        let z1c = i32::from(slab[v + 2]);
        let z_end = z1c + 1;
        let n_voxels = usize::try_from((z_end - z_start).max(0)).expect("voxel count >= 0");
        let off = v + 4;
        ranges.push(ColorRange {
            z_start,
            z_end,
            colors: &slab[off..off + n_voxels * 4],
        });

        let nextptr = slab[v];
        if nextptr == 0 {
            break;
        }
        let prev_v = v;
        v += usize::from(nextptr) * 4;
        let ze = i32::from(slab[v + 3]);
        // Ceiling color list of new slab. Voxlap stores these in the
        // tail of the *previous* slab's bytes — between its floor
        // colors and the new slab's header.
        //
        // C: ic[0] = ze + p.z - ia - i + 2, ic[1] = ze, ic[2] = v - ze*4
        // where p.z = z1c_prev, ia = z1_prev, i = nextptr_prev.
        let prev_z1 = i32::from(slab[prev_v + 1]);
        let prev_z1c = i32::from(slab[prev_v + 2]);
        let prev_nextptr = i32::from(slab[prev_v]);
        let ceil_z_start = ze + prev_z1c - prev_z1 - prev_nextptr + 2;
        let ceil_z_end = ze;
        let ceil_n =
            usize::try_from((ceil_z_end - ceil_z_start).max(0)).expect("ceiling voxel count >= 0");
        // Colors live at slab[v - ceil_n*4 .. v].
        let ceil_start = v - ceil_n * 4;
        ranges.push(ColorRange {
            z_start: ceil_z_start,
            z_end: ceil_z_end,
            colors: &slab[ceil_start..v],
        });
    }
    ranges.push(ColorRange {
        z_start: MAXZDIM,
        z_end: MAXZDIM,
        colors: &[],
    });
    ranges
}

/// Re-encode a column's `b2` z-range buffer to slab bytes.
///
/// Port of `compilerle` (voxlap5.c:4154). Walks `n0` (this column's
/// b2) voxel-by-voxel, writing one BGRA color record per exposed
/// solid voxel into `cbuf`. Color values are pulled from the
/// `original_column`'s slab bytes (where present) or from
/// `colfunc(px, py, z)` for newly-exposed voxels created by edits.
///
/// `n1..n4` are the four neighbor columns' b2 buffers (left, right,
/// north, south, in voxlap's order); they drive the "exposed" flag
/// `ia` that decides whether each voxel needs a color record.
///
/// Returns the number of bytes written to `cbuf`. Voxlap sizes
/// `cbuf` to `MAXCSIZ = 1028` bytes — the caller must do the same.
///
/// # Panics
///
/// Panics if a `b2` z value (always in `0..=MAXZDIM`) doesn't fit in
/// `u8` — would indicate a malformed b2 buffer.
#[allow(
    clippy::too_many_arguments,
    clippy::too_many_lines,
    clippy::missing_panics_doc
)]
pub(crate) fn compilerle(
    n0: &[i32],
    n1: &[i32],
    n2: &[i32],
    n3: &[i32],
    n4: &[i32],
    cbuf: &mut [u8],
    original_column: &[u8],
    px: i32,
    py: i32,
    colfunc: &mut dyn FnMut(i32, i32, i32) -> i32,
) -> usize {
    let tbuf2 = build_color_table(original_column);

    let mut p_z: i32 = n0[0];
    // Voxlap's char narrowing semantics: cbuf is byte-addressed, and
    // `cbuf[n+1] = n0[i]` in C truncates to the low 8 bits. The
    // sentinel run at the tail of `n0` carries MAXZDIM (=256) which
    // wraps to 0 — voxlap uses that as part of the terminator slab.
    #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
    let to_u8 = |v: i32| (v & 0xff) as u8;

    cbuf[1] = to_u8(p_z);
    let mut ze: i32 = n0[1];
    cbuf[2] = to_u8(ze - 1);
    cbuf[3] = 0;

    let mut i = 0usize;
    let mut onext = 0usize;
    let mut ic = 0usize;
    let mut ia: i32 = 15;
    let mut n = 4usize;
    let mut zend = if ze == MAXZDIM { -1 } else { ze - 1 };

    let mut n1_idx = 0usize;
    let mut n2_idx = 0usize;
    let mut n3_idx = 0usize;
    let mut n4_idx = 0usize;

    'outer: loop {
        let mut dacnt = 0;
        'middle: loop {
            // do { write voxel; ... } while (ia || p_z == zend)
            let exit_to_rlendit2 = loop {
                while p_z >= tbuf2[ic].z_end {
                    ic += 1;
                }
                let color: i32 = if p_z >= tbuf2[ic].z_start {
                    let off =
                        usize::try_from((p_z - tbuf2[ic].z_start) * 4).expect("color offset >= 0");
                    let bytes = &tbuf2[ic].colors[off..off + 4];
                    i32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
                } else {
                    colfunc(px, py, p_z)
                };
                cbuf[n..n + 4].copy_from_slice(&color.to_le_bytes());
                n += 4;
                p_z += 1;
                if p_z >= ze {
                    break true; // goto rlendit2
                }
                while p_z >= n1[n1_idx] {
                    n1_idx += 1;
                    ia ^= 1;
                }
                while p_z >= n2[n2_idx] {
                    n2_idx += 1;
                    ia ^= 2;
                }
                while p_z >= n3[n3_idx] {
                    n3_idx += 1;
                    ia ^= 4;
                }
                while p_z >= n4[n4_idx] {
                    n4_idx += 1;
                    ia ^= 8;
                }
                if !(ia != 0 || p_z == zend) {
                    break false; // exit do-while: buried voxel
                }
            };

            if exit_to_rlendit2 {
                if ze >= MAXZDIM {
                    break 'outer;
                }
                i += 2;
                cbuf[onext] = u8::try_from((n - onext) >> 2).expect("slab dword count fits in u8");
                onext = n;
                p_z = n0[i];
                cbuf[n + 1] = to_u8(p_z);
                cbuf[n + 3] = to_u8(ze);
                ze = n0[i + 1];
                cbuf[n + 2] = to_u8(ze - 1);
                n += 4;
                zend = if ze == MAXZDIM { -1 } else { ze - 1 };
                break 'middle; // restart 'outer with dacnt = 0
            }

            // Buried voxel: close the floor list (or open a sub-slab
            // for the next exposed run).
            if dacnt == 0 {
                cbuf[onext + 2] = to_u8(p_z - 1);
                dacnt = 1;
            } else {
                cbuf[onext] = u8::try_from((n - onext) >> 2).expect("slab dword count fits in u8");
                onext = n;
                cbuf[n + 1] = to_u8(p_z);
                cbuf[n + 2] = to_u8(p_z - 1);
                cbuf[n + 3] = to_u8(p_z);
                n += 4;
            }

            // Skip forward to the smallest neighbor breakpoint.
            let n1_v = n1[n1_idx];
            let n2_v = n2[n2_idx];
            let n3_v = n3[n3_idx];
            let n4_v = n4[n4_idx];
            if n1_v < n2_v && n1_v < n3_v && n1_v < n4_v {
                if n1_v >= ze {
                    p_z = ze - 1;
                } else {
                    p_z = n1_v;
                    n1_idx += 1;
                    ia ^= 1;
                }
            } else if n2_v < n3_v && n2_v < n4_v {
                if n2_v >= ze {
                    p_z = ze - 1;
                } else {
                    p_z = n2_v;
                    n2_idx += 1;
                    ia ^= 2;
                }
            } else if n3_v < n4_v {
                if n3_v >= ze {
                    p_z = ze - 1;
                } else {
                    p_z = n3_v;
                    n3_idx += 1;
                    ia ^= 4;
                }
            } else if n4_v >= ze {
                p_z = ze - 1;
            } else {
                p_z = n4_v;
                n4_idx += 1;
                ia ^= 8;
            }

            if p_z == MAXZDIM - 1 {
                break 'outer;
            }
            // continue 'middle: re-enter inner do-while with same dacnt
        }
    }

    cbuf[onext] = 0;
    n
}

// ====================================================================
// ScumCtx: scum2_line + scum2_finish + scum2 dispatcher (CD.2.5)
// ====================================================================
//
// Voxlap5.c:4431/4544/4507. The column-edit batch context.
//
// Acquires a `&mut Vxl` for the duration of an edit batch, manages
// the rolling 3-row b2 buffer cache (`radar`), and re-encodes each
// finished y-row through `compilerle` + `voxalloc`/`voxdealloc` /
// `column_offset` updates.
//
// User flow (matching voxlap's setspans / setsphere / setcube):
//
// ```ignore
// vxl.reserve_edit_capacity(headroom);
// let mut ctx = ScumCtx::new(&mut vxl);
// ctx.set_colfunc(|x, y, z| 0xff_8080_80);
// for span in spans {
//     let b2 = ctx.scum2(span.x, span.y).unwrap();
//     insslab(b2, span.z0, span.z1);
// }
// ctx.finish();
// ```
//
// Edits are accumulated per-column, then flushed when the y row
// advances (so the 3-row neighborhood is stable). `finish` drains
// the last 2 rows.

use crate::vxl::Vxl;

/// Voxlap's `SCPITCH` (`voxlap5.c:202`) — per-column-per-row stride
/// (in i32 units) inside the radar buffer. b2 buffer for column X
/// in a row whose base offset in radar is R lives at
/// `radar[R + X * SCPITCH * 3 .. R + X * SCPITCH * 3 + SCPITCH]`.
pub(crate) const SCPITCH: usize = 256;

/// Voxlap's `MAXCSIZ` (`voxlap5.c:93`). Maximum bytes a single
/// column can occupy after re-encoding through [`compilerle`].
pub(crate) const MAXCSIZ: usize = 1028;

/// Sentinel "no row started yet". Voxlap encodes this as
/// `0x80000000` = `i32::MIN`.
const SCOY_NONE: i32 = i32::MIN;

/// Initial radar offset for `scoym3`. Voxlap's `&radar[SCPITCH*6]`.
const SCOYM3_INITIAL: usize = SCPITCH * 6;

/// When `scoym3` reaches this offset, wrap back to
/// `SCOYM3_INITIAL`. Voxlap's `&radar[SCPITCH*9]` test.
const SCOYM3_WRAP: usize = SCPITCH * 9;

/// Column-edit batch context. Construct via [`ScumCtx::new`] after
/// calling [`Vxl::reserve_edit_capacity`] on the world.
///
/// Holds a `&mut Vxl` borrow plus the rolling 3-row b2 buffer cache.
/// Mutate columns via [`ScumCtx::scum2`] — it returns the b2 buffer
/// for the requested column; mutate via [`delslab`] / [`insslab`].
/// Edits are committed when the y row advances (or when
/// [`ScumCtx::finish`] drains the last 2 rows).
///
/// Caller MUST invoke [`ScumCtx::finish`] explicitly. Drop without
/// finish leaks the trailing 2 rows of edits — voxlap's contract.
pub struct ScumCtx<'v> {
    vxl: &'v mut Vxl,
    /// Rolling b2 buffer cache. Sized `(vsid + 4) * 3 * SCPITCH` ints.
    radar: Vec<i32>,
    /// `compilerle` output scratch (= voxlap's `tbuf`).
    cbuf: Vec<u8>,
    /// Color callback (= voxlap's `vx5.colfunc`). Called by
    /// `compilerle` for each newly-exposed voxel.
    colfunc: Box<dyn FnMut(i32, i32, i32) -> i32 + 'v>,

    // ---- rolling state (matches voxlap5.c globals) ------------------
    scoy: i32,
    scoym3: usize,
    scx0: i32,
    scx1: i32,
    scox0: i32,
    scox1: i32,
    scoox0: i32,
    scoox1: i32,
    scex0: i32,
    scex1: i32,
    sceox0: i32,
    sceox1: i32,

    /// `(x, y)` of the most-recent successful [`ScumCtx::scum2`] call,
    /// or `None` if no column has been loaded since the last row
    /// advance / context creation. Used by [`ScumCtx::with_column`]
    /// to skip the redundant `expandrle` when successive edits hit
    /// the same column — voxlap's `setspans` correctness contract:
    /// re-loading from `sptr` would wipe pending in-radar edits.
    last_scum2: Option<(i32, i32)>,
}

#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss,
    clippy::if_not_else,
    clippy::similar_names
)]
impl<'v> ScumCtx<'v> {
    /// Open a new column-edit batch on a Vxl. The Vxl MUST have been
    /// upgraded with [`Vxl::reserve_edit_capacity`] beforehand (the
    /// slab allocator must be initialised).
    ///
    /// # Panics
    ///
    /// Panics if `vxl.vbit` is empty (no edit capacity reserved).
    pub fn new(vxl: &'v mut Vxl) -> Self {
        assert!(
            !vxl.vbit.is_empty(),
            "ScumCtx::new requires Vxl::reserve_edit_capacity to be called first"
        );
        let radar_size = (vxl.vsid as usize + 4) * 3 * SCPITCH;
        Self {
            vxl,
            radar: vec![0i32; radar_size],
            cbuf: vec![0u8; MAXCSIZ],
            colfunc: Box::new(|_, _, _| 0),
            scoy: SCOY_NONE,
            scoym3: SCOYM3_INITIAL,
            scx0: 0,
            scx1: 0,
            scox0: 0,
            scox1: 0,
            scoox0: 0,
            scoox1: 0,
            scex0: 0,
            scex1: 0,
            sceox0: 0,
            sceox1: 0,
            last_scum2: None,
        }
    }

    /// Install the color callback. Voxlap's `vx5.colfunc`. Called
    /// for each newly-exposed voxel produced by edits.
    pub fn set_colfunc<F>(&mut self, f: F)
    where
        F: FnMut(i32, i32, i32) -> i32 + 'v,
    {
        self.colfunc = Box::new(f);
    }

    /// Open column `(x, y)` for editing; returns its b2 buffer.
    /// Caller mutates via [`delslab`] / [`insslab`].
    ///
    /// Auto-flushes any prior y row that's no longer in the rolling
    /// window. Returns `None` if `(x, y)` is out of world bounds.
    pub fn scum2(&mut self, x: i32, y: i32) -> Option<&mut [i32]> {
        let vsid = self.vxl.vsid as i32;
        if x < 0 || x >= vsid || y < 0 || y >= vsid {
            return None;
        }

        if y != self.scoy {
            if self.scoy != SCOY_NONE {
                self.scum2_line();
                while self.scoy < y - 1 {
                    self.scx0 = i32::MAX;
                    self.scx1 = i32::MIN;
                    self.advance_row();
                    self.scum2_line();
                }
                self.advance_row();
            } else {
                self.scoox0 = i32::MAX;
                self.scox0 = i32::MAX;
                self.sceox0 = x + 1;
                self.scex0 = x + 1;
                self.sceox1 = x;
                self.scex1 = x;
                self.scoy = y;
                self.scoym3 = SCOYM3_INITIAL;
            }
            self.scx0 = x;
        } else {
            // Same y row as previous call: fill any skipped columns
            // between scx1 and x so the 3-row window stays continuous.
            while self.scx1 < x - 1 {
                self.scx1 += 1;
                let scx1 = self.scx1;
                self.expand_column_into_row(scx1, y, self.scoym3);
            }
        }

        let radar_idx = self.scoym3 + (x as usize) * SCPITCH * 3;
        self.scx1 = x;
        self.expand_column_into_row(x, y, self.scoym3);
        self.last_scum2 = Some((x, y));
        Some(&mut self.radar[radar_idx..radar_idx + SCPITCH])
    }

    /// Edit one column with closure-based access. If `(x, y)` matches
    /// the immediately-previous successful [`ScumCtx::scum2`] /
    /// `with_column` call, reuses the cached b2 buffer in radar
    /// (skipping the redundant `expandrle` that would wipe pending
    /// edits). Otherwise calls `scum2` to load the column.
    ///
    /// This is the primary edit API for span-style batch operations
    /// where multiple z ranges land on the same column —
    /// [`set_spans`] is a thin wrapper. Returns `false` and skips
    /// the closure if `(x, y)` is out of world bounds.
    pub fn with_column<F>(&mut self, x: i32, y: i32, f: F) -> bool
    where
        F: FnOnce(&mut [i32]),
    {
        if self.last_scum2 != Some((x, y)) && self.scum2(x, y).is_none() {
            return false;
        }
        // At this point either the cache hit or scum2 succeeded —
        // both leave the column's b2 at scoym3 + x * SCPITCH * 3.
        let radar_idx = self.scoym3 + (x as usize) * SCPITCH * 3;
        let b2 = &mut self.radar[radar_idx..radar_idx + SCPITCH];
        f(b2);
        true
    }

    /// Drain the last 2 rows and consume the context. MUST be called
    /// — Drop does not auto-finish (voxlap contract).
    pub fn finish(mut self) {
        if self.scoy == SCOY_NONE {
            return;
        }
        for _ in 0..2 {
            self.scum2_line();
            self.scx0 = i32::MAX;
            self.scx1 = i32::MIN;
            self.advance_row();
        }
        self.scum2_line();
        self.scoy = SCOY_NONE;
    }

    /// Bump scoy by 1 and advance scoym3 in the radar ring.
    /// Invalidates the [`ScumCtx::with_column`] cache: the prior
    /// row's column slots are still in the radar but their relative
    /// offset to the new `scoym3` has shifted, so re-using the
    /// cached `(x, y)` would index the wrong slot.
    fn advance_row(&mut self) {
        self.scoy += 1;
        self.scoym3 += SCPITCH;
        if self.scoym3 == SCOYM3_WRAP {
            self.scoym3 = SCOYM3_INITIAL;
        }
        self.last_scum2 = None;
    }

    /// Load column `(x, y)` from the slab pool into the radar slot
    /// at `row_base + x * SCPITCH * 3`. Out-of-world columns get the
    /// all-solid sentinel `[0, MAXZDIM]` (matches voxlap's expandrle
    /// out-of-bounds behaviour).
    fn expand_column_into_row(&mut self, x: i32, y: i32, row_base: usize) {
        let vsid = self.vxl.vsid as i32;
        // Radar offset; voxlap relies on the prefix slack for x = -1.
        let radar_idx_signed = (row_base as isize) + (x as isize) * (SCPITCH as isize) * 3;
        if radar_idx_signed < 0 {
            return;
        }
        #[allow(clippy::cast_sign_loss)]
        let radar_idx = radar_idx_signed as usize;
        if radar_idx + SCPITCH > self.radar.len() {
            return;
        }
        if x < 0 || x >= vsid || y < 0 || y >= vsid {
            self.radar[radar_idx] = 0;
            self.radar[radar_idx + 1] = MAXZDIM;
            return;
        }
        let idx = (y as usize) * (vsid as usize) + (x as usize);
        let slab = self.vxl.column_data(idx);
        expandrle(slab, &mut self.radar[radar_idx..radar_idx + SCPITCH]);
    }

    /// Flush row `scoy - 1` (the middle of the rolling 3-row window).
    /// Voxlap5.c:4431.
    #[allow(clippy::too_many_lines)]
    fn scum2_line(&mut self) {
        let vsid = self.vxl.vsid as i32;

        // x0 = min(scox0-1, min(scx0, scoox0)); x1 = max(scox1+1, max(scx1, scoox1))
        let x0 = (self.scox0 - 1).min(self.scx0).min(self.scoox0);
        self.scoox0 = self.scox0;
        self.scox0 = self.scx0;
        let x1 = (self.scox1 + 1).max(self.scx1).max(self.scoox1);
        self.scoox1 = self.scox1;
        self.scox1 = self.scx1;

        let uptr = wrap_radar(self.scoym3 + SCPITCH);
        let mptr = wrap_radar(uptr + SCPITCH);

        // Load row scoy-2 (uptr) for [x0, x1] minus [sceox0, sceox1].
        let scoy_2 = self.scoy - 2;
        if x1 < self.sceox0 || x0 > self.sceox1 {
            for x in x0..=x1 {
                self.expand_column_into_row(x, scoy_2, uptr);
            }
        } else {
            for x in x0..self.sceox0 {
                self.expand_column_into_row(x, scoy_2, uptr);
            }
            let mut x = x1;
            while x > self.sceox1 {
                self.expand_column_into_row(x, scoy_2, uptr);
                x -= 1;
            }
        }

        // Load row scoy-1 (mptr) for [x0-1, x1+1].
        let scoy_1 = self.scoy - 1;
        if (self.scex1 | x1) >= 0 {
            for x in (x1 + 2)..self.scex0 {
                self.expand_column_into_row(x, scoy_1, mptr);
            }
            let mut x = x0 - 2;
            while x > self.scex1 {
                self.expand_column_into_row(x, scoy_1, mptr);
                x -= 1;
            }
        }
        if x1 + 1 < self.scex0 || x0 - 1 > self.scex1 {
            for x in (x0 - 1)..=(x1 + 1) {
                self.expand_column_into_row(x, scoy_1, mptr);
            }
        } else {
            for x in (x0 - 1)..self.scex0 {
                self.expand_column_into_row(x, scoy_1, mptr);
            }
            let mut x = x1 + 1;
            while x > self.scex1 {
                self.expand_column_into_row(x, scoy_1, mptr);
                x -= 1;
            }
        }
        self.sceox0 = (x0 - 1).min(self.scex0);
        self.sceox1 = (x1 + 1).max(self.scex1);

        // Load row scoy (scoym3) for [x0, x1] minus [scx0, scx1].
        let scoy_0 = self.scoy;
        let scoym3 = self.scoym3;
        if x1 < self.scx0 || x0 > self.scx1 {
            for x in x0..=x1 {
                self.expand_column_into_row(x, scoy_0, scoym3);
            }
        } else {
            for x in x0..self.scx0 {
                self.expand_column_into_row(x, scoy_0, scoym3);
            }
            let mut x = x1;
            while x > self.scx1 {
                self.expand_column_into_row(x, scoy_0, scoym3);
                x -= 1;
            }
        }
        self.scex0 = x0;
        self.scex1 = x1;

        // Flush row scoy-1: re-encode each column in [x0, x1] within
        // [0, vsid).
        let y = self.scoy - 1;
        if !(0..vsid).contains(&y) {
            return;
        }
        let x0_clamped = x0.max(0);
        let x1_clamped = x1.min(vsid - 1);

        for x in x0_clamped..=x1_clamped {
            self.flush_column(x, y, mptr, uptr, scoym3);
        }
    }

    /// Re-encode column (x, y) using its b2 buffer in `mptr` and
    /// neighbor b2s in mptr (left/right) + uptr (above) + scoym3
    /// (below). Commits the new bytes to the slab pool.
    #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
    fn flush_column(&mut self, x: i32, y: i32, mptr: usize, uptr: usize, scoym3: usize) {
        let vsid = self.vxl.vsid as usize;
        let k = (x as usize) * SCPITCH * 3;
        let n0_pos = mptr + k;
        let n1_pos_signed = (mptr as isize) + (k as isize) - (SCPITCH as isize) * 3;
        let n2_pos = mptr + k + SCPITCH * 3;
        let n3_pos = uptr + k;
        let n4_pos = scoym3 + k;

        // n1_pos may be at a negative offset for x = 0; voxlap relies
        // on radar prefix slack. Skip if the slot is outside our radar.
        if n1_pos_signed < 0 {
            return;
        }
        let n1_pos = n1_pos_signed as usize;

        let idx = (y as usize) * vsid + (x as usize);

        // Snapshot original column bytes — compilerle reads colors
        // from them, and we overwrite them later via voxalloc + copy.
        let original_bytes: Vec<u8> = self.vxl.column_data(idx).to_vec();

        let written = {
            let radar = &self.radar;
            let n0 = &radar[n0_pos..n0_pos + SCPITCH];
            let n1 = &radar[n1_pos..n1_pos + SCPITCH];
            let n2 = &radar[n2_pos..n2_pos + SCPITCH];
            let n3 = &radar[n3_pos..n3_pos + SCPITCH];
            let n4 = &radar[n4_pos..n4_pos + SCPITCH];
            compilerle(
                n0,
                n1,
                n2,
                n3,
                n4,
                &mut self.cbuf,
                &original_bytes,
                x,
                y,
                &mut *self.colfunc,
            )
        };

        let old_offset = self.vxl.column_offset[idx];
        self.vxl.voxdealloc(old_offset);
        let new_offset = self.vxl.voxalloc(written as u32);
        self.vxl.data[new_offset as usize..new_offset as usize + written]
            .copy_from_slice(&self.cbuf[..written]);
        self.vxl.column_offset[idx] = new_offset;
    }
}

/// Wrap a radar offset back into the rolling-window range
/// `[SCOYM3_INITIAL, SCOYM3_WRAP)`.
fn wrap_radar(off: usize) -> usize {
    if off == SCOYM3_WRAP {
        SCOYM3_INITIAL
    } else {
        off
    }
}

// ====================================================================
// set_spans (CD.3) — thin wrapper over ScumCtx + delslab/insslab.
// ====================================================================

/// One vertical span on a column: `(x, y, z0..=z1)` solid voxels.
///
/// `z1` is INCLUSIVE per voxlap's `vspans` convention — the actual
/// edited range is the half-open `[z0, z1 + 1)`. Same convention
/// makes a `Vspan { z0: 100, z1: 100 }` carve / fill exactly one
/// voxel at z=100.
///
/// `x` / `y` are full-world `u32` coordinates (cleaner than voxlap's
/// 8-bit `vspans.x` + `setspans` `offs` trick — for our cave demo
/// the patch-relative + offset machinery isn't needed).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Vspan {
    pub x: u32,
    pub y: u32,
    pub z0: u8,
    pub z1: u8,
}

/// Operation for span-style edits.
///
/// `Carve` flips the listed voxels to air (per-span [`delslab`]) —
/// the colfunc is consulted by the internal RLE re-compile step for
/// newly-exposed voxels just outside the carved range (above and
/// below) which weren't previously in the column's color list.
///
/// `Insert` flips the listed voxels to solid (per-span [`insslab`])
/// — the colfunc is consulted for the inserted voxels themselves.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpanOp {
    Carve,
    Insert,
}

/// Apply a list of column-aligned vertical spans with a custom color
/// callback. Voxlap5.c:5247 `setspans` ported with full `vx5.colfunc`
/// flexibility — the closure can capture arbitrary state to implement
/// voxlap's `curcolfunc` / `jitcolfunc` / `pngcolfunc` / `dust` /
/// procedural colour patterns.
///
/// `colfunc(x, y, z) -> i32` returns the BGRA colour for any voxel
/// that needs one: the inserted voxels (Insert op) or the newly-
/// exposed voxels just outside the carved range (Carve op).
///
/// **Contract**: `spans` MUST be sorted ascending by `(y, x)` and,
/// within each `(x, y)` group, ascending by `z0`. Voxlap relies on
/// this for correct row-flush ordering and for `with_column`'s
/// caching invariant. Out-of-bounds spans (x or y >= vsid) are
/// silently skipped.
///
/// Empty input is a no-op (no `ScumCtx` is created).
///
/// # Panics
///
/// Panics if `world.vbit` is empty — call
/// [`Vxl::reserve_edit_capacity`] first.
#[allow(clippy::cast_possible_wrap)]
pub fn set_spans_with_colfunc<F>(world: &mut Vxl, spans: &[Vspan], op: SpanOp, colfunc: F)
where
    F: FnMut(i32, i32, i32) -> i32,
{
    if spans.is_empty() {
        return;
    }
    let inserting = op == SpanOp::Insert;
    let mut ctx = ScumCtx::new(world);
    ctx.set_colfunc(colfunc);
    for span in spans {
        let x = span.x as i32;
        let y = span.y as i32;
        let z0 = i32::from(span.z0);
        let z1 = i32::from(span.z1) + 1; // inclusive → half-open exclusive
        ctx.with_column(x, y, |b2| {
            if inserting {
                insslab(b2, z0, z1);
            } else {
                delslab(b2, z0, z1);
            }
        });
    }
    ctx.finish();
}

/// Apply a list of column-aligned vertical spans with a constant
/// colour. Convenience wrapper over [`set_spans_with_colfunc`] for
/// the common cases:
///
/// - `color = None` → carve. Newly-exposed voxels get colour 0.
/// - `color = Some(c)` → insert. Inserted voxels get colour `c`.
///
/// For non-constant colours (jitter, texture-mapped, position-
/// dependent, gradient by depth), use [`set_spans_with_colfunc`]
/// directly with a closure capturing the relevant state.
///
/// See [`set_spans_with_colfunc`] for the sort-order contract and
/// panic semantics.
pub fn set_spans(world: &mut Vxl, spans: &[Vspan], color: Option<u32>) {
    let op = if color.is_some() {
        SpanOp::Insert
    } else {
        SpanOp::Carve
    };
    #[allow(clippy::cast_possible_wrap)]
    let c_i32 = color.unwrap_or(0) as i32;
    set_spans_with_colfunc(world, spans, op, move |_, _, _| c_i32);
}

// ====================================================================
// set_cube / set_rect / set_sphere (CD.4) — region wrappers.
// ====================================================================

/// Edit a single voxel at `(x, y, z)`. Voxlap5.c:4669 `setcube`.
///
/// `color = None` carves to air; `Some(c)` inserts solid coloured
/// `c`. Out-of-bounds coordinates are silently skipped.
///
/// **Note**: This port skips voxlap C's "exposed-solid in-place
/// colour overwrite" optimization — every call goes through the
/// scum2 + delslab/insslab + compilerle pipeline. Per-voxel edits
/// are rare in the cave-demo workload; the optimization can land
/// later if needed.
///
/// # Panics
///
/// Panics if `world.vbit` is empty — call
/// [`Vxl::reserve_edit_capacity`] first.
pub fn set_cube(world: &mut Vxl, x: i32, y: i32, z: i32, color: Option<u32>) {
    let op = if color.is_some() {
        SpanOp::Insert
    } else {
        SpanOp::Carve
    };
    #[allow(clippy::cast_possible_wrap)]
    let c_i32 = color.unwrap_or(0) as i32;
    set_cube_with_colfunc(world, x, y, z, op, move |_, _, _| c_i32);
}

/// [`set_cube`] with a custom colour callback.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss
)]
pub fn set_cube_with_colfunc<F>(world: &mut Vxl, x: i32, y: i32, z: i32, op: SpanOp, colfunc: F)
where
    F: FnMut(i32, i32, i32) -> i32,
{
    let vsid = world.vsid as i32;
    if x < 0 || x >= vsid || y < 0 || y >= vsid || !(0..MAXZDIM).contains(&z) {
        return;
    }
    let span = Vspan {
        x: x as u32,
        y: y as u32,
        z0: z as u8,
        z1: z as u8,
    };
    set_spans_with_colfunc(world, &[span], op, colfunc);
}

/// Edit an axis-aligned box `[lo, hi]` (inclusive on both ends in
/// every axis). Voxlap5.c:5214 `setrect`.
///
/// `color = None` carves to air; `Some(c)` inserts solid coloured
/// `c`. The box is sorted and clamped to world bounds before
/// iteration; an empty box (any axis where lo > hi after clamp) is
/// a no-op.
///
/// # Panics
///
/// Panics if `world.vbit` is empty — call
/// [`Vxl::reserve_edit_capacity`] first.
pub fn set_rect(world: &mut Vxl, lo: [i32; 3], hi: [i32; 3], color: Option<u32>) {
    let op = if color.is_some() {
        SpanOp::Insert
    } else {
        SpanOp::Carve
    };
    #[allow(clippy::cast_possible_wrap)]
    let c_i32 = color.unwrap_or(0) as i32;
    set_rect_with_colfunc(world, lo, hi, op, move |_, _, _| c_i32);
}

/// [`set_rect`] with a custom colour callback.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss
)]
pub fn set_rect_with_colfunc<F>(world: &mut Vxl, lo: [i32; 3], hi: [i32; 3], op: SpanOp, colfunc: F)
where
    F: FnMut(i32, i32, i32) -> i32,
{
    let vsid = world.vsid as i32;
    let xs = lo[0].min(hi[0]).max(0);
    let xe = lo[0].max(hi[0]).min(vsid - 1);
    let ys = lo[1].min(hi[1]).max(0);
    let ye = lo[1].max(hi[1]).min(vsid - 1);
    let zs = lo[2].min(hi[2]).max(0);
    let ze = lo[2].max(hi[2]).min(MAXZDIM - 1);
    if xs > xe || ys > ye || zs > ze {
        return;
    }
    let inserting = op == SpanOp::Insert;
    let mut ctx = ScumCtx::new(world);
    ctx.set_colfunc(colfunc);
    for y in ys..=ye {
        for x in xs..=xe {
            ctx.with_column(x, y, |b2| {
                if inserting {
                    insslab(b2, zs, ze + 1);
                } else {
                    delslab(b2, zs, ze + 1);
                }
            });
        }
    }
    ctx.finish();
}

/// Edit a sphere of voxels centred at `center` with the given
/// `radius`. Voxlap5.c:4970 `setsphere`.
///
/// Uses Euclidean distance (voxlap's default `vx5.curpow = 2.0`
/// case). For voxlap-style non-Euclidean shapes (octahedron at
/// `curpow = 1.0`, etc.) the user can drop down to [`ScumCtx`] and
/// roll their own iteration; the cave-demo's spherical bullet
/// impacts only need the Euclidean case.
///
/// `color = None` carves to air; `Some(c)` inserts solid coloured
/// `c`. The bounding box is clamped to world bounds; a sphere fully
/// outside the world is a no-op.
///
/// # Panics
///
/// Panics if `world.vbit` is empty — call
/// [`Vxl::reserve_edit_capacity`] first.
pub fn set_sphere(world: &mut Vxl, center: [i32; 3], radius: u32, color: Option<u32>) {
    let op = if color.is_some() {
        SpanOp::Insert
    } else {
        SpanOp::Carve
    };
    #[allow(clippy::cast_possible_wrap)]
    let c_i32 = color.unwrap_or(0) as i32;
    set_sphere_with_colfunc(world, center, radius, op, move |_, _, _| c_i32);
}

/// [`set_sphere`] with a custom colour callback.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss,
    clippy::cast_precision_loss,
    clippy::similar_names
)]
pub fn set_sphere_with_colfunc<F>(
    world: &mut Vxl,
    center: [i32; 3],
    radius: u32,
    op: SpanOp,
    colfunc: F,
) where
    F: FnMut(i32, i32, i32) -> i32,
{
    let vsid = world.vsid as i32;
    let cx = center[0];
    let cy = center[1];
    let cz = center[2];
    let r = radius as i32;
    let xs = (cx - r).max(0);
    let xe = (cx + r).min(vsid - 1);
    let ys = (cy - r).max(0);
    let ye = (cy + r).min(vsid - 1);
    let zs = (cz - r).max(0);
    let ze = (cz + r).min(MAXZDIM - 1);
    if xs > xe || ys > ye || zs > ze {
        return;
    }
    let r_sq = r * r;
    let inserting = op == SpanOp::Insert;
    let mut ctx = ScumCtx::new(world);
    ctx.set_colfunc(colfunc);
    for y in ys..=ye {
        let dy = y - cy;
        let dy_sq = dy * dy;
        if dy_sq > r_sq {
            continue;
        }
        for x in xs..=xe {
            let dx = x - cx;
            let dx_sq = dx * dx;
            let xy_sq = dx_sq + dy_sq;
            if xy_sq > r_sq {
                continue;
            }
            // dz_max satisfies dx² + dy² + dz² <= r²; voxel range is
            // z = cz - dz_max ..= cz + dz_max.
            let dz_max_sq = r_sq - xy_sq;
            let dz_max = (dz_max_sq as f32).sqrt() as i32;
            let z_lo = (cz - dz_max).max(zs);
            let z_hi = (cz + dz_max).min(ze);
            if z_lo > z_hi {
                continue;
            }
            ctx.with_column(x, y, |b2| {
                if inserting {
                    insslab(b2, z_lo, z_hi + 1);
                } else {
                    delslab(b2, z_lo, z_hi + 1);
                }
            });
        }
    }
    ctx.finish();
}

#[cfg(test)]
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss,
    clippy::items_after_statements
)]
mod tests {
    use super::*;

    /// Build a sentinel-terminated `b2` from a list of solid slabs.
    /// The buffer has slack at the tail so split-style ops have room
    /// to shift.
    fn build_b2(slabs: &[(i32, i32)]) -> Vec<i32> {
        let mut buf: Vec<i32> = Vec::new();
        for &(top, bot) in slabs {
            assert!(top < bot, "slab top must be < bot");
            assert!(bot < MAXZDIM, "slab bot must fit below MAXZDIM");
            buf.push(top);
            buf.push(bot);
        }
        // Sentinel pair. voxlap's expandrle terminates with
        // bot = MAXZDIM; top is unread (writes only).
        buf.push(MAXZDIM);
        buf.push(MAXZDIM);
        // Slack — accommodates worst-case growth for any test.
        buf.resize(buf.len() + 32, 0);
        buf
    }

    /// Read back the slab list before the sentinel.
    fn read_slabs(b2: &[i32]) -> Vec<(i32, i32)> {
        let mut out = Vec::new();
        let mut i = 0;
        while b2[i + 1] < MAXZDIM {
            out.push((b2[i], b2[i + 1]));
            i += 2;
        }
        out
    }

    // ---- delslab ----------------------------------------------------

    #[test]
    fn delslab_noop_y0_ge_y1() {
        let mut b2 = build_b2(&[(10, 20)]);
        delslab(&mut b2, 15, 15);
        assert_eq!(read_slabs(&b2), [(10, 20)]);
        delslab(&mut b2, 20, 10);
        assert_eq!(read_slabs(&b2), [(10, 20)]);
    }

    #[test]
    fn delslab_split_inside_one_slab() {
        let mut b2 = build_b2(&[(10, 30)]);
        delslab(&mut b2, 15, 20);
        assert_eq!(read_slabs(&b2), [(10, 15), (20, 30)]);
    }

    #[test]
    fn delslab_shrink_bot_of_slab() {
        let mut b2 = build_b2(&[(10, 30)]);
        delslab(&mut b2, 20, 30);
        assert_eq!(read_slabs(&b2), [(10, 20)]);
    }

    #[test]
    fn delslab_shrink_top_of_slab() {
        let mut b2 = build_b2(&[(10, 30)]);
        delslab(&mut b2, 5, 15);
        assert_eq!(read_slabs(&b2), [(15, 30)]);
    }

    #[test]
    fn delslab_carve_full_slab() {
        let mut b2 = build_b2(&[(10, 30)]);
        delslab(&mut b2, 5, 35);
        assert_eq!(read_slabs(&b2), Vec::<(i32, i32)>::new());
    }

    #[test]
    fn delslab_in_air_noop() {
        let mut b2 = build_b2(&[(10, 30)]);
        delslab(&mut b2, 0, 8);
        assert_eq!(read_slabs(&b2), [(10, 30)]);
        delslab(&mut b2, 35, 50);
        assert_eq!(read_slabs(&b2), [(10, 30)]);
    }

    #[test]
    fn delslab_span_two_slabs_carve_middle() {
        let mut b2 = build_b2(&[(10, 30), (50, 70)]);
        delslab(&mut b2, 20, 60);
        assert_eq!(read_slabs(&b2), [(10, 20), (60, 70)]);
    }

    #[test]
    fn delslab_carve_two_full_slabs_keep_third() {
        let mut b2 = build_b2(&[(10, 20), (30, 40), (50, 60)]);
        delslab(&mut b2, 5, 45);
        assert_eq!(read_slabs(&b2), [(50, 60)]);
    }

    #[test]
    fn delslab_y1_clamped_to_maxzdim_minus_1() {
        let mut b2 = build_b2(&[(10, 200)]);
        delslab(&mut b2, 100, MAXZDIM);
        assert_eq!(read_slabs(&b2), [(10, 100)]);
    }

    #[test]
    fn delslab_carve_top_edge_of_slab() {
        // y1 == top of slab → should leave the slab untouched (the
        // carve range ends right at the surface).
        let mut b2 = build_b2(&[(10, 30)]);
        delslab(&mut b2, 5, 10);
        assert_eq!(read_slabs(&b2), [(10, 30)]);
    }

    #[test]
    fn delslab_carve_bot_edge_of_slab() {
        // y0 == bot of slab → no overlap.
        let mut b2 = build_b2(&[(10, 30)]);
        delslab(&mut b2, 30, 35);
        assert_eq!(read_slabs(&b2), [(10, 30)]);
    }

    #[test]
    fn delslab_carve_exact_full_slab_keeps_neighbors() {
        let mut b2 = build_b2(&[(10, 20), (30, 40), (50, 60)]);
        delslab(&mut b2, 30, 40);
        assert_eq!(read_slabs(&b2), [(10, 20), (50, 60)]);
    }

    // ---- insslab ----------------------------------------------------

    #[test]
    fn insslab_noop_y0_ge_y1() {
        let mut b2 = build_b2(&[(10, 20)]);
        insslab(&mut b2, 15, 15);
        assert_eq!(read_slabs(&b2), [(10, 20)]);
        insslab(&mut b2, 20, 10);
        assert_eq!(read_slabs(&b2), [(10, 20)]);
    }

    #[test]
    fn insslab_into_pure_air() {
        let mut b2 = build_b2(&[]);
        insslab(&mut b2, 10, 30);
        assert_eq!(read_slabs(&b2), [(10, 30)]);
    }

    #[test]
    fn insslab_into_air_gap_above_slab() {
        let mut b2 = build_b2(&[(50, 70)]);
        insslab(&mut b2, 10, 30);
        assert_eq!(read_slabs(&b2), [(10, 30), (50, 70)]);
    }

    #[test]
    fn insslab_into_air_gap_between_slabs() {
        let mut b2 = build_b2(&[(10, 20), (60, 70)]);
        insslab(&mut b2, 30, 50);
        assert_eq!(read_slabs(&b2), [(10, 20), (30, 50), (60, 70)]);
    }

    #[test]
    fn insslab_into_air_gap_below_all_slabs() {
        let mut b2 = build_b2(&[(10, 20)]);
        insslab(&mut b2, 30, 50);
        assert_eq!(read_slabs(&b2), [(10, 20), (30, 50)]);
    }

    #[test]
    fn insslab_extend_top_of_slab() {
        let mut b2 = build_b2(&[(50, 70)]);
        insslab(&mut b2, 30, 60);
        assert_eq!(read_slabs(&b2), [(30, 70)]);
    }

    #[test]
    fn insslab_extend_bot_of_slab() {
        let mut b2 = build_b2(&[(50, 70)]);
        insslab(&mut b2, 60, 80);
        assert_eq!(read_slabs(&b2), [(50, 80)]);
    }

    #[test]
    fn insslab_touch_top_merges() {
        // y1 == top of slab → adjacent insert merges (extends top).
        let mut b2 = build_b2(&[(50, 70)]);
        insslab(&mut b2, 30, 50);
        assert_eq!(read_slabs(&b2), [(30, 70)]);
    }

    #[test]
    fn insslab_touch_bot_merges() {
        // y0 == bot of slab → adjacent insert merges (extends bot).
        let mut b2 = build_b2(&[(50, 70)]);
        insslab(&mut b2, 70, 80);
        assert_eq!(read_slabs(&b2), [(50, 80)]);
    }

    #[test]
    fn insslab_merge_two_slabs() {
        let mut b2 = build_b2(&[(10, 30), (50, 70)]);
        insslab(&mut b2, 20, 60);
        assert_eq!(read_slabs(&b2), [(10, 70)]);
    }

    #[test]
    fn insslab_engulf_inner_slabs() {
        let mut b2 = build_b2(&[(10, 20), (30, 40), (50, 60)]);
        insslab(&mut b2, 5, 70);
        assert_eq!(read_slabs(&b2), [(5, 70)]);
    }

    #[test]
    fn insslab_engulf_then_keep_lower() {
        let mut b2 = build_b2(&[(10, 20), (30, 40), (60, 80)]);
        insslab(&mut b2, 5, 50);
        assert_eq!(read_slabs(&b2), [(5, 50), (60, 80)]);
    }

    #[test]
    fn insslab_engulf_then_merge_lower() {
        let mut b2 = build_b2(&[(10, 20), (30, 40), (60, 80)]);
        insslab(&mut b2, 5, 60);
        assert_eq!(read_slabs(&b2), [(5, 80)]);
    }

    #[test]
    fn insslab_chain_of_touching_inserts() {
        let mut b2 = build_b2(&[]);
        insslab(&mut b2, 10, 20);
        insslab(&mut b2, 20, 30);
        insslab(&mut b2, 30, 40);
        assert_eq!(read_slabs(&b2), [(10, 40)]);
    }

    #[test]
    fn insslab_carve_then_insert_round_trip() {
        // Land on slab, carve the middle, fill it back: end result
        // is identical to the original.
        let original = [(10, 50)];
        let mut b2 = build_b2(&original);
        delslab(&mut b2, 20, 30);
        assert_eq!(read_slabs(&b2), [(10, 20), (30, 50)]);
        insslab(&mut b2, 20, 30);
        assert_eq!(read_slabs(&b2), original);
    }

    #[test]
    fn insslab_into_sentinel_only_buffer_with_z_advance() {
        // Insert below an existing slab — z advances past slab[0].
        let mut b2 = build_b2(&[(10, 20)]);
        insslab(&mut b2, 100, 150);
        assert_eq!(read_slabs(&b2), [(10, 20), (100, 150)]);
    }

    // ---- expandrle (CD.2.3) ------------------------------------------

    /// Strip the `[top, bot, top, bot, ..., MAXZDIM]` decoded shape
    /// off a `b2` produced by [`expandrle`]. Last bot is the sentinel
    /// (== MAXZDIM); preceding pairs are the solid runs.
    fn read_uind(uind: &[i32]) -> Vec<(i32, i32)> {
        let mut out = Vec::new();
        let mut i = 0;
        while uind[i + 1] < MAXZDIM {
            out.push((uind[i], uind[i + 1]));
            i += 2;
        }
        // Last solid run terminated by sentinel.
        out.push((uind[i], uind[i + 1]));
        out
    }

    #[test]
    fn expandrle_single_slab_fully_solid_column() {
        // Voxlap encoding for solid [0, MAXZDIM) — the on-disk fixture
        // we see for "ground all the way down" columns.
        // [nextptr=0, z1=0, z1c=MAXZDIM-1, z0=0] + MAXZDIM × 4 colours.
        let z1c = u8::try_from(MAXZDIM - 1).expect("MAXZDIM-1 fits in u8");
        let mut slab = vec![0u8, 0, z1c, 0];
        slab.extend(std::iter::repeat_n(0u8, (MAXZDIM as usize) * 4));
        let mut uind = vec![0i32; 16];
        expandrle(&slab, &mut uind);
        // One solid run from z=0 to MAXZDIM, followed by sentinel.
        assert_eq!(uind[0], 0);
        assert_eq!(uind[1], MAXZDIM);
    }

    #[test]
    fn expandrle_single_slab_partial_floor() {
        // [nextptr=0, z1=64, z1c=66, z0=0] + 3 colours (don't matter).
        // Solid run = [64, MAXZDIM) — voxlap treats below-floor as
        // implicit solid.
        let slab = [0u8, 64, 66, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0];
        let mut uind = vec![0i32; 16];
        expandrle(&slab, &mut uind);
        assert_eq!(uind[0], 64);
        assert_eq!(uind[1], MAXZDIM);
    }

    #[test]
    fn expandrle_two_slabs_with_cave() {
        // Slab 0: nextptr=2 (advance 8 bytes), z1=10, z1c=12, z0=0.
        // Floor list: 3 colours = 12 bytes; total slab 0 = 4 + 12 - 4 = 12?
        // Actually slab 0 size = nextptr * 4 = 8 bytes. So with floor
        // list shorter than (z1c - z1 + 1) = 3 colours = 12 bytes, size
        // would be 16. To fit nextptr=2 (= 8 bytes), z1c-z1+1 must be 1
        // colour = 4 bytes (8 = 4 header + 4 colour).
        //
        // Layout: [2, 10, 10, 0, c0, c0, c0, c0, 0, 50, 52, 30, ...].
        // Slab 0: 1-voxel floor, then implicit solid [11, 30) (between
        // slab 0 floor end and slab 1 ceiling top).
        // Slab 1: ceiling [30, 50), floor [50, 53), implicit below.
        //
        // expandrle output:
        //   uind[0] = v[1]_s0 = 10
        //   advance to slab 1; v[3]=30 < v[1]=50 → write
        //   uind[1] = 30, uind[2] = 50, i = 4
        //   slab 1 nextptr=0 → exit loop
        //   uind[3] = MAXZDIM
        let slab = [
            2u8, 10, 10, 0, // slab 0 header
            0xaa, 0, 0, 0, // slab 0 1-voxel floor colour
            0, 50, 52, 30, // slab 1 (last) header
            0xbb, 0, 0, 0, // slab 1 floor 0
            0xcc, 0, 0, 0, // slab 1 floor 1
            0xdd, 0, 0, 0, // slab 1 floor 2
        ];
        let mut uind = vec![0i32; 16];
        expandrle(&slab, &mut uind);
        assert_eq!(uind[0], 10);
        assert_eq!(uind[1], 30);
        assert_eq!(uind[2], 50);
        assert_eq!(uind[3], MAXZDIM);
    }

    #[test]
    fn expandrle_skips_degenerate_slab_with_no_ceiling_gap() {
        // Slab 1 has v[3] >= v[1]: ceiling collapses with floor → no
        // air gap above. Voxlap's `continue` skips emitting a new
        // solid run for this slab, merging it with the previous run.
        //
        // Layout:
        //   slab 0: nextptr=2, z1=10, z1c=10, z0=0, 1 floor colour
        //   slab 1: nextptr=0, z1=20, z1c=22, z0=20 (z0 == z1 → skip)
        let slab = [
            2u8, 10, 10, 0, // slab 0 header
            0xaa, 0, 0, 0, // 1 floor colour
            0, 20, 22, 20, // slab 1 (degenerate: z0=z1=20)
            0xbb, 0, 0, 0, 0xcc, 0, 0, 0, 0xdd, 0, 0, 0, // floor colours
        ];
        let mut uind = vec![0i32; 16];
        expandrle(&slab, &mut uind);
        // Only one solid run (slab 0's), since slab 1 was skipped.
        assert_eq!(uind[0], 10);
        assert_eq!(uind[1], MAXZDIM);
    }

    #[test]
    fn expandrle_round_trips_through_b2_helpers() {
        // Decode a 2-slab column, then verify delslab can carve a
        // hole into the air gap (the `read_uind` shape matches the b2
        // shape that delslab/insslab consume).
        let slab = [
            2u8, 10, 10, 0, 0xaa, 0, 0, 0, 0, 50, 52, 30, 0xbb, 0, 0, 0, 0xcc, 0, 0, 0, 0xdd, 0, 0,
            0,
        ];
        let mut uind = vec![0i32; 16];
        expandrle(&slab, &mut uind);
        let runs = read_uind(&uind[..4]);
        assert_eq!(runs, [(10, 30), (50, MAXZDIM)]);
    }

    // ---- build_color_table + compilerle (CD.2.4) ----------------------

    /// Build a sentinel-terminated all-air b2 buffer for a neighbor.
    /// Sized with slack so compilerle's index walks don't run off
    /// the end (worst case = n0's voxel count + 1).
    fn all_air_neighbor() -> Vec<i32> {
        // Just the sentinel pair + slack.
        let mut buf = vec![MAXZDIM, MAXZDIM];
        buf.resize(buf.len() + MAXZDIM as usize, MAXZDIM);
        buf
    }

    /// Build a sentinel-terminated b2 from a list of solid runs.
    /// Compatible with [`compilerle`]'s input shape — the trailing
    /// sentinel must come last with bot == MAXZDIM.
    fn b2_from_runs(runs: &[(i32, i32)]) -> Vec<i32> {
        let mut buf = Vec::new();
        for &(top, bot) in runs {
            buf.push(top);
            buf.push(bot);
        }
        buf.push(MAXZDIM);
        buf.push(MAXZDIM);
        buf.resize(buf.len() + MAXZDIM as usize, MAXZDIM);
        buf
    }

    #[test]
    fn build_color_table_single_slab_one_floor_voxel() {
        // [nextptr=0, z1=10, z1c=10, z0=0] + 1 colour.
        let slab = [0u8, 10, 10, 0, 0xa1, 0xa2, 0xa3, 0xa4];
        let table = build_color_table(&slab);
        assert_eq!(table.len(), 2);
        assert_eq!(table[0].z_start, 10);
        assert_eq!(table[0].z_end, 11);
        assert_eq!(table[0].colors, &[0xa1, 0xa2, 0xa3, 0xa4]);
        // Sentinel.
        assert_eq!(table[1].z_start, MAXZDIM);
        assert_eq!(table[1].z_end, MAXZDIM);
    }

    #[test]
    fn build_color_table_two_slabs_with_ceiling() {
        // Slab 0: nextptr=4 (16 bytes total) — 4 hdr + 1 floor + 8 ceiling-of-slab1
        //   Layout: [4, 10, 10, 0, F0,F0,F0,F0, C0,C0,C0,C0, C1,C1,C1,C1]
        // Slab 1: [0, 50, 52, 30, ...]
        //   Slab 1's ceiling list = 2 voxels at z=28..30 (stored in slab 0's tail).
        let slab = [
            4u8, 10, 10, 0, // slab 0 header
            0xf0, 0xf0, 0xf0, 0xf0, // 1 floor color
            0xc0, 0xc0, 0xc0, 0xc0, // ceiling color for z=28
            0xc1, 0xc1, 0xc1, 0xc1, // ceiling color for z=29
            0u8, 50, 52, 30, // slab 1 header
            0xfa, 0xfa, 0xfa, 0xfa, // floor z=50
            0xfb, 0xfb, 0xfb, 0xfb, // floor z=51
            0xfc, 0xfc, 0xfc, 0xfc, // floor z=52
        ];
        let table = build_color_table(&slab);
        assert_eq!(table.len(), 4);
        // Slab 0 floor.
        assert_eq!(table[0].z_start, 10);
        assert_eq!(table[0].z_end, 11);
        assert_eq!(table[0].colors.len(), 4);
        // Slab 1 ceiling — 2 voxels at z=28..30.
        assert_eq!(table[1].z_start, 28);
        assert_eq!(table[1].z_end, 30);
        assert_eq!(
            table[1].colors,
            &[0xc0, 0xc0, 0xc0, 0xc0, 0xc1, 0xc1, 0xc1, 0xc1]
        );
        // Slab 1 floor.
        assert_eq!(table[2].z_start, 50);
        assert_eq!(table[2].z_end, 53);
        assert_eq!(table[2].colors.len(), 12);
        // Sentinel.
        assert_eq!(table[3].z_start, MAXZDIM);
    }

    #[test]
    fn compilerle_round_trip_single_slab_solid_to_maxzdim() {
        // Original column: solid from z=10 to MAXZDIM, full floor
        // color list. compilerle with all-air neighbors should
        // re-encode bit-equivalently in b2 shape.
        let mut slab = vec![0u8, 10, (MAXZDIM - 1) as u8, 0];
        for z in 10..MAXZDIM {
            // Distinct color per z so we can verify exact output bytes.
            slab.extend_from_slice(&[z as u8, (z + 1) as u8, (z + 2) as u8, 0]);
        }

        // Decode to b2.
        let mut b2 = vec![0i32; (MAXZDIM as usize) + 4];
        expandrle(&slab, &mut b2);
        assert_eq!(b2[0], 10);
        assert_eq!(b2[1], MAXZDIM);

        // Re-encode with all-air neighbors → no buried-voxel skip.
        let n_air = all_air_neighbor();
        let mut cbuf = vec![0u8; 1028];
        let mut colfunc_called = 0;
        let mut colfunc = |_x: i32, _y: i32, _z: i32| -> i32 {
            colfunc_called += 1;
            0
        };
        let written = compilerle(
            &b2,
            &n_air,
            &n_air,
            &n_air,
            &n_air,
            &mut cbuf,
            &slab,
            0,
            0,
            &mut colfunc,
        );
        assert_eq!(colfunc_called, 0, "all colors should come from tbuf2");

        // Output should match the input slab byte-for-byte (it's
        // already the minimal full-floor encoding).
        assert_eq!(written, slab.len());
        assert_eq!(&cbuf[..written], &slab[..]);

        // And expandrle on the output reproduces the same b2.
        let mut b2_round = vec![0i32; (MAXZDIM as usize) + 4];
        expandrle(&cbuf[..written], &mut b2_round);
        assert_eq!(b2_round[0], 10);
        assert_eq!(b2_round[1], MAXZDIM);
    }

    #[test]
    fn compilerle_round_trip_two_solid_runs_with_cave() {
        // b2 = [10, 30, 50, MAXZDIM] — one cave between two solid runs.
        // Build a synthetic original column that has full floor color
        // lists for both slabs; ceiling list for slab 1 is non-empty.
        // For simplicity construct via compilerle from an all-air-
        // neighbor first encode of the desired b2, then round-trip.

        // Step 1: build a SEED column. We'll compilerle from a
        // hand-rolled "all is colfunc" variant — colfunc returns z as
        // its color, deterministic.
        let dummy = vec![0u8, 0, (MAXZDIM - 1) as u8, 0];
        let mut dummy_full = dummy;
        dummy_full.extend(std::iter::repeat_n(0u8, (MAXZDIM as usize) * 4));

        let n_air = all_air_neighbor();
        let b2 = b2_from_runs(&[(10, 30), (50, MAXZDIM)]);
        let mut seed = vec![0u8; 1028];
        let mut colfunc = |_x: i32, _y: i32, z: i32| -> i32 { z };
        let seed_len = compilerle(
            &b2,
            &n_air,
            &n_air,
            &n_air,
            &n_air,
            &mut seed,
            &dummy_full,
            0,
            0,
            &mut colfunc,
        );
        seed.truncate(seed_len);

        // Step 2: decode the seed back to b2.
        let mut b2_round = vec![0i32; (MAXZDIM as usize) + 4];
        expandrle(&seed, &mut b2_round);
        // Two solid runs followed by sentinel.
        assert_eq!(b2_round[0], 10);
        assert_eq!(b2_round[1], 30);
        assert_eq!(b2_round[2], 50);
        assert_eq!(b2_round[3], MAXZDIM);

        // Step 3: compilerle again using the seed as the original
        // column — should produce byte-identical output (idempotent
        // round trip).
        let mut cbuf = vec![0u8; 1028];
        let mut never_called = 0;
        let mut colfunc2 = |_x: i32, _y: i32, _z: i32| -> i32 {
            never_called += 1;
            0
        };
        let written = compilerle(
            &b2,
            &n_air,
            &n_air,
            &n_air,
            &n_air,
            &mut cbuf,
            &seed,
            0,
            0,
            &mut colfunc2,
        );
        assert_eq!(never_called, 0, "second pass needs no colfunc");
        assert_eq!(written, seed_len);
        assert_eq!(&cbuf[..written], &seed[..]);
    }

    #[test]
    fn compilerle_buried_voxel_optimization_with_all_solid_neighbors() {
        // All 4 neighbors solid means every voxel below the top one is
        // buried — compilerle's dacnt path closes the floor list right
        // after writing the first exposed voxel.

        // Self column: solid [10, MAXZDIM). Voxlap's b2 convention has
        // the last real solid run extending to MAXZDIM (solid below is
        // implicit), so we never transition into the sentinel slab.
        let b2 = b2_from_runs(&[(10, MAXZDIM)]);
        let n_solid = b2_from_runs(&[(0, MAXZDIM)]);
        // Original column over-encoded with a full floor color list so
        // colfunc is never needed (verifies tbuf2 lookup for buried
        // voxels we'd otherwise skip).
        let mut slab = vec![0u8, 10, (MAXZDIM - 1) as u8, 0];
        for z in 10..MAXZDIM {
            slab.extend_from_slice(&[z as u8, 0, 0, 0]);
        }
        let mut cbuf = vec![0u8; 1028];
        let mut colfunc_called = 0;
        let mut colfunc = |_x: i32, _y: i32, _z: i32| -> i32 {
            colfunc_called += 1;
            0
        };
        let written = compilerle(
            &b2,
            &n_solid,
            &n_solid,
            &n_solid,
            &n_solid,
            &mut cbuf,
            &slab,
            0,
            0,
            &mut colfunc,
        );
        assert_eq!(colfunc_called, 0, "tbuf2 should cover every voxel");
        // Compressed output: only the top voxel exposed (z=10) →
        // 4-byte header + 1 color = 8 bytes.
        assert_eq!(written, 8);
        assert_eq!(cbuf[0], 0); // terminator nextptr
        assert_eq!(cbuf[1], 10); // z1
        assert_eq!(cbuf[2], 10); // z1c (only one exposed voxel)
        assert_eq!(cbuf[3], 0); // z0 dummy
                                // expandrle on output reproduces the b2 shape (still solid
                                // from z=10 onward, despite the compressed encoding).
        let mut b2_round = vec![0i32; (MAXZDIM as usize) + 4];
        expandrle(&cbuf[..written], &mut b2_round);
        assert_eq!(b2_round[0], 10);
        assert_eq!(b2_round[1], MAXZDIM);
    }

    // ---- ScumCtx (CD.2.5) ---------------------------------------------

    /// Build a 1×1 Vxl with a single fully-solid column. Minimal slab
    /// encoding: 1 floor color = 8 bytes total.
    fn build_1x1_min_solid_vxl() -> Vxl {
        let column = vec![0u8, 0, 0, 0, 0xff, 0x80, 0x40, 0x20];
        let column_offset = vec![0u32, column.len() as u32].into_boxed_slice();
        Vxl {
            vsid: 1,
            ipo: [0.0; 3],
            ist: [1.0, 0.0, 0.0],
            ihe: [0.0, 0.0, 1.0],
            ifo: [0.0, 1.0, 0.0],
            data: column.into_boxed_slice(),
            column_offset,
            mip_base_offsets: Box::new([0, 2]),
            vbit: Box::new([]),
            vbiti: 0,
        }
    }

    #[test]
    fn scum2_no_edit_round_trip_1x1_minimal_column() {
        // Open a batch on a minimal-encoded 1×1 column, run scum2 +
        // finish without mutating, verify the column's b2 shape is
        // preserved.
        let mut vxl = build_1x1_min_solid_vxl();
        vxl.reserve_edit_capacity(4096);

        let mut ctx = ScumCtx::new(&mut vxl);
        let _b2 = ctx.scum2(0, 0).expect("column 0,0 in bounds");
        ctx.finish();

        let column = vxl.column_data(0);
        let mut b2_after = vec![0i32; SCPITCH];
        expandrle(column, &mut b2_after);
        assert_eq!(b2_after[0], 0);
        assert_eq!(b2_after[1], MAXZDIM);
    }

    #[test]
    fn scum2_carve_edit_1x1_creates_air_gap() {
        // Carve a hole in a fully-solid column; verify the post-edit
        // b2 reflects the carve.
        let mut vxl = build_1x1_min_solid_vxl();
        vxl.reserve_edit_capacity(4096);

        let mut ctx = ScumCtx::new(&mut vxl);
        ctx.set_colfunc(|_x, _y, _z| 0x80_60_40_20u32 as i32);
        {
            let b2 = ctx.scum2(0, 0).expect("column 0,0 in bounds");
            // Carve [50, 100) to air.
            delslab(b2, 50, 100);
        }
        ctx.finish();

        let column = vxl.column_data(0);
        let mut b2_after = vec![0i32; SCPITCH];
        expandrle(column, &mut b2_after);
        // Two solid runs now: [0, 50) and [100, MAXZDIM).
        assert_eq!(b2_after[0], 0);
        assert_eq!(b2_after[1], 50);
        assert_eq!(b2_after[2], 100);
        assert_eq!(b2_after[3], MAXZDIM);
    }

    /// Build a 4×4 Vxl with all 16 columns sharing the same minimal
    /// fully-solid encoding. Useful for testing batch edits.
    fn build_4x4_min_solid_vxl() -> Vxl {
        const COL: [u8; 8] = [0, 0, 0, 0, 0xff, 0x80, 0x40, 0x20];
        let mut data = Vec::with_capacity(16 * 8);
        let mut offsets = Vec::with_capacity(17);
        for i in 0..16 {
            offsets.push((i * 8) as u32);
            data.extend_from_slice(&COL);
        }
        offsets.push((16 * 8) as u32);
        Vxl {
            vsid: 4,
            ipo: [0.0; 3],
            ist: [1.0, 0.0, 0.0],
            ihe: [0.0, 0.0, 1.0],
            ifo: [0.0, 1.0, 0.0],
            data: data.into_boxed_slice(),
            column_offset: offsets.into_boxed_slice(),
            mip_base_offsets: Box::new([0, 17]),
            vbit: Box::new([]),
            vbiti: 0,
        }
    }

    #[test]
    fn scum2_batch_edits_multiple_columns_same_row() {
        // Edit columns (1, 2) and (2, 2) — same y row. Both should
        // get the same carve.
        let mut vxl = build_4x4_min_solid_vxl();
        vxl.reserve_edit_capacity(8192);

        let mut ctx = ScumCtx::new(&mut vxl);
        ctx.set_colfunc(|_x, _y, _z| 0);
        {
            let b2 = ctx.scum2(1, 2).unwrap();
            delslab(b2, 50, 100);
        }
        {
            let b2 = ctx.scum2(2, 2).unwrap();
            delslab(b2, 50, 100);
        }
        ctx.finish();

        for x in [1, 2] {
            let idx = 2 * 4 + x;
            let mut b2_after = vec![0i32; SCPITCH];
            expandrle(vxl.column_data(idx), &mut b2_after);
            assert_eq!(b2_after[0], 0);
            assert_eq!(b2_after[1], 50);
            assert_eq!(b2_after[2], 100);
            assert_eq!(b2_after[3], MAXZDIM);
        }
        // Untouched columns retain their original b2.
        for x in [0, 3] {
            let idx = 2 * 4 + x;
            let mut b2_after = vec![0i32; SCPITCH];
            expandrle(vxl.column_data(idx), &mut b2_after);
            assert_eq!(b2_after[0], 0);
            assert_eq!(b2_after[1], MAXZDIM);
        }
    }

    #[test]
    fn scum2_batch_edits_across_rows() {
        // Edit column (1, 1) then column (1, 2) — y advances, prior
        // row gets flushed automatically.
        let mut vxl = build_4x4_min_solid_vxl();
        vxl.reserve_edit_capacity(8192);

        let mut ctx = ScumCtx::new(&mut vxl);
        ctx.set_colfunc(|_x, _y, _z| 0);
        {
            let b2 = ctx.scum2(1, 1).unwrap();
            delslab(b2, 60, 80);
        }
        {
            let b2 = ctx.scum2(1, 2).unwrap();
            delslab(b2, 60, 80);
        }
        ctx.finish();

        for y in [1, 2] {
            let idx = y * 4 + 1;
            let mut b2_after = vec![0i32; SCPITCH];
            expandrle(vxl.column_data(idx), &mut b2_after);
            assert_eq!(b2_after[0], 0);
            assert_eq!(b2_after[1], 60);
            assert_eq!(b2_after[2], 80);
            assert_eq!(b2_after[3], MAXZDIM);
        }
    }

    #[test]
    fn scum2_finish_without_any_edit_is_noop() {
        // Begin then immediately finish without any scum2 call.
        let mut vxl = build_1x1_min_solid_vxl();
        vxl.reserve_edit_capacity(4096);
        let original = vxl.column_data(0).to_vec();
        let ctx = ScumCtx::new(&mut vxl);
        ctx.finish();
        assert_eq!(vxl.column_data(0), &original[..]);
    }

    #[test]
    fn scum2_returns_none_for_out_of_bounds() {
        let mut vxl = build_1x1_min_solid_vxl();
        vxl.reserve_edit_capacity(4096);
        let mut ctx = ScumCtx::new(&mut vxl);
        assert!(ctx.scum2(-1, 0).is_none());
        assert!(ctx.scum2(0, -1).is_none());
        assert!(ctx.scum2(1, 0).is_none());
        assert!(ctx.scum2(0, 1).is_none());
        ctx.finish();
    }

    // ---- set_spans (CD.3) --------------------------------------------

    #[test]
    fn set_spans_empty_is_noop() {
        let mut vxl = build_1x1_min_solid_vxl();
        let original = vxl.column_data(0).to_vec();
        set_spans(&mut vxl, &[], None);
        // Nothing should have changed — and we never reserved edit
        // capacity, so this also tests that empty input is fully
        // short-circuited (no ScumCtx::new + assert).
        assert_eq!(vxl.column_data(0), &original[..]);
    }

    #[test]
    fn set_spans_single_carve_creates_air_gap() {
        let mut vxl = build_1x1_min_solid_vxl();
        vxl.reserve_edit_capacity(4096);
        set_spans(
            &mut vxl,
            &[Vspan {
                x: 0,
                y: 0,
                z0: 50,
                z1: 99,
            }],
            None,
        );
        let mut b2 = vec![0i32; SCPITCH];
        expandrle(vxl.column_data(0), &mut b2);
        // Half-open exclusive end is z1+1 = 100.
        assert_eq!(b2[0], 0);
        assert_eq!(b2[1], 50);
        assert_eq!(b2[2], 100);
        assert_eq!(b2[3], MAXZDIM);
    }

    #[test]
    fn set_spans_multi_span_same_column_accumulates() {
        // Two non-overlapping carves on the same column. Voxlap's
        // setspans correctness relies on the with_column dedup —
        // re-calling scum2 between spans would wipe the first carve.
        let mut vxl = build_1x1_min_solid_vxl();
        vxl.reserve_edit_capacity(4096);
        set_spans(
            &mut vxl,
            &[
                Vspan {
                    x: 0,
                    y: 0,
                    z0: 30,
                    z1: 49,
                },
                Vspan {
                    x: 0,
                    y: 0,
                    z0: 100,
                    z1: 119,
                },
            ],
            None,
        );
        let mut b2 = vec![0i32; SCPITCH];
        expandrle(vxl.column_data(0), &mut b2);
        // Three solid runs: [0, 30), [50, 100), [120, MAXZDIM).
        assert_eq!(b2[0], 0);
        assert_eq!(b2[1], 30);
        assert_eq!(b2[2], 50);
        assert_eq!(b2[3], 100);
        assert_eq!(b2[4], 120);
        assert_eq!(b2[5], MAXZDIM);
    }

    #[test]
    fn set_spans_insert_color_fills_air() {
        // Start with a column that's already partly carved, fill the
        // air gap back in with a known color.
        let mut vxl = build_1x1_min_solid_vxl();
        vxl.reserve_edit_capacity(4096);
        // First carve [50, 100) to create air.
        set_spans(
            &mut vxl,
            &[Vspan {
                x: 0,
                y: 0,
                z0: 50,
                z1: 99,
            }],
            None,
        );
        // Now fill [60, 80) back to solid with a known color.
        const FILL: u32 = 0x80_aa_bb_cc;
        set_spans(
            &mut vxl,
            &[Vspan {
                x: 0,
                y: 0,
                z0: 60,
                z1: 79,
            }],
            Some(FILL),
        );
        let mut b2 = vec![0i32; SCPITCH];
        expandrle(vxl.column_data(0), &mut b2);
        // Three solid runs: [0, 50), [60, 80), [100, MAXZDIM).
        assert_eq!(b2[0], 0);
        assert_eq!(b2[1], 50);
        assert_eq!(b2[2], 60);
        assert_eq!(b2[3], 80);
        assert_eq!(b2[4], 100);
        assert_eq!(b2[5], MAXZDIM);
    }

    #[test]
    fn set_spans_skips_out_of_bounds_silently() {
        let mut vxl = build_1x1_min_solid_vxl();
        vxl.reserve_edit_capacity(4096);
        set_spans(
            &mut vxl,
            &[Vspan {
                x: 7,
                y: 9,
                z0: 50,
                z1: 99,
            }],
            None,
        );
        // Column (0,0) untouched — out-of-bounds span had no effect.
        let mut b2 = vec![0i32; SCPITCH];
        expandrle(vxl.column_data(0), &mut b2);
        assert_eq!(b2[0], 0);
        assert_eq!(b2[1], MAXZDIM);
    }

    #[test]
    fn set_spans_with_colfunc_z_dependent_colour() {
        // Insert solid with a colour that depends on z. To make every
        // voxel in [60, 80) exposed (and thus needing a colfunc call
        // each), use a 4x4 world with neighbors carved to air at the
        // same z range. Center column (1, 1) is then surrounded by
        // air on all 4 sides at [60, 80), giving compilerle a full
        // floor list to fill via the closure.
        let mut vxl = build_4x4_min_solid_vxl();
        vxl.reserve_edit_capacity(8192);
        // Step 1: carve [50, 100) on every column so the insert sits
        // in air on every side.
        let carve_spans: Vec<Vspan> = (0..4)
            .flat_map(|y| {
                (0..4).map(move |x| Vspan {
                    x,
                    y,
                    z0: 50,
                    z1: 99,
                })
            })
            .collect();
        set_spans(&mut vxl, &carve_spans, None);
        // Step 2: insert [60, 80) on the center column with a
        // z-dependent colour.
        set_spans_with_colfunc(
            &mut vxl,
            &[Vspan {
                x: 1,
                y: 1,
                z0: 60,
                z1: 79,
            }],
            SpanOp::Insert,
            |_x, _y, z| (0x80ff_ff00u32 as i32) | z,
        );
        // Walk column (1,1) and find the slab with z1=60; verify each
        // floor colour matches the closure's output.
        let idx = 4 + 1; // y=1, x=1 in a 4-wide world
        let column = vxl.column_data(idx);
        let mut v = 0usize;
        let mut found = false;
        loop {
            let nextptr = column[v];
            let z1 = column[v + 1];
            if z1 == 60 {
                let z1c = column[v + 2];
                assert_eq!(z1c, 79, "z1c");
                let n_voxels = usize::from(z1c) - usize::from(z1) + 1;
                for i in 0..n_voxels {
                    let off = v + 4 + i * 4;
                    let c = u32::from_le_bytes([
                        column[off],
                        column[off + 1],
                        column[off + 2],
                        column[off + 3],
                    ]);
                    let z = u32::from(z1) + (i as u32);
                    assert_eq!(
                        c,
                        0x80ff_ff00 | z,
                        "z={z}: expected colour {:#010x}, got {:#010x}",
                        0x80ff_ff00 | z,
                        c
                    );
                }
                found = true;
                break;
            }
            if nextptr == 0 {
                break;
            }
            v += usize::from(nextptr) * 4;
        }
        assert!(found, "did not find a slab with z1=60");
    }

    // ---- set_cube / set_rect / set_sphere (CD.4) ---------------------

    #[test]
    fn set_cube_carves_single_voxel() {
        let mut vxl = build_4x4_min_solid_vxl();
        vxl.reserve_edit_capacity(4096);
        set_cube(&mut vxl, 1, 1, 100, None);
        let mut b2 = vec![0i32; SCPITCH];
        expandrle(vxl.column_data(4 + 1), &mut b2);
        // Solid runs: [0, 100), [101, MAXZDIM).
        assert_eq!(b2[0], 0);
        assert_eq!(b2[1], 100);
        assert_eq!(b2[2], 101);
        assert_eq!(b2[3], MAXZDIM);
    }

    #[test]
    fn set_cube_skips_oob() {
        let mut vxl = build_4x4_min_solid_vxl();
        vxl.reserve_edit_capacity(4096);
        // Negative x, oversized y, z >= MAXZDIM, all silently no-op.
        set_cube(&mut vxl, -1, 1, 100, None);
        set_cube(&mut vxl, 5, 1, 100, None);
        set_cube(&mut vxl, 1, 1, 256, None);
        // Column (1, 1) untouched.
        let mut b2 = vec![0i32; SCPITCH];
        expandrle(vxl.column_data(4 + 1), &mut b2);
        assert_eq!(b2[0], 0);
        assert_eq!(b2[1], MAXZDIM);
    }

    #[test]
    fn set_rect_carves_aabb() {
        let mut vxl = build_4x4_min_solid_vxl();
        vxl.reserve_edit_capacity(8192);
        // Carve a 2x2x50 box at (1..=2, 1..=2, 50..=99).
        set_rect(&mut vxl, [1, 1, 50], [2, 2, 99], None);
        for y in 1..=2 {
            for x in 1..=2 {
                let idx = (y * 4 + x) as usize;
                let mut b2 = vec![0i32; SCPITCH];
                expandrle(vxl.column_data(idx), &mut b2);
                assert_eq!(b2[0], 0, "col ({x},{y})");
                assert_eq!(b2[1], 50, "col ({x},{y})");
                assert_eq!(b2[2], 100, "col ({x},{y})");
                assert_eq!(b2[3], MAXZDIM, "col ({x},{y})");
            }
        }
        // Untouched corners still solid through the full column.
        for &(x, y) in &[(0, 0), (3, 3)] {
            let idx = (y * 4 + x) as usize;
            let mut b2 = vec![0i32; SCPITCH];
            expandrle(vxl.column_data(idx), &mut b2);
            assert_eq!(b2[0], 0);
            assert_eq!(b2[1], MAXZDIM);
        }
    }

    #[test]
    fn set_rect_clamps_to_world() {
        let mut vxl = build_4x4_min_solid_vxl();
        vxl.reserve_edit_capacity(8192);
        // Box extends well past world bounds — clamps to [0, 3] in
        // each axis.
        set_rect(&mut vxl, [-10, -10, -10], [100, 100, 1000], None);
        // Every column carved over [0, MAXZDIM) → all-air.
        for idx in 0..16 {
            let mut b2 = vec![0i32; SCPITCH];
            expandrle(vxl.column_data(idx), &mut b2);
            // delslab clamps z1 to MAXZDIM-1, leaving voxel at
            // z=MAXZDIM-1 solid. The b2 reflects this: solid run
            // [255, MAXZDIM) only.
            assert_eq!(b2[0], 255, "col {idx}");
            assert_eq!(b2[1], MAXZDIM, "col {idx}");
        }
    }

    #[test]
    fn set_sphere_carves_centred_sphere() {
        // 4x4 world; sphere radius 1 carves a "+" pattern at z=128
        // (center voxel + 4 axis-adjacent + 2 z-axis voxels).
        let mut vxl = build_4x4_min_solid_vxl();
        vxl.reserve_edit_capacity(8192);
        set_sphere(&mut vxl, [1, 1, 128], 1, None);
        // Voxels carved at: (1,1,127), (1,1,128), (1,1,129) [z axis],
        // (0,1,128), (2,1,128) [x axis], (1,0,128), (1,2,128) [y axis].
        // Center column (1,1) has z range [127, 130) carved.
        let mut b2 = vec![0i32; SCPITCH];
        expandrle(vxl.column_data(4 + 1), &mut b2);
        assert_eq!(b2[0], 0);
        assert_eq!(b2[1], 127);
        assert_eq!(b2[2], 130);
        assert_eq!(b2[3], MAXZDIM);
        // Adjacent column (0, 1) has only z=128 carved.
        let mut b2 = vec![0i32; SCPITCH];
        expandrle(vxl.column_data(4), &mut b2);
        assert_eq!(b2[0], 0);
        assert_eq!(b2[1], 128);
        assert_eq!(b2[2], 129);
        assert_eq!(b2[3], MAXZDIM);
    }

    #[test]
    fn set_sphere_radius_zero_is_single_voxel() {
        let mut vxl = build_4x4_min_solid_vxl();
        vxl.reserve_edit_capacity(4096);
        set_sphere(&mut vxl, [1, 1, 100], 0, None);
        // Same as set_cube — only (1, 1, 100) carved.
        let mut b2 = vec![0i32; SCPITCH];
        expandrle(vxl.column_data(4 + 1), &mut b2);
        assert_eq!(b2[0], 0);
        assert_eq!(b2[1], 100);
        assert_eq!(b2[2], 101);
        assert_eq!(b2[3], MAXZDIM);
    }

    #[test]
    fn set_sphere_with_colfunc_position_dependent_color() {
        // Carve a cave first (so the inserted sphere has air on every
        // side, exposing its surface voxels), then insert a sphere
        // with a colfunc that returns z in the low byte. Verify
        // (a) b2 reflects the sphere shape and (b) the top exposed
        // voxel's colour is the colfunc output.
        //
        // Note: voxlap's compilerle stores colours only for EXPOSED
        // voxels (top of run + skip-forward landings); buried voxels
        // in the middle of a slab don't get colfunc-derived colours
        // recorded. So we can only verify colours for voxels at the
        // run boundary or near them.
        let mut vxl = build_4x4_min_solid_vxl();
        vxl.reserve_edit_capacity(8192);
        // Carve [50, 200) on every column.
        set_rect(&mut vxl, [0, 0, 50], [3, 3, 199], None);
        // Insert a sphere of radius 2 at (1, 1, 128). Center column
        // gets z=126..130 inclusive (5 voxels) inserted.
        set_sphere_with_colfunc(&mut vxl, [1, 1, 128], 2, SpanOp::Insert, |_, _, z| {
            (0x80ff_ff00u32 as i32) | z
        });
        // (a) b2 has the expected three solid runs.
        let mut b2 = vec![0i32; SCPITCH];
        expandrle(vxl.column_data(4 + 1), &mut b2);
        assert_eq!(b2[0], 0, "b2 first run top");
        assert_eq!(b2[1], 50, "b2 first run bot");
        assert_eq!(b2[2], 126, "b2 sphere run top");
        assert_eq!(b2[3], 131, "b2 sphere run bot");
        assert_eq!(b2[4], 200, "b2 third run top");
        assert_eq!(b2[5], MAXZDIM, "b2 third run bot");

        // (b) top of the sphere (z=126) is exposed (air above from
        // the carve). Its colour is the FIRST byte of the slab's
        // floor list.
        let column = vxl.column_data(4 + 1).to_vec();
        let mut v = 0usize;
        let mut top_color = None;
        loop {
            let nextptr = column[v];
            let z1 = column[v + 1];
            if z1 == 126 {
                let off = v + 4;
                top_color = Some(u32::from_le_bytes([
                    column[off],
                    column[off + 1],
                    column[off + 2],
                    column[off + 3],
                ]));
                break;
            }
            if nextptr == 0 {
                break;
            }
            v += usize::from(nextptr) * 4;
        }
        assert_eq!(
            top_color,
            Some(0x80ff_ff7e),
            "exposed voxel at z=126 should have colfunc-derived colour"
        );
    }

    #[test]
    fn set_spans_4x4_batch_carves_each_listed_column() {
        // Sorted (y, x) ascending; each column gets the same carve.
        let mut vxl = build_4x4_min_solid_vxl();
        vxl.reserve_edit_capacity(8192);
        let spans: Vec<Vspan> = (0..4)
            .flat_map(|y| {
                (0..4).map(move |x| Vspan {
                    x,
                    y,
                    z0: 50,
                    z1: 99,
                })
            })
            .collect();
        set_spans(&mut vxl, &spans, None);
        // Every column should have the [50, 100) carve.
        for idx in 0..16 {
            let mut b2 = vec![0i32; SCPITCH];
            expandrle(vxl.column_data(idx), &mut b2);
            assert_eq!(b2[0], 0, "col {idx}");
            assert_eq!(b2[1], 50, "col {idx}");
            assert_eq!(b2[2], 100, "col {idx}");
            assert_eq!(b2[3], MAXZDIM, "col {idx}");
        }
    }
}