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
feat(render): unified command pipeline — BatchBuilder is the single DrawCommand producer
yhh8b1b64d73944
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex b25e06b61..a2ef244cc 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -77,6 +77,9 @@ jobs:- name: Check GL boundary (no gl* outside GLDevice)run: node tools/check-gl-boundary.mjs+ - name: Check render-command boundary (DrawCommands built only by BatchBuilder)+ run: node tools/check-draw-command-boundary.mjs+- name: Install dependenciesrun: pnpm installdiff --git a/docs/REARCHITECTURE.md b/docs/REARCHITECTURE.mdindex 85e8edcc3..89c593660 100644--- a/docs/REARCHITECTURE.md+++ b/docs/REARCHITECTURE.md@@ -165,7 +165,15 @@- **RenderPass**:`beginRenderPass(desc)`/`endRenderPass` 收拢 FBO 绑定 + clear(load-op 语义:强制写掩码,修复"上帧末尾 stencil-write pipeline 会静默吞掉 clear"的潜在 bug);`bindFramebuffer` 退出公共接口。TS 驱动的主 pass clear 保留在边界(多相机 scissored clear 依赖),文档标注为 WebGPU 后端的 deferred-load-op 仿真点。- **散装状态 setter 全部转 GLDevice 私有**:公共动态状态只剩 scissor + stencil reference(与 WebGPU 划分一致)。- 验证:MockGfxDevice 四套 harness、web 构建、GL boundary guard、六个 headless 渲染场景(精灵/UI 模板遮罩/后处理链/实例化粒子/Lit 材质/tilemap)+ 编辑器截图(网格 draw_mesh 路径)全绿。-- **遗留**:散装 `setUniform*`(自定义网格 + 后处理路径)仍是 GL 式 per-program uniform——WebGPU 后端需按 sokol 方式以每 draw 暂存 UBO 仿真,或后续把这两条路径迁 UBO。+- ~~**遗留**:散装 `setUniform*`(自定义网格 + 后处理路径)仍是 GL 式 per-program uniform~~ — **✅ 已迁 UBO(2026-07-06,`4c538529`,DrawParams)**:`rewriteLooseUniforms`(renderer/DrawParams)在 `ResourceManager::createShader` 咽喉点把两 stage 的散装非 sampler uniform(float/int/vec2-4/mat3/mat4,单声明符)提升为共享的 `layout(std140) uniform DrawParams` 块(binding 4;0=Frame 1=Material 2=Light 3=Time);`Shader::setUniform` 保持原作者面,成为 facade——命中块成员写入 CPU 影子(std140 偏移,mat3 展开 vec4 stride),sampler 落回散装路径,`hasUniform` 认块成员;`commitParams()` 脏则上传、每 draw 必绑(后处理 renderPass/blit、draw_mesh(+WithUniforms) 提交)。安全网:GLSL ES 1.00 源跳过(UBO 需 300 es)、提升后编译失败回退原源重试、RenderContext 每 pass 在 binding 4 预绑 4KiB 零 fallback(未提交路径读零=旧散装默认,且满足 WebGL bound-range 检查)。`compileEsshader` 显式豁免(参数已在 MaterialConstants)。编辑器网格 shader 移植 300 es 成为生产消费者(2×mat4+3×float+4×vec4 全走一个 UBO)。验证:`tests/renderer/test_draw_params.cpp`(39 检查,MockGfxDevice 断言无散装上传)+ verify 战役(sprite 逐位一致/postprocess/粒子渐变+尺寸曲线/mat-lit-point/mat-graph)+ 编辑器截图(网格经 UBO 渲染无 shader 错误)+ GL boundary guard + SDK 2791/desktop 410/双侧 tsc 全绿。**尚余(WebGPU 前最后两片)**:① TS 驱动主 pass clear → deferred load-op;② GLSL-only `createProgram` → WGSL 通路(DrawParams 块重写已定义 WGSL 需发射的形状);之后 RHI 的 `setUniform2f/3f/4f/Mat3/Mat4` 可裁(只剩 sampler 1i + 引擎内嵌路径)。++### 渲染统一命令面(Unified Render Pipeline)— ✅ 已落地(2026-07-07)+RC5"渲染唯一路径"的收官:所有 Renderer 只**生成命令**,Sort/Merge/Batch/Submit 全部统一在 `DrawList`。审计发现命令流架构已存在(六个 plugin + spine/text/tile 直接提交都进同一 `DrawCommand`/`DrawList`),残留的是最后两个手搓命令的 plugin 与四份复制的 collect 前奏:+- **单一命令生产面**:`BatchBuilder.cpp` 成为全仓**唯一**组装 `DrawCommand` 的翻译单元。`BatchDrawKey` 增加 `layoutId`/`instanceCount`;新增布局泛型 `appendIndexedDraw`(任意顶点格式,步长由 `TransientBufferPool::vertexStride()` 单一来源提供,杜绝调用方 sizeof 与设备布局漂移)。ShapePlugin(手搓命令 + 私有 QUAD_INDICES)与 ParticlePlugin(手搓实例化命令)全部改走该面,命令语义逐字段保持(纹理槽规则:Batch 流恒 1 槽白纹理兜底,非 Batch 流无纹理则 0 槽不碰 sampler)。+- **CI guard**:`tools/check-draw-command-boundary.mjs`(对齐 GL boundary guard 模式,接入 build.yml)——`DrawCommand` 组装或 `DrawList` push 出现在 BatchBuilder.cpp 之外即失败。新增一种 Renderer(NinePatch/Trail/Mesh2D…)= 算顶点 + 填 `BatchDrawKey` + append,零底层改动。+- **共享 collect 前奏**:`CameraWorldRect` 由 `RenderFrame::collectAll` 每次 collect 计算一次进 `RenderCollectContext`(此前 Sprite/Shape/Text/Tilemap 四个 plugin 各自求逆 VP 推相机中心/边界);`parallaxedWorldPosition()` helper(RenderTypePlugin.hpp)收拢 ensureDecomposed + 视差偏移 + "cull 于绘制处"约定。+- **刻意保留的两条即时模式边界**(非场景命令流,不进 DrawList 是语义选择而非欠账):`ImmediateDraw`(编辑器/调试叠加,自带 flush 时序)与 `draw_mesh` 自定义网格(在 TS 自定义绘制回调期内即时执行,依赖 pre-scene/post-flush 顺序语义)。+- 验证:新增 `tests/renderer/test_batch_builder.cpp`(8 用例 43 断言:各流 baseVertex 步长、纹理槽规则、实例化命令组装、多纹理合并 + texIndex 重写、跨流不合并、clip 盖章、execute 分发);六套 MockGfxDevice harness、web 构建、11 个 headless 像素场景(sprite / parallax-shape / text-sdf / 粒子×2 / tilemap×2 / ui-mask / lit×2 / postprocess)全 PASS;双 boundary guard 绿。### 地基收口(Foundation Consolidation)— 🟡 进行中,RC6 前置(设计文档)见 [`REARCH_FOUNDATION_CONSOLIDATION.md`](./REARCH_FOUNDATION_CONSOLIDATION.md):diff --git a/src/esengine/renderer/BatchBuilder.cpp b/src/esengine/renderer/BatchBuilder.cppindex ac3d7a50e..28791b280 100644--- a/src/esengine/renderer/BatchBuilder.cpp+++ b/src/esengine/renderer/BatchBuilder.cpp@@ -2,7 +2,7 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file BatchBuilder.cpp- * @brief Implementation of the shared batch submission primitive.+ * @brief Implementation of the single submission face — the only DrawCommand producer.** @author ESEngine Team* @date 2026@@ -18,7 +18,7 @@ namespace esengine {namespace {-// Reused across calls so offsetting local indices into the shared Batch stream costs no+// Reused across calls so offsetting local indices into the target stream costs no// per-call heap allocation. The renderer collects single-threaded and each call fully// consumes the scratch before returning, so a file-local buffer is safe — and it amortizes// the allocation across the frame, mirroring DrawList::sorted_scratch_.@@ -31,12 +31,12 @@ void pushBatchCommandImpl(TransientBufferPool& pool, DrawList& drawList, const Cconst BatchDrawKey& key) {if (indexCount == 0) return;- u32 baseVertex = vertexByteOffset / static_cast<u32>(sizeof(BatchVertex));+ u32 baseVertex = vertexByteOffset / pool.vertexStride(key.layoutId);g_indexScratch.resize(indexCount);for (u32 i = 0; i < indexCount; ++i) {g_indexScratch[i] = baseVertex + static_cast<u32>(localIndices[i]);}- u32 indexOffset = pool.appendIndices(LayoutId::Batch, g_indexScratch.data(), indexCount);+ u32 indexOffset = pool.appendIndices(key.layoutId, g_indexScratch.data(), indexCount);pushBatchDraw(drawList, clips, vertexByteOffset, vertexCount, indexOffset, indexCount, key);}@@ -55,14 +55,18 @@ void pushBatchDraw(DrawList& drawList, const ClipState& clips,cmd.index_count = indexCount;cmd.vertex_byte_offset = vertexByteOffset;cmd.vertex_count = vertexCount;+ cmd.instance_count = key.instanceCount;cmd.shader_id = key.shaderId;cmd.blend_mode = key.blend;- cmd.layout_id = LayoutId::Batch;+ cmd.layout_id = key.layoutId;cmd.material_id = key.materialId;cmd.depth_test = key.depthTest;cmd.depth_write = key.depthWrite;cmd.cull = key.cull;- cmd.texture_count = 1;+ // The Batch stream always samples a texture (white fallback at minimum); other+ // streams bind one only when the draw actually has one (the shape stream is+ // textureless, so execute() must not touch sampler units for it).+ cmd.texture_count = (key.layoutId == LayoutId::Batch || key.textureId != 0) ? 1 : 0;cmd.texture_ids[0] = key.textureId;cmd.entity = key.entity;cmd.type = key.type;@@ -86,14 +90,21 @@ void pushBatchCommand(TransientBufferPool& pool, DrawList& drawList, const ClipSpushBatchCommandImpl(pool, drawList, clips, vertexByteOffset, vertexCount, localIndices, indexCount, key);}+void appendIndexedDraw(TransientBufferPool& pool, DrawList& drawList, const ClipState& clips,+ const void* verts, u32 vertexCount,+ const u32* localIndices, u32 indexCount,+ const BatchDrawKey& key) {+ if (vertexCount == 0 || indexCount == 0) return;+ u32 vertexByteOffset = pool.appendVertices(+ key.layoutId, verts, vertexCount * pool.vertexStride(key.layoutId));+ pushBatchCommandImpl(pool, drawList, clips, vertexByteOffset, vertexCount, localIndices, indexCount, key);+}+void appendIndexedBatch(TransientBufferPool& pool, DrawList& drawList, const ClipState& clips,const BatchVertex* verts, u32 vertexCount,const u32* localIndices, u32 indexCount,const BatchDrawKey& key) {- if (vertexCount == 0 || indexCount == 0) return;- u32 vertexByteOffset = pool.appendVertices(- LayoutId::Batch, verts, vertexCount * static_cast<u32>(sizeof(BatchVertex)));- pushBatchCommandImpl(pool, drawList, clips, vertexByteOffset, vertexCount, localIndices, indexCount, key);+ appendIndexedDraw(pool, drawList, clips, verts, vertexCount, localIndices, indexCount, key);}} // namespace esenginediff --git a/src/esengine/renderer/BatchBuilder.hpp b/src/esengine/renderer/BatchBuilder.hppindex ad747ac31..39921ab28 100644--- a/src/esengine/renderer/BatchBuilder.hpp+++ b/src/esengine/renderer/BatchBuilder.hpp@@ -2,13 +2,16 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file BatchBuilder.hpp- * @brief Backend-agnostic batch submission primitive shared by every batch render path.- * @details Collapses the "append vertices -> offset indices by baseVertex -> assemble- * DrawCommand -> apply clip state -> push" sequence that each batch emitter- * (sprite/UI/text/particle/tilemap plugins + RenderFrame's spine/tile direct- * submits) used to copy verbatim. Giving the renderer one submission face here- * is the de-risking prerequisite for the GfxDevice keystone: the keystone rewrites- * DrawList::execute against a single producer, not six.+ * @brief The single submission face: the ONLY place a DrawCommand is assembled.+ * @details Every render path — the batch-quad plugins (sprite/UI/text), the dedicated+ * streams (shape/particle/tilemap), and RenderFrame's spine/text/tile direct+ * submits — describes its draw as a BatchDrawKey plus geometry, and this face+ * does the rest: append vertices, offset indices by baseVertex, build the sort+ * key, assemble the DrawCommand, apply clip state, push into the DrawList.+ * Renderers only *generate* commands; sorting, merging, and GfxDevice submission+ * live unified in DrawList. The invariant is CI-enforced+ * (tools/check-draw-command-boundary.mjs): DrawCommand assembly outside this+ * translation unit fails the build.** @author ESEngine Team* @date 2026@@ -86,14 +89,20 @@ struct BatchDrawKey {bool depthTest = false;bool depthWrite = true;u8 cull = 0; ///< CullMode: 0 = none, 1 = back, 2 = front.+ // The transient stream this draw's geometry lives in. Only the Batch stream carries+ // a per-vertex texIndex, so only it participates in the multi-texture merge.+ LayoutId layoutId = LayoutId::Batch;+ // > 0 selects an instanced draw: indexCount indices drawn instanceCount times, with+ // per-instance attributes based at the vertex byte offset (see DrawCommand).+ u32 instanceCount = 0;};/*** @brief Atomic primitive: assemble + clip + push one DrawCommand for an index range ALREADY- * written into the Batch stream.- * @details The single piece every batch path used to duplicate. Use directly when the caller- * streams both vertices and indices in place (the particle emitter writes its whole- * index range via writeIndices() before pushing one command).+ * written into (or, for instanced draws, static in) the key's stream.+ * @details The single piece every render path used to duplicate. Use directly when the caller+ * streams both vertices and indices in place, or for instanced draws over a static+ * index range (the particle emitter's unit quad).*/void pushBatchDraw(DrawList& drawList, const ClipState& clips,u32 vertexByteOffset, u32 vertexCount, u32 indexOffset, u32 indexCount,@@ -113,10 +122,22 @@ void pushBatchCommand(TransientBufferPool& pool, DrawList& drawList, const ClipSu32 vertexByteOffset, u32 vertexCount, const u16* localIndices, u32 indexCount,const BatchDrawKey& key);+/**+ * @brief Copies raw vertices into the key's stream, then pushes one DrawCommand spanning them.+ * @details The layout-generic bulk form: @p verts must be @p vertexCount records of the+ * stream's vertex stride (TransientBufferPool::vertexStride). This is the whole+ * face a renderer with its own vertex format needs (shape today; any future+ * trail/mesh2d stream).+ */+void appendIndexedDraw(TransientBufferPool& pool, DrawList& drawList, const ClipState& clips,+ const void* verts, u32 vertexCount,+ const u32* localIndices, u32 indexCount,+ const BatchDrawKey& key);+/*** @brief Copies @p verts into the Batch stream, then pushes one DrawCommand spanning them.- * @details The bulk form — a single command over @p vertexCount vertices / @p indexCount- * indices (particle emitter, tilemap chunk, single tile).+ * @details Typed convenience over appendIndexedDraw for the shared BatchVertex format+ * (tilemap chunk, single tile); the key must target the Batch stream.*/void appendIndexedBatch(TransientBufferPool& pool, DrawList& drawList, const ClipState& clips,const BatchVertex* verts, u32 vertexCount,diff --git a/src/esengine/renderer/RenderFrame.cpp b/src/esengine/renderer/RenderFrame.cppindex c1b6350a3..dac8e323e 100644--- a/src/esengine/renderer/RenderFrame.cpp+++ b/src/esengine/renderer/RenderFrame.cpp@@ -556,7 +556,8 @@ void RenderFrame::collectAll(ecs::Registry& registry, u32 skipFlags) {auto ctx = makeContext();- RenderCollectContext collectCtx{registry, frustum_, clip_state_, pool_, draw_list_, ctx};+ RenderCollectContext collectCtx{registry, frustum_, clip_state_, pool_, draw_list_, ctx,+ computeCameraWorldRect(ctx.view_projection)};for (auto& plugin : plugins_) {if (skipFlags != 0 && (skipFlags & plugin->skipFlag()) != 0) continue;plugin->collect(collectCtx);diff --git a/src/esengine/renderer/RenderTypePlugin.hpp b/src/esengine/renderer/RenderTypePlugin.hppindex bfc1ff879..13ea1ef26 100644--- a/src/esengine/renderer/RenderTypePlugin.hpp+++ b/src/esengine/renderer/RenderTypePlugin.hpp@@ -10,6 +10,7 @@#include "ClipState.hpp"#include "TransientBufferPool.hpp"#include "../ecs/Registry.hpp"+#include "../ecs/components/Transform.hpp"#include "../resource/ResourceManager.hpp"#include <glm/glm.hpp>@@ -33,6 +34,27 @@ struct RenderFrameContext {RenderFrame* frame = nullptr;};+/** @brief The camera's view bounds in world space, derived once per collect from the+ * inverse view-projection — the single source for every plugin's parallax and+ * world-rect culling math (previously re-derived inside each plugin). */+struct CameraWorldRect {+ f32 left = 0.0f, bottom = 0.0f, right = 0.0f, top = 0.0f;+ glm::vec2 center{0.0f};+};++inline CameraWorldRect computeCameraWorldRect(const glm::mat4& viewProjection) {+ glm::mat4 invVP = glm::inverse(viewProjection);+ glm::vec4 bl = invVP * glm::vec4(-1.0f, -1.0f, 0.0f, 1.0f);+ glm::vec4 tr = invVP * glm::vec4( 1.0f, 1.0f, 0.0f, 1.0f);+ CameraWorldRect rect;+ rect.left = bl.x / bl.w;+ rect.bottom = bl.y / bl.w;+ rect.right = tr.x / tr.w;+ rect.top = tr.y / tr.w;+ rect.center = { (rect.left + rect.right) * 0.5f, (rect.bottom + rect.top) * 0.5f };+ return rect;+}+struct RenderCollectContext {ecs::Registry& registry;const Frustum& frustum;@@ -40,8 +62,21 @@ struct RenderCollectContext {TransientBufferPool& buffer_pool;DrawList& draw_list;RenderFrameContext& frame_context;+ CameraWorldRect camera;};+/** @brief Decomposes @p transform and returns its world position shifted toward the+ * camera by (1 - parallax); factor 1 = no shift, 0 = screen-pinned. Applied+ * before the frustum cull so a parallaxed renderable is culled where drawn. */+inline glm::vec3 parallaxedWorldPosition(ecs::Transform& transform, const glm::vec2& parallax,+ const CameraWorldRect& camera) {+ transform.ensureDecomposed();+ glm::vec3 position = transform.worldPosition;+ position.x += camera.center.x * (1.0f - parallax.x);+ position.y += camera.center.y * (1.0f - parallax.y);+ return position;+}+class RenderTypePlugin {public:virtual ~RenderTypePlugin() = default;diff --git a/src/esengine/renderer/TransientBufferPool.cpp b/src/esengine/renderer/TransientBufferPool.cppindex cc9a6cbe9..3173f4b23 100644--- a/src/esengine/renderer/TransientBufferPool.cpp+++ b/src/esengine/renderer/TransientBufferPool.cpp@@ -169,6 +169,10 @@ BufferHandle TransientBufferPool::indexBuffer(LayoutId layout) const {return stream(layout).ebo;}+u32 TransientBufferPool::vertexStride(LayoutId layout) const {+ return stream(layout).vertex_stride;+}+void TransientBufferPool::setupStream(LayoutId layout) {Stream& s = stream(layout);@@ -209,6 +213,7 @@ void TransientBufferPool::setupStream(LayoutId layout) {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.vertex_stride = desc.strides[1];s.layout = device_.createVertexLayout(desc);return;}@@ -251,6 +256,7 @@ void TransientBufferPool::setupStream(LayoutId layout) {default:break;}+ s.vertex_stride = desc.strides[0];s.layout = device_.createVertexLayout(desc);}diff --git a/src/esengine/renderer/TransientBufferPool.hpp b/src/esengine/renderer/TransientBufferPool.hppindex 6190caa1e..7c5c6a99f 100644--- a/src/esengine/renderer/TransientBufferPool.hpp+++ b/src/esengine/renderer/TransientBufferPool.hpp@@ -59,6 +59,11 @@ public:/** The device vertex layout a pipeline drawing this stream must reference. */VertexLayoutHandle layoutHandle(LayoutId layout) const;+ /** Byte stride of this stream's writable vertex slot (the per-instance slot for+ * ParticleInstance) — the single source for baseVertex math, so submission code+ * never hardcodes a sizeof that could drift from the device layout. */+ u32 vertexStride(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);@@ -75,6 +80,7 @@ private: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 vertices+ u32 vertex_stride = 0;u32 vertex_write_pos = 0;u32 index_write_pos = 0;u32 vbo_capacity = 0;diff --git a/src/esengine/renderer/plugins/ParticlePlugin.cpp b/src/esengine/renderer/plugins/ParticlePlugin.cppindex 23eab5f72..da755c9b0 100644--- a/src/esengine/renderer/plugins/ParticlePlugin.cpp+++ b/src/esengine/renderer/plugins/ParticlePlugin.cpp@@ -1,6 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team#include "ParticlePlugin.hpp"+#include "../BatchBuilder.hpp"#include "../RenderContext.hpp"#include "../RenderFrame.hpp"#include "../Shader.hpp"@@ -140,26 +141,21 @@ void ParticlePlugin::collect(RenderCollectContext& collect_ctx) {d.uvScaleY = sheet ? uvScaleY : 1.0f;});- DrawCommand cmd{};- cmd.sort_key = DrawCommand::buildSortKey(- ctx.current_stage, emitter.layer, particle_shader_id_, blendMode, 0,- emitterWorldPos.z);- cmd.index_offset = 0; // static unit-quad indices- cmd.index_count = 6;- cmd.vertex_byte_offset = instByteOffset; // base of this emitter's instance slice- cmd.instance_count = particleCount;- cmd.shader_id = particle_shader_id_;- cmd.blend_mode = blendMode;- cmd.layout_id = LayoutId::ParticleInstance;- cmd.texture_count = 1;- cmd.texture_ids[0] = textureId;- cmd.entity = entity;- cmd.entity_count = 1;- cmd.type = RenderType::Particle;- cmd.layer = emitter.layer;-- clips.applyTo(entity, cmd);- draw_list.push(cmd);+ BatchDrawKey key{+ .stage = ctx.current_stage,+ .layer = emitter.layer,+ .shaderId = particle_shader_id_,+ .blend = blendMode,+ .textureId = textureId,+ .depth = emitterWorldPos.z,+ .entity = entity,+ .type = RenderType::Particle,+ .layoutId = LayoutId::ParticleInstance,+ .instanceCount = particleCount,+ };+ // The stream's static unit-quad indices (offset 0) drawn once per particle,+ // with the instance slice based at instByteOffset.+ pushBatchDraw(draw_list, clips, instByteOffset, 0, 0, 6, key);}}diff --git a/src/esengine/renderer/plugins/ShapePlugin.cpp b/src/esengine/renderer/plugins/ShapePlugin.cppindex c2e698194..19ded3398 100644--- a/src/esengine/renderer/plugins/ShapePlugin.cpp+++ b/src/esengine/renderer/plugins/ShapePlugin.cpp@@ -1,6 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team#include "ShapePlugin.hpp"+#include "../BatchBuilder.hpp"#include "../RenderContext.hpp"#include "../RenderFrame.hpp"#include "../Shader.hpp"@@ -37,26 +38,12 @@ void ShapePlugin::collect(RenderCollectContext& collect_ctx) {auto& ctx = collect_ctx.frame_context;auto shapeView = registry.view<ecs::Transform, ecs::ShapeRenderer>();- // Camera center in world space (from the inverse view-projection), for parallax —- // the same derivation SpritePlugin/TilemapRenderPlugin use, so every renderable's- // parallax scrolls consistently. Computed once per collect.- glm::mat4 invVP = glm::inverse(ctx.view_projection);- glm::vec4 camBL = invVP * glm::vec4(-1.0f, -1.0f, 0.0f, 1.0f);- glm::vec4 camTR = invVP * glm::vec4( 1.0f, 1.0f, 0.0f, 1.0f);- const f32 camCenterX = (camBL.x / camBL.w + camTR.x / camTR.w) * 0.5f;- const f32 camCenterY = (camBL.y / camBL.w + camTR.y / camTR.w) * 0.5f;-for (auto entity : shapeView) {const auto& shape = shapeView.get<ecs::ShapeRenderer>(entity);if (!shape.enabled) continue;auto& transform = shapeView.get<ecs::Transform>(entity);- transform.ensureDecomposed();- glm::vec3 position = transform.worldPosition;- // Parallax: shift toward the camera by (1 - factor); factor 1 = no shift.- // Applied before the frustum cull so a parallaxed shape is culled where drawn.- position.x += camCenterX * (1.0f - shape.parallax.x);- position.y += camCenterY * (1.0f - shape.parallax.y);+ glm::vec3 position = parallaxedWorldPosition(transform, shape.parallax, collect_ctx.camera);const auto& rotation = transform.worldRotation;const auto& scale = transform.worldScale;@@ -105,31 +92,17 @@ void ShapePlugin::collect(RenderCollectContext& collect_ctx) {verts[v].cornerRadius = shape.cornerRadius;}- u32 vOff = buffers.appendVertices(LayoutId::Shape, verts, sizeof(verts));- u32 baseVertex = vOff / sizeof(ShapeVertex);-- u32 indices[6];- for (u32 i = 0; i < 6; ++i) {- indices[i] = static_cast<u32>(baseVertex + QUAD_INDICES[i]);- }- u32 iOff = buffers.appendIndices(LayoutId::Shape, indices, 6);-- DrawCommand cmd{};- cmd.sort_key = DrawCommand::buildSortKey(ctx.current_stage, shape.layer, shape_shader_id_, BlendMode::Normal, 0, position.z);- cmd.index_offset = iOff;- cmd.index_count = 6;- cmd.vertex_byte_offset = vOff;- cmd.shader_id = shape_shader_id_;- cmd.blend_mode = BlendMode::Normal;- cmd.layout_id = LayoutId::Shape;- cmd.texture_count = 0;- cmd.entity = entity;- cmd.type = RenderType::Shape;- cmd.layer = shape.layer;-- clips.applyTo(entity, cmd);-- draw_list.push(cmd);+ BatchDrawKey key{+ .stage = ctx.current_stage,+ .layer = shape.layer,+ .shaderId = shape_shader_id_,+ .blend = BlendMode::Normal,+ .depth = position.z,+ .entity = entity,+ .type = RenderType::Shape,+ .layoutId = LayoutId::Shape,+ };+ appendIndexedDraw(buffers, draw_list, clips, verts, 4, BATCH_QUAD_INDICES, 6, key);}}diff --git a/src/esengine/renderer/plugins/ShapePlugin.hpp b/src/esengine/renderer/plugins/ShapePlugin.hppindex 4d6f9bb19..47b9c0bf3 100644--- a/src/esengine/renderer/plugins/ShapePlugin.hpp+++ b/src/esengine/renderer/plugins/ShapePlugin.hpp@@ -23,8 +23,6 @@ private:f32 shapeType, halfW, halfH, cornerRadius;};- static constexpr u32 QUAD_INDICES[6] = { 0, 1, 2, 2, 3, 0 };-resource::ShaderHandle shape_shader_handle_;u32 shape_shader_id_ = 0;};diff --git a/src/esengine/renderer/plugins/SpritePlugin.cpp b/src/esengine/renderer/plugins/SpritePlugin.cppindex 5fc7622f6..306b59199 100644--- a/src/esengine/renderer/plugins/SpritePlugin.cpp+++ b/src/esengine/renderer/plugins/SpritePlugin.cpp@@ -22,15 +22,6 @@ void SpritePlugin::collect(RenderCollectContext& collect_ctx) {auto& ctx = collect_ctx.frame_context;auto spriteView = registry.view<ecs::Transform, ecs::Sprite>();- // Camera center in world space (from the inverse view-projection), for parallax —- // the same derivation TilemapRenderPlugin uses, so sprite and tilemap parallax- // scroll consistently. Computed once per collect, not per sprite.- glm::mat4 invVP = glm::inverse(ctx.view_projection);- glm::vec4 camBL = invVP * glm::vec4(-1.0f, -1.0f, 0.0f, 1.0f);- glm::vec4 camTR = invVP * glm::vec4( 1.0f, 1.0f, 0.0f, 1.0f);- const f32 camCenterX = (camBL.x / camBL.w + camTR.x / camTR.w) * 0.5f;- const f32 camCenterY = (camBL.y / camBL.w + camTR.y / camTR.w) * 0.5f;-u32 litProgram = 0;for (auto entity : spriteView) {@@ -39,12 +30,7 @@ void SpritePlugin::collect(RenderCollectContext& collect_ctx) {if (registry.has<ecs::UINode>(entity)) continue; // UI sprites are drawn by UIElementPluginauto& transform = spriteView.get<ecs::Transform>(entity);- transform.ensureDecomposed();- glm::vec3 position = transform.worldPosition;- // Parallax: shift toward the camera by (1 - factor); factor 1 = no shift. Applied- // before the frustum cull so a parallaxed sprite is culled at where it's drawn.- position.x += camCenterX * (1.0f - sprite.parallax.x);- position.y += camCenterY * (1.0f - sprite.parallax.y);+ glm::vec3 position = parallaxedWorldPosition(transform, sprite.parallax, collect_ctx.camera);const auto& rotation = transform.worldRotation;const auto& scale = transform.worldScale;diff --git a/src/esengine/renderer/plugins/TextPlugin.cpp b/src/esengine/renderer/plugins/TextPlugin.cppindex 045ac3073..bfe5c083f 100644--- a/src/esengine/renderer/plugins/TextPlugin.cpp+++ b/src/esengine/renderer/plugins/TextPlugin.cpp@@ -50,15 +50,6 @@ void TextPlugin::collect(RenderCollectContext& collect_ctx) {auto& ctx = collect_ctx.frame_context;auto textView = registry.view<ecs::Transform, ecs::BitmapText>();- // Camera center in world space (from the inverse view-projection), for parallax —- // the same derivation SpritePlugin/TilemapRenderPlugin use, so every renderable's- // parallax scrolls consistently. Computed once per collect.- glm::mat4 invVP = glm::inverse(ctx.view_projection);- glm::vec4 camBL = invVP * glm::vec4(-1.0f, -1.0f, 0.0f, 1.0f);- glm::vec4 camTR = invVP * glm::vec4( 1.0f, 1.0f, 0.0f, 1.0f);- const f32 camCenterX = (camBL.x / camBL.w + camTR.x / camTR.w) * 0.5f;- const f32 camCenterY = (camBL.y / camBL.w + camTR.y / camTR.w) * 0.5f;-for (auto entity : textView) {const auto& bt = textView.get<ecs::BitmapText>(entity);if (!bt.enabled) continue;@@ -71,12 +62,7 @@ void TextPlugin::collect(RenderCollectContext& collect_ctx) {if (!tex) continue;auto& transform = textView.get<ecs::Transform>(entity);- transform.ensureDecomposed();- glm::vec3 position = transform.worldPosition;- // Parallax: shift toward the camera by (1 - factor); factor 1 = no shift.- // Applied before the frustum cull so parallaxed text is culled where drawn.- position.x += camCenterX * (1.0f - bt.parallax.x);- position.y += camCenterY * (1.0f - bt.parallax.y);+ glm::vec3 position = parallaxedWorldPosition(transform, bt.parallax, collect_ctx.camera);const auto& scale = transform.worldScale;auto textMetrics = font->measureText(bt.text, bt.fontSize, bt.spacing);diff --git a/src/esengine/renderer/plugins/TilemapRenderPlugin.cpp b/src/esengine/renderer/plugins/TilemapRenderPlugin.cppindex 75ef8239c..61bd40a4e 100644--- a/src/esengine/renderer/plugins/TilemapRenderPlugin.cpp+++ b/src/esengine/renderer/plugins/TilemapRenderPlugin.cpp@@ -150,13 +150,7 @@ void TilemapRenderPlugin::collect(RenderCollectContext& collect_ctx) {const auto& layers = tilemap_system_->allLayers();if (layers.empty()) return;- glm::mat4 invVP = glm::inverse(ctx.view_projection);- glm::vec4 bl = invVP * glm::vec4(-1.0f, -1.0f, 0.0f, 1.0f);- glm::vec4 tr = invVP * glm::vec4( 1.0f, 1.0f, 0.0f, 1.0f);- f32 camLeft = bl.x / bl.w;- f32 camBottom = bl.y / bl.w;- f32 camRight = tr.x / tr.w;- f32 camTop = tr.y / tr.w;+ const CameraWorldRect& cam = collect_ctx.camera;for (const auto& [entity, layer] : layers) {// The TilemapLayer component is the single source of a layer's visual@@ -235,10 +229,8 @@ void TilemapRenderPlugin::collect(RenderCollectContext& collect_ctx) {glm::vec4 finalColor(tint.r, tint.g, tint.b, tint.a * opacity);u32 packedColor = packColor(finalColor);- f32 camCenterX = (camLeft + camRight) * 0.5f;- f32 camCenterY = (camBottom + camTop) * 0.5f;- f32 parallaxOffsetX = camCenterX * (1.0f - parallax.x);- f32 parallaxOffsetY = camCenterY * (1.0f - parallax.y);+ f32 parallaxOffsetX = cam.center.x * (1.0f - parallax.x);+ f32 parallaxOffsetY = cam.center.y * (1.0f - parallax.y);f32 adjOriginX = originX + parallaxOffsetX;f32 adjOriginY = originY + parallaxOffsetY;@@ -246,10 +238,10 @@ void TilemapRenderPlugin::collect(RenderCollectContext& collect_ctx) {f32 chunkWorldW = static_cast<f32>(chunkSize) * layer.tile_width;f32 chunkWorldH = static_cast<f32>(chunkSize) * layer.tile_height;- i32 minCX = static_cast<i32>(std::floor((camLeft - adjOriginX) / chunkWorldW));- i32 minCY = static_cast<i32>(std::floor((adjOriginY - camTop) / chunkWorldH));- i32 maxCX = static_cast<i32>(std::ceil((camRight - adjOriginX) / chunkWorldW));- i32 maxCY = static_cast<i32>(std::ceil((adjOriginY - camBottom) / chunkWorldH));+ i32 minCX = static_cast<i32>(std::floor((cam.left - adjOriginX) / chunkWorldW));+ i32 minCY = static_cast<i32>(std::floor((adjOriginY - cam.top) / chunkWorldH));+ i32 maxCX = static_cast<i32>(std::ceil((cam.right - adjOriginX) / chunkWorldW));+ i32 maxCY = static_cast<i32>(std::ceil((adjOriginY - cam.bottom) / chunkWorldH));if (!layer.infinite) {i32 chunksX = static_cast<i32>((layer.width + tilemap::CHUNK_SIZE - 1) / tilemap::CHUNK_SIZE);diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txtindex fd8eaaf10..2c1928361 100644--- a/tests/CMakeLists.txt+++ b/tests/CMakeLists.txt@@ -111,6 +111,25 @@ add_executable(test_buffer_devicetarget_include_directories(test_buffer_device PRIVATE ${CMAKE_SOURCE_DIR}/src)add_test(NAME test_buffer_device COMMAND test_buffer_device)+# Unified submission face (render-pipeline unification): BatchBuilder is the single+# DrawCommand producer for every stream. Compiles BatchBuilder/DrawList/+# TransientBufferPool against the MockGfxDevice and asserts per-stream baseVertex+# math, texture-slot rules, instanced assembly, merge behavior, and execute() dispatch.+add_executable(test_batch_builder+ renderer/test_batch_builder.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/BatchBuilder.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/DrawList.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/TransientBufferPool.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/MaterialStore.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/FrameCapture.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp+)+target_include_directories(test_batch_builder PRIVATE+ ${CMAKE_SOURCE_DIR}/src+ ${CMAKE_SOURCE_DIR}/third_party/glm+)+add_test(NAME test_batch_builder COMMAND test_batch_builder)+# GfxDevice compressed-texture entry (RC6-A). Header-only: drives MockGfxDevice to# assert the compressed upload + capability-gated RGBA8 fallback. No GL, no emsdk.add_executable(test_compressed_formatdiff --git a/tests/renderer/MockGfxDevice.hpp b/tests/renderer/MockGfxDevice.hppindex c83e9ae07..7e5ebd8f2 100644--- a/tests/renderer/MockGfxDevice.hpp+++ b/tests/renderer/MockGfxDevice.hpp@@ -42,6 +42,8 @@ struct MockGfxDevice final : GfxDevice {int setVertexBufferCalls = 0;int setIndexBufferCalls = 0;int setPipelineCalls = 0;+ int drawElementsCalls = 0;+ int drawElementsInstancedCalls = 0;u32 nextTextureId = 100;u32 nextBufferId = 200;@@ -70,6 +72,9 @@ struct MockGfxDevice final : GfxDevice {GfxCompressedFormat lastCompressedFormat = GfxCompressedFormat::ETC2_RGBA8;u32 lastCompressedByteLength = 0;FramebufferDesc lastFramebufferDesc{};+ u32 lastDrawIndexCount = 0;+ u32 lastDrawIndexByteOffset = 0;+ u32 lastDrawInstanceCount = 0;void init() override {}void shutdown() override {}@@ -164,9 +169,17 @@ struct MockGfxDevice final : GfxDevice {void setStencilReference(i32) override {}void invalidatePipelineCache() override {}- void drawElements(u32, GfxDataType, u32) override {}+ void drawElements(u32 indexCount, GfxDataType, u32 byteOffset) override {+ ++drawElementsCalls;+ lastDrawIndexCount = indexCount;+ lastDrawIndexByteOffset = byteOffset;+ }void drawArrays(u32, u32) override {}- void drawElementsInstanced(u32, GfxDataType, u32, u32) override {}+ void drawElementsInstanced(u32 indexCount, GfxDataType, u32, u32 instanceCount) override {+ ++drawElementsInstancedCalls;+ lastDrawIndexCount = indexCount;+ lastDrawInstanceCount = instanceCount;+ }FramebufferHandle createFramebuffer(const FramebufferDesc& desc) override {++createFramebufferCalls;diff --git a/tests/renderer/test_batch_builder.cpp b/tests/renderer/test_batch_builder.cppnew file mode 100644index 000000000..7b7ad4e66--- /dev/null+++ b/tests/renderer/test_batch_builder.cpp@@ -0,0 +1,214 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+// Unified submission face: BatchBuilder is the ONLY DrawCommand producer, and every+// stream (Batch quads, shape vertices, particle instances) routes through it. Drives+// pushBatchDraw / appendIndexedDraw / appendQuad against a real TransientBufferPool ++// DrawList over the MockGfxDevice and asserts the per-stream baseVertex math, the+// texture-slot rules, instanced command assembly, sort/merge behavior, clip stamping,+// and execute() dispatch — the invariants the per-plugin hand-rolled paths used to own.+#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN+#include <doctest.h>++#include "MockGfxDevice.hpp"+#include "esengine/renderer/BatchBuilder.hpp"+#include "esengine/renderer/DrawList.hpp"+#include "esengine/renderer/MaterialStore.hpp"+#include "esengine/renderer/TransientBufferPool.hpp"++using namespace esengine;++namespace {++struct Harness {+ MockGfxDevice device;+ TransientBufferPool pool{device};+ DrawList list;+ ClipState clips;++ Harness() {+ pool.init(64 * 1024, 16 * 1024);+ pool.beginFrame();+ }+ ~Harness() { pool.shutdown(); }+};++BatchDrawKey quadKey(u32 textureId, i32 layer = 0) {+ BatchDrawKey key{};+ key.stage = RenderStage::Transparent;+ key.layer = layer;+ key.shaderId = 7;+ key.blend = BlendMode::Normal;+ key.textureId = textureId;+ key.type = RenderType::Sprite;+ return key;+}++// The 48-byte record the Shape stream is laid out for (mirrors ShapePlugin's format).+struct TestShapeVertex {+ f32 px, py, ux, uy;+ f32 cr, cg, cb, ca;+ f32 shapeType, halfW, halfH, cornerRadius;+};+static_assert(sizeof(TestShapeVertex) == 48, "shape record must match the Shape stream stride");++} // namespace++TEST_CASE("pool reports each stream's vertex stride (single source for baseVertex math)") {+ Harness h;+ CHECK(h.pool.vertexStride(LayoutId::Batch) == sizeof(BatchVertex));+ CHECK(h.pool.vertexStride(LayoutId::Shape) == sizeof(TestShapeVertex));+ CHECK(h.pool.vertexStride(LayoutId::ParticleInstance) == 40); // per-instance slot+}++TEST_CASE("appendQuad: Batch command with baseVertex-offset indices and one texture slot") {+ Harness h;+ BatchVertex quad[4] = {+ { {0, 0}, 0xFFFFFFFFu, {0, 0} },+ { {1, 0}, 0xFFFFFFFFu, {1, 0} },+ { {1, 1}, 0xFFFFFFFFu, {1, 1} },+ { {0, 1}, 0xFFFFFFFFu, {0, 1} },+ };+ appendQuad(h.pool, h.list, h.clips, quad, quadKey(42));+ appendQuad(h.pool, h.list, h.clips, quad, quadKey(42));++ REQUIRE(h.list.commandCount() == 2);+ const DrawCommand& first = h.list.command(0);+ const DrawCommand& second = h.list.command(1);+ CHECK(first.layout_id == LayoutId::Batch);+ CHECK(first.index_count == 6);+ CHECK(first.vertex_count == 4);+ CHECK(first.texture_count == 1);+ CHECK(first.texture_ids[0] == 42);+ CHECK(first.instance_count == 0);+ // Second quad's vertices start at record 4, so its indices must be rebased there.+ CHECK(second.vertex_byte_offset == 4 * sizeof(BatchVertex));+ CHECK(second.index_offset == 6);+}++TEST_CASE("appendIndexedDraw: non-Batch stream uses its own stride for baseVertex") {+ Harness h;+ TestShapeVertex verts[4] = {};+ BatchDrawKey key = quadKey(0);+ key.type = RenderType::Shape;+ key.layoutId = LayoutId::Shape;++ appendIndexedDraw(h.pool, h.list, h.clips, verts, 4, BATCH_QUAD_INDICES, 6, key);+ appendIndexedDraw(h.pool, h.list, h.clips, verts, 4, BATCH_QUAD_INDICES, 6, key);++ REQUIRE(h.list.commandCount() == 2);+ CHECK(h.list.command(0).layout_id == LayoutId::Shape);+ // A textureless non-Batch draw must not claim a sampler slot (execute() binds+ // only texture_count units for non-Batch layouts).+ CHECK(h.list.command(0).texture_count == 0);+ CHECK(h.list.command(1).vertex_byte_offset == 4 * sizeof(TestShapeVertex));+ // Indices rebased by the SHAPE stride (4 records), not the Batch stride.+ CHECK(h.list.command(1).index_offset == 6);+ CHECK(h.pool.vertexBytesUsed(LayoutId::Shape) == 8 * sizeof(TestShapeVertex));+ CHECK(h.pool.indicesUsed(LayoutId::Shape) == 12);+}++TEST_CASE("pushBatchDraw: instanced key assembles an instanced command over static indices") {+ Harness h;+ u32 instOffset = h.pool.allocVertices(LayoutId::ParticleInstance, 3 * 40);+ BatchDrawKey key = quadKey(42); // type tag irrelevant here (stats/capture only)+ key.layoutId = LayoutId::ParticleInstance;+ key.instanceCount = 3;++ pushBatchDraw(h.list, h.clips, instOffset, 0, 0, 6, key);++ REQUIRE(h.list.commandCount() == 1);+ const DrawCommand& cmd = h.list.command(0);+ CHECK(cmd.layout_id == LayoutId::ParticleInstance);+ CHECK(cmd.instance_count == 3);+ CHECK(cmd.index_offset == 0);+ CHECK(cmd.index_count == 6);+ CHECK(cmd.texture_count == 1);+ CHECK(cmd.texture_ids[0] == 42);+}++TEST_CASE("finalize: adjacent same-key Batch draws with different textures merge multi-texture") {+ Harness h;+ BatchVertex quad[4] = {+ { {0, 0}, 0xFFFFFFFFu, {0, 0} },+ { {1, 0}, 0xFFFFFFFFu, {1, 0} },+ { {1, 1}, 0xFFFFFFFFu, {1, 1} },+ { {0, 1}, 0xFFFFFFFFu, {0, 1} },+ };+ appendQuad(h.pool, h.list, h.clips, quad, quadKey(42));+ appendQuad(h.pool, h.list, h.clips, quad, quadKey(43));++ h.list.finalize(h.pool);++ REQUIRE(h.list.mergedDrawCallCount() == 1);+ const DrawCommand& merged = h.list.command(0);+ CHECK(merged.index_count == 12);+ CHECK(merged.texture_count == 2);+ CHECK(merged.texture_ids[0] == 42);+ CHECK(merged.texture_ids[1] == 43);+ // The second quad's staged vertices got their sampler slot stamped to 1.+ const auto* verts = reinterpret_cast<const BatchVertex*>(h.pool.vertexData(LayoutId::Batch));+ CHECK(verts[3].texIndex == 0.0f);+ CHECK(verts[4].texIndex == 1.0f);+ CHECK(verts[7].texIndex == 1.0f);+}++TEST_CASE("finalize: different streams never coalesce; instanced draws stay one per emitter") {+ Harness h;+ BatchVertex quad[4] = {};+ appendQuad(h.pool, h.list, h.clips, quad, quadKey(42));++ TestShapeVertex sverts[4] = {};+ BatchDrawKey shapeKey = quadKey(0);+ shapeKey.layoutId = LayoutId::Shape;+ appendIndexedDraw(h.pool, h.list, h.clips, sverts, 4, BATCH_QUAD_INDICES, 6, shapeKey);++ BatchDrawKey inst = quadKey(42);+ inst.layoutId = LayoutId::ParticleInstance;+ inst.instanceCount = 2;+ pushBatchDraw(h.list, h.clips, 0, 0, 0, 6, inst);+ pushBatchDraw(h.list, h.clips, 80, 0, 0, 6, inst);++ h.list.finalize(h.pool);+ // Batch quad + shape + two instanced draws: nothing merges across these.+ CHECK(h.list.mergedDrawCallCount() == 4);+}++TEST_CASE("clip state is stamped onto commands from every stream") {+ Harness h;+ Entity clipped{5};+ h.clips.setScissor(clipped.id(), 1, 2, 3, 4);++ TestShapeVertex sverts[4] = {};+ BatchDrawKey key = quadKey(0);+ key.layoutId = LayoutId::Shape;+ key.entity = clipped;+ appendIndexedDraw(h.pool, h.list, h.clips, sverts, 4, BATCH_QUAD_INDICES, 6, key);++ REQUIRE(h.list.commandCount() == 1);+ const DrawCommand& cmd = h.list.command(0);+ CHECK((cmd.state_flags & CMD_STATE_SCISSOR) != 0);+ CHECK(cmd.scissor.x == 1);+ CHECK(cmd.scissor.h == 4);+}++TEST_CASE("execute: indexed and instanced commands dispatch through the device") {+ Harness h;+ MaterialStore materials;++ BatchVertex quad[4] = {};+ appendQuad(h.pool, h.list, h.clips, quad, quadKey(42));++ BatchDrawKey inst = quadKey(42);+ inst.layoutId = LayoutId::ParticleInstance;+ inst.instanceCount = 5;+ pushBatchDraw(h.list, h.clips, 0, 0, 0, 6, inst);++ h.list.finalize(h.pool);+ h.pool.upload();+ h.list.execute(h.device, h.pool, materials);++ CHECK(h.device.drawElementsCalls == 1);+ CHECK(h.device.drawElementsInstancedCalls == 1);+ CHECK(h.device.lastDrawInstanceCount == 5);+ CHECK(h.device.setPipelineCalls == 2);+}diff --git a/tools/check-draw-command-boundary.mjs b/tools/check-draw-command-boundary.mjsnew file mode 100644index 000000000..8cb263262--- /dev/null+++ b/tools/check-draw-command-boundary.mjs@@ -0,0 +1,66 @@+#!/usr/bin/env node+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+// =============================================================================+// Render-command boundary guard+//+// Enforces the unified-pipeline invariant: DrawCommand assembly and DrawList+// submission may appear ONLY in the single submission face+// (renderer/BatchBuilder.cpp). Every renderer — plugin or direct submit —+// describes its draw as a BatchDrawKey + geometry and produces the command+// through that face; sort/merge/submit stay unified in DrawList.+//+// Run: node tools/check-draw-command-boundary.mjs (exit 1 on violation)+// =============================================================================++import { readdirSync, readFileSync, statSync } from 'node:fs';+import { join } from 'node:path';++const ROOT = 'src/esengine';++// The one translation unit allowed to build + push DrawCommands.+const ALLOWED = new Set([+ 'src/esengine/renderer/BatchBuilder.cpp',+]);++// A DrawCommand local/member being assembled (`DrawCommand cmd{...}`, `= DrawCommand{...}`),+// and a command being pushed into the queue. References/params (`const DrawCommand&`) and+// the struct definition itself don't match.+const PATTERNS = [+ [/\bDrawCommand\s+\w+\s*[{;=]/, 'DrawCommand assembly'],+ [/\bdraw_?[lL]ist_?\s*\.\s*push\s*\(/, 'DrawList push'],+];++const SOURCE_EXT = /\.(cpp|cc|cxx|hpp|hxx|h)$/;++function walk(dir, out = []) {+ for (const entry of readdirSync(dir)) {+ const p = join(dir, entry);+ if (statSync(p).isDirectory()) walk(p, out);+ else if (SOURCE_EXT.test(entry)) out.push(p);+ }+ return out;+}++const violations = [];+for (const file of walk(ROOT)) {+ const rel = file.replace(/\\/g, '/');+ if (ALLOWED.has(rel)) continue;+ const lines = readFileSync(file, 'utf8').split('\n');+ lines.forEach((line, i) => {+ for (const [pattern, what] of PATTERNS) {+ if (pattern.test(line)) {+ violations.push(` ${rel}:${i + 1}: [${what}] ${line.trim()}`);+ }+ }+ });+}++if (violations.length > 0) {+ console.error('Render-command boundary violation — DrawCommands are built only by BatchBuilder:\n');+ console.error(violations.join('\n'));+ console.error(`\n${violations.length} violation(s). Submit through pushBatchDraw / appendIndexedDraw (renderer/BatchBuilder.hpp).`);+ process.exit(1);+}++console.log('Render-command boundary OK: DrawCommand assembly only in BatchBuilder.cpp.');