From 8d77498150ad23b6efd0b101cc752df268c169af Mon Sep 17 00:00:00 2001 From: Dylan Hollemaert Date: Mon, 16 Nov 2026 16:31:29 +0100 Subject: [PATCH] ECS scheduler, command buffer and access policies, along with unit tests. * ECS upgrade and tests from: [Pumpkin Engine](https://github.com/0ri0546/PumpkinEngine/) that I implemented myself two weeks ago. Signed-off-by: Dylan Hollemaert --- Doxyfile | 3 +- .../Core/ECS/Private/CommandBuffer.cppm | 114 ++ .../Core/ECS/Private/ComponentPool.cppm | 66 + Source/Engine/Core/ECS/Private/Registry.cpp | 11 + Source/Engine/Core/ECS/Private/Registry.cppm | 153 +- Source/Engine/Core/ECS/Private/SparseSet.cppm | 104 +- .../Engine/Core/ECS/Private/ThreadPool.cppm | 163 ++ Source/Engine/Core/ECS/Private/World.cpp | 17 + Source/Engine/Core/ECS/Public/Component.cppm | 11 + Source/Engine/Core/ECS/Public/ECS.cppm | 11 + Source/Engine/Core/ECS/Public/Entity.cppm | 19 + Source/Engine/Core/ECS/Public/Scheduler.cppm | 417 +++++ Source/Engine/Core/ECS/Public/World.cppm | 110 ++ Tests/Engine/Core/ECS/ECS.cpp | 694 ++++++++- Tests/Engine/Core/ECS/ECSScheduler.cpp | 1338 +++++++++++++++++ 15 files changed, 3194 insertions(+), 37 deletions(-) create mode 100644 Source/Engine/Core/ECS/Private/CommandBuffer.cppm create mode 100644 Source/Engine/Core/ECS/Private/ThreadPool.cppm create mode 100644 Source/Engine/Core/ECS/Public/Scheduler.cppm create mode 100644 Tests/Engine/Core/ECS/ECSScheduler.cpp diff --git a/Doxyfile b/Doxyfile index 693b1ef..9bb0952 100644 --- a/Doxyfile +++ b/Doxyfile @@ -290,7 +290,8 @@ TAB_SIZE = 4 # with the commands \{ and \} for these it is advised to use the version @{ and # @} or use a double escape (\\{ and \\}) -ALIASES = +ALIASES += "thread_safety=\par Thread safety:^^" +ALIASES += "complexity=\par Complexity:^^" # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources # only. Doxygen will then generate output that is more tailored for C. For diff --git a/Source/Engine/Core/ECS/Private/CommandBuffer.cppm b/Source/Engine/Core/ECS/Private/CommandBuffer.cppm new file mode 100644 index 0000000..0e4c679 --- /dev/null +++ b/Source/Engine/Core/ECS/Private/CommandBuffer.cppm @@ -0,0 +1,114 @@ +// SPDX-License-Identifier: MIT + +/// @file CommandBuffer.cppm +/// @brief Module NE.Engine.ECS.CommandBuffer: deferred structural changes recorded by systems. + +module; + +#include + +export module NE.Engine.ECS.CommandBuffer; + +import NE.Engine.ECS.Component; +import NE.Engine.ECS.Entity; +import NE.Engine.ECS.World; + +import std; + +export namespace Nexus::ECS { + /// @brief Records structural World changes so they can be applied later, single-threaded. + /// + /// Creating/destroying entities and adding/removing components cannot happen while systems + /// run in parallel (it would reallocate pools under the readers' feet). Systems therefore + /// record those operations here and the Scheduler calls Apply() once all systems of the + /// frame have finished. Each scheduled system owns its own buffer, so commands are applied + /// in system registration order. + /// + /// @note Arguments given to Add() are decay-copied/moved into the buffer at record time. + /// @thread_safety Recording methods (Destroy, Add, Remove, Spawn) are thread-safe (internal + /// mutex), e.g. from several ParallelForEach chunks; the relative order between chunks is + /// then unspecified. Apply() must not run concurrently with anything touching the World. + class NEXUS_API CommandBuffer { + using Command = std::function; + + public: + /// @brief Records the destruction of an entity. + /// @param entity Entity to destroy. If it is already dead when the buffer is applied, the command is a no-op. + /// @thread_safety Thread-safe. + /// @see World::DestroyEntity + void Destroy(Entity entity) { + Push([entity](World& world) { world.DestroyEntity(entity); }); + } + + /// @brief Records the addition of a component to an entity. + /// + /// @tparam T Component type to add. + /// @tparam Args Constructor argument types (stored by value). + /// @param entity Target entity. + /// @param args Arguments forwarded to T's constructor when the command is applied. + /// @note Skipped silently if @p entity is dead at apply time. If the entity already has a + /// T, the existing component is kept untouched (see World::Add / SparseSet::Emplace). + /// @thread_safety Thread-safe. + template + void Add(Entity entity, Args&&... args) { + Push([entity, values = std::make_tuple(std::forward(args)...)](World& world) mutable { + if (!world.IsAlive(entity)) + return; + std::apply([&](auto&&... a) { world.Add(entity, std::move(a)...); }, std::move(values)); + }); + } + + /// @brief Records the removal of a component from an entity. + /// @tparam T Component type to remove. + /// @param entity Target entity. Skipped silently if it is dead at apply time; no-op if it has no T. + /// @thread_safety Thread-safe. + template + void Remove(Entity entity) { + Push([entity](World& world) { + if (world.IsAlive(entity)) + world.Remove(entity); + }); + } + + /// @brief Records the creation of a new entity. + /// + /// The entity does not exist while recording; it is created when the buffer is applied and + /// @p init is then called with the World and the fresh handle so it can attach components. + /// + /// @param init Callback invoked at apply time as `init(world, newEntity)`. + /// @thread_safety Thread-safe. + /// @see World::CreateEntity + void Spawn(std::function init) { + Push([init = std::move(init)](World& world) mutable { init(world, world.CreateEntity()); }); + } + + /// @brief Executes every recorded command on @p world, in recording order, then empties the buffer. + /// + /// @param world World the commands are applied to. + /// @pre No system is running (call it single-threaded, after the frame's systems finished). + /// @warning If a command throws, the exception propagates and the remaining commands of + /// that batch are discarded. + /// @thread_safety The pending list is swapped out under the mutex, so commands recorded + /// during Apply() are kept for the next call. Execution itself is not + /// synchronised with other World users. + void Apply(World& world) { + std::vector commands; + { + std::scoped_lock lock(m_mutex); + commands.swap(m_commands); + } + for (auto& command : commands) + command(world); + } + + private: + /// @brief Appends a command under the lock (shared by all recording methods). + void Push(Command command) { + std::scoped_lock lock(m_mutex); + m_commands.push_back(std::move(command)); + } + + std::mutex m_mutex; + std::vector m_commands; + }; +} // namespace Nexus::ECS diff --git a/Source/Engine/Core/ECS/Private/ComponentPool.cppm b/Source/Engine/Core/ECS/Private/ComponentPool.cppm index 19b4b9f..fe38221 100644 --- a/Source/Engine/Core/ECS/Private/ComponentPool.cppm +++ b/Source/Engine/Core/ECS/Private/ComponentPool.cppm @@ -1,5 +1,8 @@ // SPDX-License-Identifier: MIT +/// @file ComponentPool.cppm +/// @brief Module NE.Engine.ECS.ComponentPool: type-erased and typed per-component storage. + module; #include @@ -7,6 +10,7 @@ module; export module NE.Engine.ECS.ComponentPool; import NE.Engine.Core.Types; + import NE.Engine.ECS.Component; import NE.Engine.ECS.Entity; import NE.Engine.ECS.SparseSet; @@ -14,65 +18,127 @@ import NE.Engine.ECS.SparseSet; import std; export namespace Nexus::ECS { + /// @brief Type-erased interface of a component pool. + /// + /// Lets the Registry operate on every pool (remove an entity everywhere, clear, query the + /// smallest pool) without knowing the component types. + /// + /// @thread_safety Same rules as SparseSet: no concurrent structural changes. class NEXUS_API IComponentPool { public: + /// @brief Virtual destructor, pools are owned through `std::unique_ptr`. virtual ~IComponentPool() = default; + /// @brief Removes the component of @p entity, if present. + /// @param entity Entity to strip from this pool. No-op if absent. virtual void Remove(Entity entity) = 0; + /// @brief Tests whether @p entity has a component in this pool. + /// @param entity Handle to test (generation-checked). + /// @return true if present. virtual bool Contains(Entity entity) const = 0; + /// @brief Pre-allocates storage. + /// @param capacity Number of components to reserve room for. virtual void Reserve(usize capacity) = 0; + /// @brief Removes every component from the pool. virtual void Clear() = 0; + /// @brief Entities that own a component in this pool. + /// @return Dense span of owners (order not stable across removals). + /// @warning Invalidated by structural changes. virtual std::span Entities() const = 0; }; + /// @brief Storage for all components of type @p T, backed by a SparseSet. + /// + /// @tparam T Component type. + /// @thread_safety Concurrent mutation of different entities' components is safe provided + /// nobody changes the pool structure (Emplace/Remove/Clear/Reserve); this is + /// the guarantee the Scheduler relies on. template class NEXUS_API ComponentPool final : public IComponentPool { public: + /// @brief Adds a component for @p entity, constructing it in place. + /// @tparam Args Constructor argument types. + /// @param entity Owner of the new component. + /// @param args Arguments forwarded to T's constructor. + /// @return Reference to the component. If the entity already had one, it is returned unchanged + /// and @p args are ignored. + /// @see SparseSet::Emplace template T& Emplace(Entity entity, Args&&... args) { return m_storage.Emplace(entity, std::forward(args)...); } + /// @copydoc IComponentPool::Remove void Remove(Entity entity) override { m_storage.Remove(entity); } + /// @copydoc IComponentPool::Contains bool Contains(Entity entity) const override { return m_storage.Contains(entity); } + /// @copydoc IComponentPool::Reserve void Reserve(usize capacity) override { m_storage.Reserve(capacity); } + /// @copydoc IComponentPool::Clear void Clear() override { m_storage.Clear(); } + /// @brief Checked access to the component of @p entity. + /// @param entity Owner. + /// @return Mutable reference to the component. + /// @throws std::out_of_range if @p entity has no such component. T& Get(Entity entity) { return m_storage.Get(entity); } + /// @brief Checked read-only access to the component of @p entity. + /// @param entity Owner. + /// @return Const reference to the component. + /// @throws std::out_of_range if @p entity has no such component. const T& Get(Entity entity) const { return m_storage.Get(entity); } + /// @brief Unchecked access to the component of @p entity. + /// @param entity Owner. + /// @pre Contains(entity) is true (undefined behaviour otherwise). + /// @return Mutable reference to the component. + T& Fetch(Entity entity) { + return m_storage.Fetch(entity); + } + + /// @brief Non-throwing lookup. + /// @param entity Owner. + /// @return Pointer to the component or nullptr. T* TryGet(Entity entity) { return m_storage.TryGet(entity); } + /// @brief Non-throwing read-only lookup. + /// @param entity Owner. + /// @return Const pointer to the component or nullptr. const T* TryGet(Entity entity) const { return m_storage.TryGet(entity); } + /// @copydoc IComponentPool::Entities std::span Entities() const override { return m_storage.Entities(); } + /// @brief Mutable view over all components, index-aligned with Entities(). + /// @warning Invalidated by structural changes. std::span Values() { return m_storage.Values(); } + /// @brief Read-only view over all components, index-aligned with Entities(). + /// @warning Invalidated by structural changes. std::span Values() const { return m_storage.Values(); } diff --git a/Source/Engine/Core/ECS/Private/Registry.cpp b/Source/Engine/Core/ECS/Private/Registry.cpp index bcbab12..6200ac1 100644 --- a/Source/Engine/Core/ECS/Private/Registry.cpp +++ b/Source/Engine/Core/ECS/Private/Registry.cpp @@ -1,9 +1,20 @@ // SPDX-License-Identifier: MIT +/// @file Registry.cpp +/// @brief Implementation unit of NE.Engine.ECS.Registry (documented in Registry.cppm). + module NE.Engine.ECS.Registry; +import std; + namespace Nexus::ECS { + ComponentId NextComponentId() { + static std::atomic id = 0; + return id.fetch_add(1, std::memory_order_relaxed); + } + void Registry::RemoveEntity(Entity entity) { + // Pools are created lazily, so the table may contain empty slots. for (const auto& pool : m_pools) if (pool) pool->Remove(entity); diff --git a/Source/Engine/Core/ECS/Private/Registry.cppm b/Source/Engine/Core/ECS/Private/Registry.cppm index 3bd9a93..8496d7e 100644 --- a/Source/Engine/Core/ECS/Private/Registry.cppm +++ b/Source/Engine/Core/ECS/Private/Registry.cppm @@ -1,5 +1,8 @@ // SPDX-License-Identifier: MIT +/// @file Registry.cppm +/// @brief Module NE.Engine.ECS.Registry: component type ids, per-type pools and multi-component queries. + module; #include @@ -14,30 +17,54 @@ import NE.Engine.ECS.Entity; import std; export namespace Nexus::ECS { + /// @brief Dense runtime identifier of a component type (index into the Registry's pool table). using ComponentId = uint32; - inline ComponentId NextComponentId() { - static ComponentId id = 0; - return id++; - } - + /// @brief Hands out the next unused ComponentId. + /// @return A process-wide unique, monotonically increasing id. + /// @thread_safety Thread-safe (atomic counter). + /// @note Ids reflect first-use order and may differ between runs: never persist them. + NEXUS_API ComponentId NextComponentId(); + + /// @brief Returns the ComponentId of type @p T, assigning one on first call. + /// @tparam T Component type. + /// @return Stable id for @p T for the lifetime of the process. + /// @thread_safety Thread-safe (function-local static initialisation). + /// @warning The id lives in a function-local static: every binary using the same Registry + /// must resolve to the same instantiation (watch DLL boundaries), or ids diverge. template NEXUS_API ComponentId ComponentTypeId() { static const ComponentId id = NextComponentId(); return id; } + /// @brief Owns one ComponentPool per component type and implements multi-component queries. + /// + /// Pools are created lazily and stored in a table indexed by ComponentId. Queries iterate + /// the smallest involved pool and probe the others. + /// + /// @thread_safety Pool creation (Pool() on a missing pool) resizes the table and is NOT + /// thread-safe; the Scheduler pre-creates all declared pools single-threaded + /// (Access::EnsurePools). Afterwards, per-entity access from different + /// threads is safe as long as no structural change happens. class NEXUS_API Registry { public: + /// @brief Creates an empty registry (no pools). Registry() = default; ~Registry() = default; + /// @brief Non-copyable (owns pools uniquely). Registry(const Registry&) = delete; Registry& operator=(const Registry&) = delete; + /// @brief Movable. Registry(Registry&&) noexcept = default; Registry& operator=(Registry&&) noexcept = default; + /// @brief Returns the pool of @p T, creating it if needed. + /// @tparam T Component type. + /// @return Mutable reference to the pool. + /// @warning May grow the pool table: not safe to call concurrently with other registry access. template ComponentPool& Pool() { const auto id = ComponentTypeId(); @@ -51,11 +78,20 @@ export namespace Nexus::ECS { return static_cast&>(*m_pools[id]); } + /// @brief Returns the existing pool of @p T (read-only). + /// @tparam T Component type. + /// @return Const reference to the pool. + /// @throws std::out_of_range if T's id is beyond the pool table. + /// @warning If the table covers T's id but the pool was never created, this dereferences an + /// empty pointer (undefined behaviour). Check HasPool() or use TryPool() first. template const ComponentPool& Pool() const { return static_cast&>(*m_pools.at(ComponentTypeId())); } + /// @brief Returns the pool of @p T without creating it. + /// @tparam T Component type. + /// @return Pointer to the pool, or nullptr if it does not exist yet. template ComponentPool* TryPool() { const auto id = ComponentTypeId(); @@ -66,6 +102,9 @@ export namespace Nexus::ECS { return static_cast*>(m_pools[id].get()); } + /// @brief Read-only variant of TryPool(). + /// @tparam T Component type. + /// @return Const pointer to the pool, or nullptr if it does not exist yet. template const ComponentPool* TryPool() const { const auto id = ComponentTypeId(); @@ -76,6 +115,9 @@ export namespace Nexus::ECS { return static_cast*>(m_pools[id].get()); } + /// @brief Tests whether the pool of @p T exists. + /// @tparam T Component type. + /// @return true if a pool was created for @p T. template bool HasPool() const { const auto id = ComponentTypeId(); @@ -83,6 +125,10 @@ export namespace Nexus::ECS { return id < m_pools.size() && m_pools[id] != nullptr; } + /// @brief Collects the entities that have all the listed components. + /// @tparam Components Required component types (distinct). + /// @return Snapshot of matching entities; empty if the pack is empty or any pool is missing. + /// @complexity O(n_min * k) with n_min the size of the smallest pool. template std::vector Query() { if constexpr (sizeof...(Components) == 0) @@ -111,34 +157,24 @@ export namespace Nexus::ECS { return result; } + /// @brief Collects the entities that have at least one of the listed components. + /// @tparam Components Component types. + /// @return Snapshot without duplicates (deduplicated by Entity::index), in pool then dense order. template std::vector QueryAny() { if constexpr (sizeof...(Components) == 0) return {}; - usize max_id = 0; - auto track_max = [&]() { - if (HasPool()) { - const auto& entities = Pool().Entities(); - if (!entities.empty()) { - max_id = std::max(max_id, static_cast(entities.back().index)); - } - } - }; - (track_max.template operator()(), ...); - - if (max_id == 0) - return {}; - - std::vector visited(max_id + 1, false); + std::vector visited; // indexed by Entity::index, grown on demand std::vector result; - result.reserve(max_id + 1); auto collect = [&]() { if (!HasPool()) return; for (const auto entity : Pool().Entities()) { const usize idx = entity.index; + if (idx >= visited.size()) + visited.resize(std::max(idx + 1, visited.size() * 2), false); if (!visited[idx]) { visited[idx] = true; result.push_back(entity); @@ -151,65 +187,117 @@ export namespace Nexus::ECS { return result; } + /// @brief Non-owning, forward-iterable view over entities having all of @p Components. + /// + /// Iteration is driven by the smallest pool (the "driver"); entities lacking one of the other + /// components are skipped. Dereferencing yields `std::tuple`, so it + /// works with structured bindings: `for (auto [e, pos, vel] : view)`. + /// + /// @tparam Components Component types of the view (distinct: they are looked up by type). + /// @warning Invalidated by any structural change to the involved pools. Changing the + /// structure while iterating is undefined behaviour. + /// @thread_safety Distinct Slice()s may be iterated on different threads; each entity then + /// belongs to exactly one slice (this is how ParallelForEach works). template - class NEXUS_API QueryView { + class QueryView { public: + /// @brief Input-style iterator over the driver pool that skips entities missing any component. struct Iterator { using value_type = std::tuple; std::span::iterator it; std::span::iterator end; std::tuple*...> pools; + const IComponentPool* driverPool; + /// @brief Advances to the first entity (from the current one) present in every pool, or to the end. void SkipToValid() { - while (it != end && !(std::get*>(pools)->Contains(*it) && ...)) + const auto has = [this](const IComponentPool* pool) { + return pool == driverPool || pool->Contains(*it); + }; + while (it != end && !(has(std::get*>(pools)) && ...)) ++it; } + /// @brief Moves to the next matching entity. @return *this. Iterator& operator++() { ++it; SkipToValid(); return *this; } + /// @brief Inequality on the driver position. @param other Iterator to compare. @return true if the positions differ. bool operator!=(const Iterator& other) const { return it != other.it; } + /// @brief Equality on the driver position. @param other Iterator to compare. @return true if both point to the same driver position. bool operator==(const Iterator& other) const { return it == other.it; } + /// @brief Dereferences to the entity and references to its components. + /// @return Tuple `(Entity, Components&...)`. + /// @pre The iterator is not at end() and was positioned by SkipToValid() (always true for iterators from begin()/++). value_type operator*() const { const Entity entity = *it; - return value_type(entity, std::get*>(pools)->Get(entity)...); + // Fetch is safe, membership was validated by SkipToValid + return value_type(entity, std::get*>(pools)->Fetch(entity)...); } }; - QueryView(std::span driver, ComponentPool*... pools) - : m_driver(driver), + /// @brief Builds a view from an explicit driver. + /// @param driverPool Pool providing the iteration order (skipped during membership checks); nullptr for an empty view. + /// @param driver Entities to iterate (normally driverPool->Entities(), or a sub-range of it). + /// @param pools Pools of every component in the view. + QueryView(const IComponentPool* driverPool, std::span driver, + ComponentPool*... pools) + : m_driverPool(driverPool), + m_driver(driver), m_pools(pools...) {} + /// @brief Iterator to the first matching entity (== end() if none). @return Begin iterator. Iterator begin() const { - Iterator iter{m_driver.begin(), m_driver.end(), m_pools}; + Iterator iter{m_driver.begin(), m_driver.end(), m_pools, m_driverPool}; iter.SkipToValid(); return iter; } + /// @brief Past-the-end iterator. @return End iterator. Iterator end() const { - return {m_driver.end(), m_driver.end(), m_pools}; + return {m_driver.end(), m_driver.end(), m_pools, m_driverPool}; + } + + /// @brief Size of the driver range. + /// @return Number of entities in the driver pool: an *upper bound* on the number of matches, not the exact count. + [[nodiscard]] usize Size() const { + return m_driver.size(); + } + + /// @brief Sub-view over a contiguous part of the driver range. + /// @param first Offset in the driver range. + /// @param count Number of driver entries to cover. + /// @pre `first + count <= Size()` (std::span::subspan precondition). + /// @return View over `[first, first + count)` of the driver; filtering still applies. + QueryView Slice(usize first, usize count) const { + return QueryView(m_driverPool, m_driver.subspan(first, count), + std::get*>(m_pools)...); } private: + const IComponentPool* m_driverPool; std::span m_driver; std::tuple*...> m_pools; }; + /// @brief Builds a QueryView over entities having all listed components. + /// @tparam Components Required component types (distinct, at least one: enforced by static_assert). + /// @return View driven by the smallest pool; an empty view if any pool does not exist. template QueryView View() { static_assert(sizeof...(Components) > 0, "View requires at least one component"); if (!(HasPool() && ...)) - return QueryView({}, static_cast*>(nullptr)...); + return QueryView(nullptr, {}, static_cast*>(nullptr)...); const std::array pools{&Pool()...}; @@ -219,11 +307,16 @@ export namespace Nexus::ECS { smallest = pool; } - return QueryView(smallest->Entities(), &Pool()...); + return QueryView(smallest, smallest->Entities(), &Pool()...); } + /// @brief Removes an entity's components from every pool. + /// @param entity Entity to strip. Pools not containing it are unaffected. + /// @complexity O(number of pools). void RemoveEntity(Entity entity); + /// @brief Empties every pool. + /// @post No component remains; the pools themselves stay allocated. void Clear(); private: diff --git a/Source/Engine/Core/ECS/Private/SparseSet.cppm b/Source/Engine/Core/ECS/Private/SparseSet.cppm index e227efa..2cde60d 100644 --- a/Source/Engine/Core/ECS/Private/SparseSet.cppm +++ b/Source/Engine/Core/ECS/Private/SparseSet.cppm @@ -1,5 +1,8 @@ // SPDX-License-Identifier: MIT +/// @file SparseSet.cppm +/// @brief Module NE.Engine.ECS.SparseSet: dense component storage indexed by Entity. + module; #include @@ -12,9 +15,46 @@ import NE.Engine.ECS.Entity; import std; export namespace Nexus::ECS { + /// @brief Sparse-set container mapping entities to values of type @p T. + /// + /// Values live contiguously in a dense array (cache-friendly iteration); a sparse array + /// indexed by Entity::index stores `denseIndex + 1` (0 means "absent"). A parallel dense + /// array holds the owning Entity of each value, so Entities() and Values() are index-aligned. + /// + /// @tparam T Stored value type (move-constructible and move-assignable). + /// @note Insertion order is not preserved after a Remove() (swap-and-pop). + /// @warning Any structural change (Emplace, Remove, Clear) may invalidate references, + /// pointers and spans previously obtained from the set. + /// @thread_safety Not thread-safe for structural changes. Concurrent const access is safe, + /// and so is concurrent mutation of *different* values through Get/Fetch/ + /// TryGet as long as no thread changes the structure. template class NEXUS_API SparseSet { public: + /// @brief Creates an empty set. + SparseSet() = default; + /// @brief Non-copyable (values are owned uniquely). + SparseSet(const SparseSet&) = delete; + SparseSet& operator=(const SparseSet&) = delete; + /// @brief Move-constructs, taking over the storage of the source. + SparseSet(SparseSet&&) noexcept = default; + SparseSet& operator=(SparseSet&&) noexcept = default; + + /// @brief Inserts a value for @p entity, constructing it in place. + /// + /// Behaviour by case: + /// - Entity absent: the value is appended to the dense array. + /// - Entity already present (same index and generation): nothing is constructed or assigned, + /// the existing value is returned and @p args are ignored. + /// - Sparse slot used by a *stale* handle (same index, older generation): that entry is + /// overwritten in place with `T(args...)`. + /// + /// @tparam Args Constructor argument types. + /// @param entity Owner of the value. + /// @param args Arguments forwarded to T's constructor. + /// @return Reference to the stored value (new or pre-existing). + /// @complexity Amortised O(1). + /// @warning The returned reference is invalidated by the next structural change. template T& Emplace(Entity entity, Args&&... args) { if (entity.index >= m_sparse.size()) [[unlikely]] { @@ -24,7 +64,13 @@ export namespace Nexus::ECS { auto& sparse_slot = m_sparse[entity.index]; if (sparse_slot != 0) [[unlikely]] { - return m_dense[sparse_slot - 1]; + const auto dense_index = sparse_slot - 1; + if (m_denseEntities[dense_index] == entity) + return m_dense[dense_index]; // already present + + m_denseEntities[dense_index] = entity; + m_dense[dense_index] = T(std::forward(args)...); + return m_dense[dense_index]; } const auto index = m_dense.size(); @@ -36,6 +82,13 @@ export namespace Nexus::ECS { return m_dense.back(); } + /// @brief Removes the value owned by @p entity, if any. + /// + /// The last dense element is moved into the freed position (swap-and-pop) and its sparse + /// slot is patched, so removal is O(1) but reorders the dense arrays. + /// + /// @param entity Entity whose value is removed. No-op if absent (or if the handle is stale). + /// @complexity O(1). void Remove(Entity entity) { if (!Contains(entity)) return; @@ -59,16 +112,34 @@ export namespace Nexus::ECS { m_sparse[entity.index] = 0; } + /// @brief Pre-allocates capacity for @p capacity elements. + /// + /// @param capacity Number of values to reserve in the dense arrays; also reserved in the + /// sparse array, which is indexed by Entity::index and still grows on demand. void Reserve(usize capacity) { m_sparse.reserve(capacity); m_dense.reserve(capacity); m_denseEntities.reserve(capacity); } + /// @brief Tests whether @p entity currently owns a value. + /// @param entity Handle to test; the generation must match, so stale handles return false. + /// @return true if a value for exactly this handle is stored. + /// @complexity O(1). bool Contains(Entity entity) const { - return entity.index < m_sparse.size() && m_sparse[entity.index] != 0; + if (entity.index >= m_sparse.size()) + return false; + + const auto slot = m_sparse[entity.index]; + + return slot != 0 && m_denseEntities[slot - 1] == entity; } + /// @brief Checked access to the value of @p entity. + /// @param entity Owner of the value. + /// @return Mutable reference to the value. + /// @throws std::out_of_range if the entity has no value in this set. + /// @see Fetch, TryGet T& Get(Entity entity) { if (!Contains(entity)) throw std::out_of_range("SparseSet::Get: entity not present"); @@ -76,6 +147,10 @@ export namespace Nexus::ECS { return m_dense[m_sparse[entity.index] - 1]; } + /// @brief Checked read-only access to the value of @p entity. + /// @param entity Owner of the value. + /// @return Const reference to the value. + /// @throws std::out_of_range if the entity has no value in this set. const T& Get(Entity entity) const { if (!Contains(entity)) throw std::out_of_range("SparseSet::Get: entity not present"); @@ -83,6 +158,18 @@ export namespace Nexus::ECS { return m_dense[m_sparse[entity.index] - 1]; } + /// @brief Unchecked access to the value of @p entity (hot-path variant of Get()). + /// @param entity Owner of the value. + /// @pre Contains(entity) is true; otherwise the behaviour is undefined. + /// @return Mutable reference to the value. + // Unchecked access: the caller guarantees Contains(entity) + T& Fetch(Entity entity) { + return m_dense[m_sparse[entity.index] - 1]; + } + + /// @brief Non-throwing lookup. + /// @param entity Owner of the value. + /// @return Pointer to the value, or nullptr if absent. T* TryGet(Entity entity) { if (!Contains(entity)) return nullptr; @@ -90,6 +177,9 @@ export namespace Nexus::ECS { return &m_dense[m_sparse[entity.index] - 1]; } + /// @brief Non-throwing read-only lookup. + /// @param entity Owner of the value. + /// @return Const pointer to the value, or nullptr if absent. const T* TryGet(Entity entity) const { if (!Contains(entity)) return nullptr; @@ -97,18 +187,28 @@ export namespace Nexus::ECS { return &m_dense[m_sparse[entity.index] - 1]; } + /// @brief Entities that own a value, in dense order. + /// @return Span index-aligned with Values(): `Entities()[i]` owns `Values()[i]`. + /// @warning Invalidated by structural changes. std::span Entities() const { return m_denseEntities; } + /// @brief Mutable view over all stored values (dense order). + /// @return Span index-aligned with Entities(). + /// @warning Invalidated by structural changes. std::span Values() { return m_dense; } + /// @brief Read-only view over all stored values (dense order). + /// @return Const span index-aligned with Entities(). std::span Values() const { return m_dense; } + /// @brief Removes every value. + /// @post Contains() is false for every entity; size is 0. Allocated capacity is kept. void Clear() { m_sparse.clear(); m_dense.clear(); diff --git a/Source/Engine/Core/ECS/Private/ThreadPool.cppm b/Source/Engine/Core/ECS/Private/ThreadPool.cppm new file mode 100644 index 0000000..12d25eb --- /dev/null +++ b/Source/Engine/Core/ECS/Private/ThreadPool.cppm @@ -0,0 +1,163 @@ +// SPDX-License-Identifier: MIT + +/// @file ThreadPool.cppm +/// @brief Module NE.Engine.ECS.ThreadPool: worker pool used by the ECS Scheduler. + +module; + +#include + +export module NE.Engine.ECS.ThreadPool; + +import NE.Engine.Core.Types; + +import std; + +export namespace Nexus::ECS { + /// @brief Fixed-size pool of worker threads executing queued tasks, with a parallel-for helper. + /// + /// Workers are `std::jthread`s waiting on a condition variable. Tasks are executed in FIFO + /// order of submission (across workers, completion order is unspecified). + /// + /// @thread_safety Submit(), ParallelFor() and Size() may be called from any thread, + /// including from inside a task running on the pool. + class NEXUS_API ThreadPool { + public: + /// @brief Unit of work executed by a worker. + using Task = std::function; + + /// @brief Starts the worker threads. + /// @param threadCount Number of workers; clamped to at least 1. Defaults to + /// `std::thread::hardware_concurrency()`. + explicit ThreadPool(usize threadCount = std::thread::hardware_concurrency()) { + threadCount = std::max(1, threadCount); + m_workers.reserve(threadCount); + for (usize i = 0; i < threadCount; ++i) + m_workers.emplace_back([this] { WorkerLoop(); }); + } + + /// @brief Requests stop and joins the workers. + /// + /// Workers finish the tasks still in the queue before exiting, so destruction blocks until + /// the queue is drained. + /// + /// @note Members are ordered so that `m_workers` is destroyed first, which joins the threads + /// before the queue and mutex they use are destroyed. + ~ThreadPool() { + { + std::scoped_lock lock(m_mutex); + m_stopping = true; + } + m_cv.notify_all(); + } + + /// @brief Non-copyable (owns threads). + ThreadPool(const ThreadPool&) = delete; + ThreadPool& operator=(const ThreadPool&) = delete; + + /// @brief Number of worker threads. + /// @return Worker count (>= 1). + [[nodiscard]] usize Size() const { + return m_workers.size(); + } + + /// @brief Queues a task and wakes one worker. + /// @param task Callable to run on a worker thread. + /// @warning An exception escaping @p task terminates the program (it would leave the + /// worker thread). Catch inside the task, as Scheduler does. + /// @thread_safety Thread-safe. + void Submit(Task task) { + { + std::scoped_lock lock(m_mutex); + m_tasks.push_back(std::move(task)); + } + m_cv.notify_one(); + } + + /// @brief Splits `[0, count)` into chunks and runs @p fn on each chunk, in parallel. + /// + /// The range is cut into `ceil(count / grain)` chunks claimed through an atomic counter. + /// Up to `min(Size(), chunks - 1)` helper tasks are submitted; the calling thread also + /// processes chunks, then waits only for chunks that are still running. Because the caller + /// participates, it is safe to call from inside a pool task (no deadlock from pool exhaustion). + /// A single chunk runs inline on the caller without touching the queue. + /// + /// @tparam F Callable invocable as `fn(usize begin, usize end)`; `end` is exclusive. + /// @param count Size of the index range; 0 returns immediately. + /// @param grain Chunk size (clamped to at least 1). Smaller values balance load better but cost more scheduling. + /// @param fn Per-chunk callback, invoked concurrently from several threads. + /// @pre @p fn is thread-safe and does not throw (an exception on a worker terminates the program). + /// @post Every index in `[0, count)` was processed exactly once when the function returns. + /// @thread_safety Thread-safe; blocks the calling thread until completion. + template + void ParallelFor(usize count, usize grain, F&& fn) { + if (count == 0) + return; + + grain = std::max(1, grain); + const usize chunks = (count + grain - 1) / grain; + + if (chunks == 1) { + fn(usize{0}, count); + return; + } + + struct State { + std::atomic next{0}; + std::atomic done{0}; + }; + // Shared so a helper that starts after we return still touches valid memory. + // Such a late helper finds no chunk left and never dereferences &fn. + auto state = std::make_shared(); + + auto work = [state, chunks, count, grain, &fn] { + for (;;) { + const usize chunk = state->next.fetch_add(1, std::memory_order_relaxed); + if (chunk >= chunks) + return; + + const usize begin = chunk * grain; + fn(begin, std::min(count, begin + grain)); + + if (state->done.fetch_add(1, std::memory_order_acq_rel) + 1 == chunks) + state->done.notify_all(); + } + }; + + const usize helpers = std::min(m_workers.size(), chunks - 1); + for (usize i = 0; i < helpers; ++i) + Submit(work); + + work(); + + for (auto seen = state->done.load(std::memory_order_acquire); seen != chunks; + seen = state->done.load(std::memory_order_acquire)) + state->done.wait(seen); + } + + private: + /// @brief Worker thread body: pops and runs tasks until stop is requested and the queue is empty. + void WorkerLoop() { + for (;;) { + Task task; + { + std::unique_lock lock(m_mutex); + m_cv.wait(lock, [this] { return m_stopping || !m_tasks.empty(); }); + // stopping and queue drained + if (m_tasks.empty()) + return; + task = std::move(m_tasks.front()); + m_tasks.pop_front(); + } + task(); + } + } + + std::mutex m_mutex; + std::condition_variable m_cv; + bool m_stopping = false; + std::deque m_tasks; + // Declared last: destroyed first, so the jthreads are joined before the queue/mutex die. + std::vector m_workers; + }; +} // namespace Nexus::ECS diff --git a/Source/Engine/Core/ECS/Private/World.cpp b/Source/Engine/Core/ECS/Private/World.cpp index fcf9369..a149605 100644 --- a/Source/Engine/Core/ECS/Private/World.cpp +++ b/Source/Engine/Core/ECS/Private/World.cpp @@ -1,5 +1,8 @@ // SPDX-License-Identifier: MIT +/// @file World.cpp +/// @brief Implementation unit of NE.Engine.ECS.World (documented in World.cppm). + module NE.Engine.ECS.World; import NE.Engine.Core.Types; @@ -11,6 +14,7 @@ namespace Nexus::ECS { Entity World::CreateEntity() { uint32 index; + // Recycle the most recently freed slot first; its generation was already bumped on destroy. if (!m_freeIndices.empty()) { index = m_freeIndices.back(); m_freeIndices.pop_back(); @@ -33,6 +37,7 @@ namespace Nexus::ECS { if (!IsAlive(entity)) return; + // Strip every component, then invalidate outstanding handles by bumping the generation. m_registry.RemoveEntity(entity); m_alive[entity.index] = 0; @@ -46,6 +51,18 @@ namespace Nexus::ECS { } void World::Clear() { + // Clear all pools, then rebuild the free list (highest index first so index 1 is reused first). m_registry.Clear(); + + // Invalidates every live handle + m_freeIndices.clear(); + m_freeIndices.reserve(m_nextIndex - 1); + for (uint32 i = m_nextIndex - 1; i >= 1; --i) { + if (m_alive[i]) { + m_alive[i] = 0; + ++m_generations[i]; + } + m_freeIndices.push_back(i); + } } } // namespace Nexus::ECS diff --git a/Source/Engine/Core/ECS/Public/Component.cppm b/Source/Engine/Core/ECS/Public/Component.cppm index ef0c0db..a147f04 100644 --- a/Source/Engine/Core/ECS/Public/Component.cppm +++ b/Source/Engine/Core/ECS/Public/Component.cppm @@ -1,10 +1,21 @@ // SPDX-License-Identifier: MIT +/// @file Component.cppm +/// @brief Module NE.Engine.ECS.Component: the concept constraining ECS component types. + export module NE.Engine.ECS.Component; import std; export namespace Nexus::ECS { + /// @brief Requirements a type must satisfy to be stored as an ECS component. + /// + /// A component must be an object type that is move-constructible, move-assignable and + /// destructible. Copyability and default-construction are NOT required. + /// Move-assignment is needed because SparseSet::Remove() fills the hole with the last + /// element (swap-and-pop). + /// + /// @tparam T Candidate component type. template concept Component = std::is_object_v && std::is_move_constructible_v && std::is_move_assignable_v && std::is_destructible_v; diff --git a/Source/Engine/Core/ECS/Public/ECS.cppm b/Source/Engine/Core/ECS/Public/ECS.cppm index fa8f003..75cc811 100644 --- a/Source/Engine/Core/ECS/Public/ECS.cppm +++ b/Source/Engine/Core/ECS/Public/ECS.cppm @@ -1,7 +1,18 @@ // SPDX-License-Identifier: MIT +/// @file ECS.cppm +/// @brief Umbrella module NE.Engine.Core.ECS: re-exports every ECS sub-module. +/// +/// `import NE.Engine.Core.ECS;` gives access to CommandBuffer, Component, Entity, Registry, +/// Scheduler, ThreadPool and World. (SparseSet and ComponentPool are reachable through +/// Registry's interface but are not re-exported here.) + export module NE.Engine.Core.ECS; +export import NE.Engine.ECS.CommandBuffer; export import NE.Engine.ECS.Component; export import NE.Engine.ECS.Entity; +export import NE.Engine.ECS.Registry; +export import NE.Engine.ECS.Scheduler; +export import NE.Engine.ECS.ThreadPool; export import NE.Engine.ECS.World; diff --git a/Source/Engine/Core/ECS/Public/Entity.cppm b/Source/Engine/Core/ECS/Public/Entity.cppm index 1b6110b..d62a7c4 100644 --- a/Source/Engine/Core/ECS/Public/Entity.cppm +++ b/Source/Engine/Core/ECS/Public/Entity.cppm @@ -1,5 +1,8 @@ // SPDX-License-Identifier: MIT +/// @file Entity.cppm +/// @brief Module NE.Engine.ECS.Entity: the generational handle used to reference entities. + module; #include @@ -9,13 +12,29 @@ export module NE.Engine.ECS.Entity; import NE.Engine.Core.Types; export namespace Nexus::ECS { + /// @brief Generational handle identifying an entity inside a World. + /// + /// An Entity is a small value type (index + generation). The index addresses a slot in the + /// World and in the sparse array of every ComponentPool; the generation is incremented each + /// time a slot is recycled, so handles that outlived their entity are detected by + /// World::IsAlive() instead of silently aliasing a newer entity. + /// + /// @note Index 0 is reserved: World never hands it out (see NullEntity). + /// @thread_safety Plain value type: copying and comparing from any thread is safe. + /// @see World::CreateEntity, World::IsAlive, NullEntity struct NEXUS_API Entity { + /// @brief Slot number inside the World (0 is reserved for NullEntity). uint32 index; + /// @brief Number of times the slot was recycled; must match the World's current generation for the handle to be alive. uint32 generation; bool operator==(const Entity& b) const { return index == b.index && generation == b.generation; } }; + /// @brief The "no entity" handle ({0, 0}). + /// + /// Index 0 is never allocated by World, so World::IsAlive(NullEntity) is always false. + /// Use it as the default value for optional entity references. NEXUS_API constexpr Entity NullEntity{}; } // namespace Nexus::ECS diff --git a/Source/Engine/Core/ECS/Public/Scheduler.cppm b/Source/Engine/Core/ECS/Public/Scheduler.cppm new file mode 100644 index 0000000..543ad03 --- /dev/null +++ b/Source/Engine/Core/ECS/Public/Scheduler.cppm @@ -0,0 +1,417 @@ +// SPDX-License-Identifier: MIT + +/// @file Scheduler.cppm +/// @brief Module NE.Engine.ECS.Scheduler: access declarations, system context and parallel system scheduler. + +module; + +#include + +export module NE.Engine.ECS.Scheduler; + +import NE.Engine.Core.Types; + +import NE.Engine.ECS.CommandBuffer; +import NE.Engine.ECS.Component; +import NE.Engine.ECS.ComponentPool; +import NE.Engine.ECS.Entity; +import NE.Engine.ECS.Registry; +import NE.Engine.ECS.ThreadPool; +import NE.Engine.ECS.World; + +import std; + +export namespace Nexus::ECS { + + /// @brief Declares which component types a system reads and writes. + /// + /// Two systems *conflict* when one writes something the other reads or writes; Write implies + /// Read. The Scheduler uses this to decide which systems may run in parallel. + /// + /// @thread_safety Builder-style; not thread-safe while being configured. Const queries are safe afterwards. + class NEXUS_API Access { + public: + /// @brief Declares read access to the given components. + /// @tparam Ts Component types read by the system. + /// @return *this, for chaining (`Access{}.Read().Write()`). + template + Access& Read() { + (AddRead(), ...); + return *this; + } + + /// @brief Declares write access (which implies read) to the given components. + /// @tparam Ts Component types written by the system. + /// @return *this, for chaining. + template + Access& Write() { + (AddWrite(), ...); + return *this; + } + + /// @brief Tests read permission. + /// @param id Component type id (see ComponentTypeId). + /// @return true if declared as read or write. + bool CanRead(ComponentId id) const { + return std::ranges::contains(m_reads, id) || std::ranges::contains(m_writes, id); + } + + /// @brief Tests write permission. + /// @param id Component type id. + /// @return true if declared as write. + bool CanWrite(ComponentId id) const { + return std::ranges::contains(m_writes, id); + } + + /// @brief Tells whether two systems must not run concurrently. + /// @param other Access of the other system. + /// @return true on write/write, write/read or read/write overlap; read/read never conflicts. + bool ConflictsWith(const Access& other) const { + const auto overlap = [](const auto& a, const auto& b) { + return std::ranges::any_of(a, [&](ComponentId id) { return std::ranges::contains(b, id); }); + }; + return overlap(m_writes, other.m_writes) || overlap(m_writes, other.m_reads) || + overlap(m_reads, other.m_writes); + } + + /// @brief Creates every declared component pool up front. + /// + /// Done single-threaded so that Registry::Pool() never resizes or allocates while systems run. + /// + /// @param registry Registry in which the pools are created. + void EnsurePools(Registry& registry) const { + for (auto ensure : m_ensure) + ensure(registry); + } + + private: + /// @brief Records read access to @p T and a pool-creation callback for EnsurePools(). + template + void AddRead() { + m_reads.push_back(ComponentTypeId()); + m_ensure.push_back([](Registry& registry) { (void)registry.Pool(); }); + } + + /// @brief Records write access to @p T and a pool-creation callback for EnsurePools(). + template + void AddWrite() { + m_writes.push_back(ComponentTypeId()); + m_ensure.push_back([](Registry& registry) { (void)registry.Pool(); }); + } + + std::vector m_reads; + std::vector m_writes; + std::vector m_ensure; + }; + + /// @brief The interface a running system uses to reach the World. + /// + /// Every component access is validated against the system's declared Access; undeclared + /// access throws instead of silently racing with other systems. Contexts are built by the + /// Scheduler, one per system invocation. + /// + /// @thread_safety Used by one system at a time; ParallelForEach fans out to pool threads internally. + class NEXUS_API SystemContext { + public: + /// @brief Builds a context (normally done by the Scheduler, not by user code). + /// @param registry Registry the system accesses. + /// @param world World, used for liveness checks. + /// @param access Declared access of the system (must outlive the context). + /// @param commands The system's own command buffer. + /// @param pool Thread pool used by ParallelForEach. + /// @param deltaTime Frame time in seconds. + SystemContext(Registry& registry, const World& world, const Access& access, CommandBuffer& commands, + ThreadPool& pool, float32 deltaTime) + : m_registry(registry), + m_world(world), + m_access(access), + m_commands(commands), + m_pool(pool), + m_deltaTime(deltaTime) {} + + /// @brief Frame time. @return Seconds passed to Scheduler::Run(). + float32 DeltaTime() const { + return m_deltaTime; + } + + /// @brief Liveness check (World::IsAlive). + /// @param entity Handle to test. + /// @return true if alive. Safe during Run: entities only change in the deferred apply phase. + bool IsAlive(Entity entity) const { + return m_world.IsAlive(entity); + } + + /// @brief The command buffer used to defer structural changes (create/destroy/add/remove). + /// @return Buffer applied after the frame, in registration order. + CommandBuffer& Commands() { + return m_commands; + } + + /// @brief Read-only access to a component pool. + /// @tparam T Component type. + /// @return Const pool of @p T. + /// @throws std::logic_error if @p T was not declared (Access::Read or Write). + template + const ComponentPool& Read() const { + Require(m_access.CanRead(ComponentTypeId()), "reading", typeid(T).name()); + return std::as_const(m_registry).Pool(); + } + + /// @brief Mutable access to a component pool. + /// @tparam T Component type. + /// @return Mutable pool of @p T. + /// @throws std::logic_error if @p T was not declared with Access::Write. + /// @warning Do not add/remove components through the pool during a frame; use Commands(). + template + ComponentPool& Write() { + Require(m_access.CanWrite(ComponentTypeId()), "writing", typeid(T).name()); + return m_registry.Pool(); + } + + /// @brief Sequential multi-component view. + /// @tparam Ts Component types iterated (each must be declared). + /// @return View over entities having all of @p Ts. + /// @throws std::logic_error if any component was not declared. + /// @warning Only *read* permission is checked, yet the view yields mutable references: + /// declare Access::Write for every component you modify through it. + template + Registry::QueryView View() { + (Require(m_access.CanRead(ComponentTypeId()), "viewing", typeid(Ts).name()), ...); + return m_registry.View(); + } + + /// @brief Iterates all entities having every component of @p Ts, in parallel. + /// + /// `fn(Entity, Ts&...)` is called once per matching entity, from several pool threads. The + /// driver range is cut in chunks of @p grain entities; each entity belongs to exactly one + /// chunk, so touching *that entity's* components is race-free. + /// + /// @tparam Ts Component types iterated (each must be declared). + /// @tparam F Callable invocable as `fn(Entity, Ts&...)`. + /// @param fn Per-entity callback. + /// @param grain Entities per chunk (default 2048). + /// @throws std::logic_error if any component was not declared. + /// @pre @p fn must not touch other entities' components (unless read-only), must not mutate + /// shared captured state without synchronisation, and must not throw. + /// @warning Like View(), only read permission is checked: declare Write for components you modify. + /// @thread_safety Blocks the caller until all chunks finish. Record structural changes with Commands() (thread-safe). + template + void ParallelForEach(F&& fn, usize grain = 2048) { + (Require(m_access.CanRead(ComponentTypeId()), "iterating", typeid(Ts).name()), ...); + + auto view = m_registry.View(); + m_pool.ParallelFor(view.Size(), grain, [&](usize begin, usize end) { + for (auto item : view.Slice(begin, end - begin)) + std::apply(fn, item); + }); + } + + private: + /// @brief Throws if an access was not declared. + /// @param allowed Whether the Access permits the operation. + /// @param what Verb used in the message ("reading", "writing", ...). + /// @param type Mangled name of the component type, for diagnostics. + /// @throws std::logic_error when @p allowed is false. + static void Require(bool allowed, std::string_view what, const char* type) { + if (!allowed) + throw std::logic_error(std::format("System is {} component '{}' without declaring it", what, type)); + } + + Registry& m_registry; + const World& m_world; + const Access& m_access; + CommandBuffer& m_commands; + ThreadPool& m_pool; + float32 m_deltaTime; + }; + + /// @brief Runs systems in parallel while respecting their declared data conflicts. + /// + /// Systems keep registration order *semantically*: a later system that conflicts with an + /// earlier one waits for it, while non-conflicting systems run concurrently on the pool. The + /// dependency graph is built lazily on the first Run()/DescribeGraph() after AddSystem(). + /// Each system has its own CommandBuffer, applied in registration order once the frame is done. + /// + /// @thread_safety Not thread-safe: call AddSystem()/Run() from a single thread and never + /// call Run() re-entrantly or modify the World meanwhile. + class NEXUS_API Scheduler { + public: + /// @brief Signature of a system: receives its SystemContext. + using SystemFn = std::function; + + /// @brief Creates a scheduler with its own worker pool. + /// @param world World the systems operate on; must outlive the scheduler. + /// @param threadCount Worker threads (default: hardware concurrency, minimum 1). + explicit Scheduler(World& world, usize threadCount = std::thread::hardware_concurrency()) + : m_world(world), + m_pool(threadCount) {} + + /// @brief Registers a system. + /// + /// @tparam F Callable invocable with `SystemContext&`. + /// @param name Label shown by DescribeGraph(). + /// @param access Components the system reads/writes (drives parallelism and access checks). + /// @param fn The system body. + /// @note Registration order defines the semantic execution order between conflicting systems. + /// @warning Do not call while Run() is executing. Marks the graph for rebuild. + template F> + void AddSystem(std::string name, Access access, F&& fn) { + auto& node = m_nodes.emplace_back(); + node.name = std::move(name); + node.access = std::move(access); + node.fn = std::forward(fn); + m_dirty = true; + } + + /// @brief Executes one frame. + /// + /// Launches every system without dependencies, starts each dependent as soon as all the + /// systems it waits for are done, blocks until all finished, then applies the command buffers + /// in registration order (single-threaded). + /// + /// @param deltaTime Frame time in seconds, exposed as SystemContext::DeltaTime(). + /// @throws Rethrows the first exception thrown by a system, *after* the command buffers were + /// applied. A throwing system does not cancel its dependents. + /// @note No-op when no system is registered. If applying a command buffer itself throws, + /// that exception propagates instead. + /// @thread_safety Call from one thread only; the calling thread blocks and does not run systems. + void Run(float32 deltaTime) { + if (m_dirty) + Build(); + if (m_nodes.empty()) + return; + + RunState state(m_nodes.size(), deltaTime); + for (usize i = 0; i < m_nodes.size(); ++i) + state.remaining[i].store(m_nodes[i].dependencyCount, std::memory_order_relaxed); + for (usize i = 0; i < m_nodes.size(); ++i) + if (m_nodes[i].dependencyCount == 0) + Launch(i, state); + + { + std::unique_lock lock(state.mutex); + state.done.wait(lock, [&] { return state.finished == m_nodes.size(); }); + } + + for (auto& node : m_nodes) + node.commands.Apply(m_world); + + if (state.error) + std::rethrow_exception(state.error); + } + + /// @brief Human-readable dependency graph for reports and debugging. + /// @return One line per system: `[index] name -> blocks: `. + /// @note Builds the graph first if systems were added since the last build. + /// Report / debugging: which system waits for which. + std::string DescribeGraph() { + if (m_dirty) + Build(); + + std::string out; + for (usize i = 0; i < m_nodes.size(); ++i) { + out += std::format("[{}] {}", i, m_nodes[i].name); + if (m_nodes[i].dependents.empty()) { + out += '\n'; + continue; + } + out += " -> blocks:"; + for (const auto d : m_nodes[i].dependents) + out += std::format(" {}", m_nodes[d].name); + out += '\n'; + } + return out; + } + + /// @brief Number of worker threads. @return Pool size. + [[nodiscard]] usize ThreadCount() const { + return m_pool.Size(); + } + + private: + /// @brief Registered system with its access, buffer and dependency edges. + struct Node { + std::string name; + Access access; + SystemFn fn; + CommandBuffer commands; + std::vector dependents; + usize dependencyCount = 0; + }; + + /// @brief Per-frame synchronisation state (pending-dependency counters, completion count, first error). + struct RunState { + RunState(usize count, float32 dt) + : remaining(std::make_unique[]>(count)), + deltaTime(dt) {} + + std::unique_ptr[]> remaining; + float32 deltaTime; + std::mutex mutex; // guards finished + error + std::condition_variable done; + usize finished = 0; + std::exception_ptr error; + }; + + /// @brief (Re)computes the dependency graph. + /// + /// Creates the declared pools, then adds an edge i -> j (i < j) for every pair whose accesses + /// conflict, so j waits for i. Cost is O(n^2) conflict checks in the number of systems. + void Build() { + Registry& registry = m_world.GetRegistry(); + + for (auto& node : m_nodes) { + node.dependents.clear(); + node.dependencyCount = 0; + node.access.EnsurePools(registry); + } + + for (usize j = 0; j < m_nodes.size(); ++j) { + for (usize i = 0; i < j; ++i) { + if (m_nodes[i].access.ConflictsWith(m_nodes[j].access)) { + m_nodes[i].dependents.push_back(j); + ++m_nodes[j].dependencyCount; + } + } + } + m_dirty = false; + } + + /// @brief Submits one system to the pool. + /// + /// The task runs the system (catching any exception into @c state.error), releases its + /// dependents (launching those whose counter reaches 0), then signals completion under the lock. + /// + /// @param index System index in the node list. + /// @param state State of the running frame. + void Launch(usize index, RunState& state) { + m_pool.Submit([this, index, &state] { + Node& node = m_nodes[index]; + std::exception_ptr error; + + try { + SystemContext context(m_world.GetRegistry(), m_world, node.access, node.commands, m_pool, + state.deltaTime); + node.fn(context); + } catch (...) { + error = std::current_exception(); + } + + for (const auto dependent : node.dependents) + if (state.remaining[dependent].fetch_sub(1, std::memory_order_acq_rel) == 1) + Launch(dependent, state); + + std::scoped_lock lock(state.mutex); + if (error && !state.error) + state.error = error; + ++state.finished; + state.done.notify_one(); // under the lock: Run() cannot destroy state before we unlock + }); + } + + World& m_world; + ThreadPool m_pool; + std::deque m_nodes; // deque: Node holds a mutex (non-movable) and must never relocate + bool m_dirty = true; + }; +} // namespace Nexus::ECS diff --git a/Source/Engine/Core/ECS/Public/World.cppm b/Source/Engine/Core/ECS/Public/World.cppm index 135a894..935b035 100644 --- a/Source/Engine/Core/ECS/Public/World.cppm +++ b/Source/Engine/Core/ECS/Public/World.cppm @@ -1,5 +1,8 @@ // SPDX-License-Identifier: MIT +/// @file World.cppm +/// @brief Module NE.Engine.ECS.World: entity lifetime management and component access facade. + module; #include @@ -14,73 +17,180 @@ import NE.Engine.ECS.Registry; import std; export namespace Nexus::ECS { + /// @brief Owns entities and their components. + /// + /// World allocates generational Entity handles (recycling freed indices) and forwards + /// component operations to its Registry. Most operations are *structural* (they can + /// allocate or move storage) and must not run while systems execute in parallel: use + /// CommandBuffer from systems. + /// + /// @thread_safety Not thread-safe. Read-only calls (IsAlive, Has, Get const, TryGet const) + /// may run concurrently with each other as long as nobody mutates the World. + /// @see Registry, CommandBuffer, Scheduler class NEXUS_API World { public: + /// @brief Creates a new entity. + /// + /// Reuses the most recently freed index if there is one (LIFO), otherwise takes the next + /// unused index; the slot arrays grow geometrically (at least 1024 slots). + /// + /// @return Handle of the new, alive entity (index >= 1). + /// @complexity Amortised O(1). Entity CreateEntity(); + /// @brief Destroys an entity and all of its components. + /// + /// Removes the entity from every pool, marks the slot dead, bumps its generation (so every + /// existing copy of the handle becomes stale) and recycles the index. + /// + /// @param entity Entity to destroy. No-op if it is not alive. + /// @complexity O(number of component pools). void DestroyEntity(Entity entity); + /// @brief Tests whether a handle refers to a live entity. + /// @param entity Handle to test. + /// @return false for NullEntity, out-of-range indices, stale generations and destroyed entities. + /// @complexity O(1). bool IsAlive(Entity entity) const; + /// @brief Destroys every entity and every component. + /// @post All previously issued handles are invalid; all indices are available again and the + /// lowest index is reused first. Pools stay allocated (empty). + /// @warning Invalidates references/spans into component storage. void Clear(); + /// @brief Pre-allocates component storage. + /// + /// Creates the pool of each listed component if it does not exist yet and reserves room in it. + /// + /// @tparam Components Component types to reserve for. + /// @param capacity Number of components per pool. + /// @note Does not reserve entity slots. template void Reserve(usize capacity) { (m_registry.Pool().Reserve(capacity), ...); } + /// @brief Attaches a component to an entity (constructed in place). + /// + /// The pool of @p T is created on first use. If the entity already has a T, that component + /// is returned untouched and @p args are ignored. + /// + /// @tparam T Component type. + /// @tparam Args Constructor argument types. + /// @param entity Target entity. + /// @param args Arguments forwarded to T's constructor. + /// @return Reference to the component. + /// @throws std::invalid_argument if @p entity is not alive. + /// @warning Structural: not allowed while systems run, record it through CommandBuffer::Add. template T& Add(Entity entity, Args&&... args) { + if (!IsAlive(entity)) [[unlikely]] + throw std::invalid_argument("World::Add: entity is not alive"); + return m_registry.Pool().Emplace(entity, std::forward(args)...); } + /// @brief Detaches the component T from an entity. + /// @tparam T Component type. + /// @param entity Target entity. No-op if it has no T. + /// @note Creates the (empty) pool of T if it did not exist. + /// @warning Structural: use CommandBuffer::Remove from systems. template void Remove(Entity entity) { m_registry.Pool().Remove(entity); } + /// @brief Tests whether an entity has a component T. + /// @tparam T Component type. + /// @param entity Entity to test. + /// @return true if present; false if absent or if no pool for T exists. template bool Has(Entity entity) const { const auto* pool = m_registry.TryPool(); return pool && pool->Contains(entity); } + /// @brief Checked access to a component. + /// @tparam T Component type. + /// @param entity Owner. + /// @return Mutable reference to the component. + /// @throws std::out_of_range if @p entity has no T. + /// @note Creates the (empty) pool of T if it did not exist. + /// @see TryGet template T& Get(Entity entity) { return m_registry.Pool().Get(entity); } + /// @brief Checked read-only access to a component. + /// @tparam T Component type. + /// @param entity Owner. + /// @return Const reference to the component. + /// @throws std::out_of_range if @p entity has no T, or if T's id lies outside the pool table. + /// @warning If the pool table already covers T's id but T's pool was never created, this + /// overload dereferences an empty pointer (undefined behaviour). Use TryGet() or + /// Has() when the component may never have been added. template const T& Get(Entity entity) const { return m_registry.Pool().Get(entity); } + /// @brief Non-throwing component lookup. + /// @tparam T Component type. + /// @param entity Owner. + /// @return Pointer to the component, or nullptr if absent / no pool. template T* TryGet(Entity entity) { auto* pool = m_registry.TryPool(); return pool ? pool->TryGet(entity) : nullptr; } + /// @brief Non-throwing read-only component lookup. + /// @tparam T Component type. + /// @param entity Owner. + /// @return Const pointer to the component, or nullptr if absent / no pool. template const T* TryGet(Entity entity) const { const auto* pool = m_registry.TryPool(); return pool ? pool->TryGet(entity) : nullptr; } + /// @brief Collects the entities that have *all* the listed components. + /// + /// @tparam Components Required component types (distinct). + /// @return Snapshot vector of matching entities; empty when the pack is empty or any pool is missing. + /// @complexity O(n_min * k): iterates the smallest pool and probes the others. + /// @see View for allocation-free iteration with component references. template std::vector Query() { return m_registry.Query(); } + /// @brief Collects the entities that have *at least one* of the listed components. + /// + /// @tparam Components Component types (any of them qualifies). + /// @return Snapshot vector without duplicates, ordered by pool then dense order; missing pools are skipped. template std::vector QueryAny() { return m_registry.QueryAny(); } + /// @brief Returns a lightweight, non-owning view over entities having all listed components. + /// @tparam Components Required component types (distinct, at least one). + /// @return View yielding `std::tuple`; empty if any pool is missing. + /// @warning The view is invalidated by structural changes to any involved pool. + /// @see Registry::QueryView template Registry::QueryView View() { return m_registry.View(); } + /// @brief Access to the underlying component registry. + /// @return Mutable reference to the Registry (used by the Scheduler). + Registry& GetRegistry() { + return m_registry; + } + private: uint32 m_nextIndex = 1; std::vector m_freeIndices; diff --git a/Tests/Engine/Core/ECS/ECS.cpp b/Tests/Engine/Core/ECS/ECS.cpp index 1f46e4f..31fd88c 100644 --- a/Tests/Engine/Core/ECS/ECS.cpp +++ b/Tests/Engine/Core/ECS/ECS.cpp @@ -29,13 +29,13 @@ namespace { }; struct Position { - float x = 0.0f; - float y = 0.0f; + float32 x = 0.0f; + float32 y = 0.0f; }; struct Velocity { - float dx = 0.0f; - float dy = 0.0f; + float32 dx = 0.0f; + float32 dy = 0.0f; }; struct Health { @@ -46,6 +46,49 @@ namespace { }; struct Tag {}; + + // Heap-owning component: exercises the move paths of the sparse set (swap-and-pop). + struct Name { + std::string value; + + Name() = default; + explicit Name(std::string v) : value(std::move(v)) {} + }; + + // Move-only component. + struct Owned { + std::unique_ptr ptr; + + explicit Owned(int32 v) : ptr(std::make_unique(v)) {} + }; + + // Counts live instances to prove every constructed component is destroyed exactly once. + struct Tracked { + static inline int32 live = 0; + int32 id; + + explicit Tracked(int32 i) : id(i) { + ++live; + } + Tracked(Tracked&& other) noexcept : id(other.id) { + ++live; + } + Tracked& operator=(Tracked&& other) noexcept { + id = other.id; + return *this; + } + ~Tracked() { + --live; + } + }; + + // Only used by the DISABLED_ const-Get test (needs two component types with ordered ids). + struct NullSlotLow { + int32 value = 0; + }; + struct NullSlotHigh { + int32 value = 0; + }; } // namespace // --------------------------------------------------------------------- @@ -437,3 +480,646 @@ TEST_F(ECSTest, ViewOverEmptyPoolYieldsNoIterations) { EXPECT_EQ(count, 0u); } + +// --------------------------------------------------------------------- +// Entity lifecycle: edge cases +// --------------------------------------------------------------------- + +TEST_F(ECSTest, CreateEntityNeverReturnsIndexZero) { + for (usize i = 0; i < 3000; ++i) + ASSERT_NE(m_World.CreateEntity().index, 0u); +} + +TEST_F(ECSTest, DestroyingNullEntityIsANoOp) { + Entity a = m_World.CreateEntity(); + + m_World.DestroyEntity(NullEntity); + + EXPECT_TRUE(m_World.IsAlive(a)); +} + +TEST_F(ECSTest, DestroyingSameEntityTwiceDoesNotCorruptTheFreeList) { + Entity a = m_World.CreateEntity(); + Entity b = m_World.CreateEntity(); + + m_World.DestroyEntity(a); + m_World.DestroyEntity(a); + + // If the index had been pushed twice, these two would share an index. + Entity c = m_World.CreateEntity(); + Entity d = m_World.CreateEntity(); + + EXPECT_NE(c.index, d.index); + EXPECT_TRUE(m_World.IsAlive(b)); + EXPECT_TRUE(m_World.IsAlive(c)); + EXPECT_TRUE(m_World.IsAlive(d)); +} + +TEST_F(ECSTest, DestroyingStaleHandleDoesNotKillTheRecycledEntity) { + Entity a = m_World.CreateEntity(); + m_World.DestroyEntity(a); + Entity b = m_World.CreateEntity(); + + m_World.DestroyEntity(a); // stale handle + + EXPECT_TRUE(m_World.IsAlive(b)); +} + +TEST_F(ECSTest, GenerationIncrementsOnEveryRecycle) { + Entity e = m_World.CreateEntity(); + const uint32 index = e.index; + + for (int i = 0; i < 10; ++i) { + m_World.DestroyEntity(e); + Entity next = m_World.CreateEntity(); + + ASSERT_EQ(next.index, index); // only one free slot, so it must be reused + EXPECT_EQ(next.generation, e.generation + 1); + EXPECT_FALSE(m_World.IsAlive(e)); + e = next; + } + EXPECT_TRUE(m_World.IsAlive(e)); +} + +TEST_F(ECSTest, FreedIndicesAreReusedInsteadOfGrowing) { + std::vector first; + uint32 maxIndex = 0; + for (int i = 0; i < 100; ++i) { + first.push_back(m_World.CreateEntity()); + maxIndex = std::max(maxIndex, first.back().index); + } + + for (Entity e : first) + m_World.DestroyEntity(e); + + std::set indices; + for (int i = 0; i < 100; ++i) { + Entity e = m_World.CreateEntity(); + EXPECT_LE(e.index, maxIndex); + EXPECT_TRUE(m_World.IsAlive(e)); + indices.insert(e.index); + } + + EXPECT_EQ(indices.size(), 100u); + for (Entity e : first) + EXPECT_FALSE(m_World.IsAlive(e)); +} + +TEST_F(ECSTest, ManyEntitiesCrossingInternalCapacityGrowth) { + constexpr usize count = 5000; // grows past the 1024 and 2048 steps + std::vector ids; + ids.reserve(count); + + for (usize i = 0; i < count; ++i) { + Entity e = m_World.CreateEntity(); + m_World.Add(e, static_cast(i)); + ids.push_back(e); + } + + std::set indices; + for (usize i = 0; i < count; ++i) { + ASSERT_TRUE(m_World.IsAlive(ids[i])); + ASSERT_EQ(m_World.Get(ids[i]).value, static_cast(i)); + indices.insert(ids[i].index); + } + EXPECT_EQ(indices.size(), count); +} + +TEST_F(ECSTest, ForgedHandlesAreHarmless) { + Entity real = m_World.CreateEntity(); + m_World.Add(real, 1.0f, 1.0f); + + const Entity outOfRange{999'999u, 0u}; + const Entity wrongGeneration{real.index, real.generation + 7}; + + EXPECT_FALSE(m_World.IsAlive(outOfRange)); + EXPECT_FALSE(m_World.IsAlive(wrongGeneration)); + EXPECT_FALSE(m_World.Has(outOfRange)); + EXPECT_FALSE(m_World.Has(wrongGeneration)); + EXPECT_EQ(m_World.TryGet(outOfRange), nullptr); + EXPECT_EQ(m_World.TryGet(wrongGeneration), nullptr); + + m_World.DestroyEntity(outOfRange); + m_World.DestroyEntity(wrongGeneration); + m_World.Remove(outOfRange); + m_World.Remove(wrongGeneration); + + EXPECT_TRUE(m_World.IsAlive(real)); + EXPECT_TRUE(m_World.Has(real)); +} + +TEST_F(ECSTest, RecycledEntityStartsWithoutComponents) { + Entity a = m_World.CreateEntity(); + m_World.Add(a, 1.0f, 2.0f); + m_World.Add(a, 5); + m_World.DestroyEntity(a); + + Entity b = m_World.CreateEntity(); + + EXPECT_FALSE(m_World.Has(b)); + EXPECT_FALSE(m_World.Has(b)); + EXPECT_FALSE(m_World.Has(a)); + EXPECT_EQ(m_World.TryGet(a), nullptr); +} + +TEST_F(ECSTest, DestroyRemovesComponentsFromEveryPool) { + Entity a = m_World.CreateEntity(); + Entity b = m_World.CreateEntity(); + m_World.Add(a, 0.0f, 0.0f); + m_World.Add(a, 0.0f, 0.0f); + m_World.Add(a, 1); + m_World.Add(b, 0.0f, 0.0f); + + m_World.DestroyEntity(a); + + std::vector positions = m_World.Query(); + EXPECT_EQ(positions.size(), 1u); + EXPECT_TRUE(m_World.Query().empty()); + EXPECT_TRUE(m_World.Query().empty()); + EXPECT_TRUE(m_World.Has(b)); +} + +// --------------------------------------------------------------------- +// Component edge cases +// --------------------------------------------------------------------- + +TEST_F(ECSTest, AddingSameComponentTwiceKeepsExistingValueAndDoesNotDuplicate) { + // Documents current behaviour: Add is a no-op returning the existing component. + Entity e = m_World.CreateEntity(); + m_World.Add(e, 10); + + Health& again = m_World.Add(e, 99); + + EXPECT_EQ(again.value, 10); + EXPECT_EQ(m_World.Get(e).value, 10); + EXPECT_EQ(m_World.Query().size(), 1u); +} + +TEST_F(ECSTest, RemoveThenReAddStoresFreshValue) { + Entity e = m_World.CreateEntity(); + m_World.Add(e, 10); + m_World.Remove(e); + m_World.Add(e, 20); + + EXPECT_EQ(m_World.Get(e).value, 20); + EXPECT_EQ(m_World.Query().size(), 1u); +} + +TEST_F(ECSTest, RemovingMissingComponentIsANoOp) { + Entity e = m_World.CreateEntity(); + + EXPECT_NO_THROW(m_World.Remove(e)); // pool never created + m_World.Add(e, 1.0f, 1.0f); + m_World.Remove(e); + EXPECT_NO_THROW(m_World.Remove(e)); // already removed + EXPECT_TRUE(m_World.IsAlive(e)); +} + +TEST_F(ECSTest, RemoveOnDeadOrNullEntityIsANoOp) { + Entity a = m_World.CreateEntity(); + m_World.Add(a, 1.0f, 1.0f); + m_World.DestroyEntity(a); + + EXPECT_NO_THROW(m_World.Remove(a)); + EXPECT_NO_THROW(m_World.Remove(NullEntity)); +} + +TEST_F(ECSTest, AddToDeadEntityThrows) { + Entity e = m_World.CreateEntity(); + m_World.DestroyEntity(e); + + EXPECT_THROW(m_World.Add(e, 1.0f, 1.0f), std::invalid_argument); + EXPECT_FALSE(m_World.Has(e)); +} + +TEST_F(ECSTest, AddToNullEntityThrows) { + EXPECT_THROW(m_World.Add(NullEntity, 1.0f, 1.0f), std::invalid_argument); +} + +TEST_F(ECSTest, AddToStaleHandleThrowsAndDoesNotTouchTheRecycledEntity) { + Entity a = m_World.CreateEntity(); + m_World.DestroyEntity(a); + Entity b = m_World.CreateEntity(); + + EXPECT_THROW(m_World.Add(a, 1.0f, 1.0f), std::invalid_argument); + EXPECT_FALSE(m_World.Has(b)); +} + +TEST_F(ECSTest, GetMissingComponentThrowsOutOfRange) { + Entity a = m_World.CreateEntity(); + Entity b = m_World.CreateEntity(); + m_World.Add(a, 1.0f, 1.0f); + + EXPECT_THROW(m_World.Get(b), std::out_of_range); // pool exists, entity missing + EXPECT_THROW(m_World.Get(a), std::out_of_range); // pool never existed +} + +TEST_F(ECSTest, GetOnDestroyedEntityThrowsOutOfRange) { + Entity e = m_World.CreateEntity(); + m_World.Add(e, 1.0f, 1.0f); + m_World.DestroyEntity(e); + + EXPECT_THROW(m_World.Get(e), std::out_of_range); +} + +TEST_F(ECSTest, ConstGetMissingComponentInExistingPoolThrows) { + Entity a = m_World.CreateEntity(); + Entity b = m_World.CreateEntity(); + m_World.Add(a, 1.0f, 1.0f); + + const World& constWorld = m_World; + EXPECT_THROW(constWorld.Get(b), std::out_of_range); +} + +TEST_F(ECSTest, HasAndTryGetAreSafeOnNullAndDeadEntities) { + Entity e = m_World.CreateEntity(); + m_World.Add(e, 1.0f, 1.0f); + m_World.DestroyEntity(e); + + EXPECT_FALSE(m_World.Has(NullEntity)); + EXPECT_FALSE(m_World.Has(e)); + EXPECT_EQ(m_World.TryGet(NullEntity), nullptr); + EXPECT_EQ(m_World.TryGet(e), nullptr); +} + +TEST_F(ECSTest, ReserveZeroIsHarmless) { + m_World.Reserve(0); + + Entity e = m_World.CreateEntity(); + m_World.Add(e, 1.0f, 2.0f); + + EXPECT_TRUE(m_World.Has(e)); +} + +// --------------------------------------------------------------------- +// Swap-and-pop integrity and non-trivial component types +// --------------------------------------------------------------------- + +TEST_F(ECSTest, RemovingFromTheMiddleKeepsOtherComponentsIntact) { + std::array es; + for (usize i = 0; i < es.size(); ++i) { + es[i] = m_World.CreateEntity(); + m_World.Add(es[i], static_cast(i * 10)); + } + + m_World.Remove(es[2]); + + EXPECT_FALSE(m_World.Has(es[2])); + EXPECT_EQ(m_World.Get(es[0]).value, 0); + EXPECT_EQ(m_World.Get(es[1]).value, 10); + EXPECT_EQ(m_World.Get(es[3]).value, 30); + EXPECT_EQ(m_World.Get(es[4]).value, 40); + + m_World.Remove(es[0]); // first + m_World.Remove(es[4]); // last + EXPECT_EQ(m_World.Get(es[1]).value, 10); + EXPECT_EQ(m_World.Get(es[3]).value, 30); + + m_World.Add(es[2], 99); + EXPECT_EQ(m_World.Get(es[2]).value, 99); + EXPECT_EQ(m_World.Query().size(), 3u); +} + +TEST_F(ECSTest, PoolCanBeEmptiedAndRefilled) { + std::vector ids; + for (int i = 0; i < 50; ++i) { + ids.push_back(m_World.CreateEntity()); + m_World.Add(ids.back(), i); + } + + for (Entity e : ids) + m_World.Remove(e); + EXPECT_TRUE(m_World.Query().empty()); + + for (usize i = 0; i < ids.size(); ++i) + m_World.Add(ids[i], static_cast(i) + 1000); + + for (usize i = 0; i < ids.size(); ++i) + EXPECT_EQ(m_World.Get(ids[i]).value, static_cast(i) + 1000); +} + +TEST_F(ECSTest, HeapOwningComponentsSurviveSwapRemove) { + const std::string longText(200, 'x'); // beyond small-string optimisation + + Entity a = m_World.CreateEntity(); + Entity b = m_World.CreateEntity(); + Entity c = m_World.CreateEntity(); + m_World.Add(a, "alpha"); + m_World.Add(b, longText + "beta"); + m_World.Add(c, longText + "gamma"); + + m_World.Remove(a); + + EXPECT_EQ(m_World.Get(b).value, longText + "beta"); + EXPECT_EQ(m_World.Get(c).value, longText + "gamma"); +} + +TEST_F(ECSTest, MoveOnlyComponentsAreSupported) { + Entity a = m_World.CreateEntity(); + Entity b = m_World.CreateEntity(); + Entity c = m_World.CreateEntity(); + m_World.Add(a, 1); + m_World.Add(b, 2); + m_World.Add(c, 3); + + m_World.Remove(b); + + ASSERT_NE(m_World.Get(a).ptr, nullptr); + ASSERT_NE(m_World.Get(c).ptr, nullptr); + EXPECT_EQ(*m_World.Get(a).ptr, 1); + EXPECT_EQ(*m_World.Get(c).ptr, 3); +} + +TEST_F(ECSTest, ComponentDestructorsRunExactlyOnce) { + const int32 baseline = Tracked::live; + + Entity a = m_World.CreateEntity(); + Entity b = m_World.CreateEntity(); + Entity c = m_World.CreateEntity(); + m_World.Add(a, 1); + m_World.Add(b, 2); + m_World.Add(c, 3); + EXPECT_EQ(Tracked::live, baseline + 3); + + m_World.Remove(a); + EXPECT_EQ(Tracked::live, baseline + 2); + + m_World.DestroyEntity(b); + EXPECT_EQ(Tracked::live, baseline + 1); + + m_World.Clear(); + EXPECT_EQ(Tracked::live, baseline); +} + +TEST_F(ECSTest, ComponentsAreDestroyedWhenTheWorldIsDestroyed) { + const int32 baseline = Tracked::live; + { + World local; + for (int32 i = 0; i < 100; ++i) { + Entity e = local.CreateEntity(); + local.Add(e, i); + } + EXPECT_EQ(Tracked::live, baseline + 100); + } + EXPECT_EQ(Tracked::live, baseline); +} + +// --------------------------------------------------------------------- +// Clear +// --------------------------------------------------------------------- + +TEST_F(ECSTest, ClearInvalidatesAllHandlesAndRemovesAllComponents) { + Entity a = m_World.CreateEntity(); + Entity b = m_World.CreateEntity(); + m_World.Add(a, 1.0f, 1.0f); + m_World.Add(b, 5); + + m_World.Clear(); + + EXPECT_FALSE(m_World.IsAlive(a)); + EXPECT_FALSE(m_World.IsAlive(b)); + EXPECT_FALSE(m_World.Has(a)); + EXPECT_TRUE(m_World.Query().empty()); + EXPECT_TRUE(m_World.Query().empty()); +} + +TEST_F(ECSTest, WorldIsUsableAfterClear) { + Entity a = m_World.CreateEntity(); + m_World.Clear(); + + Entity b = m_World.CreateEntity(); + m_World.Add(b, 2.0f, 3.0f); + + EXPECT_FALSE(m_World.IsAlive(a)); + EXPECT_TRUE(m_World.IsAlive(b)); + EXPECT_FLOAT_EQ(m_World.Get(b).x, 2.0f); + if (a.index == b.index) + EXPECT_NE(a.generation, b.generation); +} + +TEST_F(ECSTest, ClearOnEmptyWorldAndRepeatedClearAreSafe) { + EXPECT_NO_THROW(m_World.Clear()); + EXPECT_NO_THROW(m_World.Clear()); + + m_World.CreateEntity(); + EXPECT_NO_THROW(m_World.Clear()); + EXPECT_NO_THROW(m_World.Clear()); +} + +TEST_F(ECSTest, ClearAfterDestroysDoesNotProduceDuplicateIndices) { + std::vector ids; + for (int i = 0; i < 10; ++i) + ids.push_back(m_World.CreateEntity()); + for (int i = 0; i < 5; ++i) + m_World.DestroyEntity(ids[static_cast(i)]); + + m_World.Clear(); + + std::set indices; + for (int i = 0; i < 20; ++i) { + Entity e = m_World.CreateEntity(); + EXPECT_TRUE(m_World.IsAlive(e)); + indices.insert(e.index); + } + EXPECT_EQ(indices.size(), 20u); +} + +TEST_F(ECSTest, HandlesFromBeforeClearNeverComeBackToLife) { + std::vector old; + for (int i = 0; i < 50; ++i) + old.push_back(m_World.CreateEntity()); + + m_World.Clear(); + + for (int i = 0; i < 50; ++i) + m_World.CreateEntity(); // reuses the same indices + + for (Entity e : old) + EXPECT_FALSE(m_World.IsAlive(e)); +} + +// --------------------------------------------------------------------- +// Query / View: edge cases +// --------------------------------------------------------------------- + +TEST_F(ECSTest, QueryWithAMissingPoolReturnsEmpty) { + Entity e = m_World.CreateEntity(); + m_World.Add(e, 0.0f, 0.0f); + + std::vector results = m_World.Query(); // no Health pool + EXPECT_TRUE(results.empty()); +} + +TEST_F(ECSTest, QueryWithThreeComponents) { + Entity a = m_World.CreateEntity(); + Entity b = m_World.CreateEntity(); + m_World.Add(a, 0.0f, 0.0f); + m_World.Add(a, 0.0f, 0.0f); + m_World.Add(a, 1); + m_World.Add(b, 0.0f, 0.0f); + m_World.Add(b, 0.0f, 0.0f); + + std::vector results = m_World.Query(); + + ASSERT_EQ(results.size(), 1u); + EXPECT_TRUE(results.front() == a); +} + +TEST_F(ECSTest, QueryNoLongerMatchesAfterAComponentIsRemoved) { + Entity e = m_World.CreateEntity(); + m_World.Add(e, 0.0f, 0.0f); + m_World.Add(e, 0.0f, 0.0f); + + m_World.Remove(e); + + std::vector both = m_World.Query(); + std::vector onlyPosition = m_World.Query(); + EXPECT_TRUE(both.empty()); + EXPECT_EQ(onlyPosition.size(), 1u); +} + +TEST_F(ECSTest, QueryResultDoesNotDependOnComponentOrder) { + for (int i = 0; i < 50; ++i) { + Entity e = m_World.CreateEntity(); + if (i % 2 == 0) + m_World.Add(e, 0.0f, 0.0f); + if (i % 3 == 0) + m_World.Add(e, 0.0f, 0.0f); + } + + std::vector ab = m_World.Query(); + std::vector ba = m_World.Query(); + const auto byIndex = [](Entity l, Entity r) { return l.index < r.index; }; + std::ranges::sort(ab, byIndex); + std::ranges::sort(ba, byIndex); + + EXPECT_EQ(ab.size(), 9u); // multiples of 6 below 50 + EXPECT_TRUE(std::ranges::equal(ab, ba)); +} + +TEST_F(ECSTest, QueryAnyExcludesDestroyedEntitiesAndHandlesMissingPools) { + Entity a = m_World.CreateEntity(); + Entity b = m_World.CreateEntity(); + m_World.Add(a, 0.0f, 0.0f); + m_World.Add(b, 0.0f, 0.0f); + m_World.DestroyEntity(a); + + std::vector results = m_World.QueryAny(); // Health pool missing + + ASSERT_EQ(results.size(), 1u); + EXPECT_TRUE(results.front() == b); +} + +TEST_F(ECSTest, TagComponentsParticipateInQueries) { + Entity a = m_World.CreateEntity(); + Entity b = m_World.CreateEntity(); + m_World.Add(a); + m_World.Add(a, 0.0f, 0.0f); + m_World.Add(b, 0.0f, 0.0f); + + std::vector results = m_World.Query(); + + ASSERT_EQ(results.size(), 1u); + EXPECT_TRUE(results.front() == a); +} + +TEST_F(ECSTest, ViewAllowsMutatingComponents) { + Entity a = m_World.CreateEntity(); + Entity b = m_World.CreateEntity(); + m_World.Add(a, 0.0f, 0.0f); + m_World.Add(b, 1.0f, 1.0f); + + for ([[maybe_unused]] auto [e, pos] : m_World.View()) + pos.x += 10.0f; + + EXPECT_FLOAT_EQ(m_World.Get(a).x, 10.0f); + EXPECT_FLOAT_EQ(m_World.Get(b).x, 11.0f); +} + +TEST_F(ECSTest, ViewDrivenBySmallestPoolStillFiltersCorrectly) { + std::set expected; + for (int i = 0; i < 100; ++i) { + Entity e = m_World.CreateEntity(); + m_World.Add(e, 0.0f, 0.0f); + if (i % 30 == 0) { + m_World.Add(e, 0.0f, 0.0f); + expected.insert(e.index); + } + } + + std::set seen; + for ([[maybe_unused]] auto [e, pos, vel] : m_World.View()) + seen.insert(e.index); + + EXPECT_EQ(seen.size(), 4u); // i = 0, 30, 60, 90 + EXPECT_EQ(seen, expected); +} + +TEST_F(ECSTest, ViewWithAMissingPoolYieldsNothing) { + Entity e = m_World.CreateEntity(); + m_World.Add(e, 0.0f, 0.0f); + + usize count = 0; + for ([[maybe_unused]] auto [en, pos, health] : m_World.View()) + ++count; + + EXPECT_EQ(count, 0u); +} + +TEST_F(ECSTest, ViewSkipsDestroyedEntitiesAndRemovedComponents) { + Entity a = m_World.CreateEntity(); + Entity b = m_World.CreateEntity(); + Entity c = m_World.CreateEntity(); + for (Entity e : {a, b, c}) { + m_World.Add(e, 0.0f, 0.0f); + m_World.Add(e, 0.0f, 0.0f); + } + + m_World.DestroyEntity(a); + m_World.Remove(b); + + std::vector seen; + for ([[maybe_unused]] auto [e, pos, vel] : m_World.View()) + seen.push_back(e); + + ASSERT_EQ(seen.size(), 1u); + EXPECT_TRUE(seen.front() == c); +} + +TEST_F(ECSTest, ViewIsEmptyAfterClear) { + Entity e = m_World.CreateEntity(); + m_World.Add(e, 0.0f, 0.0f); + m_World.Clear(); + + usize count = 0; + for ([[maybe_unused]] auto [en, pos] : m_World.View()) + ++count; + + EXPECT_EQ(count, 0u); +} + +TEST_F(ECSTest, ViewAndQueryAgreeOnTheMatchingSet) { + for (int i = 0; i < 200; ++i) { + Entity e = m_World.CreateEntity(); + if (i % 2 == 0) + m_World.Add(e, 0.0f, 0.0f); + if (i % 3 == 0) + m_World.Add(e, 0.0f, 0.0f); + if (i % 5 == 0) + m_World.Add(e, i); + if (i % 7 == 0) + m_World.DestroyEntity(e); + } + + std::vector viaQuery = m_World.Query(); + std::vector viaView; + for ([[maybe_unused]] auto [e, p, v, h] : m_World.View()) + viaView.push_back(e); + + const auto byIndex = [](Entity l, Entity r) { return l.index < r.index; }; + std::ranges::sort(viaQuery, byIndex); + std::ranges::sort(viaView, byIndex); + + EXPECT_FALSE(viaQuery.empty()); + EXPECT_TRUE(std::ranges::equal(viaQuery, viaView)); +} diff --git a/Tests/Engine/Core/ECS/ECSScheduler.cpp b/Tests/Engine/Core/ECS/ECSScheduler.cpp new file mode 100644 index 0000000..bfb2eaf --- /dev/null +++ b/Tests/Engine/Core/ECS/ECSScheduler.cpp @@ -0,0 +1,1338 @@ +// SPDX-License-Identifier: MIT + +// Multithreading tests: ThreadPool, CommandBuffer, Access, Scheduler and concurrent World reads. + +#include + +import NE.Engine.Core.ECS; +import NE.Engine.Core.Types; + +import std; + +using namespace Nexus; +using namespace Nexus::ECS; +using namespace std::chrono_literals; + +namespace { + struct Position { + float32 x = 0.0f; + float32 y = 0.0f; + }; + + struct Velocity { + float32 dx = 0.0f; + float32 dy = 0.0f; + }; + + struct Health { + int32 value = 100; + + Health() = default; + explicit Health(int32 v) : value(v) {} + }; + + struct Hits { + int32 count = 0; + }; + + struct Marker { + int32 value = 0; + }; + + // Distinct component types, used to race ComponentTypeId initialisation. + template + struct Probe { + int32 value = 0; + }; + + constexpr float32 kDt = 0.5f; // exactly representable, keeps float32 expectations exact + + template + bool WaitFor(Pred&& pred, std::chrono::milliseconds timeout = 5000ms) { + const auto deadline = std::chrono::steady_clock::now() + timeout; + while (!pred()) { + if (std::chrono::steady_clock::now() > deadline) + return false; + std::this_thread::yield(); + } + return true; + } + + // Holds a thread "busy" for about `duration` without sleeping. On Windows sleep_for() rounds up + // to the ~15.6 ms timer tick, which made three of these tests take ~1.9 s for nothing. + inline void BusyWait(std::chrono::microseconds duration) { + const auto end = std::chrono::steady_clock::now() + duration; + while (std::chrono::steady_clock::now() < end) + std::this_thread::yield(); + } + + class SchedulerTest : public ::testing::Test { + protected: + World m_World; + + std::vector CreatePositions(usize count) { + std::vector ids; + ids.reserve(count); + for (usize i = 0; i < count; ++i) { + Entity e = m_World.CreateEntity(); + m_World.Add(e, static_cast(i), 0.0f); + ids.push_back(e); + } + return ids; + } + }; + + // --------------------------------------------------------------------------------- + // Determinism helpers: the same simulation scheduled with different worker counts + // --------------------------------------------------------------------------------- + void StepGravity(Velocity& v, float32 dt) { + v.dy -= 9.5f * dt; + } + void StepMove(Position& p, const Velocity& v, float32 dt) { + p.x += v.dx * dt; + p.y += v.dy * dt; + } + void StepBurn(Health& h) { + h.value -= 1; + } + + std::vector PopulateSimulation(World& world, usize count) { + std::vector ids; + ids.reserve(count); + for (usize i = 0; i < count; ++i) { + const float32 f = static_cast(i % 512) * 0.25f; + Entity e = world.CreateEntity(); + world.Add(e, f, -f); + world.Add(e, 1.0f + f, 0.5f * f); + world.Add(e, (i % 100 == 0) ? 3 : 1000); // 1% die after 3 frames + ids.push_back(e); + } + return ids; + } + + std::vector Snapshot(World& world, const std::vector& ids) { + std::vector out; + out.reserve(ids.size() * 3); + for (Entity e : ids) { + if (!world.IsAlive(e)) { + out.insert(out.end(), {-1.0f, -1.0f, -1.0f}); + continue; + } + const auto& p = world.Get(e); + out.push_back(p.x); + out.push_back(p.y); + out.push_back(static_cast(world.Get(e).value)); + } + return out; + } + + std::vector RunScheduledSimulation(usize workers, usize count, int frames) { + World world; + const auto ids = PopulateSimulation(world, count); + + Scheduler scheduler(world, workers); + scheduler.AddSystem("Gravity", Access{}.Write(), [](SystemContext& ctx) { + ctx.ParallelForEach([dt = ctx.DeltaTime()](Entity, Velocity& v) { StepGravity(v, dt); }, 256); + }); + scheduler.AddSystem("Movement", Access{}.Read().Write(), [](SystemContext& ctx) { + ctx.ParallelForEach( + [dt = ctx.DeltaTime()](Entity, Position& p, const Velocity& v) { StepMove(p, v, dt); }, 256); + }); + scheduler.AddSystem("Burn", Access{}.Write(), [](SystemContext& ctx) { + ctx.ParallelForEach([](Entity, Health& h) { StepBurn(h); }, 256); + }); + scheduler.AddSystem("Reaper", Access{}.Read(), [](SystemContext& ctx) { + ctx.ParallelForEach( + [&ctx](Entity e, const Health& h) { + if (h.value <= 0) + ctx.Commands().Destroy(e); + }, + 256); + }); + + for (int i = 0; i < frames; ++i) + scheduler.Run(kDt); + + return Snapshot(world, ids); + } + + std::vector RunSequentialSimulation(usize count, int frames) { + World world; + const auto ids = PopulateSimulation(world, count); + + for (int i = 0; i < frames; ++i) { + for ([[maybe_unused]] auto [e, v] : world.View()) + StepGravity(v, kDt); + for ([[maybe_unused]] auto [e, p, v] : world.View()) + StepMove(p, v, kDt); + for ([[maybe_unused]] auto [e, h] : world.View()) + StepBurn(h); + + std::vector dead; + for (auto [e, h] : world.View()) + if (h.value <= 0) + dead.push_back(e); + for (Entity e : dead) + world.DestroyEntity(e); + } + return Snapshot(world, ids); + } + + template + std::array CollectIds(std::index_sequence) { + return {ComponentTypeId>()...}; + } +} // namespace + +// ===================================================================== +// ThreadPool +// ===================================================================== + +TEST(ThreadPoolTest, SizeIsAtLeastOneAndRespectsTheRequest) { + ThreadPool zero(0); + ThreadPool three(3); + + EXPECT_GE(zero.Size(), 1u); + EXPECT_EQ(three.Size(), 3u); +} + +TEST(ThreadPoolTest, EverySubmittedTaskRuns) { + constexpr int32 count = 1000; + std::atomic counter{0}; // declared before the pool: outlives its workers + ThreadPool pool(4); + + for (int32 i = 0; i < count; ++i) + pool.Submit([&counter] { ++counter; }); + + EXPECT_TRUE(WaitFor([&] { return counter.load() == count; })); +} + +TEST(ThreadPoolTest, TasksRunOnWorkerThreadsNotOnTheCaller) { + std::atomic done{false}; + std::thread::id workerId; + ThreadPool pool(2); + + pool.Submit([&] { + workerId = std::this_thread::get_id(); + done = true; + }); + + ASSERT_TRUE(WaitFor([&] { return done.load(); })); + EXPECT_NE(workerId, std::this_thread::get_id()); +} + +TEST(ThreadPoolTest, DestructorDrainsTasksStillQueued) { + std::atomic counter{0}; + { + ThreadPool pool(2); + for (int i = 0; i < 200; ++i) + pool.Submit([&counter] { + BusyWait(50us); + ++counter; + }); + } + EXPECT_EQ(counter.load(), 200); +} + +TEST(ThreadPoolTest, ConcurrentSubmittersAreSafe) { + constexpr int32 perThread = 1000; + constexpr int32 threads = 8; + std::atomic counter{0}; + ThreadPool pool(4); + { + std::vector submitters; + for (int32 t = 0; t < threads; ++t) + submitters.emplace_back([&] { + for (int32 i = 0; i < perThread; ++i) + pool.Submit([&counter] { ++counter; }); + }); + } + EXPECT_TRUE(WaitFor([&] { return counter.load() == perThread * threads; })); +} + +TEST(ThreadPoolTest, ParallelForVisitsEveryIndexExactlyOnce) { + struct Case { + usize count; + usize grain; + }; + const std::array cases{Case{0, 16}, Case{1, 16}, Case{15, 16}, Case{16, 16}, + Case{17, 16}, Case{1000, 1}, Case{1000, 7}, Case{1000, 1000}, + Case{1000, 100'000}, Case{12'345, 0}}; // grain 0 is treated as 1 + ThreadPool pool(4); + + for (const Case& c : cases) { + SCOPED_TRACE(std::format("count={} grain={}", c.count, c.grain)); + std::vector> hits(c.count); + + pool.ParallelFor(c.count, c.grain, [&](usize begin, usize end) { + for (usize i = begin; i < end; ++i) + hits[i].fetch_add(1); + }); + + const auto wrong = std::ranges::count_if(hits, [](const auto& h) { return h.load() != 1; }); + EXPECT_EQ(wrong, 0); + } +} + +TEST(ThreadPoolTest, ParallelForChunksStayInRangeAndTileTheRange) { + constexpr usize count = 10'007; + constexpr usize grain = 100; + std::mutex mutex; + std::vector> chunks; + ThreadPool pool(4); + + pool.ParallelFor(count, grain, [&](usize begin, usize end) { + std::scoped_lock lock(mutex); + chunks.emplace_back(begin, end); + }); + + std::ranges::sort(chunks); + usize expectedBegin = 0; + for (const auto& [begin, end] : chunks) { + EXPECT_EQ(begin, expectedBegin); + EXPECT_LT(begin, end); + EXPECT_LE(end - begin, grain); + expectedBegin = end; + } + EXPECT_EQ(expectedBegin, count); +} + +TEST(ThreadPoolTest, ParallelForComputesTheCorrectSum) { + constexpr uint64 count = 1'000'000; + std::atomic total{0}; + ThreadPool pool(4); + + pool.ParallelFor(count, 1000, [&](usize begin, usize end) { + uint64 local = 0; + for (usize i = begin; i < end; ++i) + local += i; + total += local; + }); + + EXPECT_EQ(total.load(), count * (count - 1) / 2); +} + +TEST(ThreadPoolTest, ParallelForWorksWithASingleWorker) { + std::atomic total{0}; + ThreadPool pool(1); + + pool.ParallelFor(5000, 10, [&](usize begin, usize end) { total += static_cast(end - begin); }); + + EXPECT_EQ(total.load(), 5000); +} + +TEST(ThreadPoolTest, ParallelForFromInsideTheOnlyWorkerDoesNotDeadlock) { + std::atomic total{0}; + std::promise finished; + auto future = finished.get_future(); + ThreadPool pool(1); // worst case: the caller is the only thread that can make progress + + pool.Submit([&] { + pool.ParallelFor(10'000, 10, [&](usize begin, usize end) { total += static_cast(end - begin); }); + finished.set_value(); + }); + + ASSERT_EQ(future.wait_for(10s), std::future_status::ready); + EXPECT_EQ(total.load(), 10'000); +} + +TEST(ThreadPoolTest, NestedParallelForFromMoreTasksThanWorkersDoesNotDeadlock) { + constexpr int32 tasks = 8; + std::atomic finished{0}; + std::atomic total{0}; + ThreadPool pool(2); + + for (int32 t = 0; t < tasks; ++t) + pool.Submit([&] { + pool.ParallelFor(5000, 50, + [&](usize begin, usize end) { total += static_cast(end - begin); }); + ++finished; + }); + + ASSERT_TRUE(WaitFor([&] { return finished.load() == tasks; }, 10'000ms)); + EXPECT_EQ(total.load(), static_cast(tasks) * 5000); +} + +// ===================================================================== +// CommandBuffer +// ===================================================================== + +class CommandBufferTest : public ::testing::Test { +protected: + World m_World; + CommandBuffer m_Commands; +}; + +TEST_F(CommandBufferTest, NothingHappensUntilApply) { + Entity e = m_World.CreateEntity(); + + m_Commands.Destroy(e); + EXPECT_TRUE(m_World.IsAlive(e)); + + m_Commands.Apply(m_World); + EXPECT_FALSE(m_World.IsAlive(e)); +} + +TEST_F(CommandBufferTest, ApplyOnAnEmptyBufferIsSafe) { + EXPECT_NO_THROW(m_Commands.Apply(m_World)); +} + +TEST_F(CommandBufferTest, ApplyConsumesTheCommands) { + m_Commands.Spawn([](World& world, Entity e) { world.Add(e); }); + + m_Commands.Apply(m_World); + m_Commands.Apply(m_World); + + EXPECT_EQ(m_World.Query().size(), 1u); +} + +TEST_F(CommandBufferTest, AddForwardsConstructorArguments) { + Entity e = m_World.CreateEntity(); + + m_Commands.Add(e, 7); + m_Commands.Add(e, 1.0f, 2.0f); + m_Commands.Apply(m_World); + + EXPECT_EQ(m_World.Get(e).value, 7); + EXPECT_FLOAT_EQ(m_World.Get(e).y, 2.0f); +} + +TEST_F(CommandBufferTest, CommandsRunInRecordingOrder) { + Entity addedThenRemoved = m_World.CreateEntity(); + Entity removedThenAdded = m_World.CreateEntity(); + m_World.Add(removedThenAdded, 1); + + m_Commands.Add(addedThenRemoved, 5); + m_Commands.Remove(addedThenRemoved); + m_Commands.Remove(removedThenAdded); + m_Commands.Add(removedThenAdded, 9); + m_Commands.Apply(m_World); + + EXPECT_FALSE(m_World.Has(addedThenRemoved)); + ASSERT_TRUE(m_World.Has(removedThenAdded)); + EXPECT_EQ(m_World.Get(removedThenAdded).value, 9); +} + +TEST_F(CommandBufferTest, CommandsOnAnEntityDestroyedEarlierInTheBufferAreSkipped) { + Entity e = m_World.CreateEntity(); + + m_Commands.Destroy(e); + m_Commands.Add(e, 1.0f, 1.0f); // would throw if applied to a dead entity + m_Commands.Remove(e); + + EXPECT_NO_THROW(m_Commands.Apply(m_World)); + EXPECT_FALSE(m_World.IsAlive(e)); +} + +TEST_F(CommandBufferTest, AddToAnEntityThatDiedBeforeApplyDoesNotThrow) { + Entity e = m_World.CreateEntity(); + m_Commands.Add(e, 1.0f, 1.0f); + + m_World.DestroyEntity(e); + + EXPECT_NO_THROW(m_Commands.Apply(m_World)); + EXPECT_FALSE(m_World.Has(e)); +} + +TEST_F(CommandBufferTest, SpawnCreatesTheEntityAndHandsItToInit) { + Entity spawned = NullEntity; + + m_Commands.Spawn([&](World& world, Entity e) { + world.Add(e, 3.0f, 4.0f); + spawned = e; + }); + EXPECT_TRUE(m_World.Query().empty()); // nothing yet + m_Commands.Apply(m_World); + + ASSERT_FALSE(spawned == NullEntity); + EXPECT_TRUE(m_World.IsAlive(spawned)); + EXPECT_FLOAT_EQ(m_World.Get(spawned).x, 3.0f); +} + +TEST_F(CommandBufferTest, ManySpawnsProduceDistinctEntities) { + for (int i = 0; i < 100; ++i) + m_Commands.Spawn([](World& world, Entity e) { world.Add(e); }); + m_Commands.Apply(m_World); + + std::vector spawned = m_World.Query(); + std::set indices; + for (Entity e : spawned) + indices.insert(e.index); + + EXPECT_EQ(spawned.size(), 100u); + EXPECT_EQ(indices.size(), 100u); +} + +TEST_F(CommandBufferTest, RecordingFromManyThreadsLosesNothing) { + constexpr usize threads = 8; + constexpr usize perThread = 500; + { + std::vector recorders; + for (usize t = 0; t < threads; ++t) + recorders.emplace_back([&] { + for (usize i = 0; i < perThread; ++i) + m_Commands.Spawn([](World& world, Entity e) { world.Add(e); }); + }); + } + + m_Commands.Apply(m_World); + + EXPECT_EQ(m_World.Query().size(), threads * perThread); +} + +TEST_F(CommandBufferTest, ConcurrentAddsToDisjointEntitiesAreAllApplied) { + constexpr usize threads = 8; + constexpr usize perThread = 500; + std::vector ids; + for (usize i = 0; i < threads * perThread; ++i) + ids.push_back(m_World.CreateEntity()); + { + std::vector recorders; + for (usize t = 0; t < threads; ++t) + recorders.emplace_back([&, t] { + for (usize i = t * perThread; i < (t + 1) * perThread; ++i) + m_Commands.Add(ids[i], static_cast(i)); + }); + } + + m_Commands.Apply(m_World); + + for (usize i = 0; i < ids.size(); ++i) { + ASSERT_TRUE(m_World.Has(ids[i])); + ASSERT_EQ(m_World.Get(ids[i]).value, static_cast(i)); + } +} + +// ===================================================================== +// Access +// ===================================================================== + +TEST(AccessTest, ReadDoesNotImplyWrite) { + Access access; + access.Read(); + + EXPECT_TRUE(access.CanRead(ComponentTypeId())); + EXPECT_FALSE(access.CanWrite(ComponentTypeId())); +} + +TEST(AccessTest, WriteImpliesRead) { + Access access; + access.Write(); + + EXPECT_TRUE(access.CanRead(ComponentTypeId())); + EXPECT_TRUE(access.CanWrite(ComponentTypeId())); +} + +TEST(AccessTest, UndeclaredComponentsAreDenied) { + Access access; + access.Read().Write(); + + EXPECT_FALSE(access.CanRead(ComponentTypeId())); + EXPECT_FALSE(access.CanWrite(ComponentTypeId())); + EXPECT_FALSE(Access{}.CanRead(ComponentTypeId())); +} + +TEST(AccessTest, DuplicateDeclarationsAreHarmless) { + Access access; + access.Read().Write().Write(); + + EXPECT_TRUE(access.CanRead(ComponentTypeId())); + EXPECT_TRUE(access.CanWrite(ComponentTypeId())); +} + +TEST(AccessTest, ConflictMatrix) { + Access readP; + readP.Read(); + Access readP2; + readP2.Read(); + Access writeP; + writeP.Write(); + Access writeP2; + writeP2.Write(); + Access writeV; + writeV.Write(); + Access readPwriteV; + readPwriteV.Read().Write(); + Access empty; + + EXPECT_TRUE(writeP.ConflictsWith(writeP2)); // write / write + EXPECT_TRUE(writeP.ConflictsWith(readP)); // write / read + EXPECT_TRUE(readP.ConflictsWith(writeP)); // read / write + EXPECT_FALSE(readP.ConflictsWith(readP2)); // read / read + EXPECT_FALSE(writeP.ConflictsWith(writeV)); // disjoint + EXPECT_TRUE(readPwriteV.ConflictsWith(writeP)); // partial overlap + EXPECT_TRUE(readPwriteV.ConflictsWith(writeV)); + EXPECT_FALSE(empty.ConflictsWith(writeP)); + EXPECT_FALSE(empty.ConflictsWith(empty)); +} + +TEST(AccessTest, ConflictIsSymmetric) { + Access a; + a.Read().Write(); + Access b; + b.Write(); + Access c; + c.Read(); + Access d; + d.Write(); + + const std::array all{&a, &b, &c, &d}; + for (const Access* x : all) + for (const Access* y : all) + EXPECT_EQ(x->ConflictsWith(*y), y->ConflictsWith(*x)); +} + +TEST(AccessTest, EnsurePoolsCreatesExactlyTheDeclaredPools) { + Registry registry; + Access access; + access.Read().Write(); + + EXPECT_FALSE(registry.HasPool()); + access.EnsurePools(registry); + + EXPECT_TRUE(registry.HasPool()); + EXPECT_TRUE(registry.HasPool()); + EXPECT_FALSE(registry.HasPool()); +} + +// ===================================================================== +// Scheduler: basics +// ===================================================================== + +TEST_F(SchedulerTest, EmptySchedulerRunIsANoOp) { + Scheduler scheduler(m_World, 2); + + EXPECT_NO_THROW(scheduler.Run(kDt)); + EXPECT_TRUE(scheduler.DescribeGraph().empty()); +} + +TEST_F(SchedulerTest, ThreadCountIsAtLeastOneAndRespectsTheRequest) { + Scheduler zero(m_World, 0); + Scheduler three(m_World, 3); + + EXPECT_GE(zero.ThreadCount(), 1u); + EXPECT_EQ(three.ThreadCount(), 3u); +} + +TEST_F(SchedulerTest, EverySystemRunsExactlyOncePerFrame) { + std::atomic a{0}; + std::atomic b{0}; + Scheduler scheduler(m_World, 4); + scheduler.AddSystem("A", Access{}.Write(), [&](SystemContext&) { ++a; }); + scheduler.AddSystem("B", Access{}.Read(), [&](SystemContext&) { ++b; }); + + for (int frame = 1; frame <= 50; ++frame) { + scheduler.Run(kDt); + ASSERT_EQ(a.load(), frame); + ASSERT_EQ(b.load(), frame); + } +} + +TEST_F(SchedulerTest, SixtyFourIndependentSystemsAllRunEveryFrame) { + std::array, 64> runs{}; + Scheduler scheduler(m_World, 4); + for (usize i = 0; i < runs.size(); ++i) + scheduler.AddSystem(std::format("R{}", i), Access{}.Read(), + [&runs, i](SystemContext&) { ++runs[i]; }); + + for (int frame = 0; frame < 20; ++frame) + scheduler.Run(kDt); + + for (const auto& count : runs) + EXPECT_EQ(count.load(), 20); +} + +TEST_F(SchedulerTest, DeltaTimeIsPassedToSystems) { + float32 seen = 0.0f; + Scheduler scheduler(m_World, 2); + scheduler.AddSystem("Dt", Access{}, [&](SystemContext& ctx) { seen = ctx.DeltaTime(); }); + + scheduler.Run(0.25f); + + EXPECT_FLOAT_EQ(seen, 0.25f); +} + +TEST_F(SchedulerTest, DeclaredPoolsAreCreatedBeforeSystemsRun) { + Scheduler scheduler(m_World, 2); + scheduler.AddSystem("Reader", Access{}.Read(), [](SystemContext&) {}); + + EXPECT_FALSE(m_World.GetRegistry().HasPool()); + scheduler.Run(kDt); + EXPECT_TRUE(m_World.GetRegistry().HasPool()); +} + +TEST_F(SchedulerTest, SystemsAddedAfterTheFirstRunAreScheduledToo) { + std::vector order; + Scheduler scheduler(m_World, 4); + scheduler.AddSystem("First", Access{}.Write(), [&](SystemContext&) { order.push_back(0); }); + scheduler.Run(kDt); + + scheduler.AddSystem("Second", Access{}.Write(), [&](SystemContext&) { order.push_back(1); }); + order.clear(); + scheduler.Run(kDt); + + EXPECT_EQ(order, (std::vector{0, 1})); +} + +TEST_F(SchedulerTest, DescribeGraphShowsWhoBlocksWhom) { + Scheduler scheduler(m_World, 2); + scheduler.AddSystem("Writer", Access{}.Write(), [](SystemContext&) {}); + scheduler.AddSystem("Reader", Access{}.Read(), [](SystemContext&) {}); + scheduler.AddSystem("Other", Access{}.Write(), [](SystemContext&) {}); + + const std::string graph = scheduler.DescribeGraph(); + + EXPECT_TRUE(graph.contains("Writer")); + EXPECT_TRUE(graph.contains("Reader")); + EXPECT_TRUE(graph.contains("Other")); + EXPECT_TRUE(graph.contains("blocks: Reader")); + EXPECT_FALSE(graph.contains("blocks: Other")); +} + +// ===================================================================== +// Scheduler: ParallelForEach +// ===================================================================== + +TEST_F(SchedulerTest, ParallelForEachUpdatesEveryEntity) { + constexpr usize count = 10'000; + std::vector ids; + for (usize i = 0; i < count; ++i) { + Entity e = m_World.CreateEntity(); + m_World.Add(e, static_cast(i), 0.0f); + m_World.Add(e, 2.0f, 0.0f); + ids.push_back(e); + } + + Scheduler scheduler(m_World, 4); + scheduler.AddSystem("Move", Access{}.Read().Write(), [](SystemContext& ctx) { + ctx.ParallelForEach( + [dt = ctx.DeltaTime()](Entity, Position& p, const Velocity& v) { p.x += v.dx * dt; }, 128); + }); + scheduler.Run(kDt); + + for (usize i = 0; i < count; ++i) + ASSERT_FLOAT_EQ(m_World.Get(ids[i]).x, static_cast(i) + 1.0f); +} + +TEST(SchedulerEdgeCases, ParallelForEachVisitsEachEntityExactlyOnceAcrossChunkBoundaries) { + const std::array counts{0, 1, 2, 2047, 2048, 2049, 10'000}; + const std::array grains{1, 7, 2048, 1u << 20}; + + for (const usize count : counts) { + for (const usize grain : grains) { + SCOPED_TRACE(std::format("count={} grain={}", count, grain)); + World world; + for (usize i = 0; i < count; ++i) + world.Add(world.CreateEntity()); + + Scheduler scheduler(world, 4); + scheduler.AddSystem("Count", Access{}.Write(), [grain](SystemContext& ctx) { + ctx.ParallelForEach([](Entity, Hits& h) { ++h.count; }, grain); + }); + scheduler.Run(kDt); + + usize visited = 0; + usize wrong = 0; + for ([[maybe_unused]] auto [e, h] : world.View()) { + ++visited; + if (h.count != 1) + ++wrong; + } + EXPECT_EQ(visited, count); + EXPECT_EQ(wrong, 0u); + } + } +} + +TEST_F(SchedulerTest, ParallelForEachSkipsEntitiesMissingAComponent) { + std::vector ids = CreatePositions(1000); + for (usize i = 0; i < ids.size(); i += 10) + m_World.Add(ids[i], 1.0f, 0.0f); + + std::atomic visited{0}; + Scheduler scheduler(m_World, 4); + scheduler.AddSystem("Both", Access{}.Read().Read(), [&](SystemContext& ctx) { + ctx.ParallelForEach([&](Entity, const Position&, const Velocity&) { ++visited; }, 16); + }); + scheduler.Run(kDt); + + EXPECT_EQ(visited.load(), 100); +} + +TEST_F(SchedulerTest, ParallelForEachOnAnEmptyWorldDoesNothing) { + std::atomic visited{0}; + Scheduler scheduler(m_World, 4); + scheduler.AddSystem("Nothing", Access{}.Read(), [&](SystemContext& ctx) { + ctx.ParallelForEach([&](Entity, const Position&) { ++visited; }); + }); + + EXPECT_NO_THROW(scheduler.Run(kDt)); + EXPECT_EQ(visited.load(), 0); +} + +TEST_F(SchedulerTest, ReadAndWriteAccessorsGiveDirectPoolAccess) { + constexpr usize count = 100; + std::vector ids; + for (usize i = 0; i < count; ++i) { + Entity e = m_World.CreateEntity(); + m_World.Add(e, 0.0f, 0.0f); + m_World.Add(e, 3.0f, 0.0f); + ids.push_back(e); + } + + Scheduler scheduler(m_World, 2); + scheduler.AddSystem("Pools", Access{}.Read().Write(), [](SystemContext& ctx) { + const auto& velocities = ctx.Read(); + auto& positions = ctx.Write(); + const auto& alsoReadable = ctx.Read(); // Write implies read + + EXPECT_EQ(alsoReadable.Values().size(), positions.Values().size()); + for (usize i = 0; i < positions.Values().size(); ++i) + positions.Values()[i].x += velocities.Values()[i].dx; + }); + scheduler.Run(kDt); + + for (Entity e : ids) + EXPECT_FLOAT_EQ(m_World.Get(e).x, 3.0f); +} + +// ===================================================================== +// Scheduler: access enforcement +// ===================================================================== + +TEST_F(SchedulerTest, WritingAReadOnlyDeclaredComponentIsRejected) { + Scheduler scheduler(m_World, 2); + scheduler.AddSystem("Cheat", Access{}.Read(), [](SystemContext& ctx) { (void)ctx.Write(); }); + + EXPECT_THROW(scheduler.Run(kDt), std::logic_error); +} + +TEST_F(SchedulerTest, ReadingAnUndeclaredComponentIsRejected) { + Scheduler scheduler(m_World, 2); + scheduler.AddSystem("Cheat", Access{}.Read(), [](SystemContext& ctx) { (void)ctx.Read(); }); + + EXPECT_THROW(scheduler.Run(kDt), std::logic_error); +} + +TEST_F(SchedulerTest, ViewOfAnUndeclaredComponentIsRejected) { + Scheduler scheduler(m_World, 2); + scheduler.AddSystem("Cheat", Access{}.Read(), [](SystemContext& ctx) { + for ([[maybe_unused]] auto [e, h] : ctx.View()) { + } + }); + + EXPECT_THROW(scheduler.Run(kDt), std::logic_error); +} + +TEST_F(SchedulerTest, ParallelForEachWithOneUndeclaredComponentIsRejected) { + Scheduler scheduler(m_World, 2); + scheduler.AddSystem("Cheat", Access{}.Read(), [](SystemContext& ctx) { + ctx.ParallelForEach([](Entity, const Position&, const Velocity&) {}); + }); + + EXPECT_THROW(scheduler.Run(kDt), std::logic_error); +} + +TEST_F(SchedulerTest, ReadingAWriteDeclaredComponentIsAllowed) { + Scheduler scheduler(m_World, 2); + scheduler.AddSystem("Ok", Access{}.Write(), [](SystemContext& ctx) { + (void)ctx.Read(); + for ([[maybe_unused]] auto [e, p] : ctx.View()) { + } + }); + + EXPECT_NO_THROW(scheduler.Run(kDt)); +} + +TEST_F(SchedulerTest, SchedulerStaysUsableAfterARejectedAccess) { + std::atomic cheat{true}; + std::atomic runs{0}; + Scheduler scheduler(m_World, 2); + scheduler.AddSystem("Sometimes", Access{}.Read(), [&](SystemContext& ctx) { + if (cheat) + (void)ctx.Write(); + ++runs; + }); + + EXPECT_THROW(scheduler.Run(kDt), std::logic_error); + cheat = false; + EXPECT_NO_THROW(scheduler.Run(kDt)); + EXPECT_EQ(runs.load(), 1); +} + +// ===================================================================== +// Scheduler: ordering and concurrency guarantees +// ===================================================================== + +TEST_F(SchedulerTest, ConflictingSystemsRunInRegistrationOrder) { + constexpr int32 systems = 20; + std::vector order; // no lock: conflicting systems must never overlap + Scheduler scheduler(m_World, 8); + for (int32 id = 0; id < systems; ++id) + scheduler.AddSystem(std::format("S{}", id), Access{}.Write(), + [&order, id](SystemContext&) { order.push_back(id); }); + + std::vector expected(systems); + std::iota(expected.begin(), expected.end(), 0); + + for (int frame = 0; frame < 50; ++frame) { + order.clear(); + scheduler.Run(kDt); + ASSERT_EQ(order, expected) << "frame " << frame; + } +} + +TEST_F(SchedulerTest, ChainedWritersObserveEachOthersResults) { + constexpr usize count = 5000; + std::vector ids = CreatePositions(count); + + Scheduler scheduler(m_World, 8); + scheduler.AddSystem("Set", Access{}.Write(), [](SystemContext& ctx) { + ctx.ParallelForEach([](Entity, Position& p) { p.x = 1.0f; }, 64); + }); + scheduler.AddSystem("Triple", Access{}.Write(), [](SystemContext& ctx) { + ctx.ParallelForEach([](Entity, Position& p) { p.x *= 3.0f; }, 64); + }); + scheduler.AddSystem("AddTwo", Access{}.Write(), [](SystemContext& ctx) { + ctx.ParallelForEach([](Entity, Position& p) { p.x += 2.0f; }, 64); + }); + + for (int frame = 0; frame < 50; ++frame) { + scheduler.Run(kDt); + for (Entity e : ids) + ASSERT_FLOAT_EQ(m_World.Get(e).x, 5.0f) << "frame " << frame; // (1 * 3) + 2 + } +} + +TEST_F(SchedulerTest, ReadersOfTheSameComponentRunConcurrently) { + std::atomic arrived{0}; + std::atomic rendezvous{0}; + const auto reader = [&](SystemContext&) { + ++arrived; + if (WaitFor([&] { return arrived.load() >= 2; }, 3000ms)) + ++rendezvous; + }; + + Scheduler scheduler(m_World, 4); + scheduler.AddSystem("R1", Access{}.Read(), reader); + scheduler.AddSystem("R2", Access{}.Read(), reader); + scheduler.Run(kDt); + + EXPECT_EQ(rendezvous.load(), 2); // both saw the other one running +} + +TEST_F(SchedulerTest, SystemsWithDisjointAccessRunConcurrently) { + std::atomic arrived{0}; + std::atomic rendezvous{0}; + const auto body = [&](SystemContext&) { + ++arrived; + if (WaitFor([&] { return arrived.load() >= 2; }, 3000ms)) + ++rendezvous; + }; + + Scheduler scheduler(m_World, 4); + scheduler.AddSystem("WritesPosition", Access{}.Write(), body); + scheduler.AddSystem("WritesVelocity", Access{}.Write(), body); + scheduler.Run(kDt); + + EXPECT_EQ(rendezvous.load(), 2); +} + +TEST_F(SchedulerTest, ConflictingSystemsNeverOverlap) { + std::atomic active{0}; + std::atomic peak{0}; + const auto body = [&](SystemContext&) { + const int32 now = ++active; + int32 seen = peak.load(); + while (now > seen && !peak.compare_exchange_weak(seen, now)) { + } + BusyWait(100us); + --active; + }; + + Scheduler scheduler(m_World, 8); + for (int i = 0; i < 4; ++i) + scheduler.AddSystem(std::format("W{}", i), Access{}.Write(), body); + + for (int frame = 0; frame < 30; ++frame) + scheduler.Run(kDt); + + EXPECT_EQ(peak.load(), 1); +} + +TEST_F(SchedulerTest, WritersNeverOverlapWithReadersOrOtherWriters) { + std::atomic readers{0}; + std::atomic writers{0}; + std::atomic violations{0}; + + const auto reader = [&](SystemContext&) { + ++readers; + if (writers.load() > 0) + ++violations; + BusyWait(100us); + if (writers.load() > 0) + ++violations; + --readers; + }; + const auto writer = [&](SystemContext&) { + if (++writers > 1) + ++violations; + if (readers.load() > 0) + ++violations; + BusyWait(100us); + if (readers.load() > 0) + ++violations; + --writers; + }; + + Scheduler scheduler(m_World, 8); + scheduler.AddSystem("R1", Access{}.Read(), reader); + scheduler.AddSystem("R2", Access{}.Read(), reader); + scheduler.AddSystem("W1", Access{}.Write(), writer); + scheduler.AddSystem("R3", Access{}.Read(), reader); + scheduler.AddSystem("R4", Access{}.Read(), reader); + scheduler.AddSystem("W2", Access{}.Write(), writer); + + for (int frame = 0; frame < 30; ++frame) + scheduler.Run(kDt); + + EXPECT_EQ(violations.load(), 0); +} + +TEST_F(SchedulerTest, ASystemStartsAsSoonAsItsOwnDependenciesFinish) { + // "Blocked" is unrelated to everything and waits for "Dependent", which only depends on + // "Producer". A scheduler that runs systems in barrier-separated stages would deadlock here. + std::atomic dependentRan{false}; + std::atomic blockedSawIt{false}; + + Scheduler scheduler(m_World, 4); + scheduler.AddSystem("Blocked", Access{}.Write(), + [&](SystemContext&) { blockedSawIt = WaitFor([&] { return dependentRan.load(); }, 3000ms); }); + scheduler.AddSystem("Producer", Access{}.Write(), [](SystemContext&) {}); + scheduler.AddSystem("Dependent", Access{}.Read(), [&](SystemContext&) { dependentRan = true; }); + scheduler.Run(kDt); + + EXPECT_TRUE(blockedSawIt.load()); +} + +TEST_F(SchedulerTest, FewWorkersManyParallelSystemsDoNotDeadlock) { + constexpr usize count = 20'000; + constexpr usize systems = 8; + CreatePositions(count); + + std::array, systems> sums{}; + Scheduler scheduler(m_World, 2); + for (usize s = 0; s < systems; ++s) + scheduler.AddSystem(std::format("Sum{}", s), Access{}.Read(), [&sums, s](SystemContext& ctx) { + ctx.ParallelForEach( + [&sums, s](Entity, const Position& p) { sums[s] += static_cast(p.x); }, 64); + }); + + scheduler.Run(kDt); + + const uint64 expected = static_cast(count) * (count - 1) / 2; + for (const auto& sum : sums) + EXPECT_EQ(sum.load(), expected); +} + +// ===================================================================== +// Scheduler: exceptions +// ===================================================================== + +TEST_F(SchedulerTest, ExceptionFromASystemIsRethrownByRun) { + Scheduler scheduler(m_World, 2); + scheduler.AddSystem("Boom", Access{}, [](SystemContext&) { throw std::runtime_error("boom"); }); + + try { + scheduler.Run(kDt); + FAIL() << "Run() should have rethrown"; + } catch (const std::runtime_error& error) { + EXPECT_STREQ(error.what(), "boom"); + } +} + +TEST_F(SchedulerTest, OtherSystemsStillCompleteWhenOneThrows) { + std::atomic ran{0}; + Scheduler scheduler(m_World, 4); + scheduler.AddSystem("Boom", Access{}.Write(), [](SystemContext&) { throw std::runtime_error("boom"); }); + scheduler.AddSystem("Fine", Access{}.Write(), [&](SystemContext&) { ++ran; }); + + EXPECT_THROW(scheduler.Run(kDt), std::runtime_error); + EXPECT_EQ(ran.load(), 1); +} + +TEST_F(SchedulerTest, SchedulerRemainsUsableAfterASystemThrew) { + std::atomic shouldThrow{true}; + std::atomic completed{0}; + Scheduler scheduler(m_World, 2); + scheduler.AddSystem("Flaky", Access{}.Write(), [&](SystemContext&) { + if (shouldThrow) + throw std::runtime_error("first frame fails"); + ++completed; + }); + + EXPECT_THROW(scheduler.Run(kDt), std::runtime_error); + shouldThrow = false; + EXPECT_NO_THROW(scheduler.Run(kDt)); + EXPECT_NO_THROW(scheduler.Run(kDt)); + EXPECT_EQ(completed.load(), 2); +} + +TEST_F(SchedulerTest, SeveralThrowingSystemsStillSurfaceOneException) { + Scheduler scheduler(m_World, 4); + scheduler.AddSystem("A", Access{}.Write(), [](SystemContext&) { throw std::runtime_error("a"); }); + scheduler.AddSystem("B", Access{}.Write(), [](SystemContext&) { throw std::runtime_error("b"); }); + + EXPECT_THROW(scheduler.Run(kDt), std::runtime_error); +} + +// ===================================================================== +// Scheduler: command buffers +// ===================================================================== + +TEST_F(SchedulerTest, DestroyIsDeferredUntilEverySystemOfTheFrameFinished) { + constexpr usize count = 1000; + std::vector ids = CreatePositions(count); + for (Entity e : ids) + m_World.Add(e, 1); + const Entity target = ids.front(); + + std::atomic recorded{false}; + std::atomic seenByObserver{0}; + std::atomic targetAliveForObserver{false}; + + Scheduler scheduler(m_World, 4); + scheduler.AddSystem("Killer", Access{}.Read(), [&](SystemContext& ctx) { + ctx.Commands().Destroy(target); + recorded = true; + }); + scheduler.AddSystem("Observer", Access{}.Read(), [&](SystemContext& ctx) { + WaitFor([&] { return recorded.load(); }, 2000ms); // make the interesting interleaving likely + usize n = 0; + for ([[maybe_unused]] auto [e, p] : ctx.View()) + ++n; + seenByObserver = n; + targetAliveForObserver = ctx.IsAlive(target); + }); + scheduler.Run(kDt); + + EXPECT_EQ(seenByObserver.load(), count); + EXPECT_TRUE(targetAliveForObserver.load()); + EXPECT_FALSE(m_World.IsAlive(target)); // applied once the frame is over +} + +TEST_F(SchedulerTest, CommandsAreAppliedInSystemRegistrationOrder) { + Entity fromA = NullEntity; + Entity fromB = NullEntity; + Scheduler scheduler(m_World, 4); + scheduler.AddSystem("A", Access{}.Read(), + [&](SystemContext& ctx) { ctx.Commands().Spawn([&](World&, Entity e) { fromA = e; }); }); + scheduler.AddSystem("B", Access{}.Read(), + [&](SystemContext& ctx) { ctx.Commands().Spawn([&](World&, Entity e) { fromB = e; }); }); + + for (int frame = 0; frame < 50; ++frame) { + scheduler.Run(kDt); // A and B run in parallel, in any order... + ASSERT_LT(fromA.index, fromB.index) << "frame " << frame; // ...but A's commands apply first + } +} + +TEST_F(SchedulerTest, ParallelRecordedDestroysAreAllApplied) { + constexpr usize count = 20'000; + std::vector ids; + for (usize i = 0; i < count; ++i) { + Entity e = m_World.CreateEntity(); + m_World.Add(e, (i % 2 == 0) ? 0 : 10); + ids.push_back(e); + } + + Scheduler scheduler(m_World, 8); + scheduler.AddSystem("Reaper", Access{}.Read(), [](SystemContext& ctx) { + ctx.ParallelForEach( + [&ctx](Entity e, const Health& h) { + if (h.value <= 0) + ctx.Commands().Destroy(e); + }, + 64); + }); + scheduler.Run(kDt); + + for (usize i = 0; i < count; ++i) + ASSERT_EQ(m_World.IsAlive(ids[i]), i % 2 != 0) << "entity " << i; +} + +TEST_F(SchedulerTest, SpawnedEntitiesAppearAfterTheFrameAndOnlyOnce) { + bool firstFrame = true; + std::atomic seenDuringFrame{99}; + Scheduler scheduler(m_World, 2); + scheduler.AddSystem("Spawner", Access{}.Read(), [&](SystemContext& ctx) { + if (!firstFrame) + return; + for (int i = 0; i < 100; ++i) + ctx.Commands().Spawn([](World& world, Entity e) { world.Add(e, 1.0f, 1.0f); }); + usize n = 0; + for ([[maybe_unused]] auto [e, m] : ctx.View()) + ++n; + seenDuringFrame = n; + }); + + scheduler.Run(kDt); + EXPECT_EQ(m_World.Query().size(), 100u); + + firstFrame = false; + scheduler.Run(kDt); + EXPECT_EQ(m_World.Query().size(), 100u); // buffer was cleared, nothing replayed + EXPECT_EQ(seenDuringFrame.load(), 0u); +} + +TEST_F(SchedulerTest, StructuralChangesBecomeVisibleOnlyInTheNextFrame) { + constexpr usize count = 2000; + std::vector ids = CreatePositions(count); + + int32 frame = 0; + std::atomic seen{0}; + Scheduler scheduler(m_World, 4); + scheduler.AddSystem("Reader", Access{}.Read().Read(), [&](SystemContext& ctx) { + std::atomic n{0}; + ctx.ParallelForEach([&n](Entity, const Position&, const Velocity&) { ++n; }, 128); + seen = n.load(); + }); + scheduler.AddSystem("Mutator", Access{}, [&](SystemContext& ctx) { // only records commands + for (Entity e : ids) { + if (frame % 2 == 0) + ctx.Commands().Add(e, 1.0f, 1.0f); + else + ctx.Commands().Remove(e); + } + }); + + for (frame = 0; frame < 10; ++frame) { + scheduler.Run(kDt); + // the reader saw the state left by the previous frame's commands + EXPECT_EQ(seen.load(), frame % 2 == 1 ? count : 0u) << "frame " << frame; + } +} + +// ===================================================================== +// Determinism +// ===================================================================== + +TEST(SchedulerDeterminism, ResultDoesNotDependOnTheNumberOfWorkers) { + constexpr usize count = 20'000; + constexpr int frames = 20; + + const std::vector oneWorker = RunScheduledSimulation(1, count, frames); + const std::vector twoWorkers = RunScheduledSimulation(2, count, frames); + const std::vector eightWorkers = RunScheduledSimulation(8, count, frames); + + EXPECT_TRUE(oneWorker == twoWorkers); + EXPECT_TRUE(oneWorker == eightWorkers); +} + +TEST(SchedulerDeterminism, ScheduledRunMatchesPlainSequentialLoops) { + constexpr usize count = 20'000; + constexpr int frames = 20; + + const std::vector scheduled = RunScheduledSimulation(8, count, frames); + const std::vector sequential = RunSequentialSimulation(count, frames); + + ASSERT_EQ(scheduled.size(), sequential.size()); + usize different = 0; + for (usize i = 0; i < scheduled.size(); ++i) + if (std::abs(scheduled[i] - sequential[i]) > 1e-3f) + ++different; + EXPECT_EQ(different, 0u); +} + +TEST(SchedulerDeterminism, RepeatedRunsAreStable) { + const std::vector reference = RunScheduledSimulation(8, 5000, 10); + for (int i = 0; i < 10; ++i) + ASSERT_TRUE(RunScheduledSimulation(8, 5000, 10) == reference) << "run " << i; +} + +// ===================================================================== +// World read-only concurrency and component id registration +// ===================================================================== + +TEST(WorldConcurrencyTest, ConcurrentReadersOfAConstWorldSeeConsistentData) { + constexpr usize count = 20'000; + World world; + std::vector ids; + for (usize i = 0; i < count; ++i) { + Entity e = world.CreateEntity(); + world.Add(e, static_cast(i), 0.0f); + world.Add(e, static_cast(i)); + ids.push_back(e); + } + + const World& readonly = world; + std::atomic errors{0}; + { + std::vector readers; + for (int t = 0; t < 8; ++t) + readers.emplace_back([&] { + for (int round = 0; round < 5; ++round) + for (usize i = 0; i < count; ++i) { + const Entity e = ids[i]; + if (!readonly.IsAlive(e) || !readonly.Has(e)) + ++errors; + if (readonly.Get(e).x != static_cast(i)) + ++errors; + const Health* h = readonly.TryGet(e); + if (h == nullptr || h->value != static_cast(i)) + ++errors; + } + }); + } + + EXPECT_EQ(errors.load(), 0u); +} + +TEST(WorldConcurrencyTest, ConcurrentViewIterationOverExistingPoolsIsSafe) { + constexpr usize count = 10'000; + World world; + for (usize i = 0; i < count; ++i) { + Entity e = world.CreateEntity(); + world.Add(e, 1.0f, 0.0f); + world.Add(e, 2.0f, 0.0f); + } + + std::atomic errors{0}; + { + std::vector readers; + for (int t = 0; t < 8; ++t) + readers.emplace_back([&] { + usize visited = 0; + for ([[maybe_unused]] auto [e, p, v] : world.View()) { + if (p.x != 1.0f || v.dx != 2.0f) + ++errors; + ++visited; + } + if (visited != count) + ++errors; + }); + } + + EXPECT_EQ(errors.load(), 0u); +} + +TEST(ComponentIdTest, IdsAreUniqueAndConsistentWhenFirstUsedFromManyThreads) { + constexpr usize types = 32; + constexpr usize threads = 8; + + std::array, threads> results{}; + std::latch gate(1); + { + std::vector workers; + for (usize t = 0; t < threads; ++t) + workers.emplace_back([&, t] { + gate.wait(); // release every thread at once to maximise the race + results[t] = CollectIds(std::make_index_sequence{}); + }); + gate.count_down(); + } + + const std::set unique(results[0].begin(), results[0].end()); + EXPECT_EQ(unique.size(), types); // no two component types share an id + for (usize t = 1; t < threads; ++t) + EXPECT_TRUE(results[t] == results[0]) << "thread " << t << " saw different ids"; +}