EasyEcs

Migrate from DefaultEcs

Port a DefaultEcs codebase to EasyEcs: entity sets, AEntitySetSystem, WhenChanged and EntityMultiMap mapped old to new, a ported simulation and pitfalls.

DefaultEcs keeps each component in its own pool and lets systems iterate entity sets; EasyEcs keeps entities with the same components together in tables and runs generated jobs over them. The port is mostly a change of shape: an AEntitySetSystem with [With] / [Without] attributes and a World.GetComponents<T>() loop becomes an EcsSystem with one [ForEach] method whose parameters are the components; an entity built with one Set per component is created with all of them at once; WhenChanged<T>() sets fed by NotifyChanged<T>() become [Changed<T>] methods with nothing to notify. The worked example is the real port in the repository: DefaultEcsSimulation.cs and the EasyEcs world it was ported from, WorldSimulation.cs.

Before you start

Requirements

EasyEcs targets net10.0 only. Code that must run in Unity or on netstandard stays on DefaultEcs.

dotnet add package EasyEcs

Concepts

DefaultEcsEasyEcsWhat changes
WorldWorldOne owner thread per world.
Any struct is a componentA struct implementing IComponentAdd the interface.
A pool per component typeArchetype tablesAn entity's components sit in one row; gaining a new one copies the row.
EntitySet (GetEntities().With<A>().AsSet())Filters on a [ForEach] method, or a QueryFilterNo set to keep or dispose.
AEntitySetSystem<T>, AComponentSystem<T, C>EcsSystem with [ForEach] methodsThe generator writes the loop and the component access.
SequentialSystem<T>, ParallelSystem<T>world.AddSystem<T>(), WorldOptions.ParallelSystemsOrder by registration or [UpdateBefore<T>] / [UpdateAfter<T>].
World.Set<T>() / Get<T>()ISingletonComponentA ref parameter of a [ForEach] method.
NotifyChanged<T>() + WhenChanged<T>()ITrackChanges + [Changed<T>]Every ref write is the change.
WhenRemoved<T>()ITrackChanges + [Removed<T>]No Complete() to call.
EntityCommandRecorderDirect callsChanges apply at once.
Publish / SubscribeData: components or singletons later systems readNo messages.

API mapping

The rows name the components of the example below (Hp, the tag Dead). For each component the generator writes named members (e.Hp, HasHp, SetHp(…), IsDead): use them in your code. The generic calls after them (Get<T>(), Set(c), Remove<T>()) are for generic code (generated members).

Entities and components

DefaultEcsEasyEcs
new World(maxCapacity) (a hard limit)new World(new WorldOptions { InitialEntityCapacity = n }) (a starting size; the world grows)
var e = world.CreateEntity(); e.Set(a); e.Set(b);var e = world.CreateEntity(a, b);
e.Set(c) (add or replace)e.SetHp(100), e.Set(c)
e.Set<Dead>()e.SetDead()
ref var c = ref e.Get<Hp>()e.Hp to read, ref var hp = ref e.WriteHp() to write
e.Has<Hp>()e.HasHp, e.Has<T>()
e.Remove<Hp>()e.RemoveHp(), e.Remove<T>()
e.Dispose()e.Destroy()
e.Disable() / Enable()a tag (Asleep) and [Without<Asleep>]
e.Disable<Hp>() / Enable<Hp>()e.DisableHp() / EnableHp()
e.CopyTo(world)e.Clone(); world.MoveEntities(...) for another world; a Prefab for templates
e.GetHashCode() as an ide.Id (an EntityId: index and version)
world.Set(value) / world.Get<WorldStats>()world.SetWorldStats(…), world.WorldStats

Systems and sets

DefaultEcsEasyEcs
[With(typeof(A), typeof(B))] on an AEntitySetSystemthe method's parameters (ref A a, in B b); [With<A>] for one it does not read
[Without(typeof(C))][Without<C>]
Update(T state, ReadOnlySpan<Entity> entities) + World.GetComponents<A>()[e]static void M(ref A a), or a batch method taking Span<A>
the useBuffer: true constructor argumentnothing: structural changes are safe in any pass
AComponentSystem<T, A>.Update(T state, ref A a)[ForEach] static void M(ref A a)
new SequentialSystem<T>(a, b, c) + Update(state)world.AddSystem<A>(); ...; world.Update();
new ParallelSystem<T>(runner, systems)new WorldOptions { ParallelSystems = true }
AEntitySetSystem with a DefaultParallelRunner[ForEach(Parallel = true)]
GetEntities().With<A>().AsSet().Countworld.Count<A>(filter)
GetEntities().AsMultiMap<K>(), map.Count(key)IIndexed<K>, world.Index<T, K>().Count(key)
recorder.Record(e).Set<T>() + recorder.Execute()e.Set(new T())
BinarySerializer.Serialize(stream, world)world.Save(writer)
BinarySerializer.Deserialize(stream)world.Load(bytes)

A worked example: the headline simulation

Components

Add IComponent. The counters that DefaultEcs passed as the systems' state become a singleton.

Components.cs
public struct Position : IComponent { public float X, Y; }
public struct Velocity : IComponent { public float X, Y; }
public struct Health : IComponent { public int Value, Max; }
public struct Lifetime : IComponent { public int Ticks; }
public struct Player : IComponent { public long AccountId; }
public struct Projectile : IComponent { public int OwnerId; }
public struct Dead : IComponent;

public struct WorldStats : ISingletonComponent
{
    public long Tick;
    public int Spawns;
}

A set system becomes a method

DefaultEcs:

[With(typeof(Position), typeof(Velocity)), Without(typeof(Stunned), typeof(Dead))]
public sealed class MovementSystem(World world) : AEntitySetSystem<Counters>(world, false)
{
    protected override void Update(Counters c, ReadOnlySpan<Entity> entities)
    {
        var positions = World.GetComponents<Position>();
        var velocities = World.GetComponents<Velocity>();
        foreach (ref readonly var e in entities)
        {
            ref var p = ref positions[e];
            ref var v = ref velocities[e];
            p.X += v.X;
            p.Y += v.Y;
        }
    }
}

EasyEcs: the attributes become filters, the component lookups become parameters.

MovementSystem.cs
public class MovementSystem : EcsSystem
{
    [ForEach, Without<Stunned>, Without<Dead>]
    static void Move(ref Position p, in Velocity v)
    {
        p.X += v.X;
        p.Y += v.Y;
    }
}

Structural changes need no buffer

DefaultEcs passes useBuffer: true to systems that destroy or create while they iterate. EasyEcs passes are safe as they are: a method that destroys takes the Entity, one that creates takes the World, and an entity is created with all its components at once.

ProjectileSystems.cs
public class LifetimeSystem : EcsSystem
{
    [ForEach]
    static void Expire(Entity entity, ref Lifetime lifetime)
    {
        if (--lifetime.Ticks <= 0) entity.Destroy();
    }
}

public class ShootingSystem : EcsSystem
{
    [ForEach, With<Player>, Without<Dead>]
    static void Shoot(Entity shooter, in Position p, in Velocity v, ref WorldStats stats, World world)
    {
        if ((stats.Tick + shooter.Id.Index) % 20 != 0) return;
        stats.Spawns++;
        world.CreateEntity(p, new Velocity { X = v.X * 4, Y = v.Y * 4 }, new Lifetime { Ticks = 20 },
            new Projectile { OwnerId = shooter.Id.Index });
    }
}

WhenChanged becomes [Changed<T>]

DefaultEcs needs a NotifyChanged<T>() next to every write and a Complete() after reading the set:

var changed = world.GetEntities().With<Replica>().WhenChanged<Hp>().AsSet();

entity.Get<Hp>().Value--;
entity.NotifyChanged<Hp>();

foreach (ref readonly var e in changed.GetEntities()) replicas[e].Value = hps[e].Value;
changed.Complete();

EasyEcs: mark the component tracked; every write through a ref is the change.

Replication.cs
public record struct Hp(int Value) : IComponent, ITrackChanges;
public record struct Replica(int Value) : IComponent;

public class Replication : EcsSystem
{
    [ForEach, Changed<Hp>]
    static void Copy(in Hp hp, ref Replica replica) => replica = new Replica(hp.Value);
}

The tick

A SequentialSystem becomes the world's system list; the state argument becomes the singleton.

Program.cs
world.AddSingleton<WorldStats>();
world.AddSystem<MovementSystem>();
world.AddSystem<LifetimeSystem>();
world.AddSystem<ShootingSystem>();
world.AddSystem<Replication>();
world.Update();

The two versions of the whole tick, on the same machine:

One server tick of 100,000 entities: EasyEcs vs Friflo, Arch and DefaultEcs

The same simulation ported to each library's fast path, with identical results checked in setup. Shorter is faster; the badge is the time relative to EasyEcs and the memory allocated per tick.

  • EasyEcs
  • Other libraries
EasyEcs 4.60 B per tick1.68 msFriflo.Engine.ECS 3.61.08× · 0 B per tick1.83 msArch 2.13.4× · 535 KB per tick5.76 msDefaultEcs 0.173.7× · 60.9 KB per tick6.24 ms0.00 ns1.00 ms2.00 ms3.00 ms4.00 ms5.00 ms6.00 msTime per tick

BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

Data table
LibraryTimevs EasyEcsAllocated
EasyEcs 4.61.68 ms1.00×0 B
Friflo.Engine.ECS 3.61.83 ms1.08×0 B
Arch 2.15.76 ms3.4×535 KB
DefaultEcs 0.176.24 ms3.7×60.9 KB

Pitfalls

MistakeWhat happensCaught by
Porting the state object as a field of the systemSystems are statelessEECS007: use a singleton
Taking a component by value in a [ForEach] methodA copy: writes are lostEECS002, with a code fix to ref / in
Adding components one Set at a time on creationOne row copy per componentCode review: world.CreateEntity(a, b, c)
A static method without Entity or World that destroysIt promised no structural changeEECS013
Keeping NotifyChanged callsNothing to call: there is no such methodCompiler error
Taking a tracked component by ref only to read itEvery visited row counts as changedCode review: declare it in
Using GetHashCode() as an entity idIds are recycledStore entity.Id (EntityId, with its version)
Edit on GitHub

Last updated on

How is this guide?

On this page