@ignifx/core 0.11.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{environment-BCjfp1jB.js → environment-C9AjYJgV.js} +2 -2
- package/dist/{environment-BCjfp1jB.js.map → environment-C9AjYJgV.js.map} +1 -1
- package/dist/{ignifx-error-RpK-lWwE.js → ignifx-error-Dq2qJMkZ.js} +10 -3
- package/dist/ignifx-error-Dq2qJMkZ.js.map +1 -0
- package/dist/index.d.ts +105 -17
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +360 -78
- package/dist/index.js.map +1 -1
- package/dist/json-CzZZ6K4x.js +24 -0
- package/dist/json-CzZZ6K4x.js.map +1 -0
- package/dist/{material-plugin-CWtV7DkH.js → material-plugin-BOCB7Stt.js} +2 -2
- package/dist/{material-plugin-CWtV7DkH.js.map → material-plugin-BOCB7Stt.js.map} +1 -1
- package/dist/{post-effect-C42XJFmo.js → post-effect-BHl7U56q.js} +5 -4
- package/dist/post-effect-BHl7U56q.js.map +1 -0
- package/dist/{post-effect-compiler-pOvXae-i.js → post-effect-compiler-Dw6zW2cG.js} +3 -3
- package/dist/{post-effect-compiler-pOvXae-i.js.map → post-effect-compiler-Dw6zW2cG.js.map} +1 -1
- package/dist/{shader-material-B6wwFCKB.js → shader-material-BxQn9FT4.js} +2 -2
- package/dist/{shader-material-B6wwFCKB.js.map → shader-material-BxQn9FT4.js.map} +1 -1
- package/dist/{shader-material-C4VjLTfV.js → shader-material-DRZmqA_S.js} +10 -6
- package/dist/shader-material-DRZmqA_S.js.map +1 -0
- package/dist/{shader-pragma-qO9_6sTd.js → shader-pragma-DrFm5f5m.js} +2 -2
- package/dist/{shader-pragma-qO9_6sTd.js.map → shader-pragma-DrFm5f5m.js.map} +1 -1
- package/dist/{surface-shader-BaR7Kg-F.js → surface-shader-BgZchRBe.js} +4 -4
- package/dist/{surface-shader-BaR7Kg-F.js.map → surface-shader-BgZchRBe.js.map} +1 -1
- package/package.json +1 -1
- package/dist/ignifx-error-RpK-lWwE.js.map +0 -1
- package/dist/post-effect-C42XJFmo.js.map +0 -1
- package/dist/shader-material-C4VjLTfV.js.map +0 -1
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
//#region src/schema/json.ts
|
|
2
|
+
/**
|
|
3
|
+
* Sets a key on an object being built from JSON as an own, enumerable data property — what
|
|
4
|
+
* `JSON.parse` does. A plain `target[key] = value` treats the key `__proto__` as the prototype
|
|
5
|
+
* setter, so a file carrying that key would change the copy's prototype instead of holding data.
|
|
6
|
+
*
|
|
7
|
+
* @param target - The object under construction.
|
|
8
|
+
* @param key - The key, taken from parsed JSON.
|
|
9
|
+
* @param value - The value.
|
|
10
|
+
*
|
|
11
|
+
* @internal
|
|
12
|
+
*/
|
|
13
|
+
function setOwnJsonProperty(target, key, value) {
|
|
14
|
+
Object.defineProperty(target, key, {
|
|
15
|
+
value,
|
|
16
|
+
enumerable: true,
|
|
17
|
+
writable: true,
|
|
18
|
+
configurable: true
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
//#endregion
|
|
22
|
+
export { setOwnJsonProperty as t };
|
|
23
|
+
|
|
24
|
+
//# sourceMappingURL=json-CzZZ6K4x.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"json-CzZZ6K4x.js","names":[],"sources":["../src/schema/json.ts"],"sourcesContent":["/**\n * The JSON value model the serializer works in. Scene and prefab files are UTF-8 JSON\n * (`docs/architecture/06-serialization-and-scene-format.md` §1), so every encoded schema value is\n * one of these shapes. The type is recursive rather than `unknown` so that encoders cannot smuggle\n * a `Date`, a `Map`, or an `undefined` into a file (coding standards §5.2 bans `any`).\n *\n * @public\n */\nexport type JsonValue = string | number | boolean | null | JsonArray | JsonObject;\n\n/**\n * A JSON array. Read-only because encoded values are snapshots: callers copy before mutating.\n *\n * @public\n */\nexport type JsonArray = readonly JsonValue[];\n\n/**\n * A JSON object. Keys are emitted in the canonical order defined by\n * `docs/architecture/06-serialization-and-scene-format.md` §1, so two saves of the same state\n * produce byte-identical files.\n *\n * @public\n */\nexport type JsonObject = { readonly [key: string]: JsonValue };\n\n/**\n * Sets a key on an object being built from JSON as an own, enumerable data property — what\n * `JSON.parse` does. A plain `target[key] = value` treats the key `__proto__` as the prototype\n * setter, so a file carrying that key would change the copy's prototype instead of holding data.\n *\n * @param target - The object under construction.\n * @param key - The key, taken from parsed JSON.\n * @param value - The value.\n *\n * @internal\n */\nexport function setOwnJsonProperty<T>(target: Record<string, T>, key: string, value: T): void {\n Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });\n}\n"],"mappings":";;;;;;;;;;;;AAqCA,SAAgB,mBAAsB,QAA2B,KAAa,OAAgB;CAC5F,OAAO,eAAe,QAAQ,KAAK;EAAE;EAAO,YAAY;EAAM,UAAU;EAAM,cAAc;CAAK,CAAC;AACpG"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as assertNever, o as CoreErrorCode, t as IgnifxError } from "./ignifx-error-
|
|
1
|
+
import { n as assertNever, o as CoreErrorCode, t as IgnifxError } from "./ignifx-error-Dq2qJMkZ.js";
|
|
2
2
|
import { u as SHADER_UNIFORM_TYPES } from "./shader-declaration-5q__jycG.js";
|
|
3
3
|
import { createPbrMaterial, createStandardMaterial, markMaterialUboDirty, rebuildMaterial, setPbrAlphaCutoff, setPbrEmissive, setPbrUnlit, setStandardBumpTexture, setStandardEmissiveTexture, setStandardOpacityTexture, setStandardSpecularTexture } from "@babylonjs/lite";
|
|
4
4
|
//#region src/lite/material.ts
|
|
@@ -482,4 +482,4 @@ function assertUniformType(plugin, binding, type) {
|
|
|
482
482
|
//#endregion
|
|
483
483
|
export { defineMaterialPlugin as a, MATERIAL_ALPHA_MODES as c, createStandardMaterialFromProps as d, markMaterialDirty as f, setPbrMetallicRoughness as g, setPbrBaseColor as h, MATERIAL_PLUGIN_SAMPLER_BUDGET as i, createDefaultMaterial as l, setMaterialAlpha as m, MATERIAL_PLUGIN_DEFAULT_PRIORITY as n, isLiteMaterialPluginPoint as o, rebuildMaterialPipelines as p, MATERIAL_PLUGIN_RESERVED_NAMES as r, uniformComponentCount as s, LITE_MATERIAL_PLUGIN_POINTS as t, createPbrMaterialFromProps as u };
|
|
484
484
|
|
|
485
|
-
//# sourceMappingURL=material-plugin-
|
|
485
|
+
//# sourceMappingURL=material-plugin-BOCB7Stt.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"material-plugin-CWtV7DkH.js","names":[],"sources":["../src/lite/material.ts","../src/render/material-plugin.ts"],"sourcesContent":["import {\n createPbrMaterial,\n createStandardMaterial,\n enableMaterialTracking,\n markMaterialUboDirty,\n rebuildMaterial,\n setPbrAlphaCutoff,\n setPbrEmissive,\n setPbrUnlit,\n setStandardBumpTexture,\n setStandardEmissiveTexture,\n setStandardOpacityTexture,\n setStandardSpecularTexture,\n} from \"@babylonjs/lite\";\nimport { assertNever } from \"../errors/ignifx-error.js\";\nimport type { Material, PbrMaterialProps, SceneContext, StandardMaterialProps, Texture2D } from \"@babylonjs/lite\";\n\n/**\n * Material half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §2.6): the three\n * material kinds a `MaterialAsset` can produce, built from plain ignifx props.\n *\n * Everything here is `@internal`, and every colour that reaches it is **linear** — the sRGB decode\n * belongs to the asset layer.\n *\n * ## What a Lite material is (verified against `@babylonjs/lite@1.27.0`)\n *\n * - A material is plain data plus one private `_buildGroup` function; `createPbrMaterial` is\n * literally `{ ...props, _buildGroup, _uboVersion: 0 }` (`lib/material/pbr/pbr-material.js`), so\n * none of these factories touches the GPU and all of them run under the null engine.\n * - **The build group is a per-family singleton.** `getPbrGroupBuilder()`, `getStandardGroupBuilder()`\n * and `getShaderGroupBuilder()` each memoise one function for the whole process\n * (`lib/material/pbr/pbr-material.js`, `lib/material/standard/create-standard-material.js`,\n * `lib/material/shader/shader-material.js` line 123), and a scene keys its renderable groups by\n * that function (`lib/scene/scene-core.js`, `addToScene`). \"Material family\" in\n * `docs/architecture/07-rendering.md` §1.1 therefore means *pbr*, *standard*, *shader* or *node* —\n * **not** an individual material. Only node materials get a per-material builder\n * (`lib/material/node/node-material.js`). This is what makes {@link warmUpMaterialFamilies} in\n * `./gpu/warm-up.ts` cheap: one hidden mesh per family covers every material in it.\n * - Scalar and vector edits only need `markMaterialUboDirty` (`index.d.ts` 6974), which bumps\n * `_uboVersion`. Anything that changes the compiled feature set — binding or clearing a texture,\n * flipping `doubleSided`, changing culling — needs {@link rebuildMaterialPipelines}.\n *\n * ## The custom WGSL family lives elsewhere\n *\n * `createShaderMaterial` and the `setShader*` setters are in `./gpu/shader-material.ts`, not here:\n * this module is statically reachable from every app through the material asset layer, and Babylon\n * Lite exports one barrel, so a static import of the shader factory would put Lite's whole\n * shader-material pipeline in every entry chunk. That module is reached through a dynamic\n * `import()` instead (`docs/plan/2026-09-terrain-particles-shaders.md` §3.1, \"Bundle cost\").\n */\n\n/**\n * The Babylon Lite material a `MaterialAsset` owns, re-exported under an ignifx name\n * (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteMaterial = Material;\n\n/**\n * A Babylon Lite physically based material, re-exported under an ignifx name.\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LitePbrMaterial = PbrMaterialProps;\n\n/**\n * A Babylon Lite Babylon-Standard material, re-exported under an ignifx name.\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteStandardMaterial = StandardMaterialProps;\n\n/** glTF's default alpha cutoff, used when a `\"mask\"` material declares none. */\nconst DEFAULT_ALPHA_CUTOFF = 0.5;\n\n/**\n * How a material's alpha channel is interpreted, in glTF's vocabulary, in the order the inspector\n * lists them (`docs/architecture/07-rendering.md` §2.4).\n *\n * @public\n */\nexport const MATERIAL_ALPHA_MODES = [\"opaque\", \"mask\", \"blend\"] as const;\n\n/**\n * The union of the alpha modes a material can declare.\n *\n * @public\n */\nexport type MaterialAlphaMode = (typeof MATERIAL_ALPHA_MODES)[number];\n\n/**\n * The physically based material properties an ignifx `.material.json` declares\n * (`docs/architecture/06-serialization-and-scene-format.md` §6). Every field is optional; an\n * omitted field leaves Lite's own default in place.\n *\n * @internal\n */\nexport interface PbrMaterialInput {\n /** A human-readable name, used for glTF material overrides and diagnostics. */\n readonly name?: string;\n /** Linear base colour and alpha, multiplied with the base colour texture. */\n readonly baseColor?: readonly [number, number, number, number];\n /** The base colour texture. Load it with an sRGB format. */\n readonly baseColorTexture?: Texture2D;\n /** Metallic factor, 0 to 1. */\n readonly metallic?: number;\n /** Roughness factor, 0 to 1. */\n readonly roughness?: number;\n /** The packed occlusion/roughness/metallic texture (glTF `ORM`). */\n readonly metallicRoughnessTexture?: Texture2D;\n /** The tangent-space normal map. */\n readonly normalTexture?: Texture2D;\n /** Normal map strength. */\n readonly normalScale?: number;\n /** Linear emissive colour. */\n readonly emissive?: readonly [number, number, number];\n /** The emissive texture. */\n readonly emissiveTexture?: Texture2D;\n /** A separate occlusion texture, sampled on UV1 when the ORM texture is not used for it. */\n readonly occlusionTexture?: Texture2D;\n /** How strongly ambient occlusion darkens the surface, 0 to 1. */\n readonly occlusionStrength?: number;\n /** How the alpha channel is interpreted. */\n readonly alphaMode?: MaterialAlphaMode;\n /** The cutoff below which a `\"mask\"` material discards a fragment. */\n readonly alphaCutoff?: number;\n /** Overall material alpha, 0 to 1. */\n readonly alpha?: number;\n /** Whether back faces are drawn. */\n readonly doubleSided?: boolean;\n /** Whether lighting is skipped entirely. */\n readonly unlit?: boolean;\n /** How strongly the environment map contributes. */\n readonly environmentIntensity?: number;\n}\n\n/**\n * The Babylon-Standard material properties an ignifx `.material.json` declares, for the cheap\n * non-PBR path (`docs/architecture/07-rendering.md` §2.6).\n *\n * @internal\n */\nexport interface StandardMaterialInput {\n /** A human-readable name. */\n readonly name?: string;\n /** Linear diffuse colour. */\n readonly diffuse?: readonly [number, number, number];\n /** The diffuse texture. */\n readonly diffuseTexture?: Texture2D;\n /** Linear specular colour. */\n readonly specular?: readonly [number, number, number];\n /** Specular exponent; higher values give a tighter highlight. */\n readonly specularPower?: number;\n /** The specular texture. */\n readonly specularTexture?: Texture2D;\n /** Linear emissive colour. */\n readonly emissive?: readonly [number, number, number];\n /** The emissive texture. */\n readonly emissiveTexture?: Texture2D;\n /** The tangent-space normal map. */\n readonly normalTexture?: Texture2D;\n /** The opacity texture. */\n readonly opacityTexture?: Texture2D;\n /** Overall material alpha, 0 to 1. */\n readonly alpha?: number;\n /** The cutoff below which a fragment is discarded. `0` disables the alpha test. */\n readonly alphaCutoff?: number;\n /** Whether back faces are drawn. */\n readonly doubleSided?: boolean;\n /** Whether lighting is skipped entirely. */\n readonly unlit?: boolean;\n}\n\n/**\n * Builds a Lite PBR material from ignifx props.\n *\n * @param input - The declared properties.\n * @returns The material. It holds no GPU resource of its own; the textures it references do.\n *\n * @example\n * ```ts\n * const gold = createPbrMaterialFromProps({ baseColor: [1, 0.77, 0.34, 1], metallic: 1, roughness: 0.25 });\n * ```\n *\n * @internal\n */\nexport function createPbrMaterialFromProps(input: PbrMaterialInput): PbrMaterialProps {\n const props: Partial<PbrMaterialProps> = {};\n if (input.name !== undefined) {\n props.name = input.name;\n }\n if (input.baseColor !== undefined) {\n props.baseColorFactor = [input.baseColor[0], input.baseColor[1], input.baseColor[2], input.baseColor[3]];\n }\n if (input.baseColorTexture !== undefined) {\n props.baseColorTexture = input.baseColorTexture;\n }\n if (input.metallic !== undefined) {\n props.metallicFactor = input.metallic;\n }\n if (input.roughness !== undefined) {\n props.roughnessFactor = input.roughness;\n }\n if (input.metallicRoughnessTexture !== undefined) {\n props.ormTexture = input.metallicRoughnessTexture;\n }\n if (input.normalTexture !== undefined) {\n props.normalTexture = input.normalTexture;\n }\n if (input.normalScale !== undefined) {\n props.normalTextureScale = input.normalScale;\n }\n if (input.emissiveTexture !== undefined) {\n props.emissiveTexture = input.emissiveTexture;\n }\n if (input.occlusionTexture !== undefined) {\n props.occlusionTexture = input.occlusionTexture;\n }\n if (input.occlusionStrength !== undefined) {\n props.occlusionStrength = input.occlusionStrength;\n }\n if (input.alpha !== undefined) {\n props.alpha = input.alpha;\n }\n if (input.doubleSided !== undefined) {\n props.doubleSided = input.doubleSided;\n }\n if (input.environmentIntensity !== undefined) {\n props.environmentIntensity = input.environmentIntensity;\n }\n if (input.alphaMode === \"blend\") {\n props.alphaBlend = true;\n }\n const material = createPbrMaterial(props);\n if (input.alphaMode === \"mask\") {\n setPbrAlphaCutoff(material, input.alphaCutoff ?? DEFAULT_ALPHA_CUTOFF);\n }\n if (input.emissive !== undefined) {\n setPbrEmissive(material, [input.emissive[0], input.emissive[1], input.emissive[2]]);\n }\n if (input.unlit === true) {\n setPbrUnlit(material);\n }\n return material;\n}\n\n/**\n * Builds a Lite Standard material from ignifx props.\n *\n * @param input - The declared properties.\n * @returns The material.\n *\n * @internal\n */\nexport function createStandardMaterialFromProps(input: StandardMaterialInput): StandardMaterialProps {\n const material = createStandardMaterial();\n if (input.name !== undefined) {\n material.name = input.name;\n }\n if (input.diffuse !== undefined) {\n writeTriple(material.diffuseColor, input.diffuse);\n }\n if (input.specular !== undefined) {\n writeTriple(material.specularColor, input.specular);\n }\n if (input.emissive !== undefined) {\n writeTriple(material.emissiveColor, input.emissive);\n }\n if (input.specularPower !== undefined) {\n material.specularPower = input.specularPower;\n }\n if (input.alpha !== undefined) {\n material.alpha = input.alpha;\n }\n if (input.alphaCutoff !== undefined) {\n material.alphaCutOff = input.alphaCutoff;\n }\n if (input.doubleSided !== undefined) {\n material.backFaceCulling = !input.doubleSided;\n }\n if (input.unlit !== undefined) {\n material.disableLighting = input.unlit;\n }\n if (input.diffuseTexture !== undefined) {\n material.diffuseTexture = input.diffuseTexture;\n }\n if (input.specularTexture !== undefined) {\n setStandardSpecularTexture(material, input.specularTexture);\n }\n if (input.emissiveTexture !== undefined) {\n setStandardEmissiveTexture(material, input.emissiveTexture);\n }\n if (input.normalTexture !== undefined) {\n setStandardBumpTexture(material, input.normalTexture);\n }\n if (input.opacityTexture !== undefined) {\n setStandardOpacityTexture(material, input.opacityTexture);\n }\n return material;\n}\n\n/**\n * The material a `MeshRenderer` uses when it declares none: a neutral, fully rough dielectric.\n *\n * @returns A fresh material. Callers share one instance per app rather than one per renderer.\n *\n * @internal\n */\nexport function createDefaultMaterial(): PbrMaterialProps {\n return createPbrMaterialFromProps({\n name: \"ignifx:default\",\n baseColor: [1, 1, 1, 1],\n metallic: 0,\n roughness: 0.9,\n });\n}\n\n/**\n * Replaces a PBR material's linear base colour.\n *\n * @param material - The material to change.\n * @param r - The linear red component.\n * @param g - The linear green component.\n * @param b - The linear blue component.\n * @param a - The alpha component.\n *\n * @internal\n */\nexport function setPbrBaseColor(material: PbrMaterialProps, r: number, g: number, b: number, a: number): void {\n const factor = material.baseColorFactor;\n if (factor === undefined) {\n material.baseColorFactor = [r, g, b, a];\n } else {\n factor[0] = r;\n factor[1] = g;\n factor[2] = b;\n factor[3] = a;\n }\n markMaterialDirty(material);\n}\n\n/**\n * Replaces a PBR material's metallic and roughness factors.\n *\n * @param material - The material to change.\n * @param metallic - The metallic factor, 0 to 1.\n * @param roughness - The roughness factor, 0 to 1.\n *\n * @internal\n */\nexport function setPbrMetallicRoughness(material: PbrMaterialProps, metallic: number, roughness: number): void {\n material.metallicFactor = metallic;\n material.roughnessFactor = roughness;\n markMaterialDirty(material);\n}\n\n/**\n * Replaces a material's overall alpha.\n *\n * @param material - The PBR or Standard material to change.\n * @param alpha - The new alpha, 0 to 1.\n *\n * @internal\n */\nexport function setMaterialAlpha(material: PbrMaterialProps | StandardMaterialProps, alpha: number): void {\n material.alpha = alpha;\n markMaterialDirty(material);\n}\n\n/**\n * Marks a material's uniform block for re-upload on the next frame.\n *\n * @remarks\n * This is the cheap path and covers every scalar, vector, and colour edit. It does **not** cover\n * changes that alter the compiled feature set; those go through {@link rebuildMaterialPipelines}.\n *\n * @param material - The material that changed.\n *\n * @internal\n */\nexport function markMaterialDirty(material: Material): void {\n markMaterialUboDirty(material);\n}\n\n/**\n * Rebuilds the renderables of a material whose compiled feature set changed.\n *\n * @remarks\n * Needed after binding or clearing a texture, changing culling, or toggling a sub-feature\n * (`index.d.ts` 11133). `rebuildFrameGraph` is left off so a component can batch several material\n * edits and rebuild the frame graph once.\n *\n * @param scene - The scene the material renders in.\n * @param material - The material that changed.\n *\n * @internal\n */\nexport function rebuildMaterialPipelines(scene: SceneContext, material: Material): void {\n // Since 1.34 a PBR rebuild in a built scene finishes asynchronously, and Lite reports its failure\n // itself (`lib/material/material-rebuild.js`, `rebuildMaterial`), so nothing is left to await.\n void rebuildMaterial(scene, material);\n}\n\n/**\n * Installs automatic dirty tracking on a material, so property writes mark its uniform block\n * without an explicit {@link markMaterialDirty}.\n *\n * @remarks\n * Lite installs the tracker by rewriting the material's property descriptors, and the module that\n * does it is loaded lazily, so this is asynchronous (`index.d.ts` 4480,\n * `lib/material/observable-material.js`). Opt-in only: it costs an accessor call per write, which\n * the zero-allocation rules (coding standards §7) do not want on every material.\n *\n * @param material - The PBR or Standard material to track.\n * @returns A promise that resolves once the tracker is installed.\n *\n * @internal\n */\nexport function enableMaterialChangeTracking(material: PbrMaterialProps | StandardMaterialProps): Promise<void> {\n return enableMaterialTracking(material);\n}\n\n/**\n * Reports whether Lite will alpha-blend a material declared with this alpha mode.\n *\n * @param mode - The declared alpha mode.\n * @returns `true` for `\"blend\"`, `false` for `\"opaque\"` and `\"mask\"`.\n *\n * @internal\n */\nexport function isBlendedAlphaMode(mode: MaterialAlphaMode): boolean {\n switch (mode) {\n case \"opaque\":\n case \"mask\":\n return false;\n case \"blend\":\n return true;\n default:\n return assertNever(mode, \"material alpha mode\");\n }\n}\n\n/**\n * Writes three components into a Lite colour tuple in place.\n *\n * @param target - The tuple Lite owns.\n * @param source - The values to copy.\n */\nfunction writeTriple(target: [number, number, number], source: readonly [number, number, number]): void {\n target[0] = source[0];\n target[1] = source[1];\n target[2] = source[2];\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { assertNever, IgnifxError } from \"../errors/ignifx-error.js\";\nimport { SHADER_UNIFORM_TYPES } from \"./shader-declaration.js\";\nimport type { ShaderTextureDeclaration, ShaderUniformDeclaration, ShaderUniformType } from \"./shader-declaration.js\";\n\n/**\n * The raw Babylon Lite material-plugin points, as a `@beta` escape hatch\n * (`docs/plan/2026-09-terrain-particles-shaders.md` §3.2, ADR-0024).\n *\n * `@beta` because the meaning of each point is whatever the surrounding Lite template declares at\n * that line; ignifx's stable contract is the three hooks of `./surface-shader.ts`. Four rules read\n * out of `@babylonjs/lite@1.27.0`'s `lib/` on 2026-09-08:\n *\n * - Plugin uniforms and samplers are **fragment-stage only** on both families\n * (`lib/material/plugin/plugin-bridge-shared.js` 99), and there is no vertex helper-function\n * channel, so vertex code may read only attributes, `mesh.world` and the scene block, and must be\n * statements rather than functions.\n * - `CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION` is injected **twice** — Lite maps it to the two\n * adjacent PBR slots `AI` and `NI` — so its code must be idempotent or guard itself with a flag\n * set at an earlier point, and must declare nothing at statement level.\n * - Only PBR carries `CUSTOM_FRAGMENT_UPDATE_DIFFUSE` after `CUSTOM_FRAGMENT_UPDATE_ALPHA`;\n * Standard's template orders them the other way and has no `AI`/`NI`/`MF` slots.\n * - `roughness` and `metallic` are `let` in the PBR template and cannot be written.\n */\n\n/**\n * The Babylon Lite injection points a {@link MaterialPluginDefinition} may fill in.\n *\n * @remarks\n * The names are Lite's own (`MaterialPluginPoint`, `index.d.ts` 7084) and are taught verbatim,\n * because a plugin's code is written against the template around the point.\n *\n * @beta\n */\nexport const LITE_MATERIAL_PLUGIN_POINTS = [\n \"CUSTOM_FRAGMENT_DEFINITIONS\",\n \"CUSTOM_FRAGMENT_MAIN_BEGIN\",\n \"CUSTOM_FRAGMENT_UPDATE_ALPHA\",\n \"CUSTOM_FRAGMENT_UPDATE_DIFFUSE\",\n \"CUSTOM_FRAGMENT_BEFORE_LIGHTS\",\n \"CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION\",\n \"CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\",\n \"CUSTOM_VERTEX_MAIN_BEGIN\",\n \"CUSTOM_VERTEX_UPDATE_WORLDPOS\",\n \"CUSTOM_VERTEX_MAIN_END\",\n] as const;\n\n/**\n * One of Babylon Lite's ten material-plugin injection points.\n *\n * @beta\n */\nexport type LiteMaterialPluginPoint = (typeof LITE_MATERIAL_PLUGIN_POINTS)[number];\n\n/**\n * The default priority Babylon Lite gives a plugin with none (`index.d.ts` 7057).\n *\n * @beta\n */\nexport const MATERIAL_PLUGIN_DEFAULT_PRIORITY = 500;\n\n/**\n * How many `texture`/`sampler` pairs one material's plugins may declare together.\n *\n * @remarks\n * Measured on a device on 2026-09-08 (spike S0.2): a fully textured PBR material — base colour,\n * normal, ORM, emissive — with image-based lighting and one PCF shadow light already binds seven\n * textures and seven samplers of the sixteen per stage that every WebGPU implementation guarantees,\n * SwiftShader included, and Lite requests no higher `requiredLimits`. Nine is what is left, and it\n * drops to eight with a second shadow light and seven with a lightmap, so a material that means to\n * be portable should stay well under the cap.\n *\n * @beta\n */\nexport const MATERIAL_PLUGIN_SAMPLER_BUDGET = 9;\n\n/**\n * The WGSL names the PBR and Standard templates already own, which a plugin may not reuse for a\n * uniform field or a sampler.\n *\n * @remarks\n * A plugin's fields land in the host's own uniform block and its samplers in the host's own bind\n * group, so a collision is a duplicate WGSL declaration and the whole material stops compiling with\n * a message that names neither the plugin nor the field. Refusing at attach time is the difference\n * between a sentence and a shader dump. Read from `pbr-template.js` `_baseMaterialUboFields` and\n * `_baseBindings`, and `standard-template.js` `materialStruct` and `_baseBindings`.\n *\n * @beta\n */\nexport const MATERIAL_PLUGIN_RESERVED_NAMES: readonly string[] = Object.freeze([\n // Blocks and entry points the templates declare.\n \"material\",\n \"mesh\",\n \"scene\",\n \"lights\",\n \"pluginUbo\",\n \"shadowParams\",\n \"main\",\n // PBR material uniform fields.\n \"environmentIntensity\",\n \"directIntensity\",\n \"reflectance\",\n \"materialAlpha\",\n \"baseColorFactor\",\n \"metallicFactor\",\n \"roughnessFactor\",\n \"normalScale\",\n \"lightFalloffMode\",\n \"anisotropyParams\",\n // PBR samplers.\n \"baseColorTexture\",\n \"baseColorSampler\",\n \"normalTexture\",\n \"normalSampler_\",\n \"ormTexture\",\n \"ormSampler\",\n \"emissiveTexture\",\n \"emissiveSampler\",\n \"specGlossTexture\",\n \"specGlossSampler\",\n // Standard samplers (`standard-template.js` uses two-letter names).\n \"dT\",\n \"dS\",\n \"mat\",\n \"up\",\n]);\n\n/**\n * What a raw material plugin declares: a name, the values and textures it wants beside the host\n * material's own, and the WGSL it injects.\n *\n * @beta\n */\nexport interface MaterialPluginDefinition {\n /** The plugin's identity. It is part of Lite's pipeline cache key, so it must be stable. */\n readonly name: string;\n /** Lower runs first; Lite's own default is {@link MATERIAL_PLUGIN_DEFAULT_PRIORITY}. */\n readonly priority: number;\n /** The uniform fields appended to the host material's uniform block. Fragment stage only. */\n readonly uniforms: readonly ShaderUniformDeclaration[];\n /** The `texture`/`sampler` pairs added to the host material's bind group. Fragment stage only. */\n readonly textures: readonly ShaderTextureDeclaration[];\n /** The WGSL to inject, by point. Vertex points take statements; there are no vertex helpers. */\n readonly code: Readonly<Partial<Record<LiteMaterialPluginPoint, string>>>;\n}\n\n/**\n * The properties {@link defineMaterialPlugin} accepts; everything but `name` and `code` has a\n * default.\n *\n * @beta\n */\nexport interface MaterialPluginDefinitionInit {\n /** The plugin's identity. */\n readonly name: string;\n /** Lower runs first. Defaults to {@link MATERIAL_PLUGIN_DEFAULT_PRIORITY}. */\n readonly priority?: number;\n /** The uniform fields. Defaults to none. */\n readonly uniforms?: readonly ShaderUniformDeclaration[];\n /** The samplers. Defaults to none. */\n readonly textures?: readonly ShaderTextureDeclaration[];\n /** The WGSL to inject, by point. */\n readonly code: Readonly<Partial<Record<LiteMaterialPluginPoint, string>>>;\n}\n\n/** Matches a WGSL identifier. */\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Matches a legal plugin name: an identifier, optionally with `.`, `:`, or `-` inside it. */\nconst PLUGIN_NAME = /^[A-Za-z_][A-Za-z0-9_]*(?:[.:-][A-Za-z0-9_]+)*$/;\n\n/**\n * Validates a raw material-plugin declaration and fills in its defaults.\n *\n * @remarks\n * Nothing here reaches a device: the result is plain data that `attachSurfaceShaders` and\n * `attachMaterialPlugin` turn into a Lite plugin. The checks are the ones whose failure would\n * otherwise surface as a WGSL compile error with no mention of the plugin — an empty `code`, a\n * duplicate or reserved binding name, a name that is not a WGSL identifier, an unknown injection\n * point, or more samplers than {@link MATERIAL_PLUGIN_SAMPLER_BUDGET}.\n *\n * The **surface-shader compiler produces one of these**, so a bug in this validation is a bug in\n * every surface shader too, which is why it lives here rather than inside the compiler.\n *\n * @param definition - The declaration.\n * @returns The same declaration with `priority`, `uniforms`, and `textures` filled in.\n * @throws IgnifxError with code `IGX-0723` when `code` fills in no point, `IGX-0712` when a name is\n * not a legal, unique, unreserved WGSL identifier or a point name is unknown, or `IGX-0726` when the\n * plugin alone exceeds the sampler budget.\n *\n * @example\n * ```ts\n * const tint = defineMaterialPlugin({\n * name: \"tint\",\n * code: { CUSTOM_FRAGMENT_UPDATE_ALPHA: \"baseColor = baseColor * vec3<f32>(1.0, 0.5, 0.5);\" },\n * });\n * ```\n *\n * @beta\n */\nexport function defineMaterialPlugin(definition: MaterialPluginDefinitionInit): MaterialPluginDefinition {\n const name = definition.name;\n if (!PLUGIN_NAME.test(name)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${JSON.stringify(name)} is not a legal material-plugin name.`,\n {\n context: { plugin: name, name },\n hint: \"Start with a letter or underscore; letters, digits, underscores, and inner . : - follow.\",\n },\n );\n }\n const points = Object.keys(definition.code);\n let filled = 0;\n for (const point of points) {\n if (!isLiteMaterialPluginPoint(point)) {\n throw new IgnifxError(CoreErrorCode.unknownShaderBinding, `${name} declares no Lite point named ${point}.`, {\n context: { plugin: name, name: point, point },\n hint: `The ten points are ${LITE_MATERIAL_PLUGIN_POINTS.join(\", \")}.`,\n });\n }\n if ((definition.code[point] ?? \"\").trim().length > 0) {\n filled += 1;\n }\n }\n if (filled === 0) {\n throw new IgnifxError(CoreErrorCode.surfaceHookMissing, `${name} injects no WGSL at any Lite point.`, {\n context: { plugin: name, name },\n hint: \"Fill in at least one of the ten points, or do not attach the plugin.\",\n });\n }\n const uniforms = definition.uniforms ?? [];\n const textures = definition.textures ?? [];\n const seen = new Set<string>();\n for (const uniform of uniforms) {\n assertBindingName(name, uniform.name, seen);\n assertUniformType(name, uniform.name, uniform.type);\n }\n for (const texture of textures) {\n assertBindingName(name, texture.name, seen);\n assertBindingName(name, `${texture.name}Sampler`, seen);\n }\n if (textures.length > MATERIAL_PLUGIN_SAMPLER_BUDGET) {\n throw new IgnifxError(\n CoreErrorCode.surfaceSamplerBudgetExceeded,\n `${name} declares ${String(textures.length)} samplers; a material's plugins may declare ${String(MATERIAL_PLUGIN_SAMPLER_BUDGET)} together.`,\n {\n context: { plugin: name, samplers: textures.length, budget: MATERIAL_PLUGIN_SAMPLER_BUDGET },\n hint: \"Pack the maps into fewer textures — an RGBA control map rather than four masks.\",\n },\n );\n }\n return {\n name,\n priority: definition.priority ?? MATERIAL_PLUGIN_DEFAULT_PRIORITY,\n uniforms,\n textures,\n code: definition.code,\n };\n}\n\n/**\n * Whether a string is one of Lite's ten injection points.\n *\n * @param value - The candidate.\n * @returns `true` when Lite accepts it.\n *\n * @beta\n */\nexport function isLiteMaterialPluginPoint(value: string): value is LiteMaterialPluginPoint {\n for (const point of LITE_MATERIAL_PLUGIN_POINTS) {\n if (point === value) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * How many floats one uniform of a declared type occupies on the CPU side.\n *\n * @param type - The declared WGSL type.\n * @returns The component count: 1, 2, 3, 4, or 16.\n *\n * @internal\n */\nexport function uniformComponentCount(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 2;\n }\n case \"vec3<f32>\": {\n return 3;\n }\n case \"vec4<f32>\": {\n return 4;\n }\n case \"mat4x4<f32>\": {\n return 16;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 1;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * Refuses a binding name that is not a unique, unreserved WGSL identifier.\n *\n * @param plugin - The plugin's name, for the message.\n * @param binding - The candidate name.\n * @param seen - The names already taken by this plugin; the accepted name is added.\n * @throws IgnifxError with code `IGX-0712`.\n */\nfunction assertBindingName(plugin: string, binding: string, seen: Set<string>): void {\n if (!IDENTIFIER.test(binding)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${plugin} declares ${JSON.stringify(binding)}, which is not a WGSL identifier.`,\n { context: { plugin, name: binding }, hint: \"Use letters, digits, and underscores, starting with a letter.\" },\n );\n }\n if (MATERIAL_PLUGIN_RESERVED_NAMES.includes(binding)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${plugin} declares ${binding}, which Babylon Lite's own PBR or Standard shader already owns.`,\n { context: { plugin, name: binding }, hint: \"Rename it; a plugin shares the host material's WGSL namespace.\" },\n );\n }\n if (seen.has(binding)) {\n throw new IgnifxError(CoreErrorCode.unknownShaderBinding, `${plugin} declares ${binding} twice.`, {\n context: { plugin, name: binding },\n hint: \"Every uniform and texture of one plugin needs its own name.\",\n });\n }\n seen.add(binding);\n}\n\n/**\n * Refuses a uniform type Lite's plugin bridge cannot carry.\n *\n * @param plugin - The plugin's name, for the message.\n * @param binding - The uniform's name.\n * @param type - The declared type.\n * @throws IgnifxError with code `IGX-0712`.\n */\nfunction assertUniformType(plugin: string, binding: string, type: ShaderUniformType): void {\n if (!SHADER_UNIFORM_TYPES.includes(type)) {\n throw new IgnifxError(CoreErrorCode.unknownShaderBinding, `${plugin}.${binding} declares the type ${type}.`, {\n context: { plugin, name: binding, type },\n hint: `The plugin uniform types are ${SHADER_UNIFORM_TYPES.join(\", \")}.`,\n });\n }\n}\n"],"mappings":";;;;;AAmFA,MAAM,uBAAuB;;;;;;;AAQ7B,MAAa,uBAAuB;CAAC;CAAU;CAAQ;AAAO;;;;;;;;;;;;;;AAyG9D,SAAgB,2BAA2B,OAA2C;CACpF,MAAM,QAAmC,CAAC;CAC1C,IAAI,MAAM,SAAS,KAAA,GACjB,MAAM,OAAO,MAAM;CAErB,IAAI,MAAM,cAAc,KAAA,GACtB,MAAM,kBAAkB;EAAC,MAAM,UAAU;EAAI,MAAM,UAAU;EAAI,MAAM,UAAU;EAAI,MAAM,UAAU;CAAE;CAEzG,IAAI,MAAM,qBAAqB,KAAA,GAC7B,MAAM,mBAAmB,MAAM;CAEjC,IAAI,MAAM,aAAa,KAAA,GACrB,MAAM,iBAAiB,MAAM;CAE/B,IAAI,MAAM,cAAc,KAAA,GACtB,MAAM,kBAAkB,MAAM;CAEhC,IAAI,MAAM,6BAA6B,KAAA,GACrC,MAAM,aAAa,MAAM;CAE3B,IAAI,MAAM,kBAAkB,KAAA,GAC1B,MAAM,gBAAgB,MAAM;CAE9B,IAAI,MAAM,gBAAgB,KAAA,GACxB,MAAM,qBAAqB,MAAM;CAEnC,IAAI,MAAM,oBAAoB,KAAA,GAC5B,MAAM,kBAAkB,MAAM;CAEhC,IAAI,MAAM,qBAAqB,KAAA,GAC7B,MAAM,mBAAmB,MAAM;CAEjC,IAAI,MAAM,sBAAsB,KAAA,GAC9B,MAAM,oBAAoB,MAAM;CAElC,IAAI,MAAM,UAAU,KAAA,GAClB,MAAM,QAAQ,MAAM;CAEtB,IAAI,MAAM,gBAAgB,KAAA,GACxB,MAAM,cAAc,MAAM;CAE5B,IAAI,MAAM,yBAAyB,KAAA,GACjC,MAAM,uBAAuB,MAAM;CAErC,IAAI,MAAM,cA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AAM;EAAQ;EACjC,MAAM;CACR,CAAC;CAEH,KAAK,IAAI,OAAO;AAClB;;;;;;;;;AAUA,SAAS,kBAAkB,QAAgB,SAAiB,MAA+B;CACzF,IAAI,CAAC,qBAAqB,SAAS,IAAI,GACrC,MAAM,IAAI,YAAY,cAAc,sBAAsB,GAAG,OAAO,GAAG,QAAQ,qBAAqB,KAAK,IAAI;EAC3G,SAAS;GAAE;GAAQ,MAAM;GAAS;EAAK;EACvC,MAAM,gCAAgC,qBAAqB,KAAK,IAAI,EAAE;CACxE,CAAC;AAEL"}
|
|
1
|
+
{"version":3,"file":"material-plugin-BOCB7Stt.js","names":[],"sources":["../src/lite/material.ts","../src/render/material-plugin.ts"],"sourcesContent":["import {\n createPbrMaterial,\n createStandardMaterial,\n enableMaterialTracking,\n markMaterialUboDirty,\n rebuildMaterial,\n setPbrAlphaCutoff,\n setPbrEmissive,\n setPbrUnlit,\n setStandardBumpTexture,\n setStandardEmissiveTexture,\n setStandardOpacityTexture,\n setStandardSpecularTexture,\n} from \"@babylonjs/lite\";\nimport { assertNever } from \"../errors/ignifx-error.js\";\nimport type { Material, PbrMaterialProps, SceneContext, StandardMaterialProps, Texture2D } from \"@babylonjs/lite\";\n\n/**\n * Material half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §2.6): the three\n * material kinds a `MaterialAsset` can produce, built from plain ignifx props.\n *\n * Everything here is `@internal`, and every colour that reaches it is **linear** — the sRGB decode\n * belongs to the asset layer.\n *\n * ## What a Lite material is (verified against `@babylonjs/lite@1.27.0`)\n *\n * - A material is plain data plus one private `_buildGroup` function; `createPbrMaterial` is\n * literally `{ ...props, _buildGroup, _uboVersion: 0 }` (`lib/material/pbr/pbr-material.js`), so\n * none of these factories touches the GPU and all of them run under the null engine.\n * - **The build group is a per-family singleton.** `getPbrGroupBuilder()`, `getStandardGroupBuilder()`\n * and `getShaderGroupBuilder()` each memoise one function for the whole process\n * (`lib/material/pbr/pbr-material.js`, `lib/material/standard/create-standard-material.js`,\n * `lib/material/shader/shader-material.js` line 123), and a scene keys its renderable groups by\n * that function (`lib/scene/scene-core.js`, `addToScene`). \"Material family\" in\n * `docs/architecture/07-rendering.md` §1.1 therefore means *pbr*, *standard*, *shader* or *node* —\n * **not** an individual material. Only node materials get a per-material builder\n * (`lib/material/node/node-material.js`). This is what makes {@link warmUpMaterialFamilies} in\n * `./gpu/warm-up.ts` cheap: one hidden mesh per family covers every material in it.\n * - Scalar and vector edits only need `markMaterialUboDirty` (`index.d.ts` 6974), which bumps\n * `_uboVersion`. Anything that changes the compiled feature set — binding or clearing a texture,\n * flipping `doubleSided`, changing culling — needs {@link rebuildMaterialPipelines}.\n *\n * ## The custom WGSL family lives elsewhere\n *\n * `createShaderMaterial` and the `setShader*` setters are in `./gpu/shader-material.ts`, not here:\n * this module is statically reachable from every app through the material asset layer, and Babylon\n * Lite exports one barrel, so a static import of the shader factory would put Lite's whole\n * shader-material pipeline in every entry chunk. That module is reached through a dynamic\n * `import()` instead (`docs/plan/2026-09-terrain-particles-shaders.md` §3.1, \"Bundle cost\").\n */\n\n/**\n * The Babylon Lite material a `MaterialAsset` owns, re-exported under an ignifx name\n * (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteMaterial = Material;\n\n/**\n * A Babylon Lite physically based material, re-exported under an ignifx name.\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LitePbrMaterial = PbrMaterialProps;\n\n/**\n * A Babylon Lite Babylon-Standard material, re-exported under an ignifx name.\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteStandardMaterial = StandardMaterialProps;\n\n/** glTF's default alpha cutoff, used when a `\"mask\"` material declares none. */\nconst DEFAULT_ALPHA_CUTOFF = 0.5;\n\n/**\n * How a material's alpha channel is interpreted, in glTF's vocabulary, in the order the inspector\n * lists them (`docs/architecture/07-rendering.md` §2.4).\n *\n * @public\n */\nexport const MATERIAL_ALPHA_MODES = [\"opaque\", \"mask\", \"blend\"] as const;\n\n/**\n * The union of the alpha modes a material can declare.\n *\n * @public\n */\nexport type MaterialAlphaMode = (typeof MATERIAL_ALPHA_MODES)[number];\n\n/**\n * The physically based material properties an ignifx `.material.json` declares\n * (`docs/architecture/06-serialization-and-scene-format.md` §6). Every field is optional; an\n * omitted field leaves Lite's own default in place.\n *\n * @internal\n */\nexport interface PbrMaterialInput {\n /** A human-readable name, used for glTF material overrides and diagnostics. */\n readonly name?: string;\n /** Linear base colour and alpha, multiplied with the base colour texture. */\n readonly baseColor?: readonly [number, number, number, number];\n /** The base colour texture. Load it with an sRGB format. */\n readonly baseColorTexture?: Texture2D;\n /** Metallic factor, 0 to 1. */\n readonly metallic?: number;\n /** Roughness factor, 0 to 1. */\n readonly roughness?: number;\n /** The packed occlusion/roughness/metallic texture (glTF `ORM`). */\n readonly metallicRoughnessTexture?: Texture2D;\n /** The tangent-space normal map. */\n readonly normalTexture?: Texture2D;\n /** Normal map strength. */\n readonly normalScale?: number;\n /** Linear emissive colour. */\n readonly emissive?: readonly [number, number, number];\n /** The emissive texture. */\n readonly emissiveTexture?: Texture2D;\n /** A separate occlusion texture, sampled on UV1 when the ORM texture is not used for it. */\n readonly occlusionTexture?: Texture2D;\n /** How strongly ambient occlusion darkens the surface, 0 to 1. */\n readonly occlusionStrength?: number;\n /** How the alpha channel is interpreted. */\n readonly alphaMode?: MaterialAlphaMode;\n /** The cutoff below which a `\"mask\"` material discards a fragment. */\n readonly alphaCutoff?: number;\n /** Overall material alpha, 0 to 1. */\n readonly alpha?: number;\n /** Whether back faces are drawn. */\n readonly doubleSided?: boolean;\n /** Whether lighting is skipped entirely. */\n readonly unlit?: boolean;\n /** How strongly the environment map contributes. */\n readonly environmentIntensity?: number;\n}\n\n/**\n * The Babylon-Standard material properties an ignifx `.material.json` declares, for the cheap\n * non-PBR path (`docs/architecture/07-rendering.md` §2.6).\n *\n * @internal\n */\nexport interface StandardMaterialInput {\n /** A human-readable name. */\n readonly name?: string;\n /** Linear diffuse colour. */\n readonly diffuse?: readonly [number, number, number];\n /** The diffuse texture. */\n readonly diffuseTexture?: Texture2D;\n /** Linear specular colour. */\n readonly specular?: readonly [number, number, number];\n /** Specular exponent; higher values give a tighter highlight. */\n readonly specularPower?: number;\n /** The specular texture. */\n readonly specularTexture?: Texture2D;\n /** Linear emissive colour. */\n readonly emissive?: readonly [number, number, number];\n /** The emissive texture. */\n readonly emissiveTexture?: Texture2D;\n /** The tangent-space normal map. */\n readonly normalTexture?: Texture2D;\n /** The opacity texture. */\n readonly opacityTexture?: Texture2D;\n /** Overall material alpha, 0 to 1. */\n readonly alpha?: number;\n /** The cutoff below which a fragment is discarded. `0` disables the alpha test. */\n readonly alphaCutoff?: number;\n /** Whether back faces are drawn. */\n readonly doubleSided?: boolean;\n /** Whether lighting is skipped entirely. */\n readonly unlit?: boolean;\n}\n\n/**\n * Builds a Lite PBR material from ignifx props.\n *\n * @param input - The declared properties.\n * @returns The material. It holds no GPU resource of its own; the textures it references do.\n *\n * @example\n * ```ts\n * const gold = createPbrMaterialFromProps({ baseColor: [1, 0.77, 0.34, 1], metallic: 1, roughness: 0.25 });\n * ```\n *\n * @internal\n */\nexport function createPbrMaterialFromProps(input: PbrMaterialInput): PbrMaterialProps {\n const props: Partial<PbrMaterialProps> = {};\n if (input.name !== undefined) {\n props.name = input.name;\n }\n if (input.baseColor !== undefined) {\n props.baseColorFactor = [input.baseColor[0], input.baseColor[1], input.baseColor[2], input.baseColor[3]];\n }\n if (input.baseColorTexture !== undefined) {\n props.baseColorTexture = input.baseColorTexture;\n }\n if (input.metallic !== undefined) {\n props.metallicFactor = input.metallic;\n }\n if (input.roughness !== undefined) {\n props.roughnessFactor = input.roughness;\n }\n if (input.metallicRoughnessTexture !== undefined) {\n props.ormTexture = input.metallicRoughnessTexture;\n }\n if (input.normalTexture !== undefined) {\n props.normalTexture = input.normalTexture;\n }\n if (input.normalScale !== undefined) {\n props.normalTextureScale = input.normalScale;\n }\n if (input.emissiveTexture !== undefined) {\n props.emissiveTexture = input.emissiveTexture;\n }\n if (input.occlusionTexture !== undefined) {\n props.occlusionTexture = input.occlusionTexture;\n }\n if (input.occlusionStrength !== undefined) {\n props.occlusionStrength = input.occlusionStrength;\n }\n if (input.alpha !== undefined) {\n props.alpha = input.alpha;\n }\n if (input.doubleSided !== undefined) {\n props.doubleSided = input.doubleSided;\n }\n if (input.environmentIntensity !== undefined) {\n props.environmentIntensity = input.environmentIntensity;\n }\n if (input.alphaMode === \"blend\") {\n props.alphaBlend = true;\n }\n const material = createPbrMaterial(props);\n if (input.alphaMode === \"mask\") {\n setPbrAlphaCutoff(material, input.alphaCutoff ?? DEFAULT_ALPHA_CUTOFF);\n }\n if (input.emissive !== undefined) {\n setPbrEmissive(material, [input.emissive[0], input.emissive[1], input.emissive[2]]);\n }\n if (input.unlit === true) {\n setPbrUnlit(material);\n }\n return material;\n}\n\n/**\n * Builds a Lite Standard material from ignifx props.\n *\n * @param input - The declared properties.\n * @returns The material.\n *\n * @internal\n */\nexport function createStandardMaterialFromProps(input: StandardMaterialInput): StandardMaterialProps {\n const material = createStandardMaterial();\n if (input.name !== undefined) {\n material.name = input.name;\n }\n if (input.diffuse !== undefined) {\n writeTriple(material.diffuseColor, input.diffuse);\n }\n if (input.specular !== undefined) {\n writeTriple(material.specularColor, input.specular);\n }\n if (input.emissive !== undefined) {\n writeTriple(material.emissiveColor, input.emissive);\n }\n if (input.specularPower !== undefined) {\n material.specularPower = input.specularPower;\n }\n if (input.alpha !== undefined) {\n material.alpha = input.alpha;\n }\n if (input.alphaCutoff !== undefined) {\n material.alphaCutOff = input.alphaCutoff;\n }\n if (input.doubleSided !== undefined) {\n material.backFaceCulling = !input.doubleSided;\n }\n if (input.unlit !== undefined) {\n material.disableLighting = input.unlit;\n }\n if (input.diffuseTexture !== undefined) {\n material.diffuseTexture = input.diffuseTexture;\n }\n if (input.specularTexture !== undefined) {\n setStandardSpecularTexture(material, input.specularTexture);\n }\n if (input.emissiveTexture !== undefined) {\n setStandardEmissiveTexture(material, input.emissiveTexture);\n }\n if (input.normalTexture !== undefined) {\n setStandardBumpTexture(material, input.normalTexture);\n }\n if (input.opacityTexture !== undefined) {\n setStandardOpacityTexture(material, input.opacityTexture);\n }\n return material;\n}\n\n/**\n * The material a `MeshRenderer` uses when it declares none: a neutral, fully rough dielectric.\n *\n * @returns A fresh material. Callers share one instance per app rather than one per renderer.\n *\n * @internal\n */\nexport function createDefaultMaterial(): PbrMaterialProps {\n return createPbrMaterialFromProps({\n name: \"ignifx:default\",\n baseColor: [1, 1, 1, 1],\n metallic: 0,\n roughness: 0.9,\n });\n}\n\n/**\n * Replaces a PBR material's linear base colour.\n *\n * @param material - The material to change.\n * @param r - The linear red component.\n * @param g - The linear green component.\n * @param b - The linear blue component.\n * @param a - The alpha component.\n *\n * @internal\n */\nexport function setPbrBaseColor(material: PbrMaterialProps, r: number, g: number, b: number, a: number): void {\n const factor = material.baseColorFactor;\n if (factor === undefined) {\n material.baseColorFactor = [r, g, b, a];\n } else {\n factor[0] = r;\n factor[1] = g;\n factor[2] = b;\n factor[3] = a;\n }\n markMaterialDirty(material);\n}\n\n/**\n * Replaces a PBR material's metallic and roughness factors.\n *\n * @param material - The material to change.\n * @param metallic - The metallic factor, 0 to 1.\n * @param roughness - The roughness factor, 0 to 1.\n *\n * @internal\n */\nexport function setPbrMetallicRoughness(material: PbrMaterialProps, metallic: number, roughness: number): void {\n material.metallicFactor = metallic;\n material.roughnessFactor = roughness;\n markMaterialDirty(material);\n}\n\n/**\n * Replaces a material's overall alpha.\n *\n * @param material - The PBR or Standard material to change.\n * @param alpha - The new alpha, 0 to 1.\n *\n * @internal\n */\nexport function setMaterialAlpha(material: PbrMaterialProps | StandardMaterialProps, alpha: number): void {\n material.alpha = alpha;\n markMaterialDirty(material);\n}\n\n/**\n * Marks a material's uniform block for re-upload on the next frame.\n *\n * @remarks\n * This is the cheap path and covers every scalar, vector, and colour edit. It does **not** cover\n * changes that alter the compiled feature set; those go through {@link rebuildMaterialPipelines}.\n *\n * @param material - The material that changed.\n *\n * @internal\n */\nexport function markMaterialDirty(material: Material): void {\n markMaterialUboDirty(material);\n}\n\n/**\n * Rebuilds the renderables of a material whose compiled feature set changed.\n *\n * @remarks\n * Needed after binding or clearing a texture, changing culling, or toggling a sub-feature\n * (`index.d.ts` 11133). `rebuildFrameGraph` is left off so a component can batch several material\n * edits and rebuild the frame graph once.\n *\n * @param scene - The scene the material renders in.\n * @param material - The material that changed.\n *\n * @internal\n */\nexport function rebuildMaterialPipelines(scene: SceneContext, material: Material): void {\n // Since 1.34 a PBR rebuild in a built scene finishes asynchronously, and Lite reports its failure\n // itself (`lib/material/material-rebuild.js`, `rebuildMaterial`), so nothing is left to await.\n void rebuildMaterial(scene, material);\n}\n\n/**\n * Installs automatic dirty tracking on a material, so property writes mark its uniform block\n * without an explicit {@link markMaterialDirty}.\n *\n * @remarks\n * Lite installs the tracker by rewriting the material's property descriptors, and the module that\n * does it is loaded lazily, so this is asynchronous (`index.d.ts` 4480,\n * `lib/material/observable-material.js`). Opt-in only: it costs an accessor call per write, which\n * the zero-allocation rules (coding standards §7) do not want on every material.\n *\n * @param material - The PBR or Standard material to track.\n * @returns A promise that resolves once the tracker is installed.\n *\n * @internal\n */\nexport function enableMaterialChangeTracking(material: PbrMaterialProps | StandardMaterialProps): Promise<void> {\n return enableMaterialTracking(material);\n}\n\n/**\n * Reports whether Lite will alpha-blend a material declared with this alpha mode.\n *\n * @param mode - The declared alpha mode.\n * @returns `true` for `\"blend\"`, `false` for `\"opaque\"` and `\"mask\"`.\n *\n * @internal\n */\nexport function isBlendedAlphaMode(mode: MaterialAlphaMode): boolean {\n switch (mode) {\n case \"opaque\":\n case \"mask\":\n return false;\n case \"blend\":\n return true;\n default:\n return assertNever(mode, \"material alpha mode\");\n }\n}\n\n/**\n * Writes three components into a Lite colour tuple in place.\n *\n * @param target - The tuple Lite owns.\n * @param source - The values to copy.\n */\nfunction writeTriple(target: [number, number, number], source: readonly [number, number, number]): void {\n target[0] = source[0];\n target[1] = source[1];\n target[2] = source[2];\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { assertNever, IgnifxError } from \"../errors/ignifx-error.js\";\nimport { SHADER_UNIFORM_TYPES } from \"./shader-declaration.js\";\nimport type { ShaderTextureDeclaration, ShaderUniformDeclaration, ShaderUniformType } from \"./shader-declaration.js\";\n\n/**\n * The raw Babylon Lite material-plugin points, as a `@beta` escape hatch\n * (`docs/plan/2026-09-terrain-particles-shaders.md` §3.2, ADR-0024).\n *\n * `@beta` because the meaning of each point is whatever the surrounding Lite template declares at\n * that line; ignifx's stable contract is the three hooks of `./surface-shader.ts`. Four rules read\n * out of `@babylonjs/lite@1.27.0`'s `lib/` on 2026-09-08:\n *\n * - Plugin uniforms and samplers are **fragment-stage only** on both families\n * (`lib/material/plugin/plugin-bridge-shared.js` 99), and there is no vertex helper-function\n * channel, so vertex code may read only attributes, `mesh.world` and the scene block, and must be\n * statements rather than functions.\n * - `CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION` is injected **twice** — Lite maps it to the two\n * adjacent PBR slots `AI` and `NI` — so its code must be idempotent or guard itself with a flag\n * set at an earlier point, and must declare nothing at statement level.\n * - Only PBR carries `CUSTOM_FRAGMENT_UPDATE_DIFFUSE` after `CUSTOM_FRAGMENT_UPDATE_ALPHA`;\n * Standard's template orders them the other way and has no `AI`/`NI`/`MF` slots.\n * - `roughness` and `metallic` are `let` in the PBR template and cannot be written.\n */\n\n/**\n * The Babylon Lite injection points a {@link MaterialPluginDefinition} may fill in.\n *\n * @remarks\n * The names are Lite's own (`MaterialPluginPoint`, `index.d.ts` 7084) and are taught verbatim,\n * because a plugin's code is written against the template around the point.\n *\n * @beta\n */\nexport const LITE_MATERIAL_PLUGIN_POINTS = [\n \"CUSTOM_FRAGMENT_DEFINITIONS\",\n \"CUSTOM_FRAGMENT_MAIN_BEGIN\",\n \"CUSTOM_FRAGMENT_UPDATE_ALPHA\",\n \"CUSTOM_FRAGMENT_UPDATE_DIFFUSE\",\n \"CUSTOM_FRAGMENT_BEFORE_LIGHTS\",\n \"CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION\",\n \"CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\",\n \"CUSTOM_VERTEX_MAIN_BEGIN\",\n \"CUSTOM_VERTEX_UPDATE_WORLDPOS\",\n \"CUSTOM_VERTEX_MAIN_END\",\n] as const;\n\n/**\n * One of Babylon Lite's ten material-plugin injection points.\n *\n * @beta\n */\nexport type LiteMaterialPluginPoint = (typeof LITE_MATERIAL_PLUGIN_POINTS)[number];\n\n/**\n * The default priority Babylon Lite gives a plugin with none (`index.d.ts` 7057).\n *\n * @beta\n */\nexport const MATERIAL_PLUGIN_DEFAULT_PRIORITY = 500;\n\n/**\n * How many `texture`/`sampler` pairs one material's plugins may declare together.\n *\n * @remarks\n * Measured on a device on 2026-09-08 (spike S0.2): a fully textured PBR material — base colour,\n * normal, ORM, emissive — with image-based lighting and one PCF shadow light already binds seven\n * textures and seven samplers of the sixteen per stage that every WebGPU implementation guarantees,\n * SwiftShader included, and Lite requests no higher `requiredLimits`. Nine is what is left, and it\n * drops to eight with a second shadow light and seven with a lightmap, so a material that means to\n * be portable should stay well under the cap.\n *\n * @beta\n */\nexport const MATERIAL_PLUGIN_SAMPLER_BUDGET = 9;\n\n/**\n * The WGSL names the PBR and Standard templates already own, which a plugin may not reuse for a\n * uniform field or a sampler.\n *\n * @remarks\n * A plugin's fields land in the host's own uniform block and its samplers in the host's own bind\n * group, so a collision is a duplicate WGSL declaration and the whole material stops compiling with\n * a message that names neither the plugin nor the field. Refusing at attach time is the difference\n * between a sentence and a shader dump. Read from `pbr-template.js` `_baseMaterialUboFields` and\n * `_baseBindings`, and `standard-template.js` `materialStruct` and `_baseBindings`.\n *\n * @beta\n */\nexport const MATERIAL_PLUGIN_RESERVED_NAMES: readonly string[] = Object.freeze([\n // Blocks and entry points the templates declare.\n \"material\",\n \"mesh\",\n \"scene\",\n \"lights\",\n \"pluginUbo\",\n \"shadowParams\",\n \"main\",\n // PBR material uniform fields.\n \"environmentIntensity\",\n \"directIntensity\",\n \"reflectance\",\n \"materialAlpha\",\n \"baseColorFactor\",\n \"metallicFactor\",\n \"roughnessFactor\",\n \"normalScale\",\n \"lightFalloffMode\",\n \"anisotropyParams\",\n // PBR samplers.\n \"baseColorTexture\",\n \"baseColorSampler\",\n \"normalTexture\",\n \"normalSampler_\",\n \"ormTexture\",\n \"ormSampler\",\n \"emissiveTexture\",\n \"emissiveSampler\",\n \"specGlossTexture\",\n \"specGlossSampler\",\n // Standard samplers (`standard-template.js` uses two-letter names).\n \"dT\",\n \"dS\",\n \"mat\",\n \"up\",\n]);\n\n/**\n * What a raw material plugin declares: a name, the values and textures it wants beside the host\n * material's own, and the WGSL it injects.\n *\n * @beta\n */\nexport interface MaterialPluginDefinition {\n /** The plugin's identity. It is part of Lite's pipeline cache key, so it must be stable. */\n readonly name: string;\n /** Lower runs first; Lite's own default is {@link MATERIAL_PLUGIN_DEFAULT_PRIORITY}. */\n readonly priority: number;\n /** The uniform fields appended to the host material's uniform block. Fragment stage only. */\n readonly uniforms: readonly ShaderUniformDeclaration[];\n /** The `texture`/`sampler` pairs added to the host material's bind group. Fragment stage only. */\n readonly textures: readonly ShaderTextureDeclaration[];\n /** The WGSL to inject, by point. Vertex points take statements; there are no vertex helpers. */\n readonly code: Readonly<Partial<Record<LiteMaterialPluginPoint, string>>>;\n}\n\n/**\n * The properties {@link defineMaterialPlugin} accepts; everything but `name` and `code` has a\n * default.\n *\n * @beta\n */\nexport interface MaterialPluginDefinitionInit {\n /** The plugin's identity. */\n readonly name: string;\n /** Lower runs first. Defaults to {@link MATERIAL_PLUGIN_DEFAULT_PRIORITY}. */\n readonly priority?: number;\n /** The uniform fields. Defaults to none. */\n readonly uniforms?: readonly ShaderUniformDeclaration[];\n /** The samplers. Defaults to none. */\n readonly textures?: readonly ShaderTextureDeclaration[];\n /** The WGSL to inject, by point. */\n readonly code: Readonly<Partial<Record<LiteMaterialPluginPoint, string>>>;\n}\n\n/** Matches a WGSL identifier. */\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Matches a legal plugin name: an identifier, optionally with `.`, `:`, or `-` inside it. */\nconst PLUGIN_NAME = /^[A-Za-z_][A-Za-z0-9_]*(?:[.:-][A-Za-z0-9_]+)*$/;\n\n/**\n * Validates a raw material-plugin declaration and fills in its defaults.\n *\n * @remarks\n * Nothing here reaches a device: the result is plain data that `attachSurfaceShaders` and\n * `attachMaterialPlugin` turn into a Lite plugin. The checks are the ones whose failure would\n * otherwise surface as a WGSL compile error with no mention of the plugin — an empty `code`, a\n * duplicate or reserved binding name, a name that is not a WGSL identifier, an unknown injection\n * point, or more samplers than {@link MATERIAL_PLUGIN_SAMPLER_BUDGET}.\n *\n * The **surface-shader compiler produces one of these**, so a bug in this validation is a bug in\n * every surface shader too, which is why it lives here rather than inside the compiler.\n *\n * @param definition - The declaration.\n * @returns The same declaration with `priority`, `uniforms`, and `textures` filled in.\n * @throws IgnifxError with code `IGX-0723` when `code` fills in no point, `IGX-0712` when a name is\n * not a legal, unique, unreserved WGSL identifier or a point name is unknown, or `IGX-0726` when the\n * plugin alone exceeds the sampler budget.\n *\n * @example\n * ```ts\n * const tint = defineMaterialPlugin({\n * name: \"tint\",\n * code: { CUSTOM_FRAGMENT_UPDATE_ALPHA: \"baseColor = baseColor * vec3<f32>(1.0, 0.5, 0.5);\" },\n * });\n * ```\n *\n * @beta\n */\nexport function defineMaterialPlugin(definition: MaterialPluginDefinitionInit): MaterialPluginDefinition {\n const name = definition.name;\n if (!PLUGIN_NAME.test(name)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${JSON.stringify(name)} is not a legal material-plugin name.`,\n {\n context: { plugin: name, name },\n hint: \"Start with a letter or underscore; letters, digits, underscores, and inner . : - follow.\",\n },\n );\n }\n const points = Object.keys(definition.code);\n let filled = 0;\n for (const point of points) {\n if (!isLiteMaterialPluginPoint(point)) {\n throw new IgnifxError(CoreErrorCode.unknownShaderBinding, `${name} declares no Lite point named ${point}.`, {\n context: { plugin: name, name: point, point },\n hint: `The ten points are ${LITE_MATERIAL_PLUGIN_POINTS.join(\", \")}.`,\n });\n }\n if ((definition.code[point] ?? \"\").trim().length > 0) {\n filled += 1;\n }\n }\n if (filled === 0) {\n throw new IgnifxError(CoreErrorCode.surfaceHookMissing, `${name} injects no WGSL at any Lite point.`, {\n context: { plugin: name, name },\n hint: \"Fill in at least one of the ten points, or do not attach the plugin.\",\n });\n }\n const uniforms = definition.uniforms ?? [];\n const textures = definition.textures ?? [];\n const seen = new Set<string>();\n for (const uniform of uniforms) {\n assertBindingName(name, uniform.name, seen);\n assertUniformType(name, uniform.name, uniform.type);\n }\n for (const texture of textures) {\n assertBindingName(name, texture.name, seen);\n assertBindingName(name, `${texture.name}Sampler`, seen);\n }\n if (textures.length > MATERIAL_PLUGIN_SAMPLER_BUDGET) {\n throw new IgnifxError(\n CoreErrorCode.surfaceSamplerBudgetExceeded,\n `${name} declares ${String(textures.length)} samplers; a material's plugins may declare ${String(MATERIAL_PLUGIN_SAMPLER_BUDGET)} together.`,\n {\n context: { plugin: name, samplers: textures.length, budget: MATERIAL_PLUGIN_SAMPLER_BUDGET },\n hint: \"Pack the maps into fewer textures — an RGBA control map rather than four masks.\",\n },\n );\n }\n return {\n name,\n priority: definition.priority ?? MATERIAL_PLUGIN_DEFAULT_PRIORITY,\n uniforms,\n textures,\n code: definition.code,\n };\n}\n\n/**\n * Whether a string is one of Lite's ten injection points.\n *\n * @param value - The candidate.\n * @returns `true` when Lite accepts it.\n *\n * @beta\n */\nexport function isLiteMaterialPluginPoint(value: string): value is LiteMaterialPluginPoint {\n for (const point of LITE_MATERIAL_PLUGIN_POINTS) {\n if (point === value) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * How many floats one uniform of a declared type occupies on the CPU side.\n *\n * @param type - The declared WGSL type.\n * @returns The component count: 1, 2, 3, 4, or 16.\n *\n * @internal\n */\nexport function uniformComponentCount(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 2;\n }\n case \"vec3<f32>\": {\n return 3;\n }\n case \"vec4<f32>\": {\n return 4;\n }\n case \"mat4x4<f32>\": {\n return 16;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 1;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * Refuses a binding name that is not a unique, unreserved WGSL identifier.\n *\n * @param plugin - The plugin's name, for the message.\n * @param binding - The candidate name.\n * @param seen - The names already taken by this plugin; the accepted name is added.\n * @throws IgnifxError with code `IGX-0712`.\n */\nfunction assertBindingName(plugin: string, binding: string, seen: Set<string>): void {\n if (!IDENTIFIER.test(binding)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${plugin} declares ${JSON.stringify(binding)}, which is not a WGSL identifier.`,\n { context: { plugin, name: binding }, hint: \"Use letters, digits, and underscores, starting with a letter.\" },\n );\n }\n if (MATERIAL_PLUGIN_RESERVED_NAMES.includes(binding)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${plugin} declares ${binding}, which Babylon Lite's own PBR or Standard shader already owns.`,\n { context: { plugin, name: binding }, hint: \"Rename it; a plugin shares the host material's WGSL namespace.\" },\n );\n }\n if (seen.has(binding)) {\n throw new IgnifxError(CoreErrorCode.unknownShaderBinding, `${plugin} declares ${binding} twice.`, {\n context: { plugin, name: binding },\n hint: \"Every uniform and texture of one plugin needs its own name.\",\n });\n }\n seen.add(binding);\n}\n\n/**\n * Refuses a uniform type Lite's plugin bridge cannot carry.\n *\n * @param plugin - The plugin's name, for the message.\n * @param binding - The uniform's name.\n * @param type - The declared type.\n * @throws IgnifxError with code `IGX-0712`.\n */\nfunction assertUniformType(plugin: string, binding: string, type: ShaderUniformType): void {\n if (!SHADER_UNIFORM_TYPES.includes(type)) {\n throw new IgnifxError(CoreErrorCode.unknownShaderBinding, `${plugin}.${binding} declares the type ${type}.`, {\n context: { plugin, name: binding, type },\n hint: `The plugin uniform types are ${SHADER_UNIFORM_TYPES.join(\", \")}.`,\n });\n }\n}\n"],"mappings":";;;;;AAmFA,MAAM,uBAAuB;;;;;;;AAQ7B,MAAa,uBAAuB;CAAC;CAAU;CAAQ;AAAO;;;;;;;;;;;;;;AAyG9D,SAAgB,2BAA2B,OAA2C;CACpF,MAAM,QAAmC,CAAC;CAC1C,IAAI,MAAM,SAAS,KAAA,GACjB,MAAM,OAAO,MAAM;CAErB,IAAI,MAAM,cAAc,KAAA,GACtB,MAAM,kBAAkB;EAAC,MAAM,UAAU;EAAI,MAAM,UAAU;EAAI,MAAM,UAAU;EAAI,MAAM,UAAU;CAAE;CAEzG,IAAI,MAAM,qBAAqB,KAAA,GAC7B,MAAM,mBAAmB,MAAM;CAEjC,IAAI,MAAM,aAAa,KAAA,GACrB,MAAM,iBAAiB,MAAM;CAE/B,IAAI,MAAM,cAAc,KAAA,GACtB,MAAM,kBAAkB,MAAM;CAEhC,IAAI,MAAM,6BAA6B,KAAA,GACrC,MAAM,aAAa,MAAM;CAE3B,IAAI,MAAM,kBAAkB,KAAA,GAC1B,MAAM,gBAAgB,MAAM;CAE9B,IAAI,MAAM,gBAAgB,KAAA,GACxB,MAAM,qBAAqB,MAAM;CAEnC,IAAI,MAAM,oBAAoB,KAAA,GAC5B,MAAM,kBAAkB,MAAM;CAEhC,IAAI,MAAM,qBAAqB,KAAA,GAC7B,MAAM,mBAAmB,MAAM;CAEjC,IAAI,MAAM,sBAAsB,KAAA,GAC9B,MAAM,oBAAoB,MAAM;CAElC,IAAI,MAAM,UAAU,KAAA,GAClB,MAAM,QAAQ,MAAM;CAEtB,IAAI,MAAM,gBAAgB,KAAA,GACxB,MAAM,cAAc,MAAM;CAE5B,I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cAAc,sBAAsB,GAAG,OAAO,YAAY,QAAQ,UAAU;EAChG,SAAS;GAAE;GAAQ,MAAM;EAAQ;EACjC,MAAM;CACR,CAAC;CAEH,KAAK,IAAI,OAAO;AAClB;;;;;;;;;AAUA,SAAS,kBAAkB,QAAgB,SAAiB,MAA+B;CACzF,IAAI,CAAC,qBAAqB,SAAS,IAAI,GACrC,MAAM,IAAI,YAAY,cAAc,sBAAsB,GAAG,OAAO,GAAG,QAAQ,qBAAqB,KAAK,IAAI;EAC3G,SAAS;GAAE;GAAQ,MAAM;GAAS;EAAK;EACvC,MAAM,gCAAgC,qBAAqB,KAAK,IAAI,EAAE;CACxE,CAAC;AAEL"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { t as setOwnJsonProperty } from "./json-CzZZ6K4x.js";
|
|
1
2
|
//#region src/serialization/json-view.ts
|
|
2
3
|
/**
|
|
3
4
|
* Narrows a JSON value to an object. `Array.isArray` alone does not remove `JsonArray` from the
|
|
@@ -125,7 +126,7 @@ function postEffectValuesCodec() {
|
|
|
125
126
|
const json = {};
|
|
126
127
|
for (const name of Object.keys(value).toSorted()) {
|
|
127
128
|
const entry = value[name];
|
|
128
|
-
json
|
|
129
|
+
setOwnJsonProperty(json, name, typeof entry === "number" ? entry : [...entry ?? []]);
|
|
129
130
|
}
|
|
130
131
|
return json;
|
|
131
132
|
},
|
|
@@ -135,8 +136,8 @@ function postEffectValuesCodec() {
|
|
|
135
136
|
if (object === null) return value;
|
|
136
137
|
for (const name of Object.keys(object)) {
|
|
137
138
|
const entry = object[name];
|
|
138
|
-
if (typeof entry === "number") value
|
|
139
|
-
else if (Array.isArray(entry)) value
|
|
139
|
+
if (typeof entry === "number") setOwnJsonProperty(value, name, entry);
|
|
140
|
+
else if (Array.isArray(entry)) setOwnJsonProperty(value, name, entry.map((component) => typeof component === "number" ? component : 0));
|
|
140
141
|
}
|
|
141
142
|
return value;
|
|
142
143
|
},
|
|
@@ -152,4 +153,4 @@ function postEffectValuesCodec() {
|
|
|
152
153
|
//#endregion
|
|
153
154
|
export { postEffectValuesCodec as a, declaredTextureBinding as i, POST_EFFECT_FUNCTION as n, asJsonArray as o, customEffect as r, asJsonObject as s, POST_EFFECT_BUILTIN_UNIFORMS as t };
|
|
154
155
|
|
|
155
|
-
//# sourceMappingURL=post-effect-
|
|
156
|
+
//# sourceMappingURL=post-effect-BHl7U56q.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"post-effect-BHl7U56q.js","names":[],"sources":["../src/serialization/json-view.ts","../src/render/post-effect.ts"],"sourcesContent":["import type { JsonArray, JsonObject, JsonValue } from \"../schema/json.js\";\n\n/**\n * Narrows a JSON value to an object. `Array.isArray` alone does not remove `JsonArray` from the\n * `JsonValue` union in a way that lets the object half be indexed by an arbitrary string, so the\n * whole discrimination lives here rather than being repeated with an assertion at every call site.\n *\n * @param value - The JSON to narrow.\n * @returns The object, or `null` when the value is an array, `null`, or a primitive.\n *\n * @internal\n */\nexport function asJsonObject(value: JsonValue | undefined): JsonObject | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n // The guard above is exactly `JsonObject` — an\n // object that is neither `null` nor an array — which is what `JsonValue` leaves in the union.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as JsonObject;\n}\n\n/**\n * Narrows a JSON value to an array.\n *\n * @param value - The JSON to narrow.\n * @returns The array, or `null` when the value is not one.\n *\n * @internal\n */\nexport function asJsonArray(value: JsonValue | undefined): JsonArray | null {\n return Array.isArray(value) ? value : null;\n}\n","import { setOwnJsonProperty } from \"../schema/json.js\";\nimport { asJsonObject } from \"../serialization/json-view.js\";\nimport type { ShaderAsset } from \"./shader-asset.js\";\nimport type { ShaderTextureDeclaration, ShaderUniformType } from \"./shader-declaration.js\";\nimport type { TextureAsset } from \"./texture-asset.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\nimport type { JsonValue } from \"../schema/json.js\";\nimport type { CustomFieldCodec } from \"../schema/types.js\";\n\n/**\n * What a `PostProcessStack` needs to describe a custom `// @ignifx post` effect: its settings record,\n * the uniforms every effect gets for free, and the schema codec its `values` round-trip through\n * (`docs/plan/2026-09-terrain-particles-shaders.md` §3.3).\n *\n * `PostProcessStack` is in every game's static graph, so the WGSL generator and the uniform layout\n * live in `./post-effect-compiler.ts`, which the `.wgsl` loader pulls in only for a `post` file.\n */\n\n/**\n * The name a `// @ignifx post` file gives its fragment function.\n *\n * @public\n */\nexport const POST_EFFECT_FUNCTION = \"mainFragment\";\n\n/**\n * The uniforms every post effect's `shaderUniforms` block carries before the file's own, in this\n * order.\n *\n * @remarks\n * `screenSize` is in backing-store pixels — `canvas.width`/`canvas.height` — like everything else\n * the engine reports (`docs/architecture/07-rendering.md` §3). The three clocks are the app's, so\n * `time` freezes under `app.pause()` and `unscaledTime` does not.\n *\n * @public\n */\nexport const POST_EFFECT_BUILTIN_UNIFORMS: readonly { readonly name: string; readonly type: ShaderUniformType }[] =\n Object.freeze([\n { name: \"screenSize\", type: \"vec2<f32>\" },\n { name: \"time\", type: \"f32\" },\n { name: \"unscaledTime\", type: \"f32\" },\n { name: \"deltaTime\", type: \"f32\" },\n ]);\n\n/**\n * One custom effect on a `PostProcessStack` (`docs/architecture/07-rendering.md` §2.7).\n *\n * @public\n */\nexport interface CustomEffectSettings {\n /** The `// @ignifx post` shader; `null` records nothing. */\n shader: AssetHandle<ShaderAsset> | null;\n /** Whether the effect runs. */\n enabled: boolean;\n /** Position in the chain; lower runs first, alongside bloom's and SMAA's `order`. */\n order: number;\n /** Overrides of the file's declared uniform defaults, by declared name. */\n values: Record<string, number | readonly number[]>;\n /** Textures for the file's declared samplers, by declared name. */\n textures: Record<string, AssetHandle<TextureAsset> | null>;\n}\n\n/**\n * What {@link customEffect} accepts: a shader and whichever fields differ from the defaults.\n *\n * @public\n */\nexport interface CustomEffectInit {\n /** The `// @ignifx post` shader. */\n readonly shader: AssetHandle<ShaderAsset> | null;\n /** Whether the effect runs. Defaults to `true`. */\n readonly enabled?: boolean;\n /** Position in the chain. Defaults to `10`, which is after the built-ins' defaults. */\n readonly order?: number;\n /** Overrides of the file's declared uniform defaults. */\n readonly values?: Readonly<Record<string, number | readonly number[]>>;\n /** Textures for the file's declared samplers. */\n readonly textures?: Readonly<Record<string, AssetHandle<TextureAsset> | null>>;\n}\n\n/**\n * Fills in a custom effect's defaults, so a caller names only what it means to set.\n *\n * @param init - The shader and the fields to set.\n * @returns A complete settings record, ready to push onto `PostProcessStack.custom`.\n *\n * @example\n * ```ts\n * stack.custom.push(customEffect({ shader: vignette, order: 5, values: { amount: 0.6 } }));\n * ```\n *\n * @public\n */\nexport function customEffect(init: CustomEffectInit): CustomEffectSettings {\n return {\n shader: init.shader,\n enabled: init.enabled ?? true,\n order: init.order ?? 10,\n values: { ...init.values },\n textures: { ...init.textures },\n };\n}\n\n/**\n * The binding index of the chain's current colour.\n *\n * @internal\n */\nexport const INPUT_TEXTURE_BINDING = 1;\n\n/**\n * The binding index of the chain's current colour sampler.\n *\n * @internal\n */\nexport const INPUT_SAMPLER_BINDING = 2;\n\n/** The first binding index a declared texture takes. */\nconst FIRST_DECLARED_BINDING = 3;\n\n/**\n * The binding index of one declared texture, and of its sampler.\n *\n * @param index - The texture's index in declaration order.\n * @returns The texture's binding; the sampler is one higher.\n *\n * @internal\n */\nexport function declaredTextureBinding(index: number): number {\n return FIRST_DECLARED_BINDING + index * 2;\n}\n\n/**\n * One member of a compiled effect's uniform struct, with the byte offset the generated WGSL puts it\n * at.\n *\n * @internal\n */\nexport interface PostEffectUniformField {\n /** The WGSL member name. */\n readonly name: string;\n /** The WGSL type. */\n readonly type: ShaderUniformType;\n /** How many floats the value holds. */\n readonly components: number;\n /** Where the member starts in the uniform buffer, in bytes. */\n readonly byteOffset: number;\n}\n\n/**\n * A `// @ignifx post` file compiled into what Babylon Lite's fullscreen effect path needs.\n *\n * @internal\n */\nexport interface CompiledPostEffect {\n /** The shader's address, for diagnostics and for the chain's identity. */\n readonly address: string;\n /** The whole fragment module: the bindings, the generated structs, the file, and the entry point. */\n readonly fragmentWGSL: string;\n /** The uniform members, built-ins first, in struct order. */\n readonly uniforms: readonly PostEffectUniformField[];\n /** The members by name, for a value write. */\n readonly byName: ReadonlyMap<string, PostEffectUniformField>;\n /** How large the uniform buffer has to be. */\n readonly uniformByteLength: number;\n /** The file's declared samplers, in declaration order. */\n readonly textures: readonly ShaderTextureDeclaration[];\n}\n\n/**\n * The codec that round-trips a custom effect's `values` record through a scene file.\n *\n * @remarks\n * A schema field cannot describe these: the uniforms are declared by the `.wgsl`, so `map(f32)`\n * would drop every vector and colour uniform and `map(vec4)` would write `amount: 0.6` as four\n * floats. The codec round-trips exactly what a shader file allows — a number or an array of numbers.\n *\n * @returns The codec, for a `custom()` field.\n *\n * @internal\n */\nexport function postEffectValuesCodec(): CustomFieldCodec<Record<string, number | readonly number[]>> {\n return {\n createDefault(): Record<string, number | readonly number[]> {\n return {};\n },\n serialize(value: Record<string, number | readonly number[]>): JsonValue {\n const json: Record<string, JsonValue> = {};\n // Lexicographic, so two saves of the same state are byte-identical\n // (`docs/architecture/06-serialization-and-scene-format.md` §1).\n for (const name of Object.keys(value).toSorted()) {\n const entry = value[name];\n setOwnJsonProperty(json, name, typeof entry === \"number\" ? entry : [...(entry ?? [])]);\n }\n return json;\n },\n deserialize(json: JsonValue): Record<string, number | readonly number[]> {\n const value: Record<string, number | readonly number[]> = {};\n const object = asJsonObject(json);\n if (object === null) {\n return value;\n }\n for (const name of Object.keys(object)) {\n const entry = object[name];\n // Defined, not assigned: a `__proto__` key from a file stays a name instead of a prototype.\n if (typeof entry === \"number\") {\n setOwnJsonProperty(value, name, entry);\n } else if (Array.isArray(entry)) {\n setOwnJsonProperty(\n value,\n name,\n entry.map((component) => (typeof component === \"number\" ? component : 0)),\n );\n }\n }\n return value;\n },\n jsonSchema: {\n type: \"object\",\n additionalProperties: {\n oneOf: [{ type: \"number\" }, { type: \"array\", items: { type: \"number\" } }],\n },\n },\n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AAM,QAAQ,OAAO,KAAK,MAAM,GAAG;IACtC,MAAM,QAAQ,OAAO;IAErB,IAAI,OAAO,UAAU,UACnB,mBAAmB,OAAO,MAAM,KAAK;SAChC,IAAI,MAAM,QAAQ,KAAK,GAC5B,mBACE,OACA,MACA,MAAM,KAAK,cAAe,OAAO,cAAc,WAAW,YAAY,CAAE,CAC1E;GAEJ;GACA,OAAO;EACT;EACA,YAAY;GACV,MAAM;GACN,sBAAsB,EACpB,OAAO,CAAC,EAAE,MAAM,SAAS,GAAG;IAAE,MAAM;IAAS,OAAO,EAAE,MAAM,SAAS;GAAE,CAAC,EAC1E;EACF;CACF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as assertNever, o as CoreErrorCode, t as IgnifxError } from "./ignifx-error-
|
|
2
|
-
import { i as declaredTextureBinding, n as POST_EFFECT_FUNCTION, t as POST_EFFECT_BUILTIN_UNIFORMS } from "./post-effect-
|
|
1
|
+
import { n as assertNever, o as CoreErrorCode, t as IgnifxError } from "./ignifx-error-Dq2qJMkZ.js";
|
|
2
|
+
import { i as declaredTextureBinding, n as POST_EFFECT_FUNCTION, t as POST_EFFECT_BUILTIN_UNIFORMS } from "./post-effect-BHl7U56q.js";
|
|
3
3
|
//#region src/render/post-effect-compiler.ts
|
|
4
4
|
/**
|
|
5
5
|
* Turns a `// @ignifx post` file into the fragment module and uniform layout Babylon Lite's
|
|
@@ -308,4 +308,4 @@ function isBuiltinUniformName(name) {
|
|
|
308
308
|
//#endregion
|
|
309
309
|
export { compilePostEffect, compiledPostEffect, writePostEffectValues };
|
|
310
310
|
|
|
311
|
-
//# sourceMappingURL=post-effect-compiler-
|
|
311
|
+
//# sourceMappingURL=post-effect-compiler-Dw6zW2cG.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"post-effect-compiler-pOvXae-i.js","names":[],"sources":["../src/render/post-effect-compiler.ts"],"sourcesContent":["import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { assertNever, IgnifxError } from \"../errors/ignifx-error.js\";\nimport {\n declaredTextureBinding,\n INPUT_SAMPLER_BINDING,\n INPUT_TEXTURE_BINDING,\n POST_EFFECT_BUILTIN_UNIFORMS,\n POST_EFFECT_FUNCTION,\n} from \"./post-effect.js\";\nimport type { CompiledPostEffect, PostEffectUniformField } from \"./post-effect.js\";\nimport type { ShaderAsset } from \"./shader-asset.js\";\nimport type { ShaderUniformType } from \"./shader-declaration.js\";\n\n/**\n * Turns a `// @ignifx post` file into the fragment module and uniform layout Babylon Lite's\n * fullscreen-effect path needs (`docs/plan/2026-09-terrain-particles-shaders.md` §3.3).\n *\n * `mainFragment` is a plain function, not an entry point: Lite hard-codes the entry-point names\n * `effectFullscreenVertex` and `effectFragment` (`lib/effect/effect-renderer.js` 7, 258-260), so the\n * entry point is generated here and forwards to it. `createEffectWrapper` takes a byte length and a\n * raw writer and computes no offsets, so the struct's member offsets are worked out here from WGSL's\n * own alignment rules and kept in step with the generated struct.\n *\n * Everything in this module is device-free and deterministic, so it is asserted in Node. It is\n * reached through `./post-effect-support.ts` so a game with no custom post effect never loads it.\n */\n\n/**\n * Compiles a `// @ignifx post` file into a full fragment module and a uniform layout.\n *\n * @remarks\n * Device-free and deterministic, so the whole thing is unit-testable: the result is a WGSL string\n * and a set of byte offsets. It is memoised per shader asset by {@link compiledPostEffect}, because\n * the chain asks for it on every rebuild.\n *\n * @param shader - The loaded shader asset.\n * @returns The compiled effect.\n * @throws IgnifxError with code `IGX-0709` when the file is not a `post` one, or `IGX-0723` when it\n * declares no `mainFragment` function.\n *\n * @example\n * ```ts\n * const compiled = compilePostEffect(vignette.value);\n * compiled.byName.get(\"amount\")?.byteOffset; // 20, right after the four built-ins\n * ```\n *\n * @internal\n */\nexport function compilePostEffect(shader: ShaderAsset): CompiledPostEffect {\n if (shader.declaration.kind !== \"post\") {\n throw new IgnifxError(\n CoreErrorCode.invalidAssetFile,\n `${shader.address} declares @ignifx ${shader.declaration.kind}, not @ignifx post.`,\n {\n context: { file: shader.address, format: \"@ignifx post\", kind: shader.declaration.kind },\n hint: \"A PostProcessStack custom effect takes a .post.wgsl file whose pragma is @ignifx post.\",\n },\n );\n }\n if (!new RegExp(`\\\\bfn\\\\s+${POST_EFFECT_FUNCTION}\\\\s*\\\\(`, \"u\").test(shader.source)) {\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${shader.address} declares no ${POST_EFFECT_FUNCTION} function.`,\n {\n context: { asset: shader.address, hook: POST_EFFECT_FUNCTION },\n hint: `Add fn ${POST_EFFECT_FUNCTION}(in: PostInput) -> vec4<f32>; the @fragment entry point is generated.`,\n },\n );\n }\n const declared = shader.declaration.uniforms.filter((uniform) => !isBuiltinUniformName(uniform.name));\n const layout = layOutUniforms([\n ...POST_EFFECT_BUILTIN_UNIFORMS,\n ...declared.map((uniform) => ({ name: uniform.name, type: uniform.type })),\n ]);\n const byName = new Map<string, PostEffectUniformField>();\n for (const field of layout.fields) {\n byName.set(field.name, field);\n }\n return {\n address: shader.address,\n fragmentWGSL: buildFragmentModule(shader, layout.fields),\n uniforms: layout.fields,\n byName,\n uniformByteLength: layout.byteLength,\n textures: shader.declaration.textures,\n };\n}\n\n/** The compiled form of each shader asset, so a chain rebuild recompiles nothing. */\nlet compiled: WeakMap<ShaderAsset, CompiledPostEffect> | null = null;\n\n/**\n * The compiled form of a post-effect shader, compiled once per asset.\n *\n * @remarks\n * Keyed on the `ShaderAsset` itself, so a hot reload — which replaces the asset object — recompiles\n * for free.\n *\n * @param shader - The loaded shader asset.\n * @returns The compiled effect.\n * @throws IgnifxError as {@link compilePostEffect} documents.\n *\n * @internal\n */\nexport function compiledPostEffect(shader: ShaderAsset): CompiledPostEffect {\n const cache = (compiled ??= new WeakMap<ShaderAsset, CompiledPostEffect>());\n const hit = cache.get(shader);\n if (hit !== undefined) {\n return hit;\n }\n const built = compilePostEffect(shader);\n cache.set(shader, built);\n return built;\n}\n\n/**\n * Writes an effect's current values into the bytes its uniform buffer takes.\n *\n * @remarks\n * The built-in clocks and `screenSize` are written by the caller through the same `out` buffer, so\n * this only fills in the declared members: the declaration's default first, then the settings'\n * override. Unknown names are refused, which is what makes a typo in a `.scene.json` visible.\n *\n * @param effect - The compiled effect.\n * @param shader - The shader, for its declared defaults.\n * @param values - The overrides.\n * @param out - The uniform bytes, at least `effect.uniformByteLength` long.\n * @throws IgnifxError with code `IGX-0712` for an undeclared name, or `IGX-0713` for a wrongly\n * shaped value.\n *\n * @internal\n */\nexport function writePostEffectValues(\n effect: CompiledPostEffect,\n shader: ShaderAsset,\n values: Readonly<Record<string, number | readonly number[]>>,\n out: Float32Array,\n): void {\n for (const uniform of shader.declaration.uniforms) {\n const field = effect.byName.get(uniform.name);\n if (field === undefined) {\n continue;\n }\n writeField(field, uniform.defaultValue, effect.address, out);\n }\n // `for…in` rather than `Object.keys`: the chain calls this every frame for every recorded effect\n // and a key array per effect per frame is per-frame allocation (coding standards §7).\n for (const name in values) {\n if (!Object.hasOwn(values, name)) {\n continue;\n }\n const field = effect.byName.get(name);\n const value = values[name];\n if (value === undefined) {\n continue;\n }\n if (field === undefined || isBuiltinUniformName(name)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${effect.address} declares no uniform named ${name}.`,\n {\n context: { material: effect.address, asset: effect.address, name },\n hint: `It declares ${[...effect.byName.keys()].join(\", \")}.`,\n },\n );\n }\n writeField(field, value, effect.address, out);\n }\n}\n\n/** The result of laying out a uniform struct. */\ninterface UniformLayout {\n /** The members, in struct order. */\n readonly fields: readonly PostEffectUniformField[];\n /** The struct's size, in bytes. */\n readonly byteLength: number;\n}\n\n/**\n * Computes the byte offsets WGSL gives a struct of these members, in this order.\n *\n * @remarks\n * The rules are the WGSL specification's: a member's offset is its predecessor's end rounded up to\n * the member's alignment, and the struct's size is the last member's end rounded up to the struct's\n * alignment — the largest member alignment, and in the **uniform** address space never less than\n * 16. `vec3<f32>` is the one that catches people out: 16-aligned, 12 wide (plan §3.4).\n *\n * @param members - The members, in declaration order.\n * @returns The layout.\n */\nfunction layOutUniforms(\n members: readonly { readonly name: string; readonly type: ShaderUniformType }[],\n): UniformLayout {\n const fields: PostEffectUniformField[] = [];\n let offset = 0;\n // WGSL's uniform address space rounds a struct's alignment up to a multiple of 16, so the block's\n // size is always a multiple of 16 whatever its members are.\n let structAlignment = 16;\n for (const member of members) {\n const alignment = typeAlignment(member.type);\n const size = typeSize(member.type);\n structAlignment = Math.max(structAlignment, alignment);\n offset = roundUp(offset, alignment);\n fields.push({\n name: member.name,\n type: member.type,\n components: componentCount(member.type),\n byteOffset: offset,\n });\n offset += size;\n }\n return { fields, byteLength: roundUp(offset, structAlignment) };\n}\n\n/**\n * A WGSL type's alignment in the uniform address space, in bytes.\n *\n * @param type - The type.\n * @returns The alignment.\n */\nfunction typeAlignment(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 8;\n }\n case \"vec3<f32>\":\n case \"vec4<f32>\":\n case \"mat4x4<f32>\": {\n return 16;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 4;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * A WGSL type's size, in bytes.\n *\n * @param type - The type.\n * @returns The size.\n */\nfunction typeSize(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 8;\n }\n case \"vec3<f32>\": {\n return 12;\n }\n case \"vec4<f32>\": {\n return 16;\n }\n case \"mat4x4<f32>\": {\n return 64;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 4;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * How many floats one uniform of a declared type occupies.\n *\n * @remarks\n * A private copy of `material-plugin.ts`'s `uniformComponentCount`. `PostProcessStack` is in every\n * game's static graph, and importing it from there would drag `defineMaterialPlugin` and the\n * reserved-name table into a bundle that draws no custom shader at all.\n *\n * @param type - The declared WGSL type.\n * @returns The component count: 1, 2, 3, 4, or 16.\n */\nfunction componentCount(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 2;\n }\n case \"vec3<f32>\": {\n return 3;\n }\n case \"vec4<f32>\": {\n return 4;\n }\n case \"mat4x4<f32>\": {\n return 16;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 1;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * Rounds a value up to a multiple of an alignment.\n *\n * @param value - The value.\n * @param alignment - The alignment, a power of two.\n * @returns The rounded value.\n */\nfunction roundUp(value: number, alignment: number): number {\n return Math.ceil(value / alignment) * alignment;\n}\n\n/**\n * The whole fragment module: bindings, generated structs, the author's file, and the entry point\n * Lite's pipeline looks for.\n *\n * @param shader - The shader asset.\n * @param fields - The uniform members, in struct order.\n * @returns The WGSL.\n */\nfunction buildFragmentModule(shader: ShaderAsset, fields: readonly PostEffectUniformField[]): string {\n const members = fields.map((field) => `${field.name}:${field.type},`).join(\"\");\n const lines: string[] = [\n `struct PostUniforms{${members}}`,\n \"@group(0)@binding(0)var<uniform>shaderUniforms:PostUniforms;\",\n `@group(0)@binding(${String(INPUT_TEXTURE_BINDING)})var inputTexture:texture_2d<f32>;`,\n `@group(0)@binding(${String(INPUT_SAMPLER_BINDING)})var inputTextureSampler:sampler;`,\n ];\n // `for…of` with an index: the iterator yields the element type rather than `T | undefined`, and\n // this runs once per compiled shader rather than per frame.\n let index = -1;\n for (const declaration of shader.declaration.textures) {\n index += 1;\n const binding = declaredTextureBinding(index);\n const type = declaration.array ? \"texture_2d_array<f32>\" : \"texture_2d<f32>\";\n lines.push(\n `@group(0)@binding(${String(binding)})var ${declaration.name}:${type};`,\n `@group(0)@binding(${String(binding + 1)})var ${declaration.name}Sampler:sampler;`,\n );\n }\n lines.push(\n \"struct PostInput{uv:vec2<f32>,position:vec2<f32>,}\",\n shader.source,\n \"@fragment fn effectFragment(fragment:EffectVertexOutput)->@location(0)vec4<f32>{\",\n \"var ignifxPostInput:PostInput;\",\n // Lite's effect vertex puts uv (0, 0) at the bottom-left, but a texture's origin is the top-left,\n // so an unflipped uv mirrors the frame on every pass (`lib/effect/effect-renderer.js` 7).\n \"ignifxPostInput.uv=vec2<f32>(fragment.uv.x,1.0-fragment.uv.y);\",\n \"ignifxPostInput.position=fragment.position.xy;\",\n `return ${POST_EFFECT_FUNCTION}(ignifxPostInput);`,\n \"}\",\n );\n return lines.join(\"\\n\");\n}\n\n/**\n * Writes one member's value into the uniform bytes.\n *\n * @param field - The member.\n * @param value - The value.\n * @param asset - The shader's address, for diagnostics.\n * @param out - The uniform floats.\n * @throws IgnifxError with code `IGX-0713` when the shape does not match.\n */\nfunction writeField(\n field: PostEffectUniformField,\n value: number | readonly number[],\n asset: string,\n out: Float32Array,\n): void {\n const index = field.byteOffset / 4;\n if (typeof value === \"number\") {\n if (field.components !== 1) {\n throw mismatch(field, asset, \"a single number\");\n }\n out[index] = value;\n return;\n }\n if (value.length !== field.components) {\n throw mismatch(field, asset, `${String(value.length)} floats`);\n }\n out.set(value instanceof Float32Array ? value : Float32Array.from(value), index);\n}\n\n/**\n * The `IGX-0713` failure a wrongly shaped value produces.\n *\n * @param field - The member.\n * @param asset - The shader's address.\n * @param actual - What the caller passed.\n * @returns The error to throw.\n */\nfunction mismatch(field: PostEffectUniformField, asset: string, actual: string): IgnifxError {\n return new IgnifxError(\n CoreErrorCode.shaderValueMismatch,\n `${field.name} on ${asset} expects ${field.type} (${String(field.components)} floats), not ${actual}.`,\n {\n context: { name: field.name, material: asset, expected: field.type, actual },\n hint: \"A post effect's values are numbers and numeric arrays; a colour takes its three or four components.\",\n },\n );\n}\n\n/**\n * Whether a name is one of the four uniforms every post effect gets for free.\n *\n * @param name - The candidate.\n * @returns `true` when the engine writes it.\n */\nfunction isBuiltinUniformName(name: string): boolean {\n for (const builtin of POST_EFFECT_BUILTIN_UNIFORMS) {\n if (builtin.name === name) {\n return true;\n }\n }\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;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,OAAO,YAAY,KAAK,iBACnE;CACF;CACA,MAAM,KACJ,sDACA,OAAO,QACP,oFACA,kCAGA,kEACA,kDACA,UAAU,qBAAqB,qBAC/B,GACF;CACA,OAAO,MAAM,KAAK,IAAI;AACxB;;;;;;;;;;AAWA,SAAS,WACP,OACA,OACA,OACA,KACM;CACN,MAAM,QAAQ,MAAM,aAAa;CACjC,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,MAAM,eAAe,GACvB,MAAM,SAAS,OAAO,OAAO,iBAAiB;EAEhD,IAAI,SAAS;EACb;CACF;CACA,IAAI,MAAM,WAAW,MAAM,YACzB,MAAM,SAAS,OAAO,OAAO,GAAG,OAAO,MAAM,MAAM,EAAE,QAAQ;CAE/D,IAAI,IAAI,iBAAiB,eAAe,QAAQ,aAAa,KAAK,KAAK,GAAG,KAAK;AACjF;;;;;;;;;AAUA,SAAS,SAAS,OAA+B,OAAe,QAA6B;CAC3F,OAAO,IAAI,YACT,cAAc,qBACd,GAAG,MAAM,KAAK,MAAM,MAAM,WAAW,MAAM,KAAK,IAAI,OAAO,MAAM,UAAU,EAAE,gBAAgB,OAAO,IACpG;EACE,SAAS;GAAE,MAAM,MAAM;GAAM,UAAU;GAAO,UAAU,MAAM;GAAM;EAAO;EAC3E,MAAM;CACR,CACF;AACF;;;;;;;AAQA,SAAS,qBAAqB,MAAuB;CACnD,KAAK,MAAM,WAAW,8BACpB,IAAI,QAAQ,SAAS,MACnB,OAAO;CAGX,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"post-effect-compiler-Dw6zW2cG.js","names":[],"sources":["../src/render/post-effect-compiler.ts"],"sourcesContent":["import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { assertNever, IgnifxError } from \"../errors/ignifx-error.js\";\nimport {\n declaredTextureBinding,\n INPUT_SAMPLER_BINDING,\n INPUT_TEXTURE_BINDING,\n POST_EFFECT_BUILTIN_UNIFORMS,\n POST_EFFECT_FUNCTION,\n} from \"./post-effect.js\";\nimport type { CompiledPostEffect, PostEffectUniformField } from \"./post-effect.js\";\nimport type { ShaderAsset } from \"./shader-asset.js\";\nimport type { ShaderUniformType } from \"./shader-declaration.js\";\n\n/**\n * Turns a `// @ignifx post` file into the fragment module and uniform layout Babylon Lite's\n * fullscreen-effect path needs (`docs/plan/2026-09-terrain-particles-shaders.md` §3.3).\n *\n * `mainFragment` is a plain function, not an entry point: Lite hard-codes the entry-point names\n * `effectFullscreenVertex` and `effectFragment` (`lib/effect/effect-renderer.js` 7, 258-260), so the\n * entry point is generated here and forwards to it. `createEffectWrapper` takes a byte length and a\n * raw writer and computes no offsets, so the struct's member offsets are worked out here from WGSL's\n * own alignment rules and kept in step with the generated struct.\n *\n * Everything in this module is device-free and deterministic, so it is asserted in Node. It is\n * reached through `./post-effect-support.ts` so a game with no custom post effect never loads it.\n */\n\n/**\n * Compiles a `// @ignifx post` file into a full fragment module and a uniform layout.\n *\n * @remarks\n * Device-free and deterministic, so the whole thing is unit-testable: the result is a WGSL string\n * and a set of byte offsets. It is memoised per shader asset by {@link compiledPostEffect}, because\n * the chain asks for it on every rebuild.\n *\n * @param shader - The loaded shader asset.\n * @returns The compiled effect.\n * @throws IgnifxError with code `IGX-0709` when the file is not a `post` one, or `IGX-0723` when it\n * declares no `mainFragment` function.\n *\n * @example\n * ```ts\n * const compiled = compilePostEffect(vignette.value);\n * compiled.byName.get(\"amount\")?.byteOffset; // 20, right after the four built-ins\n * ```\n *\n * @internal\n */\nexport function compilePostEffect(shader: ShaderAsset): CompiledPostEffect {\n if (shader.declaration.kind !== \"post\") {\n throw new IgnifxError(\n CoreErrorCode.invalidAssetFile,\n `${shader.address} declares @ignifx ${shader.declaration.kind}, not @ignifx post.`,\n {\n context: { file: shader.address, format: \"@ignifx post\", kind: shader.declaration.kind },\n hint: \"A PostProcessStack custom effect takes a .post.wgsl file whose pragma is @ignifx post.\",\n },\n );\n }\n if (!new RegExp(`\\\\bfn\\\\s+${POST_EFFECT_FUNCTION}\\\\s*\\\\(`, \"u\").test(shader.source)) {\n throw new IgnifxError(\n CoreErrorCode.surfaceHookMissing,\n `${shader.address} declares no ${POST_EFFECT_FUNCTION} function.`,\n {\n context: { asset: shader.address, hook: POST_EFFECT_FUNCTION },\n hint: `Add fn ${POST_EFFECT_FUNCTION}(in: PostInput) -> vec4<f32>; the @fragment entry point is generated.`,\n },\n );\n }\n const declared = shader.declaration.uniforms.filter((uniform) => !isBuiltinUniformName(uniform.name));\n const layout = layOutUniforms([\n ...POST_EFFECT_BUILTIN_UNIFORMS,\n ...declared.map((uniform) => ({ name: uniform.name, type: uniform.type })),\n ]);\n const byName = new Map<string, PostEffectUniformField>();\n for (const field of layout.fields) {\n byName.set(field.name, field);\n }\n return {\n address: shader.address,\n fragmentWGSL: buildFragmentModule(shader, layout.fields),\n uniforms: layout.fields,\n byName,\n uniformByteLength: layout.byteLength,\n textures: shader.declaration.textures,\n };\n}\n\n/** The compiled form of each shader asset, so a chain rebuild recompiles nothing. */\nlet compiled: WeakMap<ShaderAsset, CompiledPostEffect> | null = null;\n\n/**\n * The compiled form of a post-effect shader, compiled once per asset.\n *\n * @remarks\n * Keyed on the `ShaderAsset` itself, so a hot reload — which replaces the asset object — recompiles\n * for free.\n *\n * @param shader - The loaded shader asset.\n * @returns The compiled effect.\n * @throws IgnifxError as {@link compilePostEffect} documents.\n *\n * @internal\n */\nexport function compiledPostEffect(shader: ShaderAsset): CompiledPostEffect {\n const cache = (compiled ??= new WeakMap<ShaderAsset, CompiledPostEffect>());\n const hit = cache.get(shader);\n if (hit !== undefined) {\n return hit;\n }\n const built = compilePostEffect(shader);\n cache.set(shader, built);\n return built;\n}\n\n/**\n * Writes an effect's current values into the bytes its uniform buffer takes.\n *\n * @remarks\n * The built-in clocks and `screenSize` are written by the caller through the same `out` buffer, so\n * this only fills in the declared members: the declaration's default first, then the settings'\n * override. Unknown names are refused, which is what makes a typo in a `.scene.json` visible.\n *\n * @param effect - The compiled effect.\n * @param shader - The shader, for its declared defaults.\n * @param values - The overrides.\n * @param out - The uniform bytes, at least `effect.uniformByteLength` long.\n * @throws IgnifxError with code `IGX-0712` for an undeclared name, or `IGX-0713` for a wrongly\n * shaped value.\n *\n * @internal\n */\nexport function writePostEffectValues(\n effect: CompiledPostEffect,\n shader: ShaderAsset,\n values: Readonly<Record<string, number | readonly number[]>>,\n out: Float32Array,\n): void {\n for (const uniform of shader.declaration.uniforms) {\n const field = effect.byName.get(uniform.name);\n if (field === undefined) {\n continue;\n }\n writeField(field, uniform.defaultValue, effect.address, out);\n }\n // `for…in` rather than `Object.keys`: the chain calls this every frame for every recorded effect\n // and a key array per effect per frame is per-frame allocation (coding standards §7).\n for (const name in values) {\n if (!Object.hasOwn(values, name)) {\n continue;\n }\n const field = effect.byName.get(name);\n const value = values[name];\n if (value === undefined) {\n continue;\n }\n if (field === undefined || isBuiltinUniformName(name)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${effect.address} declares no uniform named ${name}.`,\n {\n context: { material: effect.address, asset: effect.address, name },\n hint: `It declares ${[...effect.byName.keys()].join(\", \")}.`,\n },\n );\n }\n writeField(field, value, effect.address, out);\n }\n}\n\n/** The result of laying out a uniform struct. */\ninterface UniformLayout {\n /** The members, in struct order. */\n readonly fields: readonly PostEffectUniformField[];\n /** The struct's size, in bytes. */\n readonly byteLength: number;\n}\n\n/**\n * Computes the byte offsets WGSL gives a struct of these members, in this order.\n *\n * @remarks\n * The rules are the WGSL specification's: a member's offset is its predecessor's end rounded up to\n * the member's alignment, and the struct's size is the last member's end rounded up to the struct's\n * alignment — the largest member alignment, and in the **uniform** address space never less than\n * 16. `vec3<f32>` is the one that catches people out: 16-aligned, 12 wide (plan §3.4).\n *\n * @param members - The members, in declaration order.\n * @returns The layout.\n */\nfunction layOutUniforms(\n members: readonly { readonly name: string; readonly type: ShaderUniformType }[],\n): UniformLayout {\n const fields: PostEffectUniformField[] = [];\n let offset = 0;\n // WGSL's uniform address space rounds a struct's alignment up to a multiple of 16, so the block's\n // size is always a multiple of 16 whatever its members are.\n let structAlignment = 16;\n for (const member of members) {\n const alignment = typeAlignment(member.type);\n const size = typeSize(member.type);\n structAlignment = Math.max(structAlignment, alignment);\n offset = roundUp(offset, alignment);\n fields.push({\n name: member.name,\n type: member.type,\n components: componentCount(member.type),\n byteOffset: offset,\n });\n offset += size;\n }\n return { fields, byteLength: roundUp(offset, structAlignment) };\n}\n\n/**\n * A WGSL type's alignment in the uniform address space, in bytes.\n *\n * @param type - The type.\n * @returns The alignment.\n */\nfunction typeAlignment(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 8;\n }\n case \"vec3<f32>\":\n case \"vec4<f32>\":\n case \"mat4x4<f32>\": {\n return 16;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 4;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * A WGSL type's size, in bytes.\n *\n * @param type - The type.\n * @returns The size.\n */\nfunction typeSize(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 8;\n }\n case \"vec3<f32>\": {\n return 12;\n }\n case \"vec4<f32>\": {\n return 16;\n }\n case \"mat4x4<f32>\": {\n return 64;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 4;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * How many floats one uniform of a declared type occupies.\n *\n * @remarks\n * A private copy of `material-plugin.ts`'s `uniformComponentCount`. `PostProcessStack` is in every\n * game's static graph, and importing it from there would drag `defineMaterialPlugin` and the\n * reserved-name table into a bundle that draws no custom shader at all.\n *\n * @param type - The declared WGSL type.\n * @returns The component count: 1, 2, 3, 4, or 16.\n */\nfunction componentCount(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 2;\n }\n case \"vec3<f32>\": {\n return 3;\n }\n case \"vec4<f32>\": {\n return 4;\n }\n case \"mat4x4<f32>\": {\n return 16;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 1;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * Rounds a value up to a multiple of an alignment.\n *\n * @param value - The value.\n * @param alignment - The alignment, a power of two.\n * @returns The rounded value.\n */\nfunction roundUp(value: number, alignment: number): number {\n return Math.ceil(value / alignment) * alignment;\n}\n\n/**\n * The whole fragment module: bindings, generated structs, the author's file, and the entry point\n * Lite's pipeline looks for.\n *\n * @param shader - The shader asset.\n * @param fields - The uniform members, in struct order.\n * @returns The WGSL.\n */\nfunction buildFragmentModule(shader: ShaderAsset, fields: readonly PostEffectUniformField[]): string {\n const members = fields.map((field) => `${field.name}:${field.type},`).join(\"\");\n const lines: string[] = [\n `struct PostUniforms{${members}}`,\n \"@group(0)@binding(0)var<uniform>shaderUniforms:PostUniforms;\",\n `@group(0)@binding(${String(INPUT_TEXTURE_BINDING)})var inputTexture:texture_2d<f32>;`,\n `@group(0)@binding(${String(INPUT_SAMPLER_BINDING)})var inputTextureSampler:sampler;`,\n ];\n // `for…of` with an index: the iterator yields the element type rather than `T | undefined`, and\n // this runs once per compiled shader rather than per frame.\n let index = -1;\n for (const declaration of shader.declaration.textures) {\n index += 1;\n const binding = declaredTextureBinding(index);\n const type = declaration.array ? \"texture_2d_array<f32>\" : \"texture_2d<f32>\";\n lines.push(\n `@group(0)@binding(${String(binding)})var ${declaration.name}:${type};`,\n `@group(0)@binding(${String(binding + 1)})var ${declaration.name}Sampler:sampler;`,\n );\n }\n lines.push(\n \"struct PostInput{uv:vec2<f32>,position:vec2<f32>,}\",\n shader.source,\n \"@fragment fn effectFragment(fragment:EffectVertexOutput)->@location(0)vec4<f32>{\",\n \"var ignifxPostInput:PostInput;\",\n // Lite's effect vertex puts uv (0, 0) at the bottom-left, but a texture's origin is the top-left,\n // so an unflipped uv mirrors the frame on every pass (`lib/effect/effect-renderer.js` 7).\n \"ignifxPostInput.uv=vec2<f32>(fragment.uv.x,1.0-fragment.uv.y);\",\n \"ignifxPostInput.position=fragment.position.xy;\",\n `return ${POST_EFFECT_FUNCTION}(ignifxPostInput);`,\n \"}\",\n );\n return lines.join(\"\\n\");\n}\n\n/**\n * Writes one member's value into the uniform bytes.\n *\n * @param field - The member.\n * @param value - The value.\n * @param asset - The shader's address, for diagnostics.\n * @param out - The uniform floats.\n * @throws IgnifxError with code `IGX-0713` when the shape does not match.\n */\nfunction writeField(\n field: PostEffectUniformField,\n value: number | readonly number[],\n asset: string,\n out: Float32Array,\n): void {\n const index = field.byteOffset / 4;\n if (typeof value === \"number\") {\n if (field.components !== 1) {\n throw mismatch(field, asset, \"a single number\");\n }\n out[index] = value;\n return;\n }\n if (value.length !== field.components) {\n throw mismatch(field, asset, `${String(value.length)} floats`);\n }\n out.set(value instanceof Float32Array ? value : Float32Array.from(value), index);\n}\n\n/**\n * The `IGX-0713` failure a wrongly shaped value produces.\n *\n * @param field - The member.\n * @param asset - The shader's address.\n * @param actual - What the caller passed.\n * @returns The error to throw.\n */\nfunction mismatch(field: PostEffectUniformField, asset: string, actual: string): IgnifxError {\n return new IgnifxError(\n CoreErrorCode.shaderValueMismatch,\n `${field.name} on ${asset} expects ${field.type} (${String(field.components)} floats), not ${actual}.`,\n {\n context: { name: field.name, material: asset, expected: field.type, actual },\n hint: \"A post effect's values are numbers and numeric arrays; a colour takes its three or four components.\",\n },\n );\n}\n\n/**\n * Whether a name is one of the four uniforms every post effect gets for free.\n *\n * @param name - The candidate.\n * @returns `true` when the engine writes it.\n */\nfunction isBuiltinUniformName(name: string): boolean {\n for (const builtin of POST_EFFECT_BUILTIN_UNIFORMS) {\n if (builtin.name === name) {\n return true;\n }\n }\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,kBAAkB,QAAyC;CACzE,IAAI,OAAO,YAAY,SAAS,QAC9B,MAAM,IAAI,YACR,cAAc,kBACd,GAAG,OAAO,QAAQ,oBAAoB,OAAO,YAAY,KAAK,sBAC9D;EACE,SAAS;GAA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OACA,OACA,OACA,KACM;CACN,MAAM,QAAQ,MAAM,aAAa;CACjC,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,MAAM,eAAe,GACvB,MAAM,SAAS,OAAO,OAAO,iBAAiB;EAEhD,IAAI,SAAS;EACb;CACF;CACA,IAAI,MAAM,WAAW,MAAM,YACzB,MAAM,SAAS,OAAO,OAAO,GAAG,OAAO,MAAM,MAAM,EAAE,QAAQ;CAE/D,IAAI,IAAI,iBAAiB,eAAe,QAAQ,aAAa,KAAK,KAAK,GAAG,KAAK;AACjF;;;;;;;;;AAUA,SAAS,SAAS,OAA+B,OAAe,QAA6B;CAC3F,OAAO,IAAI,YACT,cAAc,qBACd,GAAG,MAAM,KAAK,MAAM,MAAM,WAAW,MAAM,KAAK,IAAI,OAAO,MAAM,UAAU,EAAE,gBAAgB,OAAO,IACpG;EACE,SAAS;GAAE,MAAM,MAAM;GAAM,UAAU;GAAO,UAAU,MAAM;GAAM;EAAO;EAC3E,MAAM;CACR,CACF;AACF;;;;;;;AAQA,SAAS,qBAAqB,MAAuB;CACnD,KAAK,MAAM,WAAW,8BACpB,IAAI,QAAQ,SAAS,MACnB,OAAO;CAGX,OAAO;AACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as readSceneEnvironment } from "./environment-
|
|
1
|
+
import { i as readSceneEnvironment } from "./environment-C9AjYJgV.js";
|
|
2
2
|
import { createShaderMaterial, createTexture2DArrayFromPixels, createTexture2DFromPixels, enableShaderMaterialUniformCaching, setShaderMatrix, setShaderStorageBuffer, setShaderTexture, setShaderUniform } from "@babylonjs/lite";
|
|
3
3
|
//#region src/lite/gpu/shader-material.ts
|
|
4
4
|
/** The RGBA bytes of each 1x1 fallback texture. */
|
|
@@ -204,4 +204,4 @@ function readSceneAmbient(scene, out) {
|
|
|
204
204
|
//#endregion
|
|
205
205
|
export { createFallbackTexture, createShaderMaterialFromOptions, enableShaderUniformCaching, readSceneAmbient, resolveFallbackTexture, writeShaderMatrix, writeShaderStorageBuffer, writeShaderTexture, writeShaderUniform };
|
|
206
206
|
|
|
207
|
-
//# sourceMappingURL=shader-material-
|
|
207
|
+
//# sourceMappingURL=shader-material-BxQn9FT4.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shader-material-B6wwFCKB.js","names":[],"sources":["../src/lite/gpu/shader-material.ts"],"sourcesContent":["import {\n createShaderMaterial,\n createTexture2DArrayFromPixels,\n createTexture2DFromPixels,\n enableShaderMaterialUniformCaching,\n setShaderMatrix,\n setShaderStorageBuffer,\n setShaderTexture,\n setShaderUniform,\n} from \"@babylonjs/lite\";\nimport { readSceneEnvironment } from \"./environment.js\";\nimport type {\n EngineContext,\n SceneContext,\n ShaderAttributeName,\n ShaderMaterial,\n ShaderSystemUniformName,\n ShaderUniformType,\n StorageBuffer,\n Texture2D,\n} from \"@babylonjs/lite\";\n\n/**\n * The custom-WGSL half of the Babylon Lite adapter: `createShaderMaterial`, the `setShader*`\n * setters, and the 1x1 fallback textures a declared sampler falls back to\n * (`docs/plan/2026-09-terrain-particles-shaders.md` §3.1, ADR-0024). Everything here is `@internal`.\n *\n * Lite exports one barrel, so a static import of `createShaderMaterial` anywhere in the reachable\n * graph pulls `lib/material/shader/**` into every entry chunk. This module is therefore reached with\n * `await import(...)` from `../../render/shader-support.ts`, and only loading a `.wgsl` triggers the\n * fetch. `./storage-buffer.ts` is a separate file for the same reason: `StorageBufferAsset`\n * allocates synchronously, so it cannot wait for this chunk.\n *\n * Two Lite facts it is written around:\n *\n * - Nothing may be left unbound: `createShaderBindGroup` throws (errors 309 and 310) when a declared\n * sampler has no texture or a declared storage buffer has no buffer, which is what\n * {@link createFallbackTexture} exists for.\n * - There is no front-face culling; `ShaderMaterialOptions` carries only `backFaceCulling`\n * (`lib/material/shader/shader-pipeline.js`), so the pragma parser refuses `cull front`.\n */\n\n/**\n * A Babylon Lite custom WGSL material, re-exported under an ignifx name\n * (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteShaderMaterial = ShaderMaterial;\n\n/** The RGBA bytes of each 1x1 fallback texture. */\nconst FALLBACK_PIXELS: Readonly<Record<string, readonly [number, number, number, number]>> = Object.freeze({\n white: [255, 255, 255, 255],\n black: [0, 0, 0, 255],\n transparent: [0, 0, 0, 0],\n});\n\n/**\n * One declared uniform in the form Babylon Lite's factory takes: either the name of a system\n * uniform it fills in itself, or a custom declaration with its initial value.\n *\n * @internal\n */\nexport type ShaderUniformEntry =\n | ShaderSystemUniformName\n | {\n /** The WGSL identifier. */\n readonly name: string;\n /** The WGSL type. */\n readonly type: ShaderUniformType;\n /** The initial value, **linear** for a colour. */\n readonly defaultValue: number | readonly number[];\n };\n\n/**\n * One declared sampler in the form Babylon Lite's factory takes.\n *\n * @internal\n */\nexport interface ShaderSamplerEntry {\n /** The WGSL identifier; Lite generates `<name>Sampler` beside it. */\n readonly name: string;\n /** `\"2d-array\"` for a `texture_2d_array<f32>` binding. */\n readonly viewDimension: \"2d\" | \"2d-array\";\n}\n\n/**\n * One declared storage buffer in the form Babylon Lite's factory takes.\n *\n * @internal\n */\nexport interface ShaderStorageEntry {\n /** The WGSL identifier. */\n readonly name: string;\n /** The WGSL variable type, verbatim. */\n readonly type: string;\n}\n\n/**\n * Everything Babylon Lite's `createShaderMaterial` needs, in ignifx's own vocabulary so that the\n * mapping from a `ShaderDeclaration` can be built and asserted without a device or a Lite import\n * (`src/render/shader-material.ts`).\n *\n * @remarks\n * A `null` blend state or depth comparison means \"leave Babylon Lite's own default in place\", so\n * this module never restates a Lite default that could change.\n *\n * @internal\n */\nexport interface ShaderMaterialBuildOptions {\n /** The material's name, used in pipeline and shader-module labels. */\n readonly name: string;\n /** The WGSL source, handed to Lite as both the vertex and the fragment source. */\n readonly source: string;\n /** The vertex attributes the vertex stage reads; `position` is mandatory. */\n readonly attributes: readonly ShaderAttributeName[];\n /** The system and custom uniforms, in binding-declaration order. */\n readonly uniforms: readonly ShaderUniformEntry[];\n /** The samplers. */\n readonly samplers: readonly ShaderSamplerEntry[];\n /** The read-only storage buffers. */\n readonly storageBuffers: readonly ShaderStorageEntry[];\n /** The WGSL `const` declarations, resolved from the file's defaults and the material's overrides. */\n readonly defines: Readonly<Record<string, boolean | number>>;\n /** Whether the thin-instance RGBA stream is bound and injected into `VertexInput`. */\n readonly useThinInstanceColors: boolean;\n /** Whether the surface is alpha-blended. */\n readonly needAlphaBlending: boolean;\n /** Which of Lite's two blend equations to use when no explicit state is given. */\n readonly blendMode: \"alpha\" | \"additive\";\n /** An explicit colour-target blend state, which replaces the derived one; `null` to derive it. */\n readonly blend: GPUBlendState | null;\n /** Whether the surface samples the opaque scene colour behind it. */\n readonly transmissive: boolean;\n /** Whether back faces are culled. */\n readonly backFaceCulling: boolean;\n /** Whether the draw writes depth. */\n readonly depthWrite: boolean;\n /** The depth comparison, or `null` for Lite's own reverse-Z default. */\n readonly depthCompare: GPUCompareFunction | null;\n}\n\n/**\n * Builds a Babylon Lite custom WGSL material.\n *\n * @remarks\n * Validation is eager and compilation is lazy, so this runs under the null engine; the pipeline is\n * compiled the first time a mesh wearing the material is drawn.\n *\n * @param options - The sources and the declared attribute, uniform, sampler, and storage layout.\n * @returns The material.\n * @throws Error from Babylon Lite when the declaration is not one it can build.\n *\n * @internal\n */\nexport function createShaderMaterialFromOptions(options: ShaderMaterialBuildOptions): ShaderMaterial {\n return createShaderMaterial({\n name: options.name,\n vertexSource: options.source,\n fragmentSource: options.source,\n attributes: options.attributes,\n uniforms: options.uniforms,\n samplers: options.samplers,\n storageBuffers: options.storageBuffers,\n defines: options.defines,\n useThinInstanceColors: options.useThinInstanceColors,\n needAlphaBlending: options.needAlphaBlending,\n blendMode: options.blendMode,\n ...(options.blend === null ? {} : { blend: options.blend }),\n transmissive: options.transmissive,\n backFaceCulling: options.backFaceCulling,\n depthWrite: options.depthWrite,\n ...(options.depthCompare === null ? {} : { depthCompare: options.depthCompare }),\n });\n}\n\n/**\n * Writes a declared scalar, vector, or matrix uniform.\n *\n * @remarks\n * Lite compares the incoming numbers with the ones it holds and bumps the material's uniform\n * version only when one changed, so calling this every frame with an unchanged value costs a few\n * comparisons and no upload (`lib/material/shader/shader-material.js`, `setUniformValue`).\n *\n * @param material - The material to write to.\n * @param name - The declared uniform name.\n * @param value - The value; its length must match the declared type.\n * @throws Error from Babylon Lite when the name is not declared or the length is wrong.\n *\n * @internal\n */\nexport function writeShaderUniform(\n material: ShaderMaterial,\n name: string,\n value: number | readonly number[] | Float32Array,\n): void {\n setShaderUniform(material, name, value);\n}\n\n/**\n * Writes a declared `mat4x4<f32>` uniform from sixteen column-major floats.\n *\n * @param material - The material to write to.\n * @param name - The declared uniform name.\n * @param value - The matrix.\n *\n * @internal\n */\nexport function writeShaderMatrix(material: ShaderMaterial, name: string, value: Float32Array): void {\n setShaderMatrix(material, name, value);\n}\n\n/**\n * Binds or clears a declared sampler's texture.\n *\n * @param material - The material to write to.\n * @param name - The declared sampler name.\n * @param texture - The texture, or `null` to unbind. An unbound sampler makes the material\n * unbuildable, so ignifx always binds a fallback instead.\n *\n * @internal\n */\nexport function writeShaderTexture(material: ShaderMaterial, name: string, texture: Texture2D | null): void {\n setShaderTexture(material, name, texture);\n}\n\n/**\n * Binds or clears a declared storage buffer.\n *\n * @param material - The material to write to.\n * @param name - The declared storage buffer name.\n * @param buffer - The buffer, or `null` to unbind.\n *\n * @internal\n */\nexport function writeShaderStorageBuffer(material: ShaderMaterial, name: string, buffer: StorageBuffer | null): void {\n setShaderStorageBuffer(material, name, buffer);\n}\n\n/**\n * The 1x1 texture a declared-but-unbound sampler is filled with, created on first use and shared for\n * the life of the app.\n *\n * @param engine - The engine that owns the texture.\n * @param cache - The app's fallback textures, keyed by kind; a miss is created and stored.\n * @param fallback - `\"white\"`, `\"black\"`, or `\"transparent\"`; `null` means white.\n * @param array - `true` for a one-layer `texture_2d_array<f32>`.\n * @returns The texture.\n *\n * @internal\n */\nexport function resolveFallbackTexture(\n engine: EngineContext,\n cache: Map<string, Texture2D>,\n fallback: string | null,\n array: boolean,\n): Texture2D {\n const kind = fallback ?? \"white\";\n const key = array ? `${kind}:array` : kind;\n const cached = cache.get(key);\n if (cached !== undefined) {\n return cached;\n }\n const created = createFallbackTexture(engine, kind, array);\n cache.set(key, created);\n return created;\n}\n\n/**\n * Creates the 1x1 texture a declared-but-unbound sampler is filled with.\n *\n * @remarks\n * Babylon Lite refuses to build a bind group for a sampler with nothing bound (error 309), so a\n * material whose file declares `// @ignifx texture noise` and whose `.material.json` binds nothing\n * would be undrawable. One 1x1 texture per fallback kind per app is what makes it legal, which is\n * also Godot's `hint_default_white` behaviour.\n *\n * @param engine - The engine that owns the texture.\n * @param fallback - `\"white\"`, `\"black\"`, or `\"transparent\"`.\n * @param array - `true` for a one-layer `texture_2d_array<f32>`, which is what a sampler declared\n * `array` binds.\n * @returns The texture.\n *\n * @internal\n */\nexport function createFallbackTexture(engine: EngineContext, fallback: string, array: boolean): Texture2D {\n const rgba = FALLBACK_PIXELS[fallback] ?? FALLBACK_PIXELS[\"white\"];\n const pixels = Uint8Array.from(rgba ?? [255, 255, 255, 255]);\n return array\n ? createTexture2DArrayFromPixels(engine, pixels, 1, 1, 1, { mipMaps: false })\n : createTexture2DFromPixels(engine, pixels, 1, 1, {});\n}\n\n/**\n * Turns on Babylon Lite's cached uniform serialization plans for shader materials.\n *\n * @remarks\n * Process-global and idempotent: it installs two writer functions that keep a `WeakMap` of layout\n * plans per material and rewrite only the custom uniform slots whose value changed\n * (`lib/material/shader/enable-shader-material-uniform-caching.js`). That is exactly the shape of\n * ignifx's per-frame `time` upload, so the adapter enables it as it loads rather than making every\n * project remember to.\n *\n * @internal\n */\nexport function enableShaderUniformCaching(): void {\n enableShaderMaterialUniformCaching();\n}\n\n/**\n * Reads the installed environment's ambient irradiance — the `L00` band of its diffuse spherical\n * harmonics — into `out`.\n *\n * @remarks\n * `EnvironmentTextures.sphericalHarmonics` is declared: 36 floats in a stride-4 layout beginning\n * `[L00.rgb, 0, …]` (`index.d.ts`), the same block Babylon Lite writes into the scene uniform buffer\n * as `scene.vSphericalL00` and friends (`lib/scene/scene-ubo-extras.js`, `writeEnvUbo`). So the\n * value ignifx uploads as `ambientColor` is exactly what a shader could read for itself as\n * `scene.vSphericalL00.rgb`, which is the documented alternative for a shader that would rather not\n * declare the uniform. Reaching the slot goes through `./environment.ts`, which is the one place\n * ignifx touches the undeclared `scene._envTextures` field\n * (`docs/architecture/07-rendering.md` §2.5, §8).\n *\n * @param scene - The render scene.\n * @param out - Receives the three linear channels; left untouched when nothing is installed.\n * @returns `true` when an environment supplied harmonics.\n *\n * @internal\n */\nexport function readSceneAmbient(scene: SceneContext, out: Float32Array): boolean {\n const harmonics = readSceneEnvironment(scene)?.sphericalHarmonics;\n if (harmonics === undefined || harmonics.length < 3) {\n return false;\n }\n out[0] = harmonics[0] ?? 0;\n out[1] = harmonics[1] ?? 0;\n out[2] = harmonics[2] ?? 0;\n return true;\n}\n\n/**\n * The subset of this module `src/render/shader-material.ts` reaches through its dynamic `import()`,\n * named so the memo has a type that does not have to be written as `typeof import(…)` (which the\n * `consistent-type-imports` rule forbids).\n *\n * @remarks\n * Assigning the imported module namespace to this type is what checks the two against each other,\n * so a signature that drifts is a compile error rather than a runtime surprise.\n *\n * @internal\n */\nexport interface ShaderMaterialAdapter {\n /** {@link createShaderMaterialFromOptions}. */\n readonly createShaderMaterialFromOptions: (options: ShaderMaterialBuildOptions) => ShaderMaterial;\n /** {@link writeShaderUniform}. */\n readonly writeShaderUniform: (\n material: ShaderMaterial,\n name: string,\n value: number | readonly number[] | Float32Array,\n ) => void;\n /** {@link writeShaderMatrix}. */\n readonly writeShaderMatrix: (material: ShaderMaterial, name: string, value: Float32Array) => void;\n /** {@link writeShaderTexture}. */\n readonly writeShaderTexture: (material: ShaderMaterial, name: string, texture: Texture2D | null) => void;\n /** {@link writeShaderStorageBuffer}. */\n readonly writeShaderStorageBuffer: (material: ShaderMaterial, name: string, buffer: StorageBuffer | null) => void;\n /** {@link resolveFallbackTexture}. */\n readonly resolveFallbackTexture: (\n engine: EngineContext,\n cache: Map<string, Texture2D>,\n fallback: string | null,\n array: boolean,\n ) => Texture2D;\n /** {@link enableShaderUniformCaching}. */\n readonly enableShaderUniformCaching: () => void;\n /** {@link readSceneAmbient}. */\n readonly readSceneAmbient: (scene: SceneContext, out: Float32Array) => boolean;\n}\n"],"mappings":";;;;AAsDA,MAAM,kBAAuF,OAAO,OAAO;CACzG,OAAO;EAAC;EAAK;EAAK;EAAK;CAAG;CAC1B,OAAO;EAAC;EAAG;EAAG;EAAG;CAAG;CACpB,aAAa;EAAC;EAAG;EAAG;EAAG;CAAC;AAC1B,CAAC;;;;;;;;;;;;;;AAoGD,SAAgB,gCAAgC,SAAqD;CACnG,OAAO,qBAAqB;EAC1B,MAAM,QAAQ;EACd,cAAc,QAAQ;EACtB,gBAAgB,QAAQ;EACxB,YAAY,QAAQ;EACpB,UAAU,QAAQ;EAClB,UAAU,QAAQ;EAClB,gBAAgB,QAAQ;EACxB,SAAS,QAAQ;EACjB,uBAAuB,QAAQ;EAC/B,mBAAmB,QAAQ;EAC3B,WAAW,QAAQ;EACnB,GAAI,QAAQ,UAAU,OAAO,CAAC,IAAI,EAAE,OAAO,QAAQ,MAAM;EACzD,cAAc,QAAQ;EACtB,iBAAiB,QAAQ;EACzB,YAAY,QAAQ;EACpB,GAAI,QAAQ,iBAAiB,OAAO,CAAC,IAAI,EAAE,cAAc,QAAQ,aAAa;CAChF,CAAC;AACH;;;;;;;;;;;;;;;;AAiBA,SAAgB,mBACd,UACA,MACA,OACM;CACN,iBAAiB,UAAU,MAAM,KAAK;AACxC;;;;;;;;;;AAWA,SAAgB,kBAAkB,UAA0B,MAAc,OAA2B;CACnG,gBAAgB,UAAU,MAAM,KAAK;AACvC;;;;;;;;;;;AAYA,SAAgB,mBAAmB,UAA0B,MAAc,SAAiC;CAC1G,iBAAiB,UAAU,MAAM,OAAO;AAC1C;;;;;;;;;;AAWA,SAAgB,yBAAyB,UAA0B,MAAc,QAAoC;CACnH,uBAAuB,UAAU,MAAM,MAAM;AAC/C;;;;;;;;;;;;;AAcA,SAAgB,uBACd,QACA,OACA,UACA,OACW;CACX,MAAM,OAAO,YAAY;CACzB,MAAM,MAAM,QAAQ,GAAG,KAAK,UAAU;CACtC,MAAM,SAAS,MAAM,IAAI,GAAG;CAC5B,IAAI,WAAW,KAAA,GACb,OAAO;CAET,MAAM,UAAU,sBAAsB,QAAQ,MAAM,KAAK;CACzD,MAAM,IAAI,KAAK,OAAO;CACtB,OAAO;AACT;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,sBAAsB,QAAuB,UAAkB,OAA2B;CACxG,MAAM,OAAO,gBAAgB,aAAa,gBAAgB;CAC1D,MAAM,SAAS,WAAW,KAAK,QAAQ;EAAC;EAAK;EAAK;EAAK;CAAG,CAAC;CAC3D,OAAO,QACH,+BAA+B,QAAQ,QAAQ,GAAG,GAAG,GAAG,EAAE,SAAS,MAAM,CAAC,IAC1E,0BAA0B,QAAQ,QAAQ,GAAG,GAAG,CAAC,CAAC;AACxD;;;;;;;;;;;;;AAcA,SAAgB,6BAAmC;CACjD,mCAAmC;AACrC;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,iBAAiB,OAAqB,KAA4B;CAChF,MAAM,YAAY,qBAAqB,KAAK,CAAC,EAAE;CAC/C,IAAI,cAAc,KAAA,KAAa,UAAU,SAAS,GAChD,OAAO;CAET,IAAI,KAAK,UAAU,MAAM;CACzB,IAAI,KAAK,UAAU,MAAM;CACzB,IAAI,KAAK,UAAU,MAAM;CACzB,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"shader-material-BxQn9FT4.js","names":[],"sources":["../src/lite/gpu/shader-material.ts"],"sourcesContent":["import {\n createShaderMaterial,\n createTexture2DArrayFromPixels,\n createTexture2DFromPixels,\n enableShaderMaterialUniformCaching,\n setShaderMatrix,\n setShaderStorageBuffer,\n setShaderTexture,\n setShaderUniform,\n} from \"@babylonjs/lite\";\nimport { readSceneEnvironment } from \"./environment.js\";\nimport type {\n EngineContext,\n SceneContext,\n ShaderAttributeName,\n ShaderMaterial,\n ShaderSystemUniformName,\n ShaderUniformType,\n StorageBuffer,\n Texture2D,\n} from \"@babylonjs/lite\";\n\n/**\n * The custom-WGSL half of the Babylon Lite adapter: `createShaderMaterial`, the `setShader*`\n * setters, and the 1x1 fallback textures a declared sampler falls back to\n * (`docs/plan/2026-09-terrain-particles-shaders.md` §3.1, ADR-0024). Everything here is `@internal`.\n *\n * Lite exports one barrel, so a static import of `createShaderMaterial` anywhere in the reachable\n * graph pulls `lib/material/shader/**` into every entry chunk. This module is therefore reached with\n * `await import(...)` from `../../render/shader-support.ts`, and only loading a `.wgsl` triggers the\n * fetch. `./storage-buffer.ts` is a separate file for the same reason: `StorageBufferAsset`\n * allocates synchronously, so it cannot wait for this chunk.\n *\n * Two Lite facts it is written around:\n *\n * - Nothing may be left unbound: `createShaderBindGroup` throws (errors 309 and 310) when a declared\n * sampler has no texture or a declared storage buffer has no buffer, which is what\n * {@link createFallbackTexture} exists for.\n * - There is no front-face culling; `ShaderMaterialOptions` carries only `backFaceCulling`\n * (`lib/material/shader/shader-pipeline.js`), so the pragma parser refuses `cull front`.\n */\n\n/**\n * A Babylon Lite custom WGSL material, re-exported under an ignifx name\n * (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteShaderMaterial = ShaderMaterial;\n\n/** The RGBA bytes of each 1x1 fallback texture. */\nconst FALLBACK_PIXELS: Readonly<Record<string, readonly [number, number, number, number]>> = Object.freeze({\n white: [255, 255, 255, 255],\n black: [0, 0, 0, 255],\n transparent: [0, 0, 0, 0],\n});\n\n/**\n * One declared uniform in the form Babylon Lite's factory takes: either the name of a system\n * uniform it fills in itself, or a custom declaration with its initial value.\n *\n * @internal\n */\nexport type ShaderUniformEntry =\n | ShaderSystemUniformName\n | {\n /** The WGSL identifier. */\n readonly name: string;\n /** The WGSL type. */\n readonly type: ShaderUniformType;\n /** The initial value, **linear** for a colour. */\n readonly defaultValue: number | readonly number[];\n };\n\n/**\n * One declared sampler in the form Babylon Lite's factory takes.\n *\n * @internal\n */\nexport interface ShaderSamplerEntry {\n /** The WGSL identifier; Lite generates `<name>Sampler` beside it. */\n readonly name: string;\n /** `\"2d-array\"` for a `texture_2d_array<f32>` binding. */\n readonly viewDimension: \"2d\" | \"2d-array\";\n}\n\n/**\n * One declared storage buffer in the form Babylon Lite's factory takes.\n *\n * @internal\n */\nexport interface ShaderStorageEntry {\n /** The WGSL identifier. */\n readonly name: string;\n /** The WGSL variable type, verbatim. */\n readonly type: string;\n}\n\n/**\n * Everything Babylon Lite's `createShaderMaterial` needs, in ignifx's own vocabulary so that the\n * mapping from a `ShaderDeclaration` can be built and asserted without a device or a Lite import\n * (`src/render/shader-material.ts`).\n *\n * @remarks\n * A `null` blend state or depth comparison means \"leave Babylon Lite's own default in place\", so\n * this module never restates a Lite default that could change.\n *\n * @internal\n */\nexport interface ShaderMaterialBuildOptions {\n /** The material's name, used in pipeline and shader-module labels. */\n readonly name: string;\n /** The WGSL source, handed to Lite as both the vertex and the fragment source. */\n readonly source: string;\n /** The vertex attributes the vertex stage reads; `position` is mandatory. */\n readonly attributes: readonly ShaderAttributeName[];\n /** The system and custom uniforms, in binding-declaration order. */\n readonly uniforms: readonly ShaderUniformEntry[];\n /** The samplers. */\n readonly samplers: readonly ShaderSamplerEntry[];\n /** The read-only storage buffers. */\n readonly storageBuffers: readonly ShaderStorageEntry[];\n /** The WGSL `const` declarations, resolved from the file's defaults and the material's overrides. */\n readonly defines: Readonly<Record<string, boolean | number>>;\n /** Whether the thin-instance RGBA stream is bound and injected into `VertexInput`. */\n readonly useThinInstanceColors: boolean;\n /** Whether the surface is alpha-blended. */\n readonly needAlphaBlending: boolean;\n /** Which of Lite's two blend equations to use when no explicit state is given. */\n readonly blendMode: \"alpha\" | \"additive\";\n /** An explicit colour-target blend state, which replaces the derived one; `null` to derive it. */\n readonly blend: GPUBlendState | null;\n /** Whether the surface samples the opaque scene colour behind it. */\n readonly transmissive: boolean;\n /** Whether back faces are culled. */\n readonly backFaceCulling: boolean;\n /** Whether the draw writes depth. */\n readonly depthWrite: boolean;\n /** The depth comparison, or `null` for Lite's own reverse-Z default. */\n readonly depthCompare: GPUCompareFunction | null;\n}\n\n/**\n * Builds a Babylon Lite custom WGSL material.\n *\n * @remarks\n * Validation is eager and compilation is lazy, so this runs under the null engine; the pipeline is\n * compiled the first time a mesh wearing the material is drawn.\n *\n * @param options - The sources and the declared attribute, uniform, sampler, and storage layout.\n * @returns The material.\n * @throws Error from Babylon Lite when the declaration is not one it can build.\n *\n * @internal\n */\nexport function createShaderMaterialFromOptions(options: ShaderMaterialBuildOptions): ShaderMaterial {\n return createShaderMaterial({\n name: options.name,\n vertexSource: options.source,\n fragmentSource: options.source,\n attributes: options.attributes,\n uniforms: options.uniforms,\n samplers: options.samplers,\n storageBuffers: options.storageBuffers,\n defines: options.defines,\n useThinInstanceColors: options.useThinInstanceColors,\n needAlphaBlending: options.needAlphaBlending,\n blendMode: options.blendMode,\n ...(options.blend === null ? {} : { blend: options.blend }),\n transmissive: options.transmissive,\n backFaceCulling: options.backFaceCulling,\n depthWrite: options.depthWrite,\n ...(options.depthCompare === null ? {} : { depthCompare: options.depthCompare }),\n });\n}\n\n/**\n * Writes a declared scalar, vector, or matrix uniform.\n *\n * @remarks\n * Lite compares the incoming numbers with the ones it holds and bumps the material's uniform\n * version only when one changed, so calling this every frame with an unchanged value costs a few\n * comparisons and no upload (`lib/material/shader/shader-material.js`, `setUniformValue`).\n *\n * @param material - The material to write to.\n * @param name - The declared uniform name.\n * @param value - The value; its length must match the declared type.\n * @throws Error from Babylon Lite when the name is not declared or the length is wrong.\n *\n * @internal\n */\nexport function writeShaderUniform(\n material: ShaderMaterial,\n name: string,\n value: number | readonly number[] | Float32Array,\n): void {\n setShaderUniform(material, name, value);\n}\n\n/**\n * Writes a declared `mat4x4<f32>` uniform from sixteen column-major floats.\n *\n * @param material - The material to write to.\n * @param name - The declared uniform name.\n * @param value - The matrix.\n *\n * @internal\n */\nexport function writeShaderMatrix(material: ShaderMaterial, name: string, value: Float32Array): void {\n setShaderMatrix(material, name, value);\n}\n\n/**\n * Binds or clears a declared sampler's texture.\n *\n * @param material - The material to write to.\n * @param name - The declared sampler name.\n * @param texture - The texture, or `null` to unbind. An unbound sampler makes the material\n * unbuildable, so ignifx always binds a fallback instead.\n *\n * @internal\n */\nexport function writeShaderTexture(material: ShaderMaterial, name: string, texture: Texture2D | null): void {\n setShaderTexture(material, name, texture);\n}\n\n/**\n * Binds or clears a declared storage buffer.\n *\n * @param material - The material to write to.\n * @param name - The declared storage buffer name.\n * @param buffer - The buffer, or `null` to unbind.\n *\n * @internal\n */\nexport function writeShaderStorageBuffer(material: ShaderMaterial, name: string, buffer: StorageBuffer | null): void {\n setShaderStorageBuffer(material, name, buffer);\n}\n\n/**\n * The 1x1 texture a declared-but-unbound sampler is filled with, created on first use and shared for\n * the life of the app.\n *\n * @param engine - The engine that owns the texture.\n * @param cache - The app's fallback textures, keyed by kind; a miss is created and stored.\n * @param fallback - `\"white\"`, `\"black\"`, or `\"transparent\"`; `null` means white.\n * @param array - `true` for a one-layer `texture_2d_array<f32>`.\n * @returns The texture.\n *\n * @internal\n */\nexport function resolveFallbackTexture(\n engine: EngineContext,\n cache: Map<string, Texture2D>,\n fallback: string | null,\n array: boolean,\n): Texture2D {\n const kind = fallback ?? \"white\";\n const key = array ? `${kind}:array` : kind;\n const cached = cache.get(key);\n if (cached !== undefined) {\n return cached;\n }\n const created = createFallbackTexture(engine, kind, array);\n cache.set(key, created);\n return created;\n}\n\n/**\n * Creates the 1x1 texture a declared-but-unbound sampler is filled with.\n *\n * @remarks\n * Babylon Lite refuses to build a bind group for a sampler with nothing bound (error 309), so a\n * material whose file declares `// @ignifx texture noise` and whose `.material.json` binds nothing\n * would be undrawable. One 1x1 texture per fallback kind per app is what makes it legal, which is\n * also Godot's `hint_default_white` behaviour.\n *\n * @param engine - The engine that owns the texture.\n * @param fallback - `\"white\"`, `\"black\"`, or `\"transparent\"`.\n * @param array - `true` for a one-layer `texture_2d_array<f32>`, which is what a sampler declared\n * `array` binds.\n * @returns The texture.\n *\n * @internal\n */\nexport function createFallbackTexture(engine: EngineContext, fallback: string, array: boolean): Texture2D {\n const rgba = FALLBACK_PIXELS[fallback] ?? FALLBACK_PIXELS[\"white\"];\n const pixels = Uint8Array.from(rgba ?? [255, 255, 255, 255]);\n return array\n ? createTexture2DArrayFromPixels(engine, pixels, 1, 1, 1, { mipMaps: false })\n : createTexture2DFromPixels(engine, pixels, 1, 1, {});\n}\n\n/**\n * Turns on Babylon Lite's cached uniform serialization plans for shader materials.\n *\n * @remarks\n * Process-global and idempotent: it installs two writer functions that keep a `WeakMap` of layout\n * plans per material and rewrite only the custom uniform slots whose value changed\n * (`lib/material/shader/enable-shader-material-uniform-caching.js`). That is exactly the shape of\n * ignifx's per-frame `time` upload, so the adapter enables it as it loads rather than making every\n * project remember to.\n *\n * @internal\n */\nexport function enableShaderUniformCaching(): void {\n enableShaderMaterialUniformCaching();\n}\n\n/**\n * Reads the installed environment's ambient irradiance — the `L00` band of its diffuse spherical\n * harmonics — into `out`.\n *\n * @remarks\n * `EnvironmentTextures.sphericalHarmonics` is declared: 36 floats in a stride-4 layout beginning\n * `[L00.rgb, 0, …]` (`index.d.ts`), the same block Babylon Lite writes into the scene uniform buffer\n * as `scene.vSphericalL00` and friends (`lib/scene/scene-ubo-extras.js`, `writeEnvUbo`). So the\n * value ignifx uploads as `ambientColor` is exactly what a shader could read for itself as\n * `scene.vSphericalL00.rgb`, which is the documented alternative for a shader that would rather not\n * declare the uniform. Reaching the slot goes through `./environment.ts`, which is the one place\n * ignifx touches the undeclared `scene._envTextures` field\n * (`docs/architecture/07-rendering.md` §2.5, §8).\n *\n * @param scene - The render scene.\n * @param out - Receives the three linear channels; left untouched when nothing is installed.\n * @returns `true` when an environment supplied harmonics.\n *\n * @internal\n */\nexport function readSceneAmbient(scene: SceneContext, out: Float32Array): boolean {\n const harmonics = readSceneEnvironment(scene)?.sphericalHarmonics;\n if (harmonics === undefined || harmonics.length < 3) {\n return false;\n }\n out[0] = harmonics[0] ?? 0;\n out[1] = harmonics[1] ?? 0;\n out[2] = harmonics[2] ?? 0;\n return true;\n}\n\n/**\n * The subset of this module `src/render/shader-material.ts` reaches through its dynamic `import()`,\n * named so the memo has a type that does not have to be written as `typeof import(…)` (which the\n * `consistent-type-imports` rule forbids).\n *\n * @remarks\n * Assigning the imported module namespace to this type is what checks the two against each other,\n * so a signature that drifts is a compile error rather than a runtime surprise.\n *\n * @internal\n */\nexport interface ShaderMaterialAdapter {\n /** {@link createShaderMaterialFromOptions}. */\n readonly createShaderMaterialFromOptions: (options: ShaderMaterialBuildOptions) => ShaderMaterial;\n /** {@link writeShaderUniform}. */\n readonly writeShaderUniform: (\n material: ShaderMaterial,\n name: string,\n value: number | readonly number[] | Float32Array,\n ) => void;\n /** {@link writeShaderMatrix}. */\n readonly writeShaderMatrix: (material: ShaderMaterial, name: string, value: Float32Array) => void;\n /** {@link writeShaderTexture}. */\n readonly writeShaderTexture: (material: ShaderMaterial, name: string, texture: Texture2D | null) => void;\n /** {@link writeShaderStorageBuffer}. */\n readonly writeShaderStorageBuffer: (material: ShaderMaterial, name: string, buffer: StorageBuffer | null) => void;\n /** {@link resolveFallbackTexture}. */\n readonly resolveFallbackTexture: (\n engine: EngineContext,\n cache: Map<string, Texture2D>,\n fallback: string | null,\n array: boolean,\n ) => Texture2D;\n /** {@link enableShaderUniformCaching}. */\n readonly enableShaderUniformCaching: () => void;\n /** {@link readSceneAmbient}. */\n readonly readSceneAmbient: (scene: SceneContext, out: Float32Array) => boolean;\n}\n"],"mappings":";;;;AAsDA,MAAM,kBAAuF,OAAO,OAAO;CACzG,OAAO;EA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KAAK;CACzD,MAAM,IAAI,KAAK,OAAO;CACtB,OAAO;AACT;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,sBAAsB,QAAuB,UAAkB,OAA2B;CACxG,MAAM,OAAO,gBAAgB,aAAa,gBAAgB;CAC1D,MAAM,SAAS,WAAW,KAAK,QAAQ;EAAC;EAAK;EAAK;EAAK;CAAG,CAAC;CAC3D,OAAO,QACH,+BAA+B,QAAQ,QAAQ,GAAG,GAAG,GAAG,EAAE,SAAS,MAAM,CAAC,IAC1E,0BAA0B,QAAQ,QAAQ,GAAG,GAAG,CAAC,CAAC;AACxD;;;;;;;;;;;;;AAcA,SAAgB,6BAAmC;CACjD,mCAAmC;AACrC;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,iBAAiB,OAAqB,KAA4B;CAChF,MAAM,YAAY,qBAAqB,KAAK,CAAC,EAAE;CAC/C,IAAI,cAAc,KAAA,KAAa,UAAU,SAAS,GAChD,OAAO;CAET,IAAI,KAAK,UAAU,MAAM;CACzB,IAAI,KAAK,UAAU,MAAM;CACzB,IAAI,KAAK,UAAU,MAAM;CACzB,OAAO;AACT"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { o as CoreErrorCode, t as IgnifxError } from "./ignifx-error-
|
|
1
|
+
import { o as CoreErrorCode, t as IgnifxError } from "./ignifx-error-Dq2qJMkZ.js";
|
|
2
2
|
import { t as Color } from "./color-DrR6GFTd.js";
|
|
3
|
+
import { t as setOwnJsonProperty } from "./json-CzZZ6K4x.js";
|
|
3
4
|
import { n as IGNIFX_UNIFORM_TYPES, r as LITE_SYSTEM_UNIFORM_NAMES, t as IGNIFX_UNIFORM_NAMES } from "./shader-declaration-5q__jycG.js";
|
|
4
5
|
//#region \0rolldown/runtime.js
|
|
5
6
|
var __defProp = Object.defineProperty;
|
|
@@ -172,7 +173,7 @@ let adapter = null;
|
|
|
172
173
|
*/
|
|
173
174
|
async function loadShaderMaterialAdapter() {
|
|
174
175
|
if (adapter !== null) return;
|
|
175
|
-
const loaded = await import("./shader-material-
|
|
176
|
+
const loaded = await import("./shader-material-BxQn9FT4.js");
|
|
176
177
|
loaded.enableShaderUniformCaching();
|
|
177
178
|
adapter = loaded;
|
|
178
179
|
}
|
|
@@ -667,7 +668,7 @@ var ShaderMaterialState = class {
|
|
|
667
668
|
for (let index = 0; index < declared.length; index += 1) {
|
|
668
669
|
const define = declared[index];
|
|
669
670
|
if (define === void 0) continue;
|
|
670
|
-
resolved
|
|
671
|
+
setOwnJsonProperty(resolved, define.name, this.#defines.get(define.name) ?? define.value);
|
|
671
672
|
}
|
|
672
673
|
return resolved;
|
|
673
674
|
}
|
|
@@ -877,9 +878,12 @@ function buildShaderMaterialState(app, shader, definition, textures) {
|
|
|
877
878
|
const declared = shader.declaration.defines;
|
|
878
879
|
for (let index = 0; index < declared.length; index += 1) {
|
|
879
880
|
const define = declared[index];
|
|
880
|
-
if (define !== void 0)
|
|
881
|
+
if (define !== void 0) {
|
|
882
|
+
const given = Object.hasOwn(definition.defines, define.name) ? definition.defines[define.name] : void 0;
|
|
883
|
+
setOwnJsonProperty(defines, define.name, given ?? define.value);
|
|
884
|
+
}
|
|
881
885
|
}
|
|
882
|
-
for (const name of Object.keys(definition.defines)) if (!(name
|
|
886
|
+
for (const name of Object.keys(definition.defines)) if (!Object.hasOwn(defines, name)) throw new IgnifxError(CoreErrorCode.unknownShaderBinding, `${definition.name} declares no define named ${name}.`, {
|
|
883
887
|
context: {
|
|
884
888
|
material: definition.name,
|
|
885
889
|
name
|
|
@@ -1006,4 +1010,4 @@ function shapeMismatch(declaration, material, expected, actual) {
|
|
|
1006
1010
|
//#endregion
|
|
1007
1011
|
export { shader_material_exports as n, shaderMaterialsOf as t };
|
|
1008
1012
|
|
|
1009
|
-
//# sourceMappingURL=shader-material-
|
|
1013
|
+
//# sourceMappingURL=shader-material-DRZmqA_S.js.map
|