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): get() states a contract instead of fabricating a component
yhh794411305221
diff --git a/src/esengine/core/Log.hpp b/src/esengine/core/Log.hppindex f6be56969..2402838a7 100644--- a/src/esengine/core/Log.hpp+++ b/src/esengine/core/Log.hpp@@ -374,11 +374,15 @@ inline VerifyHook& verifyHook() {* indices, container subscripts). Reserve ES_ASSERT for pure-logic invariants* that cannot happen if the surrounding code is correct.*+ * @par Choosing between ES_VERIFY and ES_VERIFY_FATAL+ * ES_VERIFY needs a recovery that is TRUE — an existing element, a sentinel the+ * caller handles, a skipped iteration. Where the only "recovery" would be a+ * stand-in object the caller writes through, use ES_VERIFY_FATAL.+ ** @code- * T& get(u32 i) {- * static T fallback{};- * ES_VERIFY(i < size_, { fallback = T{}; return fallback; });- * return data_[i];+ * bool remove(u32 i) {+ * ES_VERIFY(i < size_, return false);+ * ...* }* @endcode*/diff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hppindex a0880aed4..10334e304 100644--- a/src/esengine/ecs/Registry.hpp+++ b/src/esengine/ecs/Registry.hpp@@ -33,6 +33,7 @@#include <any>#include <functional>#include <queue>+#include <string>namespace esengine::ecs {@@ -241,14 +242,14 @@ public:* @param args Arguments forwarded to T's constructor* @return Reference to the newly created component*- * @note Asserts if entity is invalid or already has the component+ * @note An invalid entity is fatal in every build; the component already+ * being there degrades to the existing one (see SparseSet::emplace).*/template<typename T, typename... Args>T& emplace(Entity entity, Args&&... args) {- // Release-safe: an invalid entity indexes component_masks_ out of bounds- // below (entity.index() of the invalid sentinel is 0xFFFFF), and- // ES_ASSERT is stripped in release -> OOB write. Degrade to a fallback.- ES_VERIFY(valid(entity), { static T fallback{}; fallback = T{}; return fallback; });+ // An invalid entity would index component_masks_ out of bounds below (the+ // sentinel's index() is the mask), and there is no component to hand back.+ ES_VERIFY_FATAL(valid(entity), invalidEntityMessage("emplace", entity));auto& pool = assurePool<T>();auto& result = pool.emplace(entity, std::forward<Args>(args)...);component_masks_[entity.index()].set(componentTypeId<T>());@@ -267,8 +268,7 @@ public:*/template<typename T, typename... Args>T& emplaceOrReplace(Entity entity, Args&&... args) {- // Release-safe: see emplace() — invalid entity -> OOB write on the mask.- ES_VERIFY(valid(entity), { static T fallback{}; fallback = T{}; return fallback; });+ ES_VERIFY_FATAL(valid(entity), invalidEntityMessage("emplaceOrReplace", entity));auto& pool = assurePool<T>();if (pool.contains(entity)) {@@ -306,31 +306,22 @@ public:* @param entity The target entity* @return Reference to the component*- * @note Asserts if the entity doesn't have the component+ * @note A missing component is fatal in every build — the contract is that the+ * caller knows it is there. Use tryGet() where absence is expected and+ * getOrEmplace() where the component should be created.*/template<typename T>T& get(Entity entity) {auto* pool = getPool<T>();- if (!pool) {- ES_LOG_ERROR("Registry::get: component pool does not exist (returning fallback)");- // Reset each miss so a write through a prior miss can't poison the- // shared static (see SparseSet::get). tryGet() is the checked path.- static T fallback{};- fallback = T{};- return fallback;- }- return pool->get(entity); // SparseSet::get is itself release-safe+ ES_VERIFY_FATAL(pool != nullptr, noPoolMessage(entity));+ return pool->get(entity); // itself fatal on a non-member}/** @copydoc get() */template<typename T>const T& get(Entity entity) const {auto* pool = getPool<T>();- if (!pool) {- ES_LOG_ERROR("Registry::get: component pool does not exist (returning fallback)");- static const T fallback{};- return fallback;- }+ ES_VERIFY_FATAL(pool != nullptr, noPoolMessage(entity));return pool->get(entity);}@@ -367,8 +358,7 @@ public:if (pool.contains(entity)) {return pool.get(entity);}- // Release-safe: see emplace() — invalid entity -> OOB write on the mask.- ES_VERIFY(valid(entity), { static T fallback{}; fallback = T{}; return fallback; });+ ES_VERIFY_FATAL(valid(entity), invalidEntityMessage("getOrEmplace", entity));auto& result = pool.emplace(entity, std::forward<Args>(args)...);component_masks_[entity.index()].set(componentTypeId<T>());return result;@@ -631,6 +621,17 @@ private:return static_cast<const SparseSet<T>*>(pools_[typeId].get());}+ /// Built only when a contract guard is about to abort; names what was asked.+ static std::string noPoolMessage(Entity entity) {+ return "Registry::get: no pool for this component type (entity "+ + std::to_string(entity.index()) + ":" + std::to_string(entity.generation())+ + "); use tryGet() when absence is expected";+ }+ static std::string invalidEntityMessage(const char* op, Entity entity) {+ return std::string("Registry::") + op + " on an invalid entity ("+ + std::to_string(entity.index()) + ":" + std::to_string(entity.generation()) + ")";+ }+/*** @brief Activates an entity index: resizes arrays, bumps generation, returns packed Entity*/diff --git a/src/esengine/ecs/SparseSet.hpp b/src/esengine/ecs/SparseSet.hppindex fba4d0758..6b11540b6 100644--- a/src/esengine/ecs/SparseSet.hpp+++ b/src/esengine/ecs/SparseSet.hpp@@ -28,6 +28,7 @@#include <algorithm>#include <array>#include <memory>+#include <string>#include <vector>namespace esengine::ecs {@@ -208,35 +209,20 @@ public:* @param entity The entity* @return Reference to the component*- * @note Asserts if the entity doesn't have a component+ * @note A miss is fatal in every build: there is no valid `T&` to return, and+ * a stand-in would be written through silently. tryGet() is the checked+ * path, getUnchecked() the one for callers that proved membership.*/T& get(Entity entity) {- // Release-safe bounds check (ES_ASSERT is stripped in release builds).- // On a miss, log and return a fallback rather than read- // components_[INVALID_INDEX] out of bounds. Callers that have already- // proven membership should use getUnchecked() for the no-branch path.- u32 di = denseIndexOf(entity);- if (di == INVALID_INDEX || dense_[di] != entity) {- ES_LOG_ERROR("SparseSet::get on an entity without this component (returning fallback)");- // Reset on every miss: get<T> is sometimes used as a writable accessor,- // so without this a caller writing through one miss would poison the- // shared static for the next miss. (A missing-component get is a logic- // error upstream; tryGet() is the checked, non-polluting alternative.)- static T fallback{};- fallback = T{};- return fallback;- }+ const u32 di = denseIndexOf(entity);+ ES_VERIFY_FATAL(di != INVALID_INDEX && dense_[di] == entity, missMessage(entity));return components_[di];}/** @copydoc get() */const T& get(Entity entity) const {- u32 di = denseIndexOf(entity);- if (di == INVALID_INDEX || dense_[di] != entity) {- ES_LOG_ERROR("SparseSet::get on an entity without this component (returning fallback)");- static const T fallback{};- return fallback;- }+ const u32 di = denseIndexOf(entity);+ ES_VERIFY_FATAL(di != INVALID_INDEX && dense_[di] == entity, missMessage(entity));return components_[di];}@@ -510,6 +496,13 @@ public:}private:+ /// Built only when get() is about to abort, so it names the entity asked for.+ static std::string missMessage(Entity entity) {+ return "SparseSet::get on an entity without this component (entity "+ + std::to_string(entity.index()) + ":" + std::to_string(entity.generation())+ + "); use tryGet() when absence is expected";+ }+/*** @brief Looks up the dense array index for an entity* @return Dense index, or INVALID_INDEX if page not allocateddiff --git a/tests/ecs/test_registry_safety.cpp b/tests/ecs/test_registry_safety.cppindex f38032008..42a116376 100644--- a/tests/ecs/test_registry_safety.cpp+++ b/tests/ecs/test_registry_safety.cpp@@ -19,7 +19,7 @@ using esengine::u32;using esengine::ecs::Registry;namespace {-struct Pos { float x = 1.0f; float y = 2.0f; }; // fallback{} has x=1, y=2+struct Pos { float x = 1.0f; float y = 2.0f; };struct Vel { float dx = 0.0f; };}@@ -30,42 +30,36 @@ static int g_failures = 0;else { std::printf("ok: %s\n", msg); } \} while (0)-// Counts ES_VERIFY failures so tests can assert "the guard fired and we-// degraded gracefully" rather than just "it didn't crash".+// Counts ES_VERIFY failures so tests can assert "the guard fired and the+// recovery is the real value" rather than just "it didn't crash".static int g_verifyHits = 0;static void countingVerifyHook(const char*, const char*, int) { ++g_verifyHits; }int main() {- // --- A6: get<T> on an entity without the component returns fallback (no OOB) ---+ // --- get<T> has a contract; absence goes through the checked API ---+ // A miss aborts, so absence is asked with has/tryGet and created with+ // getOrEmplace — the three doors, each exercised below.{Registry r;Entity e = r.create();r.emplace<Pos>(e, Pos{10.0f, 20.0f});CHECK(r.get<Pos>(e).x == 10.0f, "get returns the real component when present");+ CHECK(r.tryGet<Pos>(e) == &r.get<Pos>(e), "tryGet points at the same component");- // Pool exists, but this entity is not a member -> SparseSet::get fallback.+ // Pool exists, but this entity is not a member.Entity other = r.create();- Pos& p = r.get<Pos>(other);- CHECK(p.x == 1.0f && p.y == 2.0f, "get<Pos> on non-member returns fallback defaults (no OOB)");+ CHECK(!r.has<Pos>(other), "has<Pos> is false for a non-member");+ CHECK(r.tryGet<Pos>(other) == nullptr, "tryGet<Pos> on a non-member is null");- // Pool does not exist at all -> Registry::get fallback.- Vel& v = r.get<Vel>(e);- CHECK(v.dx == 0.0f, "get<Vel> with no Vel pool returns fallback (no OOB)");- }+ // Pool does not exist at all.+ CHECK(!r.has<Vel>(e), "has<Vel> is false with no Vel pool");+ CHECK(r.tryGet<Vel>(e) == nullptr, "tryGet<Vel> with no Vel pool is null");- // --- A6b: writing through a missing-component get must not poison later misses ---- // Review finding: the static fallback is shared, so a write through one miss used- // to corrupt the value returned to the next miss. Reset-on-miss must prevent that.- {- Registry r;- Entity owner = r.create();- r.emplace<Pos>(owner, Pos{5.0f, 5.0f}); // creates the Pos pool- Entity a = r.create();- Entity b = r.create();- r.get<Pos>(a).x = 999.0f; // write through a's fallback (a has no Pos)- CHECK(r.get<Pos>(b).x == 1.0f, "SparseSet::get fallback reset between misses (no pollution)");- CHECK(r.get<Pos>(owner).x == 5.0f, "real component unaffected by fallback writes");+ // getOrEmplace is the third door: create it rather than assume or check.+ Vel& v = r.getOrEmplace<Vel>(e, Vel{3.0f});+ CHECK(v.dx == 3.0f && r.has<Vel>(e), "getOrEmplace creates the missing component");+ CHECK(&r.getOrEmplace<Vel>(e) == &v, "getOrEmplace returns the existing one on the next call");}// --- A7: re-entrant destroy(entity) from onDestroy must not double-teardown ---@@ -115,24 +109,15 @@ int main() {CHECK(hits == 1, "callback no longer fires once the Connection is destroyed");}- // --- ES_VERIFY: emplace / emplaceOrReplace on an invalid entity is release-safe ---- // Without the guard, component_masks_[Entity{}.index() == 0xFFFFF] is an OOB- // write (ES_ASSERT is stripped here). The guard must fire and return a fallback.+ // emplace on an invalid entity would write component_masks_[sentinel] out of+ // bounds and has no component to return: fatal, not a fallback. valid() is+ // how a caller asks beforehand; the abort itself is not exercised here.{- esengine::detail::verifyHook() = countingVerifyHook;Registry r;-- g_verifyHits = 0;- Pos& p = r.emplace<Pos>(Entity{}, Pos{7.0f, 8.0f});- CHECK(g_verifyHits == 1, "emplace(invalid) fires the verify hook");- CHECK(p.x == 1.0f && p.y == 2.0f, "emplace(invalid) returns fallback defaults (no OOB write)");-- g_verifyHits = 0;- Pos& p2 = r.emplaceOrReplace<Pos>(Entity{}, Pos{9.0f, 9.0f});- CHECK(g_verifyHits == 1, "emplaceOrReplace(invalid) fires the verify hook");- CHECK(p2.x == 1.0f, "emplaceOrReplace(invalid) returns fallback (no OOB write)");-- esengine::detail::verifyHook() = nullptr;+ CHECK(!r.valid(Entity{}), "the invalid sentinel does not pass valid()");+ Entity e = r.create();+ r.destroy(e);+ CHECK(!r.valid(e), "a destroyed entity does not pass valid()");}// --- ES_VERIFY: restore() with an over-range (deserialized) index is refused ---