ECS Architecture
This page describes how Ghost.Entities is organized internally and how the main pieces interact.
Core Objects
World- Root owner for ECS runtime state.
- Holds
EntityManager,ComponentManager,SystemManager, and command buffers. - Carries a monotonic
Versionused by change tracking.
Entity- Lightweight handle (
ID,Generation) used to validate stale references.
- Lightweight handle (
EntityManager- Responsible for create/destroy and structural changes (add/remove component).
- Tracks entity location
(archetype, chunk, row)in a slot map.
ComponentManager- Owns archetypes and query cache.
- Maps signature hashes to archetype IDs.
- Maps query-mask hashes to query IDs.
EntityQuery- Stores a compiled query mask.
- Maintains a list of matching archetypes.
- Exposes iterators (
chunk,component,entity+component) and scheduling APIs.
Archetype and Chunk Model
Entities are grouped by exact component signature into archetypes.
- Each archetype owns N chunks.
- Each chunk stores:
- packed entity IDs,
- packed component arrays,
- optional enable bitmasks for enableable components,
- per-component change versions,
- chunk structural version.
Effects:
- Data for the same component is contiguous per chunk.
- Iteration can be cache-friendly and branch-light.
- Structural operations move entities between archetypes.
Structural Changes
Adding/removing components changes an entity signature, so the entity moves:
- Resolve current
EntityLocation. - Resolve or create destination archetype.
- Allocate destination row.
- Copy shared component bytes from old to new archetype layout.
- Write the new/removed component result.
- Remove old row with swap-back compaction.
- Update
EntityLocationfor moved entities.
Archetypes cache transition edges (Add / Remove) to avoid recomputing destination lookups repeatedly.
Query Compilation and Matching
QueryBuilder compiles high-level filter methods into bitset masks.
Main mask dimensions:
- structural requirements (
All,Any,Absent), - enabled/disabled semantic filters,
- write access intent.
A query first filters at archetype level (signature match), then performs per-entity checks for enablement semantics when needed.
Systems and Update Flow
SystemManagerowns system instances.SystemGroupcan sort systems using[UpdateAfter]/[UpdateBefore].SystemBasesupportsRequireQueryForUpdategating and lifecycle hooks:OnInitialize,OnStartRunning/OnStopRunning,OnUpdate,OnCleanup.
Deferred Structural Writes
EntityCommandBuffer records structural commands into a compact byte buffer.
- Record in gameplay/jobs.
- Playback at controlled sync points.
- Avoid invalidating iterators while iterating live chunks.
Use per-thread command buffers (World.GetThreadLocalEntityCommandBuffer) in multithreaded pipelines.