sky_ecs 0.1.0

Chunk-based ECS core for Sky
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
use super::commands::InsertValue;
use super::resource::Resources;
use super::*;
use crate::ecs::entity::{EntityLocation, EntityRecord};
use crate::ecs::system::{GroupBuilder, Schedule, TickPolicy};
use crate::ecs::time::Time;
use crate::ecs::{component_type, ComponentType};
use crate::plugin::{Plugin, PluginError, PluginRegistry, PluginResult};
use rustc_hash::FxHashMap;
use smallvec::SmallVec;
use std::cell::Cell;
use std::ptr::NonNull;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct TransitionKey {
    archetype: Archetype,
    component_id: usize,
    add: bool,
}

struct TransitionPlan {
    copy_spans: SmallVec<[(usize, usize, usize); MAX_COMPONENTS]>,
    target_component_offset: Option<usize>,
    target_data_index: Cell<Option<usize>>,
}

/// The central container for all ECS data.
///
/// A `World` owns every entity, component, and resource.  It provides methods
/// for spawning and despawning entities, reading and writing components,
/// scheduling systems, and running queries.
///
/// # Drop Semantics
///
/// When a `World` is dropped, all component destructors are called
/// automatically.  Non-`Copy` components (e.g. `String`, `Vec<T>`) are
/// handled correctly.
///
/// # Examples
///
/// ```
/// use sky_ecs::World;
///
/// #[derive(Clone, Copy)]
/// struct Position { x: f32, y: f32 }
///
/// let mut world = World::new();
/// let entity = world.spawn((Position { x: 0.0, y: 0.0 },));
/// assert_eq!(world.get::<Position>(entity).unwrap().x, 0.0);
/// ```
pub struct World {
    pub time: Time,
    pub(crate) data: Vec<Data>,
    archetype_epoch: usize,
    archetype_to_data_index: FxHashMap<Archetype, usize>,
    transitions: FxHashMap<TransitionKey, Box<TransitionPlan>>,
    entities: Vec<EntityRecord>,
    free_entities: Vec<u32>,
    resources: Resources,
    plugins: PluginRegistry,
    schedule: Option<Schedule>,
}

impl Default for World {
    fn default() -> Self {
        Self::new()
    }
}

impl World {
    /// Creates an empty world with no entities, resources, or systems.
    pub fn new() -> Self {
        Self {
            time: Time::default(),
            data: Vec::new(),
            archetype_epoch: 0,
            archetype_to_data_index: FxHashMap::default(),
            transitions: FxHashMap::default(),
            entities: Vec::new(),
            free_entities: Vec::new(),
            resources: Resources::default(),
            plugins: PluginRegistry::default(),
            schedule: Some(Schedule::default()),
        }
    }

    /// Install an engine module plugin into this world.
    ///
    /// Plugin constructors are the configuration surface; installing a plugin
    /// records only the fact that the plugin type is present.  The app runner
    /// discovers capabilities from the resources/plugins that were installed
    /// rather than enforcing a fixed required set.
    pub fn install<P>(&mut self, plugin: P) -> PluginResult
    where
        P: Plugin + 'static,
    {
        let name = plugin.name();
        if let Some(existing) = self.plugins.get::<P>() {
            return Err(PluginError::new(
                name,
                format!("{existing} is already installed"),
            ));
        }
        plugin.install(self)?;
        if let Err(existing) = self.plugins.insert::<P>(name) {
            return Err(PluginError::new(
                name,
                format!("{existing} was installed during plugin setup"),
            ));
        }
        Ok(())
    }

    /// Returns `true` if plugin type `P` was installed through [`World::install`].
    #[inline]
    pub fn has_plugin<P: 'static>(&self) -> bool {
        self.plugins.contains::<P>()
    }

    /// Require plugin type `P` to have been installed.
    ///
    /// Plugins should use this for local hard dependencies.  The app runner
    /// does not use it to impose a universal set of required capabilities.
    pub fn require_plugin<P: 'static>(&self, plugin: &'static str) -> PluginResult {
        if self.has_plugin::<P>() {
            Ok(())
        } else {
            Err(PluginError::new(
                plugin,
                format!("requires {}", std::any::type_name::<P>()),
            ))
        }
    }

    // -----------------------------------------------------------------------
    // Schedule API
    // -----------------------------------------------------------------------

    /// Returns a `GroupBuilder` for the named system group.
    ///
    /// Groups execute in creation order during [`tick`](Self::tick).
    /// If the group already exists, the builder appends to it.
    pub fn group(&mut self, name: &str) -> GroupBuilder<'_> {
        let schedule = self
            .schedule
            .as_mut()
            .expect("cannot modify schedule during tick");
        let index = schedule.find_or_create_group(name);
        GroupBuilder::new(schedule, index)
    }

    /// Advances the world by one frame using wall-clock time.
    ///
    /// On the first call, delta is 0.  Subsequent calls measure elapsed time
    /// since the previous tick.  The measured delta is stored in
    /// [`Time::raw_delta`], while [`Time::frame_delta`] is affected by
    /// [`Time::time_scale`].
    ///
    /// # Panics
    ///
    /// Panics if called recursively (e.g. from within a running system).
    pub fn tick(&mut self) {
        let mut schedule = self.schedule.take().expect("cannot call tick recursively");

        let now = std::time::Instant::now();
        let raw_delta = match schedule.last_tick {
            Some(last) => (now - last).as_secs_f32(),
            None => 0.0,
        };
        schedule.last_tick = Some(now);

        self.run_schedule(&mut schedule, raw_delta, raw_delta);

        self.schedule = Some(schedule);
    }

    /// Advances the world by the given delta (in seconds).
    ///
    /// Useful for deterministic tests and fixed-step simulations.  The given
    /// delta is treated as both raw and clamped frame time.
    ///
    /// # Panics
    ///
    /// Panics if called recursively.
    pub fn tick_with_delta(&mut self, delta: f32) {
        self.tick_with_frame_delta(delta, delta);
    }

    /// Advances the world by a clamped frame delta and the raw real delta.
    ///
    /// App runners should use this when they clamp large frame deltas before
    /// simulation but still want [`Time::raw_delta`] and
    /// [`Time::raw_elapsed`] to reflect real elapsed time.
    ///
    /// # Panics
    ///
    /// Panics if called recursively.
    pub fn tick_with_frame_delta(&mut self, frame_delta: f32, raw_delta: f32) {
        let mut schedule = self.schedule.take().expect("cannot call tick recursively");

        self.run_schedule(&mut schedule, frame_delta, raw_delta);

        self.schedule = Some(schedule);
    }

    fn run_schedule(&mut self, schedule: &mut Schedule, frame_delta: f32, raw_delta: f32) {
        #[cfg(feature = "profile")]
        let _schedule_scope = sky_profile::profile_scope!("ecs", "World::run_schedule");

        let raw_delta = raw_delta.max(0.0);
        let frame_delta = frame_delta.max(0.0);
        let scaled_delta = frame_delta * self.time.time_scale;
        self.time.raw_delta = raw_delta;
        self.time.frame_delta = scaled_delta;
        self.time.delta = scaled_delta;
        self.time.frame_count += 1;

        for group in &mut schedule.groups {
            #[cfg(feature = "profile")]
            let _group_scope = sky_profile::profile_scope!("ecs", format!("group:{}", group.name));

            match group.tick_policy {
                TickPolicy::EveryFrame => {
                    self.time.delta = scaled_delta;
                    for registered in &mut group.systems {
                        #[cfg(feature = "profile")]
                        let _system_scope = sky_profile::profile_scope!(
                            "ecs",
                            format!("system:{}", registered.name)
                        );

                        if !registered.initialized {
                            registered.system.init(self);
                            registered.initialized = true;
                        }
                        registered.system.run(self);
                    }
                }
                TickPolicy::Fixed(fixed_dt) => {
                    group.accumulator += scaled_delta;
                    self.time.delta = fixed_dt;
                    let mut substep_index = 0u32;
                    while group.accumulator >= fixed_dt {
                        #[cfg(feature = "profile")]
                        let _substep_scope = sky_profile::profile_scope!(
                            "ecs",
                            format!("fixed_substep:{}#{substep_index}", group.name)
                        );

                        for registered in &mut group.systems {
                            #[cfg(feature = "profile")]
                            let _system_scope = sky_profile::profile_scope!(
                                "ecs",
                                format!("system:{}", registered.name)
                            );

                            if !registered.initialized {
                                registered.system.init(self);
                                registered.initialized = true;
                            }
                            registered.system.run(self);
                        }
                        group.accumulator -= fixed_dt;
                        substep_index = substep_index.wrapping_add(1);
                    }
                }
            }
        }

        self.time.delta = self.time.frame_delta;
        self.time.elapsed += scaled_delta;
        self.time.raw_elapsed += raw_delta;
    }

    /// Tears down all initialised systems in reverse order.
    ///
    /// Call this before dropping the world if your systems need a clean
    /// shutdown (e.g. flushing buffers, releasing external resources).
    pub fn shutdown(&mut self) {
        let mut schedule = self.schedule.take().expect("cannot shutdown during tick");

        for group in schedule.groups.iter_mut().rev() {
            for registered in group.systems.iter_mut().rev() {
                if registered.initialized {
                    registered.system.teardown(self);
                    registered.initialized = false;
                }
            }
        }

        self.schedule = Some(schedule);
    }

    fn allocate_entity(&mut self) -> EntityId {
        if let Some(index) = self.free_entities.pop() {
            let record = &self.entities[index as usize];
            EntityId::new(index, record.generation)
        } else {
            let index = self.entities.len() as u32;
            self.entities.push(EntityRecord {
                generation: 0,
                location: None,
            });
            EntityId::new(index, 0)
        }
    }

    #[inline(always)]
    fn ensure_data_index(&mut self, archetype: Archetype) -> usize {
        if let Some(index) = self.archetype_to_data_index.get(&archetype).copied() {
            return index;
        }

        let index = self.data.len();
        self.data.push(Data::new(archetype));
        self.archetype_to_data_index.insert(archetype, index);
        self.archetype_epoch += 1;
        index
    }

    #[inline(always)]
    fn entity_location(&self, entity: EntityId) -> Option<EntityLocation> {
        let record = self.entities.get(entity.index() as usize)?;
        if record.generation != entity.generation() {
            return None;
        }

        record.location
    }

    #[inline(always)]
    pub(crate) fn set_entity_location(&mut self, entity: EntityId, location: EntityLocation) {
        let record = &mut self.entities[entity.index() as usize];
        debug_assert_eq!(record.generation, entity.generation());
        record.location = Some(location);
    }

    /// Adds an entity in `archetype` without initializing component columns.
    ///
    /// # Safety
    ///
    /// The caller must initialize every component column before the entity can
    /// be observed, migrated, removed, or dropped.
    pub(crate) unsafe fn add_entity(&mut self, archetype: Archetype) -> EntityId {
        let entity = self.allocate_entity();
        let data_index = self.ensure_data_index(archetype);
        let location = unsafe { self.data[data_index].add_entity(entity) };
        self.set_entity_location(
            entity,
            EntityLocation {
                data_index,
                chunk_index: location.chunk_index,
                entity_index: location.entity_index,
            },
        );
        entity
    }

    /// Spawns a new entity with the given component bundle.
    ///
    /// Returns the [`EntityId`] of the newly created entity.  The bundle
    /// type is typically a tuple of components:
    ///
    /// ```
    /// # use sky_ecs::World;
    /// # #[derive(Clone, Copy)] struct Pos { x: f32, y: f32 }
    /// # #[derive(Clone, Copy)] struct Vel { x: f32, y: f32 }
    /// # let mut world = World::new();
    /// let entity = world.spawn((Pos { x: 0.0, y: 0.0 }, Vel { x: 1.0, y: 2.0 }));
    /// ```
    pub fn spawn<B: Bundle>(&mut self, bundle: B) -> EntityId {
        let (archetype, columns) = B::cached_meta();
        let entity = self.allocate_entity();
        let data_index = self.ensure_data_index(archetype);
        let location = unsafe { self.data[data_index].add_entity(entity) };
        self.set_entity_location(
            entity,
            EntityLocation {
                data_index,
                chunk_index: location.chunk_index,
                entity_index: location.entity_index,
            },
        );

        let chunk = &mut self.data[data_index].chunks[location.chunk_index];
        unsafe {
            bundle.write_fast(chunk, location.entity_index, columns);
        }

        entity
    }

    /// Spawns multiple entities from an iterator of bundles.
    ///
    /// More efficient than calling [`spawn`](Self::spawn) in a loop because
    /// the archetype lookup and entity record allocation are amortised.
    pub fn spawn_batch<B: Bundle>(&mut self, bundles: impl IntoIterator<Item = B>) {
        let mut iter = bundles.into_iter();
        let (lower, _) = iter.size_hint();
        let Some(first) = iter.next() else {
            return;
        };

        let (archetype, columns) = B::cached_meta();
        let data_index = self.ensure_data_index(archetype);

        // Pre-reserve entity record storage to avoid per-entity Vec reallocation.
        if lower > 0 {
            self.entities.reserve(lower);
        }

        for bundle in std::iter::once(first).chain(iter) {
            let entity = self.allocate_entity();
            let location = unsafe { self.data[data_index].add_entity(entity) };
            self.set_entity_location(
                entity,
                EntityLocation {
                    data_index,
                    chunk_index: location.chunk_index,
                    entity_index: location.entity_index,
                },
            );

            let chunk = &mut self.data[data_index].chunks[location.chunk_index];
            unsafe {
                bundle.write_fast(chunk, location.entity_index, columns);
            }
        }
    }

    pub(crate) fn spawn_dynamic_values(
        &mut self,
        values: &mut [crate::ecs::dynamic::ErasedComponentValue],
    ) -> Result<EntityId, crate::ecs::dynamic::DynamicSpawnError> {
        for (index, value) in values.iter().enumerate() {
            for other in &values[(index + 1)..] {
                if value.component.id() == other.component.id() {
                    return Err(crate::ecs::dynamic::DynamicSpawnError::DuplicateComponent {
                        component: value.component,
                    });
                }
            }
        }

        let mut builder = create_archetype();
        for value in values.iter() {
            builder = builder.add_component(value.component);
        }
        let archetype = builder.build();

        let entity = unsafe { self.add_entity(archetype) };
        let location = self
            .entity_location(entity)
            .expect("fresh dynamic entity must have a location");
        let chunk = &mut self.data[location.data_index].chunks[location.chunk_index];

        for value in values {
            let component_index = archetype
                .query_component_index(&value.component)
                .expect("dynamic component must exist in target archetype");
            let ptr = unsafe {
                chunk
                    .column_ptr(component_index)
                    .add(location.entity_index * value.component.size)
            };
            value.value.write(ptr);
        }

        Ok(entity)
    }

    /// Returns `true` if `entity` is alive in this world.
    pub fn contains(&self, entity: EntityId) -> bool {
        self.entity_location(entity).is_some()
    }

    /// Iterates all live entities in dense storage order.
    ///
    /// Entity IDs are runtime-local handles. Systems that need persistent
    /// document identity should store their own stable component alongside
    /// these IDs.
    pub fn entities(&self) -> impl Iterator<Item = EntityId> + '_ {
        self.data
            .iter()
            .flat_map(|data| data.chunks.iter())
            .flat_map(|chunk| chunk.entities().iter().copied())
    }

    /// Inserts a singleton resource, returning the previous value if one existed.
    pub fn insert_resource<R: 'static>(&mut self, resource: R) -> Option<R> {
        self.resources.insert(resource)
    }

    /// Returns an immutable reference to resource `R`, or `None`.
    pub fn get_resource<R: 'static>(&self) -> Option<&R> {
        self.resources.get::<R>()
    }

    /// Returns a mutable reference to resource `R`, or `None`.
    pub fn get_resource_mut<R: 'static>(&mut self) -> Option<&mut R> {
        self.resources.get_mut::<R>()
    }

    /// Returns `true` if the world contains resource `R`.
    pub fn contains_resource<R: 'static>(&self) -> bool {
        self.resources.contains::<R>()
    }

    /// Removes and returns resource `R`, or `None` if not present.
    pub fn remove_resource<R: 'static>(&mut self) -> Option<R> {
        self.resources.remove::<R>()
    }

    /// Returns `true` if `entity` is alive and has component `T`.
    #[inline(always)]
    pub fn has<T: 'static>(&self, entity: EntityId) -> bool {
        let Some(location) = self.entity_location(entity) else {
            return false;
        };

        self.data[location.data_index]
            .archetype
            .has_component(&component_type::<T>())
    }

    /// Destroys an entity and drops all its components.
    ///
    /// Returns `true` if the entity existed and was removed,
    /// or `false` if the entity ID was stale or invalid.
    pub fn despawn(&mut self, entity: EntityId) -> bool {
        let Some(location) = self.entity_location(entity) else {
            return false;
        };

        // Safety: location is valid and the entity is about to be destroyed.
        // We must drop its components before the swap-remove overwrites the slot.
        unsafe {
            self.data[location.data_index].chunks[location.chunk_index]
                .drop_entity_components(location.entity_index);
        }

        let moved = self.data[location.data_index].remove_entity(ChunkEntityLocation {
            chunk_index: location.chunk_index,
            entity_index: location.entity_index,
        });

        let record = &mut self.entities[entity.index() as usize];
        record.location = None;
        record.generation = record.generation.wrapping_add(1);
        self.free_entities.push(entity.index());

        if let Some((moved_entity, moved_location)) = moved {
            self.set_entity_location(
                moved_entity,
                EntityLocation {
                    data_index: location.data_index,
                    chunk_index: moved_location.chunk_index,
                    entity_index: moved_location.entity_index,
                },
            );
        }

        true
    }

    /// Returns a shared reference to component `T` on `entity`.
    ///
    /// Returns `None` if the entity is dead or does not have `T`.
    #[inline(always)]
    pub fn get<T: 'static>(&self, entity: EntityId) -> Option<&T> {
        let location = self.entity_location(entity)?;
        let data = &self.data[location.data_index];
        let chunk = &data.chunks[location.chunk_index];
        let component_index = chunk
            .archetype
            .query_component_index(&component_type::<T>())?;

        Some(unsafe {
            let ptr = chunk
                .column_ptr(component_index)
                .add(location.entity_index * std::mem::size_of::<T>());
            &*(ptr as *const T)
        })
    }

    /// Returns an exclusive reference to component `T` on `entity`.
    ///
    /// Returns `None` if the entity is dead or does not have `T`.
    #[inline(always)]
    pub fn get_mut<T: 'static>(&mut self, entity: EntityId) -> Option<&mut T> {
        let location = self.entity_location(entity)?;
        let data = &mut self.data[location.data_index];
        let chunk = &mut data.chunks[location.chunk_index];
        let component_index = chunk
            .archetype
            .query_component_index(&component_type::<T>())?;

        Some(unsafe {
            let ptr = chunk
                .column_ptr(component_index)
                .add(location.entity_index * std::mem::size_of::<T>());
            &mut *(ptr as *mut T)
        })
    }

    fn archetype_with_component(base: Archetype, component: ComponentType) -> Archetype {
        let mut builder = create_archetype();
        for existing in &base.components {
            builder = builder.add_component(*existing);
        }
        builder.add_component(component).build()
    }

    fn archetype_without_component(base: Archetype, component: ComponentType) -> Option<Archetype> {
        if !base.has_component(&component) {
            return None;
        }

        let mut builder = create_archetype();
        for existing in &base.components {
            if existing.id() != component.id() {
                builder = builder.add_component(*existing);
            }
        }

        Some(builder.build())
    }

    /// Build copy-span descriptors for transitioning entity data from `source`
    /// to `target`.  Components whose type-id appears in `skip_component_ids`
    /// are excluded (used by insert-batches to avoid copying the newly-inserted
    /// column).  Pass `&[]` when no components should be skipped.
    fn build_copy_spans(
        source: &Data,
        target: &Data,
        skip_component_ids: &[usize],
    ) -> SmallVec<[(usize, usize, usize); MAX_COMPONENTS]> {
        let mut spans = SmallVec::new();

        for (source_index, component) in source.archetype.components.iter().enumerate() {
            if skip_component_ids.iter().any(|id| *id == component.id()) {
                continue;
            }

            let Some(target_index) = target.archetype.query_component_index(component) else {
                continue;
            };
            spans.push((
                source.layout.column_offset(source_index),
                target.layout.column_offset(target_index),
                component.size,
            ));
        }

        spans
    }

    fn transition_plan(
        &mut self,
        source_data_index: usize,
        component: ComponentType,
        add: bool,
    ) -> Option<NonNull<TransitionPlan>> {
        let base = self.data[source_data_index].archetype;
        let key = TransitionKey {
            archetype: base,
            component_id: component.id(),
            add,
        };

        if let Some(plan) = self.transitions.get(&key) {
            return Some(NonNull::from(plan.as_ref()));
        }

        let plan = if add {
            if base.has_component(&component) {
                return None;
            }

            let target_archetype = Self::archetype_with_component(base, component);
            let target_data_index = self.ensure_data_index(target_archetype);
            let target_component_offset = {
                let target_index = target_archetype.query_component_index(&component).unwrap();
                self.data[target_data_index]
                    .layout
                    .column_offset(target_index)
            };
            TransitionPlan {
                copy_spans: Self::build_copy_spans(
                    &self.data[source_data_index],
                    &self.data[target_data_index],
                    &[],
                ),
                target_component_offset: Some(target_component_offset),
                target_data_index: Cell::new(Some(target_data_index)),
            }
        } else {
            let target_archetype = Self::archetype_without_component(base, component)?;
            let target_data_index = self.ensure_data_index(target_archetype);
            TransitionPlan {
                copy_spans: Self::build_copy_spans(
                    &self.data[source_data_index],
                    &self.data[target_data_index],
                    &[],
                ),
                target_component_offset: None,
                target_data_index: Cell::new(Some(target_data_index)),
            }
        };

        let entry = self
            .transitions
            .entry(key)
            .or_insert_with(|| Box::new(plan));
        Some(NonNull::from(entry.as_ref()))
    }

    pub(crate) fn copy_components_with_spans(
        source: &Chunk,
        source_entity_index: usize,
        target: &mut Chunk,
        target_entity_index: usize,
        spans: &[(usize, usize, usize)],
    ) {
        let source_base = source.data_ptr();
        let target_base = target.data_ptr();

        for &(source_offset, target_offset, component_size) in spans {
            unsafe {
                std::ptr::copy_nonoverlapping(
                    source_base.add(source_offset + source_entity_index * component_size),
                    target_base.add(target_offset + target_entity_index * component_size),
                    component_size,
                );
            }
        }
    }

    /// Adds or overwrites component `T` on `entity`.
    ///
    /// If the entity already has `T`, the old value is dropped and replaced
    /// in-place (no archetype migration).  If the entity does not have `T`,
    /// it is migrated to a new archetype that includes `T`.
    ///
    /// Returns `false` if the entity does not exist.
    pub fn insert<T: 'static>(&mut self, entity: EntityId, component: T) -> bool {
        let Some(source_location) = self.entity_location(entity) else {
            return false;
        };

        let component_ty = component_type::<T>();
        let source_archetype = self.data[source_location.data_index].archetype;

        // Overwrite path: entity already has this component.
        if source_archetype.has_component(&component_ty) {
            let component_index = source_archetype
                .query_component_index(&component_ty)
                .unwrap();
            let chunk =
                &mut self.data[source_location.data_index].chunks[source_location.chunk_index];
            unsafe {
                let ptr = chunk
                    .column_ptr(component_index)
                    .add(source_location.entity_index * std::mem::size_of::<T>())
                    as *mut T;
                // Safety: ptr points to a valid, initialised T.
                // Drop the old value, then write the new one.
                std::ptr::drop_in_place(ptr);
                std::ptr::write(ptr, component);
            }
            return true;
        }

        let plan = self
            .transition_plan(source_location.data_index, component_ty, true)
            .expect("adding a missing component must produce a transition plan");
        let plan = unsafe { plan.as_ref() };
        let target_data_index = plan
            .target_data_index
            .get()
            .expect("transition plans must cache the target data index");
        let target_location = unsafe { self.data[target_data_index].add_entity(entity) };

        {
            let (source_chunk, target_chunk) = if source_location.data_index < target_data_index {
                let (left, right) = self.data.split_at_mut(target_data_index);
                (
                    &left[source_location.data_index].chunks[source_location.chunk_index],
                    &mut right[0].chunks[target_location.chunk_index],
                )
            } else {
                let (left, right) = self.data.split_at_mut(source_location.data_index);
                (
                    &right[0].chunks[source_location.chunk_index],
                    &mut left[target_data_index].chunks[target_location.chunk_index],
                )
            };

            // Bitwise-copy existing columns to the new archetype chunk.
            // This is a semantic move: the source slot should NOT be dropped
            // for these columns.
            Self::copy_components_with_spans(
                source_chunk,
                source_location.entity_index,
                target_chunk,
                target_location.entity_index,
                &plan.copy_spans,
            );

            let component_offset = plan
                .target_component_offset
                .expect("add transition plans must include the inserted component offset");
            unsafe {
                let ptr = target_chunk.data_ptr().add(
                    component_offset + target_location.entity_index * std::mem::size_of::<T>(),
                );
                std::ptr::write(ptr as *mut T, component);
            }
        }

        self.set_entity_location(
            entity,
            EntityLocation {
                data_index: target_data_index,
                chunk_index: target_location.chunk_index,
                entity_index: target_location.entity_index,
            },
        );

        // Source entity data was bitwise-moved to target; the swap-remove
        // here only rearranges the source chunk — no drops needed.
        let moved = self.data[source_location.data_index].remove_entity(ChunkEntityLocation {
            chunk_index: source_location.chunk_index,
            entity_index: source_location.entity_index,
        });

        if let Some((moved_entity, moved_location)) = moved {
            self.set_entity_location(
                moved_entity,
                EntityLocation {
                    data_index: source_location.data_index,
                    chunk_index: moved_location.chunk_index,
                    entity_index: moved_location.entity_index,
                },
            );
        }

        true
    }

    /// Removes component `T` from `entity`, dropping it.
    ///
    /// The entity is migrated to a smaller archetype.  Returns `false` if
    /// the entity does not exist or does not have `T`.
    pub fn remove<T: 'static>(&mut self, entity: EntityId) -> bool {
        let Some(source_location) = self.entity_location(entity) else {
            return false;
        };

        let component_ty = component_type::<T>();
        let Some(plan) = self.transition_plan(source_location.data_index, component_ty, false)
        else {
            return false;
        };
        let plan = unsafe { plan.as_ref() };

        let target_data_index = plan
            .target_data_index
            .get()
            .expect("transition plans must cache the target data index");
        let target_location = unsafe { self.data[target_data_index].add_entity(entity) };

        {
            let (source_chunk, target_chunk) = if source_location.data_index < target_data_index {
                let (left, right) = self.data.split_at_mut(target_data_index);
                (
                    &left[source_location.data_index].chunks[source_location.chunk_index],
                    &mut right[0].chunks[target_location.chunk_index],
                )
            } else {
                let (left, right) = self.data.split_at_mut(source_location.data_index);
                (
                    &right[0].chunks[source_location.chunk_index],
                    &mut left[target_data_index].chunks[target_location.chunk_index],
                )
            };

            // Bitwise-copy kept columns to target (semantic move).
            Self::copy_components_with_spans(
                source_chunk,
                source_location.entity_index,
                target_chunk,
                target_location.entity_index,
                &plan.copy_spans,
            );

            // Drop the removed component column from the source entity.
            // Safety: source_location is valid and this column is being
            // discarded (not copied to the target archetype).
            if let Some(removed_component_index) =
                source_chunk.archetype.query_component_index(&component_ty)
            {
                unsafe {
                    source_chunk.drop_single_component(
                        removed_component_index,
                        source_location.entity_index,
                    );
                }
            }
        }

        self.set_entity_location(
            entity,
            EntityLocation {
                data_index: target_data_index,
                chunk_index: target_location.chunk_index,
                entity_index: target_location.entity_index,
            },
        );

        // Source entity data was bitwise-moved (kept columns) and dropped
        // (removed column); the swap-remove only rearranges the chunk.
        let moved = self.data[source_location.data_index].remove_entity(ChunkEntityLocation {
            chunk_index: source_location.chunk_index,
            entity_index: source_location.entity_index,
        });

        if let Some((moved_entity, moved_location)) = moved {
            self.set_entity_location(
                moved_entity,
                EntityLocation {
                    data_index: source_location.data_index,
                    chunk_index: moved_location.chunk_index,
                    entity_index: moved_location.entity_index,
                },
            );
        }

        true
    }

    pub(crate) fn insert_dynamic(
        &mut self,
        entity: EntityId,
        component: ComponentType,
        value: &mut InsertValue,
    ) -> bool {
        let Some(source_location) = self.entity_location(entity) else {
            return false;
        };

        let source_archetype = self.data[source_location.data_index].archetype;

        if source_archetype.has_component(&component) {
            let component_index = source_archetype.query_component_index(&component).unwrap();
            let data = &mut self.data[source_location.data_index];
            let chunk = &mut data.chunks[source_location.chunk_index];
            let ptr = unsafe {
                chunk
                    .column_ptr(component_index)
                    .add(source_location.entity_index * component.size)
            };
            // Safety: drop the old value before overwriting.
            if let Some(drop_fn) = component.drop_fn() {
                unsafe {
                    drop_fn(ptr);
                }
            }
            value.write(ptr);
            return true;
        }

        let plan = self
            .transition_plan(source_location.data_index, component, true)
            .expect("adding a missing component must produce a transition plan");
        let plan = unsafe { plan.as_ref() };
        let target_data_index = plan
            .target_data_index
            .get()
            .expect("transition plans must cache the target data index");
        let target_location = unsafe { self.data[target_data_index].add_entity(entity) };

        {
            let (source_chunk, target_chunk) = if source_location.data_index < target_data_index {
                let (left, right) = self.data.split_at_mut(target_data_index);
                (
                    &left[source_location.data_index].chunks[source_location.chunk_index],
                    &mut right[0].chunks[target_location.chunk_index],
                )
            } else {
                let (left, right) = self.data.split_at_mut(source_location.data_index);
                (
                    &right[0].chunks[source_location.chunk_index],
                    &mut left[target_data_index].chunks[target_location.chunk_index],
                )
            };

            Self::copy_components_with_spans(
                source_chunk,
                source_location.entity_index,
                target_chunk,
                target_location.entity_index,
                &plan.copy_spans,
            );

            let component_offset = plan
                .target_component_offset
                .expect("add transition plans must include the inserted component offset");
            let ptr = unsafe {
                target_chunk
                    .data_ptr()
                    .add(component_offset + target_location.entity_index * component.size)
            };
            value.write(ptr);
        }

        self.set_entity_location(
            entity,
            EntityLocation {
                data_index: target_data_index,
                chunk_index: target_location.chunk_index,
                entity_index: target_location.entity_index,
            },
        );

        let moved = self.data[source_location.data_index].remove_entity(ChunkEntityLocation {
            chunk_index: source_location.chunk_index,
            entity_index: source_location.entity_index,
        });

        if let Some((moved_entity, moved_location)) = moved {
            self.set_entity_location(
                moved_entity,
                EntityLocation {
                    data_index: source_location.data_index,
                    chunk_index: moved_location.chunk_index,
                    entity_index: moved_location.entity_index,
                },
            );
        }

        true
    }

    pub(crate) fn remove_dynamic(&mut self, entity: EntityId, component: ComponentType) -> bool {
        let Some(source_location) = self.entity_location(entity) else {
            return false;
        };

        let Some(plan) = self.transition_plan(source_location.data_index, component, false) else {
            return false;
        };
        let plan = unsafe { plan.as_ref() };

        let target_data_index = plan
            .target_data_index
            .get()
            .expect("transition plans must cache the target data index");
        let target_location = unsafe { self.data[target_data_index].add_entity(entity) };

        {
            let (source_chunk, target_chunk) = if source_location.data_index < target_data_index {
                let (left, right) = self.data.split_at_mut(target_data_index);
                (
                    &left[source_location.data_index].chunks[source_location.chunk_index],
                    &mut right[0].chunks[target_location.chunk_index],
                )
            } else {
                let (left, right) = self.data.split_at_mut(source_location.data_index);
                (
                    &right[0].chunks[source_location.chunk_index],
                    &mut left[target_data_index].chunks[target_location.chunk_index],
                )
            };

            Self::copy_components_with_spans(
                source_chunk,
                source_location.entity_index,
                target_chunk,
                target_location.entity_index,
                &plan.copy_spans,
            );

            // Drop the removed component from the source entity.
            if let Some(removed_component_index) =
                source_chunk.archetype.query_component_index(&component)
            {
                unsafe {
                    source_chunk.drop_single_component(
                        removed_component_index,
                        source_location.entity_index,
                    );
                }
            }
        }

        self.set_entity_location(
            entity,
            EntityLocation {
                data_index: target_data_index,
                chunk_index: target_location.chunk_index,
                entity_index: target_location.entity_index,
            },
        );

        let moved = self.data[source_location.data_index].remove_entity(ChunkEntityLocation {
            chunk_index: source_location.chunk_index,
            entity_index: source_location.entity_index,
        });

        if let Some((moved_entity, moved_location)) = moved {
            self.set_entity_location(
                moved_entity,
                EntityLocation {
                    data_index: source_location.data_index,
                    chunk_index: moved_location.chunk_index,
                    entity_index: moved_location.entity_index,
                },
            );
        }

        true
    }

    pub(crate) fn archetype_epoch(&self) -> usize {
        self.archetype_epoch
    }

    /// Returns the total number of live entities across all archetypes.
    pub fn entity_count(&self) -> usize {
        self.data
            .iter()
            .map(|d| d.chunks.iter().map(|c| c.entity_count).sum::<usize>())
            .sum()
    }

    /// Returns the number of distinct archetypes currently stored.
    pub fn archetype_count(&self) -> usize {
        self.data.len()
    }

    /// Removes all entities and their components, but keeps resources.
    ///
    /// Component destructors are called for every live entity.
    pub fn clear(&mut self) {
        self.data.clear();
        self.archetype_to_data_index.clear();
        self.transitions.clear();
        self.free_entities.clear();
        for (index, record) in self.entities.iter_mut().enumerate() {
            if record.location.is_some() {
                record.generation = record.generation.wrapping_add(1);
                record.location = None;
            }
            self.free_entities.push(index as u32);
        }
        self.archetype_epoch += 1;
    }

    /// Creates a typed, cached query.
    ///
    /// The query parameter `Q` is usually a reference (`&T`), a mutable
    /// reference (`&mut T`), an optional (`Option<&T>`), or a tuple of
    /// those.  The returned [`PreparedQuery`] caches matched archetypes
    /// and refreshes automatically when the world's archetype set changes.
    ///
    /// # Examples
    ///
    /// ```
    /// # use sky_ecs::World;
    /// # #[derive(Clone, Copy)] struct Pos { x: f32, y: f32 }
    /// # #[derive(Clone, Copy)] struct Vel { x: f32, y: f32 }
    /// # let mut world = World::new();
    /// # world.spawn((Pos { x: 0.0, y: 0.0 }, Vel { x: 1.0, y: 0.0 }));
    /// let mut query = world.query::<(&mut Pos, &Vel)>();
    /// query.for_each(&mut world, |(pos, vel)| {
    ///     pos.x += vel.x;
    /// });
    /// ```
    pub fn query<Q>(&self) -> PreparedQuery<Q>
    where
        Q: QuerySpec,
    {
        PreparedQuery::new()
    }

    /// Creates a typed, cached query with an archetype filter.
    ///
    /// Filters narrow which archetypes are matched.  Use [`With<T>`] to
    /// require that `T` is present, or [`Without<T>`] to exclude it.
    /// Filter tuples combine with AND semantics.
    ///
    /// # Examples
    ///
    /// ```
    /// # use sky_ecs::{World, With};
    /// # #[derive(Clone, Copy)] struct Pos { x: f32, y: f32 }
    /// # #[derive(Clone, Copy)] struct Enemy;
    /// # let mut world = World::new();
    /// let mut enemies = world.query_filtered::<&Pos, With<Enemy>>();
    /// ```
    pub fn query_filtered<Q, Flt>(&self) -> PreparedQuery<Q, Flt>
    where
        Q: QuerySpec,
        Flt: QueryFilter,
    {
        PreparedQuery::new()
    }
}

#[cfg(test)]
mod tests {
    use super::{Commands, World};

    #[derive(Clone, Copy, Debug, PartialEq)]
    struct Position {
        x: f32,
        y: f32,
    }

    #[derive(Clone, Copy, Debug, PartialEq)]
    struct Velocity {
        x: f32,
        y: f32,
    }

    #[derive(Clone, Copy, Debug, PartialEq)]
    struct Tick(u64);

    #[allow(dead_code)]
    #[derive(Clone, Copy)]
    struct HugeState([u8; 16 * 1024]);

    #[derive(Clone, Copy, Debug, PartialEq)]
    struct Health(f32);

    #[derive(Clone, Copy, Debug, PartialEq)]
    struct Damage(f32);

    #[derive(Clone, Copy, Debug, PartialEq)]
    struct Marker;

    #[test]
    fn spawn_initializes_components_and_get_reads_them() {
        let mut world = World::new();
        let entity = world.spawn((Position { x: 1.0, y: 2.0 }, Velocity { x: 3.0, y: 4.0 }));

        assert_eq!(
            world.get::<Position>(entity),
            Some(&Position { x: 1.0, y: 2.0 })
        );
        assert_eq!(
            world.get::<Velocity>(entity),
            Some(&Velocity { x: 3.0, y: 4.0 })
        );
    }

    #[test]
    fn spawn_zero_sized_marker_component() {
        let mut world = World::new();
        let entity = world.spawn((Marker,));

        assert!(world.contains(entity));
        assert_eq!(world.entity_count(), 1);
        assert_eq!(world.get::<Marker>(entity), Some(&Marker));
    }

    #[test]
    fn spawn_batch_initializes_all_component_columns() {
        let mut world = World::new();
        let expected: Vec<_> = (0..128)
            .map(|i| {
                (
                    Position {
                        x: i as f32,
                        y: i as f32 + 0.5,
                    },
                    Velocity {
                        x: i as f32 * 2.0,
                        y: i as f32 * 2.0 + 1.0,
                    },
                )
            })
            .collect();

        world.spawn_batch(expected.iter().copied());

        let mut actual = Vec::new();
        let mut query = world.query::<(&Position, &Velocity)>();
        query.for_each(&mut world, |(position, velocity)| {
            actual.push((*position, *velocity));
        });
        actual.sort_by(|(left, _), (right, _)| left.x.total_cmp(&right.x));

        assert_eq!(actual, expected);
    }

    #[test]
    fn spawn_batch_empty_iterator_is_noop() {
        let mut world = World::new();

        world.spawn_batch(Vec::<(Position,)>::new());

        assert_eq!(world.entity_count(), 0);
        assert_eq!(world.archetype_count(), 0);
        let mut positions = world.query::<&Position>();
        assert!(positions.is_empty(&world));
        assert_eq!(positions.cached_archetype_count(), 0);
    }

    #[test]
    fn get_mut_updates_entity_component() {
        let mut world = World::new();
        let entity = world.spawn((Position { x: 1.0, y: 2.0 },));

        let position = world.get_mut::<Position>(entity).unwrap();
        position.x = 5.0;

        assert_eq!(world.get::<Position>(entity).unwrap().x, 5.0);
    }

    #[test]
    fn despawn_invalidates_entity_and_keeps_other_entities_accessible() {
        let mut world = World::new();
        let first = world.spawn((Position { x: 1.0, y: 2.0 },));
        let second = world.spawn((Position { x: 3.0, y: 4.0 },));

        assert!(world.despawn(first));
        assert!(!world.contains(first));
        assert_eq!(world.get::<Position>(first), None);
        assert_eq!(
            world.get::<Position>(second),
            Some(&Position { x: 3.0, y: 4.0 })
        );
    }

    #[test]
    fn insert_adds_new_component_and_keeps_existing_values() {
        let mut world = World::new();
        let entity = world.spawn((Position { x: 1.0, y: 2.0 },));

        assert!(world.insert(entity, Velocity { x: 3.0, y: 4.0 }));
        assert!(world.has::<Velocity>(entity));
        assert_eq!(
            world.get::<Position>(entity),
            Some(&Position { x: 1.0, y: 2.0 })
        );
        assert_eq!(
            world.get::<Velocity>(entity),
            Some(&Velocity { x: 3.0, y: 4.0 })
        );
    }

    #[test]
    fn remove_moves_entity_to_smaller_archetype() {
        let mut world = World::new();
        let entity = world.spawn((Position { x: 1.0, y: 2.0 }, Velocity { x: 3.0, y: 4.0 }));

        assert!(world.remove::<Velocity>(entity));
        assert!(!world.has::<Velocity>(entity));
        assert_eq!(
            world.get::<Position>(entity),
            Some(&Position { x: 1.0, y: 2.0 })
        );
        assert_eq!(world.get::<Velocity>(entity), None);
    }

    #[test]
    fn remove_can_leave_entity_with_only_zero_sized_component() {
        let mut world = World::new();
        let entity = world.spawn((Position { x: 1.0, y: 2.0 }, Marker));

        assert!(world.remove::<Position>(entity));
        assert!(world.contains(entity));
        assert!(!world.has::<Position>(entity));
        assert!(world.has::<Marker>(entity));
        assert_eq!(world.get::<Marker>(entity), Some(&Marker));
    }

    #[test]
    fn remove_last_component_leaves_empty_entity_alive() {
        let mut world = World::new();
        let entity = world.spawn((Position { x: 1.0, y: 2.0 },));

        assert!(world.remove::<Position>(entity));
        assert!(world.contains(entity));
        assert!(!world.has::<Position>(entity));
        assert_eq!(world.entity_count(), 1);
    }

    #[test]
    fn resources_can_be_inserted_read_mutated_and_removed() {
        let mut world = World::new();

        assert!(!world.contains_resource::<Tick>());
        assert_eq!(world.insert_resource(Tick(1)), None);
        assert!(world.contains_resource::<Tick>());
        assert_eq!(world.get_resource::<Tick>(), Some(&Tick(1)));

        world.get_resource_mut::<Tick>().unwrap().0 += 1;
        assert_eq!(world.get_resource::<Tick>(), Some(&Tick(2)));
        assert_eq!(world.remove_resource::<Tick>(), Some(Tick(2)));
        assert!(!world.contains_resource::<Tick>());
    }

    #[test]
    fn commands_apply_spawns_components_and_resources() {
        let mut world = World::new();
        let mut commands = Commands::new();

        commands.insert_resource(Tick(10));
        commands.spawn((Position { x: 7.0, y: 8.0 }, Velocity { x: 1.0, y: 2.0 }));
        commands.apply(&mut world);

        assert_eq!(world.get_resource::<Tick>(), Some(&Tick(10)));

        let mut count = 0usize;
        let mut query = world.query::<(&Position, &Velocity)>();
        query.for_each(&mut world, |(position, velocity)| {
            count += 1;
            assert_eq!(position, &Position { x: 7.0, y: 8.0 });
            assert_eq!(velocity, &Velocity { x: 1.0, y: 2.0 });
        });

        assert_eq!(count, 1);
    }

    #[test]
    fn commands_apply_entity_changes_in_order() {
        let mut world = World::new();
        let entity = world.spawn((Position { x: 1.0, y: 2.0 },));
        let mut commands = Commands::new();

        commands.insert(entity, Velocity { x: 3.0, y: 4.0 });
        commands.remove::<Velocity>(entity);
        commands.despawn(entity);
        commands.apply(&mut world);

        assert!(!world.contains(entity));
    }

    #[test]
    fn commands_coalesce_repeated_component_changes_per_entity() {
        let mut world = World::new();
        let entity = world.spawn((Position { x: 1.0, y: 2.0 },));
        let mut commands = Commands::new();

        commands.insert(entity, Velocity { x: 1.0, y: 1.0 });
        commands.insert(entity, Velocity { x: 5.0, y: 8.0 });
        commands.remove::<Velocity>(entity);
        commands.insert(entity, Velocity { x: 13.0, y: 21.0 });
        commands.apply(&mut world);

        assert_eq!(
            world.get::<Velocity>(entity),
            Some(&Velocity { x: 13.0, y: 21.0 })
        );
    }

    #[test]
    fn commands_ignore_component_changes_after_despawn() {
        let mut world = World::new();
        let entity = world.spawn((Position { x: 1.0, y: 2.0 },));
        let mut commands = Commands::new();

        commands.insert(entity, Velocity { x: 1.0, y: 1.0 });
        commands.despawn(entity);
        commands.insert(entity, Velocity { x: 5.0, y: 8.0 });
        commands.remove::<Position>(entity);
        commands.apply(&mut world);

        assert!(!world.contains(entity));
        assert_eq!(world.get::<Velocity>(entity), None);
        assert_eq!(world.get::<Position>(entity), None);
    }

    #[test]
    fn commands_keep_distinct_generations_with_same_entity_index_separate() {
        let mut world = World::new();
        let stale = world.spawn((Position { x: 1.0, y: 2.0 },));
        assert!(world.despawn(stale));
        let current = world.spawn((Position { x: 3.0, y: 4.0 },));
        assert_eq!(stale.index(), current.index());
        assert_ne!(stale.generation(), current.generation());

        let mut commands = Commands::new();
        commands.insert(stale, Velocity { x: 1.0, y: 1.0 });
        commands.insert(current, Velocity { x: 5.0, y: 8.0 });
        commands.apply(&mut world);

        assert_eq!(world.get::<Velocity>(stale), None);
        assert_eq!(
            world.get::<Velocity>(current),
            Some(&Velocity { x: 5.0, y: 8.0 })
        );
    }

    #[test]
    fn commands_batch_add_component_spans_multiple_chunks() {
        let mut world = World::new();
        let entities: Vec<_> = (0..40)
            .map(|i| {
                world.spawn((
                    HugeState([i as u8; 16 * 1024]),
                    Position {
                        x: i as f32,
                        y: i as f32 + 0.5,
                    },
                ))
            })
            .collect();

        let mut commands = Commands::new();
        for &entity in &entities {
            commands.insert(entity, Velocity { x: 3.0, y: 4.0 });
        }
        commands.apply(&mut world);

        for (i, &entity) in entities.iter().enumerate() {
            assert_eq!(
                world.get::<Position>(entity),
                Some(&Position {
                    x: i as f32,
                    y: i as f32 + 0.5,
                })
            );
            assert_eq!(
                world.get::<Velocity>(entity),
                Some(&Velocity { x: 3.0, y: 4.0 })
            );
        }
    }

    #[test]
    fn commands_batch_remove_component_keeps_moved_survivor_locations_valid() {
        let mut world = World::new();
        let entities: Vec<_> = (0..40)
            .map(|i| {
                world.spawn((
                    HugeState([i as u8; 16 * 1024]),
                    Position {
                        x: i as f32,
                        y: i as f32 + 0.5,
                    },
                    Velocity {
                        x: i as f32 * 10.0,
                        y: i as f32 * 10.0 + 1.0,
                    },
                ))
            })
            .collect();

        let mut commands = Commands::new();
        for &entity in &entities[..24] {
            commands.remove::<Velocity>(entity);
        }
        commands.apply(&mut world);

        for (i, &entity) in entities.iter().enumerate() {
            assert_eq!(
                world.get::<Position>(entity),
                Some(&Position {
                    x: i as f32,
                    y: i as f32 + 0.5,
                })
            );

            if i < 24 {
                assert_eq!(world.get::<Velocity>(entity), None);
            } else {
                assert_eq!(
                    world.get::<Velocity>(entity),
                    Some(&Velocity {
                        x: i as f32 * 10.0,
                        y: i as f32 * 10.0 + 1.0,
                    })
                );
            }
        }
    }

    #[test]
    fn commands_generic_batch_add_component_handles_multiple_targets_from_same_source() {
        let mut world = World::new();
        let entities: Vec<_> = (0..24)
            .map(|i| {
                world.spawn((
                    Position {
                        x: i as f32,
                        y: i as f32 + 0.5,
                    },
                    Velocity {
                        x: i as f32 * 2.0,
                        y: i as f32 * 2.0 + 1.0,
                    },
                ))
            })
            .collect();

        let mut commands = Commands::new();
        for (i, &entity) in entities.iter().enumerate() {
            if i % 2 == 0 {
                commands.insert(entity, Health(100.0 + i as f32));
            } else {
                commands.insert(entity, Damage(i as f32));
            }
        }
        commands.apply(&mut world);

        for (i, &entity) in entities.iter().enumerate() {
            assert_eq!(
                world.get::<Position>(entity),
                Some(&Position {
                    x: i as f32,
                    y: i as f32 + 0.5,
                })
            );
            assert_eq!(
                world.get::<Velocity>(entity),
                Some(&Velocity {
                    x: i as f32 * 2.0,
                    y: i as f32 * 2.0 + 1.0,
                })
            );

            if i % 2 == 0 {
                assert_eq!(world.get::<Health>(entity), Some(&Health(100.0 + i as f32)));
                assert_eq!(world.get::<Damage>(entity), None);
            } else {
                assert_eq!(world.get::<Health>(entity), None);
                assert_eq!(world.get::<Damage>(entity), Some(&Damage(i as f32)));
            }
        }
    }

    #[test]
    fn entity_count_tracks_live_entities() {
        let mut world = World::new();
        assert_eq!(world.entity_count(), 0);

        let a = world.spawn((Position { x: 0.0, y: 0.0 },));
        let b = world.spawn((Position { x: 1.0, y: 1.0 },));
        assert_eq!(world.entity_count(), 2);

        world.despawn(a);
        assert_eq!(world.entity_count(), 1);

        world.despawn(b);
        assert_eq!(world.entity_count(), 0);
    }

    #[test]
    fn archetype_count_grows_with_distinct_shapes() {
        let mut world = World::new();
        assert_eq!(world.archetype_count(), 0);

        world.spawn((Position { x: 0.0, y: 0.0 },));
        assert_eq!(world.archetype_count(), 1);

        world.spawn((Position { x: 0.0, y: 0.0 }, Velocity { x: 1.0, y: 1.0 }));
        assert_eq!(world.archetype_count(), 2);

        // same shape reuses existing archetype
        world.spawn((Position { x: 2.0, y: 2.0 },));
        assert_eq!(world.archetype_count(), 2);
    }

    #[test]
    fn clear_removes_all_entities_but_keeps_resources() {
        let mut world = World::new();
        world.insert_resource(Tick(42));
        let entity = world.spawn((Position { x: 1.0, y: 2.0 },));

        world.clear();

        assert_eq!(world.entity_count(), 0);
        assert_eq!(world.archetype_count(), 0);
        assert!(!world.contains(entity));
        assert_eq!(world.get_resource::<Tick>(), Some(&Tick(42)));
    }

    #[test]
    fn clear_invalidates_entity_ids_before_reuse() {
        let mut world = World::new();
        let stale = world.spawn((Position { x: 1.0, y: 2.0 },));

        world.clear();
        let current = world.spawn((Position { x: 3.0, y: 4.0 },));

        assert_eq!(stale.index(), current.index());
        assert_ne!(stale.generation(), current.generation());
        assert!(!world.contains(stale));
        assert_eq!(world.get::<Position>(stale), None);
        assert_eq!(
            world.get::<Position>(current),
            Some(&Position { x: 3.0, y: 4.0 })
        );
    }

    #[test]
    fn commands_flush_in_first_seen_entity_order() {
        // Entity A is seen first; even though a later command targets A again,
        // all of A's coalesced commands should execute before B's.
        let mut world = World::new();
        let a = world.spawn((Position { x: 1.0, y: 2.0 },));
        let b = world.spawn((Position { x: 3.0, y: 4.0 },));

        let mut cmds = Commands::new();
        cmds.insert(a, Health(10.0)); // A first seen
        cmds.insert(b, Health(20.0)); // B first seen
        cmds.remove::<Health>(a); // A again — coalesces with first A entry
        cmds.apply(&mut world);

        // A: insert Health then remove Health → net result: no Health
        assert_eq!(world.get::<Health>(a), None);
        // B: insert Health → Health present
        assert_eq!(world.get::<Health>(b), Some(&Health(20.0)));
    }

    // =======================================================================
    // Drop semantics tests
    // =======================================================================

    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    /// A component whose Drop increments a shared counter.
    #[derive(Clone)]
    struct Droppable {
        counter: Arc<AtomicUsize>,
    }

    impl Droppable {
        fn new(counter: &Arc<AtomicUsize>) -> Self {
            Self {
                counter: counter.clone(),
            }
        }
    }

    impl Drop for Droppable {
        fn drop(&mut self) {
            self.counter.fetch_add(1, Ordering::Relaxed);
        }
    }

    #[test]
    fn despawn_calls_drop_on_components() {
        let counter = Arc::new(AtomicUsize::new(0));
        let mut world = World::new();
        let entity = world.spawn((Droppable::new(&counter),));
        assert_eq!(counter.load(Ordering::Relaxed), 0);

        world.despawn(entity);
        assert_eq!(counter.load(Ordering::Relaxed), 1);
    }

    /// A second droppable type to test multi-component bundles.
    #[derive(Clone)]
    struct DroppableB {
        counter: Arc<AtomicUsize>,
    }

    impl DroppableB {
        fn new(counter: &Arc<AtomicUsize>) -> Self {
            Self {
                counter: counter.clone(),
            }
        }
    }

    impl Drop for DroppableB {
        fn drop(&mut self) {
            self.counter.fetch_add(1, Ordering::Relaxed);
        }
    }

    #[test]
    fn despawn_calls_drop_on_multiple_components() {
        let counter_a = Arc::new(AtomicUsize::new(0));
        let counter_b = Arc::new(AtomicUsize::new(0));
        let mut world = World::new();
        let entity = world.spawn((Droppable::new(&counter_a), DroppableB::new(&counter_b)));

        world.despawn(entity);
        assert_eq!(counter_a.load(Ordering::Relaxed), 1);
        assert_eq!(counter_b.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn remove_component_calls_drop_on_removed_column() {
        let counter = Arc::new(AtomicUsize::new(0));
        let mut world = World::new();
        let entity = world.spawn((Position { x: 0.0, y: 0.0 }, Droppable::new(&counter)));

        world.remove::<Droppable>(entity);
        assert_eq!(counter.load(Ordering::Relaxed), 1);
        // Entity should still be alive with its Position.
        assert!(world.contains(entity));
        assert_eq!(
            world.get::<Position>(entity),
            Some(&Position { x: 0.0, y: 0.0 })
        );
    }

    #[test]
    fn insert_overwrite_calls_drop_on_old_value() {
        let counter_old = Arc::new(AtomicUsize::new(0));
        let counter_new = Arc::new(AtomicUsize::new(0));
        let mut world = World::new();
        let entity = world.spawn((Droppable::new(&counter_old),));

        world.insert(entity, Droppable::new(&counter_new));
        // Old value should have been dropped.
        assert_eq!(counter_old.load(Ordering::Relaxed), 1);
        // New value should not have been dropped yet.
        assert_eq!(counter_new.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn clear_calls_drop_on_all_entity_components() {
        let counter = Arc::new(AtomicUsize::new(0));
        let mut world = World::new();
        for _ in 0..10 {
            world.spawn((Droppable::new(&counter),));
        }
        assert_eq!(counter.load(Ordering::Relaxed), 0);

        world.clear();
        assert_eq!(counter.load(Ordering::Relaxed), 10);
    }

    #[test]
    fn world_drop_calls_drop_on_all_entity_components() {
        let counter = Arc::new(AtomicUsize::new(0));
        {
            let mut world = World::new();
            for _ in 0..5 {
                world.spawn((Droppable::new(&counter),));
            }
            assert_eq!(counter.load(Ordering::Relaxed), 0);
        }
        // World was dropped — all components should be dropped.
        assert_eq!(counter.load(Ordering::Relaxed), 5);
    }

    #[test]
    fn spawn_with_non_copy_component_and_read_back() {
        let counter = Arc::new(AtomicUsize::new(0));
        let mut world = World::new();
        let entity = world.spawn((Droppable::new(&counter),));

        // We can get an immutable reference to the non-Copy component.
        let droppable = world.get::<Droppable>(entity).unwrap();
        assert!(Arc::ptr_eq(&droppable.counter, &counter));
        assert_eq!(counter.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn insert_new_component_does_not_drop_existing_components() {
        let counter_existing = Arc::new(AtomicUsize::new(0));
        let _counter_new = Arc::new(AtomicUsize::new(0));
        let mut world = World::new();
        let entity = world.spawn((Droppable::new(&counter_existing),));

        // Insert a new component (causing archetype migration).
        world.insert(entity, Position { x: 1.0, y: 2.0 });

        // The existing Droppable should NOT have been dropped.
        assert_eq!(counter_existing.load(Ordering::Relaxed), 0);
        // Both components should be accessible.
        assert!(world.get::<Droppable>(entity).is_some());
        assert_eq!(
            world.get::<Position>(entity),
            Some(&Position { x: 1.0, y: 2.0 })
        );
    }

    #[test]
    fn commands_insert_non_copy_then_apply() {
        let counter = Arc::new(AtomicUsize::new(0));
        let mut world = World::new();
        let entity = world.spawn((Position { x: 0.0, y: 0.0 },));

        let mut cmds = Commands::new();
        cmds.insert(entity, Droppable::new(&counter));
        cmds.apply(&mut world);

        // Component should be on the entity now, not dropped.
        assert_eq!(counter.load(Ordering::Relaxed), 0);
        assert!(world.get::<Droppable>(entity).is_some());

        // Despawn should call drop.
        world.despawn(entity);
        assert_eq!(counter.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn commands_insert_value_dropped_when_not_consumed() {
        let counter = Arc::new(AtomicUsize::new(0));
        {
            let mut cmds = Commands::new();
            let entity = super::EntityId::new(9999, 0); // non-existent
            cmds.insert(entity, Droppable::new(&counter));
            // Drop cmds without applying — the InsertValue should drop its payload.
        }
        assert_eq!(counter.load(Ordering::Relaxed), 1);
    }

    #[repr(align(128))]
    struct HighAlignDroppable {
        drop_count: Arc<AtomicUsize>,
        misaligned_count: Arc<AtomicUsize>,
    }

    impl Drop for HighAlignDroppable {
        fn drop(&mut self) {
            let address = self as *const Self as usize;
            if !address.is_multiple_of(std::mem::align_of::<Self>()) {
                self.misaligned_count.fetch_add(1, Ordering::Relaxed);
            }
            self.drop_count.fetch_add(1, Ordering::Relaxed);
        }
    }

    #[test]
    fn commands_insert_value_drop_preserves_component_alignment() {
        let drop_count = Arc::new(AtomicUsize::new(0));
        let misaligned_count = Arc::new(AtomicUsize::new(0));
        {
            let mut cmds = Commands::new();
            cmds.insert(
                super::EntityId::new(9999, 0),
                HighAlignDroppable {
                    drop_count: drop_count.clone(),
                    misaligned_count: misaligned_count.clone(),
                },
            );
        }

        assert_eq!(drop_count.load(Ordering::Relaxed), 1);
        assert_eq!(misaligned_count.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn copy_types_unaffected_by_drop_machinery() {
        // Verify Copy types still work exactly as before.
        let mut world = World::new();
        let entity = world.spawn((Position { x: 1.0, y: 2.0 }, Velocity { x: 3.0, y: 4.0 }));

        assert_eq!(
            world.get::<Position>(entity),
            Some(&Position { x: 1.0, y: 2.0 })
        );
        world.insert(entity, Position { x: 5.0, y: 6.0 });
        assert_eq!(
            world.get::<Position>(entity),
            Some(&Position { x: 5.0, y: 6.0 })
        );
        world.remove::<Velocity>(entity);
        assert_eq!(world.get::<Velocity>(entity), None);
        world.despawn(entity);
        assert!(!world.contains(entity));
    }
}