EasyEcs

Structuring a real project

Lay out an EasyEcs server the way dotnet new easyecs does: Components/, one system per file, Program.cs as the host, groups for cadence, input, tests and saves.

A server outgrows one file fast. This page lays out an EasyEcs project the way the dotnet new easyecs template does and says where each part goes: data in Components/, rules in Systems/, the loop in Program.cs, one test file per system. Each part has one job, so a new feature is a new component and a new system, never an edit to the loop.

When to use it

Use it for

Any server or tool that will grow past the getting started program: a game server, a simulation, a bot farm. The layout also fits a world hosted in ASP.NET Core or a Worker Service; only the host changes (hosting).

Skip it for

A one-file experiment or a benchmark: there, folders add nothing. Splitting one world's logic over several assemblies is not needed either, unless you reload part of it at runtime (see persistence and hot reload).

How to use it

Start from the template's project structure

EasyEcs.Templates creates a console server that updates a world 20 times a second until Ctrl+C. --tests adds an NUnit project with one test file per system.

dotnet new install EasyEcs.Templates
dotnet new easyecs -n MyServer --tests
cd MyServer
dotnet run -- --ticks 100
MyServer.csproj
Program.cs
Movement.cs
Lifetime.cs
Clock.cs
Spawner.cs
SpawnSystem.cs
MovementSystem.cs
LifetimeSystem.cs
ClockSystem.cs
MyServer.Tests.csproj
SpawnSystemTests.cs
MovementSystemTests.cs
LifetimeSystemTests.cs
ClockSystemTests.cs

The package carries the generator and the analyzer, so MyServer.csproj holds one PackageReference and nothing to configure.

Put data in Components/

One file per thing the data describes, holding its components: Movement.cs has Position and Velocity, Lifetime.cs has Lifetime. Singletons go there too, one file each. Components are plain data: no methods, no references to services, and small enough that a system reads only what it needs (ECS principles).

Components/Lifetime.cs
// How many ticks an entity has left. LifetimeSystem destroys it when they run out.
public record struct Lifetime(int Ticks) : IComponent;

One system per file, one job per system

Each file in Systems/ holds one system with one responsibility, named after it: MovementSystem moves, LifetimeSystem expires. The game's rules all live here, even "spawn a wave every second", so they run in the order you choose and can be tested one by one. Add a system with the item template:

dotnet new easyecs-system -n RegenSystem -o Systems

Systems keep no state of their own (EECS007) and never call each other (EECS008): what one system leaves for another is a component or a singleton. See Systems and [ForEach].

Program.cs is only the host

Program.cs builds the world, sets the singletons, adds the systems and runs the loop. It holds no game rule: when you are about to write an if about the game there, write a system instead.

Set every singleton before the first update. A system that reads a missing singleton throws on its first run, naming it and the call that adds it (D27):

Singleton Spawner was not added to this world: set it before the systems that read it run
(world.SetSpawner(...) or world.AddSingleton<Spawner>()), or use GetOrAddSpawner() where a default is meant

Where the default value is right, such as a counter that starts at zero, GetOrAddX() says so in the code that reads it. Singletons that come from a save are not set again after Load (load at start, save at stop).

Keep the order in one place

Systems run in the order they are added. Put the AddSystem calls in one method that Program.cs and the tests both call, so a test of the whole tick runs the tick the server runs (share the setup):

Game.cs
public static class Game
{
    public static void AddSystems(World world)
    {
        world.AddSystem<MoveSystem>();
        world.AddSystem<ExpireSystem>();
    }
}

public record struct Ttl(int Ticks) : IComponent;

public class MoveSystem : EcsSystem
{
    [ForEach]
    static void Move(ref Position position, in Velocity velocity) =>
        position = new Position(position.X + velocity.X, position.Y + velocity.Y);
}

public class ExpireSystem : EcsSystem
{
    [ForEach]
    static void Expire(Entity entity, ref Ttl ttl)
    {
        if (--ttl.Ticks <= 0) entity.Destroy();
    }
}

Give each cadence a group

Not everything runs every tick. A system group is a cadence the host calls: systems marked [UpdateInGroup<G>] run on world.Update<G>(), the others on world.Update(). Use one group for input read whenever it arrives, one for replication every few ticks, one for autosaves. Inside a group, UpdateInterval runs a slow system every N-th update and UpdatePhase spreads systems with the same interval (UpdateInterval and UpdatePhase):

public record struct Census(int Entities) : ISingletonComponent;

// Every 20th update of its group: once a second at 20 ticks a second.
public class CensusSystem : EcsSystem
{
    public override int UpdateInterval => 20;

    protected override void OnUpdate() => World.GetOrAddCensus().Entities = World.EntityCount;
}

One tick of the full example, as the host runs it:

host wakes up

Update<InputGroup>()
inbox → FireRequest

Update()
Fire, Spawn, Movement,
Lifetime, Clock

sleep until
the next tick

Take input through a mailbox

The network, timers and the database run on other threads; the world belongs to the one thread that updates it. They meet in a queue you own: other threads post messages, and a system on the world's thread takes them and turns each into data. The queue is a readonly field of that system, handed in when it is added: a dependency, not state, so EECS007 allows it. Not a singleton: World.Save writes every singleton, and a queue has no formatter.

using System.Collections.Concurrent;

public readonly record struct FireCommand(float Vx, float Vy);   // a message, not a component
public record struct FireRequest(float Vx, float Vy) : IComponent;

public struct InputGroup : ISystemGroup;

[UpdateInGroup<InputGroup>]
public class ReceiveCommandsSystem(ConcurrentQueue<FireCommand> inbox) : EcsSystem
{
    private readonly ConcurrentQueue<FireCommand> _inbox = inbox;   // filled by the network threads

    protected override void OnUpdate()
    {
        while (_inbox.TryDequeue(out var command))
            World.CreateEntity(new FireRequest(command.Vx, command.Vy));
    }
}

Add it with world.AddSystem(new ReceiveCommandsSystem(inbox)), and give the same queue to the network code.

The queue's bound and what happens when it is full are yours to choose. The details are in input from other threads; a server that answers requests is in hosting.

One test file per system

MyServer.Tests has a test file per system: a world of its own with the singletons and entities the system needs, one update, assertions on the data it left. Add a test of the whole tick through Game.AddSystems. The template's MyServer.csproj leaves the test folder out of the server's build (<Compile Remove="MyServer.Tests\**"/>). See Testing systems.

Look inside when something is off

WorldOptions.MeasureSystems times every system, SystemErrors = SystemErrorPolicy.Disable turns a failing system off instead of stopping the tick, and world.Describe() shows the tables. Add them to the host's options when you need them; see Debugging and diagnostics.

Persistence and hot reload

  • Saves: load the last save before the first tick and save after the loop ends, from the host (saves, load at start, save at stop). The SaveLoad sample saves a world, a group of entities, and moves entities between worlds.
  • Hot reload: to replace game logic while the world runs, move those systems and components into a plugin assembly and load it into a collectible context (migration and unloading). The HotReload sample splits the project into contracts, plugin and host.

Full example

The template's server with the two parts a real one adds: commands from a network thread, read through a mailbox in an input group, and the system order in Game.cs, shared with the tests. Create it with dotnet new easyecs -n MyServer --tests, add the new files, and run it with dotnet run -- --ticks 60.

It prints:

tick 20: 105 entities
tick 40: 205 entities
tick 60: 205 entities
stopped after 60 ticks

The five commands arrive during the first half second and become five bullets next to the first wave of 100. At tick 60 the first wave has run out of time while the third one appears; the fired bullets, a few ticks younger, are still alive. No line of Program.cs knows about bullets: the host only sets data, adds systems and keeps time.

How to use it fast

The layout itself has no cost to tune: folders and files are gone once the project compiles. What decides the speed of the tick is in the systems: in for what a method only reads, a group or UpdateInterval for what does not run every tick, and the choices the performance guide measures.

What it costs

Nothing at run time: one system per file compiles to the same code as one file of systems, and a group is a call the host makes. The tick costs what its systems cost; performance has the numbers per feature.

Pitfalls

MistakeWhat happensCaught by
A game rule in Program.cs (a wave every second, a win condition)It cannot be tested alone or ordered against the systemsReview: move it into a system that reads a singleton
Program and tests adding the systems in different ordersThe tests pass on a tick the server never runsShare one Game.AddSystems
A singleton set after the first update, or neverThe first system that reads it throws InvalidOperationException naming itThe runtime, on the first update
A system keeping a counter or a timer in a fieldState no save, snapshot or test seesEECS007
The network thread creating entities itselfAn exception from the structural gate, or torn tables when it misses the raceEECS014 when it can see it; post to the mailbox
The test folder inside the server projectNUnit types compiled into the server<Compile Remove="MyServer.Tests\**"/> (the template has it)
Edit on GitHub

Last updated on

How is this guide?

On this page