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: unify App framework, add ServiceRegistry, expand ComponentMask
esengine2c172883ae9a
diff --git a/CMakeLists.txt b/CMakeLists.txtindex a3d824dd4..dd140603c 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -34,7 +34,6 @@ add_subdirectory(third_party)# =============================================================================set(ESENGINE_SOURCES- src/esengine/core/Application.cppsrc/esengine/core/Engine.cppsrc/esengine/core/Log.cppsrc/esengine/app/App.cpp@@ -109,11 +108,12 @@ endif()set(ESENGINE_HEADERSsrc/esengine/ESEngine.hppsrc/esengine/core/Types.hpp- src/esengine/core/Application.hppsrc/esengine/core/Engine.hppsrc/esengine/core/Log.hppsrc/esengine/core/Reflection.hpp+ src/esengine/core/ServiceRegistry.hppsrc/esengine/ecs/Entity.hpp+ src/esengine/ecs/ComponentMask.hppsrc/esengine/ecs/Component.hppsrc/esengine/ecs/System.hppsrc/esengine/ecs/Registry.hppdiff --git a/src/esengine/ESEngine.hpp b/src/esengine/ESEngine.hppindex c20ff05b4..bf3cb8890 100644--- a/src/esengine/ESEngine.hpp+++ b/src/esengine/ESEngine.hpp@@ -21,7 +21,9 @@#include "core/Types.hpp"#include "core/Log.hpp"#include "core/Engine.hpp"-#include "core/Application.hpp"++// App Framework+#include "app/App.hpp"// Math#include "math/Math.hpp"@@ -67,35 +69,35 @@// =============================================================================/**- * @brief Application entry point macro- * @details Defines the appropriate entry point based on the target platform.- * - Web: Uses Emscripten exports for JavaScript interop- * - Native: Standard main() function+ * @brief Entry point macro for App-based applications*- * @param AppClass The user's Application-derived class+ * @param SetupFunc A function void(esengine::App&) that configures the App** @code- * class MyGame : public esengine::Application {- * void onInit() override { ... }- * void onUpdate(f32 dt) override { ... }- * };- * ES_MAIN(MyGame)+ * void setup(esengine::App& app) {+ * app.setConfig({.title = "My Game", .width = 1280, .height = 720});+ * app.addPlugin<MyPlugin>();+ * app.addSystem(esengine::Schedule::Update, myUpdateSystem);+ * }+ * ES_APP_MAIN(setup)* @endcode*/#ifdef ES_PLATFORM_WEB#include <emscripten.h>- #define ES_MAIN(AppClass) \+ #define ES_APP_MAIN(SetupFunc) \extern "C" { \EMSCRIPTEN_KEEPALIVE void es_app_init() { \- static AppClass app; \+ static esengine::App app; \+ SetupFunc(app); \app.run(); \} \}#else- #define ES_MAIN(AppClass) \+ #define ES_APP_MAIN(SetupFunc) \int main(int argc, char** argv) { \(void)argc; (void)argv; \- AppClass app; \+ esengine::App app; \+ SetupFunc(app); \app.run(); \return 0; \}diff --git a/src/esengine/app/App.cpp b/src/esengine/app/App.cppindex 8faf20930..18349ec3f 100644--- a/src/esengine/app/App.cpp+++ b/src/esengine/app/App.cpp@@ -11,6 +11,10 @@#include "App.hpp"#include "../core/Log.hpp"+#include "../platform/FileSystem.hpp"+#include "../ecs/components/Canvas.hpp"++#include <glm/gtc/matrix_transform.hpp>#ifdef ES_PLATFORM_WEB#include <emscripten.h>@@ -70,10 +74,39 @@ App& App::addStartupSystem(SystemFn system) {void App::init() {if (initialized_) return;+ Log::init();ES_LOG_INFO("App initializing...");+ FileSystem::init();+platform_ = Platform::create();- platform_->initialize(config_.width, config_.height);+ if (!platform_->initialize(config_.width, config_.height)) {+ ES_LOG_FATAL("Failed to initialize platform");+ return;+ }++ platform_->setTouchCallback([this](TouchType type, const TouchPoint& point) {+ input_.onTouchEvent(type, point);+ });++ platform_->setKeyCallback([this](KeyCode key, bool pressed) {+ input_.onKeyEvent(key, pressed);+ });++ platform_->setScrollCallback([this](f32 deltaX, f32 deltaY, f32 x, f32 y) {+ input_.onScrollEvent(deltaX, deltaY);+ (void)x; (void)y;+ });++ platform_->setResizeCallback([this](u32 width, u32 height) {+ config_.width = width;+ config_.height = height;+ if (renderer_) {+ renderer_->setViewport(0, 0, width, height);+ }+ });++ input_.init();resourceManager_.init();@@ -81,6 +114,13 @@ void App::init() {renderContext_->init();renderer_ = makeUnique<Renderer>(*renderContext_);+ renderer_->setViewport(0, 0, config_.width, config_.height);++ services_.registerService<ecs::Registry>(®istry_);+ services_.registerService<resource::ResourceManager>(&resourceManager_);+ services_.registerService<Input>(&input_);+ services_.registerService<RenderContext>(renderContext_.get());+ services_.registerService<Renderer>(renderer_.get());for (auto& plugin : plugins_) {plugin->build(*this);@@ -102,11 +142,20 @@ void App::shutdown() {resourceManager_.shutdown();+ registry_.clear();++ input_.shutdown();+platform_->shutdown();platform_.reset();+ services_.clear();++ FileSystem::shutdown();+initialized_ = false;ES_LOG_INFO("App shutdown complete");+ Log::shutdown();}void App::run() {@@ -166,10 +215,26 @@ void App::runFrame() {runSystems(Schedule::Update);runSystems(Schedule::PostUpdate);+ auto canvasView = registry_.view<ecs::Canvas>();+ if (!canvasView.empty()) {+ auto entity = *canvasView.begin();+ auto& canvas = registry_.get<ecs::Canvas>(entity);+ renderer_->setClearColor(canvas.backgroundColor);+ }+renderer_->beginFrame();+ renderer_->clear();++ f32 w = static_cast<f32>(config_.width);+ f32 h = static_cast<f32>(config_.height);+ glm::mat4 projection = glm::ortho(0.0f, w, h, 0.0f, -1.0f, 1.0f);+ renderer_->beginScene(projection);+runSystems(Schedule::PreRender);runSystems(Schedule::Render);runSystems(Schedule::PostRender);++ renderer_->endScene();renderer_->endFrame();platform_->swapBuffers();diff --git a/src/esengine/app/App.hpp b/src/esengine/app/App.hppindex ef2c57cc8..6b83b935d 100644--- a/src/esengine/app/App.hpp+++ b/src/esengine/app/App.hpp@@ -12,6 +12,7 @@#include "Schedule.hpp"#include "../core/Types.hpp"+#include "../core/ServiceRegistry.hpp"#include "../ecs/Registry.hpp"#include "../platform/Platform.hpp"#include "../platform/input/Input.hpp"@@ -50,7 +51,7 @@ struct AppConfig {};// =============================================================================-// Resources (Global Singletons)+// Resources// =============================================================================struct Time {@@ -117,13 +118,15 @@ public:Renderer& renderer() { return *renderer_; }RenderContext& renderContext() { return *renderContext_; }+ ServiceRegistry& services() { return services_; }+u32 width() const { return config_.width; }u32 height() const { return config_.height; }static App& get() { return *instance_; }// =========================================================================- // JS Interop (Web platform)+ // JS Interop// =========================================================================#ifdef ES_PLATFORM_WEB@@ -140,6 +143,7 @@ private:void runSystems(Schedule schedule);AppConfig config_;+ ServiceRegistry services_;Unique<Platform> platform_;Input input_;diff --git a/src/esengine/bindings/EngineContext.cpp b/src/esengine/bindings/EngineContext.cppindex 373575d84..4af3bc5ce 100644--- a/src/esengine/bindings/EngineContext.cpp+++ b/src/esengine/bindings/EngineContext.cpp@@ -41,68 +41,33 @@ EngineContext& EngineContext::instance() {return ctx;}-void EngineContext::setRenderContext(Unique<RenderContext> ctx) { renderContext_ = std::move(ctx); }-void EngineContext::setRenderFrame(Unique<RenderFrame> frame) { renderFrame_ = std::move(frame); }-void EngineContext::setImmediateDraw(Unique<ImmediateDraw> draw) { immediateDraw_ = std::move(draw); }-void EngineContext::setGeometryManager(Unique<GeometryManager> mgr) { geometryManager_ = std::move(mgr); }-#ifdef ES_ENABLE_POSTPROCESS-void EngineContext::setPostProcessPipeline(Unique<PostProcessPipeline> pipeline) { postProcessPipeline_ = std::move(pipeline); }-#endif-void EngineContext::setResourceManager(Unique<resource::ResourceManager> mgr) { resourceManager_ = std::move(mgr); }-void EngineContext::setTransformSystem(Unique<ecs::TransformSystem> sys) { transformSystem_ = std::move(sys); }-void EngineContext::setTweenSystem(Unique<animation::TweenSystem> sys) { tweenSystem_ = std::move(sys); }-#ifdef ES_ENABLE_TIMELINE-void EngineContext::setTimelineSystem(Unique<animation::TimelineSystem> sys) { timelineSystem_ = std::move(sys); }-#endif-#ifdef ES_ENABLE_PARTICLES-void EngineContext::setParticleSystem(Unique<particle::ParticleSystem> sys) { particleSystem_ = std::move(sys); }-#endif--#ifdef ES_ENABLE_SPINE-void EngineContext::setSpineResourceManager(Unique<spine::SpineResourceManager> mgr) { spineResourceManager_ = std::move(mgr); }-void EngineContext::setSpineSystem(Unique<spine::SpineSystem> sys) { spineSystem_ = std::move(sys); }-#endif-void EngineContext::shutdown() {if (!initialized_) return;- geometryManager_.reset();-- if (renderFrame_) {- renderFrame_->shutdown();- renderFrame_.reset();+ if (auto* rf = renderFrame()) {+ rf->shutdown();}- if (immediateDraw_) {- immediateDraw_->shutdown();- immediateDraw_.reset();+ if (auto* id = immediateDraw()) {+ id->shutdown();}#ifdef ES_ENABLE_SPINE- spineSystem_.reset();- if (spineResourceManager_) {- spineResourceManager_->shutdown();- spineResourceManager_.reset();+ if (auto* srm = spineResourceManager()) {+ srm->shutdown();}#endif-#ifdef ES_ENABLE_TIMELINE- timelineSystem_.reset();-#endif-#ifdef ES_ENABLE_PARTICLES- particleSystem_.reset();-#endif- tweenSystem_.reset();- transformSystem_.reset();- if (renderContext_) {- renderContext_->shutdown();- renderContext_.reset();+ if (auto* rc = renderContext()) {+ rc->shutdown();}- if (resourceManager_) {- resourceManager_->shutdown();- resourceManager_.reset();++ if (auto* rm = resourceManager()) {+ rm->shutdown();}+ services_.clear();+if (webglContext_ > 0) {emscripten_webgl_destroy_context(webglContext_);webglContext_ = 0;diff --git a/src/esengine/bindings/EngineContext.hpp b/src/esengine/bindings/EngineContext.hppindex 5047893fe..bc2e42c89 100644--- a/src/esengine/bindings/EngineContext.hpp+++ b/src/esengine/bindings/EngineContext.hpp@@ -15,6 +15,7 @@#include <emscripten/html5.h>#include <glm/glm.hpp>#include "../core/Types.hpp"+#include "../core/ServiceRegistry.hpp"#include "../animation/TweenSystem.hpp"#include "MaterialCache.hpp"#ifdef ES_ENABLE_TIMELINE@@ -42,7 +43,6 @@ namespace ecs {class TransformSystem;}-#ifdef ES_ENABLE_SPINEnamespace spine {class SpineResourceManager;@@ -53,8 +53,8 @@ class SpineSystem;/*** @brief Centralized context for engine subsystems and state*- * @details Replaces global variables in WebSDKEntry.cpp with a singleton- * context object. Provides controlled access to subsystems and state.+ * @details Delegates subsystem storage to a ServiceRegistry.+ * Typed accessors are provided for backward compatibility.*/class EngineContext {public:@@ -67,28 +67,38 @@ public:void shutdown();- RenderContext* renderContext() { return renderContext_.get(); }- RenderFrame* renderFrame() { return renderFrame_.get(); }- ImmediateDraw* immediateDraw() { return immediateDraw_.get(); }- GeometryManager* geometryManager() { return geometryManager_.get(); }+ ServiceRegistry& services() { return services_; }++ // =========================================================================+ // Subsystem Accessors+ // =========================================================================++ RenderContext* renderContext() { return services_.getService<RenderContext>(); }+ RenderFrame* renderFrame() { return services_.getService<RenderFrame>(); }+ ImmediateDraw* immediateDraw() { return services_.getService<ImmediateDraw>(); }+ GeometryManager* geometryManager() { return services_.getService<GeometryManager>(); }#ifdef ES_ENABLE_POSTPROCESS- PostProcessPipeline* postProcessPipeline() { return postProcessPipeline_.get(); }+ PostProcessPipeline* postProcessPipeline() { return services_.getService<PostProcessPipeline>(); }#endif- resource::ResourceManager* resourceManager() { return resourceManager_.get(); }- ecs::TransformSystem* transformSystem() { return transformSystem_.get(); }- animation::TweenSystem* tweenSystem() { return tweenSystem_.get(); }+ resource::ResourceManager* resourceManager() { return services_.getService<resource::ResourceManager>(); }+ ecs::TransformSystem* transformSystem() { return services_.getService<ecs::TransformSystem>(); }+ animation::TweenSystem* tweenSystem() { return services_.getService<animation::TweenSystem>(); }#ifdef ES_ENABLE_TIMELINE- animation::TimelineSystem* timelineSystem() { return timelineSystem_.get(); }+ animation::TimelineSystem* timelineSystem() { return services_.getService<animation::TimelineSystem>(); }#endif#ifdef ES_ENABLE_PARTICLES- particle::ParticleSystem* particleSystem() { return particleSystem_.get(); }+ particle::ParticleSystem* particleSystem() { return services_.getService<particle::ParticleSystem>(); }#endif#ifdef ES_ENABLE_SPINE- spine::SpineResourceManager* spineResourceManager() { return spineResourceManager_.get(); }- spine::SpineSystem* spineSystem() { return spineSystem_.get(); }+ spine::SpineResourceManager* spineResourceManager() { return services_.getService<spine::SpineResourceManager>(); }+ spine::SpineSystem* spineSystem() { return services_.getService<spine::SpineSystem>(); }#endif+ // =========================================================================+ // State+ // =========================================================================+EMSCRIPTEN_WEBGL_CONTEXT_HANDLE webglContext() const { return webglContext_; }void setWebglContext(EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx) { webglContext_ = ctx; }@@ -120,53 +130,12 @@ public:MaterialCache& materialCache() { return materialCache_; }void setInitialized(bool initialized) { initialized_ = initialized; }- void setRenderContext(Unique<RenderContext> ctx);- void setRenderFrame(Unique<RenderFrame> frame);- void setImmediateDraw(Unique<ImmediateDraw> draw);- void setGeometryManager(Unique<GeometryManager> mgr);-#ifdef ES_ENABLE_POSTPROCESS- void setPostProcessPipeline(Unique<PostProcessPipeline> pipeline);-#endif- void setResourceManager(Unique<resource::ResourceManager> mgr);- void setTransformSystem(Unique<ecs::TransformSystem> sys);- void setTweenSystem(Unique<animation::TweenSystem> sys);-#ifdef ES_ENABLE_TIMELINE- void setTimelineSystem(Unique<animation::TimelineSystem> sys);-#endif-#ifdef ES_ENABLE_PARTICLES- void setParticleSystem(Unique<particle::ParticleSystem> sys);-#endif--#ifdef ES_ENABLE_SPINE- void setSpineResourceManager(Unique<spine::SpineResourceManager> mgr);- void setSpineSystem(Unique<spine::SpineSystem> sys);-#endifprivate:EngineContext() = default;~EngineContext() = default;- Unique<RenderContext> renderContext_;- Unique<RenderFrame> renderFrame_;- Unique<ImmediateDraw> immediateDraw_;- Unique<GeometryManager> geometryManager_;-#ifdef ES_ENABLE_POSTPROCESS- Unique<PostProcessPipeline> postProcessPipeline_;-#endif- Unique<resource::ResourceManager> resourceManager_;- Unique<ecs::TransformSystem> transformSystem_;- Unique<animation::TweenSystem> tweenSystem_;-#ifdef ES_ENABLE_TIMELINE- Unique<animation::TimelineSystem> timelineSystem_;-#endif-#ifdef ES_ENABLE_PARTICLES- Unique<particle::ParticleSystem> particleSystem_;-#endif--#ifdef ES_ENABLE_SPINE- Unique<spine::SpineResourceManager> spineResourceManager_;- Unique<spine::SpineSystem> spineSystem_;-#endif+ ServiceRegistry services_;EMSCRIPTEN_WEBGL_CONTEXT_HANDLE webglContext_ = 0;bool initialized_ = false;diff --git a/src/esengine/bindings/PostProcessBindings.cpp b/src/esengine/bindings/PostProcessBindings.cppindex de6621236..566ba9feb 100644--- a/src/esengine/bindings/PostProcessBindings.cpp+++ b/src/esengine/bindings/PostProcessBindings.cpp@@ -31,7 +31,8 @@ bool postprocess_init(u32 width, u32 height) {if (!g_initialized || !g_renderContext || !g_resourceManager) return false;if (!g_postProcessPipeline) {- ctx().setPostProcessPipeline(makeUnique<PostProcessPipeline>(*g_renderContext, *g_resourceManager));+ ctx().services().registerOwned<PostProcessPipeline>(+ makeUnique<PostProcessPipeline>(*g_renderContext, *g_resourceManager));}g_postProcessPipeline->init(width, height);@@ -43,7 +44,7 @@ bool postprocess_init(u32 width, u32 height) {void postprocess_shutdown() {if (g_postProcessPipeline) {g_postProcessPipeline->shutdown();- ctx().setPostProcessPipeline(nullptr);+ ctx().services().removeService<PostProcessPipeline>();}}diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex 6bc85e41b..7efe32c2b 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -197,35 +197,37 @@ bool getMaterialDataWithUniforms(u32 materialId, u32& shaderId, u32& blendMode,}static void initSubsystems() {+ auto& svc = ctx().services();+auto resourceManager = makeUnique<resource::ResourceManager>();resourceManager->init();- ctx().setResourceManager(std::move(resourceManager));+ svc.registerOwned<resource::ResourceManager>(std::move(resourceManager));auto renderContext = makeUnique<RenderContext>();renderContext->init();- ctx().setRenderContext(std::move(renderContext));+ svc.registerOwned<RenderContext>(std::move(renderContext));- ctx().setTransformSystem(makeUnique<ecs::TransformSystem>());- ctx().setTweenSystem(makeUnique<animation::TweenSystem>());+ svc.registerOwned<ecs::TransformSystem>(makeUnique<ecs::TransformSystem>());+ svc.registerOwned<animation::TweenSystem>(makeUnique<animation::TweenSystem>());#ifdef ES_ENABLE_TIMELINE- ctx().setTimelineSystem(makeUnique<animation::TimelineSystem>());+ svc.registerOwned<animation::TimelineSystem>(makeUnique<animation::TimelineSystem>());#endif#ifdef ES_ENABLE_PARTICLES- ctx().setParticleSystem(makeUnique<particle::ParticleSystem>());+ svc.registerOwned<particle::ParticleSystem>(makeUnique<particle::ParticleSystem>());#endif#ifdef ES_ENABLE_SPINEauto spineResourceManager = makeUnique<spine::SpineResourceManager>(*g_resourceManager);spineResourceManager->init();- ctx().setSpineResourceManager(std::move(spineResourceManager));- ctx().setSpineSystem(makeUnique<spine::SpineSystem>(*g_spineResourceManager));+ svc.registerOwned<spine::SpineResourceManager>(std::move(spineResourceManager));+ svc.registerOwned<spine::SpineSystem>(makeUnique<spine::SpineSystem>(*g_spineResourceManager));#endifauto immediateDraw = makeUnique<ImmediateDraw>(*g_renderContext, *g_resourceManager);immediateDraw->init();- ctx().setImmediateDraw(std::move(immediateDraw));+ svc.registerOwned<ImmediateDraw>(std::move(immediateDraw));- ctx().setGeometryManager(makeUnique<GeometryManager>());+ svc.registerOwned<GeometryManager>(makeUnique<GeometryManager>());auto renderFrame = makeUnique<RenderFrame>(*g_renderContext, *g_resourceManager);@@ -255,7 +257,7 @@ static void initSubsystems() {}#endifrenderFrame->init(1280, 720);- ctx().setRenderFrame(std::move(renderFrame));+ svc.registerOwned<RenderFrame>(std::move(renderFrame));ctx().setInitialized(true);diff --git a/src/esengine/core/Application.cpp b/src/esengine/core/Application.cppdeleted file mode 100644index 1733e905b..000000000--- a/src/esengine/core/Application.cpp+++ /dev/null@@ -1,205 +0,0 @@-/**- * @file Application.cpp- * @brief Application base class implementation- * @details Manages the main game loop, platform integration, and subsystem lifecycle.- *- * @author ESEngine Team- * @date 2026- *- * @copyright Copyright (c) 2026 ESEngine Team- * Licensed under the MIT License.- */--#include "Application.hpp"-#include "Log.hpp"-#include "../platform/input/Input.hpp"-#include "../platform/FileSystem.hpp"-#include "../ecs/components/Canvas.hpp"--#ifdef ES_PLATFORM_WEB- #include <emscripten.h>-#endif--namespace esengine {--Application* Application::instance_ = nullptr;--Application::Application(const ApplicationConfig& config)- : config_(config) {- ES_ASSERT(instance_ == nullptr, "Application already exists");- instance_ = this;-}--Application::~Application() {- instance_ = nullptr;-}--void Application::run() {- init();--#ifdef ES_PLATFORM_WEB- // Emscripten main loop- emscripten_set_main_loop_arg(- [](void* arg) {- auto* app = static_cast<Application*>(arg);- app->mainLoop();- },- this,- 0, // Use requestAnimationFrame- 1 // Simulate infinite loop- );-#else- // Native main loop- while (running_ && platform_->isRunning()) {- mainLoop();- }- shutdown();-#endif-}--void Application::quit() {- running_ = false;- platform_->requestQuit();--#ifdef ES_PLATFORM_WEB- emscripten_cancel_main_loop();- shutdown();-#endif-}--void Application::init() {- // Initialize logging- Log::init();- ES_LOG_INFO("Initializing ESEngine Application: {}", config_.title);-- // Initialize file system (and PathResolver)- FileSystem::init();-- // Create and initialize platform- platform_ = Platform::create();- if (!platform_->initialize(config_.width, config_.height)) {- ES_LOG_FATAL("Failed to initialize platform");- return;- }-- // Set up platform callbacks- platform_->setTouchCallback([this](TouchType type, const TouchPoint& point) {- input_.onTouchEvent(type, point);- onTouch(type, point);- });-- platform_->setKeyCallback([this](KeyCode key, bool pressed) {- input_.onKeyEvent(key, pressed);- onKey(key, pressed);- });-- platform_->setScrollCallback([this](f32 deltaX, f32 deltaY, f32 x, f32 y) {- input_.onScrollEvent(deltaX, deltaY);- (void)x; (void)y;- });-- platform_->setResizeCallback([this](u32 width, u32 height) {- config_.width = width;- config_.height = height;- if (renderer_) {- renderer_->setViewport(0, 0, width, height);- }- onResize(width, height);- });-- // Initialize subsystems- input_.init();-- // Initialize resource manager- resourceManager_.init();-- // Initialize render context and renderer- renderContext_ = makeUnique<RenderContext>();- renderContext_->init();-- renderer_ = makeUnique<Renderer>(*renderContext_);- renderer_->setViewport(0, 0, config_.width, config_.height);- renderer_->setClearColor(glm::vec4(0.1f, 0.1f, 0.1f, 1.0f));-- // Initialize systems- systems_.init(registry_);-- // Call user init- onInit();-- running_ = true;- ES_LOG_INFO("Application initialized successfully");-}--void Application::mainLoop() {- // Update platform (events, timing)- platform_->pollEvents();- deltaTime_ = platform_->getDeltaTime();-- // Update input state- input_.update();-- // Update systems- systems_.update(registry_, static_cast<f32>(deltaTime_));-- // Call user update- onUpdate(static_cast<f32>(deltaTime_));-- // Render- auto canvasView = registry_.view<ecs::Canvas>();- if (!canvasView.empty()) {- auto entity = *canvasView.begin();- auto& canvas = registry_.get<ecs::Canvas>(entity);- renderer_->setClearColor(canvas.backgroundColor);- }- renderer_->beginFrame();- renderer_->clear();-- // Set up default 2D projection- f32 width = static_cast<f32>(config_.width);- f32 height = static_cast<f32>(config_.height);- glm::mat4 projection = glm::ortho(0.0f, width, height, 0.0f, -1.0f, 1.0f);- renderer_->beginScene(projection);-- // Call user render- onRender();-- renderer_->endScene();- renderer_->endFrame();-- // Swap buffers- platform_->swapBuffers();-}--void Application::shutdown() {- ES_LOG_INFO("Shutting down application");-- // Call user shutdown- onShutdown();-- // Shutdown systems- systems_.shutdown(registry_);-- // Clear registry- registry_.clear();-- // Shutdown renderer and context- renderer_.reset();- renderContext_.reset();-- // Shutdown resource manager- resourceManager_.shutdown();-- // Shutdown input- input_.shutdown();-- // Shutdown platform- platform_->shutdown();-- // Shutdown file system- FileSystem::shutdown();-- Log::shutdown();-}--} // namespace esenginediff --git a/src/esengine/core/Application.hpp b/src/esengine/core/Application.hppdeleted file mode 100644index ab8459f9e..000000000--- a/src/esengine/core/Application.hpp+++ /dev/null@@ -1,288 +0,0 @@-/**- * @file Application.hpp- * @brief Base application class for ESEngine applications- * @details Provides the main application framework including lifecycle- * management, event handling, and access to engine subsystems.- *- * @author ESEngine Team- * @date 2026- *- * @copyright Copyright (c) 2026 ESEngine Team- * Licensed under the MIT License.- */-#pragma once--// =============================================================================-// Includes-// =============================================================================--// Project includes-#include "Types.hpp"-#include "../platform/Platform.hpp"-#include "../platform/input/Input.hpp"-#include "../ecs/Registry.hpp"-#include "../ecs/System.hpp"-#include "../resource/ResourceManager.hpp"-#include "../renderer/RenderContext.hpp"-#include "../renderer/Renderer.hpp"--namespace esengine {--// =============================================================================-// Application Configuration-// =============================================================================--/**- * @brief Configuration settings for Application initialization- *- * @details Controls window properties and rendering settings.- * Pass to Application constructor to customize behavior.- *- * @code- * ApplicationConfig config;- * config.title = "My Game";- * config.width = 1280;- * config.height = 720;- * MyApp app(config);- * @endcode- */-struct ApplicationConfig {- /** @brief Window title (native) or canvas title (web) */- std::string title = "ESEngine Application";- /** @brief Initial viewport width in pixels */- u32 width = 800;- /** @brief Initial viewport height in pixels */- u32 height = 600;- /** @brief Enable vertical sync */- bool vsync = true;-};--// =============================================================================-// Application Class-// =============================================================================--/**- * @brief Base class for ESEngine applications- *- * @details Users derive from this class and override lifecycle hooks- * to implement game logic. The Application manages:- * - Platform abstraction and window/context creation- * - Main game loop with fixed timestep- * - ECS Registry for entity/component management- * - Resource management (shaders, textures, buffers)- * - Rendering context and renderer- * - Event dispatching (input, resize, etc.)- *- * @code- * class MyGame : public esengine::Application {- * public:- * MyGame() : Application({.title = "My Game", .width = 1280}) {}- *- * protected:- * void onInit() override {- * // Load assets, create entities- * auto tex = getResourceManager().loadTexture("player.png");- * }- *- * void onUpdate(f32 deltaTime) override {- * // Game logic, physics, AI- * }- *- * void onRender() override {- * // Drawing code- * getRenderer().drawQuad({100, 100}, {50, 50}, {1, 0, 0, 1});- * }- * };- *- * ES_MAIN(MyGame)- * @endcode- *- * @note Application is a singleton - only one instance can exist.- */-class Application {-public:- /**- * @brief Constructs the application with given configuration- * @param config Application settings (window size, title, etc.)- */- Application(const ApplicationConfig& config = {});-- /** @brief Virtual destructor for proper cleanup */- virtual ~Application();-- // Non-copyable- Application(const Application&) = delete;- Application& operator=(const Application&) = delete;-- // =========================================================================- // Lifecycle- // =========================================================================-- /**- * @brief Starts the main application loop- * @details Initializes subsystems, enters the main loop, and handles- * shutdown when complete. On web platforms, this sets up- * the Emscripten main loop.- */- void run();-- /**- * @brief Requests the application to close- * @details Sets a flag that causes the main loop to exit gracefully- * after the current frame completes.- */- void quit();-- // =========================================================================- // Accessors- // =========================================================================-- /**- * @brief Gets the platform abstraction layer- * @return Reference to the Platform instance- */- Platform& getPlatform() { return *platform_; }-- /**- * @brief Gets the ECS registry- * @return Reference to the Registry for entity/component management- */- ecs::Registry& getRegistry() { return registry_; }-- /**- * @brief Gets the resource manager- * @return Reference to the ResourceManager for asset loading- */- resource::ResourceManager& getResourceManager() { return resourceManager_; }-- /**- * @brief Gets the render context- * @return Reference to the RenderContext- */- RenderContext& getRenderContext() { return *renderContext_; }-- /**- * @brief Gets the renderer- * @return Reference to the Renderer for drawing- */- Renderer& getRenderer() { return *renderer_; }-- /**- * @brief Gets the input system- * @return Reference to the Input for querying input state- */- Input& getInput() { return input_; }-- /** @brief Gets the current viewport width in pixels */- u32 getWidth() const { return config_.width; }-- /** @brief Gets the current viewport height in pixels */- u32 getHeight() const { return config_.height; }-- /**- * @brief Gets the time elapsed since last frame- * @return Delta time in seconds- */- f32 getDeltaTime() const { return static_cast<f32>(deltaTime_); }-- /**- * @brief Gets the singleton Application instance- * @return Reference to the current Application- * @note Asserts if called before Application construction- */- static Application& get() { return *instance_; }--protected:- // =========================================================================- // Lifecycle Hooks- // =========================================================================-- /**- * @brief Called once after engine initialization- * @details Override to load assets, create initial entities, etc.- */- virtual void onInit() {}-- /**- * @brief Called every frame for game logic- * @param deltaTime Time since last frame in seconds- * @details Override to update game state, physics, AI, etc.- */- virtual void onUpdate(f32 deltaTime) { (void)deltaTime; }-- /**- * @brief Called every frame for rendering- * @details Override to submit draw calls. Called after onUpdate().- */- virtual void onRender() {}-- /**- * @brief Called before application shutdown- * @details Override to save state or cleanup resources.- */- virtual void onShutdown() {}-- // =========================================================================- // Event Callbacks- // =========================================================================-- /**- * @brief Called on touch/mouse input- * @param type The type of touch event (down, up, move)- * @param point Touch position and identifier- */- virtual void onTouch(TouchType type, const TouchPoint& point) {- (void)type; (void)point;- }-- /**- * @brief Called on keyboard input- * @param key The key code- * @param pressed True if pressed, false if released- */- virtual void onKey(KeyCode key, bool pressed) {- (void)key; (void)pressed;- }-- /**- * @brief Called when viewport is resized- * @param width New width in pixels- * @param height New height in pixels- */- virtual void onResize(u32 width, u32 height) {- (void)width; (void)height;- }-- // =========================================================================- // Protected Members- // =========================================================================-- /** @brief Application configuration */- ApplicationConfig config_;- /** @brief Platform abstraction layer */- Unique<Platform> platform_;- /** @brief Input system instance */- Input input_;- /** @brief ECS entity/component registry */- ecs::Registry registry_;- /** @brief System execution group */- ecs::SystemGroup systems_;- /** @brief Resource manager for assets */- resource::ResourceManager resourceManager_;- /** @brief Rendering context with shared state */- Unique<RenderContext> renderContext_;- /** @brief Renderer instance */- Unique<Renderer> renderer_;--private:- void init();- void mainLoop();- void shutdown();-- f64 deltaTime_ = 0.0;- bool running_ = false;-- static Application* instance_;-};--} // namespace esenginediff --git a/src/esengine/core/ServiceRegistry.hpp b/src/esengine/core/ServiceRegistry.hppnew file mode 100644index 000000000..2673dedff--- /dev/null+++ b/src/esengine/core/ServiceRegistry.hpp@@ -0,0 +1,146 @@+/**+ * @file ServiceRegistry.hpp+ * @brief Typed service locator for engine subsystems+ * @details Provides a template-based registry where subsystems can be+ * registered and retrieved by type. Supports both owned and+ * borrowed services.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the MIT License.+ */+#pragma once++// =============================================================================+// Includes+// =============================================================================++#include "Types.hpp"+#include "Log.hpp"++#include <unordered_map>+#include <vector>++namespace esengine {++// =============================================================================+// ServiceRegistry Class+// =============================================================================++/**+ * @brief Typed service locator for engine subsystems+ *+ * @details Allows registering and retrieving subsystems by their C++ type.+ * - Borrowed: registerService<T>(ptr) for externally managed lifetimes+ * - Owned: registerOwned<T>(ptr) for registry-managed lifetimes+ *+ * @code+ * ServiceRegistry services;+ * services.registerOwned<RenderContext>(makeUnique<RenderContext>());+ * auto& ctx = services.require<RenderContext>();+ * @endcode+ */+class ServiceRegistry {+public:+ ServiceRegistry() = default;+ ~ServiceRegistry() { clear(); }++ ServiceRegistry(const ServiceRegistry&) = delete;+ ServiceRegistry& operator=(const ServiceRegistry&) = delete;+ ServiceRegistry(ServiceRegistry&&) noexcept = default;+ ServiceRegistry& operator=(ServiceRegistry&&) noexcept = default;++ /**+ * @brief Registers a borrowed service+ * @tparam T The service type+ * @param service Pointer to the service, caller retains ownership+ */+ template<typename T>+ void registerService(T* service) {+ services_[getTypeId<T>()] = static_cast<void*>(service);+ }++ /**+ * @brief Registers an owned service+ * @tparam T The service type+ * @param service Unique pointer transferred to the registry+ */+ template<typename T>+ void registerOwned(Unique<T> service) {+ T* raw = service.get();+ services_[getTypeId<T>()] = static_cast<void*>(raw);++ auto deleter = [](void* ptr) {+ delete static_cast<T*>(ptr);+ };+ owned_.push_back({service.release(), deleter});+ }++ /**+ * @brief Gets a service by type+ * @tparam T The service type+ * @return Pointer to the service, or nullptr if not registered+ */+ template<typename T>+ T* getService() {+ auto it = services_.find(getTypeId<T>());+ if (it == services_.end()) return nullptr;+ return static_cast<T*>(it->second);+ }++ /**+ * @brief Gets a service by type, asserts non-null+ * @tparam T The service type+ * @return Reference to the service+ */+ template<typename T>+ T& require() {+ T* svc = getService<T>();+ ES_ASSERT(svc != nullptr, "Required service not registered");+ return *svc;+ }++ /**+ * @brief Removes and destroys an owned service by type+ * @tparam T The service type to remove+ */+ template<typename T>+ void removeService() {+ TypeId id = getTypeId<T>();+ auto it = services_.find(id);+ if (it == services_.end()) return;++ void* ptr = it->second;+ services_.erase(it);++ for (auto oit = owned_.begin(); oit != owned_.end(); ++oit) {+ if (oit->ptr == ptr) {+ oit->deleter(oit->ptr);+ owned_.erase(oit);+ return;+ }+ }+ }++ /** @brief Removes all services, destroys owned ones in reverse registration order */+ void clear() {+ for (auto it = owned_.rbegin(); it != owned_.rend(); ++it) {+ it->deleter(it->ptr);+ }+ owned_.clear();+ services_.clear();+ }++private:+ struct OwnedEntry {+ void* ptr;+ void (*deleter)(void*);+ };++ std::unordered_map<TypeId, void*> services_;+ std::vector<OwnedEntry> owned_;+};++} // namespace esenginediff --git a/src/esengine/ecs/ComponentMask.hpp b/src/esengine/ecs/ComponentMask.hppnew file mode 100644index 000000000..83b9a08fc--- /dev/null+++ b/src/esengine/ecs/ComponentMask.hpp@@ -0,0 +1,142 @@+/**+ * @file ComponentMask.hpp+ * @brief Dynamic bitset for tracking entity component membership+ * @details Uses small-buffer optimization with 128 bits stored inline.+ * Heap allocation occurs only when component type IDs exceed 128.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the MIT License.+ */+#pragma once++// =============================================================================+// Includes+// =============================================================================++#include "../core/Types.hpp"++#ifdef _MSC_VER+#include <intrin.h>+#endif+#include <vector>++namespace esengine::ecs {++// =============================================================================+// ComponentMask Class+// =============================================================================++/**+ * @brief Dynamic bitset for tracking which components an entity has+ *+ * @details The first 128 bits are stored inline as two u64 words.+ * An overflow vector is allocated only when type IDs exceed 128.+ */+class ComponentMask {+public:+ static constexpr u32 INLINE_WORDS = 2;+ static constexpr u32 BITS_PER_WORD = 64;+ static constexpr u32 INLINE_BITS = INLINE_WORDS * BITS_PER_WORD;++ ComponentMask() = default;++ /** @brief Sets the given bit */+ void set(u32 bit) {+ if (bit < INLINE_BITS) {+ inline_[bit / BITS_PER_WORD] |= (u64{1} << (bit % BITS_PER_WORD));+ } else {+ u32 idx = (bit - INLINE_BITS) / BITS_PER_WORD;+ if (idx >= overflow_.size()) {+ overflow_.resize(idx + 1, 0);+ }+ overflow_[idx] |= (u64{1} << ((bit - INLINE_BITS) % BITS_PER_WORD));+ }+ }++ /** @brief Clears the given bit */+ void clear(u32 bit) {+ if (bit < INLINE_BITS) {+ inline_[bit / BITS_PER_WORD] &= ~(u64{1} << (bit % BITS_PER_WORD));+ } else {+ u32 idx = (bit - INLINE_BITS) / BITS_PER_WORD;+ if (idx < overflow_.size()) {+ overflow_[idx] &= ~(u64{1} << ((bit - INLINE_BITS) % BITS_PER_WORD));+ }+ }+ }++ /** @brief Tests the given bit */+ [[nodiscard]] bool test(u32 bit) const {+ if (bit < INLINE_BITS) {+ return (inline_[bit / BITS_PER_WORD] & (u64{1} << (bit % BITS_PER_WORD))) != 0;+ }+ u32 idx = (bit - INLINE_BITS) / BITS_PER_WORD;+ if (idx >= overflow_.size()) return false;+ return (overflow_[idx] & (u64{1} << ((bit - INLINE_BITS) % BITS_PER_WORD))) != 0;+ }++ /** @brief Clears all bits */+ void reset() {+ inline_[0] = 0;+ inline_[1] = 0;+ overflow_.clear();+ }++ /** @brief Returns true if no bits are set */+ [[nodiscard]] bool none() const {+ if (inline_[0] != 0 || inline_[1] != 0) return false;+ for (auto w : overflow_) {+ if (w != 0) return false;+ }+ return true;+ }++ /**+ * @brief Iterates all set bits, calling fn(bitIndex) for each+ * @tparam Func Callable accepting u32+ */+ template<typename Func>+ void forEachSet(Func&& fn) const {+ for (u32 w = 0; w < INLINE_WORDS; ++w) {+ u64 word = inline_[w];+ while (word != 0) {+ u32 bit = ctz64(word);+ fn(w * BITS_PER_WORD + bit);+ word &= word - 1;+ }+ }+ for (u32 i = 0; i < overflow_.size(); ++i) {+ u64 word = overflow_[i];+ while (word != 0) {+ u32 bit = ctz64(word);+ fn(INLINE_BITS + i * BITS_PER_WORD + bit);+ word &= word - 1;+ }+ }+ }++private:+ /** @brief Count trailing zeros; val must be non-zero */+ static u32 ctz64(u64 val) {+ ES_ASSERT(val != 0, "ctz64 undefined for zero");+#if defined(__GNUC__) || defined(__clang__)+ return static_cast<u32>(__builtin_ctzll(val));+#elif defined(_MSC_VER)+ unsigned long idx;+ _BitScanForward64(&idx, val);+ return static_cast<u32>(idx);+#else+ u32 count = 0;+ while ((val & 1) == 0) { val >>= 1; ++count; }+ return count;+#endif+ }++ u64 inline_[INLINE_WORDS] = {0, 0};+ std::vector<u64> overflow_;+};++} // namespace esengine::ecsdiff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hppindex fdbae7991..14368fa79 100644--- a/src/esengine/ecs/Registry.hpp+++ b/src/esengine/ecs/Registry.hpp@@ -20,6 +20,7 @@// Project includes#include "../core/Log.hpp"#include "../core/Types.hpp"+#include "ComponentMask.hpp"#include "Entity.hpp"#include "SchemaComponent.hpp"#include "SparseSet.hpp"@@ -60,8 +61,6 @@ namespace esengine::ecs {*/class Registry {public:- static constexpr u32 MAX_TRACKED_COMPONENTS = 64;-Registry() = default;~Registry() = default;@@ -95,11 +94,11 @@ public:if (entity >= entityValid_.size()) {entityValid_.resize(entity + 1, false);generations_.resize(entity + 1, 0);- component_masks_.resize(entity + 1, 0);+ component_masks_.resize(entity + 1);}entityValid_[entity] = true;generations_[entity]++;- component_masks_[entity] = 0;+ component_masks_[entity].reset();++entity_count_;ES_LOG_TRACE("Created entity {}", entity);@@ -133,11 +132,11 @@ public:if (entity >= entityValid_.size()) {entityValid_.resize(entity + 1, false);generations_.resize(entity + 1, 0);- component_masks_.resize(entity + 1, 0);+ component_masks_.resize(entity + 1);}entityValid_[entity] = true;generations_[entity]++;- component_masks_[entity] = 0;+ component_masks_[entity].reset();++entity_count_;if (entity >= nextEntity_) {@@ -162,23 +161,15 @@ public:callback(entity);}- u64 mask = component_masks_[entity];- while (mask != 0) {- u32 bit = static_cast<u32>(__builtin_ctzll(mask));+ component_masks_[entity].forEachSet([&](u32 bit) {if (bit < pools_.size() && pools_[bit]) {pools_[bit]->remove(entity);}- mask &= mask - 1;- }- for (usize i = MAX_TRACKED_COMPONENTS; i < pools_.size(); ++i) {- if (pools_[i]) {- pools_[i]->remove(entity);- }- }+ });schemaRegistry_.removeAll(entity);- component_masks_[entity] = 0;+ component_masks_[entity].reset();entityValid_[entity] = false;--entity_count_;recycled_.push(entity);@@ -268,10 +259,7 @@ public:ES_ASSERT(valid(entity), "Invalid entity");auto& pool = assurePool<T>();auto& result = pool.emplace(entity, std::forward<Args>(args)...);- TypeId typeId = getTypeId<T>();- if (typeId < MAX_TRACKED_COMPONENTS) {- component_masks_[entity] |= (u64{1} << typeId);- }+ component_masks_[entity].set(getTypeId<T>());return result;}@@ -295,10 +283,7 @@ public:return pool.get(entity);}auto& result = pool.emplace(entity, std::forward<Args>(args)...);- TypeId typeId = getTypeId<T>();- if (typeId < MAX_TRACKED_COMPONENTS) {- component_masks_[entity] |= (u64{1} << typeId);- }+ component_masks_[entity].set(getTypeId<T>());return result;}@@ -314,9 +299,8 @@ public:auto* pool = getPool<T>();if (pool) {pool->remove(entity);- TypeId typeId = getTypeId<T>();- if (typeId < MAX_TRACKED_COMPONENTS && entity < component_masks_.size()) {- component_masks_[entity] &= ~(u64{1} << typeId);+ if (entity < component_masks_.size()) {+ component_masks_[entity].clear(getTypeId<T>());}}}@@ -378,10 +362,7 @@ public:return pool.get(entity);}auto& result = pool.emplace(entity, std::forward<Args>(args)...);- TypeId typeId = getTypeId<T>();- if (typeId < MAX_TRACKED_COMPONENTS) {- component_masks_[entity] |= (u64{1} << typeId);- }+ component_masks_[entity].set(getTypeId<T>());return result;}@@ -643,7 +624,7 @@ private:std::vector<u8> entityValid_;std::vector<u32> generations_;- std::vector<u64> component_masks_;+ std::vector<ComponentMask> component_masks_;std::queue<Entity> recycled_;Entity nextEntity_ = 0;usize entity_count_ = 0;diff --git a/src/esengine/platform/input/Input.hpp b/src/esengine/platform/input/Input.hppindex 34c117dc7..826e6bf75 100644--- a/src/esengine/platform/input/Input.hpp+++ b/src/esengine/platform/input/Input.hpp@@ -72,8 +72,7 @@ struct TouchState {* layer feeds events via onTouchEvent() and onKeyEvent().** @code- * // Access through Application- * Input& input = app.getInput();+ * Input& input = app.input();** // In game loop* input.update();@@ -105,7 +104,7 @@ public:/*** @brief Initializes the input system- * @details Clears all input state. Called automatically by Application.+ * @details Clears all input state. Called automatically by App.*/void init();diff --git a/src/esengine/platform/native/NativePlatform.hpp b/src/esengine/platform/native/NativePlatform.hppindex 0e290b343..54ee0da28 100644--- a/src/esengine/platform/native/NativePlatform.hpp+++ b/src/esengine/platform/native/NativePlatform.hpp@@ -225,7 +225,7 @@ private:f64 lastFrameTime_ = 0.0; ///< Time of last framef64 deltaTime_ = 0.0; ///< Delta time between frames- bool running_ = false; ///< Application running flag+ bool running_ = false; ///< Running state flagbool mousePressed_ = false; ///< Mouse button state for touch emulationf64 mouseX_ = 0.0; ///< Current mouse X positionf64 mouseY_ = 0.0; ///< Current mouse Y position