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.

fix: renderer correctness and performance improvements

esengined8f9b066be7f
diff --git a/src/esengine/bindings/GeometryBindings.cpp b/src/esengine/bindings/GeometryBindings.cpp
index 185d1bf2f..7848d9125 100644
--- a/src/esengine/bindings/GeometryBindings.cpp
+++ b/src/esengine/bindings/GeometryBindings.cpp
@@ -53,40 +53,36 @@ u32 geometry_create() {
void geometry_init(u32 handle, uintptr_t verticesPtr, u32 vertexCount,
uintptr_t layoutPtr, u32 layoutCount, bool dynamic) {
- if (!g_geometryManager) return;
+ if (!g_geometryManager || verticesPtr == 0 || layoutPtr == 0) return;
auto* geom = g_geometryManager->get(handle);
if (!geom) return;
+ static constexpr u32 MAX_ATTRS = 8;
+ if (layoutCount == 0 || layoutCount > MAX_ATTRS) {
+ ES_LOG_WARN("geometry_init: invalid layoutCount {}, max {}", layoutCount, MAX_ATTRS);
+ return;
+ }
+
const f32* vertices = reinterpret_cast<const f32*>(verticesPtr);
const i32* layoutData = reinterpret_cast<const i32*>(layoutPtr);
- static std::vector<VertexAttribute> s_attrs;
- s_attrs.clear();
- s_attrs.reserve(layoutCount);
+ static constexpr const char* ATTR_NAMES[] = {
+ "a_attr0", "a_attr1", "a_attr2", "a_attr3",
+ "a_attr4", "a_attr5", "a_attr6", "a_attr7"
+ };
+ std::vector<VertexAttribute> attrs;
+ attrs.reserve(layoutCount);
for (u32 i = 0; i < layoutCount; ++i) {
- ShaderDataType type = static_cast<ShaderDataType>(layoutData[i]);
- std::string name = "a_attr" + std::to_string(i);
- s_attrs.emplace_back(type, name);
+ attrs.emplace_back(static_cast<ShaderDataType>(layoutData[i]), ATTR_NAMES[i]);
}
- VertexLayout layout;
- if (layoutCount == 1) {
- layout = { s_attrs[0] };
- } else if (layoutCount == 2) {
- layout = { s_attrs[0], s_attrs[1] };
- } else if (layoutCount == 3) {
- layout = { s_attrs[0], s_attrs[1], s_attrs[2] };
- } else if (layoutCount == 4) {
- layout = { s_attrs[0], s_attrs[1], s_attrs[2], s_attrs[3] };
- }
-
- geom->init(vertices, vertexCount, layout, dynamic);
+ geom->init(vertices, vertexCount, VertexLayout(std::move(attrs)), dynamic);
}
void geometry_setIndices16(u32 handle, uintptr_t indicesPtr, u32 indexCount) {
- if (!g_geometryManager) return;
+ if (!g_geometryManager || indicesPtr == 0) return;
auto* geom = g_geometryManager->get(handle);
if (!geom) return;
@@ -96,7 +92,7 @@ void geometry_setIndices16(u32 handle, uintptr_t indicesPtr, u32 indexCount) {
}
void geometry_setIndices32(u32 handle, uintptr_t indicesPtr, u32 indexCount) {
- if (!g_geometryManager) return;
+ if (!g_geometryManager || indicesPtr == 0) return;
auto* geom = g_geometryManager->get(handle);
if (!geom) return;
@@ -106,7 +102,7 @@ void geometry_setIndices32(u32 handle, uintptr_t indicesPtr, u32 indexCount) {
}
void geometry_updateVertices(u32 handle, uintptr_t verticesPtr, u32 vertexCount, u32 offset) {
- if (!g_geometryManager) return;
+ if (!g_geometryManager || verticesPtr == 0) return;
auto* geom = g_geometryManager->get(handle);
if (!geom) return;
diff --git a/src/esengine/renderer/Buffer.hpp b/src/esengine/renderer/Buffer.hpp
index f46afac07..d4b9d2dc8 100644
--- a/src/esengine/renderer/Buffer.hpp
+++ b/src/esengine/renderer/Buffer.hpp
@@ -129,6 +129,11 @@ public:
calculateOffsetsAndStride();
}
+ VertexLayout(std::vector<VertexAttribute> attributes)
+ : attributes_(std::move(attributes)) {
+ calculateOffsetsAndStride();
+ }
+
/**
* @brief Gets all vertex attributes
* @return Const reference to attribute vector
diff --git a/src/esengine/renderer/CustomGeometry.cpp b/src/esengine/renderer/CustomGeometry.cpp
index 1820a1b26..ef79f11fa 100644
--- a/src/esengine/renderer/CustomGeometry.cpp
+++ b/src/esengine/renderer/CustomGeometry.cpp
@@ -24,12 +24,10 @@ void CustomGeometry::init(const f32* vertices, u32 vertexCount, const VertexLayo
vao_ = VertexArray::create();
if (dynamic) {
- vbo_ = makeShared<VertexBuffer>();
- *vbo_ = std::move(*VertexBuffer::create(vertexCount * sizeof(f32)));
+ vbo_ = Shared<VertexBuffer>(VertexBuffer::create(vertexCount * sizeof(f32)));
vbo_->setDataRaw(vertices, vertexCount * sizeof(f32));
} else {
- vbo_ = makeShared<VertexBuffer>();
- *vbo_ = std::move(*VertexBuffer::createRaw(vertices, vertexCount * sizeof(f32)));
+ vbo_ = Shared<VertexBuffer>(VertexBuffer::createRaw(vertices, vertexCount * sizeof(f32)));
}
vbo_->setLayout(layout);
@@ -39,16 +37,14 @@ void CustomGeometry::init(const f32* vertices, u32 vertexCount, const VertexLayo
void CustomGeometry::setIndices(const u16* indices, u32 indexCount) {
if (!vao_) return;
- ibo_ = makeShared<IndexBuffer>();
- *ibo_ = std::move(*IndexBuffer::create(indices, indexCount));
+ ibo_ = Shared<IndexBuffer>(IndexBuffer::create(indices, indexCount));
vao_->setIndexBuffer(ibo_);
}
void CustomGeometry::setIndices(const u32* indices, u32 indexCount) {
if (!vao_) return;
- ibo_ = makeShared<IndexBuffer>();
- *ibo_ = std::move(*IndexBuffer::create(indices, indexCount));
+ ibo_ = Shared<IndexBuffer>(IndexBuffer::create(indices, indexCount));
vao_->setIndexBuffer(ibo_);
}
diff --git a/src/esengine/renderer/Framebuffer.cpp b/src/esengine/renderer/Framebuffer.cpp
index 52b1c6a0c..0dd280fc8 100644
--- a/src/esengine/renderer/Framebuffer.cpp
+++ b/src/esengine/renderer/Framebuffer.cpp
@@ -90,7 +90,9 @@ void Framebuffer::resize(u32 width, u32 height) {
spec_.height = height;
cleanup();
- initialize();
+ if (!initialize()) {
+ ES_LOG_ERROR("Framebuffer resize failed: {}x{}", width, height);
+ }
}
// =============================================================================
@@ -120,6 +122,8 @@ bool Framebuffer::initialize() {
GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_TEXTURE_2D, depthAttachment_, 0);
}
@@ -128,6 +132,7 @@ bool Framebuffer::initialize() {
if (status != GL_FRAMEBUFFER_COMPLETE) {
ES_LOG_ERROR("Framebuffer is incomplete! Status: 0x{:X}", status);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
+ cleanup();
return false;
}
diff --git a/src/esengine/renderer/ImmediateDraw.cpp b/src/esengine/renderer/ImmediateDraw.cpp
index 3da689ef8..71d52b807 100644
--- a/src/esengine/renderer/ImmediateDraw.cpp
+++ b/src/esengine/renderer/ImmediateDraw.cpp
@@ -87,6 +87,8 @@ void ImmediateDraw::end() {
if (!initialized_ || !inFrame_) return;
impl_->batcher->endBatch();
+ glEnable(GL_DEPTH_TEST);
+ glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
inFrame_ = false;
}
diff --git a/src/esengine/renderer/OpenGLHeaders.hpp b/src/esengine/renderer/OpenGLHeaders.hpp
index 243b7110e..558c80b1b 100644
--- a/src/esengine/renderer/OpenGLHeaders.hpp
+++ b/src/esengine/renderer/OpenGLHeaders.hpp
@@ -28,3 +28,11 @@
#endif
#include <glad/glad.h>
#endif
+
+// GL error codes not present in all headers
+#ifndef GL_CONTEXT_LOST
+ #define GL_CONTEXT_LOST 0x0507
+#endif
+#ifndef GL_CONTEXT_LOST_WEBGL
+ #define GL_CONTEXT_LOST_WEBGL 0x9242
+#endif
diff --git a/src/esengine/renderer/PostProcessPipeline.cpp b/src/esengine/renderer/PostProcessPipeline.cpp
index 70499ae90..64ad58f3d 100644
--- a/src/esengine/renderer/PostProcessPipeline.cpp
+++ b/src/esengine/renderer/PostProcessPipeline.cpp
@@ -249,33 +249,37 @@ void PostProcessPipeline::end() {
if (pass.enabled) enabledCount++;
}
+ RenderCommand::setDepthTest(false);
+ RenderCommand::setBlending(false);
+
if (enabledCount == 0) {
fboA_->unbind();
blitToScreen(fboA_->getColorAttachment());
- inFrame_ = false;
- return;
- }
+ } else {
+ u32 inputTexture = fboA_->getColorAttachment();
+ currentFBO_ = 0;
- u32 inputTexture = fboA_->getColorAttachment();
- currentFBO_ = 0;
+ for (const auto& pass : passes_) {
+ if (!pass.enabled) continue;
- for (const auto& pass : passes_) {
- if (!pass.enabled) continue;
+ Framebuffer* targetFBO = (currentFBO_ == 0) ? fboB_.get() : fboA_.get();
+ targetFBO->bind();
+ RenderCommand::setViewport(0, 0, width_, height_);
- Framebuffer* targetFBO = (currentFBO_ == 0) ? fboB_.get() : fboA_.get();
- targetFBO->bind();
- RenderCommand::setViewport(0, 0, width_, height_);
+ renderPass(pass, inputTexture);
- renderPass(pass, inputTexture);
+ inputTexture = targetFBO->getColorAttachment();
+ currentFBO_ = 1 - currentFBO_;
+ }
- inputTexture = targetFBO->getColorAttachment();
- currentFBO_ = 1 - currentFBO_;
- }
+ Framebuffer* lastFBO = (currentFBO_ == 0) ? fboA_.get() : fboB_.get();
+ lastFBO->unbind();
- Framebuffer* lastFBO = (currentFBO_ == 0) ? fboA_.get() : fboB_.get();
- lastFBO->unbind();
+ blitToScreen(inputTexture);
+ }
- blitToScreen(inputTexture);
+ RenderCommand::setBlending(true);
+ RenderCommand::setDepthTest(true);
inFrame_ = false;
}
@@ -298,12 +302,7 @@ void PostProcessPipeline::renderPass(const PostProcessPass& pass, u32 inputTextu
shader->setUniform(name, value);
}
- RenderCommand::setDepthTest(false);
- RenderCommand::setBlending(false);
-
RenderCommand::drawIndexed(*screenQuadVAO_, 6);
-
- RenderCommand::setBlending(true);
}
void PostProcessPipeline::blitToScreen(u32 texture) {
@@ -316,12 +315,7 @@ void PostProcessPipeline::blitToScreen(u32 texture) {
shader->bind();
shader->setUniform("u_texture", 0);
- RenderCommand::setDepthTest(false);
- RenderCommand::setBlending(false);
-
RenderCommand::drawIndexed(*screenQuadVAO_, 6);
-
- RenderCommand::setBlending(true);
}
u32 PostProcessPipeline::getSourceTexture() const {
diff --git a/src/esengine/renderer/RenderCommand.hpp b/src/esengine/renderer/RenderCommand.hpp
index a4e3eaee8..2b2692eb8 100644
--- a/src/esengine/renderer/RenderCommand.hpp
+++ b/src/esengine/renderer/RenderCommand.hpp
@@ -156,6 +156,8 @@ public:
*/
static void setBlendMode(BlendMode mode);
+ static void resetBlendState();
+
// =========================================================================
// Face Culling
// =========================================================================
diff --git a/src/esengine/renderer/RenderContext.cpp b/src/esengine/renderer/RenderContext.cpp
index adadac6f6..b5edd4f42 100644
--- a/src/esengine/renderer/RenderContext.cpp
+++ b/src/esengine/renderer/RenderContext.cpp
@@ -97,17 +97,11 @@ void RenderContext::initShaders() {
ShaderSources::SPRITE_FRAGMENT
);
- extMeshShader_ = Shader::create(
+ extMeshShader_ = Shader::createWithBindings(
ShaderSources::EXT_MESH_VERTEX,
- ShaderSources::EXT_MESH_FRAGMENT
+ ShaderSources::EXT_MESH_FRAGMENT,
+ {{0, "a_position"}, {1, "a_texCoord"}, {2, "a_color"}}
);
- if (extMeshShader_ && extMeshShader_->isValid()) {
- GLuint prog = extMeshShader_->getProgramId();
- glBindAttribLocation(prog, 0, "a_position");
- glBindAttribLocation(prog, 1, "a_texCoord");
- glBindAttribLocation(prog, 2, "a_color");
- glLinkProgram(prog);
- }
ES_LOG_DEBUG("Shaders initialized");
}
@@ -121,6 +115,8 @@ void RenderContext::initWhiteTexture() {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
ES_LOG_DEBUG("White texture created (ID: {})", whiteTextureId_);
}
diff --git a/src/esengine/renderer/RenderFrame.cpp b/src/esengine/renderer/RenderFrame.cpp
index 6c960eee6..7c9b3a3cc 100644
--- a/src/esengine/renderer/RenderFrame.cpp
+++ b/src/esengine/renderer/RenderFrame.cpp
@@ -2,6 +2,7 @@
#include "Renderer.hpp"
#include "RenderCommand.hpp"
#include "Texture.hpp"
+#include "CustomGeometry.hpp"
#include "../core/Log.hpp"
#include "../ecs/components/Transform.hpp"
#include "../ecs/components/Sprite.hpp"
@@ -79,24 +80,20 @@ bool Frustum::intersectsAABB(const glm::vec3& center, const glm::vec3& halfExten
return true;
}
-struct UniformData {
- char name[32];
- u32 type;
- f32 values[4];
-};
-
#ifdef ES_PLATFORM_WEB
extern bool getMaterialData(u32 materialId, u32& shaderId, u32& blendMode);
extern bool getMaterialDataWithUniforms(u32 materialId, u32& shaderId, u32& blendMode,
- std::vector<UniformData>& uniforms);
+ std::vector<MaterialUniformData>& uniforms);
+extern void clearMaterialCache();
#else
bool getMaterialData(u32 /*materialId*/, u32& /*shaderId*/, u32& /*blendMode*/) {
return false;
}
bool getMaterialDataWithUniforms(u32 /*materialId*/, u32& /*shaderId*/, u32& /*blendMode*/,
- std::vector<UniformData>& /*uniforms*/) {
+ std::vector<MaterialUniformData>& /*uniforms*/) {
return false;
}
+void clearMaterialCache() {}
#endif
RenderFrame::RenderFrame(RenderContext& context, resource::ResourceManager& resource_manager)
@@ -157,35 +154,26 @@ void RenderFrame::init(u32 width, u32 height) {
spine_vbo_capacity_ = 0;
spine_ebo_capacity_ = 0;
- spine_shader_handle_ = resource_manager_.createShader(
+ spine_shader_handle_ = resource_manager_.createShaderWithBindings(
ShaderSources::BATCH_VERTEX,
- ShaderSources::BATCH_FRAGMENT
+ ShaderSources::BATCH_FRAGMENT,
+ {{0, "a_position"}, {1, "a_color"}, {2, "a_texCoord"}, {3, "a_texIndex"}}
);
Shader* spineShader = resource_manager_.getShader(spine_shader_handle_);
if (!spineShader || !spineShader->isValid()) {
- spine_shader_handle_ = resource_manager_.createShader(
+ spine_shader_handle_ = resource_manager_.createShaderWithBindings(
ShaderSources::BATCH_VERTEX_COMPAT,
- ShaderSources::BATCH_FRAGMENT_COMPAT
+ ShaderSources::BATCH_FRAGMENT_COMPAT,
+ {{0, "a_position"}, {1, "a_color"}, {2, "a_texCoord"}, {3, "a_texIndex"}}
);
spineShader = resource_manager_.getShader(spine_shader_handle_);
}
if (spineShader && spineShader->isValid()) {
- GLuint prog = spineShader->getProgramId();
- glBindAttribLocation(prog, 0, "a_position");
- glBindAttribLocation(prog, 1, "a_color");
- glBindAttribLocation(prog, 2, "a_texCoord");
- glBindAttribLocation(prog, 3, "a_texIndex");
- glLinkProgram(prog);
-
- GLint linkStatus;
- glGetProgramiv(prog, GL_LINK_STATUS, &linkStatus);
- if (linkStatus) {
- spineShader->bind();
- GLint baseLoc = glGetUniformLocation(prog, "u_textures[0]");
- if (baseLoc >= 0) {
- for (i32 i = 0; i < static_cast<i32>(SPINE_MAX_TEXTURE_SLOTS); ++i) {
- glUniform1i(baseLoc + i, i);
- }
+ spineShader->bind();
+ GLint baseLoc = glGetUniformLocation(spineShader->getProgramId(), "u_textures[0]");
+ if (baseLoc >= 0) {
+ for (i32 i = 0; i < static_cast<i32>(SPINE_MAX_TEXTURE_SLOTS); ++i) {
+ glUniform1i(baseLoc + i, i);
}
}
}
@@ -292,6 +280,7 @@ void RenderFrame::begin(const glm::mat4& view_projection, RenderTargetManager::H
#endif
ext_storage_count_ = 0;
ext_submit_order_ = 0;
+ mat_sprite_last_shader_ = 0;
stats_ = Stats{};
bool usePostProcess = post_process_ && post_process_->isInitialized() &&
@@ -316,6 +305,7 @@ void RenderFrame::flush() {
glEnable(GL_BLEND);
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
+ RenderCommand::resetBlendState();
glDisable(GL_DEPTH_TEST);
executeStage(RenderStage::Background);
@@ -409,27 +399,17 @@ void RenderFrame::endStencilTest() {
}
void RenderFrame::submitSprites(ecs::Registry& registry) {
- auto spriteView = registry.view<ecs::LocalTransform, ecs::Sprite>();
+ auto spriteView = registry.view<ecs::Transform, ecs::Sprite>();
for (auto entity : spriteView) {
const auto& sprite = spriteView.get<ecs::Sprite>(entity);
if (!sprite.enabled) continue;
- glm::vec3 position;
- glm::quat rotation;
- glm::vec3 scale;
-
- if (registry.has<ecs::WorldTransform>(entity)) {
- const auto& world = registry.get<ecs::WorldTransform>(entity);
- position = world.position;
- rotation = world.rotation;
- scale = world.scale;
- } else {
- const auto& local = spriteView.get<ecs::LocalTransform>(entity);
- position = local.position;
- rotation = local.rotation;
- scale = local.scale;
- }
+ auto& transform = spriteView.get<ecs::Transform>(entity);
+ transform.ensureDecomposed();
+ const auto& position = transform.worldPosition;
+ const auto& rotation = transform.worldRotation;
+ const auto& scale = transform.worldScale;
glm::vec3 halfExtents = glm::vec3(sprite.size.x * scale.x, sprite.size.y * scale.y, 0.0f) * 0.5f;
if (!frustum_.intersectsAABB(position, halfExtents)) {
@@ -501,13 +481,14 @@ void RenderFrame::submitSprites(ecs::Registry& registry) {
base.data_index = static_cast<u32>(sprite_data_.size());
sprite_data_.push_back(sd);
+ base.cached_sort_key_ = base.sortKey();
items_.push_back(base);
stats_.sprites++;
}
}
void RenderFrame::submitBitmapText(ecs::Registry& registry) {
- auto textView = registry.view<ecs::LocalTransform, ecs::BitmapText>();
+ auto textView = registry.view<ecs::Transform, ecs::BitmapText>();
for (auto entity : textView) {
const auto& bt = textView.get<ecs::BitmapText>(entity);
@@ -526,18 +507,10 @@ void RenderFrame::submitBitmapText(ecs::Registry& registry) {
continue;
}
- glm::vec3 position;
- glm::vec3 scale{1.0f};
-
- if (registry.has<ecs::WorldTransform>(entity)) {
- const auto& world = registry.get<ecs::WorldTransform>(entity);
- position = world.position;
- scale = world.scale;
- } else {
- const auto& local = textView.get<ecs::LocalTransform>(entity);
- position = local.position;
- scale = local.scale;
- }
+ auto& transform = textView.get<ecs::Transform>(entity);
+ transform.ensureDecomposed();
+ const auto& position = transform.worldPosition;
+ const auto& scale = transform.worldScale;
auto textMetrics = font->measureText(bt.text, bt.fontSize, bt.spacing);
glm::vec3 halfExtents = glm::vec3(
@@ -580,6 +553,7 @@ void RenderFrame::submitBitmapText(ecs::Registry& registry) {
base.data_index = static_cast<u32>(text_data_.size());
text_data_.push_back(td);
+ base.cached_sort_key_ = base.sortKey();
items_.push_back(base);
stats_.text++;
}
@@ -600,16 +574,12 @@ void RenderFrame::submitSpine(ecs::Registry& registry, spine::SpineSystem& spine
glm::quat rotation{1.0f, 0.0f, 0.0f, 0.0f};
glm::vec3 scale{1.0f};
- if (registry.has<ecs::WorldTransform>(entity)) {
- const auto& world = registry.get<ecs::WorldTransform>(entity);
- position = world.position;
- rotation = world.rotation;
- scale = world.scale;
- } else if (registry.has<ecs::LocalTransform>(entity)) {
- const auto& local = registry.get<ecs::LocalTransform>(entity);
- position = local.position;
- rotation = local.rotation;
- scale = local.scale;
+ if (registry.has<ecs::Transform>(entity)) {
+ auto& t = registry.get<ecs::Transform>(entity);
+ t.ensureDecomposed();
+ position = t.worldPosition;
+ rotation = t.worldRotation;
+ scale = t.worldScale;
}
RenderItemBase base;
@@ -633,6 +603,7 @@ void RenderFrame::submitSpine(ecs::Registry& registry, spine::SpineSystem& spine
base.data_index = static_cast<u32>(spine_data_.size());
spine_data_.push_back(sd);
+ base.cached_sort_key_ = base.sortKey();
items_.push_back(base);
stats_.spine++;
}
@@ -647,6 +618,7 @@ void RenderFrame::submit(const RenderItemBase& item, const SpriteData& data) {
copy.data_index = static_cast<u32>(sprite_data_.size());
sprite_data_.push_back(data);
+ copy.cached_sort_key_ = copy.sortKey();
items_.push_back(copy);
switch (copy.type) {
@@ -699,6 +671,7 @@ void RenderFrame::submitExternalTriangles(
base.data_index = static_cast<u32>(ext_data_.size());
ext_data_.push_back(ed);
+ base.cached_sort_key_ = base.sortKey();
items_.push_back(base);
}
@@ -711,7 +684,7 @@ void RenderFrame::sortAndBucket() {
std::sort(sorted_indices_.begin(), sorted_indices_.end(),
[this](u32 a, u32 b) {
- return items_[a].sortKey() < items_[b].sortKey();
+ return items_[a].cached_sort_key_ < items_[b].cached_sort_key_;
});
for (auto& sb : stage_boundaries_) {
@@ -789,6 +762,7 @@ void RenderFrame::renderSprites(u32 begin, u32 end) {
bool curScissorOn = false;
ScissorRect curRect{};
bool stencilTestActive = false;
+ bool stencilWriteActive = false;
i32 curStencilRef = -1;
for (u32 i = begin; i < end; ++i) {
@@ -797,6 +771,11 @@ void RenderFrame::renderSprites(u32 begin, u32 end) {
if (base.scissor_enabled != curScissorOn ||
(base.scissor_enabled && base.scissor != curRect)) {
+ if (stencilWriteActive) {
+ batcher_->flush();
+ endStencilWrite();
+ stencilWriteActive = false;
+ }
batcher_->flush();
if (base.scissor_enabled) {
glEnable(GL_SCISSOR_TEST);
@@ -813,8 +792,17 @@ void RenderFrame::renderSprites(u32 begin, u32 end) {
auto stIt = stencil_masks_.find(static_cast<u32>(base.entity));
if (stIt != stencil_masks_.end()) {
if (stIt->second.is_mask) {
- batcher_->flush();
- beginStencilWrite(stIt->second.ref_value);
+ if (!stencilWriteActive || curStencilRef != stIt->second.ref_value) {
+ if (stencilWriteActive) {
+ batcher_->flush();
+ endStencilWrite();
+ } else {
+ batcher_->flush();
+ }
+ beginStencilWrite(stIt->second.ref_value);
+ stencilWriteActive = true;
+ curStencilRef = stIt->second.ref_value;
+ }
glm::vec2 position(base.world_position);
glm::vec2 finalSize = sd.size * base.world_scale;
@@ -828,10 +816,13 @@ void RenderFrame::renderSprites(u32 begin, u32 end) {
finalSize, base.texture_id, base.color, sd.uv_offset, sd.uv_scale);
}
- batcher_->flush();
- endStencilWrite();
continue;
} else {
+ if (stencilWriteActive) {
+ batcher_->flush();
+ endStencilWrite();
+ stencilWriteActive = false;
+ }
if (!stencilTestActive || curStencilRef != stIt->second.ref_value) {
batcher_->flush();
beginStencilTest(stIt->second.ref_value);
@@ -839,11 +830,18 @@ void RenderFrame::renderSprites(u32 begin, u32 end) {
curStencilRef = stIt->second.ref_value;
}
}
- } else if (stencilTestActive) {
- batcher_->flush();
- endStencilTest();
- stencilTestActive = false;
- curStencilRef = -1;
+ } else {
+ if (stencilWriteActive) {
+ batcher_->flush();
+ endStencilWrite();
+ stencilWriteActive = false;
+ }
+ if (stencilTestActive) {
+ batcher_->flush();
+ endStencilTest();
+ stencilTestActive = false;
+ curStencilRef = -1;
+ }
}
}
@@ -857,6 +855,17 @@ void RenderFrame::renderSprites(u32 begin, u32 end) {
glm::vec2 finalSize = sd.size * base.world_scale;
f32 angle = base.world_angle;
+ glm::vec2 uvOff = sd.uv_offset;
+ glm::vec2 uvSc = sd.uv_scale;
+ if (sd.flip_x) {
+ uvOff.x += uvSc.x;
+ uvSc.x = -uvSc.x;
+ }
+ if (sd.flip_y) {
+ uvOff.y += uvSc.y;
+ uvSc.y = -uvSc.y;
+ }
+
if (sd.use_nine_slice) {
resource::SliceBorder border;
border.left = sd.slice_border.x;
@@ -872,8 +881,8 @@ void RenderFrame::renderSprites(u32 begin, u32 end) {
border,
base.color,
angle,
- sd.uv_offset,
- sd.uv_scale
+ uvOff,
+ uvSc
);
} else if (std::abs(angle) > 0.001f) {
batcher_->drawRotatedQuad(
@@ -882,8 +891,8 @@ void RenderFrame::renderSprites(u32 begin, u32 end) {
angle,
base.texture_id,
base.color,
- sd.uv_offset,
- sd.uv_scale
+ uvOff,
+ uvSc
);
} else {
batcher_->drawQuad(
@@ -891,12 +900,17 @@ void RenderFrame::renderSprites(u32 begin, u32 end) {
finalSize,
base.texture_id,
base.color,
- sd.uv_offset,
- sd.uv_scale
+ uvOff,
+ uvSc
);
}
}
+ if (stencilWriteActive) {
+ batcher_->flush();
+ endStencilWrite();
+ }
+
if (stencilTestActive) {
batcher_->flush();
endStencilTest();
@@ -917,6 +931,7 @@ void RenderFrame::renderSpine(u32 begin, u32 end) {
spine_vertices_.clear();
spine_indices_.clear();
spine_tex_slots_.reset();
+ spine_current_blend_ = BlendMode::Normal;
static ::spine::SkeletonClipping clipper;
@@ -990,6 +1005,10 @@ void RenderFrame::renderSpine(u32 begin, u32 end) {
if (texIndex < 0.0f) {
flushSpineBatch();
texIndex = spine_tex_slots_.findOrAllocate(textureId);
+ if (texIndex < 0.0f) {
+ ES_LOG_WARN("TextureSlotAllocator: failed after flush for spine region");
+ continue;
+ }
}
if (spine_vertices_.size() + 4 > 65535) {
@@ -1067,6 +1086,10 @@ void RenderFrame::renderSpine(u32 begin, u32 end) {
if (texIndex < 0.0f) {
flushSpineBatch();
texIndex = spine_tex_slots_.findOrAllocate(textureId);
+ if (texIndex < 0.0f) {
+ ES_LOG_WARN("TextureSlotAllocator: failed after flush for spine mesh");
+ continue;
+ }
}
if (spine_vertices_.size() + vertexCount > 65535) {
@@ -1114,6 +1137,7 @@ void RenderFrame::renderSpine(u32 begin, u32 end) {
}
flushSpineBatch();
+ RenderCommand::setBlendMode(BlendMode::Normal);
}
void RenderFrame::flushSpineBatch() {
@@ -1220,6 +1244,8 @@ void RenderFrame::renderExternalMeshes(u32 begin, u32 end) {
stats_.triangles += static_cast<u32>(ed.ext_index_count / 3);
stats_.draw_calls++;
}
+
+ RenderCommand::setBlendMode(BlendMode::Normal);
}
void RenderFrame::renderMeshes(u32 begin, u32 end) {
@@ -1227,7 +1253,31 @@ void RenderFrame::renderMeshes(u32 begin, u32 end) {
const auto& base = items_[sorted_indices_[i]];
const auto& sd = sprite_data_[base.data_index];
if (!sd.geometry || !sd.shader) continue;
+
+ auto* geom = static_cast<CustomGeometry*>(sd.geometry);
+ auto* shader = static_cast<Shader*>(sd.shader);
+ if (!geom->isValid()) continue;
+
+ shader->bind();
+ shader->setUniform("u_projection", view_projection_);
+ shader->setUniform("u_model", sd.transform);
+
+ geom->bind();
+ if (geom->hasIndices()) {
+ auto* ib = geom->getVAO() ? geom->getVAO()->getIndexBuffer().get() : nullptr;
+ if (ib) {
+ GLenum type = ib->is16Bit() ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
+ glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(geom->getIndexCount()), type, nullptr);
+ }
+ } else {
+ glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(geom->getVertexCount()));
+ }
+ geom->unbind();
+
stats_.draw_calls++;
+ stats_.triangles += geom->hasIndices()
+ ? static_cast<u32>(geom->getIndexCount() / 3)
+ : static_cast<u32>(geom->getVertexCount() / 3);
}
}
@@ -1412,10 +1462,9 @@ void RenderFrame::renderText(u32 begin, u32 end) {
void RenderFrame::renderSpriteWithMaterial(const RenderItemBase& base, const SpriteData& sd) {
u32 shaderId = 0;
u32 blendMode = 0;
- static std::vector<UniformData> uniforms;
- uniforms.clear();
+ mat_uniforms_.clear();
- if (!getMaterialDataWithUniforms(sd.material_id, shaderId, blendMode, uniforms)) {
+ if (!getMaterialDataWithUniforms(sd.material_id, shaderId, blendMode, mat_uniforms_)) {
return;
}
@@ -1437,7 +1486,7 @@ void RenderFrame::renderSpriteWithMaterial(const RenderItemBase& base, const Spr
glBindTexture(GL_TEXTURE_2D, base.texture_id);
shader->setUniform(locTex, 0);
- for (const auto& ud : uniforms) {
+ for (const auto& ud : mat_uniforms_) {
i32 loc = shader->getUniformLocation(ud.name);
switch (ud.type) {
case 0:
@@ -1459,6 +1508,11 @@ void RenderFrame::renderSpriteWithMaterial(const RenderItemBase& base, const Spr
glm::vec2 halfSize = sd.size * 0.5f;
+ glm::vec2 uvMin = sd.uv_offset;
+ glm::vec2 uvMax = sd.uv_offset + sd.uv_scale;
+ if (sd.flip_x) { std::swap(uvMin.x, uvMax.x); }
+ if (sd.flip_y) { std::swap(uvMin.y, uvMax.y); }
+
struct MatSpriteVertex {
f32 px, py;
f32 tx, ty;
@@ -1466,10 +1520,10 @@ void RenderFrame::renderSpriteWithMaterial(const RenderItemBase& base, const Spr
};
MatSpriteVertex vertices[4] = {
- { -halfSize.x, -halfSize.y, 0.0f, 1.0f, base.color.r, base.color.g, base.color.b, base.color.a },
- { halfSize.x, -halfSize.y, 1.0f, 1.0f, base.color.r, base.color.g, base.color.b, base.color.a },
- { halfSize.x, halfSize.y, 1.0f, 0.0f, base.color.r, base.color.g, base.color.b, base.color.a },
- { -halfSize.x, halfSize.y, 0.0f, 0.0f, base.color.r, base.color.g, base.color.b, base.color.a },
+ { -halfSize.x, -halfSize.y, uvMin.x, uvMax.y, base.color.r, base.color.g, base.color.b, base.color.a },
+ { halfSize.x, -halfSize.y, uvMax.x, uvMax.y, base.color.r, base.color.g, base.color.b, base.color.a },
+ { halfSize.x, halfSize.y, uvMax.x, uvMin.y, base.color.r, base.color.g, base.color.b, base.color.a },
+ { -halfSize.x, halfSize.y, uvMin.x, uvMin.y, base.color.r, base.color.g, base.color.b, base.color.a },
};
glBindVertexArray(mat_sprite_vao_);
@@ -1481,25 +1535,30 @@ void RenderFrame::renderSpriteWithMaterial(const RenderItemBase& base, const Spr
}
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
- GLint attrPos = shader->getAttribLocation("a_position");
- if (attrPos >= 0) {
- glEnableVertexAttribArray(attrPos);
- glVertexAttribPointer(attrPos, 2, GL_FLOAT, GL_FALSE, sizeof(MatSpriteVertex),
- reinterpret_cast<void*>(0));
- }
+ u32 programId = shader->getProgramId();
+ if (programId != mat_sprite_last_shader_) {
+ mat_sprite_last_shader_ = programId;
- GLint attrTex = shader->getAttribLocation("a_texCoord");
- if (attrTex >= 0) {
- glEnableVertexAttribArray(attrTex);
- glVertexAttribPointer(attrTex, 2, GL_FLOAT, GL_FALSE, sizeof(MatSpriteVertex),
- reinterpret_cast<void*>(2 * sizeof(f32)));
- }
+ GLint attrPos = shader->getAttribLocation("a_position");
+ if (attrPos >= 0) {
+ glEnableVertexAttribArray(attrPos);
+ glVertexAttribPointer(attrPos, 2, GL_FLOAT, GL_FALSE, sizeof(MatSpriteVertex),
+ reinterpret_cast<void*>(0));
+ }
+
+ GLint attrTex = shader->getAttribLocation("a_texCoord");
+ if (attrTex >= 0) {
+ glEnableVertexAttribArray(attrTex);
+ glVertexAttribPointer(attrTex, 2, GL_FLOAT, GL_FALSE, sizeof(MatSpriteVertex),
+ reinterpret_cast<void*>(2 * sizeof(f32)));
+ }
- GLint attrColor = shader->getAttribLocation("a_color");
- if (attrColor >= 0) {
- glEnableVertexAttribArray(attrColor);
- glVertexAttribPointer(attrColor, 4, GL_FLOAT, GL_FALSE, sizeof(MatSpriteVertex),
- reinterpret_cast<void*>(4 * sizeof(f32)));
+ GLint attrColor = shader->getAttribLocation("a_color");
+ if (attrColor >= 0) {
+ glEnableVertexAttribArray(attrColor);
+ glVertexAttribPointer(attrColor, 4, GL_FLOAT, GL_FALSE, sizeof(MatSpriteVertex),
+ reinterpret_cast<void*>(4 * sizeof(f32)));
+ }
}
if (!mat_sprite_ebo_initialized_) {
@@ -1513,12 +1572,10 @@ void RenderFrame::renderSpriteWithMaterial(const RenderItemBase& base, const Spr
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, nullptr);
- if (attrPos >= 0) glDisableVertexAttribArray(attrPos);
- if (attrTex >= 0) glDisableVertexAttribArray(attrTex);
- if (attrColor >= 0) glDisableVertexAttribArray(attrColor);
-
glBindVertexArray(0);
+ RenderCommand::setBlendMode(BlendMode::Normal);
+
stats_.draw_calls++;
stats_.triangles += 2;
}
diff --git a/src/esengine/renderer/RenderFrame.hpp b/src/esengine/renderer/RenderFrame.hpp
index adcde2287..10c8916e6 100644
--- a/src/esengine/renderer/RenderFrame.hpp
+++ b/src/esengine/renderer/RenderFrame.hpp
@@ -30,6 +30,12 @@ struct Frustum {
class BatchRenderer2D;
+struct MaterialUniformData {
+ char name[32];
+ u32 type;
+ f32 values[4];
+};
+
#ifdef ES_ENABLE_SPINE
namespace spine {
class SpineSystem;
@@ -185,6 +191,7 @@ private:
u32 mat_sprite_ebo_ = 0;
bool mat_sprite_ebo_initialized_ = false;
bool mat_sprite_vbo_allocated_ = false;
+ u32 mat_sprite_last_shader_ = 0;
std::unordered_map<u32, ScissorRect> clip_rects_;
@@ -193,6 +200,8 @@ private:
bool is_mask = false;
};
std::unordered_map<u32, EntityStencilInfo> stencil_masks_;
+
+ std::vector<MaterialUniformData> mat_uniforms_;
};
} // namespace esengine
diff --git a/src/esengine/renderer/RenderItem.hpp b/src/esengine/renderer/RenderItem.hpp
index 58ffe2084..f49e4eb99 100644
--- a/src/esengine/renderer/RenderItem.hpp
+++ b/src/esengine/renderer/RenderItem.hpp
@@ -4,6 +4,7 @@
#include "RenderStage.hpp"
#include "BlendMode.hpp"
+#include <algorithm>
#include <glm/glm.hpp>
namespace esengine {
@@ -46,14 +47,17 @@ struct RenderItemBase {
ScissorRect scissor;
u32 data_index = 0;
+ u64 cached_sort_key_ = 0;
u64 sortKey() const {
u64 stageKey = static_cast<u64>(stage) << 60;
- i32 normalizedLayer = layer + 32768;
+ i32 normalizedLayer = std::clamp(layer + 32768, 0, 65535);
u64 layerKey = static_cast<u64>(normalizedLayer & 0xFFFF) << 44;
- u64 textureKey = static_cast<u64>(texture_id & 0xFFFFF) << 24;
+ u64 typeKey = static_cast<u64>(type) << 41;
+
+ u64 textureKey = static_cast<u64>(texture_id & 0x1FFFF) << 24;
u32 depthBits;
if (stage == RenderStage::Transparent) {
@@ -65,7 +69,7 @@ struct RenderItemBase {
}
u64 depthKey = static_cast<u64>(depthBits & 0xFFFFFF);
- return stageKey | layerKey | textureKey | depthKey;
+ return stageKey | layerKey | typeKey | textureKey | depthKey;
}
};
diff --git a/src/esengine/renderer/Renderer.cpp b/src/esengine/renderer/Renderer.cpp
index e24d1cab7..9cb4788dd 100644
--- a/src/esengine/renderer/Renderer.cpp
+++ b/src/esengine/renderer/Renderer.cpp
@@ -35,6 +35,8 @@ namespace esengine {
// RenderCommand Implementation
// ========================================
+static BlendMode s_current_blend_ = BlendMode::Normal;
+
void RenderCommand::init() {
// Enable depth testing by default
glEnable(GL_DEPTH_TEST);
@@ -98,7 +100,13 @@ void RenderCommand::setBlendFunc() {
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
}
+void RenderCommand::resetBlendState() {
+ s_current_blend_ = BlendMode::Normal;
+}
+
void RenderCommand::setBlendMode(BlendMode mode) {
+ if (mode == s_current_blend_) return;
+ s_current_blend_ = mode;
switch (mode) {
case BlendMode::Normal:
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
@@ -302,6 +310,7 @@ struct BatchRenderer2D::BatchData {
TextureSlotAllocator<MAX_TEXTURE_SLOTS> texSlots;
glm::mat4 projection{1.0f};
+ i32 projectionLoc = -1;
u32 drawCallCount = 0;
u32 quadCount = 0;
@@ -357,9 +366,10 @@ void BatchRenderer2D::init() {
data_->shader_handle = resource_manager_.loadEngineShader("batch");
#endif
if (!data_->shader_handle.isValid()) {
- data_->shader_handle = resource_manager_.createShader(
+ data_->shader_handle = resource_manager_.createShaderWithBindings(
ShaderSources::BATCH_VERTEX,
- ShaderSources::BATCH_FRAGMENT
+ ShaderSources::BATCH_FRAGMENT,
+ {{0, "a_position"}, {1, "a_color"}, {2, "a_texCoord"}, {3, "a_texIndex"}}
);
}
@@ -367,38 +377,30 @@ void BatchRenderer2D::init() {
if (!batchShader || !batchShader->isValid()) {
ES_LOG_WARN("GLSL ES 3.0 batch shader failed, trying GLSL ES 1.0 fallback");
- data_->shader_handle = resource_manager_.createShader(
+ data_->shader_handle = resource_manager_.createShaderWithBindings(
ShaderSources::BATCH_VERTEX_COMPAT,
- ShaderSources::BATCH_FRAGMENT_COMPAT
+ ShaderSources::BATCH_FRAGMENT_COMPAT,
+ {{0, "a_position"}, {1, "a_color"}, {2, "a_texCoord"}, {3, "a_texIndex"}}
);
batchShader = resource_manager_.getShader(data_->shader_handle);
}
if (batchShader && batchShader->isValid()) {
- GLuint prog = batchShader->getProgramId();
- glBindAttribLocation(prog, 0, "a_position");
- glBindAttribLocation(prog, 1, "a_color");
- glBindAttribLocation(prog, 2, "a_texCoord");
- glBindAttribLocation(prog, 3, "a_texIndex");
- glLinkProgram(prog);
-
- GLint linkStatus;
- glGetProgramiv(prog, GL_LINK_STATUS, &linkStatus);
- if (linkStatus) {
- batchShader->bind();
- GLint baseLoc = glGetUniformLocation(prog, "u_textures[0]");
- if (baseLoc >= 0) {
- for (i32 i = 0; i < static_cast<i32>(MAX_TEXTURE_SLOTS); ++i) {
- glUniform1i(baseLoc + i, i);
- }
+ batchShader->bind();
+ GLint baseLoc = glGetUniformLocation(batchShader->getProgramId(), "u_textures[0]");
+ if (baseLoc >= 0) {
+ for (i32 i = 0; i < static_cast<i32>(MAX_TEXTURE_SLOTS); ++i) {
+ glUniform1i(baseLoc + i, i);
}
- } else {
- ES_LOG_ERROR("Batch shader re-link failed after attribute binding");
}
} 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;
}
@@ -450,7 +452,7 @@ void BatchRenderer2D::flush() {
data_->texSlots.bindAll();
shader->bind();
- shader->setUniform("u_projection", data_->projection);
+ shader->setUniform(data_->projectionLoc, data_->projection);
data_->vao->bind();
@@ -495,6 +497,10 @@ void BatchRenderer2D::drawQuad(const glm::vec3& position, const glm::vec2& size,
if (texIndex < 0.0f) {
flush();
texIndex = data_->texSlots.findOrAllocate(textureId);
+ if (texIndex < 0.0f) {
+ ES_LOG_WARN("TextureSlotAllocator: failed after flush for drawQuad");
+ return;
+ }
}
for (u32 i = 0; i < 4; ++i) {
@@ -556,6 +562,10 @@ void BatchRenderer2D::drawRotatedQuad(const glm::vec2& position, const glm::vec2
if (texIndex < 0.0f) {
flush();
texIndex = data_->texSlots.findOrAllocate(textureId);
+ if (texIndex < 0.0f) {
+ ES_LOG_WARN("TextureSlotAllocator: failed after flush for drawRotatedQuad");
+ return;
+ }
}
glm::mat4 transform = glm::translate(glm::mat4(1.0f), glm::vec3(position, 0.0f));
@@ -604,13 +614,13 @@ void BatchRenderer2D::drawNineSlice(const glm::vec2& position, const glm::vec2&
f32 y3 = baseY + size.y;
f32 u0 = uvOffset.x;
- f32 u1 = uvOffset.x + (L / texSize.x) * uvScale.x;
- f32 u2 = uvOffset.x + (1.0f - R / texSize.x) * uvScale.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) * uvScale.y;
- f32 v2 = uvOffset.y + (1.0f - T / texSize.y) * uvScale.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
diff --git a/src/esengine/renderer/Shader.cpp b/src/esengine/renderer/Shader.cpp
index 3e7747a57..76ba7ed34 100644
--- a/src/esengine/renderer/Shader.cpp
+++ b/src/esengine/renderer/Shader.cpp
@@ -34,7 +34,9 @@ Shader::~Shader() {
}
Shader::Shader(Shader&& other) noexcept
- : programId_(other.programId_), uniformCache_(std::move(other.uniformCache_)) {
+ : programId_(other.programId_)
+ , uniformCache_(std::move(other.uniformCache_))
+ , attribCache_(std::move(other.attribCache_)) {
other.programId_ = 0;
}
@@ -45,6 +47,7 @@ Shader& Shader::operator=(Shader&& other) noexcept {
}
programId_ = other.programId_;
uniformCache_ = std::move(other.uniformCache_);
+ attribCache_ = std::move(other.attribCache_);
other.programId_ = 0;
}
return *this;
@@ -58,6 +61,15 @@ Unique<Shader> Shader::create(const std::string& vertexSrc, const std::string& f
return shader;
}
+Unique<Shader> Shader::createWithBindings(const std::string& vertexSrc, const std::string& fragmentSrc,
+ std::initializer_list<AttribBinding> bindings) {
+ auto shader = makeUnique<Shader>();
+ if (!shader->compile(vertexSrc, fragmentSrc, bindings)) {
+ return nullptr;
+ }
+ return shader;
+}
+
Unique<Shader> Shader::createFromFile(const std::string& vertexPath, const std::string& fragmentPath) {
auto readFile = [](const std::string& filepath) -> std::string {
std::ifstream file(filepath, std::ios::in | std::ios::binary);
@@ -105,7 +117,8 @@ void Shader::unbind() const {
glUseProgram(0);
}
-bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSrc) {
+bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSrc,
+ std::initializer_list<AttribBinding> bindings) {
// Create vertex shader
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
const char* vertexSrcPtr = vertexSrc.c_str();
@@ -148,6 +161,11 @@ bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSr
programId_ = glCreateProgram();
glAttachShader(programId_, vertexShader);
glAttachShader(programId_, fragmentShader);
+
+ for (const auto& b : bindings) {
+ glBindAttribLocation(programId_, b.index, b.name);
+ }
+
glLinkProgram(programId_);
// Check linking
@@ -241,7 +259,13 @@ void Shader::setUniform(i32 location, const glm::mat4& value) const {
}
i32 Shader::getAttribLocation(const std::string& name) const {
- return glGetAttribLocation(programId_, name.c_str());
+ auto it = attribCache_.find(name);
+ if (it != attribCache_.end()) {
+ return it->second;
+ }
+ i32 location = glGetAttribLocation(programId_, name.c_str());
+ attribCache_[name] = location;
+ return location;
}
} // namespace esengine
diff --git a/src/esengine/renderer/Shader.hpp b/src/esengine/renderer/Shader.hpp
index b4b5f80a0..454cd716d 100644
--- a/src/esengine/renderer/Shader.hpp
+++ b/src/esengine/renderer/Shader.hpp
@@ -21,11 +21,17 @@
#include "../math/Math.hpp"
// Standard library
+#include <initializer_list>
#include <string>
#include <unordered_map>
namespace esengine {
+struct AttribBinding {
+ u32 index;
+ const char* name;
+};
+
// =============================================================================
// Shader Class
// =============================================================================
@@ -69,6 +75,16 @@ public:
*/
static Unique<Shader> create(const std::string& vertexSrc, const std::string& fragmentSrc);
+ /**
+ * @brief Creates a shader with explicit attribute bindings applied before linking
+ * @param vertexSrc Vertex shader GLSL source
+ * @param fragmentSrc Fragment shader GLSL source
+ * @param bindings Attribute location bindings
+ * @return Unique pointer to the shader, or nullptr on failure
+ */
+ static Unique<Shader> createWithBindings(const std::string& vertexSrc, const std::string& fragmentSrc,
+ std::initializer_list<AttribBinding> bindings);
+
/**
* @brief Creates a shader from file paths
* @param vertexPath Path to vertex shader file
@@ -148,12 +164,14 @@ private:
* @param fragmentSrc Fragment shader source
* @return True on success
*/
- bool compile(const std::string& vertexSrc, const std::string& fragmentSrc);
+ bool compile(const std::string& vertexSrc, const std::string& fragmentSrc,
+ std::initializer_list<AttribBinding> bindings = {});
u32 programId_ = 0;
/** @brief Cached uniform locations (mutable for const uniform setters) */
mutable std::unordered_map<std::string, i32> uniformCache_;
+ mutable std::unordered_map<std::string, i32> attribCache_;
};
// =============================================================================
diff --git a/src/esengine/renderer/Texture.cpp b/src/esengine/renderer/Texture.cpp
index 335441627..bb799b81c 100644
--- a/src/esengine/renderer/Texture.cpp
+++ b/src/esengine/renderer/Texture.cpp
@@ -27,16 +27,18 @@ namespace {
#ifdef ES_PLATFORM_WEB
GLenum toGLFormat(TextureFormat format) {
switch (format) {
- case TextureFormat::RGB8: return GL_RGB;
- case TextureFormat::RGBA8: return GL_RGBA;
+ case TextureFormat::RGB8: return GL_RGB;
+ case TextureFormat::RGBA8: return GL_RGBA;
+ case TextureFormat::Depth24: return GL_DEPTH_COMPONENT;
default: return GL_RGBA;
}
}
GLenum toGLInternalFormat(TextureFormat format) {
switch (format) {
- case TextureFormat::RGB8: return GL_RGB8;
- case TextureFormat::RGBA8: return GL_RGBA8;
+ case TextureFormat::RGB8: return GL_RGB8;
+ case TextureFormat::RGBA8: return GL_RGBA8;
+ case TextureFormat::Depth24: return GL_DEPTH_COMPONENT24;
default: return GL_RGBA8;
}
}
@@ -77,6 +79,7 @@ Texture::Texture(Texture&& other) noexcept
other.textureId_ = 0;
other.width_ = 0;
other.height_ = 0;
+ other.format_ = TextureFormat::None;
}
Texture& Texture::operator=(Texture&& other) noexcept {
@@ -93,6 +96,7 @@ Texture& Texture::operator=(Texture&& other) noexcept {
other.textureId_ = 0;
other.width_ = 0;
other.height_ = 0;
+ other.format_ = TextureFormat::None;
}
return *this;
}
diff --git a/src/esengine/renderer/TextureSlotAllocator.hpp b/src/esengine/renderer/TextureSlotAllocator.hpp
index 58bebe4cc..18fe7a817 100644
--- a/src/esengine/renderer/TextureSlotAllocator.hpp
+++ b/src/esengine/renderer/TextureSlotAllocator.hpp
@@ -51,7 +51,7 @@ public:
}
void bindAll() const {
- for (u32 i = 0; i < MaxSlots; ++i) {
+ for (u32 i = 0; i < slot_count_; ++i) {
glActiveTexture(GL_TEXTURE0 + i);
glBindTexture(GL_TEXTURE_2D, slots_[i]);
}