Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(webgpu): offscreen targets + region-scoped clear emulation (WGSL phase 2 slice 4)

yhhcb1a08adac6a
diff --git a/desktop/scripts/webgpu-bringup.mjs b/desktop/scripts/webgpu-bringup.mjs
index 0608b5213..120c67169 100644
--- a/desktop/scripts/webgpu-bringup.mjs
+++ b/desktop/scripts/webgpu-bringup.mjs
@@ -105,13 +105,15 @@ app.whenReady().then(async () => {
const right = px(192, 166); // batch twin: quad sampling slot 1 → green
const corner = px(8, 128); // between the quads' outside → dark blue clear
+ const scopedClear = px(128, 128); // pass C: region-scoped clear emulation → yellow
const circleOk = near(circle.r, 255) && near(circle.g, 0) && near(circle.b, 255);
+ const scopedOk = near(scopedClear.r, 255) && near(scopedClear.g, 255) && near(scopedClear.b, 0);
const leftOk = near(left.r, 255) && near(left.g, 0) && near(left.b, 0);
const rightOk = near(right.r, 0) && near(right.g, 255) && near(right.b, 0);
const cornerOk = near(corner.r, 13) && near(corner.g, 13) && near(corner.b, 77, 60);
- const ok = framesOk && errors.length === 0 && circleOk && leftOk && rightOk && cornerOk;
+ const ok = framesOk && errors.length === 0 && circleOk && leftOk && rightOk && cornerOk && scopedOk;
- console.log(`RESULT circle=${JSON.stringify(circle)} left=${JSON.stringify(left)} right=${JSON.stringify(right)} corner=${JSON.stringify(corner)} framesOk=${framesOk} errors=${errors.length}`);
+ console.log(`RESULT circle=${JSON.stringify(circle)} left=${JSON.stringify(left)} right=${JSON.stringify(right)} scoped=${JSON.stringify(scopedClear)} corner=${JSON.stringify(corner)} framesOk=${framesOk} errors=${errors.length}`);
console.log(`\n[webgpu-bringup] ${ok ? 'PASS' : 'FAIL'}`);
process.exitCode = ok ? 0 : 1;
try { server.close(); } catch { /* ignore */ }
diff --git a/docs/REARCHITECTURE.md b/docs/REARCHITECTURE.md
index 04ca76b95..e97f5b326 100644
--- a/docs/REARCHITECTURE.md
+++ b/docs/REARCHITECTURE.md
@@ -184,12 +184,13 @@ TS 驱动的主 pass clear 退出边界,`clear` 家族退出公共 RHI:
- **方法论教训(已入记忆)**:排查期间多次实验跑在陈旧 wasm 上导致结论互相矛盾;现在的协议是每轮 bisect 在源里嵌标记字符串、grep 部署产物 + 比对双份 md5 后才采信结果。
- 验证(全部本地、BelowNormal):13 个 headless 场景全 PASS(含 postprocess-effects/lut-grade 两个后处理场景、mesh2d、ui-mask、lit×2);6 套 MockGfxDevice harness、SDK 241 测试文件(renderer/renderPipeline 测试更新为 load-op 契约)、desktop 63 文件、双侧 tsc、24 examples 全绿。**WebGPU 前仅剩一片**:GLSL-only `createProgram` → WGSL 通路。
-### WGSL/WebGPU 通路 — 🟡 进行中:Phase 2 切片 1/2/3 已落地——**首帧点亮 + 批多纹理工作**(2026-07-07)
+### WGSL/WebGPU 通路 — 🟡 进行中:Phase 2 切片 1-4 已落地——**首帧点亮、批多纹理、离屏与区域 clear 全部工作**(2026-07-07)
见 `REARCH_WGSL.md`(本地 gitignore,同 RC6/2D_PARITY 约定):着色器版图盘点(uniform 数据已全后端中立,剩程序文本)、岔路拍板(有限集人工孪生 / 图材质 AST 双发射 / 用户材质 cook 期转换——拒绝运行时翻译器的 MB 级体积代价)、四期计划(源语言接缝 → WebGPUDevice 原型 → 双语发射 → cook 期用户材质)。**Phase 0 已落地**:最后 3 个 GLSL ES 1.00 残留(SDK outline/drop-shadow/color-matrix 滤镜)重写为 fragment-only `.esshader` 反射路径——顺带修复其设计性破损(raw 形态无 `u_projection` 来源、无属性绑定、mat4 超 `setMaterialUniform` 的 vec4 上限**从未能传入**;色彩矩阵改为 4×vec4 行 + 偏移列,新增 `Filters.colorMatrixUniforms` 助手)。全仓每个程序自此都在现代缝上(300 es + UBO 反射)。
**Phase 1(源语言接缝)已落地**:RHI 补上最后一块后端中立拼图——`createProgram` 收语言标签的 `GfxShaderSource`,新增 `supportsShaderLanguage` 能力查询(GL = 仅 GLSL ES 300;`Shader::compile` 在任何 GPU 调用前对不支持的语言快速失败);语言贯穿 Shader/ResourceManager(DrawParams 重写仅对 GLSL 生效);`ShaderParser::assembleStage` 获得 `ShaderTargetLanguage` 参数(WGSL 发射 = Phase 3)。MockGfxDevice 新增 `wgslSupported` 开关 + 语言门用例;行为零变化(8 harness + 场景抽样等价)。
**Phase 2 切片 1(WebGPU 后端启动)已落地**:emdawnwebgpu 端口(Dawn)集成为测试目标独立依赖(主构建零影响);`renderer/webgpu/` 新增纯映射层(GfxEnums→WGPU 全翻译,blend/模板表镜像 GLDevice 语义,load-op 规则与 RenderPassDesc 契约一致)+ 空设备安全的 `WebGPUDevice` 骨架(缓冲/纹理/WGSL 模块真实现,布局/管线描述符保留待惰性构建,pass/draw 为切片 2 结构化桩);`test_webgpu_device` 用真 Dawn 头编译验证全部描述符拼写,入 CI。
**Phase 2 切片 2(首帧点亮)**:WebGPUDevice 长出真渲染路径——canvas 表面(页面 JS 异步取 GPUDevice 经 `Module.preinitializedWebGPUDevice` 交接,wasm 全同步零 Asyncify)、帧编码器(load-op 直译 RenderPassDesc)、惰性 pipeline(映射层直译 + 描述符去重)、group-0 UBO bind group、索引/实例化 draw。bring-up:electron 驱动 `webgpu_bringup.wasm` 用引擎同款 RHI 调用序列渲染 **shape.esshader 的 WGSL 孪生**——首次运行即像素级 PASS(SDF 红圆 + 清屏色逐像素命中,零校验错误)。本地命令:`node desktop/scripts/webgpu-bringup.mjs`(CI 暂不跑真 GPU bring-up;null-device 套件在 CI)。
**Phase 2 切片 3(纹理组)**:group-1 约定(8×`texture_2d` binding 0..7 + 共享 sampler binding 8 = `u_textures[8]` 的 WGSL 拼写;未用槽重复 slot-0 视图同 WebGL2 规则;group 1 仅在 pass 内绑过纹理时设置、每 pass 重置);**batch 默认变体 WGSL 孪生**(`textureSampleLevel` 保 uniform-flow)。bring-up 两幕同 pass(shape + 批双 quad texIndex 选择)再次首跑 PASS——sprite 管线的核心机制(逐顶点采样槽选择)在 WebGPU 上验证通过。
+**Phase 2 切片 4**:offscreen 目标(createFramebuffer→pass 以附件视图为目标)+ **区域 clear 仿真兑现**(内部全屏三角管线 + 区域 scissor,load-op 契约"区域=Load+仿真"自此在两个后端都有真实现)。bring-up 三 pass:离屏清绿→主双幕(右 quad 采样离屏渲染结果 = render-to-texture 验证)→区域黄 clear,五点像素断言全中零校验错误。
### CI 常绿门禁(push-gated invariants)— ✅ 已落地(2026-07-07)
此前 `build.yml` 仅 `workflow_dispatch`——boundary guards、全组件 ABI `static_assert`、各测试套件全是"约定"而非"机制"。现在**每次 push master 自动跑**:① web/playable/wechat 构建(编译期即验证生成断言 + ABI 哈希)+ 全部 15 个 C++ doctest harness(node 下执行);② 双 boundary guard + SDK tsc/构建/vitest + examples 检查 + desktop tsc/vitest(后两者此前完全不在 CI);③ headless 像素验证(sprite/mesh2d/parallax-shape/tilemap-flip/ui-mask,electron + xvfb + SwiftShader,需 `ELECTRON_DISABLE_SANDBOX`)。落地即抓到并修复三处腐化:`test_registry.cpp` 用已删除的 `View::sizeHint`、`test_sparse_set.cpp` 的局部常量撞 emscripten `PAGE_SIZE` 宏、以及一个**真回归**——单组件 `View::each` 活迭代(中途 emplace 会重访、swap-pop 移除会跳漏),多组件版早有快照契约,现已对齐。
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
index af1314384..9ce1510e7 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
@@ -61,6 +61,9 @@ void WebGPUDevice::shutdown() {
pipelines_.clear();
if (bind_group_) { wgpuBindGroupRelease(bind_group_); bind_group_ = nullptr; }
if (texture_group_) { wgpuBindGroupRelease(texture_group_); texture_group_ = nullptr; }
+ if (clear_bind_group_) { wgpuBindGroupRelease(clear_bind_group_); clear_bind_group_ = nullptr; }
+ if (clear_pipeline_) { wgpuRenderPipelineRelease(clear_pipeline_); clear_pipeline_ = nullptr; }
+ framebuffers_.clear();
if (sampler_) { wgpuSamplerRelease(sampler_); sampler_ = nullptr; }
if (surface_) { wgpuSurfaceRelease(surface_); surface_ = nullptr; }
if (instance_) { wgpuInstanceRelease(instance_); instance_ = nullptr; }
@@ -129,7 +132,7 @@ void WebGPUDevice::clearStencil(i32) { stubOnce("clearStencil (stencil-write qua
void WebGPUDevice::setScissorTest(bool enabled) {
// WebGPU's scissor is always on; "disabled" = the full target rectangle.
if (pass_ && !enabled) {
- wgpuRenderPassEncoderSetScissorRect(pass_, 0, 0, surface_width_, surface_height_);
+ wgpuRenderPassEncoderSetScissorRect(pass_, 0, 0, pass_width_, pass_height_);
}
}
@@ -572,6 +575,89 @@ WGPUSampler WebGPUDevice::defaultSampler() {
return sampler_;
}
+void WebGPUDevice::clearQuad(const RenderPassDesc& desc) {
+ if (!pass_ || !device_) return;
+
+ // Lazy internal pipeline: a vertex-index fullscreen triangle, color from a
+ // tiny internal UBO at group 0 binding 0. No vertex buffers, no user state.
+ if (!clear_pipeline_) {
+ static const char* kClearVS = R"(
+@vertex fn vs_main(@builtin(vertex_index) i : u32) -> @builtin(position) vec4f {
+ var p = array<vec2f, 3>(vec2f(-1.0, -3.0), vec2f(3.0, 1.0), vec2f(-1.0, 1.0));
+ return vec4f(p[i], 0.0, 1.0);
+}
+)";
+ static const char* kClearFS = R"(
+struct ClearColor { value : vec4f };
+@group(0) @binding(0) var<uniform> clearColor : ClearColor;
+@fragment fn fs_main() -> @location(0) vec4f { return clearColor.value; }
+)";
+ auto makeModule = [&](const char* code) {
+ WGPUShaderSourceWGSL wgsl{};
+ wgsl.chain.sType = WGPUSType_ShaderSourceWGSL;
+ wgsl.code = sv(code);
+ WGPUShaderModuleDescriptor md{};
+ md.nextInChain = &wgsl.chain;
+ return wgpuDeviceCreateShaderModule(device_, &md);
+ };
+ WGPUShaderModule vs = makeModule(kClearVS);
+ WGPUShaderModule fs = makeModule(kClearFS);
+
+ WGPUColorTargetState target{};
+ target.format = surface_format_;
+ target.writeMask = WGPUColorWriteMask_All;
+
+ WGPUFragmentState fragment{};
+ fragment.module = fs;
+ fragment.entryPoint = sv("fs_main");
+ fragment.targetCount = 1;
+ fragment.targets = &target;
+
+ WGPURenderPipelineDescriptor pd{};
+ pd.vertex.module = vs;
+ pd.vertex.entryPoint = sv("vs_main");
+ pd.primitive.topology = WGPUPrimitiveTopology_TriangleList;
+ pd.primitive.frontFace = WGPUFrontFace_CCW;
+ pd.primitive.cullMode = WGPUCullMode_None;
+ pd.multisample.count = 1;
+ pd.multisample.mask = 0xFFFFFFFFu;
+ pd.fragment = &fragment;
+ clear_pipeline_ = wgpuDeviceCreateRenderPipeline(device_, &pd);
+ wgpuShaderModuleRelease(vs);
+ wgpuShaderModuleRelease(fs);
+
+ clear_color_ubo_ = createBuffer({GfxBufferUsage::Uniform, 16, true}, nullptr);
+
+ auto uboIt = buffers_.find(static_cast<u32>(clear_color_ubo_));
+ WGPUBindGroupEntry entry{};
+ entry.binding = 0;
+ entry.buffer = uboIt->second.buffer;
+ entry.offset = 0;
+ entry.size = 16;
+ WGPUBindGroupDescriptor bgd{};
+ bgd.layout = wgpuRenderPipelineGetBindGroupLayout(clear_pipeline_, 0);
+ bgd.entryCount = 1;
+ bgd.entries = &entry;
+ clear_bind_group_ = wgpuDeviceCreateBindGroup(device_, &bgd);
+ if (bgd.layout) wgpuBindGroupLayoutRelease(bgd.layout);
+ }
+ if (!clear_pipeline_ || !clear_bind_group_) return;
+
+ updateBuffer(clear_color_ubo_, 0, desc.clearColorValue, 16);
+
+ wgpuRenderPassEncoderSetScissorRect(pass_, static_cast<u32>(desc.clearX),
+ static_cast<u32>(desc.clearY), desc.clearW, desc.clearH);
+ wgpuRenderPassEncoderSetPipeline(pass_, clear_pipeline_);
+ wgpuRenderPassEncoderSetBindGroup(pass_, 0, clear_bind_group_, 0, nullptr);
+ wgpuRenderPassEncoderDraw(pass_, 3, 1, 0, 0);
+ wgpuRenderPassEncoderSetScissorRect(pass_, 0, 0, pass_width_, pass_height_);
+
+ // The clear-quad clobbered pipeline/bind-group pass state; force the next
+ // user draw to re-establish everything.
+ current_pipeline_ = 0;
+ bind_group_dirty_ = true;
+}
+
void WebGPUDevice::flushBindGroup() {
if (!bind_group_dirty_ || !pass_ || !device_) return;
@@ -675,55 +761,81 @@ void WebGPUDevice::drawElementsInstanced(u32 indexCount, GfxDataType indexType,
indexByteOffset / indexSize, 0, 0);
}
-FramebufferHandle WebGPUDevice::createFramebuffer(const FramebufferDesc&) {
- stubOnce("createFramebuffer (offscreen targets)");
- return FramebufferHandle::Default;
+FramebufferHandle WebGPUDevice::createFramebuffer(const FramebufferDesc& desc) {
+ FramebufferRec rec{};
+ rec.color0 = static_cast<u32>(desc.color0);
+ rec.depthStencil = static_cast<u32>(desc.depthStencil);
+ if (rec.depthStencil != 0) stubOnce("framebuffer depth/stencil attachment");
+ // Framebuffer ids share the Default==0 namespace with the surface, so they
+ // come from their own counter offset well clear of it.
+ const u32 id = 0x40000000u + next_framebuffer_id_++;
+ framebuffers_[id] = rec;
+ return static_cast<FramebufferHandle>(id);
+}
+
+void WebGPUDevice::deleteFramebuffer(FramebufferHandle framebuffer) {
+ framebuffers_.erase(static_cast<u32>(framebuffer));
}
-void WebGPUDevice::deleteFramebuffer(FramebufferHandle) {}
void WebGPUDevice::beginRenderPass(const RenderPassDesc& desc) {
if (!device_) return;
if (pass_) endRenderPass(); // defensive: a dangling pass would deadlock the queue
+ WGPUTextureView targetView = nullptr;
if (desc.target != FramebufferHandle::Default) {
- stubOnce("beginRenderPass(offscreen target)");
- return;
- }
- if (!surface_) {
- ES_LOG_ERROR("WebGPUDevice::beginRenderPass: no surface configured");
- return;
- }
-
- WGPUSurfaceTexture st{};
- wgpuSurfaceGetCurrentTexture(surface_, &st);
- if (st.status != WGPUSurfaceGetCurrentTextureStatus_SuccessOptimal &&
- st.status != WGPUSurfaceGetCurrentTextureStatus_SuccessSuboptimal) {
- ES_LOG_ERROR("WebGPUDevice::beginRenderPass: surface texture unavailable ({})",
- static_cast<u32>(st.status));
- return;
+ auto fbIt = framebuffers_.find(static_cast<u32>(desc.target));
+ if (fbIt == framebuffers_.end()) {
+ ES_LOG_ERROR("WebGPUDevice::beginRenderPass: unknown framebuffer");
+ return;
+ }
+ auto texIt = textures_.find(fbIt->second.color0);
+ if (texIt == textures_.end()) {
+ ES_LOG_ERROR("WebGPUDevice::beginRenderPass: framebuffer color texture missing");
+ return;
+ }
+ targetView = texIt->second.view;
+ pass_width_ = texIt->second.width;
+ pass_height_ = texIt->second.height;
+ } else {
+ if (!surface_) {
+ ES_LOG_ERROR("WebGPUDevice::beginRenderPass: no surface configured");
+ return;
+ }
+ WGPUSurfaceTexture st{};
+ wgpuSurfaceGetCurrentTexture(surface_, &st);
+ if (st.status != WGPUSurfaceGetCurrentTextureStatus_SuccessOptimal &&
+ st.status != WGPUSurfaceGetCurrentTextureStatus_SuccessSuboptimal) {
+ ES_LOG_ERROR("WebGPUDevice::beginRenderPass: surface texture unavailable ({})",
+ static_cast<u32>(st.status));
+ return;
+ }
+ frame_texture_ = st.texture;
+ frame_view_ = wgpuTextureCreateView(frame_texture_, nullptr);
+ targetView = frame_view_;
+ pass_width_ = surface_width_;
+ pass_height_ = surface_height_;
}
- frame_texture_ = st.texture;
- frame_view_ = wgpuTextureCreateView(frame_texture_, nullptr);
encoder_ = wgpuDeviceCreateCommandEncoder(device_, nullptr);
const bool scoped = desc.clearW != 0;
WGPURenderPassColorAttachment color{};
- color.view = frame_view_;
+ color.view = targetView;
color.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
color.loadOp = toWGPULoadOp(desc.clearColor, scoped);
color.storeOp = WGPUStoreOp_Store;
color.clearValue = toWGPUClearColor(desc);
- if (desc.clearColor && scoped) {
- // Region-scoped clear = load + scissored clear-quad, per the RHI contract.
- stubOnce("region-scoped clear emulation");
- }
WGPURenderPassDescriptor rp{};
rp.colorAttachmentCount = 1;
rp.colorAttachments = &color;
pass_ = wgpuCommandEncoderBeginRenderPass(encoder_, &rp);
bind_group_dirty_ = true;
+
+ // Region-scoped clear = load + scissored clear-quad, per the RHI contract.
+ if (desc.clearColor && scoped) {
+ clearQuad(desc);
+ }
// Each pass starts textureless: group 1 only attaches to pipelines whose
// draws bind textures (the engine rebinds per draw), never to sampler-less
// pipelines from a previous pass's leftovers.
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.hpp b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
index 5357fb500..6ec7d3ff4 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.hpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
@@ -162,6 +162,10 @@ private:
PipelineDesc desc;
WGPURenderPipeline pipeline = nullptr; ///< Lazily built on first setPipeline.
};
+ struct FramebufferRec {
+ u32 color0 = 0; ///< TextureHandle id of the color attachment.
+ u32 depthStencil = 0; ///< TextureHandle id (0 = none; slice 5 wires it).
+ };
/** @brief Logs a not-yet-implemented path once per entry point. */
void stubOnce(const char* what);
@@ -176,6 +180,11 @@ private:
void flushBindGroup();
/** @brief The lazily created shared sampler (linear/clamp bring-up default). */
WGPUSampler defaultSampler();
+ /** @brief Emulates a region-scoped load-op clear: an internal fullscreen
+ * triangle drawn under the region's scissor (a real load-op covers the
+ * whole attachment — exactly the emulation the RenderPassDesc contract
+ * documents for WebGPU). Runs at pass start, before any user state. */
+ void clearQuad(const RenderPassDesc& desc);
/** @brief True while inside beginRenderPass/endRenderPass. */
bool inPass() const { return pass_ != nullptr; }
@@ -189,7 +198,18 @@ private:
u32 surface_width_ = 0;
u32 surface_height_ = 0;
+ // Offscreen targets.
+ std::unordered_map<u32, FramebufferRec> framebuffers_;
+ u32 next_framebuffer_id_ = 1;
+
+ // Internal clear-quad pipeline (region-scoped clear emulation).
+ WGPURenderPipeline clear_pipeline_ = nullptr;
+ WGPUBindGroup clear_bind_group_ = nullptr;
+ BufferHandle clear_color_ubo_{};
+
// Per-pass state.
+ u32 pass_width_ = 0; ///< Current pass target size (scissor-off rectangle).
+ u32 pass_height_ = 0;
WGPUCommandEncoder encoder_ = nullptr;
WGPURenderPassEncoder pass_ = nullptr;
WGPUTexture frame_texture_ = nullptr; ///< Acquired surface texture (released at end).
diff --git a/tests/renderer/webgpu_bringup.cpp b/tests/renderer/webgpu_bringup.cpp
index e12e97fab..806c9acd9 100644
--- a/tests/renderer/webgpu_bringup.cpp
+++ b/tests/renderer/webgpu_bringup.cpp
@@ -6,12 +6,15 @@
* A browser-run program: the host page acquires a GPUDevice (navigator.gpu) and
* hands it over via Module.preinitializedWebGPUDevice; this program then drives
* the REAL WebGPUDevice through the same RHI calls the engine's render path
- * makes. Each frame renders BOTH engine shader twins in one pass — pipeline
- * switch + bind-group rebuild included:
- * - shape twin: a magenta SDF circle, top-center (slice 2)
- * - batch twin (default variant): two quads sharing one draw, selecting
- * different sampler slots per-vertex via texIndex — red left, green right
- * (slice 3: texture views + shared sampler as bind group 1)
+ * makes. Each frame is THREE passes:
+ * A. offscreen: a framebuffer over a small texture, load-op cleared green —
+ * the right quad then SAMPLES this rendered target (slice 4)
+ * B. main: both engine shader twins in one pass — pipeline switch +
+ * bind-group rebuild included (shape circle, slice 2; batch quads with
+ * per-vertex sampler-slot selection, slice 3)
+ * C. region-scoped clear: a second pass on the surface whose RenderPassDesc
+ * carries a clear REGION — the load-op contract's WebGPU emulation
+ * (load + scissored clear-quad) paints a yellow square (slice 4)
* The electron runner (desktop/scripts/webgpu-bringup.mjs) asserts the pixels.
*/
#include "esengine/renderer/webgpu/WebGPUDevice.hpp"
@@ -160,7 +163,8 @@ namespace {
WebGPUDevice* g_device = nullptr;
PipelineHandle g_shapePipeline{}, g_batchPipeline{};
BufferHandle g_shapeVbo{}, g_batchVbo{}, g_ibo6{}, g_ibo12{}, g_ubo{};
-TextureHandle g_texRed{}, g_texGreen{};
+TextureHandle g_texRed{}, g_texOffscreen{};
+FramebufferHandle g_offscreenFb{};
int g_frames = 0;
// Mirrors the engine's Shape stream vertex (stride 48).
@@ -179,6 +183,16 @@ struct BatchVertex {
};
void renderFrame() {
+ // Pass A: offscreen — the load-op clear IS the render (solid green target).
+ RenderPassDesc off{};
+ off.target = g_offscreenFb;
+ off.clearColor = true;
+ off.clearColorValue[1] = 1.0f;
+ off.clearColorValue[3] = 1.0f;
+ g_device->beginRenderPass(off);
+ g_device->endRenderPass();
+
+ // Pass B: the main scene.
RenderPassDesc pass{};
pass.clearColor = true;
pass.clearColorValue[0] = 0.05f;
@@ -199,13 +213,27 @@ void renderFrame() {
g_device->setPipeline(g_batchPipeline);
g_device->setUniformBuffer(0, g_ubo);
g_device->bindTexture(0, g_texRed);
- g_device->bindTexture(1, g_texGreen);
+ g_device->bindTexture(1, g_texOffscreen); // render-to-texture output from pass A
g_device->setVertexBuffer(0, g_batchVbo, 0);
g_device->setIndexBuffer(g_ibo12);
g_device->drawElements(12, GfxDataType::UnsignedShort, 0);
g_device->endRenderPass();
+ // Pass C: a region-scoped clear on the surface — loadOp must LOAD (keeping
+ // the scene) and the emulation clear-quad paints only the region yellow.
+ RenderPassDesc scoped{};
+ scoped.clearColor = true;
+ scoped.clearColorValue[0] = 1.0f;
+ scoped.clearColorValue[1] = 1.0f;
+ scoped.clearColorValue[3] = 1.0f;
+ scoped.clearX = 96;
+ scoped.clearY = 96;
+ scoped.clearW = 64;
+ scoped.clearH = 64;
+ g_device->beginRenderPass(scoped);
+ g_device->endRenderPass();
+
if (++g_frames == 3) {
std::printf("BRINGUP_FRAMES_OK\n");
emscripten_cancel_main_loop();
@@ -272,11 +300,20 @@ int main() {
g_ibo12 = device.createBuffer({GfxBufferUsage::Index, sizeof(batchIdx), false}, batchIdx);
g_texRed = makeSolidTexture(255, 0, 0);
- g_texGreen = makeSolidTexture(0, 255, 0);
- if (g_texRed == TextureHandle::Invalid || g_texGreen == TextureHandle::Invalid) {
+ // The right quad's texture is RENDERED, not uploaded: an offscreen target
+ // cleared green by pass A each frame.
+ TextureDesc offDesc{};
+ offDesc.width = 4;
+ offDesc.height = 4;
+ offDesc.format = GfxPixelFormat::RGBA8;
+ g_texOffscreen = device.createTexture(offDesc, nullptr);
+ if (g_texRed == TextureHandle::Invalid || g_texOffscreen == TextureHandle::Invalid) {
std::printf("BRINGUP_FAIL textures\n");
return 1;
}
+ FramebufferDesc fbDesc{};
+ fbDesc.color0 = g_texOffscreen;
+ g_offscreenFb = device.createFramebuffer(fbDesc);
// --- Programs + layouts + pipelines (the engine's streams, byte for byte).
ShaderHandle shapeProgram = device.createProgram(