Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Doxyfile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
114 changes: 114 additions & 0 deletions Source/Engine/Core/ECS/Private/CommandBuffer.cppm
Original file line number Diff line number Diff line change
@@ -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 <Platform/DLL/Export.hpp>

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<void(World&)>;

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 <Component T, typename... Args>
void Add(Entity entity, Args&&... args) {
Push([entity, values = std::make_tuple(std::forward<Args>(args)...)](World& world) mutable {
if (!world.IsAlive(entity))
return;
std::apply([&](auto&&... a) { world.Add<T>(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 <Component T>
void Remove(Entity entity) {
Push([entity](World& world) {
if (world.IsAlive(entity))
world.Remove<T>(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<void(World&, Entity)> 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<Command> 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<Command> m_commands;
};
} // namespace Nexus::ECS
66 changes: 66 additions & 0 deletions Source/Engine/Core/ECS/Private/ComponentPool.cppm
Original file line number Diff line number Diff line change
@@ -1,78 +1,144 @@
// SPDX-License-Identifier: MIT

/// @file ComponentPool.cppm
/// @brief Module NE.Engine.ECS.ComponentPool: type-erased and typed per-component storage.

module;

#include <Platform/DLL/Export.hpp>

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;

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<IComponentPool>`.
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<const Entity> 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 <Component T>
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 <typename... Args>
T& Emplace(Entity entity, Args&&... args) {
return m_storage.Emplace(entity, std::forward<Args>(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<const Entity> Entities() const override {
return m_storage.Entities();
}

/// @brief Mutable view over all components, index-aligned with Entities().
/// @warning Invalidated by structural changes.
std::span<T> Values() {
return m_storage.Values();
}

/// @brief Read-only view over all components, index-aligned with Entities().
/// @warning Invalidated by structural changes.
std::span<const T> Values() const {
return m_storage.Values();
}
Expand Down
11 changes: 11 additions & 0 deletions Source/Engine/Core/ECS/Private/Registry.cpp
Original file line number Diff line number Diff line change
@@ -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<ComponentId> 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);
Expand Down
Loading