Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

Initial ESEngine project with GLM submodule

esengine194f77164155
diff --git a/.clang-format b/.clang-format
new file mode 100644
index 000000000..33e8e106b
--- /dev/null
+++ b/.clang-format
@@ -0,0 +1,87 @@
+---
+Language: Cpp
+BasedOnStyle: Google
+IndentWidth: 4
+TabWidth: 4
+UseTab: Never
+ColumnLimit: 100
+AccessModifierOffset: -4
+AlignAfterOpenBracket: Align
+AlignConsecutiveAssignments: false
+AlignConsecutiveDeclarations: false
+AlignOperands: true
+AlignTrailingComments: true
+AllowAllParametersOfDeclarationOnNextLine: true
+AllowShortBlocksOnASingleLine: false
+AllowShortCaseLabelsOnASingleLine: false
+AllowShortFunctionsOnASingleLine: Inline
+AllowShortIfStatementsOnASingleLine: false
+AllowShortLoopsOnASingleLine: false
+AlwaysBreakAfterReturnType: None
+AlwaysBreakBeforeMultilineStrings: false
+AlwaysBreakTemplateDeclarations: Yes
+BinPackArguments: true
+BinPackParameters: true
+BraceWrapping:
+ AfterClass: false
+ AfterControlStatement: false
+ AfterEnum: false
+ AfterFunction: false
+ AfterNamespace: false
+ AfterStruct: false
+ AfterUnion: false
+ BeforeCatch: false
+ BeforeElse: false
+ IndentBraces: false
+BreakBeforeBinaryOperators: None
+BreakBeforeBraces: Attach
+BreakBeforeTernaryOperators: true
+BreakConstructorInitializers: BeforeColon
+BreakStringLiterals: true
+CommentPragmas: '^ IWYU pragma:'
+CompactNamespaces: false
+ConstructorInitializerAllOnOneLineOrOnePerLine: true
+ConstructorInitializerIndentWidth: 4
+ContinuationIndentWidth: 4
+Cpp11BracedListStyle: true
+DerivePointerAlignment: false
+DisableFormat: false
+FixNamespaceComments: true
+IncludeBlocks: Preserve
+IncludeCategories:
+ - Regex: '^<.*\.h>'
+ Priority: 1
+ - Regex: '^<.*>'
+ Priority: 2
+ - Regex: '.*'
+ Priority: 3
+IndentCaseLabels: false
+IndentPPDirectives: None
+IndentWrappedFunctionNames: false
+KeepEmptyLinesAtTheStartOfBlocks: false
+MaxEmptyLinesToKeep: 1
+NamespaceIndentation: None
+PenaltyBreakAssignment: 2
+PenaltyBreakBeforeFirstCallParameter: 1
+PenaltyBreakComment: 300
+PenaltyBreakFirstLessLess: 120
+PenaltyBreakString: 1000
+PenaltyExcessCharacter: 1000000
+PenaltyReturnTypeOnItsOwnLine: 200
+PointerAlignment: Left
+ReflowComments: true
+SortIncludes: true
+SortUsingDeclarations: true
+SpaceAfterCStyleCast: false
+SpaceAfterTemplateKeyword: true
+SpaceBeforeAssignmentOperators: true
+SpaceBeforeParens: ControlStatements
+SpaceInEmptyParentheses: false
+SpacesBeforeTrailingComments: 2
+SpacesInAngles: false
+SpacesInCStyleCastParentheses: false
+SpacesInContainerLiterals: false
+SpacesInParentheses: false
+SpacesInSquareBrackets: false
+Standard: Cpp17
+---
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 000000000..177a4bb75
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,48 @@
+# Build directories
+build/
+build_*/
+out/
+
+# IDE
+.vs/
+.vscode/
+*.vcxproj*
+*.sln
+.idea/
+*.swp
+*.swo
+*~
+
+# CMake
+CMakeCache.txt
+CMakeFiles/
+cmake_install.cmake
+Makefile
+compile_commands.json
+
+# Compiled files
+*.o
+*.obj
+*.a
+*.lib
+*.so
+*.dll
+*.dylib
+*.exe
+
+# Emscripten output
+*.wasm
+*.js.mem
+*.data
+
+# OS files
+.DS_Store
+Thumbs.db
+desktop.ini
+
+# Third party (if using git submodules, keep this)
+# third_party/
+
+# Test output
+Testing/
+CTestTestfile.cmake
diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 000000000..4553c29f4
--- /dev/null
+++ b/.gitmodules
@@ -0,0 +1,3 @@
+[submodule "third_party/glm"]
+ path = third_party/glm
+ url = https://github.com/g-truc/glm.git
diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644
index 000000000..40f037414
--- /dev/null
+++ b/CMakeLists.txt
@@ -0,0 +1,139 @@
+cmake_minimum_required(VERSION 3.16)
+project(ESEngine VERSION 0.1.0 LANGUAGES CXX)
+
+set(CMAKE_CXX_STANDARD 17)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+set(CMAKE_CXX_EXTENSIONS OFF)
+
+# Build options
+option(ES_BUILD_WEB "Build for Web/Emscripten" OFF)
+option(ES_BUILD_WXGAME "Build for WeChat MiniGame" OFF)
+option(ES_BUILD_EXAMPLES "Build examples" ON)
+option(ES_BUILD_TESTS "Build tests" ON)
+
+# Include custom CMake modules
+list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
+include(ESEngineConfig)
+
+if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
+ include(Emscripten)
+endif()
+
+# Third party libraries
+add_subdirectory(third_party)
+
+# ESEngine library
+set(ESENGINE_SOURCES
+ src/esengine/core/Application.cpp
+ src/esengine/core/Engine.cpp
+ src/esengine/core/Log.cpp
+ src/esengine/renderer/Renderer.cpp
+ src/esengine/renderer/Shader.cpp
+ src/esengine/renderer/Buffer.cpp
+ src/esengine/renderer/Texture.cpp
+ src/esengine/platform/input/Input.cpp
+)
+
+set(ESENGINE_HEADERS
+ src/esengine/ESEngine.hpp
+ src/esengine/core/Types.hpp
+ src/esengine/core/Application.hpp
+ src/esengine/core/Engine.hpp
+ src/esengine/core/Log.hpp
+ src/esengine/ecs/Entity.hpp
+ src/esengine/ecs/Component.hpp
+ src/esengine/ecs/System.hpp
+ src/esengine/ecs/Registry.hpp
+ src/esengine/ecs/SparseSet.hpp
+ src/esengine/ecs/View.hpp
+ src/esengine/math/Math.hpp
+ src/esengine/renderer/Renderer.hpp
+ src/esengine/renderer/Shader.hpp
+ src/esengine/renderer/Buffer.hpp
+ src/esengine/renderer/Texture.hpp
+ src/esengine/renderer/RenderCommand.hpp
+ src/esengine/platform/Platform.hpp
+ src/esengine/platform/input/Input.hpp
+)
+
+# Platform-specific sources
+if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
+ list(APPEND ESENGINE_SOURCES
+ src/esengine/platform/web/WebPlatform.cpp
+ )
+else()
+ # Native platform (for debugging)
+ list(APPEND ESENGINE_SOURCES
+ src/esengine/platform/web/WebPlatform.cpp
+ )
+endif()
+
+add_library(esengine STATIC ${ESENGINE_SOURCES} ${ESENGINE_HEADERS})
+
+target_include_directories(esengine
+ PUBLIC
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src>
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
+ $<INSTALL_INTERFACE:include>
+ PRIVATE
+ ${CMAKE_CURRENT_SOURCE_DIR}/src
+)
+
+target_link_libraries(esengine PUBLIC glm)
+
+# Emscripten-specific settings
+if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
+ target_compile_definitions(esengine PUBLIC ES_PLATFORM_WEB)
+
+ set(EMSCRIPTEN_LINK_FLAGS
+ "-s USE_WEBGL2=1"
+ "-s FULL_ES3=1"
+ "-s ALLOW_MEMORY_GROWTH=1"
+ "-s EXPORTED_FUNCTIONS=['_main','_es_init','_es_update','_es_render','_es_on_touch']"
+ "-s EXPORTED_RUNTIME_METHODS=['ccall','cwrap']"
+ )
+
+ if(ES_BUILD_WXGAME)
+ target_compile_definitions(esengine PUBLIC ES_PLATFORM_WXGAME)
+ list(APPEND EMSCRIPTEN_LINK_FLAGS "-s ENVIRONMENT=web")
+ endif()
+
+ string(REPLACE ";" " " EMSCRIPTEN_LINK_FLAGS_STR "${EMSCRIPTEN_LINK_FLAGS}")
+ set_target_properties(esengine PROPERTIES LINK_FLAGS "${EMSCRIPTEN_LINK_FLAGS_STR}")
+endif()
+
+# Compiler warnings
+if(MSVC)
+ target_compile_options(esengine PRIVATE /W4)
+else()
+ target_compile_options(esengine PRIVATE -Wall -Wextra -Wpedantic)
+endif()
+
+# Examples
+if(ES_BUILD_EXAMPLES)
+ add_subdirectory(examples)
+endif()
+
+# Tests
+if(ES_BUILD_TESTS)
+ enable_testing()
+ add_subdirectory(tests)
+endif()
+
+# Install rules
+install(TARGETS esengine
+ EXPORT ESEngineTargets
+ LIBRARY DESTINATION lib
+ ARCHIVE DESTINATION lib
+ RUNTIME DESTINATION bin
+)
+
+install(DIRECTORY src/esengine/
+ DESTINATION include/esengine
+ FILES_MATCHING PATTERN "*.hpp"
+)
+
+install(DIRECTORY include/esengine/
+ DESTINATION include/esengine
+ FILES_MATCHING PATTERN "*.hpp"
+)
diff --git a/README.md b/README.md
new file mode 100644
index 000000000..d7f88215b
--- /dev/null
+++ b/README.md
@@ -0,0 +1,128 @@
+# ESEngine
+
+A lightweight game engine for WebAssembly and WeChat MiniGames, built with C++17 and Emscripten.
+
+## Features
+
+- **ECS Architecture**: EnTT-style Entity-Component-System for efficient game object management
+- **WebGL Rendering**: OpenGL ES 2.0/3.0 compatible renderer
+- **Cross-Platform**: Targets Web browsers and WeChat MiniGames
+- **Lightweight**: Minimal dependencies, small binary size
+
+## Requirements
+
+- CMake 3.16+
+- C++17 compatible compiler
+- Emscripten SDK (for web builds)
+- GLM (included in third_party)
+
+## Project Structure
+
+```
+esengine/
+├── src/esengine/ # Engine source code
+│ ├── core/ # Core systems (Application, Engine, Log)
+│ ├── ecs/ # Entity-Component-System
+│ ├── math/ # Math utilities (GLM wrapper)
+│ ├── renderer/ # WebGL rendering
+│ └── platform/ # Platform abstraction
+├── include/ # Public headers
+├── third_party/ # Dependencies (GLM)
+├── examples/ # Example projects
+├── tests/ # Unit tests
+└── bindings/ # JS bindings and platform adapters
+```
+
+## Building
+
+### Native (Debug)
+
+```bash
+cmake -B build -DCMAKE_BUILD_TYPE=Debug
+cmake --build build
+```
+
+### Web (Emscripten)
+
+```bash
+source /path/to/emsdk/emsdk_env.sh
+emcmake cmake -B build_web -DES_BUILD_WEB=ON
+cmake --build build_web
+```
+
+### WeChat MiniGame
+
+```bash
+source /path/to/emsdk/emsdk_env.sh
+emcmake cmake -B build_wxgame -DES_BUILD_WXGAME=ON
+cmake --build build_wxgame
+```
+
+## Usage
+
+### Basic Application
+
+```cpp
+#include <esengine/ESEngine.hpp>
+
+class MyGame : public esengine::Application {
+protected:
+ void onInit() override {
+ // Initialize game
+ }
+
+ void onUpdate(float deltaTime) override {
+ // Update game logic
+ }
+
+ void onRender() override {
+ // Render game
+ }
+};
+
+int main() {
+ MyGame game;
+ game.run();
+ return 0;
+}
+```
+
+### ECS Usage
+
+```cpp
+using namespace esengine;
+using namespace esengine::ecs;
+
+// Create entities
+Registry registry;
+Entity player = registry.create();
+
+// Add components
+registry.emplace<Transform>(player, glm::vec3(0, 0, 0));
+registry.emplace<Velocity>(player, glm::vec3(1, 0, 0));
+registry.emplace<Sprite>(player);
+
+// Query and update
+auto view = registry.view<Transform, Velocity>();
+for (auto entity : view) {
+ auto& transform = view.get<Transform>(entity);
+ auto& velocity = view.get<Velocity>(entity);
+ transform.position += velocity.linear * deltaTime;
+}
+```
+
+## Running Tests
+
+```bash
+cmake -B build -DES_BUILD_TESTS=ON
+cmake --build build
+ctest --test-dir build
+```
+
+## License
+
+MIT License - See LICENSE file for details.
+
+## Contributing
+
+Contributions are welcome! Please read CONTRIBUTING.md for guidelines.
diff --git a/bindings/platform/web/index.html b/bindings/platform/web/index.html
new file mode 100644
index 000000000..1fd677c0c
--- /dev/null
+++ b/bindings/platform/web/index.html
@@ -0,0 +1,74 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
+ <title>ESEngine</title>
+ <style>
+ * {
+ margin: 0;
+ padding: 0;
+ box-sizing: border-box;
+ }
+ html, body {
+ width: 100%;
+ height: 100%;
+ overflow: hidden;
+ background-color: #1a1a1a;
+ }
+ #canvas {
+ display: block;
+ width: 100%;
+ height: 100%;
+ touch-action: none;
+ }
+ #loading {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ color: #fff;
+ font-family: sans-serif;
+ font-size: 18px;
+ }
+ #loading.hidden {
+ display: none;
+ }
+ </style>
+</head>
+<body>
+ <div id="loading">Loading ESEngine...</div>
+ <canvas id="canvas"></canvas>
+
+ <script>
+ // ESEngine Web Loader
+ var Module = {
+ canvas: (function() {
+ return document.getElementById('canvas');
+ })(),
+ onRuntimeInitialized: function() {
+ document.getElementById('loading').classList.add('hidden');
+ console.log('ESEngine initialized');
+ },
+ print: function(text) {
+ console.log(text);
+ },
+ printErr: function(text) {
+ console.error(text);
+ }
+ };
+
+ // Handle canvas resizing
+ function resizeCanvas() {
+ var canvas = document.getElementById('canvas');
+ var dpr = window.devicePixelRatio || 1;
+ canvas.width = window.innerWidth * dpr;
+ canvas.height = window.innerHeight * dpr;
+ }
+
+ window.addEventListener('resize', resizeCanvas);
+ resizeCanvas();
+ </script>
+ <script src="hello_triangle.js"></script>
+</body>
+</html>
diff --git a/bindings/platform/wxgame/game.js b/bindings/platform/wxgame/game.js
new file mode 100644
index 000000000..847979b92
--- /dev/null
+++ b/bindings/platform/wxgame/game.js
@@ -0,0 +1,113 @@
+// ESEngine WeChat MiniGame Entry Point
+
+import './weapp-adapter.js';
+
+// Get system info
+const systemInfo = wx.getSystemInfoSync();
+const dpr = systemInfo.pixelRatio;
+const width = systemInfo.windowWidth * dpr;
+const height = systemInfo.windowHeight * dpr;
+
+// Create canvas
+const canvas = wx.createCanvas();
+canvas.width = width;
+canvas.height = height;
+
+// Set up WebGL context
+const gl = canvas.getContext('webgl2') || canvas.getContext('webgl');
+
+if (!gl) {
+ console.error('WebGL not supported');
+}
+
+// Module configuration
+var Module = {
+ canvas: canvas,
+ gl: gl,
+ print: function(text) {
+ console.log('[ESEngine]', text);
+ },
+ printErr: function(text) {
+ console.error('[ESEngine]', text);
+ },
+ onRuntimeInitialized: function() {
+ console.log('ESEngine initialized');
+ // Initialize engine
+ if (Module._es_init) {
+ Module._es_init(width, height);
+ }
+ // Start game loop
+ startGameLoop();
+ }
+};
+
+// Touch handling
+let touches = new Map();
+
+canvas.addEventListener('touchstart', (e) => {
+ for (let touch of e.changedTouches) {
+ touches.set(touch.identifier, {
+ x: touch.clientX * dpr,
+ y: touch.clientY * dpr
+ });
+ if (Module._es_on_touch) {
+ Module._es_on_touch(0, touch.clientX * dpr, touch.clientY * dpr);
+ }
+ }
+});
+
+canvas.addEventListener('touchmove', (e) => {
+ for (let touch of e.changedTouches) {
+ touches.set(touch.identifier, {
+ x: touch.clientX * dpr,
+ y: touch.clientY * dpr
+ });
+ if (Module._es_on_touch) {
+ Module._es_on_touch(1, touch.clientX * dpr, touch.clientY * dpr);
+ }
+ }
+});
+
+canvas.addEventListener('touchend', (e) => {
+ for (let touch of e.changedTouches) {
+ if (Module._es_on_touch) {
+ Module._es_on_touch(2, touch.clientX * dpr, touch.clientY * dpr);
+ }
+ touches.delete(touch.identifier);
+ }
+});
+
+canvas.addEventListener('touchcancel', (e) => {
+ for (let touch of e.changedTouches) {
+ if (Module._es_on_touch) {
+ Module._es_on_touch(3, touch.clientX * dpr, touch.clientY * dpr);
+ }
+ touches.delete(touch.identifier);
+ }
+});
+
+// Game loop
+let lastTime = Date.now();
+
+function startGameLoop() {
+ const loop = () => {
+ const now = Date.now();
+ const deltaTime = (now - lastTime) / 1000.0;
+ lastTime = now;
+
+ if (Module._es_update) {
+ Module._es_update(deltaTime);
+ }
+ if (Module._es_render) {
+ Module._es_render();
+ }
+
+ requestAnimationFrame(loop);
+ };
+
+ requestAnimationFrame(loop);
+}
+
+// Load the WASM module
+// The esengine.js file should be generated by Emscripten
+require('./esengine.js');
diff --git a/bindings/platform/wxgame/game.json b/bindings/platform/wxgame/game.json
new file mode 100644
index 000000000..cd7b3bc5b
--- /dev/null
+++ b/bindings/platform/wxgame/game.json
@@ -0,0 +1,10 @@
+{
+ "deviceOrientation": "portrait",
+ "showStatusBar": false,
+ "networkTimeout": {
+ "request": 10000,
+ "connectSocket": 10000,
+ "uploadFile": 10000,
+ "downloadFile": 10000
+ }
+}
diff --git a/bindings/platform/wxgame/weapp-adapter.js b/bindings/platform/wxgame/weapp-adapter.js
new file mode 100644
index 000000000..4ed9637b0
--- /dev/null
+++ b/bindings/platform/wxgame/weapp-adapter.js
@@ -0,0 +1,151 @@
+// WeChat MiniGame Adapter
+// Provides browser-like APIs for compatibility with Emscripten
+
+// Canvas polyfill
+if (typeof canvas === 'undefined') {
+ var canvas = wx.createCanvas();
+}
+
+// Window object polyfill
+if (typeof window === 'undefined') {
+ var window = {
+ innerWidth: canvas.width,
+ innerHeight: canvas.height,
+ devicePixelRatio: wx.getSystemInfoSync().pixelRatio,
+ performance: {
+ now: function() {
+ return Date.now();
+ }
+ },
+ addEventListener: function(type, listener, options) {
+ if (type === 'resize') {
+ // WeChat doesn't support resize events in the same way
+ }
+ },
+ removeEventListener: function(type, listener, options) {}
+ };
+}
+
+// Document polyfill
+if (typeof document === 'undefined') {
+ var document = {
+ createElement: function(tagName) {
+ if (tagName === 'canvas') {
+ return wx.createCanvas();
+ }
+ return {};
+ },
+ getElementById: function(id) {
+ if (id === 'canvas') {
+ return canvas;
+ }
+ return null;
+ },
+ body: {
+ appendChild: function() {}
+ },
+ addEventListener: function(type, listener, options) {},
+ removeEventListener: function(type, listener, options) {}
+ };
+}
+
+// Performance polyfill
+if (typeof performance === 'undefined') {
+ var performance = {
+ now: function() {
+ return Date.now();
+ }
+ };
+}
+
+// Console polyfill (WeChat has console but ensure it exists)
+if (typeof console === 'undefined') {
+ var console = {
+ log: function() {},
+ error: function() {},
+ warn: function() {},
+ info: function() {}
+ };
+}
+
+// XMLHttpRequest polyfill for asset loading
+if (typeof XMLHttpRequest === 'undefined') {
+ var XMLHttpRequest = function() {
+ this.readyState = 0;
+ this.status = 0;
+ this.responseText = '';
+ this.response = null;
+ };
+
+ XMLHttpRequest.prototype.open = function(method, url, async) {
+ this._method = method;
+ this._url = url;
+ this._async = async;
+ };
+
+ XMLHttpRequest.prototype.send = function(data) {
+ var self = this;
+ var fs = wx.getFileSystemManager();
+
+ if (this._method === 'GET') {
+ try {
+ // Try to read as a local file first
+ var content = fs.readFileSync(this._url);
+ self.status = 200;
+ self.readyState = 4;
+ self.response = content;
+ self.responseText = typeof content === 'string' ? content : '';
+ if (self.onload) self.onload();
+ } catch (e) {
+ // If local read fails, try network
+ wx.request({
+ url: this._url,
+ method: 'GET',
+ responseType: 'arraybuffer',
+ success: function(res) {
+ self.status = res.statusCode;
+ self.readyState = 4;
+ self.response = res.data;
+ if (self.onload) self.onload();
+ },
+ fail: function(err) {
+ self.status = 0;
+ self.readyState = 4;
+ if (self.onerror) self.onerror(err);
+ }
+ });
+ }
+ }
+ };
+
+ XMLHttpRequest.prototype.setRequestHeader = function(name, value) {};
+}
+
+// Image polyfill
+if (typeof Image === 'undefined') {
+ var Image = function() {
+ var img = wx.createImage();
+ return img;
+ };
+}
+
+// Audio polyfill
+if (typeof Audio === 'undefined') {
+ var Audio = function(src) {
+ var audio = wx.createInnerAudioContext();
+ if (src) {
+ audio.src = src;
+ }
+ return audio;
+ };
+}
+
+// Export for module use
+if (typeof module !== 'undefined') {
+ module.exports = {
+ window: window,
+ document: document,
+ canvas: canvas,
+ performance: performance
+ };
+}
diff --git a/cmake/ESEngineConfig.cmake b/cmake/ESEngineConfig.cmake
new file mode 100644
index 000000000..49a57c88a
--- /dev/null
+++ b/cmake/ESEngineConfig.cmake
@@ -0,0 +1,38 @@
+# ESEngine Configuration Options
+# This file contains common configuration settings for the ESEngine build
+
+# Enable position independent code
+set(CMAKE_POSITION_INDEPENDENT_CODE ON)
+
+# Output directories
+set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
+set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
+set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
+
+# Debug/Release configurations
+set(CMAKE_DEBUG_POSTFIX "_d")
+
+# Define ES_DEBUG in debug builds
+if(CMAKE_BUILD_TYPE STREQUAL "Debug")
+ add_compile_definitions(ES_DEBUG)
+endif()
+
+# Platform detection
+if(WIN32)
+ add_compile_definitions(ES_PLATFORM_WINDOWS)
+elseif(APPLE)
+ add_compile_definitions(ES_PLATFORM_MACOS)
+elseif(UNIX)
+ add_compile_definitions(ES_PLATFORM_LINUX)
+endif()
+
+# Export compile commands for IDE support
+set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
+
+# Message about current configuration
+message(STATUS "ESEngine Configuration:")
+message(STATUS " Build Type: ${CMAKE_BUILD_TYPE}")
+message(STATUS " Web Build: ${ES_BUILD_WEB}")
+message(STATUS " WxGame Build: ${ES_BUILD_WXGAME}")
+message(STATUS " Build Examples: ${ES_BUILD_EXAMPLES}")
+message(STATUS " Build Tests: ${ES_BUILD_TESTS}")
diff --git a/cmake/Emscripten.cmake b/cmake/Emscripten.cmake
new file mode 100644
index 000000000..800df1441
--- /dev/null
+++ b/cmake/Emscripten.cmake
@@ -0,0 +1,71 @@
+# Emscripten Toolchain Configuration for ESEngine
+
+if(NOT DEFINED EMSCRIPTEN)
+ message(STATUS "Emscripten toolchain not detected, checking environment...")
+
+ if(DEFINED ENV{EMSDK})
+ set(EMSCRIPTEN_ROOT "$ENV{EMSDK}/upstream/emscripten")
+ message(STATUS "Found EMSDK at: $ENV{EMSDK}")
+ else()
+ message(WARNING "EMSDK environment variable not set. Make sure to use 'emcmake cmake' for web builds.")
+ endif()
+endif()
+
+# Emscripten-specific compiler flags
+set(ES_EMSCRIPTEN_COMPILE_FLAGS
+ "-s USE_WEBGL2=1"
+ "-s FULL_ES3=1"
+)
+
+set(ES_EMSCRIPTEN_LINK_FLAGS
+ "-s WASM=1"
+ "-s ALLOW_MEMORY_GROWTH=1"
+ "-s NO_EXIT_RUNTIME=1"
+ "-s ASSERTIONS=1"
+)
+
+# Debug-specific flags
+if(CMAKE_BUILD_TYPE STREQUAL "Debug")
+ list(APPEND ES_EMSCRIPTEN_COMPILE_FLAGS
+ "-g"
+ "-s ASSERTIONS=2"
+ "-s SAFE_HEAP=1"
+ "-s STACK_OVERFLOW_CHECK=2"
+ )
+endif()
+
+# Release-specific flags
+if(CMAKE_BUILD_TYPE STREQUAL "Release")
+ list(APPEND ES_EMSCRIPTEN_COMPILE_FLAGS
+ "-O3"
+ "-s ASSERTIONS=0"
+ )
+ list(APPEND ES_EMSCRIPTEN_LINK_FLAGS
+ "-O3"
+ "--closure 1"
+ )
+endif()
+
+# WeChat MiniGame specific settings
+if(ES_BUILD_WXGAME)
+ list(APPEND ES_EMSCRIPTEN_LINK_FLAGS
+ "-s ENVIRONMENT=web"
+ "-s MODULARIZE=1"
+ "-s EXPORT_NAME='ESEngineModule'"
+ )
+endif()
+
+# Helper function to apply Emscripten settings to a target
+function(es_apply_emscripten_settings TARGET_NAME)
+ if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
+ target_compile_options(${TARGET_NAME} PRIVATE ${ES_EMSCRIPTEN_COMPILE_FLAGS})
+
+ string(REPLACE ";" " " LINK_FLAGS_STR "${ES_EMSCRIPTEN_LINK_FLAGS}")
+ set_target_properties(${TARGET_NAME} PROPERTIES
+ SUFFIX ".js"
+ LINK_FLAGS "${LINK_FLAGS_STR}"
+ )
+ endif()
+endfunction()
+
+message(STATUS "Emscripten configuration loaded")
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
new file mode 100644
index 000000000..f20ad839b
--- /dev/null
+++ b/docs/ARCHITECTURE.md
@@ -0,0 +1,226 @@
+# ESEngine Architecture
+
+This document describes the architecture and design decisions of the ESEngine game engine.
+
+## Overview
+
+ESEngine is designed as a lightweight, modular game engine targeting WebAssembly and WeChat MiniGames. The architecture prioritizes:
+
+1. **Performance**: Cache-friendly data structures, minimal allocations
+2. **Simplicity**: Clean APIs, minimal dependencies
+3. **Portability**: Abstract platform differences behind interfaces
+
+## Core Modules
+
+### Core (`src/esengine/core/`)
+
+The foundation of the engine.
+
+- **Types.hpp**: Basic type definitions (u32, f32, Entity, etc.)
+- **Log.hpp/cpp**: Logging system with levels (Trace, Debug, Info, Warn, Error, Fatal)
+- **Engine.hpp/cpp**: Engine singleton, version info, platform queries
+- **Application.hpp/cpp**: Base application class with lifecycle hooks
+
+### ECS (`src/esengine/ecs/`)
+
+Entity-Component-System architecture inspired by EnTT.
+
+```
+┌─────────────────────────────────────────────────────────────┐
+│ Registry │
+│ ┌─────────────────────────────────────────────────────┐ │
+│ │ Entity Management │ │
+│ │ - create() / destroy() │ │
+│ │ - valid() / entityCount() │ │
+│ └─────────────────────────────────────────────────────┘ │
+│ ┌─────────────────────────────────────────────────────┐ │
+│ │ Component Pools (SparseSet<T>) │ │
+│ │ ┌───────────┐ ┌───────────┐ ┌───────────┐ │ │
+│ │ │ Transform │ │ Sprite │ │ Velocity │ ... │ │
+│ │ └───────────┘ └───────────┘ └───────────┘ │ │
+│ └─────────────────────────────────────────────────────┘ │
+│ ┌─────────────────────────────────────────────────────┐ │
+│ │ Views (Query System) │ │
+│ │ - view<Transform, Sprite>() → View<T...> │ │
+│ └─────────────────────────────────────────────────────┘ │
+└─────────────────────────────────────────────────────────────┘
+```
+
+#### SparseSet
+
+The core data structure for component storage, providing O(1) operations:
+
+```cpp
+template<typename T>
+class SparseSet {
+ std::vector<Entity> sparse_; // Entity → Dense index
+ std::vector<Entity> dense_; // Dense index → Entity
+ std::vector<T> components_; // Component data (cache-friendly)
+};
+```
+
+Benefits:
+- O(1) add, remove, lookup
+- Cache-friendly iteration (dense arrays)
+- Swap-and-pop deletion (no holes)
+
+#### View System
+
+Views provide filtered iteration over entities with specific components:
+
+```cpp
+auto view = registry.view<Transform, Velocity>();
+for (auto entity : view) {
+ auto& t = view.get<Transform>(entity);
+ auto& v = view.get<Velocity>(entity);
+ t.position += v.linear * deltaTime;
+}
+```
+
+### Renderer (`src/esengine/renderer/`)
+
+WebGL-based rendering system.
+
+```
+┌─────────────────────────────────────────────────────────────┐
+│ Renderer │
+│ ┌─────────────────┐ ┌─────────────────┐ │
+│ │ RenderCommand │ │ Shader │ │
+│ │ (Low-level GL) │ │ (GLSL Program) │ │
+│ └─────────────────┘ └─────────────────┘ │
+│ ┌─────────────────┐ ┌─────────────────┐ │
+│ │ Buffer │ │ Texture │ │
+│ │ (VBO/EBO/VAO) │ │ (2D Images) │ │
+│ └─────────────────┘ └─────────────────┘ │
+└─────────────────────────────────────────────────────────────┘
+```
+
+Key classes:
+- **Renderer**: High-level static API for rendering
+- **RenderCommand**: Low-level OpenGL operations
+- **Shader**: GLSL shader compilation and uniforms
+- **Buffer**: Vertex/Index buffers with layout specification
+- **Texture**: 2D texture loading and binding
+
+### Platform (`src/esengine/platform/`)
+
+Platform abstraction layer.
+
+```
+┌─────────────────────────────────────────────────────────────┐
+│ Platform Interface │
+│ - initialize() / shutdown() │
+│ - pollEvents() / swapBuffers() │
+│ - getTime() / getDeltaTime() │
+│ - Touch/Key/Resize callbacks │
+└─────────────────────────────────────────────────────────────┘
+ │
+ ▼
+┌─────────────────────────────────────────────────────────────┐
+│ WebPlatform │
+│ - Emscripten/WebGL context │
+│ - HTML5 event handling │
+│ - Canvas management │
+└─────────────────────────────────────────────────────────────┘
+```
+
+## Data Flow
+
+### Frame Loop
+
+```
+┌───────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐
+│ Events │ → │ Update │ → │ Render │ → │ Swap │
+│ (Input) │ │ (Systems) │ │ (Draw) │ │ (Present) │
+└───────────┘ └───────────┘ └───────────┘ └───────────┘
+ │ │ │ │
+ ▼ ▼ ▼ ▼
+ Input Registry Renderer Platform
+ System .each<>() .submit() .swapBuffers()
+```
+
+### Component Access Patterns
+
+```cpp
+// Pattern 1: Direct access (when you know the entity)
+auto& transform = registry.get<Transform>(entity);
+
+// Pattern 2: View iteration (for batch processing)
+registry.view<Transform, Velocity>().each([](auto& t, auto& v) {
+ t.position += v.linear;
+});
+
+// Pattern 3: Conditional access
+if (auto* health = registry.tryGet<Health>(entity)) {
+ health->value -= damage;
+}
+```
+
+## Memory Layout
+
+### Entity IDs
+
+```
+Entity = uint32_t
+┌────────────────────────────────────┐
+│ 32-bit ID │
+│ (0 to 4,294,967,294) │
+│ INVALID_ENTITY = 4,294,967,295 │
+└────────────────────────────────────┘
+```
+
+### Component Storage
+
+```
+SparseSet<Transform>:
+sparse_: [2, -, 0, -, 1, ...] (Entity → Index)
+dense_: [E2, E4, E0] (Index → Entity)
+components_: [T2, T4, T0] (Actual data, contiguous)
+```
+
+## Platform Integration
+
+### Web/Emscripten
+
+```
+JavaScript C++ (WASM)
+ │ │
+ │ es_init(w, h) │
+ ├────────────────────────────►│
+ │ │
+ │ requestAnimationFrame │
+ │◄────────────────────────────┤
+ │ │
+ │ es_update(dt) │
+ ├────────────────────────────►│
+ │ es_render() │
+ ├────────────────────────────►│
+ │ │
+```
+
+### WeChat MiniGame
+
+The engine uses a compatibility layer (`weapp-adapter.js`) to provide browser-like APIs in the WeChat environment.
+
+## Extension Points
+
+1. **Custom Components**: Any struct can be a component
+2. **Custom Systems**: Inherit from `System` or use free functions
+3. **Custom Shaders**: Pass GLSL source to `Shader::create()`
+4. **Platform Adaptation**: Implement `Platform` interface
+
+## Performance Considerations
+
+1. **Component Iteration**: Views iterate only entities with all required components
+2. **Memory Locality**: Components stored contiguously in SparseSet
+3. **Minimal Allocations**: Entity recycling, pool-based allocation
+4. **Batch Rendering**: BatchRenderer2D for efficient sprite rendering
+
+## Future Improvements
+
+- [ ] Component groups for cache optimization
+- [ ] Event/signal system
+- [ ] Scene serialization
+- [ ] Audio system
+- [ ] Physics integration
+- [ ] UI system
diff --git a/docs/CODING_STYLE.md b/docs/CODING_STYLE.md
new file mode 100644
index 000000000..466149a2c
--- /dev/null
+++ b/docs/CODING_STYLE.md
@@ -0,0 +1,201 @@
+# ESEngine Coding Style Guide
+
+This document describes the coding conventions used in the ESEngine project.
+
+## Naming Conventions
+
+| Element | Convention | Example |
+|---------|------------|---------|
+| Namespace | lowercase | `esengine::ecs` |
+| Class/Struct | PascalCase | `Registry`, `SparseSet` |
+| Function/Method | camelCase | `createEntity()`, `getComponent()` |
+| Member Variable | snake_case + underscore suffix | `entity_count_`, `sparse_` |
+| Local Variable | camelCase | `entityId`, `deltaTime` |
+| Constant | SCREAMING_SNAKE_CASE | `MAX_ENTITIES`, `INVALID_ENTITY` |
+| Enum | PascalCase | `enum class LogLevel` |
+| Enum Value | PascalCase | `LogLevel::Debug` |
+| Template Parameter | Single uppercase or PascalCase | `T`, `Component` |
+| Macro | SCREAMING_SNAKE_CASE | `ES_LOG_INFO`, `ES_ASSERT` |
+
+## File Conventions
+
+- Header files: `.hpp` extension
+- Source files: `.cpp` extension
+- One class per file (exceptions for tightly coupled helpers)
+- Header guards: Use `#pragma once`
+- File names match class names in PascalCase
+
+## Code Style
+
+### Indentation and Formatting
+
+```cpp
+// 4 spaces, no tabs
+void example() {
+ if (condition) {
+ doSomething();
+ }
+}
+
+// Braces on same line (K&R style)
+class MyClass {
+public:
+ void method() {
+ // ...
+ }
+};
+
+// Single-line statements still use braces
+if (x > 0) {
+ return true;
+}
+```
+
+### Includes
+
+```cpp
+// Order: related header, system headers, library headers, project headers
+#include "MyClass.hpp" // Related header first
+
+#include <cstdint> // C++ standard library
+#include <vector>
+#include <string>
+
+#include <glm/glm.hpp> // Third-party libraries
+
+#include "core/Types.hpp" // Project headers
+#include "ecs/Registry.hpp"
+```
+
+### Class Layout
+
+```cpp
+class MyClass {
+public:
+ // Types and aliases
+ using ValueType = int;
+
+ // Static constants
+ static constexpr int MAX_VALUE = 100;
+
+ // Constructors and destructor
+ MyClass();
+ ~MyClass();
+
+ // Copy/move operations
+ MyClass(const MyClass&) = delete;
+ MyClass& operator=(const MyClass&) = delete;
+
+ // Public methods
+ void doSomething();
+
+protected:
+ // Protected methods
+ void helperMethod();
+
+private:
+ // Private methods
+ void internalMethod();
+
+ // Member variables (underscore suffix)
+ int value_;
+ std::string name_;
+};
+```
+
+### Modern C++ Features
+
+```cpp
+// Use nullptr, not NULL or 0
+Entity* entity = nullptr;
+
+// Use auto when type is obvious
+auto entity = registry.create();
+auto& transform = registry.get<Transform>(entity);
+
+// Use constexpr for compile-time constants
+constexpr int MAX_ENTITIES = 10000;
+
+// Use range-based for loops
+for (const auto& entity : entities) {
+ process(entity);
+}
+
+// Use initializer lists
+std::vector<int> values = {1, 2, 3, 4, 5};
+
+// Use smart pointers
+std::unique_ptr<Shader> shader = std::make_unique<Shader>();
+```
+
+### Comments
+
+```cpp
+// Single-line comments for brief explanations
+int count = 0; // Track entity count
+
+/*
+ * Multi-line comments for longer explanations.
+ * Use these sparingly - code should be self-documenting.
+ */
+
+/// Doxygen-style comments for public API documentation
+/// @param entity The entity to query
+/// @return True if entity has the component
+template<typename T>
+bool has(Entity entity) const;
+```
+
+### Error Handling
+
+```cpp
+// Use assertions for programmer errors (debug only)
+ES_ASSERT(entity != INVALID_ENTITY, "Invalid entity");
+
+// Use logging for runtime information
+ES_LOG_INFO("Created entity {}", entity);
+ES_LOG_ERROR("Failed to load shader: {}", path);
+
+// Return values or optional for expected failures
+std::optional<Entity> findEntity(const std::string& name);
+```
+
+## Best Practices
+
+1. **Keep functions short**: Aim for functions that fit on one screen
+2. **Single responsibility**: Each class/function should do one thing
+3. **Const correctness**: Mark const wherever possible
+4. **RAII**: Use constructors/destructors for resource management
+5. **Avoid raw pointers**: Use smart pointers or references
+6. **Prefer composition over inheritance**
+7. **Write self-documenting code**: Good names > comments
+8. **Handle edge cases**: Check for null, empty, invalid states
+
+## Platform-Specific Code
+
+```cpp
+// Use preprocessor for platform-specific code
+#ifdef ES_PLATFORM_WEB
+ // WebGL-specific code
+#else
+ // Native platform code
+#endif
+
+// Minimize platform-specific code in headers
+// Use PIMPL or abstract interfaces when possible
+```
+
+## Template Guidelines
+
+```cpp
+// Keep templates in headers
+template<typename T>
+class SparseSet {
+ // Implementation in header
+};
+
+// Use concepts (C++20) or SFINAE for constraints
+template<typename T>
+ requires std::is_trivially_copyable_v<T>
+class FastStorage { };
+```
diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt
new file mode 100644
index 000000000..4e353ed6f
--- /dev/null
+++ b/examples/CMakeLists.txt
@@ -0,0 +1,16 @@
+# ESEngine Examples
+
+# Hello Triangle Example
+add_executable(hello_triangle hello_triangle/main.cpp)
+target_link_libraries(hello_triangle PRIVATE esengine)
+
+if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
+ es_apply_emscripten_settings(hello_triangle)
+
+ # Copy HTML file
+ configure_file(
+ ${CMAKE_CURRENT_SOURCE_DIR}/../bindings/platform/web/index.html
+ ${CMAKE_BINARY_DIR}/bin/hello_triangle.html
+ COPYONLY
+ )
+endif()
diff --git a/examples/hello_triangle/main.cpp b/examples/hello_triangle/main.cpp
new file mode 100644
index 000000000..4383178e7
--- /dev/null
+++ b/examples/hello_triangle/main.cpp
@@ -0,0 +1,135 @@
+#include <esengine/ESEngine.hpp>
+
+using namespace esengine;
+using namespace esengine::ecs;
+
+// Simple movement system
+class MovementSystem : public System {
+public:
+ void update(Registry& registry, f32 deltaTime) override {
+ registry.each<Transform, Velocity>([deltaTime](Entity entity, Transform& transform, Velocity& velocity) {
+ (void)entity;
+ transform.position += velocity.linear * deltaTime;
+ });
+ }
+};
+
+// Demo application
+class HelloTriangleApp : public Application {
+public:
+ HelloTriangleApp() : Application({
+ .title = "Hello Triangle",
+ .width = 800,
+ .height = 600
+ }) {}
+
+protected:
+ void onInit() override {
+ ES_LOG_INFO("Hello Triangle initialized!");
+
+ // Create some entities with the ECS
+ auto& registry = getRegistry();
+
+ // Create a triangle entity
+ Entity triangle = registry.create();
+ registry.emplace<Transform>(triangle, glm::vec3(400.0f, 300.0f, 0.0f));
+ registry.emplace<Name>(triangle, "Triangle");
+
+ // Create moving entities
+ for (int i = 0; i < 5; ++i) {
+ Entity entity = registry.create();
+ registry.emplace<Transform>(entity, glm::vec3(100.0f + i * 120.0f, 100.0f, 0.0f));
+ registry.emplace<Velocity>(entity, glm::vec3(50.0f * (i % 2 == 0 ? 1.0f : -1.0f), 0.0f, 0.0f));
+ registry.emplace<Sprite>(entity);
+ }
+
+ ES_LOG_INFO("Created {} entities", registry.entityCount());
+ }
+
+ void onUpdate(f32 deltaTime) override {
+ // Update entities manually (or use SystemGroup)
+ auto& registry = getRegistry();
+ registry.each<Transform, Velocity>([deltaTime, this](Transform& transform, Velocity& velocity) {
+ transform.position += velocity.linear * deltaTime;
+
+ // Bounce off edges
+ if (transform.position.x < 0 || transform.position.x > getWidth()) {
+ velocity.linear.x *= -1.0f;
+ }
+ });
+
+ // Check for touch input
+ if (Input::isTouchPressed()) {
+ auto pos = Input::getTouchPosition();
+ ES_LOG_DEBUG("Touch at ({}, {})", pos.x, pos.y);
+ }
+
+ // Check for key input
+ if (Input::isKeyPressed(KeyCode::Escape)) {
+ quit();
+ }
+ }
+
+ void onRender() override {
+ auto& registry = getRegistry();
+
+ // Draw colored quads for entities with Transform and Sprite
+ auto view = registry.view<Transform, Sprite>();
+ for (auto entity : view) {
+ auto& transform = view.get<Transform>(entity);
+ auto& sprite = view.get<Sprite>(entity);
+
+ Renderer::drawQuad(
+ glm::vec2(transform.position.x, transform.position.y),
+ sprite.size * 50.0f,
+ sprite.color
+ );
+ }
+
+ // Draw the main triangle (entity with just Transform and Name)
+ auto triangleView = registry.view<Transform, Name>();
+ for (auto entity : triangleView) {
+ auto& transform = triangleView.get<Transform>(entity);
+ auto& name = triangleView.get<Name>(entity);
+
+ if (name.value == "Triangle") {
+ Renderer::drawQuad(
+ glm::vec2(transform.position.x, transform.position.y),
+ glm::vec2(100.0f, 100.0f),
+ glm::vec4(1.0f, 0.5f, 0.2f, 1.0f)
+ );
+ }
+ }
+ }
+
+ void onTouch(TouchType type, const TouchPoint& point) override {
+ if (type == TouchType::Begin) {
+ // Create new entity at touch position
+ auto& registry = getRegistry();
+ Entity entity = registry.create();
+ registry.emplace<Transform>(entity, glm::vec3(point.x, point.y, 0.0f));
+ registry.emplace<Sprite>(entity);
+ registry.emplace<Velocity>(entity, glm::vec3(
+ (rand() % 200 - 100.0f),
+ (rand() % 200 - 100.0f),
+ 0.0f
+ ));
+ }
+ }
+
+ void onShutdown() override {
+ ES_LOG_INFO("Hello Triangle shutdown");
+ }
+};
+
+// Entry point
+#ifndef ES_PLATFORM_WEB
+int main() {
+ HelloTriangleApp app;
+ app.run();
+ return 0;
+}
+#else
+// For web, entry is through the C API
+ES_MAIN(HelloTriangleApp)
+#endif
diff --git a/include/esengine/ESEngine.hpp b/include/esengine/ESEngine.hpp
new file mode 100644
index 000000000..69e848e26
--- /dev/null
+++ b/include/esengine/ESEngine.hpp
@@ -0,0 +1,6 @@
+#pragma once
+
+// ESEngine Public API
+// Include this file in your application
+
+#include "../../src/esengine/ESEngine.hpp"
diff --git a/src/esengine/ESEngine.hpp b/src/esengine/ESEngine.hpp
new file mode 100644
index 000000000..d22313d9f
--- /dev/null
+++ b/src/esengine/ESEngine.hpp
@@ -0,0 +1,60 @@
+#pragma once
+
+// ESEngine - Game Engine for WebAssembly and WeChat MiniGames
+// Main header file - includes all public API
+
+// Core
+#include "core/Types.hpp"
+#include "core/Log.hpp"
+#include "core/Engine.hpp"
+#include "core/Application.hpp"
+
+// Math
+#include "math/Math.hpp"
+
+// ECS
+#include "ecs/Entity.hpp"
+#include "ecs/Component.hpp"
+#include "ecs/System.hpp"
+#include "ecs/SparseSet.hpp"
+#include "ecs/View.hpp"
+#include "ecs/Registry.hpp"
+
+// Renderer
+#include "renderer/Buffer.hpp"
+#include "renderer/Shader.hpp"
+#include "renderer/Texture.hpp"
+#include "renderer/RenderCommand.hpp"
+#include "renderer/Renderer.hpp"
+
+// Platform
+#include "platform/Platform.hpp"
+#include "platform/input/Input.hpp"
+
+// Version info
+#define ESENGINE_VERSION_MAJOR 0
+#define ESENGINE_VERSION_MINOR 1
+#define ESENGINE_VERSION_PATCH 0
+#define ESENGINE_VERSION_STRING "0.1.0"
+
+// Entry point macro for applications
+#ifdef ES_PLATFORM_WEB
+ // Web: No main needed, entry is through es_init
+ #define ES_MAIN(AppClass) \
+ extern "C" { \
+ static AppClass* g_app = nullptr; \
+ EMSCRIPTEN_KEEPALIVE void es_app_init() { \
+ g_app = new AppClass(); \
+ g_app->run(); \
+ } \
+ }
+#else
+ // Native: Standard main
+ #define ES_MAIN(AppClass) \
+ int main(int argc, char** argv) { \
+ (void)argc; (void)argv; \
+ AppClass app; \
+ app.run(); \
+ return 0; \
+ }
+#endif
diff --git a/src/esengine/core/Application.cpp b/src/esengine/core/Application.cpp
new file mode 100644
index 000000000..3e7b8acce
--- /dev/null
+++ b/src/esengine/core/Application.cpp
@@ -0,0 +1,159 @@
+#include "Application.hpp"
+#include "Log.hpp"
+#include "../renderer/Renderer.hpp"
+#include "../platform/input/Input.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);
+
+ // 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_->setResizeCallback([this](u32 width, u32 height) {
+ config_.width = width;
+ config_.height = height;
+ Renderer::setViewport(0, 0, width, height);
+ onResize(width, height);
+ });
+
+ // Initialize subsystems
+ Input::init();
+ Renderer::init();
+ 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
+ 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 subsystems
+ Renderer::shutdown();
+ Input::shutdown();
+
+ // Shutdown platform
+ platform_->shutdown();
+
+ Log::shutdown();
+}
+
+} // namespace esengine
diff --git a/src/esengine/core/Application.hpp b/src/esengine/core/Application.hpp
new file mode 100644
index 000000000..0204414c8
--- /dev/null
+++ b/src/esengine/core/Application.hpp
@@ -0,0 +1,79 @@
+#pragma once
+
+#include "Types.hpp"
+#include "../platform/Platform.hpp"
+#include "../ecs/Registry.hpp"
+#include "../ecs/System.hpp"
+
+namespace esengine {
+
+// Application configuration
+struct ApplicationConfig {
+ std::string title = "ESEngine Application";
+ u32 width = 800;
+ u32 height = 600;
+ bool vsync = true;
+};
+
+// Base application class - users derive from this
+class Application {
+public:
+ Application(const ApplicationConfig& config = {});
+ virtual ~Application();
+
+ // Non-copyable
+ Application(const Application&) = delete;
+ Application& operator=(const Application&) = delete;
+
+ // Main entry point
+ void run();
+
+ // Request application to close
+ void quit();
+
+ // Accessors
+ Platform& getPlatform() { return *platform_; }
+ ecs::Registry& getRegistry() { return registry_; }
+
+ u32 getWidth() const { return config_.width; }
+ u32 getHeight() const { return config_.height; }
+ f32 getDeltaTime() const { return static_cast<f32>(deltaTime_); }
+
+ // Singleton access
+ static Application& get() { return *instance_; }
+
+protected:
+ // Lifecycle hooks - override these in derived class
+ virtual void onInit() {}
+ virtual void onUpdate(f32 deltaTime) { (void)deltaTime; }
+ virtual void onRender() {}
+ virtual void onShutdown() {}
+
+ // Event callbacks
+ virtual void onTouch(TouchType type, const TouchPoint& point) {
+ (void)type; (void)point;
+ }
+ virtual void onKey(KeyCode key, bool pressed) {
+ (void)key; (void)pressed;
+ }
+ virtual void onResize(u32 width, u32 height) {
+ (void)width; (void)height;
+ }
+
+ ApplicationConfig config_;
+ Unique<Platform> platform_;
+ ecs::Registry registry_;
+ ecs::SystemGroup systems_;
+
+private:
+ void init();
+ void mainLoop();
+ void shutdown();
+
+ f64 deltaTime_ = 0.0;
+ bool running_ = false;
+
+ static Application* instance_;
+};
+
+} // namespace esengine
diff --git a/src/esengine/core/Engine.cpp b/src/esengine/core/Engine.cpp
new file mode 100644
index 000000000..7834c75c8
--- /dev/null
+++ b/src/esengine/core/Engine.cpp
@@ -0,0 +1,65 @@
+#include "Engine.hpp"
+#include "Log.hpp"
+
+#ifdef ES_PLATFORM_WEB
+ #include <GLES3/gl3.h>
+#else
+ #ifdef _WIN32
+ #include <windows.h>
+ #endif
+ #include <GL/gl.h>
+ #ifndef GL_MAX_TEXTURE_SIZE
+ #define GL_MAX_TEXTURE_SIZE 0x0D33
+ #endif
+#endif
+
+namespace esengine {
+
+Engine& Engine::get() {
+ static Engine instance;
+ return instance;
+}
+
+const char* Engine::getPlatformName() {
+#ifdef ES_PLATFORM_WXGAME
+ return "WeChat MiniGame";
+#elif defined(ES_PLATFORM_WEB)
+ return "Web";
+#elif defined(ES_PLATFORM_WINDOWS)
+ return "Windows";
+#elif defined(ES_PLATFORM_MACOS)
+ return "macOS";
+#elif defined(ES_PLATFORM_LINUX)
+ return "Linux";
+#else
+ return "Unknown";
+#endif
+}
+
+bool Engine::isWebPlatform() {
+#ifdef ES_PLATFORM_WEB
+ return true;
+#else
+ return false;
+#endif
+}
+
+bool Engine::hasWebGL2() {
+#ifdef ES_PLATFORM_WEB
+ return true; // We require WebGL2
+#else
+ return false;
+#endif
+}
+
+u32 Engine::getMaxTextureSize() {
+#ifdef ES_PLATFORM_WEB
+ GLint maxSize = 0;
+ glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxSize);
+ return static_cast<u32>(maxSize);
+#else
+ return 2048; // Default fallback
+#endif
+}
+
+} // namespace esengine
diff --git a/src/esengine/core/Engine.hpp b/src/esengine/core/Engine.hpp
new file mode 100644
index 000000000..c0e82d19a
--- /dev/null
+++ b/src/esengine/core/Engine.hpp
@@ -0,0 +1,47 @@
+#pragma once
+
+#include "Types.hpp"
+#include <string>
+
+namespace esengine {
+
+// Engine version info
+struct EngineVersion {
+ static constexpr u32 MAJOR = 0;
+ static constexpr u32 MINOR = 1;
+ static constexpr u32 PATCH = 0;
+
+ static std::string toString() {
+ return std::to_string(MAJOR) + "." +
+ std::to_string(MINOR) + "." +
+ std::to_string(PATCH);
+ }
+};
+
+// Engine singleton - manages global engine state
+class Engine {
+public:
+ // Get engine instance
+ static Engine& get();
+
+ // Engine info
+ static const char* getName() { return "ESEngine"; }
+ static std::string getVersion() { return EngineVersion::toString(); }
+
+ // Platform info
+ static const char* getPlatformName();
+ static bool isWebPlatform();
+
+ // Feature queries
+ static bool hasWebGL2();
+ static u32 getMaxTextureSize();
+
+private:
+ Engine() = default;
+ ~Engine() = default;
+
+ Engine(const Engine&) = delete;
+ Engine& operator=(const Engine&) = delete;
+};
+
+} // namespace esengine
diff --git a/src/esengine/core/Log.cpp b/src/esengine/core/Log.cpp
new file mode 100644
index 000000000..c0305f6e0
--- /dev/null
+++ b/src/esengine/core/Log.cpp
@@ -0,0 +1,40 @@
+#include "Log.hpp"
+
+namespace esengine {
+
+LogLevel Log::level_ = LogLevel::Info;
+
+void Log::init() {
+#ifdef ES_DEBUG
+ level_ = LogLevel::Trace;
+#else
+ level_ = LogLevel::Info;
+#endif
+ info("ESEngine Log initialized");
+}
+
+void Log::shutdown() {
+ info("ESEngine Log shutdown");
+}
+
+void Log::setLevel(LogLevel level) {
+ level_ = level;
+}
+
+LogLevel Log::getLevel() {
+ return level_;
+}
+
+const char* Log::levelToString(LogLevel level) {
+ switch (level) {
+ case LogLevel::Trace: return "TRACE";
+ case LogLevel::Debug: return "DEBUG";
+ case LogLevel::Info: return "INFO ";
+ case LogLevel::Warn: return "WARN ";
+ case LogLevel::Error: return "ERROR";
+ case LogLevel::Fatal: return "FATAL";
+ default: return "UNKNOWN";
+ }
+}
+
+} // namespace esengine
diff --git a/src/esengine/core/Log.hpp b/src/esengine/core/Log.hpp
new file mode 100644
index 000000000..764b6d822
--- /dev/null
+++ b/src/esengine/core/Log.hpp
@@ -0,0 +1,123 @@
+#pragma once
+
+#include "Types.hpp"
+#include <iostream>
+#include <sstream>
+#include <string>
+
+namespace esengine {
+
+enum class LogLevel : u8 {
+ Trace = 0,
+ Debug = 1,
+ Info = 2,
+ Warn = 3,
+ Error = 4,
+ Fatal = 5
+};
+
+class Log {
+public:
+ static void init();
+ static void shutdown();
+
+ static void setLevel(LogLevel level);
+ static LogLevel getLevel();
+
+ template<typename... Args>
+ static void trace(const char* fmt, Args&&... args) {
+ log(LogLevel::Trace, fmt, std::forward<Args>(args)...);
+ }
+
+ template<typename... Args>
+ static void debug(const char* fmt, Args&&... args) {
+ log(LogLevel::Debug, fmt, std::forward<Args>(args)...);
+ }
+
+ template<typename... Args>
+ static void info(const char* fmt, Args&&... args) {
+ log(LogLevel::Info, fmt, std::forward<Args>(args)...);
+ }
+
+ template<typename... Args>
+ static void warn(const char* fmt, Args&&... args) {
+ log(LogLevel::Warn, fmt, std::forward<Args>(args)...);
+ }
+
+ template<typename... Args>
+ static void error(const char* fmt, Args&&... args) {
+ log(LogLevel::Error, fmt, std::forward<Args>(args)...);
+ }
+
+ template<typename... Args>
+ static void fatal(const char* fmt, Args&&... args) {
+ log(LogLevel::Fatal, fmt, std::forward<Args>(args)...);
+ }
+
+private:
+ static LogLevel level_;
+
+ template<typename... Args>
+ static void log(LogLevel level, const char* fmt, Args&&... args) {
+ if (level < level_) return;
+
+ std::ostringstream oss;
+ oss << "[" << levelToString(level) << "] ";
+ formatTo(oss, fmt, std::forward<Args>(args)...);
+ oss << "\n";
+
+ if (level >= LogLevel::Error) {
+ std::cerr << oss.str();
+ } else {
+ std::cout << oss.str();
+ }
+ }
+
+ static const char* levelToString(LogLevel level);
+
+ // Simple format implementation
+ static void formatTo(std::ostringstream& oss, const char* fmt) {
+ oss << fmt;
+ }
+
+ template<typename T, typename... Args>
+ static void formatTo(std::ostringstream& oss, const char* fmt, T&& value, Args&&... args) {
+ while (*fmt) {
+ if (*fmt == '{' && *(fmt + 1) == '}') {
+ oss << std::forward<T>(value);
+ formatTo(oss, fmt + 2, std::forward<Args>(args)...);
+ return;
+ }
+ oss << *fmt++;
+ }
+ }
+};
+
+// Convenience macros
+#ifdef ES_DEBUG
+ #define ES_LOG_TRACE(...) ::esengine::Log::trace(__VA_ARGS__)
+ #define ES_LOG_DEBUG(...) ::esengine::Log::debug(__VA_ARGS__)
+#else
+ #define ES_LOG_TRACE(...) ((void)0)
+ #define ES_LOG_DEBUG(...) ((void)0)
+#endif
+
+#define ES_LOG_INFO(...) ::esengine::Log::info(__VA_ARGS__)
+#define ES_LOG_WARN(...) ::esengine::Log::warn(__VA_ARGS__)
+#define ES_LOG_ERROR(...) ::esengine::Log::error(__VA_ARGS__)
+#define ES_LOG_FATAL(...) ::esengine::Log::fatal(__VA_ARGS__)
+
+// Assert macro
+#ifdef ES_DEBUG
+ #define ES_ASSERT(condition, message) \
+ do { \
+ if (!(condition)) { \
+ ES_LOG_FATAL("Assertion failed: {} at {}:{}", message, __FILE__, __LINE__); \
+ std::abort(); \
+ } \
+ } while (false)
+#else
+ #define ES_ASSERT(condition, message) ((void)0)
+#endif
+
+} // namespace esengine
diff --git a/src/esengine/core/Types.hpp b/src/esengine/core/Types.hpp
new file mode 100644
index 000000000..d7b11e6ec
--- /dev/null
+++ b/src/esengine/core/Types.hpp
@@ -0,0 +1,94 @@
+#pragma once
+
+#include <cstdint>
+#include <limits>
+#include <memory>
+#include <string>
+#include <vector>
+
+namespace esengine {
+
+// Integer types
+using u8 = std::uint8_t;
+using u16 = std::uint16_t;
+using u32 = std::uint32_t;
+using u64 = std::uint64_t;
+
+using i8 = std::int8_t;
+using i16 = std::int16_t;
+using i32 = std::int32_t;
+using i64 = std::int64_t;
+
+using f32 = float;
+using f64 = double;
+
+// Size type
+using usize = std::size_t;
+
+// Smart pointer aliases
+template<typename T>
+using Unique = std::unique_ptr<T>;
+
+template<typename T>
+using Shared = std::shared_ptr<T>;
+
+template<typename T>
+using Weak = std::weak_ptr<T>;
+
+// Helper functions for creating smart pointers
+template<typename T, typename... Args>
+constexpr Unique<T> makeUnique(Args&&... args) {
+ return std::make_unique<T>(std::forward<Args>(args)...);
+}
+
+template<typename T, typename... Args>
+constexpr Shared<T> makeShared(Args&&... args) {
+ return std::make_shared<T>(std::forward<Args>(args)...);
+}
+
+// Entity type (ECS core)
+using Entity = u32;
+constexpr Entity INVALID_ENTITY = std::numeric_limits<Entity>::max();
+
+// Type ID generation
+using TypeId = u32;
+
+namespace detail {
+ inline TypeId nextTypeId() {
+ static TypeId counter = 0;
+ return counter++;
+ }
+} // namespace detail
+
+template<typename T>
+inline TypeId getTypeId() {
+ static const TypeId id = detail::nextTypeId();
+ return id;
+}
+
+// Result type for operations that can fail
+template<typename T, typename E = std::string>
+class Result {
+public:
+ static Result ok(T value) { return Result(std::move(value), {}, true); }
+ static Result err(E error) { return Result({}, std::move(error), false); }
+
+ bool isOk() const { return success_; }
+ bool isErr() const { return !success_; }
+
+ T& value() { return value_; }
+ const T& value() const { return value_; }
+
+ E& error() { return error_; }
+ const E& error() const { return error_; }
+
+private:
+ Result(T value, E error, bool success)
+ : value_(std::move(value)), error_(std::move(error)), success_(success) {}
+
+ T value_;
+ E error_;
+ bool success_;
+};
+
+} // namespace esengine
diff --git a/src/esengine/ecs/Component.hpp b/src/esengine/ecs/Component.hpp
new file mode 100644
index 000000000..6ff52509b
--- /dev/null
+++ b/src/esengine/ecs/Component.hpp
@@ -0,0 +1,72 @@
+#pragma once
+
+#include "../core/Types.hpp"
+#include "../math/Math.hpp"
+
+namespace esengine::ecs {
+
+// Components are plain data structures
+// They should not contain logic, only data
+
+// Transform component - position, rotation, scale
+struct Transform {
+ glm::vec3 position{0.0f, 0.0f, 0.0f};
+ glm::vec3 rotation{0.0f, 0.0f, 0.0f}; // Euler angles in radians
+ glm::vec3 scale{1.0f, 1.0f, 1.0f};
+
+ Transform() = default;
+ Transform(const glm::vec3& pos) : position(pos) {}
+ Transform(const glm::vec3& pos, const glm::vec3& rot, const glm::vec3& scl)
+ : position(pos), rotation(rot), scale(scl) {}
+
+ // Get model matrix
+ glm::mat4 getMatrix() const {
+ glm::mat4 model = glm::mat4(1.0f);
+ model = glm::translate(model, position);
+ model = glm::rotate(model, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
+ model = glm::rotate(model, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
+ model = glm::rotate(model, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
+ model = glm::scale(model, scale);
+ return model;
+ }
+};
+
+// Velocity component for physics
+struct Velocity {
+ glm::vec3 linear{0.0f};
+ glm::vec3 angular{0.0f};
+
+ Velocity() = default;
+ Velocity(const glm::vec3& lin) : linear(lin) {}
+ Velocity(const glm::vec3& lin, const glm::vec3& ang) : linear(lin), angular(ang) {}
+};
+
+// Sprite component for 2D rendering
+struct Sprite {
+ u32 textureId{0};
+ glm::vec4 color{1.0f, 1.0f, 1.0f, 1.0f};
+ glm::vec2 size{1.0f, 1.0f};
+ glm::vec2 uvOffset{0.0f, 0.0f};
+ glm::vec2 uvScale{1.0f, 1.0f};
+ i32 layer{0};
+
+ Sprite() = default;
+ Sprite(u32 texId) : textureId(texId) {}
+ Sprite(u32 texId, const glm::vec4& col) : textureId(texId), color(col) {}
+};
+
+// Tag components (empty, just for marking entities)
+struct Active {};
+struct Visible {};
+struct Static {};
+
+// Name component for debugging
+struct Name {
+ std::string value;
+
+ Name() = default;
+ Name(const std::string& name) : value(name) {}
+ Name(std::string&& name) : value(std::move(name)) {}
+};
+
+} // namespace esengine::ecs
diff --git a/src/esengine/ecs/Entity.hpp b/src/esengine/ecs/Entity.hpp
new file mode 100644
index 000000000..352d558d8
--- /dev/null
+++ b/src/esengine/ecs/Entity.hpp
@@ -0,0 +1,35 @@
+#pragma once
+
+#include "../core/Types.hpp"
+
+namespace esengine::ecs {
+
+// Entity is just an ID - defined in Types.hpp
+// This file provides entity-related utilities
+
+// Entity version for entity recycling
+struct EntityVersion {
+ Entity id;
+ u32 version;
+};
+
+// Combine entity ID and version into a single value
+inline constexpr u64 makeEntityHandle(Entity id, u32 version) {
+ return (static_cast<u64>(version) << 32) | static_cast<u64>(id);
+}
+
+inline constexpr Entity getEntityId(u64 handle) {
+ return static_cast<Entity>(handle & 0xFFFFFFFF);
+}
+
+inline constexpr u32 getEntityVersion(u64 handle) {
+ return static_cast<u32>(handle >> 32);
+}
+
+// Entity traits
+struct EntityTraits {
+ static constexpr Entity null() { return INVALID_ENTITY; }
+ static constexpr bool isValid(Entity entity) { return entity != INVALID_ENTITY; }
+};
+
+} // namespace esengine::ecs
diff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hpp
new file mode 100644
index 000000000..22a977bf8
--- /dev/null
+++ b/src/esengine/ecs/Registry.hpp
@@ -0,0 +1,281 @@
+#pragma once
+
+#include "../core/Log.hpp"
+#include "../core/Types.hpp"
+#include "Entity.hpp"
+#include "SparseSet.hpp"
+#include "View.hpp"
+#include <any>
+#include <functional>
+#include <unordered_map>
+#include <queue>
+
+namespace esengine::ecs {
+
+// Registry - The main container for all entities and components
+class Registry {
+public:
+ Registry() = default;
+ ~Registry() = default;
+
+ // Non-copyable, movable
+ Registry(const Registry&) = delete;
+ Registry& operator=(const Registry&) = delete;
+ Registry(Registry&&) noexcept = default;
+ Registry& operator=(Registry&&) noexcept = default;
+
+ // ========================================
+ // Entity Management
+ // ========================================
+
+ // Create a new entity
+ Entity create() {
+ Entity entity;
+ if (!recycled_.empty()) {
+ entity = recycled_.front();
+ recycled_.pop();
+ } else {
+ entity = nextEntity_++;
+ }
+
+ if (entity >= entityValid_.size()) {
+ entityValid_.resize(entity + 1, false);
+ }
+ entityValid_[entity] = true;
+
+ ES_LOG_TRACE("Created entity {}", entity);
+ return entity;
+ }
+
+ // Create multiple entities
+ std::vector<Entity> create(usize count) {
+ std::vector<Entity> entities;
+ entities.reserve(count);
+ for (usize i = 0; i < count; ++i) {
+ entities.push_back(create());
+ }
+ return entities;
+ }
+
+ // Destroy an entity
+ void destroy(Entity entity) {
+ if (!valid(entity)) return;
+
+ // Remove all components from this entity
+ for (auto& [typeId, pool] : pools_) {
+ pool->remove(entity);
+ }
+
+ entityValid_[entity] = false;
+ recycled_.push(entity);
+
+ ES_LOG_TRACE("Destroyed entity {}", entity);
+ }
+
+ // Check if entity is valid
+ bool valid(Entity entity) const {
+ return entity < entityValid_.size() && entityValid_[entity];
+ }
+
+ // Get number of active entities
+ usize entityCount() const {
+ usize count = 0;
+ for (bool valid : entityValid_) {
+ if (valid) ++count;
+ }
+ return count;
+ }
+
+ // ========================================
+ // Component Management
+ // ========================================
+
+ // Add component to entity (in-place construction)
+ template<typename T, typename... Args>
+ T& emplace(Entity entity, Args&&... args) {
+ ES_ASSERT(valid(entity), "Invalid entity");
+ auto& pool = assurePool<T>();
+ return pool.emplace(entity, std::forward<Args>(args)...);
+ }
+
+ // Add or replace component
+ template<typename T, typename... Args>
+ T& emplaceOrReplace(Entity entity, Args&&... args) {
+ ES_ASSERT(valid(entity), "Invalid entity");
+ auto& pool = assurePool<T>();
+
+ if (pool.contains(entity)) {
+ pool.get(entity) = T(std::forward<Args>(args)...);
+ return pool.get(entity);
+ }
+ return pool.emplace(entity, std::forward<Args>(args)...);
+ }
+
+ // Remove component from entity
+ template<typename T>
+ void remove(Entity entity) {
+ auto* pool = getPool<T>();
+ if (pool) {
+ pool->remove(entity);
+ }
+ }
+
+ // Get component (must exist)
+ template<typename T>
+ T& get(Entity entity) {
+ auto* pool = getPool<T>();
+ ES_ASSERT(pool != nullptr, "Component pool does not exist");
+ return pool->get(entity);
+ }
+
+ template<typename T>
+ const T& get(Entity entity) const {
+ auto* pool = getPool<T>();
+ ES_ASSERT(pool != nullptr, "Component pool does not exist");
+ return pool->get(entity);
+ }
+
+ // Try to get component (may return nullptr)
+ template<typename T>
+ T* tryGet(Entity entity) {
+ auto* pool = getPool<T>();
+ return pool ? pool->tryGet(entity) : nullptr;
+ }
+
+ template<typename T>
+ const T* tryGet(Entity entity) const {
+ auto* pool = getPool<T>();
+ return pool ? pool->tryGet(entity) : nullptr;
+ }
+
+ // Get or add component
+ template<typename T, typename... Args>
+ T& getOrEmplace(Entity entity, Args&&... args) {
+ auto& pool = assurePool<T>();
+ if (pool.contains(entity)) {
+ return pool.get(entity);
+ }
+ return pool.emplace(entity, std::forward<Args>(args)...);
+ }
+
+ // Check if entity has component
+ template<typename T>
+ bool has(Entity entity) const {
+ auto* pool = getPool<T>();
+ return pool && pool->contains(entity);
+ }
+
+ // Check if entity has all specified components
+ template<typename... Ts>
+ bool hasAll(Entity entity) const {
+ return (has<Ts>(entity) && ...);
+ }
+
+ // Check if entity has any of specified components
+ template<typename... Ts>
+ bool hasAny(Entity entity) const {
+ return (has<Ts>(entity) || ...);
+ }
+
+ // ========================================
+ // View (Query) System
+ // ========================================
+
+ // Get view for iterating entities with specific components
+ template<typename... Components>
+ View<Components...> view() {
+ if constexpr (sizeof...(Components) == 1) {
+ return View<Components...>(&assurePool<Components...>());
+ } else {
+ return View<Components...>(
+ std::make_tuple(&assurePool<Components>()...));
+ }
+ }
+
+ // ========================================
+ // Utility
+ // ========================================
+
+ // Clear all entities and components
+ void clear() {
+ for (auto& [typeId, pool] : pools_) {
+ pool->clear();
+ }
+ entityValid_.clear();
+ while (!recycled_.empty()) recycled_.pop();
+ nextEntity_ = 0;
+ }
+
+ // Execute function for each entity with components
+ template<typename... Components, typename Func>
+ void each(Func&& func) {
+ view<Components...>().each(std::forward<Func>(func));
+ }
+
+ // Sort components by entity order
+ template<typename T, typename Compare>
+ void sort(Compare compare) {
+ auto* pool = getPool<T>();
+ if (!pool) return;
+
+ // Simple selection sort for now
+ // Could be optimized with more sophisticated algorithms
+ auto& entities = const_cast<std::vector<Entity>&>(pool->entities());
+ auto& components = pool->components();
+
+ for (usize i = 0; i < entities.size(); ++i) {
+ usize minIdx = i;
+ for (usize j = i + 1; j < entities.size(); ++j) {
+ if (compare(components[j], components[minIdx])) {
+ minIdx = j;
+ }
+ }
+ if (minIdx != i) {
+ std::swap(entities[i], entities[minIdx]);
+ std::swap(components[i], components[minIdx]);
+ }
+ }
+ }
+
+private:
+ // Get or create component pool
+ template<typename T>
+ SparseSet<T>& assurePool() {
+ TypeId typeId = getTypeId<T>();
+ auto it = pools_.find(typeId);
+ if (it == pools_.end()) {
+ auto pool = makeUnique<SparseSet<T>>();
+ auto& ref = *pool;
+ pools_[typeId] = std::move(pool);
+ return ref;
+ }
+ return *static_cast<SparseSet<T>*>(it->second.get());
+ }
+
+ // Get existing pool (may return nullptr)
+ template<typename T>
+ SparseSet<T>* getPool() {
+ TypeId typeId = getTypeId<T>();
+ auto it = pools_.find(typeId);
+ if (it == pools_.end()) return nullptr;
+ return static_cast<SparseSet<T>*>(it->second.get());
+ }
+
+ template<typename T>
+ const SparseSet<T>* getPool() const {
+ TypeId typeId = getTypeId<T>();
+ auto it = pools_.find(typeId);
+ if (it == pools_.end()) return nullptr;
+ return static_cast<const SparseSet<T>*>(it->second.get());
+ }
+
+ // Entity storage
+ std::vector<bool> entityValid_;
+ std::queue<Entity> recycled_;
+ Entity nextEntity_ = 0;
+
+ // Component pools (type-erased)
+ std::unordered_map<TypeId, Unique<SparseSetBase>> pools_;
+};
+
+} // namespace esengine::ecs
diff --git a/src/esengine/ecs/SparseSet.hpp b/src/esengine/ecs/SparseSet.hpp
new file mode 100644
index 000000000..b9d0987d0
--- /dev/null
+++ b/src/esengine/ecs/SparseSet.hpp
@@ -0,0 +1,136 @@
+#pragma once
+
+#include "../core/Types.hpp"
+#include "Entity.hpp"
+#include <algorithm>
+#include <vector>
+
+namespace esengine::ecs {
+
+// Base class for type-erased sparse set operations
+class SparseSetBase {
+public:
+ virtual ~SparseSetBase() = default;
+
+ virtual bool contains(Entity entity) const = 0;
+ virtual void remove(Entity entity) = 0;
+ virtual usize size() const = 0;
+ virtual bool empty() const = 0;
+ virtual void clear() = 0;
+};
+
+// SparseSet: O(1) insertion, deletion, lookup with cache-friendly iteration
+template<typename T>
+class SparseSet : public SparseSetBase {
+public:
+ using Iterator = typename std::vector<Entity>::const_iterator;
+
+ SparseSet() = default;
+ ~SparseSet() override = default;
+
+ // Non-copyable, movable
+ SparseSet(const SparseSet&) = delete;
+ SparseSet& operator=(const SparseSet&) = delete;
+ SparseSet(SparseSet&&) noexcept = default;
+ SparseSet& operator=(SparseSet&&) noexcept = default;
+
+ // Check if entity exists in set
+ bool contains(Entity entity) const override {
+ return entity < sparse_.size() &&
+ sparse_[entity] < dense_.size() &&
+ dense_[sparse_[entity]] == entity;
+ }
+
+ // Get component for entity (must exist)
+ T& get(Entity entity) {
+ ES_ASSERT(contains(entity), "Entity does not have component");
+ return components_[sparse_[entity]];
+ }
+
+ const T& get(Entity entity) const {
+ ES_ASSERT(contains(entity), "Entity does not have component");
+ return components_[sparse_[entity]];
+ }
+
+ // Try to get component, returns nullptr if not found
+ T* tryGet(Entity entity) {
+ if (!contains(entity)) return nullptr;
+ return &components_[sparse_[entity]];
+ }
+
+ const T* tryGet(Entity entity) const {
+ if (!contains(entity)) return nullptr;
+ return &components_[sparse_[entity]];
+ }
+
+ // Add component to entity
+ template<typename... Args>
+ T& emplace(Entity entity, Args&&... args) {
+ ES_ASSERT(!contains(entity), "Entity already has component");
+
+ // Ensure sparse array is large enough
+ if (entity >= sparse_.size()) {
+ sparse_.resize(entity + 1, INVALID_ENTITY);
+ }
+
+ // Add to dense arrays
+ sparse_[entity] = static_cast<Entity>(dense_.size());
+ dense_.push_back(entity);
+ components_.emplace_back(std::forward<Args>(args)...);
+
+ return components_.back();
+ }
+
+ // Remove component from entity
+ void remove(Entity entity) override {
+ if (!contains(entity)) return;
+
+ // Swap with last element (swap and pop)
+ const auto last = dense_.back();
+ const auto index = sparse_[entity];
+
+ // Move last element to removed position
+ dense_[index] = last;
+ components_[index] = std::move(components_.back());
+ sparse_[last] = index;
+
+ // Pop last element
+ dense_.pop_back();
+ components_.pop_back();
+ sparse_[entity] = INVALID_ENTITY;
+ }
+
+ // Container operations
+ usize size() const override { return dense_.size(); }
+ bool empty() const override { return dense_.empty(); }
+
+ void clear() override {
+ sparse_.clear();
+ dense_.clear();
+ components_.clear();
+ }
+
+ // Iteration - iterate over entities
+ Iterator begin() const { return dense_.begin(); }
+ Iterator end() const { return dense_.end(); }
+
+ // Access to dense entity array (for views)
+ const std::vector<Entity>& entities() const { return dense_; }
+
+ // Access to component array (for direct iteration)
+ std::vector<T>& components() { return components_; }
+ const std::vector<T>& components() const { return components_; }
+
+ // Get index in dense array for entity
+ usize indexOf(Entity entity) const {
+ ES_ASSERT(contains(entity), "Entity not in set");
+ return sparse_[entity];
+ }
+
+private:
+ std::vector<Entity> sparse_; // Entity -> Dense index
+ std::vector<Entity> dense_; // Dense index -> Entity
+ std::vector<T> components_; // Dense storage for components
+};
+
+} // namespace esengine::ecs
diff --git a/src/esengine/ecs/System.hpp b/src/esengine/ecs/System.hpp
new file mode 100644
index 000000000..71f3f0204
--- /dev/null
+++ b/src/esengine/ecs/System.hpp
@@ -0,0 +1,84 @@
+#pragma once
+
+#include "../core/Types.hpp"
+
+namespace esengine::ecs {
+
+// Forward declaration
+class Registry;
+
+// Base class for all systems
+class System {
+public:
+ virtual ~System() = default;
+
+ // Called once when system is added
+ virtual void init(Registry& registry) { (void)registry; }
+
+ // Called every frame
+ virtual void update(Registry& registry, f32 deltaTime) = 0;
+
+ // Called once when system is removed
+ virtual void shutdown(Registry& registry) { (void)registry; }
+
+ // Enable/disable system
+ void setEnabled(bool enabled) { enabled_ = enabled; }
+ bool isEnabled() const { return enabled_; }
+
+ // Priority for ordering (lower = runs first)
+ void setPriority(i32 priority) { priority_ = priority; }
+ i32 getPriority() const { return priority_; }
+
+protected:
+ bool enabled_ = true;
+ i32 priority_ = 0;
+};
+
+// System group for organizing systems
+class SystemGroup {
+public:
+ void addSystem(Unique<System> system) {
+ systems_.push_back(std::move(system));
+ sortSystems();
+ }
+
+ template<typename T, typename... Args>
+ T& createSystem(Args&&... args) {
+ auto system = makeUnique<T>(std::forward<Args>(args)...);
+ T& ref = *system;
+ addSystem(std::move(system));
+ return ref;
+ }
+
+ void init(Registry& registry) {
+ for (auto& system : systems_) {
+ system->init(registry);
+ }
+ }
+
+ void update(Registry& registry, f32 deltaTime) {
+ for (auto& system : systems_) {
+ if (system->isEnabled()) {
+ system->update(registry, deltaTime);
+ }
+ }
+ }
+
+ void shutdown(Registry& registry) {
+ for (auto& system : systems_) {
+ system->shutdown(registry);
+ }
+ }
+
+private:
+ void sortSystems() {
+ std::sort(systems_.begin(), systems_.end(),
+ [](const Unique<System>& a, const Unique<System>& b) {
+ return a->getPriority() < b->getPriority();
+ });
+ }
+
+ std::vector<Unique<System>> systems_;
+};
+
+} // namespace esengine::ecs
diff --git a/src/esengine/ecs/View.hpp b/src/esengine/ecs/View.hpp
new file mode 100644
index 000000000..369db883e
--- /dev/null
+++ b/src/esengine/ecs/View.hpp
@@ -0,0 +1,198 @@
+#pragma once
+
+#include "../core/Types.hpp"
+#include "Entity.hpp"
+#include "SparseSet.hpp"
+#include <tuple>
+
+namespace esengine::ecs {
+
+// Forward declaration
+class Registry;
+
+// View iterator - iterates over entities that have all specified components
+template<typename... Components>
+class ViewIterator {
+public:
+ using PoolsTuple = std::tuple<SparseSet<Components>*...>;
+
+ ViewIterator(const std::vector<Entity>* entities, usize index, PoolsTuple pools)
+ : entities_(entities), index_(index), pools_(pools) {
+ // Skip to first valid entity
+ if (entities_ && index_ < entities_->size()) {
+ skipInvalid();
+ }
+ }
+
+ Entity operator*() const {
+ return (*entities_)[index_];
+ }
+
+ ViewIterator& operator++() {
+ ++index_;
+ skipInvalid();
+ return *this;
+ }
+
+ bool operator!=(const ViewIterator& other) const {
+ return index_ != other.index_;
+ }
+
+ bool operator==(const ViewIterator& other) const {
+ return index_ == other.index_;
+ }
+
+private:
+ void skipInvalid() {
+ while (index_ < entities_->size()) {
+ Entity entity = (*entities_)[index_];
+ if (allHave(entity)) {
+ break;
+ }
+ ++index_;
+ }
+ }
+
+ bool allHave(Entity entity) const {
+ return allHaveImpl(entity, std::index_sequence_for<Components...>{});
+ }
+
+ template<usize... Is>
+ bool allHaveImpl(Entity entity, std::index_sequence<Is...>) const {
+ return (std::get<Is>(pools_)->contains(entity) && ...);
+ }
+
+ const std::vector<Entity>* entities_;
+ usize index_;
+ PoolsTuple pools_;
+};
+
+// View - provides iteration over entities with specific components
+template<typename... Components>
+class View {
+public:
+ using Iterator = ViewIterator<Components...>;
+ using PoolsTuple = std::tuple<SparseSet<Components>*...>;
+
+ View(PoolsTuple pools) : pools_(pools) {
+ // Find the smallest pool to iterate over
+ findSmallestPool();
+ }
+
+ Iterator begin() const {
+ if (!smallest_) return end();
+ return Iterator(&smallest_->entities(), 0, pools_);
+ }
+
+ Iterator end() const {
+ if (!smallest_) return Iterator(nullptr, 0, pools_);
+ return Iterator(&smallest_->entities(), smallest_->size(), pools_);
+ }
+
+ // Get component from view (entity must be valid)
+ template<typename T>
+ T& get(Entity entity) {
+ return std::get<SparseSet<T>*>(pools_)->get(entity);
+ }
+
+ template<typename T>
+ const T& get(Entity entity) const {
+ return std::get<SparseSet<T>*>(pools_)->get(entity);
+ }
+
+ // Get multiple components at once
+ std::tuple<Components&...> getAll(Entity entity) {
+ return std::tuple<Components&...>(
+ std::get<SparseSet<Components>*>(pools_)->get(entity)...);
+ }
+
+ // Check if view is empty
+ bool empty() const {
+ return !smallest_ || smallest_->empty();
+ }
+
+ // Estimate size (upper bound)
+ usize sizeHint() const {
+ return smallest_ ? smallest_->size() : 0;
+ }
+
+ // Execute function for each entity
+ template<typename Func>
+ void each(Func&& func) {
+ for (auto entity : *this) {
+ if constexpr (std::is_invocable_v<Func, Entity, Components&...>) {
+ func(entity, get<Components>(entity)...);
+ } else if constexpr (std::is_invocable_v<Func, Components&...>) {
+ func(get<Components>(entity)...);
+ } else {
+ func(entity);
+ }
+ }
+ }
+
+private:
+ void findSmallestPool() {
+ smallest_ = nullptr;
+ usize minSize = std::numeric_limits<usize>::max();
+
+ findSmallestImpl(minSize, std::index_sequence_for<Components...>{});
+ }
+
+ template<usize... Is>
+ void findSmallestImpl(usize& minSize, std::index_sequence<Is...>) {
+ ((checkPool<Is>(minSize)), ...);
+ }
+
+ template<usize I>
+ void checkPool(usize& minSize) {
+ auto* pool = std::get<I>(pools_);
+ if (pool && pool->size() < minSize) {
+ minSize = pool->size();
+ smallest_ = reinterpret_cast<SparseSetBase*>(pool);
+ }
+ }
+
+ PoolsTuple pools_;
+ SparseSetBase* smallest_ = nullptr;
+};
+
+// Single component view specialization (more efficient)
+template<typename T>
+class View<T> {
+public:
+ using Iterator = typename std::vector<Entity>::const_iterator;
+
+ explicit View(SparseSet<T>* pool) : pool_(pool) {}
+
+ Iterator begin() const { return pool_ ? pool_->begin() : Iterator{}; }
+ Iterator end() const { return pool_ ? pool_->end() : Iterator{}; }
+
+ T& get(Entity entity) { return pool_->get(entity); }
+ const T& get(Entity entity) const { return pool_->get(entity); }
+
+ bool empty() const { return !pool_ || pool_->empty(); }
+ usize size() const { return pool_ ? pool_->size() : 0; }
+
+ template<typename Func>
+ void each(Func&& func) {
+ if (!pool_) return;
+
+ const auto& entities = pool_->entities();
+ auto& components = pool_->components();
+
+ for (usize i = 0; i < entities.size(); ++i) {
+ if constexpr (std::is_invocable_v<Func, Entity, T&>) {
+ func(entities[i], components[i]);
+ } else if constexpr (std::is_invocable_v<Func, T&>) {
+ func(components[i]);
+ } else {
+ func(entities[i]);
+ }
+ }
+ }
+
+private:
+ SparseSet<T>* pool_;
+};
+
+} // namespace esengine::ecs
diff --git a/src/esengine/math/Math.hpp b/src/esengine/math/Math.hpp
new file mode 100644
index 000000000..b8b3723c0
--- /dev/null
+++ b/src/esengine/math/Math.hpp
@@ -0,0 +1,108 @@
+#pragma once
+
+// GLM Configuration
+#define GLM_FORCE_RADIANS
+#define GLM_FORCE_DEPTH_ZERO_TO_ONE
+#define GLM_ENABLE_EXPERIMENTAL
+
+// GLM Core
+#include <glm/glm.hpp>
+#include <glm/gtc/matrix_transform.hpp>
+#include <glm/gtc/type_ptr.hpp>
+#include <glm/gtc/quaternion.hpp>
+#include <glm/gtx/quaternion.hpp>
+#include <glm/gtx/euler_angles.hpp>
+
+namespace esengine {
+
+// Math constants
+namespace math {
+
+constexpr float PI = 3.14159265358979323846f;
+constexpr float TWO_PI = 2.0f * PI;
+constexpr float HALF_PI = 0.5f * PI;
+constexpr float DEG_TO_RAD = PI / 180.0f;
+constexpr float RAD_TO_DEG = 180.0f / PI;
+constexpr float EPSILON = 1e-6f;
+
+// Utility functions
+inline float toRadians(float degrees) {
+ return degrees * DEG_TO_RAD;
+}
+
+inline float toDegrees(float radians) {
+ return radians * RAD_TO_DEG;
+}
+
+inline glm::vec3 toRadians(const glm::vec3& degrees) {
+ return degrees * DEG_TO_RAD;
+}
+
+inline glm::vec3 toDegrees(const glm::vec3& radians) {
+ return radians * RAD_TO_DEG;
+}
+
+// Linear interpolation
+template<typename T>
+inline T lerp(const T& a, const T& b, float t) {
+ return a + t * (b - a);
+}
+
+// Clamp value
+template<typename T>
+inline T clamp(const T& value, const T& min, const T& max) {
+ return glm::clamp(value, min, max);
+}
+
+// Approximately equal for floating point
+inline bool approxEqual(float a, float b, float epsilon = EPSILON) {
+ return std::abs(a - b) < epsilon;
+}
+
+inline bool approxEqual(const glm::vec3& a, const glm::vec3& b, float epsilon = EPSILON) {
+ return approxEqual(a.x, b.x, epsilon) &&
+ approxEqual(a.y, b.y, epsilon) &&
+ approxEqual(a.z, b.z, epsilon);
+}
+
+// Create orthographic projection matrix
+inline glm::mat4 ortho(float left, float right, float bottom, float top, float near, float far) {
+ return glm::ortho(left, right, bottom, top, near, far);
+}
+
+// Create perspective projection matrix
+inline glm::mat4 perspective(float fov, float aspect, float near, float far) {
+ return glm::perspective(fov, aspect, near, far);
+}
+
+// Create look-at view matrix
+inline glm::mat4 lookAt(const glm::vec3& eye, const glm::vec3& center, const glm::vec3& up) {
+ return glm::lookAt(eye, center, up);
+}
+
+// Decompose transformation matrix
+inline void decompose(const glm::mat4& matrix, glm::vec3& position, glm::vec3& rotation, glm::vec3& scale) {
+ // Extract position
+ position = glm::vec3(matrix[3]);
+
+ // Extract scale
+ scale.x = glm::length(glm::vec3(matrix[0]));
+ scale.y = glm::length(glm::vec3(matrix[1]));
+ scale.z = glm::length(glm::vec3(matrix[2]));
+
+ // Remove scale from matrix for rotation extraction
+ glm::mat3 rotMatrix(
+ glm::vec3(matrix[0]) / scale.x,
+ glm::vec3(matrix[1]) / scale.y,
+ glm::vec3(matrix[2]) / scale.z
+ );
+
+ // Extract Euler angles from rotation matrix
+ rotation.x = std::atan2(rotMatrix[2][1], rotMatrix[2][2]);
+ rotation.y = std::atan2(-rotMatrix[2][0],
+ std::sqrt(rotMatrix[2][1] * rotMatrix[2][1] + rotMatrix[2][2] * rotMatrix[2][2]));
+ rotation.z = std::atan2(rotMatrix[1][0], rotMatrix[0][0]);
+}
+
+} // namespace math
+} // namespace esengine
diff --git a/src/esengine/platform/Platform.hpp b/src/esengine/platform/Platform.hpp
new file mode 100644
index 000000000..11f5bfb59
--- /dev/null
+++ b/src/esengine/platform/Platform.hpp
@@ -0,0 +1,80 @@
+#pragma once
+
+#include "../core/Types.hpp"
+#include <functional>
+
+namespace esengine {
+
+// Touch event types
+enum class TouchType : u8 {
+ Begin = 0,
+ Move = 1,
+ End = 2,
+ Cancel = 3
+};
+
+// Touch point data
+struct TouchPoint {
+ i32 id;
+ f32 x;
+ f32 y;
+};
+
+// Key codes (subset for mobile/web)
+enum class KeyCode : u32 {
+ Unknown = 0,
+ Space = 32,
+ Enter = 13,
+ Escape = 27,
+ Left = 37,
+ Up = 38,
+ Right = 39,
+ Down = 40,
+ A = 65,
+ D = 68,
+ S = 83,
+ W = 87
+};
+
+// Event callbacks
+using TouchCallback = std::function<void(TouchType type, const TouchPoint& point)>;
+using KeyCallback = std::function<void(KeyCode key, bool pressed)>;
+using ResizeCallback = std::function<void(u32 width, u32 height)>;
+
+// Platform abstraction interface
+class Platform {
+public:
+ virtual ~Platform() = default;
+
+ // Lifecycle
+ virtual bool initialize(u32 width, u32 height) = 0;
+ virtual void shutdown() = 0;
+
+ // Frame handling
+ virtual void pollEvents() = 0;
+ virtual void swapBuffers() = 0;
+
+ // Time
+ virtual f64 getTime() const = 0;
+ virtual f64 getDeltaTime() const = 0;
+
+ // Window properties
+ virtual u32 getWindowWidth() const = 0;
+ virtual u32 getWindowHeight() const = 0;
+ virtual f32 getAspectRatio() const = 0;
+ virtual f32 getDevicePixelRatio() const = 0;
+
+ // State
+ virtual bool isRunning() const = 0;
+ virtual void requestQuit() = 0;
+
+ // Callbacks
+ virtual void setTouchCallback(TouchCallback callback) = 0;
+ virtual void setKeyCallback(KeyCallback callback) = 0;
+ virtual void setResizeCallback(ResizeCallback callback) = 0;
+
+ // Factory
+ static Unique<Platform> create();
+};
+
+} // namespace esengine
diff --git a/src/esengine/platform/input/Input.cpp b/src/esengine/platform/input/Input.cpp
new file mode 100644
index 000000000..6bfa6737d
--- /dev/null
+++ b/src/esengine/platform/input/Input.cpp
@@ -0,0 +1,162 @@
+#include "Input.hpp"
+#include "../../core/Log.hpp"
+
+namespace esengine {
+
+// Static member definitions
+std::array<TouchState, MAX_TOUCH_POINTS> Input::touchStates_;
+std::array<TouchState, MAX_TOUCH_POINTS> Input::prevTouchStates_;
+std::unordered_map<u32, bool> Input::keyStates_;
+std::unordered_map<u32, bool> Input::prevKeyStates_;
+glm::vec2 Input::mousePosition_{0.0f};
+
+void Input::init() {
+ for (auto& state : touchStates_) {
+ state = TouchState{};
+ }
+ for (auto& state : prevTouchStates_) {
+ state = TouchState{};
+ }
+ keyStates_.clear();
+ prevKeyStates_.clear();
+ mousePosition_ = glm::vec2(0.0f);
+
+ ES_LOG_INFO("Input system initialized");
+}
+
+void Input::shutdown() {
+ ES_LOG_INFO("Input system shutdown");
+}
+
+void Input::update() {
+ // Store previous frame's state
+ prevTouchStates_ = touchStates_;
+ prevKeyStates_ = keyStates_;
+}
+
+// Touch input
+bool Input::isTouchDown(u32 index) {
+ if (index >= MAX_TOUCH_POINTS) return false;
+ return touchStates_[index].active;
+}
+
+bool Input::isTouchPressed(u32 index) {
+ if (index >= MAX_TOUCH_POINTS) return false;
+ return touchStates_[index].active && !prevTouchStates_[index].active;
+}
+
+bool Input::isTouchReleased(u32 index) {
+ if (index >= MAX_TOUCH_POINTS) return false;
+ return !touchStates_[index].active && prevTouchStates_[index].active;
+}
+
+glm::vec2 Input::getTouchPosition(u32 index) {
+ if (index >= MAX_TOUCH_POINTS) return glm::vec2(0.0f);
+ return glm::vec2(touchStates_[index].x, touchStates_[index].y);
+}
+
+glm::vec2 Input::getTouchDelta(u32 index) {
+ if (index >= MAX_TOUCH_POINTS) return glm::vec2(0.0f);
+ const auto& state = touchStates_[index];
+ return glm::vec2(state.x - state.startX, state.y - state.startY);
+}
+
+u32 Input::getTouchCount() {
+ u32 count = 0;
+ for (const auto& state : touchStates_) {
+ if (state.active) ++count;
+ }
+ return count;
+}
+
+// Keyboard input
+bool Input::isKeyDown(KeyCode key) {
+ auto it = keyStates_.find(static_cast<u32>(key));
+ return it != keyStates_.end() && it->second;
+}
+
+bool Input::isKeyPressed(KeyCode key) {
+ u32 keyCode = static_cast<u32>(key);
+ bool current = keyStates_.count(keyCode) && keyStates_[keyCode];
+ bool previous = prevKeyStates_.count(keyCode) && prevKeyStates_[keyCode];
+ return current && !previous;
+}
+
+bool Input::isKeyReleased(KeyCode key) {
+ u32 keyCode = static_cast<u32>(key);
+ bool current = keyStates_.count(keyCode) && keyStates_[keyCode];
+ bool previous = prevKeyStates_.count(keyCode) && prevKeyStates_[keyCode];
+ return !current && previous;
+}
+
+// Mouse input
+glm::vec2 Input::getMousePosition() {
+ return mousePosition_;
+}
+
+bool Input::isMouseButtonDown(u32 button) {
+ // Mouse button 0 is treated as touch 0
+ if (button == 0) {
+ return isTouchDown(0);
+ }
+ return false;
+}
+
+// Event handlers
+void Input::onTouchEvent(TouchType type, const TouchPoint& point) {
+ // Find or allocate touch slot
+ u32 index = MAX_TOUCH_POINTS;
+
+ // Find existing touch with this ID
+ for (u32 i = 0; i < MAX_TOUCH_POINTS; ++i) {
+ if (touchStates_[i].active && static_cast<i32>(i) == point.id) {
+ index = i;
+ break;
+ }
+ }
+
+ // If new touch, find empty slot
+ if (index == MAX_TOUCH_POINTS && type == TouchType::Begin) {
+ for (u32 i = 0; i < MAX_TOUCH_POINTS; ++i) {
+ if (!touchStates_[i].active) {
+ index = i;
+ break;
+ }
+ }
+ }
+
+ if (index >= MAX_TOUCH_POINTS) return;
+
+ auto& state = touchStates_[index];
+
+ switch (type) {
+ case TouchType::Begin:
+ state.active = true;
+ state.x = point.x;
+ state.y = point.y;
+ state.startX = point.x;
+ state.startY = point.y;
+ break;
+
+ case TouchType::Move:
+ state.x = point.x;
+ state.y = point.y;
+ break;
+
+ case TouchType::End:
+ case TouchType::Cancel:
+ state.active = false;
+ break;
+ }
+
+ // Also update mouse position for debugging
+ if (index == 0) {
+ mousePosition_ = glm::vec2(point.x, point.y);
+ }
+}
+
+void Input::onKeyEvent(KeyCode key, bool pressed) {
+ keyStates_[static_cast<u32>(key)] = pressed;
+}
+
+} // namespace esengine
diff --git a/src/esengine/platform/input/Input.hpp b/src/esengine/platform/input/Input.hpp
new file mode 100644
index 000000000..c336d8386
--- /dev/null
+++ b/src/esengine/platform/input/Input.hpp
@@ -0,0 +1,61 @@
+#pragma once
+
+#include "../../core/Types.hpp"
+#include "../Platform.hpp"
+#include <array>
+#include <unordered_map>
+
+namespace esengine {
+
+// Maximum simultaneous touch points
+constexpr u32 MAX_TOUCH_POINTS = 10;
+
+// Input state for touch points
+struct TouchState {
+ bool active = false;
+ f32 x = 0.0f;
+ f32 y = 0.0f;
+ f32 startX = 0.0f;
+ f32 startY = 0.0f;
+};
+
+// Input manager - handles all input state
+class Input {
+public:
+ static void init();
+ static void shutdown();
+ static void update();
+
+ // Touch input
+ static bool isTouchDown(u32 index = 0);
+ static bool isTouchPressed(u32 index = 0); // Just started this frame
+ static bool isTouchReleased(u32 index = 0); // Just ended this frame
+
+ static glm::vec2 getTouchPosition(u32 index = 0);
+ static glm::vec2 getTouchDelta(u32 index = 0); // Movement since touch began
+ static u32 getTouchCount();
+
+ // Keyboard input
+ static bool isKeyDown(KeyCode key);
+ static bool isKeyPressed(KeyCode key);
+ static bool isKeyReleased(KeyCode key);
+
+ // Mouse input (for web debugging)
+ static glm::vec2 getMousePosition();
+ static bool isMouseButtonDown(u32 button = 0);
+
+ // Internal - called by platform
+ static void onTouchEvent(TouchType type, const TouchPoint& point);
+ static void onKeyEvent(KeyCode key, bool pressed);
+
+private:
+ static std::array<TouchState, MAX_TOUCH_POINTS> touchStates_;
+ static std::array<TouchState, MAX_TOUCH_POINTS> prevTouchStates_;
+
+ static std::unordered_map<u32, bool> keyStates_;
+ static std::unordered_map<u32, bool> prevKeyStates_;
+
+ static glm::vec2 mousePosition_;
+};
+
+} // namespace esengine
diff --git a/src/esengine/platform/web/WebPlatform.cpp b/src/esengine/platform/web/WebPlatform.cpp
new file mode 100644
index 000000000..45246d26f
--- /dev/null
+++ b/src/esengine/platform/web/WebPlatform.cpp
@@ -0,0 +1,315 @@
+#include "../Platform.hpp"
+#include "../../core/Log.hpp"
+
+#ifdef ES_PLATFORM_WEB
+ #include <emscripten.h>
+ #include <emscripten/html5.h>
+ #include <GLES3/gl3.h>
+#endif
+
+namespace esengine {
+
+class WebPlatform : public Platform {
+public:
+ WebPlatform() = default;
+ ~WebPlatform() override = default;
+
+ bool initialize(u32 width, u32 height) override {
+ width_ = width;
+ height_ = height;
+ running_ = true;
+
+#ifdef ES_PLATFORM_WEB
+ // Create WebGL context
+ EmscriptenWebGLContextAttributes attrs;
+ emscripten_webgl_init_context_attributes(&attrs);
+ attrs.majorVersion = 2;
+ attrs.minorVersion = 0;
+ attrs.alpha = false;
+ attrs.depth = true;
+ attrs.stencil = false;
+ attrs.antialias = true;
+ attrs.premultipliedAlpha = true;
+ attrs.preserveDrawingBuffer = false;
+
+ context_ = emscripten_webgl_create_context("#canvas", &attrs);
+ if (context_ <= 0) {
+ ES_LOG_ERROR("Failed to create WebGL context");
+ return false;
+ }
+
+ emscripten_webgl_make_context_current(context_);
+
+ // Set canvas size
+ emscripten_set_canvas_element_size("#canvas", width, height);
+
+ // Get device pixel ratio
+ devicePixelRatio_ = static_cast<f32>(emscripten_get_device_pixel_ratio());
+
+ // Get actual canvas size
+ f64 cssWidth, cssHeight;
+ emscripten_get_element_css_size("#canvas", &cssWidth, &cssHeight);
+ width_ = static_cast<u32>(cssWidth * devicePixelRatio_);
+ height_ = static_cast<u32>(cssHeight * devicePixelRatio_);
+
+ // Register event callbacks
+ setupEventCallbacks();
+
+ ES_LOG_INFO("WebPlatform initialized ({}x{}, DPR: {})", width_, height_, devicePixelRatio_);
+#endif
+ lastTime_ = getTime();
+ return true;
+ }
+
+ void shutdown() override {
+#ifdef ES_PLATFORM_WEB
+ if (context_ > 0) {
+ emscripten_webgl_destroy_context(context_);
+ context_ = 0;
+ }
+#endif
+ running_ = false;
+ ES_LOG_INFO("WebPlatform shutdown");
+ }
+
+ void pollEvents() override {
+ // Events are handled via callbacks in Emscripten
+ f64 currentTime = getTime();
+ deltaTime_ = currentTime - lastTime_;
+ lastTime_ = currentTime;
+ }
+
+ void swapBuffers() override {
+ // Emscripten handles buffer swapping automatically
+ }
+
+ f64 getTime() const override {
+#ifdef ES_PLATFORM_WEB
+ return emscripten_get_now() / 1000.0;
+#else
+ return 0.0;
+#endif
+ }
+
+ f64 getDeltaTime() const override {
+ return deltaTime_;
+ }
+
+ u32 getWindowWidth() const override { return width_; }
+ u32 getWindowHeight() const override { return height_; }
+
+ f32 getAspectRatio() const override {
+ return height_ > 0 ? static_cast<f32>(width_) / static_cast<f32>(height_) : 1.0f;
+ }
+
+ f32 getDevicePixelRatio() const override { return devicePixelRatio_; }
+
+ bool isRunning() const override { return running_; }
+ void requestQuit() override { running_ = false; }
+
+ void setTouchCallback(TouchCallback callback) override {
+ touchCallback_ = std::move(callback);
+ }
+
+ void setKeyCallback(KeyCallback callback) override {
+ keyCallback_ = std::move(callback);
+ }
+
+ void setResizeCallback(ResizeCallback callback) override {
+ resizeCallback_ = std::move(callback);
+ }
+
+ // Static instance for callbacks
+ static WebPlatform* instance_;
+
+private:
+ void setupEventCallbacks() {
+#ifdef ES_PLATFORM_WEB
+ instance_ = this;
+
+ // Touch events
+ emscripten_set_touchstart_callback("#canvas", this, true, touchCallback);
+ emscripten_set_touchmove_callback("#canvas", this, true, touchCallback);
+ emscripten_set_touchend_callback("#canvas", this, true, touchCallback);
+ emscripten_set_touchcancel_callback("#canvas", this, true, touchCallback);
+
+ // Mouse events (simulate touch)
+ emscripten_set_mousedown_callback("#canvas", this, true, mouseCallback);
+ emscripten_set_mousemove_callback("#canvas", this, true, mouseCallback);
+ emscripten_set_mouseup_callback("#canvas", this, true, mouseCallback);
+
+ // Keyboard events
+ emscripten_set_keydown_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, this, true, keyCallback);
+ emscripten_set_keyup_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, this, true, keyCallback);
+
+ // Resize event
+ emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, this, true, resizeCallback);
+#endif
+ }
+
+#ifdef ES_PLATFORM_WEB
+ static EM_BOOL touchCallback(int eventType, const EmscriptenTouchEvent* event, void* userData) {
+ auto* platform = static_cast<WebPlatform*>(userData);
+ if (!platform->touchCallback_) return false;
+
+ TouchType type;
+ switch (eventType) {
+ case EMSCRIPTEN_EVENT_TOUCHSTART: type = TouchType::Begin; break;
+ case EMSCRIPTEN_EVENT_TOUCHMOVE: type = TouchType::Move; break;
+ case EMSCRIPTEN_EVENT_TOUCHEND: type = TouchType::End; break;
+ case EMSCRIPTEN_EVENT_TOUCHCANCEL: type = TouchType::Cancel; break;
+ default: return false;
+ }
+
+ for (int i = 0; i < event->numTouches; ++i) {
+ if (event->touches[i].isChanged) {
+ TouchPoint point;
+ point.id = event->touches[i].identifier;
+ point.x = static_cast<f32>(event->touches[i].targetX);
+ point.y = static_cast<f32>(event->touches[i].targetY);
+ platform->touchCallback_(type, point);
+ }
+ }
+
+ return true;
+ }
+
+ static EM_BOOL mouseCallback(int eventType, const EmscriptenMouseEvent* event, void* userData) {
+ auto* platform = static_cast<WebPlatform*>(userData);
+ if (!platform->touchCallback_) return false;
+
+ TouchType type;
+ switch (eventType) {
+ case EMSCRIPTEN_EVENT_MOUSEDOWN: type = TouchType::Begin; break;
+ case EMSCRIPTEN_EVENT_MOUSEMOVE:
+ if (!(event->buttons & 1)) return false; // Only when button pressed
+ type = TouchType::Move;
+ break;
+ case EMSCRIPTEN_EVENT_MOUSEUP: type = TouchType::End; break;
+ default: return false;
+ }
+
+ TouchPoint point;
+ point.id = 0;
+ point.x = static_cast<f32>(event->targetX);
+ point.y = static_cast<f32>(event->targetY);
+ platform->touchCallback_(type, point);
+
+ return true;
+ }
+
+ static EM_BOOL keyCallback(int eventType, const EmscriptenKeyboardEvent* event, void* userData) {
+ auto* platform = static_cast<WebPlatform*>(userData);
+ if (!platform->keyCallback_) return false;
+
+ bool pressed = (eventType == EMSCRIPTEN_EVENT_KEYDOWN);
+ KeyCode keyCode = static_cast<KeyCode>(event->keyCode);
+
+ platform->keyCallback_(keyCode, pressed);
+ return true;
+ }
+
+ static EM_BOOL resizeCallback(int eventType, const EmscriptenUiEvent* event, void* userData) {
+ (void)eventType;
+ auto* platform = static_cast<WebPlatform*>(userData);
+
+ f64 cssWidth, cssHeight;
+ emscripten_get_element_css_size("#canvas", &cssWidth, &cssHeight);
+
+ platform->width_ = static_cast<u32>(cssWidth * platform->devicePixelRatio_);
+ platform->height_ = static_cast<u32>(cssHeight * platform->devicePixelRatio_);
+
+ emscripten_set_canvas_element_size("#canvas", platform->width_, platform->height_);
+
+ if (platform->resizeCallback_) {
+ platform->resizeCallback_(platform->width_, platform->height_);
+ }
+
+ ES_LOG_DEBUG("Window resized to {}x{}", platform->width_, platform->height_);
+ return true;
+ }
+#endif
+
+ u32 width_ = 0;
+ u32 height_ = 0;
+ f32 devicePixelRatio_ = 1.0f;
+ f64 lastTime_ = 0.0;
+ f64 deltaTime_ = 0.0;
+ bool running_ = false;
+
+#ifdef ES_PLATFORM_WEB
+ EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context_ = 0;
+#endif
+
+ TouchCallback touchCallback_;
+ KeyCallback keyCallback_;
+ ResizeCallback resizeCallback_;
+};
+
+WebPlatform* WebPlatform::instance_ = nullptr;
+
+// Factory implementation
+Unique<Platform> Platform::create() {
+ return makeUnique<WebPlatform>();
+}
+
+} // namespace esengine
+
+// ========================================
+// C API for JavaScript interop
+// ========================================
+
+#ifdef ES_PLATFORM_WEB
+#include <emscripten/emscripten.h>
+
+extern "C" {
+
+static esengine::WebPlatform* g_platform = nullptr;
+
+EMSCRIPTEN_KEEPALIVE
+void es_init(int width, int height) {
+ esengine::Log::init();
+ g_platform = static_cast<esengine::WebPlatform*>(
+ esengine::Platform::create().release()
+ );
+ g_platform->initialize(width, height);
+ esengine::Renderer::init();
+}
+
+EMSCRIPTEN_KEEPALIVE
+void es_update(float deltaTime) {
+ if (g_platform) {
+ g_platform->pollEvents();
+ }
+ (void)deltaTime;
+}
+
+EMSCRIPTEN_KEEPALIVE
+void es_render() {
+ esengine::Renderer::beginFrame();
+ esengine::Renderer::clear();
+ // Application rendering would go here
+ esengine::Renderer::endFrame();
+}
+
+EMSCRIPTEN_KEEPALIVE
+void es_shutdown() {
+ esengine::Renderer::shutdown();
+ if (g_platform) {
+ g_platform->shutdown();
+ delete g_platform;
+ g_platform = nullptr;
+ }
+ esengine::Log::shutdown();
+}
+
+EMSCRIPTEN_KEEPALIVE
+void es_on_touch(int type, float x, float y) {
+ // Touch handling would be forwarded to the application
+ (void)type;
+ (void)x;
+ (void)y;
+}
+
+} // extern "C"
+#endif
diff --git a/src/esengine/renderer/Buffer.cpp b/src/esengine/renderer/Buffer.cpp
new file mode 100644
index 000000000..6daf7aa8d
--- /dev/null
+++ b/src/esengine/renderer/Buffer.cpp
@@ -0,0 +1,317 @@
+#include "Buffer.hpp"
+#include "../core/Log.hpp"
+
+#ifdef ES_PLATFORM_WEB
+ #include <GLES3/gl3.h>
+#else
+ #ifdef _WIN32
+ #include <windows.h>
+ #endif
+ #include <GL/gl.h>
+ #ifndef GL_ARRAY_BUFFER
+ #define GL_ARRAY_BUFFER 0x8892
+ #define GL_ELEMENT_ARRAY_BUFFER 0x8893
+ #define GL_STATIC_DRAW 0x88E4
+ #define GL_DYNAMIC_DRAW 0x88E8
+ #endif
+#endif
+
+namespace esengine {
+
+u32 shaderDataTypeSize(ShaderDataType type) {
+ switch (type) {
+ case ShaderDataType::Float: return 4;
+ case ShaderDataType::Float2: return 4 * 2;
+ case ShaderDataType::Float3: return 4 * 3;
+ case ShaderDataType::Float4: return 4 * 4;
+ case ShaderDataType::Int: return 4;
+ case ShaderDataType::Int2: return 4 * 2;
+ case ShaderDataType::Int3: return 4 * 3;
+ case ShaderDataType::Int4: return 4 * 4;
+ case ShaderDataType::Bool: return 1;
+ default: return 0;
+ }
+}
+
+u32 shaderDataTypeComponentCount(ShaderDataType type) {
+ switch (type) {
+ case ShaderDataType::Float: return 1;
+ case ShaderDataType::Float2: return 2;
+ case ShaderDataType::Float3: return 3;
+ case ShaderDataType::Float4: return 4;
+ case ShaderDataType::Int: return 1;
+ case ShaderDataType::Int2: return 2;
+ case ShaderDataType::Int3: return 3;
+ case ShaderDataType::Int4: return 4;
+ case ShaderDataType::Bool: return 1;
+ default: return 0;
+ }
+}
+
+// ========================================
+// VertexBuffer
+// ========================================
+
+VertexBuffer::~VertexBuffer() {
+#ifdef ES_PLATFORM_WEB
+ if (bufferId_ != 0) {
+ glDeleteBuffers(1, &bufferId_);
+ }
+#endif
+}
+
+VertexBuffer::VertexBuffer(VertexBuffer&& other) noexcept
+ : bufferId_(other.bufferId_), layout_(std::move(other.layout_)) {
+ other.bufferId_ = 0;
+}
+
+VertexBuffer& VertexBuffer::operator=(VertexBuffer&& other) noexcept {
+ if (this != &other) {
+#ifdef ES_PLATFORM_WEB
+ if (bufferId_ != 0) {
+ glDeleteBuffers(1, &bufferId_);
+ }
+#endif
+ bufferId_ = other.bufferId_;
+ layout_ = std::move(other.layout_);
+ other.bufferId_ = 0;
+ }
+ return *this;
+}
+
+Unique<VertexBuffer> VertexBuffer::create(const void* data, u32 size) {
+ auto buffer = makeUnique<VertexBuffer>();
+#ifdef ES_PLATFORM_WEB
+ glGenBuffers(1, &buffer->bufferId_);
+ glBindBuffer(GL_ARRAY_BUFFER, buffer->bufferId_);
+ glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);
+#else
+ (void)data;
+ (void)size;
+#endif
+ return buffer;
+}
+
+Unique<VertexBuffer> VertexBuffer::create(u32 size) {
+ auto buffer = makeUnique<VertexBuffer>();
+#ifdef ES_PLATFORM_WEB
+ glGenBuffers(1, &buffer->bufferId_);
+ glBindBuffer(GL_ARRAY_BUFFER, buffer->bufferId_);
+ glBufferData(GL_ARRAY_BUFFER, size, nullptr, GL_DYNAMIC_DRAW);
+#else
+ (void)size;
+#endif
+ return buffer;
+}
+
+void VertexBuffer::bind() const {
+#ifdef ES_PLATFORM_WEB
+ glBindBuffer(GL_ARRAY_BUFFER, bufferId_);
+#endif
+}
+
+void VertexBuffer::unbind() const {
+#ifdef ES_PLATFORM_WEB
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+#endif
+}
+
+void VertexBuffer::setData(const void* data, u32 size) {
+#ifdef ES_PLATFORM_WEB
+ glBindBuffer(GL_ARRAY_BUFFER, bufferId_);
+ glBufferSubData(GL_ARRAY_BUFFER, 0, size, data);
+#else
+ (void)data;
+ (void)size;
+#endif
+}
+
+// ========================================
+// IndexBuffer
+// ========================================
+
+IndexBuffer::~IndexBuffer() {
+#ifdef ES_PLATFORM_WEB
+ if (bufferId_ != 0) {
+ glDeleteBuffers(1, &bufferId_);
+ }
+#endif
+}
+
+IndexBuffer::IndexBuffer(IndexBuffer&& other) noexcept
+ : bufferId_(other.bufferId_), count_(other.count_), is16Bit_(other.is16Bit_) {
+ other.bufferId_ = 0;
+ other.count_ = 0;
+}
+
+IndexBuffer& IndexBuffer::operator=(IndexBuffer&& other) noexcept {
+ if (this != &other) {
+#ifdef ES_PLATFORM_WEB
+ if (bufferId_ != 0) {
+ glDeleteBuffers(1, &bufferId_);
+ }
+#endif
+ bufferId_ = other.bufferId_;
+ count_ = other.count_;
+ is16Bit_ = other.is16Bit_;
+ other.bufferId_ = 0;
+ other.count_ = 0;
+ }
+ return *this;
+}
+
+Unique<IndexBuffer> IndexBuffer::create(const u32* indices, u32 count) {
+ auto buffer = makeUnique<IndexBuffer>();
+ buffer->count_ = count;
+ buffer->is16Bit_ = false;
+#ifdef ES_PLATFORM_WEB
+ glGenBuffers(1, &buffer->bufferId_);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer->bufferId_);
+ glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * sizeof(u32), indices, GL_STATIC_DRAW);
+#else
+ (void)indices;
+#endif
+ return buffer;
+}
+
+Unique<IndexBuffer> IndexBuffer::create(const u16* indices, u32 count) {
+ auto buffer = makeUnique<IndexBuffer>();
+ buffer->count_ = count;
+ buffer->is16Bit_ = true;
+#ifdef ES_PLATFORM_WEB
+ glGenBuffers(1, &buffer->bufferId_);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer->bufferId_);
+ glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * sizeof(u16), indices, GL_STATIC_DRAW);
+#else
+ (void)indices;
+#endif
+ return buffer;
+}
+
+void IndexBuffer::bind() const {
+#ifdef ES_PLATFORM_WEB
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferId_);
+#endif
+}
+
+void IndexBuffer::unbind() const {
+#ifdef ES_PLATFORM_WEB
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
+#endif
+}
+
+// ========================================
+// VertexArray
+// ========================================
+
+VertexArray::VertexArray() {
+#ifdef ES_PLATFORM_WEB
+ glGenVertexArrays(1, &arrayId_);
+#endif
+}
+
+VertexArray::~VertexArray() {
+#ifdef ES_PLATFORM_WEB
+ if (arrayId_ != 0) {
+ glDeleteVertexArrays(1, &arrayId_);
+ }
+#endif
+}
+
+VertexArray::VertexArray(VertexArray&& other) noexcept
+ : arrayId_(other.arrayId_)
+ , vertexAttribIndex_(other.vertexAttribIndex_)
+ , vertexBuffers_(std::move(other.vertexBuffers_))
+ , indexBuffer_(std::move(other.indexBuffer_)) {
+ other.arrayId_ = 0;
+ other.vertexAttribIndex_ = 0;
+}
+
+VertexArray& VertexArray::operator=(VertexArray&& other) noexcept {
+ if (this != &other) {
+#ifdef ES_PLATFORM_WEB
+ if (arrayId_ != 0) {
+ glDeleteVertexArrays(1, &arrayId_);
+ }
+#endif
+ arrayId_ = other.arrayId_;
+ vertexAttribIndex_ = other.vertexAttribIndex_;
+ vertexBuffers_ = std::move(other.vertexBuffers_);
+ indexBuffer_ = std::move(other.indexBuffer_);
+ other.arrayId_ = 0;
+ other.vertexAttribIndex_ = 0;
+ }
+ return *this;
+}
+
+Unique<VertexArray> VertexArray::create() {
+ return makeUnique<VertexArray>();
+}
+
+void VertexArray::bind() const {
+#ifdef ES_PLATFORM_WEB
+ glBindVertexArray(arrayId_);
+#endif
+}
+
+void VertexArray::unbind() const {
+#ifdef ES_PLATFORM_WEB
+ glBindVertexArray(0);
+#endif
+}
+
+void VertexArray::addVertexBuffer(Shared<VertexBuffer> buffer) {
+#ifdef ES_PLATFORM_WEB
+ ES_ASSERT(!buffer->getLayout().getAttributes().empty(), "Vertex buffer has no layout");
+
+ bind();
+ buffer->bind();
+
+ const auto& layout = buffer->getLayout();
+ for (const auto& attr : layout) {
+ glEnableVertexAttribArray(vertexAttribIndex_);
+
+ GLenum glType = GL_FLOAT;
+ switch (attr.type) {
+ case ShaderDataType::Float:
+ case ShaderDataType::Float2:
+ case ShaderDataType::Float3:
+ case ShaderDataType::Float4:
+ glType = GL_FLOAT;
+ break;
+ case ShaderDataType::Int:
+ case ShaderDataType::Int2:
+ case ShaderDataType::Int3:
+ case ShaderDataType::Int4:
+ glType = GL_INT;
+ break;
+ case ShaderDataType::Bool:
+ glType = GL_BOOL;
+ break;
+ default:
+ break;
+ }
+
+ glVertexAttribPointer(
+ vertexAttribIndex_,
+ shaderDataTypeComponentCount(attr.type),
+ glType,
+ attr.normalized ? GL_TRUE : GL_FALSE,
+ layout.getStride(),
+ reinterpret_cast<const void*>(static_cast<uintptr_t>(attr.offset))
+ );
+ ++vertexAttribIndex_;
+ }
+#endif
+ vertexBuffers_.push_back(std::move(buffer));
+}
+
+void VertexArray::setIndexBuffer(Shared<IndexBuffer> buffer) {
+#ifdef ES_PLATFORM_WEB
+ bind();
+ buffer->bind();
+#endif
+ indexBuffer_ = std::move(buffer);
+}
+
+} // namespace esengine
diff --git a/src/esengine/renderer/Buffer.hpp b/src/esengine/renderer/Buffer.hpp
new file mode 100644
index 000000000..a9a94cfaa
--- /dev/null
+++ b/src/esengine/renderer/Buffer.hpp
@@ -0,0 +1,158 @@
+#pragma once
+
+#include "../core/Types.hpp"
+#include <vector>
+
+namespace esengine {
+
+// Vertex attribute types
+enum class ShaderDataType {
+ None = 0,
+ Float, Float2, Float3, Float4,
+ Int, Int2, Int3, Int4,
+ Bool
+};
+
+u32 shaderDataTypeSize(ShaderDataType type);
+u32 shaderDataTypeComponentCount(ShaderDataType type);
+
+// Single vertex attribute
+struct VertexAttribute {
+ std::string name;
+ ShaderDataType type;
+ u32 size;
+ u32 offset;
+ bool normalized;
+
+ VertexAttribute() = default;
+ VertexAttribute(ShaderDataType type, const std::string& name, bool normalized = false)
+ : name(name), type(type), size(shaderDataTypeSize(type)), offset(0), normalized(normalized) {}
+};
+
+// Vertex buffer layout
+class VertexLayout {
+public:
+ VertexLayout() = default;
+ VertexLayout(std::initializer_list<VertexAttribute> attributes)
+ : attributes_(attributes) {
+ calculateOffsetsAndStride();
+ }
+
+ const std::vector<VertexAttribute>& getAttributes() const { return attributes_; }
+ u32 getStride() const { return stride_; }
+
+ std::vector<VertexAttribute>::iterator begin() { return attributes_.begin(); }
+ std::vector<VertexAttribute>::iterator end() { return attributes_.end(); }
+ std::vector<VertexAttribute>::const_iterator begin() const { return attributes_.begin(); }
+ std::vector<VertexAttribute>::const_iterator end() const { return attributes_.end(); }
+
+private:
+ void calculateOffsetsAndStride() {
+ u32 offset = 0;
+ stride_ = 0;
+ for (auto& attr : attributes_) {
+ attr.offset = offset;
+ offset += attr.size;
+ stride_ += attr.size;
+ }
+ }
+
+ std::vector<VertexAttribute> attributes_;
+ u32 stride_ = 0;
+};
+
+// Vertex Buffer (VBO)
+class VertexBuffer {
+public:
+ VertexBuffer() = default;
+ ~VertexBuffer();
+
+ // Non-copyable, movable
+ VertexBuffer(const VertexBuffer&) = delete;
+ VertexBuffer& operator=(const VertexBuffer&) = delete;
+ VertexBuffer(VertexBuffer&& other) noexcept;
+ VertexBuffer& operator=(VertexBuffer&& other) noexcept;
+
+ // Create static buffer
+ static Unique<VertexBuffer> create(const void* data, u32 size);
+
+ // Create dynamic buffer
+ static Unique<VertexBuffer> create(u32 size);
+
+ void bind() const;
+ void unbind() const;
+
+ // Update data (for dynamic buffers)
+ void setData(const void* data, u32 size);
+
+ // Layout
+ void setLayout(const VertexLayout& layout) { layout_ = layout; }
+ const VertexLayout& getLayout() const { return layout_; }
+
+ u32 getId() const { return bufferId_; }
+
+private:
+ u32 bufferId_ = 0;
+ VertexLayout layout_;
+};
+
+// Index Buffer (EBO)
+class IndexBuffer {
+public:
+ IndexBuffer() = default;
+ ~IndexBuffer();
+
+ // Non-copyable, movable
+ IndexBuffer(const IndexBuffer&) = delete;
+ IndexBuffer& operator=(const IndexBuffer&) = delete;
+ IndexBuffer(IndexBuffer&& other) noexcept;
+ IndexBuffer& operator=(IndexBuffer&& other) noexcept;
+
+ // Create from indices
+ static Unique<IndexBuffer> create(const u32* indices, u32 count);
+ static Unique<IndexBuffer> create(const u16* indices, u32 count);
+
+ void bind() const;
+ void unbind() const;
+
+ u32 getCount() const { return count_; }
+ u32 getId() const { return bufferId_; }
+ bool is16Bit() const { return is16Bit_; }
+
+private:
+ u32 bufferId_ = 0;
+ u32 count_ = 0;
+ bool is16Bit_ = false;
+};
+
+// Vertex Array Object (VAO) - abstracts vertex attribute configuration
+class VertexArray {
+public:
+ VertexArray();
+ ~VertexArray();
+
+ // Non-copyable, movable
+ VertexArray(const VertexArray&) = delete;
+ VertexArray& operator=(const VertexArray&) = delete;
+ VertexArray(VertexArray&& other) noexcept;
+ VertexArray& operator=(VertexArray&& other) noexcept;
+
+ static Unique<VertexArray> create();
+
+ void bind() const;
+ void unbind() const;
+
+ void addVertexBuffer(Shared<VertexBuffer> buffer);
+ void setIndexBuffer(Shared<IndexBuffer> buffer);
+
+ const std::vector<Shared<VertexBuffer>>& getVertexBuffers() const { return vertexBuffers_; }
+ const Shared<IndexBuffer>& getIndexBuffer() const { return indexBuffer_; }
+
+private:
+ u32 arrayId_ = 0;
+ u32 vertexAttribIndex_ = 0;
+ std::vector<Shared<VertexBuffer>> vertexBuffers_;
+ Shared<IndexBuffer> indexBuffer_;
+};
+
+} // namespace esengine
diff --git a/src/esengine/renderer/RenderCommand.hpp b/src/esengine/renderer/RenderCommand.hpp
new file mode 100644
index 000000000..fb11710c3
--- /dev/null
+++ b/src/esengine/renderer/RenderCommand.hpp
@@ -0,0 +1,39 @@
+#pragma once
+
+#include "../core/Types.hpp"
+#include "../math/Math.hpp"
+
+namespace esengine {
+
+class VertexArray;
+
+// Static class for low-level rendering commands
+class RenderCommand {
+public:
+ static void init();
+ static void shutdown();
+
+ static void setViewport(i32 x, i32 y, u32 width, u32 height);
+ static void setClearColor(const glm::vec4& color);
+ static void clear();
+
+ static void drawIndexed(const VertexArray& vao, u32 indexCount = 0);
+ static void drawArrays(u32 vertexCount);
+
+ // Depth testing
+ static void setDepthTest(bool enabled);
+ static void setDepthWrite(bool enabled);
+
+ // Blending
+ static void setBlending(bool enabled);
+ static void setBlendFunc(); // Default: SrcAlpha, OneMinusSrcAlpha
+
+ // Face culling
+ static void setCulling(bool enabled);
+ static void setCullFace(bool front); // true = cull front, false = cull back
+
+ // Wireframe mode
+ static void setWireframe(bool enabled);
+};
+
+} // namespace esengine
diff --git a/src/esengine/renderer/Renderer.cpp b/src/esengine/renderer/Renderer.cpp
new file mode 100644
index 000000000..b6cd8dda5
--- /dev/null
+++ b/src/esengine/renderer/Renderer.cpp
@@ -0,0 +1,377 @@
+#include "Renderer.hpp"
+#include "RenderCommand.hpp"
+#include "../core/Log.hpp"
+
+#ifdef ES_PLATFORM_WEB
+ #include <GLES3/gl3.h>
+#else
+ #ifdef _WIN32
+ #include <windows.h>
+ #endif
+ #include <GL/gl.h>
+ #ifndef GL_TRIANGLES
+ #define GL_TRIANGLES 0x0004
+ #define GL_UNSIGNED_INT 0x1405
+ #define GL_UNSIGNED_SHORT 0x1403
+ #define GL_COLOR_BUFFER_BIT 0x00004000
+ #define GL_DEPTH_BUFFER_BIT 0x00000100
+ #define GL_DEPTH_TEST 0x0B71
+ #define GL_BLEND 0x0BE2
+ #define GL_SRC_ALPHA 0x0302
+ #define GL_ONE_MINUS_SRC_ALPHA 0x0303
+ #define GL_CULL_FACE 0x0B44
+ #define GL_BACK 0x0405
+ #define GL_FRONT 0x0404
+ #endif
+#endif
+
+namespace esengine {
+
+// ========================================
+// RenderCommand Implementation
+// ========================================
+
+void RenderCommand::init() {
+#ifdef ES_PLATFORM_WEB
+ ES_LOG_INFO("RenderCommand initialized (WebGL)");
+
+ // Enable depth testing by default
+ glEnable(GL_DEPTH_TEST);
+
+ // Enable blending
+ glEnable(GL_BLEND);
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+#endif
+}
+
+void RenderCommand::shutdown() {
+ ES_LOG_INFO("RenderCommand shutdown");
+}
+
+void RenderCommand::setViewport(i32 x, i32 y, u32 width, u32 height) {
+#ifdef ES_PLATFORM_WEB
+ glViewport(x, y, width, height);
+#else
+ (void)x; (void)y; (void)width; (void)height;
+#endif
+}
+
+void RenderCommand::setClearColor(const glm::vec4& color) {
+#ifdef ES_PLATFORM_WEB
+ glClearColor(color.r, color.g, color.b, color.a);
+#else
+ (void)color;
+#endif
+}
+
+void RenderCommand::clear() {
+#ifdef ES_PLATFORM_WEB
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+#endif
+}
+
+void RenderCommand::drawIndexed(const VertexArray& vao, u32 indexCount) {
+#ifdef ES_PLATFORM_WEB
+ vao.bind();
+ auto ib = vao.getIndexBuffer();
+ u32 count = indexCount ? indexCount : (ib ? ib->getCount() : 0);
+ if (count > 0 && ib) {
+ GLenum type = ib->is16Bit() ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
+ glDrawElements(GL_TRIANGLES, count, type, nullptr);
+ }
+#else
+ (void)vao; (void)indexCount;
+#endif
+}
+
+void RenderCommand::drawArrays(u32 vertexCount) {
+#ifdef ES_PLATFORM_WEB
+ glDrawArrays(GL_TRIANGLES, 0, vertexCount);
+#else
+ (void)vertexCount;
+#endif
+}
+
+void RenderCommand::setDepthTest(bool enabled) {
+#ifdef ES_PLATFORM_WEB
+ if (enabled) {
+ glEnable(GL_DEPTH_TEST);
+ } else {
+ glDisable(GL_DEPTH_TEST);
+ }
+#else
+ (void)enabled;
+#endif
+}
+
+void RenderCommand::setDepthWrite(bool enabled) {
+#ifdef ES_PLATFORM_WEB
+ glDepthMask(enabled ? GL_TRUE : GL_FALSE);
+#else
+ (void)enabled;
+#endif
+}
+
+void RenderCommand::setBlending(bool enabled) {
+#ifdef ES_PLATFORM_WEB
+ if (enabled) {
+ glEnable(GL_BLEND);
+ } else {
+ glDisable(GL_BLEND);
+ }
+#else
+ (void)enabled;
+#endif
+}
+
+void RenderCommand::setBlendFunc() {
+#ifdef ES_PLATFORM_WEB
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+#endif
+}
+
+void RenderCommand::setCulling(bool enabled) {
+#ifdef ES_PLATFORM_WEB
+ if (enabled) {
+ glEnable(GL_CULL_FACE);
+ } else {
+ glDisable(GL_CULL_FACE);
+ }
+#else
+ (void)enabled;
+#endif
+}
+
+void RenderCommand::setCullFace(bool front) {
+#ifdef ES_PLATFORM_WEB
+ glCullFace(front ? GL_FRONT : GL_BACK);
+#else
+ (void)front;
+#endif
+}
+
+void RenderCommand::setWireframe(bool enabled) {
+ (void)enabled;
+ // WebGL doesn't support wireframe mode directly
+ // Would need to render with GL_LINES instead
+}
+
+// ========================================
+// Renderer Implementation
+// ========================================
+
+namespace {
+ struct RendererData {
+ glm::mat4 viewProjection{1.0f};
+ RendererStats stats;
+
+ // Quad rendering data
+ Unique<VertexArray> quadVAO;
+ Unique<Shader> colorShader;
+ bool initialized = false;
+ };
+
+ RendererData* s_data = nullptr;
+} // namespace
+
+void Renderer::init() {
+ s_data = new RendererData();
+
+ RenderCommand::init();
+ initQuadData();
+
+ s_data->initialized = true;
+ ES_LOG_INFO("Renderer initialized");
+}
+
+void Renderer::shutdown() {
+ if (s_data) {
+ s_data->quadVAO.reset();
+ s_data->colorShader.reset();
+ delete s_data;
+ s_data = nullptr;
+ }
+
+ RenderCommand::shutdown();
+ ES_LOG_INFO("Renderer shutdown");
+}
+
+void Renderer::initQuadData() {
+#ifdef ES_PLATFORM_WEB
+ // Simple quad vertices (position only for now)
+ float vertices[] = {
+ // Position (x, y)
+ -0.5f, -0.5f,
+ 0.5f, -0.5f,
+ 0.5f, 0.5f,
+ -0.5f, 0.5f
+ };
+
+ u32 indices[] = { 0, 1, 2, 2, 3, 0 };
+
+ s_data->quadVAO = VertexArray::create();
+
+ auto vbo = VertexBuffer::create(vertices, sizeof(vertices));
+ vbo->setLayout({
+ { ShaderDataType::Float2, "a_position" }
+ });
+
+ auto ibo = IndexBuffer::create(indices, 6);
+
+ s_data->quadVAO->addVertexBuffer(Shared<VertexBuffer>(std::move(vbo)));
+ s_data->quadVAO->setIndexBuffer(Shared<IndexBuffer>(std::move(ibo)));
+
+ // Create simple color shader
+ s_data->colorShader = Shader::create(
+ ShaderSources::COLOR_VERTEX,
+ ShaderSources::COLOR_FRAGMENT
+ );
+#endif
+}
+
+void Renderer::beginFrame() {
+ s_data->stats.reset();
+}
+
+void Renderer::endFrame() {
+ // Nothing to do for now
+}
+
+void Renderer::setViewport(i32 x, i32 y, u32 width, u32 height) {
+ RenderCommand::setViewport(x, y, width, height);
+}
+
+void Renderer::setClearColor(const glm::vec4& color) {
+ RenderCommand::setClearColor(color);
+}
+
+void Renderer::clear() {
+ RenderCommand::clear();
+}
+
+void Renderer::beginScene(const glm::mat4& viewProjection) {
+ s_data->viewProjection = viewProjection;
+}
+
+void Renderer::endScene() {
+ // Nothing to do for now
+}
+
+void Renderer::submit(const Shader& shader, const VertexArray& vao, const glm::mat4& transform) {
+ shader.bind();
+ const_cast<Shader&>(shader).setUniform("u_projection", s_data->viewProjection);
+ const_cast<Shader&>(shader).setUniform("u_model", transform);
+
+ RenderCommand::drawIndexed(vao);
+
+ s_data->stats.drawCalls++;
+}
+
+void Renderer::drawQuad(const glm::vec2& position, const glm::vec2& size, const glm::vec4& color) {
+ drawQuad(glm::vec3(position, 0.0f), size, color);
+}
+
+void Renderer::drawQuad(const glm::vec3& position, const glm::vec2& size, const glm::vec4& color) {
+ if (!s_data->colorShader || !s_data->quadVAO) return;
+
+ glm::mat4 transform = glm::translate(glm::mat4(1.0f), position);
+ transform = glm::scale(transform, glm::vec3(size, 1.0f));
+
+ s_data->colorShader->bind();
+ s_data->colorShader->setUniform("u_projection", s_data->viewProjection);
+ s_data->colorShader->setUniform("u_model", transform);
+ s_data->colorShader->setUniform("u_color", color);
+
+ RenderCommand::drawIndexed(*s_data->quadVAO);
+
+ s_data->stats.drawCalls++;
+ s_data->stats.triangleCount += 2;
+}
+
+void Renderer::drawQuad(const glm::vec2& position, const glm::vec2& size,
+ const Texture& texture, const glm::vec4& tintColor) {
+ drawQuad(glm::vec3(position, 0.0f), size, texture, tintColor);
+}
+
+void Renderer::drawQuad(const glm::vec3& position, const glm::vec2& size,
+ const Texture& texture, const glm::vec4& tintColor) {
+ // TODO: Implement textured quad rendering
+ (void)texture;
+ (void)tintColor;
+ drawQuad(position, size, glm::vec4(1.0f, 0.0f, 1.0f, 1.0f)); // Placeholder: magenta
+}
+
+RendererStats Renderer::getStats() {
+ return s_data->stats;
+}
+
+void Renderer::resetStats() {
+ s_data->stats.reset();
+}
+
+// ========================================
+// BatchRenderer2D Implementation (Stub)
+// ========================================
+
+void BatchRenderer2D::init() {
+ ES_LOG_INFO("BatchRenderer2D initialized");
+}
+
+void BatchRenderer2D::shutdown() {
+ ES_LOG_INFO("BatchRenderer2D shutdown");
+}
+
+void BatchRenderer2D::beginBatch() {
+ // TODO: Implement batch rendering
+}
+
+void BatchRenderer2D::endBatch() {
+ flush();
+}
+
+void BatchRenderer2D::flush() {
+ // TODO: Implement batch flush
+}
+
+void BatchRenderer2D::drawQuad(const glm::vec2& position, const glm::vec2& size,
+ u32 textureId, const glm::vec4& color) {
+ drawQuad(glm::vec3(position, 0.0f), size, textureId, color);
+}
+
+void BatchRenderer2D::drawQuad(const glm::vec3& position, const glm::vec2& size,
+ u32 textureId, const glm::vec4& color) {
+ (void)position; (void)size; (void)textureId; (void)color;
+ // TODO: Implement
+}
+
+void BatchRenderer2D::drawQuad(const glm::vec2& position, const glm::vec2& size,
+ const glm::vec4& color) {
+ drawQuad(position, size, 0, color);
+}
+
+void BatchRenderer2D::drawRotatedQuad(const glm::vec2& position, const glm::vec2& size,
+ f32 rotation, const glm::vec4& color) {
+ (void)position; (void)size; (void)rotation; (void)color;
+ // TODO: Implement
+}
+
+void BatchRenderer2D::drawRotatedQuad(const glm::vec2& position, const glm::vec2& size,
+ f32 rotation, u32 textureId, const glm::vec4& tintColor) {
+ (void)position; (void)size; (void)rotation; (void)textureId; (void)tintColor;
+ // TODO: Implement
+}
+
+void BatchRenderer2D::setProjection(const glm::mat4& projection) {
+ (void)projection;
+ // TODO: Implement
+}
+
+u32 BatchRenderer2D::getDrawCallCount() {
+ return 0; // TODO: Implement
+}
+
+u32 BatchRenderer2D::getQuadCount() {
+ return 0; // TODO: Implement
+}
+
+} // namespace esengine
diff --git a/src/esengine/renderer/Renderer.hpp b/src/esengine/renderer/Renderer.hpp
new file mode 100644
index 000000000..23b1a37d4
--- /dev/null
+++ b/src/esengine/renderer/Renderer.hpp
@@ -0,0 +1,106 @@
+#pragma once
+
+#include "../core/Types.hpp"
+#include "../math/Math.hpp"
+#include "Buffer.hpp"
+#include "Shader.hpp"
+#include "Texture.hpp"
+
+namespace esengine {
+
+// Renderer statistics
+struct RendererStats {
+ u32 drawCalls = 0;
+ u32 triangleCount = 0;
+ u32 vertexCount = 0;
+
+ void reset() {
+ drawCalls = 0;
+ triangleCount = 0;
+ vertexCount = 0;
+ }
+};
+
+// Static renderer class
+class Renderer {
+public:
+ static void init();
+ static void shutdown();
+
+ static void beginFrame();
+ static void endFrame();
+
+ // Set viewport and clear color
+ static void setViewport(i32 x, i32 y, u32 width, u32 height);
+ static void setClearColor(const glm::vec4& color);
+ static void clear();
+
+ // Camera / Projection
+ static void beginScene(const glm::mat4& viewProjection);
+ static void endScene();
+
+ // Submit draw calls
+ static void submit(const Shader& shader,
+ const VertexArray& vao,
+ const glm::mat4& transform = glm::mat4(1.0f));
+
+ // 2D Rendering helpers
+ static void drawQuad(const glm::vec2& position, const glm::vec2& size,
+ const glm::vec4& color);
+
+ static void drawQuad(const glm::vec2& position, const glm::vec2& size,
+ const Texture& texture, const glm::vec4& tintColor = glm::vec4(1.0f));
+
+ static void drawQuad(const glm::vec3& position, const glm::vec2& size,
+ const glm::vec4& color);
+
+ static void drawQuad(const glm::vec3& position, const glm::vec2& size,
+ const Texture& texture, const glm::vec4& tintColor = glm::vec4(1.0f));
+
+ // Statistics
+ static RendererStats getStats();
+ static void resetStats();
+
+private:
+ static void initQuadData();
+ static void flushBatch();
+};
+
+// 2D Batch Renderer for efficient sprite rendering
+class BatchRenderer2D {
+public:
+ static void init();
+ static void shutdown();
+
+ static void beginBatch();
+ static void endBatch();
+ static void flush();
+
+ // Draw textured quad
+ static void drawQuad(const glm::vec2& position, const glm::vec2& size,
+ u32 textureId, const glm::vec4& color = glm::vec4(1.0f));
+
+ static void drawQuad(const glm::vec3& position, const glm::vec2& size,
+ u32 textureId, const glm::vec4& color = glm::vec4(1.0f));
+
+ // Draw colored quad (no texture)
+ static void drawQuad(const glm::vec2& position, const glm::vec2& size,
+ const glm::vec4& color);
+
+ // Draw rotated quad
+ static void drawRotatedQuad(const glm::vec2& position, const glm::vec2& size,
+ f32 rotation, const glm::vec4& color);
+
+ static void drawRotatedQuad(const glm::vec2& position, const glm::vec2& size,
+ f32 rotation, u32 textureId,
+ const glm::vec4& tintColor = glm::vec4(1.0f));
+
+ // Set projection matrix
+ static void setProjection(const glm::mat4& projection);
+
+ // Statistics
+ static u32 getDrawCallCount();
+ static u32 getQuadCount();
+};
+
+} // namespace esengine
diff --git a/src/esengine/renderer/Shader.cpp b/src/esengine/renderer/Shader.cpp
new file mode 100644
index 000000000..56cbfaf0a
--- /dev/null
+++ b/src/esengine/renderer/Shader.cpp
@@ -0,0 +1,237 @@
+#include "Shader.hpp"
+#include "../core/Log.hpp"
+
+#ifdef ES_PLATFORM_WEB
+ #include <GLES3/gl3.h>
+#else
+ // For native debugging, we'll use a minimal OpenGL header
+ // In production, you'd include GLAD or similar
+ #ifdef _WIN32
+ #include <windows.h>
+ #endif
+ #include <GL/gl.h>
+ // Define missing GL functions for native build (stub)
+ #ifndef GL_VERTEX_SHADER
+ #define GL_VERTEX_SHADER 0x8B31
+ #define GL_FRAGMENT_SHADER 0x8B30
+ #define GL_COMPILE_STATUS 0x8B81
+ #define GL_LINK_STATUS 0x8B82
+ #define GL_INFO_LOG_LENGTH 0x8B84
+ #endif
+#endif
+
+namespace esengine {
+
+Shader::~Shader() {
+ if (programId_ != 0) {
+#ifdef ES_PLATFORM_WEB
+ glDeleteProgram(programId_);
+#endif
+ programId_ = 0;
+ }
+}
+
+Shader::Shader(Shader&& other) noexcept
+ : programId_(other.programId_), uniformCache_(std::move(other.uniformCache_)) {
+ other.programId_ = 0;
+}
+
+Shader& Shader::operator=(Shader&& other) noexcept {
+ if (this != &other) {
+ if (programId_ != 0) {
+#ifdef ES_PLATFORM_WEB
+ glDeleteProgram(programId_);
+#endif
+ }
+ programId_ = other.programId_;
+ uniformCache_ = std::move(other.uniformCache_);
+ other.programId_ = 0;
+ }
+ return *this;
+}
+
+Unique<Shader> Shader::create(const std::string& vertexSrc, const std::string& fragmentSrc) {
+ auto shader = makeUnique<Shader>();
+ if (!shader->compile(vertexSrc, fragmentSrc)) {
+ return nullptr;
+ }
+ return shader;
+}
+
+Unique<Shader> Shader::createFromFile(const std::string& vertexPath, const std::string& fragmentPath) {
+ // TODO: Implement file loading
+ ES_LOG_ERROR("Shader::createFromFile not implemented yet");
+ (void)vertexPath;
+ (void)fragmentPath;
+ return nullptr;
+}
+
+void Shader::bind() const {
+#ifdef ES_PLATFORM_WEB
+ glUseProgram(programId_);
+#endif
+}
+
+void Shader::unbind() const {
+#ifdef ES_PLATFORM_WEB
+ glUseProgram(0);
+#endif
+}
+
+bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSrc) {
+#ifdef ES_PLATFORM_WEB
+ // Create vertex shader
+ GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
+ const char* vertexSrcPtr = vertexSrc.c_str();
+ glShaderSource(vertexShader, 1, &vertexSrcPtr, nullptr);
+ glCompileShader(vertexShader);
+
+ // Check vertex shader compilation
+ GLint success;
+ glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
+ if (!success) {
+ GLint logLength;
+ glGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &logLength);
+ std::string log(logLength, '\0');
+ glGetShaderInfoLog(vertexShader, logLength, nullptr, log.data());
+ ES_LOG_ERROR("Vertex shader compilation failed: {}", log);
+ glDeleteShader(vertexShader);
+ return false;
+ }
+
+ // Create fragment shader
+ GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
+ const char* fragmentSrcPtr = fragmentSrc.c_str();
+ glShaderSource(fragmentShader, 1, &fragmentSrcPtr, nullptr);
+ glCompileShader(fragmentShader);
+
+ // Check fragment shader compilation
+ glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
+ if (!success) {
+ GLint logLength;
+ glGetShaderiv(fragmentShader, GL_INFO_LOG_LENGTH, &logLength);
+ std::string log(logLength, '\0');
+ glGetShaderInfoLog(fragmentShader, logLength, nullptr, log.data());
+ ES_LOG_ERROR("Fragment shader compilation failed: {}", log);
+ glDeleteShader(vertexShader);
+ glDeleteShader(fragmentShader);
+ return false;
+ }
+
+ // Create program and link
+ programId_ = glCreateProgram();
+ glAttachShader(programId_, vertexShader);
+ glAttachShader(programId_, fragmentShader);
+ glLinkProgram(programId_);
+
+ // Check linking
+ glGetProgramiv(programId_, GL_LINK_STATUS, &success);
+ if (!success) {
+ GLint logLength;
+ glGetProgramiv(programId_, GL_INFO_LOG_LENGTH, &logLength);
+ std::string log(logLength, '\0');
+ glGetProgramInfoLog(programId_, logLength, nullptr, log.data());
+ ES_LOG_ERROR("Shader program linking failed: {}", log);
+ glDeleteShader(vertexShader);
+ glDeleteShader(fragmentShader);
+ glDeleteProgram(programId_);
+ programId_ = 0;
+ return false;
+ }
+
+ // Clean up shaders (they're now part of the program)
+ glDeleteShader(vertexShader);
+ glDeleteShader(fragmentShader);
+
+ ES_LOG_DEBUG("Shader compiled successfully (program ID: {})", programId_);
+ return true;
+#else
+ (void)vertexSrc;
+ (void)fragmentSrc;
+ ES_LOG_WARN("Shader compilation not available in native mode");
+ return false;
+#endif
+}
+
+i32 Shader::getUniformLocation(const std::string& name) {
+ auto it = uniformCache_.find(name);
+ if (it != uniformCache_.end()) {
+ return it->second;
+ }
+
+#ifdef ES_PLATFORM_WEB
+ i32 location = glGetUniformLocation(programId_, name.c_str());
+ uniformCache_[name] = location;
+ if (location == -1) {
+ ES_LOG_WARN("Uniform '{}' not found in shader", name);
+ }
+ return location;
+#else
+ return -1;
+#endif
+}
+
+void Shader::setUniform(const std::string& name, i32 value) {
+#ifdef ES_PLATFORM_WEB
+ glUniform1i(getUniformLocation(name), value);
+#else
+ (void)name;
+ (void)value;
+#endif
+}
+
+void Shader::setUniform(const std::string& name, f32 value) {
+#ifdef ES_PLATFORM_WEB
+ glUniform1f(getUniformLocation(name), value);
+#else
+ (void)name;
+ (void)value;
+#endif
+}
+
+void Shader::setUniform(const std::string& name, const glm::vec2& value) {
+#ifdef ES_PLATFORM_WEB
+ glUniform2f(getUniformLocation(name), value.x, value.y);
+#else
+ (void)name;
+ (void)value;
+#endif
+}
+
+void Shader::setUniform(const std::string& name, const glm::vec3& value) {
+#ifdef ES_PLATFORM_WEB
+ glUniform3f(getUniformLocation(name), value.x, value.y, value.z);
+#else
+ (void)name;
+ (void)value;
+#endif
+}
+
+void Shader::setUniform(const std::string& name, const glm::vec4& value) {
+#ifdef ES_PLATFORM_WEB
+ glUniform4f(getUniformLocation(name), value.x, value.y, value.z, value.w);
+#else
+ (void)name;
+ (void)value;
+#endif
+}
+
+void Shader::setUniform(const std::string& name, const glm::mat3& value) {
+#ifdef ES_PLATFORM_WEB
+ glUniformMatrix3fv(getUniformLocation(name), 1, GL_FALSE, glm::value_ptr(value));
+#else
+ (void)name;
+ (void)value;
+#endif
+}
+
+void Shader::setUniform(const std::string& name, const glm::mat4& value) {
+#ifdef ES_PLATFORM_WEB
+ glUniformMatrix4fv(getUniformLocation(name), 1, GL_FALSE, glm::value_ptr(value));
+#else
+ (void)name;
+ (void)value;
+#endif
+}
+
+} // namespace esengine
diff --git a/src/esengine/renderer/Shader.hpp b/src/esengine/renderer/Shader.hpp
new file mode 100644
index 000000000..4cd9d7b96
--- /dev/null
+++ b/src/esengine/renderer/Shader.hpp
@@ -0,0 +1,113 @@
+#pragma once
+
+#include "../core/Types.hpp"
+#include "../math/Math.hpp"
+#include <string>
+#include <unordered_map>
+
+namespace esengine {
+
+class Shader {
+public:
+ Shader() = default;
+ ~Shader();
+
+ // Non-copyable
+ Shader(const Shader&) = delete;
+ Shader& operator=(const Shader&) = delete;
+
+ // Movable
+ Shader(Shader&& other) noexcept;
+ Shader& operator=(Shader&& other) noexcept;
+
+ // Create shader from source code
+ static Unique<Shader> create(const std::string& vertexSrc, const std::string& fragmentSrc);
+
+ // Create shader from files
+ static Unique<Shader> createFromFile(const std::string& vertexPath, const std::string& fragmentPath);
+
+ // Bind/unbind shader
+ void bind() const;
+ void unbind() const;
+
+ // Uniform setters
+ void setUniform(const std::string& name, i32 value);
+ void setUniform(const std::string& name, f32 value);
+ void setUniform(const std::string& name, const glm::vec2& value);
+ void setUniform(const std::string& name, const glm::vec3& value);
+ void setUniform(const std::string& name, const glm::vec4& value);
+ void setUniform(const std::string& name, const glm::mat3& value);
+ void setUniform(const std::string& name, const glm::mat4& value);
+
+ // Check if shader is valid
+ bool isValid() const { return programId_ != 0; }
+ u32 getProgramId() const { return programId_; }
+
+private:
+ bool compile(const std::string& vertexSrc, const std::string& fragmentSrc);
+ i32 getUniformLocation(const std::string& name);
+
+ u32 programId_ = 0;
+ std::unordered_map<std::string, i32> uniformCache_;
+};
+
+// Common shader sources for 2D rendering
+namespace ShaderSources {
+
+// Basic 2D sprite vertex shader
+inline const char* SPRITE_VERTEX = R"(
+ attribute vec2 a_position;
+ attribute vec2 a_texCoord;
+
+ uniform mat4 u_projection;
+ uniform mat4 u_model;
+
+ varying vec2 v_texCoord;
+
+ void main() {
+ gl_Position = u_projection * u_model * vec4(a_position, 0.0, 1.0);
+ v_texCoord = a_texCoord;
+ }
+)";
+
+// Basic 2D sprite fragment shader
+inline const char* SPRITE_FRAGMENT = R"(
+ precision mediump float;
+
+ uniform sampler2D u_texture;
+ uniform vec4 u_color;
+
+ varying vec2 v_texCoord;
+
+ void main() {
+ vec4 texColor = texture2D(u_texture, v_texCoord);
+ gl_FragColor = texColor * u_color;
+ }
+)";
+
+// Simple color vertex shader
+inline const char* COLOR_VERTEX = R"(
+ attribute vec2 a_position;
+
+ uniform mat4 u_projection;
+ uniform mat4 u_model;
+
+ void main() {
+ gl_Position = u_projection * u_model * vec4(a_position, 0.0, 1.0);
+ }
+)";
+
+// Simple color fragment shader
+inline const char* COLOR_FRAGMENT = R"(
+ precision mediump float;
+
+ uniform vec4 u_color;
+
+ void main() {
+ gl_FragColor = u_color;
+ }
+)";
+
+} // namespace ShaderSources
+
+} // namespace esengine
diff --git a/src/esengine/renderer/Texture.cpp b/src/esengine/renderer/Texture.cpp
new file mode 100644
index 000000000..b00f8bf08
--- /dev/null
+++ b/src/esengine/renderer/Texture.cpp
@@ -0,0 +1,213 @@
+#include "Texture.hpp"
+#include "../core/Log.hpp"
+
+#ifdef ES_PLATFORM_WEB
+ #include <GLES3/gl3.h>
+#else
+ #ifdef _WIN32
+ #include <windows.h>
+ #endif
+ #include <GL/gl.h>
+ #ifndef GL_TEXTURE_2D
+ #define GL_TEXTURE_2D 0x0DE1
+ #define GL_TEXTURE_MIN_FILTER 0x2801
+ #define GL_TEXTURE_MAG_FILTER 0x2800
+ #define GL_TEXTURE_WRAP_S 0x2802
+ #define GL_TEXTURE_WRAP_T 0x2803
+ #define GL_LINEAR 0x2601
+ #define GL_NEAREST 0x2600
+ #define GL_REPEAT 0x2901
+ #define GL_CLAMP_TO_EDGE 0x812F
+ #define GL_MIRRORED_REPEAT 0x8370
+ #define GL_RGB 0x1907
+ #define GL_RGBA 0x1908
+ #define GL_UNSIGNED_BYTE 0x1401
+ #endif
+#endif
+
+namespace esengine {
+
+namespace {
+
+#ifdef ES_PLATFORM_WEB
+GLenum toGLFormat(TextureFormat format) {
+ switch (format) {
+ case TextureFormat::RGB8: return GL_RGB;
+ case TextureFormat::RGBA8: return GL_RGBA;
+ default: return GL_RGBA;
+ }
+}
+
+GLenum toGLInternalFormat(TextureFormat format) {
+ switch (format) {
+ case TextureFormat::RGB8: return GL_RGB8;
+ case TextureFormat::RGBA8: return GL_RGBA8;
+ default: return GL_RGBA8;
+ }
+}
+
+GLenum toGLFilter(TextureFilter filter) {
+ switch (filter) {
+ case TextureFilter::Nearest: return GL_NEAREST;
+ case TextureFilter::Linear: return GL_LINEAR;
+ default: return GL_LINEAR;
+ }
+}
+
+GLenum toGLWrap(TextureWrap wrap) {
+ switch (wrap) {
+ case TextureWrap::Repeat: return GL_REPEAT;
+ case TextureWrap::ClampToEdge: return GL_CLAMP_TO_EDGE;
+ case TextureWrap::MirroredRepeat: return GL_MIRRORED_REPEAT;
+ default: return GL_REPEAT;
+ }
+}
+#endif
+
+} // namespace
+
+Texture::~Texture() {
+#ifdef ES_PLATFORM_WEB
+ if (textureId_ != 0) {
+ glDeleteTextures(1, &textureId_);
+ }
+#endif
+}
+
+Texture::Texture(Texture&& other) noexcept
+ : textureId_(other.textureId_)
+ , width_(other.width_)
+ , height_(other.height_)
+ , format_(other.format_) {
+ other.textureId_ = 0;
+ other.width_ = 0;
+ other.height_ = 0;
+}
+
+Texture& Texture::operator=(Texture&& other) noexcept {
+ if (this != &other) {
+#ifdef ES_PLATFORM_WEB
+ if (textureId_ != 0) {
+ glDeleteTextures(1, &textureId_);
+ }
+#endif
+ textureId_ = other.textureId_;
+ width_ = other.width_;
+ height_ = other.height_;
+ format_ = other.format_;
+ other.textureId_ = 0;
+ other.width_ = 0;
+ other.height_ = 0;
+ }
+ return *this;
+}
+
+Unique<Texture> Texture::create(const TextureSpecification& spec) {
+ auto texture = makeUnique<Texture>();
+ if (!texture->initialize(spec)) {
+ return nullptr;
+ }
+ return texture;
+}
+
+Unique<Texture> Texture::create(u32 width, u32 height, const void* data, TextureFormat format) {
+ TextureSpecification spec;
+ spec.width = width;
+ spec.height = height;
+ spec.format = format;
+
+ auto texture = makeUnique<Texture>();
+ if (!texture->initialize(spec)) {
+ return nullptr;
+ }
+
+ if (data) {
+ texture->setData(data, width * height * (format == TextureFormat::RGBA8 ? 4 : 3));
+ }
+
+ return texture;
+}
+
+Unique<Texture> Texture::createFromFile(const std::string& path) {
+ // TODO: Implement image loading (requires stb_image or similar)
+ ES_LOG_ERROR("Texture::createFromFile not implemented: {}", path);
+ return nullptr;
+}
+
+bool Texture::initialize(const TextureSpecification& spec) {
+ width_ = spec.width;
+ height_ = spec.height;
+ format_ = spec.format;
+
+#ifdef ES_PLATFORM_WEB
+ glGenTextures(1, &textureId_);
+ glBindTexture(GL_TEXTURE_2D, textureId_);
+
+ // Set texture parameters
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, toGLFilter(spec.minFilter));
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, toGLFilter(spec.magFilter));
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, toGLWrap(spec.wrapS));
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, toGLWrap(spec.wrapT));
+
+ // Allocate texture storage
+ glTexImage2D(
+ GL_TEXTURE_2D,
+ 0,
+ toGLInternalFormat(spec.format),
+ width_,
+ height_,
+ 0,
+ toGLFormat(spec.format),
+ GL_UNSIGNED_BYTE,
+ nullptr
+ );
+
+ if (spec.generateMips) {
+ glGenerateMipmap(GL_TEXTURE_2D);
+ }
+
+ ES_LOG_DEBUG("Created texture {}x{} (ID: {})", width_, height_, textureId_);
+ return true;
+#else
+ (void)spec;
+ return false;
+#endif
+}
+
+void Texture::bind(u32 slot) const {
+#ifdef ES_PLATFORM_WEB
+ glActiveTexture(GL_TEXTURE0 + slot);
+ glBindTexture(GL_TEXTURE_2D, textureId_);
+#else
+ (void)slot;
+#endif
+}
+
+void Texture::unbind() const {
+#ifdef ES_PLATFORM_WEB
+ glBindTexture(GL_TEXTURE_2D, 0);
+#endif
+}
+
+void Texture::setData(const void* data, u32 size) {
+#ifdef ES_PLATFORM_WEB
+ u32 bpp = (format_ == TextureFormat::RGBA8) ? 4 : 3;
+ ES_ASSERT(size == width_ * height_ * bpp, "Data size mismatch");
+
+ glBindTexture(GL_TEXTURE_2D, textureId_);
+ glTexSubImage2D(
+ GL_TEXTURE_2D,
+ 0,
+ 0, 0,
+ width_, height_,
+ toGLFormat(format_),
+ GL_UNSIGNED_BYTE,
+ data
+ );
+#else
+ (void)data;
+ (void)size;
+#endif
+}
+
+} // namespace esengine
diff --git a/src/esengine/renderer/Texture.hpp b/src/esengine/renderer/Texture.hpp
new file mode 100644
index 000000000..43dc0f368
--- /dev/null
+++ b/src/esengine/renderer/Texture.hpp
@@ -0,0 +1,84 @@
+#pragma once
+
+#include "../core/Types.hpp"
+#include <string>
+
+namespace esengine {
+
+enum class TextureFormat {
+ None = 0,
+ RGB8,
+ RGBA8,
+ Depth24
+};
+
+enum class TextureFilter {
+ Nearest,
+ Linear
+};
+
+enum class TextureWrap {
+ Repeat,
+ ClampToEdge,
+ MirroredRepeat
+};
+
+struct TextureSpecification {
+ u32 width = 1;
+ u32 height = 1;
+ TextureFormat format = TextureFormat::RGBA8;
+ TextureFilter minFilter = TextureFilter::Linear;
+ TextureFilter magFilter = TextureFilter::Linear;
+ TextureWrap wrapS = TextureWrap::Repeat;
+ TextureWrap wrapT = TextureWrap::Repeat;
+ bool generateMips = true;
+};
+
+class Texture {
+public:
+ Texture() = default;
+ virtual ~Texture();
+
+ // Non-copyable, movable
+ Texture(const Texture&) = delete;
+ Texture& operator=(const Texture&) = delete;
+ Texture(Texture&& other) noexcept;
+ Texture& operator=(Texture&& other) noexcept;
+
+ // Create from specification (empty texture)
+ static Unique<Texture> create(const TextureSpecification& spec);
+
+ // Create from raw data
+ static Unique<Texture> create(u32 width, u32 height, const void* data,
+ TextureFormat format = TextureFormat::RGBA8);
+
+ // Create from file (requires file loading implementation)
+ static Unique<Texture> createFromFile(const std::string& path);
+
+ // Bind to texture unit
+ void bind(u32 slot = 0) const;
+ void unbind() const;
+
+ // Update texture data
+ void setData(const void* data, u32 size);
+
+ // Getters
+ u32 getId() const { return textureId_; }
+ u32 getWidth() const { return width_; }
+ u32 getHeight() const { return height_; }
+ TextureFormat getFormat() const { return format_; }
+
+ bool operator==(const Texture& other) const {
+ return textureId_ == other.textureId_;
+ }
+
+private:
+ bool initialize(const TextureSpecification& spec);
+
+ u32 textureId_ = 0;
+ u32 width_ = 0;
+ u32 height_ = 0;
+ TextureFormat format_ = TextureFormat::None;
+};
+
+} // namespace esengine
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
new file mode 100644
index 000000000..f9dbfd857
--- /dev/null
+++ b/tests/CMakeLists.txt
@@ -0,0 +1,10 @@
+# ESEngine Tests
+
+# Simple test framework (minimal, no external dependencies)
+add_executable(test_ecs
+ ecs/test_registry.cpp
+)
+target_link_libraries(test_ecs PRIVATE esengine)
+
+# Add test
+add_test(NAME test_ecs COMMAND test_ecs)
diff --git a/tests/ecs/test_registry.cpp b/tests/ecs/test_registry.cpp
new file mode 100644
index 000000000..bd100ff06
--- /dev/null
+++ b/tests/ecs/test_registry.cpp
@@ -0,0 +1,331 @@
+// ESEngine ECS Unit Tests
+// Simple test framework without external dependencies
+
+#include <esengine/ESEngine.hpp>
+#include <iostream>
+#include <cassert>
+
+using namespace esengine;
+using namespace esengine::ecs;
+
+// Simple test macros
+#define TEST(name) void test_##name()
+#define RUN_TEST(name) do { \
+ std::cout << "Running " #name "... "; \
+ test_##name(); \
+ std::cout << "PASSED" << std::endl; \
+ passed++; \
+} while(0)
+
+#define ASSERT_TRUE(cond) do { \
+ if (!(cond)) { \
+ std::cerr << "FAILED: " #cond << " at line " << __LINE__ << std::endl; \
+ failed++; \
+ return; \
+ } \
+} while(0)
+
+#define ASSERT_EQ(a, b) ASSERT_TRUE((a) == (b))
+#define ASSERT_NE(a, b) ASSERT_TRUE((a) != (b))
+
+static int passed = 0;
+static int failed = 0;
+
+// Test components
+struct Position {
+ float x, y;
+};
+
+struct Velocity {
+ float dx, dy;
+};
+
+struct Health {
+ int value;
+};
+
+// Tests
+TEST(entity_creation) {
+ Registry registry;
+
+ Entity e1 = registry.create();
+ Entity e2 = registry.create();
+ Entity e3 = registry.create();
+
+ ASSERT_TRUE(registry.valid(e1));
+ ASSERT_TRUE(registry.valid(e2));
+ ASSERT_TRUE(registry.valid(e3));
+ ASSERT_NE(e1, e2);
+ ASSERT_NE(e2, e3);
+ ASSERT_EQ(registry.entityCount(), 3u);
+}
+
+TEST(entity_destruction) {
+ Registry registry;
+
+ Entity e1 = registry.create();
+ Entity e2 = registry.create();
+
+ registry.destroy(e1);
+
+ ASSERT_TRUE(!registry.valid(e1));
+ ASSERT_TRUE(registry.valid(e2));
+ ASSERT_EQ(registry.entityCount(), 1u);
+}
+
+TEST(entity_recycling) {
+ Registry registry;
+
+ Entity e1 = registry.create();
+ registry.destroy(e1);
+ Entity e2 = registry.create();
+
+ // e2 should reuse e1's ID
+ ASSERT_EQ(e1, e2);
+ ASSERT_TRUE(registry.valid(e2));
+}
+
+TEST(component_emplace) {
+ Registry registry;
+ Entity entity = registry.create();
+
+ auto& pos = registry.emplace<Position>(entity, 10.0f, 20.0f);
+
+ ASSERT_TRUE(registry.has<Position>(entity));
+ ASSERT_EQ(pos.x, 10.0f);
+ ASSERT_EQ(pos.y, 20.0f);
+}
+
+TEST(component_get) {
+ Registry registry;
+ Entity entity = registry.create();
+ registry.emplace<Position>(entity, 5.0f, 15.0f);
+
+ auto& pos = registry.get<Position>(entity);
+
+ ASSERT_EQ(pos.x, 5.0f);
+ ASSERT_EQ(pos.y, 15.0f);
+
+ // Modify through reference
+ pos.x = 100.0f;
+ ASSERT_EQ(registry.get<Position>(entity).x, 100.0f);
+}
+
+TEST(component_remove) {
+ Registry registry;
+ Entity entity = registry.create();
+ registry.emplace<Position>(entity, 1.0f, 2.0f);
+
+ ASSERT_TRUE(registry.has<Position>(entity));
+
+ registry.remove<Position>(entity);
+
+ ASSERT_TRUE(!registry.has<Position>(entity));
+}
+
+TEST(component_try_get) {
+ Registry registry;
+ Entity entity = registry.create();
+
+ ASSERT_TRUE(registry.tryGet<Position>(entity) == nullptr);
+
+ registry.emplace<Position>(entity, 1.0f, 2.0f);
+
+ auto* pos = registry.tryGet<Position>(entity);
+ ASSERT_TRUE(pos != nullptr);
+ ASSERT_EQ(pos->x, 1.0f);
+}
+
+TEST(multiple_components) {
+ Registry registry;
+ Entity entity = registry.create();
+
+ registry.emplace<Position>(entity, 1.0f, 2.0f);
+ registry.emplace<Velocity>(entity, 3.0f, 4.0f);
+ registry.emplace<Health>(entity, 100);
+
+ ASSERT_TRUE(registry.has<Position>(entity));
+ ASSERT_TRUE(registry.has<Velocity>(entity));
+ ASSERT_TRUE(registry.has<Health>(entity));
+
+ ASSERT_EQ(registry.get<Position>(entity).x, 1.0f);
+ ASSERT_EQ(registry.get<Velocity>(entity).dx, 3.0f);
+ ASSERT_EQ(registry.get<Health>(entity).value, 100);
+}
+
+TEST(view_single_component) {
+ Registry registry;
+
+ Entity e1 = registry.create();
+ Entity e2 = registry.create();
+ Entity e3 = registry.create();
+
+ registry.emplace<Position>(e1, 1.0f, 1.0f);
+ registry.emplace<Position>(e2, 2.0f, 2.0f);
+ // e3 has no Position
+
+ auto view = registry.view<Position>();
+ int count = 0;
+ for (auto entity : view) {
+ (void)entity;
+ count++;
+ }
+
+ ASSERT_EQ(count, 2);
+}
+
+TEST(view_multiple_components) {
+ Registry registry;
+
+ Entity e1 = registry.create();
+ Entity e2 = registry.create();
+ Entity e3 = registry.create();
+
+ registry.emplace<Position>(e1, 1.0f, 1.0f);
+ registry.emplace<Velocity>(e1, 1.0f, 1.0f);
+
+ registry.emplace<Position>(e2, 2.0f, 2.0f);
+ // e2 has no Velocity
+
+ registry.emplace<Velocity>(e3, 3.0f, 3.0f);
+ // e3 has no Position
+
+ auto view = registry.view<Position, Velocity>();
+ int count = 0;
+ for (auto entity : view) {
+ (void)entity;
+ count++;
+ }
+
+ ASSERT_EQ(count, 1); // Only e1 has both
+}
+
+TEST(view_each) {
+ Registry registry;
+
+ Entity e1 = registry.create();
+ Entity e2 = registry.create();
+
+ registry.emplace<Position>(e1, 10.0f, 20.0f);
+ registry.emplace<Velocity>(e1, 1.0f, 2.0f);
+
+ registry.emplace<Position>(e2, 30.0f, 40.0f);
+ registry.emplace<Velocity>(e2, 3.0f, 4.0f);
+
+ float totalX = 0.0f;
+ auto view = registry.view<Position, Velocity>();
+ view.each([&totalX](Entity entity, Position& pos, Velocity& vel) {
+ (void)entity;
+ pos.x += vel.dx;
+ totalX += pos.x;
+ });
+
+ ASSERT_EQ(registry.get<Position>(e1).x, 11.0f);
+ ASSERT_EQ(registry.get<Position>(e2).x, 33.0f);
+ ASSERT_EQ(totalX, 44.0f);
+}
+
+TEST(has_all_any) {
+ Registry registry;
+ Entity entity = registry.create();
+
+ registry.emplace<Position>(entity, 0.0f, 0.0f);
+ registry.emplace<Velocity>(entity, 0.0f, 0.0f);
+
+ ASSERT_TRUE(registry.hasAll<Position, Velocity>(entity));
+ ASSERT_TRUE(!registry.hasAll<Position, Health>(entity));
+ ASSERT_TRUE(registry.hasAny<Position, Health>(entity));
+ ASSERT_TRUE(!registry.hasAny<Health>(entity));
+}
+
+TEST(clear_registry) {
+ Registry registry;
+
+ for (int i = 0; i < 10; ++i) {
+ Entity e = registry.create();
+ registry.emplace<Position>(e, static_cast<float>(i), 0.0f);
+ }
+
+ ASSERT_EQ(registry.entityCount(), 10u);
+
+ registry.clear();
+
+ ASSERT_EQ(registry.entityCount(), 0u);
+
+ // Should be able to create new entities after clear
+ Entity e = registry.create();
+ ASSERT_TRUE(registry.valid(e));
+}
+
+TEST(sparse_set_basic) {
+ SparseSet<Position> set;
+
+ Entity e1 = 0;
+ Entity e2 = 5;
+ Entity e3 = 100;
+
+ set.emplace(e1, 1.0f, 1.0f);
+ set.emplace(e2, 2.0f, 2.0f);
+ set.emplace(e3, 3.0f, 3.0f);
+
+ ASSERT_TRUE(set.contains(e1));
+ ASSERT_TRUE(set.contains(e2));
+ ASSERT_TRUE(set.contains(e3));
+ ASSERT_TRUE(!set.contains(50));
+
+ ASSERT_EQ(set.get(e1).x, 1.0f);
+ ASSERT_EQ(set.get(e2).x, 2.0f);
+ ASSERT_EQ(set.get(e3).x, 3.0f);
+
+ ASSERT_EQ(set.size(), 3u);
+}
+
+TEST(sparse_set_remove) {
+ SparseSet<Position> set;
+
+ Entity e1 = 0;
+ Entity e2 = 1;
+ Entity e3 = 2;
+
+ set.emplace(e1, 1.0f, 1.0f);
+ set.emplace(e2, 2.0f, 2.0f);
+ set.emplace(e3, 3.0f, 3.0f);
+
+ set.remove(e2);
+
+ ASSERT_TRUE(set.contains(e1));
+ ASSERT_TRUE(!set.contains(e2));
+ ASSERT_TRUE(set.contains(e3));
+
+ // Values should still be correct after swap-and-pop
+ ASSERT_EQ(set.get(e1).x, 1.0f);
+ ASSERT_EQ(set.get(e3).x, 3.0f);
+
+ ASSERT_EQ(set.size(), 2u);
+}
+
+int main() {
+ std::cout << "ESEngine ECS Unit Tests" << std::endl;
+ std::cout << "========================" << std::endl;
+
+ RUN_TEST(entity_creation);
+ RUN_TEST(entity_destruction);
+ RUN_TEST(entity_recycling);
+ RUN_TEST(component_emplace);
+ RUN_TEST(component_get);
+ RUN_TEST(component_remove);
+ RUN_TEST(component_try_get);
+ RUN_TEST(multiple_components);
+ RUN_TEST(view_single_component);
+ RUN_TEST(view_multiple_components);
+ RUN_TEST(view_each);
+ RUN_TEST(has_all_any);
+ RUN_TEST(clear_registry);
+ RUN_TEST(sparse_set_basic);
+ RUN_TEST(sparse_set_remove);
+
+ std::cout << "========================" << std::endl;
+ std::cout << "Results: " << passed << " passed, " << failed << " failed" << std::endl;
+
+ return failed > 0 ? 1 : 0;
+}
diff --git a/third_party/CMakeLists.txt b/third_party/CMakeLists.txt
new file mode 100644
index 000000000..bff10c4e2
--- /dev/null
+++ b/third_party/CMakeLists.txt
@@ -0,0 +1,13 @@
+# Third-party libraries for ESEngine
+
+# GLM - OpenGL Mathematics Library
+# GLM is a header-only library
+add_library(glm INTERFACE)
+target_include_directories(glm INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/glm)
+
+# Define GLM options
+target_compile_definitions(glm INTERFACE
+ GLM_FORCE_RADIANS
+ GLM_FORCE_DEPTH_ZERO_TO_ONE
+ GLM_ENABLE_EXPERIMENTAL
+)
diff --git a/third_party/glm b/third_party/glm
new file mode 160000
index 000000000..e7970a8b2
--- /dev/null
+++ b/third_party/glm
@@ -0,0 +1 @@
+Subproject commit e7970a8b26732f1b0df9690f7180546f8c30e48e