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
feat: Implement automatic binding generation system with reflection macros
esengine72d90c9d9814
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 7a8094129..d74f11e71 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -135,7 +135,8 @@ if(ES_BUILD_WEB OR ES_BUILD_WXGAME)list(APPEND ESENGINE_SOURCESsrc/esengine/platform/web/WebPlatform.cppsrc/esengine/platform/web/WebFileSystem.cpp- src/esengine/bindings/WebBindings.cpp+ # Generated Web bindings (from tools/generate_bindings.py)+ ${GENERATED_WEB_BINDINGS})else()# Native platform (GLFW + OpenGL)@@ -145,7 +146,8 @@ else()# Scripting (Native only - Web uses Emscripten bindings)src/esengine/scripting/ScriptContext.cppsrc/esengine/scripting/ScriptValue.cpp- src/esengine/scripting/bindings/ECSBindings.cpp+ # Generated QuickJS bindings (from tools/generate_bindings.py)+ ${GENERATED_QUICKJS_BINDINGS}src/esengine/ecs/systems/ScriptSystem.cpp)list(APPEND ESENGINE_HEADERS@@ -163,10 +165,66 @@ endif()# Platform-independent headerslist(APPEND ESENGINE_HEADERSsrc/esengine/platform/FileSystem.hpp+ src/esengine/core/Reflection.hpp)+# =============================================================================+# Automatic Binding Generation+# =============================================================================++# Find Python3 for binding generator+find_package(Python3 COMPONENTS Interpreter)++if(Python3_FOUND)+ # Generated binding files+ set(GENERATED_WEB_BINDINGS "${CMAKE_CURRENT_SOURCE_DIR}/src/esengine/bindings/WebBindings.generated.cpp")+ set(GENERATED_QUICKJS_BINDINGS "${CMAKE_CURRENT_SOURCE_DIR}/src/esengine/scripting/bindings/ECSBindings.generated.cpp")+ set(GENERATED_TS_DEFINITIONS "${CMAKE_CURRENT_SOURCE_DIR}/bindings/esengine.d.ts")++ # Component header files to scan+ file(GLOB_RECURSE COMPONENT_HEADERS+ "${CMAKE_CURRENT_SOURCE_DIR}/src/esengine/ecs/components/*.hpp"+ )++ # Custom command to generate bindings+ add_custom_command(+ OUTPUT+ ${GENERATED_WEB_BINDINGS}+ ${GENERATED_QUICKJS_BINDINGS}+ ${GENERATED_TS_DEFINITIONS}+ COMMAND ${Python3_EXECUTABLE}+ "${CMAKE_CURRENT_SOURCE_DIR}/tools/generate_bindings.py"+ --input "${CMAKE_CURRENT_SOURCE_DIR}/src/esengine/ecs/components"+ --output "${CMAKE_CURRENT_SOURCE_DIR}/src/esengine/bindings"+ DEPENDS+ ${COMPONENT_HEADERS}+ "${CMAKE_CURRENT_SOURCE_DIR}/tools/generate_bindings.py"+ WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"+ COMMENT "Generating bindings from marked components..."+ VERBATIM+ )++ # Create custom target for binding generation+ add_custom_target(generate_bindings+ DEPENDS+ ${GENERATED_WEB_BINDINGS}+ ${GENERATED_QUICKJS_BINDINGS}+ ${GENERATED_TS_DEFINITIONS}+ )++ message(STATUS "Automatic binding generation: ENABLED")+else()+ message(WARNING "Python3 not found - automatic binding generation DISABLED")+ message(WARNING "Using pre-existing binding files (may be outdated)")+endif()+add_library(esengine STATIC ${ESENGINE_SOURCES} ${ESENGINE_HEADERS})+# Add dependency on binding generation if Python is available+if(Python3_FOUND)+ add_dependencies(esengine generate_bindings)+endif()+target_include_directories(esenginePUBLIC$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src>diff --git a/bindings/esengine.d.ts b/bindings/esengine.d.tsnew file mode 100644index 000000000..26b436867--- /dev/null+++ b/bindings/esengine.d.ts@@ -0,0 +1,163 @@+/**+ * @file esengine.d.ts+ * @brief TypeScript definitions for ESEngine+ * @details Generated by tools/generate_bindings.py - DO NOT EDIT MANUALLY+ */++declare namespace Module {+ // =============================================================================+ // Core Types+ // =============================================================================++ type Entity = number;++ // =============================================================================+ // Math Types+ // =============================================================================++ interface Vec2 {+ x: number;+ y: number;+ }++ interface Vec3 {+ x: number;+ y: number;+ z: number;+ }++ interface Vec4 {+ x: number;+ y: number;+ z: number;+ w: number;+ }++ interface Quat {+ x: number;+ y: number;+ z: number;+ w: number;+ }++ // =============================================================================+ // ECS Components+ // =============================================================================++ interface Camera {+ projectionType: any;+ fov: number;+ orthoSize: number;+ nearPlane: number;+ farPlane: number;+ aspectRatio: number;+ isActive: boolean;+ priority: number;+ }++ interface Parent {+ entity: Entity;+ }++ interface Children {+ }++ interface Sprite {+ texture: any;+ color: Vec4;+ size: Vec2;+ uvOffset: Vec2;+ uvScale: Vec2;+ layer: number;+ flipX: boolean;+ flipY: boolean;+ }++ interface LocalTransform {+ position: Vec3;+ rotation: Quat;+ scale: Vec3;+ matrix: any;+ position: Vec3;+ rotation: Quat;+ scale: Vec3;+ }++ interface WorldTransform {+ matrix: any;+ position: Vec3;+ rotation: Quat;+ scale: Vec3;+ }++ interface Velocity {+ linear: Vec3;+ angular: Vec3;+ }++ // =============================================================================+ // ECS Registry+ // =============================================================================++ class Registry {+ constructor();++ // Entity management+ create(): Entity;+ destroy(entity: Entity): void;+ valid(entity: Entity): boolean;+ entityCount(): number;++ // Camera component+ hasCamera(entity: Entity): boolean;+ getCamera(entity: Entity): Camera;+ addCamera(entity: Entity, component: Camera): Camera;+ removeCamera(entity: Entity): void;++ // Parent component+ hasParent(entity: Entity): boolean;+ getParent(entity: Entity): Parent;+ addParent(entity: Entity, component: Parent): Parent;+ removeParent(entity: Entity): void;++ // Children component+ hasChildren(entity: Entity): boolean;+ getChildren(entity: Entity): Children;+ addChildren(entity: Entity, component: Children): Children;+ removeChildren(entity: Entity): void;++ // Sprite component+ hasSprite(entity: Entity): boolean;+ getSprite(entity: Entity): Sprite;+ addSprite(entity: Entity, component: Sprite): Sprite;+ removeSprite(entity: Entity): void;++ // LocalTransform component+ hasLocalTransform(entity: Entity): boolean;+ getLocalTransform(entity: Entity): LocalTransform;+ addLocalTransform(entity: Entity, component: LocalTransform): LocalTransform;+ removeLocalTransform(entity: Entity): void;++ // WorldTransform component+ hasWorldTransform(entity: Entity): boolean;+ getWorldTransform(entity: Entity): WorldTransform;+ addWorldTransform(entity: Entity, component: WorldTransform): WorldTransform;+ removeWorldTransform(entity: Entity): void;++ // Velocity component+ hasVelocity(entity: Entity): boolean;+ getVelocity(entity: Entity): Velocity;+ addVelocity(entity: Entity, component: Velocity): Velocity;+ removeVelocity(entity: Entity): void;++ }++ // =============================================================================+ // Module Lifecycle+ // =============================================================================++ function onRuntimeInitialized(): void;+}++export = Module;+export as namespace Module;diff --git a/cmake/Emscripten.cmake b/cmake/Emscripten.cmakeindex e39b363f0..bc6da2680 100644--- a/cmake/Emscripten.cmake+++ b/cmake/Emscripten.cmake@@ -18,7 +18,7 @@ set(ES_EMSCRIPTEN_COMPILE_FLAGSset(ES_EMSCRIPTEN_LINK_FLAGS--bind # Enable embind for C++ bindings- --embind-emit-tsd=esengine.d.ts # Auto-generate TypeScript definitions+ --emit-tsd esengine.d.ts # Auto-generate TypeScript definitions-sWASM=1-sUSE_WEBGL2=1-sFULL_ES3=1diff --git a/src/esengine/bindings/WebBindings.cpp b/src/esengine/bindings/WebBindings.cppdeleted file mode 100644index 1fea6bf62..000000000--- a/src/esengine/bindings/WebBindings.cpp+++ /dev/null@@ -1,229 +0,0 @@-/**- * @file WebBindings.cpp- * @brief Emscripten bindings for exposing C++ ECS API to JavaScript- *- * @author ESEngine Team- * @date 2026- *- * @copyright Copyright (c) 2026 ESEngine Team- * Licensed under the MIT License.- */--#ifdef ES_PLATFORM_WEB--#include <emscripten/bind.h>-#include "../ecs/Registry.hpp"-#include "../ecs/Entity.hpp"-#include "../ecs/components/Transform.hpp"-#include "../ecs/components/Hierarchy.hpp"-#include "../ecs/components/Velocity.hpp"-#include "../ecs/components/Camera.hpp"-#include "../ecs/components/Sprite.hpp"-#include "../math/Math.hpp"--using namespace emscripten;--namespace esengine {--// =============================================================================-// Math Types-// =============================================================================--EMSCRIPTEN_BINDINGS(esengine_math) {- // Vec2- value_object<glm::vec2>("Vec2")- .field("x", &glm::vec2::x)- .field("y", &glm::vec2::y);-- // Vec3- value_object<glm::vec3>("Vec3")- .field("x", &glm::vec3::x)- .field("y", &glm::vec3::y)- .field("z", &glm::vec3::z);-- // Vec4- value_object<glm::vec4>("Vec4")- .field("x", &glm::vec4::x)- .field("y", &glm::vec4::y)- .field("z", &glm::vec4::z)- .field("w", &glm::vec4::w);-- // Quat- value_object<glm::quat>("Quat")- .field("x", &glm::quat::x)- .field("y", &glm::quat::y)- .field("z", &glm::quat::z)- .field("w", &glm::quat::w);-- // Mat4 (exposed as array for simplicity)- // JavaScript can construct and pass as Float32Array-}--// =============================================================================-// ECS Entity Type-// =============================================================================--EMSCRIPTEN_BINDINGS(esengine_entity) {- // Entity is just u32, expose as integer- // JavaScript will treat it as a number-}--// =============================================================================-// ECS Components-// =============================================================================--EMSCRIPTEN_BINDINGS(esengine_components) {- // LocalTransform component- value_object<ecs::LocalTransform>("LocalTransform")- .field("position", &ecs::LocalTransform::position)- .field("rotation", &ecs::LocalTransform::rotation)- .field("scale", &ecs::LocalTransform::scale);-- // WorldTransform component (read-only from JS)- value_object<ecs::WorldTransform>("WorldTransform")- .field("matrix", &ecs::WorldTransform::matrix)- .field("position", &ecs::WorldTransform::position)- .field("rotation", &ecs::WorldTransform::rotation)- .field("scale", &ecs::WorldTransform::scale);-- // Parent component- value_object<ecs::Parent>("Parent")- .field("entity", &ecs::Parent::entity);-- // Children component (expose size and access)- class_<ecs::Children>("Children")- .function("count", &ecs::Children::count)- .function("empty", &ecs::Children::empty)- .function("at", optional_override([](const ecs::Children& children, usize index) {- return children.entities[index];- }));-- // Velocity component- value_object<ecs::Velocity>("Velocity")- .field("linear", &ecs::Velocity::linear)- .field("angular", &ecs::Velocity::angular);-- // Camera component- value_object<ecs::Camera>("Camera")- .field("fov", &ecs::Camera::fov)- .field("nearPlane", &ecs::Camera::nearPlane)- .field("farPlane", &ecs::Camera::farPlane)- .field("aspectRatio", &ecs::Camera::aspectRatio);-- // Sprite component- value_object<ecs::Sprite>("Sprite")- .field("color", &ecs::Sprite::color)- .field("size", &ecs::Sprite::size);-}--// =============================================================================-// ECS Registry-// =============================================================================--EMSCRIPTEN_BINDINGS(esengine_registry) {- class_<ecs::Registry>("Registry")- .constructor<>()-- // Entity management- .function("create", optional_override([](ecs::Registry& self) {- return self.create();- }))- .function("destroy", optional_override([](ecs::Registry& self, Entity e) {- self.destroy(e);- }))- .function("valid", optional_override([](ecs::Registry& self, Entity e) {- return self.valid(e);- }))- .function("entityCount", optional_override([](const ecs::Registry& self) {- return self.entityCount();- }))-- // LocalTransform component- .function("hasTransform", optional_override([](ecs::Registry& self, Entity e) {- return self.has<ecs::LocalTransform>(e);- }))- .function("getTransform", optional_override([](ecs::Registry& self, Entity e) -> ecs::LocalTransform& {- return self.get<ecs::LocalTransform>(e);- }))- .function("addTransform", optional_override([](ecs::Registry& self, Entity e, const ecs::LocalTransform& t) -> ecs::LocalTransform& {- return self.emplaceOrReplace<ecs::LocalTransform>(e, t);- }))- .function("removeTransform", optional_override([](ecs::Registry& self, Entity e) {- self.remove<ecs::LocalTransform>(e);- }))-- // WorldTransform component (usually managed by TransformSystem)- .function("hasWorldTransform", optional_override([](ecs::Registry& self, Entity e) {- return self.has<ecs::WorldTransform>(e);- }))- .function("getWorldTransform", optional_override([](ecs::Registry& self, Entity e) -> ecs::WorldTransform& {- return self.get<ecs::WorldTransform>(e);- }))-- // Parent/Children hierarchy- .function("hasParent", optional_override([](ecs::Registry& self, Entity e) {- return self.has<ecs::Parent>(e);- }))- .function("getParent", optional_override([](ecs::Registry& self, Entity e) -> ecs::Parent& {- return self.get<ecs::Parent>(e);- }))- .function("addParent", optional_override([](ecs::Registry& self, Entity e, const ecs::Parent& p) -> ecs::Parent& {- return self.emplaceOrReplace<ecs::Parent>(e, p);- }))- .function("removeParent", optional_override([](ecs::Registry& self, Entity e) {- self.remove<ecs::Parent>(e);- }))-- .function("hasChildren", optional_override([](ecs::Registry& self, Entity e) {- return self.has<ecs::Children>(e);- }))- .function("getChildren", optional_override([](ecs::Registry& self, Entity e) -> ecs::Children& {- return self.get<ecs::Children>(e);- }))-- // Velocity component- .function("hasVelocity", optional_override([](ecs::Registry& self, Entity e) {- return self.has<ecs::Velocity>(e);- }))- .function("getVelocity", optional_override([](ecs::Registry& self, Entity e) -> ecs::Velocity& {- return self.get<ecs::Velocity>(e);- }))- .function("addVelocity", optional_override([](ecs::Registry& self, Entity e, const ecs::Velocity& v) -> ecs::Velocity& {- return self.emplaceOrReplace<ecs::Velocity>(e, v);- }))- .function("removeVelocity", optional_override([](ecs::Registry& self, Entity e) {- self.remove<ecs::Velocity>(e);- }))-- // Camera component- .function("hasCamera", optional_override([](ecs::Registry& self, Entity e) {- return self.has<ecs::Camera>(e);- }))- .function("getCamera", optional_override([](ecs::Registry& self, Entity e) -> ecs::Camera& {- return self.get<ecs::Camera>(e);- }))- .function("addCamera", optional_override([](ecs::Registry& self, Entity e, const ecs::Camera& c) -> ecs::Camera& {- return self.emplaceOrReplace<ecs::Camera>(e, c);- }))- .function("removeCamera", optional_override([](ecs::Registry& self, Entity e) {- self.remove<ecs::Camera>(e);- }))-- // Sprite component- .function("hasSprite", optional_override([](ecs::Registry& self, Entity e) {- return self.has<ecs::Sprite>(e);- }))- .function("getSprite", optional_override([](ecs::Registry& self, Entity e) -> ecs::Sprite& {- return self.get<ecs::Sprite>(e);- }))- .function("addSprite", optional_override([](ecs::Registry& self, Entity e, const ecs::Sprite& s) -> ecs::Sprite& {- return self.emplaceOrReplace<ecs::Sprite>(e, s);- }))- .function("removeSprite", optional_override([](ecs::Registry& self, Entity e) {- self.remove<ecs::Sprite>(e);- }));-}--} // namespace esengine--#endif // ES_PLATFORM_WEBdiff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cppnew file mode 100644index 000000000..6611f50e5--- /dev/null+++ b/src/esengine/bindings/WebBindings.generated.cpp@@ -0,0 +1,256 @@+/**+ * @file WebBindings.generated.cpp+ * @brief Auto-generated Emscripten bindings+ * @details Generated by tools/generate_bindings.py - DO NOT EDIT MANUALLY+ *+ * @author ESEngine Binding Generator+ * @date 2026+ */++#ifdef ES_PLATFORM_WEB++#include <emscripten/bind.h>+#include "../ecs/Registry.hpp"+#include "../ecs/Entity.hpp"+#include "../math/Math.hpp"++#include "../ecs/components/Camera.hpp"+#include "../ecs/components/Hierarchy.hpp"+#include "../ecs/components/Sprite.hpp"+#include "../ecs/components/Transform.hpp"+#include "../ecs/components/Velocity.hpp"++using namespace emscripten;++namespace esengine {++// =============================================================================+// Math Types+// =============================================================================++EMSCRIPTEN_BINDINGS(esengine_math) {+ // Vec2+ value_object<glm::vec2>("Vec2")+ .field("x", &glm::vec2::x)+ .field("y", &glm::vec2::y);++ // Vec3+ value_object<glm::vec3>("Vec3")+ .field("x", &glm::vec3::x)+ .field("y", &glm::vec3::y)+ .field("z", &glm::vec3::z);++ // Vec4+ value_object<glm::vec4>("Vec4")+ .field("x", &glm::vec4::x)+ .field("y", &glm::vec4::y)+ .field("z", &glm::vec4::z)+ .field("w", &glm::vec4::w);++ // Quat+ value_object<glm::quat>("Quat")+ .field("x", &glm::quat::x)+ .field("y", &glm::quat::y)+ .field("z", &glm::quat::z)+ .field("w", &glm::quat::w);+}++// =============================================================================+// ECS Entity Type+// =============================================================================++EMSCRIPTEN_BINDINGS(esengine_entity) {+ // Entity is u32, exposed as number in JavaScript+}++// =============================================================================+// ECS Components+// =============================================================================++EMSCRIPTEN_BINDINGS(esengine_components) {+ // Camera component+ value_object<esengine::ecs::Camera>("Camera")+ .field("projectionType", &esengine::ecs::Camera::projectionType)+ .field("fov", &esengine::ecs::Camera::fov)+ .field("orthoSize", &esengine::ecs::Camera::orthoSize)+ .field("nearPlane", &esengine::ecs::Camera::nearPlane)+ .field("farPlane", &esengine::ecs::Camera::farPlane)+ .field("aspectRatio", &esengine::ecs::Camera::aspectRatio)+ .field("isActive", &esengine::ecs::Camera::isActive)+ .field("priority", &esengine::ecs::Camera::priority)+ ;++ // Parent component+ value_object<esengine::ecs::Parent>("Parent")+ .field("entity", &esengine::ecs::Parent::entity)+ ;++ // Children component+ value_object<esengine::ecs::Children>("Children")+ ;++ // Sprite component+ value_object<esengine::ecs::Sprite>("Sprite")+ .field("texture", &esengine::ecs::Sprite::texture)+ .field("color", &esengine::ecs::Sprite::color)+ .field("size", &esengine::ecs::Sprite::size)+ .field("uvOffset", &esengine::ecs::Sprite::uvOffset)+ .field("uvScale", &esengine::ecs::Sprite::uvScale)+ .field("layer", &esengine::ecs::Sprite::layer)+ .field("flipX", &esengine::ecs::Sprite::flipX)+ .field("flipY", &esengine::ecs::Sprite::flipY)+ ;++ // LocalTransform component+ value_object<esengine::ecs::LocalTransform>("LocalTransform")+ .field("position", &esengine::ecs::LocalTransform::position)+ .field("rotation", &esengine::ecs::LocalTransform::rotation)+ .field("scale", &esengine::ecs::LocalTransform::scale)+ .field("matrix", &esengine::ecs::LocalTransform::matrix)+ .field("position", &esengine::ecs::LocalTransform::position)+ .field("rotation", &esengine::ecs::LocalTransform::rotation)+ .field("scale", &esengine::ecs::LocalTransform::scale)+ ;++ // WorldTransform component+ value_object<esengine::ecs::WorldTransform>("WorldTransform")+ .field("matrix", &esengine::ecs::WorldTransform::matrix)+ .field("position", &esengine::ecs::WorldTransform::position)+ .field("rotation", &esengine::ecs::WorldTransform::rotation)+ .field("scale", &esengine::ecs::WorldTransform::scale)+ ;++ // Velocity component+ value_object<esengine::ecs::Velocity>("Velocity")+ .field("linear", &esengine::ecs::Velocity::linear)+ .field("angular", &esengine::ecs::Velocity::angular)+ ;++}++// =============================================================================+// ECS Registry+// =============================================================================++EMSCRIPTEN_BINDINGS(esengine_registry) {+ class_<ecs::Registry>("Registry")+ .constructor<>()++ // Entity management+ .function("create", optional_override([](ecs::Registry& self) {+ return self.create();+ }))+ .function("destroy", optional_override([](ecs::Registry& self, Entity e) {+ self.destroy(e);+ }))+ .function("valid", optional_override([](ecs::Registry& self, Entity e) {+ return self.valid(e);+ }))+ .function("entityCount", optional_override([](const ecs::Registry& self) {+ return self.entityCount();+ }))++ // Camera component+ .function("hasCamera", optional_override([](ecs::Registry& self, Entity e) {+ return self.has<esengine::ecs::Camera>(e);+ }))+ .function("getCamera", optional_override([](ecs::Registry& self, Entity e) -> esengine::ecs::Camera& {+ return self.get<esengine::ecs::Camera>(e);+ }))+ .function("addCamera", optional_override([](ecs::Registry& self, Entity e, const esengine::ecs::Camera& c) -> esengine::ecs::Camera& {+ return self.emplaceOrReplace<esengine::ecs::Camera>(e, c);+ }))+ .function("removeCamera", optional_override([](ecs::Registry& self, Entity e) {+ self.remove<esengine::ecs::Camera>(e);+ }))++ // Parent component+ .function("hasParent", optional_override([](ecs::Registry& self, Entity e) {+ return self.has<esengine::ecs::Parent>(e);+ }))+ .function("getParent", optional_override([](ecs::Registry& self, Entity e) -> esengine::ecs::Parent& {+ return self.get<esengine::ecs::Parent>(e);+ }))+ .function("addParent", optional_override([](ecs::Registry& self, Entity e, const esengine::ecs::Parent& c) -> esengine::ecs::Parent& {+ return self.emplaceOrReplace<esengine::ecs::Parent>(e, c);+ }))+ .function("removeParent", optional_override([](ecs::Registry& self, Entity e) {+ self.remove<esengine::ecs::Parent>(e);+ }))++ // Children component+ .function("hasChildren", optional_override([](ecs::Registry& self, Entity e) {+ return self.has<esengine::ecs::Children>(e);+ }))+ .function("getChildren", optional_override([](ecs::Registry& self, Entity e) -> esengine::ecs::Children& {+ return self.get<esengine::ecs::Children>(e);+ }))+ .function("addChildren", optional_override([](ecs::Registry& self, Entity e, const esengine::ecs::Children& c) -> esengine::ecs::Children& {+ return self.emplaceOrReplace<esengine::ecs::Children>(e, c);+ }))+ .function("removeChildren", optional_override([](ecs::Registry& self, Entity e) {+ self.remove<esengine::ecs::Children>(e);+ }))++ // Sprite component+ .function("hasSprite", optional_override([](ecs::Registry& self, Entity e) {+ return self.has<esengine::ecs::Sprite>(e);+ }))+ .function("getSprite", optional_override([](ecs::Registry& self, Entity e) -> esengine::ecs::Sprite& {+ return self.get<esengine::ecs::Sprite>(e);+ }))+ .function("addSprite", optional_override([](ecs::Registry& self, Entity e, const esengine::ecs::Sprite& c) -> esengine::ecs::Sprite& {+ return self.emplaceOrReplace<esengine::ecs::Sprite>(e, c);+ }))+ .function("removeSprite", optional_override([](ecs::Registry& self, Entity e) {+ self.remove<esengine::ecs::Sprite>(e);+ }))++ // LocalTransform component+ .function("hasLocalTransform", optional_override([](ecs::Registry& self, Entity e) {+ return self.has<esengine::ecs::LocalTransform>(e);+ }))+ .function("getLocalTransform", optional_override([](ecs::Registry& self, Entity e) -> esengine::ecs::LocalTransform& {+ return self.get<esengine::ecs::LocalTransform>(e);+ }))+ .function("addLocalTransform", optional_override([](ecs::Registry& self, Entity e, const esengine::ecs::LocalTransform& c) -> esengine::ecs::LocalTransform& {+ return self.emplaceOrReplace<esengine::ecs::LocalTransform>(e, c);+ }))+ .function("removeLocalTransform", optional_override([](ecs::Registry& self, Entity e) {+ self.remove<esengine::ecs::LocalTransform>(e);+ }))++ // WorldTransform component+ .function("hasWorldTransform", optional_override([](ecs::Registry& self, Entity e) {+ return self.has<esengine::ecs::WorldTransform>(e);+ }))+ .function("getWorldTransform", optional_override([](ecs::Registry& self, Entity e) -> esengine::ecs::WorldTransform& {+ return self.get<esengine::ecs::WorldTransform>(e);+ }))+ .function("addWorldTransform", optional_override([](ecs::Registry& self, Entity e, const esengine::ecs::WorldTransform& c) -> esengine::ecs::WorldTransform& {+ return self.emplaceOrReplace<esengine::ecs::WorldTransform>(e, c);+ }))+ .function("removeWorldTransform", optional_override([](ecs::Registry& self, Entity e) {+ self.remove<esengine::ecs::WorldTransform>(e);+ }))++ // Velocity component+ .function("hasVelocity", optional_override([](ecs::Registry& self, Entity e) {+ return self.has<esengine::ecs::Velocity>(e);+ }))+ .function("getVelocity", optional_override([](ecs::Registry& self, Entity e) -> esengine::ecs::Velocity& {+ return self.get<esengine::ecs::Velocity>(e);+ }))+ .function("addVelocity", optional_override([](ecs::Registry& self, Entity e, const esengine::ecs::Velocity& c) -> esengine::ecs::Velocity& {+ return self.emplaceOrReplace<esengine::ecs::Velocity>(e, c);+ }))+ .function("removeVelocity", optional_override([](ecs::Registry& self, Entity e) {+ self.remove<esengine::ecs::Velocity>(e);+ }))++ ;+}++} // namespace esengine++#endif // ES_PLATFORM_WEBdiff --git a/src/esengine/core/Reflection.hpp b/src/esengine/core/Reflection.hppnew file mode 100644index 000000000..a69b81d27--- /dev/null+++ b/src/esengine/core/Reflection.hpp@@ -0,0 +1,188 @@+/**+ * @file Reflection.hpp+ * @brief Reflection and metadata system for automatic binding generation+ * @details Provides macros for marking components and properties that should+ * be automatically exposed to scripting languages. Uses a declarative+ * macro-based approach for code generation.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the MIT License.+ */+#pragma once++// =============================================================================+// Reflection Macros+// =============================================================================++/**+ * @brief Mark a struct/class as a component that should be exposed to scripts+ *+ * @details This macro generates metadata that the binding generator tool uses+ * to automatically create JavaScript/TypeScript bindings. Place this+ * macro immediately before the struct/class definition.+ *+ * @code+ * ES_COMPONENT()+ * struct Transform {+ * ES_PROPERTY()+ * glm::vec3 position{0.0f};+ * };+ * @endcode+ */+#define ES_COMPONENT()++/**+ * @brief Mark a field as a property that should be exposed to scripts+ *+ * @details Properties marked with this macro will be accessible from+ * JavaScript/TypeScript with automatic getter/setter generation.+ * Only works inside ES_COMPONENT() marked types.+ */+#define ES_PROPERTY()++/**+ * @brief Mark a method that should be exposed to scripts+ *+ * @details Methods marked with this macro will be callable from+ * JavaScript/TypeScript. Works for both member functions+ * and static functions.+ *+ * @param ... Optional attributes (e.g., "const", "static")+ */+#define ES_METHOD(...)++/**+ * @brief Mark an enum that should be exposed to scripts+ *+ * @details Enums marked with this macro will be available as+ * TypeScript enums with proper type checking.+ */+#define ES_ENUM()++/**+ * @brief Mark an enum value for explicit naming in bindings+ *+ * @details Use this to provide custom names for enum values in scripts,+ * or to document their meaning for the binding generator.+ *+ * @param name Optional custom name for the enum value+ */+#define ES_ENUM_VALUE(name)++// =============================================================================+// Metadata Extraction Markers+// =============================================================================++/**+ * @brief Begin a reflection block for the binding generator+ *+ * @details The binding generator tool scans for blocks between+ * ES_REFLECT_BEGIN and ES_REFLECT_END to find types that+ * need bindings. This is used in header files.+ */+#define ES_REFLECT_BEGIN++/**+ * @brief End a reflection block for the binding generator+ */+#define ES_REFLECT_END++// =============================================================================+// Type Traits for Reflection+// =============================================================================++namespace esengine {++/**+ * @brief Type trait to detect if a type is a reflected component+ *+ * @details This is used by the binding system to verify types at compile time.+ * Specialized by the binding generator for each ES_COMPONENT type.+ *+ * @tparam T Type to check+ */+template<typename T>+struct is_component : std::false_type {};++/**+ * @brief Helper variable template for is_component+ */+template<typename T>+inline constexpr bool is_component_v = is_component<T>::value;++/**+ * @brief Get the script name for a component type+ *+ * @details Returns the name used in JavaScript/TypeScript bindings.+ * Specialized by the binding generator for each ES_COMPONENT type.+ *+ * @tparam T Component type+ * @return Script name as string literal+ */+template<typename T>+inline constexpr const char* component_name() {+ return "UnknownComponent";+}++} // namespace esengine++// =============================================================================+// Usage Examples+// =============================================================================++/**+ * @example Basic Component+ *+ * @code+ * ES_COMPONENT()+ * struct Position {+ * ES_PROPERTY()+ * f32 x = 0.0f;+ *+ * ES_PROPERTY()+ * f32 y = 0.0f;+ * };+ * @endcode+ *+ * @example Component with Methods+ *+ * @code+ * ES_COMPONENT()+ * struct Health {+ * ES_PROPERTY()+ * f32 current = 100.0f;+ *+ * ES_PROPERTY()+ * f32 maximum = 100.0f;+ *+ * ES_METHOD()+ * void heal(f32 amount) {+ * current = std::min(current + amount, maximum);+ * }+ *+ * ES_METHOD(const)+ * bool isDead() const {+ * return current <= 0.0f;+ * }+ * };+ * @endcode+ *+ * @example Enum Binding+ *+ * @code+ * ES_ENUM()+ * enum class DamageType : u8 {+ * ES_ENUM_VALUE("Physical")+ * Physical,+ *+ * ES_ENUM_VALUE("Magical")+ * Magical,+ *+ * ES_ENUM_VALUE("True")+ * True+ * };+ * @endcode+ */diff --git a/src/esengine/ecs/components/Camera.hpp b/src/esengine/ecs/components/Camera.hppindex 9a18ffb32..aa41709dc 100644--- a/src/esengine/ecs/components/Camera.hpp+++ b/src/esengine/ecs/components/Camera.hpp@@ -16,6 +16,7 @@// =============================================================================#include "../../core/Types.hpp"+#include "../../core/Reflection.hpp"namespace esengine::ecs {@@ -50,29 +51,38 @@ enum class ProjectionType : u8 {* cam.isActive = true;* @endcode*/+ES_COMPONENT()struct Camera {/** @brief Projection type */+ ES_PROPERTY()ProjectionType projectionType{ProjectionType::Perspective};/** @brief Field of view in degrees (perspective only) */+ ES_PROPERTY()f32 fov{60.0f};/** @brief Orthographic size (half-height in world units) */+ ES_PROPERTY()f32 orthoSize{5.0f};/** @brief Near clipping plane distance */+ ES_PROPERTY()f32 nearPlane{0.1f};/** @brief Far clipping plane distance */+ ES_PROPERTY()f32 farPlane{1000.0f};/** @brief Aspect ratio (width / height), 0 = auto from viewport */+ ES_PROPERTY()f32 aspectRatio{0.0f};/** @brief Whether this is the active camera */+ ES_PROPERTY()bool isActive{false};/** @brief Priority for determining active camera (higher = preferred) */+ ES_PROPERTY()i32 priority{0};Camera() = default;diff --git a/src/esengine/ecs/components/Hierarchy.hpp b/src/esengine/ecs/components/Hierarchy.hppindex b97129cc4..e0a2704b8 100644--- a/src/esengine/ecs/components/Hierarchy.hpp+++ b/src/esengine/ecs/components/Hierarchy.hpp@@ -16,6 +16,7 @@// =============================================================================#include "../../core/Types.hpp"+#include "../../core/Reflection.hpp"#include <vector>@@ -39,8 +40,10 @@ namespace esengine::ecs {* registry.get<Children>(parent).entities.push_back(child);* @endcode*/+ES_COMPONENT()struct Parent {/** @brief Parent entity ID */+ ES_PROPERTY()Entity entity = INVALID_ENTITY;Parent() = default;@@ -57,6 +60,7 @@ struct Parent {* @details Stores references to all child entities. Maintained in sync* with Parent components by the hierarchy management system.*/+ES_COMPONENT()struct Children {/** @brief List of child entity IDs */std::vector<Entity> entities;diff --git a/src/esengine/ecs/components/Sprite.hpp b/src/esengine/ecs/components/Sprite.hppindex 909968f57..962153bf3 100644--- a/src/esengine/ecs/components/Sprite.hpp+++ b/src/esengine/ecs/components/Sprite.hpp@@ -16,6 +16,7 @@// =============================================================================#include "../../core/Types.hpp"+#include "../../core/Reflection.hpp"#include "../../math/Math.hpp"#include "../../resource/Handle.hpp"@@ -40,29 +41,38 @@ namespace esengine::ecs {* sprite.layer = 10; // Render on top* @endcode*/+ES_COMPONENT()struct Sprite {/** @brief Texture resource handle (type-safe) */+ ES_PROPERTY()resource::TextureHandle texture;/** @brief Color tint (RGBA, 0-1 range) */+ ES_PROPERTY()glm::vec4 color{1.0f, 1.0f, 1.0f, 1.0f};/** @brief Sprite size in world units */+ ES_PROPERTY()glm::vec2 size{1.0f, 1.0f};/** @brief UV coordinate offset for sprite sheets */+ ES_PROPERTY()glm::vec2 uvOffset{0.0f, 0.0f};/** @brief UV coordinate scale for sprite sheets */+ ES_PROPERTY()glm::vec2 uvScale{1.0f, 1.0f};/** @brief Sorting layer (higher = rendered on top) */+ ES_PROPERTY()i32 layer{0};/** @brief Flip sprite horizontally */+ ES_PROPERTY()bool flipX{false};/** @brief Flip sprite vertically */+ ES_PROPERTY()bool flipY{false};/** @brief Default constructor (white, no texture) */diff --git a/src/esengine/ecs/components/Transform.hpp b/src/esengine/ecs/components/Transform.hppindex 47b1784c6..b4d9cd3be 100644--- a/src/esengine/ecs/components/Transform.hpp+++ b/src/esengine/ecs/components/Transform.hpp@@ -17,6 +17,7 @@// =============================================================================#include "../../core/Types.hpp"+#include "../../core/Reflection.hpp"#include "../../math/Math.hpp"namespace esengine::ecs {@@ -44,14 +45,18 @@ namespace esengine::ecs {* transform.rotation = glm::angleAxis(glm::radians(45.0f), glm::vec3(0, 1, 0));* @endcode*/+ES_COMPONENT()struct LocalTransform {/** @brief Position relative to parent */+ ES_PROPERTY()glm::vec3 position{0.0f, 0.0f, 0.0f};/** @brief Rotation as quaternion (no gimbal lock) */+ ES_PROPERTY()glm::quat rotation{1.0f, 0.0f, 0.0f, 0.0f}; // Identity quaternion (w, x, y, z)/** @brief Scale factors */+ ES_PROPERTY()glm::vec3 scale{1.0f, 1.0f, 1.0f};/** @brief Default constructor (identity transform) */@@ -95,17 +100,22 @@ struct LocalTransform {* @note Do not modify this component directly - it will be overwritten* by TransformSystem. Modify LocalTransform instead.*/+ES_COMPONENT()struct WorldTransform {/** @brief Combined world-space transformation matrix */+ ES_PROPERTY()glm::mat4 matrix{1.0f};/** @brief World-space position (extracted from matrix for convenience) */+ ES_PROPERTY()glm::vec3 position{0.0f, 0.0f, 0.0f};/** @brief World-space rotation (extracted from matrix) */+ ES_PROPERTY()glm::quat rotation{1.0f, 0.0f, 0.0f, 0.0f};/** @brief World-space scale (extracted from matrix) */+ ES_PROPERTY()glm::vec3 scale{1.0f, 1.0f, 1.0f};WorldTransform() = default;diff --git a/src/esengine/ecs/components/Velocity.hpp b/src/esengine/ecs/components/Velocity.hppindex 4fa9f346a..e53ac4cda 100644--- a/src/esengine/ecs/components/Velocity.hpp+++ b/src/esengine/ecs/components/Velocity.hpp@@ -16,6 +16,7 @@// =============================================================================#include "../../core/Types.hpp"+#include "../../core/Reflection.hpp"#include "../../math/Math.hpp"namespace esengine::ecs {@@ -32,11 +33,14 @@ namespace esengine::ecs {** @note Angular velocity is in radians per second around each axis.*/+ES_COMPONENT()struct Velocity {/** @brief Linear velocity (units per second) */+ ES_PROPERTY()glm::vec3 linear{0.0f};/** @brief Angular velocity (radians per second) */+ ES_PROPERTY()glm::vec3 angular{0.0f};/** @brief Default constructor (zero velocity) */diff --git a/src/esengine/scripting/bindings/ECSBindings.cpp b/src/esengine/scripting/bindings/ECSBindings.cppdeleted file mode 100644index c9fa3b4e1..000000000--- a/src/esengine/scripting/bindings/ECSBindings.cpp+++ /dev/null@@ -1,416 +0,0 @@-/**- * @file ECSBindings.cpp- * @brief JavaScript bindings for ECS system implementation- *- * @author ESEngine Team- * @date 2026- *- * @copyright Copyright (c) 2026 ESEngine Team- * Licensed under the MIT License.- */--#include "ECSBindings.hpp"-#include "../../core/Log.hpp"-#include "../../ecs/Registry.hpp"-#include "../../ecs/components/Transform.hpp"-#include "../../ecs/components/Velocity.hpp"-#include "../ScriptValue.hpp"--#ifdef ES_SCRIPTING_ENABLED- #include <quickjs.h>-#endif--namespace esengine {--#ifdef ES_SCRIPTING_ENABLED--// Global registry pointer (set by bindECS)-static ecs::Registry* g_registry = nullptr;--// =============================================================================-// Helper functions for type conversion-// =============================================================================--/**- * @brief Convert JavaScript object to glm::vec3- */-static glm::vec3 jsToVec3(JSContext* ctx, JSValue jsObj) {- glm::vec3 result(0.0f);-- JSValue x = JS_GetPropertyStr(ctx, jsObj, "x");- JSValue y = JS_GetPropertyStr(ctx, jsObj, "y");- JSValue z = JS_GetPropertyStr(ctx, jsObj, "z");-- double dx, dy, dz;- JS_ToFloat64(ctx, &dx, x);- JS_ToFloat64(ctx, &dy, y);- JS_ToFloat64(ctx, &dz, z);-- result.x = static_cast<f32>(dx);- result.y = static_cast<f32>(dy);- result.z = static_cast<f32>(dz);-- JS_FreeValue(ctx, x);- JS_FreeValue(ctx, y);- JS_FreeValue(ctx, z);-- return result;-}--/**- * @brief Convert glm::vec3 to JavaScript object- */-static JSValue vec3ToJS(JSContext* ctx, const glm::vec3& vec) {- JSValue obj = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, obj, "x", JS_NewFloat64(ctx, vec.x));- JS_SetPropertyStr(ctx, obj, "y", JS_NewFloat64(ctx, vec.y));- JS_SetPropertyStr(ctx, obj, "z", JS_NewFloat64(ctx, vec.z));- return obj;-}--/**- * @brief Convert JavaScript object to glm::quat- */-static glm::quat jsToQuat(JSContext* ctx, JSValue jsObj) {- glm::quat result(1.0f, 0.0f, 0.0f, 0.0f); // identity-- JSValue w = JS_GetPropertyStr(ctx, jsObj, "w");- JSValue x = JS_GetPropertyStr(ctx, jsObj, "x");- JSValue y = JS_GetPropertyStr(ctx, jsObj, "y");- JSValue z = JS_GetPropertyStr(ctx, jsObj, "z");-- double dw, dx, dy, dz;- JS_ToFloat64(ctx, &dw, w);- JS_ToFloat64(ctx, &dx, x);- JS_ToFloat64(ctx, &dy, y);- JS_ToFloat64(ctx, &dz, z);-- result.w = static_cast<f32>(dw);- result.x = static_cast<f32>(dx);- result.y = static_cast<f32>(dy);- result.z = static_cast<f32>(dz);-- JS_FreeValue(ctx, w);- JS_FreeValue(ctx, x);- JS_FreeValue(ctx, y);- JS_FreeValue(ctx, z);-- return result;-}--/**- * @brief Convert glm::quat to JavaScript object- */-static JSValue quatToJS(JSContext* ctx, const glm::quat& quat) {- JSValue obj = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, obj, "w", JS_NewFloat64(ctx, quat.w));- JS_SetPropertyStr(ctx, obj, "x", JS_NewFloat64(ctx, quat.x));- JS_SetPropertyStr(ctx, obj, "y", JS_NewFloat64(ctx, quat.y));- JS_SetPropertyStr(ctx, obj, "z", JS_NewFloat64(ctx, quat.z));- return obj;-}--// =============================================================================-// Registry bindings-// =============================================================================--/**- * @brief Registry.create() - Create new entity- */-static JSValue js_Registry_create(JSContext* ctx, JSValue this_val, int argc, JSValue* argv) {- (void)this_val;- (void)argc;- (void)argv;-- if (!g_registry) {- return JS_ThrowReferenceError(ctx, "Registry not bound");- }-- Entity entity = g_registry->create();- return JS_NewUint32(ctx, static_cast<u32>(entity));-}--/**- * @brief Registry.destroy(entity) - Destroy entity- */-static JSValue js_Registry_destroy(JSContext* ctx, JSValue this_val, int argc, JSValue* argv) {- (void)this_val;-- if (argc < 1) {- return JS_ThrowTypeError(ctx, "destroy() requires entity argument");- }-- if (!g_registry) {- return JS_ThrowReferenceError(ctx, "Registry not bound");- }-- u32 entityId;- if (JS_ToUint32(ctx, &entityId, argv[0]) < 0) {- return JS_ThrowTypeError(ctx, "entity must be a number");- }-- g_registry->destroy(static_cast<Entity>(entityId));- return JS_UNDEFINED;-}--/**- * @brief Registry.valid(entity) - Check if entity is valid- */-static JSValue js_Registry_valid(JSContext* ctx, JSValue this_val, int argc, JSValue* argv) {- (void)this_val;-- if (argc < 1) {- return JS_ThrowTypeError(ctx, "valid() requires entity argument");- }-- if (!g_registry) {- return JS_ThrowReferenceError(ctx, "Registry not bound");- }-- u32 entityId;- if (JS_ToUint32(ctx, &entityId, argv[0]) < 0) {- return JS_ThrowTypeError(ctx, "entity must be a number");- }-- bool isValid = g_registry->valid(static_cast<Entity>(entityId));- return JS_NewBool(ctx, isValid);-}--// =============================================================================-// Transform component bindings-// =============================================================================--/**- * @brief Registry.getTransform(entity) - Get LocalTransform component- */-static JSValue js_Registry_getTransform(JSContext* ctx, JSValue this_val, int argc, JSValue* argv) {- (void)this_val;-- if (argc < 1) {- return JS_ThrowTypeError(ctx, "getTransform() requires entity argument");- }-- if (!g_registry) {- return JS_ThrowReferenceError(ctx, "Registry not bound");- }-- u32 entityId;- if (JS_ToUint32(ctx, &entityId, argv[0]) < 0) {- return JS_ThrowTypeError(ctx, "entity must be a number");- }-- Entity entity = static_cast<Entity>(entityId);-- if (!g_registry->has<ecs::LocalTransform>(entity)) {- return JS_ThrowReferenceError(ctx, "Entity does not have Transform component");- }-- const auto& transform = g_registry->get<ecs::LocalTransform>(entity);-- // Create JavaScript object- JSValue obj = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, obj, "position", vec3ToJS(ctx, transform.position));- JS_SetPropertyStr(ctx, obj, "rotation", quatToJS(ctx, transform.rotation));- JS_SetPropertyStr(ctx, obj, "scale", vec3ToJS(ctx, transform.scale));-- return obj;-}--/**- * @brief Registry.setTransform(entity, transform) - Set LocalTransform component- */-static JSValue js_Registry_setTransform(JSContext* ctx, JSValue this_val, int argc, JSValue* argv) {- (void)this_val;-- if (argc < 2) {- return JS_ThrowTypeError(ctx, "setTransform() requires entity and transform arguments");- }-- if (!g_registry) {- return JS_ThrowReferenceError(ctx, "Registry not bound");- }-- u32 entityId;- if (JS_ToUint32(ctx, &entityId, argv[0]) < 0) {- return JS_ThrowTypeError(ctx, "entity must be a number");- }-- Entity entity = static_cast<Entity>(entityId);-- // Parse transform object- JSValue jsTransform = argv[1];- if (!JS_IsObject(jsTransform)) {- return JS_ThrowTypeError(ctx, "transform must be an object");- }-- ecs::LocalTransform transform;-- // Get position- JSValue jsPosition = JS_GetPropertyStr(ctx, jsTransform, "position");- if (JS_IsObject(jsPosition)) {- transform.position = jsToVec3(ctx, jsPosition);- }- JS_FreeValue(ctx, jsPosition);-- // Get rotation- JSValue jsRotation = JS_GetPropertyStr(ctx, jsTransform, "rotation");- if (JS_IsObject(jsRotation)) {- transform.rotation = jsToQuat(ctx, jsRotation);- }- JS_FreeValue(ctx, jsRotation);-- // Get scale- JSValue jsScale = JS_GetPropertyStr(ctx, jsTransform, "scale");- if (JS_IsObject(jsScale)) {- transform.scale = jsToVec3(ctx, jsScale);- }- JS_FreeValue(ctx, jsScale);-- // Set or add component- g_registry->emplaceOrReplace<ecs::LocalTransform>(entity, transform);-- return JS_UNDEFINED;-}--// =============================================================================-// Velocity component bindings-// =============================================================================--/**- * @brief Registry.getVelocity(entity) - Get Velocity component- */-static JSValue js_Registry_getVelocity(JSContext* ctx, JSValue this_val, int argc, JSValue* argv) {- (void)this_val;-- if (argc < 1) {- return JS_ThrowTypeError(ctx, "getVelocity() requires entity argument");- }-- if (!g_registry) {- return JS_ThrowReferenceError(ctx, "Registry not bound");- }-- u32 entityId;- if (JS_ToUint32(ctx, &entityId, argv[0]) < 0) {- return JS_ThrowTypeError(ctx, "entity must be a number");- }-- Entity entity = static_cast<Entity>(entityId);-- if (!g_registry->has<ecs::Velocity>(entity)) {- return JS_ThrowReferenceError(ctx, "Entity does not have Velocity component");- }-- const auto& velocity = g_registry->get<ecs::Velocity>(entity);-- JSValue obj = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, obj, "linear", vec3ToJS(ctx, velocity.linear));- JS_SetPropertyStr(ctx, obj, "angular", vec3ToJS(ctx, velocity.angular));-- return obj;-}--/**- * @brief Registry.setVelocity(entity, velocity) - Set Velocity component- */-static JSValue js_Registry_setVelocity(JSContext* ctx, JSValue this_val, int argc, JSValue* argv) {- (void)this_val;-- if (argc < 2) {- return JS_ThrowTypeError(ctx, "setVelocity() requires entity and velocity arguments");- }-- if (!g_registry) {- return JS_ThrowReferenceError(ctx, "Registry not bound");- }-- u32 entityId;- if (JS_ToUint32(ctx, &entityId, argv[0]) < 0) {- return JS_ThrowTypeError(ctx, "entity must be a number");- }-- Entity entity = static_cast<Entity>(entityId);-- JSValue jsVelocity = argv[1];- if (!JS_IsObject(jsVelocity)) {- return JS_ThrowTypeError(ctx, "velocity must be an object");- }-- ecs::Velocity velocity;-- JSValue jsLinear = JS_GetPropertyStr(ctx, jsVelocity, "linear");- if (JS_IsObject(jsLinear)) {- velocity.linear = jsToVec3(ctx, jsLinear);- }- JS_FreeValue(ctx, jsLinear);-- JSValue jsAngular = JS_GetPropertyStr(ctx, jsVelocity, "angular");- if (JS_IsObject(jsAngular)) {- velocity.angular = jsToVec3(ctx, jsAngular);- }- JS_FreeValue(ctx, jsAngular);-- g_registry->emplaceOrReplace<ecs::Velocity>(entity, velocity);-- return JS_UNDEFINED;-}--// =============================================================================-// Main binding function-// =============================================================================--void bindECS(ScriptContext& ctx, ecs::Registry& registry) {- if (!ctx.isInitialized()) {- ES_LOG_ERROR("Cannot bind ECS to uninitialized ScriptContext");- return;- }-- g_registry = ®istry;-- JSContext* jsCtx = ctx.getJSContext();-- // Get global object- JSValue global = JS_GetGlobalObject(jsCtx);-- // Create Registry object- JSValue registryObj = JS_NewObject(jsCtx);-- // Bind Registry methods- JS_SetPropertyStr(jsCtx, registryObj, "create",- JS_NewCFunction(jsCtx, js_Registry_create, "create", 0));- JS_SetPropertyStr(jsCtx, registryObj, "destroy",- JS_NewCFunction(jsCtx, js_Registry_destroy, "destroy", 1));- JS_SetPropertyStr(jsCtx, registryObj, "valid",- JS_NewCFunction(jsCtx, js_Registry_valid, "valid", 1));-- // Bind Transform methods- JS_SetPropertyStr(jsCtx, registryObj, "getTransform",- JS_NewCFunction(jsCtx, js_Registry_getTransform, "getTransform", 1));- JS_SetPropertyStr(jsCtx, registryObj, "setTransform",- JS_NewCFunction(jsCtx, js_Registry_setTransform, "setTransform", 2));-- // Bind Velocity methods- JS_SetPropertyStr(jsCtx, registryObj, "getVelocity",- JS_NewCFunction(jsCtx, js_Registry_getVelocity, "getVelocity", 1));- JS_SetPropertyStr(jsCtx, registryObj, "setVelocity",- JS_NewCFunction(jsCtx, js_Registry_setVelocity, "setVelocity", 2));-- // Set Registry on global object- JS_SetPropertyStr(jsCtx, global, "Registry", registryObj);-- JS_FreeValue(jsCtx, global);-- ES_LOG_INFO("ECS bindings registered (Registry, Transform, Velocity)");-}--#else--void bindECS(ScriptContext& ctx, ecs::Registry& registry) {- (void)ctx;- (void)registry;- ES_LOG_WARN("Scripting not enabled on this platform");-}--#endif // ES_SCRIPTING_ENABLED--} // namespace esenginediff --git a/src/esengine/scripting/bindings/ECSBindings.generated.cpp b/src/esengine/scripting/bindings/ECSBindings.generated.cppnew file mode 100644index 000000000..8fdae22ae--- /dev/null+++ b/src/esengine/scripting/bindings/ECSBindings.generated.cpp@@ -0,0 +1,432 @@+/**+ * @file ECSBindings.generated.cpp+ * @brief Auto-generated QuickJS bindings for Native platform+ * @details Generated by tools/generate_bindings.py - DO NOT EDIT MANUALLY+ *+ * @author ESEngine Binding Generator+ * @date 2026+ */++#ifdef ES_SCRIPTING_ENABLED++#include "ECSBindings.hpp"+#include "../../ecs/Registry.hpp"+#include "../../math/Math.hpp"++#include "../../ecs/components/Camera.hpp"+#include "../../ecs/components/Hierarchy.hpp"+#include "../../ecs/components/Sprite.hpp"+#include "../../ecs/components/Transform.hpp"+#include "../../ecs/components/Velocity.hpp"++namespace esengine::scripting {++// Global registry pointer for C callbacks+static ecs::Registry* g_registry = nullptr;++// =============================================================================+// Type Conversion Helpers+// =============================================================================++static glm::vec3 jsToVec3(JSContext* ctx, JSValue jsObj) {+ glm::vec3 result(0.0f);+ JSValue x = JS_GetPropertyStr(ctx, jsObj, "x");+ JSValue y = JS_GetPropertyStr(ctx, jsObj, "y");+ JSValue z = JS_GetPropertyStr(ctx, jsObj, "z");+ double dx, dy, dz;+ JS_ToFloat64(ctx, &dx, x);+ JS_ToFloat64(ctx, &dy, y);+ JS_ToFloat64(ctx, &dz, z);+ result.x = static_cast<f32>(dx);+ result.y = static_cast<f32>(dy);+ result.z = static_cast<f32>(dz);+ JS_FreeValue(ctx, x);+ JS_FreeValue(ctx, y);+ JS_FreeValue(ctx, z);+ return result;+}++static JSValue vec3ToJS(JSContext* ctx, const glm::vec3& vec) {+ JSValue obj = JS_NewObject(ctx);+ JS_SetPropertyStr(ctx, obj, "x", JS_NewFloat64(ctx, vec.x));+ JS_SetPropertyStr(ctx, obj, "y", JS_NewFloat64(ctx, vec.y));+ JS_SetPropertyStr(ctx, obj, "z", JS_NewFloat64(ctx, vec.z));+ return obj;+}++static glm::quat jsToQuat(JSContext* ctx, JSValue jsObj) {+ glm::quat result(1.0f, 0.0f, 0.0f, 0.0f);+ JSValue w = JS_GetPropertyStr(ctx, jsObj, "w");+ JSValue x = JS_GetPropertyStr(ctx, jsObj, "x");+ JSValue y = JS_GetPropertyStr(ctx, jsObj, "y");+ JSValue z = JS_GetPropertyStr(ctx, jsObj, "z");+ double dw, dx, dy, dz;+ JS_ToFloat64(ctx, &dw, w);+ JS_ToFloat64(ctx, &dx, x);+ JS_ToFloat64(ctx, &dy, y);+ JS_ToFloat64(ctx, &dz, z);+ result.w = static_cast<f32>(dw);+ result.x = static_cast<f32>(dx);+ result.y = static_cast<f32>(dy);+ result.z = static_cast<f32>(dz);+ JS_FreeValue(ctx, w);+ JS_FreeValue(ctx, x);+ JS_FreeValue(ctx, y);+ JS_FreeValue(ctx, z);+ return result;+}++static JSValue quatToJS(JSContext* ctx, const glm::quat& quat) {+ JSValue obj = JS_NewObject(ctx);+ JS_SetPropertyStr(ctx, obj, "w", JS_NewFloat64(ctx, quat.w));+ JS_SetPropertyStr(ctx, obj, "x", JS_NewFloat64(ctx, quat.x));+ JS_SetPropertyStr(ctx, obj, "y", JS_NewFloat64(ctx, quat.y));+ JS_SetPropertyStr(ctx, obj, "z", JS_NewFloat64(ctx, quat.z));+ return obj;+}++// =============================================================================+// Camera Component Bindings+// =============================================================================++static JSValue js_Registry_getCamera(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {+ u32 entity;+ JS_ToUint32(ctx, &entity, argv[0]);+ if (!g_registry->has<esengine::ecs::Camera>(entity)) {+ return JS_ThrowReferenceError(ctx, "Entity does not have Camera component");+ }+ auto& comp = g_registry->get<esengine::ecs::Camera>(entity);+ JSValue obj = JS_NewObject(ctx);+ // TODO: Add converter for ProjectionType+ JS_SetPropertyStr(ctx, obj, "fov", JS_NewFloat64(ctx, comp.fov));+ JS_SetPropertyStr(ctx, obj, "orthoSize", JS_NewFloat64(ctx, comp.orthoSize));+ JS_SetPropertyStr(ctx, obj, "nearPlane", JS_NewFloat64(ctx, comp.nearPlane));+ JS_SetPropertyStr(ctx, obj, "farPlane", JS_NewFloat64(ctx, comp.farPlane));+ JS_SetPropertyStr(ctx, obj, "aspectRatio", JS_NewFloat64(ctx, comp.aspectRatio));+ // TODO: Add converter for bool+ // TODO: Add converter for i32+ return obj;+}++static JSValue js_Registry_addCamera(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {+ u32 entity;+ JS_ToUint32(ctx, &entity, argv[0]);+ esengine::ecs::Camera comp;+ JSValue projectionTypeVal = JS_GetPropertyStr(ctx, argv[1], "projectionType");+ JS_FreeValue(ctx, projectionTypeVal);+ JSValue fovVal = JS_GetPropertyStr(ctx, argv[1], "fov");+ double dfov;+ JS_ToFloat64(ctx, &dfov, fovVal);+ comp.fov = static_cast<f32>(dfov);+ JS_FreeValue(ctx, fovVal);+ JSValue orthoSizeVal = JS_GetPropertyStr(ctx, argv[1], "orthoSize");+ double dorthoSize;+ JS_ToFloat64(ctx, &dorthoSize, orthoSizeVal);+ comp.orthoSize = static_cast<f32>(dorthoSize);+ JS_FreeValue(ctx, orthoSizeVal);+ JSValue nearPlaneVal = JS_GetPropertyStr(ctx, argv[1], "nearPlane");+ double dnearPlane;+ JS_ToFloat64(ctx, &dnearPlane, nearPlaneVal);+ comp.nearPlane = static_cast<f32>(dnearPlane);+ JS_FreeValue(ctx, nearPlaneVal);+ JSValue farPlaneVal = JS_GetPropertyStr(ctx, argv[1], "farPlane");+ double dfarPlane;+ JS_ToFloat64(ctx, &dfarPlane, farPlaneVal);+ comp.farPlane = static_cast<f32>(dfarPlane);+ JS_FreeValue(ctx, farPlaneVal);+ JSValue aspectRatioVal = JS_GetPropertyStr(ctx, argv[1], "aspectRatio");+ double daspectRatio;+ JS_ToFloat64(ctx, &daspectRatio, aspectRatioVal);+ comp.aspectRatio = static_cast<f32>(daspectRatio);+ JS_FreeValue(ctx, aspectRatioVal);+ JSValue isActiveVal = JS_GetPropertyStr(ctx, argv[1], "isActive");+ JS_FreeValue(ctx, isActiveVal);+ JSValue priorityVal = JS_GetPropertyStr(ctx, argv[1], "priority");+ JS_FreeValue(ctx, priorityVal);+ g_registry->emplaceOrReplace<esengine::ecs::Camera>(entity, comp);+ return JS_UNDEFINED;+}++// =============================================================================+// Parent Component Bindings+// =============================================================================++static JSValue js_Registry_getParent(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {+ u32 entity;+ JS_ToUint32(ctx, &entity, argv[0]);+ if (!g_registry->has<esengine::ecs::Parent>(entity)) {+ return JS_ThrowReferenceError(ctx, "Entity does not have Parent component");+ }+ auto& comp = g_registry->get<esengine::ecs::Parent>(entity);+ JSValue obj = JS_NewObject(ctx);+ // TODO: Add converter for Entity+ return obj;+}++static JSValue js_Registry_addParent(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {+ u32 entity;+ JS_ToUint32(ctx, &entity, argv[0]);+ esengine::ecs::Parent comp;+ JSValue entityVal = JS_GetPropertyStr(ctx, argv[1], "entity");+ JS_FreeValue(ctx, entityVal);+ g_registry->emplaceOrReplace<esengine::ecs::Parent>(entity, comp);+ return JS_UNDEFINED;+}++// =============================================================================+// Children Component Bindings+// =============================================================================++static JSValue js_Registry_getChildren(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {+ u32 entity;+ JS_ToUint32(ctx, &entity, argv[0]);+ if (!g_registry->has<esengine::ecs::Children>(entity)) {+ return JS_ThrowReferenceError(ctx, "Entity does not have Children component");+ }+ auto& comp = g_registry->get<esengine::ecs::Children>(entity);+ JSValue obj = JS_NewObject(ctx);+ return obj;+}++static JSValue js_Registry_addChildren(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {+ u32 entity;+ JS_ToUint32(ctx, &entity, argv[0]);+ esengine::ecs::Children comp;+ g_registry->emplaceOrReplace<esengine::ecs::Children>(entity, comp);+ return JS_UNDEFINED;+}++// =============================================================================+// Sprite Component Bindings+// =============================================================================++static JSValue js_Registry_getSprite(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {+ u32 entity;+ JS_ToUint32(ctx, &entity, argv[0]);+ if (!g_registry->has<esengine::ecs::Sprite>(entity)) {+ return JS_ThrowReferenceError(ctx, "Entity does not have Sprite component");+ }+ auto& comp = g_registry->get<esengine::ecs::Sprite>(entity);+ JSValue obj = JS_NewObject(ctx);+ // TODO: Add converter for resource::TextureHandle+ // TODO: Add converter for glm::vec4+ // TODO: Add converter for glm::vec2+ // TODO: Add converter for glm::vec2+ // TODO: Add converter for glm::vec2+ // TODO: Add converter for i32+ // TODO: Add converter for bool+ // TODO: Add converter for bool+ return obj;+}++static JSValue js_Registry_addSprite(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {+ u32 entity;+ JS_ToUint32(ctx, &entity, argv[0]);+ esengine::ecs::Sprite comp;+ JSValue textureVal = JS_GetPropertyStr(ctx, argv[1], "texture");+ JS_FreeValue(ctx, textureVal);+ JSValue colorVal = JS_GetPropertyStr(ctx, argv[1], "color");+ JS_FreeValue(ctx, colorVal);+ JSValue sizeVal = JS_GetPropertyStr(ctx, argv[1], "size");+ JS_FreeValue(ctx, sizeVal);+ JSValue uvOffsetVal = JS_GetPropertyStr(ctx, argv[1], "uvOffset");+ JS_FreeValue(ctx, uvOffsetVal);+ JSValue uvScaleVal = JS_GetPropertyStr(ctx, argv[1], "uvScale");+ JS_FreeValue(ctx, uvScaleVal);+ JSValue layerVal = JS_GetPropertyStr(ctx, argv[1], "layer");+ JS_FreeValue(ctx, layerVal);+ JSValue flipXVal = JS_GetPropertyStr(ctx, argv[1], "flipX");+ JS_FreeValue(ctx, flipXVal);+ JSValue flipYVal = JS_GetPropertyStr(ctx, argv[1], "flipY");+ JS_FreeValue(ctx, flipYVal);+ g_registry->emplaceOrReplace<esengine::ecs::Sprite>(entity, comp);+ return JS_UNDEFINED;+}++// =============================================================================+// LocalTransform Component Bindings+// =============================================================================++static JSValue js_Registry_getLocalTransform(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {+ u32 entity;+ JS_ToUint32(ctx, &entity, argv[0]);+ if (!g_registry->has<esengine::ecs::LocalTransform>(entity)) {+ return JS_ThrowReferenceError(ctx, "Entity does not have LocalTransform component");+ }+ auto& comp = g_registry->get<esengine::ecs::LocalTransform>(entity);+ JSValue obj = JS_NewObject(ctx);+ JS_SetPropertyStr(ctx, obj, "position", vec3ToJS(ctx, comp.position));+ JS_SetPropertyStr(ctx, obj, "rotation", quatToJS(ctx, comp.rotation));+ JS_SetPropertyStr(ctx, obj, "scale", vec3ToJS(ctx, comp.scale));+ // TODO: Add converter for glm::mat4+ JS_SetPropertyStr(ctx, obj, "position", vec3ToJS(ctx, comp.position));+ JS_SetPropertyStr(ctx, obj, "rotation", quatToJS(ctx, comp.rotation));+ JS_SetPropertyStr(ctx, obj, "scale", vec3ToJS(ctx, comp.scale));+ return obj;+}++static JSValue js_Registry_addLocalTransform(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {+ u32 entity;+ JS_ToUint32(ctx, &entity, argv[0]);+ esengine::ecs::LocalTransform comp;+ JSValue positionVal = JS_GetPropertyStr(ctx, argv[1], "position");+ comp.position = jsToVec3(ctx, positionVal);+ JS_FreeValue(ctx, positionVal);+ JSValue rotationVal = JS_GetPropertyStr(ctx, argv[1], "rotation");+ comp.rotation = jsToQuat(ctx, rotationVal);+ JS_FreeValue(ctx, rotationVal);+ JSValue scaleVal = JS_GetPropertyStr(ctx, argv[1], "scale");+ comp.scale = jsToVec3(ctx, scaleVal);+ JS_FreeValue(ctx, scaleVal);+ JSValue matrixVal = JS_GetPropertyStr(ctx, argv[1], "matrix");+ JS_FreeValue(ctx, matrixVal);+ JSValue positionVal = JS_GetPropertyStr(ctx, argv[1], "position");+ comp.position = jsToVec3(ctx, positionVal);+ JS_FreeValue(ctx, positionVal);+ JSValue rotationVal = JS_GetPropertyStr(ctx, argv[1], "rotation");+ comp.rotation = jsToQuat(ctx, rotationVal);+ JS_FreeValue(ctx, rotationVal);+ JSValue scaleVal = JS_GetPropertyStr(ctx, argv[1], "scale");+ comp.scale = jsToVec3(ctx, scaleVal);+ JS_FreeValue(ctx, scaleVal);+ g_registry->emplaceOrReplace<esengine::ecs::LocalTransform>(entity, comp);+ return JS_UNDEFINED;+}++// =============================================================================+// WorldTransform Component Bindings+// =============================================================================++static JSValue js_Registry_getWorldTransform(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {+ u32 entity;+ JS_ToUint32(ctx, &entity, argv[0]);+ if (!g_registry->has<esengine::ecs::WorldTransform>(entity)) {+ return JS_ThrowReferenceError(ctx, "Entity does not have WorldTransform component");+ }+ auto& comp = g_registry->get<esengine::ecs::WorldTransform>(entity);+ JSValue obj = JS_NewObject(ctx);+ // TODO: Add converter for glm::mat4+ JS_SetPropertyStr(ctx, obj, "position", vec3ToJS(ctx, comp.position));+ JS_SetPropertyStr(ctx, obj, "rotation", quatToJS(ctx, comp.rotation));+ JS_SetPropertyStr(ctx, obj, "scale", vec3ToJS(ctx, comp.scale));+ return obj;+}++static JSValue js_Registry_addWorldTransform(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {+ u32 entity;+ JS_ToUint32(ctx, &entity, argv[0]);+ esengine::ecs::WorldTransform comp;+ JSValue matrixVal = JS_GetPropertyStr(ctx, argv[1], "matrix");+ JS_FreeValue(ctx, matrixVal);+ JSValue positionVal = JS_GetPropertyStr(ctx, argv[1], "position");+ comp.position = jsToVec3(ctx, positionVal);+ JS_FreeValue(ctx, positionVal);+ JSValue rotationVal = JS_GetPropertyStr(ctx, argv[1], "rotation");+ comp.rotation = jsToQuat(ctx, rotationVal);+ JS_FreeValue(ctx, rotationVal);+ JSValue scaleVal = JS_GetPropertyStr(ctx, argv[1], "scale");+ comp.scale = jsToVec3(ctx, scaleVal);+ JS_FreeValue(ctx, scaleVal);+ g_registry->emplaceOrReplace<esengine::ecs::WorldTransform>(entity, comp);+ return JS_UNDEFINED;+}++// =============================================================================+// Velocity Component Bindings+// =============================================================================++static JSValue js_Registry_getVelocity(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {+ u32 entity;+ JS_ToUint32(ctx, &entity, argv[0]);+ if (!g_registry->has<esengine::ecs::Velocity>(entity)) {+ return JS_ThrowReferenceError(ctx, "Entity does not have Velocity component");+ }+ auto& comp = g_registry->get<esengine::ecs::Velocity>(entity);+ JSValue obj = JS_NewObject(ctx);+ JS_SetPropertyStr(ctx, obj, "linear", vec3ToJS(ctx, comp.linear));+ JS_SetPropertyStr(ctx, obj, "angular", vec3ToJS(ctx, comp.angular));+ return obj;+}++static JSValue js_Registry_addVelocity(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {+ u32 entity;+ JS_ToUint32(ctx, &entity, argv[0]);+ esengine::ecs::Velocity comp;+ JSValue linearVal = JS_GetPropertyStr(ctx, argv[1], "linear");+ comp.linear = jsToVec3(ctx, linearVal);+ JS_FreeValue(ctx, linearVal);+ JSValue angularVal = JS_GetPropertyStr(ctx, argv[1], "angular");+ comp.angular = jsToVec3(ctx, angularVal);+ JS_FreeValue(ctx, angularVal);+ g_registry->emplaceOrReplace<esengine::ecs::Velocity>(entity, comp);+ return JS_UNDEFINED;+}++// =============================================================================+// Main Binding Function+// =============================================================================++void bindECS(ScriptContext& ctx, ecs::Registry& registry) {+ g_registry = ®istry;+ JSContext* jsCtx = ctx.getJSContext();+ JSValue global = JS_GetGlobalObject(jsCtx);+ JSValue registryObj = JS_NewObject(jsCtx);++ // Entity management+ JS_SetPropertyStr(jsCtx, registryObj, "create",+ JS_NewCFunction(jsCtx, js_Registry_create, "create", 0));+ JS_SetPropertyStr(jsCtx, registryObj, "destroy",+ JS_NewCFunction(jsCtx, js_Registry_destroy, "destroy", 1));+ JS_SetPropertyStr(jsCtx, registryObj, "valid",+ JS_NewCFunction(jsCtx, js_Registry_valid, "valid", 1));++ // Camera component+ JS_SetPropertyStr(jsCtx, registryObj, "getCamera",+ JS_NewCFunction(jsCtx, js_Registry_getCamera, "getCamera", 1));+ JS_SetPropertyStr(jsCtx, registryObj, "addCamera",+ JS_NewCFunction(jsCtx, js_Registry_addCamera, "addCamera", 2));++ // Parent component+ JS_SetPropertyStr(jsCtx, registryObj, "getParent",+ JS_NewCFunction(jsCtx, js_Registry_getParent, "getParent", 1));+ JS_SetPropertyStr(jsCtx, registryObj, "addParent",+ JS_NewCFunction(jsCtx, js_Registry_addParent, "addParent", 2));++ // Children component+ JS_SetPropertyStr(jsCtx, registryObj, "getChildren",+ JS_NewCFunction(jsCtx, js_Registry_getChildren, "getChildren", 1));+ JS_SetPropertyStr(jsCtx, registryObj, "addChildren",+ JS_NewCFunction(jsCtx, js_Registry_addChildren, "addChildren", 2));++ // Sprite component+ JS_SetPropertyStr(jsCtx, registryObj, "getSprite",+ JS_NewCFunction(jsCtx, js_Registry_getSprite, "getSprite", 1));+ JS_SetPropertyStr(jsCtx, registryObj, "addSprite",+ JS_NewCFunction(jsCtx, js_Registry_addSprite, "addSprite", 2));++ // LocalTransform component+ JS_SetPropertyStr(jsCtx, registryObj, "getLocalTransform",+ JS_NewCFunction(jsCtx, js_Registry_getLocalTransform, "getLocalTransform", 1));+ JS_SetPropertyStr(jsCtx, registryObj, "addLocalTransform",+ JS_NewCFunction(jsCtx, js_Registry_addLocalTransform, "addLocalTransform", 2));++ // WorldTransform component+ JS_SetPropertyStr(jsCtx, registryObj, "getWorldTransform",+ JS_NewCFunction(jsCtx, js_Registry_getWorldTransform, "getWorldTransform", 1));+ JS_SetPropertyStr(jsCtx, registryObj, "addWorldTransform",+ JS_NewCFunction(jsCtx, js_Registry_addWorldTransform, "addWorldTransform", 2));++ // Velocity component+ JS_SetPropertyStr(jsCtx, registryObj, "getVelocity",+ JS_NewCFunction(jsCtx, js_Registry_getVelocity, "getVelocity", 1));+ JS_SetPropertyStr(jsCtx, registryObj, "addVelocity",+ JS_NewCFunction(jsCtx, js_Registry_addVelocity, "addVelocity", 2));++ JS_SetPropertyStr(jsCtx, global, "Registry", registryObj);+ JS_FreeValue(jsCtx, global);+}+++} // namespace esengine::scripting++#endif // ES_SCRIPTING_ENABLEDdiff --git a/tools/generate_bindings.py b/tools/generate_bindings.pynew file mode 100644index 000000000..4bf3b33f6--- /dev/null+++ b/tools/generate_bindings.py@@ -0,0 +1,854 @@+#!/usr/bin/env python3+"""+Binding Generator for ESEngine++This tool automatically generates JavaScript/TypeScript bindings for C++ components+marked with ES_COMPONENT() macros. It parses C++ headers and generates:+ 1. WebBindings.generated.cpp - Emscripten embind bindings+ 2. ECSBindings.generated.cpp - QuickJS bindings for native platform+ 3. esengine.d.ts - TypeScript definition file++Usage:+ python generate_bindings.py --input src/esengine/ecs/components --output src/esengine/bindings+"""++import re+import os+import sys+import argparse+from pathlib import Path+from typing import List, Dict, Optional+from dataclasses import dataclass, field+++# =============================================================================+# Data Structures+# =============================================================================++@dataclass+class Property:+ """Represents a C++ property marked with ES_PROPERTY()"""+ name: str+ type: str+ default_value: Optional[str] = None+++@dataclass+class Method:+ """Represents a C++ method marked with ES_METHOD()"""+ name: str+ return_type: str+ parameters: List[tuple] # [(type, name), ...]+ is_const: bool = False+ is_static: bool = False+++@dataclass+class Component:+ """Represents a C++ component marked with ES_COMPONENT()"""+ name: str+ namespace: str+ properties: List[Property] = field(default_factory=list)+ methods: List[Method] = field(default_factory=list)+ header_path: str = ""+ is_struct: bool = True # True for struct, False for class+++# =============================================================================+# Parser+# =============================================================================++class ComponentParser:+ """Parses C++ headers to extract component metadata"""++ # Regex patterns+ COMPONENT_PATTERN = re.compile(+ r'ES_COMPONENT\(\)\s*(?:struct|class)\s+(\w+)',+ re.MULTILINE+ )++ PROPERTY_PATTERN = re.compile(+ r'ES_PROPERTY\(\)\s*([^;]+?)\s+(\w+)(?:\s*\{([^}]*)\}|\s*=\s*([^;]+))?;',+ re.MULTILINE+ )++ METHOD_PATTERN = re.compile(+ r'ES_METHOD\((.*?)\)\s*([^(]+?)\s+(\w+)\s*\(([^)]*)\)',+ re.MULTILINE+ )++ NAMESPACE_PATTERN = re.compile(+ r'namespace\s+([\w:]+)\s*\{',+ re.MULTILINE+ )++ def __init__(self):+ self.components: List[Component] = []++ def parse_file(self, filepath: Path):+ """Parse a single C++ header file"""+ content = filepath.read_text(encoding='utf-8')++ # Extract namespace+ namespace_match = self.NAMESPACE_PATTERN.search(content)+ namespace = namespace_match.group(1) if namespace_match else ""++ # Find all components+ for match in self.COMPONENT_PATTERN.finditer(content):+ component_name = match.group(1)+ component_start = match.end()++ # Find the matching closing brace+ brace_count = 0+ component_end = component_start+ for i in range(component_start, len(content)):+ if content[i] == '{':+ brace_count += 1+ elif content[i] == '}':+ brace_count -= 1+ if brace_count == -1:+ component_end = i+ break++ component_body = content[component_start:component_end]++ # Get relative path, handling both absolute and relative paths+ try:+ if filepath.is_absolute():+ rel_path = filepath.relative_to(Path.cwd())+ else:+ rel_path = filepath+ except ValueError:+ # If relative_to fails, just use the name+ rel_path = filepath.name++ component = Component(+ name=component_name,+ namespace=namespace,+ header_path=str(rel_path).replace('\\', '/')+ )++ # Parse properties+ for prop_match in self.PROPERTY_PATTERN.finditer(component_body):+ prop_type = prop_match.group(1).strip()+ prop_name = prop_match.group(2).strip()+ default_val = prop_match.group(3) or prop_match.group(4)++ component.properties.append(Property(+ name=prop_name,+ type=prop_type,+ default_value=default_val.strip() if default_val else None+ ))++ # Parse methods+ for method_match in self.METHOD_PATTERN.finditer(component_body):+ attributes = method_match.group(1).strip()+ return_type = method_match.group(2).strip()+ method_name = method_match.group(3).strip()+ params_str = method_match.group(4).strip()++ # Parse parameters+ parameters = []+ if params_str:+ for param in params_str.split(','):+ param = param.strip()+ if param:+ parts = param.rsplit(None, 1)+ if len(parts) == 2:+ parameters.append((parts[0], parts[1]))++ component.methods.append(Method(+ name=method_name,+ return_type=return_type,+ parameters=parameters,+ is_const='const' in attributes,+ is_static='static' in attributes+ ))++ self.components.append(component)++ def parse_directory(self, directory: Path):+ """Recursively parse all .hpp files in a directory"""+ for filepath in directory.rglob('*.hpp'):+ try:+ self.parse_file(filepath)+ except Exception as e:+ print(f"Warning: Failed to parse {filepath}: {e}", file=sys.stderr)+++# =============================================================================+# Emscripten Binding Generator+# =============================================================================++class EmscriptenGenerator:+ """Generates Emscripten embind bindings"""++ def __init__(self, components: List[Component]):+ self.components = components++ def generate(self) -> str:+ """Generate complete WebBindings.generated.cpp file"""+ lines = [+ "/**",+ " * @file WebBindings.generated.cpp",+ " * @brief Auto-generated Emscripten bindings",+ " * @details Generated by tools/generate_bindings.py - DO NOT EDIT MANUALLY",+ " *",+ " * @author ESEngine Binding Generator",+ " * @date 2026",+ " */",+ "",+ "#ifdef ES_PLATFORM_WEB",+ "",+ "#include <emscripten/bind.h>",+ "#include \"../ecs/Registry.hpp\"",+ "#include \"../ecs/Entity.hpp\"",+ "#include \"../math/Math.hpp\"",+ ""+ ]++ # Component headers+ included_headers = set()+ for component in self.components:+ rel_path = component.header_path.replace('src/esengine/', '')+ include_line = f'#include "../{rel_path}"'+ if include_line not in included_headers:+ lines.append(include_line)+ included_headers.add(include_line)++ lines.extend([+ "",+ "using namespace emscripten;",+ "",+ "namespace esengine {",+ "",+ "// =============================================================================",+ "// Math Types",+ "// =============================================================================",+ "",+ "EMSCRIPTEN_BINDINGS(esengine_math) {",+ " // Vec2",+ " value_object<glm::vec2>(\"Vec2\")",+ " .field(\"x\", &glm::vec2::x)",+ " .field(\"y\", &glm::vec2::y);",+ "",+ " // Vec3",+ " value_object<glm::vec3>(\"Vec3\")",+ " .field(\"x\", &glm::vec3::x)",+ " .field(\"y\", &glm::vec3::y)",+ " .field(\"z\", &glm::vec3::z);",+ "",+ " // Vec4",+ " value_object<glm::vec4>(\"Vec4\")",+ " .field(\"x\", &glm::vec4::x)",+ " .field(\"y\", &glm::vec4::y)",+ " .field(\"z\", &glm::vec4::z)",+ " .field(\"w\", &glm::vec4::w);",+ "",+ " // Quat",+ " value_object<glm::quat>(\"Quat\")",+ " .field(\"x\", &glm::quat::x)",+ " .field(\"y\", &glm::quat::y)",+ " .field(\"z\", &glm::quat::z)",+ " .field(\"w\", &glm::quat::w);",+ "}",+ "",+ "// =============================================================================",+ "// ECS Entity Type",+ "// =============================================================================",+ "",+ "EMSCRIPTEN_BINDINGS(esengine_entity) {",+ " // Entity is u32, exposed as number in JavaScript",+ "}",+ ""+ ])++ # Generate component bindings+ lines.extend(self._generate_components())++ # Generate Registry bindings+ lines.extend(self._generate_registry())++ lines.extend([+ "",+ "} // namespace esengine",+ "",+ "#endif // ES_PLATFORM_WEB",+ ""+ ])++ return '\n'.join(lines)++ def _generate_components(self) -> List[str]:+ """Generate bindings for all components"""+ lines = [+ "// =============================================================================",+ "// ECS Components",+ "// =============================================================================",+ "",+ "EMSCRIPTEN_BINDINGS(esengine_components) {"+ ]++ for component in self.components:+ full_name = f"{component.namespace}::{component.name}"++ lines.append(f" // {component.name} component")+ lines.append(f' value_object<{full_name}>("{component.name}")')++ for prop in component.properties:+ lines.append(f' .field("{prop.name}", &{full_name}::{prop.name})')++ for method in component.methods:+ if not method.is_static:+ lines.append(f' .function("{method.name}", &{full_name}::{method.name})')++ lines.append(" ;")+ lines.append("")++ lines.append("}")+ lines.append("")++ return lines++ def _generate_registry(self) -> List[str]:+ """Generate Registry bindings with automatic component accessors"""+ lines = [+ "// =============================================================================",+ "// ECS Registry",+ "// =============================================================================",+ "",+ "EMSCRIPTEN_BINDINGS(esengine_registry) {",+ " class_<ecs::Registry>(\"Registry\")",+ " .constructor<>()",+ "",+ " // Entity management",+ " .function(\"create\", optional_override([](ecs::Registry& self) {",+ " return self.create();",+ " }))",+ " .function(\"destroy\", optional_override([](ecs::Registry& self, Entity e) {",+ " self.destroy(e);",+ " }))",+ " .function(\"valid\", optional_override([](ecs::Registry& self, Entity e) {",+ " return self.valid(e);",+ " }))",+ " .function(\"entityCount\", optional_override([](const ecs::Registry& self) {",+ " return self.entityCount();",+ " }))",+ ""+ ]++ for component in self.components:+ full_name = f"{component.namespace}::{component.name}"+ camel_name = component.name++ lines.extend([+ f" // {component.name} component",+ f' .function("has{camel_name}", optional_override([](ecs::Registry& self, Entity e) {{',+ f" return self.has<{full_name}>(e);",+ " }))",+ f' .function("get{camel_name}", optional_override([](ecs::Registry& self, Entity e) -> {full_name}& {{',+ f" return self.get<{full_name}>(e);",+ " }))",+ f' .function("add{camel_name}", optional_override([](ecs::Registry& self, Entity e, const {full_name}& c) -> {full_name}& {{',+ f" return self.emplaceOrReplace<{full_name}>(e, c);",+ " }))",+ f' .function("remove{camel_name}", optional_override([](ecs::Registry& self, Entity e) {{',+ f" self.remove<{full_name}>(e);",+ " }))",+ ""+ ])++ lines.append(" ;")+ lines.append("}")++ return lines+++# =============================================================================+# TypeScript Definition Generator+# =============================================================================++class TypeScriptGenerator:+ """Generates TypeScript definition files"""++ def __init__(self, components: List[Component]):+ self.components = components++ def generate(self) -> str:+ """Generate complete esengine.d.ts file"""+ lines = [+ "/**",+ " * @file esengine.d.ts",+ " * @brief TypeScript definitions for ESEngine",+ " * @details Generated by tools/generate_bindings.py - DO NOT EDIT MANUALLY",+ " */",+ "",+ "declare namespace Module {",+ " // =============================================================================",+ " // Core Types",+ " // =============================================================================",+ "",+ " type Entity = number;",+ "",+ " // =============================================================================",+ " // Math Types",+ " // =============================================================================",+ "",+ " interface Vec2 {",+ " x: number;",+ " y: number;",+ " }",+ "",+ " interface Vec3 {",+ " x: number;",+ " y: number;",+ " z: number;",+ " }",+ "",+ " interface Vec4 {",+ " x: number;",+ " y: number;",+ " z: number;",+ " w: number;",+ " }",+ "",+ " interface Quat {",+ " x: number;",+ " y: number;",+ " z: number;",+ " w: number;",+ " }",+ "",+ " // =============================================================================",+ " // ECS Components",+ " // =============================================================================",+ ""+ ]++ # Generate component interfaces+ for component in self.components:+ lines.append(f" interface {component.name} {{")++ for prop in component.properties:+ ts_type = self._cpp_to_ts_type(prop.type)+ lines.append(f" {prop.name}: {ts_type};")++ for method in component.methods:+ if not method.is_static:+ params = ', '.join([f"{name}: {self._cpp_to_ts_type(ptype)}"+ for ptype, name in method.parameters])+ ret_type = self._cpp_to_ts_type(method.return_type)+ lines.append(f" {method.name}({params}): {ret_type};")++ lines.append(" }")+ lines.append("")++ # Generate Registry interface+ lines.extend([+ " // =============================================================================",+ " // ECS Registry",+ " // =============================================================================",+ "",+ " class Registry {",+ " constructor();",+ "",+ " // Entity management",+ " create(): Entity;",+ " destroy(entity: Entity): void;",+ " valid(entity: Entity): boolean;",+ " entityCount(): number;",+ ""+ ])++ for component in self.components:+ lines.extend([+ f" // {component.name} component",+ f" has{component.name}(entity: Entity): boolean;",+ f" get{component.name}(entity: Entity): {component.name};",+ f" add{component.name}(entity: Entity, component: {component.name}): {component.name};",+ f" remove{component.name}(entity: Entity): void;",+ ""+ ])++ lines.extend([+ " }",+ "",+ " // =============================================================================",+ " // Module Lifecycle",+ " // =============================================================================",+ "",+ " function onRuntimeInitialized(): void;",+ "}",+ "",+ "export = Module;",+ "export as namespace Module;",+ ""+ ])++ return '\n'.join(lines)++ def _cpp_to_ts_type(self, cpp_type: str) -> str:+ """Convert C++ type to TypeScript type"""+ cpp_type = cpp_type.strip()++ # Basic types+ type_map = {+ 'bool': 'boolean',+ 'f32': 'number',+ 'f64': 'number',+ 'u8': 'number',+ 'u16': 'number',+ 'u32': 'number',+ 'u64': 'number',+ 'i8': 'number',+ 'i16': 'number',+ 'i32': 'number',+ 'i64': 'number',+ 'float': 'number',+ 'double': 'number',+ 'int': 'number',+ 'unsigned': 'number',+ 'size_t': 'number',+ 'usize': 'number',+ 'Entity': 'Entity',+ 'std::string': 'string',+ 'void': 'void'+ }++ # Remove const and references+ cpp_type = cpp_type.replace('const', '').replace('&', '').strip()++ # Check direct mapping+ if cpp_type in type_map:+ return type_map[cpp_type]++ # GLM types+ if cpp_type.startswith('glm::'):+ glm_type = cpp_type[5:]+ if glm_type in ['vec2', 'vec3', 'vec4', 'quat']:+ return glm_type.capitalize()++ # Default to any for unknown types+ return 'any'+++# =============================================================================+# QuickJS Binding Generator+# =============================================================================++class QuickJSGenerator:+ """Generates QuickJS bindings for Native platform"""++ def __init__(self, components: List[Component]):+ self.components = components++ def generate(self) -> str:+ """Generate complete ECSBindings.generated.cpp file"""+ lines = [+ "/**",+ " * @file ECSBindings.generated.cpp",+ " * @brief Auto-generated QuickJS bindings for Native platform",+ " * @details Generated by tools/generate_bindings.py - DO NOT EDIT MANUALLY",+ " *",+ " * @author ESEngine Binding Generator",+ " * @date 2026",+ " */",+ "",+ "#ifdef ES_SCRIPTING_ENABLED",+ "",+ "#include \"ECSBindings.hpp\"",+ "#include \"../../ecs/Registry.hpp\"",+ "#include \"../../math/Math.hpp\"",+ ""+ ]++ # Component headers+ included_headers = set()+ for component in self.components:+ rel_path = component.header_path.replace('src/esengine/', '')+ include_line = f'#include "../../{rel_path}"'+ if include_line not in included_headers:+ lines.append(include_line)+ included_headers.add(include_line)++ lines.extend([+ "",+ "namespace esengine::scripting {",+ "",+ "// Global registry pointer for C callbacks",+ "static ecs::Registry* g_registry = nullptr;",+ ""+ ])++ # Generate helper functions for type conversions+ lines.extend(self._generate_helpers())++ # Generate component binding functions+ for component in self.components:+ lines.extend(self._generate_component_bindings(component))++ # Generate main binding function+ lines.extend(self._generate_main_bind())++ lines.extend([+ "",+ "} // namespace esengine::scripting",+ "",+ "#endif // ES_SCRIPTING_ENABLED",+ ""+ ])++ return '\n'.join(lines)++ def _generate_helpers(self) -> List[str]:+ """Generate type conversion helper functions"""+ return [+ "// =============================================================================",+ "// Type Conversion Helpers",+ "// =============================================================================",+ "",+ "static glm::vec3 jsToVec3(JSContext* ctx, JSValue jsObj) {",+ " glm::vec3 result(0.0f);",+ " JSValue x = JS_GetPropertyStr(ctx, jsObj, \"x\");",+ " JSValue y = JS_GetPropertyStr(ctx, jsObj, \"y\");",+ " JSValue z = JS_GetPropertyStr(ctx, jsObj, \"z\");",+ " double dx, dy, dz;",+ " JS_ToFloat64(ctx, &dx, x);",+ " JS_ToFloat64(ctx, &dy, y);",+ " JS_ToFloat64(ctx, &dz, z);",+ " result.x = static_cast<f32>(dx);",+ " result.y = static_cast<f32>(dy);",+ " result.z = static_cast<f32>(dz);",+ " JS_FreeValue(ctx, x);",+ " JS_FreeValue(ctx, y);",+ " JS_FreeValue(ctx, z);",+ " return result;",+ "}",+ "",+ "static JSValue vec3ToJS(JSContext* ctx, const glm::vec3& vec) {",+ " JSValue obj = JS_NewObject(ctx);",+ " JS_SetPropertyStr(ctx, obj, \"x\", JS_NewFloat64(ctx, vec.x));",+ " JS_SetPropertyStr(ctx, obj, \"y\", JS_NewFloat64(ctx, vec.y));",+ " JS_SetPropertyStr(ctx, obj, \"z\", JS_NewFloat64(ctx, vec.z));",+ " return obj;",+ "}",+ "",+ "static glm::quat jsToQuat(JSContext* ctx, JSValue jsObj) {",+ " glm::quat result(1.0f, 0.0f, 0.0f, 0.0f);",+ " JSValue w = JS_GetPropertyStr(ctx, jsObj, \"w\");",+ " JSValue x = JS_GetPropertyStr(ctx, jsObj, \"x\");",+ " JSValue y = JS_GetPropertyStr(ctx, jsObj, \"y\");",+ " JSValue z = JS_GetPropertyStr(ctx, jsObj, \"z\");",+ " double dw, dx, dy, dz;",+ " JS_ToFloat64(ctx, &dw, w);",+ " JS_ToFloat64(ctx, &dx, x);",+ " JS_ToFloat64(ctx, &dy, y);",+ " JS_ToFloat64(ctx, &dz, z);",+ " result.w = static_cast<f32>(dw);",+ " result.x = static_cast<f32>(dx);",+ " result.y = static_cast<f32>(dy);",+ " result.z = static_cast<f32>(dz);",+ " JS_FreeValue(ctx, w);",+ " JS_FreeValue(ctx, x);",+ " JS_FreeValue(ctx, y);",+ " JS_FreeValue(ctx, z);",+ " return result;",+ "}",+ "",+ "static JSValue quatToJS(JSContext* ctx, const glm::quat& quat) {",+ " JSValue obj = JS_NewObject(ctx);",+ " JS_SetPropertyStr(ctx, obj, \"w\", JS_NewFloat64(ctx, quat.w));",+ " JS_SetPropertyStr(ctx, obj, \"x\", JS_NewFloat64(ctx, quat.x));",+ " JS_SetPropertyStr(ctx, obj, \"y\", JS_NewFloat64(ctx, quat.y));",+ " JS_SetPropertyStr(ctx, obj, \"z\", JS_NewFloat64(ctx, quat.z));",+ " return obj;",+ "}",+ ""+ ]++ def _generate_component_bindings(self, component: Component) -> List[str]:+ """Generate QuickJS bindings for a single component"""+ lines = [+ f"// =============================================================================",+ f"// {component.name} Component Bindings",+ f"// =============================================================================",+ ""+ ]++ full_name = f"{component.namespace}::{component.name}"++ # Generate get method+ lines.extend([+ f"static JSValue js_Registry_get{component.name}(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {{",+ f" u32 entity;",+ f" JS_ToUint32(ctx, &entity, argv[0]);",+ f" if (!g_registry->has<{full_name}>(entity)) {{",+ f' return JS_ThrowReferenceError(ctx, "Entity does not have {component.name} component");',+ f" }}",+ f" auto& comp = g_registry->get<{full_name}>(entity);",+ f" JSValue obj = JS_NewObject(ctx);",+ ])++ # Add property getters+ for prop in component.properties:+ if 'vec3' in prop.type:+ lines.append(f' JS_SetPropertyStr(ctx, obj, "{prop.name}", vec3ToJS(ctx, comp.{prop.name}));')+ elif 'quat' in prop.type:+ lines.append(f' JS_SetPropertyStr(ctx, obj, "{prop.name}", quatToJS(ctx, comp.{prop.name}));')+ elif 'f32' in prop.type or 'float' in prop.type:+ lines.append(f' JS_SetPropertyStr(ctx, obj, "{prop.name}", JS_NewFloat64(ctx, comp.{prop.name}));')+ else:+ lines.append(f' // TODO: Add converter for {prop.type}')++ lines.extend([+ f" return obj;",+ f"}}",+ ""+ ])++ # Generate set method+ lines.extend([+ f"static JSValue js_Registry_add{component.name}(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {{",+ f" u32 entity;",+ f" JS_ToUint32(ctx, &entity, argv[0]);",+ f" {full_name} comp;",+ ])++ # Parse properties from JS object+ for prop in component.properties:+ lines.append(f' JSValue {prop.name}Val = JS_GetPropertyStr(ctx, argv[1], "{prop.name}");')+ if 'vec3' in prop.type:+ lines.append(f' comp.{prop.name} = jsToVec3(ctx, {prop.name}Val);')+ elif 'quat' in prop.type:+ lines.append(f' comp.{prop.name} = jsToQuat(ctx, {prop.name}Val);')+ elif 'f32' in prop.type or 'float' in prop.type:+ lines.extend([+ f' double d{prop.name};',+ f' JS_ToFloat64(ctx, &d{prop.name}, {prop.name}Val);',+ f' comp.{prop.name} = static_cast<f32>(d{prop.name});'+ ])+ lines.append(f' JS_FreeValue(ctx, {prop.name}Val);')++ lines.extend([+ f" g_registry->emplaceOrReplace<{full_name}>(entity, comp);",+ f" return JS_UNDEFINED;",+ f"}}",+ ""+ ])++ return lines++ def _generate_main_bind(self) -> List[str]:+ """Generate main binding registration function"""+ lines = [+ "// =============================================================================",+ "// Main Binding Function",+ "// =============================================================================",+ "",+ "void bindECS(ScriptContext& ctx, ecs::Registry& registry) {",+ " g_registry = ®istry;",+ " JSContext* jsCtx = ctx.getJSContext();",+ " JSValue global = JS_GetGlobalObject(jsCtx);",+ " JSValue registryObj = JS_NewObject(jsCtx);",+ "",+ " // Entity management",+ " JS_SetPropertyStr(jsCtx, registryObj, \"create\",",+ " JS_NewCFunction(jsCtx, js_Registry_create, \"create\", 0));",+ " JS_SetPropertyStr(jsCtx, registryObj, \"destroy\",",+ " JS_NewCFunction(jsCtx, js_Registry_destroy, \"destroy\", 1));",+ " JS_SetPropertyStr(jsCtx, registryObj, \"valid\",",+ " JS_NewCFunction(jsCtx, js_Registry_valid, \"valid\", 1));",+ ""+ ]++ # Register all component methods+ for component in self.components:+ lines.extend([+ f" // {component.name} component",+ f' JS_SetPropertyStr(jsCtx, registryObj, "get{component.name}",',+ f' JS_NewCFunction(jsCtx, js_Registry_get{component.name}, "get{component.name}", 1));',+ f' JS_SetPropertyStr(jsCtx, registryObj, "add{component.name}",',+ f' JS_NewCFunction(jsCtx, js_Registry_add{component.name}, "add{component.name}", 2));',+ ""+ ])++ lines.extend([+ ' JS_SetPropertyStr(jsCtx, global, "Registry", registryObj);',+ " JS_FreeValue(jsCtx, global);",+ "}",+ ""+ ])++ return lines+++# =============================================================================+# Main Entry Point+# =============================================================================++def main():+ parser = argparse.ArgumentParser(+ description='Generate bindings for ESEngine components'+ )+ parser.add_argument(+ '--input',+ type=str,+ default='src/esengine/ecs/components',+ help='Input directory containing component headers'+ )+ parser.add_argument(+ '--output',+ type=str,+ default='src/esengine/bindings',+ help='Output directory for generated bindings'+ )+ parser.add_argument(+ '--verbose',+ action='store_true',+ help='Enable verbose output'+ )++ args = parser.parse_args()++ # Parse components+ print(f"Parsing components from: {args.input}")+ parser_obj = ComponentParser()+ parser_obj.parse_directory(Path(args.input))++ if args.verbose:+ print(f"Found {len(parser_obj.components)} components:")+ for comp in parser_obj.components:+ print(f" - {comp.namespace}::{comp.name} ({len(comp.properties)} properties, {len(comp.methods)} methods)")++ if not parser_obj.components:+ print("Warning: No components found!", file=sys.stderr)+ return 1++ # Create output directory+ output_dir = Path(args.output)+ output_dir.mkdir(parents=True, exist_ok=True)++ # Generate Emscripten bindings+ print("Generating Emscripten bindings...")+ emscripten_gen = EmscriptenGenerator(parser_obj.components)+ emscripten_code = emscripten_gen.generate()+ (output_dir / 'WebBindings.generated.cpp').write_text(emscripten_code, encoding='utf-8')++ # Generate TypeScript definitions+ print("Generating TypeScript definitions...")+ ts_gen = TypeScriptGenerator(parser_obj.components)+ ts_code = ts_gen.generate()+ (Path('bindings') / 'esengine.d.ts').write_text(ts_code, encoding='utf-8')++ # Generate QuickJS bindings+ print("Generating QuickJS bindings...")+ quickjs_gen = QuickJSGenerator(parser_obj.components)+ quickjs_code = quickjs_gen.generate()+ (Path('src/esengine/scripting/bindings') / 'ECSBindings.generated.cpp').write_text(quickjs_code, encoding='utf-8')++ print("[OK] Binding generation complete!")+ return 0+++if __name__ == '__main__':+ sys.exit(main())