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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
refactor(renderer): vertex layout joins the pipeline; VAO becomes a GL-backend detail
yhh0ebb39bed387
diff --git a/src/esengine/bindings/GeometryBindings.cpp b/src/esengine/bindings/GeometryBindings.cppindex 317f569df..d009501e1 100644--- a/src/esengine/bindings/GeometryBindings.cpp+++ b/src/esengine/bindings/GeometryBindings.cpp@@ -36,14 +36,21 @@ static void flushImmediateDrawIfActive() {}}-static void restoreImmediateDrawState() {- if (g_immediateDrawActive) {- auto* dev = g_device;- dev->setBlendEnabled(true);- dev->setBlendMode(BlendMode::Normal);- dev->setDepthTest(false);- dev->bindTexture(0, TextureHandle::Invalid);+// A mesh draw's pipeline: the requested shader + this geometry's vertex layout,+// with blend/depth taken from the immediate-draw session state (Draw.setBlendMode /+// setDepthTest apply to mesh draws too). The pipeline cache dedupes repeats.+static void applyMeshPipeline(GfxDevice& device, const Shader& shader, const CustomGeometry& geom) {+ PipelineDesc desc{};+ desc.program = shader.handle();+ desc.vertexLayout = geom.layoutHandle();+ desc.blendEnabled = true;+ desc.depthWrite = true;+ if (auto* imm = g_immediateDraw) {+ desc.blend = imm->blendMode();+ desc.depthTest = imm->depthTest();}+ device.invalidatePipelineCache();+ device.setPipeline(device.createPipeline(desc));}u32 geometry_create() {@@ -135,14 +142,14 @@ void draw_mesh(u32 geometryHandle, u32 shaderHandle, uintptr_t transformPtr) {const f32* transformData = reinterpret_cast<const f32*>(transformPtr);glm::mat4 transform = glm::make_mat4(transformData);- shader->bind();+ applyMeshPipeline(*g_device, *shader, *geom);shader->setUniform("u_projection", g_currentViewProjection);shader->setUniform("u_model", transform);geom->bind(ctx().require<GfxDevice>());if (geom->hasIndices()) {- auto* ib = geom->getVAO() ? geom->getVAO()->getIndexBuffer().get() : nullptr;+ auto* ib = geom->indexBuffer();if (ib) {auto type = ib->is16Bit() ? GfxDataType::UnsignedShort : GfxDataType::UnsignedInt;g_device->drawElements(geom->getIndexCount(), type, 0);@@ -150,9 +157,6 @@ void draw_mesh(u32 geometryHandle, u32 shaderHandle, uintptr_t transformPtr) {} else {g_device->drawArrays(0, geom->getVertexCount());}-- geom->unbind();- restoreImmediateDrawState();}void draw_meshWithUniforms(u32 geometryHandle, u32 shaderHandle, uintptr_t transformPtr,@@ -170,7 +174,7 @@ void draw_meshWithUniforms(u32 geometryHandle, u32 shaderHandle, uintptr_t transconst f32* transformData = reinterpret_cast<const f32*>(transformPtr);glm::mat4 transform = glm::make_mat4(transformData);- shader->bind();+ applyMeshPipeline(*g_device, *shader, *geom);shader->setUniform("u_projection", g_currentViewProjection);shader->setUniform("u_model", transform);@@ -232,7 +236,7 @@ void draw_meshWithUniforms(u32 geometryHandle, u32 shaderHandle, uintptr_t transgeom->bind(ctx().require<GfxDevice>());if (geom->hasIndices()) {- auto* ib = geom->getVAO() ? geom->getVAO()->getIndexBuffer().get() : nullptr;+ auto* ib = geom->indexBuffer();if (ib) {auto type = ib->is16Bit() ? GfxDataType::UnsignedShort : GfxDataType::UnsignedInt;g_device->drawElements(geom->getIndexCount(), type, 0);@@ -240,9 +244,6 @@ void draw_meshWithUniforms(u32 geometryHandle, u32 shaderHandle, uintptr_t trans} else {g_device->drawArrays(0, geom->getVertexCount());}-- geom->unbind();- restoreImmediateDrawState();}} // namespace esenginediff --git a/src/esengine/bindings/ImmediateDrawBindings.cpp b/src/esengine/bindings/ImmediateDrawBindings.cppindex fdabb136c..4d1e37efa 100644--- a/src/esengine/bindings/ImmediateDrawBindings.cpp+++ b/src/esengine/bindings/ImmediateDrawBindings.cpp@@ -160,13 +160,13 @@ u32 draw_getPrimitiveCount() {}void draw_setBlendMode(i32 mode) {- flushImmediateDrawIfActive();- g_device->setBlendMode(static_cast<BlendMode>(mode));+ if (!g_immediateDraw) return;+ g_immediateDraw->setBlendMode(static_cast<BlendMode>(mode));}void draw_setDepthTest(bool enabled) {- flushImmediateDrawIfActive();- g_device->setDepthTest(enabled);+ if (!g_immediateDraw) return;+ g_immediateDraw->setDepthTest(enabled);}} // namespace esenginediff --git a/src/esengine/renderer/Buffer.cpp b/src/esengine/renderer/Buffer.cppindex db1616a41..028c4875d 100644--- a/src/esengine/renderer/Buffer.cpp+++ b/src/esengine/renderer/Buffer.cpp@@ -3,8 +3,8 @@/*** @file Buffer.cpp* @brief GPU buffer implementations (device-backed)- * @details VertexBuffer, IndexBuffer and VertexArray delegate every GPU- * operation to GfxDevice. This file contains no GL calls.+ * @details VertexBuffer and IndexBuffer delegate every GPU operation to+ * GfxDevice. This file contains no GL calls.** @author ESEngine Team* @date 2025@@ -51,24 +51,6 @@ u32 shaderDataTypeComponentCount(ShaderDataType type) {}}-namespace {--GfxDataType toGfxDataType(ShaderDataType type) {- switch (type) {- case ShaderDataType::Int:- case ShaderDataType::Int2:- case ShaderDataType::Int3:- case ShaderDataType::Int4:- return GfxDataType::Int;- case ShaderDataType::Bool:- case ShaderDataType::UByte4N:- return GfxDataType::UnsignedByte;- default:- return GfxDataType::Float;- }-}--} // namespace// ========================================// VertexBuffer@@ -112,14 +94,6 @@ Unique<VertexBuffer> VertexBuffer::create(GfxDevice& device, u32 size) {return buffer;}-void VertexBuffer::bind() const {- if (device_) device_->bindVertexBuffer(handle_);-}--void VertexBuffer::unbind() const {- if (device_) device_->bindVertexBuffer(BufferHandle::Invalid);-}-void VertexBuffer::setDataRaw(const void* data, u32 sizeBytes) {if (!device_) return;device_->updateBuffer(handle_, 0, data, sizeBytes);@@ -181,96 +155,4 @@ Unique<IndexBuffer> IndexBuffer::create(GfxDevice& device, const u16* indices, ureturn buffer;}-void IndexBuffer::bind() const {- if (device_) device_->bindIndexBuffer(handle_);-}--void IndexBuffer::unbind() const {- if (device_) device_->bindIndexBuffer(BufferHandle::Invalid);-}--// ========================================-// VertexArray-// ========================================--VertexArray::~VertexArray() {- if (arrayId_ != 0 && device_) {- device_->deleteVertexArray(arrayId_);- }-}--VertexArray::VertexArray(VertexArray&& other) noexcept- : device_(other.device_)- , arrayId_(other.arrayId_)- , vertexAttribIndex_(other.vertexAttribIndex_)- , vertexBuffers_(std::move(other.vertexBuffers_))- , indexBuffer_(std::move(other.indexBuffer_)) {- other.arrayId_ = 0;- other.vertexAttribIndex_ = 0;-}--VertexArray& VertexArray::operator=(VertexArray&& other) noexcept {- if (this != &other) {- if (arrayId_ != 0 && device_) {- device_->deleteVertexArray(arrayId_);- }- device_ = other.device_;- arrayId_ = other.arrayId_;- vertexAttribIndex_ = other.vertexAttribIndex_;- vertexBuffers_ = std::move(other.vertexBuffers_);- indexBuffer_ = std::move(other.indexBuffer_);- other.arrayId_ = 0;- other.vertexAttribIndex_ = 0;- }- return *this;-}--Unique<VertexArray> VertexArray::create(GfxDevice& device) {- auto vao = makeUnique<VertexArray>();- vao->device_ = &device;- vao->arrayId_ = device.createVertexArray();- return vao;-}--void VertexArray::bind() const {- if (device_) device_->bindVertexArray(arrayId_);-}--void VertexArray::unbind() const {- if (device_) device_->bindVertexArray(0);-}--void VertexArray::addVertexBuffer(Shared<VertexBuffer> buffer) {- ES_ASSERT(!buffer->getLayout().getAttributes().empty(), "Vertex buffer has no layout");-- if (device_) {- device_->bindVertexArray(arrayId_);- buffer->bind();-- const auto& layout = buffer->getLayout();- for (const auto& attr : layout) {- bool normalized = attr.normalized || attr.type == ShaderDataType::UByte4N;- device_->enableVertexAttrib(vertexAttribIndex_);- device_->vertexAttribPointer(- vertexAttribIndex_,- static_cast<i32>(shaderDataTypeComponentCount(attr.type)),- toGfxDataType(attr.type),- normalized,- static_cast<i32>(layout.getStride()),- attr.offset- );- ++vertexAttribIndex_;- }- }- vertexBuffers_.push_back(std::move(buffer));-}--void VertexArray::setIndexBuffer(Shared<IndexBuffer> buffer) {- if (device_) {- device_->bindVertexArray(arrayId_);- buffer->bind();- }- indexBuffer_ = std::move(buffer);-}-} // namespace esenginediff --git a/src/esengine/renderer/Buffer.hpp b/src/esengine/renderer/Buffer.hppindex 64c984374..56c8f02da 100644--- a/src/esengine/renderer/Buffer.hpp+++ b/src/esengine/renderer/Buffer.hpp@@ -3,9 +3,9 @@/*** @file Buffer.hpp* @brief GPU buffer abstractions for vertex and index data- * @details VertexBuffer, IndexBuffer and VertexArray are thin RAII handles over- * GfxDevice. They hold no GL state directly — every GPU operation is- * delegated to the device, so this layer has zero GL dependency.+ * @details VertexBuffer and IndexBuffer are thin RAII handles over GfxDevice.+ * They hold no GL state directly — every GPU operation is delegated+ * to the device, so this layer has zero GL dependency.** @author ESEngine Team* @date 2026@@ -255,12 +255,6 @@ public:// Operations// =========================================================================- /** @brief Binds the buffer for rendering */- void bind() const;-- /** @brief Unbinds the buffer */- void unbind() const;-/*** @brief Updates buffer data from a span*/@@ -402,12 +396,6 @@ public:// Operations// =========================================================================- /** @brief Binds the buffer for rendering */- void bind() const;-- /** @brief Unbinds the buffer */- void unbind() const;-/** @brief Gets the number of indices */u32 getCount() const { return count_; }@@ -424,87 +412,4 @@ private:bool is16Bit_ = false;};-// =============================================================================-// Vertex Array Object-// =============================================================================--/**- * @brief Encapsulates vertex attribute configuration- *- * @details Wraps a GfxDevice vertex array object. Stores the association- * between vertex buffers and their attribute layouts.- *- * @code- * auto vao = VertexArray::create(device);- *- * auto vbo = VertexBuffer::create(device, vertices);- * vbo->setLayout({...});- * vao->addVertexBuffer(std::move(vbo));- *- * auto ebo = IndexBuffer::create(device, indices, 6);- * vao->setIndexBuffer(std::move(ebo));- *- * // Rendering- * vao->bind();- * device.drawElements(ebo->getCount(), GfxDataType::UnsignedInt, 0);- * @endcode- */-class VertexArray {-public:- VertexArray() = default;- ~VertexArray();-- // Non-copyable, movable- VertexArray(const VertexArray&) = delete;- VertexArray& operator=(const VertexArray&) = delete;- VertexArray(VertexArray&& other) noexcept;- VertexArray& operator=(VertexArray&& other) noexcept;-- /**- * @brief Creates a new vertex array- * @param device Graphics device- * @return Unique pointer to the VAO- */- static Unique<VertexArray> create(GfxDevice& device);-- /** @brief Binds the VAO for rendering */- void bind() const;-- /** @brief Unbinds the VAO */- void unbind() const;-- /**- * @brief Adds a vertex buffer to the VAO- * @param buffer Shared pointer to the vertex buffer- *- * @details The buffer's layout must be set before adding.- */- void addVertexBuffer(Shared<VertexBuffer> buffer);-- /**- * @brief Sets the index buffer- * @param buffer Shared pointer to the index buffer- */- void setIndexBuffer(Shared<IndexBuffer> buffer);-- /**- * @brief Gets all attached vertex buffers- * @return Const reference to buffer vector- */- const std::vector<Shared<VertexBuffer>>& getVertexBuffers() const { return vertexBuffers_; }-- /**- * @brief Gets the index buffer- * @return Const reference to the index buffer pointer- */- const Shared<IndexBuffer>& getIndexBuffer() const { return indexBuffer_; }--private:- GfxDevice* device_ = nullptr; ///< Set by create(); all GL goes through it.- u32 arrayId_ = 0;- u32 vertexAttribIndex_ = 0;- std::vector<Shared<VertexBuffer>> vertexBuffers_;- Shared<IndexBuffer> indexBuffer_;-};-} // namespace esenginediff --git a/src/esengine/renderer/CustomGeometry.cpp b/src/esengine/renderer/CustomGeometry.cppindex ecc2fb446..145d22133 100644--- a/src/esengine/renderer/CustomGeometry.cpp+++ b/src/esengine/renderer/CustomGeometry.cpp@@ -18,45 +18,71 @@namespace esengine {+namespace {++GfxDataType toGfxDataType(ShaderDataType type) {+ switch (type) {+ case ShaderDataType::Int:+ case ShaderDataType::Int2:+ case ShaderDataType::Int3:+ case ShaderDataType::Int4:+ return GfxDataType::Int;+ case ShaderDataType::Bool:+ case ShaderDataType::UByte4N:+ return GfxDataType::UnsignedByte;+ default:+ return GfxDataType::Float;+ }+}++} // namespace+void CustomGeometry::init(GfxDevice& device, const f32* vertices, u32 vertexCount,const VertexLayout& layout, bool dynamic) {device_ = &device;dynamic_ = dynamic;stride_ = layout.getStride();- if (stride_ == 0) {+ if (stride_ == 0 || layout.getAttributes().size() > MAX_VERTEX_ATTRIBUTES) {// An empty vertex layout would make the divide below a divide-by-zero- // (a wasm trap). Leave the geometry uninitialized: vao_ stays null, so- // isValid() is false and bind()/draw become no-ops.- ES_LOG_ERROR("CustomGeometry::init: empty vertex layout (stride 0); skipping setup");+ // (a wasm trap). Leave the geometry uninitialized: layout_ stays Invalid,+ // so isValid() is false and bind()/draw become no-ops.+ ES_LOG_ERROR("CustomGeometry::init: unusable vertex layout (stride {}, {} attributes); skipping setup",+ stride_, layout.getAttributes().size());return;}vertexCount_ = vertexCount * sizeof(f32) / stride_;- vao_ = VertexArray::create(device);-if (dynamic) {vbo_ = Shared<VertexBuffer>(VertexBuffer::create(device, vertexCount * sizeof(f32)));vbo_->setDataRaw(vertices, vertexCount * sizeof(f32));} else {vbo_ = Shared<VertexBuffer>(VertexBuffer::createRaw(device, vertices, vertexCount * sizeof(f32)));}-vbo_->setLayout(layout);- vao_->addVertexBuffer(vbo_);++ VertexLayoutDesc desc;+ desc.strides[0] = stride_;+ for (const auto& attr : layout) {+ GfxVertexAttribute& out = desc.attributes[desc.attributeCount];+ out.location = desc.attributeCount;+ out.components = static_cast<u8>(shaderDataTypeComponentCount(attr.type));+ out.type = toGfxDataType(attr.type);+ out.normalized = attr.normalized || attr.type == ShaderDataType::UByte4N;+ out.offset = attr.offset;+ out.bufferSlot = 0;+ ++desc.attributeCount;+ }+ layout_ = device.createVertexLayout(desc);}void CustomGeometry::setIndices(const u16* indices, u32 indexCount) {- if (!vao_ || !device_) return;-+ if (!isValid() || !device_) return;ibo_ = Shared<IndexBuffer>(IndexBuffer::create(*device_, indices, indexCount));- vao_->setIndexBuffer(ibo_);}void CustomGeometry::setIndices(const u32* indices, u32 indexCount) {- if (!vao_ || !device_) return;-+ if (!isValid() || !device_) return;ibo_ = Shared<IndexBuffer>(IndexBuffer::create(*device_, indices, indexCount));- vao_->setIndexBuffer(ibo_);}void CustomGeometry::updateVertices(const f32* vertices, u32 vertexCount, u32 offset) {@@ -75,54 +101,9 @@ void CustomGeometry::updateVertices(const f32* vertices, u32 vertexCount, u32 of}void CustomGeometry::bind(GfxDevice& device) const {- if (!vao_) return;-- vao_->bind();-- // Explicitly rebind VBO + attribute pointers + IBO to work around- // WeChat WebGL VAO state restoration bug- if (vbo_) {- vbo_->bind();- const auto& layout = vbo_->getLayout();- u32 index = 0;- for (const auto& attr : layout) {- GfxDataType gfxType = GfxDataType::Float;- switch (attr.type) {- case ShaderDataType::Int:- case ShaderDataType::Int2:- case ShaderDataType::Int3:- case ShaderDataType::Int4:- gfxType = GfxDataType::Int;- break;- case ShaderDataType::Bool:- case ShaderDataType::UByte4N:- gfxType = GfxDataType::UnsignedByte;- break;- default:- gfxType = GfxDataType::Float;- break;- }- device.enableVertexAttrib(index);- device.vertexAttribPointer(- index,- static_cast<i32>(shaderDataTypeComponentCount(attr.type)),- gfxType,- attr.normalized,- static_cast<i32>(layout.getStride()),- attr.offset- );- ++index;- }- }- if (ibo_) {- ibo_->bind();- }-}--void CustomGeometry::unbind() const {- if (vao_) {- vao_->unbind();- }+ if (!isValid()) return;+ device.setVertexBuffer(0, vbo_ ? vbo_->handle() : BufferHandle::Invalid, 0);+ device.setIndexBuffer(ibo_ ? ibo_->handle() : BufferHandle::Invalid);}u32 CustomGeometry::getIndexCount() const {diff --git a/src/esengine/renderer/CustomGeometry.hpp b/src/esengine/renderer/CustomGeometry.hppindex c0f0bb737..542b63555 100644--- a/src/esengine/renderer/CustomGeometry.hpp+++ b/src/esengine/renderer/CustomGeometry.hpp@@ -69,20 +69,19 @@ public:void updateVertices(const f32* vertices, u32 vertexCount, u32 offset = 0);/**- * @brief Binds the geometry for rendering+ * @brief Binds the geometry's buffers for the next draw*/void bind(GfxDevice& device) const;/**- * @brief Unbinds the geometry+ * @brief The device vertex layout a pipeline drawing this geometry must reference*/- void unbind() const;+ VertexLayoutHandle layoutHandle() const { return layout_; }/**- * @brief Gets the VAO for rendering+ * @brief Gets the index buffer (null when non-indexed)*/- VertexArray* getVAO() { return vao_.get(); }- const VertexArray* getVAO() const { return vao_.get(); }+ const IndexBuffer* indexBuffer() const { return ibo_.get(); }/*** @brief Gets the index count@@ -107,11 +106,11 @@ public:/*** @brief Checks if geometry is initialized*/- bool isValid() const { return vao_ != nullptr; }+ bool isValid() const { return layout_ != VertexLayoutHandle::Invalid; }private:GfxDevice* device_ = nullptr; ///< Set in init(); used to create index buffers later.- Unique<VertexArray> vao_;+ VertexLayoutHandle layout_ = VertexLayoutHandle::Invalid;Shared<VertexBuffer> vbo_;Shared<IndexBuffer> ibo_;u32 vertexCount_ = 0;diff --git a/src/esengine/renderer/DrawList.cpp b/src/esengine/renderer/DrawList.cppindex ca3dfc92b..3773dd89b 100644--- a/src/esengine/renderer/DrawList.cpp+++ b/src/esengine/renderer/DrawList.cpp@@ -115,7 +115,7 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,// caches; a one-entry memo skips the lookup for identical consecutive (sorted) commands.PipelineDesc desc{};desc.program = ShaderHandle{cmd.shader_id};- desc.vertexLayout = cmd.layout_id;+ desc.vertexLayout = buffers.layoutHandle(cmd.layout_id);desc.blend = cmd.blend_mode;desc.blendEnabled = true;desc.depthTest = cmd.depth_test;diff --git a/src/esengine/renderer/GLDevice.cpp b/src/esengine/renderer/GLDevice.cppindex 098dee4c5..7330b64b6 100644--- a/src/esengine/renderer/GLDevice.cpp+++ b/src/esengine/renderer/GLDevice.cpp@@ -550,6 +550,7 @@ void GLDevice::uploadBufferStore(BufferHandle buffer, u32 offsetBytes, const voi// VAO is bound would silently rewire that VAO's index buffer. Detach first.if (meta.usage == GfxBufferUsage::Index) {glBindVertexArray(0);+ bound_vao_ = 0;}const GLenum target = toGLBufferTarget(meta.usage);@@ -587,12 +588,91 @@ void GLDevice::setUniformBuffer(u32 slot, BufferHandle buffer) {glBindBufferBase(GL_UNIFORM_BUFFER, slot, static_cast<GLuint>(buffer));}-void GLDevice::bindVertexBuffer(BufferHandle buffer) {- glBindBuffer(GL_ARRAY_BUFFER, static_cast<GLuint>(buffer));+// =============================================================================+// Vertex Input+// =============================================================================++VertexLayoutHandle GLDevice::createVertexLayout(const VertexLayoutDesc& desc) {+ LayoutRecord rec;+ rec.desc = desc;+ rec.alive = true;+ layouts_.push_back(rec);+ return static_cast<VertexLayoutHandle>(layouts_.size()); // 1-based; 0 == Invalid+}++void GLDevice::deleteVertexLayout(VertexLayoutHandle layout) {+ const u32 index = static_cast<u32>(layout);+ if (index == 0 || index > layouts_.size()) return;+ LayoutRecord& rec = layouts_[index - 1];+ if (rec.vao != 0) {+ if (bound_vao_ == rec.vao) {+ glBindVertexArray(0);+ bound_vao_ = 0;+ }+ glDeleteVertexArrays(1, &rec.vao);+ rec.vao = 0;+ }+ rec.alive = false;}-void GLDevice::bindIndexBuffer(BufferHandle buffer) {- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, static_cast<GLuint>(buffer));+void GLDevice::setVertexBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes) {+ if (slot >= MAX_VERTEX_BUFFER_SLOTS) return;+ pending_vbo_[slot] = static_cast<u32>(buffer);+ pending_vbo_offset_[slot] = offsetBytes;+}++void GLDevice::setIndexBuffer(BufferHandle buffer) {+ pending_ibo_ = static_cast<u32>(buffer);+}++void GLDevice::prepareVertexState() {+ const u32 index = static_cast<u32>(current_layout_);+ if (index == 0 || index > layouts_.size()) return;+ LayoutRecord& rec = layouts_[index - 1];+ if (!rec.alive) return;++ if (rec.vao == 0) {+ glGenVertexArrays(1, &rec.vao);+ rec.configured = false;+ }+ if (bound_vao_ != rec.vao) {+ glBindVertexArray(rec.vao);+ bound_vao_ = rec.vao;+ }++ if (!rec.configured || rec.bakedIbo != pending_ibo_) {+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, pending_ibo_);+ rec.bakedIbo = pending_ibo_;+ }++ for (u32 slot = 0; slot < MAX_VERTEX_BUFFER_SLOTS; ++slot) {+ bool slotUsed = false;+ for (u32 a = 0; a < rec.desc.attributeCount; ++a) {+ if (rec.desc.attributes[a].bufferSlot == slot) { slotUsed = true; break; }+ }+ if (!slotUsed) continue;+ if (rec.configured && rec.bakedVbo[slot] == pending_vbo_[slot]+ && rec.bakedOffset[slot] == pending_vbo_offset_[slot]) {+ continue;+ }++ glBindBuffer(GL_ARRAY_BUFFER, pending_vbo_[slot]);+ for (u32 a = 0; a < rec.desc.attributeCount; ++a) {+ const GfxVertexAttribute& attr = rec.desc.attributes[a];+ if (attr.bufferSlot != slot) continue;+ glEnableVertexAttribArray(attr.location);+ glVertexAttribPointer(+ attr.location, attr.components, toGLDataType(attr.type),+ attr.normalized ? GL_TRUE : GL_FALSE,+ static_cast<GLsizei>(rec.desc.strides[slot]),+ reinterpret_cast<const void*>(+ static_cast<uintptr_t>(pending_vbo_offset_[slot] + attr.offset)));+ glVertexAttribDivisor(attr.location, rec.desc.instanceStep[slot] ? 1 : 0);+ }+ rec.bakedVbo[slot] = pending_vbo_[slot];+ rec.bakedOffset[slot] = pending_vbo_offset_[slot];+ }+ rec.configured = true;}u32 GLDevice::getUniformBlockIndex(ShaderHandle program, const char* name) {@@ -659,6 +739,7 @@ void GLDevice::setPipeline(PipelineHandle handle) {current_pipeline_ = handle;current_stencil_mode_ = desc.stencil;+ current_layout_ = desc.vertexLayout;}void GLDevice::setStencilReference(i32 ref) {@@ -679,53 +760,23 @@ void GLDevice::invalidatePipelineCache() {current_stencil_mode_ = GfxStencilMode::Off;}-// =============================================================================-// VAO Operations-// =============================================================================--u32 GLDevice::createVertexArray() {- GLuint id = 0;- glGenVertexArrays(1, &id);- return static_cast<u32>(id);-}--void GLDevice::deleteVertexArray(u32 vaoId) {- GLuint id = static_cast<GLuint>(vaoId);- glDeleteVertexArrays(1, &id);-}--void GLDevice::bindVertexArray(u32 vaoId) {- glBindVertexArray(vaoId);-}--void GLDevice::enableVertexAttrib(u32 index) {- glEnableVertexAttribArray(index);-}--void GLDevice::vertexAttribPointer(u32 index, i32 size, GfxDataType type,- bool normalized, i32 stride, u32 offset) {- glVertexAttribPointer(index, size, toGLDataType(type), normalized ? GL_TRUE : GL_FALSE,- stride, reinterpret_cast<const void*>(static_cast<uintptr_t>(offset)));-}--void GLDevice::vertexAttribDivisor(u32 index, u32 divisor) {- glVertexAttribDivisor(index, divisor);-}-// =============================================================================// Draw Calls// =============================================================================void GLDevice::drawElements(u32 indexCount, GfxDataType indexType, u32 byteOffset) {+ prepareVertexState();glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(indexCount), toGLDataType(indexType),reinterpret_cast<const void*>(static_cast<uintptr_t>(byteOffset)));}void GLDevice::drawArrays(u32 first, u32 vertexCount) {+ prepareVertexState();glDrawArrays(GL_TRIANGLES, static_cast<GLint>(first), static_cast<GLsizei>(vertexCount));}void GLDevice::drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 byteOffset, u32 instanceCount) {+ prepareVertexState();glDrawElementsInstanced(GL_TRIANGLES, static_cast<GLsizei>(indexCount), toGLDataType(indexType),reinterpret_cast<const void*>(static_cast<uintptr_t>(byteOffset)),static_cast<GLsizei>(instanceCount));diff --git a/src/esengine/renderer/GLDevice.hpp b/src/esengine/renderer/GLDevice.hppindex 9944cfbb2..5486d87d4 100644--- a/src/esengine/renderer/GLDevice.hpp+++ b/src/esengine/renderer/GLDevice.hpp@@ -67,8 +67,11 @@ public:void updateBuffer(BufferHandle buffer, u32 offsetBytes, const void* data, u32 sizeBytes) override;void resizeBuffer(BufferHandle buffer, u32 sizeBytes, const void* data) override;void setUniformBuffer(u32 slot, BufferHandle buffer) override;- void bindVertexBuffer(BufferHandle buffer) override;- void bindIndexBuffer(BufferHandle buffer) override;++ VertexLayoutHandle createVertexLayout(const VertexLayoutDesc& desc) override;+ void deleteVertexLayout(VertexLayoutHandle layout) override;+ void setVertexBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes) override;+ void setIndexBuffer(BufferHandle buffer) override;TextureHandle createTexture(const TextureDesc& desc, const void* pixels) override;TextureHandle createCompressedTexture(const TextureDesc& desc, GfxCompressedFormat format,@@ -108,14 +111,6 @@ public:void setStencilReference(i32 ref) override;void invalidatePipelineCache() override;- u32 createVertexArray() override;- void deleteVertexArray(u32 vaoId) override;- void bindVertexArray(u32 vaoId) override;- void enableVertexAttrib(u32 index) override;- void vertexAttribPointer(u32 index, i32 size, GfxDataType type,- bool normalized, i32 stride, u32 offset) override;- void vertexAttribDivisor(u32 index, u32 divisor) override;-void drawElements(u32 indexCount, GfxDataType indexType, u32 byteOffset) override;void drawArrays(u32 first, u32 vertexCount) override;void drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 byteOffset, u32 instanceCount) override;@@ -145,10 +140,32 @@ private:void uploadBufferStore(BufferHandle buffer, u32 offsetBytes, const void* data, u32 sizeBytes, bool respec);+ // Applies the current pipeline's vertex layout to the pending buffer bindings:+ // the layout's lazily-created VAO is bound, and any slot whose buffer/offset+ // differs from what the VAO has baked is re-pointed. WebGL2 has no explicit+ // vertex-input object, so the VAO is purely a backend cache here.+ void prepareVertexState();+std::vector<PipelineDesc> pipelines_;PipelineHandle current_pipeline_ = PipelineHandle::Invalid;GfxStencilMode current_stencil_mode_ = GfxStencilMode::Off;+ struct LayoutRecord {+ VertexLayoutDesc desc;+ u32 vao = 0;+ bool alive = false;+ bool configured = false;+ u32 bakedVbo[MAX_VERTEX_BUFFER_SLOTS] = {};+ u32 bakedOffset[MAX_VERTEX_BUFFER_SLOTS] = {};+ u32 bakedIbo = 0;+ };+ std::vector<LayoutRecord> layouts_;+ VertexLayoutHandle current_layout_ = VertexLayoutHandle::Invalid;+ u32 pending_vbo_[MAX_VERTEX_BUFFER_SLOTS] = {};+ u32 pending_vbo_offset_[MAX_VERTEX_BUFFER_SLOTS] = {};+ u32 pending_ibo_ = 0;+ u32 bound_vao_ = 0;+// Per-handle metadata the GL bind-to-edit protocol needs but the interface no// longer carries: buffer target/usage for uploads, texture transfer format for// sub-image updates.diff --git a/src/esengine/renderer/GfxDevice.hpp b/src/esengine/renderer/GfxDevice.hppindex 74d2d1f95..de47ce9e7 100644--- a/src/esengine/renderer/GfxDevice.hpp+++ b/src/esengine/renderer/GfxDevice.hpp@@ -161,11 +161,25 @@ public:/** @brief Binds a buffer to a uniform binding slot (the block index shaders are linked to). */virtual void setUniformBuffer(u32 slot, BufferHandle buffer) = 0;- /** @brief Binds a vertex buffer for vertex-layout setup */- virtual void bindVertexBuffer(BufferHandle buffer) = 0;+ // =========================================================================+ // Vertex Input (layout in the pipeline, buffers bound per draw)+ // =========================================================================++ /** @brief Registers an immutable vertex layout; pipelines reference it by handle. */+ virtual VertexLayoutHandle createVertexLayout(const VertexLayoutDesc& desc) = 0;++ /** @brief Deletes a vertex layout (no pipeline may reference it afterwards) */+ virtual void deleteVertexLayout(VertexLayoutHandle layout) = 0;- /** @brief Binds an index buffer for vertex-layout setup */- virtual void bindIndexBuffer(BufferHandle buffer) = 0;+ /**+ * @brief Binds a vertex buffer to a layout slot for subsequent draws.+ * @param offsetBytes Byte offset of element 0 — how an instanced draw rebases+ * its per-instance stream (GLES3 has no baseInstance).+ */+ virtual void setVertexBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes) = 0;++ /** @brief Binds the index buffer for subsequent indexed draws */+ virtual void setIndexBuffer(BufferHandle buffer) = 0;// =========================================================================// Textures@@ -306,29 +320,6 @@ public:*/virtual void invalidatePipelineCache() = 0;- // =========================================================================- // VAO Operations- // =========================================================================-- /** @brief Creates a vertex array object */- virtual u32 createVertexArray() = 0;-- /** @brief Deletes a vertex array object */- virtual void deleteVertexArray(u32 vaoId) = 0;-- /** @brief Binds a vertex array object */- virtual void bindVertexArray(u32 vaoId) = 0;-- /** @brief Enables a vertex attribute */- virtual void enableVertexAttrib(u32 index) = 0;-- /** @brief Configures a vertex attribute pointer */- virtual void vertexAttribPointer(u32 index, i32 size, GfxDataType type,- bool normalized, i32 stride, u32 offset) = 0;-- /** @brief Sets vertex attribute divisor for instanced rendering */- virtual void vertexAttribDivisor(u32 index, u32 divisor) = 0;-// =========================================================================// Draw Calls// =========================================================================diff --git a/src/esengine/renderer/GfxEnums.hpp b/src/esengine/renderer/GfxEnums.hppindex 999773e3b..6627fe4cb 100644--- a/src/esengine/renderer/GfxEnums.hpp+++ b/src/esengine/renderer/GfxEnums.hpp@@ -88,6 +88,37 @@ enum class GfxDataType : u8 {UnsignedInt,};+// =============================================================================+// Vertex Layout (part of a pipeline's identity; see PipelineDesc)+// =============================================================================++static constexpr u32 MAX_VERTEX_ATTRIBUTES = 8;+static constexpr u32 MAX_VERTEX_BUFFER_SLOTS = 2;++struct GfxVertexAttribute {+ u32 location = 0;+ u8 components = 4; ///< 1..4+ GfxDataType type = GfxDataType::Float;+ bool normalized = false;+ u32 offset = 0; ///< Byte offset within one element of its buffer slot.+ u8 bufferSlot = 0;+};++/**+ * @brief Describes how vertex-buffer bytes map to shader attributes.+ * @details Registered once (createVertexLayout) and referenced by pipelines;+ * the buffers themselves bind per draw via setVertexBuffer. A slot with+ * `instanceStep` advances per instance (attribute divisor 1).+ */+struct VertexLayoutDesc {+ GfxVertexAttribute attributes[MAX_VERTEX_ATTRIBUTES] = {};+ u32 attributeCount = 0;+ u32 strides[MAX_VERTEX_BUFFER_SLOTS] = {};+ bool instanceStep[MAX_VERTEX_BUFFER_SLOTS] = {};+};++enum class VertexLayoutHandle : u32 { Invalid = 0 };+// =============================================================================// Stencil Function// =============================================================================diff --git a/src/esengine/renderer/ImmediateDraw.cpp b/src/esengine/renderer/ImmediateDraw.cppindex 236dd88c2..c8416209f 100644--- a/src/esengine/renderer/ImmediateDraw.cpp+++ b/src/esengine/renderer/ImmediateDraw.cpp@@ -81,18 +81,20 @@ void ImmediateDraw::init() {}device_.useProgram(ShaderHandle::Invalid);- // One immutable pipeline: the batch shader, Batch layout, normal blend, depth+ // The base pipeline: the batch shader, Batch layout, normal blend, depth// test off (write on, matching the world batch path), no stencil, no culling.- PipelineDesc desc{};- desc.program = batch_shader_;- desc.vertexLayout = LayoutId::Batch;- desc.blend = BlendMode::Normal;- desc.blendEnabled = true;- desc.depthTest = false;- desc.depthWrite = true;- desc.stencil = GfxStencilMode::Off;- desc.cullEnabled = false;- pipeline_ = device_.createPipeline(desc);+ // setBlendMode/setDepthTest swap in cached sibling pipelines per state.+ base_desc_ = PipelineDesc{};+ base_desc_.program = batch_shader_;+ base_desc_.vertexLayout = pool_.layoutHandle(LayoutId::Batch);+ base_desc_.blend = BlendMode::Normal;+ base_desc_.blendEnabled = true;+ base_desc_.depthTest = false;+ base_desc_.depthWrite = true;+ base_desc_.stencil = GfxStencilMode::Off;+ base_desc_.cullEnabled = false;+ current_desc_ = base_desc_;+ pipeline_ = device_.createPipeline(current_desc_);} else {ES_LOG_ERROR("ImmediateDraw: failed to create batch shader");}@@ -122,6 +124,27 @@ void ImmediateDraw::begin(const glm::mat4& viewProjection) {primitiveCount_ = 0;drawCallCount_ = 0;inFrame_ = true;++ // Each session starts from the base state; a prior session's blend/depth+ // overrides do not leak across frames.+ if (!(current_desc_ == base_desc_)) {+ current_desc_ = base_desc_;+ pipeline_ = device_.createPipeline(current_desc_);+ }+}++void ImmediateDraw::setBlendMode(BlendMode mode) {+ if (current_desc_.blend == mode) return;+ if (pendingGeometry_) flush();+ current_desc_.blend = mode;+ pipeline_ = device_.createPipeline(current_desc_);+}++void ImmediateDraw::setDepthTest(bool enabled) {+ if (current_desc_.depthTest == enabled) return;+ if (pendingGeometry_) flush();+ current_desc_.depthTest = enabled;+ pipeline_ = device_.createPipeline(current_desc_);}void ImmediateDraw::flush() {diff --git a/src/esengine/renderer/ImmediateDraw.hpp b/src/esengine/renderer/ImmediateDraw.hppindex 863603d81..1299d2579 100644--- a/src/esengine/renderer/ImmediateDraw.hpp+++ b/src/esengine/renderer/ImmediateDraw.hpp@@ -20,6 +20,7 @@#include "../core/Types.hpp"#include "../math/Math.hpp"+#include "PipelineState.hpp"#include "TransientBufferPool.hpp"#include <glm/glm.hpp>@@ -148,6 +149,13 @@ public:void setDepth(f32 depth) { currentDepth_ = depth; }f32 getDepth() const { return currentDepth_; }+ /** Switches the blend mode for subsequent primitives (flushes pending geometry). */+ void setBlendMode(BlendMode mode);+ /** Toggles depth testing for subsequent primitives (flushes pending geometry). */+ void setDepthTest(bool enabled);+ BlendMode blendMode() const { return current_desc_.blend; }+ bool depthTest() const { return current_desc_.depthTest; }+// =========================================================================// Statistics// =========================================================================@@ -173,6 +181,8 @@ private:TransientBufferPool pool_;ShaderHandle batch_shader_ = ShaderHandle::Invalid;+ PipelineDesc base_desc_{};+ PipelineDesc current_desc_{};PipelineHandle pipeline_ = PipelineHandle::Invalid;u32 white_texture_id_ = 0;u32 currentTexture_ = 0;diff --git a/src/esengine/renderer/PipelineState.hpp b/src/esengine/renderer/PipelineState.hppindex bf1dbc1cb..c0094f9cf 100644--- a/src/esengine/renderer/PipelineState.hpp+++ b/src/esengine/renderer/PipelineState.hpp@@ -22,7 +22,7 @@#include "../core/Types.hpp"#include "BlendMode.hpp"-#include "GfxEnums.hpp" // LayoutId+#include "GfxEnums.hpp"namespace esengine {@@ -42,7 +42,7 @@ enum class GfxStencilMode : u8 {*/struct PipelineDesc {ShaderHandle program = ShaderHandle::Invalid;- LayoutId vertexLayout = LayoutId::Batch;+ VertexLayoutHandle vertexLayout = VertexLayoutHandle::Invalid;BlendMode blend = BlendMode::Normal;bool blendEnabled = true;bool depthTest = false;diff --git a/src/esengine/renderer/PostProcessPipeline.cpp b/src/esengine/renderer/PostProcessPipeline.cppindex 25d2281a9..71f1e110b 100644--- a/src/esengine/renderer/PostProcessPipeline.cpp+++ b/src/esengine/renderer/PostProcessPipeline.cpp@@ -122,9 +122,9 @@ void PostProcessPipeline::shutdown() {device->deleteBuffer(screen_quad_vbo_);screen_quad_vbo_ = BufferHandle::Invalid;}- if (screen_quad_vao_ != 0 && device) {- device->deleteVertexArray(screen_quad_vao_);- screen_quad_vao_ = 0;+ if (screen_quad_layout_ != VertexLayoutHandle::Invalid && device) {+ device->deleteVertexLayout(screen_quad_layout_);+ screen_quad_layout_ = VertexLayoutHandle::Invalid;}fboA_.reset();@@ -245,41 +245,41 @@ PostProcessPass* PostProcessPipeline::findPass(const std::string& name) {}void PostProcessPipeline::ensureScreenQuad() {- if (screen_quad_vao_ != 0) return;-- auto* device = &device_;+ if (screen_quad_layout_ != VertexLayoutHandle::Invalid) return;+ // One fullscreen triangle (position + uv), drawn non-indexed.f32 vertices[] = {-1.0f, -1.0f, 0.0f, 0.0f,3.0f, -1.0f, 2.0f, 0.0f,-1.0f, 3.0f, 0.0f, 2.0f,};-- constexpr i32 STRIDE = 4 * static_cast<i32>(sizeof(f32));-- u32 vao = device->createVertexArray();- device->bindVertexArray(vao);-- BufferHandle vbo = device->createBuffer(+ screen_quad_vbo_ = device_.createBuffer({GfxBufferUsage::Vertex, static_cast<u32>(sizeof(vertices)), /*dynamic=*/false}, vertices);- device->bindVertexBuffer(vbo);- device->enableVertexAttrib(0);- device->vertexAttribPointer(0, 2, GfxDataType::Float, false, STRIDE, 0);- device->enableVertexAttrib(1);- device->vertexAttribPointer(1, 2, GfxDataType::Float, false, STRIDE, 2 * sizeof(f32));-- device->bindVertexArray(0);-- screen_quad_vao_ = vao;- screen_quad_vbo_ = vbo;+ VertexLayoutDesc desc;+ desc.attributeCount = 2;+ desc.strides[0] = 4 * sizeof(f32);+ desc.attributes[0] = {0, 2, GfxDataType::Float, false, 0, 0};+ desc.attributes[1] = {1, 2, GfxDataType::Float, false, 2 * sizeof(f32), 0};+ screen_quad_layout_ = device_.createVertexLayout(desc);}void PostProcessPipeline::drawScreenQuad() {+ device_.setVertexBuffer(0, screen_quad_vbo_, 0);+ device_.setIndexBuffer(BufferHandle::Invalid);+ device_.drawArrays(0, 3);+}++void PostProcessPipeline::applyPassPipeline(const Shader& shader) {ensureScreenQuad();- auto* device = &device_;- device->bindVertexArray(screen_quad_vao_);- device->drawArrays(0, 3);+ // Fullscreen passes overwrite every pixel: no blend, no depth, no stencil.+ PipelineDesc desc{};+ desc.program = shader.handle();+ desc.vertexLayout = screen_quad_layout_;+ desc.blendEnabled = false;+ desc.depthTest = false;+ desc.depthWrite = false;+ device_.setPipeline(device_.createPipeline(desc));}void PostProcessPipeline::begin() {@@ -307,11 +307,10 @@ void PostProcessPipeline::end() {if (pass.enabled) enabledCount++;}- device->setDepthTest(false);- device->setBlendEnabled(false);+ // Blend/depth/stencil/color-mask come from the fullscreen pass pipeline;+ // scissor is dynamic state and must be dropped explicitly.+ device->invalidatePipelineCache();device->setScissorTest(false);- device->setStencilTest(false);- device->setColorMask(true, true, true, true);sceneTexture_ = fboOriginal_->getColorAttachment();fboOriginal_->unbind();@@ -344,8 +343,7 @@ void PostProcessPipeline::end() {blitToOutput(inputTexture);}- device->setBlendEnabled(true);- device->setDepthTest(true);+ device->invalidatePipelineCache();inFrame_ = false;output_target_fbo_ = FramebufferHandle::Default;}@@ -357,7 +355,7 @@ void PostProcessPipeline::renderPass(const PostProcessPass& pass, TextureHandleauto* device = &device_;device->bindTexture(0, inputTexture);- shader->bind();+ applyPassPipeline(*shader);shader->setUniform("u_texture", 0);// u_sceneTexture and u_resolution are engine-provided builtins that only some// passes use (bloom's composite taps the untouched scene; kawase/pixelate/fxaa@@ -410,7 +408,7 @@ void PostProcessPipeline::blitToOutput(TextureHandle texture) {device->bindTexture(0, texture);- shader->bind();+ applyPassPipeline(*shader);shader->setUniform("u_texture", 0);drawScreenQuad();@@ -475,15 +473,13 @@ void PostProcessPipeline::executeScreenPasses() {}if (enabledCount == 0) {+ device->invalidatePipelineCache();blitToOutput(screenFBO_->getColorAttachment());return;}- device->setDepthTest(false);- device->setBlendEnabled(false);+ device->invalidatePipelineCache();device->setScissorTest(false);- device->setStencilTest(false);- device->setColorMask(true, true, true, true);ensureFBOs();if (!fbosCreated_) return;@@ -516,8 +512,7 @@ void PostProcessPipeline::executeScreenPasses() {device->setViewport(0, 0, width_, height_);blitToOutput(inputTexture);- device->setBlendEnabled(true);- device->setDepthTest(true);+ device->invalidatePipelineCache();}u32 PostProcessPipeline::addScreenPass(const std::string& name, resource::ShaderHandle shader) {diff --git a/src/esengine/renderer/PostProcessPipeline.hpp b/src/esengine/renderer/PostProcessPipeline.hppindex b1aa85904..82c424687 100644--- a/src/esengine/renderer/PostProcessPipeline.hpp+++ b/src/esengine/renderer/PostProcessPipeline.hpp@@ -26,6 +26,7 @@ namespace esengine {class GfxDevice;class RenderContext;+class Shader;namespace resource {class ResourceManager;@@ -222,6 +223,7 @@ private:void ensureFBOs();void ensureScreenQuad();void drawScreenQuad();+ void applyPassPipeline(const Shader& shader);void renderPass(const PostProcessPass& pass, TextureHandle inputTexture);void blitToOutput(TextureHandle texture);@@ -232,7 +234,7 @@ private:Unique<Framebuffer> fboA_;Unique<Framebuffer> fboB_;Unique<Framebuffer> fboOriginal_;- u32 screen_quad_vao_ = 0;+ VertexLayoutHandle screen_quad_layout_ = VertexLayoutHandle::Invalid;BufferHandle screen_quad_vbo_ = BufferHandle::Invalid;resource::ShaderHandle blitShader_;diff --git a/src/esengine/renderer/TransientBufferPool.cpp b/src/esengine/renderer/TransientBufferPool.cppindex dfb2d732d..cc9a6cbe9 100644--- a/src/esengine/renderer/TransientBufferPool.cpp+++ b/src/esengine/renderer/TransientBufferPool.cpp@@ -28,7 +28,10 @@ void TransientBufferPool::shutdown() {if (!initialized_) return;for (auto& s : streams_) {- if (s.vao) { device_.deleteVertexArray(s.vao); s.vao = 0; }+ if (s.layout != VertexLayoutHandle::Invalid) {+ device_.deleteVertexLayout(s.layout);+ s.layout = VertexLayoutHandle::Invalid;+ }if (s.vbo != BufferHandle::Invalid) { device_.deleteBuffer(s.vbo); s.vbo = BufferHandle::Invalid; }if (s.ebo != BufferHandle::Invalid) { device_.deleteBuffer(s.ebo); s.ebo = BufferHandle::Invalid; }if (s.quad_vbo != BufferHandle::Invalid) { device_.deleteBuffer(s.quad_vbo); s.quad_vbo = BufferHandle::Invalid; }@@ -100,9 +103,8 @@ u32 TransientBufferPool::appendIndices(LayoutId layout, const u32* data, u32 cou}void TransientBufferPool::upload() {- // Growth goes through resizeBuffer, which keeps the handle stable — the stream's- // VAO association survives. Index uploads are safe against VAO capture because the- // device detaches the bound VAO before touching the element-array target.+ // Growth goes through resizeBuffer, which keeps the handle stable, so per-draw+ // buffer bindings and the backend's cached vertex state stay valid.for (auto& s : streams_) {if (s.vbo == BufferHandle::Invalid) continue;if (s.vertex_write_pos == 0 && s.index_write_pos == 0) continue;@@ -124,27 +126,27 @@ void TransientBufferPool::upload() {device_.updateBuffer(s.ebo, 0, s.index_staging.data(), eboBytes);}}- // Leave a neutral VAO bound so execute()'s bindLayout starts from a known state.- device_.bindVertexArray(0);}void TransientBufferPool::bindLayout(LayoutId layout) {const Stream& s = stream(layout);- if (s.vao) device_.bindVertexArray(s.vao);+ if (layout == LayoutId::ParticleInstance) {+ bindInstanceLayout(layout, 0);+ return;+ }+ device_.setVertexBuffer(0, s.vbo, 0);+ device_.setIndexBuffer(s.ebo);}void TransientBufferPool::bindInstanceLayout(LayoutId layout, u32 instanceByteOffset) {- Stream& s = stream(layout);- device_.bindVertexArray(s.vao);- // Rebase the per-instance attributes to this emitter's slice (no baseInstance in GLES3).- device_.bindVertexBuffer(s.vbo);- constexpr u32 IS = 40;- device_.vertexAttribPointer(2, 2, GfxDataType::Float, false, IS, instanceByteOffset + 0);- device_.vertexAttribPointer(3, 2, GfxDataType::Float, false, IS, instanceByteOffset + 8);- device_.vertexAttribPointer(4, 1, GfxDataType::Float, false, IS, instanceByteOffset + 16);- device_.vertexAttribPointer(5, 4, GfxDataType::UnsignedByte, true, IS, instanceByteOffset + 20);- device_.vertexAttribPointer(6, 2, GfxDataType::Float, false, IS, instanceByteOffset + 24);- device_.vertexAttribPointer(7, 2, GfxDataType::Float, false, IS, instanceByteOffset + 32);+ const Stream& s = stream(layout);+ device_.setVertexBuffer(0, s.quad_vbo, 0);+ device_.setVertexBuffer(1, s.vbo, instanceByteOffset);+ device_.setIndexBuffer(s.ebo);+}++VertexLayoutHandle TransientBufferPool::layoutHandle(LayoutId layout) const {+ return stream(layout).layout;}u8* TransientBufferPool::vertexData(LayoutId layout) {@@ -192,30 +194,22 @@ void TransientBufferPool::setupStream(LayoutId layout) {s.ebo = device_.createBuffer({GfxBufferUsage::Index, static_cast<u32>(sizeof(quadIdx)), /*dynamic=*/false}, quadIdx);- s.vao = device_.createVertexArray();- device_.bindVertexArray(s.vao);- device_.bindIndexBuffer(s.ebo);-- // Static quad attributes (divisor 0).- device_.bindVertexBuffer(s.quad_vbo);- device_.enableVertexAttrib(0);- device_.vertexAttribPointer(0, 2, GfxDataType::Float, false, 16, 0);- device_.enableVertexAttrib(1);- device_.vertexAttribPointer(1, 2, GfxDataType::Float, false, 16, 8);-- // Per-instance attributes (divisor 1); offsets rebased per draw in bindInstanceLayout.- constexpr u32 IS = 40;- device_.bindVertexBuffer(s.vbo);- device_.enableVertexAttrib(2); device_.vertexAttribPointer(2, 2, GfxDataType::Float, false, IS, 0); device_.vertexAttribDivisor(2, 1);- device_.enableVertexAttrib(3); device_.vertexAttribPointer(3, 2, GfxDataType::Float, false, IS, 8); device_.vertexAttribDivisor(3, 1);- device_.enableVertexAttrib(4); device_.vertexAttribPointer(4, 1, GfxDataType::Float, false, IS, 16); device_.vertexAttribDivisor(4, 1);- device_.enableVertexAttrib(5); device_.vertexAttribPointer(5, 4, GfxDataType::UnsignedByte, true, IS, 20); device_.vertexAttribDivisor(5, 1);- device_.enableVertexAttrib(6); device_.vertexAttribPointer(6, 2, GfxDataType::Float, false, IS, 24); device_.vertexAttribDivisor(6, 1);- device_.enableVertexAttrib(7); device_.vertexAttribPointer(7, 2, GfxDataType::Float, false, IS, 32); device_.vertexAttribDivisor(7, 1);-- device_.bindVertexArray(0);- device_.bindVertexBuffer(BufferHandle::Invalid);- device_.bindIndexBuffer(BufferHandle::Invalid);+ // Slot 0: the static quad (per vertex). Slot 1: the instance stream (per instance),+ // rebased per draw in bindInstanceLayout.+ VertexLayoutDesc desc;+ desc.attributeCount = 8;+ desc.strides[0] = 16;+ desc.strides[1] = 40;+ desc.instanceStep[1] = true;+ desc.attributes[0] = {0, 2, GfxDataType::Float, false, 0, 0};+ desc.attributes[1] = {1, 2, GfxDataType::Float, false, 8, 0};+ desc.attributes[2] = {2, 2, GfxDataType::Float, false, 0, 1};+ desc.attributes[3] = {3, 2, GfxDataType::Float, false, 8, 1};+ desc.attributes[4] = {4, 1, GfxDataType::Float, false, 16, 1};+ desc.attributes[5] = {5, 4, GfxDataType::UnsignedByte, true, 20, 1};+ desc.attributes[6] = {6, 2, GfxDataType::Float, false, 24, 1};+ desc.attributes[7] = {7, 2, GfxDataType::Float, false, 32, 1};+ s.layout = device_.createVertexLayout(desc);return;}@@ -228,53 +222,36 @@ void TransientBufferPool::setupStream(LayoutId layout) {s.ebo = device_.createBuffer({GfxBufferUsage::Index, static_cast<u32>(s.ebo_capacity * sizeof(u32)), /*dynamic=*/true}, nullptr);- s.vao = device_.createVertexArray();- device_.bindVertexArray(s.vao);- // VAO captures the ELEMENT_ARRAY_BUFFER binding at this point, and every- // subsequent vertexAttribPointer captures the currently-bound ARRAY_BUFFER.- device_.bindVertexBuffer(s.vbo);- device_.bindIndexBuffer(s.ebo);-+ VertexLayoutDesc desc;switch (layout) {- case LayoutId::Batch: {- constexpr u32 STRIDE = 24; // BatchVertex: pos(8) + color(4) + uv(8) + texIndex(4)- device_.enableVertexAttrib(0);- device_.vertexAttribPointer(0, 2, GfxDataType::Float, false, STRIDE, 0);- device_.enableVertexAttrib(1);- device_.vertexAttribPointer(1, 4, GfxDataType::UnsignedByte, true, STRIDE, 8);- device_.enableVertexAttrib(2);- device_.vertexAttribPointer(2, 2, GfxDataType::Float, false, STRIDE, 12);- device_.enableVertexAttrib(3);- device_.vertexAttribPointer(3, 1, GfxDataType::Float, false, STRIDE, 20);+ case LayoutId::Batch:+ // BatchVertex: pos(8) + color(4) + uv(8) + texIndex(4)+ desc.attributeCount = 4;+ desc.strides[0] = 24;+ desc.attributes[0] = {0, 2, GfxDataType::Float, false, 0, 0};+ desc.attributes[1] = {1, 4, GfxDataType::UnsignedByte, true, 8, 0};+ desc.attributes[2] = {2, 2, GfxDataType::Float, false, 12, 0};+ desc.attributes[3] = {3, 1, GfxDataType::Float, false, 20, 0};break;- }- case LayoutId::Shape: {- constexpr u32 STRIDE = 48;- device_.enableVertexAttrib(0);- device_.vertexAttribPointer(0, 2, GfxDataType::Float, false, STRIDE, 0);- device_.enableVertexAttrib(1);- device_.vertexAttribPointer(1, 2, GfxDataType::Float, false, STRIDE, 8);- device_.enableVertexAttrib(2);- device_.vertexAttribPointer(2, 4, GfxDataType::Float, false, STRIDE, 16);- device_.enableVertexAttrib(3);- device_.vertexAttribPointer(3, 4, GfxDataType::Float, false, STRIDE, 32);+ case LayoutId::Shape:+ desc.attributeCount = 4;+ desc.strides[0] = 48;+ desc.attributes[0] = {0, 2, GfxDataType::Float, false, 0, 0};+ desc.attributes[1] = {1, 2, GfxDataType::Float, false, 8, 0};+ desc.attributes[2] = {2, 4, GfxDataType::Float, false, 16, 0};+ desc.attributes[3] = {3, 4, GfxDataType::Float, false, 32, 0};break;- }- case LayoutId::MatSprite: {- constexpr u32 STRIDE = 32;- device_.enableVertexAttrib(0);- device_.vertexAttribPointer(0, 2, GfxDataType::Float, false, STRIDE, 0);- device_.enableVertexAttrib(1);- device_.vertexAttribPointer(1, 2, GfxDataType::Float, false, STRIDE, 8);- device_.enableVertexAttrib(2);- device_.vertexAttribPointer(2, 4, GfxDataType::Float, false, STRIDE, 16);+ case LayoutId::MatSprite:+ desc.attributeCount = 3;+ desc.strides[0] = 32;+ desc.attributes[0] = {0, 2, GfxDataType::Float, false, 0, 0};+ desc.attributes[1] = {1, 2, GfxDataType::Float, false, 8, 0};+ desc.attributes[2] = {2, 4, GfxDataType::Float, false, 16, 0};+ break;+ default:break;- }}-- device_.bindVertexArray(0);- device_.bindVertexBuffer(BufferHandle::Invalid);- device_.bindIndexBuffer(BufferHandle::Invalid);+ s.layout = device_.createVertexLayout(desc);}void TransientBufferPool::growVertexStaging(Stream& s, u32 requiredBytes) {diff --git a/src/esengine/renderer/TransientBufferPool.hpp b/src/esengine/renderer/TransientBufferPool.hppindex 66287dc7d..6190caa1e 100644--- a/src/esengine/renderer/TransientBufferPool.hpp+++ b/src/esengine/renderer/TransientBufferPool.hpp@@ -14,7 +14,7 @@ namespace esengine {// reference LayoutId without pulling in the GfxDevice include cycle./**- * Per-frame vertex/index staging with one independent VBO+EBO+VAO per layout.+ * Per-frame vertex/index staging with one independent VBO+EBO+vertex-layout per stream.** Design note: heterogeneous vertex formats (BatchVertex 20B, ShapeVertex 48B,* ...) cannot safely share a single VBO because each plugin computes@@ -46,16 +46,19 @@ public:/** Upload every non-empty stream's staging to its VBO/EBO. */void upload();- /** Bind the VAO for this layout (which also binds its EBO — VAO state). */+ /** Bind this stream's vertex + index buffers for the next draw. */void bindLayout(LayoutId layout);/**- * Bind an instanced layout and re-point its per-instance attributes to @p instanceByteOffset.+ * Bind an instanced stream with its per-instance buffer rebased to @p instanceByteOffset.* GLES3 has no baseInstance, so each emitter's instanced draw rebases the instance- * attributes here before drawElementsInstanced. The static quad attributes are untouched.+ * slot here before drawElementsInstanced. The static quad slot is untouched.*/void bindInstanceLayout(LayoutId layout, u32 instanceByteOffset);+ /** The device vertex layout a pipeline drawing this stream must reference. */+ VertexLayoutHandle layoutHandle(LayoutId layout) const;+/** Direct write-through pointer into a layout's staging, for hot paths* that want to format vertices in place after `allocVertices`. */u8* vertexData(LayoutId layout);@@ -68,8 +71,8 @@ private:struct Stream {BufferHandle vbo = BufferHandle::Invalid; // for ParticleInstance: the per-instance (streamed) bufferBufferHandle ebo = BufferHandle::Invalid;- u32 vao = 0;- BufferHandle quad_vbo = BufferHandle::Invalid; // ParticleInstance only: static unit-quad geometry (divisor 0)+ VertexLayoutHandle layout = VertexLayoutHandle::Invalid;+ BufferHandle quad_vbo = BufferHandle::Invalid; // ParticleInstance only: static unit-quad geometry (slot 0)std::vector<u8> vertex_staging;std::vector<u32> index_staging; // 32-bit indices: a single Batch stream can exceed 65535 verticesu32 vertex_write_pos = 0;diff --git a/tests/renderer/MockGfxDevice.hpp b/tests/renderer/MockGfxDevice.hppindex d4ef8471e..f487a5cd7 100644--- a/tests/renderer/MockGfxDevice.hpp+++ b/tests/renderer/MockGfxDevice.hpp@@ -15,9 +15,6 @@ struct MockGfxDevice final : GfxDevice {// call countersint useProgramCalls = 0;int bindTextureCalls = 0;- int bindVertexArrayCalls = 0;- int bindVertexBufferCalls = 0;- int bindIndexBufferCalls = 0;int bindFramebufferCalls = 0;int createProgramCalls = 0;int deleteProgramCalls = 0;@@ -38,16 +35,16 @@ struct MockGfxDevice final : GfxDevice {int updateBufferCalls = 0;int resizeBufferCalls = 0;int setUniformBufferCalls = 0;- int createVertexArrayCalls = 0;- int deleteVertexArrayCalls = 0;- int enableVertexAttribCalls = 0;- int vertexAttribPointerCalls = 0;+ int createVertexLayoutCalls = 0;+ int deleteVertexLayoutCalls = 0;+ int setVertexBufferCalls = 0;+ int setIndexBufferCalls = 0;int setPipelineCalls = 0;u32 nextTextureId = 100;u32 nextBufferId = 200;u32 nextFramebufferId = 500;- u32 nextVaoId = 800;+ u32 nextVertexLayoutId = 800;u32 nextPipelineId = 0;bool createTextureFails = false; // toggle to exercise the OOM / lost-context path (-> Invalid)@@ -55,7 +52,7 @@ struct MockGfxDevice final : GfxDevice {// last argsShaderHandle lastProgram = ShaderHandle::Invalid;- u32 lastVao = 0;+ VertexLayoutDesc lastVertexLayoutDesc{};BufferHandle lastVbo = BufferHandle::Invalid;BufferHandle lastIbo = BufferHandle::Invalid;FramebufferHandle lastFbo = FramebufferHandle::Default;@@ -105,8 +102,15 @@ struct MockGfxDevice final : GfxDevice {void updateBuffer(BufferHandle, u32, const void*, u32) override { ++updateBufferCalls; }void resizeBuffer(BufferHandle, u32, const void*) override { ++resizeBufferCalls; }void setUniformBuffer(u32, BufferHandle) override { ++setUniformBufferCalls; }- void bindVertexBuffer(BufferHandle buffer) override { ++bindVertexBufferCalls; lastVbo = buffer; }- void bindIndexBuffer(BufferHandle buffer) override { ++bindIndexBufferCalls; lastIbo = buffer; }++ VertexLayoutHandle createVertexLayout(const VertexLayoutDesc& desc) override {+ ++createVertexLayoutCalls;+ lastVertexLayoutDesc = desc;+ return VertexLayoutHandle{nextVertexLayoutId++};+ }+ void deleteVertexLayout(VertexLayoutHandle) override { ++deleteVertexLayoutCalls; }+ void setVertexBuffer(u32, BufferHandle buffer, u32) override { ++setVertexBufferCalls; lastVbo = buffer; }+ void setIndexBuffer(BufferHandle buffer) override { ++setIndexBufferCalls; lastIbo = buffer; }TextureHandle createTexture(const TextureDesc& desc, const void* pixels) override {++createTextureCalls;@@ -163,13 +167,6 @@ struct MockGfxDevice final : GfxDevice {void setStencilReference(i32) override {}void invalidatePipelineCache() override {}- u32 createVertexArray() override { ++createVertexArrayCalls; return nextVaoId++; }- void deleteVertexArray(u32) override { ++deleteVertexArrayCalls; }- void bindVertexArray(u32 vaoId) override { ++bindVertexArrayCalls; lastVao = vaoId; }- void enableVertexAttrib(u32) override { ++enableVertexAttribCalls; }- void vertexAttribPointer(u32, i32, GfxDataType, bool, i32, u32) override { ++vertexAttribPointerCalls; }- void vertexAttribDivisor(u32, u32) override {}-void drawElements(u32, GfxDataType, u32) override {}void drawArrays(u32, u32) override {}void drawElementsInstanced(u32, GfxDataType, u32, u32) override {}diff --git a/tests/renderer/test_buffer_device.cpp b/tests/renderer/test_buffer_device.cppindex c4ccf4ee2..f03e8a233 100644--- a/tests/renderer/test_buffer_device.cpp+++ b/tests/renderer/test_buffer_device.cpp@@ -1,8 +1,8 @@-// Native MSVC/CTest harness for Buffer + CustomGeometry (RC5-GfxDevice).+// Native MSVC/CTest harness for Buffer + CustomGeometry (GfxDevice).//// Compiles the converted Buffer.cpp + CustomGeometry.cpp against MockGfxDevice.// Linking proves they no longer touch GL; the asserts confirm create/upload/-// attribute-setup/bind/delete all route through GfxDevice.+// layout-registration/bind/delete all route through GfxDevice.#include "MockGfxDevice.hpp"#include "esengine/renderer/Buffer.hpp"@@ -51,24 +51,6 @@ int main() {CHECK(!ibo->is16Bit(), "u32 indices not flagged 16-bit");}- // --- VertexArray + attribute setup ---- {- MockGfxDevice d;- float verts[] = { 0, 0, 0, 0 };- auto vao = VertexArray::create(d);- CHECK(d.createVertexArrayCalls == 1, "VertexArray::create -> device.createVertexArray");-- auto vbo = Shared<VertexBuffer>(VertexBuffer::createRaw(d, verts, sizeof(verts)));- vbo->setLayout({- { ShaderDataType::Float2, "a_position" },- { ShaderDataType::Float2, "a_texCoord" },- });- vao->addVertexBuffer(vbo);- CHECK(d.enableVertexAttribCalls == 2, "addVertexBuffer enables one attrib per layout entry");- CHECK(d.vertexAttribPointerCalls == 2, "addVertexBuffer sets one pointer per layout entry");- CHECK(d.bindVertexArrayCalls >= 1, "addVertexBuffer binds the VAO via device");- }-// --- CustomGeometry end-to-end (init + indices + bind, all via device) ---{MockGfxDevice d;@@ -80,15 +62,19 @@ int main() {{ ShaderDataType::Float2, "a_texCoord" },});CHECK(geom.isValid(), "CustomGeometry initialized");- CHECK(d.createVertexArrayCalls == 1, "geom.init creates a VAO via device");CHECK(d.createBufferCalls == 1, "geom.init creates a VBO via device");+ CHECK(d.createVertexLayoutCalls == 1, "geom.init registers its vertex layout via device");+ CHECK(d.lastVertexLayoutDesc.attributeCount == 2, "layout carries one entry per attribute");+ CHECK(d.lastVertexLayoutDesc.strides[0] == 16, "layout carries the vertex stride");+ CHECK(geom.layoutHandle() != VertexLayoutHandle::Invalid, "geometry exposes its layout handle");geom.setIndices(idx, 3);CHECK(geom.hasIndices() && geom.getIndexCount() == 3, "geom.setIndices stored an index buffer");CHECK(d.createBufferCalls == 2, "geom.setIndices creates an IBO via device");geom.bind(d);- CHECK(d.bindVertexArrayCalls >= 1, "geom.bind routes through device");+ CHECK(d.setVertexBufferCalls == 1 && d.setIndexBufferCalls == 1,+ "geom.bind sets the vertex + index buffers via device");}// --- CustomGeometry: an empty vertex layout must not divide-by-zero ---@@ -100,8 +86,9 @@ int main() {geom.init(d, verts, 4, VertexLayout{}); // empty layout -> stride 0CHECK(!geom.isValid(), "init with an empty layout leaves the geometry invalid (no crash)");CHECK(d.createBufferCalls == 0, "no VBO is created for an empty layout");+ CHECK(d.createVertexLayoutCalls == 0, "no device layout is registered for an empty layout");geom.bind(d);- CHECK(d.bindVertexArrayCalls == 0, "bind on an empty-layout geometry is a no-op");+ CHECK(d.setVertexBufferCalls == 0, "bind on an empty-layout geometry is a no-op");}if (g_failures == 0) {