A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
refactor(ecs): collapse to one component store, delete dead Schema/Dynamic (RC2)
esengine9b8285943d43
diff --git a/docs/REARCHITECTURE.md b/docs/REARCHITECTURE.mdindex 4b17431aa..7f02c3f68 100644--- a/docs/REARCHITECTURE.md+++ b/docs/REARCHITECTURE.md@@ -132,5 +132,11 @@### 验证能力(已确认可用)本机**存在原生 C++ 工具链**:VS Build Tools(`D:\VisualStudioBuildTools`,cl.exe 14.50)+ ninja + cmake,doctest 已 vendored,glm 子模块已初始化。被改的 ECS/事件/服务/资源代码均为 header-only,可用独立 harness 直接编译+运行验证(如 RC4 所做)。完整 `esengine` 静态库的原生构建还需更多子模块/native 依赖(glfw/glad/box2d/spine 等),属后续 CI 门禁范畴。**结论**:RC2/RC3/RC5 的 header-only 部分可在本机即时编译验证,不再是纯人工审阅。-### RC2 / RC3 / RC5 — 未开始-按执行顺序依次推进,全程在 RC1 的 `static_assert` + 握手护栏内进行,并尽量用独立 harness 即时编译验证。+### RC2 存储统一 — ✅ 已落地并**编译+运行验证**+- **调研推翻了"四套并行实现"的前提**:`DynamicComponentPool` 是**纯死代码**(全仓无引用);`SchemaComponentPool`/`SchemaRegistry` **几乎全死**(Registry 暴露 13 个包装,但只有 `getSchemaPoolVersion` 一个绑定有注册,且 SDK 侧零调用);唯一活着的存储是 typed `SparseSet<T>`,而 JS 零拷贝**早已直接读 typed 存储的指针**(`getXxxPtr` 返回 `tryGet<T>()` 的 `T*`,按 keystone 偏移读 HEAP)。+- 故根治改为**靠删除而非改造**:删 `DynamicComponent.hpp`、`SchemaComponent.hpp`;从 Registry 移除 `schemaRegistry_`、13 个 schema 包装、destroy 里的 schema 清理(销毁路径现为纯 mask 驱动的单一路径);移除死绑定 `registry_getSchemaPoolVersion`(C++ impl/decl/注册 + `wasm.ts` 声明)。存储实现数 **3 → 1**,零 UB 风险(typed `std::vector<T>` 本就正确处理非平凡组件)。+- `SparseSet` 新增 `version()`:在组件缓冲**重分配**(emplace 扩容)、**relocate**(remove swap-pop、sort/rebuildSparse)时自增——作为 RC3 跨界指针失效守卫的**单一来源**,取代已删除的 `SchemaComponentPool::poolVersion`(后者还漏了 remove 时不自增的 bug)。+- **验证**:native MSVC harness 编译+运行通过(version() 在 fill/remove/clear 后均自增;destroy 后回收的实体无残留组件);SDK typecheck + 2012 测试全过。++### RC3 / RC5 — 未开始+按执行顺序依次推进,全程在 RC1 的 `static_assert` + 握手护栏内进行,并尽量用独立 harness 即时编译验证。RC3 第一件事就是把 `getXxxPtr` 的失效守卫接到 RC2 新增的 `SparseSet::version()` 上。diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex dd6902b88..7e48bd470 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -292,7 +292,6 @@ export interface ESEngineModule {registry_getCameraEntities(registry: CppRegistry): number[];getChildEntities(registry: CppRegistry, entity: number): number[];registry_getGeneration(registry: CppRegistry, entity: number): number;- registry_getSchemaPoolVersion(registry: CppRegistry, poolId: number): number;registry_batchSyncPhysicsTransforms(registry: CppRegistry, bufferPtr: number, count: number, ppu: number): void;// GL Debug APIdiff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cppindex c05f2ab5a..371b825b7 100644--- a/src/esengine/bindings/RendererBindings.cpp+++ b/src/esengine/bindings/RendererBindings.cpp@@ -740,10 +740,6 @@ u32 registry_getGeneration(ecs::Registry& registry, u32 entity) {return Entity::fromRaw(entity).generation();}-u32 registry_getSchemaPoolVersion(ecs::Registry& registry, u32 poolId) {- return registry.getSchemaPoolVersion(poolId);-}-void registry_batchSyncPhysicsTransforms(ecs::Registry& registry, uintptr_t bufferPtr, int count, float ppu) {const float* buffer = reinterpret_cast<const float*>(bufferPtr);for (int i = 0; i < count; i++) {diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hppindex f1d0710d3..79cee3f3a 100644--- a/src/esengine/bindings/RendererBindings.hpp+++ b/src/esengine/bindings/RendererBindings.hpp@@ -149,7 +149,6 @@ i32 registry_getCanvasEntity(ecs::Registry& registry);emscripten::val registry_getCameraEntities(ecs::Registry& registry);emscripten::val getChildEntities(ecs::Registry& registry, u32 entity);u32 registry_getGeneration(ecs::Registry& registry, u32 entity);-u32 registry_getSchemaPoolVersion(ecs::Registry& registry, u32 poolId);void registry_batchSyncPhysicsTransforms(ecs::Registry& registry, uintptr_t bufferPtr, int count, float ppu);} // namespace esenginediff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex 6af3ede14..1cdc3c4c7 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -494,7 +494,6 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {emscripten::function("registry_getCameraEntities", &esengine::registry_getCameraEntities);emscripten::function("getChildEntities", &esengine::getChildEntities);emscripten::function("registry_getGeneration", &esengine::registry_getGeneration);- emscripten::function("registry_getSchemaPoolVersion", &esengine::registry_getSchemaPoolVersion);emscripten::function("registry_batchSyncPhysicsTransforms", &esengine::registry_batchSyncPhysicsTransforms);emscripten::function("gl_enableErrorCheck", &esengine::gl_enableErrorCheck);diff --git a/src/esengine/ecs/DynamicComponent.hpp b/src/esengine/ecs/DynamicComponent.hppdeleted file mode 100644index 93aee97a4..000000000--- a/src/esengine/ecs/DynamicComponent.hpp+++ /dev/null@@ -1,328 +0,0 @@-/**- * @file DynamicComponent.hpp- * @brief Dynamic component storage for script-defined components- * @details Provides type-erased component storage that allows TypeScript- * to define and use custom components without C++ compile-time types.- *- * @author ESEngine Team- * @date 2026- *- * @copyright Copyright (c) 2026 ESEngine Team- * Licensed under the MIT License.- */-#pragma once--// =============================================================================-// Includes-// =============================================================================--#include "../core/Types.hpp"-#include "Entity.hpp"-#include "SparseSet.hpp"--#include <any>-#include <string>-#include <unordered_map>-#include <vector>--#ifdef ES_PLATFORM_WEB-#include <emscripten/val.h>-#endif--namespace esengine::ecs {--// =============================================================================-// DynamicValue-// =============================================================================--#ifdef ES_PLATFORM_WEB-using DynamicValue = emscripten::val;-#else-using DynamicValue = std::any;-#endif--// =============================================================================-// DynamicComponentPool-// =============================================================================--/**- * @brief Storage for a single dynamic component type- *- * @details Uses SparseSet-like storage to efficiently store script-defined- * component data. On Web platform, stores emscripten::val directly- * to minimize JS/C++ boundary crossing overhead.- */-class DynamicComponentPool {-public:- DynamicComponentPool() = default;- ~DynamicComponentPool() = default;-- DynamicComponentPool(const DynamicComponentPool&) = delete;- DynamicComponentPool& operator=(const DynamicComponentPool&) = delete;- DynamicComponentPool(DynamicComponentPool&&) noexcept = default;- DynamicComponentPool& operator=(DynamicComponentPool&&) noexcept = default;-- // =========================================================================- // Lookup Operations- // =========================================================================-- /** @brief Checks if entity has this component */- bool contains(Entity entity) const {- const u32 idx = entity.index();- return idx < sparse_.size() &&- sparse_[idx] < dense_.size() &&- dense_[sparse_[idx]] == entity;- }-- /** @brief Gets component data (must exist) */- DynamicValue& get(Entity entity) {- ES_ASSERT(contains(entity), "Entity does not have component");- return values_[sparse_[entity.index()]];- }-- /** @brief Gets component data (const) */- const DynamicValue& get(Entity entity) const {- ES_ASSERT(contains(entity), "Entity does not have component");- return values_[sparse_[entity.index()]];- }-- /** @brief Tries to get component data (returns nullptr if not found) */- DynamicValue* tryGet(Entity entity) {- if (!contains(entity)) return nullptr;- return &values_[sparse_[entity.index()]];- }-- // =========================================================================- // Modification Operations- // =========================================================================-- /** @brief Adds component data to entity */- void emplace(Entity entity, DynamicValue value) {- ES_ASSERT(!contains(entity), "Entity already has component");-- const u32 idx = entity.index();- if (idx >= sparse_.size()) {- sparse_.resize(idx + 1, INVALID_DENSE_INDEX);- }-- sparse_[idx] = static_cast<u32>(dense_.size());- dense_.push_back(entity);- values_.push_back(std::move(value));- }-- /** @brief Adds or replaces component data */- void emplaceOrReplace(Entity entity, DynamicValue value) {- if (contains(entity)) {- values_[sparse_[entity.index()]] = std::move(value);- } else {- emplace(entity, std::move(value));- }- }-- /** @brief Removes component from entity */- void remove(Entity entity) {- if (!contains(entity)) return;-- const u32 idx = entity.index();- const Entity last = dense_.back();- const u32 denseIdx = sparse_[idx];-- dense_[denseIdx] = last;- std::swap(values_[denseIdx], values_.back());- ES_ASSERT(last.index() < sparse_.size(),- "DynamicComponentPool sparse/dense out of sync");- if (last.index() < sparse_.size()) {- sparse_[last.index()] = denseIdx;- }-- dense_.pop_back();- values_.pop_back();- sparse_[idx] = INVALID_DENSE_INDEX;- }-- // =========================================================================- // Container Operations- // =========================================================================-- usize size() const { return dense_.size(); }- bool empty() const { return dense_.empty(); }-- void clear() {- sparse_.clear();- dense_.clear();- values_.clear();- }-- const std::vector<Entity>& entities() const { return dense_; }--private:- std::vector<u32> sparse_; ///< Entity index -> dense index- std::vector<Entity> dense_; ///< Dense entity array (packed entities)- std::vector<DynamicValue> values_;-};--// =============================================================================-// DynamicComponentRegistry-// =============================================================================--/**- * @brief Manages all dynamic component pools- *- * @details Provides a central registry for script-defined components,- * allowing TypeScript to create and manage components by name- * without requiring C++ type definitions.- */-class DynamicComponentRegistry {-public:- DynamicComponentRegistry() = default;- ~DynamicComponentRegistry() = default;-- // =========================================================================- // Component Type Registration- // =========================================================================-- /**- * @brief Registers a new dynamic component type- * @param name Unique name for the component type- * @return Component type ID for fast lookup- */- u32 registerComponent(const std::string& name) {- auto it = nameToId_.find(name);- if (it != nameToId_.end()) {- return it->second;- }-- u32 id = static_cast<u32>(pools_.size());- pools_.emplace_back();- nameToId_[name] = id;- idToName_[id] = name;- return id;- }-- /** @brief Gets component ID by name (returns INVALID_DENSE_INDEX if not found) */- u32 getComponentId(const std::string& name) const {- auto it = nameToId_.find(name);- return it != nameToId_.end() ? it->second : INVALID_DENSE_INDEX;- }-- /** @brief Gets component name by ID */- const std::string& getComponentName(u32 id) const {- static const std::string empty;- auto it = idToName_.find(id);- return it != idToName_.end() ? it->second : empty;- }-- /** @brief Checks if component type is registered */- bool isRegistered(const std::string& name) const {- return nameToId_.find(name) != nameToId_.end();- }-- // =========================================================================- // Component Operations (by ID)- // =========================================================================-- bool has(Entity entity, u32 componentId) const {- if (componentId >= pools_.size()) return false;- return pools_[componentId].contains(entity);- }-- DynamicValue& get(Entity entity, u32 componentId) {- ES_ASSERT(componentId < pools_.size(), "Invalid component ID");- return pools_[componentId].get(entity);- }-- const DynamicValue& get(Entity entity, u32 componentId) const {- ES_ASSERT(componentId < pools_.size(), "Invalid component ID");- return pools_[componentId].get(entity);- }-- void add(Entity entity, u32 componentId, DynamicValue value) {- ES_ASSERT(componentId < pools_.size(), "Invalid component ID");- pools_[componentId].emplaceOrReplace(entity, std::move(value));- }-- void remove(Entity entity, u32 componentId) {- if (componentId < pools_.size()) {- pools_[componentId].remove(entity);- }- }-- // =========================================================================- // Component Operations (by name)- // =========================================================================-- bool hasByName(Entity entity, const std::string& name) const {- u32 id = getComponentId(name);- return id != INVALID_DENSE_INDEX && has(entity, id);- }-- DynamicValue* getByName(Entity entity, const std::string& name) {- u32 id = getComponentId(name);- if (id == INVALID_DENSE_INDEX) return nullptr;- return pools_[id].tryGet(entity);- }-- void addByName(Entity entity, const std::string& name, DynamicValue value) {- u32 id = registerComponent(name);- pools_[id].emplaceOrReplace(entity, std::move(value));- }-- void removeByName(Entity entity, const std::string& name) {- u32 id = getComponentId(name);- if (id != INVALID_DENSE_INDEX) {- pools_[id].remove(entity);- }- }-- // =========================================================================- // Entity Operations- // =========================================================================-- /** @brief Removes all dynamic components from entity */- void removeAll(Entity entity) {- for (auto& pool : pools_) {- pool.remove(entity);- }- }-- // =========================================================================- // Query Operations- // =========================================================================-- /** @brief Gets all entities with a specific dynamic component */- const std::vector<Entity>& entitiesWith(u32 componentId) const {- static const std::vector<Entity> empty;- if (componentId >= pools_.size()) return empty;- return pools_[componentId].entities();- }-- /** @brief Gets pool for direct access */- DynamicComponentPool* getPool(u32 componentId) {- if (componentId >= pools_.size()) return nullptr;- return &pools_[componentId];- }-- const DynamicComponentPool* getPool(u32 componentId) const {- if (componentId >= pools_.size()) return nullptr;- return &pools_[componentId];- }-- // =========================================================================- // Utility- // =========================================================================-- void clear() {- for (auto& pool : pools_) {- pool.clear();- }- }-- usize componentTypeCount() const { return pools_.size(); }--private:- std::vector<DynamicComponentPool> pools_;- std::unordered_map<std::string, u32> nameToId_;- std::unordered_map<u32, std::string> idToName_;-};--} // namespace esengine::ecsdiff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hppindex 0ecec9307..53f7b9d55 100644--- a/src/esengine/ecs/Registry.hpp+++ b/src/esengine/ecs/Registry.hpp@@ -22,7 +22,6 @@#include "../core/Types.hpp"#include "ComponentMask.hpp"#include "Entity.hpp"-#include "SchemaComponent.hpp"#include "SparseSet.hpp"#include "View.hpp"@@ -159,8 +158,6 @@ public:}});- schemaRegistry_.removeAll(entity);-component_masks_[idx].reset();entityValid_[idx] = false;--entity_count_;@@ -507,65 +504,6 @@ public:pool->rebuildSparse();}- // =========================================================================- // Schema Component Management (Script-defined, direct memory access)- // =========================================================================-- /** @brief Registers a schema component pool */- u32 registerSchemaPool(const std::string& name, u32 stride) {- return schemaRegistry_.registerPool(name, stride);- }-- /** @brief Gets schema pool ID by name */- u32 getSchemaPoolId(const std::string& name) const {- return schemaRegistry_.getPoolId(name);- }-- /** @brief Adds schema component to entity, returns byte offset */- u32 addSchemaComponent(u32 poolId, Entity entity) {- ES_ASSERT(valid(entity), "Invalid entity");- return schemaRegistry_.addComponent(poolId, entity);- }-- /** @brief Checks if entity has schema component */- bool hasSchemaComponent(u32 poolId, Entity entity) const {- return schemaRegistry_.hasComponent(poolId, entity);- }-- /** @brief Gets byte offset of entity's schema component */- u32 getSchemaComponentOffset(u32 poolId, Entity entity) const {- return schemaRegistry_.getComponentOffset(poolId, entity);- }-- /** @brief Removes schema component from entity */- void removeSchemaComponent(u32 poolId, Entity entity) {- schemaRegistry_.removeComponent(poolId, entity);- }-- /** @brief Gets base pointer for schema pool (for JS direct access) */- uintptr_t getSchemaPoolBasePtr(u32 poolId) const {- return schemaRegistry_.getPoolBasePtr(poolId);- }-- /** @brief Gets stride for schema pool */- u32 getSchemaPoolStride(u32 poolId) const {- return schemaRegistry_.getPoolStride(poolId);- }-- /** @brief Gets schema pool version (detects reallocation) */- u32 getSchemaPoolVersion(u32 poolId) const {- return schemaRegistry_.getPoolVersion(poolId);- }-- /** @brief Gets entities with schema component */- const std::vector<Entity>& getSchemaEntities(u32 poolId) const {- return schemaRegistry_.getEntities(poolId);- }-- /** @brief Gets the schema registry */- SchemaRegistry& schemaRegistry() { return schemaRegistry_; }- const SchemaRegistry& schemaRegistry() const { return schemaRegistry_; }-private:// =========================================================================// Private Helpers@@ -639,9 +577,6 @@ private:/** @brief Type-erased component pools indexed by TypeId */std::vector<Unique<SparseSetBase>> pools_;- /** @brief Schema component registry for script-defined components */- SchemaRegistry schemaRegistry_;-struct DestroyEntry {u32 id;DestroyCallback callback;diff --git a/src/esengine/ecs/SchemaComponent.hpp b/src/esengine/ecs/SchemaComponent.hppdeleted file mode 100644index 13ebf3a0d..000000000--- a/src/esengine/ecs/SchemaComponent.hpp+++ /dev/null@@ -1,325 +0,0 @@-/**- * @file SchemaComponent.hpp- * @brief Schema-based component storage with direct memory access- * @details Provides zero-copy component access from TypeScript by storing- * component data in WASM linear memory with a defined layout.- *- * @author ESEngine Team- * @date 2026- *- * @copyright Copyright (c) 2026 ESEngine Team- * Licensed under the MIT License.- */-#pragma once--// =============================================================================-// Includes-// =============================================================================--#include "../core/Types.hpp"-#include "Entity.hpp"--#include <cstring>-#include <string>-#include <unordered_map>-#include <vector>--namespace esengine::ecs {--// =============================================================================-// SchemaComponentPool-// =============================================================================--/**- * @brief Component pool with fixed-stride memory layout for direct JS access- *- * @details Stores component data in a contiguous memory block that can be- * directly accessed from TypeScript via WASM HEAP. Each component- * occupies exactly `stride` bytes.- *- * Memory layout:- * ┌────────────┬────────────┬────────────┬─────┐- * │ Component0 │ Component1 │ Component2 │ ... │- * └────────────┴────────────┴────────────┴─────┘- * │<- stride ->│- */-class SchemaComponentPool {-public:- explicit SchemaComponentPool(u32 stride, u32 initialCapacity = 64)- : stride_(stride) {- ES_ASSERT(stride > 0, "stride must be > 0");- data_.reserve(initialCapacity * stride);- }-- ~SchemaComponentPool() = default;-- SchemaComponentPool(const SchemaComponentPool&) = delete;- SchemaComponentPool& operator=(const SchemaComponentPool&) = delete;- SchemaComponentPool(SchemaComponentPool&&) noexcept = default;- SchemaComponentPool& operator=(SchemaComponentPool&&) noexcept = default;-- // =========================================================================- // Component Operations- // =========================================================================-- /**- * @brief Adds a component to an entity- * @param entity The entity to add component to- * @return Byte offset of the component data in the pool- */- u32 add(Entity entity) {- if (contains(entity)) {- return getOffset(entity);- }-- const u32 idx = entity.index();- if (idx >= sparse_.size()) {- sparse_.resize(idx + 1, INVALID_DENSE_INDEX);- }-- u32 denseIdx = static_cast<u32>(dense_.size());- sparse_[idx] = denseIdx;- dense_.push_back(entity);-- usize oldSize = data_.size();- const u8* oldPtr = data_.data();- data_.resize(oldSize + stride_, 0);- if (data_.data() != oldPtr) {- pool_version_++;- }-- return static_cast<u32>(oldSize);- }-- /**- * @brief Gets the byte offset of an entity's component data- * @param entity The entity- * @return Byte offset in the data buffer- */- u32 getOffset(Entity entity) const {- ES_ASSERT(contains(entity), "Entity does not have component");- return sparse_[entity.index()] * stride_;- }-- /**- * @brief Checks if entity has this component- */- bool contains(Entity entity) const {- const u32 idx = entity.index();- return idx < sparse_.size() &&- sparse_[idx] < dense_.size() &&- dense_[sparse_[idx]] == entity;- }-- /**- * @brief Removes component from entity- */- void remove(Entity entity) {- if (!contains(entity)) return;-- const u32 idx = entity.index();- u32 denseIdx = sparse_[idx];- Entity lastEntity = dense_.back();- u32 lastDenseIdx = static_cast<u32>(dense_.size() - 1);-- if (denseIdx != lastDenseIdx) {- u8* dstPtr = data_.data() + denseIdx * stride_;- u8* srcPtr = data_.data() + lastDenseIdx * stride_;- std::memcpy(dstPtr, srcPtr, stride_);-- dense_[denseIdx] = lastEntity;- sparse_[lastEntity.index()] = denseIdx;- }-- dense_.pop_back();- data_.resize(data_.size() - stride_);- sparse_[idx] = INVALID_DENSE_INDEX;- }-- // =========================================================================- // Memory Access- // =========================================================================-- /**- * @brief Gets base pointer for direct memory access from JS- * @warning This pointer may be invalidated by add() if the internal- * vector reallocates. Check poolVersion() to detect changes.- */- uintptr_t basePtr() const {- return reinterpret_cast<uintptr_t>(data_.data());- }-- /** @brief Version counter incremented on each potential reallocation */- u32 poolVersion() const { return pool_version_; }-- /** @brief Gets the stride (bytes per component) */- u32 stride() const { return stride_; }-- /** @brief Gets number of components */- usize size() const { return dense_.size(); }-- /** @brief Gets entity at dense index */- Entity entityAt(usize index) const { return dense_[index]; }-- /** @brief Gets all entities */- const std::vector<Entity>& entities() const { return dense_; }-- /** @brief Clears all components */- void clear() {- sparse_.clear();- dense_.clear();- data_.clear();- }-- /**- * @brief Gets raw pointer to component data (for C++ access)- * @param entity The entity- * @return Pointer to component data- */- u8* getData(Entity entity) {- return data_.data() + getOffset(entity);- }-- const u8* getData(Entity entity) const {- return data_.data() + getOffset(entity);- }--private:- u32 stride_; ///< Bytes per component- u32 pool_version_ = 0; ///< Incremented on potential reallocation- std::vector<u8> data_; ///< Contiguous component data- std::vector<u32> sparse_; ///< Entity index -> dense index- std::vector<Entity> dense_; ///< Dense entity array (packed entities)-};--// =============================================================================-// SchemaRegistry-// =============================================================================--/**- * @brief Registry for schema-based component pools- */-class SchemaRegistry {-public:- SchemaRegistry() = default;- ~SchemaRegistry() = default;-- // =========================================================================- // Pool Management- // =========================================================================-- /**- * @brief Registers a new component type- * @param name Component type name- * @param stride Bytes per component- * @return Pool ID for fast access- */- u32 registerPool(const std::string& name, u32 stride) {- auto it = nameToId_.find(name);- if (it != nameToId_.end()) {- return it->second;- }-- u32 id = static_cast<u32>(pools_.size());- pools_.push_back(makeUnique<SchemaComponentPool>(stride));- nameToId_[name] = id;- idToName_[id] = name;- return id;- }-- /** @brief Gets pool ID by name */- u32 getPoolId(const std::string& name) const {- auto it = nameToId_.find(name);- return it != nameToId_.end() ? it->second : INVALID_DENSE_INDEX;- }-- /** @brief Gets pool by ID */- SchemaComponentPool* getPool(u32 id) {- return id < pools_.size() ? pools_[id].get() : nullptr;- }-- const SchemaComponentPool* getPool(u32 id) const {- return id < pools_.size() ? pools_[id].get() : nullptr;- }-- // =========================================================================- // Component Operations- // =========================================================================-- /**- * @brief Adds component to entity- * @return Byte offset in pool's data buffer- */- u32 addComponent(u32 poolId, Entity entity) {- ES_ASSERT(poolId < pools_.size(), "Invalid pool ID");- return pools_[poolId]->add(entity);- }-- bool hasComponent(u32 poolId, Entity entity) const {- if (poolId >= pools_.size()) return false;- return pools_[poolId]->contains(entity);- }-- u32 getComponentOffset(u32 poolId, Entity entity) const {- ES_ASSERT(poolId < pools_.size(), "Invalid pool ID");- return pools_[poolId]->getOffset(entity);- }-- void removeComponent(u32 poolId, Entity entity) {- if (poolId < pools_.size()) {- pools_[poolId]->remove(entity);- }- }-- /** @brief Gets base pointer for a pool */- uintptr_t getPoolBasePtr(u32 poolId) const {- if (poolId >= pools_.size()) return 0;- return pools_[poolId]->basePtr();- }-- /** @brief Gets stride for a pool */- u32 getPoolStride(u32 poolId) const {- if (poolId >= pools_.size()) return 0;- return pools_[poolId]->stride();- }-- /** @brief Gets pool version (incremented on reallocation) */- u32 getPoolVersion(u32 poolId) const {- if (poolId >= pools_.size()) return 0;- return pools_[poolId]->poolVersion();- }-- /** @brief Gets entities with component */- const std::vector<Entity>& getEntities(u32 poolId) const {- static const std::vector<Entity> empty;- if (poolId >= pools_.size()) return empty;- return pools_[poolId]->entities();- }-- // =========================================================================- // Entity Cleanup- // =========================================================================-- /** @brief Removes all components from an entity */- void removeAll(Entity entity) {- for (auto& pool : pools_) {- pool->remove(entity);- }- }-- /** @brief Clears all pools */- void clear() {- for (auto& pool : pools_) {- pool->clear();- }- }-- usize poolCount() const { return pools_.size(); }--private:- std::vector<Unique<SchemaComponentPool>> pools_;- std::unordered_map<std::string, u32> nameToId_;- std::unordered_map<u32, std::string> idToName_;-};--} // namespace esengine::ecsdiff --git a/src/esengine/ecs/SparseSet.hpp b/src/esengine/ecs/SparseSet.hppindex 007ec4a3b..c740d80a8 100644--- a/src/esengine/ecs/SparseSet.hpp+++ b/src/esengine/ecs/SparseSet.hpp@@ -80,6 +80,18 @@ public:* @return Const reference to the entity vector*/virtual const std::vector<Entity>& entities() const = 0;++ /**+ * @brief Monotonic version, bumped whenever stored components may have+ * moved in memory (buffer reallocation on growth, or swap-and-pop+ * relocation on removal).+ * @details Single source of truth for the cross-boundary pointer-staleness+ * guard: a raw component pointer handed to JS (e.g. getTransformPtr)+ * is only valid while this value is unchanged. Replaces the old+ * SchemaComponentPool::poolVersion (which lived in a now-deleted+ * parallel store and, notably, was not bumped on remove).+ */+ virtual u32 version() const = 0;};// =============================================================================@@ -251,7 +263,14 @@ public:(*pages_[pageIndex])[offset] = static_cast<u32>(dense_.size());dense_.push_back(entity);++ // Bump the version only when the component buffer actually reallocates+ // (base pointer moves) — that is exactly when previously-handed-out raw+ // pointers into components_ become stale. A non-reallocating append+ // leaves existing component addresses intact, so no bump is needed.+ const T* before = components_.data();components_.emplace_back(std::forward<Args>(args)...);+ if (components_.data() != before) ++version_;return components_.back();}@@ -267,6 +286,10 @@ public:void remove(Entity entity) override {if (!contains(entity)) return;+ // Swap-and-pop relocates the last component into the freed slot, so any+ // raw pointer previously handed out for the moved entity is now stale.+ ++version_;+const u32 idx = entity.index();const auto pageIndex = idx / SPARSE_PAGE_SIZE;const auto offset = idx % SPARSE_PAGE_SIZE;@@ -312,12 +335,19 @@ public:* @brief Removes all components*/void clear() override {+ ++version_;pages_.clear();dense_.clear();components_.clear();}+ /** @copydoc SparseSetBase::version() */+ u32 version() const override { return version_; }+void rebuildSparse() {+ // Called after Registry::sort permutes dense_/components_ in place —+ // component addresses changed, so any handed-out raw pointer is stale.+ ++version_;pages_.clear();for (usize i = 0; i < dense_.size(); ++i) {const u32 idx = dense_[i].index();@@ -426,6 +456,9 @@ private:* @details components_[i] belongs to entity dense_[i].*/std::vector<T> components_;++ /** @brief Pointer-staleness generation; see SparseSetBase::version(). */+ u32 version_ = 0;};} // namespace esengine::ecs