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(render): a material past seven textures takes the units below 8 its shader never reads, and Water gains a foam texture

yhhb4ba8033a74d
diff --git a/desktop b/desktop
index 6eba138f7..23218c037 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 6eba138f7651e9302efc2f30615de88bd2df56cb
+Subproject commit 23218c03773b7d590505bdc6384f4345d5484f17
diff --git a/docs/astro/src/content/docs/graphics/materials.mdx b/docs/astro/src/content/docs/graphics/materials.mdx
index 6184e5137..0b7b5f74d 100644
--- a/docs/astro/src/content/docs/graphics/materials.mdx
+++ b/docs/astro/src/content/docs/graphics/materials.mdx
@@ -205,6 +205,16 @@ the engine derives from it. A material that is not a bake can read it for a mask
The sprite's texture is `u_textures[0]` (declare `uniform sampler2D u_textures[8];`
— units 0–7 belong to the batch; texture *params* bind above them automatically).
+A draw has sixteen texture units on every device the engine targets (WebGL2 and WebGPU promise no more), and the
+top one is the engine's. Texture params take units 8–14 in the order they are declared; past seven, each further
+one takes a unit below 8 that **this** shader never reads: one whose engine texture it does not sample. A `Lit`
+shader reads the shadow map, the reflections, the morph deltas, the bake and both 2D masks there, so it has units
+1 and 0 left, nine textures in all; an `Unlit` one has every unit but the morph deltas' (4), fourteen in all. A
+shader that reads `u_textures` keeps all of 0–7 for the batch, and a `PostProcess` one stays at seven. In a WGSL
+twin, a `t` or `s` followed by a number (`t1`, `s0`) is a unit's name, a local of that name included, so give a
+local any other name or that unit stays the engine's. A param past what is left draws its default and the console
+says which one found no unit.
+
### Declaring parameters with `#pragma param`
```glsl
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 a603936cc..4855193d3 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx
@@ -169,6 +169,13 @@ WGSL。不用自己写:编辑器读取 shader 时会从 GLSL 自动派生,每次
精灵纹理是 `u_textures[0]`(声明 `uniform sampler2D u_textures[8];`——单元 0–7 归批处理;
纹理*参数*自动绑定在其上方)。
+在引擎面向的所有设备上,一次绘制有 16 个贴图单元(WebGL2 和 WebGPU 都不保证更多),最高那个归引擎。纹理参数按声明顺序
+占用 8–14 号单元;超过 7 张后,每多一张就占一个 8 号以下、**这个**着色器不会读的单元,也就是它不采样那里的引擎贴图。
+`Lit` 着色器会在那里读阴影贴图、反射、形变、烘焙光照和两张 2D 遮罩,所以只剩 1 号和 0 号,总共 9 张;`Unlit` 着色器
+除了形变的 4 号都能用,总共 14 张。读 `u_textures` 的着色器把 0–7 号全部留给批处理,`PostProcess` 着色器仍是 7 张。
+在 WGSL 版本里,`t` 或 `s` 后面跟数字(`t1`、`s0`)就是某个单元的名字,同名的局部变量也算,所以局部变量请换个名字,
+否则那个单元会留给引擎。超出剩余单元的参数会画成它的默认值,控制台会说明是哪个参数没分到单元。
+
### 用 `#pragma param` 声明参数
```glsl
diff --git a/pipeline/tests/fixtures/solidPng.d.mts b/pipeline/tests/fixtures/solidPng.d.mts
index b79a10a62..dde09b9de 100644
--- a/pipeline/tests/fixtures/solidPng.d.mts
+++ b/pipeline/tests/fixtures/solidPng.d.mts
@@ -8,3 +8,8 @@ export function solidPng(
rgba?: readonly [number, number, number, number],
): Buffer;
export function noisePng(width: number, height: number, seed?: number): Buffer;
+export function pixelPng(
+ width: number,
+ height: number,
+ texel: (x: number, y: number) => readonly [number, number, number, number],
+): Buffer;
diff --git a/pipeline/tests/fixtures/solidPng.mjs b/pipeline/tests/fixtures/solidPng.mjs
index 5c7fc0742..295543271 100644
--- a/pipeline/tests/fixtures/solidPng.mjs
+++ b/pipeline/tests/fixtures/solidPng.mjs
@@ -80,3 +80,26 @@ export function noisePng(width, height, seed = 1) {
return Buffer.concat([sig, chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)),
chunk('IEND', Buffer.alloc(0))]);
}
+
+/** A `width`×`height` image whose every texel `texel(x, y)` gives as `[r,g,b,a]` (0–255): a pattern a check can find again. */
+export function pixelPng(width, height, texel) {
+ const sig = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
+ const ihdr = Buffer.alloc(13);
+ ihdr.writeUInt32BE(width, 0);
+ ihdr.writeUInt32BE(height, 4);
+ ihdr[8] = 8;
+ ihdr[9] = 6;
+ const rowLen = width * 4;
+ const raw = Buffer.alloc((rowLen + 1) * height);
+ for (let y = 0; y < height; y++) {
+ const off = y * (rowLen + 1);
+ raw[off] = 0;
+ for (let x = 0; x < width; x++) {
+ const [r, g, b, a] = texel(x, y);
+ const p = off + 1 + x * 4;
+ raw[p] = r; raw[p + 1] = g; raw[p + 2] = b; raw[p + 3] = a;
+ }
+ }
+ return Buffer.concat([sig, chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)),
+ chunk('IEND', Buffer.alloc(0))]);
+}
diff --git a/sdk/src/water/waterShader.ts b/sdk/src/water/waterShader.ts
index d99add05d..daf8f4f1e 100644
--- a/sdk/src/water/waterShader.ts
+++ b/sdk/src/water/waterShader.ts
@@ -108,6 +108,13 @@ const WATER = `#pragma shader "Water"
#pragma param u_rippleRange float default(1) range(0.0001,1000) ui(slider)
#pragma param u_sceneColor texture default(white)
#pragma param u_sceneDepthMap texture default(white) texel(data)
+// What the foam is made of: a tiled texture whose red says how much foam a texel holds where foam is wanted (bubbles, threads, a web),
+// u_foamTile world units to a repeat, sliding u_foamFlow world units a second. Read as coverage, so the foam the shore, crests and ripples
+// ask for thins out through the texture's own pattern instead of dimming evenly; the default white keeps the foam exactly as computed.
+// Declared after every other texture, on purpose: the material units above it were full, and this one takes a unit the water never reads.
+#pragma param u_foamMap texture default(white) texel(data)
+#pragma param u_foamTile float default(3) range(0.01,100000) ui(slider)
+#pragma param u_foamFlow vec2 default(0.04,0.03)
#pragma vertexbounds 16
#pragma vertexoffset
@@ -629,6 +636,8 @@ void main() {
float ripFade = smoothstep(0.0, 0.15, min(ripEdge.x, ripEdge.y));
vec2 ripSlope = ripIn ? vec2(ripR - ripL, ripU - ripD) * u_rippleRange / ripCell * ripFade : vec2(0.0);
float ripFoam = ripIn ? ripC.g * ripFade : 0.0;
+ // How much foam the foam texture holds here (1 where none was given), read with the ripples, before any branch.
+ float foamCover = texture(u_foamMap, (wp + u_foamFlow * time) / max(u_foamTile, 1e-4)).r;
float crest;
vec2 slope;
if (dot(flow, flow) > 1e-6) {
@@ -639,9 +648,10 @@ void main() {
float ph1 = fract(time / cycle + 0.5);
float w0 = 1.0 - abs(2.0 * ph0 - 1.0);
float crest0, crest1;
- vec2 s0 = waterSurface(wp - flow * (ph0 * cycle), time, waterDist, damp, calm, crest0);
- vec2 s1 = waterSurface(wp - flow * (ph1 * cycle), time, waterDist, damp, calm, crest1);
- slope = mix(s1, s0, w0);
+ // Named copy0/copy1 because a t or s followed by a number is a texture unit's name (ShaderParser::materialOverflowUnits).
+ vec2 copy0 = waterSurface(wp - flow * (ph0 * cycle), time, waterDist, damp, calm, crest0);
+ vec2 copy1 = waterSurface(wp - flow * (ph1 * cycle), time, waterDist, damp, calm, crest1);
+ slope = mix(copy1, copy0, w0);
crest = mix(crest1, crest0, w0);
} else {
slope = waterSurface(wp, time, waterDist, damp, calm, crest);
@@ -742,6 +752,9 @@ void main() {
// A breaker whitens as much on a beach as the waves are big, but bursts whitest on rock.
float surfFoam = surf.y * smoothstep(0.15, 0.6, breakup + surf.y * 0.4) * mix(0.2, 1.0, zoneOn ? waterZoneSteep(wp) : 1.0);
float foam = clamp(max(max(max(shore, onCrest * u_foamCrest), ripFoam * (0.55 + 0.45 * breakup)), surfFoam), 0.0, 1.0);
+ // The texture as coverage: a texel holding c of foam shows where the foam asked for is more than 1 - c, rising to full over the rest,
+ // so thin foam keeps only the texture's densest marks and thick foam fills it. c = 1 leaves the foam as it was.
+ foam = clamp((foam - (1.0 - foamCover)) / max(foamCover, 1e-3), 0.0, 1.0);
// Foam floats on top: from under the water it is a thin shadow on the light, not a white sheet.
if (below) foam *= 0.2;
@@ -1106,6 +1119,8 @@ fn waterSurface(p : vec2f, time : f32, dist : f32, amp : f32, calm : f32) -> vec
let ripEdge = min(ripUv, vec2f(1.0) - ripUv);
let ripFade = smoothstep(0.0, 0.15, min(ripEdge.x, ripEdge.y));
if (ripIn) { ripSlope = vec2f(ripR - ripL, ripU - ripD) * mc.u_rippleRange / ripCell * ripFade; ripFoam = ripC.g * ripFade; }
+ // How much foam the foam texture holds here (1 where none was given), read in uniform control flow with the ripples.
+ let foamCover = textureSample(u_foamMap, u_foamMap_s, (wp + mc.u_foamFlow * time) / max(mc.u_foamTile, 1e-4)).r;
var surface = vec3f(0.0);
if (dot(flow, flow) > 1e-6) {
// A current: two copies of the surface carried downstream a cycle at a time, each fading in as the other fades out.
@@ -1113,9 +1128,10 @@ fn waterSurface(p : vec2f, time : f32, dist : f32, amp : f32, calm : f32) -> vec
let ph0 = fract(time / cycle);
let ph1 = fract(time / cycle + 0.5);
let w0 = 1.0 - abs(2.0 * ph0 - 1.0);
- let s0 = waterSurface(wp - flow * (ph0 * cycle), time, waterDist, damp, calm);
- let s1 = waterSurface(wp - flow * (ph1 * cycle), time, waterDist, damp, calm);
- surface = mix(s1, s0, w0);
+ // Named copy0/copy1: in WGSL an s followed by a number names a texture unit's sampler.
+ let copy0 = waterSurface(wp - flow * (ph0 * cycle), time, waterDist, damp, calm);
+ let copy1 = waterSurface(wp - flow * (ph1 * cycle), time, waterDist, damp, calm);
+ surface = mix(copy1, copy0, w0);
} else {
surface = waterSurface(wp, time, waterDist, damp, calm);
}
@@ -1205,6 +1221,8 @@ fn waterSurface(p : vec2f, time : f32, dist : f32, amp : f32, calm : f32) -> vec
if (zoneOn) { steepHere = waterZoneSteep(wp); }
let surfFoam = surf.y * smoothstep(0.15, 0.6, breakup + surf.y * 0.4) * mix(0.2, 1.0, steepHere);
var foam = clamp(max(max(max(shore, onCrest * mc.u_foamCrest), ripFoam * (0.55 + 0.45 * breakup)), surfFoam), 0.0, 1.0);
+ // The texture as coverage (see the GLSL): c = 1 leaves the foam as it was.
+ foam = clamp((foam - (1.0 - foamCover)) / max(foamCover, 1e-3), 0.0, 1.0);
if (below) { foam = foam * 0.2; }
var ext = surfaceExtNone(N);
diff --git a/src/esengine/renderer/draw/DrawList.cpp b/src/esengine/renderer/draw/DrawList.cpp
index 4651256c5..5d7d46323 100644
--- a/src/esengine/renderer/draw/DrawList.cpp
+++ b/src/esengine/renderer/draw/DrawList.cpp
@@ -510,12 +510,6 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,
}
device.setPipeline(lastHandle);
- // Per-material constants (binding 1): upload-if-dirty + bind this draw's material UBO.
- // A no-op for material 0 and for materials whose shader declares no params.
- if (cmd.material_id != 0) {
- materials.bindForDraw(cmd.material_id);
- }
-
if (cmd.skin_count > 0 && blocks.skin) {
blocks.skin->bind(SKIN_CONSTANTS_BINDING, staged.skin);
}
@@ -554,6 +548,14 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,
}
}
+ // Per-material constants (binding 1) and textures: upload-if-dirty + bind this draw's material UBO. A no-op for material 0 and
+ // for materials whose shader declares no params. After the draw's own units, because a material past seven textures takes units
+ // below the base that its shader never reads from the draw (ShaderParser::materialOverflowUnits): the material's binding is the
+ // one this draw samples there.
+ if (cmd.material_id != 0) {
+ materials.bindForDraw(cmd.material_id);
+ }
+
if (cmd.hasPersistentGeometry()) {
// Geometry the GPU already holds: instanced when it is a mesh placed by records, plain when it is a run of quads a plugin keeps
// between frames (a tilemap's chunk strip), which has no records and draws once.
diff --git a/src/esengine/renderer/store/EngineTextureUnits.hpp b/src/esengine/renderer/store/EngineTextureUnits.hpp
new file mode 100644
index 000000000..b68dd084a
--- /dev/null
+++ b/src/esengine/renderer/store/EngineTextureUnits.hpp
@@ -0,0 +1,66 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file EngineTextureUnits.hpp
+ * @brief The samplers the engine injects into a shader, and the texture unit each is pinned to.
+ * @details One table for the three that act on it: Shader::compile pins the samplers, BatchBuilder fills a draw's units with what
+ * they read, and ShaderParser hands a material texture only a unit its shader does not read from here. Dependency free,
+ * so the parser and its native harness take it without the renderer's math.
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#pragma once
+
+#include "../../core/Types.hpp"
+
+namespace esengine {
+
+/**
+ * @brief The injected shadow-map sampler, and the texture unit Shader::compile pins it to.
+ * @details Every Lit shader gets the sampler from the injected header, so the unit is a
+ * contract rather than something each compile site repeats. Slot 2 sits after the
+ * draw's own two (base colour, normal map) — see BatchBuilder's slot assembly.
+ */
+inline constexpr const char* SHADOW_MAP_SAMPLER = "u_shadowMap";
+inline constexpr u32 SHADOW_MAP_TEXTURE_UNIT = 2;
+
+/** @brief The injected reflection sampler, one unit past the shadow map's. */
+inline constexpr const char* ENV_MAP_SAMPLER = "u_envMap";
+inline constexpr u32 ENV_MAP_TEXTURE_UNIT = 3;
+
+/** @brief The sampler a mesh's morph deltas arrive through, and the unit it is pinned to. */
+inline constexpr const char* MORPH_DELTA_SAMPLER = "u_morphDeltas";
+inline constexpr u32 MORPH_DELTA_TEXTURE_UNIT = 4;
+
+/**
+ * @brief The baked-light atlas, and the unit a lightmapped mesh samples it from.
+ * @details Unit 5 and not 4: the morph deltas hold that one and 6/7 are the
+ * frame's 2D masks, so this is the last a draw's own stream can claim.
+ * A lit fragment ADDS the bake as its indirect term; an unlit one takes
+ * it as the whole of its light.
+ */
+inline constexpr const char* LIGHTMAP_SAMPLER = "u_lightmap";
+inline constexpr u32 LIGHTMAP_TEXTURE_UNIT = 5;
+
+/**
+ * @brief The 2D light-shape mask, and the unit below the shadow mask's.
+ * @details The same target shape carrying the other half of "how much of this light is
+ * here": what its SHAPE covers, drawn as the light's own cookie. Two planes
+ * rather than one channel, because a fragment needs both numbers to multiply
+ * them — a single channel could only carry their sum.
+ */
+inline constexpr const char* SHAPE_2D_SAMPLER = "u_lightShape2D";
+inline constexpr u32 SHAPE_2D_TEXTURE_UNIT = 6;
+
+/**
+ * @brief The 2D shadow mask, and the texture unit every Lit shader samples it from.
+ * @details One screen-sized RGBA8 target, a channel per casting light: the shadow pass
+ * draws what each occluder hides and a Lit fragment reads its own channel at
+ * its own pixel. Unit 7 is the top of the batch stream's eight, taken from it
+ * only while a mask exists — so a scene with no 2D shadows pays no merge slot.
+ */
+inline constexpr const char* SHADOW_2D_SAMPLER = "u_shadow2D";
+inline constexpr u32 SHADOW_2D_TEXTURE_UNIT = 7;
+
+} // namespace esengine
diff --git a/src/esengine/renderer/store/LightConstants.hpp b/src/esengine/renderer/store/LightConstants.hpp
index 1d6affe4a..ecd63fbba 100644
--- a/src/esengine/renderer/store/LightConstants.hpp
+++ b/src/esengine/renderer/store/LightConstants.hpp
@@ -13,6 +13,7 @@
#pragma once
#include "../../core/Types.hpp"
+#include "./EngineTextureUnits.hpp"
#include "./TiledLights.hpp"
#include <algorithm>
@@ -26,29 +27,6 @@ inline constexpr u32 LIGHT_CONSTANTS_BINDING = 2;
/** @brief GLSL block name; must match ShaderParser's injected block + Shader::compile lookup. */
inline constexpr const char* LIGHT_CONSTANTS_BLOCK = "LightConstants";
-/**
- * @brief The injected shadow-map sampler, and the texture unit Shader::compile pins it to.
- * @details Every Lit shader gets the sampler from the injected header, so the unit is a
- * contract rather than something each compile site repeats. Slot 2 sits after the
- * draw's own two (base colour, normal map) — see BatchBuilder's slot assembly.
- */
-inline constexpr const char* SHADOW_MAP_SAMPLER = "u_shadowMap";
-inline constexpr u32 SHADOW_MAP_TEXTURE_UNIT = 2;
-
-/** @brief The injected reflection sampler, one unit past the shadow map's. */
-inline constexpr const char* ENV_MAP_SAMPLER = "u_envMap";
-inline constexpr u32 ENV_MAP_TEXTURE_UNIT = 3;
-
-/**
- * @brief The baked-light atlas, and the unit a lightmapped mesh samples it from.
- * @details Unit 5 and not 4: the morph deltas hold that one and 6/7 are the
- * frame's 2D masks, so this is the last a draw's own stream can claim.
- * A lit fragment ADDS the bake as its indirect term; an unlit one takes
- * it as the whole of its light.
- */
-inline constexpr const char* LIGHTMAP_SAMPLER = "u_lightmap";
-inline constexpr u32 LIGHTMAP_TEXTURE_UNIT = 5;
-
/**
* @brief Max simultaneous 2D lights packed into the UBO. The injected fragment loop is a fixed
* bound; inactive slots are zeroed (intensity 0) so they contribute nothing. Must match
@@ -56,26 +34,6 @@ inline constexpr u32 LIGHTMAP_TEXTURE_UNIT = 5;
*/
inline constexpr u32 MAX_LIGHTS = 16;
-/**
- * @brief The 2D shadow mask, and the texture unit every Lit shader samples it from.
- * @details One screen-sized RGBA8 target, a channel per casting light: the shadow pass
- * draws what each occluder hides and a Lit fragment reads its own channel at
- * its own pixel. Unit 7 is the top of the batch stream's eight, taken from it
- * only while a mask exists — so a scene with no 2D shadows pays no merge slot.
- */
-inline constexpr const char* SHADOW_2D_SAMPLER = "u_shadow2D";
-inline constexpr u32 SHADOW_2D_TEXTURE_UNIT = 7;
-
-/**
- * @brief The 2D light-shape mask, and the unit below the shadow mask's.
- * @details The same target shape carrying the other half of "how much of this light is
- * here": what its SHAPE covers, drawn as the light's own cookie. Two planes
- * rather than one channel, because a fragment needs both numbers to multiply
- * them — a single channel could only carry their sum.
- */
-inline constexpr const char* SHAPE_2D_SAMPLER = "u_lightShape2D";
-inline constexpr u32 SHAPE_2D_TEXTURE_UNIT = 6;
-
/** @brief Lights whose SHAPE one frame can carry — the shape mask's four channels. */
inline constexpr u32 MAX_SHAPE_2D_LIGHTS = 4;
diff --git a/src/esengine/renderer/store/MaterialStore.cpp b/src/esengine/renderer/store/MaterialStore.cpp
index 8873cdd33..f4a37c322 100644
--- a/src/esengine/renderer/store/MaterialStore.cpp
+++ b/src/esengine/renderer/store/MaterialStore.cpp
@@ -411,8 +411,9 @@ void MaterialStore::bindForDraw(u32 materialId) {
device_->setUniformBuffer(MATERIAL_CONSTANTS_BINDING, rec.ubo);
}
- // Texture params — bound to their sampler units (>= MATERIAL_TEXTURE_UNIT_BASE), above the
- // batch path's 0..7. Iterate the shader's layout (not just the material's explicit bindings)
+ // Texture params — bound to their sampler units: MATERIAL_TEXTURE_UNIT_BASE upward, then any
+ // unit below it the shader never reads from the draw (ShaderParser::materialOverflowUnits), which
+ // is why the draw binds its own units first. Iterate the shader's layout (not just the material's explicit bindings)
// so an unset param binds its declared default (white/black/flatnormal) instead of sampling
// whatever stale texture is at the unit.
if (lit != layouts_.end()) {
diff --git a/src/esengine/renderer/store/MorphConstants.hpp b/src/esengine/renderer/store/MorphConstants.hpp
index 6771b5c10..aa1e9472e 100644
--- a/src/esengine/renderer/store/MorphConstants.hpp
+++ b/src/esengine/renderer/store/MorphConstants.hpp
@@ -16,6 +16,7 @@
#pragma once
#include "../../core/Types.hpp"
+#include "./EngineTextureUnits.hpp"
#include "../rhi/GfxEnums.hpp"
#include "../../math/Math.hpp"
@@ -27,10 +28,6 @@ inline constexpr u32 MORPH_CONSTANTS_BINDING = 6;
/** @brief GLSL block name; must match the shader's declaration + Shader::compile lookup. */
inline constexpr const char* MORPH_CONSTANTS_BLOCK = "MorphConstants";
-/** @brief The sampler the deltas arrive through, and the unit it is pinned to. */
-inline constexpr const char* MORPH_DELTA_SAMPLER = "u_morphDeltas";
-inline constexpr u32 MORPH_DELTA_TEXTURE_UNIT = 4;
-
/** @brief std140 mirror of the block. */
struct MorphConstants {
/// x = live shapes below, y = vertices, z = texels one vertex occupies (2
diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cpp
index 0d0977b26..3b4706c59 100644
--- a/src/esengine/resource/ShaderParser.cpp
+++ b/src/esengine/resource/ShaderParser.cpp
@@ -14,6 +14,7 @@
#include "ShaderParser.hpp"
#include "../core/Log.hpp"
#include "../renderer/store/InstanceConstants.hpp"
+#include "../renderer/store/EngineTextureUnits.hpp"
#include "../renderer/store/MaterialConstants.hpp"
#include "../renderer/rhi/GfxEnums.hpp"
#include "../renderer/rhi/WgslBindings.hpp"
@@ -1162,9 +1163,23 @@ const char* kTimeHeaderWGSL =
// de-combined into texture_2d t0..t7 (bindings 0..7) + samplers s0..s7
// (bindings 8..15) — the group-1 convention (WebGPUMappings). Bodies sample
// `textureSampleLevel(t0, s0, uv, 0.0)` where GLSL reads u_textures[0].
-std::string wgslBatchTextureDecls(bool postProcess) {
+/** The units below the material base a material texture of @p parsed took (see ShaderParser::materialOverflowUnits). */
+u32 materialLowUnits(const ParsedShader& parsed) {
+ u32 mask = 0;
+ for (const auto& p : parsed.properties) {
+ if (p.fromParam && p.type == ShaderPropertyType::Texture && p.textureUnit >= 0
+ && p.textureUnit < static_cast<i32>(MATERIAL_TEXTURE_UNIT_BASE)) {
+ mask |= 1u << p.textureUnit;
+ }
+ }
+ return mask;
+}
+
+std::string wgslBatchTextureDecls(bool postProcess, u32 materialUnits = 0) {
std::string src;
for (u32 i = 0; i < 8; ++i) {
+ // A batch unit a material texture took is that texture's binding now: the shader reads no batch texture there.
+ if ((materialUnits & (1u << i)) != 0) continue;
const std::string n = std::to_string(i);
// A fullscreen pass reads the scene's DEPTH at the top engine unit, and a
// depth texture is its own WGSL type with no sampler under it. PostProcess
@@ -1223,10 +1238,10 @@ std::string wgslMaterialTextureDecls(const ParsedShader& parsed, const std::stri
if (!p.fromParam || p.type != ShaderPropertyType::Texture || p.textureUnit < 0) continue;
if (only && only->find(p.name) == std::string::npos) continue;
const u32 unit = static_cast<u32>(p.textureUnit);
- src += "@group(1) @binding(" + std::to_string(unit + 8) + ") var " + p.name +
+ src += "@group(1) @binding(" + std::to_string(textureBindingForUnit(unit)) + ") var " + p.name +
(p.layered ? " : texture_2d_array<f32>;\n" : " : texture_2d<f32>;\n");
if (body.find(p.name + "_s") == std::string::npos) continue;
- src += "@group(1) @binding(" + std::to_string(unit + 16) + ") var " + p.name +
+ src += "@group(1) @binding(" + std::to_string(samplerBindingForUnit(unit)) + ") var " + p.name +
"_s : sampler;\n";
}
return src;
@@ -2434,7 +2449,7 @@ ShaderParser::AssembledStage assembleWGSLStage(const ParsedShader& parsed,
// 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(parsed.domain == "PostProcess"));
+ inject(wgslBatchTextureDecls(parsed.domain == "PostProcess", materialLowUnits(parsed)));
}
inject(kFrameHeaderWGSL);
inject(kTimeHeaderWGSL);
@@ -3915,6 +3930,75 @@ ShaderProperty ShaderParser::parseParamDirective(const std::string& argument) {
return prop;
}
+namespace {
+
+/** Whether @p text names @p word as a whole identifier. */
+bool namesIdentifier(const std::string& text, std::string_view word) {
+ const auto isIdent = [](char c) { return std::isalnum(static_cast<unsigned char>(c)) || c == '_'; };
+ for (usize at = text.find(word); at != std::string::npos; at = text.find(word, at + 1)) {
+ const bool startOk = at == 0 || !isIdent(text[at - 1]);
+ const usize end = at + word.size();
+ if (startOk && (end >= text.size() || !isIdent(text[end]))) return true;
+ }
+ return false;
+}
+
+} // namespace
+
+/**
+ * The units below MATERIAL_TEXTURE_UNIT_BASE a material texture may take on @p shader, as a mask.
+ * @details The engine binds those units per draw, so one is free only where this shader never reads what the engine puts
+ * there. Two questions decide it. What the domain's injected code reads: a Lit stage takes the shadow map, the
+ * reflection atlas, the bake and both 2D masks, and every mesh variant takes the morph deltas. And what the
+ * shader's own text names, in either language, all variants at once: the batch textures (u_textures, every one
+ * of 0..7, since a merged run puts its sprites there), an engine sampler by name, or a `tN`/`sN` unit. A
+ * fullscreen pass and the UI reach their low units through their own conventions, so they keep none free.
+ */
+u32 ShaderParser::materialOverflowUnits(const ParsedShader& shader) {
+ u32 reads = 0;
+ if (shader.domain == "Lit") {
+ reads = (1u << SHADOW_MAP_TEXTURE_UNIT) | (1u << ENV_MAP_TEXTURE_UNIT) | (1u << MORPH_DELTA_TEXTURE_UNIT)
+ | (1u << LIGHTMAP_TEXTURE_UNIT) | (1u << SHAPE_2D_TEXTURE_UNIT) | (1u << SHADOW_2D_TEXTURE_UNIT);
+ } else if (shader.domain == "Unlit") {
+ reads = 1u << MORPH_DELTA_TEXTURE_UNIT;
+ } else {
+ return 0;
+ }
+
+ std::string glsl = shader.sharedCode + shader.vertexHook;
+ for (const auto& [stage, source] : shader.stages) glsl += source;
+ for (const auto& [platform, source] : shader.variants) glsl += source;
+ std::string wgsl = shader.wgslVertexHook;
+ for (const auto& [stage, source] : shader.wgslStages) wgsl += source;
+ const std::string both = glsl + wgsl;
+
+ if (namesIdentifier(both, "u_textures")) reads |= 0xFFu;
+ static constexpr struct { const char* name; u32 unit; } kEngine[] = {
+ {SHADOW_MAP_SAMPLER, SHADOW_MAP_TEXTURE_UNIT}, {ENV_MAP_SAMPLER, ENV_MAP_TEXTURE_UNIT},
+ {MORPH_DELTA_SAMPLER, MORPH_DELTA_TEXTURE_UNIT}, {LIGHTMAP_SAMPLER, LIGHTMAP_TEXTURE_UNIT},
+ {SHAPE_2D_SAMPLER, SHAPE_2D_TEXTURE_UNIT}, {SHADOW_2D_SAMPLER, SHADOW_2D_TEXTURE_UNIT},
+ };
+ for (const auto& e : kEngine) {
+ if (namesIdentifier(both, e.name)) reads |= 1u << e.unit;
+ }
+ u32 reachedTex = 0;
+ u32 reachedSam = 0;
+ scanWGSLReachedUnits(wgsl.c_str(), reachedTex, reachedSam);
+ reads |= reachedTex | reachedSam;
+
+ return ~reads & ((1u << MATERIAL_TEXTURE_UNIT_BASE) - 1u);
+}
+
+/** The next unit to hand out of @p free (see materialOverflowUnits), highest first, or -1 when none is left. */
+i32 ShaderParser::takeOverflowUnit(u32& free) {
+ for (i32 unit = static_cast<i32>(MATERIAL_TEXTURE_UNIT_BASE) - 1; unit >= 0; --unit) {
+ if ((free & (1u << unit)) == 0) continue;
+ free &= ~(1u << unit);
+ return unit;
+ }
+ return -1;
+}
+
void ShaderParser::computeMaterialLayout(ParsedShader& shader) {
// std140 size/alignment for the supported scalar/vector param types.
auto sizeAlign = [](ShaderPropertyType t, u32& size, u32& align) {
@@ -3931,27 +4015,34 @@ void ShaderParser::computeMaterialLayout(ParsedShader& shader) {
auto alignUp = [](u32 v, u32 a) -> u32 { return a == 0 ? v : (v + a - 1) & ~(a - 1); };
// Material texture units start above the batch path's 0..7 slots
- // (must match renderer/MaterialConstants.hpp MATERIAL_TEXTURE_UNIT_BASE).
- u32 textureUnit = 8;
+ // (must match renderer/MaterialConstants.hpp MATERIAL_TEXTURE_UNIT_BASE). Past
+ // those, a texture takes a unit below the base that THIS shader never reads.
+ u32 textureUnit = MATERIAL_TEXTURE_UNIT_BASE;
+ u32 overflowFree = materialOverflowUnits(shader);
u32 offset = 0;
for (auto& p : shader.properties) {
if (!p.fromParam) continue; // legacy properties-block entries are reflection-only
if (p.type == ShaderPropertyType::Texture) {
+ p.std140Offset = -1;
// The top unit is the frame's per-object record, on every mesh shader
// there is. Handing it out here would bind a material's texture over
// the records and draw every object at the origin.
- if (textureUnit >= MESH_INSTANCE_TEXTURE_UNIT) {
- ES_LOG_ERROR("shader {}: texture param \"{}\" would take unit {}, which is the"
- " per-object record; a material reads at most {} textures",
- shader.name, p.name, textureUnit,
- MESH_INSTANCE_TEXTURE_UNIT - MATERIAL_TEXTURE_UNIT_BASE);
- p.textureUnit = -1;
- p.std140Offset = -1;
+ if (textureUnit < MESH_INSTANCE_TEXTURE_UNIT) {
+ p.textureUnit = static_cast<i32>(textureUnit++);
continue;
}
- p.textureUnit = static_cast<i32>(textureUnit++);
- p.std140Offset = -1;
+ const i32 low = takeOverflowUnit(overflowFree);
+ if (low >= 0) {
+ p.textureUnit = low;
+ continue;
+ }
+ ES_LOG_ERROR("shader {}: texture param \"{}\" finds no free texture unit: units {}..{} are"
+ " taken, and the {} domain leaves none of the engine's units below {} that this"
+ " shader does not read",
+ shader.name, p.name, MATERIAL_TEXTURE_UNIT_BASE, MESH_INSTANCE_TEXTURE_UNIT - 1,
+ shader.domain, MATERIAL_TEXTURE_UNIT_BASE);
+ p.textureUnit = -1;
continue;
}
u32 size = 0, align = 0;
diff --git a/src/esengine/resource/ShaderParser.hpp b/src/esengine/resource/ShaderParser.hpp
index 559708bd4..4f6233e37 100644
--- a/src/esengine/resource/ShaderParser.hpp
+++ b/src/esengine/resource/ShaderParser.hpp
@@ -398,6 +398,14 @@ private:
/// and sets ParsedShader::materialBlockSize. Run once after all params are collected.
static void computeMaterialLayout(ParsedShader& shader);
+public:
+ /// The units below the material base a texture param may take on @p shader (a mask): the ones it never reads from the engine.
+ static u32 materialOverflowUnits(const ParsedShader& shader);
+
+private:
+ /// Takes the highest unit left in @p free, or -1.
+ static i32 takeOverflowUnit(u32& free);
+
static ShaderProperty parsePropertyAnnotation(const std::string& line);
static ShaderPropertyType stringToPropertyType(const std::string& typeStr);
diff --git a/tests/renderer/test_shader_variant.cpp b/tests/renderer/test_shader_variant.cpp
index df9fa6776..00b1409af 100644
--- a/tests/renderer/test_shader_variant.cpp
+++ b/tests/renderer/test_shader_variant.cpp
@@ -241,6 +241,67 @@ static void testTextureArrayParam() {
"WGSL declares the array param as texture_2d_array at its unit's bindings");
}
+// A material shader with `count` texture params u_m0.., each sampled in both languages; `extraGlsl` / `extraWgsl` go into the
+// fragment bodies, so a case can make the shader read an engine unit.
+static std::string manyTextures(const char* domain, int count, const std::string& extraGlsl = "",
+ const std::string& extraWgsl = "") {
+ std::string src = std::string("#pragma shader \"Many\"\n#pragma version 300 es\n#pragma domain ") + domain + "\n";
+ for (int i = 0; i < count; ++i) src += "#pragma param u_m" + std::to_string(i) + " texture default(white)\n";
+ src += "#pragma fragment\nprecision mediump float;\nin vec2 v_texCoord;\nout vec4 fragColor;\nvoid main() {\n"
+ " vec4 c = vec4(0.0);\n";
+ for (int i = 0; i < count; ++i) src += " c += texture(u_m" + std::to_string(i) + ", v_texCoord);\n";
+ src += extraGlsl + " fragColor = c;\n}\n#pragma end\n";
+ src += "#pragma fragment wgsl\n@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {\n var c = vec4f(0.0);\n";
+ for (int i = 0; i < count; ++i) {
+ const std::string n = "u_m" + std::to_string(i);
+ src += " c += textureSample(" + n + ", " + n + "_s, v.v_texCoord);\n";
+ }
+ src += extraWgsl + " return c;\n}\n#pragma end\n";
+ return src;
+}
+
+static int unitOf(const ParsedShader& p, const std::string& name) {
+ for (const auto& prop : p.properties) if (prop.name == name) return prop.textureUnit;
+ return -100;
+}
+
+static void testMaterialOverflowUnits() {
+ // Seven fill the material units as before; the rest take engine units this shader never reads, highest first.
+ ParsedShader unlit = ShaderParser::parse(manyTextures("Unlit", 9));
+ CHECK(unlit.valid, "a nine-texture Unlit shader parses");
+ CHECK(unitOf(unlit, "u_m0") == 8 && unitOf(unlit, "u_m6") == 14, "the first seven keep units 8..14");
+ CHECK(unitOf(unlit, "u_m7") == 7 && unitOf(unlit, "u_m8") == 6, "an Unlit shader's eighth and ninth take units 7 and 6");
+
+ const std::string wgsl = ShaderParser::assembleStage(unlit, ShaderStage::Fragment, "", {}, ShaderTargetLanguage::WGSL);
+ CHECK(wgsl.find("@group(1) @binding(7) var u_m7 : texture_2d<f32>;") != std::string::npos &&
+ wgsl.find("@group(1) @binding(15) var u_m7_s : sampler;") != std::string::npos &&
+ wgsl.find("@group(1) @binding(6) var u_m8 : texture_2d<f32>;") != std::string::npos,
+ "WGSL declares a low unit at the batch range's bindings");
+ CHECK(wgsl.find("var t7 :") == std::string::npos && wgsl.find("var s7 :") == std::string::npos &&
+ wgsl.find("var t6 :") == std::string::npos && wgsl.find("var t5 :") != std::string::npos,
+ "the batch declarations leave out exactly the units a material took");
+
+ // Lit reads the shadow map, reflections, morph, bake and both 2D masks (2..7): only 1 and 0 are left.
+ ParsedShader lit = ShaderParser::parse(manyTextures("Lit", 9));
+ CHECK(lit.valid && unitOf(lit, "u_m7") == 1 && unitOf(lit, "u_m8") == 0, "a Lit shader overflows into units 1 and 0");
+ ParsedShader litFull = ShaderParser::parse(manyTextures("Lit", 10));
+ CHECK(unitOf(litFull, "u_m9") == -1, "a Lit shader's tenth texture finds no unit");
+
+ // What the shader's own text reads is not free, in either language.
+ ParsedShader readsBatch = ShaderParser::parse(manyTextures("Unlit", 8, " c += texture(u_textures[0], v_texCoord);\n"));
+ CHECK(unitOf(readsBatch, "u_m7") == -1, "a shader that reads the batch textures keeps all of 0..7");
+ ParsedShader readsT7 = ShaderParser::parse(manyTextures("Unlit", 8, "", " c += textureSample(t7, s7, v.v_texCoord);\n"));
+ CHECK(unitOf(readsT7, "u_m7") == 6, "a WGSL twin that reads t7 leaves unit 7 alone");
+ ParsedShader readsShape = ShaderParser::parse(manyTextures("Unlit", 8, " c += texture(u_lightShape2D, v_texCoord);\n"));
+ CHECK(unitOf(readsShape, "u_m7") == 7, "u_lightShape2D (unit 6) does not stop unit 7");
+ ParsedShader readsShadow2D = ShaderParser::parse(manyTextures("Unlit", 8, " c += texture(u_shadow2D, v_texCoord);\n"));
+ CHECK(unitOf(readsShadow2D, "u_m7") == 6, "u_shadow2D keeps unit 7 for the engine");
+
+ // A fullscreen pass reaches its low units through its own conventions.
+ ParsedShader post = ShaderParser::parse(manyTextures("PostProcess", 8));
+ CHECK(unitOf(post, "u_m6") == 14 && unitOf(post, "u_m7") == -1, "a PostProcess shader stays at seven");
+}
+
static void testWGSLEmission() {
const auto wgsl = [](const ParsedShader& p, ShaderStage s,
const std::vector<std::string>& features = {}) {
@@ -736,6 +797,7 @@ int main() {
testHandWrittenFrameBlock();
testWGSLEmission();
testTextureArrayParam();
+ testMaterialOverflowUnits();
testSystemValuesTrailAttributes();
testVertexHook();
testShadowGraft();