KenseiECS Architecture
How the framework works internally. Written for contributors and for users who want to reason about the cost of an operation before they write it. The user-facing API is documented in the guide and the core concepts; this document explains the mechanisms behind that API.
All code discussed here lives in KenseiECS/Core, KenseiECS/Systems, KenseiECS/Unity and KenseiECS.Generators.
Data model at a glance
World
├── entity slots _generations[i] _alive[i] _componentCounts[i] indexed by entity index
├── component masks _componentMasks[word][i] ulong per (word, entity); 64 types per word
├── free list _freeIndices[] / _freeCount, _nextIndex slot recycling stack and high-water mark
├── pool registry _pools[typeIndex] ComponentPoolBase, created on first Pool<T>()
├── filter registry _allFilters plus _filtersByType[typeIndex] -> { Include[], Exclude[], Any[] } or null
├── groups _groups owning groups; each owned pool points back via _ownerGroup
├── world listeners IWorldEventListener[] copy-on-write; _dispatch = listeners present and not suppressed
└── counters _tick, _changeVersion
ComponentPool<T> _sparse[entity] -> dense index _denseEntities[d] -> entity _denseData[d] -> T
_changedVersions[d] (opt-in) _addHooks / _removeHooks (listeners, owner group, tracking; list owner / running frames)
Filter paged sparse[entity] -> dense slot _denseEntities[slot] -> entity slot 0 = terminator
Group _pools[] _count members occupy dense 0.._count-1 of every owned pool, same orderThree kinds of identifiers appear throughout:
intentity index: a slot number. Filters and groups yield these; pools are addressed by them.Entityhandle:(Index, Generation), 8 bytes.Worldmethods take these.inttype index:ComponentType<T>.Index, process-wide.
Entity slots
An entity is a slot index into parallel arrays owned by World:
| Array | Meaning |
|---|---|
_generations[i] | Generation currently stamped on the slot. Starts at 1. |
_alive[i] | Whether the slot currently holds a live entity. |
_componentCounts[i] | Number of components on the entity. Drives auto-destroy. |
_componentMasks[w][i] | Bit t & 63 of word t >> 6 is set when the entity has component type t. |
_usedWords[i] | Which mask words from 1 on may hold a component of the entity: bit w for word w (1 to 62), bit 63 for every word from 63 on. Set by an Add whose word was zero, reset only when the slot is released or the world cleared, so a clear bit means a zero word. DestroyEntity and CopyEntity read word 0 and the words with a bit. Allocated with the second mask word, so a world whose types all have indices below 64 has none (type indices are process-wide). |
_nextIndex is the high-water mark: slots below it have been handed out at least once. _freeIndices is a stack of released slots. CreateEntityInternal pops the free stack if it is not empty, otherwise takes _nextIndex++ and grows every slot array (doubling) when needed.
Generation changes on reuse, not on free
// CreateEntityInternal, free-list branch
index = _freeIndices[--_freeCount];
int generation = _generations[index] + 1;
if (generation == 0) {
generation = 1;
}
_generations[index] = generation;DestroyEntity clears _alive[i] and pushes the slot onto the free stack but leaves _generations[i] alone. The generation only advances when the slot is handed to a new entity. The consequence:
IsAlive(handle)isidx < _nextIndex && _alive[idx] && _generations[idx] == handle.Generation. A handle to a destroyed entity fails on_alive; after the slot is reused it fails on the generation.GetEntity(int)is simplynew Entity(index, _generations[index]). On a dead slot it returns exactly the handle the dead entity had while alive, andIsAliveis false for it. If the generation were bumped on free instead,GetEntityon a dead slot would return the handle of whatever entity is created in that slot next: a forged handle that starts out dead and later comes alive for an entity the caller never saw. Bumping on reuse closes that hole, which is why the debug layer no longer needs to throw onGetEntityfor dead slots.TryGetEntity(int, out Entity)is the bounds-checked form for arbitrary integers: it returns true and the handle only whenindex < _nextIndexand the slot is alive, andEntity.Nullotherwise.GetEntityhas no bounds check and is meant for indices a filter, group or pool just yielded.
Entity.Null is default(Entity), i.e. (0, 0). Generations start at 1 and wrap back to 1, never 0, so Entity.Null never matches a real entity in any world.
World.Clear() increments the generation of every slot below _nextIndex (alive or not), then resets _nextIndex and the free stack to zero. Every handle issued before Clear therefore fails the generation check afterwards, even if its slot is immediately reused. An AutoReset that throws during Clear does not stop it: every component of every pool is reset and dropped, filters and groups are emptied, then the first exception leaves (up to 2.4.0 the pools after the failing one, the filters and the groups kept their contents while the entities were already gone).
Component type registry
ComponentType<T>.Index is a static readonly int initialized from ComponentType.Register(typeof(T)) on first touch of the generic instantiation. Registration is process-wide, guarded by a lock, and stores the reverse map index -> Type, so ComponentType.TypeOf(int) and ComponentType.NameOf(int) resolve any index issued so far. Indices are dense and assigned in first-touch order; they are not stable across runs and must not be persisted. Snapshots identify types by name for this reason.
Because indices are process-wide and not per-world, every World in the process shares the same numbering. A world only allocates a pool for a type when Pool<T>() is first called on it; _pools, _filtersByType and the mask words are sized by the highest type index the world has seen.
Component pools
ComponentPool<T> is a sparse set per component type:
_sparse[entityIndex] -> dense index, or -1
_denseEntities[dense] -> entityIndex (ComponentPoolBase)
_denseData[dense] -> T (ComponentPool<T>)
_changedVersions[dense] -> int (ComponentPool<T>, null unless TrackChanges was called)
_count -> number of live entries; dense arrays have no gapsHas(int) is entityIndex < _sparse.Length && _sparse[entityIndex] != -1. Get(int) is two array reads. Iterating RawData/RawEntities from 0 to Count walks every component of the type contiguously.
Hooks and the _addHooks / _removeHooks fast path
Three optional features hang off a pool, each represented by a nullable field: IComponentListener<T> listeners (_listeners), an owning group (_ownerGroup) and change tracking (_changedVersions). A fourth is fixed by the type: _listOwner is set for components that hold a pooled list (EventBuffer<T>, see built on the core), and only Add needs it. One bool per direction is kept equal to "at least one of the three is set", plus the list owner for _addHooks and "a hooked call of this pool is running" for _removeHooks: AddListener and TrackChanges set both, the constructor sets _addHooks for a list owner, SetOwnerGroup, the RemoveListener that empties the list and the end of the outermost running call recompute them through RefreshHooks.
Add tests _addHooks and Remove tests _removeHooks. A pool with no hooks runs the plain path with one predictable branch and no further field reads; a pool with hooks calls the NoInlining helpers AddHooked / RemoveHooked, which examine the fields individually (RemoveHooked hands removals with typed listeners to RemoveNotified, which holds the try/finally of the hook frames, so a tracking or group pool does not pay for it). Most pools in a world have no hooks, so the common structural change stays at its minimum cost regardless of how many features exist.
Re-entrant calls: hook frames
Typed listeners run user code in the middle of an Add or Remove of their own pool, and that code may call the pool again: remove the same component (an OnRemoved that destroys its entity), remove a linked entity's component that removes this one in turn, or remove the component and add it again, to the same entity or to a new one that takes the freed slot. A pool with listeners therefore keeps a small stack of frames, one per Add or Remove whose typed listeners are running: the entity, whether it is a removal, a Done flag and, for a removal, the next listener to notify. The innermost frame lives in plain fields (_topEntity, _topNext, _topRemoving, _topDone), so a call that does not nest touches no array; a nested call moves it into _frames (four entries, allocated by the first AddListener, doubled for deeper nesting) and back when it returns.
- A
Removethat finds a frame for its entity that is a removal and notDonejoins it: it continues the notification from the frame's next listener, over the listener array the removal started with, and performs the removal. Linked entities that remove each other (A removes B, B removes A) therefore end: the secondRemoveof A joins A's frame instead of starting a new notification, so every listener gets oneOnRemovedper component and aHas-guarded cycle cannot recurse forever. - The swap-remove marks every frame of its entity
Done. A call whose frame isDonestops after the listener that returned: the component it was working on is gone, and whatever the slot holds now (the same entity's re-added component, or a new entity's) is a different component, announced by its ownAdd. The outerRemovedoes not remove it, and the outerAddgives the rest of its listeners noOnAdded.World.Clearfrom a listener marks every frameDonetoo, and ends aDestroyEntityin progress (seeworld.DestroyEntity). - Listeners that unsubscribe during a removal do not shift it:
AddListenerandRemoveListenerrecord the array being replaced in every running removal that has not recorded one yet, so the common case stores no array reference (and pays no GC write barrier). - While a frame runs,
_removeHooksstays set even if the last listener unsubscribed, so every nestedRemoveof the pool goes through the hooked path and keeps the frames exact.
A pool without listeners never pushes a frame: no user code runs inside its Add/Remove before the swap-remove, and filter and world listeners run after it.
Add
Add(int entityIndex, T value) throws if the entity already has the component (in every build), grows the sparse array to cover entityIndex and the dense arrays if full, writes the three arrays and increments _count. Then:
- Without hooks:
World.OnComponentAdded(entityIndex, TypeIndex)and return arefto the component.OnComponentAddedtells whether a filter or world listener ran and, if one did, whether the entity still has the component: when none ran, nothing can have moved it and therefis taken from the dense indexAddwrote. While no filter of that type has listeners and no world listener is registered, no user code can run there:OnComponentAddedupdates the filters without any re-check and reads nothing else; otherwise it reads the slot's generation first and re-checks the entity after each filter whose listeners ran. Each type's entry in_filtersByTypecounts the filters listing it that have listeners (Filter.AddListenerandRemoveListenerupdate every type of the filter when it gets its first or loses its last listener), so a listened filter of one type does not slow down theAddof the others. The part ofOnComponentAddedthat everyAddruns (count, mask bit, the_filtersByTypelookup) is inlined into the pool'sAdd; a type no filter mentions returns from there without a call, a type with filters continues inOnComponentAddedFiltered. In the same wayOnComponentRemovedis inlined intoRemove: without world listeners, a type no filter mentions clears its bit and decides the auto-destroy from the count it has just decremented, and a type with filters continues inOnComponentRemovedFiltered, which re-reads the count and the alive flag before the auto-destroy only when a filter listener could have run. While no user code can run, the filter loops (UpdateFiltersOnAddQuietly,UpdateFiltersOnRemoveQuietly) read the mask arrays once, not once per filter. - With hooks,
AddHooked, in this order: for a list owner, check the stored value's list (below); stamp_changedVersions[dense]withworld.NextChangeVersion()if tracking;group.OnAdded(entityIndex)if owned; with typed listeners, read the slot's generation and push anAddframe;World.OnComponentAdded(masks, counts, filters, world listeners);IComponentListener<T>.OnAddedwith arefto the stored value, to the typed listeners that were subscribed when theAddstarted and still are after the world update: one that a filter or world listener unsubscribed gets nothing, and one it subscribed is not told of thisAdd, which happened before it subscribed (the listener array is compared with the one read at the start; only when it changed,StillSubscribedbuilds the array to tell, an allocation); pop the frame; return theref. A pool without typed listeners when theAddstarts pushes no frame and sends noOnAddedfor it. Either way a typed listener subscribed during anAddgets its firstOnAddedfrom the next one (up to 2.4.0 it got this one when the pool already had a typed listener).
Every callback on the way (group, filter and world listeners, typed listeners) may move the component, by adding or removing this type elsewhere, or remove it again, even destroy the entity and let a new entity take its slot. So the dense index is re-read from _sparse before each typed listener and before returning the ref. Once the component is removed (the frame is Done), the remaining typed listeners get no OnAdded, also when the slot has the type again. Add returns a ref to a static scratch value (_orphan, reset to default each time) when the component is gone or the slot's generation changed, i.e. the entity was destroyed and the slot reused: writes through it land nowhere instead of on whichever entity took the freed slot. If a listener removed the component and added it to the same entity again, the ref points at the entity's new component.
The returned ref points at a dense slot, not at the entity. It is valid until the next Add of the same type to any entity (the dense array may be reallocated), or the next Remove of the same type from any entity (swap-remove moves the last component into the freed slot and clears the tail, so a ref to the entity that was last now points past _count). In a pool owned by a group, an Add or Remove of any of the group's types can also swap dense slots of every owned pool, for whichever entities occupy them.
Remove and swap-remove
Remove(int entityIndex) is a no-op when the component is absent. Otherwise, in order:
- With hooks,
RemoveHooked(with typed listeners,RemoveNotified):IComponentListener<T>.OnRemovedruns first, before any index is read, because a listener may remove other components of the same type and shift the dense layout; the data is still intact here. The removal runs in a frame (hook frames): a listener that removes this very component again (anOnRemovedthat destroys its own entity, or a linked entity that removes it back) joins the frame, continues the notification from the next listener and performs the removal; back in the outerRemove, the frame isDoneand it stops. Every listener gets oneOnRemoved, and the component is removed once. - If
TimplementsIAutoReset<T>,AutoResetruns on the component being removed. It is the only user code after the typed listeners and runs before the pool changes anything for the removal, on the hooked path (TakeOut) as on the plain one: when it throws, the component stays, its entity is still a member of the owning group and the component keeps its own change version. Up to 2.4.0 the hooked path ran it after the two steps below, so a throwingAutoResetleft the entity out of its group although it still had every owned component, and the component with the version of the pool's last one.AutoResetonly resets the value, so the order makes no other difference. Then, with hooks,group.OnRemoving(entityIndex)if owned, which moves the entity to the end of the member range in every owned pool while it still holds every owned component, and, if tracking, the version of the last dense entry is copied into the slot about to be freed (versions[_sparse[e]] = versions[_count - 1]), since that entry is the one the swap-remove will move there. - Swap-remove: the last dense entry (
_count - 1) is moved into the removed slot, and its owner's sparse entry is repointed. The vacated tail slot is set todefault(T), not AutoReset: after the move, the tail is a bitwise duplicate of the live component that was moved, so runningAutoReseton it would clear reference fields the live copy still uses. _sparse[entityIndex] = -1,_count--. With frames running, every frame of the entity is markedDone.World.OnComponentRemoved(entityIndex, TypeIndex): mask, count, filters, world listeners, auto-destroy.
The AutoReset branch tests the instance field _autoReset (the delegate bound at pool creation) for null. A static readonly bool would fold into a constant under the JIT, but IL2CPP turns each access into a class-init check plus a field load through the generic context.
SwapDense
SwapDense(int a, int b) exchanges two dense slots in full: _denseEntities, _denseData, _changedVersions when present, and the two sparse entries. It is internal and used only by owning groups. It is a no-op when a == b.
AutoReset and AutoCopy bridges
IAutoReset<T>.AutoReset(ref T) and IAutoCopy<T>.AutoCopy(ref T) are invoked through the interface on one boxed default(T) the pool constructor makes ((object)default(T) as IAutoReset<T>, null when T does not implement it). This is one boxing allocation per implemented bridge per pool, no allocation per call (the component is passed by ref), works for explicit interface implementations, and avoids runtime generic instantiation of a value-type bridge, which is not AOT-safe under IL2CPP. The call is plain IL, so Unity's managed code stripping, .NET trimming and NativeAOT see it and keep the implementations of every component type the code uses. Up to 2.4.0 the pool built closed delegates with Delegate.CreateDelegate over a method taken from typeof(T).GetInterfaceMap(...): no IL called the methods, stripping at Medium and High removed them (the interface map came back empty and the pool constructor threw). On CoreCLR the interface call costs what the delegate did: Remove with AutoReset measures the same within noise.
Growth
Sparse arrays grow to max(length * 2, entityIndex + 1) and are filled with -1; dense arrays (entities, data and versions when present) grow to max(length * 2, needed). Reserve sizes them exactly instead, for pools and filters alike: it states the need, and doubling would overshoot it. Starting sizes come from WorldConfig.InitialPoolSparseCapacity and InitialPoolDenseCapacity. A pool's sparse array only grows when a high-index entity actually receives the component, so a type that lives on few entities does not pay for the whole world.
Parallel arrays are allocated before any of them is replaced, both when a pool's dense arrays grow and when the world's slot arrays do (GrowEntityCapacity): an OutOfMemoryException leaves them all at the old size rather than some grown and some not. Growth moves the data to new arrays, so a ref or a RawData/RawEntities array taken before it no longer reaches the pool.
ComponentPoolBase vs ComponentPool<T>
ComponentPoolBase holds everything that does not depend on T: the sparse array, _denseEntities, _count, _ownerGroup, TypeIndex, ComponentType, Has, Remove (abstract), the introspection properties (SparseCapacity, DenseCapacity, ComponentSize, AllocatedBytes) and the internal GetDenseIndex, SwapDense, SetOwnerGroup, AddDefault, Clear, CopyTo, WriteComponents, ReadComponent. World, Group and WorldSerializer work through this base so that DestroyEntity, CopyEntity, Warmup, Clear, group swaps and snapshots can operate on pools without knowing T.
ComponentPool<T> is sealed so that the fast path in World.Pool<T>(), pools[typeIdx] is ComponentPool<T> pool, compiles to a single method-table comparison.
Clear, AddDefault, CopyTo, SwapDense, WriteComponents and ReadComponent are internal because each is one step of a larger operation that maintains the surrounding invariants:
Clearempties the pool without notifyingWorld; onlyWorld.Clearcalls it, andWorld.Clearresets masks, counts, filters and groups itself. Called on its own it would leave masks and filters pointing at components that no longer exist.AddDefaultexists forWarmup, which runs it on a temporary entity with events suppressed.CopyTois the per-pool step ofCopyEntity, which allocates the destination slot first and dispatches a singleOnEntityCreatedafter every pool has copied.SwapDensepermutes dense slots; only a group knows which permutation keeps the alignment invariant.WriteComponents/ReadComponentare the per-pool steps ofWorldSerializer.Save/Load, which own the stream format and the entity slots.
Remove stays public because it notifies World and is safe to call directly (that is how World.Remove<T>, OneFrameCleanup<T> (through RemoveAll, see built on the core) and CommandBuffer call it).
Component bitmasks
The mask is stored word-major: _componentMasks[word] is a ulong[] indexed by entity, and the world keeps _maskWordCount such arrays. Type index t lives in word t >> 6, bit t & 63. Two things grow it:
GrowEntityCapacityresizes every word array when a new slot is allocated past the current capacity.World.ReserveEntities(n)runs it ahead of time and sizes the free-slot list forn. Of the pools and filters it extends only the reserved ones (a pool givenReserve(k), a filter whose Inc types are all reserved or that has aReserveof its own), whose sparse side then covers thenslots, also when they are reserved after it; every other pool and filter keeps its size and grows on demand (see World config). The obsoleteWorld.Reserve(n)grew the sparse side of every pool and filter, those created later included: about4 × nbytes per pool and 4 KB per 1024 indices per filter. The reserved sizes are recorded after everything was allocated, so a reserve that fails does not make later pools and filters try the same allocation.EnsureMaskWordsallocates a freshulong[entityCapacity]for each new word when a pool is created for a type in a new 64-type block, or when a filter is registered that constrains such a block. The second word also brings_usedWords(see the table above). Type indices are process-wide, so a world gets the second word, and the summary, as soon as it uses any type whose index is 64 or above, whatever the number of types it uses itself.
Word-major layout means a single-word filter test reads one array, and adding a new 64-type block never touches existing arrays. With about 1000 component types the mask is 16 words, i.e. 128 bytes per entity slot, plus 8 bytes of _usedWords.
Has<T>
World.Has<T>(entity) reads the mask only:
int typeIdx = ComponentType<T>.Index;
int word = typeIdx >> 6;
if (word >= _maskWordCount) {
return false;
}
ulong[] maskWord = _componentMasks[word];
if ((uint)entity.Index >= (uint)maskWord.Length) {
return false;
}
return (maskWord[entity.Index] & (1UL << (typeIdx & 63))) != 0;It never creates a pool and never touches pool memory.
DestroyEntity and CopyEntity walk the mask
Both iterate only the set bits of the entity's words:
for (int w = 0; w < _maskWordCount; w++) {
ulong mask = _componentMasks[w][idx];
while (mask != 0) {
int bit = TrailingZeroCount(mask);
int typeIdx = (w << 6) | bit;
_pools[typeIdx].Remove(idx); // or .CopyTo(srcIdx, dstIdx)
mask &= mask - 1;
}
}TrailingZeroCount is BitOperations.TrailingZeroCount on .NET 5+. Elsewhere (Unity, netstandard2.1) it is the population count of ~mask & (mask - 1), the zeros below the lowest set bit, written as the usual shift-and-mask sum: no lookup table, so World has no static constructor and IL2CPP adds no class-initialization check or static-field load to each bit, and clang compiles the expression to a single count-trailing-zeros (rbit + clz on ARM64; MSVC keeps the arithmetic, still without a memory load). The cost is proportional to the number of mask words plus the number of components on the entity, not to the number of registered types. GetComponentTypes uses the same walk. DrainComponents and CopyEntity read word 0 and then only the words whose bit is set in _usedWords[i] (re-read after every word whose components ran user code, as are the mask arrays and the word count), and DrainComponents stops after the last word that holds one of the entity's components (see world.DestroyEntity).
Filters
A Filter is a sparse set of entity indices with no payload, kept up to date by World on every structural change.
Constraints and precomputed masks
The builder produces three sorted, deduplicated int[] of type indices: IncludedTypeIndices, ExcludedTypeIndices, AnyTypeIndices. The constructor turns them into three ulong[] masks sized to the highest constrained type index, plus:
ActiveWords: the words in which any of the three masks has a bit, so matching skips words the filter does not constrain.SingleWord/SingleIncludeMask/SingleExcludeMask/SingleAnyMask: when exactly one word is active, matching reads these scalar fields instead of walking arrays.SingleWordis -1 for multi-word filters.
A filter is single-word when all of its constrained types fall in the same 64-type block. With many component types this depends on first-touch registration order, not on how many types the filter names.
The all-ones Any mask trick
The single-word test is:
ulong entityWord = _componentMasks[w][entityIndex];
return (entityWord & include) == include
&& (entityWord & exclude) == 0
&& (entityWord & any) != 0;When the filter has no Any constraint, SingleAnyMask is ulong.MaxValue. End() guarantees that a filter without Any has at least one Inc, so a word that passes the include test is non-zero, and (entityWord & ulong.MaxValue) != 0 is true. The Any test therefore costs one AND per match with no branch on HasAny. The multi-word path accumulates anyHit across ActiveWords and returns anyHit || !filter.HasAny.
Sparse set with a 1-based dense array and a slot-0 sentinel
_denseEntities[0] = FreeSlot (-1), permanent terminator
_denseEntities[1.._count] = entity indices, no gaps
_denseEntities[_count+1..] = FreeSlot
sparse[entity] = dense slot (1-based), or -1Entities is new ReadOnlySpan<int>(_denseEntities, 1, _count). First()/Single() read slot 1.
The sparse side is paged: _sparsePages[entityIndex >> 10][entityIndex & 1023], with 1024-entry pages allocated on first touch and filled with -1. Iteration never reads the sparse side, so the extra indirection is not on the hot path, and a filter matching a few entities in a world with many slots pays only for the pages it touches instead of an int per entity slot. Contains(int) returns false for an index whose page was never allocated.
AddEntity returns early if the entity is already present. This matters because the world may test the same filter twice for one change (for example a type that is in a filter's Any list and a different type in its Inc list), and because UpdateFilterForEntity calls AddEntity without knowing the current membership.
RemoveEntity swap-removes: the entity in the last slot moves into the freed slot, the freed last slot is written with FreeSlot, the sparse entry becomes -1, _count--.
The reverse enumerator
Filter.Enumerator is a ref struct holding the filter, a Span<int> over _denseEntities (the array itself under IL2CPP, see below), _index and _current. It starts at _count + 1 and walks down:
public bool MoveNext() {
int i = _index - 1;
int entity = _entities[i];
if (entity == FreeSlot) {
Filter filter = _filter;
_entities = filter._denseEntities;
int count = filter._count;
if (i > count) {
i = count;
}
if (i == 0) {
_index = 1;
return false;
}
entity = _entities[i];
}
_index = i;
_current = entity;
return true;
}The normal step is one span load, one compare against FreeSlot, two field writes. Reading FreeSlot means one of three things, all handled by the same slow path:
- The terminator at slot 0: normal end of iteration.
_indexis parked at 1 so extraMoveNextcalls keep probing the terminator instead of reading out of range. - The live range shrank below the cursor because several entities were removed in one loop step: re-read
_count, clampito it, continue from there. - The cached span points at a retired array (see growth below): re-cache and continue at the same slot, which holds the same entity in the new array.
Why the hot path is call-free: MoveNext makes no method calls on this and reads nothing from the heap except the element. Passing a struct by reference to a helper exposes its address, which prevents the JIT from promoting the enumerator's fields to registers; keeping the slow path inline avoids that. Using a Span<int> rather than the raw array keeps the length inside the promoted struct, so the bounds check on _entities[i] does not become a heap load of array.Length after a re-cache. Under IL2CPP the field is the raw int[] instead: the enumerator's Il2CppSetOption attributes drop the array's bounds check, which they cannot do for a Span indexer (an IL2CPP intrinsic that always checks), and the span also added a metadata-initialization check to every inlined MoveNext. The cursor never leaves the cached array: it starts at _count, below the array's length, only goes down, and is clamped to the count of the array it re-caches. No per-step version or count check is needed because the sentinel doubles as the end-of-range check.
Why reverse: swap-remove fills a freed slot with the entity from the highest live slot. Iterating from high to low, that entity has already been visited, so removing the current entity (or anything at or above the cursor) never causes a double visit. New entities are appended above the cursor and are not visited in the current loop.
Poisoning the retired array on growth
GrowDense allocates the bigger array, copies, fills the new tail with FreeSlot, then fills the old array entirely with FreeSlot:
_denseEntities = grown;
Array.Fill(old, FreeSlot, 0, old.Length);An enumerator still holding a span over the old array lands on the FreeSlot path on its next step and re-caches the current array. Without poisoning it would keep reading stale entity indices from the retired array.
The per-type table and which lists are tested on add vs. remove
World._filtersByType is an array indexed by type index. Each entry is either null, for a type no filter mentions, or a TypeFilters object with three arrays: Include, Exclude, Any. RegisterFilter creates the entry on demand (TypeFiltersFor) and appends the filter to the array matching each constraint kind. Keeping the three lists in one object means a structural change looks up one entry and tests it for null once; for the many types no filter constrains, that single branch is the entire filter cost.
When the entry exists, UpdateFiltersOnAdd / UpdateFiltersOnRemove walk the three arrays:
| Event | Include filters of t | Exclude filters of t | Any filters of t |
|---|---|---|---|
component t added | full mask test, AddEntity on match | RemoveEntity without a test (an excluded type appeared, the entity cannot match) | full mask test, AddEntity on match |
component t removed | RemoveEntity without a test (a required type is gone) | full mask test, AddEntity on match | full test, AddEntity or RemoveEntity (another Any type may still satisfy it) |
Adding t can only move an entity into filters that require t and out of filters that exclude it; removing t only the reverse. Half of the updates therefore skip the mask test entirely. The lists are arrays, not List<Filter>, because this loop runs on every Add and Remove.
The untested half relies on t staying put, and a filter listener can break that: an OnEntityRemoved that adds t back during a removal, or an OnEntityAdded/OnEntityRemoved that removes t again (or destroys the entity, whose slot a new entity may then take) during an add. The nested call has already updated every filter for the entity, so the outer loop must not undo it. AddEntity and RemoveEntity return whether listeners ran; only then is the entity re-checked: on remove, the Include loop stops when t is back; on add, the update stops when the entity no longer has t or the slot's generation changed, before the Exclude filters would drop an entity that matches them. Without listeners the loops cost what they did before.
EntityMatchesFilter performs no bounds check against _maskWordCount: RegisterFilter calls EnsureMaskWords for every word the filter constrains, so the mask arrays it reads always exist, and an unregistered type's word simply reads zeros.
Registration, deduplication, PopulateFilter
FilterBuilder.End():
- Throws if there is neither an
Incnor anAnyconstraint. - Throws if a type is in both
IncandExc, or in bothAnyandExc. - Drops any
Anytype that is also inInc(redundant: a required type always satisfies "at least one of"). - Sorts all three lists and calls
World.RegisterFilter.
RegisterFilter compares the three sorted arrays against every registered filter and returns the existing instance on a match. Order of Inc<A>().Inc<B>() versus Inc<B>().Inc<A>() does not matter. Static specs (world.Filter<Inc<A, B>, Exc<C>>()) and generated Init code go through the same builder, so they deduplicate against builder-made filters. The comparison is linear in the number of registered filters, which is why filters belong in Init, not Run.
For a new filter, PopulateFilter first checks that every Inc type has a pool; if one does not, nothing can match yet and the scan is skipped. Otherwise it walks every slot below _nextIndex, tests alive entities against the filter and adds the matches. Filters are never unregistered; they live until World.Destroy.
Owning groups
A filter finds entities; reading their components still goes through each pool's sparse array. An owning group removes that indirection for a fixed set of component types by rearranging the pools themselves. world.Group<T1, T2>() (also three and four types) returns a Group<T1, T2> whose Data1, Data2 and Entities spans can be indexed in lockstep.
The alignment invariant
A group holds its owned pools (ComponentPoolBase[] _pools) and a member count _count. The invariant it maintains at all times:
In every owned pool, dense slots
0 .. _count-1hold the components of exactly the entities that have all owned components, in the same entity order in every pool.
Members are packed at the front; entities that have some but not all of the owned types sit in the remaining slots _count .. pool.Count-1 in no particular order. From this:
Entitiesis_pools[0].RawEntities[0 .. _count),Data1is_p1.RawData[0 .. Count), and so on.Data1[i],Data2[i]andEntities[i]belong to the same entity.- Iteration is a plain loop over spans: no sparse lookup, no mask test, one bounds check per span access.
Contains(e)(internal) ispools[0].Has(e) && pools[0].GetDenseIndex(e) < _count. Checking the first pool is enough because a member sits at the same slot in every pool.
Because the group permutes dense slots, the order of RawData/RawEntities in an owned pool is no longer insertion order: members come first. The two arrays stay parallel, and sparse entries are always repointed, so pool.Get(e) and filter loops are unaffected.
OnAdded: joining the group
AddHooked calls group.OnAdded(entityIndex) immediately after the pool has stored the new component, before filters, world listeners and pool listeners run:
- If any owned pool lacks the entity, return: not a member yet.
- If
pools[0].GetDenseIndex(e) < _count, return: already a member. slot = _count++; for every owned pool,pool.SwapDense(pool.GetDenseIndex(e), slot).
Step 3 moves the entity's component into the first non-member slot of each pool and moves whatever non-member was there into the entity's old slot. AddHooked then re-reads the dense index from _sparse, so the ref it returns and hands to pool listeners points at the moved component.
OnRemoving: leaving the group
RemoveHooked calls group.OnRemoving(entityIndex) after pool listeners and AutoReset and before the swap-remove, while the entity still holds every owned component:
- If not
Contains(e), return. last = --_count; for every owned pool,pool.SwapDense(pool.GetDenseIndex(e), last).
The entity now sits at slot last in every owned pool, which is the first non-member slot, and the member that used to be last has taken its place. The pool that is actually removing the component then swap-removes from slot last as usual: the pool's final element (a non-member, or the component itself) lands there, outside the member range. In the other owned pools the entity's components stay at slot last among the non-members, which is exactly where an entity that lacks one owned type belongs.
DestroyEntity drains components one pool at a time; the first owned pool's Remove ends the membership, the remaining owned pools see !Contains and do nothing.
Populate
RegisterGroup throws if any pool already has an owner or if a type is listed twice, sets _ownerGroup on every pool (which sets _addHooks and _removeHooks), adds the group to _groups and calls Populate(). Populate picks the pool with the fewest components and calls OnAdded for each of its dense entities, walking forward. A hit swaps the member to slot _count, which is at or below the cursor; the non-member displaced to the cursor's slot was already visited, so the forward walk still sees every entity exactly once. Cost: O(smallest pool count × P), P being the number of owned pools.
Interaction with filters, Clear, Warmup and snapshots
- Filters store entity indices and never look at dense order, so a filter over grouped types keeps working, and destroying entities from inside a filter loop keeps the group exact (
Group_FilterAndGroup_Coexistin the tests). World.Clearsets every group's_countto 0 after emptying the pools.Warmupadds a default of every registered type to its temporary entity, which makes it a member of every group whose types are all registered; destroying it removes it again, so no group keeps the dummy. If a listener destroys the temporary entity,Warmupchecks its handle before every type and continues on a fresh one, never on an entity the listener created in the freed slot; a type a listener already added is skipped.WorldSerializer.Loadrestores components throughpool.Add, so groups that exist beforeLoadfill normally.
Why a pool belongs to one group
The invariant fixes the dense position of every member in the pool. Two groups owning the same pool would each demand that the array be packed by their own membership, and both orders cannot hold at once. RegisterGroup therefore rejects a pool that already has an owner. world.Group<A, B>() returns the existing group only for the same types in the same order (OwnsExactly compares position by position); asking for Group<B, A>() afterwards throws, because the pools are owned.
Destroying members inside a group loop
Iterate downward. Destroying the member at index i swaps it with the last member (at an index >= i) and then swap-removes within the pool, which touches only slots >= i; slots below i are untouched, so the loop continues correctly. A forward loop would skip the member that was moved into slot i.
Cost per structural change
Addof an owned type: PHaschecks; if the entity thereby gains all owned types, PSwapDensecalls, each moving twoints, twoTvalues, two version entries when tracked, and two sparse writes.Addof a type nobody owns: unchanged.Removeof an owned type from a member: P swaps plus the ordinary swap-remove. From a non-member: oneContains.- Iteration: O(members), contiguous, no indirection.
Change tracking
Change tracking is opt-in per pool. TrackChanges() allocates _changedVersions, an int[] parallel to the dense arrays (resized with them in GrowDense), stamps every existing component with one fresh version so they all count as "changed now", and sets _addHooks and _removeHooks. TracksChanges reports the state.
Per-slot versions and the world-wide counter
World._changeVersion is a counter: NextChangeVersion() returns the next value (see counter wrap for what happens after int.MaxValue), and World.ChangeVersion reads the current value. Three operations take the next value and write it at the component's dense slot:
Addon a tracking pool (insideAddHooked, before the group swap so the value travels with the component).Modify(entityIndex), which stamps and returns theref.MarkChanged(entityIndex), which stamps without returning anything.
ChangedVersion(entityIndex) reads the entry and throws InvalidOperationException if the pool does not track. ChangedSince(entityIndex, version) is ChangedVersion(entityIndex) > version until the counter first wraps, and a comparison by age after that.
The consumer pattern is to store world.ChangeVersion at the end of a system's Run and pass it to ChangedSince the next time. Because every write takes a distinct, increasing number, a bookmark taken at any point in a frame separates "written before" from "written after" exactly, whether the producer runs earlier or later in the pipeline than the consumer. A per-tick stamp could not tell a write made earlier in the same frame (already handled) from one made later (not yet handled). World.Clear resets the tick but not the change counter, so bookmarks stay meaningful across it.
Versions follow the component
Versions are stored per dense slot, so every operation that moves components moves versions with them:
Remove:RemoveHookedcopiesversions[_count - 1](the entry of the last component, which the swap-remove is about to move into the freed slot) into the freed slot's entry. The removed component's own version is discarded with it; the stale value left at the tail is overwritten by the nextAdd.SwapDense: swaps the two version entries along with the data, so a group joining or leaving keeps each component's version (Group_ChangeTracking_FollowsSwapsin the tests).GrowDense: resizes the version array with the dense arrays.
Counter wrap
The counter advances with every Add, Modify and MarkChanged on a tracking pool, so a game that marks a few thousand components per frame passes int.MaxValue after hours of play. When the increment overflows, the counter starts again at 1 (0 and below never name a write) and the world sets _changeVersionWrapped; every pool copies that flag into its own _changeCounterWrapped when the wrap happens and when it starts tracking, so ChangedSince reads a field of the pool, not of the world.
Until the first wrap nothing changes: ChangedSince is the plain changed > version. After it, ChangedSince compares ages (World.ChangedAfterWrap): the age of a version is the number of writes between it and the current counter value, current - version, plus int.MaxValue when that is negative (the ring 1..int.MaxValue). A component changed since a bookmark when its version is younger than the bookmark; a bookmark of 0 or below, the value of a world that tracked no write yet, means "everything changed since".
Ages only order versions that are less than one turn of the counter old. A component left alone for a whole turn would look new again, so the stored versions are aged: at the wrap and then every ChangeVersionAgingPeriod (2^29) writes, NextChangeVersion calls AgeChangeVersions, which walks every tracking pool and gives each version older than ChangeVersionAgeLimit (2^30) writes exactly that age. Before the first wrap those calls (one test of the low bits per write, a call every 2^29 writes) age nothing. Modify and MarkChanged may run in a ParallelRunner job, and the counter is incremented without synchronization: workers can hand out the same version, and a worker that read the counter late can write it back below versions other workers already stored. Three things keep such writes from being lost after the first wrap. A stored version whose age comes out larger than any stored version can have (ChangeVersionLeadLimit: the age limit plus an aging period plus 2^28) is ahead of the counter, and StoredChangeVersionAge counts it as age 0, the newest, for ChangedSince and for the aging. AgeChangeVersions replaces a version with Interlocked.CompareExchange, only if it is still the old one it read, so a version a worker has just written is never overwritten. The first wrap (FirstWrap) is aged by one worker, chosen by a compare-exchange on _changeVersionWrapGate, by the plain difference to int.MaxValue (the versions of the old turn may be of any age then); the others spin until it sets _changeVersionWrapped before they store a version of the new turn, which that pass would take for ancient, and the aging worker sets the flag also when its pass throws, so the others go on. What remains is harmless: a job's writes may share a version, and may show as changed against a bookmark taken after the job; no write is lost. The consequences for a caller, also stated on World.ChangeVersion:
- After the wrap, a bookmark is exact for the next 2^30 (about a billion) counted writes. Against an older bookmark, a component written before it can be reported as changed (its version was aged to 2^30); a bookmark older than
int.MaxValuewrites means nothing. - Versions must be compared with
ChangedSince. A hand-writtenpool.ChangedVersion(e) > bookmarkkeeps working until the wrap and breaks after it.
Up to 2.4.0 the counter went negative at the wrap, so ChangedSince reported nothing as changed against a bookmark taken before it and old components as changed against one taken after it.
Why Get stays untracked
Get is the read path and by far the most frequent pool operation. Tracking it would put a counter increment and an array store on every read, and, since a ref return cannot tell a read from a write, would mark every read as a change and make ChangedSince meaningless. Writes therefore opt in: Modify for read-modify-write, MarkChanged after a write done some other way. Writes through Get, RawData, group Data spans or the inspector's SetRaw are invisible to tracking unless followed by MarkChanged. CommandBuffer.Set on an existing component and a CopyEntity that overwrites a component write through Modify, so they count as changes.
Cost: 4 bytes per dense slot on tracking pools; one store plus one counter increment per Add, Modify and MarkChanged; two reads and a test of the pool's wrap flag per ChangedSince (an age comparison once the counter has wrapped). Pools that do not track pay nothing beyond the shared _addHooks / _removeHooks branch.
Structural change flow
world.Add<T>(entity, value)
- Under
KENSEI_DEBUG,ValidateHandle: the handle must be alive, or be the entity whoseDestroyEntityis running (see the debug section). Pool<T>(): fast path type check on_pools[typeIdx]; on first useCreatePool<T>grows_poolsand the mask words to cover the type index and allocates the pool.pool.Add(entity.Index, value):- Under
KENSEI_DEBUG, the slot must be alive or dying. - Throws
InvalidOperationExceptionif the component is already present. - Grows sparse/dense arrays as needed, stores the value,
_count++. - If
_addHooks: list ownership check, version stamp, groupOnAdded(may swap the component to the front), then the steps below, thenIComponentListener<T>.OnAdded. World.OnComponentAdded:_componentCounts[e]++, sets the mask bit (and the word's bit in_usedWords[e]when the word was zero and is not word 0), looks up_filtersByType[t]; if it exists,Include(test, add),Exclude(remove),Any(test, add), eachAddEntity/RemoveEntityfiringIFilterListenercallbacks synchronously; after a filter whose listeners ran, the update stops if the entity losttor the slot was reused. With world listeners theAddis their notification from the start (BeginNotify, before the filters), then everyIWorldEventListener.OnComponentAdded(e, t)while the entity still hast(NotifyWorld): a filter listener that tooktaway told them nothing, and they hear of neither (see notification frames).- Returns
ref _denseData[dense], or the scratch value when the component is gone or the slot holds another entity.
- Under
CreateEntity<T>(T) is CreateEntityInternal() (allocate a live, empty slot), then this Add, then OnEntityCreated to world listeners. CopyEntity is CreateEntityInternal(), then CopyTo per set mask bit of the source (each of which goes through pool.Add and the flow above), then a single OnEntityCreated. With world listeners both begin the creation as a notification of its own (a LifecycleKey frame) before the first component is added, so an entity that a listener of one of its components destroys while it is built gets neither OnEntityCreated nor OnEntityDestroyed.
world.Remove<T>(entity)
- Under
KENSEI_DEBUG,ValidateHandle. - If no pool exists for
T, return.Removenever creates a pool. pool.Remove(entity.Index):- Return if the component is absent.
- If
_removeHooks:IComponentListener<T>.OnRemovedwith the data intact. AutoReseton the removed component, if implemented.- If
_removeHooks: groupOnRemoving(member moved to the end of the member range in every owned pool), version copy for the slot about to be freed. - Swap-remove, tail defaulted, sparse cleared,
_count--. World.OnComponentRemoved: decrements_componentCounts[e](only if the entity is alive; see the drain loop below), clears the mask bit, looks up_filtersByType[t]; if it exists,Include(remove),Exclude(test, add),Any(test, add or remove). For an entity whoseDestroyEntityis draining it, onlyIncludeandAny(remove): its components not removed yet are still in the mask and would let it intoExcludefilters oft. With world listeners the removal is their notification from the start (BeginNotifyreads the slot's generation before the filters), thenOnComponentRemoved(e, t)to them while the entity is still alive and still lackst: a filter listener that addedtback told them nothing, and they hear of neither. A listener that destroys the entity and creates another that takes the slot gets the slot it would get without listeners; beforeCreateEntityhands it out, the world listeners not told of the removal yet are told (see notification frames below).- Auto-destroy: if
_componentCounts[e] == 0and the entity is alive,DestroyEntityInternal(e)runs beforeRemovereturns.
_dispatch is a single bool kept equal to _eventListeners.Length > 0 && !_suppressEvents; AddEventListener, RemoveEventListener and SuppressEvents recompute it, so the hot path tests one field instead of two.
world.DestroyEntity(entity)
public void DestroyEntity(Entity entity) {
if (!IsAlive(entity)) {
return;
}
DestroyEntityInternal(entity.Index);
}DestroyEntityInternal(idx):
_alive[idx] = falsebefore anything else. A listener that callsDestroyEntityon the same entity re-entrantly hits theIsAlivecheck and becomes a no-op; a listener that callsRemoveon it does not decrement the count (see step 3). UnderKENSEI_DEBUGthe slot is pushed onto a stack of dying slots, which handle validation accepts.OnEntityDestroyed(idx)to world listeners. The entity is dead (IsAlivefalse) but its components are still readable.DrainComponents(idx), in afinallyso it runs even if a listener threw:csharpdo { int remaining = _componentCounts[idx]; // never below the set bits _componentCounts[idx] = 0; if (_orphans) { remaining = int.MaxValue; // an orphan's removal broke that: read every word } else if (remaining == 0) { return; // auto-destroy: no bit is set } var masks = _componentMasks; int words = _maskWordCount; for (int w = 0; w < words; w = NextUsedWord(idx, w)) { ulong mask = masks[w][idx]; if (mask == 0) { continue; // a word emptied by Remove keeps its bit } do { if (_clears != clears) { return; // a listener called World.Clear } int bit = TrailingZeroCount(mask); _pools[(w << 6) | bit].Remove(idx); mask &= mask - 1; remaining--; } while (mask != 0); if (remaining <= 0 && _componentCounts[idx] == 0) { return; // every bit met, nothing added } masks = _componentMasks; // a listener may have added a mask word words = _maskWordCount; } } while (_componentCounts[idx] != 0 && _clears == clears);Each
Removeruns the full pool flow (pool listeners, AutoReset, group swap, filter updates, worldOnComponentRemoved). Listeners may re-add components to the dying entity. Such a component goes through the normalAddflow, so the dying entity enters the filters it matches together with the components not removed yet (filter listeners getOnEntityAddedfor an entity whoseIsAliveis false) and leaves them again when the next pass removes it.OnComponentAddedincrements_componentCountsunconditionally, whileOnComponentRemovedskips the decrement for a dead entity, so after a pass a non-zero count means "something was re-added" and the loop runs again, reading oneintinstead of rescanning every mask word. The mask is not cleared ahead of the removals: eachRemoveclears its own bit, so the listeners of one removal still see the components not removed yet (world.Hasagrees with the pools, as in a plainRemove), and a component re-added during the pass sets its bit again for the next pass. Up to 2.2.1 each mask word was zeroed before its bits were iterated, soHassaidfalsefor components still in their pools, and components in later words could let the dying entity intoExcludefilters. A pass stops early once it has met as many set bits as the count it started from while the count is still 0 (nothing was added): the count is never below the number of set bits (equal while the entity is alive, anAddraises both, a removal from the dying entity lowers only the bits), so the bits met are every bit there was, and the words after are empty. An auto-destroy (count 0) reads no word at all; a component that a listener removed before the pass reached it, or one added during the pass, makes the pass read every word as before. The one case where the count can fall below the bits is an orphan (see exception safety): an interrupted destroy leaves components in their pools without mask bits, and removing one later lowers the count of the entity that took the slot. The world remembers that it released a slot with bits still set (_orphans), and from then untilWorld.Clearevery pass reads every word without stopping early. After word 0 the pass reads only the words whose bit is set in_usedWords[idx], a clear bit meaning a zero word. The mask arrays, the word count and the summary are read once and again only after a word whose bits were removed, since only a removal runs code that can add a mask word or a component in a new word: an empty word costs the load of its array and of the slot's bits in it. The loop is bounded by_maskWordCount, not by the length of the outer array, which anEnsureMaskWordsthat ran out of memory may have left longer. A listener that callsWorld.Clearchanges_clears: the drain stops before the next removal, because the slot has been reset and may already hold an entity the listener created. UnderKENSEI_DEBUGmore than 1000 passes throws.ReleaseSlot(idx), in an innerfinally: count and mask words zeroed after an interrupted drain (a completed one leaves them zero, which is what letsCreateEntityInternaltake a free slot's count without writing it), and when that drain left bits set, the slot taken out of every filter and owning group (LeaveFiltersAndGroups); the slot's_usedWordscleared,_aliveCount--,_releases++, and the slot pushed onto the free stack (growing the stack is a separate, non-inlined call), except a slot whose drain left orphans, which is kept off the free stack untilClear(KeepSlot, see exception safety). Skipped after aWorld.Clearfrom a listener, which has already released every slot. UnderKENSEI_DEBUGthe debug name is dropped and the slot leaves the stack of dying slots it joined in step 1.
Warmup uses the same machinery on a temporary entity with events suppressed, so world listeners and the profiler never see it.
Event ordering and exception safety
Ordering follows directly from the flows above:
- On
Add: version stamp and group swap (invisible to listeners), then filter listeners (per filter, in table order), thenIWorldEventListener.OnComponentAdded, thenIComponentListener<T>.OnAdded. ForCreateEntity/CopyEntity,OnEntityCreatedcomes last, after every component is in place, so listeners never observe an entity without components; it does not come at all when a listener of one of the components destroyed the entity (CopyEntitystops copying then, and when the source is destroyed; it checks both handles whenever_releaseschanged during a copied component). A listener that removes the component again ends theAddfor everyone after it: a filter listener's removal tells world listeners nothing (with world listeners theAddis their notification from its start, before the filters are updated, and none of them has heard of it yet; see the notification frames below), and typed listeners after the removal get noOnAdded. A filter listener that removes the component and adds it back right away tells world listeners of neither, and the outerAdd, whose change holds again, sends oneOnComponentAdded; typed listeners get oneOnAdded, from the nestedAdd. Up to 2.4.0 world listeners got theOnComponentRemovedalone after a removal, and the removal and then two additions after a removal and a re-add (as documented in 2.2.1 and 2.2.2). - On
Remove:IComponentListener<T>.OnRemoved(data intact, entity still a group member), thenAutoReset, then the group swap and version copy, then the swap-remove, then filter listeners, thenIWorldEventListener.OnComponentRemovedwith the entity still alive, then auto-destroy if it was the last component. A filter listener that adds the component back tells world listeners of neither the removal nor the addition (up to 2.4.0 they got theOnComponentAddedalone). One that destroys the entity and creates one in its slot (a replacement) does not change the slot the new entity gets: the world listeners not told of the removal yet hear it before the new entity's events. - On
DestroyEntity:OnEntityDestroyedfirst, with the dead flag set and components still readable; then oneRemoveflow per component. - Notification frames. A listener may undo the change it is told about, directly or from a callback further in (a listener of another entity's change, a filter listener under a world notification). Every listener has to hear an entity's changes alternately, and the last call it gets has to match the world.
FilterandWorldeach keep a stack of the notifications in progress (NotifyFrame, innermost last, re-indexed after every callback since a nested notification may grow it). A filter's frame holds the slot,Told(the position of the listener being told) and the listener arrays below; the world's also holds the slot's generation, the key (the component type, orLifecycleKeyforOnEntityCreatedandOnEntityDestroyed), theKind(added, removed, created, destroyed),Told(-1 before the first listener) andLast, the position of the last listener to be told (-2 untilResolveNotifyhas chosen them). A notification of the same entity nested in an open one (a filter: the same slot; the world: the same slot, generation and key) goes only to the listeners that heard of the change it undoes: positions 0 to the open frame'sTold, in the same order. The outer notification goes on only while its change holds, checked before every listener but the first (the world checks before the first too when user code ran since the change): a filter checks that the entity is still in it (or still out), the world (ChangeHolds) that the slot still has the frame's generation and that the component's mask bit is set (or clear) or the slot alive (or dead). Once the change is undone it stops, so the listeners after the one that undid it heard of neither. A notification of another entity, or of another key, goes to every listener. Fast path: with one listener and no open frame of the entity (for a worldAddorRemove, also no filter listener of the type), no frame is pushed: a nested notification would be limited to that listener, which is every listener, and there is no listener after it to stop for. Up to 2.4.0 only typed listeners stopped: a second filter listener gotOnEntityRemovedand thenOnEntityAddedfor an entity the first had taken out of the filter again, and the same for world listeners. - Changes count from the start. With world listeners,
AddandRemovebegin their frame before the filters are updated, andCreateEntityandCopyEntitybegin aLifecycleKeyframe of kind created before the first component is added (Told-1): a filter listener, or a listener of the new entity's component, that undoes them tells world listeners nothing. A destroy nested in the creation is a lifecycle notification nested in it, so it goes only to the listeners that heardOnEntityCreated: none before it is sent.OnEntityCreateditself goes to the listeners subscribed when it is sent (also one that a listener of the components subscribed while they were added), and a listener that is to hear it but has not yet, or that subscribed before it was sent, is not told of a destroy that undoes it; one subscribed while it is sent is. Without world listeners when the creation began, no frame is pushed:CreateEntityandCopyEntityrecord the entity in_unannounceduntil itsOnEntityCreated(the innermost creation; the ones it is nested in, when a listener of a component of an entity being made creates another, are pushed to_unannouncedOuter, allocated only then), andNotifyEntityDestroyedskips every such entity (Unannounced), so a world listener that a listener of its components subscribed meanwhile does not hear the destroy of an entity whose creation it never heard of. This holds for every creation still in progress, the outer ones of nested creations included. To such a listener the entity's lifecycle is absent untilOnEntityCreated, while its components follow the general rule: it hears the component changes that happen after it subscribed. Each creation saves the innermost entry and the depth when it begins and puts them back when it ends, also through its handler (since 2.5.1; the handler is inCreateEntityObservedandCopyEntityObservedonly, not in theCreateEntityof a world without listeners), so an entry is there exactly while its creation runs: aNextTickor aSystemsRunner.Runthat a listener calls inside a creation keeps it. An exception that leaves a creation beforeOnEntityCreated, with or without world listeners, records the entity in a list of its own (_cut,CutCreation): it gets noOnEntityDestroyedeither, untilNextTickoutside a runner or the end of the outermostSystemsRunner.Runforgets that list (ForgetCut).ClearandWorldSerializer.Loadend the work in progress (AbandonWorkInProgress), as the restored generations may give an entity the handle of one that work is about: every frame gets generation 0 (no entity has it: it matches no notification and its change never holds;TellWorldreads the generation from the frame) andLast-1 (no listener left to tell), the entries are emptied (DropUnannounced; the depth is kept, which every creation still running restores when it ends), and_clearsis raised, which stops aDestroyEntityand aCopyEntityin progress. A creation that finds its own entry empty when it ends announces nothing and puts back none of the entries it saved. - Replacements. Listeners never change which slot or handle an entity gets. A listener may destroy the entity whose component's removal is being told and create another, which takes the freed slot (the top of the free stack). With world listeners
CreateEntitytakes the slot throughCreateEntityNotified, andCopyEntitycallsFinishRemovalsOfNextSlotbefore it checks its source (a listener told there may destroy the source;CopyEntitythen returnsEntity.Null, or throws underKENSEI_DEBUG, as for any dead source, instead of leaving an entity without components) and makes the copy inCopyEntityNotifying: while the slot it is about to hand out has an open removal frame of the old entity with listeners left (RemovalOpen: kind removed, same generation,Lastnot reached),FinishRemovalsOfSlottells those listenersOnComponentRemovedfirst, innermost frame first, advancing each frame'sTold. Then the slot goes to the new entity, whose events go to every listener, and the outer removal loops find nothing left:NotifyWorldskips the positions up toTold, andChangeHoldsfails once the slot holds the new generation. A removal thatFinishRemovalsOfSlotreached before its own loop began (its filter update was still running) goes on after the listeners already told. A filter tells entities by slot, as it holds them, so to a filter's frame a new entity in the slot is the same entity. Up to 2.4.0 such a replacement cut the removal short: the listeners after the one that made it never heard the removal, and then heard the new entity's component come. Warmup,ClearandWorldSerializer.Loadfire no world events and no profiler records:WarmupandLoadcallSuppressEvents(true), which clears_dispatchand is honoured byEcsProfiler;Clearnever callsRemoveat all, it resets pools, filters and groups directly. Filter listeners and pool listeners are not suppressed: they hang offFilter.AddEntity/RemoveEntityandAddHooked/RemoveHooked, whichLoadandWarmupdo exercise.
Listener lists (World, Filter, ComponentPool<T>) are copy-on-write arrays. A dispatch loops over the array it captured at its start, so a listener that adds or removes listeners mid-dispatch neither shifts the loop nor gets skipped or invoked twice. A listener hears the changes that happen after it subscribed. AddListener/RemoveListener (AddEventListener/RemoveEventListener) store the array of the moment in every open frame that has none yet (NotifyFrame.Base: the listeners when that change happened). A notification nested in a frame whose listeners changed goes to Join: of the listeners the outer one tells (Listeners, or Base) those up to its Told that are still subscribed, in their order, then those of the array when the nested change happened that were not in the outer frame's Base (they subscribed after the outer change, while the entity was as it left it, so the nested change is news to them), are still subscribed and have not heard of the outer change. A listener subscribed after a change happened is not told of it: a world listener that a filter listener subscribes while the filters are updated hears the changes after it, not the one in progress (up to 2.4.0 it got that change, and could hear it twice). A listener unsubscribed during a dispatch is still called by that dispatch, which goes over the listeners it chose, but is in no nested one. Join allocates, only after a listener subscribed or unsubscribed during a notification. Listeners are compared by reference, so an object unsubscribed and subscribed again during one notification counts as having stayed subscribed (a known limitation). Each dispatch of a structural change starts when the ones before it in the order above are done, and goes to the listeners that were subscribed when the change happened and still are when it starts: the OnAdded dispatch of an Add to the typed listeners subscribed when the Add started, less those the filter and world listeners unsubscribed (see Add), and the world listeners of an Add or a Remove are the ones subscribed when it happened, before the filter listeners ran.
Exception safety:
- A world listener or
AutoResetthat throws duringDestroyEntitypropagates after thefinallychain has drained what it could and released the slot. Components whoseRemovedid not run stay orphaned in their pools (the pool's sparse entry was never cleared for them), while the slot's mask and count are reset, andReleaseSlottakes the slot out of every filter it is still in and every owning group (LeaveFiltersAndGroups, without notifying anyone) and keeps it off the free list untilClear(KeepSlot,_keptSlots): a new entity in it would meet the orphans (anAddof one of their types throws "already has", and a pool'sHas, which an owning group checks, would see them as the new entity's). A snapshot stores the kept slots, and the loaded world keeps them off its free list too. Up to 2.4.0 the slot stayed in the filters of those components, and an owning group kept counting it as a member. An orphan belongs to no entity:WorldSerializer.Loadrefuses a world whose pools hold one. Treat the exception as fatal for that world orClear()it. Before thefinallychain existed, the slot was never released at all. - A filter or world listener that throws in the middle of an
AddorRemove(outside aDestroyEntitydrain, above) runs after the pool, the mask and the count hold the change, but possibly before every filter of the type was updated or before the auto-destroy of an entity that lost its last component. The dispatch that catches the exception (Filter.Notify, the world'sOnComponentRemoveddispatch) callsWorld.SettleAfterListenerThrewbefore rethrowing: every filter of the world is set to the slot's state without notifying its listeners (Filter.SetMemberQuietly; a live entity ends up in exactly the filters it matches, a dying one only leaves those it no longer matches), and a live entity without components is destroyed, which reportsOnEntityDestroyed(a world listener that throws there too is not reported: the slot is released in afinally, and the first exception stays the one on its way out). Then the exception leavesAdd,RemoveorDestroyEntity; the listeners not called yet are not called for that change, typedOnAddedlisteners included. No handler sits in theAddandRemovepaths themselves: the cost is one pass over every filter of the world, paid only when a listener throws. UnderKENSEI_DEBUGthe removal-during-iteration check of a filter ends the same way:Filter.RemoveEntitydecides before its swap-remove whether the removal breaks a running loop, makes the removal, thenReportRemovalDuringIterationsettles the entity and throws, so the report leaves filters that agree with the pools (SetMemberQuietlydoes not check again while it settles). Up to 2.4.0 the filters the update had not reached kept their old membership (an entity without the component stayed in anIncfilter) and an entity whose last component was removed stayed alive without components. - A pool listener or
AutoResetthat throws duringRemoveruns before anything is modified; the component stays, in its group and with its change version. Hook frames are popped infinally, so a throwing listener leaves no re-entrancy state behind. SystemsRunner.Initrecords progress in_initProgress; if a system'sInitthrows, the runner walks_initSystems[0.._initProgress)in reverse and destroys the systems there that implementIDestroySystem(a nested runner that completed itsInitis walked system by system by the same rule; a system with onlyIDestroySystemis not in_initSystems, so no rollback reaches it), resets the progress and stays uninitialized, so the nextInitstarts over. Exceptions from thoseDestroycalls are collected into oneAggregateExceptionafter the original one, marked inException.Data("KenseiECS.SystemsRunner.InitFailure"), so that a parent whose own rollback throws as well merges its inner exceptions into its list instead of nesting it.Runcleans OneFrame components also when a system threw, so a throwing system cannot leave events to be processed twice. When the cleanup of one type throws as well (a listener of its components,AutoReset), the types after it are still cleaned (CleanOneFramesAfterFailure, which drops their exceptions), and the first exception is the oneRunreports: the system's when a system threw, otherwise the one of the first cleanup that failed. Up to 2.4.0 the cleanup's exception replaced the system's and the types after it were not cleaned.Destroyresets the initialized flag before callingIDestroySystem.Destroyin reverse order.SystemsRunner.Destroywalks_destroySystemsin reverse and nested runners system by system, collecting the exceptions: every system is destroyed, then one exception is rethrown as is, several as one flatAggregateExceptionin the order they were thrown (up to 2.4.0Destroystopped at the first throwing system).CopyEntitydestroys the copy when anAutoCopyor a listener of a copied component throws, before the exception leaves (the caller never gets the handle); the copy is destroyed inside its own creation, so world listeners hear nothing of it.CommandBuffer.Playbackclears the buffer in afinally; a throwing command discards the rest. Commands that a listener records into the buffer duringPlaybackare applied by the samePlayback, after the ones recorded before; the table of resolved pending entities grows when they create more entities than it was sized for (up to 2.4.0PlaybackthrewIndexOutOfRangeExceptiononce they went past its size, 16 at first, and dropped the rest).WorldSerializer.LoadrestoresSuppressEvents(false)in afinally; a malformed stream leaves a partially restored world, which the caller shouldClear().
Snapshots
WorldSerializer (Core/Serialization) writes every live entity that has components, and those components, to a Stream and restores them into an empty world. Entities keep their index and generation, so Entity values stored in components, or held by the caller, are valid in the restored world; component types are identified by name, not by their runtime index.
File layout (version 2)
Integers are written by BinaryWriter (little-endian); strings are BinaryWriter strings (length-prefixed UTF-8).
uint32 magic 0x5343454B, the bytes "KECS"
int32 version 2
int32 tick world.Tick
int32 entityCount number of live entities with components
entityCount × { int32 index; int32 generation; } in ascending index order
int32 slotCount the high-water mark (_nextIndex) version 2 only
int32 freeCount number of free slots below slotCount version 2 only
freeCount × { int32 index; int32 generation; } free-slot list order, bottom to top
int32 keptCount slots kept off the free list until Clear version 2 only
keptCount × { int32 index; int32 generation; }
int32 raisedCount slots at or above slotCount with generation ≠ 1 version 2 only
raisedCount × { int32 index; int32 generation; } in ascending index order
int32 poolCount number of pools with a component of a saved entity
poolCount × {
string assembly-qualified component type name
int32 count
count × { int32 entityIndex; payload } in the pool's dense order, saved entities only
}Below the high-water mark every slot without an entity is a free slot. They are written in the order of the world's free-slot list, bottom to top (World.FreeSlotAt; CreateEntity takes the top one first), so the loaded world reuses them in the same order: the entities created after Load get the slots, and the handles, they would have got in the saved world. Save writes the live entities that have components, not EntityCount: an entity whose DestroyEntity is running (Save called by one of its listeners) is still counted there, and an entity inside the removal of its last component (Save called by a listener of that removal) is alive without components until the auto-destroy that follows. Neither is saved, nor are its components (ComponentPoolBase.SavedCount and WriteComponents take only components whose entity holds them, HoldsComponent); its slot is not on the free list yet and is written after it, on top, where its destroy will put it. Up to 2.4.0 Save called from a DestroyEntity listener wrote the dying entity, a stream Load rejected. The slots kept off the free list until Clear (an interrupted DestroyEntity left orphans there) follow as keptCount; the orphans themselves are not written (up to 2.4.0 they were, and Load put them on a free slot). Above the mark only the slots whose generation is not that of a new world (1), which a Clear raises, are written. A slot keeps its generation when it is freed and the next entity in it takes the next one (see Generation changes on reuse), so with these generations a handle that was dead when the world was saved stays dead after Load: the next entity in its slot gets the generation it would have got in the saved world.
Version 1 (2.4.0 and earlier) has no slotCount, no free, kept or raised slots; Load still reads it, and then the slots without an entity start from the generation of a new world, so a handle that was dead at Save can name the next entity created in its slot. 2.4.0 and earlier refuse a version 2 snapshot ("Unsupported snapshot version 2").
payload is either what the registered IComponentFormatter<T>.Write produced, or, for a component type with no formatter, sizeof(T) raw bytes taken with MemoryMarshal.AsBytes over the dense element. Pools with no components are skipped. Save iterates AliveEntities (linear in the high-water mark) and ActivePools (linear in registered types), then each pool's dense array.
Blittable path vs formatter path
ComponentPool<T> decides per type: IsBlittable = !RuntimeHelpers.IsReferenceOrContainsReferences<T>(). A registered formatter is always used when present, blittable or not. Without a formatter, a blittable type is written and read bit-for-bit, and a type that contains references throws InvalidOperationException from WriteComponents/ReadComponent. The raw form is the in-memory layout of the struct, padding included, so a snapshot written on one platform is readable only where T has the same layout and endianness. Entity is two ints and therefore round-trips raw. On read the pool fills a default(T) through a Span<byte> in a loop until sizeof(T) bytes arrived, throwing EndOfStreamException if the stream ends first.
RestoreEntity and FinishRestore
Load refuses a world with EntityCount != 0, and one whose pools still hold components (orphans of a DestroyEntity that a throwing listener or AutoReset interrupted: without entities a component in a pool belongs to no entity, and the entity restored into its slot would find it in the pool but not in its mask), with InvalidOperationException (call Clear() first). Up to 2.4.0 it did not check, and a stored component that met an orphan in its pool threw "already has component" halfway through the restore. Then it validates magic and version, reads the tick and the entity count, notes this world's own high-water mark (ownMark), and calls SuppressEvents(true) for the rest of the restore:
- For each stored entity,
World.RestoreEntity(index, generation): grows the slot arrays if needed, throws if the slot is already alive (a corrupt stream restoring one slot twice), stamps the generation verbatim, marks the slot alive with zero components, and raises_nextIndexpast it. The serializer also notes the generation it restored into each slot (_restoredGenerations, kept between calls so a repeatedLoaddoes not allocate it again; aLoadtakes the array out of the serializer while it runs and puts it back at the end, so aLoadthat a listener runs meanwhile with the same serializer, into another world, uses an array of its own and the outer one keeps checking its components against its own generations). - Version 2: reads the saved high-water mark (
savedMark), then the free slots and the raised slots, callingWorld.RestoreFreeSlot(index, generation, savedFree, savedMark, ownMark)for each. A count out of range, a free or kept slot listed twice or at or pastsavedMark, and a raised slot below it throwInvalidDataException. Kept slots get their generation the same way and are marked like the free ones.RestoreFreeSlotgrows the slot arrays if needed, throws if the slot holds a restored entity, and stamps a generation without making the slot alive. The world loaded into may have a past of its own in the slot (a rollback:Clear, thenLoadinto the same world), and a view or a system may still hold the handle of an entity that lived there after the snapshot was taken. So of the generation the next entity in the slot would get in the saved world (the stored one + 1 for a free slot, skipping 0; the stored one itself for a raised slot) and the one it would get in this world (its generation + 1 belowownMark; above it, its generation when aClearraised it, not 1), the later is kept (LaterGeneration: generations count pastint.MaxValueinto the negative numbers, so "later" is the sign of the difference). Below the new high-water mark the slot is free, and one less is stored, since its next entity adds one. A slot this world never used takes the saved generation as it is. World.FinishRestore(tick, savedMark, freeList, freeCount, listed, kept, keptCount): raises_nextIndextosavedMark(0 for version 1, which leaves it where step 1 put it) and rebuilds the free stack. At the bottom go the slots below_nextIndexwithout an entity that the snapshot does not list (this world's own free slots abovesavedMark; for version 1 every free slot), pushed from the highest index down, so that the lowest of them is taken first; on top of them the saved free list in its order. The kept slots of the snapshot go to_keptSlotsand stay off the stack untilClear; this world's own kept slots are dropped (they hold no orphans, whichLoadrefused) and are free like its other slots. The entities created afterLoadtake the saved world's free slots in the order it would have taken them, then the other free slots in ascending order, as the saved world would take new slots. It also sets_tick. Only these three methods write generations and_nextIndexdirectly; they areinternaland valid only on an empty world.- For each stored pool: resolve the type name to a
ComponentPoolBase(ResolvePool), then for each entry read the entity index and callpool.ReadComponentwith the generation noted for that slot in step 1. It decodes the value and then:- if the entity restored into the slot is no longer alive (a pool or filter listener of a component restored before destroyed it, and may have created an entity of its own in the slot), the value is dropped, as
CreateEntityandCopyEntitydrop the rest of an entity a listener destroyed. Up to 2.4.0 it was added to the freed slot, where the next entity inherited it, or to the listener's entity; underKENSEI_DEBUGLoadthrew; - if the entity already has the component, as its mask bit tells (a listener derived it from another restored component, in a world wired like the saved one; the pool would also hold an orphan, which belongs to no entity),
RestoreOverwrites the stored value over it throughModify(so it is marked changed), after resetting the old value as aRemovewould (AutoReset, or the list owner'sReplacefor a pooled list). No listener is told: there is no secondOnAdded. Up to 2.4.0Loadthrew "already has component"; - otherwise it calls the ordinary
pool.Add(entityIndex, value).
- if the entity restored into the slot is no longer alive (a pool or filter listener of a component restored before destroyed it, and may have created an entity of its own in the slot), the value is dropped, as
Because step 4 is the normal Add, masks, component counts, filters, groups, change versions and pool listeners all update as they would for live code; because _dispatch is false, world listeners and the profiler observe nothing, and no OnEntityCreated is dispatched. SuppressEvents(false) runs in a finally.
Type resolution: Type.GetType(assemblyQualifiedName) first; if that fails (the assembly version embedded in the name changed), the namespace-qualified part before the first comma is looked up in every loaded assembly. A type that is not loaded throws InvalidDataException. Pools are reached through a per-type accessor: Register<T>() (with or without a formatter) installs a typed accessor that calls world.Pool<T>() directly, while a type that appears only in the stream gets a reflection accessor built with MethodInfo.MakeGenericMethod. Registering is what makes Load independent of reflection under IL2CPP for a type no other code touches.
Not part of a snapshot: debug names, listeners, filter and group registrations (they belong to the World object; those that exist before Load are filled), and the change counter (restored components on tracking pools are stamped as changed by Add).
Built on the core
CommandBufferrecords(Op, PendingId, Entity, TypeIndex, PayloadIndex)structs and stores payloads in per-typePayloadStore<T>arrays indexed by type index, so nothing is boxed.PlaybackresolvesPendingEntityids throughworld.CreateEntity, skips commands whoseEntityis dead, and appliesAddviapool.Add(throws on duplicate),Setvia overwrite-or-add,Removeviaworld.GetPool(typeIndex)?.Remove(no pool creation) andDestroyviaworld.DestroyEntity. After the first frame the arrays are reused;Clearonly wipes payload arrays for types that contain references, so the GC can collect them. It walks the list of stores the buffer has created (_storeList), not every slot of the type-indexed_stores.EventBuffer<T>is a component holding aList<T>rented from a static per-typeListPool<T>; itsAutoResetreturns the list, soOneFrame<EventBuffer<T>>stops allocating once the pool and its lists have grown to the peak load. A struct copy of the component shares the list, and a copy kept past the component's removal (avar b = pool.Get(e)written back withAddorCommandBuffer.Setafter a OneFrame cleanup) would hand a pooled list to two entities. The pool hands out aPooledList<T>that records whether it is free and which entity holds it, as the holder pool'sPoolId(unique across worlds) and the entity index rather than a reference: on IL2CPP every store of a reference field pays a GC write barrier, and these fields change on every rent and return.EventBuffer<T>implements the internalIPooledListComponent<T>, from which its pool takes aPooledListOwner<T>once (_listOwner, an abstract class: a virtual call is cheaper than an interface call on a boxed struct): every store of a value (Add,CommandBuffer.Set's overwrite,CopyEntity, snapshot loads) claims a fresh list for the entity, replaces a list that is free or held by another entity with an empty list of its own (an overwrite with such a value keeps the entity's buffer instead), and an overwrite with a new list returns the replaced one.Returnpools only its own lists and ignores a second return, andRentclears a list a stale copy appended to while it was free. List owners take the hookedAdd/Removepath; other pools pay nothing. A write straight into the pool's storage (through areffromGet, orRawData) is not seen and is not supported for copies.World.Warmupdoes not fill the pool: its defaultEventBuffer<T>has anulllist and rents nothing;EventBuffer<T>.Prewarm(lists, capacity)does: it prepares only the toplistsfree lists (the next onesRenthands out). Each slot keeps a list that is already large enough or takes one from below; when none is, the largest remaining list is grown tocapacity, so at mostlistslists are grown and a pool left large by an earlier peak is not inflated wholesale. Missing lists are created on top, and the prepared lists end up at the top of the pool.ListPool<T>is static, so all worlds in the process share it.world.AddEventappends to an existing buffer or adds a new one; for a buffer the entity has without a list (added empty, or set todefault) it rents the list itself and records the entity as its holder, sinceEventBuffer<T>.Addcannot know the entity: apool.Get(e).Add(v)on such a buffer rents a list without a holder, which a copy of the buffer can then give to a second entity.Listeners<T>is a component holding aList<T>of interface implementations and nothing else: a system that dispatches walksValuesitself, which costs no delegate, snapshot or allocation.Subscribeadds the component on first use,Unsubscribekeeps it even when empty so the entity is not auto-destroyed by unsubscribing, andHasListenersreports false for an empty list. A callback must not change the list it is called from: the documentedforloop does not check it (aforeachwould, through the list's version, but under IL2CPP its shared-generic enumerator costs 1.5 to 3 times as much asfor).UnsubscribeLaterappends the entity and the listener to a per-world, per-typePendingUnsubscribes<T>(found through a short list ofIPendingUnsubscribes, an interface call rather than a delegate) and marks the world.SystemsRunner.Run(World)brackets its work withWorld.EnterRun/ExitRunin an outertry/finally; the call that brings the depth back to 0 (the outermostRun, including a phase driven on its own) applies the queues, and so doesNextTickat depth 0 (the root runner calls it first, a world without a runner calls it itself);Applylooks the pool up without creating it: each removal checks the entity's generation, so one queued for a destroyed entity does not touch an entity that reused the slot, and the queue clears its listener slots so it holds no view alive.World.Cleardrops the queues. The 2.2Invokeoverloads, obsolete since 2.3.0, still copy the list into an array rented fromArrayPool<T>.Sharedand skip listeners unsubscribed mid-dispatch, until 3.0 removes them. The list itself is not pooled:AutoResetclears and drops it, because a struct copy of the component written back after a remove (AddorCommandBuffer.Set) would otherwise hand a pooled list to two entities.SystemsRunnerkeeps separate lists ofIInitSystem,IRunSystemandIDestroySystemsoRundoes no type checks. A phase (AddPhase, or the obsoleteAdd(runner, name)) is registered as an init/destroy participant but excluded from_runSystems, which is what makes it a separate phase; an inline group (AddGroup, or an unnamedAdd(runner)) is an ordinaryIRunSystemin the parent's list, and its slot flag and its ownIsEnabledare kept in sync. A runner has at most one parent (_parent, with its entry there in_registration):AddCorerejects, in every build and before anything is registered, a runner that already has a parent and one that is the parent itself or one of its ancestors, andSetActive(bool)on an inline group writes the parent's slot through_registration.RunIndex. Only the root's parameterlessRun()advances the world tick.OneFrameCleanup<T>callspool.RemoveAll(), which walkspool.RawEntitiesfromCount - 1down to 0 callingpool.Remove, which is safe with swap-remove and with group swaps. When no callback can run during the removals (no hooks on the pool, no world listener, no filter of the type with listeners:World.RemovesQuietly), nothing else changes the pool, so every component to remove is the last one:RemoveAllthen removes it in place (AutoReset, tail default, sparse entry, count,World.OnComponentRemoved), without the lookup, the hook check and the swap ofRemove, in the same order. AutoReset is the only user code on that path; it should reset the value and nothing else, and one that changes the world anyway (moves the pool's count or entity array, subscribes a listener) is caught after its own removal, and the rest of the cleanup goes throughRemoveas the plain loop would. A removal that throws does not stopRemoveAllon either path: the components below it are removed throughRemove, exceptions thrown there are dropped, and the first one leaves. The handler of the in-place loop is told the dense slot whose removal was running, because the pool's count does not say it: anAutoResetthrows before anything of that removal was done (its component stays), while an exception from the world's side of it (underKENSEI_DEBUGthe report of a removal that breaks a running loop over a filter) comes after the component left the pool. The loop of a type withoutAutoResetruns no user code and has a handler only underKENSEI_DEBUG;DelHere<T>registers the same object as a run system at that position. On Unity every run system is wrapped in aProfilerMarker; underKENSEI_DEBUGStopwatchtimings are recorded per system.- The Unity layer (
KenseiECS/Unity) is thin.EcsBootstrapis an abstractMonoBehaviourthat creates theWorld(fromCreateConfig()), aSharedData, a rootSystemsRunnerand two child runners, calls the subclass'sConfigure(update, fixedUpdate, lateUpdate, shared)inAwake, then registers the children as the named phases"fixed"and"late".StartcallsWarmup()orInit();Update,FixedUpdateandLateUpdateeach run their runner only while that runner'sIsInitializedis true, so a failedInit, or anAwakethat failed before the phases were registered, does not turn into an exception (or a world tick) per frame; underKENSEI_DEBUGAwakechecks right afterConfigurethat nothing in the update runner was registered under"fixed"or"late";OnDestroydestroys the systems, then the world. It implementsIEcsWorldProviderandIEcsSystemsProvider, which the editor windows use to list its world first and label it with the GameObject.EcsComponentProvider<T>is aMonoBehaviourholding one serializedT;EcsEntityView.Spawn(world)collects the providers on the GameObject in component order, creates the entity from the first (CreateEntity) and adds the rest (Add), assigns the serializedEntityNameas the debug name (a no-op withoutKENSEI_DEBUG), and binds the view. - The editor windows list worlds through
Core/WorldRegistry.cs, compiled only underUNITY_EDITOR || KENSEI_DEBUG. TheWorldconstructor registers the world andDestroyunregisters it;SystemsRunner.Initregisters a root runner (no parent) once it completes. Entries areWeakReferences, so the registry never keeps a world alive; collected entries are swept when a list reaches a size that then doubles from what is left, so creating many worlds costs amortized O(1). Reads return live entries in registration order under a lock. The registry isinternal;[assembly: InternalsVisibleTo("KenseiECS.Editor")]in the same file opens it to the editor assembly, whoseEcsWorldPickerputs the worlds ofIEcsWorldProvider/IEcsSystemsProviderbehaviours first and the registry's after them, and draws the toolbar dropdown of the three windows.
The source generator
KenseiECS.Generators/SystemInjectionGenerator.cs is a Roslyn ISourceGenerator compiled against Microsoft.CodeAnalysis.CSharp 3.8.0 for netstandard2.0, so it loads in the compiler shipped with Unity 2021.3 as well as newer ones. The built assembly is committed as KenseiECS/Plugins/KenseiECS.Generators.dll. Its .meta file carries the RoslynAnalyzer asset label and disables every platform: Unity's convention for an analyzer or generator, which is handed to the C# compiler rather than loaded as a runtime assembly. A .NET project uses it by referencing the generator project (or DLL) as an analyzer, as KenseiECS.Generators.Tests does.
The attributes it reads are ordinary runtime attributes in Core/InjectAttributes.cs: [Inc(params Type[])], [Exc(params Type[])], [Any(params Type[])] for Filter fields, [Pool] for ComponentPool<T> fields, [Group] for Group<...> fields, [Shared] / [Shared("key")] for anything registered in SharedData. All are field-only and single-use.
What it does, per compilation:
A syntax receiver flags every class, struct or record that declares a field (or, for KECS015, an auto-property or a field-like event with a
field:target) carrying an attribute whose short name isInc,Exc,Any,Pool,GrouporShared(with or without theAttributesuffix), or the name of a using alias (also aglobal usingin another file) that points to one of them. The receiver only collects candidates by name; step 2 decides by the attribute class.Each flagged class symbol is processed once (partial declarations are deduplicated). Its non-static fields are inspected and attributes are matched by full name (
KenseiECS.IncAttributeand so on), so a same-named attribute from another namespace is ignored. A marked field that the generatedInitcannot fill is reported and left out: a static field (warningKECS014), the backing field of an auto-property or of a field-like event marked[field: ...](warningKECS015). A field with two kinds of injection attribute is injected by the first in the order filter,[Pool],[Group],[Shared], and the other is the warningKECS016.Each injected field yields one assignment line:
[Inc]/[Exc]/[Any]on aKenseiECS.Filterfield:this.f = world.Filter().Inc<A>().Inc<B>().Exc<C>().Any<D>().End();with fully qualified type names.KECS003if the field is not aFilter(compared without the nullable annotation, soFilter?passes);KECS004if there is[Exc]without[Inc]or[Any];KECS007if[Inc]and[Any]together list no type;KECS008if a listed type is not a struct implementingIComponent(an unresolved type, for example one produced by another generator, is left to the compiler);KECS019if a type is listed in[Exc]and also in[Inc]or[Any](tuple element names do not make a different type);KECS017if a listed type is file-local.[Pool]on aComponentPool<T>field:this.f = world.Pool<T>();.KECS003otherwise.[Group]on aGroup<...>field:this.f = world.Group<...>();.KECS003otherwise.[Shared]on a field of any reference typeT:this.f = shared.Get<T>();, orshared.Get<T>("key")when a key is given.KECS003for a value type.- Any injected field declared
readonly:KECS009.
A class with no injected fields gets nothing. A
recordorstructwith injected fields getsKECS010. Otherwise:KECS017if the class is file-local or nested in a file-local type (the generated part is another file);KECS001if the class is notpartial;KECS002if the class itself declares anInit(World, SharedData)in source (static or not, with any return type; anInitwith other parameters is an overload) or implementsIInitSystem.Initexplicitly;KECS018if the nameInitis taken: the class is namedInit, has a type parameter namedInit, or declares a field, property, event or nested type namedInit;KECS011if a containing type is arecordor aninterface;KECS005if a containing type is notpartial.Inheritance is resolved after the per-class checks, base classes first (a base in the same compilation is analysed on demand when a derived class reaches it). A base that neither implements
IInitSystemnor has injected fields anywhere up its chain is not a system: the generatedInitis no override, and it is declarednewexactly when it hides an accessible inherited member (anInit(World, SharedData)with any return type, static or not, or a non-method member namedInit). Otherwise the walk up the base chain takes the first class that either has injected fields in this compilation (it must have generated successfully, otherwise the derived class is skipped silently, the base already reported its own error) or declares anInit(World, SharedData): an explicitIInitSystem.Initfirst, whatever the member order, since the interface maps to it; else an instancevoid Init(World, SharedData)with by-value parameters, not generic and accessible from the derived class. The generatedInitis anoverridethat fills its own fields, callsbase.Init(world, shared)(not when the baseInitis abstract) and thenOnInit, so the baseInitand the virtual hooks it calls see the derived fields.KECS006if the foundInitis explicit, not virtual, sealed, not public, or a non-overrideInitthat is not whatIInitSystem.Initmaps to for its class (FindImplementationForInterfaceMember; anew virtual Inithiding the interface method is not). An explicitIInitSystem.Initthat calls an ordinaryInit(World, SharedData)of its class that can be overridden (Init(...)orthis.Init(...)in its body, bound by the compiler; only a declaration in source can be read) is the one exception: thatInitis chained instead, since the runner reaches it, and an override of it, through the explicit one. In that case only a class that listsIInitSystem, or an interface that extends it, among its own bases is accepted, with the 2.1 layout (its ownInitre-implements the interface, declarednewwhen it hides something, and itsOnInitcalls the base), and only when the class has abase.Initin its own declarations: without one the baseInitwould be skipped, which isKECS006when the base has injected fields or the runner reaches the foundInitthroughIInitSystem.Init: it is what the interface maps to, theInitan explicit implementation calls, or an override of either (the interface maps to the first declaration of the slot, not to asealedorprotectedoverride in a class that does not list the interface). An explicit implementation itself cannot be reached throughbase.Init, so it is exempt.KECS006also when a hand-written class between the derived class and the chained base declares a member namedInitthat is not a method (the override would fail with CS0505) or another accessibleInitoverload that a(World, SharedData)call could bind to (a method type parameter that neither argument can infer makes it inapplicable), since C# would pick it for the generatedbase.Init. When the generatedInitcalls the base, everybase.Initmember access in the class's own declarations (nested types excluded) isKECS012: a syntactic check with no overload resolution, because the user's call would run the base a second time. A hand-written class without injected fields whoseoverrideofInit(World, SharedData)ends up overriding a generatedInit(directly or through hand-written overriding classes) and that has nobase.Initin its own declarations gets the warningKECS013. So does one whosebase.Initcalls all go to anotherInitoverload. The compilation the generator sees cannot say where such a call goes: it has no generatedInityet, so it binds the call to an overload that the generatedInitwill beat, or to a hand-written override that C# will later look up at the generated base, above an overload that then wins. When a base declares anInitoverload at all, the calls are therefore bound in a copy of the compilation with the generatedInitof every base added, which gives the compiler's own answer; thebase.Initcall of the 2.1 layout is judged the same way (KECS006). A generated base in a referenced assembly is recognised only by injected fields visible from here, because private members of referenced assemblies are not imported.OnInitis normally apartial voiddeclaration plus a call at the end ofInit: implement it in your part of the class to run code after the fields are filled (and after the baseInit), or leave it out and the compiler drops the call. A class that declares anOnInit(World, SharedData)of its own that is not the implementation of that partial gets no declaration: a non-override one is called, and so is an override of a base hook, unless the generatedInitcalls a baseInit(step 5) and the hook is first declared in that base or below it, where the baseInitcan call it. A hook declared between the two (in a hand-written class over a generated base), an abstract baseInitor a base that is not a system leave nothing else to call it. In the 2.1 layout an override of a hook the replaced baseInitcan call isKECS006: the generatedInitwould call it, and thebase.InitthatOnInitmust call would call it again. When a base has an accessible member namedOnInitwith that signature or a non-method one (the virtual hook of a hand-written base, or the privateOnInitof a generated base that the class is nested in), the partial would hide it: it is declared, inside#pragma warning disable CS0108, CS0114because a partial method without an access modifier cannot benew, only when the class implements it, and otherwise left out together with its call. A class namedOnInit, or with a type parameter namedOnInit, gets neither the declaration nor the call: no member of it can have that name (CS0542, CS0102).The emitted file,
{FullName}.Injection.g.cs(namespaces, containing types and the type name without@, with_for the type-parameter brackets), re-opens the namespace and every containing type aspartial(keepingstatic,class/structand type parameters; keywords in names are escaped as@name, and a[Shared]key is written as an escaped string literal), then declares:csharppartial class MovementSystem : global::KenseiECS.IInitSystem { partial void OnInit(global::KenseiECS.World world, global::KenseiECS.SharedData shared); public virtual void Init(global::KenseiECS.World world, global::KenseiECS.SharedData shared) { this._moving = world.Filter().Inc<global::Game.Position>().Inc<global::Game.Velocity>().End(); this._positions = world.Pool<global::Game.Position>(); OnInit(world, shared); } }The
: IInitSystembase is omitted when the class already implements it or overrides an inheritedInit;Initispublic overridewhen it chains (step 5), otherwisepublic virtual voidin a class that is notsealedandpublic voidin a sealed one, withnewwhen it hides an inherited member. The form never depends on which subclasses the compilation contains, so a subclass in another assembly, or one compiled only under a define, sees the sameInit. Roslyn compares hint names without case and drops the whole generator output when two are equal, so names that differ only in case (Game.AI.MoveandGame.Ai.Move) get a numeric segment (Game.Ai.Move.2.Injection.g.cs), assigned in ordinal order of the full names so that it does not depend on the order of the files; a type or namespace name cannot start with a digit, so the segment cannot meet another name.Each class is analysed and written on its own. An exception on the way (a bug of the generator, or a Roslyn API that answers differently on code with compiler errors) is caught and reported on that class as the error
KECS020, with the exception type and message; the class gets noInit, a class derived from it is skipped without a second error, and every other class is generated as usual. Uncaught, the exception would make Roslyn drop the whole generator output (warning CS8785), and no system of the assembly would get itsInit.
The generated code calls the same public API a hand-written Init would. There is no reflection and nothing for IL2CPP to strip; filters built this way deduplicate against builder-made and spec-made filters like any other.
The KENSEI_DEBUG layer
Everything in this section is inside #if KENSEI_DEBUG and does not exist in a release build: no fields, no checks, no Dispose on the enumerator, no profiler hooks. The cost in release is zero.
What is checked:
| Where | Check |
|---|---|
World.Add/Get/Has/Remove, AddEvent | ValidateHandle: the handle must be alive, or be the entity whose DestroyEntity is running (its slot is on the stack of dying slots and the generation matches). Dead and stale handles throw, also while another entity is being destroyed. |
World.CopyEntity, GetComponentTypes, GetComponentCount, SetName | Throw on a dead entity (release returns Entity.Null / reads the slot / ignores). |
World.DrainComponents | Throws after 1000 passes when a listener keeps re-adding components to a dying entity. |
ComponentPool<T>.Add(int) | IsSlotAcceptingComponents: the slot must be below _nextIndex and alive, or be the slot being destroyed. An int carries no generation, so this is the strongest check possible. |
ComponentPool<T>.Get(int), Modify(int), MarkChanged(int), ChangedVersion(int) | Throw when the component is absent. (ChangedVersion throws in every build when the pool does not track.) |
WorldListenerExtensions.Subscribe/Unsubscribe | Throw on a dead entity. |
Filter | The iteration guard below. |
SystemsRunner | Add after Init, Run before Init, Init/Run with a different World or explicitly different SharedData, nested runner with a different World/SharedData, unknown names in SetActive/IsActive/GetRunner. Per-system LastRunMs/PeakRunMs. |
| Tooling | EcsProfiler hooks on create/destroy/add/remove (skipped while events are suppressed), WorldDebugView as DebuggerTypeProxy for World, GetRaw/SetRaw on pools, entity debug names (SetName, EcsEntityView.EntityName). |
Groups, change tracking and snapshots add no debug-only checks beyond the pool ones listed; their consistency errors (double ownership, non-empty world on Load, missing formatter, bad magic) throw in every build.
The iteration guard
Each Filter keeps _debugCursors (one slot per live enumerator, innermost last) and _debugIterators (depth). The enumerator constructor records its depth and writes its starting cursor (_count + 1); every successful MoveNext writes the slot it is on; Dispose decrements the depth. foreach calls Dispose on a ref struct enumerator through pattern-based disposal, so the guard is released on normal exit, break and exceptions.
RemoveEntity checks every live cursor before the swap:
for (int d = 0; d < _debugIterators; d++) {
int cursor = _debugCursors[d];
if (denseIdx < cursor && lastIdx >= cursor) {
throw new InvalidOperationException(
$"Entity {entityIndex} left a filter that is being iterated before the loop reached it; " +
"an already visited entity would be visited twice");
}
}Reverse iteration has visited every slot above the cursor and is currently on the cursor. Removing the entity at denseIdx moves the entity from lastIdx into denseIdx. The move is harmful only when the destination has not been visited yet (denseIdx < cursor) and the moved entity has (lastIdx >= cursor): it would be yielded again. Every other combination is safe: removing the current entity (denseIdx == cursor) or a visited one, or removing an unvisited entity when the last slot is also unvisited (lastIdx < cursor), which happens after the loop has already shrunk the live range. Nested loops over the same filter are covered because every enumerator's cursor is checked.
There is no equivalent guard for group loops; the reverse-iteration rule for destroying members is documented above and is the user's responsibility.
Performance characteristics
W is the number of mask words (ceil(types / 64)), C the number of components on the entity, F(t) the number of filters that constrain type t, P the number of pools an owning group owns, L the number of listeners that fire.
| Operation | Cost | Notes |
|---|---|---|
CreateEntity<T>(T) | O(1) amortized + one Add | Pops the free stack or bumps the high-water mark; may grow every slot array and mask word. |
Add<T> | O(1) + O(F(t) + L) | One _addHooks branch. Each filter test is one or a few ulong operations. Sparse/dense growth is amortized. |
Add<T> on an owned type | + O(P) | P Has checks; P SwapDense when the entity becomes a member. |
Add<T> on a tracking pool | + O(1) | One counter increment, one store. |
Remove<T> | O(1) + O(F(t) + L) | Swap-remove. Plus a DestroyEntity if it was the last component. |
Remove<T> on an owned type | + O(P) when the entity was a member | Otherwise one Contains. |
Get<T> / pool.Get(int) | O(1) | Sparse read, then dense read. Untracked. |
pool.Modify(int), MarkChanged(int) | O(1) | Get plus a counter increment and a store. |
pool.ChangedSince(int, int) | O(1) | Sparse read, version read, compare. |
Has<T> | O(1) | One mask word read; no pool access. |
pool.Has(int) | O(1) | Sparse read. |
IsAlive, GetEntity(int), TryGetEntity(int), GetComponentCount | O(1) | |
DestroyEntity | O(W + C × (F + L + P)) | Mask walk over set bits only, up to the last word holding a component (none for an auto-destroy); each component pays its own Remove. |
CopyEntity | O(W + C) + C × Add | Same walk; AutoCopy per component that implements it. |
GetComponentTypes | O(W + C) | |
foreach (int e in filter) | O(matches) | One span load per step, zero allocation; component access is a sparse lookup per pool. |
Group loop over Data1..DataN | O(members) | Contiguous spans, no sparse lookups, no per-entity mask test. |
Filter.Count/IsEmpty/Contains/First/Single | O(1) | |
Filter().…End(), Filter<Spec>() | O(registered filters) + O(entity slots) | Dedup scan, then PopulateFilter. Allocates. Build in Init. |
Group<T1, T2>() | O(registered groups) + O(smallest owned pool × P) | Dedup scan, then Populate. Allocates. Build in Init. |
pool.TrackChanges() | O(pool count) once | Allocates the version array. |
Pool<T>() | O(1) | Type check on _pools[typeIdx]; first call allocates the pool. |
GetSingleton<T> | O(1) | pool.RawData[0] after a count check. |
CommandBuffer.Playback | O(commands) | Each command pays the corresponding world operation. |
SystemsRunner.Run | O(systems) + Σ OneFrame pool counts | |
WorldSerializer.Save | O(high-water slots + registered types + Σ components) | Plus stream I/O. |
WorldSerializer.Load | O(entities + high-water slots) + Σ components × Add | Plus one type resolution per stored pool. |
Warmup | O(registered pools) × (Add + Remove) | |
Clear | O(high-water slots × W) + Σ pool counts + Σ filter counts + groups | Pools and filters reset through their dense lists, not their sparse arrays. |
What scales with the number of component types versus the entity's own components:
- Per-frame operations (
Add,Remove,Get,Has, iteration,DestroyEntity,CopyEntity) never loop over registered types.DestroyEntityandCopyEntityread word 0, then only the words whose bit is set in the slot's_usedWords(at mostW), then only set bits;DestroyEntityalso stops after the word that holds the entity's last component. Warmup,World.Clear,World.Destroy,WorldSerializer.SaveandActivePoolsloop over_pools, i.e. over registered types. They are setup, teardown and save operations.- Filter matching is O(active words), at most
W; single-word filters read three scalars.
Memory, per element:
- Entity slot: 4 bytes generation, 1 byte alive, 4 bytes count, 8 × W bytes of masks, and 8 bytes of
_usedWordswhen W > 1. - Pool: 4 bytes per sparse slot (grows to cover the highest entity index that ever held the component, starting at
InitialPoolSparseCapacity), plus (4 +sizeof(T)) per dense slot (starts atInitialPoolDenseCapacity, doubles with the component count), plus 4 bytes per dense slot onceTrackChangeswas called. One boxeddefault(T)per implemented bridge interface (IAutoReset<T>,IAutoCopy<T>).ComponentPoolBase.AllocatedBytesreports the array sizes (without the version array). - Filter: 4 bytes per dense slot plus one, 4 KB per touched 1024-entity page, three mask arrays of
ceil(maxConstrainedType / 64)words.Filter.AllocatedBytesreports it. - Group: P pool references and a count; no arrays of its own.
- Registry:
_poolsand_filtersByTypehold one reference per type index up to the highest seen;TypeFiltersobjects exist only for constrained types.
Known limitations and design decisions
No archetypes. Storage is one sparse set per component type. Structural changes are O(1) and never move an entity's other components; a ref T stays valid across adds of other types; filters are cheap sparse sets updated incrementally; there is no combinatorial explosion of archetypes when many optional components exist. The price is iteration: reading two components per entity through a filter is two sparse-to-dense indirections into two unrelated arrays, which loses to chunked archetype layouts on pure iteration (see the benchmarks) and wins on structural changes and mixed frames. Owning groups recover contiguous iteration for a chosen set of types at the cost of one extra swap per owned pool when an entity joins or leaves, and of the one-owner-per-pool rule.
CreateEntity requires a component. The invariant is "alive if and only if it has at least one component". An empty entity would be invisible to every filter, invisible to world listeners (OnEntityCreated fires after the first component), and would be destroyed by the first Remove anyway. Requiring the component at creation removes the empty state entirely, so there is no leak class to detect and no "empty entity" check to run. CommandBuffer.CreateEntity<T>(T) and EcsEntityView.Spawn (which throws without a provider) mirror the rule.
Auto-destroy on last component removal. Same invariant from the other side. It makes "event entities" free: an entity whose only component is a one-frame component disappears in the cleanup. The one place where this surprised users, unsubscribing the last listener, is handled by keeping the empty Listeners<T> component.
Single-threaded. World, pools, filters and groups have no synchronization. Reading RawData/RawEntities/group spans from several threads is safe only while no structural change happens anywhere. ComponentType<T>.Index registration is thread-safe. EventBuffer<T>'s list pool is a static per-type stack shared by all worlds in the process and is not thread-safe either.
Iteration order is unspecified and changes with every swap-remove and every group swap. Removing a not-yet-visited entity from the filter being iterated can double-visit an already visited entity (thrown under KENSEI_DEBUG); defer such changes with a CommandBuffer. Group loops that destroy members must run downward.
Exclude-only and empty filters are rejected. Membership is driven solely by add/remove of constrained types, and PopulateFilter needs at least one required or alternative type to reason about; add an Inc for a component the target entities always have. The generator reports the same rule as KECS004.
One owner per pool, order-sensitive. A component type can be owned by one group, groups take two to four types, Group<A, B> and Group<B, A> are different requests (the second throws), and groups cannot be unregistered. Owning a pool changes the order of its RawData, which was never guaranteed.
Change tracking is opt-in and write-side. Only Add, Modify and MarkChanged stamp versions; writes through Get, raw arrays or group spans do not.
Snapshots are layout-bound and partial. Raw components are the writing platform's struct layout; the format is version 2 since 2.5.0 (version 1 still loads, 2.4.0 cannot read version 2); listeners, debug names, filter and group registrations are not stored; component types are found by name, so renaming or moving a type breaks old files.
The generator injects fields only. It needs a partial class (and partial containers), forbids a hand-written two-parameter Init next to injected fields, and targets the Roslyn 3.8 API.
ref T invalidation. A ref from Get/Add/Modify is valid until the next Add or Remove of the same type on any entity (including those inside DestroyEntity, CopyEntity, one-frame cleanup, CommandBuffer.Playback and listeners), or, in a group-owned pool, the next Add or Remove of any of the group's types, or a Reserve that grows the pool's dense arrays, or Clear/Destroy of the world.
Type indices are process-wide and depend on first-touch order. They are not stable across runs and must not be serialized (snapshots use names). Every world's registries are sized by the highest type index it has seen, not by how many types it uses.
Entity carries no world id. Using a handle from one world on another is undefined; the generation check catches it only by accident.
Filters cannot be unregistered. They live until World.Destroy. Static specs are limited to Inc 1-6, Exc 1-4, Any 2-4 types; the builder and the attributes have no limit.
