@ignifx/core 0.17.0 → 0.18.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-CMpzGXTz.js → environment-DZ6WUHbm.js} +2 -2
- package/dist/{environment-CMpzGXTz.js.map → environment-DZ6WUHbm.js.map} +1 -1
- package/dist/{hdr-output-BrUvpAsE.js → hdr-output-Dbv0lhFl.js} +4 -3
- package/dist/{hdr-output-BrUvpAsE.js.map → hdr-output-Dbv0lhFl.js.map} +1 -1
- package/dist/{ignifx-error-Der0bpHK.js → ignifx-error-B8ByiSfJ.js} +10 -1
- package/dist/ignifx-error-B8ByiSfJ.js.map +1 -0
- package/dist/index.d.ts +110 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +836 -35
- package/dist/index.js.map +1 -1
- package/dist/light-probe-asset-B60_X-yN.js +331 -0
- package/dist/light-probe-asset-B60_X-yN.js.map +1 -0
- package/dist/light-probes-DkYN89Qw.js +284 -0
- package/dist/light-probes-DkYN89Qw.js.map +1 -0
- package/dist/{material-plugin-B-hartHR.js → material-plugin-CiAmriQ_.js} +2 -2
- package/dist/{material-plugin-B-hartHR.js.map → material-plugin-CiAmriQ_.js.map} +1 -1
- package/dist/{post-effect-CuoYvrhb.js → post-effect-CQnlX1RH.js} +2 -2
- package/dist/{post-effect-CuoYvrhb.js.map → post-effect-CQnlX1RH.js.map} +1 -1
- package/dist/{post-effect-compiler-Bps8QbiJ.js → post-effect-compiler-C_7HTHZy.js} +3 -3
- package/dist/{post-effect-compiler-Bps8QbiJ.js.map → post-effect-compiler-C_7HTHZy.js.map} +1 -1
- package/dist/{prefab-overrides-76IhcF-e.d.ts → prefab-overrides-BLQn5yHS.d.ts} +231 -7
- package/dist/prefab-overrides-BLQn5yHS.d.ts.map +1 -0
- package/dist/{prefab-overrides-DGiGTSN-.js → prefab-overrides-DT-wHHAJ.js} +2 -2
- package/dist/{prefab-overrides-DGiGTSN-.js.map → prefab-overrides-DT-wHHAJ.js.map} +1 -1
- package/dist/prefab.d.ts +1 -1
- package/dist/prefab.js +1 -1
- package/dist/{reflection-probe-C0pzGrG_.js → reflection-probe-DlVsl3zJ.js} +3 -3
- package/dist/{reflection-probe-C0pzGrG_.js.map → reflection-probe-DlVsl3zJ.js.map} +1 -1
- package/dist/{reflection-probes-B8_vK9YR.js → reflection-probes-B8S9WnVX.js} +3 -3
- package/dist/{reflection-probes-B8_vK9YR.js.map → reflection-probes-B8S9WnVX.js.map} +1 -1
- package/dist/{render-path-Be7WgN7r.js → render-path-D11i_7X8.js} +3 -2
- package/dist/{render-path-Be7WgN7r.js.map → render-path-D11i_7X8.js.map} +1 -1
- package/dist/{scene-color-passes-DlNr-qyZ.js → scene-color-passes-B93qTOka.js} +35 -12
- package/dist/scene-color-passes-B93qTOka.js.map +1 -0
- package/dist/{shader-material-Cjfq7nFS.js → shader-material-C2_UCYdO.js} +5 -5
- package/dist/{shader-material-Cjfq7nFS.js.map → shader-material-C2_UCYdO.js.map} +1 -1
- package/dist/{shader-material-DCjYDdkh.js → shader-material-CaAkv5nT.js} +2 -2
- package/dist/{shader-material-DCjYDdkh.js.map → shader-material-CaAkv5nT.js.map} +1 -1
- package/dist/{shader-pragma-cjEC-EPK.js → shader-pragma-DmZpxGUo.js} +2 -2
- package/dist/{shader-pragma-cjEC-EPK.js.map → shader-pragma-DmZpxGUo.js.map} +1 -1
- package/dist/{surface-shader-D40hXQ8c.js → surface-shader-BeDRofOV.js} +4 -4
- package/dist/{surface-shader-D40hXQ8c.js.map → surface-shader-BeDRofOV.js.map} +1 -1
- package/package.json +1 -1
- package/dist/ignifx-error-Der0bpHK.js.map +0 -1
- package/dist/prefab-overrides-76IhcF-e.d.ts.map +0 -1
- package/dist/scene-color-passes-DlNr-qyZ.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"light-probes-DkYN89Qw.js","names":[],"sources":["../src/lite/gpu/light-probes.ts","../src/render/gpu/light-probes.ts"],"sourcesContent":["import { createRenderTexture2D, enableMaterialPlugins, getPbrUnlit, isPbrMaterial, isPbrSkybox } from \"@babylonjs/lite\";\nimport { markMaterialDirty, rebuildMaterialPipelines } from \"../material.js\";\nimport { deviceOf } from \"./render-texture.js\";\nimport type { EngineContext, MaterialPlugin, SceneContext, Texture2D } from \"@babylonjs/lite\";\n\n/**\n * Light probes on the GPU (`docs/plan/2026-11-gi-phase-2-execution-plan.md`, step B2). Its own chunk,\n * loaded only once a world has a `LightProbeVolume` (`CONSTITUTION.md` §2.5). Every Lite claim was\n * read from `@babylonjs/lite@1.34.0`.\n *\n * - **Texture.** The grid's coefficients, packed by `packLightProbeTexels`, in an `rgba16float`\n * texture read with `textureLoad` (plugins bind `texture_2d<f32>` only, `index.d.ts` 10607, so no\n * 3D texture).\n * - **Plugin.** Lite declares `environmentIrradiance` with `let` inside the IBL code\n * (`lib/material/pbr/fragments/ibl-fragment.js`), so a plugin cannot replace it. Instead the plugin\n * adds `(probes − environment) · surfaceAlbedo · occlusion` to `color`, recomputing the\n * environment's harmonics from the scene uniforms the IBL code reads. Its point,\n * `CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION`, is injected twice (`AI` before the IBL code, `NI`\n * after it; `lib/material/plugin/plugin-bridge-shared.js` line 13), so a private counter applies it\n * on the second pass only. Its priority runs it before the HDR linear-output plugin saves `color`.\n * - **Grid constants** are written into the WGSL, so a different grid is a different plugin and a\n * material rebuild: grids change rarely. `intensity` is a uniform on the host material's block,\n * so changing it rebuilds nothing.\n */\n\n/**\n * The name the plugin carries; part of Lite's pipeline cache key.\n *\n * @internal\n */\nexport const LIGHT_PROBE_PLUGIN_NAME = \"ignifx-light-probes\";\n\n/**\n * The grid shape the shader needs.\n *\n * @internal\n */\nexport interface LightProbeGridShape {\n /** Probe `(0, 0, 0)`'s world position. */\n readonly origin: readonly [number, number, number];\n /** The cell size per axis. */\n readonly cellSize: readonly [number, number, number];\n /** Probe counts per axis. */\n readonly counts: readonly [number, number, number];\n}\n\n/**\n * The plugin's live settings: read on every material uniform write, so changing them needs only\n * {@link refreshLightProbeUniforms}, not a pipeline rebuild.\n *\n * @internal\n */\nexport interface LightProbeUniforms {\n /** The multiplier on the probes' light. */\n intensity: number;\n}\n\n/** The uniform field the plugin adds to each host material's block. */\nconst INTENSITY_FIELD = \"ignifxLpIntensity\";\n\n/**\n * A WGSL float literal.\n *\n * @param value - A finite number.\n * @returns The literal.\n */\nfunction f(value: number): string {\n return Number.isInteger(value) ? `${String(value)}.0` : String(value);\n}\n\n/**\n * The plugin's WGSL.\n *\n * @param shape - The grid.\n * @returns The definitions and the composition code.\n *\n * @internal\n */\nexport function lightProbePluginWgsl(shape: LightProbeGridShape): { definitions: string; composition: string } {\n const [nx, ny, nz] = shape.counts;\n const origin = `vec3<f32>(${shape.origin.map(f).join(\",\")})`;\n const inverse = `vec3<f32>(${shape.cellSize.map((size) => f(1 / size)).join(\",\")})`;\n const maxCell = `vec3<f32>(${f(nx - 1)},${f(ny - 1)},${f(nz - 1)})`;\n const definitions =\n \"var<private> igxLpPass:i32;\" +\n \"fn igxLpTexel(c:vec3<i32>,k:i32)->vec3<f32>{\" +\n `return textureLoad(ignifxLp,vec2<i32>(c.x+${String(nx)}*k,c.y+${String(ny)}*c.z),0).rgb;}` +\n \"fn igxLpAt(c:vec3<i32>,n:vec3<f32>)->vec3<f32>{\" +\n \"return igxLpTexel(c,0)+igxLpTexel(c,1)*n.y+igxLpTexel(c,2)*n.z+igxLpTexel(c,3)*n.x;}\" +\n \"fn igxLpSample(p:vec3<f32>,n:vec3<f32>)->vec3<f32>{\" +\n `let m=${maxCell};let g=clamp((p-${origin})*${inverse},vec3<f32>(0.0),m);` +\n \"let lo=min(floor(g),max(m-1.0,vec3<f32>(0.0)));let t=g-lo;let hi=min(lo+1.0,m);\" +\n \"var r=vec3<f32>(0.0);\" +\n \"for(var i=0;i<8;i++){let s=vec3<i32>(i&1,(i>>1u)&1,(i>>2u)&1)==vec3<i32>(1);\" +\n \"let w=select(1.0-t,t,s);r+=igxLpAt(vec3<i32>(select(lo,hi,s)),n)*(w.x*w.y*w.z);}\" +\n // Trilinear blending of ringing harmonics can dip below zero; light never does.\n \"return max(r,vec3<f32>(0.0));}\";\n const composition =\n \"igxLpPass=igxLpPass+1;\" +\n \"if(igxLpPass==2){\" +\n \"let igxC=cos(scene.envRotationY);let igxS=sin(scene.envRotationY);\" +\n \"let igxN=vec3<f32>(N.x*igxC+N.z*igxS,N.y,-N.x*igxS+N.z*igxC);\" +\n \"let igxEnv=(scene.vSphericalL00.rgb+scene.vSphericalL1_1.rgb*igxN.y+scene.vSphericalL10.rgb*igxN.z\" +\n \"+scene.vSphericalL11.rgb*igxN.x+scene.vSphericalL2_2.rgb*(igxN.y*igxN.x)+scene.vSphericalL2_1.rgb*(igxN.y*igxN.z)\" +\n \"+scene.vSphericalL20.rgb*(3.0*igxN.z*igxN.z-1.0)+scene.vSphericalL21.rgb*(igxN.z*igxN.x)\" +\n \"+scene.vSphericalL22.rgb*(igxN.x*igxN.x-igxN.y*igxN.y))*material.environmentIntensity;\" +\n `color+=(igxLpSample(input.worldPos,N)*material.${INTENSITY_FIELD}-igxEnv)*surfaceAlbedo*occlusion;}`;\n return { definitions, composition };\n}\n\n/**\n * Installs Lite's material-plugin bridges, which the plugin needs, unless the project already did.\n *\n * @remarks\n * Idempotent (`lib/material/plugin/enable-material-plugins.js` replaces its one scene hook). The\n * HDR path calls it before `registerScene` (`./hdr-output.ts`); here it runs after, which works for\n * PBR because the bridge assigns a material's plugin identity during the rebuild that attaching\n * the plugin queues. `light-probe.browser.test.ts` covers that case with HDR off.\n *\n * @param scene - The registered scene.\n *\n * @internal\n */\nexport function enableLightProbePlugins(scene: SceneContext): void {\n enableMaterialPlugins(scene);\n}\n\n/**\n * Uploads packed probe texels into a texture.\n *\n * @param engine - The engine.\n * @param width - The texel width.\n * @param height - The texel height.\n * @param texels - Four half floats per texel.\n * @returns The texture, or `null` when the engine has no device.\n *\n * @internal\n */\nexport function createLightProbeTexture(\n engine: EngineContext,\n width: number,\n height: number,\n texels: Uint16Array,\n): Texture2D | null {\n const device = deviceOf(engine);\n if (device === null) {\n return null;\n }\n const texture = createRenderTexture2D(engine, width, height, {\n format: \"rgba16float\",\n minFilter: \"nearest\",\n magFilter: \"nearest\",\n });\n device.queue.writeTexture({ texture: texture.texture }, texels, { bytesPerRow: width * 8 }, { width, height });\n return texture;\n}\n\n/**\n * Builds the plugin for one grid and its texture.\n *\n * @param shape - The grid.\n * @param texture - The packed texture.\n * @param uniforms - The live settings; the plugin reads them on every uniform write.\n * @returns The plugin, shared by every lit PBR material.\n *\n * @internal\n */\nexport function createLightProbePlugin(\n shape: LightProbeGridShape,\n texture: Texture2D,\n uniforms: LightProbeUniforms,\n): MaterialPlugin {\n const wgsl = lightProbePluginWgsl(shape);\n const fragment = {\n CUSTOM_FRAGMENT_DEFINITIONS: wgsl.definitions,\n CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION: wgsl.composition,\n };\n return {\n name: LIGHT_PROBE_PLUGIN_NAME,\n // Before the HDR linear-output plugin (priority 0) saves `color` at the same point.\n priority: -100,\n getSamplers: () => [{ texture: \"ignifxLp\", sampler: \"ignifxLpSampler\" }],\n getUniforms: () => ({ ubo: [{ name: INTENSITY_FIELD, type: \"f32\" }] }),\n writeUbo: (data, offsets) => {\n // Lite hands over byte offsets.\n const byteOffset = offsets.get(INTENSITY_FIELD);\n if (byteOffset !== undefined) {\n data[byteOffset / 4] = uniforms.intensity;\n }\n },\n bindTextures: (out) => {\n out.push({ texture });\n },\n getCustomCode: (stage) => (stage === \"fragment\" ? fragment : null),\n };\n}\n\n/**\n * Re-uploads the plugin's uniforms on every material that carries it, after\n * {@link LightProbeUniforms} changed.\n *\n * @param scene - The scene.\n * @param plugin - The plugin.\n *\n * @internal\n */\nexport function refreshLightProbeUniforms(scene: SceneContext, plugin: MaterialPlugin): void {\n const meshes = scene.meshes;\n for (let index = 0; index < meshes.length; index += 1) {\n const material = meshes[index]?.material;\n // Declared non-null, but Lite's mesh factories create meshes with `material: null`.\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n if (material === undefined || material === null || !isPbrMaterial(material)) {\n continue;\n }\n if (material.plugins?.includes(plugin) === true) {\n markMaterialDirty(material);\n }\n }\n}\n\n/**\n * Gives every lit PBR material `next` in place of `previous`, rebuilding the ones that changed.\n *\n * @param scene - The registered scene.\n * @param previous - The plugin to take off, or `null`.\n * @param next - The plugin to put on, or `null` to only take `previous` off.\n *\n * @internal\n */\nexport function swapLightProbePlugin(\n scene: SceneContext,\n previous: MaterialPlugin | null,\n next: MaterialPlugin | null,\n): void {\n const meshes = scene.meshes;\n for (let index = 0; index < meshes.length; index += 1) {\n const material = meshes[index]?.material;\n // Declared non-null, but Lite's mesh factories create meshes with `material: null`.\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n if (material === undefined || material === null || !isPbrMaterial(material)) {\n continue;\n }\n const current = material.plugins ?? [];\n const lit = getPbrUnlit(material) === undefined && !isPbrSkybox(material);\n const hasPrevious = previous !== null && current.includes(previous);\n const wantsNext = next !== null && lit;\n if (!hasPrevious && (!wantsNext || current.includes(next))) {\n continue;\n }\n const kept = hasPrevious ? current.filter((plugin) => plugin !== previous) : current;\n material.plugins = wantsNext && !kept.includes(next) ? [...kept, next] : kept;\n rebuildMaterialPipelines(scene, material);\n }\n}\n","import { readSceneEnvironment } from \"../../lite/gpu/environment.js\";\nimport {\n createLightProbePlugin,\n createLightProbeTexture,\n enableLightProbePlugins,\n refreshLightProbeUniforms,\n swapLightProbePlugin,\n} from \"../../lite/gpu/light-probes.js\";\nimport { packLightProbeTexels } from \"../light-probe-asset.js\";\nimport type { LightProbeUniforms } from \"../../lite/gpu/light-probes.js\";\nimport type { LiteMaterialPlugin } from \"../../lite/gpu/material-plugin.js\";\nimport type { LiteEngine, LiteScene } from \"../../lite/scene.js\";\nimport type { LightProbeAsset } from \"../light-probe-asset.js\";\nimport type { LightProbeVolume } from \"../light-probe-volume.js\";\n\n/**\n * The render layer's half of light probes (`docs/plan/2026-11-gi-phase-2-execution-plan.md`, step\n * B2): which volume lights the scene, and keeping its plugin on every lit PBR material. Loaded with\n * `../../lite/gpu/light-probes.ts` as one chunk, only once a world has a `LightProbeVolume`.\n */\n\n/** Frames a replaced texture outlives its plugin, so no in-flight bind group still names it. */\nconst RETIRE_FRAMES = 8;\n\n/** What is applied: which grid, at which intensity, through which plugin. */\ninterface Applied {\n readonly asset: LightProbeAsset;\n readonly uniforms: LightProbeUniforms;\n readonly plugin: LiteMaterialPlugin;\n readonly destroy: () => void;\n}\n\n/**\n * The light probes of a renderer.\n *\n * @internal\n */\nexport interface LightProbeRuntime {\n /** Whether a grid is applied. */\n readonly isLighting: boolean;\n /**\n * Picks the volume that lights the scene and keeps its plugin on every lit PBR material.\n *\n * @param volumes - Every `LightProbeVolume` in the world.\n */\n update(volumes: readonly LightProbeVolume[]): void;\n /** Takes the plugin off every material and frees the texture. */\n dispose(): void;\n}\n\n/**\n * Creates the runtime.\n *\n * @param engine - The engine.\n * @param scene - The registered render scene.\n * @returns The runtime.\n *\n * @internal\n */\nexport function createLightProbeRuntime(engine: LiteEngine, scene: LiteScene): LightProbeRuntime {\n enableLightProbePlugins(scene);\n let applied: Applied | null = null;\n const retiring: { destroy: () => void; frames: number }[] = [];\n\n const apply = (asset: LightProbeAsset, intensity: number): Applied | null => {\n const { data } = asset;\n const packed = packLightProbeTexels(data);\n const texture = createLightProbeTexture(engine, packed.width, packed.height, packed.texels);\n if (texture === null) {\n return null;\n }\n const uniforms: LightProbeUniforms = { intensity };\n const plugin = createLightProbePlugin(\n {\n origin: [data.origin.x, data.origin.y, data.origin.z],\n cellSize: [data.cellSize.x, data.cellSize.y, data.cellSize.z],\n counts: [data.counts.x, data.counts.y, data.counts.z],\n },\n texture,\n uniforms,\n );\n return { asset, uniforms, plugin, destroy: () => texture.texture.destroy() };\n };\n\n const replace = (next: Applied | null): void => {\n swapLightProbePlugin(scene, applied?.plugin ?? null, next?.plugin ?? null);\n if (applied !== null) {\n retiring.push({ destroy: applied.destroy, frames: RETIRE_FRAMES });\n }\n applied = next;\n };\n\n return {\n get isLighting(): boolean {\n return applied !== null;\n },\n update(volumes: readonly LightProbeVolume[]): void {\n for (let index = retiring.length - 1; index >= 0; index -= 1) {\n const entry = retiring[index];\n if (entry !== undefined && --entry.frames <= 0) {\n entry.destroy();\n retiring.splice(index, 1);\n }\n }\n let winner: LightProbeVolume | null = null;\n let asset: LightProbeAsset | null = null;\n // The plugin recomputes the environment's harmonics, so it needs one installed.\n if (readSceneEnvironment(scene) !== null) {\n for (const volume of volumes) {\n const loaded = volume.isEnabledInHierarchy ? volume.loadedProbes() : null;\n if (loaded !== null) {\n winner = volume;\n asset = loaded;\n }\n }\n }\n if (winner === null || asset === null) {\n if (applied !== null) {\n replace(null);\n }\n return;\n }\n if (applied === null || applied.asset !== asset) {\n replace(apply(asset, winner.intensity));\n return;\n }\n if (applied.uniforms.intensity !== winner.intensity) {\n applied.uniforms.intensity = winner.intensity;\n refreshLightProbeUniforms(scene, applied.plugin);\n }\n // Meshes created since the last frame get the plugin too; nothing is rebuilt otherwise.\n swapLightProbePlugin(scene, null, applied.plugin);\n },\n dispose(): void {\n replace(null);\n for (const entry of retiring) {\n entry.destroy();\n }\n retiring.length = 0;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAa,0BAA0B;;AA4BvC,MAAM,kBAAkB;;;;;;;AAQxB,SAAS,EAAE,OAAuB;CAChC,OAAO,OAAO,UAAU,KAAK,IAAI,GAAG,OAAO,KAAK,EAAE,MAAM,OAAO,KAAK;AACtE;;;;;;;;;AAUA,SAAgB,qBAAqB,OAA0E;CAC7G,MAAM,CAAC,IAAI,IAAI,MAAM,MAAM;CAC3B,MAAM,SAAS,aAAa,MAAM,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;CAC1D,MAAM,UAAU,aAAa,MAA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AAQ,UAAU,MAAM;IACrC,IAAI,YAAY,MACd,QAAQ,IAAI;IAEd;GACF;GACA,IAAI,YAAY,QAAQ,QAAQ,UAAU,OAAO;IAC/C,QAAQ,MAAM,OAAO,OAAO,SAAS,CAAC;IACtC;GACF;GACA,IAAI,QAAQ,SAAS,cAAc,OAAO,WAAW;IACnD,QAAQ,SAAS,YAAY,OAAO;IACpC,0BAA0B,OAAO,QAAQ,MAAM;GACjD;GAEA,qBAAqB,OAAO,MAAM,QAAQ,MAAM;EAClD;EACA,UAAgB;GACd,QAAQ,IAAI;GACZ,KAAK,MAAM,SAAS,UAClB,MAAM,QAAQ;GAEhB,SAAS,SAAS;EACpB;CACF;AACF"}
|
|
@@ -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-B8ByiSfJ.js";
|
|
2
2
|
import { u as SHADER_UNIFORM_TYPES } from "./shader-declaration-5q__jycG.js";
|
|
3
3
|
//#region src/render/material-plugin.ts
|
|
4
4
|
/**
|
|
@@ -281,4 +281,4 @@ function assertUniformType(plugin, binding, type) {
|
|
|
281
281
|
//#endregion
|
|
282
282
|
export { defineMaterialPlugin as a, MATERIAL_PLUGIN_SAMPLER_BUDGET as i, MATERIAL_PLUGIN_DEFAULT_PRIORITY as n, isLiteMaterialPluginPoint as o, MATERIAL_PLUGIN_RESERVED_NAMES as r, uniformComponentCount as s, LITE_MATERIAL_PLUGIN_POINTS as t };
|
|
283
283
|
|
|
284
|
-
//# sourceMappingURL=material-plugin-
|
|
284
|
+
//# sourceMappingURL=material-plugin-CiAmriQ_.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"material-plugin-B-hartHR.js","names":[],"sources":["../src/render/material-plugin.ts"],"sourcesContent":["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"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AEF,IAAI,+BAA+B,SAAS,OAAO,GACjD,MAAM,IAAI,YACR,cAAc,sBACd,GAAG,OAAO,YAAY,QAAQ,kEAC9B;EAAE,SAAS;GAAE;GAAQ,MAAM;EAAQ;EAAG,MAAM;CAAiE,CAC/G;CAEF,IAAI,KAAK,IAAI,OAAO,GAClB,MAAM,IAAI,YAAY,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
|
+
{"version":3,"file":"material-plugin-CiAmriQ_.js","names":[],"sources":["../src/render/material-plugin.ts"],"sourcesContent":["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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,8BAA8B;CACzC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;AAcA,MAAa,mCAAmC;;;;;;;;;;;;;;AAehD,MAAa,iCAAiC;;;;;;;;;;;;;;AAe9C,MAAa,iCAAoD,OAAO,OAAO;CAE7E;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;AACF,CAAC;;AAyCD,MAAM,aAAa;;AAGnB,MAAM,cAAc;;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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,4 +1,4 @@
|
|
|
1
|
-
import { M as setOwnJsonProperty, j as asJsonObject } from "./prefab-overrides-
|
|
1
|
+
import { M as setOwnJsonProperty, j as asJsonObject } from "./prefab-overrides-DT-wHHAJ.js";
|
|
2
2
|
//#region src/render/post-effect.ts
|
|
3
3
|
/**
|
|
4
4
|
* What a `PostProcessStack` needs to describe a custom `// @ignifx post` effect: its settings record,
|
|
@@ -126,4 +126,4 @@ function postEffectValuesCodec() {
|
|
|
126
126
|
//#endregion
|
|
127
127
|
export { postEffectValuesCodec as a, declaredTextureBinding as i, POST_EFFECT_FUNCTION as n, customEffect as r, POST_EFFECT_BUILTIN_UNIFORMS as t };
|
|
128
128
|
|
|
129
|
-
//# sourceMappingURL=post-effect-
|
|
129
|
+
//# sourceMappingURL=post-effect-CQnlX1RH.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"post-effect-
|
|
1
|
+
{"version":3,"file":"post-effect-CQnlX1RH.js","names":[],"sources":["../src/render/post-effect.ts"],"sourcesContent":["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 };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuBA,MAAa,uBAAuB;;;;;;;;;;;;AAapC,MAAa,+BACX,OAAO,OAAO;CACZ;EAAE,MAAM;EA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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-B8ByiSfJ.js";
|
|
2
|
+
import { i as declaredTextureBinding, n as POST_EFFECT_FUNCTION, t as POST_EFFECT_BUILTIN_UNIFORMS } from "./post-effect-CQnlX1RH.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-C_7HTHZy.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"post-effect-compiler-Bps8QbiJ.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;GAAE,MAAM,OAAO;GAAS,QAAQ;GAAgB,MAAM,OAAO,YAAY;EAAK;EACvF,MAAM;CACR,CACF;CAEF,IAAI,CAAC,IAAI,OAAO,gCAA2C,GAAG,CAAC,CAAC,KAAK,OAAO,MAAM,GA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AAS;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-C_7HTHZy.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;GAAE,MAAM,OAAO;GAAS,QAAQ;GAAgB,MAAM,OAAO,YAAY;EAAK;EACvF,MAAM;CACR,CACF;CAEF,IAAI,CAAC,IAAI,OAAO,gCAA2C,GAAG,CAAC,CAAC,KAAK,OAAO,MAAM,GAChF,MAAM,IAAI,YACR,cAAc,oBACd,GAAG,OAAO,QAAQ,eAAe,qBAAqB,aACtD;EACE,SAAS;GAAE,OAAO,OAAO;GAAS,MAAM;EAAqB;EAC7D,MAAM,UAAU,qBAAqB;CACvC,CACF;CAEF,MAAM,WAAW,OAAO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