Kumo
A hand-rolled game engine.
git clone https://git.sentomk.me/Kumo.git
commit 7d8d486e594a98b57a490373258d429d9fdc1e1b parent 555ff14fa83b84e83e1aadf677355cb451118368 Author: sentomk <sentomk@proton.me> Date: Tue, 24 Nov 2026 17:27:13 +0800 feat: add generational Entity and SparseSet for ECS Diffstat:
| A | src/ecs/entity.h | | | 49 | +++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | src/ecs/sparse_set.h | | | 126 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | tests/unit/sparse_set_test.cpp | | | 115 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
3 files changed, 290 insertions(+), 0 deletions(-)
diff --git a/src/ecs/entity.h b/src/ecs/entity.h @@ -0,0 +1,49 @@ +/// @file ecs/entity.h +/// @brief Compact generational entity handle. +#pragma once + +#include <cassert> + +#include "core/types.h" + +namespace kumo { + +/// @brief Opaque handle identifying one entity in a World. +/// +/// The low 20 bits hold the slot index (up to 1,048,576 concurrent entities) +/// and the high 12 bits hold a generation counter that advances each time a +/// slot is reused. Zero is always the null/invalid entity, so valid generations +/// start at 1 (wrapping from kMaxGeneration back to 1). +struct Entity { + static constexpr uint32_t kIndexBits = 20; + static constexpr uint32_t kGenerationBits = 32 - kIndexBits; + static constexpr uint32_t kIndexMask = (uint32_t{1} << kIndexBits) - 1; + static constexpr uint32_t kMaxIndex = kIndexMask; + static constexpr uint32_t kMaxGeneration = + (uint32_t{1} << kGenerationBits) - 1; + + uint32_t raw = 0; + + static constexpr Entity null() { return Entity{0}; } + + static constexpr Entity make(uint32_t index, uint32_t generation) { + assert(index <= kMaxIndex); + assert(generation >= 1 && generation <= kMaxGeneration); + return Entity{(generation << kIndexBits) | index}; + } + + constexpr uint32_t index() const { return raw & kIndexMask; } + constexpr uint32_t generation() const { return raw >> kIndexBits; } + constexpr bool valid() const { return raw != 0; } + + constexpr explicit operator bool() const { return valid(); } + constexpr bool operator==(const Entity&) const = default; +}; + +/// @brief Advances a generation counter, skipping 0 so Entity::null() stays +/// unique. +constexpr uint32_t next_generation(uint32_t generation) { + return generation >= Entity::kMaxGeneration ? 1u : generation + 1u; +} + +} // namespace kumo diff --git a/src/ecs/sparse_set.h b/src/ecs/sparse_set.h @@ -0,0 +1,126 @@ +/// @file ecs/sparse_set.h +/// @brief Contiguous per-component storage with O(1) lookup, insert and erase. +#pragma once + +#include <cassert> +#include <limits> +#include <utility> +#include <vector> + +#include "core/types.h" +#include "ecs/entity.h" + +namespace kumo { + +/// @brief Type-erased interface shared by every component pool in a World. +/// +/// Kept minimal so World can destroy an entity across all pools without RTTI. +class PoolBase { + public: + virtual ~PoolBase() = default; + + virtual bool has(Entity entity) const = 0; + virtual bool remove(Entity entity) = 0; + virtual void clear() = 0; + virtual size_t size() const = 0; + virtual const std::vector<Entity>& entities() const = 0; +}; + +/// @brief Sparse-set component storage for one component type @p T. +/// +/// `sparse_` maps `entity.index()` to a dense index in `dense_` / `data_`. +/// `dense_` stores the full Entity handle (including generation), so stale +/// handles to a reused slot never match. Removal uses swap-and-pop, keeping +/// `data_` tightly packed and deterministic. +template <typename T> +class SparseSet final : public PoolBase { + public: + static constexpr uint32_t kInvalid = std::numeric_limits<uint32_t>::max(); + + /// @brief Adds or replaces the component for @p entity. + template <typename... Args> + T& emplace(Entity entity, Args&&... args) { + assert(entity.valid()); + const uint32_t idx = entity.index(); + if (idx >= sparse_.size()) { + sparse_.resize(static_cast<size_t>(idx + 1), kInvalid); + } + + const uint32_t existing = sparse_[idx]; + if (existing != kInvalid) { + assert(dense_[existing] == entity); + data_[existing] = T{std::forward<Args>(args)...}; + return data_[existing]; + } + + const uint32_t dense_idx = static_cast<uint32_t>(dense_.size()); + sparse_[idx] = dense_idx; + dense_.push_back(entity); + data_.push_back(T{std::forward<Args>(args)...}); + return data_.back(); + } + + bool has(Entity entity) const override { + if (!entity.valid()) return false; + const uint32_t idx = entity.index(); + if (idx >= sparse_.size()) return false; + const uint32_t dense_idx = sparse_[idx]; + return dense_idx != kInvalid && dense_[dense_idx] == entity; + } + + /// @brief Removes the component for @p entity via swap-and-pop. + /// @return `true` if the component existed and was removed. + bool remove(Entity entity) override { + if (!has(entity)) return false; + const uint32_t dense_idx = sparse_[entity.index()]; + const uint32_t last_idx = static_cast<uint32_t>(dense_.size() - 1); + if (dense_idx != last_idx) { + const Entity moved = dense_[last_idx]; + dense_[dense_idx] = moved; + data_[dense_idx] = std::move(data_[last_idx]); + sparse_[moved.index()] = dense_idx; + } + dense_.pop_back(); + data_.pop_back(); + sparse_[entity.index()] = kInvalid; + return true; + } + + T& get(Entity entity) { + assert(has(entity)); + return data_[sparse_[entity.index()]]; + } + + const T& get(Entity entity) const { + assert(has(entity)); + return data_[sparse_[entity.index()]]; + } + + T* try_get(Entity entity) { + return has(entity) ? &data_[sparse_[entity.index()]] : nullptr; + } + + const T* try_get(Entity entity) const { + return has(entity) ? &data_[sparse_[entity.index()]] : nullptr; + } + + void clear() override { + sparse_.clear(); + dense_.clear(); + data_.clear(); + } + + size_t size() const override { return dense_.size(); } + bool empty() const { return dense_.empty(); } + + const std::vector<Entity>& entities() const override { return dense_; } + std::vector<T>& data() { return data_; } + const std::vector<T>& data() const { return data_; } + + private: + std::vector<uint32_t> sparse_; + std::vector<Entity> dense_; + std::vector<T> data_; +}; + +} // namespace kumo diff --git a/tests/unit/sparse_set_test.cpp b/tests/unit/sparse_set_test.cpp @@ -0,0 +1,115 @@ +#include "ecs/sparse_set.h" + +#include "check.h" +#include "core/types.h" +#include "ecs/entity.h" + +using kumo::Entity; +using kumo::next_generation; +using kumo::SparseSet; + +namespace { + +struct Counter { + int value = 0; + int tag = 0; +}; + +} // namespace + +TEST(entity_packs_index_and_generation) { + constexpr Entity null_entity = Entity::null(); + CHECK(!null_entity.valid()); + CHECK(!static_cast<bool>(null_entity)); + CHECK_EQ(Entity{}, null_entity); + + constexpr Entity e0 = Entity::make(0, 1); + CHECK(e0.valid()); + CHECK_EQ(e0.index(), 0u); + CHECK_EQ(e0.generation(), 1u); + constexpr Entity e_max = + Entity::make(Entity::kMaxIndex, Entity::kMaxGeneration); + CHECK(e_max.valid()); + CHECK_EQ(e_max.index(), Entity::kMaxIndex); + CHECK_EQ(e_max.generation(), Entity::kMaxGeneration); + CHECK_EQ(next_generation(1), 2u); + CHECK_EQ(next_generation(Entity::kMaxGeneration), 1u); +} + +TEST(sparse_set_emplace_get_and_replace) { + SparseSet<Counter> set; + const Entity a = Entity::make(0, 1); + const Entity b = Entity::make(10, 1); + CHECK(set.empty()); + CHECK(!set.has(a)); + CHECK(set.try_get(a) == nullptr); + Counter& ca = set.emplace(a, 42, 1); + CHECK_EQ(ca.value, 42); + CHECK_EQ(ca.tag, 1); + set.emplace(b, 99, 2); + CHECK_EQ(set.size(), 2u); + CHECK(set.has(a)); + CHECK(set.has(b)); + CHECK_EQ(set.get(a).value, 42); + CHECK_EQ(set.get(b).value, 99); + // Emplacing again on the same entity replaces the value in place. + set.emplace(a, 7, 3); + CHECK_EQ(set.size(), 2u); + CHECK_EQ(set.get(a).value, 7); + CHECK_EQ(set.get(a).tag, 3); +} +TEST(sparse_set_remove_uses_swap_and_pop_and_keeps_others_valid) { + SparseSet<int> set; + const Entity a = Entity::make(1, 1); + const Entity b = Entity::make(4, 1); + const Entity c = Entity::make(9, 1); + set.emplace(a, 10); + set.emplace(b, 20); + set.emplace(c, 30); + // Removing a middle element moves the last element into its dense slot. + CHECK(set.remove(a)); + CHECK(!set.remove(a)); // second removal is a no-op + CHECK(!set.has(a)); + CHECK(set.try_get(a) == nullptr); + CHECK_EQ(set.size(), 2u); + CHECK_EQ(set.get(b), 20); + CHECK_EQ(set.get(c), 30); + // Removing the last element works as well. + CHECK(set.remove(b)); + CHECK_EQ(set.size(), 1u); + CHECK_EQ(set.get(c), 30); + // Removing the only remaining element leaves the set empty. + CHECK(set.remove(c)); + CHECK(set.empty()); +} +TEST(sparse_set_rejects_stale_generation_and_null_handles) { + SparseSet<int> set; + const Entity v1 = Entity::make(3, 1); + const Entity v2 = Entity::make(3, 2); + set.emplace(v1, 123); + CHECK(!set.has(Entity::null())); + CHECK(!set.has(v2)); + CHECK(set.try_get(v2) == nullptr); + CHECK(!set.remove(v2)); + CHECK_EQ(set.get(v1), 123); + // After removing v1, the same index with a new generation can be inserted. + CHECK(set.remove(v1)); + set.emplace(v2, 456); + CHECK(!set.has(v1)); + CHECK(set.has(v2)); + CHECK_EQ(set.get(v2), 456); +} +TEST(sparse_set_clear_empties_all_entries) { + SparseSet<int> set; + const Entity a = Entity::make(2, 1); + const Entity b = Entity::make(5, 1); + set.emplace(a, 1); + set.emplace(b, 2); + set.clear(); + CHECK(set.empty()); + CHECK(!set.has(a)); + CHECK(!set.has(b)); + set.emplace(a, 9); + CHECK_EQ(set.size(), 1u); + CHECK_EQ(set.get(a), 9); +}
