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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(shader): a param may not take a name the engine declares for its domain, read from what the engine injects rather than a list of three
yhhffd78a11fc77
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ce5703332..f33fe4f44 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,7 @@ published separately; it ships inside the editor.### Fixed+- **A material parameter named like an engine uniform is refused on every platform.** A `#pragma param u_ambient` in a `Lit` shader compiled on WebGPU and failed only on WebGL, a WeChat mini-game among them, with `redefinition of an interface block member name`. The names a parameter may not take are no longer a hand-kept list of three: they are read from what the engine actually declares for the shader's domain, so every member of the light block is refused at load, a name only the light block uses stays free in an `Unlit` shader, and the error says which block owns it.- **World text under a perspective camera no longer eats the memory.** A `Text` left on `renderMode: Auto` in world space, seen through a perspective camera, was rasterized as if the camera were orthographic: a 32 px label asked for glyphs tens of thousands of pixels high. On a phone the native heap swung between 2.4 and 4.2 GB and the game drew about one frame in two seconds. Auto now draws world text under a perspective camera as SDF, since no single bitmap size lands 1:1 at every depth; the same eight floating labels hold the heap at about 45 MB and 60 fps. A bitmap glyph is also never rasterized larger than half an atlas page (512 px), which also covers an orthographic camera zoomed far in and a forced `Bitmap`; past that it is drawn from 512 px and the log says so once.- **Sound comes back when a device's audio dies on its own.** On the Android and iOS hosts, a game whose audio device did not start again on returning from the background, or whose output stream was dropped while it was away, stayed silent until it was restarted. The host now checks every frame that the device is still taking sound while the game wants it; after half a second of nothing it restarts the device, and from the third try rebuilds it, retrying at growing intervals of up to 5 seconds. Sounds that were playing carry on where they were, and the log says each time it acts.- **A render target works on a native device.** On the Android and iOS hosts `RenderTexture.create` handed back 0 for its handle and its texture, so a camera's `renderTarget` and anything painted into a texture drew nothing, and nothing was logged. The SDK asked only the web's engine module for a target; it now asks whichever engine core is running, and a device names the target's texture for a `Sprite` as the web does. A target that cannot be made is now reported once in the log.diff --git a/docs/astro/src/content/docs/graphics/materials.mdx b/docs/astro/src/content/docs/graphics/materials.mdxindex db87e5619..5f8718911 100644--- a/docs/astro/src/content/docs/graphics/materials.mdx+++ b/docs/astro/src/content/docs/graphics/materials.mdx@@ -169,7 +169,7 @@ One file holds every stage plus its metadata, separated by pragmas:| `#pragma shader "Name"` | Display name. || `#pragma version 300 es` | GLSL version line for every stage. || `#pragma domain <D>` | `Unlit` (default), `Lit`, `PostProcess`, `UI`. `Lit` injects the lighting uniforms + helpers. The older spellings `Unlit2D` / `Lit2D` still load as these. |-| `#pragma param …` | A reflected material parameter (table below). |+| `#pragma param …` | A reflected material parameter (table below). A name the engine already declares for the shader's domain (`u_time`, `u_viewport`, `u_projection` everywhere; the light block's `u_ambient`, `u_lights`, `u_shadowMatrix` … in a `Lit` shader) is refused when the shader loads, on every platform: WebGL keeps every block member in one namespace, so the second declaration would not compile there. || `#pragma switch NAME [default(on)]` | Material-facing static permutation toggle (a `#define`). || `#pragma feature NAME` | Engine-chosen compile-time variant keyword. || `#pragma lighting direct` | A `Lit` shader lit by the sixteen lights of the block and hard-edged shadows only. It compiles without the tiled lights past those sixteen, the 2D light masks, and soft and hair shadows, which every pixel pays for on a phone whether a scene uses them or not. A light with a size (a sun's `sourceAngle`) casts a hard shadow here. The Water shader declares it, and the `low` and `medium` quality levels compile every lit mesh this way (see [Lighting on a phone](/docs/graphics/lighting/#lighting-on-a-phone)). |diff --git a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdxindex 06b1aec0c..ba50dccde 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx@@ -138,7 +138,7 @@ Terrain、Foliage、Water、Hair、Skin、Eye 这几个模板属于各自的模| `#pragma shader "Name"` | 显示名。 || `#pragma version 300 es` | 每个 stage 的 GLSL 版本行。 || `#pragma domain <D>` | `Unlit`(默认)、`Lit`、`PostProcess`、`UI`。`Lit` 注入光照 uniform + helper。旧拼写 `Unlit2D` / `Lit2D` 仍按这两个域加载。 |-| `#pragma param …` | 反射的材质参数(见下表)。 |+| `#pragma param …` | 反射的材质参数(见下表)。与引擎为该域已声明的名字重名会在着色器加载时被拒绝,所有平台一致(任何域都有的 `u_time`、`u_viewport`、`u_projection`;`Lit` 着色器里光照块的 `u_ambient`、`u_lights`、`u_shadowMatrix` 等):WebGL 里所有块成员共用一个命名空间,重复声明在那里编译不过。 || `#pragma switch NAME [default(on)]` | 材质可控的静态排列开关(一个 `#define`)。 || `#pragma coverage PARAM` | 浮点参数 `PARAM` 大于零时,着色器输出的 alpha 就是覆盖率——镂空的 alpha 在阈值附近锐化到约一个像素宽(`cutoutCoverage(alpha, cutoff, fwidth(alpha))`)。不透明物体画进多重采样目标时,它会转成多重采样覆盖率,镂空边缘就有抗锯齿而不是台阶;没有多重采样时就是硬切。任何距离都在阈值处切,与 glTF 的 MASK 定义一致:镂空缩小显示时之所以还保持原来的面积,是因为烘焙时把每级 mip 的 alpha 缩放到与原图在阈值处相同的覆盖率。内置 Model 着色器声明了 `u_alphaCutoff`。 || `#pragma feature NAME` | 引擎选择的编译期变体关键字。 |diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cppindex 8d1f88341..0d5457d68 100644--- a/src/esengine/resource/ShaderParser.cpp+++ b/src/esengine/resource/ShaderParser.cpp@@ -24,6 +24,8 @@#include <cctype>#include <cstdlib>#include <cstring>+#include <mutex>+#include <unordered_map>#include <unordered_set>namespace esengine::resource {@@ -733,6 +735,76 @@ enum class ParseState {VertexHook};+namespace {++bool identChar(char c) { return std::isalnum(static_cast<unsigned char>(c)) || c == '_'; }++std::string declaredName(std::string_view decl) {+ const size_t bracket = decl.find('[');+ if (bracket != std::string_view::npos) decl = decl.substr(0, bracket);+ while (!decl.empty() && !identChar(decl.back())) decl.remove_suffix(1);+ size_t start = decl.size();+ while (start > 0 && identChar(decl[start - 1])) --start;+ return std::string(decl.substr(start));+}++void collectUniformNames(const std::string& glsl, std::unordered_map<std::string, std::string>& out) {+ size_t at = 0;+ while ((at = glsl.find("uniform ", at)) != std::string::npos) {+ if (at > 0 && identChar(glsl[at - 1])) { at += 8; continue; }+ const size_t end = glsl.find_first_of("{;", at);+ if (end == std::string::npos) break;+ if (glsl[end] == ';') {+ const std::string name = declaredName(std::string_view(glsl).substr(at, end - at));+ if (!name.empty()) out.emplace(name, "a uniform");+ at = end + 1;+ continue;+ }+ const std::string block = declaredName(std::string_view(glsl).substr(at, end - at));+ const size_t close = glsl.find('}', end);+ if (close == std::string::npos) break;+ size_t member = end + 1;+ while (member < close) {+ const size_t semi = glsl.find(';', member);+ if (semi == std::string::npos || semi > close) break;+ std::string_view line = std::string_view(glsl).substr(member, semi - member);+ const size_t hash = line.rfind('\n');+ if (hash != std::string_view::npos) line = line.substr(hash + 1);+ const std::string name = declaredName(line);+ if (!name.empty() && line.find('#') == std::string_view::npos) out.emplace(name, block);+ member = semi + 1;+ }+ at = close + 1;+ }+}++const std::unordered_map<std::string, std::string>& engineUniformNames(const ParsedShader& parsed) {+ static std::mutex lock;+ static std::unordered_map<std::string, std::unordered_map<std::string, std::string>> byDomain;+ std::lock_guard<std::mutex> guard(lock);+ const std::string key = parsed.domain + (parsed.vertexIsCanonical ? "|canonical" : "|own");+ auto found = byDomain.find(key);+ if (found != byDomain.end()) return found->second;++ ParsedShader probe;+ probe.valid = true;+ probe.version = parsed.version;+ probe.domain = parsed.domain;+ probe.vertexIsCanonical = parsed.vertexIsCanonical;+ probe.stages[ShaderStage::Vertex] = parsed.vertexIsCanonical ? parsed.stages.at(ShaderStage::Vertex) : "void main() {}\n";+ probe.stages[ShaderStage::Fragment] = "void main() {}\n";+ const std::vector<std::string> everything{+ "MESH", "MESH_NORMALS", "MESH_TANGENTS", "MESH_LIGHTMAP", "SKINNED", "ES_RECEIVE_SHADOW",+ "ES_ENV_MAP", "ES_SURFACE_3D", "ES_GBUFFER", "ES_VELOCITY"};+ auto& names = byDomain[key];+ for (const ShaderStage stage : {ShaderStage::Vertex, ShaderStage::Fragment}) {+ collectUniformNames(ShaderParser::assembleStage(probe, stage, "", everything, ShaderTargetLanguage::GLSL_ES300), names);+ }+ return names;+}++} // namespace+// =============================================================================// Public Methods// =============================================================================@@ -801,19 +873,7 @@ ParsedShader ShaderParser::parse(const std::string& source, const ShaderIncludeR// Declarative material parameter: ShaderParser owns its std140 slot in the// generated MaterialConstants block (or a sampler unit for textures).ShaderProperty prop = parseParamDirective(argument);- if (!prop.name.empty()) {- // Engine-injected uniforms — a param with the same name would redeclare them.- if (prop.name == "u_time" || prop.name == "u_viewport" || prop.name == "u_projection") {- // Say what to do instead: the clock and the canvas size are- // already there, and the author wanted exactly them.- result.errorMessage = "#pragma param '" + prop.name +- "' is reserved: the engine injects it into every shader. Remove the param and read it directly "- "(GLSL: u_time.x = seconds, u_time.y = frame delta, u_viewport.xy = canvas pixels; "- "WGSL: tc.u_time / tc.u_viewport). Give a parameter of your own a different name.";- return result;- }- result.properties.push_back(prop);- }+ if (!prop.name.empty()) result.properties.push_back(prop);continue;}@@ -1058,6 +1118,23 @@ ParsedShader ShaderParser::parse(const std::string& source, const ShaderIncludeR}}+ if (!result.properties.empty()) {+ const auto& engine = engineUniformNames(result);+ for (const auto& prop : result.properties) {+ const auto clash = engine.find(prop.name);+ if (clash == engine.end()) continue;+ result.errorMessage = "#pragma param '" + prop.name + "' is reserved: the engine declares it in " ++ (clash->second == "a uniform" ? std::string("a uniform") : "the " + clash->second + " block") ++ " of every " + result.domain + " shader, and on WebGL two declarations of one name do not compile. " ++ (clash->second == "TimeConstants"+ ? "Read it directly instead (GLSL: u_time.x = seconds, u_time.y = frame delta, u_viewport.xy = canvas pixels; "+ "WGSL: tc.u_time / tc.u_viewport). "+ : "") ++ "Give a parameter of your own a different name.";+ return result;+ }+ }+computeMaterialLayout(result);result.valid = true;diff --git a/tests/renderer/test_shader_variant.cpp b/tests/renderer/test_shader_variant.cppindex e627b5b4f..e998cc283 100644--- a/tests/renderer/test_shader_variant.cpp+++ b/tests/renderer/test_shader_variant.cpp@@ -835,6 +835,27 @@ static void testLightingDirect() {"asked by the shader and the renderer, the define is written once");}+static ParsedShader paramShader(const char* domain, const char* param) {+ std::string src = std::string("#pragma shader \"P\"\n#pragma version 300 es\n#pragma domain ") + domain ++ "\n#pragma param " + param + " color default(0.3,0.3,0.3,1)\n#pragma fragment\nprecision highp float;\n"+ "out vec4 fragColor;\nvoid main() { fragColor = vec4(1.0); }\n#pragma end\n";+ return ShaderParser::parse(src);+}++static void testParamsTheEngineDeclares() {+ std::printf("\n-- #pragma param names the engine declares --\n");+ for (const char* name : {"u_ambient", "u_lights", "u_shadowMatrix", "u_envIrradiance"}) {+ const ParsedShader lit = paramShader("Lit", name);+ CHECK(!lit.valid && lit.errorMessage.find("is reserved") != std::string::npos+ && lit.errorMessage.find("LightConstants") != std::string::npos, name);+ }+ CHECK(paramShader("Unlit", "u_ambient").valid, "a name the Lit block takes is free in an Unlit shader, which has no light block");+ const ParsedShader time = paramShader("Unlit", "u_time");+ CHECK(!time.valid && time.errorMessage.find("u_time.x = seconds") != std::string::npos, "the clock is reserved everywhere, and the error says how to read it");+ CHECK(!paramShader("Lit", "u_projection").valid, "so is the frame's projection");+ CHECK(paramShader("Lit", "u_tint").valid && paramShader("Lit", "u_skyAmbient").valid, "a name of the author's own is taken as it is");+}+int main() {ParsedShader p = ShaderParser::parse(SRC);CHECK(p.valid, "shader parses");@@ -862,6 +883,7 @@ int main() {testVertexHook();testShadowGraft();testLightingDirect();+ testParamsTheEngineDeclares();if (g_failures == 0) {std::printf("\nALL SHADER-VARIANT TESTS PASSED\n");diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 6073b7c45..f4aa0f828 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -4124,4 +4124,6 @@ export const NOTED = {{"note": "Sound comes back when a device's audio dies on its own."},"fix(text): world text under a perspective camera draws as SDF, and no bitmap glyph is rasterized past half an atlas page":{"note": "World text under a perspective camera no longer eats the memory."},+ "fix(shader): a param may not take a name the engine declares for its domain, read from what the engine injects rather than a list of three":+ {"note": "A material parameter named like an engine uniform is refused on every platform."},};