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(postprocess): 13 effects migrate to reflected params + WGSL twins - loose uniforms retired (WGSL phase 3 slice 5, phase 3 complete)

yhhfc784ce63fef
diff --git a/sdk/src/postprocess/postProcessEffects.ts b/sdk/src/postprocess/postProcessEffects.ts
index 0584086d0..26e042b34 100644
--- a/sdk/src/postprocess/postProcessEffects.ts
+++ b/sdk/src/postprocess/postProcessEffects.ts
@@ -1,15 +1,20 @@
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file postProcessEffects.ts
* @brief Stateless post-process shader factories.
- * @details Pure Material.createShader builders, extracted verbatim from the
- * former four-in-one PostProcess object. No state, no per-App, no
- * module — just shader source. (B2b: slim the god-object.)
+ * @details Fragment-only `.esshader` sources on the reflected `#pragma param`
+ * seam (domain PostProcess: the engine injects the canonical
+ * fullscreen vertex stage), each with a `#pragma fragment wgsl` twin
+ * so every effect compiles on the WebGPU backend. Conventions: the
+ * pass input is the loose `u_texture` sampler (unit 0; t0/s0 in the
+ * twin), the untouched scene `u_sceneTexture` (unit 1; t1/s1), LUT
+ * textures are texture params at their reflected material units, and
+ * resolution comes from the injected `u_viewport` (xy = pixels,
+ * zw = 1/pixels) instead of a per-pass upload.
*/
import type { ShaderHandle } from '../material';
import { Material } from '../material';
-import { POSTPROCESS_VERTEX } from './shaders';
export const postProcessEffects = {
createLutGrade(): ShaderHandle {
@@ -18,13 +23,17 @@ export const postProcessEffects = {
// blue coordinate and mixed, giving trilinear-quality grading from a
// plain PNG. The LUT texture binds via the pass's texture params
// (PostProcessVolume `textures: { u_lut: <ref> }`).
- const fragmentSrc = `#version 300 es
+ const source = `#pragma shader "PP LUT Grade"
+#pragma version 300 es
+#pragma domain PostProcess
+#pragma param u_intensity float default(1) range(0,1)
+#pragma param u_lut texture default(white)
+
+#pragma fragment
precision highp float;
in vec2 v_texCoord;
uniform sampler2D u_texture;
-uniform sampler2D u_lut;
-uniform float u_intensity;
out vec4 fragColor;
vec3 sampleLut(vec3 c) {
@@ -43,22 +52,45 @@ void main() {
vec4 color = texture(u_texture, v_texCoord);
fragColor = vec4(mix(color.rgb, sampleLut(color.rgb), u_intensity), color.a);
}
+#pragma end
+
+#pragma fragment wgsl
+fn sampleLut(c : vec3f) -> vec3f {
+ let size = 32.0;
+ let b = clamp(c.b, 0.0, 1.0) * (size - 1.0);
+ let slice0 = floor(b);
+ let slice1 = min(slice0 + 1.0, size - 1.0);
+ let u = (clamp(c.r, 0.0, 1.0) * (size - 1.0) + 0.5) / (size * size);
+ let v = (clamp(c.g, 0.0, 1.0) * (size - 1.0) + 0.5) / size;
+ let a = textureSampleLevel(u_lut, u_lut_s, vec2f(u + slice0 / size, v), 0.0).rgb;
+ let d = textureSampleLevel(u_lut, u_lut_s, vec2f(u + slice1 / size, v), 0.0).rgb;
+ return mix(a, d, b - slice0);
+}
+
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let color = textureSampleLevel(t0, s0, v.v_texCoord, 0.0);
+ return vec4f(mix(color.rgb, sampleLut(color.rgb), mc.u_intensity), color.a);
+}
+#pragma end
`;
- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
+ return Material.compileShader(source);
},
createBlur(): ShaderHandle {
- const fragmentSrc = `#version 300 es
+ const source = `#pragma shader "PP Blur"
+#pragma version 300 es
+#pragma domain PostProcess
+#pragma param u_intensity float default(2) range(0,20)
+
+#pragma fragment
precision highp float;
in vec2 v_texCoord;
uniform sampler2D u_texture;
-uniform vec2 u_resolution;
-uniform float u_intensity;
out vec4 fragColor;
void main() {
- vec2 texelSize = 1.0 / u_resolution;
+ vec2 texelSize = u_viewport.zw;
float offset = u_intensity;
vec4 color = vec4(0.0);
@@ -74,18 +106,44 @@ void main() {
fragColor = color;
}
+#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let texelSize = tc.u_viewport.zw;
+ let offset = mc.u_intensity;
+ let uv = v.v_texCoord;
+
+ var color = vec4f(0.0);
+ color += textureSampleLevel(t0, s0, uv + vec2f(-offset, -offset) * texelSize, 0.0) * 0.0625;
+ color += textureSampleLevel(t0, s0, uv + vec2f( 0.0, -offset) * texelSize, 0.0) * 0.125;
+ color += textureSampleLevel(t0, s0, uv + vec2f( offset, -offset) * texelSize, 0.0) * 0.0625;
+ color += textureSampleLevel(t0, s0, uv + vec2f(-offset, 0.0) * texelSize, 0.0) * 0.125;
+ color += textureSampleLevel(t0, s0, uv, 0.0) * 0.25;
+ color += textureSampleLevel(t0, s0, uv + vec2f( offset, 0.0) * texelSize, 0.0) * 0.125;
+ color += textureSampleLevel(t0, s0, uv + vec2f(-offset, offset) * texelSize, 0.0) * 0.0625;
+ color += textureSampleLevel(t0, s0, uv + vec2f( 0.0, offset) * texelSize, 0.0) * 0.125;
+ color += textureSampleLevel(t0, s0, uv + vec2f( offset, offset) * texelSize, 0.0) * 0.0625;
+
+ return color;
+}
+#pragma end
`;
- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
+ return Material.compileShader(source);
},
createVignette(): ShaderHandle {
- const fragmentSrc = `#version 300 es
+ const source = `#pragma shader "PP Vignette"
+#pragma version 300 es
+#pragma domain PostProcess
+#pragma param u_intensity float default(0.6) range(0,1)
+#pragma param u_softness float default(0.5) range(0,1)
+
+#pragma fragment
precision highp float;
in vec2 v_texCoord;
uniform sampler2D u_texture;
-uniform float u_intensity;
-uniform float u_softness;
out vec4 fragColor;
void main() {
@@ -95,17 +153,32 @@ void main() {
float vig = 1.0 - smoothstep(1.0 - u_softness, 1.0, dist);
fragColor = vec4(color.rgb * mix(1.0, vig, u_intensity), color.a);
}
+#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let color = textureSampleLevel(t0, s0, v.v_texCoord, 0.0);
+ let uv = v.v_texCoord * 2.0 - 1.0;
+ let dist = length(uv);
+ let vig = 1.0 - smoothstep(1.0 - mc.u_softness, 1.0, dist);
+ return vec4f(color.rgb * mix(1.0, vig, mc.u_intensity), color.a);
+}
+#pragma end
`;
- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
+ return Material.compileShader(source);
},
createGrayscale(): ShaderHandle {
- const fragmentSrc = `#version 300 es
+ const source = `#pragma shader "PP Grayscale"
+#pragma version 300 es
+#pragma domain PostProcess
+#pragma param u_intensity float default(1) range(0,1)
+
+#pragma fragment
precision highp float;
in vec2 v_texCoord;
uniform sampler2D u_texture;
-uniform float u_intensity;
out vec4 fragColor;
void main() {
@@ -113,17 +186,30 @@ void main() {
float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));
fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);
}
+#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let color = textureSampleLevel(t0, s0, v.v_texCoord, 0.0);
+ let gray = dot(color.rgb, vec3f(0.299, 0.587, 0.114));
+ return vec4f(mix(color.rgb, vec3f(gray), mc.u_intensity), color.a);
+}
+#pragma end
`;
- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
+ return Material.compileShader(source);
},
createBloomExtract(): ShaderHandle {
- const fragmentSrc = `#version 300 es
+ const source = `#pragma shader "PP Bloom Extract"
+#pragma version 300 es
+#pragma domain PostProcess
+#pragma param u_threshold float default(0.4) range(0,1)
+
+#pragma fragment
precision highp float;
in vec2 v_texCoord;
uniform sampler2D u_texture;
-uniform float u_threshold;
out vec4 fragColor;
void main() {
@@ -137,23 +223,42 @@ void main() {
contrib /= max(brightness, 0.00001);
fragColor = vec4(color.rgb * contrib, 1.0);
}
+#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let color = textureSampleLevel(t0, s0, v.v_texCoord, 0.0);
+ let brightness = dot(color.rgb, vec3f(0.2126, 0.7152, 0.0722));
+ let knee = mc.u_threshold * 0.5;
+ var soft = brightness - mc.u_threshold + knee;
+ soft = clamp(soft, 0.0, 2.0 * knee);
+ soft = soft * soft / (4.0 * knee + 0.00001);
+ var contrib = max(soft, brightness - mc.u_threshold);
+ contrib /= max(brightness, 0.00001);
+ return vec4f(color.rgb * contrib, 1.0);
+}
+#pragma end
`;
- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
+ return Material.compileShader(source);
},
createBloomKawase(iteration: number): ShaderHandle {
- const fragmentSrc = `#version 300 es
+ const d = `(${iteration.toFixed(1)} + 0.5)`;
+ const source = `#pragma shader "PP Bloom Kawase ${iteration.toFixed(0)}"
+#pragma version 300 es
+#pragma domain PostProcess
+#pragma param u_radius float default(1) range(0.5,5)
+
+#pragma fragment
precision highp float;
in vec2 v_texCoord;
uniform sampler2D u_texture;
-uniform vec2 u_resolution;
-uniform float u_radius;
out vec4 fragColor;
void main() {
- float d = (${iteration.toFixed(1)} + 0.5) * max(u_radius, 0.5);
- vec2 ts = 1.0 / u_resolution;
+ float d = ${d} * max(u_radius, 0.5);
+ vec2 ts = u_viewport.zw;
fragColor = (
texture(u_texture, v_texCoord + vec2(-d, -d) * ts) +
texture(u_texture, v_texCoord + vec2( d, -d) * ts) +
@@ -161,18 +266,37 @@ void main() {
texture(u_texture, v_texCoord + vec2( d, d) * ts)
) * 0.25;
}
+#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let d = ${d} * max(mc.u_radius, 0.5);
+ let ts = tc.u_viewport.zw;
+ let uv = v.v_texCoord;
+ return (
+ textureSampleLevel(t0, s0, uv + vec2f(-d, -d) * ts, 0.0) +
+ textureSampleLevel(t0, s0, uv + vec2f( d, -d) * ts, 0.0) +
+ textureSampleLevel(t0, s0, uv + vec2f(-d, d) * ts, 0.0) +
+ textureSampleLevel(t0, s0, uv + vec2f( d, d) * ts, 0.0)
+ ) * 0.25;
+}
+#pragma end
`;
- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
+ return Material.compileShader(source);
},
createBloomComposite(): ShaderHandle {
- const fragmentSrc = `#version 300 es
+ const source = `#pragma shader "PP Bloom Composite"
+#pragma version 300 es
+#pragma domain PostProcess
+#pragma param u_intensity float default(1.5) range(0,5)
+
+#pragma fragment
precision highp float;
in vec2 v_texCoord;
uniform sampler2D u_texture;
uniform sampler2D u_sceneTexture;
-uniform float u_intensity;
out vec4 fragColor;
void main() {
@@ -180,21 +304,34 @@ void main() {
vec4 scene = texture(u_sceneTexture, v_texCoord);
fragColor = vec4(scene.rgb + blur.rgb * u_intensity, scene.a);
}
+#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let blur = textureSampleLevel(t0, s0, v.v_texCoord, 0.0);
+ let scene = textureSampleLevel(t1, s1, v.v_texCoord, 0.0);
+ return vec4f(scene.rgb + blur.rgb * mc.u_intensity, scene.a);
+}
+#pragma end
`;
- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
+ return Material.compileShader(source);
},
createColorGrade(): ShaderHandle {
- const fragmentSrc = `#version 300 es
+ const source = `#pragma shader "PP Color Grade"
+#pragma version 300 es
+#pragma domain PostProcess
+#pragma param u_exposure float default(0) range(-3,3)
+#pragma param u_contrast float default(1) range(0,2)
+#pragma param u_saturation float default(1) range(0,2)
+#pragma param u_temperature float default(0) range(-1,1)
+#pragma param u_tint float default(0) range(-1,1)
+
+#pragma fragment
precision highp float;
in vec2 v_texCoord;
uniform sampler2D u_texture;
-uniform float u_exposure; // stops; 0 = unchanged
-uniform float u_contrast; // 1 = unchanged
-uniform float u_saturation; // 1 = unchanged
-uniform float u_temperature; // -1 cool .. +1 warm
-uniform float u_tint; // -1 green .. +1 magenta
out vec4 fragColor;
void main() {
@@ -218,30 +355,66 @@ void main() {
fragColor = vec4(clamp(c, 0.0, 1.0), src.a);
}
+#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let src = textureSampleLevel(t0, s0, v.v_texCoord, 0.0);
+ var c = src.rgb;
+
+ c *= exp2(mc.u_exposure);
+
+ c.r *= 1.0 + mc.u_temperature * 0.2;
+ c.b *= 1.0 - mc.u_temperature * 0.2;
+ c.g *= 1.0 + mc.u_tint * 0.2;
+
+ c = (c - 0.5) * mc.u_contrast + 0.5;
+
+ let luma = dot(c, vec3f(0.2126, 0.7152, 0.0722));
+ c = mix(vec3f(luma), c, mc.u_saturation);
+
+ return vec4f(clamp(c, vec3f(0.0), vec3f(1.0)), src.a);
+}
+#pragma end
`;
- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
+ return Material.compileShader(source);
},
createChromaticAberration(): ShaderHandle {
- const fragmentSrc = `#version 300 es
+ const source = `#pragma shader "PP Chromatic Aberration"
+#pragma version 300 es
+#pragma domain PostProcess
+#pragma param u_intensity float default(3) range(0,20)
+
+#pragma fragment
precision highp float;
in vec2 v_texCoord;
uniform sampler2D u_texture;
-uniform vec2 u_resolution;
-uniform float u_intensity;
out vec4 fragColor;
void main() {
- vec2 offset = u_intensity / u_resolution;
+ vec2 offset = u_intensity * u_viewport.zw;
float r = texture(u_texture, v_texCoord + offset).r;
float g = texture(u_texture, v_texCoord).g;
float b = texture(u_texture, v_texCoord - offset).b;
float a = texture(u_texture, v_texCoord).a;
fragColor = vec4(r, g, b, a);
}
+#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let offset = mc.u_intensity * tc.u_viewport.zw;
+ let r = textureSampleLevel(t0, s0, v.v_texCoord + offset, 0.0).r;
+ let g = textureSampleLevel(t0, s0, v.v_texCoord, 0.0).g;
+ let b = textureSampleLevel(t0, s0, v.v_texCoord - offset, 0.0).b;
+ let a = textureSampleLevel(t0, s0, v.v_texCoord, 0.0).a;
+ return vec4f(r, g, b, a);
+}
+#pragma end
`;
- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
+ return Material.compileShader(source);
},
createTonemap(): ShaderHandle {
@@ -249,12 +422,16 @@ void main() {
// radiance into a display range with a filmic shoulder/toe. Unlike the
// grade/blur effects this always reshapes the curve (that is the point of
// tonemapping); only the exposure pre-multiply is identity at its default.
- const fragmentSrc = `#version 300 es
+ const source = `#pragma shader "PP Tonemap"
+#pragma version 300 es
+#pragma domain PostProcess
+#pragma param u_exposure float default(0) range(-3,3)
+
+#pragma fragment
precision highp float;
in vec2 v_texCoord;
uniform sampler2D u_texture;
-uniform float u_exposure; // stops; 0 = unchanged exposure
out vec4 fragColor;
vec3 aces(vec3 x) {
@@ -271,21 +448,42 @@ void main() {
vec3 c = src.rgb * exp2(u_exposure);
fragColor = vec4(aces(c), src.a);
}
+#pragma end
+
+#pragma fragment wgsl
+fn aces(x : vec3f) -> vec3f {
+ let a = 2.51;
+ let b = 0.03;
+ let c = 2.43;
+ let d = 0.59;
+ let e = 0.14;
+ return clamp((x * (a * x + b)) / (x * (c * x + d) + e), vec3f(0.0), vec3f(1.0));
+}
+
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let src = textureSampleLevel(t0, s0, v.v_texCoord, 0.0);
+ let c = src.rgb * exp2(mc.u_exposure);
+ return vec4f(aces(c), src.a);
+}
+#pragma end
`;
- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
+ return Material.compileShader(source);
},
createFxaa(): ShaderHandle {
// Luma-based FXAA (Lottes' classic edge-directed blur). Reads only the
- // built-in u_texture/u_resolution; u_intensity blends the AA result back
+ // built-in u_texture/u_viewport; u_intensity blends the AA result back
// toward the original so 0 is an exact no-op.
- const fragmentSrc = `#version 300 es
+ const source = `#pragma shader "PP FXAA"
+#pragma version 300 es
+#pragma domain PostProcess
+#pragma param u_intensity float default(1) range(0,1)
+
+#pragma fragment
precision highp float;
in vec2 v_texCoord;
uniform sampler2D u_texture;
-uniform vec2 u_resolution;
-uniform float u_intensity; // 0 = off (identity), 1 = full AA
out vec4 fragColor;
const float REDUCE_MIN = 1.0 / 128.0;
@@ -295,7 +493,7 @@ const float SPAN_MAX = 8.0;
float luma(vec3 c) { return dot(c, vec3(0.299, 0.587, 0.114)); }
void main() {
- vec2 inv = 1.0 / u_resolution;
+ vec2 inv = u_viewport.zw;
vec4 srcM = texture(u_texture, v_texCoord);
vec3 rgbNW = texture(u_texture, v_texCoord + vec2(-1.0, -1.0) * inv).rgb;
vec3 rgbNE = texture(u_texture, v_texCoord + vec2( 1.0, -1.0) * inv).rgb;
@@ -325,8 +523,53 @@ void main() {
vec3 aa = (lB < lMin || lB > lMax) ? rgbA : rgbB;
fragColor = vec4(mix(srcM.rgb, aa, clamp(u_intensity, 0.0, 1.0)), srcM.a);
}
+#pragma end
+
+#pragma fragment wgsl
+const REDUCE_MIN = 1.0 / 128.0;
+const REDUCE_MUL = 1.0 / 8.0;
+const SPAN_MAX = 8.0;
+
+fn luma(c : vec3f) -> f32 { return dot(c, vec3f(0.299, 0.587, 0.114)); }
+
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let inv = tc.u_viewport.zw;
+ let uv = v.v_texCoord;
+ let srcM = textureSampleLevel(t0, s0, uv, 0.0);
+ let rgbNW = textureSampleLevel(t0, s0, uv + vec2f(-1.0, -1.0) * inv, 0.0).rgb;
+ let rgbNE = textureSampleLevel(t0, s0, uv + vec2f( 1.0, -1.0) * inv, 0.0).rgb;
+ let rgbSW = textureSampleLevel(t0, s0, uv + vec2f(-1.0, 1.0) * inv, 0.0).rgb;
+ let rgbSE = textureSampleLevel(t0, s0, uv + vec2f( 1.0, 1.0) * inv, 0.0).rgb;
+
+ let lM = luma(srcM.rgb);
+ let lNW = luma(rgbNW);
+ let lNE = luma(rgbNE);
+ let lSW = luma(rgbSW);
+ let lSE = luma(rgbSE);
+ let lMin = min(lM, min(min(lNW, lNE), min(lSW, lSE)));
+ let lMax = max(lM, max(max(lNW, lNE), max(lSW, lSE)));
+
+ var dir : vec2f;
+ dir.x = -((lNW + lNE) - (lSW + lSE));
+ dir.y = ((lNW + lSW) - (lNE + lSE));
+ let reduce = max((lNW + lNE + lSW + lSE) * 0.25 * REDUCE_MUL, REDUCE_MIN);
+ let rcpMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + reduce);
+ dir = clamp(dir * rcpMin, vec2f(-SPAN_MAX), vec2f(SPAN_MAX)) * inv;
+
+ let rgbA = 0.5 * (
+ textureSampleLevel(t0, s0, uv + dir * (1.0 / 3.0 - 0.5), 0.0).rgb +
+ textureSampleLevel(t0, s0, uv + dir * (2.0 / 3.0 - 0.5), 0.0).rgb);
+ let rgbB = rgbA * 0.5 + 0.25 * (
+ textureSampleLevel(t0, s0, uv + dir * -0.5, 0.0).rgb +
+ textureSampleLevel(t0, s0, uv + dir * 0.5, 0.0).rgb);
+
+ let lB = luma(rgbB);
+ let aa = select(rgbB, rgbA, lB < lMin || lB > lMax);
+ return vec4f(mix(srcM.rgb, aa, clamp(mc.u_intensity, 0.0, 1.0)), srcM.a);
+}
+#pragma end
`;
- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
+ return Material.compileShader(source);
},
createLensDistortion(): ShaderHandle {
@@ -334,13 +577,17 @@ void main() {
// u_zoom rescales to keep edges in frame. Identity at strength 0 / zoom 1
// (sample uv == source uv). Out-of-source taps resolve to transparent
// black so a warped edge does not smear.
- const fragmentSrc = `#version 300 es
+ const source = `#pragma shader "PP Lens Distortion"
+#pragma version 300 es
+#pragma domain PostProcess
+#pragma param u_strength float default(0) range(-1,1)
+#pragma param u_zoom float default(1) range(0.5,2)
+
+#pragma fragment
precision highp float;
in vec2 v_texCoord;
uniform sampler2D u_texture;
-uniform float u_strength; // 0 = none; + barrel, - pincushion
-uniform float u_zoom; // 1 = none
out vec4 fragColor;
void main() {
@@ -354,29 +601,55 @@ void main() {
fragColor = texture(u_texture, suv);
}
}
+#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let uv = v.v_texCoord * 2.0 - 1.0;
+ let r2 = dot(uv, uv);
+ let warped = uv * (1.0 + mc.u_strength * r2) / max(mc.u_zoom, 0.0001);
+ let suv = warped * 0.5 + 0.5;
+ if (suv.x < 0.0 || suv.x > 1.0 || suv.y < 0.0 || suv.y > 1.0) {
+ return vec4f(0.0);
+ }
+ return textureSampleLevel(t0, s0, suv, 0.0);
+}
+#pragma end
`;
- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
+ return Material.compileShader(source);
},
createPixelate(): ShaderHandle {
// Snaps sampling to a grid of u_pixelSize-device-pixel blocks — the
// canonical retro/mosaic 2D look. u_pixelSize <= 1 samples per-texel
- // (identity). Uses the built-in u_resolution for block sizing.
- const fragmentSrc = `#version 300 es
+ // (identity). Uses the injected u_viewport for block sizing.
+ const source = `#pragma shader "PP Pixelate"
+#pragma version 300 es
+#pragma domain PostProcess
+#pragma param u_pixelSize float default(4) range(1,64)
+
+#pragma fragment
precision highp float;
in vec2 v_texCoord;
uniform sampler2D u_texture;
-uniform vec2 u_resolution;
-uniform float u_pixelSize; // device pixels per block; <= 1 = identity
out vec4 fragColor;
void main() {
- vec2 blocks = u_resolution / max(u_pixelSize, 1.0);
+ vec2 blocks = u_viewport.xy / max(u_pixelSize, 1.0);
vec2 uv = (floor(v_texCoord * blocks) + 0.5) / blocks;
fragColor = texture(u_texture, uv);
}
+#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let blocks = tc.u_viewport.xy / max(mc.u_pixelSize, 1.0);
+ let uv = (floor(v.v_texCoord * blocks) + 0.5) / blocks;
+ return textureSampleLevel(t0, s0, uv, 0.0);
+}
+#pragma end
`;
- return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
+ return Material.compileShader(source);
},
};
diff --git a/sdk/tests/postprocess.test.ts b/sdk/tests/postprocess.test.ts
index 167fa89a5..c4288d46f 100644
--- a/sdk/tests/postprocess.test.ts
+++ b/sdk/tests/postprocess.test.ts
@@ -3,6 +3,7 @@
vi.mock('../src/material', () => ({
Material: {
createShader: vi.fn().mockReturnValue(42),
+ compileShader: vi.fn().mockReturnValue(42),
releaseShader: vi.fn(),
},
}));
@@ -327,53 +328,45 @@ describe('PostProcess API', () => {
// =========================================================================
describe('built-in effects', () => {
- it('should create blur shader using Material.createShader', () => {
+ // Effects are fragment-only PostProcess-domain .esshaders on the
+ // reflected #pragma param seam, compiled via Material.compileShader.
+ const lastSource = (): string => {
+ const calls = (Material.compileShader as ReturnType<typeof vi.fn>).mock.calls;
+ return calls[calls.length - 1][0] as string;
+ };
+
+ it('should create blur as a param-reflected PostProcess esshader', () => {
const handle = postProcessEffects.createBlur();
- expect(Material.createShader).toHaveBeenCalledWith(
- expect.stringContaining('a_position'),
- expect.stringContaining('u_intensity'),
- );
+ const src = lastSource();
+ expect(src).toContain('#pragma domain PostProcess');
+ expect(src).toContain('#pragma param u_intensity float');
+ expect(src).not.toContain('#pragma vertex'); // canonical stage is engine-injected
expect(handle).toBe(42);
});
- it('should create vignette shader using Material.createShader', () => {
- const handle = postProcessEffects.createVignette();
- expect(Material.createShader).toHaveBeenCalledWith(
- expect.stringContaining('a_position'),
- expect.stringContaining('u_softness'),
- );
- expect(handle).toBe(42);
+ it('should create vignette with its params reflected', () => {
+ postProcessEffects.createVignette();
+ expect(lastSource()).toContain('#pragma param u_softness float');
});
- it('should create grayscale shader using Material.createShader', () => {
- const handle = postProcessEffects.createGrayscale();
- expect(Material.createShader).toHaveBeenCalledWith(
- expect.stringContaining('a_position'),
- expect.stringContaining('0.299'),
- );
- expect(handle).toBe(42);
+ it('should create grayscale with Rec.601 luma weights', () => {
+ postProcessEffects.createGrayscale();
+ expect(lastSource()).toContain('0.299');
});
- it('should create chromatic aberration shader using Material.createShader', () => {
- const handle = postProcessEffects.createChromaticAberration();
- expect(Material.createShader).toHaveBeenCalledWith(
- expect.stringContaining('a_position'),
- expect.stringContaining('u_intensity'),
- );
- expect(handle).toBe(42);
+ it('should size chromatic aberration from the injected viewport', () => {
+ postProcessEffects.createChromaticAberration();
+ const src = lastSource();
+ expect(src).toContain('u_intensity * u_viewport.zw');
+ expect(src).not.toContain('u_resolution');
});
- it('should create color grade shader using Material.createShader', () => {
- const handle = postProcessEffects.createColorGrade();
- expect(Material.createShader).toHaveBeenCalledWith(
- expect.stringContaining('a_position'),
- expect.stringContaining('u_exposure'),
- );
- expect(Material.createShader).toHaveBeenCalledWith(
- expect.anything(),
- expect.stringContaining('u_saturation'),
- );
- expect(handle).toBe(42);
+ it('should create color grade with every grading param reflected', () => {
+ postProcessEffects.createColorGrade();
+ const src = lastSource();
+ for (const p of ['u_exposure', 'u_contrast', 'u_saturation', 'u_temperature', 'u_tint']) {
+ expect(src).toContain(`#pragma param ${p} float`);
+ }
});
it('registers colorGrade with identity defaults (no-op at defaults)', () => {
@@ -386,23 +379,44 @@ describe('PostProcess API', () => {
});
});
- it('should use the shared POSTPROCESS_VERTEX shader for all effects', () => {
+ it('every effect ships a WGSL twin and stays fragment-only', () => {
+ postProcessEffects.createLutGrade();
postProcessEffects.createBlur();
postProcessEffects.createVignette();
postProcessEffects.createGrayscale();
+ postProcessEffects.createBloomExtract();
+ postProcessEffects.createBloomKawase(0);
+ postProcessEffects.createBloomComposite();
+ postProcessEffects.createColorGrade();
postProcessEffects.createChromaticAberration();
postProcessEffects.createTonemap();
postProcessEffects.createFxaa();
postProcessEffects.createLensDistortion();
postProcessEffects.createPixelate();
- const calls = (Material.createShader as ReturnType<typeof vi.fn>).mock.calls;
- const vertexShaders = calls.map((c: unknown[]) => c[0]);
- const firstVertex = vertexShaders[0];
- for (const vs of vertexShaders) {
- expect(vs).toBe(firstVertex);
+ const calls = (Material.compileShader as ReturnType<typeof vi.fn>).mock.calls;
+ expect(calls.length).toBe(13);
+ for (const c of calls) {
+ const src = c[0] as string;
+ expect(src).toContain('#pragma domain PostProcess');
+ expect(src).toContain('#pragma fragment wgsl');
+ expect(src).toContain('fn fs_main(');
+ expect(src).not.toContain('#pragma vertex');
+ expect(src).not.toContain('u_resolution'); // u_viewport replaced it
}
});
+
+ it('lutGrade declares the LUT as a texture param', () => {
+ postProcessEffects.createLutGrade();
+ expect(lastSource()).toContain('#pragma param u_lut texture default(white)');
+ });
+
+ it('bloom composite reads the untouched scene through the engine unit', () => {
+ postProcessEffects.createBloomComposite();
+ const src = lastSource();
+ expect(src).toContain('u_sceneTexture'); // GLSL: loose engine sampler (unit 1)
+ expect(src).toContain('t1, s1'); // WGSL twin: the unit-1 pair
+ });
});
// =========================================================================
@@ -410,52 +424,39 @@ describe('PostProcess API', () => {
// =========================================================================
describe('extended effects', () => {
+ const lastSource = (): string => {
+ const calls = (Material.compileShader as ReturnType<typeof vi.fn>).mock.calls;
+ return calls[calls.length - 1][0] as string;
+ };
+
it('should create an ACES tonemap shader with exposure', () => {
const handle = postProcessEffects.createTonemap();
- expect(Material.createShader).toHaveBeenCalledWith(
- expect.stringContaining('a_position'),
- expect.stringContaining('u_exposure'),
- );
+ const src = lastSource();
+ expect(src).toContain('#pragma param u_exposure float');
// ACES Narkowicz curve constant — guards the operator identity.
- expect(Material.createShader).toHaveBeenCalledWith(
- expect.anything(),
- expect.stringContaining('2.51'),
- );
+ expect(src).toContain('2.51');
expect(handle).toBe(42);
});
- it('should create an FXAA shader sampling by resolution', () => {
+ it('should create an FXAA shader sampling by the injected viewport', () => {
const handle = postProcessEffects.createFxaa();
- expect(Material.createShader).toHaveBeenCalledWith(
- expect.anything(),
- expect.stringContaining('u_resolution'),
- );
- expect(Material.createShader).toHaveBeenCalledWith(
- expect.anything(),
- expect.stringContaining('u_intensity'),
- );
+ const src = lastSource();
+ expect(src).toContain('u_viewport.zw');
+ expect(src).toContain('#pragma param u_intensity float');
expect(handle).toBe(42);
});
it('should create a lens distortion shader with strength and zoom', () => {
const handle = postProcessEffects.createLensDistortion();
- expect(Material.createShader).toHaveBeenCalledWith(
- expect.anything(),
- expect.stringContaining('u_strength'),
- );
- expect(Material.createShader).toHaveBeenCalledWith(
- expect.anything(),
- expect.stringContaining('u_zoom'),
- );
+ const src = lastSource();
+ expect(src).toContain('#pragma param u_strength float');
+ expect(src).toContain('#pragma param u_zoom float');
expect(handle).toBe(42);
});
it('should create a pixelate shader with pixel size', () => {
const handle = postProcessEffects.createPixelate();
- expect(Material.createShader).toHaveBeenCalledWith(
- expect.anything(),
- expect.stringContaining('u_pixelSize'),
- );
+ expect(lastSource()).toContain('#pragma param u_pixelSize float');
expect(handle).toBe(42);
});
diff --git a/sdk/tests/shader-twins.test.ts b/sdk/tests/shader-twins.test.ts
index b86fc69d6..a146fa8ab 100644
--- a/sdk/tests/shader-twins.test.ts
+++ b/sdk/tests/shader-twins.test.ts
@@ -43,12 +43,15 @@ const CASES: Array<{ name: string; source: string }> = [
...BUILTIN_SHADER_TEMPLATES.map((t) => ({ name: `template:${t.id}`, source: t.source })),
...embeddedEsshaders('filters.ts').map((source, i) => ({ name: `filters.ts[${i}]`, source })),
...embeddedEsshaders('spriteFilter.ts').map((source, i) => ({ name: `spriteFilter.ts[${i}]`, source })),
+ ...embeddedEsshaders('postprocess/postProcessEffects.ts').map(
+ (source, i) => ({ name: `postProcessEffects.ts[${i}]`, source })),
];
describe('embedded .esshader structure', () => {
- it('found the filter sources', () => {
+ it('found the filter and effect sources', () => {
expect(CASES.filter((c) => c.name.startsWith('filters.ts')).length).toBe(1);
expect(CASES.filter((c) => c.name.startsWith('spriteFilter.ts')).length).toBe(2);
+ expect(CASES.filter((c) => c.name.startsWith('postProcessEffects.ts')).length).toBe(13);
});
for (const { name, source } of CASES) {
diff --git a/src/esengine/data/shaders/blit.esshader b/src/esengine/data/shaders/blit.esshader
index 339f5ffc6..056128a31 100644
--- a/src/esengine/data/shaders/blit.esshader
+++ b/src/esengine/data/shaders/blit.esshader
@@ -2,18 +2,6 @@
#pragma version 300 es
#pragma domain PostProcess
-#pragma vertex
-layout(location = 0) in vec2 a_position;
-layout(location = 1) in vec2 a_texCoord;
-
-out vec2 v_texCoord;
-
-void main() {
- v_texCoord = a_texCoord;
- gl_Position = vec4(a_position, 0.0, 1.0);
-}
-#pragma end
-
#pragma fragment
precision highp float;
@@ -26,33 +14,7 @@ void main() {
}
#pragma end
-#pragma vertex wgsl
-struct VSIn {
- @location(0) a_position : vec2f,
- @location(1) a_texCoord : vec2f,
-};
-struct VSOut {
- @builtin(position) pos : vec4f,
- @location(0) v_texCoord : vec2f,
-};
-
-@vertex fn vs_main(v : VSIn) -> VSOut {
- var out : VSOut;
- out.pos = vec4f(v.a_position, 0.0, 1.0);
- out.v_texCoord = v.a_texCoord;
- return out;
-}
-#pragma end
-
#pragma fragment wgsl
-@group(1) @binding(0) var t0 : texture_2d<f32>;
-@group(1) @binding(8) var s0 : sampler;
-
-struct VSOut {
- @builtin(position) pos : vec4f,
- @location(0) v_texCoord : vec2f,
-};
-
@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
return textureSampleLevel(t0, s0, v.v_texCoord, 0.0);
}
diff --git a/src/esengine/renderer/MaterialStore.hpp b/src/esengine/renderer/MaterialStore.hpp
index 39fc00d68..3ffcce664 100644
--- a/src/esengine/renderer/MaterialStore.hpp
+++ b/src/esengine/renderer/MaterialStore.hpp
@@ -188,6 +188,14 @@ public:
return it != materials_.end() ? &it->second : nullptr;
}
+ /// The registered #pragma-param layout for a shader program, or nullptr.
+ /// The post-process pipeline reads it to pack pass params through the same
+ /// reflected MaterialConstants block a material would use.
+ const MaterialUniformLayout* layoutFor(u32 shaderId) const {
+ auto it = layouts_.find(shaderId);
+ return it != layouts_.end() ? &it->second : nullptr;
+ }
+
/// Uploads (when dirty) and binds the material's MaterialConstants UBO at binding 1.
/// No-op for materials whose shader declares no params (uboBytes stays empty).
void bindForDraw(u32 materialId);
diff --git a/src/esengine/renderer/PostProcessPipeline.cpp b/src/esengine/renderer/PostProcessPipeline.cpp
index 8b4870ae5..b8233074a 100644
--- a/src/esengine/renderer/PostProcessPipeline.cpp
+++ b/src/esengine/renderer/PostProcessPipeline.cpp
@@ -14,12 +14,14 @@
#include "PostProcessPipeline.hpp"
#include "RenderContext.hpp"
#include "GfxDevice.hpp"
+#include "MaterialConstants.hpp"
#include "Shader.hpp"
#include "ShaderEmbeds.generated.hpp"
#include "../resource/ResourceManager.hpp"
#include "../resource/ShaderParser.hpp"
#include "../core/Log.hpp"
#include <algorithm>
+#include <cstring>
#include "GfxEnums.hpp"
@@ -99,6 +101,8 @@ void PostProcessPipeline::ensureFBOs() {
void PostProcessPipeline::shutdown() {
if (!initialized_) return;
+ for (auto& pass : passes_) releasePassResources(pass);
+ for (auto& pass : screenPasses_) releasePassResources(pass);
passes_.clear();
screenPasses_.clear();
@@ -167,11 +171,19 @@ u32 PostProcessPipeline::addPass(const std::string& name, resource::ShaderHandle
return static_cast<u32>(passes_.size() - 1);
}
+void PostProcessPipeline::releasePassResources(PostProcessPass& pass) {
+ if (pass.paramUbo != BufferHandle::Invalid) {
+ device_.deleteBuffer(pass.paramUbo);
+ pass.paramUbo = BufferHandle::Invalid;
+ }
+}
+
void PostProcessPipeline::removePass(const std::string& name) {
auto it = std::find_if(passes_.begin(), passes_.end(),
[&name](const PostProcessPass& p) { return p.name == name; });
if (it != passes_.end()) {
+ releasePassResources(*it);
passes_.erase(it);
}
}
@@ -195,6 +207,7 @@ void PostProcessPipeline::setPassUniformFloat(const std::string& passName,
const std::string& uniform, f32 value) {
if (auto* pass = findPass(passName)) {
pass->floatUniforms[uniform] = value;
+ pass->paramDirty = true;
}
}
@@ -213,6 +226,7 @@ void PostProcessPipeline::setPassUniformVec4(const std::string& passName,
const glm::vec4& value) {
if (auto* pass = findPass(passName)) {
pass->vec4Uniforms[uniform] = value;
+ pass->paramDirty = true;
}
}
@@ -327,7 +341,7 @@ void PostProcessPipeline::end() {
device->bindTexture(1, sceneTexture_);
device->bindTexture(0, TextureHandle::Invalid);
- for (const auto& pass : passes_) {
+ for (auto& pass : passes_) {
if (!pass.enabled) continue;
Framebuffer* targetFBO = (currentFBO_ == 0) ? fboA_.get() : fboB_.get();
@@ -351,7 +365,7 @@ void PostProcessPipeline::end() {
output_target_fbo_ = FramebufferHandle::Default;
}
-void PostProcessPipeline::renderPass(const PostProcessPass& pass, TextureHandle inputTexture) {
+void PostProcessPipeline::renderPass(PostProcessPass& pass, TextureHandle inputTexture) {
Shader* shader = resourceManager_.getShader(pass.shader);
if (!shader) return;
@@ -359,45 +373,89 @@ void PostProcessPipeline::renderPass(const PostProcessPass& pass, TextureHandle
device->bindTexture(0, inputTexture);
applyPassPipeline(*shader);
- shader->setUniform("u_texture", 0);
- // u_sceneTexture and u_resolution are engine-provided builtins that only some
- // passes use (bloom's composite taps the untouched scene; kawase/pixelate/fxaa
- // need the resolution). Supply them only where declared so passes that omit
- // them don't log a spurious "uniform not found".
- if (shader->hasUniform("u_sceneTexture")) shader->setUniform("u_sceneTexture", 1);
- if (shader->hasUniform("u_resolution")) {
- shader->setUniform("u_resolution", glm::vec2(static_cast<f32>(width_), static_cast<f32>(height_)));
- }
-
- // Effect-declared textures (LUTs, masks) bind above the two engine units.
- u32 extraUnit = 2;
- for (const auto& [name, glId] : pass.textureUniforms) {
- if (glId != 0 && shader->hasUniform(name)) {
- device->bindTexture(extraUnit, TextureHandle{glId});
- shader->setUniform(name, static_cast<i32>(extraUnit));
+ const bool glsl = shader->language() == GfxShaderLanguage::GLSL_ES300;
+ if (glsl) {
+ // Engine sampler seeding is a GLSL concept; the WGSL twins read the
+ // input/scene as the t0/s0 and t1/s1 bind-group pairs.
+ shader->setUniform("u_texture", 0);
+ if (shader->hasUniform("u_sceneTexture")) shader->setUniform("u_sceneTexture", 1);
+ }
+
+ // #pragma-param effects: params ride the reflected MaterialConstants block
+ // (binding 1) exactly like a material's — compileEsshader registered the
+ // layout when the effect compiled. Resolution-style inputs come from the
+ // injected u_viewport, so nothing per-pass remains loose.
+ const MaterialUniformLayout* layout = context_.materials().layoutFor(shader->getProgramId());
+ if (layout) {
+ if (layout->blockSize > 0) {
+ if (pass.paramDirty || pass.paramBytes.size() < layout->blockSize) {
+ // Defaults first, then the pass's set values by reflected offset.
+ // A multi-pass effect (bloom) carries its full uniform set; each
+ // sub-pass layout picks only the params it declares.
+ pass.paramBytes.assign(layout->blockSize, 0);
+ for (const auto& p : layout->params) {
+ std::memcpy(pass.paramBytes.data() + p.offset, p.defaults,
+ p.arity * sizeof(f32));
+ if (auto fit = pass.floatUniforms.find(p.name); fit != pass.floatUniforms.end()) {
+ std::memcpy(pass.paramBytes.data() + p.offset, &fit->second, sizeof(f32));
+ }
+ if (auto vit = pass.vec4Uniforms.find(p.name); vit != pass.vec4Uniforms.end()) {
+ std::memcpy(pass.paramBytes.data() + p.offset, &vit->second.x,
+ std::min(p.arity, 4u) * sizeof(f32));
+ }
+ }
+ pass.paramDirty = false;
+ if (pass.paramUbo == BufferHandle::Invalid) {
+ pass.paramUbo = device->createBuffer(
+ {GfxBufferUsage::Uniform, layout->blockSize, /*dynamic=*/true},
+ pass.paramBytes.data());
+ } else {
+ device->updateBuffer(pass.paramUbo, 0, pass.paramBytes.data(),
+ static_cast<u32>(pass.paramBytes.size()));
+ }
+ }
+ if (pass.paramUbo != BufferHandle::Invalid) {
+ device->setUniformBuffer(MATERIAL_CONSTANTS_BINDING, pass.paramUbo);
+ }
}
- ++extraUnit;
- }
-
- // A multi-pass effect (e.g. bloom) applies its full uniform set to every one
- // of its sub-pass shaders, each of which declares only a subset — upload each
- // uniform only to the passes that actually use it.
- for (const auto& [name, value] : pass.floatUniforms) {
- if (shader->hasUniform(name)) shader->setUniform(name, value);
- }
-
- for (const auto& [name, value] : pass.vec4Uniforms) {
- if (shader->hasUniform(name)) shader->setUniform(name, value);
+ // Texture params (LUTs, masks) bind at their reflected material units;
+ // an unset param gets its declared default (white/black/flatnormal).
+ for (const auto& slot : layout->textures) {
+ u32 glTexture = slot.defaultGlTexture;
+ for (const auto& [name, glId] : pass.textureUniforms) {
+ if (name == slot.name && glId != 0) { glTexture = glId; break; }
+ }
+ if (glTexture != 0) device->bindTexture(slot.unit, TextureHandle{glTexture});
+ }
+ } else if (glsl) {
+ // Legacy loose-uniform path for raw-GLSL passes (addPass with a
+ // hand-created shader): resolution, in-order extra textures, and the
+ // DrawParams block lifted at creation.
+ if (shader->hasUniform("u_resolution")) {
+ shader->setUniform("u_resolution", glm::vec2(static_cast<f32>(width_), static_cast<f32>(height_)));
+ }
+ u32 extraUnit = 2;
+ for (const auto& [name, glId] : pass.textureUniforms) {
+ if (glId != 0 && shader->hasUniform(name)) {
+ device->bindTexture(extraUnit, TextureHandle{glId});
+ shader->setUniform(name, static_cast<i32>(extraUnit));
+ }
+ ++extraUnit;
+ }
+ for (const auto& [name, value] : pass.floatUniforms) {
+ if (shader->hasUniform(name)) shader->setUniform(name, value);
+ }
+ for (const auto& [name, value] : pass.vec4Uniforms) {
+ if (shader->hasUniform(name)) shader->setUniform(name, value);
+ }
+ shader->commitParams();
}
- // Effect parameters live in the shader's DrawParams block (lifted at
- // creation); flush + bind them for this draw.
- shader->commitParams();
-
drawScreenQuad();
}
void PostProcessPipeline::clearPasses() {
+ for (auto& pass : passes_) releasePassResources(pass);
passes_.clear();
}
@@ -508,7 +566,7 @@ void PostProcessPipeline::executeScreenPasses() {
device->bindTexture(1, sceneTexture_);
device->bindTexture(0, TextureHandle::Invalid);
- for (const auto& pass : screenPasses_) {
+ for (auto& pass : screenPasses_) {
if (!pass.enabled) continue;
Framebuffer* targetFBO = (pingPong == 0) ? fboA_.get() : fboB_.get();
@@ -542,6 +600,7 @@ u32 PostProcessPipeline::addScreenPass(const std::string& name, resource::Shader
}
void PostProcessPipeline::clearScreenPasses() {
+ for (auto& pass : screenPasses_) releasePassResources(pass);
screenPasses_.clear();
}
@@ -558,6 +617,7 @@ void PostProcessPipeline::setScreenPassUniformFloat(const std::string& passName,
const std::string& uniform, f32 value) {
if (auto* pass = findScreenPass(passName)) {
pass->floatUniforms[uniform] = value;
+ pass->paramDirty = true;
}
}
@@ -566,6 +626,7 @@ void PostProcessPipeline::setScreenPassUniformVec4(const std::string& passName,
const glm::vec4& value) {
if (auto* pass = findScreenPass(passName)) {
pass->vec4Uniforms[uniform] = value;
+ pass->paramDirty = true;
}
}
diff --git a/src/esengine/renderer/PostProcessPipeline.hpp b/src/esengine/renderer/PostProcessPipeline.hpp
index 72d23406f..2a0569f1e 100644
--- a/src/esengine/renderer/PostProcessPipeline.hpp
+++ b/src/esengine/renderer/PostProcessPipeline.hpp
@@ -41,9 +41,18 @@ struct PostProcessPass {
bool enabled = true;
std::unordered_map<std::string, f32> floatUniforms;
std::unordered_map<std::string, glm::vec4> vec4Uniforms;
- /// Effect-declared textures (LUTs, masks): sampler uniform name -> GL texture
- /// id, bound in order above the two engine units (0 = input, 1 = scene).
+ /// Effect-declared textures (LUTs, masks): sampler uniform name -> GL
+ /// texture id. #pragma-param shaders bind them at their reflected material
+ /// units; the legacy loose path binds in order above the two engine units
+ /// (0 = input, 1 = scene).
std::vector<std::pair<std::string, u32>> textureUniforms;
+
+ /// #pragma-param shaders: the pass's packed MaterialConstants payload +
+ /// its UBO (binding 1) — the same reflected block a material would use.
+ /// Rebuilt from float/vec4Uniforms over the layout defaults when dirty.
+ std::vector<u8> paramBytes;
+ BufferHandle paramUbo = BufferHandle::Invalid;
+ bool paramDirty = true;
};
/**
@@ -241,8 +250,10 @@ private:
void ensureScreenQuad();
void drawScreenQuad();
void applyPassPipeline(const Shader& shader);
- void renderPass(const PostProcessPass& pass, TextureHandle inputTexture);
+ void renderPass(PostProcessPass& pass, TextureHandle inputTexture);
void blitToOutput(TextureHandle texture);
+ /// Frees a pass's GPU-side param UBO (removePass/clearPasses/shutdown).
+ void releasePassResources(PostProcessPass& pass);
GfxDevice& device_;
RenderContext& context_;
diff --git a/src/esengine/renderer/ShaderEmbeds.generated.hpp b/src/esengine/renderer/ShaderEmbeds.generated.hpp
index 29642dcce..cfb721057 100644
--- a/src/esengine/renderer/ShaderEmbeds.generated.hpp
+++ b/src/esengine/renderer/ShaderEmbeds.generated.hpp
@@ -184,18 +184,6 @@ inline constexpr const char* BLIT = R"esshader(#pragma shader "Blit"
#pragma version 300 es
#pragma domain PostProcess
-#pragma vertex
-layout(location = 0) in vec2 a_position;
-layout(location = 1) in vec2 a_texCoord;
-
-out vec2 v_texCoord;
-
-void main() {
- v_texCoord = a_texCoord;
- gl_Position = vec4(a_position, 0.0, 1.0);
-}
-#pragma end
-
#pragma fragment
precision highp float;
@@ -208,33 +196,7 @@ void main() {
}
#pragma end
-#pragma vertex wgsl
-struct VSIn {
- @location(0) a_position : vec2f,
- @location(1) a_texCoord : vec2f,
-};
-struct VSOut {
- @builtin(position) pos : vec4f,
- @location(0) v_texCoord : vec2f,
-};
-
-@vertex fn vs_main(v : VSIn) -> VSOut {
- var out : VSOut;
- out.pos = vec4f(v.a_position, 0.0, 1.0);
- out.v_texCoord = v.a_texCoord;
- return out;
-}
-#pragma end
-
#pragma fragment wgsl
-@group(1) @binding(0) var t0 : texture_2d<f32>;
-@group(1) @binding(8) var s0 : sampler;
-
-struct VSOut {
- @builtin(position) pos : vec4f,
- @location(0) v_texCoord : vec2f,
-};
-
@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
return textureSampleLevel(t0, s0, v.v_texCoord, 0.0);
}
diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cpp
index 36ded39a1..a11514fad 100644
--- a/src/esengine/resource/ShaderParser.cpp
+++ b/src/esengine/resource/ShaderParser.cpp
@@ -140,6 +140,51 @@ std::string canonical2DVertexStageWGSL(bool lit) {
return src;
}
+// The PostProcess domain's varying interface: a fullscreen pass carries only
+// the uv (plus the position builtin, which doubles as the pixel coordinate).
+std::string wgslPPVSOut() {
+ return
+ "struct VSOut {\n"
+ " @builtin(position) pos : vec4f,\n"
+ " @location(0) v_texCoord : vec2f,\n"
+ "};\n";
+}
+
+// WGSL twin of canonicalPPVertexStage.
+std::string canonicalPPVertexStageWGSL() {
+ std::string src = wgslPPVSOut();
+ src +=
+ "\n"
+ "struct VSIn {\n"
+ " @location(0) a_position : vec2f,\n"
+ " @location(1) a_texCoord : vec2f,\n"
+ "};\n"
+ "\n"
+ "@vertex fn vs_main(v : VSIn) -> VSOut {\n"
+ " var out : VSOut;\n"
+ " out.pos = vec4f(v.a_position, 0.0, 1.0);\n"
+ " out.v_texCoord = v.a_texCoord;\n"
+ " return out;\n"
+ "}\n";
+ return src;
+}
+
+// Canonical PostProcess vertex stage for fragment-only .esshaders: fullscreen
+// passes all share the clip-space pass-through (the engine draws one
+// fullscreen triangle; no projection, no color).
+std::string canonicalPPVertexStage() {
+ return
+ "layout(location = 0) in vec2 a_position;\n"
+ "layout(location = 1) in vec2 a_texCoord;\n"
+ "\n"
+ "out vec2 v_texCoord;\n"
+ "\n"
+ "void main() {\n"
+ " v_texCoord = a_texCoord;\n"
+ " gl_Position = vec4(a_position, 0.0, 1.0);\n"
+ "}\n";
+}
+
// Canonical 2D vertex stage for fragment-only .esshaders: the batch path bakes the
// world transform into the vertices, so all 2D shaders share this pass-through.
std::string canonical2DVertexStage(bool lit) {
@@ -397,9 +442,12 @@ ParsedShader ShaderParser::parse(const std::string& source, const ShaderIncludeR
}
if (result.stages.find(ShaderStage::Vertex) == result.stages.end()) {
- // 2D domains: `#pragma vertex` is optional — the canonical stage is injected.
+ // Fragment-only authoring: 2D domains get the canonical batch-space
+ // pass-through, PostProcess the canonical fullscreen pass-through.
if (result.domain == "Unlit2D" || result.domain == "Lit2D") {
result.stages[ShaderStage::Vertex] = canonical2DVertexStage(result.domain == "Lit2D");
+ } else if (result.domain == "PostProcess") {
+ result.stages[ShaderStage::Vertex] = canonicalPPVertexStage();
} else {
result.errorMessage = "Missing vertex shader stage";
return result;
@@ -411,14 +459,18 @@ ParsedShader ShaderParser::parse(const std::string& source, const ShaderIncludeR
return result;
}
- // Same for the WGSL twin: a fragment-only 2D twin gets the canonical WGSL
- // vertex, and the flag makes the fragment assembly inject the matching
+ // Same for the WGSL twin: a fragment-only twin gets the domain's canonical
+ // WGSL vertex, and the flag makes the fragment assembly inject the matching
// VSOut interface. A file with no wgsl sections simply has no twin.
if (result.wgslStages.count(ShaderStage::Fragment) != 0 &&
- result.wgslStages.count(ShaderStage::Vertex) == 0 &&
- (result.domain == "Unlit2D" || result.domain == "Lit2D")) {
- result.wgslStages[ShaderStage::Vertex] = canonical2DVertexStageWGSL(result.domain == "Lit2D");
- result.wgslVertexIsCanonical = true;
+ result.wgslStages.count(ShaderStage::Vertex) == 0) {
+ if (result.domain == "Unlit2D" || result.domain == "Lit2D") {
+ result.wgslStages[ShaderStage::Vertex] = canonical2DVertexStageWGSL(result.domain == "Lit2D");
+ result.wgslVertexIsCanonical = true;
+ } else if (result.domain == "PostProcess") {
+ result.wgslStages[ShaderStage::Vertex] = canonicalPPVertexStageWGSL();
+ result.wgslVertexIsCanonical = true;
+ }
}
computeMaterialLayout(result);
@@ -731,9 +783,10 @@ ShaderParser::AssembledStage assembleWGSLStage(const ParsedShader& parsed,
const bool lit = parsed.domain == "Lit2D";
if (stage == ShaderStage::Fragment && parsed.wgslVertexIsCanonical) {
- // The canonical vertex's varying interface + the batch texture
- // contract — fragment-only twins run under the batch conventions.
- inject(wgslCanonicalVSOut(lit));
+ // The canonical vertex's varying interface (domain-shaped) + the
+ // engine texture contract — fragment-only twins run under the batch
+ // conventions (PostProcess reads its input/scene as t0/s0 and t1/s1).
+ inject(parsed.domain == "PostProcess" ? wgslPPVSOut() : wgslCanonicalVSOut(lit));
inject(wgslBatchTextureDecls());
}
inject(kTimeHeaderWGSL);
diff --git a/tests/renderer/test_shader_variant.cpp b/tests/renderer/test_shader_variant.cpp
index 69a3f558b..cbc792004 100644
--- a/tests/renderer/test_shader_variant.cpp
+++ b/tests/renderer/test_shader_variant.cpp
@@ -68,9 +68,29 @@ void main() { fragColor = vec4(applyLighting2D(v_color.rgb, vec3(0.0, 0.0, 1.0),
#pragma end
)";
-static const char* FRAG_ONLY_POSTPROCESS = R"(#pragma shader "NoCanonical"
+static const char* FRAG_ONLY_POSTPROCESS = R"(#pragma shader "PPCanonical"
#pragma version 300 es
#pragma domain PostProcess
+#pragma param u_intensity float default(1)
+
+#pragma fragment
+precision highp float;
+in vec2 v_texCoord;
+uniform sampler2D u_texture;
+out vec4 fragColor;
+void main() { fragColor = texture(u_texture, v_texCoord) * u_intensity * u_viewport.z; }
+#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ return textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * mc.u_intensity * tc.u_viewport.z;
+}
+#pragma end
+)";
+
+static const char* FRAG_ONLY_UNKNOWN_DOMAIN = R"(#pragma shader "NoCanonical"
+#pragma version 300 es
+#pragma domain Compute3D
#pragma fragment
precision mediump float;
@@ -249,6 +269,23 @@ static void testWGSLEmission() {
ParsedShader noTwin = ShaderParser::parse(FRAG_ONLY_UNLIT);
CHECK(wgsl(noTwin, ShaderStage::Fragment).empty(), "missing twin yields an empty assembly");
+ // PostProcess twins get the fullscreen canonical vertex + the PP-shaped
+ // VSOut (uv only), with the same tc/mc/texture injections.
+ ParsedShader pp = ShaderParser::parse(FRAG_ONLY_POSTPROCESS);
+ CHECK(pp.valid && pp.wgslVertexIsCanonical, "fragment-only PP twin gets the canonical WGSL vertex");
+ const std::string ppVs = wgsl(pp, ShaderStage::Vertex);
+ CHECK(ppVs.find("out.pos = vec4f(v.a_position, 0.0, 1.0);") != std::string::npos &&
+ ppVs.find("frame.projection") == std::string::npos,
+ "PP canonical WGSL vertex is the clip-space pass-through");
+ const std::string ppFs = wgsl(pp, ShaderStage::Fragment);
+ CHECK(ppFs.find("@location(0) v_texCoord : vec2f,") != std::string::npos &&
+ ppFs.find("v_color") == std::string::npos,
+ "PP VSOut carries only the uv varying");
+ CHECK(ppFs.find("var<uniform> tc") != std::string::npos &&
+ ppFs.find("var<uniform> mc") != std::string::npos &&
+ ppFs.find("var t0 : texture_2d<f32>;") != std::string::npos,
+ "PP fragment twin gets the tc/mc blocks + engine texture contract");
+
// Unknown stage language tags fail the parse with a pointed message.
ParsedShader badTag = ShaderParser::parse(
"#pragma shader \"Bad\"\n#pragma fragment glsl450\nvoid main() {}\n#pragma end\n");
@@ -288,7 +325,14 @@ static void testFragmentOnly() {
CHECK(lf.find("applyLighting2D") != std::string::npos, "Lit2D fragment gets the lighting helper injected");
ParsedShader pp = ShaderParser::parse(FRAG_ONLY_POSTPROCESS);
- CHECK(!pp.valid, "non-2D domain without a vertex stage still errors");
+ CHECK(pp.valid, "fragment-only PostProcess shader parses");
+ const std::string ppv = ShaderParser::assembleStage(pp, ShaderStage::Vertex);
+ CHECK(ppv.find("gl_Position = vec4(a_position, 0.0, 1.0);") != std::string::npos &&
+ ppv.find("FrameConstants") == std::string::npos,
+ "PostProcess canonical vertex is the clip-space pass-through (no projection)");
+
+ ParsedShader unknownDomain = ShaderParser::parse(FRAG_ONLY_UNKNOWN_DOMAIN);
+ CHECK(!unknownDomain.valid, "a domain with no canonical vertex still errors");
ParsedShader authored = ShaderParser::parse(SRC);
const std::string av = ShaderParser::assembleStage(authored, ShaderStage::Vertex);
diff --git a/tests/renderer/webgpu_engine_bringup.cpp b/tests/renderer/webgpu_engine_bringup.cpp
index 48a3d4745..048870da5 100644
--- a/tests/renderer/webgpu_engine_bringup.cpp
+++ b/tests/renderer/webgpu_engine_bringup.cpp
@@ -150,31 +150,68 @@ void main() {
#pragma end
)";
+// A PostProcess-domain probe: the canonical fullscreen vertex, the loose
+// engine samplers (u_texture/u_sceneTexture on GLSL; the t0/s0 + t1/s1 pairs
+// in the twin), a reflected param, a LUT-style texture param, and the injected
+// u_viewport standing in for the old per-pass resolution.
+const char* kEmitterProbePP = R"(#pragma shader "EmitterProbePP"
+#pragma version 300 es
+#pragma domain PostProcess
+#pragma param u_intensity float default(1)
+#pragma param u_lut texture default(white)
+
+#pragma fragment
+precision highp float;
+in vec2 v_texCoord;
+uniform sampler2D u_texture;
+uniform sampler2D u_sceneTexture;
+out vec4 fragColor;
+void main() {
+ vec4 c = texture(u_texture, v_texCoord + u_viewport.zw);
+ vec4 scene = texture(u_sceneTexture, v_texCoord);
+ vec4 lut = texture(u_lut, v_texCoord);
+ fragColor = mix(scene, c * lut, u_intensity);
+}
+#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let c = textureSampleLevel(t0, s0, v.v_texCoord + tc.u_viewport.zw, 0.0);
+ let scene = textureSampleLevel(t1, s1, v.v_texCoord, 0.0);
+ let lut = textureSampleLevel(u_lut, u_lut_s, v.v_texCoord, 0.0);
+ return mix(scene, c * lut, mc.u_intensity);
+}
+#pragma end
+)";
+
bool compileEmitterProbe(EstellaContext& ctx, bool useGL) {
using resource::ShaderParser;
using resource::ShaderStage;
using resource::ShaderTargetLanguage;
auto& rm = ctx.require<resource::ResourceManager>();
- resource::ParsedShader parsed = ShaderParser::parse(kEmitterProbe);
- if (!parsed.valid) {
- std::printf("PARITY_FAIL emitter probe parse: %s\n", parsed.errorMessage.c_str());
- return false;
- }
const auto target = useGL ? ShaderTargetLanguage::GLSL_ES300 : ShaderTargetLanguage::WGSL;
const auto language = useGL ? GfxShaderLanguage::GLSL_ES300 : GfxShaderLanguage::WGSL;
- const std::string vs = ShaderParser::assembleStage(parsed, ShaderStage::Vertex, "", {"GLOW"}, target);
- const std::string fs = ShaderParser::assembleStage(parsed, ShaderStage::Fragment, "", {"GLOW"}, target);
- if (vs.empty() || fs.empty()) {
- std::printf("PARITY_FAIL emitter probe assembly\n");
- return false;
- }
- const auto handle = rm.createShader(vs, fs, /*rewriteLoose=*/false, language);
- if (!handle.isValid()) {
- std::printf("PARITY_FAIL emitter probe compile\n");
- return false;
+
+ for (const char* source : {kEmitterProbe, kEmitterProbePP}) {
+ resource::ParsedShader parsed = ShaderParser::parse(source);
+ if (!parsed.valid) {
+ std::printf("PARITY_FAIL emitter probe parse: %s\n", parsed.errorMessage.c_str());
+ return false;
+ }
+ const std::string vs = ShaderParser::assembleStage(parsed, ShaderStage::Vertex, "", {"GLOW"}, target);
+ const std::string fs = ShaderParser::assembleStage(parsed, ShaderStage::Fragment, "", {"GLOW"}, target);
+ if (vs.empty() || fs.empty()) {
+ std::printf("PARITY_FAIL emitter probe assembly (%s)\n", parsed.name.c_str());
+ return false;
+ }
+ const auto handle = rm.createShader(vs, fs, /*rewriteLoose=*/false, language);
+ if (!handle.isValid()) {
+ std::printf("PARITY_FAIL emitter probe compile (%s)\n", parsed.name.c_str());
+ return false;
+ }
+ rm.releaseShader(handle);
}
- rm.releaseShader(handle);
return true;
}