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.

feat: Add RenderPipeline for unified 2D sprite rendering

esengine5d6896d13bb6
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 09e0f6953..4aac96c59 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -49,6 +49,7 @@ set(ESENGINE_SOURCES
src/esengine/renderer/Buffer.cpp
src/esengine/renderer/Texture.cpp
src/esengine/renderer/Framebuffer.cpp
+ src/esengine/renderer/RenderPipeline.cpp
src/esengine/renderer/stb_image_impl.cpp
src/esengine/platform/input/Input.cpp
src/esengine/platform/PathResolver.cpp
diff --git a/src/esengine/editor/panels/SceneViewPanel.cpp b/src/esengine/editor/panels/SceneViewPanel.cpp
index de81e6e4d..dacff3d20 100644
--- a/src/esengine/editor/panels/SceneViewPanel.cpp
+++ b/src/esengine/editor/panels/SceneViewPanel.cpp
@@ -463,43 +463,16 @@ void SceneViewPanel::renderSprites(const glm::mat4& viewProj) {
if (!ctx) return;
RenderContext& renderCtx = ctx->getRenderContext();
- Shader* shader = renderCtx.getTextureShader();
- VertexArray* quadVAO = renderCtx.getQuadVAO();
- if (!shader || !quadVAO) return;
-
- glEnable(GL_BLEND);
- glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
-
- auto spriteView = registry_.view<ecs::LocalTransform, ecs::Sprite>();
-
- for (auto entity : spriteView) {
- const auto& transform = spriteView.get<ecs::LocalTransform>(entity);
- const auto& sprite = spriteView.get<ecs::Sprite>(entity);
-
- glm::mat4 model = glm::mat4(1.0f);
- model = glm::translate(model, transform.position);
- model *= glm::mat4_cast(transform.rotation);
- model = glm::scale(model, glm::vec3(sprite.size.x * transform.scale.x, sprite.size.y * transform.scale.y, 1.0f));
-
- shader->bind();
- shader->setUniform("u_projection", viewProj);
- shader->setUniform("u_model", model);
- shader->setUniform("u_color", sprite.color);
-
- glActiveTexture(GL_TEXTURE0);
- u32 textureId = renderCtx.getWhiteTextureId();
- if (sprite.texture.isValid()) {
- Texture* tex = resourceManager_.getTexture(sprite.texture);
- if (tex) {
- textureId = tex->getId();
- }
- }
- glBindTexture(GL_TEXTURE_2D, textureId);
- shader->setUniform("u_texture", 0);
-
- RenderCommand::drawIndexed(*quadVAO);
+ // Lazy initialize RenderPipeline
+ if (!renderPipeline_) {
+ renderPipeline_ = makeUnique<RenderPipeline>(renderCtx, resourceManager_);
}
+
+ // Use RenderPipeline for sprite rendering
+ renderPipeline_->begin(viewProj);
+ renderPipeline_->submit(registry_);
+ renderPipeline_->end();
}
void SceneViewPanel::renderSelectionBox(const glm::mat4& viewProj) {
diff --git a/src/esengine/editor/panels/SceneViewPanel.hpp b/src/esengine/editor/panels/SceneViewPanel.hpp
index a7dc6886e..0b66fcdfc 100644
--- a/src/esengine/editor/panels/SceneViewPanel.hpp
+++ b/src/esengine/editor/panels/SceneViewPanel.hpp
@@ -30,6 +30,7 @@
#include "../gizmo/TransformGizmo.hpp"
#include "../command/CommandHistory.hpp"
#include "../../events/Connection.hpp"
+#include "../../renderer/RenderPipeline.hpp"
namespace esengine::editor {
@@ -172,6 +173,7 @@ private:
Unique<SceneToolbar> toolbar_;
Unique<TransformGizmo> transformGizmo_;
+ Unique<RenderPipeline> renderPipeline_;
bool gridVisible_ = true;
bool gizmosVisible_ = true;
ui::Rect viewportBounds_;
diff --git a/src/esengine/renderer/RenderPipeline.cpp b/src/esengine/renderer/RenderPipeline.cpp
new file mode 100644
index 000000000..9b9e0d801
--- /dev/null
+++ b/src/esengine/renderer/RenderPipeline.cpp
@@ -0,0 +1,296 @@
+/**
+ * @file RenderPipeline.cpp
+ * @brief Unified 2D render pipeline implementation
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+#include "RenderPipeline.hpp"
+#include "Renderer.hpp"
+#include "RenderCommand.hpp"
+#include "../core/Log.hpp"
+
+#ifdef ES_PLATFORM_WEB
+ #include <GLES3/gl3.h>
+#else
+ #ifdef _WIN32
+ #include <windows.h>
+ #endif
+ #include <glad/glad.h>
+#endif
+
+#include <algorithm>
+
+namespace esengine {
+
+// =============================================================================
+// RenderItem
+// =============================================================================
+
+u64 RenderItem::sortKey() const {
+ u64 key = 0;
+
+ // Layer: convert signed to unsigned (add 32768 to handle negative layers)
+ u64 layerKey = static_cast<u64>(layer + 32768) & 0xFFFF;
+ key |= layerKey << 48;
+
+ // Texture ID: for batch optimization
+ u64 texKey = static_cast<u64>(texture_id) & 0xFFFFFF;
+ key |= texKey << 24;
+
+ // Depth: convert float to sortable integer
+ f32 normalizedDepth = (depth + 1000.0f) * 10000.0f;
+ u64 depthKey = static_cast<u64>(normalizedDepth) & 0xFFFFFF;
+ key |= depthKey;
+
+ return key;
+}
+
+// =============================================================================
+// Constructor / Destructor
+// =============================================================================
+
+RenderPipeline::RenderPipeline(RenderContext& context,
+ resource::ResourceManager& resource_manager)
+ : context_(context)
+ , resource_manager_(resource_manager)
+ , view_bounds_(0.0f) {
+
+ batcher_ = makeUnique<BatchRenderer2D>(context_);
+ batcher_->init();
+
+ items_.reserve(1024);
+ batches_.reserve(64);
+
+ ES_LOG_INFO("RenderPipeline initialized");
+}
+
+RenderPipeline::~RenderPipeline() {
+ if (batcher_) {
+ batcher_->shutdown();
+ }
+ ES_LOG_INFO("RenderPipeline shutdown");
+}
+
+// =============================================================================
+// Rendering
+// =============================================================================
+
+void RenderPipeline::begin(const glm::mat4& view_projection) {
+ view_projection_ = view_projection;
+ items_.clear();
+ batches_.clear();
+ stats_ = Stats{};
+}
+
+void RenderPipeline::submit(ecs::Registry& registry) {
+ collectFromRegistry(registry);
+}
+
+void RenderPipeline::submit(const RenderItem& item) {
+ items_.push_back(item);
+ stats_.total_items++;
+}
+
+void RenderPipeline::end() {
+ if (items_.empty()) {
+ return;
+ }
+
+ if (culling_enabled_) {
+ cullItems();
+ } else {
+ stats_.visible_items = static_cast<u32>(items_.size());
+ }
+
+ sortItems();
+ buildBatches();
+
+#ifdef ES_PLATFORM_WEB
+ if (batching_enabled_) {
+ executeBatches();
+ } else {
+ executeNonBatched();
+ }
+#else
+ executeNonBatched();
+#endif
+}
+
+// =============================================================================
+// Private Methods
+// =============================================================================
+
+void RenderPipeline::collectFromRegistry(ecs::Registry& registry) {
+ auto spriteView = registry.view<ecs::LocalTransform, ecs::Sprite>();
+
+ for (auto entity : spriteView) {
+ const auto& transform = spriteView.get<ecs::LocalTransform>(entity);
+ const auto& sprite = spriteView.get<ecs::Sprite>(entity);
+
+ RenderItem item;
+ item.entity = entity;
+ item.position = transform.position;
+ item.rotation = transform.rotation;
+ item.scale = transform.scale;
+ item.size = sprite.size;
+ item.color = sprite.color;
+ item.uv_offset = sprite.uvOffset;
+ item.uv_scale = sprite.uvScale;
+ item.layer = sprite.layer;
+ item.depth = transform.position.z;
+ item.flip_x = sprite.flipX;
+ item.flip_y = sprite.flipY;
+
+ item.texture_id = context_.getWhiteTextureId();
+ if (sprite.texture.isValid()) {
+ Texture* tex = resource_manager_.getTexture(sprite.texture);
+ if (tex) {
+ item.texture_id = tex->getId();
+ }
+ }
+
+ items_.push_back(item);
+ stats_.total_items++;
+ }
+}
+
+void RenderPipeline::cullItems() {
+ if (view_bounds_ == glm::vec4(0.0f)) {
+ stats_.visible_items = static_cast<u32>(items_.size());
+ return;
+ }
+
+ auto it = std::remove_if(items_.begin(), items_.end(),
+ [this](const RenderItem& item) {
+ return !isItemVisible(item);
+ });
+
+ stats_.culled_items = static_cast<u32>(std::distance(it, items_.end()));
+ items_.erase(it, items_.end());
+ stats_.visible_items = static_cast<u32>(items_.size());
+}
+
+bool RenderPipeline::isItemVisible(const RenderItem& item) const {
+ f32 halfWidth = item.size.x * item.scale.x * 0.5f;
+ f32 halfHeight = item.size.y * item.scale.y * 0.5f;
+
+ f32 left = item.position.x - halfWidth;
+ f32 right = item.position.x + halfWidth;
+ f32 bottom = item.position.y - halfHeight;
+ f32 top = item.position.y + halfHeight;
+
+ return !(right < view_bounds_.x || left > view_bounds_.y ||
+ top < view_bounds_.z || bottom > view_bounds_.w);
+}
+
+void RenderPipeline::sortItems() {
+ std::sort(items_.begin(), items_.end(),
+ [](const RenderItem& a, const RenderItem& b) {
+ return a.sortKey() < b.sortKey();
+ });
+}
+
+void RenderPipeline::buildBatches() {
+ batches_.clear();
+ if (items_.empty()) {
+ return;
+ }
+
+ u32 currentTexture = items_[0].texture_id;
+ u32 batchStart = 0;
+
+ for (u32 i = 1; i < items_.size(); ++i) {
+ if (items_[i].texture_id != currentTexture) {
+ batches_.push_back({currentTexture, batchStart, i - batchStart});
+ currentTexture = items_[i].texture_id;
+ batchStart = i;
+ }
+ }
+
+ batches_.push_back({currentTexture, batchStart,
+ static_cast<u32>(items_.size()) - batchStart});
+
+ stats_.batch_count = static_cast<u32>(batches_.size());
+}
+
+void RenderPipeline::executeBatches() {
+#ifdef ES_PLATFORM_WEB
+ glEnable(GL_BLEND);
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+
+ batcher_->setProjection(view_projection_);
+ batcher_->beginBatch();
+
+ for (const auto& item : items_) {
+ glm::vec2 finalSize = item.size * glm::vec2(item.scale);
+
+ f32 angle = glm::angle(item.rotation);
+ glm::vec3 axis = glm::axis(item.rotation);
+ if (axis.z < 0) {
+ angle = -angle;
+ }
+
+ if (std::abs(angle) > 0.001f) {
+ batcher_->drawRotatedQuad(
+ glm::vec2(item.position),
+ finalSize,
+ angle,
+ item.texture_id,
+ item.color
+ );
+ } else {
+ batcher_->drawQuad(
+ glm::vec3(item.position.x, item.position.y, item.depth),
+ finalSize,
+ item.texture_id,
+ item.color
+ );
+ }
+ }
+
+ batcher_->endBatch();
+ stats_.draw_calls = batcher_->getDrawCallCount();
+#endif
+}
+
+void RenderPipeline::executeNonBatched() {
+ Shader* shader = context_.getTextureShader();
+ VertexArray* quadVAO = context_.getQuadVAO();
+
+ if (!shader || !quadVAO) {
+ return;
+ }
+
+ glEnable(GL_BLEND);
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+
+ for (const auto& item : items_) {
+ glm::mat4 model = glm::mat4(1.0f);
+ model = glm::translate(model, item.position);
+ model *= glm::mat4_cast(item.rotation);
+ model = glm::scale(model, glm::vec3(
+ item.size.x * item.scale.x,
+ item.size.y * item.scale.y,
+ 1.0f
+ ));
+
+ shader->bind();
+ shader->setUniform("u_projection", view_projection_);
+ shader->setUniform("u_model", model);
+ shader->setUniform("u_color", item.color);
+
+ glActiveTexture(GL_TEXTURE0);
+ glBindTexture(GL_TEXTURE_2D, item.texture_id);
+ shader->setUniform("u_texture", 0);
+
+ RenderCommand::drawIndexed(*quadVAO);
+ stats_.draw_calls++;
+ }
+}
+
+} // namespace esengine
diff --git a/src/esengine/renderer/RenderPipeline.hpp b/src/esengine/renderer/RenderPipeline.hpp
new file mode 100644
index 000000000..cb5fb50e9
--- /dev/null
+++ b/src/esengine/renderer/RenderPipeline.hpp
@@ -0,0 +1,204 @@
+/**
+ * @file RenderPipeline.hpp
+ * @brief Unified 2D render pipeline with batching and sorting
+ * @details Provides efficient sprite rendering with layer sorting,
+ * texture batching, and optional frustum culling.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+#pragma once
+
+// =============================================================================
+// Includes
+// =============================================================================
+
+#include "../core/Types.hpp"
+#include "../math/Math.hpp"
+#include "../ecs/Registry.hpp"
+#include "../ecs/components/Transform.hpp"
+#include "../ecs/components/Sprite.hpp"
+#include "RenderContext.hpp"
+#include "../resource/ResourceManager.hpp"
+
+#include <vector>
+
+namespace esengine {
+
+// =============================================================================
+// Forward Declarations
+// =============================================================================
+
+class BatchRenderer2D;
+
+// =============================================================================
+// RenderItem
+// =============================================================================
+
+/**
+ * @brief Single renderable item in the pipeline
+ */
+struct RenderItem {
+ Entity entity; ///< Source entity ID
+ glm::vec3 position; ///< World position
+ glm::quat rotation; ///< World rotation
+ glm::vec3 scale; ///< World scale
+ glm::vec2 size; ///< Sprite size
+ glm::vec4 color; ///< Tint color
+ glm::vec2 uv_offset; ///< UV offset for sprite sheets
+ glm::vec2 uv_scale; ///< UV scale for sprite sheets
+ u32 texture_id; ///< GPU texture handle
+ i32 layer; ///< Render layer
+ f32 depth; ///< Z depth for sorting
+ bool flip_x; ///< Horizontal flip
+ bool flip_y; ///< Vertical flip
+
+ /** @brief Generates a 64-bit sort key for efficient sorting */
+ u64 sortKey() const;
+};
+
+// =============================================================================
+// RenderBatch
+// =============================================================================
+
+/**
+ * @brief Group of render items sharing the same texture
+ */
+struct RenderBatch {
+ u32 texture_id; ///< Batch texture
+ u32 start_index; ///< Start index in items array
+ u32 count; ///< Number of items in batch
+};
+
+// =============================================================================
+// RenderPipeline
+// =============================================================================
+
+/**
+ * @brief Unified 2D render pipeline
+ *
+ * @details Provides a collect-cull-sort-batch-render pipeline for efficient
+ * 2D sprite rendering. Uses BatchRenderer2D for batching multiple
+ * sprites into single draw calls.
+ *
+ * @code
+ * RenderPipeline pipeline(context, resourceManager);
+ *
+ * pipeline.begin(viewProjection);
+ * pipeline.submit(registry);
+ * pipeline.end();
+ *
+ * auto stats = pipeline.getStats();
+ * @endcode
+ */
+class RenderPipeline {
+public:
+ // =========================================================================
+ // Types
+ // =========================================================================
+
+ /**
+ * @brief Pipeline statistics
+ */
+ struct Stats {
+ u32 total_items = 0; ///< Total items submitted
+ u32 culled_items = 0; ///< Items culled by frustum
+ u32 visible_items = 0; ///< Items actually rendered
+ u32 batch_count = 0; ///< Number of batches
+ u32 draw_calls = 0; ///< Number of draw calls
+ };
+
+ // =========================================================================
+ // Constructor / Destructor
+ // =========================================================================
+
+ /**
+ * @brief Constructs render pipeline
+ * @param context Render context for shared resources
+ * @param resource_manager Resource manager for texture lookup
+ */
+ RenderPipeline(RenderContext& context, resource::ResourceManager& resource_manager);
+ ~RenderPipeline();
+
+ RenderPipeline(const RenderPipeline&) = delete;
+ RenderPipeline& operator=(const RenderPipeline&) = delete;
+
+ // =========================================================================
+ // Configuration
+ // =========================================================================
+
+ /**
+ * @brief Enables or disables frustum culling
+ * @param enabled True to enable culling
+ */
+ void setCullingEnabled(bool enabled) { culling_enabled_ = enabled; }
+
+ /**
+ * @brief Sets the view bounds for frustum culling
+ * @param bounds View bounds (left, right, bottom, top in world space)
+ */
+ void setViewBounds(const glm::vec4& bounds) { view_bounds_ = bounds; }
+
+ // =========================================================================
+ // Rendering
+ // =========================================================================
+
+ /**
+ * @brief Begins a new render frame
+ * @param view_projection Combined view-projection matrix
+ */
+ void begin(const glm::mat4& view_projection);
+
+ /**
+ * @brief Submits all sprite entities from registry
+ * @param registry ECS registry to collect from
+ */
+ void submit(ecs::Registry& registry);
+
+ /**
+ * @brief Submits a single render item manually
+ * @param item The item to render
+ */
+ void submit(const RenderItem& item);
+
+ /** @brief Ends the frame (sorts, batches, and renders) */
+ void end();
+
+ // =========================================================================
+ // Statistics
+ // =========================================================================
+
+ /** @brief Gets pipeline statistics for the last frame */
+ const Stats& getStats() const { return stats_; }
+
+ /** @brief Resets statistics counters */
+ void resetStats() { stats_ = Stats{}; }
+
+private:
+ void collectFromRegistry(ecs::Registry& registry);
+ void cullItems();
+ void sortItems();
+ void buildBatches();
+ void executeBatches();
+ void executeNonBatched();
+ bool isItemVisible(const RenderItem& item) const;
+
+ RenderContext& context_;
+ resource::ResourceManager& resource_manager_;
+ Unique<BatchRenderer2D> batcher_;
+
+ std::vector<RenderItem> items_;
+ std::vector<RenderBatch> batches_;
+
+ glm::mat4 view_projection_;
+ glm::vec4 view_bounds_;
+ bool culling_enabled_ = false;
+ bool batching_enabled_ = true;
+
+ Stats stats_;
+};
+
+} // namespace esengine