Skip to content

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.

fix(engine): Phase 2/3 callback, cancel, hot-reload, scene cleanup

esenginec3ca7597caba
diff --git a/sdk/src/sceneManager.ts b/sdk/src/sceneManager.ts
index 7fe839c75..c1e342bbc 100644
--- a/sdk/src/sceneManager.ts
+++ b/sdk/src/sceneManager.ts
@@ -77,6 +77,7 @@ class SceneInstance {
readonly drawCallbacks = new Map<string, DrawCallback>();
readonly postProcessBindings = new Map<Entity, PostProcessStack>();
readonly savedEnabled = new Map<Entity, Map<AnyComponentDef, boolean>>();
+ readonly systemIds: symbol[] = [];
loadedTextures: Set<string> | null = null;
loadedMaterials: Set<number> | null = null;
loadedFonts: Set<string> | null = null;
@@ -392,6 +393,11 @@ export class SceneManagerState {
}
instance.drawCallbacks.clear();
+ for (const id of instance.systemIds) {
+ this.app_.removeSystem(id);
+ }
+ instance.systemIds.length = 0;
+
for (const camera of instance.postProcessBindings.keys()) {
PostProcess.unbind(camera);
}
@@ -463,6 +469,7 @@ export class SceneManagerState {
for (const { schedule, system } of config.systems) {
const wrapped = wrapSceneSystem(this.app_, name, system);
this.app_.addSystemToSchedule(schedule, wrapped);
+ instance.systemIds.push(wrapped._id);
}
}
diff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hpp
index de7c495f7..5012e35e0 100644
--- a/src/esengine/ecs/Registry.hpp
+++ b/src/esengine/ecs/Registry.hpp
@@ -27,6 +27,7 @@
#include "View.hpp"
// Standard library
+#include <algorithm>
#include <any>
#include <functional>
#include <queue>
@@ -139,8 +140,17 @@ public:
const u32 idx = entity.index();
- for (auto& entry : on_destroy_entries_) {
- entry.callback(entity);
+ ++firing_destroy_;
+ for (usize i = 0; i < on_destroy_entries_.size(); ++i) {
+ if (on_destroy_entries_[i].dead) continue;
+ on_destroy_entries_[i].callback(entity);
+ }
+ --firing_destroy_;
+ if (firing_destroy_ == 0) {
+ on_destroy_entries_.erase(
+ std::remove_if(on_destroy_entries_.begin(), on_destroy_entries_.end(),
+ [](const DestroyEntry& e) { return e.dead; }),
+ on_destroy_entries_.end());
}
component_masks_[idx].forEachSet([&](u32 bit) {
@@ -163,15 +173,20 @@ public:
u32 onDestroy(DestroyCallback callback) {
u32 id = next_callback_id_++;
- on_destroy_entries_.push_back({id, std::move(callback)});
+ on_destroy_entries_.push_back({id, std::move(callback), false});
return id;
}
void removeOnDestroy(u32 callbackId) {
- for (usize i = 0; i < on_destroy_entries_.size(); ++i) {
- if (on_destroy_entries_[i].id == callbackId) {
- auto pos = static_cast<std::ptrdiff_t>(i);
- on_destroy_entries_.erase(on_destroy_entries_.begin() + pos);
+ for (auto& entry : on_destroy_entries_) {
+ if (entry.id == callbackId) {
+ entry.dead = true;
+ if (firing_destroy_ == 0) {
+ on_destroy_entries_.erase(
+ std::remove_if(on_destroy_entries_.begin(), on_destroy_entries_.end(),
+ [](const DestroyEntry& e) { return e.dead; }),
+ on_destroy_entries_.end());
+ }
return;
}
}
@@ -630,10 +645,12 @@ private:
struct DestroyEntry {
u32 id;
DestroyCallback callback;
+ bool dead;
};
std::vector<DestroyEntry> on_destroy_entries_;
u32 next_callback_id_ = 0;
+ u32 firing_destroy_ = 0;
};
} // namespace esengine::ecs
diff --git a/src/esengine/resource/HotReloadManager.cpp b/src/esengine/resource/HotReloadManager.cpp
index 58a2e3a45..6b123aa7c 100644
--- a/src/esengine/resource/HotReloadManager.cpp
+++ b/src/esengine/resource/HotReloadManager.cpp
@@ -13,6 +13,8 @@
#include "../core/Log.hpp"
#include "../core/RuntimeConfig.hpp"
+#include <vector>
+
namespace esengine::resource {
// =============================================================================
@@ -63,11 +65,19 @@ void HotReloadManager::update() {
return;
}
- std::unordered_set<std::string> reloadsToProcess;
+ std::vector<std::string> reloadsToProcess;
{
std::lock_guard<std::mutex> lock(mutex_);
- reloadsToProcess = std::move(pendingReloads_);
- pendingReloads_.clear();
+ const auto now = std::chrono::steady_clock::now();
+ const auto quietFor = std::chrono::milliseconds(debounce_ms_);
+ for (auto it = pendingReloads_.begin(); it != pendingReloads_.end(); ) {
+ if (now - it->second >= quietFor) {
+ reloadsToProcess.push_back(it->first);
+ it = pendingReloads_.erase(it);
+ } else {
+ ++it;
+ }
+ }
}
for (const auto& path : reloadsToProcess) {
@@ -132,7 +142,7 @@ bool HotReloadManager::isWatching(const std::string& path) const {
void HotReloadManager::onFileChanged(const std::string& path) {
std::lock_guard<std::mutex> lock(mutex_);
- pendingReloads_.insert(path);
+ pendingReloads_[path] = std::chrono::steady_clock::now();
}
} // namespace esengine::resource
diff --git a/src/esengine/resource/HotReloadManager.hpp b/src/esengine/resource/HotReloadManager.hpp
index 944c1ca54..e18d6455f 100644
--- a/src/esengine/resource/HotReloadManager.hpp
+++ b/src/esengine/resource/HotReloadManager.hpp
@@ -20,10 +20,10 @@
#include "../platform/FileSystem.hpp"
#include "Handle.hpp"
+#include <chrono>
#include <string>
#include <mutex>
#include <unordered_map>
-#include <unordered_set>
#include <functional>
#include <typeindex>
@@ -154,6 +154,10 @@ public:
*/
usize getWatchCount() const { return watchedFiles_.size(); }
+ /** Time window (ms) a file must be quiet for before reload fires. */
+ void setDebounceMs(u32 ms) { debounce_ms_ = ms; }
+ u32 getDebounceMs() const { return debounce_ms_; }
+
// =========================================================================
// Reload Signals
// =========================================================================
@@ -167,8 +171,9 @@ private:
bool enabled_ = false;
bool initialized_ = false;
+ u32 debounce_ms_ = 150;
std::unordered_map<std::string, WatchEntry> watchedFiles_;
- std::unordered_set<std::string> pendingReloads_;
+ std::unordered_map<std::string, std::chrono::steady_clock::time_point> pendingReloads_;
mutable std::mutex mutex_;
};
diff --git a/src/esengine/resource/LoaderJobQueue.cpp b/src/esengine/resource/LoaderJobQueue.cpp
index b38901133..9b3120144 100644
--- a/src/esengine/resource/LoaderJobQueue.cpp
+++ b/src/esengine/resource/LoaderJobQueue.cpp
@@ -213,12 +213,15 @@ void LoaderJobQueue::workerThread() {
}
}
+ bool cancelledDuringWork = false;
{
std::lock_guard<std::mutex> lock(activeJobsMutex_);
- activeJobIds_.erase(job.jobId);
+ if (activeJobIds_.erase(job.jobId) == 0) {
+ cancelledDuringWork = true;
+ }
}
- if (job.completeFn) {
+ if (!cancelledDuringWork && job.completeFn) {
std::lock_guard<std::mutex> lock(completionMutex_);
completions_.push(std::move(job.completeFn));
}
diff --git a/tests/ecs/test_registry.cpp b/tests/ecs/test_registry.cpp
index 3d2893653..54db0dde9 100644
--- a/tests/ecs/test_registry.cpp
+++ b/tests/ecs/test_registry.cpp
@@ -472,6 +472,34 @@ TEST_CASE("view_each tolerates mid-iteration remove of the current entity") {
CHECK_EQ(registry.view<test::Position>().sizeHint(), 0u);
}
+TEST_CASE("onDestroy callback can safely removeOnDestroy itself") {
+ esengine::ecs::Registry registry;
+ esengine::Entity e = registry.create();
+
+ bool other_fired = false;
+ u32 self_id = 0;
+ u32 self_fires = 0;
+
+ u32 other_id = registry.onDestroy([&](esengine::Entity) { other_fired = true; });
+ self_id = registry.onDestroy([&](esengine::Entity) {
+ ++self_fires;
+ registry.removeOnDestroy(self_id);
+ });
+
+ registry.destroy(e);
+
+ CHECK(other_fired);
+ CHECK_EQ(self_fires, 1u);
+
+ esengine::Entity e2 = registry.create();
+ other_fired = false;
+ registry.destroy(e2);
+ CHECK(other_fired);
+ CHECK_EQ(self_fires, 1u);
+
+ registry.removeOnDestroy(other_id);
+}
+
TEST_CASE("setParent is idempotent on duplicate reparent") {
esengine::ecs::Registry registry;
esengine::Entity parent = registry.create();