> For the complete documentation index, see [llms.txt](https://wise-shepherd-games.gitbook.io/theia-ecs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wise-shepherd-games.gitbook.io/theia-ecs/execution/systems.md).

# Systems

Explicit execution order and wrap queries

A system **declares what runs and when**. It wraps query execution in a per-tick lifecycle and is the **unit of work** that `SystemsRoot` drives each tick. Together, systems **give queries a home**.

The structure is designed to be **predictable**, **maintainable**, and **flexible**. Every system follows the **same contract**, the tick is **readable at a glance** from `SystemsRoot`, and lifecycle hooks are virtual. As the simulation grows, **adding behavior means adding a system node**; the rest stays untouched.

#### Systems Root

`SystemsRoot` is the top-level tick driver. It holds an **ordered list of systems and runs each one's full lifecycle sequentially,** **in registration order**, on every `Execute()` call:

```csharp
SystemsRoot root = new SystemsRoot(
    spawnSystem,
    movementSystem,
    combatSystem
);

/* On each tick: */
root.Execute();
```

`root.Dispose()` walks every system and calls `Dispose()` on each.

Once created, `SystemsRoot` is **immutable**. The **system order is fixed at construction time and cannot be changed**: no reordering, no swapping and no dynamic insertion. Systems themselves follow the same contract: **once registered, a system always executes**. There is no activate or deactivate mechanism, no conditional execution, **no hidden state**.

**What you declare is what runs, every tick, in the same order.**

#### Three System Shapes

Parameterless `System` is used for **per-tick logic that doesn't iterate entities**: timer ticks, input processing, anything that runs each frame but doesn't need to walk archetype storage.

```csharp
public class SpawnSystem : System
{
    private float _elapsed;

    public override void Execute()
    {
        _elapsed += Game.GameTime.ElapsedGameTime;

        if (_elapsed >= 5.0f)
        {
            /* Spawn a new wave... */
            _elapsed = 0f;
        }
    }
}
```

`System<QueryT1>` is bound to **exactly one query**. Use when the **work is self-contained** and doesn't need to communicate with another query's results. The binding **is an explicit declaration of intent**, consistent with the framework's philosophy of **making purpose visible at a glance**: "*this system exists to execute this query*".&#x20;

Declaring the callback inside the system that owns the query keeps iteration logic co-located with the system that drives it; o**ne place to look, one place to change**:

```csharp
public class MovementSystem : System<NomadQuery<Transform, Velocity>>
{
    private ref struct MoveForEach : IForEach<Transform, Velocity>
    {
        public readonly float DeltaTime;
        
        public void Execute(ref Transform transform, ref Velocity velocity)
        {
            transform.Position.X += velocity.X * DeltaTime;
            transform.Position.Y += velocity.Y * DeltaTime;
        }
    }

    public MovementSystem(NomadQuery<Transform, Velocity> query) : base(query) { }

    public override void ExecuteQueryT1(in NomadQuery<Transform, Velocity> query)
    {
        MoveForEach forEach = new MoveForEach() { 
            DeltaTime = Game.GameTime.ElapsedGameTime 
        };
        query.ForEach(ref forEach);
    }
}
```

`System<TSharedData, QueryT1, QueryT2...T16>` binds **multiple queries that cooperate** through a single shared struct, passed by `ref` through each execute phase in order. Use when queries **need to produce and consume state together as a unit.** The first phase accumulates into shared state, subsequent phases consume or extend it:

```csharp
public ref struct RaidData
{
    public int WeakDwarves;
}

public class RaidMoodSystem : 
    System <
        RaidData,
        SettlerQuery<Transform, Health, Axe>,
        NomadQuery<Mood>
    >
{
    private ref struct DwarfForEach : IForEach<Transform, Health, Axe>
    {
        private const int WeakDwarfHealth = 50;
        public RaidData Data;

        public void Execute(ref Transform _, ref Health health, ref Axe __)
        {
            if (health.Current < WeakDwarfHealth)
                Data.WeakDwarves++;
        }
    }

    private ref struct FuriousMoodForEach : IForEach<Mood>
    {
        public void Execute(ref Mood mood)
        {
            mood.Furious = true;
        }
    }

    public RaidMoodSystem(
        SettlerQuery<Transform, Health, Axe> dwarfQuery,
        NomadQuery<Mood> moodQuery
    ) : base(dwarfQuery, moodQuery) { }

    public override RaidData CreateData() => new RaidData();

    public override void ExecuteQueryT1(
        ref RaidData data,
        in SettlerQuery<Transform, Health, Axe> query)
    {
        DwarfForEach forEach = new DwarfForEach();
        query.ForEach(ref forEach);
        /* Propagate weak dwarf count into shared state */
        data = forEach.Data; 
    }

    public override void ExecuteQueryT2(
        ref RaidData data,
        in NomadQuery<Mood> query)
    {
        if (data.WeakDwarves > 0) {
            FuriousMoodForEach forEach = new FuriousMoodForEach();
            query.ForEach(ref forEach);
        }
    }
}
```

`TSharedData` is a single struct shared across all phases: one value flowing through `ExecuteQueryT1`, `ExecuteQueryT2`, and so on in order. It may be a `ref struct`, allowing it to carry spans or other stack-only state across phases.

#### Lifecycle Hooks

Every system runs the same per-tick sequence:&#x20;

1. `Before`;&#x20;
2. Execute;
3. &#x20;`After`.&#x20;

All hooks are virtual, override only what the system needs:

```csharp
public class WeaponDurabilitySystem : System<NomadQuery<Weapon>>
{
    public WeaponDurabilitySystem(NomadQuery<Weapon> query) : base(query) { }

    public override void Before()
    {
        /* Per-tick setup, e.g: reset accumulators */
    }

    public override void ExecuteQueryT1(in NomadQuery<Weapon> query)
    {
        /* Per-tick update */
    }

    public override void After()
    {
        /* Per-tick cleanup */
    }

    public override void Dispose()
    {
        /* Release resources at world teardown */
    }
}
```

#### Parallel Systems

`ParallelSystems` is an opt-in parallelism node. It wraps **two or more child systems and dispatches each one's full lifecycle** **as a job** through `JobScheduler`, blocking until all children finish. From `SystemsRoot`'s perspective it is just another system in the sequence, the parallelism it introduces is fully contained within it:

```csharp
SystemsRoot root = new SystemsRoot(
    spawnSystem,
    movementSystem,
    new ParallelSystems(
        craftSystem,
        spellsSystem,
        aiSystem
    )
);
```

Passing fewer than two systems to `ParallelSystems` throws since a single system has no parallelism to exploit.

{% hint style="warning" %}
**Correctness is the caller's responsibility.**

The framework does not analyze component access to detect conflicts. **Compose only systems whose data access is known to be disjoint**.
{% endhint %}
