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): first pixels — surface, pass encoding, lazy pipelines, bind groups (WGSL phase 2 slice 2)

yhhf90a3205a388
diff --git a/desktop/scripts/webgpu-bringup.mjs b/desktop/scripts/webgpu-bringup.mjs
new file mode 100644
index 000000000..651b85864
--- /dev/null
+++ b/desktop/scripts/webgpu-bringup.mjs
@@ -0,0 +1,115 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file WebGPU bring-up runner (REARCH_WGSL Phase 2 slice 2).
+ *
+ * Drives tests' webgpu_bringup.wasm in a real browser context: the page acquires
+ * a GPUDevice (navigator.gpu), hands it to the wasm via
+ * Module.preinitializedWebGPUDevice, and the program renders a red SDF circle on
+ * a dark blue clear through the real WebGPUDevice. This runner asserts the
+ * pixels and surfaces device validation errors — the first true frame the
+ * WebGPU backend ever produces.
+ *
+ * Run: node desktop/scripts/webgpu-bringup.mjs (electron resolved from desktop/)
+ * Prereq: cmake --build build/wasm/web-tests --target webgpu_bringup
+ */
+import { app, BrowserWindow } from 'electron';
+import http from 'node:http';
+import os from 'node:os';
+import { readFile } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+try {
+ os.setPriority(os.constants.priority.PRIORITY_BELOW_NORMAL);
+} catch { /* not fatal */ }
+
+const BIN = path.resolve(path.dirname(fileURLToPath(import.meta.url)),
+ '..', '..', 'build', 'wasm', 'web-tests', 'bin');
+
+const PAGE = `<!doctype html>
+<html><body style="margin:0">
+<canvas id="canvas" width="256" height="256"></canvas>
+<script>
+(async () => {
+ try {
+ if (!navigator.gpu) { console.error('BRINGUP_FAIL no navigator.gpu'); return; }
+ const adapter = await navigator.gpu.requestAdapter();
+ if (!adapter) { console.error('BRINGUP_FAIL no adapter'); return; }
+ const device = await adapter.requestDevice();
+ device.addEventListener('uncapturederror', (e) => {
+ console.error('BRINGUP_VALIDATION ' + e.error.message);
+ });
+ window.Module = { preinitializedWebGPUDevice: device };
+ const s = document.createElement('script');
+ s.src = '/webgpu_bringup.js';
+ document.body.appendChild(s);
+ } catch (e) {
+ console.error('BRINGUP_FAIL ' + e.message);
+ }
+})();
+</script></body></html>`;
+
+function serve() {
+ const server = http.createServer(async (req, res) => {
+ try {
+ const rel = decodeURIComponent(new URL(req.url, 'http://x').pathname).replace(/^\/+/, '');
+ if (rel === '' || rel === 'index.html') {
+ res.writeHead(200, { 'content-type': 'text/html' }).end(PAGE);
+ return;
+ }
+ const abs = path.join(BIN, rel);
+ if (!abs.startsWith(BIN)) { res.writeHead(403).end(); return; }
+ const bytes = await readFile(abs);
+ const mime = rel.endsWith('.wasm') ? 'application/wasm' : 'text/javascript';
+ res.writeHead(200, { 'content-type': mime }).end(bytes);
+ } catch {
+ res.writeHead(404).end();
+ }
+ });
+ return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server)));
+}
+
+app.whenReady().then(async () => {
+ const server = await serve();
+ const url = `http://127.0.0.1:${server.address().port}/index.html`;
+
+ const win = new BrowserWindow({ show: false, width: 256, height: 256 });
+ let framesOk = false;
+ const errors = [];
+ win.webContents.on('console-message', (...args) => {
+ const msg = args.map((a) => (a && typeof a === 'object' ? a.message ?? '' : String(a))).join(' ');
+ if (/BRINGUP|error|warn/i.test(msg)) console.log('[page]', msg.slice(0, 200));
+ if (msg.includes('BRINGUP_FRAMES_OK')) framesOk = true;
+ if (msg.includes('BRINGUP_FAIL') || msg.includes('BRINGUP_VALIDATION')) errors.push(msg);
+ });
+ await win.loadURL(url);
+
+ // Give adapter/device acquisition + 3 rendered frames a generous window.
+ const deadline = Date.now() + 15000;
+ while (!framesOk && errors.length === 0 && Date.now() < deadline) {
+ await new Promise((r) => setTimeout(r, 250));
+ }
+ // One extra beat so the last frame reaches the compositor before capture.
+ await new Promise((r) => setTimeout(r, 500));
+
+ const image = await win.webContents.capturePage({ x: 0, y: 0, width: 256, height: 256 });
+ const png = image.toBitmap(); // BGRA rows
+ const px = (x, y) => {
+ const i = (y * image.getSize().width + x) * 4;
+ return { b: png[i], g: png[i + 1], r: png[i + 2] };
+ };
+ const center = px(128, 128); // inside the circle → red
+ const corner = px(8, 8); // outside → dark blue clear
+ const near = (v, want, tol = 40) => Math.abs(v - want) <= tol;
+
+ const centerOk = near(center.r, 255) && near(center.g, 0) && near(center.b, 0);
+ const cornerOk = near(corner.r, 13) && near(corner.g, 13) && near(corner.b, 77, 60);
+ const ok = framesOk && errors.length === 0 && centerOk && cornerOk;
+
+ console.log(`RESULT center=${JSON.stringify(center)} 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 */ }
+ app.quit();
+});
diff --git a/docs/REARCHITECTURE.md b/docs/REARCHITECTURE.md
index e2c307d10..b66735471 100644
--- a/docs/REARCHITECTURE.md
+++ b/docs/REARCHITECTURE.md
@@ -184,10 +184,11 @@ 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 0+1 + Phase 2 切片 1 已落地(2026-07-07)
+### WGSL/WebGPU 通路 — 🟡 进行中:Phase 0+1 + Phase 2 切片 1/2 已落地,**首帧点亮**(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)。
### 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 c844fc325..f1fb2d0dd 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
@@ -2,7 +2,9 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file WebGPUDevice.cpp
- * @brief WebGPU backend skeleton (REARCH_WGSL Phase 2, slice 1).
+ * @brief WebGPU backend (REARCH_WGSL Phase 2): resources (slice 1) + live
+ * render path — surface, pass encoding, lazy pipelines, bind groups,
+ * draws (slice 2).
*/
#include "WebGPUDevice.hpp"
#include "WebGPUMappings.hpp"
@@ -25,7 +27,10 @@ WGPUStringView sv(const char* text) {
} // namespace
WebGPUDevice::WebGPUDevice(WGPUDevice device) : device_(device) {
- if (device_) queue_ = wgpuDeviceGetQueue(device_);
+ if (device_) {
+ queue_ = wgpuDeviceGetQueue(device_);
+ instance_ = wgpuCreateInstance(nullptr);
+ }
}
WebGPUDevice::~WebGPUDevice() {
@@ -49,7 +54,52 @@ void WebGPUDevice::shutdown() {
}
programs_.clear();
layouts_.clear();
+ for (auto& [id, rec] : pipelines_) {
+ if (rec.pipeline) wgpuRenderPipelineRelease(rec.pipeline);
+ }
pipelines_.clear();
+ if (bind_group_) { wgpuBindGroupRelease(bind_group_); bind_group_ = nullptr; }
+ if (surface_) { wgpuSurfaceRelease(surface_); surface_ = nullptr; }
+ if (instance_) { wgpuInstanceRelease(instance_); instance_ = nullptr; }
+}
+
+// =============================================================================
+// Surface (bring-up: a canvas is the Default framebuffer)
+// =============================================================================
+
+bool WebGPUDevice::configureSurface(const char* selector, u32 width, u32 height) {
+ if (!device_ || !instance_) {
+ ES_LOG_ERROR("WebGPUDevice::configureSurface: no device/instance");
+ return false;
+ }
+
+ WGPUEmscriptenSurfaceSourceCanvasHTMLSelector canvas{};
+ canvas.chain.sType = WGPUSType_EmscriptenSurfaceSourceCanvasHTMLSelector;
+ canvas.selector = sv(selector);
+
+ WGPUSurfaceDescriptor sd{};
+ sd.nextInChain = &canvas.chain;
+ surface_ = wgpuInstanceCreateSurface(instance_, &sd);
+ if (!surface_) {
+ ES_LOG_ERROR("WebGPUDevice::configureSurface: surface creation failed for '{}'", selector);
+ return false;
+ }
+
+ // The canvas swapchain prefers BGRA on most platforms; RGBA8 is universally
+ // valid for emscripten surfaces and keeps readback simple during bring-up.
+ surface_format_ = WGPUTextureFormat_RGBA8Unorm;
+ WGPUSurfaceConfiguration cfg{};
+ cfg.device = device_;
+ cfg.format = surface_format_;
+ cfg.usage = WGPUTextureUsage_RenderAttachment;
+ cfg.width = width;
+ cfg.height = height;
+ cfg.alphaMode = WGPUCompositeAlphaMode_Opaque;
+ cfg.presentMode = WGPUPresentMode_Fifo;
+ wgpuSurfaceConfigure(surface_, &cfg);
+ surface_width_ = width;
+ surface_height_ = height;
+ return true;
}
void WebGPUDevice::stubOnce(const char* what) {
@@ -64,10 +114,28 @@ void WebGPUDevice::stubOnce(const char* what) {
// Dynamic state (recorded in slice 2's pass encoder)
// =============================================================================
-void WebGPUDevice::setViewport(i32, i32, u32, u32) { stubOnce("setViewport"); }
-void WebGPUDevice::clearStencil(i32) { stubOnce("clearStencil"); }
-void WebGPUDevice::setScissorTest(bool) { stubOnce("setScissorTest"); }
-void WebGPUDevice::setScissor(i32, i32, i32, i32) { stubOnce("setScissor"); }
+void WebGPUDevice::setViewport(i32 x, i32 y, u32 w, u32 h) {
+ if (pass_) {
+ wgpuRenderPassEncoderSetViewport(pass_, static_cast<f32>(x), static_cast<f32>(y),
+ static_cast<f32>(w), static_cast<f32>(h), 0.0f, 1.0f);
+ }
+}
+
+void WebGPUDevice::clearStencil(i32) { stubOnce("clearStencil (stencil-write quad)"); }
+
+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_);
+ }
+}
+
+void WebGPUDevice::setScissor(i32 x, i32 y, i32 w, i32 h) {
+ if (pass_ && w > 0 && h > 0) {
+ wgpuRenderPassEncoderSetScissorRect(pass_, static_cast<u32>(x), static_cast<u32>(y),
+ static_cast<u32>(w), static_cast<u32>(h));
+ }
+}
// =============================================================================
// Buffers
@@ -137,7 +205,14 @@ void WebGPUDevice::resizeBuffer(BufferHandle buffer, u32 sizeBytes, const void*
}
}
-void WebGPUDevice::setUniformBuffer(u32, BufferHandle) { stubOnce("setUniformBuffer (bind groups)"); }
+void WebGPUDevice::setUniformBuffer(u32 slot, BufferHandle buffer) {
+ if (slot >= kUniformSlots) return;
+ const u32 id = static_cast<u32>(buffer);
+ if (uniform_slots_[slot] != id) {
+ uniform_slots_[slot] = id;
+ bind_group_dirty_ = true;
+ }
+}
// =============================================================================
// Vertex layouts (descriptors retained; pipelines consume them at build time)
@@ -163,8 +238,18 @@ void WebGPUDevice::deleteVertexLayout(VertexLayoutHandle layout) {
layouts_.erase(static_cast<u32>(layout));
}
-void WebGPUDevice::setVertexBuffer(u32, BufferHandle, u32) { stubOnce("setVertexBuffer"); }
-void WebGPUDevice::setIndexBuffer(BufferHandle) { stubOnce("setIndexBuffer"); }
+void WebGPUDevice::setVertexBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes) {
+ auto it = buffers_.find(static_cast<u32>(buffer));
+ if (!pass_ || it == buffers_.end()) return;
+ wgpuRenderPassEncoderSetVertexBuffer(pass_, slot, it->second.buffer, offsetBytes,
+ it->second.size - offsetBytes);
+}
+
+void WebGPUDevice::setIndexBuffer(BufferHandle buffer) {
+ // The RHI carries the index TYPE on the draw, not the bind - record the
+ // buffer and bind it at draw time with the draw's format.
+ bound_index_buffer_ = static_cast<u32>(buffer);
+}
const VertexLayoutDesc* WebGPUDevice::layoutDesc(VertexLayoutHandle handle) const {
auto it = layouts_.find(static_cast<u32>(handle));
@@ -173,7 +258,7 @@ const VertexLayoutDesc* WebGPUDevice::layoutDesc(VertexLayoutHandle handle) cons
const PipelineDesc* WebGPUDevice::pipelineDesc(PipelineHandle handle) const {
auto it = pipelines_.find(static_cast<u32>(handle));
- return it != pipelines_.end() ? &it->second : nullptr;
+ return it != pipelines_.end() ? &it->second.desc : nullptr;
}
// =============================================================================
@@ -350,30 +435,247 @@ void WebGPUDevice::uniformBlockBinding(ShaderHandle, u32, u32) {}
// =============================================================================
PipelineHandle WebGPUDevice::createPipeline(const PipelineDesc& desc) {
+ // Dedup on the descriptor like GLDevice's pipeline cache.
+ for (const auto& [id, rec] : pipelines_) {
+ if (rec.desc == desc) return static_cast<PipelineHandle>(id);
+ }
const u32 id = next_id_++;
- pipelines_[id] = desc;
+ pipelines_[id] = PipelineRec{desc, nullptr};
return static_cast<PipelineHandle>(id);
}
-void WebGPUDevice::setPipeline(PipelineHandle) { stubOnce("setPipeline"); }
-void WebGPUDevice::setStencilReference(i32) { stubOnce("setStencilReference"); }
+WGPURenderPipeline WebGPUDevice::ensurePipeline(u32 id) {
+ auto it = pipelines_.find(id);
+ if (it == pipelines_.end() || !device_) return nullptr;
+ if (it->second.pipeline) return it->second.pipeline;
+
+ const PipelineDesc& desc = it->second.desc;
+ auto progIt = programs_.find(static_cast<u32>(desc.program));
+ auto layoutIt = layouts_.find(static_cast<u32>(desc.vertexLayout));
+ if (progIt == programs_.end() || layoutIt == layouts_.end()) {
+ ES_LOG_ERROR("WebGPUDevice::ensurePipeline: missing program or layout");
+ return nullptr;
+ }
+ const VertexLayoutDesc& vl = layoutIt->second;
+
+ // RHI layout (attributes across up to 2 slots) -> per-slot WGPU buffer layouts.
+ WGPUVertexAttribute attrs[MAX_VERTEX_ATTRIBUTES] = {};
+ WGPUVertexBufferLayout slots[MAX_VERTEX_BUFFER_SLOTS] = {};
+ u32 attrCursor = 0;
+ u32 slotCount = 0;
+ for (u32 slot = 0; slot < MAX_VERTEX_BUFFER_SLOTS; ++slot) {
+ const u32 first = attrCursor;
+ for (u32 i = 0; i < vl.attributeCount; ++i) {
+ const auto& a = vl.attributes[i];
+ if (a.bufferSlot != slot) continue;
+ attrs[attrCursor].format = toWGPUVertexFormat(a.components, a.type, a.normalized);
+ attrs[attrCursor].offset = a.offset;
+ attrs[attrCursor].shaderLocation = a.location;
+ ++attrCursor;
+ }
+ if (attrCursor == first) continue;
+ slots[slotCount].stepMode = vl.instanceStep[slot] ? WGPUVertexStepMode_Instance
+ : WGPUVertexStepMode_Vertex;
+ slots[slotCount].arrayStride = vl.strides[slot];
+ slots[slotCount].attributeCount = attrCursor - first;
+ slots[slotCount].attributes = &attrs[first];
+ ++slotCount;
+ }
+
+ const BlendStateWGPU blend = toWGPUBlend(desc.blend);
+ WGPUBlendState blendState{};
+ blendState.color = blend.color;
+ blendState.alpha = blend.alpha;
+
+ WGPUColorTargetState target{};
+ target.format = surface_format_;
+ target.blend = desc.blendEnabled ? &blendState : nullptr;
+ target.writeMask = (desc.stencil == GfxStencilMode::Write) ? WGPUColorWriteMask_None
+ : WGPUColorWriteMask_All;
+
+ WGPUFragmentState fragment{};
+ fragment.module = progIt->second.fragment;
+ fragment.entryPoint = sv("fs_main");
+ fragment.targetCount = 1;
+ fragment.targets = &target;
+
+ WGPURenderPipelineDescriptor pd{};
+ pd.vertex.module = progIt->second.vertex;
+ pd.vertex.entryPoint = sv("vs_main");
+ pd.vertex.bufferCount = slotCount;
+ pd.vertex.buffers = slots;
+ pd.primitive.topology = WGPUPrimitiveTopology_TriangleList;
+ pd.primitive.frontFace = WGPUFrontFace_CCW;
+ pd.primitive.cullMode = toWGPUCullMode(desc.cullEnabled, desc.cullFront);
+ pd.multisample.count = 1;
+ pd.multisample.mask = 0xFFFFFFFFu;
+ pd.fragment = &fragment;
+ // Bring-up passes carry no depth/stencil attachment; the depth/stencil
+ // pipeline states join when the surface gains a depth buffer (slice 3).
+ if (desc.depthTest || desc.stencil != GfxStencilMode::Off) {
+ stubOnce("depth/stencil pipeline state");
+ }
+
+ it->second.pipeline = wgpuDeviceCreateRenderPipeline(device_, &pd);
+ if (!it->second.pipeline) {
+ ES_LOG_ERROR("WebGPUDevice::ensurePipeline: creation failed");
+ }
+ return it->second.pipeline;
+}
+
+void WebGPUDevice::setPipeline(PipelineHandle pipeline) {
+ const u32 id = static_cast<u32>(pipeline);
+ current_pipeline_ = id;
+ if (!pass_) return;
+ if (WGPURenderPipeline p = ensurePipeline(id)) {
+ wgpuRenderPassEncoderSetPipeline(pass_, p);
+ bind_group_dirty_ = true; // group layout may differ across pipelines
+ }
+}
+
+void WebGPUDevice::setStencilReference(i32 reference) {
+ if (pass_) wgpuRenderPassEncoderSetStencilReference(pass_, static_cast<u32>(reference));
+}
+
void WebGPUDevice::invalidatePipelineCache() {}
+void WebGPUDevice::flushBindGroup() {
+ if (!bind_group_dirty_ || !pass_ || !device_) return;
+
+ WGPURenderPipeline p = ensurePipeline(current_pipeline_);
+ if (!p) return;
+
+ // Group 0 = the engine's UBO bindings (0..4). Entries must match the
+ // pipeline's layout exactly, so only slots the shader declares may appear;
+ // bring-up shaders declare exactly the slots the scene sets. Full slot-mask
+ // reflection ships with the WGSL emitter metadata (Phase 3).
+ WGPUBindGroupEntry entries[kUniformSlots];
+ u32 count = 0;
+ for (u32 slot = 0; slot < kUniformSlots; ++slot) {
+ if (uniform_slots_[slot] == 0) continue;
+ auto it = buffers_.find(uniform_slots_[slot]);
+ if (it == buffers_.end()) continue;
+ WGPUBindGroupEntry e{};
+ e.binding = slot;
+ e.buffer = it->second.buffer;
+ e.offset = 0;
+ e.size = it->second.size;
+ entries[count++] = e;
+ }
+
+ if (bind_group_) { wgpuBindGroupRelease(bind_group_); bind_group_ = nullptr; }
+ if (count == 0) { bind_group_dirty_ = false; return; }
+
+ WGPUBindGroupDescriptor bgd{};
+ bgd.layout = wgpuRenderPipelineGetBindGroupLayout(p, 0);
+ bgd.entryCount = count;
+ bgd.entries = entries;
+ bind_group_ = wgpuDeviceCreateBindGroup(device_, &bgd);
+ if (bgd.layout) wgpuBindGroupLayoutRelease(bgd.layout);
+ if (bind_group_) wgpuRenderPassEncoderSetBindGroup(pass_, 0, bind_group_, 0, nullptr);
+ bind_group_dirty_ = false;
+}
+
// =============================================================================
// Draws / passes — slice 2 (per-frame command encoder + surface plumbing)
// =============================================================================
-void WebGPUDevice::drawElements(u32, GfxDataType, u32) { stubOnce("drawElements"); }
-void WebGPUDevice::drawArrays(u32, u32) { stubOnce("drawArrays"); }
-void WebGPUDevice::drawElementsInstanced(u32, GfxDataType, u32, u32) { stubOnce("drawElementsInstanced"); }
+void WebGPUDevice::drawElements(u32 indexCount, GfxDataType indexType, u32 indexByteOffset) {
+ if (!pass_) return;
+ auto it = buffers_.find(bound_index_buffer_);
+ if (it == buffers_.end()) return;
+ flushBindGroup();
+ wgpuRenderPassEncoderSetIndexBuffer(pass_, it->second.buffer, toWGPUIndexFormat(indexType),
+ 0, it->second.size);
+ const u32 indexSize = (indexType == GfxDataType::UnsignedShort) ? 2 : 4;
+ wgpuRenderPassEncoderDrawIndexed(pass_, indexCount, 1, indexByteOffset / indexSize, 0, 0);
+}
+
+void WebGPUDevice::drawArrays(u32 firstVertex, u32 vertexCount) {
+ if (!pass_) return;
+ flushBindGroup();
+ wgpuRenderPassEncoderDraw(pass_, vertexCount, 1, firstVertex, 0);
+}
+
+void WebGPUDevice::drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 indexByteOffset,
+ u32 instanceCount) {
+ if (!pass_) return;
+ auto it = buffers_.find(bound_index_buffer_);
+ if (it == buffers_.end()) return;
+ flushBindGroup();
+ wgpuRenderPassEncoderSetIndexBuffer(pass_, it->second.buffer, toWGPUIndexFormat(indexType),
+ 0, it->second.size);
+ const u32 indexSize = (indexType == GfxDataType::UnsignedShort) ? 2 : 4;
+ wgpuRenderPassEncoderDrawIndexed(pass_, indexCount, instanceCount,
+ indexByteOffset / indexSize, 0, 0);
+}
FramebufferHandle WebGPUDevice::createFramebuffer(const FramebufferDesc&) {
- stubOnce("createFramebuffer");
+ stubOnce("createFramebuffer (offscreen targets)");
return FramebufferHandle::Default;
}
void WebGPUDevice::deleteFramebuffer(FramebufferHandle) {}
-void WebGPUDevice::beginRenderPass(const RenderPassDesc&) { stubOnce("beginRenderPass"); }
-void WebGPUDevice::endRenderPass() { stubOnce("endRenderPass"); }
+
+void WebGPUDevice::beginRenderPass(const RenderPassDesc& desc) {
+ if (!device_) return;
+ if (pass_) endRenderPass(); // defensive: a dangling pass would deadlock the queue
+
+ 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;
+ }
+ 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.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;
+}
+
+void WebGPUDevice::endRenderPass() {
+ if (!pass_) return;
+ wgpuRenderPassEncoderEnd(pass_);
+ wgpuRenderPassEncoderRelease(pass_);
+ pass_ = nullptr;
+
+ WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder_, nullptr);
+ wgpuCommandEncoderRelease(encoder_);
+ encoder_ = nullptr;
+ wgpuQueueSubmit(queue_, 1, &commands);
+ wgpuCommandBufferRelease(commands);
+
+ if (frame_view_) { wgpuTextureViewRelease(frame_view_); frame_view_ = nullptr; }
+ if (frame_texture_) { wgpuTextureRelease(frame_texture_); frame_texture_ = nullptr; }
+}
void WebGPUDevice::readPixels(i32, i32, u32, u32, GfxPixelFormat, void*) { stubOnce("readPixels"); }
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.hpp b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
index 972f66c78..c64cc8eca 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.hpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
@@ -3,13 +3,16 @@
/**
* @file WebGPUDevice.hpp
* @brief WebGPU (Dawn / emdawnwebgpu) backend skeleton for GfxDevice (REARCH_WGSL Phase 2).
- * @details Slice 1: resource creation (buffers / textures / shader modules /
- * layout+pipeline descriptors) is implemented against the real Dawn C API;
- * pass encoding and draws are structured stubs for slice 2 (they need the
- * per-frame command-encoder model wired to a surface). The class is
- * null-device safe: constructed without a WGPUDevice it degrades every
- * entry point to a logged no-op, so handle bookkeeping and the language
- * gate are testable without an adapter.
+ * @details Slice 1 implemented resource creation against the real Dawn C API;
+ * slice 2 adds the live render path: a canvas surface (configureSurface),
+ * per-pass command encoding (beginRenderPass acquires the surface texture
+ * and applies the RenderPassDesc load-ops; endRenderPass submits), lazy
+ * WGPURenderPipeline builds from the retained PipelineDesc + layout +
+ * shader modules, a minimal group-0 bind group over the UBO slots
+ * (setUniformBuffer), and indexed/instanced draw recording. The class
+ * stays null-device safe: constructed without a WGPUDevice it degrades
+ * every entry point to a logged no-op, so handle bookkeeping and the
+ * language gate are testable without an adapter.
*
* Compiled only under ES_ENABLE_WEBGPU; never part of the GL build.
*
@@ -125,6 +128,13 @@ public:
// -------------------------------------------------------------------------
bool hasDevice() const { return device_ != nullptr; }
+
+ /**
+ * @brief Binds a canvas as the default render target (bring-up entry, not part
+ * of the GfxDevice interface). @p selector is a CSS selector the
+ * emscripten surface source resolves, e.g. "#canvas".
+ */
+ bool configureSurface(const char* selector, u32 width, u32 height);
usize bufferCount() const { return buffers_.size(); }
usize textureCount() const { return textures_.size(); }
usize layoutCount() const { return layouts_.size(); }
@@ -147,19 +157,49 @@ private:
WGPUShaderModule vertex = nullptr;
WGPUShaderModule fragment = nullptr;
};
+ struct PipelineRec {
+ PipelineDesc desc;
+ WGPURenderPipeline pipeline = nullptr; ///< Lazily built on first setPipeline.
+ };
- /** @brief Logs the slice-2 stub once per entry point (draws/passes). */
+ /** @brief Logs a not-yet-implemented path once per entry point. */
void stubOnce(const char* what);
+ /** @brief Builds (once) and returns the WGPURenderPipeline for a handle. */
+ WGPURenderPipeline ensurePipeline(u32 id);
+ /** @brief (Re)creates the group-0 bind group from the recorded UBO slots. */
+ void flushBindGroup();
+ /** @brief True while inside beginRenderPass/endRenderPass. */
+ bool inPass() const { return pass_ != nullptr; }
+
WGPUDevice device_ = nullptr;
WGPUQueue queue_ = nullptr;
+ WGPUInstance instance_ = nullptr;
+
+ // Surface (the Default framebuffer target).
+ WGPUSurface surface_ = nullptr;
+ WGPUTextureFormat surface_format_ = WGPUTextureFormat_RGBA8Unorm;
+ u32 surface_width_ = 0;
+ u32 surface_height_ = 0;
+
+ // Per-pass state.
+ WGPUCommandEncoder encoder_ = nullptr;
+ WGPURenderPassEncoder pass_ = nullptr;
+ WGPUTexture frame_texture_ = nullptr; ///< Acquired surface texture (released at end).
+ WGPUTextureView frame_view_ = nullptr;
+ u32 current_pipeline_ = 0;
+ u32 bound_index_buffer_ = 0;
+ static constexpr u32 kUniformSlots = 8;
+ u32 uniform_slots_[kUniformSlots] = {}; ///< BufferHandle id per UBO binding slot.
+ bool bind_group_dirty_ = true;
+ WGPUBindGroup bind_group_ = nullptr;
u32 next_id_ = 1;
std::unordered_map<u32, BufferRec> buffers_;
std::unordered_map<u32, TextureRec> textures_;
std::unordered_map<u32, ProgramRec> programs_;
std::unordered_map<u32, VertexLayoutDesc> layouts_;
- std::unordered_map<u32, PipelineDesc> pipelines_;
+ std::unordered_map<u32, PipelineRec> pipelines_;
std::vector<std::string> stub_logged_;
};
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 94652f627..2929bcfe5 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -130,6 +130,24 @@ if(EMSCRIPTEN)
add_test(NAME test_webgpu_device COMMAND test_webgpu_device)
endif()
+# WebGPU bring-up program (REARCH_WGSL Phase 2 slice 2): NOT a test harness — a
+# browser-run wasm that renders the shape-shader WGSL twin through the real
+# WebGPUDevice (surface pass + lazy pipeline + bind group + indexed draw). Driven
+# by desktop/scripts/webgpu-bringup.mjs under electron, which asserts the pixels.
+if(EMSCRIPTEN)
+ add_executable(webgpu_bringup
+ renderer/webgpu_bringup.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/webgpu/WebGPUDevice.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp
+ )
+ target_include_directories(webgpu_bringup PRIVATE
+ ${CMAKE_SOURCE_DIR}/src
+ ${CMAKE_SOURCE_DIR}/third_party/glm
+ )
+ target_compile_options(webgpu_bringup PRIVATE --use-port=emdawnwebgpu)
+ target_link_options(webgpu_bringup PRIVATE --use-port=emdawnwebgpu)
+endif()
+
# Boundary-span validation (RC3): JS-supplied pointer+length pairs are null-,
# overflow-, and heap-range-checked ALWAYS ON. Header-only + Log.cpp; under
# emscripten the heap-range cases exercise the real linear-memory bound.
diff --git a/tests/renderer/webgpu_bringup.cpp b/tests/renderer/webgpu_bringup.cpp
new file mode 100644
index 000000000..c91496a81
--- /dev/null
+++ b/tests/renderer/webgpu_bringup.cpp
@@ -0,0 +1,185 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file WebGPU bring-up (REARCH_WGSL Phase 2 slice 2) — NOT a doctest harness.
+ *
+ * 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 — surface pass with a load-op clear, lazy pipeline from the Shape layout,
+ * group-0 FrameConstants bind group, one indexed draw of the shape-shader WGSL
+ * twin — and renders a red SDF circle on a dark blue clear. The electron runner
+ * (desktop/scripts/webgpu-bringup.mjs) asserts the pixels.
+ */
+#include "esengine/renderer/webgpu/WebGPUDevice.hpp"
+
+#include <emscripten.h>
+#include <emscripten/html5.h>
+
+#include <cstdio>
+
+using namespace esengine;
+
+// WGSL twin of src/esengine/data/shaders/shape.esshader — same attribute
+// locations (Shape layout 0..3), same FrameConstants block (UBO binding 0),
+// same SDF math line for line. `v` instead of `in` (a WGSL reserved word).
+static const char* kShapeWGSL_Vertex = R"(
+struct FrameConstants { projection : mat4x4f };
+@group(0) @binding(0) var<uniform> frame : FrameConstants;
+
+struct VSIn {
+ @location(0) position : vec2f,
+ @location(1) uv : vec2f,
+ @location(2) color : vec4f,
+ @location(3) shapeInfo : vec4f,
+};
+struct VSOut {
+ @builtin(position) pos : vec4f,
+ @location(0) uv : vec2f,
+ @location(1) color : vec4f,
+ @location(2) shapeInfo : vec4f,
+};
+
+@vertex fn vs_main(v : VSIn) -> VSOut {
+ var out : VSOut;
+ out.pos = frame.projection * vec4f(v.position, 0.0, 1.0);
+ out.uv = v.uv;
+ out.color = v.color;
+ out.shapeInfo = v.shapeInfo;
+ return out;
+}
+)";
+
+static const char* kShapeWGSL_Fragment = R"(
+struct VSOut {
+ @builtin(position) pos : vec4f,
+ @location(0) uv : vec2f,
+ @location(1) color : vec4f,
+ @location(2) shapeInfo : vec4f,
+};
+
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let halfSize = v.shapeInfo.yz;
+ let cornerRadius = v.shapeInfo.w;
+ let p = v.uv * halfSize;
+ let shapeType = v.shapeInfo.x;
+
+ var dist : f32;
+ if (shapeType < 0.5) {
+ let r = min(halfSize.x, halfSize.y);
+ dist = length(p) - r;
+ } else if (shapeType < 1.5) {
+ let r = min(halfSize.x, halfSize.y);
+ let elongation = halfSize - vec2f(r, r);
+ let q = abs(p) - elongation;
+ dist = length(max(q, vec2f(0.0, 0.0))) - r;
+ } else {
+ let r = min(cornerRadius, min(halfSize.x, halfSize.y));
+ let q = abs(p) - halfSize + vec2f(r, r);
+ dist = length(max(q, vec2f(0.0, 0.0))) + min(max(q.x, q.y), 0.0) - r;
+ }
+
+ let fw = fwidth(dist);
+ let alpha = 1.0 - smoothstep(-fw, fw, dist);
+ if (alpha < 0.001) { discard; }
+ return vec4f(v.color.rgb, v.color.a * alpha);
+}
+)";
+
+namespace {
+
+WebGPUDevice* g_device = nullptr;
+PipelineHandle g_pipeline{};
+BufferHandle g_vbo{}, g_ibo{}, g_ubo{};
+int g_frames = 0;
+
+// One ShapeVertex (mirrors the engine's Shape stream, stride 48).
+struct ShapeVertex {
+ f32 px, py, ux, uy;
+ f32 cr, cg, cb, ca;
+ f32 shapeType, halfW, halfH, cornerRadius;
+};
+
+void renderFrame() {
+ RenderPassDesc pass{};
+ pass.clearColor = true;
+ pass.clearDepth = false;
+ pass.clearColorValue[0] = 0.05f;
+ pass.clearColorValue[1] = 0.05f;
+ pass.clearColorValue[2] = 0.30f;
+ pass.clearColorValue[3] = 1.0f;
+
+ g_device->beginRenderPass(pass);
+ g_device->setPipeline(g_pipeline);
+ g_device->setUniformBuffer(0, g_ubo);
+ g_device->setVertexBuffer(0, g_vbo, 0);
+ g_device->setIndexBuffer(g_ibo);
+ g_device->drawElements(6, GfxDataType::UnsignedShort, 0);
+ g_device->endRenderPass();
+
+ if (++g_frames == 3) {
+ std::printf("BRINGUP_FRAMES_OK\n");
+ emscripten_cancel_main_loop();
+ }
+}
+
+} // namespace
+
+int main() {
+ WGPUDevice raw = emscripten_webgpu_get_device();
+ if (!raw) {
+ std::printf("BRINGUP_FAIL no preinitialized device\n");
+ return 1;
+ }
+
+ static WebGPUDevice device(raw);
+ g_device = &device;
+
+ if (!device.configureSurface("#canvas", 256, 256)) {
+ std::printf("BRINGUP_FAIL surface\n");
+ return 1;
+ }
+
+ // FrameConstants: identity projection (positions are authored in clip space).
+ const f32 identity[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
+ g_ubo = device.createBuffer({GfxBufferUsage::Uniform, sizeof(identity), false}, identity);
+
+ // A quad in clip space; uv spans ±1 so p = uv*halfSize inscribes the circle.
+ const ShapeVertex verts[4] = {
+ {-0.8f, -0.8f, -1, -1, 1, 0, 0, 1, /*circle*/ 0, 100, 100, 0},
+ { 0.8f, -0.8f, 1, -1, 1, 0, 0, 1, 0, 100, 100, 0},
+ { 0.8f, 0.8f, 1, 1, 1, 0, 0, 1, 0, 100, 100, 0},
+ {-0.8f, 0.8f, -1, 1, 1, 0, 0, 1, 0, 100, 100, 0},
+ };
+ const u16 indices[6] = {0, 1, 2, 2, 3, 0};
+ g_vbo = device.createBuffer({GfxBufferUsage::Vertex, sizeof(verts), false}, verts);
+ g_ibo = device.createBuffer({GfxBufferUsage::Index, sizeof(indices), false}, indices);
+
+ ShaderHandle program = device.createProgram(
+ GfxShaderSource{GfxShaderLanguage::WGSL, kShapeWGSL_Vertex, kShapeWGSL_Fragment},
+ nullptr, 0, nullptr, nullptr);
+ if (program == ShaderHandle::Invalid) {
+ std::printf("BRINGUP_FAIL program\n");
+ return 1;
+ }
+
+ // The engine's Shape layout, byte for byte (TransientBufferPool::setupStream).
+ VertexLayoutDesc layout{};
+ layout.attributeCount = 4;
+ layout.strides[0] = 48;
+ layout.attributes[0] = {0, 2, GfxDataType::Float, false, 0, 0};
+ layout.attributes[1] = {1, 2, GfxDataType::Float, false, 8, 0};
+ layout.attributes[2] = {2, 4, GfxDataType::Float, false, 16, 0};
+ layout.attributes[3] = {3, 4, GfxDataType::Float, false, 32, 0};
+
+ PipelineDesc pd{};
+ pd.program = program;
+ pd.vertexLayout = device.createVertexLayout(layout);
+ pd.blend = BlendMode::Normal;
+ pd.blendEnabled = true;
+ g_pipeline = device.createPipeline(pd);
+
+ std::printf("BRINGUP_INIT_OK\n");
+ emscripten_set_main_loop(renderFrame, 0, /*simulate_infinite_loop=*/false);
+ return 0;
+}