← BACK_TO_LOGS
ARCHITECTURE[2024.10.28] // 8 min read

Modular Entity Component Systems (ECS)

A deep-dive into decoupled system architecture for large-scale simulations. How we discuss spatial hashing and data-oriented design patterns used in NEURAL_OS kernel simulations.

ECSArchitectureTypeScriptPerformance

Modular Entity Component Systems (ECS)

ECS is not just an architecture pattern — it's a mindset shift from thinking in objects to thinking in data transformations. For large-scale simulations, this difference is the line between 60fps and a slideshow.

Core Concepts

// Entity is just an ID
type Entity = number;

// Components are pure data
interface Position { x: number; y: number; z: number; }
interface Velocity { dx: number; dy: number; dz: number; }
interface Health { current: number; max: number; }

// World manages component storage
class World {
  private pools = new Map<string, ComponentPool>();

  addComponent<T>(entity: Entity, type: string, data: T): void {
    this.pools.get(type)?.set(entity, data);
  }

  query<T>(...types: string[]): [Entity, ...T[]][] {
    // Returns entities that have ALL specified components
    return this.intersect(types.map(t => this.pools.get(t)!));
  }
}

Spatial Hashing for Collision

Naive O(n²) collision detection kills performance at scale. Spatial hashing reduces it to near O(n):

class SpatialHash {
  private cells = new Map<number, Entity[]>();
  private cellSize: number;

  hash(x: number, y: number): number {
    return (Math.floor(x / this.cellSize) * 73856093) ^
           (Math.floor(y / this.cellSize) * 19349663);
  }

  insert(entity: Entity, pos: Position): void {
    const key = this.hash(pos.x, pos.y);
    if (!this.cells.has(key)) this.cells.set(key, []);
    this.cells.get(key)!.push(entity);
  }
}

Memory Layout Matters

Storing components in Structure of Arrays (SoA) instead of Array of Structures (AoS) dramatically improves cache coherence when systems iterate over components.

Conclusion

ECS paired with spatial hashing scales to 100k+ entities at 60fps. The discipline of separating data from behavior pays dividends at every stage of development.