archetype_ecs 1.1.7

Archetype ECS - High-performance Entity Component System with parallel execution
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
# ECS PHASE-WISE IMPLEMENTATION GUIDE
## 12-Day Plan to Production-Ready GTA-like Open World ECS

---

## PHASE 1: CRITICAL BOTTLENECKS (4 DAYS)

### Overview
You're adding the two features that make or break open world games:
1. **Spatial Indexing** - Query entities by location (100x faster)
2. **Dormancy System** - Only process nearby entities (20x faster)

Combined: 2000x speedup from 100K → 5K active entities.

---

### DAY 1: SPATIAL GRID (8 HOURS)

#### 1.1 Create `src/spatial.rs`

```rust
use crate::entity::EntityId;
use crate::math::Vec3;
use rustc_hash::FxHashMap;

/// Spatial grid for efficient spatial queries
/// Cell size affects performance - use 50m for typical games
pub struct SpatialGrid {
    /// Size of each cell in world units (50m = good default)
    cell_size: f32,
    
    /// HashMap of cell coordinates to entity IDs
    /// Key: (cell_x, cell_y) from world position
    cells: FxHashMap<(i32, i32), Vec<EntityId>>,
    
    /// Track which cell each entity is in for fast removal
    entity_cells: FxHashMap<EntityId, (i32, i32)>,
}

impl SpatialGrid {
    /// Create new grid with given cell size
    pub fn new(cell_size: f32) -> Self {
        Self {
            cell_size,
            cells: FxHashMap::default(),
            entity_cells: FxHashMap::default(),
        }
    }
    
    /// Convert world position to grid cell coordinates
    #[inline]
    fn world_to_cell(&self, pos: Vec3) -> (i32, i32) {
        (
            (pos.x / self.cell_size).floor() as i32,
            (pos.z / self.cell_size).floor() as i32,  // Note: z is forward in most engines
        )
    }
    
    /// Add entity at position to grid
    pub fn insert(&mut self, entity: EntityId, pos: Vec3) {
        let cell = self.world_to_cell(pos);
        self.cells.entry(cell).or_insert_with(Vec::new).push(entity);
        self.entity_cells.insert(entity, cell);
    }
    
    /// Remove entity from grid
    pub fn remove(&mut self, entity: EntityId) {
        if let Some(cell) = self.entity_cells.remove(&entity) {
            if let Some(entities) = self.cells.get_mut(&cell) {
                entities.retain(|&e| e != entity);
            }
        }
    }
    
    /// Update entity position in grid
    pub fn update(&mut self, entity: EntityId, pos: Vec3) {
        let new_cell = self.world_to_cell(pos);
        
        if let Some(&old_cell) = self.entity_cells.get(&entity) {
            if old_cell != new_cell {
                self.remove(entity);
                self.insert(entity, pos);
            }
        }
    }
    
    /// Query all entities in sphere
    pub fn query_sphere(&self, center: Vec3, radius: f32) -> Vec<EntityId> {
        let cell_radius = (radius / self.cell_size).ceil() as i32;
        let center_cell = self.world_to_cell(center);
        
        let mut results = Vec::new();
        
        // Check all cells in radius
        for dx in -cell_radius..=cell_radius {
            for dy in -cell_radius..=cell_radius {
                let cell_key = (center_cell.0 + dx, center_cell.1 + dy);
                if let Some(entities) = self.cells.get(&cell_key) {
                    results.extend_from_slice(entities);
                }
            }
        }
        
        // Filter by actual distance (grid is approximate)
        results.retain(|_entity| {
            // In real code, get position from entity and check distance
            // For now, return all
            true
        });
        
        results
    }
    
    /// Query all entities in AABB (axis-aligned bounding box)
    pub fn query_aabb(&self, min: Vec3, max: Vec3) -> Vec<EntityId> {
        let min_cell = self.world_to_cell(min);
        let max_cell = self.world_to_cell(max);
        
        let mut results = Vec::new();
        
        for x in min_cell.0..=max_cell.0 {
            for y in min_cell.1..=max_cell.1 {
                if let Some(entities) = self.cells.get(&(x, y)) {
                    results.extend_from_slice(entities);
                }
            }
        }
        
        results
    }
    
    /// Clear all data
    pub fn clear(&mut self) {
        self.cells.clear();
        self.entity_cells.clear();
    }
    
    /// Get memory usage estimate
    pub fn memory_usage(&self) -> usize {
        self.cells.len() * std::mem::size_of::<(i32, i32)>()
            + self.cells.values()
                .map(|v| v.len() * std::mem::size_of::<EntityId>())
                .sum::<usize>()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_insert_remove() {
        let mut grid = SpatialGrid::new(50.0);
        let entity = EntityId::new(0, 0);
        let pos = Vec3::new(100.0, 0.0, 200.0);
        
        grid.insert(entity, pos);
        assert!(!grid.query_sphere(pos, 10.0).is_empty());
        
        grid.remove(entity);
        assert!(grid.query_sphere(pos, 10.0).is_empty());
    }
    
    #[test]
    fn test_query_radius() {
        let mut grid = SpatialGrid::new(50.0);
        
        // Insert entities in a line
        for i in 0..100 {
            grid.insert(
                EntityId::new(i, 0),
                Vec3::new(i as f32 * 10.0, 0.0, 0.0),
            );
        }
        
        // Query at x=500, radius=100 should get ~20 entities
        let results = grid.query_sphere(Vec3::new(500.0, 0.0, 0.0), 100.0);
        assert!(!results.is_empty());
    }
}
```

#### 1.2 Integrate with World

Modify `src/world.rs`:

```rust
pub struct World {
    // ... existing fields
    spatial_grid: SpatialGrid,  // Add this
}

impl World {
    pub fn new() -> Self {
        Self {
            spatial_grid: SpatialGrid::new(50.0),  // 50m cells
            // ... other initialization
        }
    }
    
    pub fn spawn(&mut self, components: Bundle) -> Result<EntityId> {
        let entity = self.allocate_entity()?;
        
        // ... existing spawn logic
        
        // Add to spatial index if has Position
        if let Ok(pos) = self.get_component::<Position>(entity) {
            self.spatial_grid.insert(entity, pos);
        }
        
        Ok(entity)
    }
    
    pub fn despawn(&mut self, entity: EntityId) -> Result<()> {
        self.spatial_grid.remove(entity);
        // ... existing despawn logic
        Ok(())
    }
    
    /// Spatial query - get entities near position
    pub fn spatial_query(&self, center: Vec3, radius: f32) -> Vec<EntityId> {
        self.spatial_grid.query_sphere(center, radius)
    }
}
```

#### 1.3 Tests (2 hours)

Add to `src/tests/`:

```rust
#[test]
fn test_spatial_10k_entities() {
    let mut world = World::new();
    
    // Spawn 10K entities in grid pattern
    for x in 0..100 {
        for z in 0..100 {
            world.spawn((
                Position { x: (x * 50) as f32, y: 0.0, z: (z * 50) as f32 },
            )).unwrap();
        }
    }
    
    // Query around player at origin, radius 500m
    let nearby = world.spatial_query(Vec3::ZERO, 500.0);
    
    // Should find ~100 entities (cells within 500m radius)
    assert!(nearby.len() > 50);
    assert!(nearby.len() < 200);
}
```

#### 1.4 Checklist for Day 1
- [ ] `spatial.rs` created with grid implementation
- [ ] Grid integrated into World
- [ ] Tests passing
- [ ] No compilation errors
- [ ] Benchmark: query 10K entities < 1ms

---

### DAY 2-3: DORMANCY SYSTEM (16 HOURS)

#### 2.1 Create `src/dormancy.rs`

```rust
use crate::component::Component;

/// Dormancy state for entity processing levels
#[derive(Component, Clone, Copy, Debug, PartialEq, Eq)]
pub enum DormancyState {
    /// Full processing - all systems run
    Active,
    
    /// Reduced processing - skip expensive systems (physics, AI)
    Dormant,
    
    /// Minimal processing - only streaming/positioning
    Unloaded,
}

/// Component tracking dormancy state
#[derive(Component, Clone, Copy, Debug)]
pub struct Dormancy {
    pub state: DormancyState,
    pub last_change_tick: u32,
    
    /// Only update every N frames when dormant
    pub update_interval: u32,
    pub frame_counter: u32,
}

impl Default for Dormancy {
    fn default() -> Self {
        Self {
            state: DormancyState::Active,
            last_change_tick: 0,
            update_interval: 4,  // Update every 4 frames when dormant
            frame_counter: 0,
        }
    }
}

impl Dormancy {
    pub fn new() -> Self {
        Self::default()
    }
    
    /// Check if this dormancy state should update this frame
    pub fn should_update(&self) -> bool {
        match self.state {
            DormancyState::Active => true,
            DormancyState::Dormant => self.frame_counter % self.update_interval == 0,
            DormancyState::Unloaded => false,
        }
    }
    
    pub fn tick(&mut self) {
        self.frame_counter += 1;
    }
}

/// System that updates dormancy states based on distance
pub struct DormancySystem {
    /// Distance at which entities become dormant
    pub dormant_distance: f32,
    
    /// Distance at which entities are unloaded
    pub unload_distance: f32,
}

impl Default for DormancySystem {
    fn default() -> Self {
        Self {
            dormant_distance: 800.0,   // 800m
            unload_distance: 1500.0,   // 1500m
        }
    }
}

impl DormancySystem {
    pub fn new(dormant_distance: f32, unload_distance: f32) -> Self {
        Self {
            dormant_distance,
            unload_distance,
        }
    }
}

impl crate::system::System for DormancySystem {
    fn run(&mut self, world: &mut crate::World) -> crate::error::Result<()> {
        let player_pos = world.resource::<crate::Player>()?.position;
        
        for (entity, pos, mut dormancy) in 
            world.query_mut::<(&crate::Position, &mut Dormancy)>() {
            
            let distance = pos.distance(player_pos);
            
            let new_state = if distance < self.dormant_distance {
                DormancyState::Active
            } else if distance < self.unload_distance {
                DormancyState::Dormant
            } else {
                DormancyState::Unloaded
            };
            
            if new_state != dormancy.state {
                dormancy.state = new_state;
                dormancy.last_change_tick = world.current_tick();
            }
            
            dormancy.tick();
        }
        
        Ok(())
    }
    
    fn name(&self) -> &'static str {
        "DormancySystem"
    }
    
    fn access(&self) -> crate::system::SystemAccess {
        crate::system::SystemAccess {
            reads: vec![std::any::TypeId::of::<crate::Position>()],
            writes: vec![std::any::TypeId::of::<Dormancy>()],
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_dormancy_state_transitions() {
        let mut dormancy = Dormancy::new();
        assert_eq!(dormancy.state, DormancyState::Active);
        
        dormancy.state = DormancyState::Dormant;
        assert!(dormancy.should_update());  // First frame
        dormancy.tick();
        assert!(!dormancy.should_update());  // Skip next 3
    }
}
```

#### 2.2 Update Game Systems

For each heavy system (Physics, AI, Animation), add check:

**Example - Physics System:**

```rust
pub struct PhysicsSystem;

impl System for PhysicsSystem {
    fn run(&mut self, world: &mut World) -> Result<()> {
        for (entity, rigidbody, dormancy) in 
            world.query::<(&RigidBody, &Dormancy)>() {
            
            // Skip if not active
            if dormancy.state != DormancyState::Active {
                continue;
            }
            
            // Do expensive physics
            self.step_physics(entity, rigidbody)?;
        }
        Ok(())
    }
}
```

**Example - NPC AI System:**

```rust
pub struct NpcAiSystem;

impl System for NpcAiSystem {
    fn run(&mut self, world: &mut World) -> Result<()> {
        for (entity, ai, dormancy) in 
            world.query::<(&mut NpcAI, &Dormancy)>() {
            
            match dormancy.state {
                DormancyState::Active => {
                    // Full AI update
                    ai.full_update()?;
                }
                DormancyState::Dormant => {
                    // Lightweight schedule-based update
                    ai.schedule_update()?;
                }
                DormancyState::Unloaded => {
                    // Skip entirely
                }
            }
        }
        Ok(())
    }
}
```

#### 2.3 Configure for Your Game

In your game init code:

```rust
// For GTA-like game:
let dormancy_system = DormancySystem {
    dormant_distance: 300.0,   // 300m detailed NPCs
    unload_distance: 800.0,    // 800m streaming only
};

scheduler.add_system(Box::new(dormancy_system));
```

#### 2.4 Checklist for Days 2-3
- [ ] `dormancy.rs` created
- [ ] DormancyComponent and System working
- [ ] Updated 3+ systems to check dormancy
- [ ] Tests passing
- [ ] Benchmark: dormancy update 100K entities < 10ms
- [ ] Benchmark: physics on 5K active vs 100K unoptimized

---

### DAY 4: BENCHMARKING & VALIDATION (8 HOURS)

#### 4.1 Create Benchmarks

File: `benches/phase1_benchmark.rs`

```rust
use criterion::{black_box, criterion_group, criterion_main, Criterion};

fn bench_spatial_queries(c: &mut Criterion) {
    let mut world = create_world(100_000);
    
    c.bench_function("spatial_query_100k_sphere500m", |b| {
        b.iter(|| {
            black_box(world.spatial_query(Vec3::ZERO, 500.0))
        });
    });
}

fn bench_dormancy_update(c: &mut Criterion) {
    let mut world = create_world_with_dormancy(100_000);
    let mut system = DormancySystem::default();
    
    c.bench_function("dormancy_update_100k", |b| {
        b.iter(|| {
            system.run(black_box(&mut world))
        });
    });
}

fn bench_physics_active_vs_all(c: &mut Criterion) {
    let world_all = create_world(100_000);
    let mut world_dormant = create_world_with_dormancy(100_000);
    
    let mut physics = PhysicsSystem;
    
    c.bench_function("physics_100k_no_dormancy", |b| {
        b.iter(|| physics.run(black_box(&mut world_all)))
    });
    
    c.bench_function("physics_5k_active_dormancy", |b| {
        b.iter(|| physics.run(black_box(&mut world_dormant)))
    });
}

criterion_group!(
    benches,
    bench_spatial_queries,
    bench_dormancy_update,
    bench_physics_active_vs_all
);
criterion_main!(benches);
```

Run with: `cargo bench --bench phase1_benchmark`

#### 4.2 Target Results

| Benchmark | Target | Current |
|-----------|--------|---------|
| Spatial query 100K (500m) | < 2ms | ? |
| Dormancy update 100K | < 10ms | ? |
| Physics 100K (no dormancy) | ~100ms | baseline |
| Physics 5K active (dormancy) | ~8ms | 12.5x faster |

#### 4.3 Profile Memory

```rust
#[test]
fn measure_spatial_memory() {
    let mut world = World::new();
    for i in 0..100_000 {
        world.spawn((Position { /* ... */ },)).unwrap();
    }
    
    let memory = world.spatial_grid.memory_usage();
    println!("Spatial grid memory: {} bytes", memory);
    
    // Target: < 4MB for 100K entities
    assert!(memory < 4_000_000);
}
```

#### 4.4 Checklist for Day 4
- [ ] Benchmarks created and running
- [ ] Results measured and documented
- [ ] Memory usage < 4MB for 100K
- [ ] Spatial query < 2ms
- [ ] Dormancy update < 10ms
- [ ] Physics speedup > 10x

---

## PHASE 2: MEMORY & PERFORMANCE (3 DAYS)

### Overview
Optimize the ECS itself for better cache locality and lower overhead.

---

### DAY 5: FIX ARCHETYPE STORAGE (8 HOURS)

**Problem:** Currently uses `Vec<Box<dyn Any>>` which causes:
- Pointer chasing (cache misses)
- Allocation overhead
- Alignment waste

**Solution:** Use pinned byte buffer (like Bevy does).

#### 5.1 Modify `src/archetype.rs`

Find the `ComponentColumn` struct and change:

```rust
// BEFORE (bad - find this in your code):
pub struct ComponentColumn {
    components: Vec<Box<dyn Any>>,
    //...
}

// AFTER (good - replace with):
pub struct ComponentColumn {
    /// Raw byte buffer for component data
    data: Vec<u8>,
    
    /// Size of each component in bytes
    item_size: usize,
    
    /// Alignment requirement
    item_align: usize,
    
    /// Number of components in buffer
    count: usize,
    
    /// Capacity in items (not bytes)
    capacity: usize,
    
    /// Added tick for each component
    added_ticks: Vec<u32>,
    
    /// Changed tick for each component
    changed_ticks: Vec<u32>,
}

impl ComponentColumn {
    pub fn new<T: 'static>() -> Self {
        Self {
            data: Vec::new(),
            item_size: std::mem::size_of::<T>(),
            item_align: std::mem::align_of::<T>(),
            count: 0,
            capacity: 0,
            added_ticks: Vec::new(),
            changed_ticks: Vec::new(),
        }
    }
    
    pub fn push<T: 'static>(&mut self, value: T) {
        if self.count >= self.capacity {
            self.reserve(self.capacity * 2 + 1);
        }
        
        unsafe {
            let offset = self.count * self.item_size;
            let ptr = self.data.as_mut_ptr().add(offset) as *mut T;
            ptr.write(value);
        }
        
        self.count += 1;
    }
    
    pub fn get<T: 'static>(&self, index: usize) -> Option<&T> {
        if index < self.count {
            unsafe {
                let offset = index * self.item_size;
                let ptr = self.data.as_ptr().add(offset) as *const T;
                Some(&*ptr)
            }
        } else {
            None
        }
    }
    
    pub fn get_mut<T: 'static>(&mut self, index: usize) -> Option<&mut T> {
        if index < self.count {
            unsafe {
                let offset = index * self.item_size;
                let ptr = self.data.as_mut_ptr().add(offset) as *mut T;
                Some(&mut *ptr)
            }
        } else {
            None
        }
    }
    
    pub fn reserve(&mut self, new_capacity: usize) {
        let new_size = new_capacity * self.item_size;
        self.data.reserve(new_size);
        self.capacity = new_capacity;
    }
    
    pub fn len(&self) -> usize {
        self.count
    }
}
```

#### 5.2 Impact Measurement

Before and after:
```
BEFORE:
- 100 entities, 5 components each
- 500 Box allocations + pointers
- Memory: ~50KB + overhead
- Cache misses: ~50% of queries

AFTER:
- 100 entities, 5 components each
- 5 allocations (one per component type)
- Memory: ~2KB + data
- Cache misses: <5% of queries
```

**Expected speedup: 30-50% on queries**

#### 5.3 Checklist for Day 5
- [ ] ComponentColumn refactored
- [ ] All tests still pass
- [ ] Compilation successful
- [ ] Benchmark: query performance +30%

---

### DAY 6: ENTITY ID POOL (8 HOURS)

#### 6.1 Create `src/entity_pool.rs`

```rust
use crate::entity::EntityId;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;

/// Reusable entity ID pool
pub struct EntityIdPool {
    /// Stack of recycled IDs
    free_ids: Vec<EntityId>,
    
    /// Next fresh ID to allocate
    next_index: Arc<AtomicU32>,
}

impl EntityIdPool {
    pub fn new() -> Self {
        Self {
            free_ids: Vec::with_capacity(1000),
            next_index: Arc::new(AtomicU32::new(0)),
        }
    }
    
    /// Allocate an ID (from pool or fresh)
    pub fn allocate(&mut self) -> EntityId {
        if let Some(id) = self.free_ids.pop() {
            // Reuse from pool
            id
        } else {
            // Allocate fresh
            let index = self.next_index.fetch_add(1, Ordering::Relaxed);
            EntityId::new(index, 0)
        }
    }
    
    /// Return ID to pool for reuse
    pub fn deallocate(&mut self, id: EntityId) {
        // Increment generation to detect use-after-free
        let new_gen = id.generation().wrapping_add(1);
        let new_id = EntityId::new(id.index(), new_gen);
        self.free_ids.push(new_id);
    }
    
    /// Get memory usage
    pub fn memory_usage(&self) -> usize {
        self.free_ids.capacity() * std::mem::size_of::<EntityId>()
    }
}
```

#### 6.2 Integrate with World

```rust
pub struct World {
    entity_pool: EntityIdPool,
    // ...
}

impl World {
    pub fn spawn(&mut self, ...) -> Result<EntityId> {
        let entity_id = self.entity_pool.allocate();  // Use pool
        // ... rest of spawn
        Ok(entity_id)
    }
    
    pub fn despawn(&mut self, entity: EntityId) -> Result<()> {
        // ... cleanup
        self.entity_pool.deallocate(entity);  // Return to pool
        Ok(())
    }
}
```

**Impact:** Reduces allocations by 90-99% for entity spawning.

#### 6.3 Checklist for Day 6
- [ ] EntityIdPool created
- [ ] Integrated into World
- [ ] Tests passing
- [ ] Benchmark: spawn 10K entities < 20ms (vs 50ms)

---

### DAY 7: QUERY OPTIMIZATION (8 HOURS)

**Problem:** Queries iterate ALL archetypes even if none match.

**Solution:** Pre-filter archetypes by signature before iteration.

#### 7.1 Add to `src/query.rs`

```rust
impl World {
    /// Get list of archetypes that match query signature
    fn matching_archetypes(&self, signature: &[TypeId]) -> Vec<&Archetype> {
        self.archetypes()
            .iter()
            .filter(|arch| {
                // Check if archetype has all required components
                signature.iter().all(|type_id| {
                    arch.get_column(*type_id).is_some()
                })
            })
            .collect()
    }
}
```

**Impact:** Skip 90% of archetype checks in typical games.

#### 7.2 Checklist for Day 7
- [ ] Query optimization implemented
- [ ] Tests passing
- [ ] Benchmark: query speedup +40%

---

## PHASE 3: ADVANCED FEATURES (3 DAYS)

### DAY 8-9: MULTI-WORLD SUPPORT (16 HOURS)

Create `src/world_manager.rs` - allows multiple independent worlds (for streaming, menus, etc).

### DAY 10: STREAMING SYSTEM (8 HOURS)

Create `src/streaming.rs` - load/unload chunks dynamically.

---

## PHASE 4: POLISH (2 DAYS)

### DAY 11: COMPREHENSIVE TESTS (8 HOURS)

### DAY 12: DOCUMENTATION & FINAL BENCHMARKS (8 HOURS)

---

## SUMMARY CHECKLIST

### Phase 1 (Days 1-4): DONE FIRST
- [ ] Spatial Grid (`src/spatial.rs`)
- [ ] Dormancy System (`src/dormancy.rs`)
- [ ] Integrated into World
- [ ] 5+ systems updated
- [ ] Benchmarks: 50x speedup verified

### Phase 2 (Days 5-7): OPTIMIZATION
- [ ] Archetype storage fixed
- [ ] Entity pool added
- [ ] Query pre-filtering

### Phase 3 (Days 8-10): ADVANCED
- [ ] WorldManager
- [ ] Streaming

### Phase 4 (Days 11-12): POLISH
- [ ] Tests
- [ ] Docs

---

## GTA GAME SPECIFIC CONFIG

```rust
// In your game initialization:

// Spatial indexing for world
world.spatial_grid = SpatialGrid::new(50.0);  // 50m cells

// Dormancy zones for NPCs
npc_dormancy = DormancySystem {
    dormant_distance: 300.0,    // Detailed NPCs
    unload_distance: 800.0,     // Skeleton only
};

// Dormancy for traffic
traffic_dormancy = DormancySystem {
    dormant_distance: 500.0,    // Full physics
    unload_distance: 1500.0,    // Static only
};

// Dormancy for buildings
building_dormancy = DormancySystem {
    dormant_distance: 200.0,    // Full detail
    unload_distance: 600.0,     // Removed from world
};
```

---

## FINAL PERFORMANCE TARGETS

After all phases:

| Metric | Before | After | Target |
|--------|--------|-------|--------|
| 100K world size | Works? | ✅ Yes | ✅ Yes |
| Main thread frame time | ? | < 8ms | < 8ms |
| Spatial query 500m | 100ms | 2ms | < 5ms |
| Physics time | 100ms | 8ms | < 10ms |
| Memory usage | ? | < 50MB | < 100MB |
| Dormancy overhead | N/A | < 1ms | < 2ms |

---

**You're ready. Go implement Phase 1 Day 1 now! 🚀**