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(renderer): retire legacy Renderer/BatchRenderer2D; ImmediateDraw on TransientBufferPool (RC5 Batch 5)

esengine2d42d9d726f5
diff --git a/CMakeLists.txt b/CMakeLists.txt
index ea76a133d..6b52d9979 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -40,7 +40,6 @@ set(ESENGINE_SOURCES
src/esengine/resource/ResourceManager.cpp
src/esengine/resource/ShaderParser.cpp
src/esengine/renderer/RenderContext.cpp
- src/esengine/renderer/Renderer.cpp
src/esengine/renderer/Shader.cpp
src/esengine/renderer/Buffer.cpp
src/esengine/renderer/Texture.cpp
@@ -137,7 +136,6 @@ set(ESENGINE_HEADERS
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
src/esengine/renderer/Texture.hpp
diff --git a/src/esengine/ESEngine.hpp b/src/esengine/ESEngine.hpp
index 77df86d88..3550e60f9 100644
--- a/src/esengine/ESEngine.hpp
+++ b/src/esengine/ESEngine.hpp
@@ -42,7 +42,6 @@
#include "renderer/Buffer.hpp"
#include "renderer/Shader.hpp"
#include "renderer/Texture.hpp"
-#include "renderer/Renderer.hpp"
// Platform
#include "platform/Platform.hpp"
diff --git a/src/esengine/core/EstellaContext.cpp b/src/esengine/core/EstellaContext.cpp
index 3fb19518c..eba81a65e 100644
--- a/src/esengine/core/EstellaContext.cpp
+++ b/src/esengine/core/EstellaContext.cpp
@@ -129,7 +129,7 @@ void EstellaContext::initSubsystems() {
auto* rm = services_.getService<resource::ResourceManager>();
auto* rc = services_.getService<RenderContext>();
- auto immediateDraw = makeUnique<ImmediateDraw>(*gfxDevicePtr, *rc, *rm);
+ auto immediateDraw = makeUnique<ImmediateDraw>(*gfxDevicePtr, *statePtr, *rc, *rm);
immediateDraw->init();
services_.registerOwned<ImmediateDraw>(std::move(immediateDraw));
diff --git a/src/esengine/renderer/ImmediateDraw.cpp b/src/esengine/renderer/ImmediateDraw.cpp
index e8b3a1e4f..8cb546355 100644
--- a/src/esengine/renderer/ImmediateDraw.cpp
+++ b/src/esengine/renderer/ImmediateDraw.cpp
@@ -1,6 +1,9 @@
/**
* @file ImmediateDraw.cpp
* @brief Immediate mode 2D drawing implementation
+ * @details Generates BatchVertex geometry into a TransientBufferPool and draws
+ * it through StateTracker + GfxDevice — the same path RenderFrame uses.
+ * Primitives are batched per texture and flushed in submission order.
*
* @author ESEngine Team
* @date 2026
@@ -10,29 +13,39 @@
*/
#include "ImmediateDraw.hpp"
-#include "Renderer.hpp"
#include "GfxDevice.hpp"
+#include "StateTracker.hpp"
#include "RenderContext.hpp"
+#include "Shader.hpp"
+#include "BatchVertex.hpp"
#include "../resource/ResourceManager.hpp"
#include "../core/Log.hpp"
#include <glm/gtc/constants.hpp>
+#include <glm/gtc/type_ptr.hpp>
+#include <array>
#include <cmath>
namespace esengine {
-struct ImmediateDraw::Impl {
- Unique<BatchRenderer2D> batcher;
- glm::mat4 viewProjection{1.0f};
+namespace {
+
+constexpr glm::vec2 QUAD_LOCAL[4] = {
+ {-0.5f, -0.5f}, {0.5f, -0.5f}, {0.5f, 0.5f}, {-0.5f, 0.5f}
+};
+constexpr glm::vec2 QUAD_UV[4] = {
+ {0.0f, 0.0f}, {1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 1.0f}
};
-ImmediateDraw::ImmediateDraw(GfxDevice& device,
- RenderContext& context,
+} // namespace
+
+ImmediateDraw::ImmediateDraw(GfxDevice& device, StateTracker& state, RenderContext& context,
resource::ResourceManager& resource_manager)
- : impl_(makeUnique<Impl>())
- , device_(device)
+ : device_(device)
+ , state_(state)
, context_(context)
- , resource_manager_(resource_manager) {
+ , resource_manager_(resource_manager)
+ , pool_(device) {
}
ImmediateDraw::~ImmediateDraw() {
@@ -44,20 +57,31 @@ ImmediateDraw::~ImmediateDraw() {
void ImmediateDraw::init() {
if (initialized_) return;
- impl_->batcher = makeUnique<BatchRenderer2D>(device_, context_, resource_manager_);
- impl_->batcher->init();
+ pool_.init();
+ white_texture_id_ = context_.getWhiteTextureId();
+
+ auto handle = resource_manager_.createShaderWithBindings(
+ ShaderSources::BATCH_VERTEX,
+ ShaderSources::BATCH_FRAGMENT,
+ {{0, "a_position"}, {1, "a_color"}, {2, "a_texCoord"}}
+ );
+ Shader* shader = resource_manager_.getShader(handle);
+ if (shader && shader->isValid()) {
+ batch_shader_id_ = shader->getProgramId();
+ state_.useProgram(batch_shader_id_);
+ i32 texLoc = device_.getUniformLocation(batch_shader_id_, "u_texture");
+ if (texLoc >= 0) device_.setUniform1i(texLoc, 0);
+ state_.useProgram(0);
+ } else {
+ ES_LOG_ERROR("ImmediateDraw: failed to create batch shader");
+ }
initialized_ = true;
}
void ImmediateDraw::shutdown() {
if (!initialized_) return;
-
- if (impl_->batcher) {
- impl_->batcher->shutdown();
- impl_->batcher.reset();
- }
-
+ pool_.shutdown();
initialized_ = false;
ES_LOG_INFO("ImmediateDraw shutdown");
}
@@ -65,31 +89,94 @@ void ImmediateDraw::shutdown() {
void ImmediateDraw::begin(const glm::mat4& viewProjection) {
if (!initialized_) return;
- device_.setBlendEnabled(true);
- device_.setBlendMode(BlendMode::Normal);
- device_.setDepthTest(false);
-
- impl_->viewProjection = viewProjection;
- impl_->batcher->setProjection(viewProjection);
- impl_->batcher->beginBatch();
+ viewProjection_ = viewProjection;
+ state_.setBlendEnabled(true);
+ state_.setBlendMode(BlendMode::Normal);
+ state_.setDepthTest(false);
+ pool_.beginFrame();
+ currentTexture_ = white_texture_id_;
+ pendingGeometry_ = false;
primitiveCount_ = 0;
+ drawCallCount_ = 0;
inFrame_ = true;
}
+void ImmediateDraw::flush() {
+ if (!initialized_ || !inFrame_ || !pendingGeometry_) return;
+
+ pool_.upload();
+
+ state_.useProgram(batch_shader_id_);
+ i32 loc = device_.getUniformLocation(batch_shader_id_, "u_projection");
+ if (loc >= 0) device_.setUniformMat4(loc, glm::value_ptr(viewProjection_));
+ state_.bindTexture(0, currentTexture_);
+
+ pool_.bindLayout(LayoutId::Batch);
+ device_.drawElements(pool_.indicesUsed(LayoutId::Batch), GfxDataType::UnsignedInt, 0);
+ ++drawCallCount_;
+
+ pool_.beginFrame(); // reset staging for the next batch
+ pendingGeometry_ = false;
+}
+
void ImmediateDraw::end() {
- if (!initialized_ || !inFrame_) return;
+ if (!inFrame_) return;
- impl_->batcher->endBatch();
- device_.setDepthTest(true);
- device_.setBlendMode(BlendMode::Normal);
+ flush();
+ state_.setDepthTest(true);
+ state_.setBlendMode(BlendMode::Normal);
inFrame_ = false;
}
-void ImmediateDraw::flush() {
- if (!initialized_ || !inFrame_) return;
+void ImmediateDraw::useTexture(u32 textureId) {
+ if (textureId != currentTexture_) {
+ if (pendingGeometry_) flush();
+ currentTexture_ = textureId;
+ }
+}
+
+void ImmediateDraw::emitQuad(const glm::vec2& center, const glm::vec2& size, f32 rotation,
+ const glm::vec4& color, u32 textureId,
+ const glm::vec2& uvOffset, const glm::vec2& uvScale) {
+ useTexture(textureId);
+
+ const u32 packed = packColor(color);
+ const f32 cosR = rotation != 0.0f ? std::cos(rotation) : 1.0f;
+ const f32 sinR = rotation != 0.0f ? std::sin(rotation) : 0.0f;
+
+ std::array<BatchVertex, 4> verts{};
+ for (u32 i = 0; i < 4; ++i) {
+ glm::vec2 scaled = QUAD_LOCAL[i] * size;
+ glm::vec2 rotated = rotation != 0.0f
+ ? glm::vec2(scaled.x * cosR - scaled.y * sinR, scaled.x * sinR + scaled.y * cosR)
+ : scaled;
+ verts[i].position = center + rotated;
+ verts[i].color = packed;
+ verts[i].texCoord = QUAD_UV[i] * uvScale + uvOffset;
+ }
- impl_->batcher->flush();
+ u32 base = pool_.appendVertices(LayoutId::Batch, verts.data(), sizeof(verts)) / sizeof(BatchVertex);
+ u32 idx[6] = { base + 0, base + 1, base + 2, base + 2, base + 3, base + 0 };
+ pool_.appendIndices(LayoutId::Batch, idx, 6);
+ pendingGeometry_ = true;
+}
+
+void ImmediateDraw::emitTriangle(const glm::vec2& p0, const glm::vec2& p1, const glm::vec2& p2,
+ const glm::vec4& color) {
+ useTexture(white_texture_id_);
+
+ const u32 packed = packColor(color);
+ std::array<BatchVertex, 3> verts{
+ BatchVertex{ p0, packed, {0.0f, 0.0f} },
+ BatchVertex{ p1, packed, {1.0f, 0.0f} },
+ BatchVertex{ p2, packed, {1.0f, 1.0f} },
+ };
+
+ u32 base = pool_.appendVertices(LayoutId::Batch, verts.data(), sizeof(verts)) / sizeof(BatchVertex);
+ u32 idx[3] = { base + 0, base + 1, base + 2 };
+ pool_.appendIndices(LayoutId::Batch, idx, 3);
+ pendingGeometry_ = true;
}
void ImmediateDraw::line(const glm::vec2& from, const glm::vec2& to,
@@ -102,12 +189,10 @@ void ImmediateDraw::line(const glm::vec2& from, const glm::vec2& to,
glm::vec2 dir = delta / length;
glm::vec2 center = (from + to) * 0.5f;
- glm::vec2 size(length, thickness);
-
f32 angle = std::atan2(dir.y, dir.x);
- impl_->batcher->drawRotatedQuad(center, size, angle, color);
- primitiveCount_++;
+ emitQuad(center, glm::vec2(length, thickness), angle, color, white_texture_id_);
+ ++primitiveCount_;
}
void ImmediateDraw::polyline(std::span<const glm::vec2> vertices,
@@ -117,7 +202,6 @@ void ImmediateDraw::polyline(std::span<const glm::vec2> vertices,
for (size_t i = 0; i < vertices.size() - 1; ++i) {
line(vertices[i], vertices[i + 1], color, thickness);
}
-
if (closed && vertices.size() > 2) {
line(vertices.back(), vertices.front(), color, thickness);
}
@@ -128,8 +212,8 @@ void ImmediateDraw::rect(const glm::vec2& position, const glm::vec2& size,
if (!inFrame_) return;
if (filled) {
- impl_->batcher->drawQuad(position, size, color);
- primitiveCount_++;
+ emitQuad(position, size, 0.0f, color, white_texture_id_);
+ ++primitiveCount_;
} else {
rectOutline(position, size, color, 1.0f);
}
@@ -159,14 +243,12 @@ void ImmediateDraw::circle(const glm::vec2& center, f32 radius,
if (filled) {
for (i32 i = 0; i < segments; ++i) {
- f32 angle1 = static_cast<f32>(i) / static_cast<f32>(segments) * glm::two_pi<f32>();
- f32 angle2 = static_cast<f32>(i + 1) / static_cast<f32>(segments) * glm::two_pi<f32>();
-
- glm::vec2 p1 = center + glm::vec2(std::cos(angle1), std::sin(angle1)) * radius;
- glm::vec2 p2 = center + glm::vec2(std::cos(angle2), std::sin(angle2)) * radius;
-
- impl_->batcher->drawTriangle(center, p1, p2, color);
- primitiveCount_++;
+ f32 a1 = static_cast<f32>(i) / static_cast<f32>(segments) * glm::two_pi<f32>();
+ f32 a2 = static_cast<f32>(i + 1) / static_cast<f32>(segments) * glm::two_pi<f32>();
+ glm::vec2 p1 = center + glm::vec2(std::cos(a1), std::sin(a1)) * radius;
+ glm::vec2 p2 = center + glm::vec2(std::cos(a2), std::sin(a2)) * radius;
+ emitTriangle(center, p1, p2, color);
+ ++primitiveCount_;
}
} else {
circleOutline(center, radius, color, 1.0f, segments);
@@ -178,44 +260,35 @@ void ImmediateDraw::circleOutline(const glm::vec2& center, f32 radius,
if (!inFrame_ || segments < 3) return;
for (i32 i = 0; i < segments; ++i) {
- f32 angle1 = static_cast<f32>(i) / static_cast<f32>(segments) * glm::two_pi<f32>();
- f32 angle2 = static_cast<f32>(i + 1) / static_cast<f32>(segments) * glm::two_pi<f32>();
-
- glm::vec2 p1 = center + glm::vec2(std::cos(angle1), std::sin(angle1)) * radius;
- glm::vec2 p2 = center + glm::vec2(std::cos(angle2), std::sin(angle2)) * radius;
-
+ f32 a1 = static_cast<f32>(i) / static_cast<f32>(segments) * glm::two_pi<f32>();
+ f32 a2 = static_cast<f32>(i + 1) / static_cast<f32>(segments) * glm::two_pi<f32>();
+ glm::vec2 p1 = center + glm::vec2(std::cos(a1), std::sin(a1)) * radius;
+ glm::vec2 p2 = center + glm::vec2(std::cos(a2), std::sin(a2)) * radius;
line(p1, p2, color, thickness);
}
}
-void ImmediateDraw::polygon(std::span<const glm::vec2> vertices,
- const glm::vec4& color) {
+void ImmediateDraw::polygon(std::span<const glm::vec2> vertices, const glm::vec4& color) {
if (!inFrame_ || vertices.size() < 3) return;
for (size_t i = 1; i + 1 < vertices.size(); ++i) {
- impl_->batcher->drawTriangle(vertices[0], vertices[i], vertices[i + 1], color);
- primitiveCount_++;
+ emitTriangle(vertices[0], vertices[i], vertices[i + 1], color);
+ ++primitiveCount_;
}
}
void ImmediateDraw::texture(const glm::vec2& position, const glm::vec2& size,
u32 textureId, const glm::vec4& tint) {
if (!inFrame_) return;
-
- impl_->batcher->drawQuad(position, size, textureId, tint);
- primitiveCount_++;
+ emitQuad(position, size, 0.0f, tint, textureId);
+ ++primitiveCount_;
}
void ImmediateDraw::textureRotated(const glm::vec2& position, const glm::vec2& size,
f32 rotation, u32 textureId, const glm::vec4& tint) {
if (!inFrame_) return;
-
- impl_->batcher->drawRotatedQuad(position, size, rotation, textureId, tint);
- primitiveCount_++;
-}
-
-u32 ImmediateDraw::getDrawCallCount() const {
- return impl_->batcher ? impl_->batcher->getDrawCallCount() : 0;
+ emitQuad(position, size, rotation, tint, textureId);
+ ++primitiveCount_;
}
} // namespace esengine
diff --git a/src/esengine/renderer/ImmediateDraw.hpp b/src/esengine/renderer/ImmediateDraw.hpp
index 0482d0e6e..1df59c255 100644
--- a/src/esengine/renderer/ImmediateDraw.hpp
+++ b/src/esengine/renderer/ImmediateDraw.hpp
@@ -5,6 +5,9 @@
* circles, polygons) with automatic batching for efficient rendering.
* All draw commands are cleared each frame.
*
+ * Backed by the same TransientBufferPool + StateTracker + GfxDevice
+ * machinery as RenderFrame — there is no separate batch renderer.
+ *
* @author ESEngine Team
* @date 2026
*
@@ -15,6 +18,7 @@
#include "../core/Types.hpp"
#include "../math/Math.hpp"
+#include "TransientBufferPool.hpp"
#include <glm/glm.hpp>
#include <vector>
@@ -23,8 +27,8 @@
namespace esengine {
class GfxDevice;
+class StateTracker;
class RenderContext;
-class BatchRenderer2D;
namespace resource {
class ResourceManager;
@@ -34,14 +38,13 @@ namespace resource {
* @brief Immediate mode 2D drawing API
*
* @details Provides a simple API for drawing 2D primitives. All commands
- * submitted between begin() and end() are batched for efficient
- * rendering. The draw buffer is automatically cleared each frame.
+ * submitted between begin() and end() are batched (per texture) and
+ * drawn in submission order. The buffer is cleared each frame.
*
* @code
- * ImmediateDraw draw(context, resourceManager);
+ * ImmediateDraw draw(device, state, context, resourceManager);
* draw.init();
*
- * // Each frame
* draw.begin(viewProjection);
* draw.line({0, 0}, {100, 100}, {1, 0, 0, 1});
* draw.rect({50, 50}, {30, 30}, {0, 1, 0, 1});
@@ -53,10 +56,13 @@ class ImmediateDraw {
public:
/**
* @brief Constructs an immediate draw instance
- * @param context Render context for shared resources
- * @param resource_manager Resource manager for shader/texture access
+ * @param device Graphics device (GPU command sink)
+ * @param state Shared per-App GPU state cache
+ * @param context Render context for shared resources (white texture)
+ * @param resource_manager Resource manager for shader access
*/
- ImmediateDraw(GfxDevice& device, RenderContext& context, resource::ResourceManager& resource_manager);
+ ImmediateDraw(GfxDevice& device, StateTracker& state, RenderContext& context,
+ resource::ResourceManager& resource_manager);
~ImmediateDraw();
ImmediateDraw(const ImmediateDraw&) = delete;
@@ -73,21 +79,16 @@ public:
// Frame Management
// =========================================================================
- /**
- * @brief Begins a new draw frame
- * @param viewProjection Combined view-projection matrix
- */
+ /** @brief Begins a new draw frame */
void begin(const glm::mat4& viewProjection);
- /**
- * @brief Ends the frame and submits all draw commands
- */
+ /** @brief Ends the frame and submits all draw commands */
void end();
/**
* @brief Flushes pending draw commands without ending the frame
- * @details Use this before operations that change GL state (e.g. custom geometry draws)
- * to ensure accumulated primitives are rendered with the correct state.
+ * @details Use before operations that change GL state to ensure accumulated
+ * primitives are rendered with the correct state.
*/
void flush();
@@ -95,23 +96,9 @@ public:
// Line Drawing
// =========================================================================
- /**
- * @brief Draws a line between two points
- * @param from Start point
- * @param to End point
- * @param color RGBA color
- * @param thickness Line thickness in pixels (default: 1.0)
- */
void line(const glm::vec2& from, const glm::vec2& to,
const glm::vec4& color, f32 thickness = 1.0f);
- /**
- * @brief Draws a polyline through multiple points
- * @param vertices Array of points
- * @param color RGBA color
- * @param thickness Line thickness in pixels (default: 1.0)
- * @param closed If true, connects last point to first (default: false)
- */
void polyline(std::span<const glm::vec2> vertices, const glm::vec4& color,
f32 thickness = 1.0f, bool closed = false);
@@ -119,23 +106,9 @@ public:
// Rectangle Drawing
// =========================================================================
- /**
- * @brief Draws a filled or outlined rectangle
- * @param position Center position
- * @param size Width and height
- * @param color RGBA color
- * @param filled If true, draws filled; if false, draws outline (default: true)
- */
void rect(const glm::vec2& position, const glm::vec2& size,
const glm::vec4& color, bool filled = true);
- /**
- * @brief Draws a rectangle outline
- * @param position Center position
- * @param size Width and height
- * @param color RGBA color
- * @param thickness Line thickness in pixels (default: 1.0)
- */
void rectOutline(const glm::vec2& position, const glm::vec2& size,
const glm::vec4& color, f32 thickness = 1.0f);
@@ -143,25 +116,9 @@ public:
// Circle Drawing
// =========================================================================
- /**
- * @brief Draws a filled or outlined circle
- * @param center Center position
- * @param radius Circle radius
- * @param color RGBA color
- * @param filled If true, draws filled; if false, draws outline (default: true)
- * @param segments Number of segments for approximation (default: 32)
- */
void circle(const glm::vec2& center, f32 radius,
const glm::vec4& color, bool filled = true, i32 segments = 32);
- /**
- * @brief Draws a circle outline
- * @param center Center position
- * @param radius Circle radius
- * @param color RGBA color
- * @param thickness Line thickness in pixels (default: 1.0)
- * @param segments Number of segments for approximation (default: 32)
- */
void circleOutline(const glm::vec2& center, f32 radius,
const glm::vec4& color, f32 thickness = 1.0f, i32 segments = 32);
@@ -169,35 +126,15 @@ public:
// Polygon Drawing
// =========================================================================
- /**
- * @brief Draws a filled polygon
- * @param vertices Array of vertices (must be convex for correct fill)
- * @param color RGBA color
- */
void polygon(std::span<const glm::vec2> vertices, const glm::vec4& color);
// =========================================================================
// Texture Drawing
// =========================================================================
- /**
- * @brief Draws a textured quad
- * @param position Center position
- * @param size Width and height
- * @param textureId GPU texture handle
- * @param tint Color tint (default: white)
- */
void texture(const glm::vec2& position, const glm::vec2& size,
u32 textureId, const glm::vec4& tint = glm::vec4(1.0f));
- /**
- * @brief Draws a rotated textured quad
- * @param position Center position
- * @param size Width and height
- * @param rotation Rotation angle in radians
- * @param textureId GPU texture handle
- * @param tint Color tint (default: white)
- */
void textureRotated(const glm::vec2& position, const glm::vec2& size,
f32 rotation, u32 textureId,
const glm::vec4& tint = glm::vec4(1.0f));
@@ -206,48 +143,46 @@ public:
// Configuration
// =========================================================================
- /**
- * @brief Sets the current render layer
- * @param layer Layer index (higher layers render on top)
- */
void setLayer(i32 layer) { currentLayer_ = layer; }
-
- /**
- * @brief Gets the current render layer
- * @return Current layer index
- */
i32 getLayer() const { return currentLayer_; }
-
- /**
- * @brief Sets the current depth for sorting within a layer
- * @param depth Z depth value
- */
void setDepth(f32 depth) { currentDepth_ = depth; }
-
- /**
- * @brief Gets the current depth
- * @return Current depth value
- */
f32 getDepth() const { return currentDepth_; }
// =========================================================================
// Statistics
// =========================================================================
- u32 getDrawCallCount() const;
+ u32 getDrawCallCount() const { return drawCallCount_; }
u32 getPrimitiveCount() const { return primitiveCount_; }
private:
- struct Impl;
- Unique<Impl> impl_;
+ /** Emits a (optionally rotated) textured quad into the current batch. */
+ void emitQuad(const glm::vec2& center, const glm::vec2& size, f32 rotation,
+ const glm::vec4& color, u32 textureId,
+ const glm::vec2& uvOffset = glm::vec2(0.0f),
+ const glm::vec2& uvScale = glm::vec2(1.0f));
+ /** Emits a flat triangle (white texture) into the current batch. */
+ void emitTriangle(const glm::vec2& p0, const glm::vec2& p1, const glm::vec2& p2,
+ const glm::vec4& color);
+ /** Switches the batch texture, flushing first if it changed. */
+ void useTexture(u32 textureId);
GfxDevice& device_;
+ StateTracker& state_;
RenderContext& context_;
resource::ResourceManager& resource_manager_;
+ TransientBufferPool pool_;
+ u32 batch_shader_id_ = 0;
+ u32 white_texture_id_ = 0;
+ glm::mat4 viewProjection_{1.0f};
+ u32 currentTexture_ = 0;
+ bool pendingGeometry_ = false;
+
i32 currentLayer_ = 0;
f32 currentDepth_ = 0.0f;
u32 primitiveCount_ = 0;
+ u32 drawCallCount_ = 0;
bool initialized_ = false;
bool inFrame_ = false;
};
diff --git a/src/esengine/renderer/Renderer.cpp b/src/esengine/renderer/Renderer.cpp
deleted file mode 100644
index be6ea7e07..000000000
--- a/src/esengine/renderer/Renderer.cpp
+++ /dev/null
@@ -1,602 +0,0 @@
-/**
- * @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 "BatchVertex.hpp"
-#include "GfxDevice.hpp"
-#include "TextureSlotAllocator.hpp"
-#include "ShaderEmbeds.generated.hpp"
-#include "../resource/ShaderParser.hpp"
-#include "../core/Log.hpp"
-#include "../resource/ResourceManager.hpp"
-
-#include <array>
-#include <cmath>
-#include <vector>
-
-namespace esengine {
-
-// ========================================
-// Renderer Implementation
-// ========================================
-
-Renderer::Renderer(GfxDevice& device, RenderContext& context)
- : device_(device), context_(context) {
-}
-
-void Renderer::beginFrame() {
- context_.stats().reset();
-}
-
-void Renderer::endFrame() {
- // Nothing to do for now
-}
-
-void Renderer::setViewport(i32 x, i32 y, u32 width, u32 height) {
- device_.setViewport(x, y, width, height);
-}
-
-void Renderer::setClearColor(const glm::vec4& color) {
- device_.setClearColor(color.r, color.g, color.b, color.a);
-}
-
-void Renderer::clear() {
- device_.clear(true, true, false);
-}
-
-void Renderer::beginScene(const glm::mat4& viewProjection) {
- context_.viewProjection() = viewProjection;
-}
-
-void Renderer::endScene() {
- // Nothing to do for now
-}
-
-void Renderer::submit(const Shader& shader, const VertexArray& vao, const glm::mat4& transform) {
- shader.bind();
- shader.setUniform("u_projection", context_.viewProjection());
- shader.setUniform("u_model", transform);
-
- vao.bind();
- auto ib = vao.getIndexBuffer();
- u32 count = ib ? ib->getCount() : 0;
- if (count > 0 && ib) {
- auto type = ib->is16Bit() ? GfxDataType::UnsignedShort : GfxDataType::UnsignedInt;
- device_.drawElements(count, type, 0);
- }
-
- context_.stats().drawCalls++;
-}
-
-void Renderer::drawQuad(const glm::vec2& position, const glm::vec2& size, const glm::vec4& color) {
- drawQuad(glm::vec3(position, 0.0f), size, color);
-}
-
-void Renderer::drawQuad(const glm::vec3& position, const glm::vec2& size, const glm::vec4& color) {
- 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));
-
- shader->bind();
- shader->setUniform("u_projection", context_.viewProjection());
- shader->setUniform("u_model", transform);
- shader->setUniform("u_color", color);
-
- vao->bind();
- {
- auto ib = vao->getIndexBuffer();
- u32 cnt = ib ? ib->getCount() : 0;
- if (cnt > 0 && ib) {
- auto type = ib->is16Bit() ? GfxDataType::UnsignedShort : GfxDataType::UnsignedInt;
- device_.drawElements(cnt, type, 0);
- }
- }
-
- context_.stats().drawCalls++;
- context_.stats().triangleCount += 2;
-}
-
-void Renderer::drawQuad(const glm::vec2& position, const glm::vec2& size,
- const Texture& texture, const glm::vec4& tintColor) {
- drawQuad(glm::vec3(position, 0.0f), size, texture, tintColor);
-}
-
-void Renderer::drawQuad(const glm::vec3& position, const glm::vec2& size,
- const Texture& texture, const glm::vec4& tintColor) {
- 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);
-
- vao->bind();
- {
- auto ib = vao->getIndexBuffer();
- u32 cnt = ib ? ib->getCount() : 0;
- if (cnt > 0 && ib) {
- auto type = ib->is16Bit() ? GfxDataType::UnsignedShort : GfxDataType::UnsignedInt;
- device_.drawElements(cnt, type, 0);
- }
- }
-
- 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() const {
- return context_.stats();
-}
-
-void Renderer::resetStats() {
- context_.stats().reset();
-}
-
-// ========================================
-// BatchRenderer2D Implementation
-// ========================================
-
-
-// Batch rendering constants
-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;
-
-// Quad vertex positions (CCW from bottom-left)
-constexpr glm::vec4 QUAD_POSITIONS[4] = {
- { -0.5f, -0.5f, 0.0f, 1.0f },
- { 0.5f, -0.5f, 0.0f, 1.0f },
- { 0.5f, 0.5f, 0.0f, 1.0f },
- { -0.5f, 0.5f, 0.0f, 1.0f }
-};
-
-constexpr glm::vec2 QUAD_TEX_COORDS[4] = {
- { 0.0f, 0.0f },
- { 1.0f, 0.0f },
- { 1.0f, 1.0f },
- { 0.0f, 1.0f }
-};
-
-// BatchRenderer2D internal data
-struct BatchRenderer2D::BatchData {
- Unique<VertexArray> vao;
- Shared<VertexBuffer> vbo;
- resource::ShaderHandle shader_handle;
-
- std::vector<BatchVertex> vertices;
- std::vector<BatchVertex> triVertices;
- u32 indexCount = 0;
- u32 triangleCount = 0;
-
- TextureSlotAllocator<MAX_TEXTURE_SLOTS> texSlots;
-
- glm::mat4 projection{1.0f};
- i32 projectionLoc = -1;
-
- u32 drawCallCount = 0;
- u32 quadCount = 0;
-
- bool initialized = false;
-};
-
-BatchRenderer2D::BatchRenderer2D(GfxDevice& device,
- RenderContext& context,
- resource::ResourceManager& resource_manager)
- : data_(makeUnique<BatchData>())
- , device_(device)
- , context_(context)
- , resource_manager_(resource_manager) {
-}
-
-void BatchRenderer2D::setFlushCallback(FlushCallback cb, void* userData) {
- flush_callback_ = cb;
- flush_callback_data_ = userData;
-}
-
-BatchRenderer2D::~BatchRenderer2D() {
- if (data_ && data_->initialized) {
- shutdown();
- }
-}
-
-void BatchRenderer2D::init() {
- data_->vertices.reserve(MAX_VERTICES);
- data_->triVertices.reserve(MAX_VERTICES);
-
- data_->vao = VertexArray::create(device_);
-
- data_->vbo = makeShared<VertexBuffer>();
- *data_->vbo = std::move(*VertexBuffer::create(device_, MAX_VERTICES * sizeof(BatchVertex)));
- data_->vbo->setLayout({
- { ShaderDataType::Float2, "a_position" },
- { ShaderDataType::UByte4N, "a_color" },
- { ShaderDataType::Float2, "a_texCoord" }
- });
-
- data_->vao->addVertexBuffer(data_->vbo);
-
- std::vector<u16> indices(MAX_INDICES);
- u16 offset = 0;
- for (u32 i = 0; i < MAX_INDICES; i += 6) {
- indices[i + 0] = offset + 0;
- indices[i + 1] = offset + 1;
- indices[i + 2] = offset + 2;
- indices[i + 3] = offset + 2;
- indices[i + 4] = offset + 3;
- indices[i + 5] = offset + 0;
- offset += 4;
- }
- auto ibo = IndexBuffer::create(device_, indices.data(), MAX_INDICES);
- data_->vao->setIndexBuffer(Shared<IndexBuffer>(std::move(ibo)));
-
-#ifndef ES_PLATFORM_WEB
- data_->shader_handle = resource_manager_.loadEngineShader("batch");
-#endif
- if (!data_->shader_handle.isValid()) {
- data_->shader_handle = resource_manager_.createShaderWithBindings(
- ShaderSources::BATCH_VERTEX,
- ShaderSources::BATCH_FRAGMENT,
- {{0, "a_position"}, {1, "a_color"}, {2, "a_texCoord"}}
- );
- }
-
- Shader* batchShader = resource_manager_.getShader(data_->shader_handle);
-
- if (!batchShader || !batchShader->isValid()) {
- ES_LOG_WARN("GLSL ES 3.0 batch shader failed, trying GLSL ES 1.0 fallback");
- auto batchParsed = resource::ShaderParser::parse(ShaderEmbeds::BATCH);
- data_->shader_handle = resource_manager_.createShaderWithBindings(
- resource::ShaderParser::assembleStage(batchParsed, resource::ShaderStage::Vertex),
- resource::ShaderParser::assembleStage(batchParsed, resource::ShaderStage::Fragment),
- {{0, "a_position"}, {1, "a_color"}, {2, "a_texCoord"}}
- );
- batchShader = resource_manager_.getShader(data_->shader_handle);
- }
-
- if (batchShader && batchShader->isValid()) {
- batchShader->bind();
- i32 texLoc = device_.getUniformLocation(batchShader->getProgramId(), "u_texture");
- if (texLoc >= 0) {
- device_.setUniform1i(texLoc, 0);
- }
- } else {
- ES_LOG_ERROR("All batch shader variants FAILED!");
- }
-
- if (batchShader) {
- data_->projectionLoc = batchShader->getUniformLocation("u_projection");
- }
-
- data_->texSlots.init(context_.getWhiteTextureId());
- data_->initialized = true;
-}
-
-void BatchRenderer2D::shutdown() {
- if (!data_ || !data_->initialized) return;
-
- data_->vao.reset();
- data_->vbo.reset();
- data_->initialized = false;
-
- ES_LOG_INFO("BatchRenderer2D shutdown");
-}
-
-void BatchRenderer2D::beginBatch() {
- data_->vertices.clear();
- data_->triVertices.clear();
- data_->indexCount = 0;
- data_->triangleCount = 0;
- data_->texSlots.reset();
- data_->drawCallCount = 0;
- data_->quadCount = 0;
-}
-
-void BatchRenderer2D::endBatch() {
- flush();
-}
-
-void BatchRenderer2D::flush() {
- bool hasQuads = !data_->vertices.empty();
- bool hasTris = !data_->triVertices.empty();
- if (!hasQuads && !hasTris) return;
-
- u32 vertexCount = static_cast<u32>(data_->vertices.size() + data_->triVertices.size());
- u32 triangleCount = data_->quadCount * 2 + static_cast<u32>(data_->triVertices.size()) / 3;
- u8 slotUsage = static_cast<u8>(data_->texSlots.slotCount());
-
- Shader* shader = resource_manager_.getShader(data_->shader_handle);
- if (!shader) return;
-
- u32 quadBytes = static_cast<u32>(data_->vertices.size() * sizeof(BatchVertex));
- u32 triBytes = static_cast<u32>(data_->triVertices.size() * sizeof(BatchVertex));
-
- if (hasQuads) {
- data_->vbo->setDataRaw(data_->vertices.data(), quadBytes);
- if (hasTris) {
- data_->vbo->setSubDataRaw(data_->triVertices.data(), triBytes, quadBytes);
- }
- } else {
- data_->vbo->setDataRaw(data_->triVertices.data(), triBytes);
- }
-
- data_->texSlots.bindAll(device_);
-
- shader->bind();
- shader->setUniform(data_->projectionLoc, data_->projection);
-
- data_->vao->bind();
-
- if (hasQuads) {
- auto ib = data_->vao->getIndexBuffer();
- if (ib) {
- ib->bind();
- auto type = ib->is16Bit() ? GfxDataType::UnsignedShort : GfxDataType::UnsignedInt;
- device_.drawElements(data_->indexCount, type, 0);
- }
- data_->drawCallCount++;
- }
-
- if (hasTris) {
- device_.drawArrays(static_cast<u32>(data_->vertices.size()),
- static_cast<u32>(data_->triVertices.size()));
- data_->drawCallCount++;
- }
-
- if (flush_callback_) {
- flush_callback_(next_flush_reason_, vertexCount, triangleCount, slotUsage, flush_callback_data_);
- next_flush_reason_ = FlushReason::FrameEnd;
- }
-
- data_->vertices.clear();
- data_->triVertices.clear();
- data_->indexCount = 0;
- data_->triangleCount = 0;
- data_->texSlots.reset();
-}
-
-void BatchRenderer2D::drawQuad(const glm::vec2& position, const glm::vec2& size,
- u32 textureId, const glm::vec4& color,
- const glm::vec2& uvOffset, const glm::vec2& uvScale) {
- drawQuad(glm::vec3(position, 0.0f), size, textureId, color, uvOffset, uvScale);
-}
-
-void BatchRenderer2D::drawQuad(const glm::vec3& position, const glm::vec2& size,
- u32 textureId, const glm::vec4& color,
- const glm::vec2& uvOffset, const glm::vec2& uvScale) {
- if (data_->vertices.size() + data_->triVertices.size() + 4 > MAX_VERTICES) {
- next_flush_reason_ = FlushReason::BatchFull;
- flush();
- }
-
- for (u32 i = 0; i < 4; ++i) {
- BatchVertex vertex;
- vertex.position = glm::vec2(
- position.x + QUAD_POSITIONS[i].x * size.x,
- position.y + QUAD_POSITIONS[i].y * size.y
- );
- vertex.color = packColor(color);
- vertex.texCoord = QUAD_TEX_COORDS[i] * uvScale + uvOffset;
- data_->vertices.push_back(vertex);
- }
-
- data_->indexCount += 6;
- data_->quadCount++;
-}
-
-void BatchRenderer2D::drawQuad(const glm::vec2& position, const glm::vec2& size,
- const glm::vec4& color) {
- drawQuad(glm::vec3(position, 0.0f), size, 0, color);
-}
-
-void BatchRenderer2D::drawTriangle(const glm::vec2& p0, const glm::vec2& p1,
- const glm::vec2& p2, const glm::vec4& color) {
- if (data_->vertices.size() + data_->triVertices.size() + 3 > MAX_VERTICES) {
- next_flush_reason_ = FlushReason::BatchFull;
- flush();
- }
-
- BatchVertex v;
- v.color = packColor(color);
- v.texCoord = { 0.0f, 0.0f };
-
- v.position = p0;
- data_->triVertices.push_back(v);
- v.position = p1;
- data_->triVertices.push_back(v);
- v.position = p2;
- data_->triVertices.push_back(v);
-
- data_->triangleCount++;
-}
-
-void BatchRenderer2D::drawRotatedQuad(const glm::vec2& position, const glm::vec2& size,
- f32 rotation, const glm::vec4& color) {
- drawRotatedQuad(position, size, rotation, 0, color);
-}
-
-void BatchRenderer2D::drawRotatedQuad(const glm::vec2& position, const glm::vec2& size,
- f32 rotation, u32 textureId, const glm::vec4& tintColor,
- const glm::vec2& uvOffset, const glm::vec2& uvScale) {
- if (data_->vertices.size() + data_->triVertices.size() + 4 > MAX_VERTICES) {
- next_flush_reason_ = FlushReason::BatchFull;
- flush();
- }
-
- glm::mat4 transform = glm::translate(glm::mat4(1.0f), glm::vec3(position, 0.0f));
- transform = glm::rotate(transform, rotation, glm::vec3(0.0f, 0.0f, 1.0f));
- transform = glm::scale(transform, glm::vec3(size, 1.0f));
-
- for (u32 i = 0; i < 4; ++i) {
- BatchVertex vertex;
- vertex.position = glm::vec2(transform * QUAD_POSITIONS[i]);
- vertex.color = packColor(tintColor);
- vertex.texCoord = QUAD_TEX_COORDS[i] * uvScale + uvOffset;
- data_->vertices.push_back(vertex);
- }
-
- data_->indexCount += 6;
- data_->quadCount++;
-}
-
-void BatchRenderer2D::setProjection(const glm::mat4& projection) {
- data_->projection = projection;
-}
-
-void BatchRenderer2D::drawNineSlice(const glm::vec2& position, const glm::vec2& size,
- u32 textureId, const glm::vec2& texSize,
- const resource::SliceBorder& border,
- const glm::vec4& color,
- f32 rotation,
- const glm::vec2& uvOffset, const glm::vec2& uvScale) {
- f32 L = border.left;
- f32 R = border.right;
- f32 T = border.top;
- f32 B = border.bottom;
-
- f32 baseX = position.x - size.x * 0.5f;
- f32 baseY = position.y - size.y * 0.5f;
-
- f32 x0 = baseX;
- f32 x1 = baseX + L;
- f32 x2 = baseX + size.x - R;
- f32 x3 = baseX + size.x;
-
- f32 y0 = baseY;
- f32 y1 = baseY + B;
- f32 y2 = baseY + size.y - T;
- f32 y3 = baseY + size.y;
-
- f32 u0 = uvOffset.x;
- f32 u1 = uvOffset.x + L / texSize.x;
- f32 u2 = uvOffset.x + uvScale.x - R / texSize.x;
- f32 u3 = uvOffset.x + uvScale.x;
-
- f32 v0 = uvOffset.y;
- f32 v1 = uvOffset.y + B / texSize.y;
- f32 v2 = uvOffset.y + uvScale.y - T / texSize.y;
- f32 v3 = uvOffset.y + uvScale.y;
-
- // Precompute rotation sin/cos
- f32 cosR = std::cos(rotation);
- f32 sinR = std::sin(rotation);
-
- // Helper to rotate a point around center (position)
- auto rotatePoint = [&position, cosR, sinR](f32 x, f32 y) -> glm::vec2 {
- f32 dx = x - position.x;
- f32 dy = y - position.y;
- return glm::vec2(
- position.x + dx * cosR - dy * sinR,
- position.y + dx * sinR + dy * cosR
- );
- };
-
- u32 packedColor = packColor(color);
- auto drawSlice = [this, packedColor, &rotatePoint](
- f32 px, f32 py, f32 pw, f32 ph,
- f32 uvX, f32 uvY, f32 uvW, f32 uvH) {
-
- if (pw <= 0 || ph <= 0) return;
-
- if (data_->vertices.size() + data_->triVertices.size() + 4 > MAX_VERTICES) {
- next_flush_reason_ = FlushReason::BatchFull;
- flush();
- }
-
- BatchVertex v0, v1, v2, v3;
-
- glm::vec2 p0 = rotatePoint(px, py);
- glm::vec2 p1 = rotatePoint(px + pw, py);
- glm::vec2 p2 = rotatePoint(px + pw, py + ph);
- glm::vec2 p3 = rotatePoint(px, py + ph);
-
- v0.position = p0;
- v0.color = packedColor;
- v0.texCoord = glm::vec2(uvX, uvY);
-
- v1.position = p1;
- v1.color = packedColor;
- v1.texCoord = glm::vec2(uvX + uvW, uvY);
-
- v2.position = p2;
- v2.color = packedColor;
- v2.texCoord = glm::vec2(uvX + uvW, uvY + uvH);
-
- v3.position = p3;
- v3.color = packedColor;
- v3.texCoord = glm::vec2(uvX, uvY + uvH);
-
- data_->vertices.push_back(v0);
- data_->vertices.push_back(v1);
- data_->vertices.push_back(v2);
- data_->vertices.push_back(v3);
-
- data_->indexCount += 6;
- data_->quadCount++;
- };
-
- // Draw 9 slices (3x3 grid)
- // Row 1 (bottom): y0 to y1
- drawSlice(x0, y0, x1 - x0, y1 - y0, u0, v0, u1 - u0, v1 - v0); // Bottom-left
- drawSlice(x1, y0, x2 - x1, y1 - y0, u1, v0, u2 - u1, v1 - v0); // Bottom-center
- drawSlice(x2, y0, x3 - x2, y1 - y0, u2, v0, u3 - u2, v1 - v0); // Bottom-right
-
- // Row 2 (middle): y1 to y2
- drawSlice(x0, y1, x1 - x0, y2 - y1, u0, v1, u1 - u0, v2 - v1); // Middle-left
- drawSlice(x1, y1, x2 - x1, y2 - y1, u1, v1, u2 - u1, v2 - v1); // Center
- drawSlice(x2, y1, x3 - x2, y2 - y1, u2, v1, u3 - u2, v2 - v1); // Middle-right
-
- // Row 3 (top): y2 to y3
- drawSlice(x0, y2, x1 - x0, y3 - y2, u0, v2, u1 - u0, v3 - v2); // Top-left
- drawSlice(x1, y2, x2 - x1, y3 - y2, u1, v2, u2 - u1, v3 - v2); // Top-center
- drawSlice(x2, y2, x3 - x2, y3 - y2, u2, v2, u3 - u2, v3 - v2); // Top-right
-}
-
-u32 BatchRenderer2D::getDrawCallCount() const {
- return data_ ? data_->drawCallCount : 0;
-}
-
-u32 BatchRenderer2D::getQuadCount() const {
- return data_ ? data_->quadCount : 0;
-}
-
-u32 BatchRenderer2D::getTriangleCount() const {
- return data_ ? data_->triangleCount : 0;
-}
-
-u32 BatchRenderer2D::getShaderProgramId() const {
- if (!data_ || !data_->shader_handle.isValid()) return 0;
- Shader* shader = resource_manager_.getShader(data_->shader_handle);
- return shader ? shader->getProgramId() : 0;
-}
-
-} // namespace esengine
diff --git a/src/esengine/renderer/Renderer.hpp b/src/esengine/renderer/Renderer.hpp
deleted file mode 100644
index e1f2b96cb..000000000
--- a/src/esengine/renderer/Renderer.hpp
+++ /dev/null
@@ -1,430 +0,0 @@
-/**
- * @file Renderer.hpp
- * @brief Core rendering functionality for ESEngine
- * @details Provides both immediate-mode rendering (Renderer) and efficient
- * batched 2D sprite rendering (BatchRenderer2D) for WebGL/OpenGL ES.
- *
- * @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 "../math/Math.hpp"
-#include "Buffer.hpp"
-#include "Shader.hpp"
-#include "Texture.hpp"
-#include "RenderContext.hpp"
-#include "FrameCapture.hpp"
-#include "../resource/Handle.hpp"
-#include "../resource/TextureMetadata.hpp"
-
-// Forward declaration
-namespace esengine::resource {
- class ResourceManager;
-}
-
-namespace esengine {
-
-// =============================================================================
-// Renderer Statistics
-// =============================================================================
-
-using RendererStats = RenderContextStats;
-
-// =============================================================================
-// Renderer Class
-// =============================================================================
-
-/**
- * @brief Instance-based renderer for 2D drawing
- *
- * @details Provides immediate-mode 2D rendering with dependency injection.
- * Requires a RenderContext for shared resources and state.
- *
- * @code
- * RenderContext context;
- * context.init();
- *
- * Renderer renderer(context);
- *
- * // Frame rendering
- * renderer.beginFrame();
- * renderer.clear();
- * renderer.beginScene(camera.getViewProjection());
- *
- * renderer.drawQuad({100, 100}, {50, 50}, {1, 0, 0, 1}); // Red quad
- *
- * renderer.endScene();
- * renderer.endFrame();
- * @endcode
- */
-class Renderer {
-public:
- /**
- * @brief Constructs a renderer with the given device and context
- * @param device Reference to the graphics device
- * @param context Reference to the rendering context
- */
- Renderer(GfxDevice& device, RenderContext& context);
-
- ~Renderer() = default;
-
- // Non-copyable
- Renderer(const Renderer&) = delete;
- Renderer& operator=(const Renderer&) = delete;
-
- // =========================================================================
- // Frame Management
- // =========================================================================
-
- /** @brief Begins a new frame */
- void beginFrame();
-
- /** @brief Ends the current frame */
- void endFrame();
-
- // =========================================================================
- // Viewport and Clearing
- // =========================================================================
-
- /**
- * @brief Sets the rendering viewport
- * @param x Viewport X origin in pixels
- * @param y Viewport Y origin in pixels
- * @param width Viewport width in pixels
- * @param height Viewport height in pixels
- */
- 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)
- */
- void setClearColor(const glm::vec4& color);
-
- /** @brief Clears the color and depth buffers */
- void clear();
-
- // =========================================================================
- // Scene Management
- // =========================================================================
-
- /**
- * @brief Begins a scene with the given camera transform
- * @param viewProjection Combined view-projection matrix
- */
- void beginScene(const glm::mat4& viewProjection);
-
- /** @brief Ends the current scene */
- void endScene();
-
- // =========================================================================
- // Draw Submission
- // =========================================================================
-
- /**
- * @brief Submits geometry for rendering with a shader
- * @param shader The shader program to use
- * @param vao The vertex array containing geometry
- * @param transform Model transform matrix (defaults to identity)
- */
- void submit(const Shader& shader,
- const VertexArray& vao,
- const glm::mat4& transform = glm::mat4(1.0f));
-
- // =========================================================================
- // 2D Rendering Helpers
- // =========================================================================
-
- /**
- * @brief Draws a colored quad at a 2D position
- * @param position Center position (x, y)
- * @param size Width and height
- * @param color RGBA 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
- * @param position Center position (x, y)
- * @param size Width and height
- * @param texture Texture to apply
- * @param tintColor Optional color tint (defaults to white)
- */
- void drawQuad(const glm::vec2& 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)
- * @param size Width and height
- * @param texture Texture to apply
- * @param tintColor Optional color tint (defaults to white)
- */
- 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 using a texture handle
- * @param position Center position (x, y)
- * @param size Width and height
- * @param texture Texture handle
- * @param rm Resource manager to resolve the handle
- * @param tintColor Optional color tint (defaults to white)
- */
- 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
- // =========================================================================
-
- /**
- * @brief Gets the current frame's rendering statistics
- * @return RendererStats with draw call and geometry counts
- */
- RendererStats getStats() const;
-
- /** @brief Resets statistics counters */
- void resetStats();
-
- // =========================================================================
- // Context Access
- // =========================================================================
-
- /**
- * @brief Gets the rendering context
- * @return Reference to the context
- */
- RenderContext& getContext() { return context_; }
-
-private:
- GfxDevice& device_;
- RenderContext& context_;
-};
-
-// =============================================================================
-// BatchRenderer2D Class
-// =============================================================================
-
-/**
- * @brief High-performance batched 2D sprite renderer
- *
- * @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 batch(context);
- * batch.setProjection(orthoMatrix);
- *
- * batch.beginBatch();
- * for (auto& sprite : sprites) {
- * batch.drawQuad(sprite.pos, sprite.size, sprite.textureId);
- * }
- * batch.endBatch();
- * batch.flush();
- * @endcode
- */
-class BatchRenderer2D {
-public:
- /**
- * @brief Constructs a batch renderer
- * @param device Graphics device
- * @param context Render context for shared resources
- * @param resource_manager Resource manager for shader loading
- */
- BatchRenderer2D(GfxDevice& device, RenderContext& context, resource::ResourceManager& resource_manager);
-
- ~BatchRenderer2D();
-
- // Non-copyable
- BatchRenderer2D(const BatchRenderer2D&) = delete;
- BatchRenderer2D& operator=(const BatchRenderer2D&) = delete;
-
- // =========================================================================
- // Lifecycle
- // =========================================================================
-
- /** @brief Initializes batch rendering resources */
- void init();
-
- /** @brief Shuts down and releases resources */
- void shutdown();
-
- // =========================================================================
- // Batch Operations
- // =========================================================================
-
- /** @brief Begins a new batch */
- void beginBatch();
-
- /** @brief Ends the current batch (prepares for flush) */
- void endBatch();
-
- /** @brief Flushes the batch to the GPU (issues draw call) */
- void flush();
-
- // =========================================================================
- // Textured Quads
- // =========================================================================
-
- /**
- * @brief Draws a textured quad at a 2D position
- * @param position Position (x, y)
- * @param size Width and height
- * @param textureId GPU texture handle
- * @param color Color tint (defaults to white)
- */
- void drawQuad(const glm::vec2& position, const glm::vec2& size,
- u32 textureId, const glm::vec4& color = glm::vec4(1.0f),
- const glm::vec2& uvOffset = glm::vec2(0.0f),
- const glm::vec2& uvScale = glm::vec2(1.0f));
-
- /**
- * @brief Draws a textured quad at a 3D position
- * @param position Position (x, y, z)
- * @param size Width and height
- * @param textureId GPU texture handle
- * @param color Color tint (defaults to white)
- * @param uvOffset UV offset for atlas mapping
- * @param uvScale UV scale for atlas mapping
- */
- void drawQuad(const glm::vec3& position, const glm::vec2& size,
- u32 textureId, const glm::vec4& color = glm::vec4(1.0f),
- const glm::vec2& uvOffset = glm::vec2(0.0f),
- const glm::vec2& uvScale = glm::vec2(1.0f));
-
- // =========================================================================
- // Colored Quads
- // =========================================================================
-
- /**
- * @brief Draws a solid colored quad (no texture)
- * @param position Position (x, y)
- * @param size Width and height
- * @param color RGBA color
- */
- void drawQuad(const glm::vec2& position, const glm::vec2& size,
- const glm::vec4& color);
-
- // =========================================================================
- // Rotated Quads
- // =========================================================================
-
- /**
- * @brief Draws a rotated colored quad
- * @param position Position (x, y)
- * @param size Width and height
- * @param rotation Rotation angle in radians
- * @param color RGBA color
- */
- void drawRotatedQuad(const glm::vec2& position, const glm::vec2& size,
- f32 rotation, const glm::vec4& color);
-
- /**
- * @brief Draws a rotated textured quad
- * @param position Position (x, y)
- * @param size Width and height
- * @param rotation Rotation angle in radians
- * @param textureId GPU texture handle
- * @param tintColor Color tint (defaults to white)
- */
- void drawRotatedQuad(const glm::vec2& position, const glm::vec2& size,
- f32 rotation, u32 textureId,
- const glm::vec4& tintColor = glm::vec4(1.0f),
- const glm::vec2& uvOffset = glm::vec2(0.0f),
- const glm::vec2& uvScale = glm::vec2(1.0f));
-
- // =========================================================================
- // Triangle Drawing
- // =========================================================================
-
- void drawTriangle(const glm::vec2& p0, const glm::vec2& p1, const glm::vec2& p2,
- const glm::vec4& color);
-
- // =========================================================================
- // Nine-Slice Rendering
- // =========================================================================
-
- /**
- * @brief Draws a nine-slice sprite
- * @param position Center position (x, y)
- * @param size Total width and height
- * @param textureId GPU texture handle
- * @param texSize Texture dimensions in pixels
- * @param border Nine-slice border configuration
- * @param color Color tint (defaults to white)
- * @param rotation Rotation angle in radians (defaults to 0)
- */
- void drawNineSlice(const glm::vec2& position, const glm::vec2& size,
- u32 textureId, const glm::vec2& texSize,
- const resource::SliceBorder& border,
- const glm::vec4& color = glm::vec4(1.0f),
- f32 rotation = 0.0f,
- const glm::vec2& uvOffset = glm::vec2(0.0f),
- const glm::vec2& uvScale = glm::vec2(1.0f));
-
- // =========================================================================
- // Configuration
- // =========================================================================
-
- /**
- * @brief Sets the projection matrix for 2D rendering
- * @param projection Orthographic projection matrix
- */
- void setProjection(const glm::mat4& projection);
-
- // =========================================================================
- // Statistics
- // =========================================================================
-
- /** @brief Gets the number of draw calls in the current/last frame */
- u32 getDrawCallCount() const;
-
- /** @brief Gets the number of quads rendered in the current/last frame */
- u32 getQuadCount() const;
-
- /** @brief Gets the number of triangles rendered in the current/last frame */
- u32 getTriangleCount() const;
-
- using FlushCallback = void(*)(FlushReason reason, u32 vertexCount, u32 triangleCount,
- u8 textureSlotUsage, void* userData);
- void setFlushCallback(FlushCallback cb, void* userData);
-
- void setNextFlushReason(FlushReason reason) { next_flush_reason_ = reason; }
-
- u32 getShaderProgramId() const;
-
-private:
- struct BatchData;
- Unique<BatchData> data_;
- GfxDevice& device_;
- RenderContext& context_;
- resource::ResourceManager& resource_manager_;
- FlushCallback flush_callback_ = nullptr;
- void* flush_callback_data_ = nullptr;
- FlushReason next_flush_reason_ = FlushReason::FrameEnd;
-};
-
-} // namespace esengine