Ce qu’il fait
- Requêtes par chunk avec pointeurs bruts
- Tags à coût nul et buffer de commandes
- Ordonnanceur de systèmes basé sur les conflits d'accès
- Ressources, hiérarchie et observateurs
- Snapshots avec remappage des handles
- Exécution parallèle via la jonction avec <code>concurrency</code>
Mesuré
- Release, MSVC 19.51, i7-6700. Création de 1 million d'entités par lot : 7.38 ms (objectif 10 ms)
- Itération sur 1 million avec 3 composants : 4.19 ms, au plafond de bande passante mémoire (14.3 GB/s). Objectif de 1 ms non atteint
- Déterminisme : 200 exécutions avec 1 à 16 workers, monde identique au bit près
Limites connues
- En dessous d'environ 16,000 entités, l'exécution parallèle est plus lente que la séquentielle
Archetype storage, generational entities, queries, zero-cost tags and the command buffer are complete and measured. **The iteration target is not reached, and the section "The millisecond" explains why, with the measurement that proves it and one that contradicts the spec's own premise. It is the first thing to read. Systems and the scheduler are delivered, with topological ordering, grouping by mask conflict, verification of declared access and measured determinism. The C ABI layer is delivered, and so are the hierarchy, resources, serialization and observers. The glue with Concurrency is delivered and measured, and its table shows the point from which it pays off. What is missing are minor items**, all listed at the end.
---
What this module is
CWorld M;
ETL_UNUSED( M.Init( SWorldParams() ) );
const SEntity E = M.CreateWith( SPos{ 0, 0, 0 }, SVel{ 1, 0, 0 } );
CQuery< SPos, SVel > Q( M );
Q.ForEachChunk( []( SEntity *, SPos * const pP, SVel * const pV, const std::size_t n )
{
for( std::size_t i = 0; i < n; ++i )
pP[ i ].x += pV[ i ].x;
} );ForEachChunk hands over raw pointers to the chunk's arrays. It is the path the numbers use and the one the documentation recommends. ForEach works per entity, is more convenient and is slower.
---
The four decisions that govern everything
Archetype storage, structure of arrays inside the chunk. Entities with the same set of components live in the same 16 KB chunk, and inside it each component has its own contiguous array. A system that only reads position and velocity walks two dense arrays and touches nothing else. With an array of structures, every cache line would also bring in what that system does not use.
Sixteen kilobytes, at compile time. With a constant, converting an index into a chunk and a row is a bit shift. With a parameter it would be an integer division, more than twenty cycles, inside the module's hottest loop.
Identity in 64 bits: index and generation. IsAlive is an index into an array and a comparison, and destroying advances the generation. Without this, recycling an index would make an old handle point to a new entity, which is the classic ECS defect.
Every structural change is deferred. Adding a component moves the entity to another archetype, which takes it out of the chunk being walked and brings the last entity into its place. The running loop then skips one entity and visits another twice, with no error at all. That is why the command buffer exists.
---
The millisecond
"Iterate 1 million entities with three components in under 1 ms single threaded. That is roughly 1 ns per entity, which is achievable only with contiguous storage and a loop the compiler can vectorize."
Not reached: measured 4.19 ms, or 4.19 ns per entity. Release, MSVC 19.51, x64, Intel i7-6700.
The cause, measured in three experiments
First: the same loop over a set that fits in cache.
| ns per entity | |
|---|---|
| one million entities (50 MB) | 4.19 |
| fifty thousand (~2 MB, fits in L3) | 2.44 |
The large loop moves 60 bytes per entity (36 read, 24 written), which gives 14.3 GB/s, and that is the practical memory ceiling of this machine (DDR4-2133, two channels). The large path is waiting on memory, not on the processor.
Second: the vectorizer report, which the spec says to inspect.
three-float component ........ "loop not vectorized due to '1300'"
one-scalar component ......... "loop vectorized"And the cause is not the ECS layout. The arrays are contiguous and unit-stride, as the spec asks. The problem is that a component that is itself a structure of three floats gives each field a stride of twelve bytes within its array. The spec says the lack of vectorization is "a defect, not an acceptable outcome", and the third experiment shows that here it is neither.
Third: the same computation with one scalar per component, which vectorizes.
Nine one-float components instead of three twelve-byte ones. Exactly the same arithmetic, exactly the same memory traffic, and the compiler vectorizes.
| three floats (does not vectorize) | one scalar (vectorizes) | |
|---|---|---|
| one million | 4.19 ns | 4.71 ns |
| fifty thousand, in L3 | 2.44 ns | 2.59 ns |
The vectorized version is slower in both cases. Nine memory streams cost the prefetcher more than the vector units save, and with the large set there is not even processor work to save.
What this means
The spec's premise ("achievable only with ... a loop the compiler can vectorize") does not hold on this machine. The limit is memory bandwidth, and vectorizing adds no bandwidth at all.
Reaching 1 ns per entity would require moving fewer bytes, not generating better code: smaller components (half precision, positions in 16-bit integers), or systems that read fewer components at a time. That choice belongs to whoever models the game, not to this module. The module provides the memory layout so that the choice has an effect.
What is the module's job is done: 2.44 ns per entity with everything hot is the floor of the loop, and the 14.3 GB/s show that the large path is using the whole machine.
---
What was measured and is enforced
| create one million in a batch | 7.38 ms (the spec target is 10 ms) |
random Get, hot data | 9.4 ns (the spec target is 10) |
random Get over 50 MB | 93.5 ns (two cache misses: the record and the chunk) |
| archetype migration | 58 ns per entity |
| tags | 816 entities per chunk with and without two tags, that is, they cost zero bytes |
| allocations during iteration | zero, in twenty passes over two hundred thousand entities |
| allocations while recording commands | zero, in two hundred thousand commands |
| generation | a thousand recyclings of the same index, and the original handle rejected in all of them |
| queries | the list is recomputed only when an archetype is born, and nothing else invalidates it |
| command determinism | fifty rounds, two overlapping buffers, always the same result |
| system determinism | two hundred runs, five worker counts, the same world bit for bit |
| system order | the declared one, not the insertion order. A cycle is rejected and reported by name |
| grouping | two systems that write the same component never land in the same group |
| undeclared access | detected, and Run returns eUndeclaredAccess |
| stages | a system that only recorded commands sees the world change at the end of the stage, not before |
| resources | creating a singleton creates no archetype and no entity |
| hierarchy | a thousand new leaves, and none forces the depth order to be recomputed |
| traversal | each node visited after its parent, always, without recursion |
| cycles in the tree | rejected on entry, and the tree stays intact |
| propagation | moving the root moves the grandchild. Rotation, scale and translation verified |
| observers | none is called inside an Add. All at the sync point |
value of an OnRemove | reaches the observer after the component no longer exists in the world |
| observer chain | a delivery does not deliver what it caused itself |
| no observers | a hundred Add/Remove and zero notifications recorded |
| snapshot | 222 entities in 6,971 bytes, and the values come back intact |
| unknown component | skipped with a report, and the rest of the entity does not become misaligned |
| remapping | the handle stored inside a component points to the new entity |
| truncated snapshot | rejected, not half read |
| non-trivial component | does not compile without an explicit declaration |
| lifetimes of a non-trivial one | 557 constructions, 557 destructions: the books balance |
| migrating a non-trivial one | leaves one, and it is the same pointer that travels |
| world with non-trivial ones | the world destructor leaves nothing unreleased |
The allocation counter fails the test. The global allocation functions are replaced, the complete set, including the nothrow variants.
Batch creation: 2.3x, not 10x
"the batch path should be at least 10x faster."
Measured: 1.47 ms one at a time against 0.64 ms in a batch, for a hundred thousand. The ratio is 2.3x.
And the numerator is the explanation. The one-at-a-time path already does little: it looks up archetype zero (an index), asks the last chunk whether it has room (a comparison) and writes the record. The batch removes those first two steps per entity, and what remains (writing eight bytes to the entity array and sixteen to the record) is the same in both.
Reaching 10x would require the one-at-a-time path to be ten times worse than it is. The slow path was not left artificially slow to make the ratio look good.
---
How this was verified
tests/ecs.cpp, 222 checks, and tests/ecs_c_abi.c, 52 in plain C, compiled as C11 and as C17. Green in Debug and Release, and the systems section was run three times in a row in each configuration.
One defect the test caught was in the test itself, and it is worth recording because it is the kind of thing that goes unnoticed: the test of the buffer's guarantees counted entities with x == 42, and one of the fifty created earlier already had that value. It now uses a value that cannot collide.
In Debug the benchmark runs with fifty thousand instead of one million. The number is meaningless, and that is on purpose, but the benchmark still compiles and runs.
---
Systems and the scheduler
SSystemDescriptor D;
D.pName = "mover";
D.pRun = &SysMove;
D.eStage = EStage::eUpdate;
D.Reads = MaskOf< SVel >(); // what it promises to only read
D.Writes = MaskOf< SPos >(); // and what it promises to write
ETL_UNUSED( S.Add( D ) );The access declaration is not documentation
"Access masks are declared, and the scheduler verifies them. (...) Without this, parallel execution is unsound."
The scheduler runs two systems at the same time because they declared that they do not overlap. If the declaration lies, both write to the same array from two cores. No error appears, only swapped data.
What makes this verifiable is that the query states what it does. CQuery< const SPos, SVel > reads position and writes velocity, and that is in the type: what ForEachChunk hands over is const SPos * and SVel *.
Half of the verification never even reaches run time: writing to a position declared as read does not compile. The other half is the query's mask checked against the system's, and there is a test with a system that declares it reads position and writes it: Run returns eUndeclaredAccess, and the same body with the correct declaration passes.
**The "hard error" is Run refusing the round**, not aborting the process. This module does not use exceptions, and a failure that kills the process cannot be verified by a test, which is exactly what the spec wants to exist. In Release the verification is off. Turning it on takes one field of the parameters.
Grouping
Two systems conflict when a write touches a write, a write touches a read, or a read touches a write. Read against read is not a conflict, and that is what makes it worth declaring reads instead of declaring everything as a write. Detection is a bitwise & over four words.
The ordering is topological by layers, and within each layer the systems are separated by conflict. A cycle is rejected and reported by name: Build returns eCycle and the systems caught in it are in CycleName. Silently choosing an order would be worse than choosing none.
The scheduler brings no threads, and that is on purpose
The spec says "Depends on: nothing at link time" and treats parallel execution as "optional glue with Concurrency". If the module brought its own thread pool, anyone who only wants the ECS would take the pool along, and anyone who already has one would end up with two.
What it brings is the IExecutor injection point: "run these N tasks and return when they have all finished". Without an executor, everything runs serially, which is the default. The threaded executor in the test is thirty lines long, and that is the measure of what the injection point asks of whoever uses it.
Determinism
"identical world state across 1000 runs at varying worker counts, bit exact. Determinism is a hard requirement, not a nice property."
Two hundred runs, five worker counts (1, 2, 4, 8 and 16), and the same world, bit for bit: digest 0xE446BB2B3D854714 in all of them.
What guarantees this is two fixed orders, and neither of them is the order in which work finished:
- the groups run in the order the topological sort fixed.
- the commands are merged in worker order, with one buffer per worker so that there is no lock at all on the path that records a command.
---
The C layer
"A reduced surface: world handle, entity create and destroy, component registration by ID and size, raw chunk iteration through a callback. The template surface does not cross."
uint32_t uPos = ETLC_EcsRegisterComponent( sizeof( SPos ), 4u, "pos" );
ETLC_EcsWorld World = ETLC_EcsWorldCreate( 1024u, 8u );
uint32_t uInclude[] = { uPos };
ETLC_EcsForEachChunk( World, uInclude, 1u, NULL, 0u, &CountChunk, pCtx );What the crossing forced us to build
CQuery< SPos, SVel > resolves the columns in the template. A template has no representation in a C ABI, and there is no honest way to pretend it does. That is why the module gained a second query, CDynamicQuery, built from a list of numbers and handing over the chunks as void **.
It does not serve only the C layer: an editor, an interpreter or a scene loader does not know the types either. There is a test that checks it against the typed query: the same count, the same chunks, and the sum of the arrays equal byte for byte. If the two diverged there would be two ECS and not one, and the defect would only show up for whoever used the C layer.
What it costs: the columns are resolved per archetype instead of per type, and what the function receives is void **. The inner loop is still flat and over the same arrays. What is lost is the compiler knowing the types, and with it the chance to inline the body into the loop.
The entity crosses as a 64-bit integer
On the C++ side it is { uint32 index, uint32 generation }. On the C side it is one uint64_t, and there is a reason for that: a small structure returned by value is passed differently depending on the ABI and the compiler, and a 64-bit integer goes in a register in all of them.
The two conversions are two functions and nothing more, and **three static_assert prevent the layout from changing on one side without anyone noticing**. That is what lets the C side's CreateBatch write directly into the caller's array, without an intermediate copy of a million handles.
What does not cross, and why
Systems and the scheduler. The spec enumerates the reduced surface and they are not in it. And there is a better reason than that: the scheduler lives on declared masks that the C++ side verifies against the type of the queries. Without types there is nothing to verify, and half of its guarantee would be lost in the crossing. Anyone who wants systems writes them in C++ and calls C code from inside them.
Non-trivial components. On the C side a component is a size and an alignment, and the world copies it byte by byte. That is what it already is today on the C++ side.
What crosses in full
The world, and the component numbers. A component registered with ETLC_EcsRegisterComponent gets a number from the same counter that the C++ side's ComponentId< T > uses, and a world created in C is the same CWorld. The two sides can share a world.
One thing the spec does not ask for, and that is there anyway
The command buffer. The spec's list enumerates the minimum. Without it, the only way for a C consumer to change the world during an iteration would be to do exactly what the header says not to do, and the C layer would be offering a path to the accident the rest of the module exists to prevent.
How it was verified
tests/ecs_c_abi.c, 52 checks in plain C, compiled as C11 and as C17. The first target is the build itself: a C header that is only ever compiled by a C++ compiler stops being C without anyone noticing.
The test covers what can only be seen from outside: that writing through the pointer the iteration hands over really changes the world, that a tag's column comes back null, that an old handle is still rejected after its index is recycled, and that no function crashes with a null handle (it returns ENTITY_NONE or not-initialised).
---
The hierarchy and resources
They are the two things in an ECS that are not per entity, and that is why neither of them lives in an archetype.
A singleton is not an entity
"Singleton data that is not per entity (time, input state, render context). Stored separately from archetypes and accessed by type with a direct array index."
Storing the time or the input state as an entity with one component is the obvious temptation, and it is wrong for three reasons:
- one archetype per singleton, each with one entity inside and a 16 KB chunk to hold it.
- each of them enters every query that happens to match, and those queries then have to exclude it by hand.
- reading it would cost the same as a random access: find the entity, the chunk, the row.
Here it costs an index into an array. There is a test that confirms what this implies: creating a resource creates no archetype and no entity.
Resource numbers come from their own counter, not from the component mask. A resource never appears in an archetype, and spending one of the mask's 256 bits on it would be a waste. A new resource starts zeroed, precisely because it is the place where nobody expects to have to initialize before reading.
The traversal is linear, not a tree per frame
"Depth order is maintained incrementally so the walk is linear, not a recursive tree traversal per frame."
What a recursive traversal costs: one call per node, a stack that grows with depth and, worst of all, unpredictable memory jumps, because a node's children are wherever they happened to end up.
What is done instead: the nodes are stored by increasing depth, in a flat array. Walking it from one end to the other visits each node after its parent, always, because the parent has a smaller depth. One pass, without recursion and without a stack. And the parent's transform is already computed when the child is reached, so there is never a need to climb the tree.
What "incrementally" means here, measured: a thousand new leaves under the same root enter the traversal and none of them forces the order to be recomputed. Changing a node's parent does, because the depth of all its descendants changes. That is flagged and paid once, on the next traversal, not per frame.
The recomputation is a counting sort over depth: linear, not a comparison sort.
The parent lives in the child
A parent can have zero or a thousand children, and a variable-length list inside a component would break the chunk layout. In the child it is always one entity, always eight bytes. The reverse direction is a query on SParent, which is what makes the relationship queryable like any other. The hierarchy writes the component, not a private record.
Cycles are rejected on entry. A node that was its own ancestor has no depth at all, and the recomputation would never finish. SetParent climbs the chain of the intended parent before accepting. Putting the root under its grandchild returns eInvalidArgument, and the root stays without a parent.
The hierarchy is not notified of a destruction, on purpose: forcing the world to know about it would couple the two. Dead nodes are discarded during the traversal, and confirming that one is alive is an index and a comparison. There is a test that destroys five of eleven and checks that the traversal then sees six.
The transform does not use the Math module
Section 2 of the conventions forbids a module from including another module's header to obtain functionality. It is thirty lines of quaternions so that anyone who only wants an ECS does not take the math module along.
It is translation, rotation and scale, not a 4×4 matrix: ten floats per entity against sixteen, and composing two TRS costs twenty-odd multiplications against the sixty-four of two matrices. Anyone who needs the matrix builds it at the end, once, not at every level of the tree.
Rotation is tested, not just translation. It is the part most likely to be wrong (quaternion convention, multiplication order, sign of the cross product), and a test with only translation and scale would pass with all of that swapped. Ninety degrees about Z on the parent takes the child from +X to +Y.
A mistake that writing this code almost let through
SEntity{} is { index 0, generation 0 }, which is the first entity any world creates. Using it as the "no parent" marker would make the first entity in the world be treated as the root of everything. The marker is SEntity::None(), and that is stated on the field where it goes.
---
Observers
*"
OnAdd,OnRemove,OnDestroyhooks per component type. Invoked at sync points, never in the middle of an iteration, because mutating during iteration is the classic ECS crash."*
The spec's sentence sums up the whole design, and it is worth seeing why. The obvious approach (calling the observer the instant the component is added) puts user code running inside the Add. And what that code almost always does is add or remove another component: an observer of "an enemy was born" gives it health, a weapon and sound.
That is a structural change in the middle of another one. Notifications are recorded and delivered at a sync point. It is the same reasoning as the command buffer, and CSystemScheduler delivers the notifications at the same instant it applies the commands.
The value travels with the notification
An OnRemove observer almost always wants to see what was removed, to release a resource or notify someone. At delivery time that component no longer exists in the world, so its bytes are copied into the notification. There is a test that confirms this: the component is no longer there and the value arrives anyway.
Destroying is different from removing
eRemoved and eDestroyed are distinct events, and the difference matters. Whoever observes "a weapon is no longer equipped" wants to drop it on the ground. Whoever observes "the owner died" may not.
A chain of observers does not chase itself
An observer can change the world, and that is what it exists for. The notifications it causes itself are kept for the next delivery. If a delivery delivered within itself, an observer that observed what it causes itself would recurse until the stack overflowed, in a place unrelated to the cause.
Without observers you pay nothing
The world tests one bit in a mask before recording anything, and the mask of a program without observers is all zero. There is a test that does a hundred Add/Remove with no subscription at all and checks that no notification was recorded.
---
Serialization
A component's number cannot be saved
The number is assigned on first use, and therefore depends on the order in which the program touches the types. Two versions of the program almost certainly give different numbers.
Saving it is saving a pointer to a table that no longer exists. A world saved today would come back with positions where the velocities were, and with no error at all, because the sizes could match.
That is why what is saved is the name, and a component without a name cannot be saved: it is skipped, and the report says which one. There is no better choice here. Inventing a name from the type would give something that changes with the compiler.
An unknown component does not make the load fail
"Version tolerance: unknown components are skipped with a report rather than failing the whole load."
It is the difference between a save still opening after an update and the player losing everything. The snapshot stores the size of each component, so one this program does not know is skipped by its size and the rest of the entity is still read. A known name with a different size is treated as unknown. The bytes would fit and the value would come out wrong silently, which is worse.
There is a test that saves a component and then "forgets" its name: the thirty entities come back, the report says there was an unknown one and how many times it was skipped, and the values of what remained do not become misaligned.
Indices do not survive, and there is a consequence that catches everyone
"Entity ID remapping on load, since indices will differ."
A loaded world creates the entities again, and the indices depend on what was already there. CEntityRemap translates a saved handle into the new one, and the translation checks the generation. Without that, the handle of an entity that had already died before the save would be translated to whoever recycled its index.
And a component that stores an entity inside it (a parent, a target, an owner) is left with an old handle. Saving the bytes is not enough. The module does not guess which fields of a component are entities, and there is no way to do that without type descriptions, which this SDK does not have. Anyone who stores an entity in a component registers a FixupFn. SParent already comes with its own, because it belongs to the module, and there is a test that saves a tree, misaligns the indices on purpose and checks that the loaded SParent points to the new parent.
A truncated snapshot is rejected, not half read
The reader states how many bytes remain, and the load checks this before trusting a count that comes from the file. Without that, a cut-off snapshot would make the load allocate memory that does not exist. Bytes that are not a snapshot are rejected by the signature.
What the snapshot does not carry, and why
Resources, because they belong to the program and not to the world. The hierarchy, because it rebuilds itself from the SParent components the snapshot already carries.
And the integers are written in explicit little-endian, but the component bytes are not. A snapshot is a file and crosses machines, so the headers and counts are written byte by byte. The components are raw memory, with the padding the compiler chose. A snapshot travels between machines with the same ABI, and that is stated here so it is not discovered later.
A defect the test caught, and that looked like "it works"
The load stored the offsets of the values inside the pointers it was going to pass to the world. Offset zero, which is that of the first component of each entity, gave a null pointer, which the next step read as "this is a tag, it has no value".
The result was the first component of every entity coming back zeroed, with the whole structure matching: correct counts, correct remapping, correct archetypes, wrong values. The offsets now live in their own array.
---
Non-trivial components
"Components must be trivially copyable by default. Non-trivial components are supported through an explicit opt-in registration that supplies move and destroy function pointers, and the documentation states the performance cost."
Why that is the default
An archetype moves rows with memcpy: on each removal the last entity goes into the hole, on each migration the shared components change chunk. With a component that owns a pointer (a string, a vector), copying the bytes duplicates the pointer and two owners free the same memory.
And that produced no error at all. The memcpy compiles with any type, and the damage showed up in a place unrelated to the cause. Now there is a static_assert in ComponentId< T >(), and a component with a destructor does not compile without being declared:
struct SName { std::string s; };
ETL_ECS_NON_TRIVIAL_COMPONENT( SName ) // at global scope, before first use
ETL_UNUSED( RegisterNonTrivial< SName >() ); // at initialization, onceThey are two separate things because the first is a build-time step and the second a run-time one. And the registration also requires the type to move without throwing: the world moves rows in places where an exception would leave the chunk half done.
The three operations, or none
pCopy, pMove, pDestroy. Registering only two of them is rejected. With two, the world would move a row and not destroy it, or the other way around, and the leak would be silent.
The five places where the world now uses them: adding (constructs in raw memory), overwriting (destroys and reconstructs, because writing bytes over a live object loses what it held), migrating archetype (moves, and what is left behind is destroyed right after), removing an entity (destroys the row and moves the last one into the hole) and the world destructor.
What it costs
| trivial | non-trivial | |
|---|---|---|
| moving a row | one memcpy of everything at once | one indirect call per component |
| removing an entity | one memcpy | one destruction + one move + one destruction, per component |
| snapshot | saved | does not fit |
| observer notification | carries the value | does not carry it |
A world with only trivial components pays absolutely nothing: the non-trivial mask is all zero and the check fails right away. There is a test that confirms this: ComponentOps( ComponentId< SPos >() ) is null.
Where they cannot go, and why
The snapshot does not carry them. Their bytes are pointers to memory of this run. Saving them would be saving addresses that mean nothing when read back, and the damage would be silent. They are skipped and the report says so. Anyone who wants to save one converts it to a flat form (an identifier, an index into a resource table) and saves that form.
An observer's notification travels without a value. There is a better reason than convenience: a component is non-trivial precisely because it has a destructor that releases something, and when it is removed that destructor has already run. There is nothing left for the observer to release. What it wants to know is which entity and which component, and that goes in the notification.
How it was verified
A component that counts its own lifetimes: constructions, destructions and live instances. If the world copied it byte by byte instead of constructing and destroying it, the numbers would not balance.
At the end of the whole section: 557 constructions and 557 destructions. And along the way:
- migrating archetype leaves one, and it is the same pointer that travels.
- destroying twenty-five entities from the middle of a chunk leaves exactly twenty-five, and the ones that remain have their own value, not the value of whoever landed on top of them.
- a world with two hundred live components destroys all of them when it dies.
- a command buffer that dies without being applied destroys what it had constructed.
--- ---
The glue with Concurrency
The ECS module does not know Concurrency exists: it declares IExecutor and nothing more. Anyone who wants the two together links Ethereal::EcsConcurrencyGlue, and it is there, in src/Ethereal/glue/, that the only file in the tree that includes both lives.
One task per system group was a design error, and that is measured
The first version submitted one CreateJob per system, every round. Measured on this machine (i7-6700, Release, manager with four workers), submitting seven at a time:
| measured | |
|---|---|
| submitting the seven | 175 to 371 µs (~28 µs per CreateJob) |
| until the last one starts | 2.7 to 5.4 ms |
An ECS system group runs in tens of microseconds. Submitting cost more than the whole work, and the latency was a hundred times the work. The test measured exactly this: 0 of 8,000 tasks picked up by workers. The caller always finished everything alone before anyone woke up, and the barrier the test existed to exercise never had to wait for anyone.
That is not a defect of the manager. Its header says what it is for: "routines intended for continuous execution", with a maximum deadline measured in seconds. It was built for long-lived routines. Using it as a per-frame fork-join was using it backwards.
So submission is paid once, in the constructor. The executor leaves a crew of continuous routines living on the manager's workers, and each RunAll then costs one signal on a condition_variable.
The barrier, and the trap it has to avoid
IExecutor::RunAll promises one thing: run these N tasks and only return when they have all finished. CJobManager::CreateJob is fire-and-forget: it returns no handle, does not signal when it finishes, has no wait. And its header says that in ePersistentWorkers a task is discarded when no worker is free.
A naive barrier that counted N completions would wait forever for a task that never ran, and the symptom would be a game that freezes now and then, with no error at all. The design that solves this has three pieces:
- A crew member only counts after it signs in. Signing in is the first thing it does when the manager starts running it. One that was rejected never signs in, and so is never waited for.
- Tasks are not distributed: they are claimed on an atomic counter. No slice is assigned to anyone, so no slice is left undone if someone is missing.
- The calling thread also works. With no crew at all (zero workers in the manager), it runs everything and the round ends. It gets slow, and it stays correct.
The wait has no deadline, on purpose. Giving up on it would mean returning to the scheduler with systems still running, and right after that it applies commands and iterates the world on top of them. A system that hangs must hang the frame, visibly.
And both conditions of the wait are necessary. "The work is done" is not enough: a crew member that has already done the last task is still inside the loop, reading this round's pointer and number. Returning at that point would let the next round overwrite them while it reads them. That is how the first version, with the shared block on the caller's stack, got a segmentation fault on the third round.
The manager gives half of what is asked, and the glue does not bake that into a magic number
Measured: asking for N continuous routines gives half of them, capped at the number of workers. With 8 workers, asking for 1 gives 1, asking for 5 gives 3, asking for 8 gives 4, asking for 12 gives 6. With 4 workers, asking for 12 gives 4.
Doubling the request would solve it, but it would bake in here a number taken from the current behavior of a manager that promises it nowhere. So the glue asks, counts, and asks for what is missing, stopping when a round adds no one. It works whatever the manager's rule is. CrewSize() says how many there actually are.
What the glue is worth, measured
Seven systems, of which only four are in a group that can be split. The other three run serially, with or without an executor. With a parallel fraction of 4/7 and five working (four crew members and the caller), the Amdahl ceiling for this load is 1.84×, not 5×.
| entities | serial | with the glue | ratio |
|---|---|---|---|
| 800 | 0.0070 ms | 0.0165 ms | 0.42× |
| 4,000 | 0.0146 ms | 0.0221 ms | 0.66× |
| 16,000 | 0.0583 ms | 0.0540 ms | 1.08× |
| 40,000 | 0.1452 ms | 0.1124 ms | 1.29× |
| 80,000 | 0.3158 ms | 0.2163 ms | 1.46× |
| 200,000 | 1.5175 ms | 1.1420 ms | 1.33× |
The glue loses with small worlds, and that is stated here. Below ~16,000 entities the cost of waking up and waiting is greater than the split work. The peak is 1.46× (79% of the ceiling), and the drop at 200,000 is the same bandwidth wall that the millisecond section measures: from there on, parallelism is not what is missing, memory is.
A group with a single system does not even wake anyone: it runs on the calling thread. In a dependency chain that is the most common case, and that is why the measured gain is what it is.
A defect this forced us to fix in the scheduler itself
RunOne indexes the command buffer by the task's index within the group, not by the worker number. With the serial executor that was harmless, because the tasks ran one after another. With a real executor, a group larger than the executor's width put two tasks writing to the same buffer at the same time. Build() now prepares max(Width(), largest group) buffers.
How it was verified
tests/ecs_glue.cpp, 16 checks. Thirty runs with the glue give exactly the same world digest as the serial executor, in Debug and in Release. The manager is restarted with zero workers in the middle of the test, and the round has to finish anyway, quickly and with the correct world. That is where "the caller also works" is enforced, not assumed. And there is a stress test of a thousand rounds of eight tasks each, with tasks that take time on purpose: all 8,000 must be done, exactly once each, and the workers must have claimed some. Without that last check, a glue that ignored the manager and ran everything serially would pass all the rest.
The measurement itself had to be corrected once, and the lesson stayed in the table: the marking system destroys entities from x > 900 onward, so an 80 thousand world emptied itself on the first frame and the first numbers were from an empty world, 4 µs per frame for 560 thousand updates. The live entities column is there for that.
---
What is missing
- The glue with Concurrency exists, but its gain has a condition.
ethereal-ecs-concurrency-glueis delivered and measured. What remains to be said here is the limit: below ~16,000 entities it is slower than running serially. An executor on top of the Coroutine module's fiber scheduler (context switches of 17.8 ns, instead of waking a thread) is the path to explore for small worlds. - A query kept between rounds, on the C side. Today
ETLC_EcsForEachChunkbuilds the query on every call, which makes it walk the world's archetypes once per round. For a game loop that is waste, and the spec only enumerates the walk. But anETLC_EcsQuerycreated once and reused is the missing piece for the C layer to be as fast as the C++ side. - The snapshot does not cross different ABIs. The integers are written in explicit little-endian, but the component bytes are raw memory, with the padding the compiler chose. A portable format would require field descriptions per component, which is the same piece that is missing for automatic handle fixup.
- The sanitizers and the twenty-four-hour run.
- The order within a chunk is not stable. Removing an entity brings the last one into its place, because an array with holes would force a test of every row inside the loop. Anyone who needs order stores it in a component. This is stated in the code, and it appears here again because it is the kind of thing that surprises newcomers.