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(render): a shader that will not compile says which binding is missing
esengine59764250cec9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 054f3c8d5..766fceb4a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -41,6 +41,18 @@ published separately; it ships inside the editor.### Fixed+- **A shader that fails to compile says why.** `ResourceManager` asked the device to+ build a program, got a reason back, and logged "Failed to create shader from source"+ without it — so the one thing that could have named the problem was the one thing+ dropped. It prints the device's own log now, for both backends.++ And on WebGPU the device refuses a WGSL stage that reaches a `tN`/`sN` binding it does+ not declare, naming it. That is an unresolved identifier, which WebGPU reports as an+ invalid *pipeline* with no shader named anywhere in it — an error that costs an hour to+ place and reads as a renderer bug. The repo's own shaders are held to the same rule by+ `check-wgsl-twin` before a push; this is what answers for a material somebody else+ wrote, where no gate of ours runs at all.+- **A 2D shadow caster can carry its own outline.** Every occluder was a box, so around prop threw a rectangle and a wall that was not rectangular threw the wrongwall. `ShadowCaster2D.path` is the shape itself — three points or more in thediff --git a/src/esengine/renderer/rhi/Shader.cpp b/src/esengine/renderer/rhi/Shader.cppindex b623a9251..78268330d 100644--- a/src/esengine/renderer/rhi/Shader.cpp+++ b/src/esengine/renderer/rhi/Shader.cpp@@ -288,11 +288,13 @@ bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSrShaderCompileOutcome Shader::createEx(GfxDevice& device,const std::string& vertexSrc,const std::string& fragmentSrc,- std::initializer_list<AttribBinding> bindings) {+ std::initializer_list<AttribBinding> bindings,+ GfxShaderLanguage language) {ShaderCompileOutcome outcome;auto shader = makeUnique<Shader>();shader->device_ = &device;- if (!shader->compile(vertexSrc, fragmentSrc, bindings, &outcome.log, &outcome.failedStage)) {+ if (!shader->compile(vertexSrc, fragmentSrc, bindings, &outcome.log, &outcome.failedStage,+ language)) {return outcome;}outcome.shader = std::move(shader);diff --git a/src/esengine/renderer/rhi/Shader.hpp b/src/esengine/renderer/rhi/Shader.hppindex 74bddda4a..136eccbd0 100644--- a/src/esengine/renderer/rhi/Shader.hpp+++ b/src/esengine/renderer/rhi/Shader.hpp@@ -142,7 +142,8 @@ public:static ShaderCompileOutcome createEx(GfxDevice& device,const std::string& vertexSrc,const std::string& fragmentSrc,- std::initializer_list<AttribBinding> bindings = {});+ std::initializer_list<AttribBinding> bindings = {},+ GfxShaderLanguage language = GfxShaderLanguage::GLSL_ES300);// =========================================================================// Operationsdiff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cppindex 0de0bba5d..2ea509ca3 100644--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp@@ -14,6 +14,7 @@#include <algorithm>#include <cstring>+#include <string>#include <vector>namespace esengine {@@ -1031,6 +1032,39 @@ ShaderHandle WebGPUDevice::createProgram(const GfxShaderSource& source,return ShaderHandle::Invalid;}+ // A stage that names `tN`/`sN` without declaring it cannot compile, and WebGPU says+ // so as an invalid PIPELINE naming no shader — so the refusal is here, where the+ // source is still in hand. check-wgsl-twin holds the repo's own to the same rule.+ const auto undeclared = [&](const char* src, const char* stage) -> bool {+ u32 reachedTex = 0;+ u32 reachedSam = 0;+ scanWGSLReachedUnits(src, reachedTex, reachedSam);+ const u32 declared = scanWGSLBindingMask(src, 1);+ for (u32 unit = 0; unit < 16; ++unit) {+ const bool tex = (reachedTex & (1u << unit)) != 0+ && (declared & (1u << textureBindingForUnit(unit))) == 0;+ const bool sam = (reachedSam & (1u << unit)) != 0+ && (declared & (1u << samplerBindingForUnit(unit))) == 0;+ if (!tex && !sam) continue;+ if (outLog) {+ *outLog = std::string("the ") + stage + " stage reaches "+ + (tex ? "t" : "s") + std::to_string(unit) + " and declares no binding for it";+ }+ ES_LOG_ERROR("WebGPUDevice::createProgram: the {} stage reaches {}{} and declares "+ "no binding for it", stage, tex ? "t" : "s", unit);+ return true;+ }+ return false;+ };+ if (undeclared(source.vertexSrc, "vertex")) {+ if (outFailedStage) *outFailedStage = GfxShaderStage::Vertex;+ return ShaderHandle::Invalid;+ }+ if (undeclared(source.fragmentSrc, "fragment")) {+ if (outFailedStage) *outFailedStage = GfxShaderStage::Fragment;+ return ShaderHandle::Invalid;+ }+auto makeModule = [&](const char* code) -> WGPUShaderModule {WGPUShaderSourceWGSL wgsl{};wgsl.chain.sType = WGPUSType_ShaderSourceWGSL;diff --git a/src/esengine/renderer/webgpu/WebGPUMappings.hpp b/src/esengine/renderer/webgpu/WebGPUMappings.hppindex 15632f5eb..8c72537a0 100644--- a/src/esengine/renderer/webgpu/WebGPUMappings.hpp+++ b/src/esengine/renderer/webgpu/WebGPUMappings.hpp@@ -407,6 +407,33 @@ inline u32 scanWGSLBindingMask(const char* source, u32 group) {return mask;}+/**+ * @brief The engine's `tN` / `sN` group-1 names a WGSL source REACHES, by unit.+ * @details The other half of {@link scanWGSLBindingMask}: what a stage names, as+ * against what it declares. A name reached and not declared is an+ * unresolved identifier, and WebGPU reports that as an invalid PIPELINE+ * with no shader named anywhere in it.+ */+inline void scanWGSLReachedUnits(const char* source, u32& textures, u32& samplers) {+ textures = 0;+ samplers = 0;+ if (!source) return;+ const auto isIdent = [](char c) {+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';+ };+ for (const char* p = source; *p; ++p) {+ if (*p != 't' && *p != 's') continue;+ if (p != source && isIdent(p[-1])) continue;+ char* end = nullptr;+ const unsigned long unit = std::strtoul(p + 1, &end, 10);+ if (end == p + 1 || isIdent(*end)) continue;+ if (unit < 16) {+ (*p == 't' ? textures : samplers) |= (1u << unit);+ }+ p = end - 1;+ }+}+/*** @brief Bit mask of the group's bindings a WGSL source declares as DEPTH textures.* @details A `texture_depth_2d` binding needs `sampleType = Depth` in its layoutdiff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cppindex 498d46e6b..8390aba01 100644--- a/src/esengine/resource/ResourceManager.cpp+++ b/src/esengine/resource/ResourceManager.cpp@@ -102,12 +102,15 @@ ShaderHandle ResourceManager::createShader(const std::string& vertSrc, const std}}- auto shader = Shader::create(*device_, vertSrc, fragSrc, language);- if (!shader) {- ES_LOG_ERROR("Failed to create shader from source");+ // Through createEx for the LOG: the device already answers why it refused, and a+ // caller that drops it leaves "failed to create" as the only thing anybody sees.+ auto outcome = Shader::createEx(*device_, vertSrc, fragSrc, {}, language);+ if (!outcome.shader) {+ ES_LOG_ERROR("Failed to create shader from source: {}",+ outcome.log.empty() ? "no reason given by the device" : outcome.log.c_str());return ShaderHandle();}- return shaders_.add(std::move(shader));+ return shaders_.add(std::move(outcome.shader));}ShaderHandle ResourceManager::createShaderWithBindings(const std::string& vertSrc, const std::string& fragSrc,diff --git a/tools/check-shader-conditionals.mjs b/tools/check-shader-conditionals.mjsindex ca95172b5..170a211a0 100644--- a/tools/check-shader-conditionals.mjs+++ b/tools/check-shader-conditionals.mjs@@ -14,17 +14,20 @@* The two halves of a file therefore do NOT have the same powers, which is the* kind of asymmetry nothing else would state.*/-import { readFileSync } from 'node:fs';-import { execFileSync } from 'node:child_process';+import { readFileSync, existsSync } from 'node:fs';+import { corpusRoots, censusFindings, sourceFiles } from './lib/sourceCensus.mjs';import path from 'node:path';import { fileURLToPath } from 'node:url';const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');-const files = execFileSync('git', ['ls-files', '*.esshader'], { cwd: ROOT, encoding: 'utf8' })- .split('\n').filter(Boolean);-const problems = [];+// The census, which spans the submodules holding our source and the files not yet+// tracked: a shader that is NEW is the one whose conditionals nobody has read.+const ROOTS = corpusRoots();+for (const finding of censusFindings(ROOTS)) problems.push(`census: ${finding}`);+const files = ROOTS.flatMap((r) => sourceFiles(r, /\.esshader$/))+ .filter((f) => existsSync(path.join(ROOT, f)));let wgslBlocks = 0;for (const file of files) {const text = readFileSync(path.join(ROOT, file), 'utf8');diff --git a/tools/check-wgsl-twin.mjs b/tools/check-wgsl-twin.mjsindex ebf487411..40dd3cf22 100644--- a/tools/check-wgsl-twin.mjs+++ b/tools/check-wgsl-twin.mjs@@ -20,8 +20,8 @@* Not every dual-language shader is a file. The SDK writes some of its own into* template literals, and those reach the same parser and the same backend.*/-import { readFileSync } from 'node:fs';-import { execFileSync } from 'node:child_process';+import { readFileSync, existsSync } from 'node:fs';+import { corpusRoots, censusFindings, sourceFiles } from './lib/sourceCensus.mjs';import path from 'node:path';import { fileURLToPath } from 'node:url';@@ -97,13 +97,6 @@ function bindingsReachedBy(name, seen = new Set()) {return out;}-// git grep exits 1 when nothing matches, which is an answer and not a failure.-const listed = (args) => {- try {- return execFileSync('git', args, { cwd: ROOT, encoding: 'utf8' }).split('\n').filter(Boolean);- } catch { return []; }-};-/** Every template literal in `text` that carries shader source, labelled by line. */function embedded(file, text) {const out = [];@@ -120,15 +113,19 @@ function embedded(file, text) {return out;}+const problems = [];const sources = [];-// --others: a shader that is NEW is the one most likely to be missing a binding, and-// a listing of only tracked files answers "clean" about the file nobody has read.-for (const file of listed(['ls-files', '--cached', '--others', '--exclude-standard',- '*.esshader'])) {- sources.push({ label: file, text: readFileSync(path.join(ROOT, file), 'utf8') });-}-for (const file of listed(['grep', '-l', '-F', '#pragma fragment wgsl', '--', '*.ts'])) {- sources.push(...embedded(file, readFileSync(path.join(ROOT, file), 'utf8')));+// The census rather than a listing of this repo: it spans the submodules that hold our+// source AND the files not yet tracked, and a shader that is NEW is the one most likely+// to be missing a binding.+const ROOTS = corpusRoots();+for (const finding of censusFindings(ROOTS)) problems.push(`census: ${finding}`);+for (const file of ROOTS.flatMap((r) => sourceFiles(r, /\.(esshader|ts)$/))) {+ const full = path.join(ROOT, file);+ if (!existsSync(full)) continue;+ const text = readFileSync(full, 'utf8');+ if (file.endsWith('.esshader')) sources.push({ label: file, text });+ else if (text.includes('#pragma fragment wgsl')) sources.push(...embedded(file, text));}/** `#pragma <stage> wgsl` … `#pragma end` for one stage, or null. */@@ -137,7 +134,6 @@ function wgslStage(text, stage) {return m ? m[1] : null;}-const problems = [];let checked = 0;for (const { label: file, text } of sources) {diff --git a/tools/lib/sourceCensus.mjs b/tools/lib/sourceCensus.mjsindex bf989d7f3..4f585c012 100644--- a/tools/lib/sourceCensus.mjs+++ b/tools/lib/sourceCensus.mjs@@ -118,6 +118,18 @@ export function untrackedFiles(root) {return out.split('\n').filter(Boolean).map((f) => (root.prefix ? `${root.prefix}/${f}` : f));}+/**+ * Every file in `root` a scan is entitled to say it looked at: tracked and+ * untracked-but-not-ignored, in one list. A scan that lists only tracked files+ * answers "clean" about the file most likely to be wrong — the one just written,+ * which is why both halves live here rather than in each caller.+ */+export function sourceFiles(root, match = null) {+ const all = [...trackedFiles(root), ...untrackedFiles(root)];+ const seen = new Set();+ return all.filter((f) => (match && !match.test(f) ? false : !seen.has(f) && seen.add(f)));+}+/** `git diff` output for what `root` has added since it left the remote. */export function addedDiff(root, args) {if (!root.present) return '';diff --git a/tools/tests/source-census.test.ts b/tools/tests/source-census.test.tsindex e97588f70..945143007 100644--- a/tools/tests/source-census.test.ts+++ b/tools/tests/source-census.test.ts@@ -8,8 +8,11 @@* inside one. Every scan that judged "the repository" judged half of it.*/import { describe, it, expect } from 'vitest';+import { writeFileSync, rmSync } from 'node:fs';+import path from 'node:path';// @ts-expect-error — a repo tool, shipped as .mjs with no declarations-import { corpusRoots, censusFindings, trackedFiles } from '../lib/sourceCensus.mjs';+import { corpusRoots, censusFindings, trackedFiles, untrackedFiles, sourceFiles, ROOT }+ from '../lib/sourceCensus.mjs';type Root = { prefix: string; present: boolean };@@ -63,4 +66,29 @@ describe('the source census spans this repository and the submodules that hold oexpect(files.length).toBeGreaterThan(100);expect(files.every((f) => f.startsWith('desktop/'))).toBe(true);});++ // A tracked-only scan answers "clean" about the file most likely to be wrong: the+ // one just written. The probe is written HERE because a clean tree has no untracked+ // file, and the assertion would pass by having nothing to say.+ it('offers tracked and untracked as one list, deduplicated', () => {+ const root = roots.find((r) => (r as { present: boolean }).present)!;+ const dir = path.join(ROOT, (root as { prefix: string }).prefix);+ const name = `census-probe-${process.pid}.esshader`;+ const probe = path.join(dir, name);+ writeFileSync(probe, '#pragma shader "Probe"\n');+ try {+ const rel = [(root as { prefix: string }).prefix, name].filter(Boolean).join('/');+ expect(trackedFiles(root)).not.toContain(rel);+ expect(untrackedFiles(root)).toContain(rel);+ const all: string[] = sourceFiles(root);+ expect(all).toContain(rel);+ expect(all.length).toBe(new Set(all).size);+ // And it filters where a caller asks, so a scan says which corpus it took.+ const shaders: string[] = sourceFiles(root, /\.esshader$/);+ expect(shaders).toContain(rel);+ expect(shaders.every((f) => f.endsWith('.esshader'))).toBe(true);+ } finally {+ rmSync(probe, { force: true });+ }+ });});