concinnity-engine 0.19.2

Runtime engine for Concinnity: ECS schedule, graphics, spawn, streaming
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
// src/gfx/draw_list.rs
//
// Render-prep helpers that consume asset components and produce GPU-ready data.
// None of these functions hold or borrow a backend handle.

use crate::components::{
    File, FileKind, InstancedProp, InstancedPropGeometry, ProceduralMesh, Room, SubMeshRef,
    VoxelChunk,
};
use crate::ecs::PipelineContext;
use crate::ecs::asset_id::AssetId;
use crate::ecs::{MaterialHandle, MeshHandle, TextureHandle};
use crate::gfx::material_entry::{MaterialEntry, resolve_material_slots};
use crate::gfx::mesh_payload::Vertex;
use crate::gfx::render_types::{
    DrawObject, InstancedCluster, LodSlice, MaterialUniforms, NO_NORMAL_MAP_SLOT,
};

pub(crate) use crate::gfx::transform::IDENTITY as IDENTITY4;

// Geometry decoded for one Room: the asset, its vertices, LOD0 indices, and
// LOD alternates (switch_distance, indices).
pub(crate) type RoomGeometry = (Room, Vec<Vertex>, Vec<u16>, Vec<(f32, Vec<u16>)>);

// Mesh-geometry lookup tables from `load_mesh_geometry`: the loaded geometry
// (dense, indexed by the unified mesh-source handle -- a `.mesh` reference's
// `MeshHandle` indexes it directly), file-backed Mesh source metadata keyed by
// handle (dev-only), the always-resident handle set, and the asset id ->
// handle map for the geometry producers that are still components
// (ProceduralMesh / VoxelChunk / File).
pub(crate) type MeshGeometryMaps = (
    Vec<LoadedMesh>,
    std::collections::HashMap<usize, MeshSourceMeta>,
    std::collections::HashSet<usize>,
    std::collections::HashMap<AssetId, usize>,
    std::collections::HashMap<usize, DeferredMeshSeed>,
);

// A deferred mesh's payload reference, captured while its decode was skipped:
// the locator, plus the raw bytes when the blob is RAM-backed (an in-memory
// world may release its payload sections after init, so the bytes are copied
// out now; a disk-backed world re-reads the blob file range instead).
pub(crate) struct DeferredMeshSeed {
    pub locator: crate::ecs::PayloadLocator,
    pub bytes: Option<Vec<u8>>,
}

// Mesh sources whose payload decode init defers: exclusively owned by a scene
// other than the start scene, with baked bounds from the blob. `bounds` and
// `counts` are keyed by mesh-source handle; a member with no baked record
// decodes eagerly.
#[derive(Default)]
pub(crate) struct DeferredMeshSources {
    pub(crate) by_handle: std::collections::HashSet<u32>,
    pub(crate) by_def: std::collections::HashSet<AssetId>,
    pub bounds: std::collections::HashMap<u32, ([f32; 3], [f32; 3])>,
    pub counts: std::collections::HashMap<u32, (u32, u32)>,
}

impl DeferredMeshSources {
    // Baked bounds for a deferred resource-stream Mesh, or None to decode.
    fn resource_bounds(&self, handle: usize) -> Option<([f32; 3], [f32; 3])> {
        if !self.by_handle.contains(&(handle as u32)) {
            return None;
        }
        self.bounds.get(&(handle as u32)).copied()
    }

    // Baked bounds for a deferred mesh-source component at its push position,
    // or None to decode.
    fn def_bounds(&self, id: AssetId, handle: usize) -> Option<([f32; 3], [f32; 3])> {
        if !self.by_def.contains(&id) {
            return None;
        }
        self.bounds.get(&(handle as u32)).copied()
    }
}

// Output of `build_draw_list`. `prop_draw_indices` and `prop_local_bounds`
// are column-aligned with the input `items`; `mesh_handle_to_draws` backs
// hot-reload. A prop whose meshes carry no vertices gets the non-finite
// UNCULLED_BB as its local bounds (unpickable, uncullable).
pub(crate) struct DrawListData {
    pub vertices: Vec<Vertex>,
    pub indices: Vec<u32>,
    pub(crate) draw_objects: Vec<DrawObject>,
    pub(crate) instanced_clusters: Vec<InstancedCluster>,
    pub(crate) prop_draw_indices: Vec<Vec<usize>>,
    pub(crate) mesh_handle_to_draws: std::collections::HashMap<usize, Vec<usize>>,
    pub(crate) prop_local_bounds: Vec<([f32; 3], [f32; 3])>,
}

// One appended mesh's placement in the shared buffers: vertex_offset,
// vertex_count, index_offset, index_count, LOD slices, and local AABB min/max.
type AppendedMesh = (
    usize,
    usize,
    usize,
    usize,
    Vec<LodSlice>,
    [f32; 3],
    [f32; 3],
);

// Sentinel AABB used when a draw object opts out of culling (e.g. unbounded
// skybox geometry). Both metal and vulkan/directx backends should treat any
// non-finite component as "always draw".
const UNCULLED_BB: ([f32; 3], [f32; 3]) = (
    [f32::NAN, f32::NAN, f32::NAN],
    [f32::NAN, f32::NAN, f32::NAN],
);

fn local_bounds(verts: &[Vertex]) -> ([f32; 3], [f32; 3]) {
    if verts.is_empty() {
        return UNCULLED_BB;
    }
    let mut mn = [f32::INFINITY; 3];
    let mut mx = [f32::NEG_INFINITY; 3];
    for v in verts {
        for i in 0..3 {
            mn[i] = mn[i].min(v.pos[i]);
            mx[i] = mx[i].max(v.pos[i]);
        }
    }
    (mn, mx)
}

// The renderer-relevant view of one placement that build_draw_list consumes:
// the mesh/model/material/texture refs, the cull distance, whether it is dynamic
// (skips frustum culling), and the asset id (error logging only). Built from an
// entity's MeshRenderer/ModelRenderer + tag components by
// `decomposed_renderable_item`.
//
// An entity is dynamic (pulled out of the BVH and always drawn after a per-object
// frustum test) when it carries a Pickup, Interactable, Parent, or Collider tag.
// The BVH is built once at init and does not refit, so a moving entity would
// otherwise risk being culled against its stale init-time AABB.
#[derive(Debug, PartialEq)]
pub(crate) struct RenderableItem {
    pub asset_id: AssetId,
    pub model: Option<AssetId>,
    pub mesh: Option<MeshHandle>,
    pub material: Option<MaterialHandle>,
    pub texture: Option<TextureHandle>,
    pub cull_distance: f32,
    pub(crate) is_dynamic: bool,
}

// Build one entity's RenderableItem: read its renderer fields from its
// MeshRenderer xor ModelRenderer and its dynamic flag from the Pickup /
// Interactable / Parent / Collider tags. asset_id is for error logging only
// (resolved from the name index by the caller).
pub(crate) fn decomposed_renderable_item(
    ctx: &crate::ecs::PipelineContext,
    entity: crate::ecs::Entity,
    asset_id: AssetId,
) -> RenderableItem {
    use crate::components::{Collider, Interactable, MeshRenderer, ModelRenderer, Parent, Pickup};

    let (model, mesh, material, texture, cull_distance) =
        if let Some(m) = ctx.get::<ModelRenderer>(entity) {
            (Some(m.model), None, None, None, m.cull_distance)
        } else if let Some(m) = ctx.get::<MeshRenderer>(entity) {
            (None, m.mesh, m.material, m.texture, m.cull_distance)
        } else {
            (None, None, None, None, 0.0)
        };
    let is_dynamic = ctx.get::<Pickup>(entity).is_some()
        || ctx.get::<Interactable>(entity).is_some()
        || ctx.get::<Parent>(entity).is_some()
        || ctx.get::<Collider>(entity).is_some();
    RenderableItem {
        asset_id,
        model,
        mesh,
        material,
        texture,
        cull_distance,
        is_dynamic,
    }
}

// Append each LOD alternate's indices to `indices`, rebased onto `base`, and
// return the slice table addressing them. The alternates share the base mesh's
// vertex range, so only the index run differs per level.
pub(crate) fn append_lod_slices<T>(
    indices: &mut Vec<T>,
    alternates: &[(f32, Vec<u16>)],
    base: T,
) -> Vec<LodSlice>
where
    T: Copy + From<u16> + std::ops::Add<Output = T>,
{
    let mut slices = Vec::with_capacity(alternates.len());
    for (switch_distance, alt) in alternates {
        let index_offset = indices.len();
        indices.extend(alt.iter().map(|&i| T::from(i) + base));
        slices.push(LodSlice {
            index_offset,
            index_count: alt.len(),
            switch_distance: *switch_distance,
        });
    }
    slices
}

// Decoded mesh geometry plus its optional LOD trailer. Returned by
// `load_mesh_geometry` and consumed by `build_draw_list`. The `vertices`
// slice is shared across LOD0 and every alternate; vertex-clustering
// decimation reuses the original vertex set and only generates new index
// lists. Empty `lod_alternates` means the mesh declared `lod_levels <= 1`
// (or the build dropped degenerate decimations); the runtime then keeps
// the single LOD0 slice.
pub(crate) struct LoadedMesh {
    pub vertices: Vec<Vertex>,
    pub indices: Vec<u16>,
    pub lod_alternates: Vec<(f32, Vec<u16>)>,
    // Baked local AABB for a deferred mesh whose vertices were not decoded;
    // None computes bounds from the vertices.
    pub bounds: Option<([f32; 3], [f32; 3])>,
    // Baked (vertex, index) counts for a deferred mesh, so its draw record
    // matches the geometry the streamer uploads later; None uses the decoded
    // lengths.
    pub counts: Option<(u32, u32)>,
}

// Hot-reload source metadata for a file-backed `Mesh`. Captured by
// `load_mesh_geometry` before the Mesh is drained and consumed; the
// `(asset_id, source, primitive_index, lod_levels, lod_distances)` tuple is
// later cross-referenced against `build_draw_list`'s mesh_id → draw_indices
// map to build the runtime
// [`MeshSourceMap`](crate::gfx::graphics_system::hot_reload_sources::MeshSourceMap).
pub(crate) struct MeshSourceMeta {
    pub source: String,
    pub primitive_index: u32,
    pub lod_levels: u32,
    pub lod_distances: Vec<f32>,
}

// Decode all mesh-source payloads into a dense, handle-indexed geometry table.
// The Mesh block comes from the blob's resource stream (`MeshTable`); the
// remaining geometry producers (ProceduralMesh, VoxelChunk, mesh-kind File) are
// still components and are decoded after it, in the same fixed block order cook
// assigned handles, so `geometry[h]` is the source cook gave handle `h`.
// Returns None if any payload is missing or malformed. Also returns a
// handle-keyed source-meta map for file-backed Mesh declarations under
// `cn debug` (from the dev `MeshSources` catalogue), the set of handles whose
// props must always stay resident (skybox-class geometry that encloses the
// camera), and the asset id -> handle map for the still-component producers.
pub(crate) fn load_mesh_geometry(
    ctx: &mut PipelineContext,
    deferred: &DeferredMeshSources,
    blob_disk_backed: bool,
) -> Option<MeshGeometryMaps> {
    let mut deferred_payloads: std::collections::HashMap<usize, DeferredMeshSeed> =
        std::collections::HashMap::new();
    let mesh_table = ctx
        .resource::<crate::resource::MeshTable>()
        .cloned()
        .unwrap_or_default();
    // Dev-only source catalogue (present under `cn debug`) so the hot-reload
    // watcher can map a mesh handle back to the file that backs it. Mesh is a
    // resource now, so there is no drained component `source` to capture.
    let capture_sources = crate::app::dev_flags::enabled();
    let mut mesh_sources: std::collections::HashMap<usize, MeshSourceMeta> =
        std::collections::HashMap::new();
    if capture_sources && let Some(sources) = ctx.resource::<crate::resource::MeshSources>() {
        for (handle, info) in sources.0.iter().enumerate() {
            if !info.source.is_empty() {
                mesh_sources.insert(
                    handle,
                    MeshSourceMeta {
                        source: info.source.clone(),
                        primitive_index: info.primitive_index,
                        lod_levels: info.lod_levels,
                        lod_distances: info.lod_distances.clone(),
                    },
                );
            }
        }
    }
    // ProceduralMesh components are cloned rather than drained: PhysicsSystem
    // inits after GraphicsSystem and resolves its `terrain_mesh` reference by
    // querying ProceduralMesh for the live heightfield args. Same precedent as
    // the audio-clip residency the graphics init leaves resident for AudioSystem:
    // leave the component in place so a later init step can still read it.
    // A generator the world baked for itself at start carries no locator; those
    // are the trailing `MeshBlock::Runtime` block, loaded after the compiled
    // ones so a handle the build assigned keeps its index.
    let (proc_meshes, baked_meshes): (Vec<ProceduralMesh>, Vec<ProceduralMesh>) = ctx
        .query::<ProceduralMesh>()
        .cloned()
        .partition(|m| m.locator.is_some());
    let baked_payloads = ctx
        .resource::<concinnity_core::resource::RuntimeMeshPayloads>()
        .cloned()
        .unwrap_or_default();
    let voxel_chunks = ctx.drain::<VoxelChunk>();
    let file_assets = ctx.drain::<File>();
    let file_meshes: Vec<&File> = file_assets
        .iter()
        .filter(|f| f.kind.as_ref().map(FileKind::is_mesh).unwrap_or(false))
        .collect();

    if mesh_table.is_empty()
        && proc_meshes.is_empty()
        && baked_meshes.is_empty()
        && voxel_chunks.is_empty()
        && file_meshes.is_empty()
    {
        // Room path can carry the scene without any explicit Mesh/ProceduralMesh
        tracing::info!(
            "GraphicsSystem: no Mesh, ProceduralMesh, VoxelChunk, or mesh-kind File sources found"
        );
    }

    let mut geometry: Vec<LoadedMesh> = Vec::new();
    // Asset id -> handle for the geometry producers that are still components,
    // so init can cross-reference their id-keyed metadata (e.g. the
    // ProceduralMesh args snapshot) with the handle-keyed draw map.
    let mut component_mesh_handles: std::collections::HashMap<AssetId, usize> =
        std::collections::HashMap::new();

    // Mesh block first: decode each resource-table entry at its handle position.
    for (handle, entry) in mesh_table.0.iter().enumerate() {
        let locator = match &entry.payload {
            Some(l) => l,
            None => {
                tracing::error!(
                    "GraphicsSystem: Mesh handle {} has no compiled payload -- did the build succeed?",
                    handle
                );
                return None;
            }
        };
        if let Some(bounds) = deferred.resource_bounds(handle) {
            let bytes = if blob_disk_backed {
                None
            } else {
                match ctx.read_payload(locator) {
                    Ok(b) => Some(b.to_vec()),
                    Err(e) => {
                        tracing::error!("GraphicsSystem: failed to read Mesh payload: {:?}", e);
                        return None;
                    }
                }
            };
            deferred_payloads.insert(
                handle,
                DeferredMeshSeed {
                    locator: locator.clone(),
                    bytes,
                },
            );
            geometry.push(LoadedMesh {
                vertices: Vec::new(),
                indices: Vec::new(),
                lod_alternates: Vec::new(),
                bounds: Some(bounds),
                counts: deferred.counts.get(&(handle as u32)).copied(),
            });
            continue;
        }
        let bytes = match ctx.read_payload(locator) {
            Ok(b) => b.to_vec(),
            Err(e) => {
                tracing::error!("GraphicsSystem: failed to read Mesh payload: {:?}", e);
                return None;
            }
        };
        // `deserialise_with_lods` parses the optional LOD trailer when the
        // build emitted one and falls back to an empty alternates vec for
        // legacy single-LOD payloads.
        match crate::gfx::mesh_payload::deserialise_with_lods(&bytes) {
            Ok((verts, idxs, alternates)) => geometry.push(LoadedMesh {
                vertices: verts,
                indices: idxs,
                lod_alternates: alternates,
                bounds: None,
                counts: None,
            }),
            Err(e) => {
                tracing::error!("GraphicsSystem: malformed Mesh payload: {}", e);
                return None;
            }
        }
    }

    macro_rules! load_meshes {
        ($label:expr_2021, $items:expr_2021) => {
            for (i, mesh) in $items.iter().enumerate() {
                let locator = match &mesh.locator {
                    Some(l) => l,
                    None => {
                        tracing::error!(
                            "GraphicsSystem: {}[{}] {} has no compiled payload",
                            $label,
                            i,
                            mesh.asset_id
                        );
                        return None;
                    }
                };
                if let Some(bounds) = deferred.def_bounds(mesh.asset_id, geometry.len()) {
                    let bytes = if blob_disk_backed {
                        None
                    } else {
                        match ctx.read_payload(locator) {
                            Ok(b) => Some(b.to_vec()),
                            Err(e) => {
                                tracing::error!(
                                    "GraphicsSystem: failed to read {} payload: {:?}",
                                    $label,
                                    e
                                );
                                return None;
                            }
                        }
                    };
                    deferred_payloads.insert(
                        geometry.len(),
                        DeferredMeshSeed {
                            locator: locator.clone(),
                            bytes,
                        },
                    );
                    component_mesh_handles.insert(mesh.asset_id, geometry.len());
                    let counts = deferred.counts.get(&(geometry.len() as u32)).copied();
                    geometry.push(LoadedMesh {
                        vertices: Vec::new(),
                        indices: Vec::new(),
                        lod_alternates: Vec::new(),
                        bounds: Some(bounds),
                        counts,
                    });
                    continue;
                }
                let bytes = match ctx.read_payload(locator) {
                    Ok(b) => b.to_vec(),
                    Err(e) => {
                        tracing::error!(
                            "GraphicsSystem: failed to read {} payload: {:?}",
                            $label,
                            e
                        );
                        return None;
                    }
                };
                match crate::gfx::mesh_payload::deserialise_with_lods(&bytes) {
                    Ok((verts, idxs, alternates)) => {
                        // This source's handle is its push position: the blocks
                        // are loaded in cook's block order and each iterates in
                        // declaration order.
                        component_mesh_handles.insert(mesh.asset_id, geometry.len());
                        geometry.push(LoadedMesh {
                            vertices: verts,
                            indices: idxs,
                            lod_alternates: alternates,
                            bounds: None,
                            counts: None,
                        });
                    }
                    Err(e) => {
                        tracing::error!("GraphicsSystem: malformed {} payload: {}", $label, e);
                        return None;
                    }
                }
            }
        };
    }
    load_meshes!("ProceduralMesh", proc_meshes);
    load_meshes!("VoxelChunk", voxel_chunks);
    load_meshes!("File", file_meshes);

    // The world's own block: geometry baked at start, whose payload bytes are
    // already in memory rather than behind a locator.
    for mesh in &baked_meshes {
        let Some(bytes) = baked_payloads.get(mesh.asset_id) else {
            tracing::error!(
                "GraphicsSystem: ProceduralMesh {} was baked at start but left no payload",
                mesh.asset_id
            );
            return None;
        };
        match crate::gfx::mesh_payload::deserialise_with_lods(bytes) {
            Ok((verts, idxs, alternates)) => {
                component_mesh_handles.insert(mesh.asset_id, geometry.len());
                geometry.push(LoadedMesh {
                    vertices: verts,
                    indices: idxs,
                    lod_alternates: alternates,
                    bounds: None,
                    counts: None,
                });
            }
            Err(e) => {
                tracing::error!(
                    "GraphicsSystem: malformed baked ProceduralMesh payload: {}",
                    e
                );
                return None;
            }
        }
    }

    // Skybox-generated meshes enclose the camera, so any prop using one must
    // opt out of frustum culling AND streaming residency (per the
    // StreamingConfig docstring's "skybox always stays resident" promise).
    let always_resident_meshes: std::collections::HashSet<usize> = proc_meshes
        .iter()
        .chain(&baked_meshes)
        .filter(|pm| pm.generator == "skybox")
        .filter_map(|pm| component_mesh_handles.get(&pm.asset_id).copied())
        .collect();

    Some((
        geometry,
        mesh_sources,
        always_resident_meshes,
        component_mesh_handles,
        deferred_payloads,
    ))
}

// Decode all Room mesh payloads and collect blob indices for the release step.
// Returns None if any payload is missing or malformed (error already logged).
pub(crate) fn load_room_geometry(
    ctx: &mut PipelineContext,
) -> Option<(Vec<RoomGeometry>, Vec<u32>)> {
    let rooms = ctx.drain::<Room>();
    let mut room_geometry: Vec<RoomGeometry> = Vec::new();
    let mut blob_indices: Vec<u32> = Vec::new();

    for (i, room) in rooms.into_iter().enumerate() {
        let locator = match &room.locator {
            Some(l) => l.clone(),
            None => {
                tracing::error!(
                    "GraphicsSystem: Room[{}] {} has no compiled payload -- did the build succeed?",
                    i,
                    room.asset_id
                );
                return None;
            }
        };
        blob_indices.push(locator.blob_index);
        let bytes = match ctx.read_payload(&locator) {
            Ok(b) => b.to_vec(),
            Err(e) => {
                tracing::error!(
                    "GraphicsSystem: failed to read Room {} payload: {:?}",
                    room.asset_id,
                    e
                );
                return None;
            }
        };
        match crate::gfx::mesh_payload::deserialise_with_lods(&bytes) {
            Ok((verts, idxs, alternates)) => room_geometry.push((room, verts, idxs, alternates)),
            Err(e) => {
                tracing::error!("GraphicsSystem: malformed Room payload: {}", e);
                return None;
            }
        }
    }

    Some((room_geometry, blob_indices))
}

// Assemble the shared vertex/index buffers and per-object draw records from all
// scene geometry (props, unreferenced meshes, rooms). Also returns the per-prop
// draw-index table for runtime model-matrix updates and the GPU-instanced
// cluster list (one entry per InstancedProp).
// Returns None if any referenced asset is missing (error already logged).
// The read-only scene lookup tables consumed by [`build_draw_list`]: the
// renderable items and instanced props plus every catalogue needed to resolve
// their geometry, textures, and materials.
pub(crate) struct DrawListInputs<'a> {
    pub items: &'a [RenderableItem],
    pub instanced_props: &'a [InstancedProp],
    pub world_mats: &'a [[[f32; 4]; 4]],
    pub model_map: &'a std::collections::HashMap<AssetId, Vec<SubMeshRef>>,
    // Dense mesh-source geometry from `load_mesh_geometry`: a `.mesh`
    // reference's `MeshHandle` indexes it directly.
    pub mesh_geometry: &'a [LoadedMesh],
    pub room_geometry: &'a [RoomGeometry],
    // Size of the shared texture pool; a texture handle is in range when its
    // index is below this. A legacy texture-on-mesh reference past it falls back
    // to slot 0.
    pub texture_count: usize,
    pub material_map: &'a std::collections::HashMap<MaterialHandle, MaterialEntry>,
    pub always_resident_meshes: &'a std::collections::HashSet<usize>,
}

pub(crate) fn build_draw_list(inputs: DrawListInputs) -> Option<DrawListData> {
    let DrawListInputs {
        items,
        instanced_props,
        world_mats,
        model_map,
        mesh_geometry,
        room_geometry,
        texture_count,
        material_map,
        always_resident_meshes,
    } = inputs;
    let mut all_vertices: Vec<Vertex> = Vec::new();
    let mut all_indices: Vec<u32> = Vec::new();
    let mut draw_objects: Vec<DrawObject> = Vec::new();
    let mut instanced_clusters: Vec<InstancedCluster> = Vec::new();
    let mut prop_draw_indices: Vec<Vec<usize>> = Vec::new();
    let mut prop_local_bounds: Vec<([f32; 3], [f32; 3])> = Vec::new();
    // Map every mesh-source handle to the draw slots that received a copy of
    // its geometry. Hot-reload (`cn debug` only) walks this to know which slots
    // to overwrite when the source `.glb` changes. The `Vec<usize>` accumulates
    // every push since a mesh shared by N `Prop`s yields N independent draw
    // objects.
    let mut mesh_handle_to_draws: std::collections::HashMap<usize, Vec<usize>> =
        std::collections::HashMap::new();

    // track explicitly referenced mesh handles so unreferenced ones get auto-rendered
    let mut referenced: std::collections::HashSet<usize> = std::collections::HashSet::new();
    for item in items {
        if let Some(mesh) = item.mesh {
            referenced.insert(mesh.index());
        }
        if let Some(model_id) = item.model
            && let Some(submeshes) = model_map.get(&model_id)
        {
            for sub in submeshes {
                if let Some(sub_mesh) = sub.mesh {
                    referenced.insert(sub_mesh.index());
                }
            }
        }
    }
    for inst in instanced_props {
        if let Some(mesh) = inst.mesh {
            referenced.insert(mesh.index());
        }
    }

    // append_mesh: add a mesh into the shared buffers by handle, return
    // (vertex_offset, vertex_count, index_offset, index_count, lod_slices,
    // local_bb_min, local_bb_max). `lod_slices` is empty for legacy
    // single-LOD meshes; otherwise each entry is a `LodSlice` pointing at the
    // alternate's rebased indices in `all_indices`, paired with its switch
    // distance. Every LOD alternate reuses the same `vertex_offset` /
    // `vertex_count` since clustering decimation does not modify the vertex
    // set.
    let mut append_mesh = |handle: usize| -> Option<AppendedMesh> {
        let loaded = mesh_geometry.get(handle)?;
        let vertex_byte_offset = all_vertices.len() * std::mem::size_of::<Vertex>();
        let index_elem_offset = all_indices.len();
        let base = all_vertices.len() as u32;
        let (bb_min, bb_max) = loaded
            .bounds
            .unwrap_or_else(|| local_bounds(&loaded.vertices));
        all_vertices.extend_from_slice(&loaded.vertices);
        all_indices.extend(loaded.indices.iter().map(|i| u32::from(*i) + base));
        let lod_slices = append_lod_slices(&mut all_indices, &loaded.lod_alternates, base);
        // A deferred mesh appended no bytes; its draw record carries the baked
        // counts so the streamed upload's size check matches the real geometry.
        let (vertex_count, index_count) = loaded
            .counts
            .map(|(v, i)| (v as usize, i as usize))
            .unwrap_or((loaded.vertices.len(), loaded.indices.len()));
        Some((
            vertex_byte_offset,
            vertex_count,
            index_elem_offset,
            index_count,
            lod_slices,
            bb_min,
            bb_max,
        ))
    };

    for (item_idx, item) in items.iter().enumerate() {
        let model_mat = world_mats[item_idx];
        let mut prop_idxs: Vec<usize> = Vec::new();
        // Union of this prop's sub-mesh local bounds (all in the same model
        // space). NaN sentinels from empty meshes fall out of min/max.
        let mut prop_min = [f32::INFINITY; 3];
        let mut prop_max = [f32::NEG_INFINITY; 3];
        let mut union_local = |mn: [f32; 3], mx: [f32; 3]| {
            for i in 0..3 {
                prop_min[i] = prop_min[i].min(mn[i]);
                prop_max[i] = prop_max[i].max(mx[i]);
            }
        };

        if let Some(model_id) = item.model {
            // multi-mesh model path: one draw object per sub-mesh
            let submeshes = match model_map.get(&model_id) {
                Some(s) => s,
                None => {
                    tracing::error!(
                        "GraphicsSystem: Prop {} references unknown model {} -- add a Model asset with that id",
                        item.asset_id,
                        model_id
                    );
                    return None;
                }
            };
            for sub in submeshes {
                let sub_mesh = match sub.mesh {
                    Some(m) => m.index(),
                    None => {
                        tracing::error!(
                            "GraphicsSystem: Model {} has a sub-mesh with no mesh",
                            model_id
                        );
                        return None;
                    }
                };
                let (
                    vertex_offset,
                    vertex_count,
                    index_offset,
                    index_count,
                    lod_alternates,
                    local_min,
                    local_max,
                ) = match append_mesh(sub_mesh) {
                    Some(t) => t,
                    None => {
                        tracing::error!(
                            "GraphicsSystem: Model {} sub-mesh handle {} out of range -- add a Mesh or ProceduralMesh asset with that name",
                            model_id,
                            sub_mesh
                        );
                        return None;
                    }
                };
                let mat_entry =
                    match resolve_material_slots(sub.material, None, material_map, texture_count) {
                        Ok(entry) => entry,
                        Err(mat_id) => {
                            tracing::error!(
                                "GraphicsSystem: Model {} sub-mesh material {} not found",
                                model_id,
                                mat_id.index()
                            );
                            return None;
                        }
                    };
                let (bb_min, bb_max) =
                    if item.is_dynamic || always_resident_meshes.contains(&sub_mesh) {
                        UNCULLED_BB
                    } else {
                        crate::gfx::frustum::transform_aabb(local_min, local_max, model_mat)
                    };
                union_local(local_min, local_max);
                prop_idxs.push(draw_objects.len());
                mesh_handle_to_draws
                    .entry(sub_mesh)
                    .or_default()
                    .push(draw_objects.len());
                draw_objects.push(DrawObject {
                    vertex_offset,
                    vertex_count,
                    index_offset,
                    index_count,
                    // Static geometry: indices are absolute into the shared
                    // vertex buffer, so no per-draw base.
                    base_vertex: 0,
                    geometry_generation: 0,
                    model: model_mat,
                    texture_slot: mat_entry.albedo_slot,
                    normal_map_slot: mat_entry.normal_map_slot,
                    material: mat_entry.uniforms,
                    shader_bucket: mat_entry.shader_bucket,
                    visible: true,
                    resident: true,
                    bb_min,
                    bb_max,
                    cull_distance: item.cull_distance,
                    lod_alternates,
                });
            }
        } else {
            // single-mesh path
            let mesh_handle = match item.mesh {
                Some(m) => m.index(),
                None => {
                    tracing::error!(
                        "GraphicsSystem: Prop {} has neither a model nor a mesh",
                        item.asset_id
                    );
                    return None;
                }
            };
            let (
                vertex_offset,
                vertex_count,
                index_offset,
                index_count,
                lod_alternates,
                local_min,
                local_max,
            ) = match append_mesh(mesh_handle) {
                Some(t) => t,
                None => {
                    tracing::error!(
                        "GraphicsSystem: Prop {} references out-of-range mesh handle {} -- add a Mesh or ProceduralMesh asset with that name",
                        item.asset_id,
                        mesh_handle
                    );
                    return None;
                }
            };
            // The texture handle is the texture's declaration-order pool slot;
            // an out-of-range handle falls back to slot 0.
            let mat_entry = match resolve_material_slots(
                item.material,
                item.texture,
                material_map,
                texture_count,
            ) {
                Ok(entry) => entry,
                Err(mat_id) => {
                    tracing::error!(
                        "GraphicsSystem: Prop {} references unknown material {} -- add a Material asset with that id",
                        item.asset_id,
                        mat_id.index()
                    );
                    return None;
                }
            };
            let (bb_min, bb_max) =
                if item.is_dynamic || always_resident_meshes.contains(&mesh_handle) {
                    UNCULLED_BB
                } else {
                    crate::gfx::frustum::transform_aabb(local_min, local_max, model_mat)
                };
            union_local(local_min, local_max);
            prop_idxs.push(draw_objects.len());
            mesh_handle_to_draws
                .entry(mesh_handle)
                .or_default()
                .push(draw_objects.len());
            draw_objects.push(DrawObject {
                vertex_offset,
                vertex_count,
                index_offset,
                index_count,
                base_vertex: 0,
                geometry_generation: 0,
                model: model_mat,
                texture_slot: mat_entry.albedo_slot,
                normal_map_slot: mat_entry.normal_map_slot,
                material: mat_entry.uniforms,
                shader_bucket: mat_entry.shader_bucket,
                visible: true,
                resident: true,
                bb_min,
                bb_max,
                cull_distance: item.cull_distance,
                lod_alternates,
            });
        }

        prop_draw_indices.push(prop_idxs);
        let finite = prop_min
            .iter()
            .chain(prop_max.iter())
            .all(|v| v.is_finite());
        prop_local_bounds.push(if finite {
            (prop_min, prop_max)
        } else {
            UNCULLED_BB
        });
    }

    // InstancedProp -> one GPU-instanced cluster per InstancedProp.
    // The cluster mesh is appended once; per-instance model matrices are
    // resolved up front and uploaded to the GPU each frame. The cluster's
    // union AABB is used as a single frustum-cull test for the whole batch.
    for inst in instanced_props {
        let mesh_handle = match inst.mesh {
            Some(m) if !inst.instances.is_empty() => m.index(),
            _ => continue,
        };
        // Instanced clusters carry the mesh's LOD alternates and bucket
        // their per-instance matrices by camera distance at draw time;
        // see [`InstancedCluster::lod_buckets`].
        let (
            vertex_offset,
            vertex_count,
            index_offset,
            index_count,
            lod_alternates,
            local_min,
            local_max,
        ) = match append_mesh(mesh_handle) {
            Some(t) => t,
            None => {
                tracing::error!(
                    "GraphicsSystem: InstancedProp {} references out-of-range mesh handle {}",
                    inst.asset_id,
                    mesh_handle
                );
                return None;
            }
        };
        let mat_entry = match resolve_material_slots(
            inst.material,
            inst.texture,
            material_map,
            texture_count,
        ) {
            Ok(entry) => entry,
            Err(mat_id) => {
                tracing::error!(
                    "GraphicsSystem: InstancedProp {} references unknown material {}",
                    inst.asset_id,
                    mat_id.index()
                );
                return None;
            }
        };
        let (texture_slot, normal_map_slot, material) = (
            mat_entry.albedo_slot,
            mat_entry.normal_map_slot,
            mat_entry.uniforms,
        );

        let mut instance_mats: Vec<[[f32; 4]; 4]> = Vec::with_capacity(inst.instances.len());
        let mut cluster_min = [f32::INFINITY; 3];
        let mut cluster_max = [f32::NEG_INFINITY; 3];
        for i in 0..inst.instances.len() {
            let Some(model_mat) = inst.instance_model_matrix(i) else {
                continue;
            };
            let (bb_min, bb_max) =
                crate::gfx::frustum::transform_aabb(local_min, local_max, model_mat);
            for k in 0..3 {
                cluster_min[k] = cluster_min[k].min(bb_min[k]);
                cluster_max[k] = cluster_max[k].max(bb_max[k]);
            }
            instance_mats.push(model_mat);
        }
        if instance_mats.is_empty() {
            continue;
        }

        instanced_clusters.push(InstancedCluster {
            vertex_offset,
            vertex_count,
            index_offset,
            index_count,
            texture_slot,
            normal_map_slot,
            material,
            cluster_bb_min: cluster_min,
            cluster_bb_max: cluster_max,
            local_bb_min: local_min,
            local_bb_max: local_max,
            cull_distance: inst.cull_distance,
            instances: instance_mats,
            lod_alternates,
        });
    }

    // unreferenced meshes (e.g. a standalone room): identity model matrix, slot 0.
    // These are drawn unconditionally; culling is disabled via the sentinel AABB.
    for mesh_handle in 0..mesh_geometry.len() {
        if referenced.contains(&mesh_handle) {
            continue;
        }
        if let Some((
            vertex_offset,
            vertex_count,
            index_offset,
            index_count,
            lod_alternates,
            _,
            _,
        )) = append_mesh(mesh_handle)
        {
            // Auto-rendered unreferenced meshes (e.g. a standalone room mesh)
            // are non-cullable, so distance-keyed LOD swaps make no sense
            // here. Drop any alternates the build emitted; the LOD0 draw is
            // the only one that will fire.
            let _ = lod_alternates;
            mesh_handle_to_draws
                .entry(mesh_handle)
                .or_default()
                .push(draw_objects.len());
            draw_objects.push(DrawObject {
                vertex_offset,
                vertex_count,
                index_offset,
                index_count,
                base_vertex: 0,
                geometry_generation: 0,
                model: IDENTITY4,
                texture_slot: 0,
                normal_map_slot: NO_NORMAL_MAP_SLOT,
                material: MaterialUniforms::DEFAULT,
                shader_bucket: 0,
                visible: true,
                resident: true,
                bb_min: UNCULLED_BB.0,
                bb_max: UNCULLED_BB.1,
                cull_distance: 0.0,
                lod_alternates: Vec::new(),
            });
        }
    }

    // Room components placed at the world origin with optional texture.
    // Rooms also opt out of culling (they enclose the camera). LOD picks
    // come from camera-to-origin distance per [`crate::gfx::lod::camera_distance`]'s
    // sentinel-AABB fallback, so practical swaps only fire if the camera
    // wanders far from the world origin.
    for (room, verts, idxs, room_lods) in room_geometry {
        let vertex_byte_offset = all_vertices.len() * std::mem::size_of::<Vertex>();
        let index_elem_offset = all_indices.len();
        let base = all_vertices.len() as u32;
        all_vertices.extend_from_slice(verts);
        all_indices.extend(idxs.iter().map(|i| u32::from(*i) + base));
        let lod_slices = append_lod_slices(&mut all_indices, room_lods, base);
        // A room's texture carries its cook-assigned `TextureHandle`, whose
        // value is the texture's slot in the albedo pool. An out-of-range handle
        // (an unresolved generator name) falls back to slot 0, as before.
        let texture_slot = match room.effective_texture() {
            None => 0,
            Some(handle) => {
                let slot = handle.index();
                if slot < texture_count { slot } else { 0 }
            }
        };
        draw_objects.push(DrawObject {
            vertex_offset: vertex_byte_offset,
            vertex_count: verts.len(),
            index_offset: index_elem_offset,
            index_count: idxs.len(),
            base_vertex: 0,
            geometry_generation: 0,
            model: IDENTITY4,
            texture_slot,
            normal_map_slot: NO_NORMAL_MAP_SLOT,
            material: MaterialUniforms::DEFAULT,
            shader_bucket: 0,
            visible: true,
            resident: true,
            bb_min: UNCULLED_BB.0,
            bb_max: UNCULLED_BB.1,
            cull_distance: 0.0,
            lod_alternates: lod_slices,
        });
    }

    Some(DrawListData {
        vertices: all_vertices,
        indices: all_indices,
        draw_objects,
        instanced_clusters,
        prop_draw_indices,
        mesh_handle_to_draws,
        prop_local_bounds,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::components::Prop;
    use crate::ecs::TextureHandle;
    use crate::gfx::render_types::NO_ALBEDO_SLOT;

    fn make_prop(position: [f32; 3]) -> Prop {
        Prop {
            asset_id: AssetId::default(),
            model: None,
            mesh: None,
            material: None,
            texture: None,
            position,
            rotation_deg: [0.0, 0.0, 0.0],
            scale: [1.0, 1.0, 1.0],
            collider: None,
            interactable: false,
            pickup: false,
            parent: None,
            scene: None,
            prefab: String::new(),
            cull_distance: 0.0,
            is_held: false,
        }
    }

    fn unit_quad_mesh() -> LoadedMesh {
        // Axis-aligned unit cube centred at origin; bounds = [-0.5, 0.5]^3.
        let mk = |x, y, z| Vertex {
            pos: [x, y, z],
            normal: [0.0, 1.0, 0.0],
            tangent: [1.0, 0.0, 0.0],
            color: [1.0, 1.0, 1.0],
            uv: [0.0, 0.0],
        };
        let v = vec![
            mk(-0.5, -0.5, -0.5),
            mk(0.5, -0.5, -0.5),
            mk(0.5, 0.5, -0.5),
            mk(-0.5, 0.5, -0.5),
        ];
        let i = vec![0u16, 1, 2, 0, 2, 3];
        LoadedMesh {
            vertices: v,
            indices: i,
            lod_alternates: Vec::new(),
            bounds: None,
            counts: None,
        }
    }

    #[test]
    fn build_draw_list_emits_one_cluster_for_instanced_prop() {
        let mesh_geometry = vec![unit_quad_mesh()];

        let inst = crate::components::InstancedProp {
            asset_id: AssetId::default(),
            mesh: Some(MeshHandle(0)),
            material: None,
            texture: None,
            cull_distance: 0.0,
            instances: vec![
                crate::components::InstanceTransform {
                    position: [0.0, 0.0, 0.0],
                    rotation_deg: [0.0; 3],
                    scale: [1.0; 3],
                },
                crate::components::InstanceTransform {
                    position: [5.0, 0.0, 0.0],
                    rotation_deg: [0.0; 3],
                    scale: [1.0; 3],
                },
                crate::components::InstanceTransform {
                    position: [-3.0, 0.0, 2.0],
                    rotation_deg: [0.0; 3],
                    scale: [1.0; 3],
                },
            ],
        };

        let data = build_draw_list(DrawListInputs {
            items: &[],
            instanced_props: &[inst],
            world_mats: &[],
            model_map: &std::collections::HashMap::new(),
            mesh_geometry: &mesh_geometry,
            room_geometry: &[],
            texture_count: 0,
            material_map: &std::collections::HashMap::new(),
            always_resident_meshes: &std::collections::HashSet::new(),
        })
        .expect("build_draw_list");
        let DrawListData {
            vertices: verts,
            indices: idxs,
            draw_objects,
            instanced_clusters: clusters,
            mesh_handle_to_draws,
            ..
        } = data;

        // Cluster mesh appended exactly once into the shared buffers.
        assert_eq!(verts.len(), 4);
        assert_eq!(idxs.len(), 6);
        // InstancedProp meshes go into clusters, not draw_objects; the
        // hot-reload map (which only tracks draw_objects-backed pushes) stays
        // empty for this scene.
        assert!(mesh_handle_to_draws.is_empty());

        // Each instance no longer emits its own DrawObject; the cluster carries
        // every transform.
        assert!(draw_objects.is_empty());
        assert_eq!(clusters.len(), 1);
        let c = &clusters[0];
        assert_eq!(c.instances.len(), 3);
        assert_eq!(c.index_count, 6);

        // Union AABB over all per-instance world AABBs. The unit_quad_mesh
        // is planar at z=-0.5, so each instance contributes a flat slab in z;
        // x and y span the quad extent [-0.5, 0.5].
        assert!((c.cluster_bb_min[0] - (-3.5)).abs() < 1e-5);
        assert!((c.cluster_bb_max[0] - 5.5).abs() < 1e-5);
        assert!((c.cluster_bb_min[1] - (-0.5)).abs() < 1e-5);
        assert!((c.cluster_bb_max[1] - 0.5).abs() < 1e-5);
        // z: instances at z=0 give [-0.5,-0.5]; instance at z=2 gives [1.5,1.5];
        // union is [-0.5, 1.5].
        assert!((c.cluster_bb_min[2] - (-0.5)).abs() < 1e-5);
        assert!((c.cluster_bb_max[2] - 1.5).abs() < 1e-5);
    }

    #[test]
    fn build_draw_list_skips_empty_instanced_prop() {
        let mesh_geometry = vec![unit_quad_mesh()];

        let inst = crate::components::InstancedProp {
            asset_id: AssetId::default(),
            mesh: Some(MeshHandle(0)),
            material: None,
            texture: None,
            cull_distance: 0.0,
            instances: Vec::new(),
        };

        let data = build_draw_list(DrawListInputs {
            items: &[],
            instanced_props: &[inst],
            world_mats: &[],
            model_map: &std::collections::HashMap::new(),
            mesh_geometry: &mesh_geometry,
            room_geometry: &[],
            texture_count: 0,
            material_map: &std::collections::HashMap::new(),
            always_resident_meshes: &std::collections::HashSet::new(),
        })
        .expect("build_draw_list");
        let DrawListData {
            draw_objects,
            instanced_clusters: clusters,
            ..
        } = data;

        assert!(draw_objects.is_empty());
        assert!(clusters.is_empty());
    }

    #[test]
    fn always_resident_mesh_forces_uncullable_bb_on_static_prop() {
        // A static prop with no dynamic flags would normally get a finite AABB
        // and be picked up by the streamer's `obj.cullable()` selection. When
        // its mesh is in the always_resident_meshes set (e.g. the auto-generated
        // skybox), the bb is forced to NaN so the prop opts out of frustum
        // culling and of mesh streaming. This is what the StreamingConfig
        // docstring promises for the skybox.
        let mesh_geometry = vec![unit_quad_mesh()];

        // A single static mesh-backed item referencing the always-resident mesh.
        let items = vec![RenderableItem {
            asset_id: AssetId(0),
            model: None,
            mesh: Some(MeshHandle(0)),
            material: None,
            texture: None,
            cull_distance: 0.0,
            is_dynamic: false,
        }];
        let world_mats = vec![IDENTITY4];

        let mut always_resident = std::collections::HashSet::new();
        always_resident.insert(0usize);

        let data = build_draw_list(DrawListInputs {
            items: &items,
            instanced_props: &[],
            world_mats: &world_mats,
            model_map: &std::collections::HashMap::new(),
            mesh_geometry: &mesh_geometry,
            room_geometry: &[],
            texture_count: 0,
            material_map: &std::collections::HashMap::new(),
            always_resident_meshes: &always_resident,
        })
        .expect("build_draw_list");
        let DrawListData { draw_objects, .. } = data;

        assert_eq!(draw_objects.len(), 1);
        // UNCULLED_BB is all-NaN; `cullable()` returns false in that case.
        assert!(draw_objects[0].bb_min[0].is_nan());
        assert!(draw_objects[0].bb_max[0].is_nan());
        assert!(!draw_objects[0].cullable());
    }

    // The item built from a mesh entity's components reads the renderer fields
    // from MeshRenderer and marks the entity dynamic from its Pickup / Collider
    // tags.
    #[test]
    fn decomposed_renderable_item_matches_a_mesh_prop() {
        use crate::blob::BlobData;
        use crate::components::{Collider, MeshRenderer, Pickup, PropCollider};
        use crate::ecs::{ComponentStorage, PipelineContext, Resources};
        use crate::gfx::profile::FrameProfile;

        let mut prop = make_prop([0.0; 3]);
        prop.asset_id = AssetId(7);
        prop.mesh = Some(MeshHandle(10));
        prop.material = Some(MaterialHandle(20));
        prop.cull_distance = 50.0;
        prop.pickup = true;
        prop.collider = Some(PropCollider::default());

        let mut components = ComponentStorage::default();
        let mut blob = BlobData::empty();
        let mut profile = FrameProfile::default();
        let mut resources = Resources::new();
        let scratch = crate::ecs::Arena::with_capacity(64 * 1024);
        let mut ctx = PipelineContext {
            components: &mut components,
            blob: &mut blob,
            profile: &mut profile,
            resources: &mut resources,
            frame: crate::ecs::FrameContext::new(&scratch),
        };

        let e = ctx.components.spawn();
        ctx.insert(
            e,
            MeshRenderer {
                mesh: prop.mesh,
                material: prop.material,
                texture: prop.texture,
                cull_distance: prop.cull_distance,
            },
        );
        ctx.insert(e, Pickup);
        ctx.insert(e, Collider(prop.collider.clone().unwrap()));

        let item = decomposed_renderable_item(&ctx, e, prop.asset_id);
        assert_eq!(
            item,
            RenderableItem {
                asset_id: AssetId(7),
                model: None,
                mesh: Some(MeshHandle(10)),
                material: Some(MaterialHandle(20)),
                texture: None,
                cull_distance: 50.0,
                is_dynamic: true,
            }
        );
    }

    fn mesh_item(mesh: AssetId) -> RenderableItem {
        RenderableItem {
            asset_id: mesh,
            model: None,
            // A `.mesh` handle indexes the dense geometry slice directly, so a
            // test item's handle is the geometry index it draws.
            mesh: Some(MeshHandle(mesh.0)),
            material: None,
            texture: None,
            cull_distance: 0.0,
            is_dynamic: false,
        }
    }

    fn model_item(model: AssetId) -> RenderableItem {
        RenderableItem {
            asset_id: model,
            model: Some(model),
            mesh: None,
            material: None,
            texture: None,
            cull_distance: 0.0,
            is_dynamic: false,
        }
    }

    // The model path emits one draw object per sub-mesh, each over its own
    // geometry region, and records both draws under the shared prop index.
    #[test]
    fn build_draw_list_model_emits_one_draw_per_submesh() {
        let mesh_geometry = vec![unit_quad_mesh(), unit_quad_mesh()];

        let mut model_map = std::collections::HashMap::new();
        model_map.insert(
            AssetId(1),
            vec![
                SubMeshRef {
                    mesh: Some(MeshHandle(0)),
                    material: Some(MaterialHandle(20)),
                },
                SubMeshRef {
                    mesh: Some(MeshHandle(1)),
                    material: None,
                },
            ],
        );

        let mut material_map = std::collections::HashMap::new();
        material_map.insert(
            MaterialHandle(20),
            MaterialEntry {
                albedo_slot: 3,
                normal_map_slot: 4,
                uniforms: MaterialUniforms::DEFAULT,
                shader_bucket: 0,
            },
        );

        let data = build_draw_list(DrawListInputs {
            items: &[model_item(AssetId(1))],
            instanced_props: &[],
            world_mats: &[IDENTITY4],
            model_map: &model_map,
            mesh_geometry: &mesh_geometry,
            room_geometry: &[],
            texture_count: 0,
            material_map: &material_map,
            always_resident_meshes: &std::collections::HashSet::new(),
        })
        .expect("build_draw_list");
        let DrawListData {
            vertices: verts,
            indices: idxs,
            draw_objects,
            instanced_clusters: clusters,
            prop_draw_indices: prop_idxs,
            mesh_handle_to_draws,
            ..
        } = data;

        assert!(clusters.is_empty());
        // Two sub-meshes -> two draws, both belonging to the one prop.
        assert_eq!(draw_objects.len(), 2);
        assert_eq!(prop_idxs, vec![vec![0, 1]]);
        assert_eq!(verts.len(), 8, "each quad's 4 verts appended once");
        assert_eq!(idxs.len(), 12);
        // First sub-mesh took its material's albedo/normal slots; the second
        // used the default (white, flat normal).
        assert_eq!(draw_objects[0].texture_slot, 3);
        assert_eq!(draw_objects[0].normal_map_slot, 4);
        assert_eq!(draw_objects[1].texture_slot, NO_ALBEDO_SLOT);
        assert_eq!(draw_objects[1].normal_map_slot, NO_NORMAL_MAP_SLOT);
        // Hot-reload map tracks each sub-mesh id -> its draw slot.
        assert_eq!(mesh_handle_to_draws.get(&0), Some(&vec![0]));
        assert_eq!(mesh_handle_to_draws.get(&1), Some(&vec![1]));
    }

    // A mesh present in the geometry table but referenced by no item, model, or
    // instanced prop is auto-rendered at the origin with culling disabled.
    #[test]
    fn build_draw_list_auto_renders_unreferenced_mesh() {
        let mesh_geometry = vec![unit_quad_mesh()];

        let data = build_draw_list(DrawListInputs {
            items: &[],
            instanced_props: &[],
            world_mats: &[],
            model_map: &std::collections::HashMap::new(),
            mesh_geometry: &mesh_geometry,
            room_geometry: &[],
            texture_count: 0,
            material_map: &std::collections::HashMap::new(),
            always_resident_meshes: &std::collections::HashSet::new(),
        })
        .expect("build_draw_list");
        let DrawListData {
            draw_objects,
            prop_draw_indices: prop_idxs,
            mesh_handle_to_draws,
            ..
        } = data;

        assert!(prop_idxs.is_empty(), "no props drove this draw");
        assert_eq!(draw_objects.len(), 1);
        let d = &draw_objects[0];
        assert_eq!(d.model, IDENTITY4);
        assert_eq!(d.texture_slot, 0);
        assert!(!d.cullable(), "unreferenced mesh draws unconditionally");
        assert!(d.lod_alternates.is_empty());
        assert_eq!(mesh_handle_to_draws.get(&0), Some(&vec![0]));
    }

    // A Room is placed at the origin with culling disabled; its cook-assigned
    // texture handle is used directly as its albedo pool slot and its LOD
    // alternates carry through.
    #[test]
    fn build_draw_list_places_room_at_origin_with_texture_and_lods() {
        let room = Room {
            asset_id: AssetId(50),
            half_width: 8.0,
            half_depth: 10.0,
            ceiling_height: 3.5,
            texture: Some(TextureHandle(6)),
            wall_texture: None,
            floor_texture: None,
            ceiling_texture: None,
            locator: None,
        };
        let verts = unit_quad_mesh().vertices;
        let idxs = vec![0u16, 1, 2, 0, 2, 3];
        let room_lods = vec![(12.0_f32, vec![0u16, 1, 2])];
        let room_geometry = vec![(room, verts, idxs, room_lods)];

        // Handle 6 must land inside the pool; a 7-texture pool (slots 0..=6)
        // makes it the last valid slot.
        let data = build_draw_list(DrawListInputs {
            items: &[],
            instanced_props: &[],
            world_mats: &[],
            model_map: &std::collections::HashMap::new(),
            mesh_geometry: &[],
            room_geometry: &room_geometry,
            texture_count: 7,
            material_map: &std::collections::HashMap::new(),
            always_resident_meshes: &std::collections::HashSet::new(),
        })
        .expect("build_draw_list");
        let DrawListData {
            vertices: rv,
            indices: ri,
            draw_objects,
            ..
        } = data;

        assert_eq!(draw_objects.len(), 1);
        let d = &draw_objects[0];
        assert_eq!(d.model, IDENTITY4);
        assert_eq!(d.texture_slot, 6, "room texture resolved to its slot");
        assert!(!d.cullable(), "rooms enclose the camera and skip culling");
        assert_eq!(d.lod_alternates.len(), 1);
        assert_eq!(d.lod_alternates[0].switch_distance, 12.0);
        // LOD0 (6) + one alternate (3) indices appended after the 4 verts.
        assert_eq!(rv.len(), 4);
        assert_eq!(ri.len(), 9);
    }

    // A single-mesh item with a texture (and no material) resolves the texture
    // slot and keeps the default material.
    #[test]
    fn build_draw_list_single_mesh_resolves_texture_slot() {
        let mesh_geometry = vec![unit_quad_mesh()];
        // The texture handle is the pool slot directly; the pool size (3) makes
        // slot 2 in range.
        let item = RenderableItem {
            asset_id: AssetId(0),
            model: None,
            mesh: Some(MeshHandle(0)),
            material: None,
            texture: Some(TextureHandle(2)),
            cull_distance: 0.0,
            is_dynamic: false,
        };

        let data = build_draw_list(DrawListInputs {
            items: &[item],
            instanced_props: &[],
            world_mats: &[IDENTITY4],
            model_map: &std::collections::HashMap::new(),
            mesh_geometry: &mesh_geometry,
            room_geometry: &[],
            texture_count: 3,
            material_map: &std::collections::HashMap::new(),
            always_resident_meshes: &std::collections::HashSet::new(),
        })
        .expect("build_draw_list");
        let DrawListData { draw_objects, .. } = data;

        assert_eq!(draw_objects.len(), 1);
        assert_eq!(draw_objects[0].texture_slot, 2);
        assert_eq!(draw_objects[0].normal_map_slot, NO_NORMAL_MAP_SLOT);
    }

    // Every missing-reference branch returns None (the error is logged and the
    // build aborts) rather than emitting a partial draw list.
    #[test]
    fn build_draw_list_returns_none_on_missing_references() {
        let mesh = || vec![unit_quad_mesh()];
        let none = |inputs: DrawListInputs| build_draw_list(inputs).is_none();

        // Model referenced by an item but absent from the model_map.
        assert!(none(DrawListInputs {
            items: &[model_item(AssetId(1))],
            instanced_props: &[],
            world_mats: &[IDENTITY4],
            model_map: &std::collections::HashMap::new(),
            mesh_geometry: &mesh(),
            room_geometry: &[],
            texture_count: 0,
            material_map: &std::collections::HashMap::new(),
            always_resident_meshes: &std::collections::HashSet::new(),
        }));

        // Model sub-mesh with no mesh field.
        let mut model_no_mesh = std::collections::HashMap::new();
        model_no_mesh.insert(
            AssetId(1),
            vec![SubMeshRef {
                mesh: None,
                material: None,
            }],
        );
        assert!(none(DrawListInputs {
            items: &[model_item(AssetId(1))],
            instanced_props: &[],
            world_mats: &[IDENTITY4],
            model_map: &model_no_mesh,
            mesh_geometry: &mesh(),
            room_geometry: &[],
            texture_count: 0,
            material_map: &std::collections::HashMap::new(),
            always_resident_meshes: &std::collections::HashSet::new(),
        }));

        // Model sub-mesh whose mesh id has no geometry.
        let mut model_bad_geo = std::collections::HashMap::new();
        model_bad_geo.insert(
            AssetId(1),
            vec![SubMeshRef {
                mesh: Some(MeshHandle(999)),
                material: None,
            }],
        );
        assert!(none(DrawListInputs {
            items: &[model_item(AssetId(1))],
            instanced_props: &[],
            world_mats: &[IDENTITY4],
            model_map: &model_bad_geo,
            mesh_geometry: &mesh(),
            room_geometry: &[],
            texture_count: 0,
            material_map: &std::collections::HashMap::new(),
            always_resident_meshes: &std::collections::HashSet::new(),
        }));

        // Model sub-mesh referencing a material absent from the material_map.
        let mut model_bad_mat = std::collections::HashMap::new();
        model_bad_mat.insert(
            AssetId(1),
            vec![SubMeshRef {
                mesh: Some(MeshHandle(0)),
                material: Some(MaterialHandle(404)),
            }],
        );
        assert!(none(DrawListInputs {
            items: &[model_item(AssetId(1))],
            instanced_props: &[],
            world_mats: &[IDENTITY4],
            model_map: &model_bad_mat,
            mesh_geometry: &mesh(),
            room_geometry: &[],
            texture_count: 0,
            material_map: &std::collections::HashMap::new(),
            always_resident_meshes: &std::collections::HashSet::new(),
        }));

        // Single-mesh item whose mesh id has no geometry.
        assert!(none(DrawListInputs {
            items: &[mesh_item(AssetId(999))],
            instanced_props: &[],
            world_mats: &[IDENTITY4],
            model_map: &std::collections::HashMap::new(),
            mesh_geometry: &mesh(),
            room_geometry: &[],
            texture_count: 0,
            material_map: &std::collections::HashMap::new(),
            always_resident_meshes: &std::collections::HashSet::new(),
        }));

        // Single-mesh item referencing a material absent from the material_map.
        let mut item_bad_mat = mesh_item(AssetId(0));
        item_bad_mat.material = Some(MaterialHandle(404));
        assert!(none(DrawListInputs {
            items: &[item_bad_mat],
            instanced_props: &[],
            world_mats: &[IDENTITY4],
            model_map: &std::collections::HashMap::new(),
            mesh_geometry: &mesh(),
            room_geometry: &[],
            texture_count: 0,
            material_map: &std::collections::HashMap::new(),
            always_resident_meshes: &std::collections::HashSet::new(),
        }));

        // Item carrying neither a model nor a mesh.
        assert!(none(DrawListInputs {
            items: &[RenderableItem {
                asset_id: AssetId(0),
                model: None,
                mesh: None,
                material: None,
                texture: None,
                cull_distance: 0.0,
                is_dynamic: false,
            }],
            instanced_props: &[],
            world_mats: &[IDENTITY4],
            model_map: &std::collections::HashMap::new(),
            mesh_geometry: &mesh(),
            room_geometry: &[],
            texture_count: 0,
            material_map: &std::collections::HashMap::new(),
            always_resident_meshes: &std::collections::HashSet::new(),
        }));

        // InstancedProp mesh id has no geometry.
        let inst_bad_mesh = InstancedProp {
            asset_id: AssetId::default(),
            mesh: Some(MeshHandle(999)),
            material: None,
            texture: None,
            cull_distance: 0.0,
            instances: vec![crate::components::InstanceTransform::default()],
        };
        assert!(none(DrawListInputs {
            items: &[],
            instanced_props: &[inst_bad_mesh],
            world_mats: &[],
            model_map: &std::collections::HashMap::new(),
            mesh_geometry: &mesh(),
            room_geometry: &[],
            texture_count: 0,
            material_map: &std::collections::HashMap::new(),
            always_resident_meshes: &std::collections::HashSet::new(),
        }));

        // InstancedProp material absent from the material_map.
        let inst_bad_mat = InstancedProp {
            asset_id: AssetId::default(),
            mesh: Some(MeshHandle(0)),
            material: Some(MaterialHandle(404)),
            texture: None,
            cull_distance: 0.0,
            instances: vec![crate::components::InstanceTransform::default()],
        };
        assert!(none(DrawListInputs {
            items: &[],
            instanced_props: &[inst_bad_mat],
            world_mats: &[],
            model_map: &std::collections::HashMap::new(),
            mesh_geometry: &mesh(),
            room_geometry: &[],
            texture_count: 0,
            material_map: &std::collections::HashMap::new(),
            always_resident_meshes: &std::collections::HashSet::new(),
        }));
    }

    // Accumulates components + a single blob section so load_mesh_geometry /
    // load_room_geometry can decode in-memory payloads, mirroring the
    // GraphicsSystem WorldBuilder precedent.
    struct BlobWorld {
        components: crate::ecs::ComponentStorage,
        section: Vec<u8>,
    }

    struct SealedWorld {
        components: crate::ecs::ComponentStorage,
        blob: crate::blob::BlobData,
        profile: crate::gfx::profile::FrameProfile,
        resources: crate::ecs::Resources,
        scratch: crate::ecs::Arena,
    }

    impl BlobWorld {
        fn new() -> Self {
            Self {
                components: crate::ecs::ComponentStorage::default(),
                section: Vec::new(),
            }
        }

        fn payload(&mut self, bytes: &[u8]) -> crate::ecs::PayloadLocator {
            let offset = self.section.len() as u64;
            self.section.extend_from_slice(bytes);
            crate::ecs::PayloadLocator {
                blob_index: 0,
                offset,
                len: bytes.len() as u64,
            }
        }

        fn push<C: crate::ecs::ComponentSlot>(&mut self, c: C) {
            self.components.push_typed(c);
        }

        fn seal(self) -> SealedWorld {
            SealedWorld {
                components: self.components,
                blob: crate::blob::BlobData::new(vec![Some(self.section)]),
                profile: crate::gfx::profile::FrameProfile::default(),
                resources: crate::ecs::Resources::new(),
                scratch: crate::ecs::Arena::with_capacity(64 * 1024),
            }
        }
    }

    impl SealedWorld {
        fn ctx(&mut self) -> crate::ecs::PipelineContext<'_> {
            crate::ecs::PipelineContext {
                components: &mut self.components,
                blob: &mut self.blob,
                profile: &mut self.profile,
                resources: &mut self.resources,
                frame: crate::ecs::FrameContext::new(&self.scratch),
            }
        }

        // Install a `MeshTable` with one entry per locator (handle == index),
        // standing in for the blob resource stream a real build provides.
        fn with_mesh_table(
            mut self,
            locators: Vec<Option<crate::ecs::PayloadLocator>>,
        ) -> SealedWorld {
            let entries = locators
                .into_iter()
                .map(|payload| crate::resource::ResourceEntry {
                    payload,
                    data_bytes: Vec::new(),
                })
                .collect();
            self.resources.insert(crate::resource::MeshTable(entries));
            self
        }
    }

    // A single-triangle static mesh payload in the compiled format.
    fn tri_payload() -> Vec<u8> {
        let v = |x: f32, z: f32| {
            (
                [x, 0.0, z],
                [0.0, 1.0, 0.0],
                [1.0, 0.0, 0.0],
                [1.0, 1.0, 1.0],
                [0.0, 0.0],
            )
        };
        crate::gfx::mesh_payload::serialise(&[v(0.0, 0.0), v(1.0, 0.0), v(0.0, 1.0)], &[0u16, 1, 2])
    }

    // load_mesh_geometry decodes a MeshTable entry's in-memory payload into the
    // dense geometry table at its handle.
    #[test]
    fn load_mesh_geometry_decodes_in_memory_mesh() {
        let mut b = BlobWorld::new();
        let loc = b.payload(&tri_payload());
        let mut world = b.seal().with_mesh_table(vec![Some(loc)]);
        let mut ctx = world.ctx();

        let (geometry, sources, resident, component_handles, _deferred) =
            load_mesh_geometry(&mut ctx, &DeferredMeshSources::default(), false).expect("decoded");
        assert_eq!(geometry.len(), 1);
        let m = &geometry[0];
        assert_eq!(m.vertices.len(), 3);
        assert_eq!(m.indices, vec![0, 1, 2]);
        assert!(m.lod_alternates.is_empty());
        // No component-backed producers in this world.
        assert!(component_handles.is_empty());
        // The source-capture map only fills under the dev-flag global, which the
        // tests never set, so it stays empty here.
        assert!(sources.is_empty());
        assert!(
            resident.is_empty(),
            "no skybox mesh -> nothing always-resident"
        );
    }

    // A deferred Mesh skips its decode: empty geometry with the baked bounds,
    // and its payload seed (locator + RAM bytes) is captured for the streamer.
    #[test]
    fn load_mesh_geometry_defers_scene_owned_mesh_with_baked_bounds() {
        let mut b = BlobWorld::new();
        let loc = b.payload(&tri_payload());
        let mut world = b.seal().with_mesh_table(vec![Some(loc)]);
        let mut ctx = world.ctx();

        let mut deferred = DeferredMeshSources::default();
        deferred.by_handle.insert(0);
        deferred
            .bounds
            .insert(0, ([-1.0, -2.0, -3.0], [1.0, 2.0, 3.0]));

        let (geometry, _sources, _resident, _handles, seeds) =
            load_mesh_geometry(&mut ctx, &deferred, false).expect("ok");
        assert_eq!(geometry.len(), 1);
        assert!(geometry[0].vertices.is_empty(), "decode skipped");
        assert_eq!(
            geometry[0].bounds,
            Some(([-1.0, -2.0, -3.0], [1.0, 2.0, 3.0]))
        );
        let seed = seeds.get(&0).expect("payload seed captured");
        assert!(
            seed.bytes.as_deref().is_some_and(|b| !b.is_empty()),
            "RAM-backed seed carries the payload bytes"
        );
    }

    // A deferred member with no baked bounds record decodes eagerly.
    #[test]
    fn load_mesh_geometry_decodes_eagerly_without_baked_bounds() {
        let mut b = BlobWorld::new();
        let loc = b.payload(&tri_payload());
        let mut world = b.seal().with_mesh_table(vec![Some(loc)]);
        let mut ctx = world.ctx();

        let mut deferred = DeferredMeshSources::default();
        deferred.by_handle.insert(0);

        let (geometry, _sources, _resident, _handles, seeds) =
            load_mesh_geometry(&mut ctx, &deferred, false).expect("ok");
        assert_eq!(geometry[0].vertices.len(), 3, "no bounds record -> decode");
        assert!(seeds.is_empty());
    }

    // A skybox ProceduralMesh decodes and is marked always-resident so its props
    // opt out of culling and streaming.
    #[test]
    fn load_mesh_geometry_marks_skybox_always_resident() {
        let mut b = BlobWorld::new();
        let loc = b.payload(&tri_payload());
        b.push(ProceduralMesh {
            asset_id: AssetId(2),
            generator: "skybox".to_string(),
            locator: Some(loc),
            ..Default::default()
        });
        let mut world = b.seal();
        let mut ctx = world.ctx();

        let (geometry, _sources, resident, component_handles, _deferred) =
            load_mesh_geometry(&mut ctx, &DeferredMeshSources::default(), false).expect("decoded");
        // The lone component-backed producer got the first handle.
        assert_eq!(component_handles.get(&AssetId(2)), Some(&0));
        assert_eq!(geometry.len(), 1);
        assert!(resident.contains(&0), "skybox generator stays resident");
    }

    // Geometry the world baked for itself at start loads from the payload map
    // rather than a locator, and lands past every handle the build assigned.
    #[test]
    fn load_mesh_geometry_loads_the_baked_block_last() {
        let mut b = BlobWorld::new();
        let compiled = b.payload(&tri_payload());
        // One compiled ProceduralMesh (handle 1, after the Mesh block) and one
        // baked at start.
        b.push(ProceduralMesh {
            asset_id: AssetId(2),
            generator: "box".to_string(),
            locator: Some(compiled.clone()),
            ..Default::default()
        });
        b.push(ProceduralMesh {
            asset_id: AssetId(3),
            generator: "skybox".to_string(),
            ..Default::default()
        });
        let mut world = b.seal().with_mesh_table(vec![Some(compiled)]);
        let mut payloads = concinnity_core::resource::RuntimeMeshPayloads::default();
        payloads.0.insert(AssetId(3), tri_payload());
        world.resources.insert(payloads);
        let mut ctx = world.ctx();

        let (geometry, _sources, resident, component_handles, _deferred) =
            load_mesh_geometry(&mut ctx, &DeferredMeshSources::default(), false).expect("decoded");
        assert_eq!(geometry.len(), 3);
        assert_eq!(component_handles.get(&AssetId(2)), Some(&1));
        assert_eq!(
            component_handles.get(&AssetId(3)),
            Some(&2),
            "the baked mesh trails the compiled blocks"
        );
        assert_eq!(geometry[2].vertices.len(), 3, "the baked payload decoded");
        assert!(resident.contains(&2), "a baked skybox stays resident too");
    }

    // A mesh baked at start whose payload never reached the map aborts the
    // load, the way a missing compiled payload does.
    #[test]
    fn load_mesh_geometry_baked_mesh_without_a_payload_returns_none() {
        let mut b = BlobWorld::new();
        b.push(ProceduralMesh {
            asset_id: AssetId(3),
            generator: "skybox".to_string(),
            ..Default::default()
        });
        let mut world = b.seal();
        let mut ctx = world.ctx();
        assert!(load_mesh_geometry(&mut ctx, &DeferredMeshSources::default(), false).is_none());
    }

    // A Mesh with no compiled payload aborts the whole load.
    #[test]
    fn load_mesh_geometry_missing_locator_returns_none() {
        let mut world = BlobWorld::new().seal().with_mesh_table(vec![None]);
        let mut ctx = world.ctx();
        assert!(load_mesh_geometry(&mut ctx, &DeferredMeshSources::default(), false).is_none());
    }

    // A malformed payload (too short to hold its declared vertices) aborts.
    #[test]
    fn load_mesh_geometry_malformed_payload_returns_none() {
        let mut b = BlobWorld::new();
        // Claims one vertex but carries no vertex bytes.
        let loc = b.payload(&1u32.to_le_bytes());
        let mut world = b.seal().with_mesh_table(vec![Some(loc)]);
        let mut ctx = world.ctx();
        assert!(load_mesh_geometry(&mut ctx, &DeferredMeshSources::default(), false).is_none());
    }

    // An empty world (no mesh sources at all) still succeeds with empty maps.
    #[test]
    fn load_mesh_geometry_empty_world_is_ok_and_empty() {
        let mut world = BlobWorld::new().seal();
        let mut ctx = world.ctx();
        let (geometry, sources, resident, component_handles, _deferred) =
            load_mesh_geometry(&mut ctx, &DeferredMeshSources::default(), false).expect("ok");
        assert!(geometry.is_empty() && sources.is_empty() && resident.is_empty());
        assert!(component_handles.is_empty());
    }

    fn test_room(locator: Option<crate::ecs::PayloadLocator>) -> Room {
        Room {
            asset_id: AssetId(50),
            half_width: 8.0,
            half_depth: 10.0,
            ceiling_height: 3.5,
            texture: None,
            wall_texture: None,
            floor_texture: None,
            ceiling_texture: None,
            locator,
        }
    }

    // load_room_geometry decodes each Room payload and reports its blob index.
    #[test]
    fn load_room_geometry_decodes_in_memory_room() {
        let mut b = BlobWorld::new();
        let loc = b.payload(&tri_payload());
        b.push(test_room(Some(loc)));
        let mut world = b.seal();
        let mut ctx = world.ctx();

        let (room_geometry, blob_indices) = load_room_geometry(&mut ctx).expect("decoded");
        assert_eq!(room_geometry.len(), 1);
        let (_room, verts, idxs, _lods) = &room_geometry[0];
        assert_eq!(verts.len(), 3);
        assert_eq!(*idxs, vec![0, 1, 2]);
        assert_eq!(blob_indices, vec![0]);
    }

    // A Room with no compiled payload aborts the load.
    #[test]
    fn load_room_geometry_missing_locator_returns_none() {
        let mut b = BlobWorld::new();
        b.push(test_room(None));
        let mut world = b.seal();
        let mut ctx = world.ctx();
        assert!(load_room_geometry(&mut ctx).is_none());
    }

    // Same for a model entity: ModelRenderer fields, and with no dynamic tags the
    // item is static.
    #[test]
    fn decomposed_renderable_item_matches_a_model_prop() {
        use crate::blob::BlobData;
        use crate::components::ModelRenderer;
        use crate::ecs::{ComponentStorage, PipelineContext, Resources};
        use crate::gfx::profile::FrameProfile;

        let mut prop = make_prop([0.0; 3]);
        prop.asset_id = AssetId(8);
        prop.model = Some(AssetId(100));
        prop.cull_distance = 30.0;

        let mut components = ComponentStorage::default();
        let mut blob = BlobData::empty();
        let mut profile = FrameProfile::default();
        let mut resources = Resources::new();
        let scratch = crate::ecs::Arena::with_capacity(64 * 1024);
        let mut ctx = PipelineContext {
            components: &mut components,
            blob: &mut blob,
            profile: &mut profile,
            resources: &mut resources,
            frame: crate::ecs::FrameContext::new(&scratch),
        };

        let e = ctx.components.spawn();
        ctx.insert(
            e,
            ModelRenderer {
                model: prop.model.unwrap(),
                cull_distance: prop.cull_distance,
            },
        );

        let item = decomposed_renderable_item(&ctx, e, prop.asset_id);
        assert_eq!(
            item,
            RenderableItem {
                asset_id: AssetId(8),
                model: Some(AssetId(100)),
                mesh: None,
                material: None,
                texture: None,
                cull_distance: 30.0,
                is_dynamic: false,
            }
        );
    }
}