EasyEcs

Snapshots

Copy a whole world into memory with Capture and put it back with Restore, for rollback netcode, replays and test resets, allocation-free when reused.

world.Capture() copies the world's entities, their components and its singletons into a WorldSnapshot, and world.Restore(snapshot) puts them back, any number of times. A turn-based server undoes a move, a rollback server rewinds a few ticks to apply a late input and re-simulates, a replay jumps back, a test resets its world. Capturing into a snapshot you keep reuses its arrays, so capturing every tick allocates nothing.

When to use it

Use it for

Undoing a turn, rollback and client-side prediction (a ring of recent ticks), replays within a session, resetting a world between tests or matches.

Skip it for

Persistence: a snapshot lives in memory and shares managed references with the world. Use saves for disk and other processes. Capturing millions of entities every tick: each capture copies every row.

How to use it

Capture and restore

var before = world.Capture();               // O(entities × components)
int held = before.EntityCount;              // the alive entities it holds: log it, or size a ring by it

world.Update();                             // simulate a turn
bool turnAccepted = hero.Health.Value > 0;  // the game's rule: a turn that kills the hero is undone
if (!turnAccepted) world.Restore(before);   // same entities, same values, same singletons

A snapshot stays as it was after a restore, so it can be restored again:

world.Update();
world.Restore(before);                      // back to the same state a second time

Reuse snapshots for rollback

Capture(into) overwrites a snapshot of this world and reuses its arrays. A ring of the last ticks then costs no allocation once its snapshots are large enough.

public static class Rollback
{
    public const int Ticks = 8;
}
var history = new WorldSnapshot[Rollback.Ticks];
for (int tick = 0; tick < 100; tick++)
{
    history[tick % Rollback.Ticks] = world.Capture(history[tick % Rollback.Ticks]);   // null the first time: a new one
    world.Update();
}

world.Restore(history[(100 - 3) % Rollback.Ticks]);                                 // back three ticks, then re-simulate

What a snapshot holds

  • Entities and components, copied by value. A managed reference inside a component (a string, an array, a List<T>) is shared with the world, not cloned: a collection in a component comes back as it is now, not as it was. A DynamicBuffer<T> is the exception: its elements are copied on capture and on restore. Disabled components keep their kept values.
  • Singletons, copied by value. After Restore every singleton has the snapshot's value in its existing storage, so a SingletonRef<T> taken before keeps working; singletons added after the capture are removed.
  • Handles. Handles to entities alive in the snapshot are valid again. Every other handle is stale, including handles to entities created after the capture, even when a later entity reuses their id.
  • Not systems, options or the GroupBy configuration. Systems keep running as registered, and the world keeps its GroupBy calls; tables created after the capture stay, empty. What a snapshot does hold is each row's group: every entity comes back in the group table it was in at the capture.

What a restore tells the rest of the world

  • Change tracking: every restored row of a tracked component counts as written, and every restored row lacking one counts as removed, so replication re-sends the restored state.
  • Indexes re-index from scratch on their next lookup.
  • Relations re-index too.

Both calls take the structural gate and throw while a query iterates: call them between updates, or from a system's OnUpdate outside its [ForEach] methods. A snapshot belongs to the world it was taken from (ArgumentException otherwise), and one taken before RemoveTypes cannot be restored after it (InvalidOperationException).

Full example

A turn of poison undone: the world is captured before the turn, five updates and a new entity happen, and the restore brings back the hero's health and the entity count. Put the files in a console project that references EasyEcs (dotnet add package EasyEcs) and run it with dotnet run.

It prints:

after the turn: hero 50 hp, entities: 2
restored: hero 100 hp, entities: 1
minion alive: False

The minion was created after the capture, so the restore removes it and its handle stays stale even if a later entity reuses its id.

How to use it fast

Instead ofDoWhy
Capture() every tickCapture(snapshot) into a kept snapshotReuses its arrays: nothing allocated once large enough
A snapshot every tick of a huge worldEvery few ticks, or a smaller world per zoneCapture is O(entities × components)
A snapshot for diskSave / LoadBytes, field hashes, other processes
Collections in components you roll backDynamicBuffer<T>Buffers are copied; other collections are shared

100,000 entities in two tables with a singleton: a capture into a new snapshot, a restore, and for comparison a save into a reused buffer and a load (SnapshotBenchmark):

CaseMeanvs baselineAllocated
Capture931 μs—2.67 MB
Restore428 μs—0 B
Save262 μs—0 B
Load1.00 ms—0 B
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

The capture's allocation is the new snapshot itself; Capture(into) reuses one.

What it costs

  • Memory: a copy of every row, every singleton and the entity records.
  • Time: O(entities × components + tables + singletons) both ways; rows are copied column by column.
  • After a restore: one re-indexing walk per index on its next lookup, and every tracked row counts as changed.
  • Worlds that never capture pay nothing.

Pitfalls

MistakeWhat happensCaught by
Expecting a List<T> in a component to roll backIt is shared: it comes back as it is nowUse DynamicBuffer<T>
Capturing or restoring while a query iteratesInvalidOperationExceptionAt run time
Restoring a snapshot into another worldArgumentExceptionAt run time
Restoring a snapshot taken before RemoveTypesInvalidOperationException: its tables are goneAt run time: capture again after RemoveTypes
Keeping handles of entities created after the captureThey are stale after the restoreIsAlive
Writing snapshots to diskThey are object graphs, not bytesUse saves
Capturing or restoring from another threadStructural changes belong to the owner threadEECS014
Edit on GitHub

Last updated on

How is this guide?

On this page