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.

fix(render): textures are mipmapped on WebGPU

esengineb0b73cd591c8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 755e79165..5833a898a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,9 +23,10 @@ published separately; it ships inside the editor.
### Fixed
+- Textures are sampled through mip levels on WebGPU. The device built no chain for an image it uploaded, and the built-in material shaders read level 0 even of a KTX2 that carried one, so every texture drawn smaller than itself shimmered on WebGPU. An image now gets its chain on upload, rebuilt when its pixels change, and the Sprite, Lit, Outline, Dissolve, UV Scroll and Model shaders sample through it; Pixelate keeps level 0, which is its look. Khronos's AlphaBlendModeTest forty metres off shimmers as little on WebGPU as on WebGL2.
- WebGPU post-processing keeps the picture the right way up. Every fullscreen pass sampled its input upside down, so a frame came out inverted whenever its chain had an odd number of them — a linear project with no post-process effect, for one — and an effect that reads depth, such as SSAO or distance fog, laid its result over the colour mirrored.
- Ambient occlusion works behind another post-process effect. The scene's image went back to the pool after the last pass that read its colour, taking its depth with it, so an SSAO placed after a colour grade — as ORCA Bistro's volume has it — found no depth and occluded nothing, at any radius or intensity. The scene now lives until the chain's last pass.
-- A shipped game's textures are sampled through mip levels. An image the engine uploads itself — in a web export, a mini-game and the editor's Play — got no mip chain on WebGL2, so a texture drawn smaller than itself took one texel per pixel: in ORCA Bistro the trees turned to noise and the shutters to broken bright lines, while the editor's viewport, which uploads through its own path, looked right. The chain is now built from the pixels and rebuilt whenever they change, as that path does. WebGPU does not build one yet.
+- A shipped game's textures are sampled through mip levels. An image the engine uploads itself — in a web export, a mini-game and the editor's Play — got no mip chain on WebGL2, so a texture drawn smaller than itself took one texel per pixel: in ORCA Bistro the trees turned to noise and the shutters to broken bright lines, while the editor's viewport, which uploads through its own path, looked right. The chain is now built from the pixels and rebuilt whenever they change, as that path does.
## [0.74.0] - 2026-09-27
diff --git a/examples/physics-3d/assets/materials/decal-target.esshader b/examples/physics-3d/assets/materials/decal-target.esshader
index 879fc57df..afc0d85b0 100644
--- a/examples/physics-3d/assets/materials/decal-target.esshader
+++ b/examples/physics-3d/assets/materials/decal-target.esshader
@@ -27,7 +27,7 @@ void main() {
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 144f76db1f5f521a
-// assembled-hash: 11e880f98c97fd94
+// assembled-hash: 9d2b226ba9f613f0
struct MaterialConstants {
u_tint: vec4<f32>,
}
diff --git a/fixtures/scenes/mat-builtin-lit/lit.esshader b/fixtures/scenes/mat-builtin-lit/lit.esshader
index 19e49905d..4e59fb3a1 100644
--- a/fixtures/scenes/mat-builtin-lit/lit.esshader
+++ b/fixtures/scenes/mat-builtin-lit/lit.esshader
@@ -27,7 +27,7 @@ void main() {
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 5330079245724fa2
-// assembled-hash: f630aceaa74351b1
+// assembled-hash: 4f341ebfcf19c1f8
struct FrameConstants {
u_projection: mat4x4<f32>,
u_camera: vec4<f32>,
diff --git a/fixtures/scenes/mat-generated-mesh/split.esshader b/fixtures/scenes/mat-generated-mesh/split.esshader
index 9c7763eeb..12ce2ed44 100644
--- a/fixtures/scenes/mat-generated-mesh/split.esshader
+++ b/fixtures/scenes/mat-generated-mesh/split.esshader
@@ -22,7 +22,7 @@ void main() {
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 7af6948ea05e1a30
-// assembled-hash: 12dac50e0d49bb35
+// assembled-hash: db772a2e99ede0f9
struct MaterialConstants {
u_tint: vec4<f32>,
}
diff --git a/fixtures/scenes/mat-lit-flatnormal/lit-fn.esshader b/fixtures/scenes/mat-lit-flatnormal/lit-fn.esshader
index fa4552bed..e419adcd4 100644
--- a/fixtures/scenes/mat-lit-flatnormal/lit-fn.esshader
+++ b/fixtures/scenes/mat-lit-flatnormal/lit-fn.esshader
@@ -47,7 +47,7 @@ void main() {
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: a8853729e0f76d55
-// assembled-hash: 7018c9fe2d0593dc
+// assembled-hash: b3b46cf005738836
struct gl_PerVertex {
@builtin(position) gl_Position: vec4<f32>,
gl_PointSize: f32,
@@ -123,7 +123,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: a8853729e0f76d55
-// assembled-hash: 7018c9fe2d0593dc
+// assembled-hash: b3b46cf005738836
struct FrameConstants {
u_projection: mat4x4<f32>,
u_camera: vec4<f32>,
diff --git a/fixtures/scenes/mat-lit-normal/lit-normal.esshader b/fixtures/scenes/mat-lit-normal/lit-normal.esshader
index c1e8d08cc..c9e6dd081 100644
--- a/fixtures/scenes/mat-lit-normal/lit-normal.esshader
+++ b/fixtures/scenes/mat-lit-normal/lit-normal.esshader
@@ -47,7 +47,7 @@ void main() {
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 577c1ff7b66006ff
-// assembled-hash: ae6a70cd0e4bbc69
+// assembled-hash: 5f7a9a4e82a4b110
struct gl_PerVertex {
@builtin(position) gl_Position: vec4<f32>,
gl_PointSize: f32,
@@ -123,7 +123,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 577c1ff7b66006ff
-// assembled-hash: ae6a70cd0e4bbc69
+// assembled-hash: 5f7a9a4e82a4b110
struct FrameConstants {
u_projection: mat4x4<f32>,
u_camera: vec4<f32>,
diff --git a/fixtures/scenes/mat-lit/lit.esshader b/fixtures/scenes/mat-lit/lit.esshader
index 09701467b..2fd42f9d7 100644
--- a/fixtures/scenes/mat-lit/lit.esshader
+++ b/fixtures/scenes/mat-lit/lit.esshader
@@ -53,7 +53,7 @@ void main() {
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 8c118f2b442c055e
-// assembled-hash: fa2a2c85e10fb0e9
+// assembled-hash: f57668e95653c702
struct gl_PerVertex {
@builtin(position) gl_Position: vec4<f32>,
gl_PointSize: f32,
@@ -125,7 +125,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 8c118f2b442c055e
-// assembled-hash: fa2a2c85e10fb0e9
+// assembled-hash: f57668e95653c702
struct FrameConstants {
u_projection: mat4x4<f32>,
u_camera: vec4<f32>,
diff --git a/sdk/src/render/builtinShaders.ts b/sdk/src/render/builtinShaders.ts
index c69d619b8..c0a2a132b 100644
--- a/sdk/src/render/builtinShaders.ts
+++ b/sdk/src/render/builtinShaders.ts
@@ -70,7 +70,10 @@ void main() {
#pragma fragment wgsl
@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
- return textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color * mc.u_tint;
+ // Taken before any branch: a derivative needs every fragment of its quad.
+ let duvx = dpdx(v.v_texCoord);
+ let duvy = dpdy(v.v_texCoord);
+ return textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy) * v.v_color * mc.u_tint;
}
#pragma end
`;
@@ -115,13 +118,16 @@ void main() {
#pragma fragment wgsl
@fragment fn fs_main(v : VSOut, @builtin(front_facing) front : bool) -> @location(0) vec4f {
- let base = textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color * mc.u_tint;
+ // Taken before any branch: a derivative needs every fragment of its quad.
+ let duvx = dpdx(v.v_texCoord);
+ let duvy = dpdy(v.v_texCoord);
+ let base = textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy) * v.v_color * mc.u_tint;
#ifdef MESH_NORMALS
var N = perturbNormal(normalize(v.v_worldNormal), v.v_worldXYZ, v.v_texCoord,
- sampleNormal(u_normalMap, u_normalMap_s, v.v_texCoord));
+ sampleNormalGrad(u_normalMap, u_normalMap_s, v.v_texCoord, duvx, duvy));
if (!front) { N = -N; }
#else
- let N = sampleNormal(u_normalMap, u_normalMap_s, v.v_texCoord);
+ let N = sampleNormalGrad(u_normalMap, u_normalMap_s, v.v_texCoord, duvx, duvy);
#endif
return vec4f(applyLighting2D(base.rgb, N, v.v_worldPos), base.a);
}
@@ -153,7 +159,10 @@ void main() {
#pragma fragment wgsl
@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
- let base = textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color;
+ // Taken before any branch: a derivative needs every fragment of its quad.
+ let duvx = dpdx(v.v_texCoord);
+ let duvy = dpdy(v.v_texCoord);
+ let base = textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy) * v.v_color;
return vec4f(mix(base.rgb, mc.u_flashColor.rgb, mc.u_flash), base.a);
}
#pragma end
@@ -193,17 +202,20 @@ void main() {
#pragma fragment wgsl
@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
- let base = textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color;
+ // Taken before any branch: a derivative needs every fragment of its quad.
+ let duvx = dpdx(v.v_texCoord);
+ let duvy = dpdy(v.v_texCoord);
+ let base = textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy) * v.v_color;
let texel = mc.u_outlineWidth / vec2f(textureDimensions(t0, 0));
var edge = 0.0;
- edge = max(edge, textureSampleLevel(t0, s0, v.v_texCoord + vec2f( texel.x, 0.0), 0.0).a);
- edge = max(edge, textureSampleLevel(t0, s0, v.v_texCoord + vec2f(-texel.x, 0.0), 0.0).a);
- edge = max(edge, textureSampleLevel(t0, s0, v.v_texCoord + vec2f(0.0, texel.y), 0.0).a);
- edge = max(edge, textureSampleLevel(t0, s0, v.v_texCoord + vec2f(0.0, -texel.y), 0.0).a);
- edge = max(edge, textureSampleLevel(t0, s0, v.v_texCoord + vec2f( texel.x, texel.y), 0.0).a);
- edge = max(edge, textureSampleLevel(t0, s0, v.v_texCoord + vec2f( texel.x, -texel.y), 0.0).a);
- edge = max(edge, textureSampleLevel(t0, s0, v.v_texCoord + vec2f(-texel.x, texel.y), 0.0).a);
- edge = max(edge, textureSampleLevel(t0, s0, v.v_texCoord + vec2f(-texel.x, -texel.y), 0.0).a);
+ edge = max(edge, textureSampleGrad(t0, s0, v.v_texCoord + vec2f( texel.x, 0.0), duvx, duvy).a);
+ edge = max(edge, textureSampleGrad(t0, s0, v.v_texCoord + vec2f(-texel.x, 0.0), duvx, duvy).a);
+ edge = max(edge, textureSampleGrad(t0, s0, v.v_texCoord + vec2f(0.0, texel.y), duvx, duvy).a);
+ edge = max(edge, textureSampleGrad(t0, s0, v.v_texCoord + vec2f(0.0, -texel.y), duvx, duvy).a);
+ edge = max(edge, textureSampleGrad(t0, s0, v.v_texCoord + vec2f( texel.x, texel.y), duvx, duvy).a);
+ edge = max(edge, textureSampleGrad(t0, s0, v.v_texCoord + vec2f( texel.x, -texel.y), duvx, duvy).a);
+ edge = max(edge, textureSampleGrad(t0, s0, v.v_texCoord + vec2f(-texel.x, texel.y), duvx, duvy).a);
+ edge = max(edge, textureSampleGrad(t0, s0, v.v_texCoord + vec2f(-texel.x, -texel.y), duvx, duvy).a);
return mix(vec4f(mc.u_outlineColor.rgb, edge * mc.u_outlineColor.a), base, base.a);
}
#pragma end
@@ -258,7 +270,10 @@ fn noise2d(p : vec2f) -> f32 {
}
@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
- let base = textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color;
+ // Taken before any branch: a derivative needs every fragment of its quad.
+ let duvx = dpdx(v.v_texCoord);
+ let duvy = dpdy(v.v_texCoord);
+ let base = textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy) * v.v_color;
let n = noise2d(v.v_texCoord * mc.u_noiseScale);
let cut = mc.u_progress * (1.0 + mc.u_edgeWidth);
if (n < cut - mc.u_edgeWidth) { discard; }
@@ -321,8 +336,11 @@ void main() {
#pragma fragment wgsl
@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ // Taken before any branch: a derivative needs every fragment of its quad.
+ let duvx = dpdx(v.v_texCoord);
+ let duvy = dpdy(v.v_texCoord);
let uv = fract(v.v_texCoord + tc.u_time.x * mc.u_scrollSpeed);
- return textureSampleLevel(t0, s0, uv, 0.0) * v.v_color;
+ return textureSampleGrad(t0, s0, uv, duvx, duvy) * v.v_color;
}
#pragma end
`;
@@ -400,11 +418,14 @@ void main() {
#pragma fragment wgsl
@fragment fn fs_main(v : VSOut, @builtin(front_facing) front : bool) -> @location(0) vec4f {
+ // Taken before any branch: a derivative needs every fragment of its quad.
+ let duvx = dpdx(v.v_texCoord);
+ let duvy = dpdy(v.v_texCoord);
// WGSL has no module varying: the entry point hands the injected header the
// run its GLSL twin reads straight off one. Without this every material-shaded
// draw read instance 0's indirect light — one probe volume for the lot.
g_probeSlot = v.v_probeSlot;
- let base = textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color * mc.u_tint;
+ let base = textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy) * v.v_color * mc.u_tint;
// Before any discard: a derivative needs every fragment of its quad.
let edge = max(fwidth(base.a), 1e-4);
var alpha = base.a;
@@ -415,15 +436,14 @@ void main() {
}
#ifdef MESH_NORMALS
var N = perturbNormal(normalize(v.v_worldNormal), v.v_worldXYZ, v.v_texCoord,
- sampleNormal(u_normalMap, u_normalMap_s, v.v_texCoord));
+ sampleNormalGrad(u_normalMap, u_normalMap_s, v.v_texCoord, duvx, duvy));
if (!front) { N = -N; }
#else
- let N = sampleNormal(u_normalMap, u_normalMap_s, v.v_texCoord);
+ let N = sampleNormalGrad(u_normalMap, u_normalMap_s, v.v_texCoord, duvx, duvy);
#endif
- let occl = textureSampleLevel(u_occlusionMap, u_occlusionMap_s, v.v_texCoord, 0.0).r;
+ let occl = textureSampleGrad(u_occlusionMap, u_occlusionMap_s, v.v_texCoord, duvx, duvy).r;
let ao = mix(1.0, occl, mc.u_occlusionStrength);
- let mr = textureSampleLevel(u_metallicRoughnessMap, u_metallicRoughnessMap_s,
- v.v_texCoord, 0.0).rgb;
+ let mr = textureSampleGrad(u_metallicRoughnessMap, u_metallicRoughnessMap_s, v.v_texCoord, duvx, duvy).rgb;
#ifdef MESH_NORMALS
let P = v.v_worldXYZ;
#else
@@ -432,7 +452,7 @@ void main() {
let lit = applyLightingPBR(base.rgb, N, P, viewDirection(P),
mc.u_metallic * mr.b, mc.u_roughness * mr.g, 1.0, ao);
let emit = mc.u_emissive.rgb
- * textureSampleLevel(u_emissiveMap, u_emissiveMap_s, v.v_texCoord, 0.0).rgb;
+ * textureSampleGrad(u_emissiveMap, u_emissiveMap_s, v.v_texCoord, duvx, duvy).rgb;
return vec4f(lit + emit, alpha);
}
#pragma end
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
index 25b58668a..c3a4d8c6e 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
@@ -238,6 +238,14 @@ void WebGPUDevice::releaseDeviceObjects() {
if (depth_resolve_bgl_) { wgpuBindGroupLayoutRelease(depth_resolve_bgl_); depth_resolve_bgl_ = nullptr; }
if (depth_resolve_vs_) { wgpuShaderModuleRelease(depth_resolve_vs_); depth_resolve_vs_ = nullptr; }
if (depth_resolve_fs_) { wgpuShaderModuleRelease(depth_resolve_fs_); depth_resolve_fs_ = nullptr; }
+ for (auto& [key, pipeline] : mip_pipelines_) {
+ if (pipeline) wgpuRenderPipelineRelease(pipeline);
+ }
+ mip_pipelines_.clear();
+ if (mip_layout_) { wgpuPipelineLayoutRelease(mip_layout_); mip_layout_ = nullptr; }
+ if (mip_bgl_) { wgpuBindGroupLayoutRelease(mip_bgl_); mip_bgl_ = nullptr; }
+ if (mip_module_) { wgpuShaderModuleRelease(mip_module_); mip_module_ = nullptr; }
+ if (mip_sampler_) { wgpuSamplerRelease(mip_sampler_); mip_sampler_ = nullptr; }
for (auto& [key, layout] : pipeline_layouts_) {
if (layout) wgpuPipelineLayoutRelease(layout);
}
@@ -829,8 +837,11 @@ bool WebGPUDevice::makeTexture(const TextureDesc& desc, const void* pixels, Text
td.dimension = WGPUTextureDimension_2D;
td.format = toWGPUTextureFormat(desc.format);
td.size = WGPUExtent3D{desc.width, desc.height, 1};
- td.mipLevelCount = 1;
td.sampleCount = desc.samples > 1 ? kMsaaSamples : 1;
+ td.mipLevelCount = 1;
+ if (desc.mipmaps && td.sampleCount == 1 && !isDepthFormat(td.format)) {
+ for (u32 side = std::max(desc.width, desc.height); side > 1; side >>= 1) ++td.mipLevelCount;
+ }
// Depth-stencil takes no upload and no readback (writeTexture cannot fill
// it, CopySrc is refused on depth24plus) but IS sampled: an effect reads the
// scene's depth. Colour carries CopySrc for the async readback seam.
@@ -853,7 +864,18 @@ bool WebGPUDevice::makeTexture(const TextureDesc& desc, const void* pixels, Text
return false;
}
- WGPUTextureView view = wgpuTextureCreateView(texture, nullptr);
+ WGPUTextureView view = nullptr;
+ if (td.mipLevelCount > 1) {
+ WGPUTextureViewDescriptor vd{};
+ vd.format = td.format;
+ vd.dimension = WGPUTextureViewDimension_2D;
+ vd.mipLevelCount = 1;
+ vd.arrayLayerCount = 1;
+ vd.aspect = WGPUTextureAspect_All;
+ view = wgpuTextureCreateView(texture, &vd);
+ } else {
+ view = wgpuTextureCreateView(texture, nullptr);
+ }
// A depth-stencil texture has two aspects and a sample may name only one, so
// the view a binding uses is depth-only. Every other format samples through
// the view it already has — the two members alias, and cleanup knows it.
@@ -871,17 +893,20 @@ bool WebGPUDevice::makeTexture(const TextureDesc& desc, const void* pixels, Text
vd.arrayLayerCount = 1;
vd.aspect = WGPUTextureAspect_DepthOnly;
sampleView = wgpuTextureCreateView(texture, &vd);
+ } else if (td.mipLevelCount > 1) {
+ sampleView = wgpuTextureCreateView(texture, nullptr);
}
out = TextureRec{texture, view, sampleView,
desc.width, desc.height, td.format, desc.format,
packSamplerKey(desc.minFilter, desc.magFilter, desc.wrapS, desc.wrapT),
- td.sampleCount};
+ td.sampleCount, td.mipLevelCount};
if (pixels && !isDepthFormat(td.format)) {
// desc.flipY, not false: the caller's orientation request has to reach the
// upload, which is where the row reversal happens (see writeTexture).
writeTexture(out, 0, 0, desc.width, desc.height, pixels, desc.flipY);
+ if (out.mipLevels > 1) buildMipChain(out);
}
return true;
}
@@ -1048,7 +1073,10 @@ void WebGPUDevice::backendSetTextureParams(u32 id, const TextureDesc& desc) {
}
}
-void WebGPUDevice::backendGenerateMipmaps(u32) { stubOnce("generateMipmaps"); }
+void WebGPUDevice::backendGenerateMipmaps(u32 id) {
+ auto it = textures_.find(id);
+ if (it != textures_.end() && it->second.mipLevels > 1) buildMipChain(it->second);
+}
void WebGPUDevice::bindTexture(u32 slot, TextureHandle texture) {
if (slot >= kTextureSlots) return;
@@ -1391,6 +1419,152 @@ WGPURenderPipeline WebGPUDevice::ensureDepthResolvePipeline(WGPUTextureFormat fo
return pipeline;
}
+WGPURenderPipeline WebGPUDevice::ensureMipPipeline(WGPUTextureFormat format) {
+ const u32 key = static_cast<u32>(format);
+ auto it = mip_pipelines_.find(key);
+ if (it != mip_pipelines_.end()) return it->second;
+ if (!device_) return nullptr;
+
+ // The triangle's uv runs down the target as its rows do, so a level keeps the
+ // orientation of the one it is made from.
+ static const char* kWGSL = R"(
+struct VSOut { @builtin(position) pos : vec4f, @location(0) uv : vec2f };
+@vertex fn vs_main(@builtin(vertex_index) i : u32) -> VSOut {
+ var p = array<vec2f, 3>(vec2f(-1.0, 1.0), vec2f(3.0, 1.0), vec2f(-1.0, -3.0));
+ var out : VSOut;
+ out.pos = vec4f(p[i], 0.0, 1.0);
+ out.uv = vec2f(p[i].x * 0.5 + 0.5, 0.5 - p[i].y * 0.5);
+ return out;
+}
+@group(0) @binding(0) var src : texture_2d<f32>;
+@group(0) @binding(1) var smp : sampler;
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ return textureSampleLevel(src, smp, v.uv, 0.0);
+}
+)";
+ if (!mip_module_) {
+ WGPUShaderSourceWGSL wgsl{};
+ wgsl.chain.sType = WGPUSType_ShaderSourceWGSL;
+ wgsl.code = sv(kWGSL);
+ WGPUShaderModuleDescriptor md{};
+ md.nextInChain = &wgsl.chain;
+ mip_module_ = wgpuDeviceCreateShaderModule(device_, &md);
+ }
+ if (!mip_bgl_) {
+ WGPUBindGroupLayoutEntry entries[2]{};
+ entries[0].binding = 0;
+ entries[0].visibility = WGPUShaderStage_Fragment;
+ entries[0].texture.sampleType = WGPUTextureSampleType_Float;
+ entries[0].texture.viewDimension = WGPUTextureViewDimension_2D;
+ entries[1].binding = 1;
+ entries[1].visibility = WGPUShaderStage_Fragment;
+ entries[1].sampler.type = WGPUSamplerBindingType_Filtering;
+ WGPUBindGroupLayoutDescriptor bld{};
+ bld.entryCount = 2;
+ bld.entries = entries;
+ mip_bgl_ = wgpuDeviceCreateBindGroupLayout(device_, &bld);
+ WGPUPipelineLayoutDescriptor pld{};
+ pld.bindGroupLayoutCount = 1;
+ pld.bindGroupLayouts = &mip_bgl_;
+ mip_layout_ = wgpuDeviceCreatePipelineLayout(device_, &pld);
+ WGPUSamplerDescriptor sd{};
+ sd.minFilter = WGPUFilterMode_Linear;
+ sd.magFilter = WGPUFilterMode_Linear;
+ sd.mipmapFilter = WGPUMipmapFilterMode_Nearest;
+ sd.addressModeU = WGPUAddressMode_ClampToEdge;
+ sd.addressModeV = WGPUAddressMode_ClampToEdge;
+ sd.addressModeW = WGPUAddressMode_ClampToEdge;
+ sd.lodMaxClamp = 32.0f;
+ sd.maxAnisotropy = 1;
+ mip_sampler_ = wgpuDeviceCreateSampler(device_, &sd);
+ }
+
+ WGPURenderPipelineDescriptor pd{};
+ pd.layout = mip_layout_;
+ pd.vertex.module = mip_module_;
+ 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;
+ WGPUColorTargetState target{};
+ target.format = format;
+ target.writeMask = WGPUColorWriteMask_All;
+ WGPUFragmentState fragment{};
+ fragment.module = mip_module_;
+ fragment.entryPoint = sv("fs_main");
+ fragment.targetCount = 1;
+ fragment.targets = &target;
+ pd.fragment = &fragment;
+
+ WGPURenderPipeline pipeline = wgpuDeviceCreateRenderPipeline(device_, &pd);
+ if (!pipeline) ES_LOG_ERROR("WebGPUDevice: mip pipeline creation failed");
+ mip_pipelines_[key] = pipeline;
+ return pipeline;
+}
+
+void WebGPUDevice::buildMipChain(const TextureRec& rec) {
+ if (!device_ || !queue_ || rec.mipLevels < 2) return;
+ WGPURenderPipeline pipeline = ensureMipPipeline(rec.format);
+ if (!pipeline) return;
+
+ // Its own encoder, submitted at once: an upload can land in the middle of a
+ // frame, and the frame's encoder may have a pass open.
+ WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_, nullptr);
+ if (!encoder) return;
+ std::vector<WGPUTextureView> views;
+ std::vector<WGPUBindGroup> groups;
+ for (u32 level = 0; level < rec.mipLevels; ++level) {
+ WGPUTextureViewDescriptor vd{};
+ vd.format = rec.format;
+ vd.dimension = WGPUTextureViewDimension_2D;
+ vd.baseMipLevel = level;
+ vd.mipLevelCount = 1;
+ vd.arrayLayerCount = 1;
+ vd.aspect = WGPUTextureAspect_All;
+ views.push_back(wgpuTextureCreateView(rec.texture, &vd));
+ }
+ for (u32 level = 1; level < rec.mipLevels; ++level) {
+ WGPUBindGroupEntry entries[2]{};
+ entries[0].binding = 0;
+ entries[0].textureView = views[level - 1];
+ entries[1].binding = 1;
+ entries[1].sampler = mip_sampler_;
+ WGPUBindGroupDescriptor bgd{};
+ bgd.layout = mip_bgl_;
+ bgd.entryCount = 2;
+ bgd.entries = entries;
+ WGPUBindGroup group = wgpuDeviceCreateBindGroup(device_, &bgd);
+ if (!group) break;
+ groups.push_back(group);
+
+ WGPURenderPassColorAttachment color{};
+ color.view = views[level];
+ color.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
+ color.loadOp = WGPULoadOp_Clear;
+ color.storeOp = WGPUStoreOp_Store;
+ WGPURenderPassDescriptor rp{};
+ rp.colorAttachmentCount = 1;
+ rp.colorAttachments = &color;
+ WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(encoder, &rp);
+ if (!pass) break;
+ wgpuRenderPassEncoderSetPipeline(pass, pipeline);
+ wgpuRenderPassEncoderSetBindGroup(pass, 0, group, 0, nullptr);
+ wgpuRenderPassEncoderDraw(pass, 3, 1, 0, 0);
+ wgpuRenderPassEncoderEnd(pass);
+ wgpuRenderPassEncoderRelease(pass);
+ }
+ WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder, nullptr);
+ if (commands) {
+ wgpuQueueSubmit(queue_, 1, &commands);
+ wgpuCommandBufferRelease(commands);
+ }
+ wgpuCommandEncoderRelease(encoder);
+ for (WGPUBindGroup group : groups) wgpuBindGroupRelease(group);
+ for (WGPUTextureView view : views) wgpuTextureViewRelease(view);
+}
+
void WebGPUDevice::resolveDepthAttachment(u32 msaaDepth, u32 resolveDepth) {
if (!device_ || !encoder_) return;
auto srcIt = textures_.find(msaaDepth);
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.hpp b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
index 9a833fb45..a86b8f4d2 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.hpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
@@ -354,6 +354,9 @@ private:
u8 samplerKey = 0; ///< Packed filter/wrap params (sampler cache key).
/// 1, or kMsaaSamples for an attachment drawn into and resolved out of.
u32 samples = 1;
+ /// 1, or the whole chain for a texture that declared mipmaps. `view` is
+ /// then level 0 alone (an attachment is one level) and `sampleView` all.
+ u32 mipLevels = 1;
};
struct ProgramRec {
WGPUShaderModule vertex = nullptr;
@@ -532,6 +535,15 @@ private:
* multisampled target. WebGPU has no depth resolve of its own. */
void resolveDepthAttachment(u32 msaaDepth, u32 resolveDepth);
WGPURenderPipeline ensureDepthResolvePipeline(WGPUTextureFormat format);
+ /** @brief Fills every level below 0 from the one above, a linear sample at each
+ * texel's centre — a box average of the four under it. */
+ void buildMipChain(const TextureRec& rec);
+ WGPURenderPipeline ensureMipPipeline(WGPUTextureFormat format);
+ WGPUShaderModule mip_module_ = nullptr;
+ WGPUBindGroupLayout mip_bgl_ = nullptr;
+ WGPUPipelineLayout mip_layout_ = nullptr;
+ WGPUSampler mip_sampler_ = nullptr;
+ std::unordered_map<u32, WGPURenderPipeline> mip_pipelines_;
WGPUShaderModule depth_resolve_vs_ = nullptr;
WGPUShaderModule depth_resolve_fs_ = nullptr;
WGPUBindGroupLayout depth_resolve_bgl_ = nullptr;
diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cpp
index 83d4e925e..2c713b469 100644
--- a/src/esengine/resource/ShaderParser.cpp
+++ b/src/esengine/resource/ShaderParser.cpp
@@ -1211,6 +1211,12 @@ fn sampleNormal(map : texture_2d<f32>, samp : sampler, uv : vec2f) -> vec3f {
let xy = textureSampleLevel(map, samp, uv, 0.0).xy * 2.0 - 1.0;
return vec3f(xy, sqrt(max(0.0, 1.0 - dot(xy, xy))));
}
+// Through the mip chain, with gradients the caller took before any branch.
+fn sampleNormalGrad(map : texture_2d<f32>, samp : sampler, uv : vec2f,
+ ddx : vec2f, ddy : vec2f) -> vec3f {
+ let xy = textureSampleGrad(map, samp, uv, ddx, ddy).xy * 2.0 - 1.0;
+ return vec3f(xy, sqrt(max(0.0, 1.0 - dot(xy, xy))));
+}
fn perturbNormal(N : vec3f, worldPos : vec3f, uv : vec2f, tangentNormal : vec3f) -> vec3f {
let dp1 = dpdx(worldPos);
// Negated: this backend's framebuffer y runs the other way, so dpdy answers
@@ -2044,6 +2050,11 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p
" highp vec2 xy = texture(map, uv).xy * 2.0 - 1.0;\n"
" return vec3(xy, sqrt(max(0.0, 1.0 - dot(xy, xy))));\n"
"}\n"
+ "highp vec3 sampleNormalGrad(in highp sampler2D map, in highp vec2 uv,\n"
+ " in highp vec2 ddx, in highp vec2 ddy) {\n"
+ " highp vec2 xy = textureGrad(map, uv, ddx, ddy).xy * 2.0 - 1.0;\n"
+ " return vec3(xy, sqrt(max(0.0, 1.0 - dot(xy, xy))));\n"
+ "}\n"
// Tangent frame from screen-space derivatives, so a tangent-space normal
// lands in world space without the geometry carrying a tangent channel —
// which most exported models do not. Degenerate UVs return N unchanged.
diff --git a/tools/check-shader-blocks.mjs b/tools/check-shader-blocks.mjs
index 7ebea5033..453601e55 100644
--- a/tools/check-shader-blocks.mjs
+++ b/tools/check-shader-blocks.mjs
@@ -96,6 +96,7 @@ const ALIASES = {
*/
const SIGNATURE_GAPS = {
sampleNormal: 'WGSL takes the texture and its sampler apart; GLSL has one combined type',
+ sampleNormalGrad: 'WGSL takes the texture and its sampler apart; GLSL has one combined type',
};
/** A field name as the comparison sees it: the `u_` a shader adds is not part of it. */
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 4b4abfb9a..31d3904de 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -1262,6 +1262,8 @@ export const NOTED = {
{ note: 'A cutout\'s mip levels keep its coverage' },
'feat(import): images several materials share get every setting they ask for':
{ note: 'A cutout\'s mip levels keep its coverage' },
+ 'fix(render): textures are mipmapped on WebGPU':
+ { note: 'Textures are sampled through mip levels on WebGPU' },
'fix(render): WebGPU post-processing keeps the picture the right way up':
{ note: 'WebGPU post-processing keeps the picture the right way up' },
'fix(render): ambient occlusion works behind another effect':
diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjs
index 51c575b72..0ee681a6a 100644
--- a/tools/renderScenes.mjs
+++ b/tools/renderScenes.mjs
@@ -711,8 +711,8 @@ export const SCENES = [
{ id: "corpus-cutout-edge", tier: "pr", webgpu: true, corpora: ["khronos-alpha-blend-mode-test"], env: { ESTELLA_VERIFY_PREFAB: "/corpora/khronos-alpha-blend-mode-test/imported/AlphaBlendModeTest.esprefab", ESTELLA_VERIFY_SCENE: "/scenes/corpus-cutout-edge.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/corpus-alpha-modes.textures.json", ESTELLA_VERIFY_COLORSPACE: "linear", ESTELLA_VERIFY_MSAA: "4", ESTELLA_VERIFY_W: "640", ESTELLA_VERIFY_H: "640", ESTELLA_VERIFY_STEPS: "8", ESTELLA_VERIFY_CUTOUT_EDGE: "{\"box\":[0.5813,0.4219,0.6641,0.6875],\"lit\":180,\"run\":4,\"partial\":[115,180],\"minShare\":0.2}" } },
// The same asset forty metres off, its textures uploaded as a shipped game's are:
// with a mip chain the stripes average to a flat tint (ripple 7.8), sampling the top
- // level they shimmer (17.5). WebGL2 only: WebGPU builds no chain yet.
- { id: "corpus-distant-texture", tier: "pr", webgpu: false, corpora: ["khronos-alpha-blend-mode-test"], env: { ESTELLA_VERIFY_PREFAB: "/corpora/khronos-alpha-blend-mode-test/imported/AlphaBlendModeTest.esprefab", ESTELLA_VERIFY_SCENE: "/scenes/corpus-distant-texture.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/corpus-alpha-modes.textures.json", ESTELLA_VERIFY_COLORSPACE: "linear", ESTELLA_VERIFY_TEXTURES: "runtime", ESTELLA_VERIFY_W: "640", ESTELLA_VERIFY_H: "640", ESTELLA_VERIFY_STEPS: "8", ESTELLA_VERIFY_MINIFIED: "{\"box\":[0.469,0.461,0.688,0.516],\"maxRipple\":11,\"minMean\":100}" } },
+ // level they shimmer (17.5); 7.9 on WebGPU, 13.7 before it built a chain.
+ { id: "corpus-distant-texture", tier: "pr", webgpu: true, corpora: ["khronos-alpha-blend-mode-test"], env: { ESTELLA_VERIFY_PREFAB: "/corpora/khronos-alpha-blend-mode-test/imported/AlphaBlendModeTest.esprefab", ESTELLA_VERIFY_SCENE: "/scenes/corpus-distant-texture.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/corpus-alpha-modes.textures.json", ESTELLA_VERIFY_COLORSPACE: "linear", ESTELLA_VERIFY_TEXTURES: "runtime", ESTELLA_VERIFY_W: "640", ESTELLA_VERIFY_H: "640", ESTELLA_VERIFY_STEPS: "8", ESTELLA_VERIFY_MINIFIED: "{\"box\":[0.469,0.461,0.688,0.516],\"maxRipple\":11,\"minMean\":100}" } },
// Khronos's AlphaBlendModeTest (tools/corpora.mjs): the opaque box ignores its alpha, and
// each cutout box is cut exactly at its own threshold — wall above the mark, stripes below.
{ id: "corpus-alpha-modes", tier: "pr", webgpu: true, corpora: ["khronos-alpha-blend-mode-test"], env: { ESTELLA_VERIFY_PREFAB: "/corpora/khronos-alpha-blend-mode-test/imported/AlphaBlendModeTest.esprefab", ESTELLA_VERIFY_SCENE: "/scenes/corpus-alpha-modes.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/corpus-alpha-modes.textures.json", ESTELLA_VERIFY_W: "960", ESTELLA_VERIFY_H: "540", ESTELLA_VERIFY_STEPS: "8", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.2344,\"y\":0.3185,\"rgb\":[255,255,107],\"tol\":40},{\"x\":0.5135,\"y\":0.3167,\"rgb\":[255,255,255],\"tol\":40},{\"x\":0.5125,\"y\":0.4444,\"rgb\":[255,255,108],\"tol\":40},{\"x\":0.651,\"y\":0.3704,\"rgb\":[255,255,255],\"tol\":40},{\"x\":0.651,\"y\":0.487,\"rgb\":[255,255,108],\"tol\":40},{\"x\":0.7896,\"y\":0.4444,\"rgb\":[255,255,255],\"tol\":40},{\"x\":0.7875,\"y\":0.5185,\"rgb\":[107,255,255],\"tol\":40}]" } },