Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
esengine::ecs::SparseSet< T > Class Template Reference

Sparse set container for efficient entity-component storage. More...

#include <SparseSet.hpp>

Inheritance diagram for esengine::ecs::SparseSet< T >:

Public Types

using Iterator = typename std::vector<Entity>::const_iterator
 Iterator type for entity iteration.
using Page = std::array<u32, SPARSE_PAGE_SIZE>
 Page type: array of dense indices.

Public Member Functions

 SparseSet ()=default
 Default constructor.
 ~SparseSet () override=default
 Destructor.
 SparseSet (const SparseSet &)=delete
SparseSet & operator= (const SparseSet &)=delete
 SparseSet (SparseSet &&) noexcept=default
SparseSet & operator= (SparseSet &&) noexcept=default
bool contains (Entity entity) const override
 Checks if an entity has a component in this set.
T & get (Entity entity)
 Gets the component for an entity (must exist).
const T & get (Entity entity) const
 Gets the component for an entity (must exist).
T & getUnchecked (Entity entity)
const T & getUnchecked (Entity entity) const
T * tryGet (Entity entity)
 Tries to get a component (returns nullptr if not found).
const T * tryGet (Entity entity) const
 Tries to get a component (returns nullptr if not found).
u32 changedTick (Entity entity) const
 The tick of entity's last write, 0 when it has none here.
u32 changedTickOf (Entity entity) const override
 The tick of entity's last write here, 0 where it has no component: the type-erased changedTick.
void markChanged (Entity entity, u32 tick) override
 Stamps entity's component with tick: it was written. No-op for an entity without one.
u32 * changeTicks ()
 The stamps, parallel to components(): where a writer that holds a component's place stamps it.
const u32 * changeTicks () const
u32 * lastChangedSlot ()
 Where the pool's last-change tick lives, for a writer that stamps through changeTicks() to lift with it.
u32 lastChangedTick () const override
 The tick of the last write to any component of this pool, or of the last add or remove: "anything since?" in O(1).
void noteStructural (u32 tick) override
 Notes an add or a remove at tick, which no stamp of a component that is still there records.
void clampStamps (u32 floor) override
 Lifts every stamp older than floor to it, so a stamp never reads as newer after the tick wraps.
std::string_view typeName () const override
 The component type's name, for what the audit says.
bool auditable () const override
 Whether this pool's components can be audited (see above).
void auditKeep (AuditCopy &copy, u32 tick) const override
 Keeps the pool's state as it is at tick.
u32 auditCompare (const AuditCopy &copy, void(*report)(void *, Entity), void *user) const override
 Calls report for each entity whose component changed since copy without a stamp after copy.tick.
template<typename... Args>
T & emplace (Entity entity, Args &&... args)
 Adds a component to an entity with in-place construction.
void remove (Entity entity) override
 Removes a component from an entity.
usize size () const override
 Gets the number of components in the set.
bool empty () const override
 Checks if the set is empty.
void clear () override
 Removes all components.
u32 version () const override
 Monotonic version, bumped whenever stored components may have moved in memory (buffer reallocation on growth, or swap-and-pop relocation on removal).
void reorderBy (const std::vector< u32 > &rank) override
 Permutes storage so iteration follows rank.
void permute (std::vector< usize > &perm)
 Puts slot perm[i] at position i, for every i: the entity, its component and its stamp together.
void rebuildSparse ()
Iterator begin () const
 Returns iterator to the first entity.
Iterator end () const
 Returns iterator past the last entity.
const std::vector< Entity > & entities () const override
 Gets the dense entity array.
std::vector< T > & components ()
 Gets the component array for direct iteration.
const std::vector< T > & components () const
 Gets the component array for direct iteration.
usize indexOf (Entity entity) const
 Gets the dense array index for an entity.
Public Member Functions inherited from esengine::ecs::SparseSetBase
virtual ~SparseSetBase ()=default
 Virtual destructor for proper cleanup.

Static Public Attributes

static constexpr usize SPARSE_PAGE_SIZE = 4096
 Page size for paged sparse array (entities per page).
static constexpr u32 INVALID_INDEX = INVALID_DENSE_INDEX
 Sentinel for empty sparse slots.
static constexpr bool kAuditBytes = std::is_trivially_copyable_v<T>
static constexpr bool kAuditValues = !kAuditBytes && std::is_copy_constructible_v<T> && std::equality_comparable<T>
Static Public Attributes inherited from esengine::ecs::SparseSetBase
static constexpr u32 UNRANKED = 0xFFFFFFFFu
 Rank for an entity the caller did not order — sorts last, stably.

Additional Inherited Members

Static Public Member Functions inherited from esengine::ecs::SparseSetBase
static std::vector< usize > stablePermutation (const std::vector< Entity > &dense, const std::vector< u32 > &rank)
 Which current slot belongs at each position when dense is put in rank order (stable).

Detailed Description

template<typename T>
class esengine::ecs::SparseSet< T >

Sparse set container for efficient entity-component storage.

Template Parameters
TThe component type to store

The sparse set uses a paged sparse array and dense arrays:

  • Paged sparse array: Maps entity IDs to dense array indices Divided into fixed-size pages (4096 entities each) allocated on-demand to avoid unbounded memory growth for sparse entity IDs.
  • Dense array: Stores entities and components contiguously

This provides:

  • O(1) insertion, deletion, and lookup
  • Cache-friendly iteration over components
  • Stable component pointers during iteration
  • Bounded memory usage even with sparse entity IDs

The "swap and pop" deletion strategy maintains density without gaps, at the cost of unstable ordering.

Memory efficiency: With paging, entity ID 1,000,000 only allocates 244 pages (~16KB) instead of 4MB.

// Add components
positions.emplace(entity1, 0.0f, 0.0f);
positions.emplace(entity2, 10.0f, 5.0f);
// Access component
if (positions.contains(entity1)) {
Position& pos = positions.get(entity1);
}
// Iterate all
for (Entity e : positions) {
Position& pos = positions.get(e);
}
bool contains(Entity entity) const override
Checks if an entity has a component in this set.
SparseSet()=default
Default constructor.
T & emplace(Entity entity, Args &&... args)
Adds a component to an entity with in-place construction.
T & get(Entity entity)
Gets the component for an entity (must exist).
Entity identifier with packed index + generation.
Definition Types.hpp:135

Definition at line 256 of file SparseSet.hpp.

Member Typedef Documentation

◆ Iterator

template<typename T>
using esengine::ecs::SparseSet< T >::Iterator = typename std::vector<Entity>::const_iterator

Iterator type for entity iteration.

Definition at line 259 of file SparseSet.hpp.

◆ Page

template<typename T>
using esengine::ecs::SparseSet< T >::Page = std::array<u32, SPARSE_PAGE_SIZE>

Page type: array of dense indices.

Definition at line 268 of file SparseSet.hpp.

Constructor & Destructor Documentation

◆ SparseSet() [1/3]

template<typename T>
esengine::ecs::SparseSet< T >::SparseSet ( )
default

Default constructor.

Referenced by SparseSet(), SparseSet(), operator=(), and operator=().

◆ ~SparseSet()

template<typename T>
esengine::ecs::SparseSet< T >::~SparseSet ( )
overridedefault

Destructor.

◆ SparseSet() [2/3]

template<typename T>
esengine::ecs::SparseSet< T >::SparseSet ( const SparseSet< T > & )
delete

References SparseSet().

◆ SparseSet() [3/3]

template<typename T>
esengine::ecs::SparseSet< T >::SparseSet ( SparseSet< T > && )
defaultnoexcept

References SparseSet().

Member Function Documentation

◆ auditable()

template<typename T>
bool esengine::ecs::SparseSet< T >::auditable ( ) const
inlineoverridevirtual

Whether this pool's components can be audited (see above).

Implements esengine::ecs::SparseSetBase.

Definition at line 386 of file SparseSet.hpp.

References kAuditBytes, and kAuditValues.

◆ auditCompare()

template<typename T>
u32 esengine::ecs::SparseSet< T >::auditCompare ( const AuditCopy & copy,
void(* report )(void *, Entity),
void * user ) const
inlineoverridevirtual

◆ auditKeep()

template<typename T>
void esengine::ecs::SparseSet< T >::auditKeep ( AuditCopy & copy,
u32 tick ) const
inlineoverridevirtual

◆ begin()

template<typename T>
Iterator esengine::ecs::SparseSet< T >::begin ( ) const
inline

Returns iterator to the first entity.

Returns
Begin iterator

Definition at line 634 of file SparseSet.hpp.

Referenced by emplace(), and rebuildSparse().

◆ changedTick()

template<typename T>
u32 esengine::ecs::SparseSet< T >::changedTick ( Entity entity) const
inline

The tick of entity's last write, 0 when it has none here.

Definition at line 352 of file SparseSet.hpp.

References INVALID_INDEX.

Referenced by changedTickOf().

◆ changedTickOf()

template<typename T>
u32 esengine::ecs::SparseSet< T >::changedTickOf ( Entity entity) const
inlineoverridevirtual

The tick of entity's last write here, 0 where it has no component: the type-erased changedTick.

Implements esengine::ecs::SparseSetBase.

Definition at line 357 of file SparseSet.hpp.

References changedTick().

◆ changeTicks() [1/2]

template<typename T>
u32 * esengine::ecs::SparseSet< T >::changeTicks ( )
inline

The stamps, parallel to components(): where a writer that holds a component's place stamps it.

Definition at line 368 of file SparseSet.hpp.

◆ changeTicks() [2/2]

template<typename T>
const u32 * esengine::ecs::SparseSet< T >::changeTicks ( ) const
inline

Definition at line 369 of file SparseSet.hpp.

◆ clampStamps()

template<typename T>
void esengine::ecs::SparseSet< T >::clampStamps ( u32 floor)
inlineoverridevirtual

Lifts every stamp older than floor to it, so a stamp never reads as newer after the tick wraps.

Implements esengine::ecs::SparseSetBase.

Definition at line 378 of file SparseSet.hpp.

References esengine::ecs::tickAfter().

◆ clear()

template<typename T>
void esengine::ecs::SparseSet< T >::clear ( )
inlineoverridevirtual

Removes all components.

Implements esengine::ecs::SparseSetBase.

Definition at line 546 of file SparseSet.hpp.

◆ components() [1/2]

template<typename T>
std::vector< T > & esengine::ecs::SparseSet< T >::components ( )
inline

Gets the component array for direct iteration.

Returns
Reference to component vector

Allows iterating components directly without looking up by entity. Components are stored in the same order as entities().

Definition at line 657 of file SparseSet.hpp.

◆ components() [2/2]

template<typename T>
const std::vector< T > & esengine::ecs::SparseSet< T >::components ( ) const
inline

Gets the component array for direct iteration.

Returns
Reference to component vector

Allows iterating components directly without looking up by entity. Components are stored in the same order as entities().

Definition at line 660 of file SparseSet.hpp.

◆ contains()

template<typename T>
bool esengine::ecs::SparseSet< T >::contains ( Entity entity) const
inlineoverridevirtual

Checks if an entity has a component in this set.

Parameters
entityThe entity to check
Returns
True if the entity has a component

O(1) complexity. Validates the sparse-dense mapping. Uses paged lookup to avoid unbounded memory growth.

Implements esengine::ecs::SparseSetBase.

Definition at line 294 of file SparseSet.hpp.

References contains(), and INVALID_INDEX.

Referenced by contains(), emplace(), and remove().

◆ emplace()

template<typename T>
template<typename... Args>
T & esengine::ecs::SparseSet< T >::emplace ( Entity entity,
Args &&... args )
inline

Adds a component to an entity with in-place construction.

Template Parameters
ArgsConstructor argument types
Parameters
entityThe entity to add a component to
argsArguments forwarded to T's constructor
Returns
Reference to the newly created component
Note
Asserts if the entity already has a component

O(1) amortized complexity. Allocates pages on-demand. Memory usage is bounded: O(num_pages * SPARSE_PAGE_SIZE) where num_pages = ceil(max_entity_id / SPARSE_PAGE_SIZE).

Definition at line 448 of file SparseSet.hpp.

References begin(), contains(), end(), ES_VERIFY, get(), esengine::Entity::index(), INVALID_INDEX, and SPARSE_PAGE_SIZE.

◆ empty()

template<typename T>
bool esengine::ecs::SparseSet< T >::empty ( ) const
inlineoverridevirtual

Checks if the set is empty.

Returns
True if no components are stored

Implements esengine::ecs::SparseSetBase.

Definition at line 541 of file SparseSet.hpp.

◆ end()

template<typename T>
Iterator esengine::ecs::SparseSet< T >::end ( ) const
inline

Returns iterator past the last entity.

Returns
End iterator

Definition at line 640 of file SparseSet.hpp.

Referenced by emplace(), and rebuildSparse().

◆ entities()

template<typename T>
const std::vector< Entity > & esengine::ecs::SparseSet< T >::entities ( ) const
inlineoverridevirtual

Gets the dense entity array.

Returns
Const reference to entity vector

Implements esengine::ecs::SparseSetBase.

Definition at line 646 of file SparseSet.hpp.

◆ get() [1/2]

template<typename T>
T & esengine::ecs::SparseSet< T >::get ( Entity entity)
inline

Gets the component for an entity (must exist).

Parameters
entityThe entity
Returns
Reference to the component
Note
A miss is fatal in every build: there is no valid T& to return, and a stand-in would be written through silently. tryGet() is the checked path, getUnchecked() the one for callers that proved membership.

Definition at line 308 of file SparseSet.hpp.

References ES_VERIFY_FATAL, and INVALID_INDEX.

Referenced by emplace().

◆ get() [2/2]

template<typename T>
const T & esengine::ecs::SparseSet< T >::get ( Entity entity) const
inline

Gets the component for an entity (must exist).

Parameters
entityThe entity
Returns
Reference to the component
Note
A miss is fatal in every build: there is no valid T& to return, and a stand-in would be written through silently. tryGet() is the checked path, getUnchecked() the one for callers that proved membership.

Definition at line 315 of file SparseSet.hpp.

References ES_VERIFY_FATAL, and INVALID_INDEX.

◆ getUnchecked() [1/2]

template<typename T>
T & esengine::ecs::SparseSet< T >::getUnchecked ( Entity entity)
inline

Definition at line 321 of file SparseSet.hpp.

◆ getUnchecked() [2/2]

template<typename T>
const T & esengine::ecs::SparseSet< T >::getUnchecked ( Entity entity) const
inline

Definition at line 325 of file SparseSet.hpp.

◆ indexOf()

template<typename T>
usize esengine::ecs::SparseSet< T >::indexOf ( Entity entity) const
inline

Gets the dense array index for an entity.

Parameters
entityThe entity
Returns
Index in the dense/component arrays
Note
Asserts if the entity is not in the set

Definition at line 669 of file SparseSet.hpp.

References ES_VERIFY, and INVALID_INDEX.

◆ lastChangedSlot()

template<typename T>
u32 * esengine::ecs::SparseSet< T >::lastChangedSlot ( )
inline

Where the pool's last-change tick lives, for a writer that stamps through changeTicks() to lift with it.

Definition at line 372 of file SparseSet.hpp.

◆ lastChangedTick()

template<typename T>
u32 esengine::ecs::SparseSet< T >::lastChangedTick ( ) const
inlineoverridevirtual

The tick of the last write to any component of this pool, or of the last add or remove: "anything since?" in O(1).

Implements esengine::ecs::SparseSetBase.

Definition at line 374 of file SparseSet.hpp.

◆ markChanged()

template<typename T>
void esengine::ecs::SparseSet< T >::markChanged ( Entity entity,
u32 tick )
inlineoverridevirtual

Stamps entity's component with tick: it was written. No-op for an entity without one.

Implements esengine::ecs::SparseSetBase.

Definition at line 360 of file SparseSet.hpp.

References INVALID_INDEX, and esengine::ecs::tickAfter().

◆ noteStructural()

template<typename T>
void esengine::ecs::SparseSet< T >::noteStructural ( u32 tick)
inlineoverridevirtual

Notes an add or a remove at tick, which no stamp of a component that is still there records.

Implements esengine::ecs::SparseSetBase.

Definition at line 375 of file SparseSet.hpp.

References esengine::ecs::tickAfter().

◆ operator=() [1/2]

template<typename T>
SparseSet & esengine::ecs::SparseSet< T >::operator= ( const SparseSet< T > & )
delete

References SparseSet().

◆ operator=() [2/2]

template<typename T>
SparseSet & esengine::ecs::SparseSet< T >::operator= ( SparseSet< T > && )
defaultnoexcept

References SparseSet().

◆ permute()

template<typename T>
void esengine::ecs::SparseSet< T >::permute ( std::vector< usize > & perm)
inline

Puts slot perm[i] at position i, for every i: the entity, its component and its stamp together.

The one way storage is reordered (reorderBy, Registry::sort). A permutation that moves nothing leaves storage, and every handed-out pointer, alone. Consumes perm.

Definition at line 575 of file SparseSet.hpp.

References rebuildSparse().

Referenced by reorderBy().

◆ rebuildSparse()

template<typename T>
void esengine::ecs::SparseSet< T >::rebuildSparse ( )
inline

Definition at line 606 of file SparseSet.hpp.

References begin(), end(), INVALID_INDEX, and SPARSE_PAGE_SIZE.

Referenced by permute().

◆ remove()

template<typename T>
void esengine::ecs::SparseSet< T >::remove ( Entity entity)
inlineoverridevirtual

Removes a component from an entity.

Parameters
entityThe entity whose component to remove

O(1) complexity using swap-and-pop. The last element is moved to fill the gap, maintaining density. No-op if the entity doesn't have a component.

Implements esengine::ecs::SparseSetBase.

Definition at line 492 of file SparseSet.hpp.

References contains(), esengine::Entity::index(), INVALID_INDEX, and SPARSE_PAGE_SIZE.

◆ reorderBy()

template<typename T>
void esengine::ecs::SparseSet< T >::reorderBy ( const std::vector< u32 > & rank)
inlineoverridevirtual

Permutes storage so iteration follows rank.

Parameters
rankRank per ENTITY INDEX (Entity::index()); lower ranks iterate first

Storage order is iteration order, and iteration order is the renderer's within-layer painter order, so this is how a scene's authored entity order reaches the draw list without respawning anything. Entities with no rank (index past the end, or the UNRANKED sentinel) keep their relative order after the ranked ones — the sort is stable. A no-op reorder leaves storage (and therefore every handed-out component pointer) untouched.

Implements esengine::ecs::SparseSetBase.

Definition at line 558 of file SparseSet.hpp.

References permute(), and esengine::ecs::SparseSetBase::stablePermutation().

◆ size()

template<typename T>
usize esengine::ecs::SparseSet< T >::size ( ) const
inlineoverridevirtual

Gets the number of components in the set.

Returns
Component count

Implements esengine::ecs::SparseSetBase.

Definition at line 535 of file SparseSet.hpp.

◆ tryGet() [1/2]

template<typename T>
T * esengine::ecs::SparseSet< T >::tryGet ( Entity entity)
inline

Tries to get a component (returns nullptr if not found).

Parameters
entityThe entity
Returns
Pointer to the component, or nullptr

Definition at line 334 of file SparseSet.hpp.

References INVALID_INDEX.

◆ tryGet() [2/2]

template<typename T>
const T * esengine::ecs::SparseSet< T >::tryGet ( Entity entity) const
inline

Tries to get a component (returns nullptr if not found).

Parameters
entityThe entity
Returns
Pointer to the component, or nullptr

Definition at line 341 of file SparseSet.hpp.

References INVALID_INDEX.

◆ typeName()

template<typename T>
std::string_view esengine::ecs::SparseSet< T >::typeName ( ) const
inlineoverridevirtual

The component type's name, for what the audit says.

Implements esengine::ecs::SparseSetBase.

Definition at line 382 of file SparseSet.hpp.

References esengine::ecs::componentTypeName().

◆ version()

template<typename T>
u32 esengine::ecs::SparseSet< T >::version ( ) const
inlineoverridevirtual

Monotonic version, bumped whenever stored components may have moved in memory (buffer reallocation on growth, or swap-and-pop relocation on removal).

Single source of truth for the cross-boundary pointer-staleness guard: a raw component pointer handed to JS (e.g. getTransformPtr) is only valid while this value is unchanged. Replaces the old SchemaComponentPool::poolVersion (which lived in a now-deleted parallel store and, notably, was not bumped on remove).

Implements esengine::ecs::SparseSetBase.

Definition at line 555 of file SparseSet.hpp.

Member Data Documentation

◆ INVALID_INDEX

template<typename T>
u32 esengine::ecs::SparseSet< T >::INVALID_INDEX = INVALID_DENSE_INDEX
staticconstexpr

Sentinel for empty sparse slots.

Definition at line 265 of file SparseSet.hpp.

Referenced by auditCompare(), changedTick(), contains(), emplace(), get(), get(), indexOf(), markChanged(), rebuildSparse(), remove(), tryGet(), and tryGet().

◆ kAuditBytes

template<typename T>
bool esengine::ecs::SparseSet< T >::kAuditBytes = std::is_trivially_copyable_v<T>
staticconstexpr

Definition at line 384 of file SparseSet.hpp.

Referenced by auditable(), auditCompare(), and auditKeep().

◆ kAuditValues

template<typename T>
bool esengine::ecs::SparseSet< T >::kAuditValues = !kAuditBytes && std::is_copy_constructible_v<T> && std::equality_comparable<T>
staticconstexpr

Definition at line 385 of file SparseSet.hpp.

Referenced by auditable(), auditCompare(), and auditKeep().

◆ SPARSE_PAGE_SIZE

template<typename T>
usize esengine::ecs::SparseSet< T >::SPARSE_PAGE_SIZE = 4096
staticconstexpr

Page size for paged sparse array (entities per page).

Definition at line 262 of file SparseSet.hpp.

Referenced by emplace(), rebuildSparse(), and remove().


The documentation for this class was generated from the following file:
  • /home/runner/work/estella/estella/src/esengine/ecs/SparseSet.hpp