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): a cut-out seen small lets through as much as its texture covers, instead of closing into a sheet

yhh6397fe5a040b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 813c90f27..039de4782 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -53,6 +53,8 @@ published separately; it ships inside the editor.
### Fixed
+- **Mip chains on WebGPU.** On the WebGPU backend, a mesh without a material, a sprite and a particle are sampled through their texture's mip chain, as they always were on WebGL2: their WGSL read level 0 alone, so anything drawn smaller than its texture shimmered into stripes and moire there and not on the other backend. A compressed (KTX2) texture also keeps every level of its chain on WebGPU: the upload stopped at the first level whose side is not a multiple of four, which left a 1240x1268 hair atlas with level 0 alone. In the render lab a card of fine strands seen small now reads the same on both backends.
+- **Cut-outs at a distance.** A cut-out seen from far enough away that its texture is smaller than a texel a pixel lets through as much as its texture covers. Its alpha was sharpened to a texel around the cutoff at every distance, and once the mips had averaged fine strands and the gaps between them to one value above the cutoff, the whole card turned solid: a hair card at arm's length drew as a plate. Where the texture is minified the mip-averaged alpha is now the coverage under multisampling, and the cutoff moves to a per-pixel threshold without it. In the render lab a card of fine cut-out strands lets through within 3% of what Blender does, where it let through nothing; the shader helper is cutoutCoverage, and u_time.w carries the scene's multisampling.
- **Faces speckled with dirt in shadow.** The high quality profile's shadow cascades are now 1024 texels on a 4096 atlas (they were 512 on 2048). At 512 a cascade's texel is several millimetres across a close character, so a brow, a hairline or a lash card sitting a fraction of a millimetre above the skin fell inside one texel of it and the shadow speckled the face with dirt; at 1024 the face is clean. Medium and low are unchanged.
- **Ambient occlusion at metre scale.** The ambient-occlusion effects, ssao and gtao, accept a radius down to a centimetre (they stopped at one world unit), so a 3D scene measured in metres can use them on hair and faces. A radius of 0.05 separates the cards of a hair mesh without the black speckle a larger one leaves on their edges.
- **Global illumination at metre scale.** The global-illumination effects accept lengths down to a centimetre: the voxel size of voxelGI, and the radius and thickness of ssgi, used to stop at four, ten and one world units, so a 3D scene measured in metres could not set them small enough to do anything. Against Blender's render of the same frame, a character lit by one sun gets its soft bounce light in the shadows once they are set to metre-scale values.
diff --git a/docs/astro/src/content/docs/graphics/materials.mdx b/docs/astro/src/content/docs/graphics/materials.mdx
index 252db19e6..5185ade0b 100644
--- a/docs/astro/src/content/docs/graphics/materials.mdx
+++ b/docs/astro/src/content/docs/graphics/materials.mdx
@@ -166,7 +166,7 @@ One file holds every stage plus its metadata, separated by pragmas:
| `#pragma param …` | A reflected material parameter (table below). |
| `#pragma switch NAME [default(on)]` | Material-facing static permutation toggle (a `#define`). |
| `#pragma feature NAME` | Engine-chosen compile-time variant keyword. |
-| `#pragma coverage PARAM` | While the float param `PARAM` is above zero, the shader's output alpha is coverage — a cutout's alpha sharpened to about a texel around the cutoff. An opaque draw into a multisampled target then turns it into multisample coverage, so the cutout's edge is antialiased instead of stair-stepped. The built-in Model shader declares `u_alphaCutoff`. |
+| `#pragma coverage PARAM` | While the float param `PARAM` is above zero, the shader's output alpha is coverage — a cutout's alpha sharpened to about a texel around the cutoff. An opaque draw into a multisampled target then turns it into multisample coverage, so the cutout's edge is antialiased instead of stair-stepped. Where the texture is seen smaller than a texel a pixel, its edges are finer than the pixel and its own mip-averaged alpha is used as the coverage (or, without multisampling, against a per-pixel threshold), so a card of fine strands far away lets through as much as it covers instead of closing into a solid sheet. A shader does this with `cutoutCoverage(alpha, cutoff, edge, texelsPerPixel, pixel, u_time.w)`; `u_time.w` is the scene's multisampling. The built-in Model shader declares `u_alphaCutoff`. |
| `#pragma hairshadow PARAM` | While the float param `PARAM` is above zero, meshes drawn with the material are hair for shadows: the sun's cascades gain one fitted to them alone, and a shader that sets `g_hairShadow` before it lights reads the shadow as a density along the light instead of a hard compare. The value is the density. The built-in Hair shader declares `u_hairShadow`. |
| `#pragma gbuffer` | A `PostProcess` shader reads the scene's surface record (see [the G-buffer](/docs/graphics/post-processing/#the-g-buffer)) at `u_gbuffer`. Declaring it is what makes the frame draw one; a chain whose shaders do not never pays for it. |
| `#pragma vertex` / `#pragma fragment` … `#pragma end` | Stage bodies. **The vertex block is optional for 2D domains** — the engine injects the canonical stage. |
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx
index 21c643b60..fc3078876 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx
@@ -135,7 +135,7 @@ std140 uniform 块,于是 CPU 能按名字设置、并安全地送到 GPU。一
| `#pragma domain <D>` | `Unlit`(默认)、`Lit`、`PostProcess`、`UI`。`Lit` 注入光照 uniform + helper。旧拼写 `Unlit2D` / `Lit2D` 仍按这两个域加载。 |
| `#pragma param …` | 反射的材质参数(见下表)。 |
| `#pragma switch NAME [default(on)]` | 材质可控的静态排列开关(一个 `#define`)。 |
-| `#pragma coverage PARAM` | 浮点参数 `PARAM` 大于零时,着色器输出的 alpha 就是覆盖率——镂空的 alpha 在阈值附近锐化到约一个纹素宽。不透明物体画进多重采样目标时,它会转成多重采样覆盖率,镂空边缘就有抗锯齿而不是台阶。内置 Model 着色器声明了 `u_alphaCutoff`。 |
+| `#pragma coverage PARAM` | 浮点参数 `PARAM` 大于零时,着色器输出的 alpha 就是覆盖率——镂空的 alpha 在阈值附近锐化到约一个纹素宽。不透明物体画进多重采样目标时,它会转成多重采样覆盖率,镂空边缘就有抗锯齿而不是台阶。贴图被缩小到一个像素覆盖多个纹素时,边缘比像素还细,这时直接用经过 mip 平均的 alpha 作为覆盖率(没有多重采样时则与逐像素阈值比较),所以远处一张细发丝卡片透出的比例与它实际覆盖的一致,不会合成一整块实心板。着色器用 `cutoutCoverage(alpha, cutoff, edge, texelsPerPixel, pixel, u_time.w)` 实现,`u_time.w` 是场景的多重采样数。内置 Model 着色器声明了 `u_alphaCutoff`。 |
| `#pragma feature NAME` | 引擎选择的编译期变体关键字。 |
| `#pragma hairshadow PARAM` | 浮点参数 `PARAM` 大于零时,用这个材质画的网格就是阴影意义上的头发:太阳的级联多出一个只拟合它们的级联,并且着色器在打光前设置 `g_hairShadow` 的话,阴影就按沿光线的密度读,而不是硬比较。参数值就是密度。内置 Hair 着色器声明了 `u_hairShadow`。 |
| `#pragma gbuffer` | `PostProcess` 着色器要读取场景的表面记录(见[G-buffer](/docs/zh-cn/graphics/post-processing/#g-buffer)),在 `u_gbuffer` 处。声明它才会让这一帧画出一份;着色器里没有它的链路永远不付这笔钱。 |
diff --git a/sdk/src/character/characterShaders.ts b/sdk/src/character/characterShaders.ts
index b760970e5..54a8d0939 100644
--- a/sdk/src/character/characterShaders.ts
+++ b/sdk/src/character/characterShaders.ts
@@ -106,6 +106,8 @@ void main() {
#endif
vec4 base = texture(u_textures[0], v_texCoord, u_sharpen) * v_color * u_tint;
// Before any discard: a derivative needs every fragment of its quad.
+ vec2 mapSize = vec2(textureSize(u_textures[0], 0));
+ float texels = max(length(dFdx(v_texCoord) * mapSize), length(dFdy(v_texCoord) * mapSize));
float alpha = 1.0;
#ifdef ES_TIP_PASS
// The band below the cutoff, fading in toward it, and a texel past it so it meets the opaque card without a gap.
@@ -114,7 +116,7 @@ void main() {
alpha = min(alpha, 1.0);
#else
if (u_alphaCutoff > 0.0) {
- alpha = (base.a - u_alphaCutoff) / max(fwidth(base.a), 1e-4) + 0.5;
+ alpha = cutoutCoverage(base.a, u_alphaCutoff, fwidth(base.a), texels, gl_FragCoord.xy, u_time.w);
if (alpha <= 0.0) discard;
alpha = min(alpha, 1.0);
}
@@ -178,6 +180,8 @@ fn packNormal(n : vec3f) -> vec2f {
#endif
var base = textureSampleBias(t0, s0, v.v_texCoord, mc.u_sharpen) * v.v_color * mc.u_tint;
let edge = max(abs(dpdx(base.a)) + abs(dpdy(base.a)), 1e-4);
+ let mapSize = vec2f(textureDimensions(t0));
+ let texels = max(length(duvx * mapSize), length(duvy * mapSize));
let flowTex = textureSampleGrad(u_flowMap, u_flowMap_s, v.v_texCoord, duvx, duvy).rg * 2.0 - vec2f(1.0);
let orm = textureSampleGrad(u_ormMap, u_ormMap_s, v.v_texCoord, duvx, duvy);
let shiftTex = textureSampleGrad(u_shiftMap, u_shiftMap_s, v.v_texCoord * mc.u_shiftTile, duvx * mc.u_shiftTile, duvy * mc.u_shiftTile).r;
@@ -206,7 +210,7 @@ fn packNormal(n : vec3f) -> vec2f {
alpha = min(alpha, 1.0);
#else
if (mc.u_alphaCutoff > 0.0) {
- alpha = (base.a - mc.u_alphaCutoff) / edge + 0.5;
+ alpha = cutoutCoverage(base.a, mc.u_alphaCutoff, edge, texels, v.pos.xy, tc.u_time.w);
if (alpha <= 0.0) { discard; }
alpha = min(alpha, 1.0);
}
diff --git a/sdk/src/render/builtinShaders.ts b/sdk/src/render/builtinShaders.ts
index 0cab20af3..0cabee15b 100644
--- a/sdk/src/render/builtinShaders.ts
+++ b/sdk/src/render/builtinShaders.ts
@@ -449,11 +449,12 @@ void main() {
highp vec3 dndy = dFdy(v_worldNormal);
#endif
vec4 base = texture(u_textures[0], v_texCoord) * v_color * u_tint;
- // A cutout's alpha becomes coverage: sharpened to about a texel around the
- // cutoff, so alpha-to-coverage feathers the edge instead of stair-stepping it.
+ // A cutout's alpha becomes coverage (cutoutCoverage): sharpened where the map is magnified, its own average where it is minified.
+ vec2 mapSize = vec2(textureSize(u_textures[0], 0));
+ float texels = max(length(dFdx(v_texCoord) * mapSize), length(dFdy(v_texCoord) * mapSize));
float alpha = base.a;
if (u_alphaCutoff > 0.0) {
- alpha = (base.a - u_alphaCutoff) / max(fwidth(base.a), 1e-4) + 0.5;
+ alpha = cutoutCoverage(base.a, u_alphaCutoff, fwidth(base.a), texels, gl_FragCoord.xy, u_time.w);
if (alpha <= 0.0) discard;
alpha = min(alpha, 1.0);
}
@@ -595,9 +596,11 @@ fn packNormal(n : vec3f) -> vec2f {
var 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);
+ let mapSize = vec2f(textureDimensions(t0));
+ let texels = max(length(duvx * mapSize), length(duvy * mapSize));
var alpha = base.a;
if (mc.u_alphaCutoff > 0.0) {
- alpha = (base.a - mc.u_alphaCutoff) / edge + 0.5;
+ alpha = cutoutCoverage(base.a, mc.u_alphaCutoff, edge, texels, v.pos.xy, tc.u_time.w);
if (alpha <= 0.0) { discard; }
alpha = min(alpha, 1.0);
}
diff --git a/src/esengine/renderer/frame/FrameConstants.hpp b/src/esengine/renderer/frame/FrameConstants.hpp
index 75990e347..ef9da18c5 100644
--- a/src/esengine/renderer/frame/FrameConstants.hpp
+++ b/src/esengine/renderer/frame/FrameConstants.hpp
@@ -85,7 +85,7 @@ inline constexpr const char* FRAME_CONSTANTS_BLOCK = "FrameConstants";
/**
* @brief CPU mirror of the injected TimeConstants block (std140).
- * @details u_time = (elapsed s, delta s, view exposure EV, 0); u_viewport = (w, h, 1/w, 1/h) of the
+ * @details u_time = (elapsed s, delta s, view exposure EV, the scene's multisampling); u_viewport = (w, h, 1/w, 1/h) of the
* canvas in pixels. Engine-owned: ShaderParser injects the block into every
* assembled stage — shaders never declare it.
*/
diff --git a/src/esengine/renderer/frame/RenderContext.cpp b/src/esengine/renderer/frame/RenderContext.cpp
index 3ba058c1d..7f491e0b9 100644
--- a/src/esengine/renderer/frame/RenderContext.cpp
+++ b/src/esengine/renderer/frame/RenderContext.cpp
@@ -222,7 +222,7 @@ void RenderContext::setFrameTime(f32 elapsedSec, u32 viewportW, u32 viewportH) {
const f32 w = static_cast<f32>(viewportW);
const f32 h = static_cast<f32>(viewportH);
TimeConstants time{
- glm::vec4(elapsedSec, dt, viewExposure_, 0.0f),
+ glm::vec4(elapsedSec, dt, viewExposure_, coverageSamples_),
glm::vec4(w, h, w > 0.0f ? 1.0f / w : 0.0f, h > 0.0f ? 1.0f / h : 0.0f),
};
device_.updateBuffer(timeUbo_, 0, &time, sizeof(TimeConstants));
diff --git a/src/esengine/renderer/frame/RenderContext.hpp b/src/esengine/renderer/frame/RenderContext.hpp
index fe96af017..1c886e34d 100644
--- a/src/esengine/renderer/frame/RenderContext.hpp
+++ b/src/esengine/renderer/frame/RenderContext.hpp
@@ -191,6 +191,13 @@ public:
* exp2(0) = 1, an exact no-op.
*/
void setViewExposure(f32 ev) { viewExposure_ = ev; }
+
+ /**
+ * @brief The multisampling the scene is drawn with, carried to every shader in u_time.w: a cut-out's minified alpha is coverage
+ * where there are samples to cover, and a per-pixel threshold where there are none (cutoutCoverage). Uploaded with the
+ * next frame's clock, so a change reaches the shaders a frame late.
+ */
+ void setCoverageSamples(u32 samples) { coverageSamples_ = static_cast<f32>(samples > 0 ? samples : 1); }
f32 viewExposure() const { return viewExposure_; }
/**
@@ -263,6 +270,7 @@ public:
private:
f32 lastElapsed_ = 0.0f;
f32 viewExposure_ = 0.0f;
+ f32 coverageSamples_ = 1.0f;
MaterialStore materials_;
LightStore lights_;
ProbeStore probes_;
diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cpp
index cc4d8353d..b85e08b55 100644
--- a/src/esengine/renderer/frame/RenderFrame.cpp
+++ b/src/esengine/renderer/frame/RenderFrame.cpp
@@ -246,7 +246,10 @@ void RenderFrame::drawScene(DrawList::Phase phase) {
// sub-pixel amount each frame, so its history samples what a single frame cannot.
// The scene only: the overlay and the shadow maps are drawn with constants of their own.
glm::vec2 jitter{0.0f};
+ u32 coverageSamples = 1;
#ifdef ES_ENABLE_POSTPROCESS
+ // The scene's multisampling, chain or not: with no chain it draws to a surface given the same count.
+ if (post_process_) coverageSamples = post_process_->sceneSamples();
// The atlas the meshes reflect, for an effect that adds a reflection of its own where the scene's ray found none.
if (post_process_) post_process_->setEnvironmentTexture(environment_texture_id_);
if (phase == DrawList::Phase::SceneColorOnly || phase == DrawList::Phase::BlendedOnly) {
@@ -260,6 +263,7 @@ void RenderFrame::drawScene(DrawList::Phase phase) {
}
#endif
scene_jitter_ = jitter;
+ context_.setCoverageSamples(coverageSamples);
context_.updateCameraConstants(view_projection_, jitter);
// Where THIS camera's pixels sit inside the 2D shadow mask. Per camera because the
// mask is screen space: two cameras drew into two parts of one target, and a
diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cpp
index 316c95e60..fe16530bc 100644
--- a/src/esengine/resource/ShaderParser.cpp
+++ b/src/esengine/resource/ShaderParser.cpp
@@ -1440,6 +1440,16 @@ fn shadowFactor3D(worldPos : vec3f, N : vec3f, L : vec3f, source : vec2f,
return 1.0;
#endif
}
+// The coverage a cut-out's alpha gives this pixel. Magnified, the cut is sharpened to about a texel so alpha-to-coverage feathers its edge.
+// Minified, the edges are finer than the pixel and the map's own alpha, averaged by its mips, already is the share of the pixel the cut-out
+// covers: under multisampling it is that coverage as it is, and without it the cut moves to a per-pixel threshold so the share holds on
+// average. `texels` is how many texels of the map one pixel spans, `samples` the multisampling of the pass (u_time.w).
+fn cutoutCoverage(a : f32, cutoff : f32, edge : f32, texels : f32, pixel : vec2f, samples : f32) -> f32 {
+ let minified = clamp(log2(max(texels, 1e-4)), 0.0, 1.0);
+ if (samples > 1.5) { return mix((a - cutoff) / max(edge, 1e-4) + 0.5, a, minified); }
+ let noise = fract(52.9829189 * fract(dot(floor(pixel), vec2f(0.06711056, 0.00583715))));
+ return (a - mix(cutoff, noise, minified)) / max(edge, 1e-4) + 0.5;
+}
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))));
@@ -2530,6 +2540,15 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p
// The one normal-map unpack: X and Y from RG, Z rebuilt to unit length, so a
// two-channel map (BC5, or B left at 0) lights like the three-channel one. 2D
// applies it screen-space; a flat surface uses vec3(0,0,1).
+ // The coverage a cut-out's alpha gives this pixel: sharpened to a texel where the map is magnified, and the map's own (mip-averaged)
+ // alpha where it is minified, as coverage under multisampling and against a per-pixel threshold without it. See the WGSL twin.
+ "highp float cutoutCoverage(in highp float a, in highp float cutoff, in highp float edge, in highp float texels,\n"
+ " in highp vec2 pixel, in highp float samples) {\n"
+ " highp float minified = clamp(log2(max(texels, 1e-4)), 0.0, 1.0);\n"
+ " if (samples > 1.5) return mix((a - cutoff) / max(edge, 1e-4) + 0.5, a, minified);\n"
+ " highp float noise = fract(52.9829189 * fract(dot(floor(pixel), vec2(0.06711056, 0.00583715))));\n"
+ " return (a - mix(cutoff, noise, minified)) / max(edge, 1e-4) + 0.5;\n"
+ "}\n"
"highp vec3 sampleNormal(in highp sampler2D map, in highp vec2 uv) {\n"
" 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"
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 9091cd4d2..aa428b7e8 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -66,6 +66,10 @@ export const NOTED = {
{"note":"The Hair shader can draw a card's strands as locks: u_clumpCount sets how many across its width, u_clumpTone how much lighter or darker one is than the next, u_clumpShift how far each lock's highlight is pushed along the strand so it breaks from lock to lock, and u_clumpGap how dark the seam between locks is; 0 leaves the card as authored. A hair material imported from a glTF is set to seven locks, so cards cut from one strand texture no longer read as a combed plate. Against Blender's render of the same frame the top of the hair comes out within about ten percent in every channel, where it was half again as bright."},
'feat(render): hair casts and receives its own shadow, with a cascade fitted to it and a density along the light':
{"note":"A hair material draws the sun's shadow of hair as hair. The Hair shader gains u_hairShadow, how much light a layer of strands takes per world unit along it (declared with the new `#pragma hairshadow`), and while it is above zero the frame adds a cascade fitted to the hair alone as the first in the sun's list: cards a few millimetres apart fell inside one texel of a cascade spread over the view, so the layers could not shadow each other, and the face under a fringe is now shadowed at the hair's resolution too. The light left after a depth of hair falls off with that depth, from the nearest card to this one, as a deep shadow map reads it, with a card's own surface left out so it does not shadow itself. A hair material imported from a glTF is set to a density of 400. The Hair shader has u_strandDiffuse, how much of the diffuse is the strand's own Kajiya-Kay term against a surface's N dot L, and a hair material imported from a glTF sets it to 0. At the old 0.6 a card turned edge-on to the light still took a third of it, so every lock was lit to one tone and the gaps between locks never went dark; with the Principled shader's diffuse they do. With the lamp highlight at a tenth and the tinted second lobe at half what they were, the top of the hair comes out within about six percent of Blender's render of the same frame on both backends, where it was half again as bright."},
+ 'fix(webgpu): meshes, sprites and particles sample through their mip chain, and a compressed texture keeps every level':
+ {"note":"On the WebGPU backend, a mesh without a material, a sprite and a particle are sampled through their texture's mip chain, as they always were on WebGL2: their WGSL read level 0 alone, so anything drawn smaller than its texture shimmered into stripes and moire there and not on the other backend. A compressed (KTX2) texture also keeps every level of its chain on WebGPU: the upload stopped at the first level whose side is not a multiple of four, which left a 1240x1268 hair atlas with level 0 alone. In the render lab a card of fine strands seen small now reads the same on both backends."},
+ 'fix(render): a cut-out seen small lets through as much as its texture covers, instead of closing into a sheet':
+ {"note":"A cut-out seen from far enough away that its texture is smaller than a texel a pixel lets through as much as its texture covers. Its alpha was sharpened to a texel around the cutoff at every distance, and once the mips had averaged fine strands and the gaps between them to one value above the cutoff, the whole card turned solid: a hair card at arm's length drew as a plate. Where the texture is minified the mip-averaged alpha is now the coverage under multisampling, and the cutoff moves to a per-pixel threshold without it. In the render lab a card of fine cut-out strands lets through within 3% of what Blender does, where it let through nothing; the shader helper is cutoutCoverage, and u_time.w carries the scene's multisampling."},
'fix: serialize binaryen optimization on windows': { internal: 'Uses one optimizer worker after wider builds reproduced heap corruption with four; release optimization flags stay unchanged.' },
'feat: add budgeted 2d and 3d particle scene collisions': { note: 'Budgeted particle scene collisions.' },
'feat(editor): add particle collision authoring and diagnostics': { note: 'Budgeted particle scene collisions.' },