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): depth/stencil complete + sampler cache + twins move home (WGSL phase 2 slice 5a)

yhh36f87ec6af36
diff --git a/desktop/scripts/webgpu-bringup.mjs b/desktop/scripts/webgpu-bringup.mjs
index 120c67169..362b6913e 100644
--- a/desktop/scripts/webgpu-bringup.mjs
+++ b/desktop/scripts/webgpu-bringup.mjs
@@ -1,14 +1,15 @@
// 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).
+ * @file WebGPU bring-up runner (REARCH_WGSL Phase 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.
+ * Module.preinitializedWebGPUDevice, and the program renders the engine's WGSL
+ * twins through the real WebGPUDevice — SDF shapes, a multi-texture batch draw
+ * over render-to-texture output with NEAREST sampling, the stencil mask flow
+ * with a mid-pass reset, and a region-scoped clear emulation. This runner
+ * asserts the pixels and surfaces device validation errors.
*
* Run: node desktop/scripts/webgpu-bringup.mjs (electron resolved from desktop/)
* Prereq: cmake --build build/wasm/web-tests --target webgpu_bringup
@@ -74,7 +75,9 @@ 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 });
+ // width/height must size the CONTENT (the capture space), not the window frame
+ // — pixel asserts in the lower half land outside a frame-sized capture.
+ const win = new BrowserWindow({ show: false, width: 256, height: 256, useContentSize: true });
let framesOk = false;
const errors = [];
win.webContents.on('console-message', (...args) => {
@@ -100,20 +103,34 @@ app.whenReady().then(async () => {
return { b: png[i], g: png[i + 1], r: png[i + 2] };
};
const near = (v, want, tol = 40) => Math.abs(v - want) <= tol;
+ const isClear = (p) => near(p.r, 13) && near(p.g, 13) && near(p.b, 77, 60);
const circle = px(128, 32); // shape twin: magenta SDF circle, top-center
- const left = px(64, 166); // batch twin: quad sampling slot 0 → red
- const right = px(192, 166); // batch twin: quad sampling slot 1 → green
+ // Batch quad slot 0: 2x2 checker sampled NEAREST — off-center sample points
+ // must be PURE texels (linear would blend them towards purple).
+ const checkerRed = px(54, 182); // uv ~(0.4, 0.4) → texel (0,0) = red
+ const checkerBlue = px(84, 197); // uv ~(0.7, 0.3) → texel (1,0) = blue
+ const right = px(192, 166); // batch twin: quad sampling slot 1 → offscreen green
const corner = px(8, 128); // between the quads' outside → dark blue clear
+ // Stencil flow: cyan only INSIDE the Write-mode mask; the oversized Test rect
+ // is clipped outside it; the post-clearStencil rect must be invisible.
+ const maskIn = px(38, 38); // inside mask ∩ cyan test rect → cyan
+ const maskOut = px(78, 30); // inside cyan test rect, outside mask → clear color
+ const afterReset = px(210, 38); // orange rect after mid-pass clearStencil → clear color
+
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 checkerOk = near(checkerRed.r, 255) && near(checkerRed.g, 0) && near(checkerRed.b, 0)
+ && near(checkerBlue.r, 0) && near(checkerBlue.g, 0) && near(checkerBlue.b, 255);
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 && scopedOk;
+ const cornerOk = isClear(corner);
+ const stencilOk = near(maskIn.r, 0) && near(maskIn.g, 255) && near(maskIn.b, 255)
+ && isClear(maskOut) && isClear(afterReset);
+ const ok = framesOk && errors.length === 0 && circleOk && checkerOk && rightOk
+ && cornerOk && scopedOk && stencilOk;
- 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(`RESULT circle=${JSON.stringify(circle)} checkerRed=${JSON.stringify(checkerRed)} checkerBlue=${JSON.stringify(checkerBlue)} right=${JSON.stringify(right)} maskIn=${JSON.stringify(maskIn)} maskOut=${JSON.stringify(maskOut)} afterReset=${JSON.stringify(afterReset)} 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/src/esengine/renderer/webgpu/WGSLTwins.hpp b/src/esengine/renderer/webgpu/WGSLTwins.hpp
new file mode 100644
index 000000000..c30a6a554
--- /dev/null
+++ b/src/esengine/renderer/webgpu/WGSLTwins.hpp
@@ -0,0 +1,171 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file WGSLTwins.hpp
+ * @brief Hand-authored WGSL twins of the engine's embedded shaders (REARCH_WGSL Phase 2).
+ * @details Each twin mirrors its .esshader source line for line: same attribute
+ * locations, same UBO blocks at the same binding slots (group 0), and
+ * the multi-texture set as bind group 1 — 8 texture_2d at bindings 0..7
+ * paired with 8 samplers at bindings 8..15 (GL's combined
+ * texture+sampler state arrives de-combined; sampler i carries texture
+ * i's filter/wrap params). Consumed by the WebGPU bring-up today and by
+ * the engine's WGSL program selection when the backend reports WGSL;
+ * Phase 3's dual-language emitter replaces the hand-written pairs.
+ *
+ * Compiled only under ES_ENABLE_WEBGPU; never part of the GL build.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#pragma once
+
+namespace esengine::webgpu {
+
+// =============================================================================
+// shape.esshader — SDF shapes over the Shape stream (locations 0..3), the
+// FrameConstants block at group 0 binding 0, the same SDF math per shape type.
+// `v` instead of `in` (a WGSL reserved word).
+// =============================================================================
+
+inline constexpr 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;
+}
+)";
+
+inline constexpr 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);
+}
+)";
+
+// =============================================================================
+// batch.esshader (default variant) — the Batch stream (pos, unorm8x4 color, uv,
+// texIndex at locations 0..3), FrameConstants at group 0, and u_textures[8] as
+// the group-1 texture/sampler pairs. textureSampleLevel(…, 0) keeps sampling
+// uniform-flow-legal inside the branch chain; 2D sprites sample mip 0 (the
+// mipped path is a Phase 3 topic).
+// =============================================================================
+
+inline constexpr const char* kBatchWGSL_Vertex = R"(
+struct FrameConstants { projection : mat4x4f };
+@group(0) @binding(0) var<uniform> frame : FrameConstants;
+
+struct VSIn {
+ @location(0) position : vec2f,
+ @location(1) color : vec4f,
+ @location(2) uv : vec2f,
+ @location(3) texIndex : f32,
+};
+struct VSOut {
+ @builtin(position) pos : vec4f,
+ @location(0) color : vec4f,
+ @location(1) uv : vec2f,
+ @location(2) texIndex : f32,
+};
+
+@vertex fn vs_main(v : VSIn) -> VSOut {
+ var out : VSOut;
+ out.pos = frame.projection * vec4f(v.position, 0.0, 1.0);
+ out.color = v.color;
+ out.uv = v.uv;
+ out.texIndex = v.texIndex;
+ return out;
+}
+)";
+
+inline constexpr const char* kBatchWGSL_Fragment = R"(
+@group(1) @binding(0) var t0 : texture_2d<f32>;
+@group(1) @binding(1) var t1 : texture_2d<f32>;
+@group(1) @binding(2) var t2 : texture_2d<f32>;
+@group(1) @binding(3) var t3 : texture_2d<f32>;
+@group(1) @binding(4) var t4 : texture_2d<f32>;
+@group(1) @binding(5) var t5 : texture_2d<f32>;
+@group(1) @binding(6) var t6 : texture_2d<f32>;
+@group(1) @binding(7) var t7 : texture_2d<f32>;
+@group(1) @binding(8) var s0 : sampler;
+@group(1) @binding(9) var s1 : sampler;
+@group(1) @binding(10) var s2 : sampler;
+@group(1) @binding(11) var s3 : sampler;
+@group(1) @binding(12) var s4 : sampler;
+@group(1) @binding(13) var s5 : sampler;
+@group(1) @binding(14) var s6 : sampler;
+@group(1) @binding(15) var s7 : sampler;
+
+struct VSOut {
+ @builtin(position) pos : vec4f,
+ @location(0) color : vec4f,
+ @location(1) uv : vec2f,
+ @location(2) texIndex : f32,
+};
+
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let idx = i32(v.texIndex + 0.5);
+ var c : vec4f;
+ if (idx == 0) { c = textureSampleLevel(t0, s0, v.uv, 0.0); }
+ else if (idx == 1) { c = textureSampleLevel(t1, s1, v.uv, 0.0); }
+ else if (idx == 2) { c = textureSampleLevel(t2, s2, v.uv, 0.0); }
+ else if (idx == 3) { c = textureSampleLevel(t3, s3, v.uv, 0.0); }
+ else if (idx == 4) { c = textureSampleLevel(t4, s4, v.uv, 0.0); }
+ else if (idx == 5) { c = textureSampleLevel(t5, s5, v.uv, 0.0); }
+ else if (idx == 6) { c = textureSampleLevel(t6, s6, v.uv, 0.0); }
+ else { c = textureSampleLevel(t7, s7, v.uv, 0.0); }
+ return c * v.color;
+}
+)";
+
+} // namespace esengine::webgpu
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
index 9ce1510e7..8f1450384 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
@@ -2,9 +2,10 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file WebGPUDevice.cpp
- * @brief WebGPU backend (REARCH_WGSL Phase 2): resources (slice 1) + live
- * render path — surface, pass encoding, lazy pipelines, bind groups,
- * draws (slice 2).
+ * @brief WebGPU backend (REARCH_WGSL Phase 2): resources + the live render
+ * path — surface, pass encoding with depth-stencil attachments, lazy
+ * per-DS-shape pipelines, texture/sampler bind groups, draws, and the
+ * internal clear-triangle emulations.
*/
#include "WebGPUDevice.hpp"
#include "WebGPUMappings.hpp"
@@ -24,6 +25,24 @@ WGPUStringView sv(const char* text) {
view.length = text ? std::strlen(text) : 0;
return view;
}
+
+bool isDepthFormat(WGPUTextureFormat format) {
+ return format == WGPUTextureFormat_Depth24Plus ||
+ format == WGPUTextureFormat_Depth24PlusStencil8;
+}
+
+u32 dsVariantOf(WGPUTextureFormat format) {
+ if (format == WGPUTextureFormat_Undefined) return WebGPUDevice::kDsNone;
+ return hasStencilPlanes(format) ? WebGPUDevice::kDsDepthStencil : WebGPUDevice::kDsDepthOnly;
+}
+
+u8 packSamplerKey(TextureFilter minFilter, TextureFilter magFilter,
+ TextureWrap wrapS, TextureWrap wrapT) {
+ return static_cast<u8>((minFilter == TextureFilter::Nearest ? 1u : 0u) |
+ (magFilter == TextureFilter::Nearest ? 2u : 0u) |
+ (static_cast<u32>(wrapS) << 2) |
+ (static_cast<u32>(wrapT) << 4));
+}
} // namespace
WebGPUDevice::WebGPUDevice(WGPUDevice device) : device_(device) {
@@ -56,15 +75,27 @@ void WebGPUDevice::shutdown() {
programs_.clear();
layouts_.clear();
for (auto& [id, rec] : pipelines_) {
- if (rec.pipeline) wgpuRenderPipelineRelease(rec.pipeline);
+ for (WGPURenderPipeline variant : rec.variants) {
+ if (variant) wgpuRenderPipelineRelease(variant);
+ }
}
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; }
+ for (auto& [key, pipeline] : clear_pipelines_) {
+ if (pipeline) wgpuRenderPipelineRelease(pipeline);
+ }
+ clear_pipelines_.clear();
+ if (clear_layout_) { wgpuPipelineLayoutRelease(clear_layout_); clear_layout_ = nullptr; }
+ if (clear_bgl_) { wgpuBindGroupLayoutRelease(clear_bgl_); clear_bgl_ = nullptr; }
framebuffers_.clear();
- if (sampler_) { wgpuSamplerRelease(sampler_); sampler_ = nullptr; }
+ for (auto& [key, sampler] : samplers_) {
+ if (sampler) wgpuSamplerRelease(sampler);
+ }
+ samplers_.clear();
+ if (surface_depth_view_) { wgpuTextureViewRelease(surface_depth_view_); surface_depth_view_ = nullptr; }
+ if (surface_depth_texture_) { wgpuTextureRelease(surface_depth_texture_); surface_depth_texture_ = nullptr; }
if (surface_) { wgpuSurfaceRelease(surface_); surface_ = nullptr; }
if (instance_) { wgpuInstanceRelease(instance_); instance_ = nullptr; }
}
@@ -105,7 +136,24 @@ bool WebGPUDevice::configureSurface(const char* selector, u32 width, u32 height)
wgpuSurfaceConfigure(surface_, &cfg);
surface_width_ = width;
surface_height_ = height;
- return true;
+
+ // The default target's companion depth-stencil planes — the WebGL canvas has
+ // them implicitly, and engine stencil masks / depth-tested draws target the
+ // backbuffer expecting both.
+ if (surface_depth_view_) { wgpuTextureViewRelease(surface_depth_view_); surface_depth_view_ = nullptr; }
+ if (surface_depth_texture_) { wgpuTextureRelease(surface_depth_texture_); surface_depth_texture_ = nullptr; }
+ WGPUTextureDescriptor dd{};
+ dd.dimension = WGPUTextureDimension_2D;
+ dd.format = WGPUTextureFormat_Depth24PlusStencil8;
+ dd.size = WGPUExtent3D{width, height, 1};
+ dd.mipLevelCount = 1;
+ dd.sampleCount = 1;
+ dd.usage = WGPUTextureUsage_RenderAttachment;
+ surface_depth_texture_ = wgpuDeviceCreateTexture(device_, &dd);
+ if (surface_depth_texture_) {
+ surface_depth_view_ = wgpuTextureCreateView(surface_depth_texture_, nullptr);
+ }
+ return surface_depth_view_ != nullptr;
}
void WebGPUDevice::stubOnce(const char* what) {
@@ -127,7 +175,20 @@ void WebGPUDevice::setViewport(i32 x, i32 y, u32 w, u32 h) {
}
}
-void WebGPUDevice::clearStencil(i32) { stubOnce("clearStencil (stencil-write quad)"); }
+void WebGPUDevice::clearStencil(i32 value) {
+ // Mid-pass stencil reset (mask rebuild) — the one clear that cannot restart
+ // the pass. Emulated with a stencil-write triangle under whatever scissor is
+ // currently active, matching GL's glClear-honors-scissor semantics.
+ if (!pass_) {
+ ES_LOG_WARN("WebGPUDevice::clearStencil: no active pass");
+ return;
+ }
+ if (!hasStencilPlanes(pass_ds_format_)) {
+ ES_LOG_WARN("WebGPUDevice::clearStencil: pass target has no stencil planes");
+ return;
+ }
+ drawInternalClear(false, false, true, nullptr, value, nullptr);
+}
void WebGPUDevice::setScissorTest(bool enabled) {
// WebGPU's scissor is always on; "disabled" = the full target rectangle.
@@ -283,8 +344,12 @@ TextureHandle WebGPUDevice::createTexture(const TextureDesc& desc, const void* p
td.size = WGPUExtent3D{desc.width, desc.height, 1};
td.mipLevelCount = 1;
td.sampleCount = 1;
- td.usage = WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst |
- WGPUTextureUsage_RenderAttachment;
+ // Depth-stencil textures are attachment-only: writeTexture cannot fill them
+ // and the engine never samples its depth attachments.
+ td.usage = isDepthFormat(td.format)
+ ? WGPUTextureUsage_RenderAttachment
+ : (WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst |
+ WGPUTextureUsage_RenderAttachment);
WGPUTexture texture = wgpuDeviceCreateTexture(device_, &td);
if (!texture) {
@@ -294,9 +359,11 @@ TextureHandle WebGPUDevice::createTexture(const TextureDesc& desc, const void* p
const u32 id = next_id_++;
textures_[id] = TextureRec{texture, wgpuTextureCreateView(texture, nullptr),
- desc.width, desc.height};
+ desc.width, desc.height, td.format,
+ packSamplerKey(desc.minFilter, desc.magFilter,
+ desc.wrapS, desc.wrapT)};
- if (pixels) {
+ if (pixels && !isDepthFormat(td.format)) {
updateTexture(TextureHandle{id}, 0, 0, desc.width, desc.height, pixels, false);
}
return TextureHandle{id};
@@ -327,6 +394,10 @@ void WebGPUDevice::updateTexture(TextureHandle texture, i32 x, i32 y, u32 width,
const void* pixels, bool flipY) {
auto it = textures_.find(static_cast<u32>(texture));
if (it == textures_.end() || !pixels || !queue_) return;
+ if (isDepthFormat(it->second.format)) {
+ ES_LOG_ERROR("WebGPUDevice::updateTexture: depth-stencil textures are attachment-only");
+ return;
+ }
if (flipY) {
// The GL backend flips via UNPACK_FLIP_Y_WEBGL; WebGPU has no upload flip.
// Slice 2 decides the single flip point (CPU pre-flip at the loader).
@@ -346,11 +417,21 @@ void WebGPUDevice::updateTexture(TextureHandle texture, i32 x, i32 y, u32 width,
static_cast<usize>(width) * height * 4, &layout, &extent);
}
-void WebGPUDevice::setTextureParams(TextureHandle, TextureFilter, TextureFilter,
- TextureWrap, TextureWrap) {
- // Sampler state is a bind-group object on WebGPU, not texture state; the
- // sampler cache keyed by (filter, wrap) lands with bind groups in slice 2.
- stubOnce("setTextureParams (sampler objects)");
+void WebGPUDevice::setTextureParams(TextureHandle texture, TextureFilter minFilter,
+ TextureFilter magFilter, TextureWrap wrapS, TextureWrap wrapT) {
+ // GL's texture-object sampler state, de-combined: the texture record carries
+ // its params key and the bind group pairs it with a cached sampler object.
+ auto it = textures_.find(static_cast<u32>(texture));
+ if (it == textures_.end()) return;
+ const u8 key = packSamplerKey(minFilter, magFilter, wrapS, wrapT);
+ if (it->second.samplerKey == key) return;
+ it->second.samplerKey = key;
+ for (u32 slot = 0; slot < kTextureSlots; ++slot) {
+ if (texture_slots_[slot] == it->first) {
+ bind_group_dirty_ = true;
+ break;
+ }
+ }
}
void WebGPUDevice::generateMipmaps(TextureHandle) { stubOnce("generateMipmaps"); }
@@ -402,6 +483,10 @@ ShaderHandle WebGPUDevice::createProgram(const GfxShaderSource& source,
ProgramRec rec{};
rec.vertex = makeModule(source.vertexSrc);
rec.fragment = makeModule(source.fragmentSrc);
+ // Group 1 is the texture set by engine convention; a program that never
+ // spells it must never have the group bound (auto layouts omit it).
+ rec.usesTextureGroup = (source.fragmentSrc && std::strstr(source.fragmentSrc, "@group(1)")) ||
+ (source.vertexSrc && std::strstr(source.vertexSrc, "@group(1)"));
if (!rec.vertex || !rec.fragment) {
if (rec.vertex) wgpuShaderModuleRelease(rec.vertex);
if (rec.fragment) wgpuShaderModuleRelease(rec.fragment);
@@ -447,8 +532,8 @@ u32 WebGPUDevice::getUniformBlockIndex(ShaderHandle, const char*) {
void WebGPUDevice::uniformBlockBinding(ShaderHandle, u32, u32) {}
// =============================================================================
-// Pipelines (descriptors retained; WGPURenderPipeline builds in slice 2 where
-// bind-group layouts exist)
+// Pipelines (descriptors retained; WGPURenderPipeline built lazily per pass
+// depth-stencil shape — WebGPU validates that coupling, GL never had it)
// =============================================================================
PipelineHandle WebGPUDevice::createPipeline(const PipelineDesc& desc) {
@@ -457,14 +542,15 @@ PipelineHandle WebGPUDevice::createPipeline(const PipelineDesc& desc) {
if (rec.desc == desc) return static_cast<PipelineHandle>(id);
}
const u32 id = next_id_++;
- pipelines_[id] = PipelineRec{desc, nullptr};
+ pipelines_[id] = PipelineRec{desc, {}};
return static_cast<PipelineHandle>(id);
}
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 u32 variant = dsVariantOf(pass_ds_format_);
+ if (it->second.variants[variant]) return it->second.variants[variant];
const PipelineDesc& desc = it->second.desc;
auto progIt = programs_.find(static_cast<u32>(desc.program));
@@ -527,17 +613,20 @@ WGPURenderPipeline WebGPUDevice::ensurePipeline(u32 id) {
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");
+ WGPUDepthStencilState ds{};
+ if (variant != kDsNone) {
+ ds = toWGPUDepthStencil(desc, pass_ds_format_);
+ pd.depthStencil = &ds;
+ } else if (desc.depthTest || desc.stencil != GfxStencilMode::Off) {
+ ES_LOG_WARN("WebGPUDevice::ensurePipeline: depth/stencil requested but the "
+ "pass target has no depth-stencil attachment");
}
- it->second.pipeline = wgpuDeviceCreateRenderPipeline(device_, &pd);
- if (!it->second.pipeline) {
+ it->second.variants[variant] = wgpuDeviceCreateRenderPipeline(device_, &pd);
+ if (!it->second.variants[variant]) {
ES_LOG_ERROR("WebGPUDevice::ensurePipeline: creation failed");
}
- return it->second.pipeline;
+ return it->second.variants[variant];
}
void WebGPUDevice::setPipeline(PipelineHandle pipeline) {
@@ -551,83 +640,87 @@ void WebGPUDevice::setPipeline(PipelineHandle pipeline) {
}
void WebGPUDevice::setStencilReference(i32 reference) {
+ stencil_ref_ = reference;
if (pass_) wgpuRenderPassEncoderSetStencilReference(pass_, static_cast<u32>(reference));
}
void WebGPUDevice::invalidatePipelineCache() {}
-WGPUSampler WebGPUDevice::defaultSampler() {
- if (!sampler_ && device_) {
- // Bring-up default: linear filtering, clamped — per-texture sampler state
- // (setTextureParams) becomes a keyed sampler cache in a later slice.
- WGPUSamplerDescriptor sd{};
- sd.addressModeU = WGPUAddressMode_ClampToEdge;
- sd.addressModeV = WGPUAddressMode_ClampToEdge;
- sd.addressModeW = WGPUAddressMode_ClampToEdge;
- sd.magFilter = WGPUFilterMode_Linear;
- sd.minFilter = WGPUFilterMode_Linear;
- sd.mipmapFilter = WGPUMipmapFilterMode_Nearest;
- sd.lodMinClamp = 0.0f;
- sd.lodMaxClamp = 32.0f;
- sd.maxAnisotropy = 1;
- sampler_ = wgpuDeviceCreateSampler(device_, &sd);
- }
- return sampler_;
-}
-
-void WebGPUDevice::clearQuad(const RenderPassDesc& desc) {
- if (!pass_ || !device_) return;
+WGPUSampler WebGPUDevice::samplerFor(u8 key) {
+ auto it = samplers_.find(key);
+ if (it != samplers_.end()) return it->second;
+ if (!device_) return nullptr;
+
+ WGPUSamplerDescriptor sd{};
+ sd.minFilter = (key & 1u) ? WGPUFilterMode_Nearest : WGPUFilterMode_Linear;
+ sd.magFilter = (key & 2u) ? WGPUFilterMode_Nearest : WGPUFilterMode_Linear;
+ sd.addressModeU = toWGPUAddressMode(static_cast<TextureWrap>((key >> 2) & 3u));
+ sd.addressModeV = toWGPUAddressMode(static_cast<TextureWrap>((key >> 4) & 3u));
+ sd.addressModeW = WGPUAddressMode_ClampToEdge;
+ // Every texture is single-mip today (generateMipmaps pending), so the mip
+ // filter never engages; Nearest mirrors GL's non-mipmapped min filters.
+ sd.mipmapFilter = WGPUMipmapFilterMode_Nearest;
+ sd.lodMinClamp = 0.0f;
+ sd.lodMaxClamp = 32.0f;
+ sd.maxAnisotropy = 1;
+ WGPUSampler sampler = wgpuDeviceCreateSampler(device_, &sd);
+ samplers_[key] = sampler;
+ return sampler;
+}
+
+// =============================================================================
+// Internal clear family — the two clears WebGPU load-ops cannot spell: a
+// region-scoped pass clear and a mid-pass stencil reset. A fullscreen triangle
+// at z=1 (GL's clear depth) writes exactly the attachments requested: color via
+// the write mask, depth via depthWriteEnabled + Always, stencil via
+// Replace + the encoder's stencil reference.
+// =============================================================================
- // 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"(
+WGPURenderPipeline WebGPUDevice::ensureClearPipeline(bool color, bool depth, bool stencil) {
+ const u32 key = dsVariantOf(pass_ds_format_) << 3 |
+ (color ? 1u : 0u) | (depth ? 2u : 0u) | (stencil ? 4u : 0u);
+ auto it = clear_pipelines_.find(key);
+ if (it != clear_pipelines_.end()) return it->second;
+
+ 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);
+ return vec4f(p[i], 1.0, 1.0);
}
)";
- static const char* kClearFS = R"(
+ 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);
+ 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);
+ };
- clear_color_ubo_ = createBuffer({GfxBufferUsage::Uniform, 16, true}, nullptr);
+ // One explicit layout for the whole family, so the single bind group is
+ // valid with every write-mask variant (auto layouts are per-pipeline).
+ if (!clear_bgl_) {
+ WGPUBindGroupLayoutEntry ble{};
+ ble.binding = 0;
+ ble.visibility = WGPUShaderStage_Fragment;
+ ble.buffer.type = WGPUBufferBindingType_Uniform;
+ ble.buffer.minBindingSize = 16;
+ WGPUBindGroupLayoutDescriptor bld{};
+ bld.entryCount = 1;
+ bld.entries = &ble;
+ clear_bgl_ = wgpuDeviceCreateBindGroupLayout(device_, &bld);
+
+ WGPUPipelineLayoutDescriptor pld{};
+ pld.bindGroupLayoutCount = 1;
+ pld.bindGroupLayouts = &clear_bgl_;
+ clear_layout_ = wgpuDeviceCreatePipelineLayout(device_, &pld);
+ clear_color_ubo_ = createBuffer({GfxBufferUsage::Uniform, 16, true}, nullptr);
auto uboIt = buffers_.find(static_cast<u32>(clear_color_ubo_));
WGPUBindGroupEntry entry{};
entry.binding = 0;
@@ -635,24 +728,92 @@ struct ClearColor { value : vec4f };
entry.offset = 0;
entry.size = 16;
WGPUBindGroupDescriptor bgd{};
- bgd.layout = wgpuRenderPipelineGetBindGroupLayout(clear_pipeline_, 0);
+ bgd.layout = clear_bgl_;
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);
+ WGPUShaderModule vs = makeModule(kClearVS);
+ WGPUShaderModule fs = makeModule(kClearFS);
+
+ WGPUColorTargetState target{};
+ target.format = surface_format_;
+ target.writeMask = color ? WGPUColorWriteMask_All : WGPUColorWriteMask_None;
+
+ WGPUFragmentState fragment{};
+ fragment.module = fs;
+ fragment.entryPoint = sv("fs_main");
+ fragment.targetCount = 1;
+ fragment.targets = &target;
+
+ WGPURenderPipelineDescriptor pd{};
+ pd.layout = clear_layout_;
+ 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;
- wgpuRenderPassEncoderSetScissorRect(pass_, static_cast<u32>(desc.clearX),
- static_cast<u32>(desc.clearY), desc.clearW, desc.clearH);
- wgpuRenderPassEncoderSetPipeline(pass_, clear_pipeline_);
+ WGPUDepthStencilState ds{};
+ if (pass_ds_format_ != WGPUTextureFormat_Undefined) {
+ ds.format = pass_ds_format_;
+ ds.depthCompare = WGPUCompareFunction_Always;
+ ds.depthWriteEnabled = depth ? WGPUOptionalBool_True : WGPUOptionalBool_False;
+ WGPUStencilFaceState face{};
+ face.compare = WGPUCompareFunction_Always;
+ face.failOp = stencil ? WGPUStencilOperation_Replace : WGPUStencilOperation_Keep;
+ face.depthFailOp = face.failOp;
+ face.passOp = face.failOp;
+ ds.stencilFront = face;
+ ds.stencilBack = face;
+ ds.stencilReadMask = 0xFFu;
+ ds.stencilWriteMask = stencil ? 0xFFu : 0x00u;
+ pd.depthStencil = &ds;
+ }
+
+ WGPURenderPipeline pipeline = wgpuDeviceCreateRenderPipeline(device_, &pd);
+ wgpuShaderModuleRelease(vs);
+ wgpuShaderModuleRelease(fs);
+ clear_pipelines_[key] = pipeline;
+ return pipeline;
+}
+
+void WebGPUDevice::drawInternalClear(bool color, bool depth, bool stencil,
+ const f32 rgba[4], i32 stencilValue,
+ const RenderPassDesc* region) {
+ if (!pass_ || !device_) return;
+ WGPURenderPipeline pipeline = ensureClearPipeline(color, depth, stencil);
+ if (!pipeline || !clear_bind_group_) return;
+
+ const f32 black[4] = {0.0f, 0.0f, 0.0f, 0.0f};
+ updateBuffer(clear_color_ubo_, 0, rgba ? rgba : black, 16);
+
+ // A region rides its own scissor and restores the full target; without one
+ // (mid-pass stencil reset) the currently active scissor applies — the same
+ // rectangle glClear would have honored.
+ if (region) {
+ wgpuRenderPassEncoderSetScissorRect(pass_, static_cast<u32>(region->clearX),
+ static_cast<u32>(region->clearY),
+ region->clearW, region->clearH);
+ }
+ wgpuRenderPassEncoderSetPipeline(pass_, pipeline);
wgpuRenderPassEncoderSetBindGroup(pass_, 0, clear_bind_group_, 0, nullptr);
+ if (stencil) {
+ wgpuRenderPassEncoderSetStencilReference(pass_, static_cast<u32>(stencilValue));
+ }
wgpuRenderPassEncoderDraw(pass_, 3, 1, 0, 0);
- wgpuRenderPassEncoderSetScissorRect(pass_, 0, 0, pass_width_, pass_height_);
+ if (region) {
+ wgpuRenderPassEncoderSetScissorRect(pass_, 0, 0, pass_width_, pass_height_);
+ }
+ if (stencil) {
+ wgpuRenderPassEncoderSetStencilReference(pass_, static_cast<u32>(stencil_ref_));
+ }
- // The clear-quad clobbered pipeline/bind-group pass state; force the next
+ // The triangle clobbered pipeline/bind-group pass state; force the next
// user draw to re-establish everything.
current_pipeline_ = 0;
bind_group_dirty_ = true;
@@ -694,30 +855,39 @@ void WebGPUDevice::flushBindGroup() {
if (bind_group_) wgpuRenderPassEncoderSetBindGroup(pass_, 0, bind_group_, 0, nullptr);
// Group 1: the texture units. The WGSL twin convention is 8 texture_2d at
- // bindings 0..7 + one shared sampler at binding 8 (the batch shader's
- // u_textures[8]). Unused slots repeat slot 0's view — the same trick
- // DrawList::execute uses for WebGL2's complete-texture rule. Only set when
- // the pass bound textures, so sampler-less shaders keep a group-0-only layout.
- if (any_texture_bound_) {
- WGPUTextureView slot0 = nullptr;
+ // bindings 0..7 paired with 8 samplers at bindings 8..15 (the batch shader's
+ // u_textures[8], de-combined: sampler i carries texture i's filter/wrap
+ // params via the sampler cache). Unused slots repeat slot 0's view/sampler —
+ // the same trick DrawList::execute uses for WebGL2's complete-texture rule.
+ // Only set when the pass bound textures AND the current program declares the
+ // group — a sampler-less shader (shape) drawn after textured ones must keep
+ // its group-0-only layout.
+ bool wantsTextures = false;
+ if (auto pipeIt = pipelines_.find(current_pipeline_); pipeIt != pipelines_.end()) {
+ auto progIt = programs_.find(static_cast<u32>(pipeIt->second.desc.program));
+ wantsTextures = progIt != programs_.end() && progIt->second.usesTextureGroup;
+ }
+ if (any_texture_bound_ && wantsTextures) {
+ const TextureRec* slot0 = nullptr;
for (u32 slot = 0; slot < kTextureSlots && !slot0; ++slot) {
auto it = textures_.find(texture_slots_[slot]);
- if (it != textures_.end()) slot0 = it->second.view;
+ if (it != textures_.end()) slot0 = &it->second;
}
if (slot0) {
- WGPUBindGroupEntry texEntries[kTextureSlots + 1] = {};
+ WGPUBindGroupEntry texEntries[kTextureSlots * 2] = {};
for (u32 slot = 0; slot < kTextureSlots; ++slot) {
auto it = textures_.find(texture_slots_[slot]);
+ const TextureRec& rec = (it != textures_.end()) ? it->second : *slot0;
texEntries[slot].binding = slot;
- texEntries[slot].textureView = (it != textures_.end()) ? it->second.view : slot0;
+ texEntries[slot].textureView = rec.view;
+ texEntries[kTextureSlots + slot].binding = kTextureSlots + slot;
+ texEntries[kTextureSlots + slot].sampler = samplerFor(rec.samplerKey);
}
- texEntries[kTextureSlots].binding = kTextureSlots;
- texEntries[kTextureSlots].sampler = defaultSampler();
if (texture_group_) { wgpuBindGroupRelease(texture_group_); texture_group_ = nullptr; }
WGPUBindGroupDescriptor tgd{};
tgd.layout = wgpuRenderPipelineGetBindGroupLayout(p, 1);
- tgd.entryCount = kTextureSlots + 1;
+ tgd.entryCount = kTextureSlots * 2;
tgd.entries = texEntries;
texture_group_ = wgpuDeviceCreateBindGroup(device_, &tgd);
if (tgd.layout) wgpuBindGroupLayoutRelease(tgd.layout);
@@ -765,7 +935,10 @@ 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");
+ if (rec.depthStencil != 0 && !textures_.count(rec.depthStencil)) {
+ ES_LOG_ERROR("WebGPUDevice::createFramebuffer: unknown depth-stencil texture");
+ return FramebufferHandle::Default;
+ }
// 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_++;
@@ -782,6 +955,8 @@ void WebGPUDevice::beginRenderPass(const RenderPassDesc& desc) {
if (pass_) endRenderPass(); // defensive: a dangling pass would deadlock the queue
WGPUTextureView targetView = nullptr;
+ WGPUTextureView dsView = nullptr;
+ pass_ds_format_ = WGPUTextureFormat_Undefined;
if (desc.target != FramebufferHandle::Default) {
auto fbIt = framebuffers_.find(static_cast<u32>(desc.target));
if (fbIt == framebuffers_.end()) {
@@ -796,6 +971,13 @@ void WebGPUDevice::beginRenderPass(const RenderPassDesc& desc) {
targetView = texIt->second.view;
pass_width_ = texIt->second.width;
pass_height_ = texIt->second.height;
+ if (fbIt->second.depthStencil != 0) {
+ auto dsIt = textures_.find(fbIt->second.depthStencil);
+ if (dsIt != textures_.end()) {
+ dsView = dsIt->second.view;
+ pass_ds_format_ = dsIt->second.format;
+ }
+ }
} else {
if (!surface_) {
ES_LOG_ERROR("WebGPUDevice::beginRenderPass: no surface configured");
@@ -814,6 +996,8 @@ void WebGPUDevice::beginRenderPass(const RenderPassDesc& desc) {
targetView = frame_view_;
pass_width_ = surface_width_;
pass_height_ = surface_height_;
+ dsView = surface_depth_view_;
+ pass_ds_format_ = WGPUTextureFormat_Depth24PlusStencil8;
}
encoder_ = wgpuDeviceCreateCommandEncoder(device_, nullptr);
@@ -829,12 +1013,30 @@ void WebGPUDevice::beginRenderPass(const RenderPassDesc& desc) {
WGPURenderPassDescriptor rp{};
rp.colorAttachmentCount = 1;
rp.colorAttachments = &color;
+
+ WGPURenderPassDepthStencilAttachment ds{};
+ if (dsView) {
+ ds.view = dsView;
+ ds.depthLoadOp = toWGPULoadOp(desc.clearDepth, scoped);
+ ds.depthStoreOp = WGPUStoreOp_Store;
+ ds.depthClearValue = 1.0f; // GL's default clear depth; no RHI override exists
+ if (hasStencilPlanes(pass_ds_format_)) {
+ ds.stencilLoadOp = toWGPULoadOp(desc.clearStencil, scoped);
+ ds.stencilStoreOp = WGPUStoreOp_Store;
+ ds.stencilClearValue = static_cast<u32>(desc.clearStencilValue);
+ }
+ rp.depthStencilAttachment = &ds;
+ }
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);
+ stencil_ref_ = 0; // a fresh pass encoder resets its stencil reference
+
+ // Region-scoped clear = load + scissored clear-triangle, per the RHI
+ // contract — for every attachment the desc asks to clear.
+ if (scoped && (desc.clearColor || desc.clearDepth || desc.clearStencil)) {
+ drawInternalClear(desc.clearColor, desc.clearDepth && dsView,
+ desc.clearStencil && hasStencilPlanes(pass_ds_format_),
+ desc.clearColorValue, desc.clearStencilValue, &desc);
}
// Each pass starts textureless: group 1 only attaches to pipelines whose
// draws bind textures (the engine rebinds per draw), never to sampler-less
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.hpp b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
index 6ec7d3ff4..c58c62a87 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.hpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
@@ -2,17 +2,20 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file WebGPUDevice.hpp
- * @brief WebGPU (Dawn / emdawnwebgpu) backend skeleton for GfxDevice (REARCH_WGSL Phase 2).
- * @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.
+ * @brief WebGPU (Dawn / emdawnwebgpu) backend for GfxDevice (REARCH_WGSL Phase 2).
+ * @details The live render path: a canvas surface (configureSurface) with a
+ * companion depth-stencil texture, per-pass command encoding
+ * (beginRenderPass applies the RenderPassDesc load-ops on color AND
+ * depth-stencil; endRenderPass submits), lazy WGPURenderPipeline builds
+ * from the retained PipelineDesc + layout + shader modules — one variant
+ * per pass depth-stencil shape, since WebGPU validates that coupling —
+ * bind groups (group 0 = UBO slots, group 1 = texture/sampler pairs with
+ * a per-params sampler cache), indexed/instanced draw recording, and an
+ * internal clear-triangle family that emulates region-scoped clears and
+ * mid-pass stencil resets (the two clears WebGPU load-ops cannot spell).
+ * 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.
*
@@ -36,6 +39,11 @@ namespace esengine {
class WebGPUDevice final : public GfxDevice {
public:
+ /** @brief Depth-stencil attachment shape of a pass — one WGPURenderPipeline
+ * per shape, since WebGPU validates a pipeline's depthStencil state
+ * against the pass it draws into (GL has no such coupling). */
+ enum DsVariant : u32 { kDsNone = 0, kDsDepthOnly = 1, kDsDepthStencil = 2, kDsVariantCount = 3 };
+
/** @brief @p device may be null for bookkeeping-only use (tests, bring-up). */
explicit WebGPUDevice(WGPUDevice device = nullptr);
~WebGPUDevice() override;
@@ -153,38 +161,51 @@ private:
WGPUTextureView view = nullptr; ///< Default full view, created with the texture.
u32 width = 0;
u32 height = 0;
+ WGPUTextureFormat format = WGPUTextureFormat_RGBA8Unorm;
+ u8 samplerKey = 0; ///< Packed filter/wrap params (sampler cache key).
};
struct ProgramRec {
WGPUShaderModule vertex = nullptr;
WGPUShaderModule fragment = nullptr;
+ /** @brief Whether the WGSL declares the group-1 texture set. A pipeline
+ * without it must never have group 1 set (its auto layout has no
+ * such group), even when the pass bound textures for other draws. */
+ bool usesTextureGroup = false;
};
struct PipelineRec {
PipelineDesc desc;
- WGPURenderPipeline pipeline = nullptr; ///< Lazily built on first setPipeline.
+ WGPURenderPipeline variants[kDsVariantCount] = {}; ///< Lazily built per pass DS shape.
};
struct FramebufferRec {
u32 color0 = 0; ///< TextureHandle id of the color attachment.
- u32 depthStencil = 0; ///< TextureHandle id (0 = none; slice 5 wires it).
+ u32 depthStencil = 0; ///< TextureHandle id (0 = none).
};
/** @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. */
+ /** @brief Builds (once) and returns the WGPURenderPipeline for a handle,
+ * in the variant matching the current pass's depth-stencil shape. */
WGPURenderPipeline ensurePipeline(u32 id);
/** @brief (Re)creates the bind groups: group 0 = UBO slots, group 1 = the
- * texture units (8 texture_2d at bindings 0..7 + one shared sampler at
- * binding 8 — the WGSL twin convention for the batch sampler array).
- * Group 1 is set only when the pass bound any texture, so shaders
- * without samplers (shape) never see a mismatched group. */
+ * texture units (8 texture_2d at bindings 0..7 + their 8 samplers at
+ * bindings 8..15 — the WGSL twin convention for u_textures[8]; GL's
+ * combined texture+sampler state arrives de-combined, sampler i
+ * carrying texture i's filter/wrap params). Group 1 is set only when
+ * the pass bound any texture, so shaders without samplers (shape)
+ * never see a mismatched group. */
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 Returns the cached sampler for packed filter/wrap params. */
+ WGPUSampler samplerFor(u8 key);
+ /** @brief Builds (once) an internal clear pipeline: fullscreen triangle at
+ * z=1, color from the internal UBO. Keyed on which attachments it
+ * writes (color/depth/stencil masks) plus the pass DS shape. */
+ WGPURenderPipeline ensureClearPipeline(bool color, bool depth, bool stencil);
+ /** @brief Draws the internal clear triangle mid-pass. Restores scissor (when
+ * @p region is given), the user's stencil reference, and forces
+ * pipeline + bind groups to re-establish on the next user draw. */
+ void drawInternalClear(bool color, bool depth, bool stencil,
+ const f32 rgba[4], i32 stencilValue, const RenderPassDesc* region);
/** @brief True while inside beginRenderPass/endRenderPass. */
bool inPass() const { return pass_ != nullptr; }
@@ -192,30 +213,39 @@ private:
WGPUQueue queue_ = nullptr;
WGPUInstance instance_ = nullptr;
- // Surface (the Default framebuffer target).
+ // Surface (the Default framebuffer target). The companion depth-stencil
+ // texture mirrors the WebGL canvas's depth+stencil planes — engine stencil
+ // masks and depth-tested draws target the backbuffer and expect them.
WGPUSurface surface_ = nullptr;
WGPUTextureFormat surface_format_ = WGPUTextureFormat_RGBA8Unorm;
u32 surface_width_ = 0;
u32 surface_height_ = 0;
+ WGPUTexture surface_depth_texture_ = nullptr;
+ WGPUTextureView surface_depth_view_ = nullptr;
// 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;
+ // Internal clear family (region-scoped clears + mid-pass clearStencil).
+ // Explicit layout so ONE bind group serves every write-mask variant.
+ std::unordered_map<u32, WGPURenderPipeline> clear_pipelines_;
+ WGPUBindGroupLayout clear_bgl_ = nullptr;
+ WGPUPipelineLayout clear_layout_ = 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;
+ WGPUTextureFormat pass_ds_format_ = WGPUTextureFormat_Undefined;
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;
+ i32 stencil_ref_ = 0; ///< Last user-set reference (re-applied after internal quads).
static constexpr u32 kUniformSlots = 8;
u32 uniform_slots_[kUniformSlots] = {}; ///< BufferHandle id per UBO binding slot.
static constexpr u32 kTextureSlots = 8;
@@ -224,7 +254,7 @@ private:
bool bind_group_dirty_ = true;
WGPUBindGroup bind_group_ = nullptr;
WGPUBindGroup texture_group_ = nullptr;
- WGPUSampler sampler_ = nullptr;
+ std::unordered_map<u8, WGPUSampler> samplers_; ///< Keyed by packed filter/wrap params.
u32 next_id_ = 1;
std::unordered_map<u32, BufferRec> buffers_;
diff --git a/src/esengine/renderer/webgpu/WebGPUMappings.hpp b/src/esengine/renderer/webgpu/WebGPUMappings.hpp
index c322e2ad7..ba7a3dd38 100644
--- a/src/esengine/renderer/webgpu/WebGPUMappings.hpp
+++ b/src/esengine/renderer/webgpu/WebGPUMappings.hpp
@@ -253,6 +253,40 @@ inline WGPUStencilFaceState toWGPUStencilFace(GfxStencilMode mode) {
return face;
}
+/** @brief Stencil write mask per mode — the applyStencilMode table: Write fills
+ * all planes, Test reads without writing, Off never touches stencil. */
+inline u32 toWGPUStencilWriteMask(GfxStencilMode mode) {
+ return mode == GfxStencilMode::Write ? 0xFFu : 0x00u;
+}
+
+/**
+ * @brief A pipeline's full depth-stencil state against a pass attachment format.
+ * @details GL semantics carried over exactly: a disabled depth test neither
+ * compares NOR writes (glDepthMask only applies while GL_DEPTH_TEST is
+ * on); an enabled one compares with GL's default Less func. Stencil
+ * faces/masks come from the same tables applyStencilMode uses.
+ */
+inline WGPUDepthStencilState toWGPUDepthStencil(const PipelineDesc& desc, WGPUTextureFormat format) {
+ WGPUDepthStencilState ds{};
+ ds.format = format;
+ ds.depthWriteEnabled = (desc.depthTest && desc.depthWrite) ? WGPUOptionalBool_True
+ : WGPUOptionalBool_False;
+ ds.depthCompare = desc.depthTest ? WGPUCompareFunction_Less : WGPUCompareFunction_Always;
+ ds.stencilFront = toWGPUStencilFace(desc.stencil);
+ ds.stencilBack = toWGPUStencilFace(desc.stencil);
+ ds.stencilReadMask = 0xFFu;
+ ds.stencilWriteMask = toWGPUStencilWriteMask(desc.stencil);
+ return ds;
+}
+
+/** @brief True when a depth-stencil format carries stencil planes (drives whether
+ * a pass may set stencil load/store ops — Depth24Plus alone must not). */
+inline bool hasStencilPlanes(WGPUTextureFormat format) {
+ return format == WGPUTextureFormat_Depth24PlusStencil8 ||
+ format == WGPUTextureFormat_Depth32FloatStencil8 ||
+ format == WGPUTextureFormat_Stencil8;
+}
+
// =============================================================================
// Render pass load-ops (RenderPassDesc carries the values since the load-op
// unification; a scoped clear region has NO load-op equivalent — the device
diff --git a/tests/renderer/test_webgpu_device.cpp b/tests/renderer/test_webgpu_device.cpp
index e731627e3..645b5b621 100644
--- a/tests/renderer/test_webgpu_device.cpp
+++ b/tests/renderer/test_webgpu_device.cpp
@@ -66,6 +66,40 @@ TEST_CASE("stencil modes translate to the same table GLDevice applies") {
auto test = toWGPUStencilFace(GfxStencilMode::Test);
CHECK(test.compare == WGPUCompareFunction_Equal);
CHECK(test.passOp == WGPUStencilOperation_Keep);
+
+ // The applyStencilMode mask table: Write fills, Test reads only.
+ CHECK(toWGPUStencilWriteMask(GfxStencilMode::Write) == 0xFFu);
+ CHECK(toWGPUStencilWriteMask(GfxStencilMode::Test) == 0x00u);
+ CHECK(toWGPUStencilWriteMask(GfxStencilMode::Off) == 0x00u);
+}
+
+TEST_CASE("pipeline depth-stencil state carries GL semantics exactly") {
+ // GL: a disabled depth test neither compares nor writes — even when the
+ // pipeline asks for depth writes (glDepthMask is inert without the test).
+ PipelineDesc off{};
+ off.depthTest = false;
+ off.depthWrite = true;
+ auto dsOff = toWGPUDepthStencil(off, WGPUTextureFormat_Depth24PlusStencil8);
+ CHECK(dsOff.format == WGPUTextureFormat_Depth24PlusStencil8);
+ CHECK(dsOff.depthCompare == WGPUCompareFunction_Always);
+ CHECK(dsOff.depthWriteEnabled == WGPUOptionalBool_False);
+
+ // GL never calls glDepthFunc, so an enabled test compares with the default Less.
+ PipelineDesc on{};
+ on.depthTest = true;
+ on.depthWrite = true;
+ on.stencil = GfxStencilMode::Write;
+ auto dsOn = toWGPUDepthStencil(on, WGPUTextureFormat_Depth24Plus);
+ CHECK(dsOn.depthCompare == WGPUCompareFunction_Less);
+ CHECK(dsOn.depthWriteEnabled == WGPUOptionalBool_True);
+ CHECK(dsOn.stencilFront.passOp == WGPUStencilOperation_Replace);
+ CHECK(dsOn.stencilBack.passOp == WGPUStencilOperation_Replace);
+ CHECK(dsOn.stencilWriteMask == 0xFFu);
+
+ // Stencil-plane detection drives whether a pass may spell stencil load-ops.
+ CHECK(hasStencilPlanes(WGPUTextureFormat_Depth24PlusStencil8));
+ CHECK(!hasStencilPlanes(WGPUTextureFormat_Depth24Plus));
+ CHECK(!hasStencilPlanes(WGPUTextureFormat_Undefined));
}
TEST_CASE("pass load-ops: full-target clear is a real load-op, a scoped clear is not") {
diff --git a/tests/renderer/webgpu_bringup.cpp b/tests/renderer/webgpu_bringup.cpp
index 806c9acd9..f0bb09492 100644
--- a/tests/renderer/webgpu_bringup.cpp
+++ b/tests/renderer/webgpu_bringup.cpp
@@ -1,169 +1,48 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
- * @file WebGPU bring-up (REARCH_WGSL Phase 2 slices 2+3) — NOT a doctest harness.
+ * @file WebGPU bring-up (REARCH_WGSL Phase 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. 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)
+ * makes, with the engine's WGSL twins (WGSLTwins.hpp). Each frame is THREE
+ * passes:
+ * A. offscreen: a framebuffer with color + depth-stencil attachments, all
+ * load-op cleared (color green) — the right batch quad then SAMPLES the
+ * rendered color target
+ * B. main (the surface + its companion depth-stencil):
+ * act 1 shape twin — magenta SDF circle
+ * act 2 batch twin — two quads in one draw with per-vertex sampler-slot
+ * selection; slot 0 is a 2x2 checker sampled NEAREST (the sampler
+ * cache assert: linear would blend the texels), slot 1 the
+ * offscreen render
+ * act 3 stencil mask — a Write-mode rect stamps ref 1, an oversized
+ * Test-mode cyan rect lands only inside it; then a MID-PASS
+ * clearStencil(0) (the stencil-write triangle emulation) and a
+ * second Test-mode rect that must stay invisible
+ * C. region-scoped clear: a surface pass whose RenderPassDesc carries a clear
+ * REGION — the load-op contract's WebGPU emulation paints a yellow square
* The electron runner (desktop/scripts/webgpu-bringup.mjs) asserts the pixels.
*/
#include "esengine/renderer/webgpu/WebGPUDevice.hpp"
+#include "esengine/renderer/webgpu/WGSLTwins.hpp"
#include <emscripten.h>
#include <emscripten/html5.h>
+#include <array>
#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);
-}
-)";
-
-// WGSL twin of the batch shader's DEFAULT variant (batch.esshader): Batch layout
-// attributes 0..3 (pos, unorm8x4 color, uv, texIndex), FrameConstants at group 0,
-// and the multi-texture set as bind group 1 — 8 texture_2d at bindings 0..7 plus
-// one shared sampler at binding 8 (the WGSL spelling of u_textures[8]).
-// textureSampleLevel(…, 0) keeps sampling uniform-flow-legal inside the branch
-// chain; 2D sprites sample mip 0 (the mipped path is a phase-3 topic).
-static const char* kBatchWGSL_Vertex = R"(
-struct FrameConstants { projection : mat4x4f };
-@group(0) @binding(0) var<uniform> frame : FrameConstants;
-
-struct VSIn {
- @location(0) position : vec2f,
- @location(1) color : vec4f,
- @location(2) uv : vec2f,
- @location(3) texIndex : f32,
-};
-struct VSOut {
- @builtin(position) pos : vec4f,
- @location(0) color : vec4f,
- @location(1) uv : vec2f,
- @location(2) texIndex : f32,
-};
-
-@vertex fn vs_main(v : VSIn) -> VSOut {
- var out : VSOut;
- out.pos = frame.projection * vec4f(v.position, 0.0, 1.0);
- out.color = v.color;
- out.uv = v.uv;
- out.texIndex = v.texIndex;
- return out;
-}
-)";
-
-static const char* kBatchWGSL_Fragment = R"(
-@group(1) @binding(0) var t0 : texture_2d<f32>;
-@group(1) @binding(1) var t1 : texture_2d<f32>;
-@group(1) @binding(2) var t2 : texture_2d<f32>;
-@group(1) @binding(3) var t3 : texture_2d<f32>;
-@group(1) @binding(4) var t4 : texture_2d<f32>;
-@group(1) @binding(5) var t5 : texture_2d<f32>;
-@group(1) @binding(6) var t6 : texture_2d<f32>;
-@group(1) @binding(7) var t7 : texture_2d<f32>;
-@group(1) @binding(8) var samp : sampler;
-
-struct VSOut {
- @builtin(position) pos : vec4f,
- @location(0) color : vec4f,
- @location(1) uv : vec2f,
- @location(2) texIndex : f32,
-};
-
-@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
- let idx = i32(v.texIndex + 0.5);
- var c : vec4f;
- if (idx == 0) { c = textureSampleLevel(t0, samp, v.uv, 0.0); }
- else if (idx == 1) { c = textureSampleLevel(t1, samp, v.uv, 0.0); }
- else if (idx == 2) { c = textureSampleLevel(t2, samp, v.uv, 0.0); }
- else if (idx == 3) { c = textureSampleLevel(t3, samp, v.uv, 0.0); }
- else if (idx == 4) { c = textureSampleLevel(t4, samp, v.uv, 0.0); }
- else if (idx == 5) { c = textureSampleLevel(t5, samp, v.uv, 0.0); }
- else if (idx == 6) { c = textureSampleLevel(t6, samp, v.uv, 0.0); }
- else { c = textureSampleLevel(t7, samp, v.uv, 0.0); }
- return c * v.color;
-}
-)";
-
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_texOffscreen{};
+PipelineHandle g_maskWritePipeline{}, g_maskTestPipeline{};
+BufferHandle g_shapeVbo{}, g_batchVbo{}, g_stencilVbo{}, g_ibo6{}, g_ibo12{}, g_ibo18{}, g_ubo{};
+TextureHandle g_texChecker{}, g_texOffscreen{}, g_texOffscreenDepth{};
FramebufferHandle g_offscreenFb{};
int g_frames = 0;
@@ -183,12 +62,14 @@ struct BatchVertex {
};
void renderFrame() {
- // Pass A: offscreen — the load-op clear IS the render (solid green target).
+ // Pass A: offscreen — full-target load-op clears on color AND depth-stencil.
RenderPassDesc off{};
off.target = g_offscreenFb;
off.clearColor = true;
off.clearColorValue[1] = 1.0f;
off.clearColorValue[3] = 1.0f;
+ off.clearDepth = true;
+ off.clearStencil = true;
g_device->beginRenderPass(off);
g_device->endRenderPass();
@@ -199,6 +80,8 @@ void renderFrame() {
pass.clearColorValue[1] = 0.05f;
pass.clearColorValue[2] = 0.30f;
pass.clearColorValue[3] = 1.0f;
+ pass.clearDepth = true;
+ pass.clearStencil = true;
g_device->beginRenderPass(pass);
@@ -212,16 +95,36 @@ void renderFrame() {
// Act 2: batch twin — two quads in ONE draw, per-vertex sampler selection.
g_device->setPipeline(g_batchPipeline);
g_device->setUniformBuffer(0, g_ubo);
- g_device->bindTexture(0, g_texRed);
+ g_device->bindTexture(0, g_texChecker);
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);
+ // Act 3: the stencil mask flow (Write → Test → mid-pass reset → Test).
+ // Textures stay bound from act 2 — the shape-family pipelines must keep
+ // their group-0-only layout regardless.
+ g_device->setPipeline(g_maskWritePipeline);
+ g_device->setUniformBuffer(0, g_ubo);
+ g_device->setVertexBuffer(0, g_stencilVbo, 0);
+ g_device->setIndexBuffer(g_ibo18);
+ g_device->setStencilReference(1);
+ g_device->drawElements(6, GfxDataType::UnsignedShort, 0);
+
+ g_device->setPipeline(g_maskTestPipeline);
+ g_device->setStencilReference(1);
+ g_device->drawElements(6, GfxDataType::UnsignedShort, 12);
+
+ g_device->clearStencil(0);
+
+ g_device->setPipeline(g_maskTestPipeline);
+ g_device->setStencilReference(1);
+ g_device->drawElements(6, GfxDataType::UnsignedShort, 24);
+
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.
+ // the scene) and the emulation triangle paints only the region yellow.
RenderPassDesc scoped{};
scoped.clearColor = true;
scoped.clearColorValue[0] = 1.0f;
@@ -240,18 +143,23 @@ void renderFrame() {
}
}
-TextureHandle makeSolidTexture(u8 r, u8 g, u8 b) {
- u8 pixels[4 * 4 * 4];
- for (int i = 0; i < 16; ++i) {
- pixels[i * 4 + 0] = r;
- pixels[i * 4 + 1] = g;
- pixels[i * 4 + 2] = b;
- pixels[i * 4 + 3] = 255;
+TextureHandle makeCheckerTexture() {
+ // 2x2 red/blue checker sampled NEAREST: texel centers sit at uv 0.25/0.75,
+ // so any off-center sample point separates nearest (pure texel) from
+ // linear (a visible blend) — the sampler-cache pixel assert.
+ const u8 red[4] = {255, 0, 0, 255};
+ const u8 blue[4] = {0, 0, 255, 255};
+ u8 pixels[2 * 2 * 4];
+ const u8* rows[4] = {red, blue, blue, red};
+ for (int i = 0; i < 4; ++i) {
+ for (int c = 0; c < 4; ++c) pixels[i * 4 + c] = rows[i][c];
}
TextureDesc td{};
- td.width = 4;
- td.height = 4;
+ td.width = 2;
+ td.height = 2;
td.format = GfxPixelFormat::RGBA8;
+ td.minFilter = TextureFilter::Nearest;
+ td.magFilter = TextureFilter::Nearest;
return g_device->createTexture(td, pixels);
}
@@ -287,7 +195,7 @@ int main() {
g_shapeVbo = device.createBuffer({GfxBufferUsage::Vertex, sizeof(shapeVerts), false}, shapeVerts);
g_ibo6 = device.createBuffer({GfxBufferUsage::Index, sizeof(quadIdx), false}, quadIdx);
- // --- Batch scene: left quad samples slot 0 (red), right quad slot 1 (green).
+ // --- Batch scene: left quad samples slot 0 (checker), right quad slot 1 (green).
const u32 white = 0xFFFFFFFFu;
const BatchVertex batchVerts[8] = {
{-0.9f, -0.9f, white, 0, 0, 0}, {-0.1f, -0.9f, white, 1, 0, 0},
@@ -299,28 +207,63 @@ int main() {
g_batchVbo = device.createBuffer({GfxBufferUsage::Vertex, sizeof(batchVerts), false}, batchVerts);
g_ibo12 = device.createBuffer({GfxBufferUsage::Index, sizeof(batchIdx), false}, batchIdx);
- g_texRed = makeSolidTexture(255, 0, 0);
+ // --- Stencil scene (SDF rects, shapeType 2 with radius 0): quad 0 = the
+ // mask (top-left), quad 1 = an oversized cyan rect testing INTO the mask,
+ // quad 2 = an orange rect drawn after the mid-pass stencil reset (top-right,
+ // must stay invisible).
+ auto rect = [](f32 x0, f32 y0, f32 x1, f32 y1, f32 r, f32 g, f32 b) {
+ return std::array<ShapeVertex, 4>{{
+ {x0, y0, -1, -1, r, g, b, 1, 2, 100, 100, 0},
+ {x1, y0, 1, -1, r, g, b, 1, 2, 100, 100, 0},
+ {x1, y1, 1, 1, r, g, b, 1, 2, 100, 100, 0},
+ {x0, y1, -1, 1, r, g, b, 1, 2, 100, 100, 0},
+ }};
+ };
+ ShapeVertex stencilVerts[12];
+ const auto mask = rect(-0.9f, 0.5f, -0.5f, 0.9f, 1, 1, 1);
+ const auto cyan = rect(-0.95f, 0.45f, -0.3f, 0.95f, 0, 1, 1);
+ const auto orange = rect(0.3f, 0.45f, 0.95f, 0.95f, 1, 0.5f, 0);
+ for (int i = 0; i < 4; ++i) {
+ stencilVerts[i] = mask[i];
+ stencilVerts[4 + i] = cyan[i];
+ stencilVerts[8 + i] = orange[i];
+ }
+ const u16 stencilIdx[18] = {0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 10, 11, 8};
+ g_stencilVbo = device.createBuffer({GfxBufferUsage::Vertex, sizeof(stencilVerts), false}, stencilVerts);
+ g_ibo18 = device.createBuffer({GfxBufferUsage::Index, sizeof(stencilIdx), false}, stencilIdx);
+
+ g_texChecker = makeCheckerTexture();
// The right quad's texture is RENDERED, not uploaded: an offscreen target
- // cleared green by pass A each frame.
+ // cleared green by pass A each frame — now with depth-stencil planes.
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) {
+ TextureDesc offDepthDesc{};
+ offDepthDesc.width = 4;
+ offDepthDesc.height = 4;
+ offDepthDesc.format = GfxPixelFormat::Depth24Stencil8;
+ g_texOffscreenDepth = device.createTexture(offDepthDesc, nullptr);
+ if (g_texChecker == TextureHandle::Invalid || g_texOffscreen == TextureHandle::Invalid ||
+ g_texOffscreenDepth == TextureHandle::Invalid) {
std::printf("BRINGUP_FAIL textures\n");
return 1;
}
FramebufferDesc fbDesc{};
fbDesc.color0 = g_texOffscreen;
+ fbDesc.depthStencil = g_texOffscreenDepth;
g_offscreenFb = device.createFramebuffer(fbDesc);
- // --- Programs + layouts + pipelines (the engine's streams, byte for byte).
+ // --- Programs + layouts + pipelines (the engine's streams, byte for byte,
+ // with the engine's WGSL twins).
ShaderHandle shapeProgram = device.createProgram(
- GfxShaderSource{GfxShaderLanguage::WGSL, kShapeWGSL_Vertex, kShapeWGSL_Fragment},
+ GfxShaderSource{GfxShaderLanguage::WGSL,
+ webgpu::kShapeWGSL_Vertex, webgpu::kShapeWGSL_Fragment},
nullptr, 0, nullptr, nullptr);
ShaderHandle batchProgram = device.createProgram(
- GfxShaderSource{GfxShaderLanguage::WGSL, kBatchWGSL_Vertex, kBatchWGSL_Fragment},
+ GfxShaderSource{GfxShaderLanguage::WGSL,
+ webgpu::kBatchWGSL_Vertex, webgpu::kBatchWGSL_Fragment},
nullptr, 0, nullptr, nullptr);
if (shapeProgram == ShaderHandle::Invalid || batchProgram == ShaderHandle::Invalid) {
std::printf("BRINGUP_FAIL programs\n");
@@ -353,6 +296,17 @@ int main() {
batchPd.vertexLayout = device.createVertexLayout(batchLayout);
g_batchPipeline = device.createPipeline(batchPd);
+ // The mask pipelines are the shape pipeline in the engine's two stencil
+ // modes (Write = no color, Replace; Test = Equal, keep) — the same
+ // PipelineDesc split DrawList uses for mask draws.
+ PipelineDesc maskWritePd = shapePd;
+ maskWritePd.stencil = GfxStencilMode::Write;
+ g_maskWritePipeline = device.createPipeline(maskWritePd);
+
+ PipelineDesc maskTestPd = shapePd;
+ maskTestPd.stencil = GfxStencilMode::Test;
+ g_maskTestPipeline = device.createPipeline(maskTestPd);
+
std::printf("BRINGUP_INIT_OK\n");
emscripten_set_main_loop(renderFrame, 0, /*simulate_infinite_loop=*/false);
return 0;