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 param name the shader never declared says so
yhh2f7e43e6d32c
diff --git a/desktop/src/material/materialInspectorModel.ts b/desktop/src/material/materialInspectorModel.tsindex bd8c55d45..f9cdbeb20 100644--- a/desktop/src/material/materialInspectorModel.ts+++ b/desktop/src/material/materialInspectorModel.ts@@ -12,11 +12,13 @@* handle for the live viewport preview. The engine stays the single source of the* std140 layout; this is the editor view of the declarations.*/-import { BlendMode, CullMode, Material, builtinShaderTemplate, type MaterialAssetData, type UniformValue } from 'esengine';+import {+ BlendMode, CullMode, Material, builtinShaderTemplate, paramDefaultValue, reflectEsshader,+ type MaterialAssetData, type ShaderParam, type ShaderReflection, type UniformValue,+} from 'esengine';import type { InspectorComponent, InspectorField, InspectorFieldType, EnumOption, GradientValue, CurveValue, DimensionValue, MapValue } from '@/types';import { t } from '@/i18n';import { MaterialDocument } from './MaterialDocument';-import { reflectEsshader, type ShaderParam, type ShaderReflection } from './shaderReflect';const BLEND_OPTIONS: EnumOption[] = [{ label: t('mat.blendNormal'), value: BlendMode.Normal },@@ -60,16 +62,10 @@ function arrayToVec(arr: number[], arity: number): Record<string, number> {return o;}-/** A param's declared shader default, in the asset's stored shape (color/vec object, or scalar). */-function shaderDefaultAsset(param: ShaderParam): unknown {- if (param.type === 'texture') return param.defaultTexture ?? 0;- if (param.type === 'color') {- const d = param.default;- return { r: d[0] ?? 0, g: d[1] ?? 0, b: d[2] ?? 0, a: d[3] ?? 1 };- }- if (param.type === 'float' || param.type === 'int') return param.default[0] ?? 0;- return arrayToVec(param.default, ARITY[param.type] ?? 1);-}+/** A param's declared shader default, in the asset's stored shape (color/vec object, or scalar).+ * The SDK's, because a material born from a built-in template gets its `properties` from the+ * same conversion — two of them and a template's default stops matching its own inspector row. */+const shaderDefaultAsset = paramDefaultValue;/** Deep value equality for the asset's stored shapes (scalar / color obj / vec obj / ref). */function assetEquals(a: unknown, b: unknown): boolean {diff --git a/desktop/src/material/shaderReflect.ts b/desktop/src/material/shaderReflect.tsdeleted file mode 100644index b1aa29414..000000000--- a/desktop/src/material/shaderReflect.ts+++ /dev/null@@ -1,118 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file shaderReflect.ts- * @brief Editor-side reflection of a `.esshader`'s `#pragma param` declarations.- * @details Parses the same param grammar the engine's C++ ShaderParser does, but only the- * UI-facing metadata (name / type / default / range / ui hint / display name) — the- * editor builds a parameter panel from it. The engine remains the single source of- * the std140 layout + GLSL codegen; this is the static, editor-only view of the- * declarations, so the Material Editor needn't round-trip through a compiled shader.- *- * Grammar (matches ShaderParser):- * #pragma param <name> <type> [default(csv)] [range(min,max)] [ui(hint)]- * #pragma domain <Unlit2D|Lit2D|PostProcess|UI>- */--export type ShaderParamType = 'float' | 'vec2' | 'vec3' | 'vec4' | 'color' | 'int' | 'texture';--export interface ShaderParam {- name: string;- type: ShaderParamType;- /** Human label for the inspector row (leading `u_` stripped, capitalized). */- displayName: string;- /** Default components for a scalar/vector param (length 1–4); empty for a texture. */- default: number[];- /** Default texture hint for a texture param (e.g. "white"); undefined otherwise. */- defaultTexture?: string;- /** Optional slider bounds from `range(min,max)`. */- range?: { min: number; max: number };- /** Optional UI hint from `ui(...)`, e.g. "slider". */- ui?: string;-}--export interface ShaderReflection {- domain: string;- params: ShaderParam[];-}--const TYPES = new Set<ShaderParamType>(['float', 'vec2', 'vec3', 'vec4', 'color', 'int', 'texture']);-const ARITY: Record<string, number> = { float: 1, int: 1, vec2: 2, vec3: 3, vec4: 4, color: 4 };--// Extract the contents of a `key(...)` clause from a directive argument.-function clause(arg: string, key: string): string | undefined {- const token = `${key}(`;- const open = arg.indexOf(token);- if (open < 0) return undefined;- const start = open + token.length;- const close = arg.indexOf(')', start);- if (close < 0) return undefined;- return arg.slice(start, close).trim();-}--function defaultForType(type: ShaderParamType): number[] {- if (type === 'texture') return [];- if (type === 'color') return [0, 0, 0, 1];- return new Array(ARITY[type] ?? 1).fill(0);-}--function displayNameFor(name: string): string {- let s = name.startsWith('u_') ? name.slice(2) : name;- if (s.length > 0) s = s[0].toUpperCase() + s.slice(1);- return s;-}--function parseParam(arg: string): ShaderParam | null {- const tokens = arg.trim().split(/\s+/);- const name = tokens[0];- const typeStr = tokens[1];- if (!name || !typeStr || !TYPES.has(typeStr as ShaderParamType)) return null;- const type = typeStr as ShaderParamType;-- const param: ShaderParam = { name, type, displayName: displayNameFor(name), default: defaultForType(type) };-- const def = clause(arg, 'default');- if (def !== undefined) {- if (type === 'texture') {- param.defaultTexture = def;- } else {- const nums = def.split(',').map((s) => parseFloat(s.trim())).filter((n) => !Number.isNaN(n));- if (nums.length > 0) param.default = nums;- }- }-- const range = clause(arg, 'range');- if (range !== undefined) {- const [min, max] = range.split(',').map((s) => parseFloat(s.trim()));- if (!Number.isNaN(min) && !Number.isNaN(max)) param.range = { min, max };- }-- const ui = clause(arg, 'ui');- if (ui !== undefined) param.ui = ui;-- return param;-}--/** Parse a `.esshader` source into its editor-facing parameter reflection. */-export function reflectEsshader(source: string): ShaderReflection {- const params: ShaderParam[] = [];- let domain = 'Unlit2D';-- for (const raw of source.split('\n')) {- const line = raw.trim();- if (!line.startsWith('#pragma')) continue;- const rest = line.slice('#pragma'.length).trim();- const sp = rest.search(/\s/);- const directive = sp < 0 ? rest : rest.slice(0, sp);- const arg = sp < 0 ? '' : rest.slice(sp + 1).trim();-- if (directive === 'param') {- const p = parseParam(arg);- if (p) params.push(p);- } else if (directive === 'domain' && arg) {- domain = arg;- }- }-- return { domain, params };-}diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 2b180abe5..e0f31d37b 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1437 stable · 17 beta · 1 deprecated+Symbols: 1442 stable · 17 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -6372,6 +6372,28 @@ static prototype: ServicesPluginnumber```+## ShaderParam — interface+```+default: number[]+defaultTexture: string | undefined+displayName: string+name: string+range: { min: number; max: number; } | undefined+type: ShaderParamType+ui: string | undefined+```++## ShaderParamType — type+```+'float' | 'vec2' | 'vec3' | 'vec4' | 'color' | 'int' | 'texture'+```++## ShaderReflection — interface+```+domain: string+params: ShaderParam[]+```+## ShaderSources — const```{ SPRITE_VERTEX: string; SPRITE_FRAGMENT: string; COLOR_VERTEX: string; COLOR_FRAGMENT: string; }@@ -10014,6 +10036,11 @@ NavPlugin(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; }```+## paramDefaultValue — function+```+(param: ShaderParam): unknown+```+## parseActionArg — function```(arg: string | undefined, params: readonly AiParamDef[], separator?: string): Record<string, AiParamValue>@@ -10224,6 +10251,11 @@ PrefabsPlugin(entities: ProcessedEntity[]): void```+## reflectEsshader — function+```+(source: string): ShaderReflection+```+## registerAction — function```(name: string, fn: AiAction<AiContext>): voiddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 4e4e190ba..6afa6184b 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1456 stable · 22 beta · 1 deprecated+Symbols: 1461 stable · 22 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -6542,6 +6542,28 @@ static prototype: ServicesPluginnumber```+## ShaderParam — interface+```+default: number[]+defaultTexture: string | undefined+displayName: string+name: string+range: { min: number; max: number; } | undefined+type: ShaderParamType+ui: string | undefined+```++## ShaderParamType — type+```+'float' | 'vec2' | 'vec3' | 'vec4' | 'color' | 'int' | 'texture'+```++## ShaderReflection — interface+```+domain: string+params: ShaderParam[]+```+## ShaderSources — const```{ SPRITE_VERTEX: string; SPRITE_FRAGMENT: string; COLOR_VERTEX: string; COLOR_FRAGMENT: string; }@@ -10234,6 +10256,11 @@ NavPlugin(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; }```+## paramDefaultValue — function+```+(param: ShaderParam): unknown+```+## parseActionArg — function```(arg: string | undefined, params: readonly AiParamDef[], separator?: string): Record<string, AiParamValue>@@ -10444,6 +10471,11 @@ PrefabsPlugin(entities: ProcessedEntity[]): void```+## reflectEsshader — function+```+(source: string): ShaderReflection+```+## registerAction — function```(name: string, fn: AiAction<AiContext>): voiddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 4c135a541..341533bae 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1436 stable · 19 beta · 1 deprecated+Symbols: 1441 stable · 19 beta · 1 deprecated## ANCHOR_AXES — const```@@ -6367,6 +6367,28 @@ static prototype: ServicesPluginnumber```+## ShaderParam — interface+```+default: number[]+defaultTexture: string | undefined+displayName: string+name: string+range: { min: number; max: number; } | undefined+type: ShaderParamType+ui: string | undefined+```++## ShaderParamType — type+```+'float' | 'vec2' | 'vec3' | 'vec4' | 'color' | 'int' | 'texture'+```++## ShaderReflection — interface+```+domain: string+params: ShaderParam[]+```+## ShaderSources — const```{ SPRITE_VERTEX: string; SPRITE_FRAGMENT: string; COLOR_VERTEX: string; COLOR_FRAGMENT: string; }@@ -10019,6 +10041,11 @@ NodePlatformAdapter(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; }```+## paramDefaultValue — function+```+(param: ShaderParam): unknown+```+## parseActionArg — function```(arg: string | undefined, params: readonly AiParamDef[], separator?: string): Record<string, AiParamValue>@@ -10229,6 +10256,11 @@ PrefabsPlugin(entities: ProcessedEntity[]): void```+## reflectEsshader — function+```+(source: string): ShaderReflection+```+## registerAction — function```(name: string, fn: AiAction<AiContext>): voiddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 281b406cf..0b0ee2335 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1457 stable · 17 beta · 1 deprecated+Symbols: 1462 stable · 17 beta · 1 deprecated## ANCHOR_AXES — const```@@ -6612,6 +6612,28 @@ static prototype: ServicesPluginnumber```+## ShaderParam — interface+```+default: number[]+defaultTexture: string | undefined+displayName: string+name: string+range: { min: number; max: number; } | undefined+type: ShaderParamType+ui: string | undefined+```++## ShaderParamType — type+```+'float' | 'vec2' | 'vec3' | 'vec4' | 'color' | 'int' | 'texture'+```++## ShaderReflection — interface+```+domain: string+params: ShaderParam[]+```+## ShaderSources — const```{ SPRITE_VERTEX: string; SPRITE_FRAGMENT: string; COLOR_VERTEX: string; COLOR_FRAGMENT: string; }@@ -10269,6 +10291,11 @@ NavPlugin(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; }```+## paramDefaultValue — function+```+(param: ShaderParam): unknown+```+## parseActionArg — function```(arg: string | undefined, params: readonly AiParamDef[], separator?: string): Record<string, AiParamValue>@@ -10479,6 +10506,11 @@ PrefabsPlugin(entities: ProcessedEntity[]): void```+## reflectEsshader — function+```+(source: string): ShaderReflection+```+## registerAction — function```(name: string, fn: AiAction<AiContext>): voiddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 45708c421..2307efabc 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1447 stable · 17 beta · 1 deprecated+Symbols: 1452 stable · 17 beta · 1 deprecated## ANCHOR_AXES — const```@@ -6374,6 +6374,28 @@ static prototype: ServicesPluginnumber```+## ShaderParam — interface+```+default: number[]+defaultTexture: string | undefined+displayName: string+name: string+range: { min: number; max: number; } | undefined+type: ShaderParamType+ui: string | undefined+```++## ShaderParamType — type+```+'float' | 'vec2' | 'vec3' | 'vec4' | 'color' | 'int' | 'texture'+```++## ShaderReflection — interface+```+domain: string+params: ShaderParam[]+```+## ShaderSources — const```{ SPRITE_VERTEX: string; SPRITE_FRAGMENT: string; COLOR_VERTEX: string; COLOR_FRAGMENT: string; }@@ -10041,6 +10063,11 @@ NavPlugin(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; }```+## paramDefaultValue — function+```+(param: ShaderParam): unknown+```+## parseActionArg — function```(arg: string | undefined, params: readonly AiParamDef[], separator?: string): Record<string, AiParamValue>@@ -10251,6 +10278,11 @@ PrefabsPlugin(entities: ProcessedEntity[]): void```+## reflectEsshader — function+```+(source: string): ShaderReflection+```+## registerAction — function```(name: string, fn: AiAction<AiContext>): voiddiff --git a/sdk/src/core-render.ts b/sdk/src/core-render.tsindex e1317b275..ba63d1687 100644--- a/sdk/src/core-render.ts+++ b/sdk/src/core-render.ts@@ -91,6 +91,16 @@ export {type BuiltinShaderTemplate,} from './render/builtinShaders';+// What a `.esshader` declares, read from its source: the editor's parameter panel, the+// built-in templates' defaults and setUniform's "no such param" all read the one parser.+export {+ reflectEsshader,+ paramDefaultValue,+ type ShaderParam,+ type ShaderParamType,+ type ShaderReflection,+} from './render/shaderReflect';+export {compileMaterialGraph,newMaterialGraph,diff --git a/sdk/src/render/builtinShaders.ts b/sdk/src/render/builtinShaders.tsindex 0fd4a44e1..23ce42a6a 100644--- a/sdk/src/render/builtinShaders.ts+++ b/sdk/src/render/builtinShaders.ts@@ -11,16 +11,43 @@* frame clock as tc.u_time / tc.u_viewport.*/+import { paramDefaultValue, reflectEsshader } from './shaderReflect';+export interface BuiltinShaderTemplate {id: string;/** Menu / picker label, e.g. "Lit". */label: string;description: string;source: string;- /** Initial .esmaterial `properties` for a material born from this template. */+ /** Initial .esmaterial `properties` for a material born from this template — DERIVED+ * from `source`, never written down beside it (see {@link templateDefaults}). */defaults: Record<string, unknown>;}+/**+ * The `properties` a new material of this template starts with: every declared non-texture+ * param at its shader default.+ *+ * Derived rather than listed, because a hand-kept copy is a second place to remember. Five+ * of the seven templates carried `defaults: {}` — their parameter vocabulary existed only+ * inside the shader string, so a material made from Dissolve came out with no `u_progress`+ * in it, and nothing anywhere named that word to whoever went looking for the slider.+ *+ * A texture param is skipped: its default is a name the engine resolves (`white`,+ * `flatnormal`), and storing that as a property would make it look like an asset ref.+ */+function templateDefaults(source: string): Record<string, unknown> {+ const out: Record<string, unknown> = {};+ for (const param of reflectEsshader(source).params) {+ if (param.type === 'texture') continue;+ out[param.name] = paramDefaultValue(param);+ }+ return out;+}++const template = (id: string, label: string, description: string, source: string): BuiltinShaderTemplate =>+ ({ id, label, description, source, defaults: templateDefaults(source) });+const SPRITE_UNLIT = `#pragma shader "Sprite Unlit"#pragma version 300 es#pragma domain Unlit2D@@ -282,55 +309,17 @@ void main() {`;export const BUILTIN_SHADER_TEMPLATES: readonly BuiltinShaderTemplate[] = [- {- id: 'sprite-unlit',- label: 'Unlit',- description: 'Texture × vertex color × tint, no lighting.',- source: SPRITE_UNLIT,- defaults: { u_tint: { r: 1, g: 1, b: 1, a: 1 } },- },- {- id: 'sprite-lit',- label: 'Lit',- description: 'Lit by the scene\'s 2D lights; optional normal map.',- source: SPRITE_LIT,- defaults: { u_tint: { r: 1, g: 1, b: 1, a: 1 } },- },- {- id: 'sprite-hit-flash',- label: 'Hit Flash',- description: 'Blend toward a flash color; drive u_flash from code for damage blinks.',- source: SPRITE_HIT_FLASH,- defaults: {},- },- {- id: 'sprite-outline',- label: 'Outline',- description: 'Colored silhouette outline around the sprite\'s opaque pixels.',- source: SPRITE_OUTLINE,- defaults: {},- },- {- id: 'sprite-dissolve',- label: 'Dissolve',- description: 'Noise-driven burn-away with a glowing edge (u_progress 0→1).',- source: SPRITE_DISSOLVE,- defaults: {},- },- {- id: 'sprite-pixelate',- label: 'Pixelate',- description: 'Quantizes UVs to a coarse pixel grid.',- source: SPRITE_PIXELATE,- defaults: {},- },- {- id: 'sprite-uv-scroll',- label: 'UV Scroll',- description: 'Scrolls the texture over time (conveyors, water, clouds).',- source: SPRITE_UV_SCROLL,- defaults: {},- },+ template('sprite-unlit', 'Unlit', 'Texture × vertex color × tint, no lighting.', SPRITE_UNLIT),+ template('sprite-lit', 'Lit', 'Lit by the scene\'s 2D lights; optional normal map.', SPRITE_LIT),+ template('sprite-hit-flash', 'Hit Flash',+ 'Blend toward a flash color; drive u_flash from code for damage blinks.', SPRITE_HIT_FLASH),+ template('sprite-outline', 'Outline',+ 'Colored silhouette outline around the sprite\'s opaque pixels.', SPRITE_OUTLINE),+ template('sprite-dissolve', 'Dissolve',+ 'Noise-driven burn-away with a glowing edge (u_progress 0→1).', SPRITE_DISSOLVE),+ template('sprite-pixelate', 'Pixelate', 'Quantizes UVs to a coarse pixel grid.', SPRITE_PIXELATE),+ template('sprite-uv-scroll', 'UV Scroll',+ 'Scrolls the texture over time (conveyors, water, clouds).', SPRITE_UV_SCROLL),];export function builtinShaderTemplate(id: string): BuiltinShaderTemplate | undefined {diff --git a/sdk/src/render/material.ts b/sdk/src/render/material.tsindex 237fb724d..f41e2b94a 100644--- a/sdk/src/render/material.ts+++ b/sdk/src/render/material.ts@@ -13,6 +13,7 @@ import { requireResourceManager } from '../wasm/resourceManager';import { awaitReadback, READBACK_READY } from './readback';import type { Vec2, Vec3, Vec4 } from '../types';import { BlendMode } from './blend';+import { reflectEsshader } from './shaderReflect';export type { Vec2, Vec3, Vec4 } from '../types';@@ -175,6 +176,15 @@ let nextMaterialId = 1;const materials = new Map<MaterialHandle, MaterialData>();// Reverse index parent -> instances, so editing a base material re-flushes its instances.const childrenOf = new Map<MaterialHandle, Set<MaterialHandle>>();+// What each compiled shader DECLARES, by handle. Recorded where the source enters the+// engine (compileShader), so every route to a shader — a `.esmaterial`'s file, a built-in+// template, a compiled material graph, a post-process effect — is covered by one door.+// A shader built from raw GLSL (createShader) declares nothing and gets no entry: no+// vocabulary, no verdict.+const declaredParams = new Map<ShaderHandle, Set<string>>();+// One complaint per (shader, param). A uniform driven from a system is written every+// frame, and a warning that repeats 60 times a second is a log nobody can read.+const warnedParams = new Set<string>();// =============================================================================// Initialization@@ -194,11 +204,41 @@ export function initMaterialAPI(engine: NonNullable<EngineApi>): void {export function shutdownMaterialAPI(): void {materials.clear();childrenOf.clear();+ declaredParams.clear();+ warnedParams.clear();nextMaterialId = 1;bridge.disconnect();module = null;}+/** The shader a material draws with — its own, or the one it inherits as an instance. */+function shaderOf(handle: MaterialHandle): ShaderHandle | undefined {+ let data = materials.get(handle);+ // Bounded: a cycle in the parent chain would otherwise hang a per-write check.+ for (let depth = 0; data?.parent !== undefined && depth < 16; depth++) data = materials.get(data.parent);+ return data?.shader;+}++/**+ * Say so when a param name is not one the shader declares.+ *+ * The engine drops an unknown param without a word — MaterialStore keys the std140 layout+ * by the reflected name, so a value under any other name has nowhere to land. That makes a+ * typo the most expensive kind of mistake here: the call succeeds, the value is stored, and+ * the effect never happens. `Material.setUniform(m, 'u_amount', x)` against a shader whose+ * slider is `u_progress` reads as a broken shader, and spelling is the last thing anyone+ * checks. Naming what the shader DOES declare turns that into a one-line fix.+ */+function warnUndeclared(shader: ShaderHandle | undefined, name: string): void {+ const declared = shader !== undefined ? declaredParams.get(shader) : undefined;+ if (!declared || declared.has(name)) return;+ const key = `${shader}:${name}`;+ if (warnedParams.has(key)) return;+ warnedParams.add(key);+ const known = [...declared].join(', ') || '(none)';+ console.warn(`[material] "${name}" is not a parameter of this shader — the value is ignored. It declares: ${known}`);+}+// Pack the render-state flags the engine store expects: depthTest (bit 0), depthWrite// (bit 1), CullMode (bits 2-3).function materialFlags(depthTest: boolean, depthWrite: boolean, cull: CullMode): number {@@ -316,6 +356,7 @@ export const Material = {*/releaseShader(shader: ShaderHandle): void {if (shader > 0) {+ declaredParams.delete(shader);requireResourceManager().releaseShader(shader);}},@@ -343,6 +384,7 @@ export const Material = {if (options.uniforms) {for (const [key, value] of Object.entries(options.uniforms)) {+ warnUndeclared(options.shader, key);data.uniforms.set(key, value);}}@@ -359,7 +401,13 @@ export const Material = {* should reach the GPU. Returns a shader handle, or 0 on failure.*/compileShader(esshaderSource: string, features: string[] = []): ShaderHandle {- return module?.material_compileEsshader(esshaderSource, features.join(',')) ?? 0;+ const handle = module?.material_compileEsshader(esshaderSource, features.join(',')) ?? 0;+ // The same `#pragma param` lines the engine reflected into the layout, kept on this+ // side so a write to a name that is not among them can be reported (warnUndeclared).+ if (handle > 0) {+ declaredParams.set(handle, new Set(reflectEsshader(esshaderSource).params.map((p) => p.name)));+ }+ return handle;},/** Gets an enabled static switch (false when unset). */@@ -393,6 +441,7 @@ export const Material = {setUniform(material: MaterialHandle, name: string, value: UniformValue): void {const data = materials.get(material);if (data) {+ warnUndeclared(shaderOf(material), name);// On an instance, the local uniforms map *is* the override set (presence = override).data.uniforms.set(name, value);data.dirty_ = true; // immediate-mode mesh path re-encodes its uniform cache.diff --git a/sdk/src/render/shaderReflect.ts b/sdk/src/render/shaderReflect.tsnew file mode 100644index 000000000..95e8f18bd--- /dev/null+++ b/sdk/src/render/shaderReflect.ts@@ -0,0 +1,144 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file shaderReflect.ts+ * @brief What a `.esshader`'s `#pragma param` lines declare, read from the source.+ * @details Parses the same param grammar the engine's C++ ShaderParser does, but only the+ * declaration metadata (name / type / default / range / ui hint / display name).+ * The engine remains the single source of the std140 layout + GLSL codegen; this is+ * the static view of the declarations, for everything that needs to know a shader's+ * parameter vocabulary without compiling one.+ *+ * Three things read it, which is why it lives here rather than in the editor where+ * it started: the Material inspector builds its parameter panel from it, the built-in+ * templates derive their material defaults from it (so the defaults cannot drift from+ * the shader that consumes them), and `Material.setUniform` uses it to tell a caller+ * that the name it just wrote is not one this shader has — a value the engine would+ * otherwise drop without a word.+ *+ * Grammar (matches ShaderParser):+ * #pragma param <name> <type> [default(csv)] [range(min,max)] [ui(hint)]+ * #pragma domain <Unlit2D|Lit2D|PostProcess|UI>+ */++export type ShaderParamType = 'float' | 'vec2' | 'vec3' | 'vec4' | 'color' | 'int' | 'texture';++export interface ShaderParam {+ name: string;+ type: ShaderParamType;+ /** Human label for the inspector row (leading `u_` stripped, capitalized). */+ displayName: string;+ /** Default components for a scalar/vector param (length 1–4); empty for a texture. */+ default: number[];+ /** Default texture hint for a texture param (e.g. "white"); undefined otherwise. */+ defaultTexture?: string;+ /** Optional slider bounds from `range(min,max)`. */+ range?: { min: number; max: number };+ /** Optional UI hint from `ui(...)`, e.g. "slider". */+ ui?: string;+}++export interface ShaderReflection {+ domain: string;+ params: ShaderParam[];+}++const TYPES = new Set<ShaderParamType>(['float', 'vec2', 'vec3', 'vec4', 'color', 'int', 'texture']);+const ARITY: Record<string, number> = { float: 1, int: 1, vec2: 2, vec3: 3, vec4: 4, color: 4 };+const VEC_KEYS = ['x', 'y', 'z', 'w'] as const;++// Extract the contents of a `key(...)` clause from a directive argument.+function clause(arg: string, key: string): string | undefined {+ const token = `${key}(`;+ const open = arg.indexOf(token);+ if (open < 0) return undefined;+ const start = open + token.length;+ const close = arg.indexOf(')', start);+ if (close < 0) return undefined;+ return arg.slice(start, close).trim();+}++function defaultForType(type: ShaderParamType): number[] {+ if (type === 'texture') return [];+ if (type === 'color') return [0, 0, 0, 1];+ return new Array(ARITY[type] ?? 1).fill(0);+}++function displayNameFor(name: string): string {+ let s = name.startsWith('u_') ? name.slice(2) : name;+ if (s.length > 0) s = s[0].toUpperCase() + s.slice(1);+ return s;+}++function parseParam(arg: string): ShaderParam | null {+ const tokens = arg.trim().split(/\s+/);+ const name = tokens[0];+ const typeStr = tokens[1];+ if (!name || !typeStr || !TYPES.has(typeStr as ShaderParamType)) return null;+ const type = typeStr as ShaderParamType;++ const param: ShaderParam = { name, type, displayName: displayNameFor(name), default: defaultForType(type) };++ const def = clause(arg, 'default');+ if (def !== undefined) {+ if (type === 'texture') {+ param.defaultTexture = def;+ } else {+ const nums = def.split(',').map((s) => parseFloat(s.trim())).filter((n) => !Number.isNaN(n));+ if (nums.length > 0) param.default = nums;+ }+ }++ const range = clause(arg, 'range');+ if (range !== undefined) {+ const [min, max] = range.split(',').map((s) => parseFloat(s.trim()));+ if (!Number.isNaN(min) && !Number.isNaN(max)) param.range = { min, max };+ }++ const ui = clause(arg, 'ui');+ if (ui !== undefined) param.ui = ui;++ return param;+}++/**+ * A param's declared default in the shape a `.esmaterial`'s `properties` stores it: a number+ * for float/int, `{r,g,b,a}` for a color, `{x,y,…}` for a vector, and for a texture the+ * default's NAME (`"white"`, `"flatnormal"` — an engine-resolved stand-in, not an asset ref).+ */+export function paramDefaultValue(param: ShaderParam): unknown {+ if (param.type === 'texture') return param.defaultTexture ?? 0;+ if (param.type === 'color') {+ const d = param.default;+ return { r: d[0] ?? 0, g: d[1] ?? 0, b: d[2] ?? 0, a: d[3] ?? 1 };+ }+ if (param.type === 'float' || param.type === 'int') return param.default[0] ?? 0;+ const vec: Record<string, number> = {};+ const arity = ARITY[param.type] ?? 1;+ for (let i = 0; i < arity; i++) vec[VEC_KEYS[i]] = param.default[i] ?? 0;+ return vec;+}++/** Parse a `.esshader` source into its declared parameters and domain. */+export function reflectEsshader(source: string): ShaderReflection {+ const params: ShaderParam[] = [];+ let domain = 'Unlit2D';++ for (const raw of source.split('\n')) {+ const line = raw.trim();+ if (!line.startsWith('#pragma')) continue;+ const rest = line.slice('#pragma'.length).trim();+ const sp = rest.search(/\s/);+ const directive = sp < 0 ? rest : rest.slice(0, sp);+ const arg = sp < 0 ? '' : rest.slice(sp + 1).trim();++ if (directive === 'param') {+ const p = parseParam(arg);+ if (p) params.push(p);+ } else if (directive === 'domain' && arg) {+ domain = arg;+ }+ }++ return { domain, params };+}diff --git a/sdk/tests/material.test.ts b/sdk/tests/material.test.tsindex e62753d98..94462a521 100644--- a/sdk/tests/material.test.ts+++ b/sdk/tests/material.test.ts@@ -731,6 +731,80 @@ describe('Material API', () => {// Uninitialized guard// =========================================================================+ // =========================================================================+ // A param name the shader does not declare+ // =========================================================================++ describe('writing a param the shader has no such name for', () => {+ // The engine drops it: MaterialStore keys the std140 layout by the reflected+ // name, so a value under any other name has nowhere to land. Silence made a+ // typo look like a broken shader — `u_amount` on a shader whose slider is+ // `u_progress` is a call that succeeds and an effect that never happens.+ const SRC = '#pragma domain Unlit2D\n#pragma param u_progress float default(0)\n'+ + '#pragma param u_edgeColor color default(1,0.5,0,1)\n';++ it('names what the shader DOES declare', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const shader = Material.compileShader(SRC);+ const mat = Material.create({ shader });++ Material.setUniform(mat, 'u_amount', 0.5);++ expect(warn).toHaveBeenCalledTimes(1);+ const said = String(warn.mock.calls[0][0]);+ expect(said).toContain('u_amount');+ expect(said).toContain('u_progress');+ expect(said).toContain('u_edgeColor');+ warn.mockRestore();+ });++ it('says nothing about a name the shader declares', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const mat = Material.create({ shader: Material.compileShader(SRC) });+ Material.setUniform(mat, 'u_progress', 0.5);+ expect(warn).not.toHaveBeenCalled();+ warn.mockRestore();+ });++ it('complains once, not once per frame', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const mat = Material.create({ shader: Material.compileShader(SRC) });+ for (let i = 0; i < 60; i++) Material.setUniform(mat, 'u_amount', i);+ expect(warn).toHaveBeenCalledTimes(1);+ warn.mockRestore();+ });++ it('checks the properties a material file arrives with, not only later writes', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const shader = Material.compileShader(SRC);+ Material.createFromAsset(+ { version: '1.0', type: 'material', shader: 'x.esshader', properties: { u_amount: 0 } } as MaterialAssetData,+ shader,+ );+ expect(warn).toHaveBeenCalledTimes(1);+ warn.mockRestore();+ });++ it('stays quiet for a shader built from raw GLSL — it declares no vocabulary', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const mat = Material.create({ shader: Material.createShader('v', 'f') });+ Material.setUniform(mat, 'anything', 1);+ expect(warn).not.toHaveBeenCalled();+ warn.mockRestore();+ });++ it('judges an instance by the shader it inherits', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const base = Material.create({ shader: Material.compileShader(SRC) });+ const instance = Material.createInstance(base);+ Material.setUniform(instance, 'u_progress', 1); // declared — inherited from the base+ expect(warn).not.toHaveBeenCalled();+ Material.setUniform(instance, 'u_amount', 1);+ expect(warn).toHaveBeenCalledTimes(1);+ warn.mockRestore();+ });+ });+describe('uninitialized guard', () => {it('should throw when createShader called without init', () => {shutdownMaterialAPI();diff --git a/desktop/tests/shader-reflect.test.ts b/sdk/tests/shader-reflect.test.tssimilarity index 58%rename from desktop/tests/shader-reflect.test.tsrename to sdk/tests/shader-reflect.test.tsindex fe270e1ec..a1c57cb8c 100644--- a/desktop/tests/shader-reflect.test.ts+++ b/sdk/tests/shader-reflect.test.ts@@ -1,7 +1,8 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { describe, it, expect } from 'vitest';-import { reflectEsshader } from '../src/material/shaderReflect';+import { reflectEsshader, paramDefaultValue } from '../src/render/shaderReflect';+import { BUILTIN_SHADER_TEMPLATES, builtinShaderTemplate } from '../src/render/builtinShaders';const SRC = `#pragma shader "ParamTest"@@ -70,3 +71,40 @@ describe('reflectEsshader', () => {expect(reflectEsshader('#pragma param u_a float').domain).toBe('Unlit2D');});});++describe('a declared default in the shape a material stores it', () => {+ it('maps each param type to its stored shape', () => {+ const p = (name: string) => reflectEsshader(SRC).params.find((x) => x.name === name)!;+ expect(paramDefaultValue(p('u_strength'))).toBe(1);+ expect(paramDefaultValue(p('u_tint'))).toEqual({ r: 1, g: 0.5, b: 0.25, a: 1 });+ expect(paramDefaultValue(p('u_offset'))).toEqual({ x: 3, y: 4 });+ // A texture default is a NAME the engine resolves, not a ref to an asset.+ expect(paramDefaultValue(p('u_noise'))).toBe('white');+ });+});++describe('the built-in templates take their defaults from their own source', () => {+ // Five of the seven used to carry `defaults: {}` while their shader declared four+ // parameters: a material made from Dissolve came out empty, and the word `u_progress`+ // appeared nowhere a caller could find it. Deriving them is why that cannot recur.+ it('names every non-texture param a template declares', () => {+ for (const tpl of BUILTIN_SHADER_TEMPLATES) {+ const declared = reflectEsshader(tpl.source).params.filter((p) => p.type !== 'texture');+ expect([tpl.id, Object.keys(tpl.defaults).sort()])+ .toEqual([tpl.id, declared.map((p) => p.name).sort()]);+ }+ });++ it('carries the dissolve slider the engine actually reads', () => {+ expect(builtinShaderTemplate('sprite-dissolve')!.defaults).toEqual({+ u_progress: 0,+ u_edgeColor: { r: 1, g: 0.5, b: 0, a: 1 },+ u_edgeWidth: 0.08,+ u_noiseScale: 12,+ });+ });++ it('leaves a texture param out — a stored "flatnormal" would read as an asset ref', () => {+ expect(builtinShaderTemplate('sprite-lit')!.defaults).toEqual({ u_tint: { r: 1, g: 1, b: 1, a: 1 } });+ });+});