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.

refactor: Add resource management system and modernize renderer

esengined4d1e951c3d7
diff --git a/.gitignore b/.gitignore
index 177a4bb75..46660d35b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -40,6 +40,9 @@ compile_commands.json
Thumbs.db
desktop.ini
+# Claude Code
+CLAUDE.md
+
# Third party (if using git submodules, keep this)
# third_party/
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 9d8d4a491..782a16d51 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,7 +1,7 @@
cmake_minimum_required(VERSION 3.16)
project(ESEngine VERSION 0.1.0 LANGUAGES CXX)
-set(CMAKE_CXX_STANDARD 17)
+set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
@@ -27,6 +27,8 @@ set(ESENGINE_SOURCES
src/esengine/core/Application.cpp
src/esengine/core/Engine.cpp
src/esengine/core/Log.cpp
+ src/esengine/resource/ResourceManager.cpp
+ src/esengine/renderer/RenderContext.cpp
src/esengine/renderer/Renderer.cpp
src/esengine/renderer/Shader.cpp
src/esengine/renderer/Buffer.cpp
@@ -48,6 +50,11 @@ set(ESENGINE_HEADERS
src/esengine/ecs/SparseSet.hpp
src/esengine/ecs/View.hpp
src/esengine/math/Math.hpp
+ src/esengine/resource/Handle.hpp
+ src/esengine/resource/ResourcePool.hpp
+ src/esengine/resource/ResourceManager.hpp
+ src/esengine/resource/Resource.hpp
+ src/esengine/renderer/RenderContext.hpp
src/esengine/renderer/Renderer.hpp
src/esengine/renderer/Shader.hpp
src/esengine/renderer/Buffer.hpp
diff --git a/README.md b/README.md
index b13901a2b..84a979bbc 100644
--- a/README.md
+++ b/README.md
@@ -2,10 +2,10 @@
# ESEngine
-**A lightweight C++17 game engine for WebAssembly and WeChat MiniGames**
+**A lightweight C++20 game engine for WebAssembly and WeChat MiniGames**
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
-[![C++17](https://img.shields.io/badge/C%2B%2B-17-blue.svg)](https://isocpp.org/)
+[![C++20](https://img.shields.io/badge/C%2B%2B-20-blue.svg)](https://isocpp.org/)
[![Platform](https://img.shields.io/badge/Platform-Web%20%7C%20WeChat-green.svg)]()
[Getting Started](#getting-started) • [Documentation](#documentation) • [Examples](examples/) • [Contributing](#contributing)
@@ -33,7 +33,7 @@ ESEngine is a minimal, high-performance game engine designed for WebAssembly dep
### Prerequisites
- CMake 3.16+
-- C++17 compiler
+- C++20 compiler
- [Emscripten SDK](https://emscripten.org/) (for web builds)
### Build
diff --git a/examples/hello_triangle/main.cpp b/examples/hello_triangle/main.cpp
index 9573f0e37..ed76f88c4 100644
--- a/examples/hello_triangle/main.cpp
+++ b/examples/hello_triangle/main.cpp
@@ -77,6 +77,7 @@ protected:
void onRender() override {
auto& registry = getRegistry();
+ auto& renderer = getRenderer();
// Draw colored quads for entities with Transform and Sprite
auto view = registry.view<Transform, Sprite>();
@@ -84,21 +85,21 @@ protected:
auto& transform = view.get<Transform>(entity);
auto& sprite = view.get<Sprite>(entity);
- Renderer::drawQuad(
+ 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)
+ // Draw the main triangle
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(
+ 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)
diff --git a/src/esengine/core/Application.cpp b/src/esengine/core/Application.cpp
index 3e7b8acce..d95762d73 100644
--- a/src/esengine/core/Application.cpp
+++ b/src/esengine/core/Application.cpp
@@ -1,6 +1,17 @@
+/**
+ * @file Application.cpp
+ * @brief Application base class implementation
+ * @details Manages the main game loop, platform integration, and subsystem lifecycle.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
#include "Application.hpp"
#include "Log.hpp"
-#include "../renderer/Renderer.hpp"
#include "../platform/input/Input.hpp"
#ifdef ES_PLATFORM_WEB
@@ -80,15 +91,25 @@ void Application::init() {
platform_->setResizeCallback([this](u32 width, u32 height) {
config_.width = width;
config_.height = height;
- Renderer::setViewport(0, 0, width, height);
+ if (renderer_) {
+ 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 resource manager
+ resourceManager_.init();
+
+ // Initialize render context and renderer
+ renderContext_ = makeUnique<RenderContext>();
+ renderContext_->init();
+
+ renderer_ = makeUnique<Renderer>(*renderContext_);
+ renderer_->setViewport(0, 0, config_.width, config_.height);
+ renderer_->setClearColor(glm::vec4(0.1f, 0.1f, 0.1f, 1.0f));
// Initialize systems
systems_.init(registry_);
@@ -115,20 +136,20 @@ void Application::mainLoop() {
onUpdate(static_cast<f32>(deltaTime_));
// Render
- Renderer::beginFrame();
- Renderer::clear();
+ 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);
+ renderer_->beginScene(projection);
// Call user render
onRender();
- Renderer::endScene();
- Renderer::endFrame();
+ renderer_->endScene();
+ renderer_->endFrame();
// Swap buffers
platform_->swapBuffers();
@@ -146,8 +167,14 @@ void Application::shutdown() {
// Clear registry
registry_.clear();
- // Shutdown subsystems
- Renderer::shutdown();
+ // Shutdown renderer and context
+ renderer_.reset();
+ renderContext_.reset();
+
+ // Shutdown resource manager
+ resourceManager_.shutdown();
+
+ // Shutdown input
Input::shutdown();
// Shutdown platform
diff --git a/src/esengine/core/Application.hpp b/src/esengine/core/Application.hpp
index 67cf5900a..29dfd4a75 100644
--- a/src/esengine/core/Application.hpp
+++ b/src/esengine/core/Application.hpp
@@ -5,9 +5,9 @@
* management, event handling, and access to engine subsystems.
*
* @author ESEngine Team
- * @date 2025
+ * @date 2026
*
- * @copyright Copyright (c) 2025 ESEngine Team
+ * @copyright Copyright (c) 2026 ESEngine Team
* Licensed under the MIT License.
*/
#pragma once
@@ -21,6 +21,9 @@
#include "../platform/Platform.hpp"
#include "../ecs/Registry.hpp"
#include "../ecs/System.hpp"
+#include "../resource/ResourceManager.hpp"
+#include "../renderer/RenderContext.hpp"
+#include "../renderer/Renderer.hpp"
namespace esengine {
@@ -65,6 +68,8 @@ struct ApplicationConfig {
* - Platform abstraction and window/context creation
* - Main game loop with fixed timestep
* - ECS Registry for entity/component management
+ * - Resource management (shaders, textures, buffers)
+ * - Rendering context and renderer
* - Event dispatching (input, resize, etc.)
*
* @code
@@ -75,6 +80,7 @@ struct ApplicationConfig {
* protected:
* void onInit() override {
* // Load assets, create entities
+ * auto tex = getResourceManager().loadTexture("player.png");
* }
*
* void onUpdate(f32 deltaTime) override {
@@ -83,6 +89,7 @@ struct ApplicationConfig {
*
* void onRender() override {
* // Drawing code
+ * getRenderer().drawQuad({100, 100}, {50, 50}, {1, 0, 0, 1});
* }
* };
*
@@ -141,6 +148,24 @@ public:
*/
ecs::Registry& getRegistry() { return registry_; }
+ /**
+ * @brief Gets the resource manager
+ * @return Reference to the ResourceManager for asset loading
+ */
+ resource::ResourceManager& getResourceManager() { return resourceManager_; }
+
+ /**
+ * @brief Gets the render context
+ * @return Reference to the RenderContext
+ */
+ RenderContext& getRenderContext() { return *renderContext_; }
+
+ /**
+ * @brief Gets the renderer
+ * @return Reference to the Renderer for drawing
+ */
+ Renderer& getRenderer() { return *renderer_; }
+
/** @brief Gets the current viewport width in pixels */
u32 getWidth() const { return config_.width; }
@@ -162,7 +187,7 @@ public:
protected:
// =========================================================================
- // Lifecycle Hooks (Override in Derived Class)
+ // Lifecycle Hooks
// =========================================================================
/**
@@ -191,7 +216,7 @@ protected:
virtual void onShutdown() {}
// =========================================================================
- // Event Callbacks (Override in Derived Class)
+ // Event Callbacks
// =========================================================================
/**
@@ -233,6 +258,12 @@ protected:
ecs::Registry registry_;
/** @brief System execution group */
ecs::SystemGroup systems_;
+ /** @brief Resource manager for assets */
+ resource::ResourceManager resourceManager_;
+ /** @brief Rendering context with shared state */
+ Unique<RenderContext> renderContext_;
+ /** @brief Renderer instance */
+ Unique<Renderer> renderer_;
private:
void init();
diff --git a/src/esengine/core/Engine.cpp b/src/esengine/core/Engine.cpp
index 7834c75c8..c4fb77fb7 100644
--- a/src/esengine/core/Engine.cpp
+++ b/src/esengine/core/Engine.cpp
@@ -1,3 +1,15 @@
+/**
+ * @file Engine.cpp
+ * @brief Engine singleton implementation
+ * @details Provides platform detection and GPU capability queries.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
#include "Engine.hpp"
#include "Log.hpp"
diff --git a/src/esengine/core/Log.cpp b/src/esengine/core/Log.cpp
index c0305f6e0..a69f860d5 100644
--- a/src/esengine/core/Log.cpp
+++ b/src/esengine/core/Log.cpp
@@ -1,3 +1,15 @@
+/**
+ * @file Log.cpp
+ * @brief Logging system implementation
+ * @details Provides multi-level logging output to console.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
#include "Log.hpp"
namespace esengine {
diff --git a/src/esengine/core/Types.hpp b/src/esengine/core/Types.hpp
index 3dfca49b0..d227f4051 100644
--- a/src/esengine/core/Types.hpp
+++ b/src/esengine/core/Types.hpp
@@ -6,9 +6,9 @@
* error handling.
*
* @author ESEngine Team
- * @date 2025
+ * @date 2026
*
- * @copyright Copyright (c) 2025 ESEngine Team
+ * @copyright Copyright (c) 2026 ESEngine Team
* Licensed under the MIT License.
*/
#pragma once
@@ -21,6 +21,7 @@
#include <cstdint>
#include <limits>
#include <memory>
+#include <span>
#include <string>
#include <vector>
@@ -106,7 +107,7 @@ constexpr Shared<T> makeShared(Args&&... args) {
}
// =============================================================================
-// Entity Types (ECS Core)
+// Entity Types
// =============================================================================
/**
@@ -231,4 +232,14 @@ private:
bool success_;
};
+// =============================================================================
+// Span Types
+// =============================================================================
+
+template<typename T>
+using Span = std::span<T>;
+
+template<typename T>
+using ConstSpan = std::span<const T>;
+
} // namespace esengine
diff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hpp
index af18d0aed..7a05f1d3f 100644
--- a/src/esengine/ecs/Registry.hpp
+++ b/src/esengine/ecs/Registry.hpp
@@ -307,7 +307,7 @@ public:
}
// =========================================================================
- // View (Query) System
+ // View Query System
// =========================================================================
/**
@@ -385,7 +385,7 @@ public:
auto* pool = getPool<T>();
if (!pool) return;
- // Selection sort (could be optimized)
+ // Selection sort
auto& entities = const_cast<std::vector<Entity>&>(pool->entities());
auto& components = pool->components();
diff --git a/src/esengine/ecs/SparseSet.hpp b/src/esengine/ecs/SparseSet.hpp
index 31f9ae530..4aec575fc 100644
--- a/src/esengine/ecs/SparseSet.hpp
+++ b/src/esengine/ecs/SparseSet.hpp
@@ -231,7 +231,7 @@ public:
void remove(Entity entity) override {
if (!contains(entity)) return;
- // Swap with last element (swap and pop)
+ // Swap and pop
const auto last = dense_.back();
const auto index = sparse_[entity];
diff --git a/src/esengine/ecs/View.hpp b/src/esengine/ecs/View.hpp
index bad2e3417..f2fa23801 100644
--- a/src/esengine/ecs/View.hpp
+++ b/src/esengine/ecs/View.hpp
@@ -141,7 +141,7 @@ private:
};
// =============================================================================
-// View (Multi-Component)
+// Multi-Component View
// =============================================================================
/**
@@ -332,7 +332,7 @@ private:
};
// =============================================================================
-// View<T> Specialization (Single Component)
+// Single-Component View Specialization
// =============================================================================
/**
diff --git a/src/esengine/platform/input/Input.cpp b/src/esengine/platform/input/Input.cpp
index 6bfa6737d..0f49d5f6f 100644
--- a/src/esengine/platform/input/Input.cpp
+++ b/src/esengine/platform/input/Input.cpp
@@ -1,3 +1,15 @@
+/**
+ * @file Input.cpp
+ * @brief Input system implementation
+ * @details Manages touch, mouse, and keyboard input state tracking.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
#include "Input.hpp"
#include "../../core/Log.hpp"
diff --git a/src/esengine/platform/input/Input.hpp b/src/esengine/platform/input/Input.hpp
index a5e97252b..897735ff4 100644
--- a/src/esengine/platform/input/Input.hpp
+++ b/src/esengine/platform/input/Input.hpp
@@ -180,7 +180,7 @@ public:
static bool isKeyReleased(KeyCode key);
// =========================================================================
- // Mouse Input (Web Debugging)
+ // Mouse Input for web debugging
// =========================================================================
/**
@@ -200,7 +200,7 @@ public:
static bool isMouseButtonDown(u32 button = 0);
// =========================================================================
- // Platform Interface (Internal)
+ // Platform Interface for internal use
// =========================================================================
/**
diff --git a/src/esengine/platform/web/WebPlatform.cpp b/src/esengine/platform/web/WebPlatform.cpp
index 0c7f4b6f4..68ad8325e 100644
--- a/src/esengine/platform/web/WebPlatform.cpp
+++ b/src/esengine/platform/web/WebPlatform.cpp
@@ -1,3 +1,16 @@
+/**
+ * @file WebPlatform.cpp
+ * @brief Web/Emscripten platform implementation
+ * @details Implements Platform interface for WebGL context management,
+ * event handling, and JavaScript interop via C API.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
#include "../Platform.hpp"
#include "../../core/Log.hpp"
#include "../../renderer/Renderer.hpp"
diff --git a/src/esengine/renderer/Buffer.cpp b/src/esengine/renderer/Buffer.cpp
index 77c6a9a3d..381948491 100644
--- a/src/esengine/renderer/Buffer.cpp
+++ b/src/esengine/renderer/Buffer.cpp
@@ -1,3 +1,16 @@
+/**
+ * @file Buffer.cpp
+ * @brief GPU buffer implementations for vertex and index data
+ * @details Implements VertexBuffer, IndexBuffer, and VertexArray classes
+ * for OpenGL/WebGL buffer management.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
#include "Buffer.hpp"
#include "../core/Log.hpp"
diff --git a/src/esengine/renderer/Buffer.hpp b/src/esengine/renderer/Buffer.hpp
index 86a9221ed..5b395a1cc 100644
--- a/src/esengine/renderer/Buffer.hpp
+++ b/src/esengine/renderer/Buffer.hpp
@@ -5,9 +5,9 @@
* objects including VertexBuffer, IndexBuffer, and VertexArray.
*
* @author ESEngine Team
- * @date 2025
+ * @date 2026
*
- * @copyright Copyright (c) 2025 ESEngine Team
+ * @copyright Copyright (c) 2026 ESEngine Team
* Licensed under the MIT License.
*/
#pragma once
@@ -20,6 +20,7 @@
#include "../core/Types.hpp"
// Standard library
+#include <span>
#include <vector>
namespace esengine {
@@ -165,7 +166,7 @@ private:
};
// =============================================================================
-// Vertex Buffer (VBO)
+// Vertex Buffer
// =============================================================================
/**
@@ -178,7 +179,7 @@ private:
* struct Vertex { float x, y, u, v; };
* std::vector<Vertex> vertices = {...};
*
- * auto vbo = VertexBuffer::create(vertices);
+ * auto vbo = VertexBuffer::create(std::span(vertices));
* vbo->setLayout({
* {ShaderDataType::Float2, "a_position"},
* {ShaderDataType::Float2, "a_texCoord"}
@@ -197,9 +198,20 @@ public:
VertexBuffer& operator=(VertexBuffer&& other) noexcept;
// =========================================================================
- // Creation
+ // Type-Safe Creation Methods
// =========================================================================
+ /**
+ * @brief Creates a static buffer from a span
+ * @tparam T Vertex type
+ * @param data Span of vertex data
+ * @return Unique pointer to the buffer
+ */
+ template<typename T>
+ static Unique<VertexBuffer> create(std::span<const T> data) {
+ return createRaw(data.data(), static_cast<u32>(data.size_bytes()));
+ }
+
/**
* @brief Creates a static buffer from a vector
* @tparam T Vertex type
@@ -208,7 +220,7 @@ public:
*/
template<typename T>
static Unique<VertexBuffer> create(const std::vector<T>& data) {
- return createRaw(data.data(), static_cast<u32>(data.size() * sizeof(T)));
+ return create(std::span<const T>(data));
}
/**
@@ -220,7 +232,7 @@ public:
*/
template<typename T, usize N>
static Unique<VertexBuffer> create(const T (&data)[N]) {
- return createRaw(data, static_cast<u32>(N * sizeof(T)));
+ return create(std::span<const T>(data, N));
}
/**
@@ -232,14 +244,6 @@ public:
*/
static Unique<VertexBuffer> create(u32 sizeBytes);
- /**
- * @brief Creates a buffer from raw data pointer
- * @param data Pointer to vertex data
- * @param sizeBytes Size of data in bytes
- * @return Unique pointer to the buffer
- */
- static Unique<VertexBuffer> createRaw(const void* data, u32 sizeBytes);
-
// =========================================================================
// Operations
// =========================================================================
@@ -250,6 +254,16 @@ public:
/** @brief Unbinds the buffer */
void unbind() const;
+ /**
+ * @brief Updates buffer data from a span
+ * @tparam T Vertex type
+ * @param data New vertex data
+ */
+ template<typename T>
+ void setData(std::span<const T> data) {
+ setDataRaw(data.data(), static_cast<u32>(data.size_bytes()));
+ }
+
/**
* @brief Updates buffer data from a vector
* @tparam T Vertex type
@@ -257,7 +271,7 @@ public:
*/
template<typename T>
void setData(const std::vector<T>& data) {
- setDataRaw(data.data(), static_cast<u32>(data.size() * sizeof(T)));
+ setData(std::span<const T>(data));
}
/**
@@ -268,16 +282,9 @@ public:
*/
template<typename T, usize N>
void setData(const T (&data)[N]) {
- setDataRaw(data, static_cast<u32>(N * sizeof(T)));
+ setData(std::span<const T>(data, N));
}
- /**
- * @brief Updates buffer data from raw pointer
- * @param data Pointer to new data
- * @param sizeBytes Size of data in bytes
- */
- void setDataRaw(const void* data, u32 sizeBytes);
-
// =========================================================================
// Layout
// =========================================================================
@@ -300,13 +307,32 @@ public:
*/
u32 getId() const { return bufferId_; }
+ // =========================================================================
+ // Raw API for internal use only
+ // =========================================================================
+
+ /**
+ * @brief Creates a buffer from raw data pointer for internal use
+ * @param data Pointer to vertex data
+ * @param sizeBytes Size of data in bytes
+ * @return Unique pointer to the buffer
+ */
+ static Unique<VertexBuffer> createRaw(const void* data, u32 sizeBytes);
+
+ /**
+ * @brief Updates buffer data from raw pointer (internal use)
+ * @param data Pointer to new data
+ * @param sizeBytes Size of data in bytes
+ */
+ void setDataRaw(const void* data, u32 sizeBytes);
+
private:
u32 bufferId_ = 0;
VertexLayout layout_;
};
// =============================================================================
-// Index Buffer (EBO)
+// Index Buffer
// =============================================================================
/**
@@ -316,8 +342,8 @@ private:
* both 16-bit and 32-bit indices.
*
* @code
- * u32 indices[] = {0, 1, 2, 2, 3, 0};
- * auto ebo = IndexBuffer::create(indices, 6);
+ * std::vector<u32> indices = {0, 1, 2, 2, 3, 0};
+ * auto ebo = IndexBuffer::create(std::span(indices));
* @endcode
*/
class IndexBuffer {
@@ -331,8 +357,48 @@ public:
IndexBuffer(IndexBuffer&& other) noexcept;
IndexBuffer& operator=(IndexBuffer&& other) noexcept;
+ // =========================================================================
+ // Type-Safe Creation Methods
+ // =========================================================================
+
+ /**
+ * @brief Creates an index buffer from a span of 32-bit indices
+ * @param indices Span of index data
+ * @return Unique pointer to the buffer
+ */
+ static Unique<IndexBuffer> create(std::span<const u32> indices) {
+ return create(indices.data(), static_cast<u32>(indices.size()));
+ }
+
+ /**
+ * @brief Creates an index buffer from a span of 16-bit indices
+ * @param indices Span of index data
+ * @return Unique pointer to the buffer
+ */
+ static Unique<IndexBuffer> create(std::span<const u16> indices) {
+ return create(indices.data(), static_cast<u32>(indices.size()));
+ }
+
+ /**
+ * @brief Creates an index buffer from a vector of 32-bit indices
+ * @param indices Vector of index data
+ * @return Unique pointer to the buffer
+ */
+ static Unique<IndexBuffer> create(const std::vector<u32>& indices) {
+ return create(std::span<const u32>(indices));
+ }
+
/**
- * @brief Creates an index buffer with 32-bit indices
+ * @brief Creates an index buffer from a vector of 16-bit indices
+ * @param indices Vector of index data
+ * @return Unique pointer to the buffer
+ */
+ static Unique<IndexBuffer> create(const std::vector<u16>& indices) {
+ return create(std::span<const u16>(indices));
+ }
+
+ /**
+ * @brief Creates an index buffer with 32-bit indices from pointer
* @param indices Pointer to index data
* @param count Number of indices
* @return Unique pointer to the buffer
@@ -340,7 +406,7 @@ public:
static Unique<IndexBuffer> create(const u32* indices, u32 count);
/**
- * @brief Creates an index buffer with 16-bit indices
+ * @brief Creates an index buffer with 16-bit indices from pointer
* @param indices Pointer to index data
* @param count Number of indices
* @return Unique pointer to the buffer
@@ -350,6 +416,10 @@ public:
*/
static Unique<IndexBuffer> create(const u16* indices, u32 count);
+ // =========================================================================
+ // Operations
+ // =========================================================================
+
/** @brief Binds the buffer for rendering */
void bind() const;
@@ -372,7 +442,7 @@ private:
};
// =============================================================================
-// Vertex Array Object (VAO)
+// Vertex Array Object
// =============================================================================
/**
diff --git a/src/esengine/renderer/RenderContext.cpp b/src/esengine/renderer/RenderContext.cpp
new file mode 100644
index 000000000..426dbaacd
--- /dev/null
+++ b/src/esengine/renderer/RenderContext.cpp
@@ -0,0 +1,138 @@
+/**
+ * @file RenderContext.cpp
+ * @brief Rendering context implementation
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+#include "RenderContext.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_TEXTURE_2D
+ #define GL_TEXTURE_2D 0x0DE1
+ #define GL_TEXTURE_MIN_FILTER 0x2801
+ #define GL_TEXTURE_MAG_FILTER 0x2800
+ #define GL_NEAREST 0x2600
+ #define GL_RGBA 0x1908
+ #define GL_UNSIGNED_BYTE 0x1401
+ #endif
+#endif
+
+namespace esengine {
+
+RenderContext::~RenderContext() {
+ if (initialized_) {
+ shutdown();
+ }
+}
+
+void RenderContext::init() {
+ if (initialized_) {
+ ES_LOG_WARN("RenderContext already initialized");
+ return;
+ }
+
+ RenderCommand::init();
+ initQuadData();
+ initShaders();
+ initWhiteTexture();
+
+ initialized_ = true;
+ ES_LOG_INFO("RenderContext initialized");
+}
+
+void RenderContext::shutdown() {
+ if (!initialized_) {
+ return;
+ }
+
+#ifdef ES_PLATFORM_WEB
+ if (whiteTextureId_ != 0) {
+ glDeleteTextures(1, &whiteTextureId_);
+ whiteTextureId_ = 0;
+ }
+#endif
+
+ quadVAO_.reset();
+ colorShader_.reset();
+ textureShader_.reset();
+
+ RenderCommand::shutdown();
+ initialized_ = false;
+ ES_LOG_INFO("RenderContext shutdown");
+}
+
+void RenderContext::initQuadData() {
+#ifdef ES_PLATFORM_WEB
+ // Quad vertices with position and texture coordinates
+ float vertices[] = {
+ // Position (x, y) TexCoord (u, v)
+ -0.5f, -0.5f, 0.0f, 0.0f,
+ 0.5f, -0.5f, 1.0f, 0.0f,
+ 0.5f, 0.5f, 1.0f, 1.0f,
+ -0.5f, 0.5f, 0.0f, 1.0f
+ };
+
+ u32 indices[] = { 0, 1, 2, 2, 3, 0 };
+
+ quadVAO_ = VertexArray::create();
+
+ auto vbo = VertexBuffer::createRaw(vertices, sizeof(vertices));
+ vbo->setLayout({
+ { ShaderDataType::Float2, "a_position" },
+ { ShaderDataType::Float2, "a_texCoord" }
+ });
+
+ auto ibo = IndexBuffer::create(indices, 6);
+
+ quadVAO_->addVertexBuffer(Shared<VertexBuffer>(std::move(vbo)));
+ quadVAO_->setIndexBuffer(Shared<IndexBuffer>(std::move(ibo)));
+
+ ES_LOG_DEBUG("Quad VAO initialized");
+#endif
+}
+
+void RenderContext::initShaders() {
+ // Color shader (no texture)
+ colorShader_ = Shader::create(
+ ShaderSources::COLOR_VERTEX,
+ ShaderSources::COLOR_FRAGMENT
+ );
+
+ // Texture shader
+ textureShader_ = Shader::create(
+ ShaderSources::SPRITE_VERTEX,
+ ShaderSources::SPRITE_FRAGMENT
+ );
+
+ ES_LOG_DEBUG("Shaders initialized");
+}
+
+void RenderContext::initWhiteTexture() {
+#ifdef ES_PLATFORM_WEB
+ glGenTextures(1, &whiteTextureId_);
+ glBindTexture(GL_TEXTURE_2D, whiteTextureId_);
+
+ u32 whiteData = 0xFFFFFFFF;
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, &whiteData);
+
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+
+ ES_LOG_DEBUG("White texture created (ID: {})", whiteTextureId_);
+#endif
+}
+
+} // namespace esengine
diff --git a/src/esengine/renderer/RenderContext.hpp b/src/esengine/renderer/RenderContext.hpp
new file mode 100644
index 000000000..a950be1bf
--- /dev/null
+++ b/src/esengine/renderer/RenderContext.hpp
@@ -0,0 +1,172 @@
+/**
+ * @file RenderContext.hpp
+ * @brief Rendering context containing all renderer state
+ * @details Replaces global renderer state with an injectable context object
+ * that owns shader and geometry resources for basic 2D rendering.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+#pragma once
+
+// =============================================================================
+// Includes
+// =============================================================================
+
+// Project includes
+#include "../core/Types.hpp"
+#include "Buffer.hpp"
+#include "Shader.hpp"
+
+// Third-party
+#include <glm/glm.hpp>
+
+namespace esengine {
+
+// =============================================================================
+// Renderer Statistics
+// =============================================================================
+
+/**
+ * @brief Statistics for rendering performance analysis
+ */
+struct RenderContextStats {
+ u32 drawCalls = 0; ///< Number of draw calls this frame
+ u32 triangleCount = 0; ///< Number of triangles rendered this frame
+
+ /** @brief Resets all counters to zero */
+ void reset() {
+ drawCalls = 0;
+ triangleCount = 0;
+ }
+};
+
+// =============================================================================
+// RenderContext Class
+// =============================================================================
+
+/**
+ * @brief Rendering context containing shared renderer state
+ *
+ * @details Owns the resources and state needed for basic 2D rendering,
+ * including the quad VAO, color shader, and view-projection matrix.
+ * Replaces global static state with dependency injection.
+ *
+ * @code
+ * RenderContext context;
+ * context.init();
+ *
+ * Renderer renderer(context);
+ * renderer.beginFrame();
+ * renderer.drawQuad({100, 100}, {50, 50}, {1, 0, 0, 1});
+ * renderer.endFrame();
+ *
+ * context.shutdown();
+ * @endcode
+ */
+class RenderContext {
+public:
+ RenderContext() = default;
+ ~RenderContext();
+
+ // Non-copyable
+ RenderContext(const RenderContext&) = delete;
+ RenderContext& operator=(const RenderContext&) = delete;
+
+ // =========================================================================
+ // Lifecycle
+ // =========================================================================
+
+ /**
+ * @brief Initializes rendering resources
+ * @details Creates the quad VAO, shaders, and default textures.
+ */
+ void init();
+
+ /**
+ * @brief Releases all rendering resources
+ */
+ void shutdown();
+
+ /**
+ * @brief Checks if the context is initialized
+ * @return True if init() has been called successfully
+ */
+ bool isInitialized() const { return initialized_; }
+
+ // =========================================================================
+ // State Access
+ // =========================================================================
+
+ /**
+ * @brief Gets the current view-projection matrix
+ * @return Reference to the matrix
+ */
+ glm::mat4& viewProjection() { return viewProjection_; }
+
+ /**
+ * @brief Gets the current view-projection matrix (const)
+ * @return Const reference to the matrix
+ */
+ const glm::mat4& viewProjection() const { return viewProjection_; }
+
+ /**
+ * @brief Gets the rendering statistics
+ * @return Reference to the stats
+ */
+ RenderContextStats& stats() { return stats_; }
+
+ /**
+ * @brief Gets the rendering statistics (const)
+ * @return Const reference to the stats
+ */
+ const RenderContextStats& stats() const { return stats_; }
+
+ // =========================================================================
+ // Internal Resources
+ // =========================================================================
+
+ /**
+ * @brief Gets the quad vertex array
+ * @return Pointer to the quad VAO
+ */
+ VertexArray* getQuadVAO() { return quadVAO_.get(); }
+
+ /**
+ * @brief Gets the color shader
+ * @return Pointer to the color shader
+ */
+ Shader* getColorShader() { return colorShader_.get(); }
+
+ /**
+ * @brief Gets the texture shader
+ * @return Pointer to the texture shader
+ */
+ Shader* getTextureShader() { return textureShader_.get(); }
+
+ /**
+ * @brief Gets the white texture ID (for untextured quads)
+ * @return GPU texture handle
+ */
+ u32 getWhiteTextureId() const { return whiteTextureId_; }
+
+private:
+ void initQuadData();
+ void initShaders();
+ void initWhiteTexture();
+
+ glm::mat4 viewProjection_{1.0f};
+ RenderContextStats stats_;
+
+ Unique<VertexArray> quadVAO_;
+ Unique<Shader> colorShader_;
+ Unique<Shader> textureShader_;
+ u32 whiteTextureId_ = 0;
+
+ bool initialized_ = false;
+};
+
+} // namespace esengine
diff --git a/src/esengine/renderer/Renderer.cpp b/src/esengine/renderer/Renderer.cpp
index e27a7179b..1c03f8638 100644
--- a/src/esengine/renderer/Renderer.cpp
+++ b/src/esengine/renderer/Renderer.cpp
@@ -1,6 +1,19 @@
+/**
+ * @file Renderer.cpp
+ * @brief 2D renderer and batch renderer implementation
+ * @details Implements immediate-mode and batched 2D rendering with quad primitives.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
#include "Renderer.hpp"
#include "RenderCommand.hpp"
#include "../core/Log.hpp"
+#include "../resource/ResourceManager.hpp"
#include <array>
#include <vector>
@@ -155,84 +168,18 @@ void RenderCommand::setCullFace(bool front) {
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); // Type-safe: size deduced from array
- 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
+Renderer::Renderer(RenderContext& context)
+ : context_(context) {
}
void Renderer::beginFrame() {
- s_data->stats.reset();
+ context_.stats().reset();
}
void Renderer::endFrame() {
@@ -252,7 +199,7 @@ void Renderer::clear() {
}
void Renderer::beginScene(const glm::mat4& viewProjection) {
- s_data->viewProjection = viewProjection;
+ context_.viewProjection() = viewProjection;
}
void Renderer::endScene() {
@@ -261,12 +208,12 @@ void Renderer::endScene() {
void Renderer::submit(const Shader& shader, const VertexArray& vao, const glm::mat4& transform) {
shader.bind();
- shader.setUniform("u_projection", s_data->viewProjection);
+ shader.setUniform("u_projection", context_.viewProjection());
shader.setUniform("u_model", transform);
RenderCommand::drawIndexed(vao);
- s_data->stats.drawCalls++;
+ context_.stats().drawCalls++;
}
void Renderer::drawQuad(const glm::vec2& position, const glm::vec2& size, const glm::vec4& color) {
@@ -274,20 +221,22 @@ void Renderer::drawQuad(const glm::vec2& position, const glm::vec2& size, const
}
void Renderer::drawQuad(const glm::vec3& position, const glm::vec2& size, const glm::vec4& color) {
- if (!s_data->colorShader || !s_data->quadVAO) return;
+ auto* shader = context_.getColorShader();
+ auto* vao = context_.getQuadVAO();
+ if (!shader || !vao) 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);
+ shader->bind();
+ shader->setUniform("u_projection", context_.viewProjection());
+ shader->setUniform("u_model", transform);
+ shader->setUniform("u_color", color);
- RenderCommand::drawIndexed(*s_data->quadVAO);
+ RenderCommand::drawIndexed(*vao);
- s_data->stats.drawCalls++;
- s_data->stats.triangleCount += 2;
+ context_.stats().drawCalls++;
+ context_.stats().triangleCount += 2;
}
void Renderer::drawQuad(const glm::vec2& position, const glm::vec2& size,
@@ -297,26 +246,48 @@ void Renderer::drawQuad(const glm::vec2& position, const glm::vec2& size,
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
+ auto* shader = context_.getTextureShader();
+ auto* vao = context_.getQuadVAO();
+ if (!shader || !vao) return;
+
+ glm::mat4 transform = glm::translate(glm::mat4(1.0f), position);
+ transform = glm::scale(transform, glm::vec3(size, 1.0f));
+
+ texture.bind(0);
+
+ shader->bind();
+ shader->setUniform("u_projection", context_.viewProjection());
+ shader->setUniform("u_model", transform);
+ shader->setUniform("u_color", tintColor);
+ shader->setUniform("u_texture", 0);
+
+ RenderCommand::drawIndexed(*vao);
+
+ context_.stats().drawCalls++;
+ context_.stats().triangleCount += 2;
+}
+
+void Renderer::drawQuad(const glm::vec2& position, const glm::vec2& size,
+ resource::TextureHandle texture, resource::ResourceManager& rm,
+ const glm::vec4& tintColor) {
+ Texture* tex = rm.getTexture(texture);
+ if (tex) {
+ drawQuad(position, size, *tex, tintColor);
+ }
}
-RendererStats Renderer::getStats() {
- return s_data->stats;
+RendererStats Renderer::getStats() const {
+ return context_.stats();
}
void Renderer::resetStats() {
- s_data->stats.reset();
+ context_.stats().reset();
}
// ========================================
// BatchRenderer2D Implementation
// ========================================
-namespace {
-
// Batch vertex structure
struct BatchVertex {
glm::vec3 position;
@@ -329,31 +300,7 @@ struct BatchVertex {
constexpr u32 MAX_QUADS = 10000;
constexpr u32 MAX_VERTICES = MAX_QUADS * 4;
constexpr u32 MAX_INDICES = MAX_QUADS * 6;
-constexpr u32 MAX_TEXTURE_SLOTS = 8; // WebGL typically supports 8
-
-// Batch rendering data
-struct BatchData {
- Unique<VertexArray> vao;
- Unique<VertexBuffer> vbo;
- Unique<Shader> shader;
-
- std::vector<BatchVertex> vertices;
- u32 indexCount = 0;
-
- std::array<u32, MAX_TEXTURE_SLOTS> textureSlots;
- u32 textureSlotIndex = 1; // 0 = white texture
-
- u32 whiteTextureId = 0;
- glm::mat4 projection{1.0f};
-
- // Statistics
- u32 drawCallCount = 0;
- u32 quadCount = 0;
-
- bool initialized = false;
-};
-
-BatchData* s_batchData = nullptr;
+constexpr u32 MAX_TEXTURE_SLOTS = 8;
// Quad vertex positions (CCW from bottom-left)
constexpr glm::vec4 QUAD_POSITIONS[4] = {
@@ -404,7 +351,7 @@ const char* BATCH_FRAGMENT_SHADER = R"(
int index = int(v_texIndex);
vec4 texColor = vec4(1.0);
- // WebGL 1.0 doesn't support dynamic array indexing, use if-else
+ // WebGL 1.0 doesn't support dynamic array indexing
if (index == 0) texColor = texture2D(u_textures[0], v_texCoord);
else if (index == 1) texColor = texture2D(u_textures[1], v_texCoord);
else if (index == 2) texColor = texture2D(u_textures[2], v_texCoord);
@@ -418,26 +365,55 @@ const char* BATCH_FRAGMENT_SHADER = R"(
}
)";
-} // namespace
+// BatchRenderer2D internal data
+struct BatchRenderer2D::BatchData {
+ Unique<VertexArray> vao;
+ Shared<VertexBuffer> vbo;
+ Unique<Shader> shader;
+
+ std::vector<BatchVertex> vertices;
+ u32 indexCount = 0;
+
+ std::array<u32, MAX_TEXTURE_SLOTS> textureSlots;
+ u32 textureSlotIndex = 1; // 0 = white texture
+
+ glm::mat4 projection{1.0f};
+
+ // Statistics
+ u32 drawCallCount = 0;
+ u32 quadCount = 0;
+
+ bool initialized = false;
+};
+
+BatchRenderer2D::BatchRenderer2D(RenderContext& context)
+ : data_(makeUnique<BatchData>()), context_(context) {
+}
+
+BatchRenderer2D::~BatchRenderer2D() {
+ if (data_ && data_->initialized) {
+ shutdown();
+ }
+}
void BatchRenderer2D::init() {
- s_batchData = new BatchData();
- s_batchData->vertices.reserve(MAX_VERTICES);
+ data_->vertices.reserve(MAX_VERTICES);
#ifdef ES_PLATFORM_WEB
// Create VAO
- s_batchData->vao = VertexArray::create();
+ data_->vao = VertexArray::create();
// Create dynamic vertex buffer
- s_batchData->vbo = VertexBuffer::create(MAX_VERTICES * sizeof(BatchVertex));
- s_batchData->vbo->setLayout({
+ data_->vbo = makeShared<VertexBuffer>();
+ *data_->vbo = std::move(*VertexBuffer::create(MAX_VERTICES * sizeof(BatchVertex)));
+ data_->vbo->setLayout({
{ ShaderDataType::Float3, "a_position" },
{ ShaderDataType::Float4, "a_color" },
{ ShaderDataType::Float2, "a_texCoord" },
{ ShaderDataType::Float, "a_texIndex" }
});
- s_batchData->vao->addVertexBuffer(Shared<VertexBuffer>(std::move(s_batchData->vbo)));
+ data_->vao->addVertexBuffer(data_->vbo);
// Create index buffer (pre-computed pattern for quads)
std::vector<u32> indices(MAX_INDICES);
@@ -452,49 +428,37 @@ void BatchRenderer2D::init() {
offset += 4;
}
auto ibo = IndexBuffer::create(indices.data(), MAX_INDICES);
- s_batchData->vao->setIndexBuffer(Shared<IndexBuffer>(std::move(ibo)));
+ data_->vao->setIndexBuffer(Shared<IndexBuffer>(std::move(ibo)));
// Create batch shader
- s_batchData->shader = Shader::create(BATCH_VERTEX_SHADER, BATCH_FRAGMENT_SHADER);
-
- // Create 1x1 white texture for colored quads
- glGenTextures(1, &s_batchData->whiteTextureId);
- glBindTexture(GL_TEXTURE_2D, s_batchData->whiteTextureId);
- u32 whiteData = 0xFFFFFFFF;
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, &whiteData);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-
- // Initialize texture slots
- s_batchData->textureSlots[0] = s_batchData->whiteTextureId;
+ data_->shader = Shader::create(BATCH_VERTEX_SHADER, BATCH_FRAGMENT_SHADER);
+
+ // Initialize texture slots (slot 0 = white texture from context)
+ data_->textureSlots[0] = context_.getWhiteTextureId();
for (u32 i = 1; i < MAX_TEXTURE_SLOTS; ++i) {
- s_batchData->textureSlots[i] = 0;
+ data_->textureSlots[i] = 0;
}
#endif
- s_batchData->initialized = true;
+ data_->initialized = true;
ES_LOG_INFO("BatchRenderer2D initialized (max {} quads per batch)", MAX_QUADS);
}
void BatchRenderer2D::shutdown() {
- if (s_batchData) {
-#ifdef ES_PLATFORM_WEB
- if (s_batchData->whiteTextureId != 0) {
- glDeleteTextures(1, &s_batchData->whiteTextureId);
- }
-#endif
- s_batchData->vao.reset();
- s_batchData->shader.reset();
- delete s_batchData;
- s_batchData = nullptr;
- }
+ if (!data_ || !data_->initialized) return;
+
+ data_->vao.reset();
+ data_->vbo.reset();
+ data_->shader.reset();
+ data_->initialized = false;
+
ES_LOG_INFO("BatchRenderer2D shutdown");
}
void BatchRenderer2D::beginBatch() {
- s_batchData->vertices.clear();
- s_batchData->indexCount = 0;
- s_batchData->textureSlotIndex = 1;
+ data_->vertices.clear();
+ data_->indexCount = 0;
+ data_->textureSlotIndex = 1;
}
void BatchRenderer2D::endBatch() {
@@ -502,39 +466,39 @@ void BatchRenderer2D::endBatch() {
}
void BatchRenderer2D::flush() {
- if (s_batchData->vertices.empty()) return;
+ if (data_->vertices.empty()) return;
#ifdef ES_PLATFORM_WEB
// Upload vertex data
- s_batchData->vao->getVertexBuffers()[0]->setDataRaw(
- s_batchData->vertices.data(),
- static_cast<u32>(s_batchData->vertices.size() * sizeof(BatchVertex))
+ data_->vbo->setDataRaw(
+ data_->vertices.data(),
+ static_cast<u32>(data_->vertices.size() * sizeof(BatchVertex))
);
// Bind textures
- for (u32 i = 0; i < s_batchData->textureSlotIndex; ++i) {
+ for (u32 i = 0; i < data_->textureSlotIndex; ++i) {
glActiveTexture(GL_TEXTURE0 + i);
- glBindTexture(GL_TEXTURE_2D, s_batchData->textureSlots[i]);
+ glBindTexture(GL_TEXTURE_2D, data_->textureSlots[i]);
}
// Set uniforms and draw
- s_batchData->shader->bind();
- s_batchData->shader->setUniform("u_projection", s_batchData->projection);
+ data_->shader->bind();
+ data_->shader->setUniform("u_projection", data_->projection);
// Set texture uniform array
i32 samplers[MAX_TEXTURE_SLOTS] = { 0, 1, 2, 3, 4, 5, 6, 7 };
- glUniform1iv(glGetUniformLocation(s_batchData->shader->getProgramId(), "u_textures"),
+ glUniform1iv(glGetUniformLocation(data_->shader->getProgramId(), "u_textures"),
MAX_TEXTURE_SLOTS, samplers);
- RenderCommand::drawIndexed(*s_batchData->vao, s_batchData->indexCount);
+ RenderCommand::drawIndexed(*data_->vao, data_->indexCount);
- s_batchData->drawCallCount++;
+ data_->drawCallCount++;
#endif
// Reset batch
- s_batchData->vertices.clear();
- s_batchData->indexCount = 0;
- s_batchData->textureSlotIndex = 1;
+ data_->vertices.clear();
+ data_->indexCount = 0;
+ data_->textureSlotIndex = 1;
}
void BatchRenderer2D::drawQuad(const glm::vec2& position, const glm::vec2& size,
@@ -545,7 +509,7 @@ void BatchRenderer2D::drawQuad(const glm::vec2& position, const glm::vec2& size,
void BatchRenderer2D::drawQuad(const glm::vec3& position, const glm::vec2& size,
u32 textureId, const glm::vec4& color) {
// Check if batch is full
- if (s_batchData->vertices.size() >= MAX_VERTICES) {
+ if (data_->vertices.size() >= MAX_VERTICES) {
flush();
}
@@ -553,20 +517,20 @@ void BatchRenderer2D::drawQuad(const glm::vec3& position, const glm::vec2& size,
f32 texIndex = 0.0f;
if (textureId != 0) {
bool found = false;
- for (u32 i = 0; i < s_batchData->textureSlotIndex; ++i) {
- if (s_batchData->textureSlots[i] == textureId) {
+ for (u32 i = 0; i < data_->textureSlotIndex; ++i) {
+ if (data_->textureSlots[i] == textureId) {
texIndex = static_cast<f32>(i);
found = true;
break;
}
}
if (!found) {
- if (s_batchData->textureSlotIndex >= MAX_TEXTURE_SLOTS) {
+ if (data_->textureSlotIndex >= MAX_TEXTURE_SLOTS) {
flush();
}
- s_batchData->textureSlots[s_batchData->textureSlotIndex] = textureId;
- texIndex = static_cast<f32>(s_batchData->textureSlotIndex);
- s_batchData->textureSlotIndex++;
+ data_->textureSlots[data_->textureSlotIndex] = textureId;
+ texIndex = static_cast<f32>(data_->textureSlotIndex);
+ data_->textureSlotIndex++;
}
}
@@ -581,11 +545,11 @@ void BatchRenderer2D::drawQuad(const glm::vec3& position, const glm::vec2& size,
vertex.color = color;
vertex.texCoord = QUAD_TEX_COORDS[i];
vertex.texIndex = texIndex;
- s_batchData->vertices.push_back(vertex);
+ data_->vertices.push_back(vertex);
}
- s_batchData->indexCount += 6;
- s_batchData->quadCount++;
+ data_->indexCount += 6;
+ data_->quadCount++;
}
void BatchRenderer2D::drawQuad(const glm::vec2& position, const glm::vec2& size,
@@ -601,7 +565,7 @@ void BatchRenderer2D::drawRotatedQuad(const glm::vec2& position, const glm::vec2
void BatchRenderer2D::drawRotatedQuad(const glm::vec2& position, const glm::vec2& size,
f32 rotation, u32 textureId, const glm::vec4& tintColor) {
// Check if batch is full
- if (s_batchData->vertices.size() >= MAX_VERTICES) {
+ if (data_->vertices.size() >= MAX_VERTICES) {
flush();
}
@@ -609,20 +573,20 @@ void BatchRenderer2D::drawRotatedQuad(const glm::vec2& position, const glm::vec2
f32 texIndex = 0.0f;
if (textureId != 0) {
bool found = false;
- for (u32 i = 0; i < s_batchData->textureSlotIndex; ++i) {
- if (s_batchData->textureSlots[i] == textureId) {
+ for (u32 i = 0; i < data_->textureSlotIndex; ++i) {
+ if (data_->textureSlots[i] == textureId) {
texIndex = static_cast<f32>(i);
found = true;
break;
}
}
if (!found) {
- if (s_batchData->textureSlotIndex >= MAX_TEXTURE_SLOTS) {
+ if (data_->textureSlotIndex >= MAX_TEXTURE_SLOTS) {
flush();
}
- s_batchData->textureSlots[s_batchData->textureSlotIndex] = textureId;
- texIndex = static_cast<f32>(s_batchData->textureSlotIndex);
- s_batchData->textureSlotIndex++;
+ data_->textureSlots[data_->textureSlotIndex] = textureId;
+ texIndex = static_cast<f32>(data_->textureSlotIndex);
+ data_->textureSlotIndex++;
}
}
@@ -638,23 +602,23 @@ void BatchRenderer2D::drawRotatedQuad(const glm::vec2& position, const glm::vec2
vertex.color = tintColor;
vertex.texCoord = QUAD_TEX_COORDS[i];
vertex.texIndex = texIndex;
- s_batchData->vertices.push_back(vertex);
+ data_->vertices.push_back(vertex);
}
- s_batchData->indexCount += 6;
- s_batchData->quadCount++;
+ data_->indexCount += 6;
+ data_->quadCount++;
}
void BatchRenderer2D::setProjection(const glm::mat4& projection) {
- s_batchData->projection = projection;
+ data_->projection = projection;
}
-u32 BatchRenderer2D::getDrawCallCount() {
- return s_batchData ? s_batchData->drawCallCount : 0;
+u32 BatchRenderer2D::getDrawCallCount() const {
+ return data_ ? data_->drawCallCount : 0;
}
-u32 BatchRenderer2D::getQuadCount() {
- return s_batchData ? s_batchData->quadCount : 0;
+u32 BatchRenderer2D::getQuadCount() const {
+ return data_ ? data_->quadCount : 0;
}
} // namespace esengine
diff --git a/src/esengine/renderer/Renderer.hpp b/src/esengine/renderer/Renderer.hpp
index b9728deb0..3e8470e2d 100644
--- a/src/esengine/renderer/Renderer.hpp
+++ b/src/esengine/renderer/Renderer.hpp
@@ -5,9 +5,9 @@
* batched 2D sprite rendering (BatchRenderer2D) for WebGL/OpenGL ES.
*
* @author ESEngine Team
- * @date 2025
+ * @date 2026
*
- * @copyright Copyright (c) 2025 ESEngine Team
+ * @copyright Copyright (c) 2026 ESEngine Team
* Licensed under the MIT License.
*/
#pragma once
@@ -22,6 +22,13 @@
#include "Buffer.hpp"
#include "Shader.hpp"
#include "Texture.hpp"
+#include "RenderContext.hpp"
+#include "../resource/Handle.hpp"
+
+// Forward declaration
+namespace esengine::resource {
+ class ResourceManager;
+}
namespace esengine {
@@ -29,67 +36,58 @@ namespace esengine {
// Renderer Statistics
// =============================================================================
-/**
- * @brief Statistics for rendering performance analysis
- *
- * @details Tracks draw calls and geometry counts per frame.
- * Use Renderer::getStats() to retrieve current values.
- */
-struct RendererStats {
- /** @brief Number of draw calls this frame */
- u32 drawCalls = 0;
- /** @brief Number of triangles rendered this frame */
- u32 triangleCount = 0;
- /** @brief Number of vertices processed this frame */
- u32 vertexCount = 0;
-
- /** @brief Resets all counters to zero */
- void reset() {
- drawCalls = 0;
- triangleCount = 0;
- vertexCount = 0;
- }
-};
+using RendererStats = RenderContextStats;
// =============================================================================
// Renderer Class
// =============================================================================
/**
- * @brief Static renderer for immediate-mode drawing
+ * @brief Instance-based renderer for 2D drawing
*
- * @details Provides low-level rendering operations and a simple 2D quad
- * drawing API. For performance-critical sprite rendering, prefer
- * BatchRenderer2D.
+ * @details Provides immediate-mode 2D rendering with dependency injection.
+ * Requires a RenderContext for shared resources and state.
*
* @code
- * // Initialization (called by Application)
- * Renderer::init();
+ * RenderContext context;
+ * context.init();
+ *
+ * Renderer renderer(context);
*
* // Frame rendering
- * Renderer::beginFrame();
- * Renderer::clear();
- * Renderer::beginScene(camera.getViewProjection());
+ * renderer.beginFrame();
+ * renderer.clear();
+ * renderer.beginScene(camera.getViewProjection());
*
- * Renderer::drawQuad({100, 100}, {50, 50}, {1, 0, 0, 1}); // Red quad
+ * renderer.drawQuad({100, 100}, {50, 50}, {1, 0, 0, 1}); // Red quad
*
- * Renderer::endScene();
- * Renderer::endFrame();
+ * renderer.endScene();
+ * renderer.endFrame();
* @endcode
*/
class Renderer {
public:
- /** @brief Initializes the renderer (call once at startup) */
- static void init();
+ /**
+ * @brief Constructs a renderer with the given context
+ * @param context Reference to the rendering context
+ */
+ explicit Renderer(RenderContext& context);
+
+ ~Renderer() = default;
- /** @brief Shuts down the renderer and releases resources */
- static void shutdown();
+ // Non-copyable
+ Renderer(const Renderer&) = delete;
+ Renderer& operator=(const Renderer&) = delete;
+
+ // =========================================================================
+ // Frame Management
+ // =========================================================================
/** @brief Begins a new frame */
- static void beginFrame();
+ void beginFrame();
/** @brief Ends the current frame */
- static void endFrame();
+ void endFrame();
// =========================================================================
// Viewport and Clearing
@@ -102,16 +100,16 @@ public:
* @param width Viewport width in pixels
* @param height Viewport height in pixels
*/
- static void setViewport(i32 x, i32 y, u32 width, u32 height);
+ void setViewport(i32 x, i32 y, u32 width, u32 height);
/**
* @brief Sets the clear color for subsequent clear() calls
* @param color RGBA color (0-1 range)
*/
- static void setClearColor(const glm::vec4& color);
+ void setClearColor(const glm::vec4& color);
/** @brief Clears the color and depth buffers */
- static void clear();
+ void clear();
// =========================================================================
// Scene Management
@@ -121,10 +119,10 @@ public:
* @brief Begins a scene with the given camera transform
* @param viewProjection Combined view-projection matrix
*/
- static void beginScene(const glm::mat4& viewProjection);
+ void beginScene(const glm::mat4& viewProjection);
/** @brief Ends the current scene */
- static void endScene();
+ void endScene();
// =========================================================================
// Draw Submission
@@ -136,9 +134,9 @@ public:
* @param vao The vertex array containing geometry
* @param transform Model transform matrix (defaults to identity)
*/
- static void submit(const Shader& shader,
- const VertexArray& vao,
- const glm::mat4& transform = glm::mat4(1.0f));
+ void submit(const Shader& shader,
+ const VertexArray& vao,
+ const glm::mat4& transform = glm::mat4(1.0f));
// =========================================================================
// 2D Rendering Helpers
@@ -150,8 +148,17 @@ public:
* @param size Width and height
* @param color RGBA color
*/
- static void drawQuad(const glm::vec2& position, const glm::vec2& size,
- const glm::vec4& color);
+ void drawQuad(const glm::vec2& position, const glm::vec2& size,
+ const glm::vec4& color);
+
+ /**
+ * @brief Draws a colored quad at a 3D position
+ * @param position Center position (x, y, z)
+ * @param size Width and height
+ * @param color RGBA color
+ */
+ void drawQuad(const glm::vec3& position, const glm::vec2& size,
+ const glm::vec4& color);
/**
* @brief Draws a textured quad at a 2D position
@@ -160,27 +167,30 @@ public:
* @param texture Texture to apply
* @param tintColor Optional color tint (defaults to white)
*/
- static void drawQuad(const glm::vec2& position, const glm::vec2& size,
- const Texture& texture, const glm::vec4& tintColor = glm::vec4(1.0f));
+ void drawQuad(const glm::vec2& position, const glm::vec2& size,
+ const Texture& texture, const glm::vec4& tintColor = glm::vec4(1.0f));
/**
- * @brief Draws a colored quad at a 3D position
+ * @brief Draws a textured quad at a 3D position
* @param position Center position (x, y, z)
* @param size Width and height
- * @param color RGBA color
+ * @param texture Texture to apply
+ * @param tintColor Optional color tint (defaults to white)
*/
- static void drawQuad(const glm::vec3& position, const glm::vec2& size,
- const glm::vec4& color);
+ void drawQuad(const glm::vec3& position, const glm::vec2& size,
+ const Texture& texture, const glm::vec4& tintColor = glm::vec4(1.0f));
/**
- * @brief Draws a textured quad at a 3D position
- * @param position Center position (x, y, z)
+ * @brief Draws a textured quad using a texture handle
+ * @param position Center position (x, y)
* @param size Width and height
- * @param texture Texture to apply
+ * @param texture Texture handle
+ * @param rm Resource manager to resolve the handle
* @param tintColor Optional color tint (defaults to white)
*/
- static void drawQuad(const glm::vec3& position, const glm::vec2& size,
- const Texture& texture, const glm::vec4& tintColor = glm::vec4(1.0f));
+ void drawQuad(const glm::vec2& position, const glm::vec2& size,
+ resource::TextureHandle texture, resource::ResourceManager& rm,
+ const glm::vec4& tintColor = glm::vec4(1.0f));
// =========================================================================
// Statistics
@@ -190,14 +200,23 @@ public:
* @brief Gets the current frame's rendering statistics
* @return RendererStats with draw call and geometry counts
*/
- static RendererStats getStats();
+ RendererStats getStats() const;
+
+ /** @brief Resets statistics counters */
+ void resetStats();
+
+ // =========================================================================
+ // Context Access
+ // =========================================================================
- /** @brief Resets statistics counters (call at frame start) */
- static void resetStats();
+ /**
+ * @brief Gets the rendering context
+ * @return Reference to the context
+ */
+ RenderContext& getContext() { return context_; }
private:
- static void initQuadData();
- static void flushBatch();
+ RenderContext& context_;
};
// =============================================================================
@@ -209,38 +228,56 @@ private:
*
* @details Batches multiple quads into single draw calls for optimal
* performance. Supports textured and colored quads with rotation.
+ * Now uses RenderContext for shared state.
*
* @code
- * BatchRenderer2D::init();
- * BatchRenderer2D::setProjection(orthoMatrix);
+ * BatchRenderer2D batch(context);
+ * batch.setProjection(orthoMatrix);
*
- * BatchRenderer2D::beginBatch();
+ * batch.beginBatch();
* for (auto& sprite : sprites) {
- * BatchRenderer2D::drawQuad(sprite.pos, sprite.size, sprite.textureId);
+ * batch.drawQuad(sprite.pos, sprite.size, sprite.textureId);
* }
- * BatchRenderer2D::endBatch();
- * BatchRenderer2D::flush();
+ * batch.endBatch();
+ * batch.flush();
* @endcode
- *
- * @note The batch is automatically flushed when full or when texture
- * slots are exhausted.
*/
class BatchRenderer2D {
public:
- /** @brief Initializes the batch renderer */
- static void init();
+ /**
+ * @brief Constructs a batch renderer with the given context
+ * @param context Reference to the rendering context
+ */
+ explicit BatchRenderer2D(RenderContext& context);
+
+ ~BatchRenderer2D();
+
+ // Non-copyable
+ BatchRenderer2D(const BatchRenderer2D&) = delete;
+ BatchRenderer2D& operator=(const BatchRenderer2D&) = delete;
+
+ // =========================================================================
+ // Lifecycle
+ // =========================================================================
- /** @brief Shuts down and releases batch renderer resources */
- static void shutdown();
+ /** @brief Initializes batch rendering resources */
+ void init();
+
+ /** @brief Shuts down and releases resources */
+ void shutdown();
+
+ // =========================================================================
+ // Batch Operations
+ // =========================================================================
/** @brief Begins a new batch */
- static void beginBatch();
+ void beginBatch();
/** @brief Ends the current batch (prepares for flush) */
- static void endBatch();
+ void endBatch();
/** @brief Flushes the batch to the GPU (issues draw call) */
- static void flush();
+ void flush();
// =========================================================================
// Textured Quads
@@ -253,8 +290,8 @@ public:
* @param textureId GPU texture handle
* @param color Color tint (defaults to white)
*/
- static void drawQuad(const glm::vec2& position, const glm::vec2& size,
- u32 textureId, const glm::vec4& color = glm::vec4(1.0f));
+ void drawQuad(const glm::vec2& position, const glm::vec2& size,
+ u32 textureId, const glm::vec4& color = glm::vec4(1.0f));
/**
* @brief Draws a textured quad at a 3D position
@@ -263,8 +300,8 @@ public:
* @param textureId GPU texture handle
* @param color Color tint (defaults to white)
*/
- static void drawQuad(const glm::vec3& position, const glm::vec2& size,
- u32 textureId, const glm::vec4& color = glm::vec4(1.0f));
+ void drawQuad(const glm::vec3& position, const glm::vec2& size,
+ u32 textureId, const glm::vec4& color = glm::vec4(1.0f));
// =========================================================================
// Colored Quads
@@ -276,8 +313,8 @@ public:
* @param size Width and height
* @param color RGBA color
*/
- static void drawQuad(const glm::vec2& position, const glm::vec2& size,
- const glm::vec4& color);
+ void drawQuad(const glm::vec2& position, const glm::vec2& size,
+ const glm::vec4& color);
// =========================================================================
// Rotated Quads
@@ -290,8 +327,8 @@ public:
* @param rotation Rotation angle in radians
* @param color RGBA color
*/
- static void drawRotatedQuad(const glm::vec2& position, const glm::vec2& size,
- f32 rotation, const glm::vec4& color);
+ void drawRotatedQuad(const glm::vec2& position, const glm::vec2& size,
+ f32 rotation, const glm::vec4& color);
/**
* @brief Draws a rotated textured quad
@@ -301,9 +338,9 @@ public:
* @param textureId GPU texture handle
* @param tintColor Color tint (defaults to white)
*/
- static void drawRotatedQuad(const glm::vec2& position, const glm::vec2& size,
- f32 rotation, u32 textureId,
- const glm::vec4& tintColor = glm::vec4(1.0f));
+ void drawRotatedQuad(const glm::vec2& position, const glm::vec2& size,
+ f32 rotation, u32 textureId,
+ const glm::vec4& tintColor = glm::vec4(1.0f));
// =========================================================================
// Configuration
@@ -313,17 +350,22 @@ public:
* @brief Sets the projection matrix for 2D rendering
* @param projection Orthographic projection matrix
*/
- static void setProjection(const glm::mat4& projection);
+ void setProjection(const glm::mat4& projection);
// =========================================================================
// Statistics
// =========================================================================
/** @brief Gets the number of draw calls in the current/last frame */
- static u32 getDrawCallCount();
+ u32 getDrawCallCount() const;
/** @brief Gets the number of quads rendered in the current/last frame */
- static u32 getQuadCount();
+ u32 getQuadCount() const;
+
+private:
+ struct BatchData;
+ Unique<BatchData> data_;
+ RenderContext& context_;
};
} // namespace esengine
diff --git a/src/esengine/renderer/Shader.cpp b/src/esengine/renderer/Shader.cpp
index 3b662d24f..43e90319d 100644
--- a/src/esengine/renderer/Shader.cpp
+++ b/src/esengine/renderer/Shader.cpp
@@ -1,3 +1,15 @@
+/**
+ * @file Shader.cpp
+ * @brief Shader program implementation for OpenGL/WebGL
+ * @details Implements shader compilation, linking, and uniform management.
+ *
+ * @author ESEngine Team
+ * @date 2025
+ *
+ * @copyright Copyright (c) 2025 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
#include "Shader.hpp"
#include "../core/Log.hpp"
diff --git a/src/esengine/renderer/Texture.cpp b/src/esengine/renderer/Texture.cpp
index e8213eb2d..6a9233800 100644
--- a/src/esengine/renderer/Texture.cpp
+++ b/src/esengine/renderer/Texture.cpp
@@ -1,5 +1,19 @@
+/**
+ * @file Texture.cpp
+ * @brief Texture implementation for OpenGL/WebGL
+ * @details Implements texture creation, loading (via stb_image), and management.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
#include "Texture.hpp"
#include "../core/Log.hpp"
+
+#include <span>
#include <stb_image.h>
#ifdef ES_PLATFORM_WEB
@@ -111,12 +125,16 @@ Unique<Texture> Texture::create(const TextureSpecification& spec) {
return texture;
}
-Unique<Texture> Texture::create(u32 width, u32 height, const std::vector<u8>& pixels, TextureFormat format) {
+Unique<Texture> Texture::create(u32 width, u32 height, std::span<const u8> pixels, TextureFormat format) {
[[maybe_unused]] u32 expectedSize = width * height * (format == TextureFormat::RGBA8 ? 4 : 3);
ES_ASSERT(pixels.size() == expectedSize, "Pixel data size mismatch");
return createRaw(width, height, pixels.data(), format);
}
+Unique<Texture> Texture::create(u32 width, u32 height, const std::vector<u8>& pixels, TextureFormat format) {
+ return create(width, height, std::span<const u8>(pixels), format);
+}
+
Unique<Texture> Texture::createRaw(u32 width, u32 height, const void* data, TextureFormat format) {
TextureSpecification spec;
spec.width = width;
@@ -234,12 +252,16 @@ void Texture::unbind() const {
#endif
}
-void Texture::setData(const std::vector<u8>& pixels) {
+void Texture::setData(std::span<const u8> pixels) {
[[maybe_unused]] u32 expectedSize = width_ * height_ * (format_ == TextureFormat::RGBA8 ? 4 : 3);
ES_ASSERT(pixels.size() == expectedSize, "Pixel data size mismatch");
setDataRaw(pixels.data(), static_cast<u32>(pixels.size()));
}
+void Texture::setData(const std::vector<u8>& pixels) {
+ setData(std::span<const u8>(pixels));
+}
+
void Texture::setDataRaw(const void* data, u32 sizeBytes) {
#ifdef ES_PLATFORM_WEB
[[maybe_unused]] u32 bpp = (format_ == TextureFormat::RGBA8) ? 4 : 3;
diff --git a/src/esengine/renderer/Texture.hpp b/src/esengine/renderer/Texture.hpp
index caad9aa07..b5da5012a 100644
--- a/src/esengine/renderer/Texture.hpp
+++ b/src/esengine/renderer/Texture.hpp
@@ -5,9 +5,9 @@
* including creation, binding, and pixel data management.
*
* @author ESEngine Team
- * @date 2025
+ * @date 2026
*
- * @copyright Copyright (c) 2025 ESEngine Team
+ * @copyright Copyright (c) 2026 ESEngine Team
* Licensed under the MIT License.
*/
#pragma once
@@ -20,6 +20,7 @@
#include "../core/Types.hpp"
// Standard library
+#include <span>
#include <string>
#include <vector>
@@ -115,7 +116,7 @@ struct TextureSpecification {
*
* // Create from pixel data
* std::vector<u8> pixels = {...}; // RGBA data
- * auto texture = Texture::create(64, 64, pixels);
+ * auto texture = Texture::create(64, 64, std::span(pixels));
*
* // Bind for rendering
* texture->bind(0); // Bind to texture unit 0
@@ -147,26 +148,26 @@ public:
static Unique<Texture> create(const TextureSpecification& spec);
/**
- * @brief Creates a texture from pixel vector
+ * @brief Creates a texture from a span of pixel data
* @param width Texture width in pixels
* @param height Texture height in pixels
* @param pixels Pixel data (size must match width*height*channels)
* @param format Pixel format (default RGBA8)
* @return Unique pointer to the texture
*/
- static Unique<Texture> create(u32 width, u32 height, const std::vector<u8>& pixels,
+ static Unique<Texture> create(u32 width, u32 height, std::span<const u8> pixels,
TextureFormat format = TextureFormat::RGBA8);
/**
- * @brief Creates a texture from raw pixel pointer
+ * @brief Creates a texture from pixel vector
* @param width Texture width in pixels
* @param height Texture height in pixels
- * @param data Pointer to pixel data
+ * @param pixels Pixel data (size must match width*height*channels)
* @param format Pixel format (default RGBA8)
* @return Unique pointer to the texture
*/
- static Unique<Texture> createRaw(u32 width, u32 height, const void* data,
- TextureFormat format = TextureFormat::RGBA8);
+ static Unique<Texture> create(u32 width, u32 height, const std::vector<u8>& pixels,
+ TextureFormat format = TextureFormat::RGBA8);
/**
* @brief Creates a texture from an image file
@@ -191,17 +192,16 @@ public:
void unbind() const;
/**
- * @brief Updates texture pixel data from vector
+ * @brief Updates texture pixel data from span
* @param pixels New pixel data
*/
- void setData(const std::vector<u8>& pixels);
+ void setData(std::span<const u8> pixels);
/**
- * @brief Updates texture pixel data from raw pointer
- * @param data Pointer to pixel data
- * @param sizeBytes Size of data in bytes
+ * @brief Updates texture pixel data from vector
+ * @param pixels New pixel data
*/
- void setDataRaw(const void* data, u32 sizeBytes);
+ void setData(const std::vector<u8>& pixels);
// =========================================================================
// Properties
@@ -228,6 +228,28 @@ public:
return textureId_ == other.textureId_;
}
+ // =========================================================================
+ // Raw API for internal use only
+ // =========================================================================
+
+ /**
+ * @brief Creates a texture from raw pixel pointer (internal use)
+ * @param width Texture width in pixels
+ * @param height Texture height in pixels
+ * @param data Pointer to pixel data
+ * @param format Pixel format (default RGBA8)
+ * @return Unique pointer to the texture
+ */
+ static Unique<Texture> createRaw(u32 width, u32 height, const void* data,
+ TextureFormat format = TextureFormat::RGBA8);
+
+ /**
+ * @brief Updates texture pixel data from raw pointer (internal use)
+ * @param data Pointer to pixel data
+ * @param sizeBytes Size of data in bytes
+ */
+ void setDataRaw(const void* data, u32 sizeBytes);
+
private:
/**
* @brief Initializes the texture on GPU
diff --git a/src/esengine/resource/Handle.hpp b/src/esengine/resource/Handle.hpp
new file mode 100644
index 000000000..f21d048bf
--- /dev/null
+++ b/src/esengine/resource/Handle.hpp
@@ -0,0 +1,127 @@
+/**
+ * @file Handle.hpp
+ * @brief Type-safe resource handle system
+ * @details Provides lightweight, type-safe handles for referencing GPU
+ * resources without exposing raw pointers or ownership semantics.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+#pragma once
+
+// =============================================================================
+// Includes
+// =============================================================================
+
+// Project includes
+#include "../core/Types.hpp"
+
+// Standard library
+#include <limits>
+
+namespace esengine::resource {
+
+// =============================================================================
+// Handle Template
+// =============================================================================
+
+/**
+ * @brief Type-safe resource handle
+ *
+ * @details Lightweight identifier for resources stored in ResourcePool.
+ * Handles are copyable and comparable, but do not manage resource
+ * lifetime - use ResourceManager for acquire/release.
+ *
+ * @tparam T The resource type this handle references
+ *
+ * @code
+ * ShaderHandle shader = resourceManager.loadShader("vert.glsl", "frag.glsl");
+ * if (shader.isValid()) {
+ * Shader* ptr = resourceManager.getShader(shader);
+ * }
+ * @endcode
+ */
+template<typename T>
+class Handle {
+public:
+ using IdType = u32;
+ static constexpr IdType INVALID = std::numeric_limits<IdType>::max();
+
+ /** @brief Creates an invalid handle */
+ Handle() = default;
+
+ /**
+ * @brief Creates a handle with the given ID
+ * @param id The resource identifier
+ */
+ explicit Handle(IdType id) : id_(id) {}
+
+ /** @brief Checks if the handle references a valid resource */
+ bool isValid() const { return id_ != INVALID; }
+
+ /** @brief Gets the raw identifier */
+ IdType id() const { return id_; }
+
+ /** @brief Equality comparison */
+ bool operator==(const Handle& other) const { return id_ == other.id_; }
+
+ /** @brief Inequality comparison */
+ bool operator!=(const Handle& other) const { return id_ != other.id_; }
+
+ /** @brief Explicit bool conversion (true if valid) */
+ explicit operator bool() const { return isValid(); }
+
+private:
+ IdType id_ = INVALID;
+};
+
+} // namespace esengine::resource
+
+// =============================================================================
+// Forward Declarations
+// =============================================================================
+
+namespace esengine {
+ class Shader;
+ class Texture;
+ class VertexBuffer;
+ class IndexBuffer;
+}
+
+// =============================================================================
+// Handle Type Aliases
+// =============================================================================
+
+namespace esengine::resource {
+
+/** @brief Handle to a shader resource */
+using ShaderHandle = Handle<esengine::Shader>;
+
+/** @brief Handle to a texture resource */
+using TextureHandle = Handle<esengine::Texture>;
+
+/** @brief Handle to a vertex buffer resource */
+using VertexBufferHandle = Handle<esengine::VertexBuffer>;
+
+/** @brief Handle to an index buffer resource */
+using IndexBufferHandle = Handle<esengine::IndexBuffer>;
+
+} // namespace esengine::resource
+
+// =============================================================================
+// Std Hash Support
+// =============================================================================
+
+namespace std {
+
+template<typename T>
+struct hash<esengine::resource::Handle<T>> {
+ size_t operator()(const esengine::resource::Handle<T>& handle) const noexcept {
+ return hash<esengine::u32>{}(handle.id());
+ }
+};
+
+} // namespace std
diff --git a/src/esengine/resource/Resource.hpp b/src/esengine/resource/Resource.hpp
new file mode 100644
index 000000000..77a1a8763
--- /dev/null
+++ b/src/esengine/resource/Resource.hpp
@@ -0,0 +1,15 @@
+/**
+ * @file Resource.hpp
+ * @brief Aggregate header for resource management system
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+#pragma once
+
+#include "Handle.hpp"
+#include "ResourcePool.hpp"
+#include "ResourceManager.hpp"
diff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cpp
new file mode 100644
index 000000000..6bf8daf57
--- /dev/null
+++ b/src/esengine/resource/ResourceManager.cpp
@@ -0,0 +1,236 @@
+/**
+ * @file ResourceManager.cpp
+ * @brief Central resource management system implementation
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+#include "ResourceManager.hpp"
+#include "../core/Log.hpp"
+#include "../renderer/Shader.hpp"
+#include "../renderer/Texture.hpp"
+#include "../renderer/Buffer.hpp"
+
+namespace esengine::resource {
+
+void ResourceManager::init() {
+ if (initialized_) {
+ ES_LOG_WARN("ResourceManager already initialized");
+ return;
+ }
+
+ stats_ = {};
+ initialized_ = true;
+ ES_LOG_INFO("ResourceManager initialized");
+}
+
+void ResourceManager::shutdown() {
+ if (!initialized_) {
+ return;
+ }
+
+ ES_LOG_INFO("ResourceManager shutting down (shaders: {}, textures: {}, vbos: {}, ibos: {})",
+ shaders_.size(), textures_.size(), vertexBuffers_.size(), indexBuffers_.size());
+
+ shaders_.clear();
+ textures_.clear();
+ vertexBuffers_.clear();
+ indexBuffers_.clear();
+
+ initialized_ = false;
+ ES_LOG_INFO("ResourceManager shutdown complete");
+}
+
+// =============================================================================
+// Shader Resources
+// =============================================================================
+
+ShaderHandle ResourceManager::createShader(const std::string& vertSrc, const std::string& fragSrc) {
+ auto shader = Shader::create(vertSrc, fragSrc);
+ if (!shader) {
+ ES_LOG_ERROR("Failed to create shader from source");
+ return ShaderHandle();
+ }
+ return shaders_.add(std::move(shader));
+}
+
+ShaderHandle ResourceManager::loadShader(const std::string& vertPath, const std::string& fragPath) {
+ // Create cache key from paths
+ std::string cacheKey = vertPath + ":" + fragPath;
+
+ // Check cache
+ auto cached = shaders_.findByPath(cacheKey);
+ if (cached.isValid()) {
+ shaders_.addRef(cached);
+ stats_.cacheHits++;
+ return cached;
+ }
+
+ // Load from files
+ auto shader = Shader::createFromFile(vertPath, fragPath);
+ if (!shader) {
+ stats_.cacheMisses++;
+ return ShaderHandle();
+ }
+
+ stats_.cacheMisses++;
+ return shaders_.add(std::move(shader), cacheKey);
+}
+
+Shader* ResourceManager::getShader(ShaderHandle handle) {
+ return shaders_.get(handle);
+}
+
+const Shader* ResourceManager::getShader(ShaderHandle handle) const {
+ return shaders_.get(handle);
+}
+
+void ResourceManager::releaseShader(ShaderHandle handle) {
+ if (handle.isValid()) {
+ shaders_.release(handle.id());
+ }
+}
+
+// =============================================================================
+// Texture Resources
+// =============================================================================
+
+TextureHandle ResourceManager::createTexture(const TextureSpecification& spec) {
+ auto texture = Texture::create(spec);
+ if (!texture) {
+ ES_LOG_ERROR("Failed to create texture from spec");
+ return TextureHandle();
+ }
+ return textures_.add(std::move(texture));
+}
+
+TextureHandle ResourceManager::createTexture(u32 width, u32 height, ConstSpan<u8> pixels,
+ TextureFormat format) {
+ std::vector<u8> pixelVec(pixels.begin(), pixels.end());
+ auto texture = Texture::create(width, height, pixelVec, format);
+ if (!texture) {
+ ES_LOG_ERROR("Failed to create texture from pixels");
+ return TextureHandle();
+ }
+ return textures_.add(std::move(texture));
+}
+
+TextureHandle ResourceManager::loadTexture(const std::string& path) {
+ // Check cache
+ auto cached = textures_.findByPath(path);
+ if (cached.isValid()) {
+ textures_.addRef(cached);
+ stats_.cacheHits++;
+ return cached;
+ }
+
+ // Load from file
+ auto texture = Texture::createFromFile(path);
+ if (!texture) {
+ stats_.cacheMisses++;
+ return TextureHandle();
+ }
+
+ stats_.cacheMisses++;
+ return textures_.add(std::move(texture), path);
+}
+
+Texture* ResourceManager::getTexture(TextureHandle handle) {
+ return textures_.get(handle);
+}
+
+const Texture* ResourceManager::getTexture(TextureHandle handle) const {
+ return textures_.get(handle);
+}
+
+void ResourceManager::releaseTexture(TextureHandle handle) {
+ if (handle.isValid()) {
+ textures_.release(handle.id());
+ }
+}
+
+// =============================================================================
+// Vertex Buffer Resources
+// =============================================================================
+
+VertexBufferHandle ResourceManager::createVertexBuffer(u32 sizeBytes) {
+ auto buffer = VertexBuffer::create(sizeBytes);
+ if (!buffer) {
+ ES_LOG_ERROR("Failed to create dynamic vertex buffer");
+ return VertexBufferHandle();
+ }
+ return vertexBuffers_.add(std::move(buffer));
+}
+
+VertexBuffer* ResourceManager::getVertexBuffer(VertexBufferHandle handle) {
+ return vertexBuffers_.get(handle);
+}
+
+const VertexBuffer* ResourceManager::getVertexBuffer(VertexBufferHandle handle) const {
+ return vertexBuffers_.get(handle);
+}
+
+void ResourceManager::releaseVertexBuffer(VertexBufferHandle handle) {
+ if (handle.isValid()) {
+ vertexBuffers_.release(handle.id());
+ }
+}
+
+// =============================================================================
+// Index Buffer Resources
+// =============================================================================
+
+IndexBufferHandle ResourceManager::createIndexBuffer(ConstSpan<u32> indices) {
+ auto buffer = IndexBuffer::create(indices.data(), static_cast<u32>(indices.size()));
+ if (!buffer) {
+ ES_LOG_ERROR("Failed to create index buffer (u32)");
+ return IndexBufferHandle();
+ }
+ return indexBuffers_.add(std::move(buffer));
+}
+
+IndexBufferHandle ResourceManager::createIndexBuffer(ConstSpan<u16> indices) {
+ auto buffer = IndexBuffer::create(indices.data(), static_cast<u32>(indices.size()));
+ if (!buffer) {
+ ES_LOG_ERROR("Failed to create index buffer (u16)");
+ return IndexBufferHandle();
+ }
+ return indexBuffers_.add(std::move(buffer));
+}
+
+IndexBuffer* ResourceManager::getIndexBuffer(IndexBufferHandle handle) {
+ return indexBuffers_.get(handle);
+}
+
+const IndexBuffer* ResourceManager::getIndexBuffer(IndexBufferHandle handle) const {
+ return indexBuffers_.get(handle);
+}
+
+void ResourceManager::releaseIndexBuffer(IndexBufferHandle handle) {
+ if (handle.isValid()) {
+ indexBuffers_.release(handle.id());
+ }
+}
+
+// =============================================================================
+// Statistics
+// =============================================================================
+
+ResourceStats ResourceManager::getStats() const {
+ stats_.shaderCount = shaders_.size();
+ stats_.textureCount = textures_.size();
+ stats_.vertexBufferCount = vertexBuffers_.size();
+ stats_.indexBufferCount = indexBuffers_.size();
+ return stats_;
+}
+
+void ResourceManager::resetCacheStats() {
+ stats_.cacheHits = 0;
+ stats_.cacheMisses = 0;
+}
+
+} // namespace esengine::resource
diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hpp
new file mode 100644
index 000000000..4a962c832
--- /dev/null
+++ b/src/esengine/resource/ResourceManager.hpp
@@ -0,0 +1,308 @@
+/**
+ * @file ResourceManager.hpp
+ * @brief Central resource management system
+ * @details Provides unified interface for creating, loading, caching, and
+ * releasing GPU resources with automatic deduplication.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+#pragma once
+
+// =============================================================================
+// Includes
+// =============================================================================
+
+// Project includes
+#include "../core/Types.hpp"
+#include "Handle.hpp"
+#include "ResourcePool.hpp"
+#include "../renderer/Shader.hpp"
+#include "../renderer/Texture.hpp"
+#include "../renderer/Buffer.hpp"
+
+// Standard library
+#include <string>
+
+namespace esengine::resource {
+
+// =============================================================================
+// Resource Manager Statistics
+// =============================================================================
+
+/**
+ * @brief Statistics about resource usage
+ */
+struct ResourceStats {
+ usize shaderCount = 0; ///< Number of active shaders
+ usize textureCount = 0; ///< Number of active textures
+ usize vertexBufferCount = 0; ///< Number of active vertex buffers
+ usize indexBufferCount = 0; ///< Number of active index buffers
+ usize cacheHits = 0; ///< Number of cache hits since reset
+ usize cacheMisses = 0; ///< Number of cache misses since reset
+};
+
+// =============================================================================
+// ResourceManager Class
+// =============================================================================
+
+/**
+ * @brief Central manager for GPU resources
+ *
+ * @details Manages the lifecycle of shaders, textures, and buffers.
+ * Provides handle-based access with reference counting and
+ * path-based caching for deduplication.
+ *
+ * @code
+ * ResourceManager rm;
+ * rm.init();
+ *
+ * auto shader = rm.createShader(vertSrc, fragSrc);
+ * auto texture = rm.loadTexture("assets/player.png");
+ *
+ * Shader* shaderPtr = rm.getShader(shader);
+ * Texture* texturePtr = rm.getTexture(texture);
+ *
+ * rm.releaseShader(shader);
+ * rm.releaseTexture(texture);
+ *
+ * rm.shutdown();
+ * @endcode
+ */
+class ResourceManager {
+public:
+ ResourceManager() = default;
+ ~ResourceManager() = default;
+
+ // Non-copyable, movable
+ ResourceManager(const ResourceManager&) = delete;
+ ResourceManager& operator=(const ResourceManager&) = delete;
+ ResourceManager(ResourceManager&&) = default;
+ ResourceManager& operator=(ResourceManager&&) = default;
+
+ // =========================================================================
+ // Lifecycle
+ // =========================================================================
+
+ /**
+ * @brief Initializes the resource manager
+ */
+ void init();
+
+ /**
+ * @brief Shuts down and releases all resources
+ */
+ void shutdown();
+
+ /**
+ * @brief Checks if the manager is initialized
+ * @return True if init() has been called
+ */
+ bool isInitialized() const { return initialized_; }
+
+ // =========================================================================
+ // Shader Resources
+ // =========================================================================
+
+ /**
+ * @brief Creates a shader from source strings
+ * @param vertSrc Vertex shader GLSL source
+ * @param fragSrc Fragment shader GLSL source
+ * @return Handle to the shader, or invalid handle on failure
+ */
+ ShaderHandle createShader(const std::string& vertSrc, const std::string& fragSrc);
+
+ /**
+ * @brief Loads a shader from file paths (with caching)
+ * @param vertPath Path to vertex shader file
+ * @param fragPath Path to fragment shader file
+ * @return Handle to the shader, or invalid handle on failure
+ */
+ ShaderHandle loadShader(const std::string& vertPath, const std::string& fragPath);
+
+ /**
+ * @brief Gets a shader by handle
+ * @param handle The shader handle
+ * @return Pointer to the shader, or nullptr if invalid
+ */
+ Shader* getShader(ShaderHandle handle);
+
+ /**
+ * @brief Gets a shader by handle (const)
+ * @param handle The shader handle
+ * @return Const pointer to the shader, or nullptr if invalid
+ */
+ const Shader* getShader(ShaderHandle handle) const;
+
+ /**
+ * @brief Releases a shader (decrements ref count)
+ * @param handle The shader handle
+ */
+ void releaseShader(ShaderHandle handle);
+
+ // =========================================================================
+ // Texture Resources
+ // =========================================================================
+
+ /**
+ * @brief Creates a texture from specification
+ * @param spec Texture creation parameters
+ * @return Handle to the texture, or invalid handle on failure
+ */
+ TextureHandle createTexture(const TextureSpecification& spec);
+
+ /**
+ * @brief Creates a texture from pixel data
+ * @param width Texture width in pixels
+ * @param height Texture height in pixels
+ * @param pixels Pixel data
+ * @param format Pixel format (default RGBA8)
+ * @return Handle to the texture, or invalid handle on failure
+ */
+ TextureHandle createTexture(u32 width, u32 height, ConstSpan<u8> pixels,
+ TextureFormat format);
+
+ /**
+ * @brief Loads a texture from file (with caching)
+ * @param path Path to the image file
+ * @return Handle to the texture, or invalid handle on failure
+ */
+ TextureHandle loadTexture(const std::string& path);
+
+ /**
+ * @brief Gets a texture by handle
+ * @param handle The texture handle
+ * @return Pointer to the texture, or nullptr if invalid
+ */
+ Texture* getTexture(TextureHandle handle);
+
+ /**
+ * @brief Gets a texture by handle (const)
+ * @param handle The texture handle
+ * @return Const pointer to the texture, or nullptr if invalid
+ */
+ const Texture* getTexture(TextureHandle handle) const;
+
+ /**
+ * @brief Releases a texture (decrements ref count)
+ * @param handle The texture handle
+ */
+ void releaseTexture(TextureHandle handle);
+
+ // =========================================================================
+ // Vertex Buffer Resources
+ // =========================================================================
+
+ /**
+ * @brief Creates a vertex buffer from typed data
+ * @tparam T Vertex type
+ * @param data Span of vertex data
+ * @return Handle to the buffer, or invalid handle on failure
+ */
+ template<typename T>
+ VertexBufferHandle createVertexBuffer(ConstSpan<T> data);
+
+ /**
+ * @brief Creates a dynamic vertex buffer
+ * @param sizeBytes Buffer size in bytes
+ * @return Handle to the buffer, or invalid handle on failure
+ */
+ VertexBufferHandle createVertexBuffer(u32 sizeBytes);
+
+ /**
+ * @brief Gets a vertex buffer by handle
+ * @param handle The buffer handle
+ * @return Pointer to the buffer, or nullptr if invalid
+ */
+ VertexBuffer* getVertexBuffer(VertexBufferHandle handle);
+
+ /**
+ * @brief Gets a vertex buffer by handle (const)
+ * @param handle The buffer handle
+ * @return Const pointer to the buffer, or nullptr if invalid
+ */
+ const VertexBuffer* getVertexBuffer(VertexBufferHandle handle) const;
+
+ /**
+ * @brief Releases a vertex buffer (decrements ref count)
+ * @param handle The buffer handle
+ */
+ void releaseVertexBuffer(VertexBufferHandle handle);
+
+ // =========================================================================
+ // Index Buffer Resources
+ // =========================================================================
+
+ /**
+ * @brief Creates an index buffer from 32-bit indices
+ * @param indices Span of index data
+ * @return Handle to the buffer, or invalid handle on failure
+ */
+ IndexBufferHandle createIndexBuffer(ConstSpan<u32> indices);
+
+ /**
+ * @brief Creates an index buffer from 16-bit indices
+ * @param indices Span of index data
+ * @return Handle to the buffer, or invalid handle on failure
+ */
+ IndexBufferHandle createIndexBuffer(ConstSpan<u16> indices);
+
+ /**
+ * @brief Gets an index buffer by handle
+ * @param handle The buffer handle
+ * @return Pointer to the buffer, or nullptr if invalid
+ */
+ IndexBuffer* getIndexBuffer(IndexBufferHandle handle);
+
+ /**
+ * @brief Gets an index buffer by handle (const)
+ * @param handle The buffer handle
+ * @return Const pointer to the buffer, or nullptr if invalid
+ */
+ const IndexBuffer* getIndexBuffer(IndexBufferHandle handle) const;
+
+ /**
+ * @brief Releases an index buffer (decrements ref count)
+ * @param handle The buffer handle
+ */
+ void releaseIndexBuffer(IndexBufferHandle handle);
+
+ // =========================================================================
+ // Statistics
+ // =========================================================================
+
+ /**
+ * @brief Gets current resource statistics
+ * @return Resource counts and cache statistics
+ */
+ ResourceStats getStats() const;
+
+ /**
+ * @brief Resets cache hit/miss counters
+ */
+ void resetCacheStats();
+
+private:
+ ResourcePool<Shader> shaders_;
+ ResourcePool<Texture> textures_;
+ ResourcePool<VertexBuffer> vertexBuffers_;
+ ResourcePool<IndexBuffer> indexBuffers_;
+ mutable ResourceStats stats_;
+ bool initialized_ = false;
+};
+
+// =============================================================================
+// Template Implementations
+// =============================================================================
+
+template<typename T>
+VertexBufferHandle ResourceManager::createVertexBuffer(ConstSpan<T> data) {
+ auto buffer = VertexBuffer::create(data);
+ if (!buffer) return VertexBufferHandle();
+ return vertexBuffers_.add(std::move(buffer));
+}
+
+} // namespace esengine::resource
diff --git a/src/esengine/resource/ResourcePool.hpp b/src/esengine/resource/ResourcePool.hpp
new file mode 100644
index 000000000..255d771cc
--- /dev/null
+++ b/src/esengine/resource/ResourcePool.hpp
@@ -0,0 +1,226 @@
+/**
+ * @file ResourcePool.hpp
+ * @brief Type-erased resource pool with reference counting
+ * @details Manages collections of GPU resources with handle-based access,
+ * reference counting, and optional path-based caching.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+#pragma once
+
+// =============================================================================
+// Includes
+// =============================================================================
+
+// Project includes
+#include "../core/Types.hpp"
+#include "Handle.hpp"
+
+// Standard library
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+namespace esengine::resource {
+
+// =============================================================================
+// ResourcePoolBase
+// =============================================================================
+
+/**
+ * @brief Abstract base class for resource pools
+ *
+ * @details Provides a type-erased interface for managing resource pools,
+ * allowing ResourceManager to handle different resource types
+ * uniformly.
+ */
+class ResourcePoolBase {
+public:
+ virtual ~ResourcePoolBase() = default;
+
+ /**
+ * @brief Releases a resource by ID
+ * @param id The resource identifier
+ */
+ virtual void release(u32 id) = 0;
+
+ /**
+ * @brief Gets the number of active resources
+ * @return Count of non-freed resources
+ */
+ virtual usize size() const = 0;
+
+ /**
+ * @brief Releases all resources
+ */
+ virtual void clear() = 0;
+};
+
+// =============================================================================
+// ResourcePool Template
+// =============================================================================
+
+/**
+ * @brief Typed resource pool with reference counting
+ *
+ * @details Stores resources in a dense array with a free list for recycling
+ * slots. Supports optional path-based caching for deduplication.
+ *
+ * @tparam T The resource type to manage (must be movable)
+ *
+ * @code
+ * ResourcePool<Shader> shaders;
+ * auto handle = shaders.add(Shader::create(...), "shaders/color.glsl");
+ * Shader* ptr = shaders.get(handle);
+ * shaders.release(handle.id());
+ * @endcode
+ */
+template<typename T>
+class ResourcePool : public ResourcePoolBase {
+public:
+ /**
+ * @brief Entry storing a resource with metadata
+ */
+ struct Entry {
+ Unique<T> resource; ///< The owned resource
+ u32 refCount = 0; ///< Reference count (0 = freed)
+ std::string path; ///< Optional path for caching
+ };
+
+ ResourcePool() = default;
+ ~ResourcePool() override = default;
+
+ // Non-copyable, movable
+ ResourcePool(const ResourcePool&) = delete;
+ ResourcePool& operator=(const ResourcePool&) = delete;
+ ResourcePool(ResourcePool&&) = default;
+ ResourcePool& operator=(ResourcePool&&) = default;
+
+ /**
+ * @brief Adds a resource to the pool
+ * @param resource The resource to add (takes ownership)
+ * @param path Optional path for cache lookup
+ * @return Handle to the added resource
+ */
+ Handle<T> add(Unique<T> resource, const std::string& path = "") {
+ u32 id;
+ if (!freeList_.empty()) {
+ id = freeList_.back();
+ freeList_.pop_back();
+ entries_[id] = {std::move(resource), 1, path};
+ } else {
+ id = static_cast<u32>(entries_.size());
+ entries_.push_back({std::move(resource), 1, path});
+ }
+ if (!path.empty()) {
+ pathToId_[path] = id;
+ }
+ return Handle<T>(id);
+ }
+
+ /**
+ * @brief Gets a resource by handle
+ * @param handle The resource handle
+ * @return Pointer to the resource, or nullptr if invalid
+ */
+ T* get(Handle<T> handle) {
+ if (!handle.isValid() || handle.id() >= entries_.size()) {
+ return nullptr;
+ }
+ auto& entry = entries_[handle.id()];
+ return entry.refCount > 0 ? entry.resource.get() : nullptr;
+ }
+
+ /**
+ * @brief Gets a resource by handle (const)
+ * @param handle The resource handle
+ * @return Const pointer to the resource, or nullptr if invalid
+ */
+ const T* get(Handle<T> handle) const {
+ if (!handle.isValid() || handle.id() >= entries_.size()) {
+ return nullptr;
+ }
+ const auto& entry = entries_[handle.id()];
+ return entry.refCount > 0 ? entry.resource.get() : nullptr;
+ }
+
+ /**
+ * @brief Finds a resource by its cached path
+ * @param path The path to look up
+ * @return Handle to the resource, or invalid handle if not found
+ */
+ Handle<T> findByPath(const std::string& path) const {
+ auto it = pathToId_.find(path);
+ return it != pathToId_.end() ? Handle<T>(it->second) : Handle<T>();
+ }
+
+ /**
+ * @brief Increments the reference count for a resource
+ * @param handle The resource handle
+ */
+ void addRef(Handle<T> handle) {
+ if (handle.isValid() && handle.id() < entries_.size()) {
+ auto& entry = entries_[handle.id()];
+ if (entry.refCount > 0) {
+ entry.refCount++;
+ }
+ }
+ }
+
+ /**
+ * @brief Decrements the reference count and frees if zero
+ * @param id The resource identifier
+ */
+ void release(u32 id) override {
+ if (id < entries_.size() && entries_[id].refCount > 0) {
+ if (--entries_[id].refCount == 0) {
+ if (!entries_[id].path.empty()) {
+ pathToId_.erase(entries_[id].path);
+ }
+ entries_[id].resource.reset();
+ entries_[id].path.clear();
+ freeList_.push_back(id);
+ }
+ }
+ }
+
+ /**
+ * @brief Gets the number of active resources
+ * @return Count of non-freed resources
+ */
+ usize size() const override {
+ return entries_.size() - freeList_.size();
+ }
+
+ /**
+ * @brief Releases all resources
+ */
+ void clear() override {
+ entries_.clear();
+ freeList_.clear();
+ pathToId_.clear();
+ }
+
+ /**
+ * @brief Gets the current reference count for a resource
+ * @param handle The resource handle
+ * @return Reference count, or 0 if invalid
+ */
+ u32 getRefCount(Handle<T> handle) const {
+ if (!handle.isValid() || handle.id() >= entries_.size()) {
+ return 0;
+ }
+ return entries_[handle.id()].refCount;
+ }
+
+private:
+ std::vector<Entry> entries_;
+ std::vector<u32> freeList_;
+ std::unordered_map<std::string, u32> pathToId_;
+};
+
+} // namespace esengine::resource