Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 124 additions & 0 deletions docs/ecs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# OpenVic ECS — user documentation

This directory documents the archetype-based ECS in `src/openvic-simulation/ecs/`. Only the core infrastructure exists on this branch — no game code has been migrated yet. These docs are usage-focused: they tell you how to write game code *against* the ECS, what each API guarantees, and which rules are load-bearing for performance and lockstep determinism. The terse upstream summary lives at [`ECS.md`](../../ECS.md) in the repo root — read it first; this directory expands it.

## The mental model

- One **`World`** per session owns everything: entity slots, archetypes, chunks, singletons, registered systems, and the scheduler. Game code creates it, populates it, registers systems once, then calls `tick_systems(today)` once per simulation day.
- An **entity** is a stable handle — `EntityID { index, generation }` — plus the set of plain-struct **components** attached at `create_entity` time. Pre-attach everything the entity will ever need: changing the component set later is an archetype migration per call.
- Every unique component set is an **archetype**; an archetype stores its entities column-wise in fixed 16 KB **chunks**. That layout is why iteration is fast — and why raw component pointers are short-lived.
- Per-tick logic lives in **systems**: CRTP structs whose `tick` signature *is* their access declaration (`C const&` = Read, `C&` = Write). Singleton and cross-archetype access must be declared via `extra_reads()` / `extra_writes()` — undeclared access silently breaks determinism.
- The **scheduler** builds one DAG per World from declared access plus explicit edges/phases, and runs it as a sequence of stages; systems proven conflict-free run in parallel within a stage.
- Inside a tick, structural mutation through the World is refused — it goes through **`ctx.cmd`** (a `CommandBuffer`) and applies at the stage barrier in a deterministic, worker-count-independent order.
- Everything serves the **determinism contract**: fixed-point math only, declared access, deterministic reductions, bit-identical results at every worker count, save-stable `EntityID`s, and full-state checksums to prove it.

```
World ──────────── tick_systems(today), once per simulation day
├─ entities EntityID { index, generation } — stable, save-stable handles
├─ archetypes one per unique component set
│ └─ chunks fixed 16 KB blocks; one contiguous column (slab) per component
├─ singletons one value per type, owned by the World, outside all archetypes
└─ scheduler one DAG from declared access + edges/phases
stage 0: SysA ─┐
SysB ─┼── run in parallel (proven conflict-free)
SysC ─┘
═══ stage barrier: each system's CommandBuffer applies ═══
stage 1: SysD (observes everything stage 0 created/destroyed)
═══ barrier ═══
...
```

## Quick start

A component, a singleton, a system, a session (assembled from [world.md](world.md) and [systems.md](systems.md)):

```cpp
#include "openvic-simulation/ecs/SystemImpl.hpp" // required in the TU that registers systems
#include "openvic-simulation/ecs/World.hpp"

using namespace OpenVic::ecs;
using OpenVic::Date;

struct Position {
int32_t x = 0;
int32_t y = 0;
};

struct Velocity {
int32_t dx = 0;
int32_t dy = 0;
};

struct GameClock {
bool paused = false;
};

// Register at global namespace scope; the string literal is the type's durable identity.
ECS_COMPONENT(Position, "game::Position")
ECS_COMPONENT(Velocity, "game::Velocity")
ECS_COMPONENT(GameClock, "game::GameClock")

struct MovementSystem : System<MovementSystem> {
// The tick body reads the GameClock singleton. That access is invisible in the
// tick signature, so it MUST be declared (see systems.md).
static constexpr std::array<component_type_id_t, 1> extra_reads() {
return { component_type_id_of<GameClock>() };
}

void tick(TickContext const& ctx, Position& p, Velocity const& v) {
GameClock const* clock = ctx.world.get_singleton<GameClock>();
if (clock->paused) {
return;
}
p.x += v.dx;
p.y += v.dy;
}
};
ECS_SYSTEM(MovementSystem)

void run_session() {
World world;

// Singletons first — never create one mid-tick.
world.set_singleton<GameClock>();

// Pre-attach every component at creation; add_component later means a migration.
EntityID const mover = world.create_entity(Position { 0, 0 }, Velocity { 1, 2 });

world.register_system<MovementSystem>();

Date const today { 1836, 1, 1 };
for (int day = 0; day < 5; ++day) {
world.tick_systems(today);
}

Position const* p = world.get_component<Position>(mover);
// p->x == 5, p->y == 10
(void) p;
}
```

## Reading order

| # | Doc | What it covers |
|---|---|---|
| 1 | [storage-model.md](storage-model.md) | Archetypes, chunks, columns — the mental model behind every performance rule |
| 2 | [entities.md](entities.md) | `EntityID`, create/destroy, immutable entities, bulk creation, save-stable ids, `CachedRef` |
| 3 | [components.md](components.md) | Defining and registering components, tags, singletons, checksum rules, `DenseSlotAllocator` |
| 4 | [world.md](world.md) | `World` API reference: lifecycle, iteration, singletons, identity snapshots / save-load |
| 5 | [queries.md](queries.md) | Building a `Query`, the `for_each` family, system `Filters`, the query cache |
| 6 | [systems.md](systems.md) | Writing `System` / `SystemThreaded` / `ChunkSystem`, access declarations, `should_run`, `TickContext` |
| 7 | [scheduling.md](scheduling.md) | Stages, conflict resolution, explicit edges, phases, `schedule_hash` |
| 8 | [command-buffer.md](command-buffer.md) | Deferred structural mutation from inside system ticks |
| 9 | [threading-and-reductions.md](threading-and-reductions.md) | What is safe in parallel, `EcsThreadPool`, deterministic `reductions::*` folds |
| 10 | [determinism.md](determinism.md) | The lockstep contract: rules, checksums, worker-count invariance |
| 11 | [pitfalls.md](pitfalls.md) | The consolidated rules and footguns list — read last, re-read often |

## Build and test

```powershell
scons # build sim library + headless
scons run_ovsim_tests=yes # build & run unit tests (snitch)
```
Loading
Loading