@ignifx/core 0.21.0 → 0.21.1
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/README.md +22 -0
- package/dist/{agx-tone-mapping-Cgt844j6.js → agx-tone-mapping-CCdGk_ly.js} +2 -2
- package/dist/agx-tone-mapping-CCdGk_ly.js.map +1 -0
- package/dist/auto-exposure-uzPn0beO.js.map +1 -1
- package/dist/{bloom-hdr-CLtQj-oY.js → bloom-hdr-xPwkIdHG.js} +5 -6
- package/dist/bloom-hdr-xPwkIdHG.js.map +1 -0
- package/dist/contact-shadows-T523EXaP.js.map +1 -1
- package/dist/effect-task-CMbuO6Kb.js.map +1 -1
- package/dist/{environment-Bf4aphSb.js → environment-7fJbN402.js} +2 -2
- package/dist/{environment-Bf4aphSb.js.map → environment-7fJbN402.js.map} +1 -1
- package/dist/{gtao-Bpu5-0Ne.js → gtao-BmdrXXJz.js} +10 -11
- package/dist/gtao-BmdrXXJz.js.map +1 -0
- package/dist/{hdr-output-DBQwMphy.js → hdr-output-_2TU-jWy.js} +8 -8
- package/dist/hdr-output-_2TU-jWy.js.map +1 -0
- package/dist/index.d.ts +40 -42
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +104 -108
- package/dist/index.js.map +1 -1
- package/dist/{instanced-mesh-instance-B-fXKSrY.js → instanced-mesh-instance-BLdAJTj8.js} +3 -3
- package/dist/instanced-mesh-instance-BLdAJTj8.js.map +1 -0
- package/dist/{light-probe-asset-BqfSrJe9.js → light-probe-asset-DGNIwKNb.js} +2 -2
- package/dist/light-probe-asset-DGNIwKNb.js.map +1 -0
- package/dist/{light-probes-DDojYajw.js → light-probes-C8jharz9.js} +6 -6
- package/dist/light-probes-C8jharz9.js.map +1 -0
- package/dist/lightmaps-BUUIIkt9.js.map +1 -1
- package/dist/material-myMbl9mW.js.map +1 -1
- package/dist/{material-plugin-DapJNj04.js → material-plugin-BBxIy6eo.js} +4 -4
- package/dist/material-plugin-BBxIy6eo.js.map +1 -0
- package/dist/{overlay-CjVgsfrm.js → overlay-DokHzP6_.js} +2 -3
- package/dist/overlay-DokHzP6_.js.map +1 -0
- package/dist/{post-effect-Cu3Enpz7.js → post-effect-DEZD-r0I.js} +3 -3
- package/dist/post-effect-DEZD-r0I.js.map +1 -0
- package/dist/{post-effect-compiler-cCq9lcHt.js → post-effect-compiler-unDD3hod.js} +4 -4
- package/dist/post-effect-compiler-unDD3hod.js.map +1 -0
- package/dist/{prefab-overrides-C2GsgOQc.js → prefab-overrides-Bb7jVm7A.js} +3 -3
- package/dist/prefab-overrides-Bb7jVm7A.js.map +1 -0
- package/dist/{prefab-overrides-htDc_5Po.d.ts → prefab-overrides-DwrPDVVt.d.ts} +61 -63
- package/dist/{prefab-overrides-htDc_5Po.d.ts.map → prefab-overrides-DwrPDVVt.d.ts.map} +1 -1
- package/dist/prefab.d.ts +1 -1
- package/dist/prefab.js +1 -1
- package/dist/{reflection-probe-QkD1Fo_d.js → reflection-probe-C2jcreI1.js} +5 -5
- package/dist/reflection-probe-C2jcreI1.js.map +1 -0
- package/dist/{reflection-probes-CAzSuqf8.js → reflection-probes-BMVQfbhm.js} +10 -10
- package/dist/reflection-probes-BMVQfbhm.js.map +1 -0
- package/dist/{render-path-D11i_7X8.js → render-path-CWXHrRa2.js} +2 -2
- package/dist/render-path-CWXHrRa2.js.map +1 -0
- package/dist/{scene-color-passes-B93qTOka.js → scene-color-passes-DgXJ45Ql.js} +2 -2
- package/dist/scene-color-passes-DgXJ45Ql.js.map +1 -0
- package/dist/{scene-inputs-BxGOsnIZ.js → scene-inputs-_0j2Hi6L.js} +9 -8
- package/dist/scene-inputs-_0j2Hi6L.js.map +1 -0
- package/dist/{shader-declaration-5q__jycG.js → shader-declaration-BGprFBLq.js} +4 -4
- package/dist/shader-declaration-BGprFBLq.js.map +1 -0
- package/dist/{shader-material-TM4f8eKA.js → shader-material-C9sYMGWw.js} +8 -9
- package/dist/shader-material-C9sYMGWw.js.map +1 -0
- package/dist/{shader-material-CJIDFvSb.js → shader-material-vmkJ25II.js} +3 -3
- package/dist/shader-material-vmkJ25II.js.map +1 -0
- package/dist/{shader-pragma-ljmAbVc2.js → shader-pragma-D0MjCOIg.js} +3 -3
- package/dist/shader-pragma-D0MjCOIg.js.map +1 -0
- package/dist/ssgi-DSnhqotl.js.map +1 -1
- package/dist/{surface-shader-rpPpeosD.js → surface-shader-BfADq9Wx.js} +6 -6
- package/dist/surface-shader-BfADq9Wx.js.map +1 -0
- package/dist/{taa-BwBZLy11.js → taa-nxVA78Ur.js} +5 -6
- package/dist/taa-nxVA78Ur.js.map +1 -0
- package/dist/vec3-2C3LBZnt.js.map +1 -1
- package/package.json +1 -1
- package/dist/agx-tone-mapping-Cgt844j6.js.map +0 -1
- package/dist/bloom-hdr-CLtQj-oY.js.map +0 -1
- package/dist/gtao-Bpu5-0Ne.js.map +0 -1
- package/dist/hdr-output-DBQwMphy.js.map +0 -1
- package/dist/instanced-mesh-instance-B-fXKSrY.js.map +0 -1
- package/dist/light-probe-asset-BqfSrJe9.js.map +0 -1
- package/dist/light-probes-DDojYajw.js.map +0 -1
- package/dist/material-plugin-DapJNj04.js.map +0 -1
- package/dist/overlay-CjVgsfrm.js.map +0 -1
- package/dist/post-effect-Cu3Enpz7.js.map +0 -1
- package/dist/post-effect-compiler-cCq9lcHt.js.map +0 -1
- package/dist/prefab-overrides-C2GsgOQc.js.map +0 -1
- package/dist/reflection-probe-QkD1Fo_d.js.map +0 -1
- package/dist/reflection-probes-CAzSuqf8.js.map +0 -1
- package/dist/render-path-D11i_7X8.js.map +0 -1
- package/dist/scene-color-passes-B93qTOka.js.map +0 -1
- package/dist/scene-inputs-BxGOsnIZ.js.map +0 -1
- package/dist/shader-declaration-5q__jycG.js.map +0 -1
- package/dist/shader-material-CJIDFvSb.js.map +0 -1
- package/dist/shader-material-TM4f8eKA.js.map +0 -1
- package/dist/shader-pragma-ljmAbVc2.js.map +0 -1
- package/dist/surface-shader-rpPpeosD.js.map +0 -1
- package/dist/taa-BwBZLy11.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"instanced-mesh-instance-B-fXKSrY.js","names":["setThinInstances","setThinInstanceCount","flushThinInstances","setThinInstanceColors","enableThinInstanceGpuCulling","setThinInstanceCullBoundsPad","enableThinInstanceWorldBounds","enableThinInstanceDynamicDrawCount","setThinInstanceLodPartner","clearThinInstanceLodPartner"],"sources":["../src/lite/gpu/thin-instances.ts","../src/render/gpu/instanced-mesh-instance.ts"],"sourcesContent":["import {\n clearThinInstanceLodPartner as liteClearThinInstanceLodPartner,\n enableThinInstanceDynamicDrawCount as liteEnableThinInstanceDynamicDrawCount,\n enableThinInstanceGpuCulling as liteEnableThinInstanceGpuCulling,\n enableThinInstanceWorldBounds as liteEnableThinInstanceWorldBounds,\n flushThinInstances as liteFlushThinInstances,\n setThinInstanceColors as liteSetThinInstanceColors,\n setThinInstanceCount as liteSetThinInstanceCount,\n setThinInstanceCullBoundsPad as liteSetThinInstanceCullBoundsPad,\n setThinInstanceDrawCount as liteSetThinInstanceDrawCount,\n setThinInstanceLodPartner as liteSetThinInstanceLodPartner,\n setThinInstances as liteSetThinInstances,\n} from \"@babylonjs/lite\";\nimport type { Mesh } from \"@babylonjs/lite\";\n\n/**\n * Thin-instance half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §2.3,\n * `docs/plan/2026-09-terrain-particles-shaders.md` §3.5). Everything here is `@internal` and needs a\n * WebGPU device, so the browser project is what covers it.\n *\n * Lite fixes the order these must be called in, and both the culling opt-in and the LOD pairing only\n * take effect through the renderable `registerScene` compiles:\n *\n * 1. {@link setThinInstances} — its `count` argument becomes `_capacity`, and the GPU buffer is\n * sized `_capacity * 64` bytes for the life of the mesh, so pass the **capacity** here once and\n * lower the active count with {@link setThinInstanceCount} straight afterwards.\n * 2. {@link enableThinInstanceWorldBounds} — gives the scene AABB the cloud rather than the\n * prototype. It does not fix a shadow frustum: `computeDirectionalLightMatrix` reads\n * `boundMin`/`boundMax` directly (`lib/shadow/shadow-base.js` 54).\n * 3. {@link enableThinInstanceGpuCulling} — compute-based, opaque only.\n * 4. {@link enableThinInstanceDynamicDrawCount} — indirect draw arguments, so a later count change\n * keeps the cached bundle valid.\n * 5. {@link setThinInstanceLodPartner} — needs both meshes instanced already and stamps both\n * `_clone`, so neither can be cloned afterwards.\n * 6. `addMeshToScene`, and only then `registerScene`.\n *\n * Moving instances costs three different amounts (`lib/mesh/thin-instance.js`):\n * {@link flushThinInstances} re-uploads the whole active range and is the only sub-range-free path\n * Lite exposes; {@link setThinInstanceCount} re-uploads as well; {@link setThinInstanceDrawCount}\n * uploads nothing but throws until the pool has completed one GPU synchronisation, which is private\n * state — {@link trySetThinInstanceDrawCount} asks by trying.\n */\n\n/**\n * Points a mesh at a matrix slab and fixes its capacity.\n *\n * @remarks\n * The `capacity` argument is written straight to Lite's `_capacity`, which sizes the GPU buffer\n * (`_capacity * 64` bytes) once and for good. Only the first `count` matrices are ever read from\n * `matrices`, and Lite clamps its dirty range to the active count\n * (`lib/mesh/thin-instance-gpu.js`), so a slab shorter than `capacity * 16` floats is safe as long\n * as the active count is lowered with {@link setThinInstanceCount} before the next frame.\n *\n * Lite keeps the array by reference and never copies it: the caller owns it, and mutating it is the\n * intended way to move instances, followed by {@link flushThinInstances}.\n *\n * @param mesh - The mesh to instance.\n * @param matrices - 16 floats per instance, column-major, caller-owned.\n * @param capacity - The largest instance count this mesh will ever draw.\n *\n * @internal\n */\nexport function setThinInstances(mesh: Mesh, matrices: Float32Array, capacity: number): void {\n liteSetThinInstances(mesh, matrices, capacity);\n}\n\n/**\n * Sets how many instances draw, re-uploading the active range.\n *\n * @remarks\n * Prefer {@link trySetThinInstanceDrawCount} for a per-frame change: this one marks `[0, count)`\n * dirty as well, so it costs a `count * 64`-byte upload.\n *\n * @param mesh - The instanced mesh.\n * @param count - The active count, at most the capacity.\n *\n * @internal\n */\nexport function setThinInstanceCount(mesh: Mesh, count: number): void {\n liteSetThinInstanceCount(mesh, count);\n}\n\n/**\n * Sets how many instances draw without re-uploading anything, when Lite accepts it.\n *\n * @remarks\n * Lite requires the pool to have completed one full-capacity GPU synchronisation first and throws\n * otherwise (`lib/mesh/thin-instance.js`, `ThrowLiteError(369)`); the state it checks — the matrix\n * buffer's existence and its version — is private, so the only way to ask is to call. The throw\n * happens before anything is mutated, so a refusal leaves the mesh untouched and the caller can\n * fall back to {@link setThinInstanceCount}.\n *\n * @param mesh - The instanced mesh.\n * @param count - The active count, at most the capacity.\n * @returns `true` when the count was changed, `false` when Lite is not ready for a bare count\n * change yet.\n *\n * @internal\n */\nexport function trySetThinInstanceDrawCount(mesh: Mesh, count: number): boolean {\n try {\n liteSetThinInstanceDrawCount(mesh, count);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Marks the whole active matrix range dirty, after the caller mutated the slab in place.\n *\n * @param mesh - The instanced mesh.\n *\n * @internal\n */\nexport function flushThinInstances(mesh: Mesh): void {\n liteFlushThinInstances(mesh);\n}\n\n/**\n * Installs, replaces, or removes the per-instance RGBA colours.\n *\n * @remarks\n * Lite exports no way to *remove* colours: `setThinInstanceColors` only assigns, and the colour\n * version counters that drive the upload are private. `ThinInstanceData.colors` is declared\n * optional and mutable (`index.d.ts` 12985), so clearing is a direct field write —\n * which is enough, because `syncThinInstanceGpuData` skips the colour upload entirely while\n * `colors` is null, and the renderable rebuild the caller triggers is what drops\n * `useThinInstanceColors` from the compiled pipeline.\n *\n * @param mesh - The instanced mesh.\n * @param colors - Four floats per instance (linear RGBA), or `null` to stop reading colours.\n *\n * @internal\n */\nexport function setThinInstanceColors(mesh: Mesh, colors: Float32Array | null): void {\n if (colors !== null) {\n liteSetThinInstanceColors(mesh, colors);\n return;\n }\n const data = mesh.thinInstances;\n if (data !== null && data !== undefined) {\n data.colors = null;\n }\n}\n\n/**\n * Turns compute-based GPU frustum culling on or off for an instanced mesh.\n *\n * @remarks\n * Opaque meshes only, and it must run after {@link setThinInstances} and before the scene is\n * registered.\n *\n * @param mesh - The instanced mesh.\n * @param enabled - Whether the culling compute pass runs.\n *\n * @internal\n */\nexport function enableThinInstanceGpuCulling(mesh: Mesh, enabled: boolean): void {\n liteEnableThinInstanceGpuCulling(mesh, enabled);\n}\n\n/**\n * Grows every instance's GPU-culling sphere by a world-space distance.\n *\n * @remarks\n * The culler builds each sphere from the prototype's vertices (`lib/mesh/thin-instance-gpu-culling.js`\n * 426), so a vertex stage that moves an instance outside it gets the instance culled while it is\n * still on screen. Lite reads the pad on every culled pass (`index.d.ts` 11232), so it can change\n * live. Needs {@link setThinInstances} first.\n *\n * @param mesh - The instanced mesh that owns the culling pass.\n * @param pad - The extra radius in world units; `0` is the exact sphere.\n *\n * @internal\n */\nexport function setThinInstanceCullBoundsPad(mesh: Mesh, pad: number): void {\n liteSetThinInstanceCullBoundsPad(mesh, pad);\n}\n\n/**\n * Makes a mesh's world bounds the union of its instances' boxes rather than the prototype's own.\n *\n * @remarks\n * The hook it installs is `O(count)` per bounds computation, and it clamps to\n * `matrices.length / 16`, so a short slab cannot walk off the end. It is read by\n * `expandWorldAabbForMesh` — the scene camera's extent and PBR's scene-size probe — and **not** by\n * the directional shadow fit; see the module note.\n *\n * @param mesh - The instanced mesh.\n *\n * @internal\n */\nexport function enableThinInstanceWorldBounds(mesh: Mesh): void {\n liteEnableThinInstanceWorldBounds(mesh);\n}\n\n/**\n * Opts a fixed-capacity pool into indirect draw arguments, so a later count change keeps the\n * cached render bundle valid.\n *\n * @param mesh - The instanced mesh.\n *\n * @internal\n */\nexport function enableThinInstanceDynamicDrawCount(mesh: Mesh): void {\n liteEnableThinInstanceDynamicDrawCount(mesh);\n}\n\n/**\n * Where a LOD pairing switches, and how softly.\n *\n * @internal\n */\nexport interface ThinInstanceLodOptions {\n /** The camera distance, in world units, at which an in-frustum instance switches to the partner. */\n readonly distance: number;\n /** The width of the per-instance threshold dither window centred on `distance`; `0` is a hard cut. */\n readonly band: number;\n}\n\n/**\n * Pairs a GPU-culled instanced mesh with a lower-detail partner.\n *\n * @remarks\n * Both meshes must already carry thin instances, and the partner may reference the very same matrix\n * slab. While paired the partner draws **only** the far bucket, and the pairing switches its own\n * GPU culling on. Lite refuses the pairing when either mesh has more than one thin-instance owner,\n * when the partner is already paired, or when the partner carries colours the full mesh does not\n * (`ThrowLiteError(375)`, `(377)`, `(379)`). Calling it again with the same pair re-sets `distance`\n * and `band` live.\n *\n * @param fullMesh - The near mesh, which owns the culling pass.\n * @param lodMesh - The far mesh.\n * @param options - Where the switch happens, and how softly.\n *\n * @internal\n */\nexport function setThinInstanceLodPartner(fullMesh: Mesh, lodMesh: Mesh, options: ThinInstanceLodOptions): void {\n liteSetThinInstanceLodPartner(fullMesh, lodMesh, { distance: options.distance, band: options.band });\n}\n\n/**\n * Dissolves a LOD pairing, returning both meshes to independent rendering.\n *\n * @remarks\n * A no-op when the mesh is not paired, so it is safe on the teardown path.\n *\n * @param fullMesh - The near mesh of the pair.\n *\n * @internal\n */\nexport function clearThinInstanceLodPartner(fullMesh: Mesh): void {\n liteClearThinInstanceLodPartner(fullMesh);\n}\n\n/**\n * How many instances a mesh is currently drawing, as Lite sees it.\n *\n * @remarks\n * The browser tests assert against Lite's own state rather than against the component's copy of it,\n * which is the only way to prove the two agree.\n *\n * @param mesh - The mesh to read.\n * @returns The active count, or `0` when the mesh carries no thin instances.\n *\n * @internal\n */\nexport function thinInstanceCount(mesh: Mesh): number {\n return mesh.thinInstances?.count ?? 0;\n}\n","import {\n addMeshToScene,\n cloneMeshUnderNode,\n detachMeshBounds,\n removeMeshFromScene,\n setMeshBounds,\n setMeshId,\n setMeshMaterial,\n setMeshPickable,\n setMeshReceiveShadows,\n setMeshRenderOrder,\n setMeshSubtreeVisible,\n} from \"../../lite/gpu/mesh.js\";\nimport {\n clearThinInstanceLodPartner,\n enableThinInstanceDynamicDrawCount,\n enableThinInstanceGpuCulling,\n enableThinInstanceWorldBounds,\n flushThinInstances,\n setThinInstanceColors,\n setThinInstanceCount,\n setThinInstanceCullBoundsPad,\n setThinInstanceLodPartner,\n setThinInstances,\n trySetThinInstanceDrawCount,\n} from \"../../lite/gpu/thin-instances.js\";\nimport { tagNode } from \"../../lite/node.js\";\nimport { Vec3 } from \"../../math/vec3.js\";\nimport type { LiteMesh } from \"../../lite/gpu/mesh.js\";\nimport type { LiteMaterial } from \"../../lite/material.js\";\nimport type { LiteSceneNode, NodeTag } from \"../../lite/node.js\";\nimport type { LiteScene } from \"../../lite/scene.js\";\nimport type { Transform } from \"../../transform/transform.js\";\n\n/**\n * One `InstancedMeshRenderer`'s near mesh and its optional LOD partner, and everything that writes\n * to them (`docs/plan/2026-09-terrain-particles-shaders.md` §3.5).\n *\n * Every line needs a WebGPU device, which is why it sits in `src/render/gpu/` — excluded from the\n * Node coverage floor and measured by the browser project — and why the component reaches it through\n * a dynamic `import()` (`../instanced-mesh-support.ts`).\n *\n * `capacity`, `gpuCulling` and the partner's identity are constructor arguments rather than `apply*`\n * methods because Lite fixes all three at `registerScene`; `distance` and `band` may be re-set live\n * by calling the pairing again. Both meshes share one matrix slab, which the pairing requires: it\n * compacts the near mesh's culling output into two buckets drawn from the same matrices.\n *\n * Bounds are the one thing an instanced caster needs that a plain mesh does not.\n * `computeDirectionalLightMatrix` composes `mesh.worldMatrix × mesh.boundMin/boundMax` directly\n * (`lib/shadow/shadow-base.js` 54) and never consults the `_expandWorldBounds` hook\n * `enableThinInstanceWorldBounds` installs, so a cloud left at its prototype's box casts nothing\n * (measured on SwiftShader, 2026-09-08). {@link InstancedMeshInstance.applyBounds} publishes the\n * union of the live placements instead; culling accuracy is unaffected because each instance's cull\n * sphere comes from the real vertices (`lib/mesh/thin-instance-gpu-culling.js` 426).\n */\n\n/** What the component remembers between uploads. Mutated in place, so a frame allocates nothing. */\nexport interface InstancedUploadState {\n /** The whole slab has to be re-pointed and re-uploaded. */\n isSlabDirty: boolean;\n /** The caller mutated the slab in place, so the active range has to be re-uploaded. */\n isRangeDirty: boolean;\n /** The count the meshes were last told about. */\n appliedCount: number;\n /** The capacity the meshes were built with. */\n appliedCapacity: number;\n /** Whether the union bounds have been published at least once. */\n hasAppliedBounds: boolean;\n /** Whether the last upload carried a colour slab. */\n hadColors: boolean;\n}\n\n/** The LOD switch the component declares, as much of it as the adapter reads. */\nexport interface InstancedLodFields {\n /** The camera distance at which an instance switches to the partner. */\n readonly distance: number;\n /** The width of the per-instance dither window. */\n readonly band: number;\n}\n\n/** The LOD partner an instance is built with. */\nexport interface InstancedLodConfig {\n /** The coarse template to clone. */\n readonly template: LiteMesh;\n /** The camera distance, in world units, at which an instance switches to the partner. */\n readonly distance: number;\n /** The width of the per-instance dither window centred on `distance`. */\n readonly band: number;\n}\n\n/** The settings Lite fixes when the meshes are built. */\nexport interface InstancedMeshSettings {\n /** The largest instance count the meshes will ever draw. */\n readonly capacity: number;\n /** Whether the compute culling pass runs. */\n readonly gpuCulling: boolean;\n /** The LOD partner, or `null`. */\n readonly lod: InstancedLodConfig | null;\n}\n\n/**\n * A live instanced mesh, and its LOD partner, in a scene.\n *\n * @internal\n */\nexport class InstancedMeshInstance {\n /** The cloned near mesh, parented under the entity's node. */\n readonly clone: LiteSceneNode;\n\n readonly #lod: LiteSceneNode | null;\n\n #material: LiteMaterial;\n\n #receiveShadows: boolean | null = null;\n\n #renderOrder = Number.NaN;\n\n #pickable: boolean | null = null;\n\n #visible = false;\n\n #lodDistance: number;\n\n #lodBand: number;\n\n readonly #nearBox: Float64Array;\n\n readonly #lodBox: Float64Array | null;\n\n readonly #union = new Float64Array(6);\n\n /** The world-space displacement the culling pad and the bounds were last widened by. */\n #displacement = 0;\n\n /** The same displacement in object units, per axis, as the published bounds carry it. */\n readonly #margin = new Vec3();\n\n /** Scratch for the entity's world scale. */\n readonly #scale = new Vec3();\n\n /**\n * Clones the templates, gives them thin instances, applies the baked settings in Lite's required\n * order, and adds them to the scene.\n *\n * @param scene - The render scene.\n * @param template - The near mesh's template.\n * @param parent - The entity's transform node.\n * @param tag - The owning entity and component, for picking.\n * @param meshId - The string id Lite's light include/exclude sets match on.\n * @param material - The material both meshes draw with. Assigned **before** the meshes join the\n * scene, for the reason `MeshInstance`'s constructor records: `addToScene` buckets a mesh by its\n * material's build group.\n * @param settings - Capacity, GPU culling, and the LOD pairing.\n * @param matrices - The matrix slab, caller-owned and never copied.\n * @param count - How many instances draw.\n * @param colors - Four floats per instance, or `null`.\n */\n constructor(\n scene: LiteScene,\n template: LiteMesh,\n parent: LiteSceneNode,\n tag: NodeTag,\n meshId: string,\n material: LiteMaterial,\n settings: InstancedMeshSettings,\n matrices: Float32Array,\n count: number,\n colors: Float32Array | null,\n ) {\n const clone = cloneMeshUnderNode(template, parent);\n tagNode(clone, tag);\n const mesh = asMesh(clone);\n setMeshId(mesh, meshId);\n setMeshMaterial(mesh, material);\n // A clone shares the template's bound arrays, and `applyBounds` mutates them in place.\n detachMeshBounds(mesh);\n this.#nearBox = readBox(mesh);\n installThinInstances(mesh, settings.capacity, matrices, count, colors);\n enableThinInstanceGpuCulling(mesh, settings.gpuCulling);\n enableThinInstanceDynamicDrawCount(mesh);\n\n const lodConfig = settings.lod;\n let lodClone: LiteSceneNode | null = null;\n let lodBox: Float64Array | null = null;\n if (lodConfig !== null) {\n lodClone = cloneMeshUnderNode(lodConfig.template, parent);\n tagNode(lodClone, tag);\n const lodMesh = asMesh(lodClone);\n setMeshId(lodMesh, `${meshId}#lod`);\n setMeshMaterial(lodMesh, material);\n detachMeshBounds(lodMesh);\n lodBox = readBox(lodMesh);\n installThinInstances(lodMesh, settings.capacity, matrices, count, colors);\n setThinInstanceLodPartner(mesh, lodMesh, { distance: lodConfig.distance, band: lodConfig.band });\n }\n this.#lodBox = lodBox;\n\n this.#material = material;\n this.#lodDistance = lodConfig?.distance ?? 0;\n this.#lodBand = lodConfig?.band ?? 0;\n // Hidden until the first `applyVisible`, so a renderer on an inactive entity never flashes.\n setMeshSubtreeVisible(clone, false);\n addMeshToScene(scene, clone);\n if (lodClone !== null) {\n setMeshSubtreeVisible(lodClone, false);\n addMeshToScene(scene, lodClone);\n }\n this.clone = clone;\n this.#lod = lodClone;\n }\n\n /**\n * Whether the meshes are currently drawn.\n *\n * @returns `true` when Lite's `visible` is set on them.\n */\n get isVisible(): boolean {\n return this.#visible;\n }\n\n /**\n * The near mesh.\n *\n * @returns The clone, typed as a mesh.\n */\n get mesh(): LiteMesh {\n return asMesh(this.clone);\n }\n\n /**\n * The LOD partner.\n *\n * @returns The partner clone, or `null` when the renderer declares no LOD.\n */\n get lodMesh(): LiteMesh | null {\n const lod = this.#lod;\n return lod === null ? null : asMesh(lod);\n }\n\n /**\n * Assigns the material to both meshes, when it changed.\n *\n * @param material - The Lite material to draw with.\n */\n applyMaterial(material: LiteMaterial): void {\n if (material === this.#material) {\n return;\n }\n this.#material = material;\n setMeshMaterial(this.mesh, material);\n const lod = this.lodMesh;\n if (lod !== null) {\n setMeshMaterial(lod, material);\n }\n }\n\n /**\n * Writes the per-mesh flags that changed, to both meshes.\n *\n * @param receiveShadows - Whether shadow maps darken the meshes.\n * @param renderOrder - The sort key within the phase.\n * @param pickable - Whether picking considers the meshes at all.\n */\n applyFlags(receiveShadows: boolean, renderOrder: number, pickable: boolean): void {\n if (this.#receiveShadows !== receiveShadows) {\n this.#receiveShadows = receiveShadows;\n this.#eachMesh(setMeshReceiveShadows, receiveShadows);\n }\n if (this.#renderOrder !== renderOrder) {\n this.#renderOrder = renderOrder;\n this.#eachMesh(setMeshRenderOrder, renderOrder);\n }\n if (this.#pickable !== pickable) {\n this.#pickable = pickable;\n this.#eachMesh(setMeshPickable, pickable);\n }\n }\n\n /**\n * Re-sets the LOD switch distance and dither band, when either changed.\n *\n * @param distance - The camera distance at which an instance switches to the partner.\n * @param band - The width of the per-instance dither window centred on `distance`.\n */\n applyLod(distance: number, band: number): void {\n const lod = this.lodMesh;\n if (lod === null || (distance === this.#lodDistance && band === this.#lodBand)) {\n return;\n }\n this.#lodDistance = distance;\n this.#lodBand = band;\n setThinInstanceLodPartner(this.mesh, lod, { distance, band });\n }\n\n /**\n * Shows or hides both meshes, when the state changed.\n *\n * @param visible - `entity.activeInHierarchy && component.enabled`.\n */\n applyVisible(visible: boolean): void {\n if (visible === this.#visible) {\n return;\n }\n this.#visible = visible;\n setMeshSubtreeVisible(this.clone, visible);\n const lod = this.#lod;\n if (lod !== null) {\n setMeshSubtreeVisible(lod, visible);\n }\n }\n\n /**\n * Re-points both meshes at a matrix slab and re-uploads the active range.\n *\n * @param capacity - The capacity the meshes were built with; re-stating it keeps `_capacity`\n * unchanged, which is what stops Lite from re-creating the GPU buffer.\n * @param matrices - The slab, caller-owned.\n * @param count - How many instances draw.\n * @param colors - Four floats per instance, or `null`.\n */\n applySlab(capacity: number, matrices: Float32Array, count: number, colors: Float32Array | null): void {\n installThinInstances(this.mesh, capacity, matrices, count, colors);\n const lod = this.lodMesh;\n if (lod !== null) {\n installThinInstances(lod, capacity, matrices, count, colors);\n }\n }\n\n /**\n * Changes how many instances draw, by the cheapest route Lite accepts.\n *\n * @param count - The active count, at most the capacity.\n */\n applyCount(count: number): void {\n applyMeshCount(this.mesh, count);\n const lod = this.lodMesh;\n if (lod !== null) {\n applyMeshCount(lod, count);\n }\n }\n\n /**\n * Marks the whole active range dirty, after the caller mutated the slab in place.\n *\n * @param colors - The colour slab, when the renderer has one, so its own dirty range moves too.\n */\n flush(colors: Float32Array | null): void {\n flushThinInstances(this.mesh);\n const lod = this.lodMesh;\n if (lod !== null) {\n flushThinInstances(lod);\n }\n if (colors !== null) {\n setThinInstanceColors(this.mesh, colors);\n if (lod !== null) {\n setThinInstanceColors(lod, colors);\n }\n }\n }\n\n /**\n * Publishes the union of the live instance placements as both meshes' object-local bounds, so a\n * directional light's shadow frustum is fitted to the cloud rather than to the prototype.\n *\n * @remarks\n * `O(count)`, allocation-free, and worth paying only for a caster — see the module note. A count\n * of zero restores the prototype's own box, so an empty cloud does not report an infinite one.\n *\n * @param matrices - The live matrix slab.\n * @param count - How many instances are drawn.\n */\n applyBounds(matrices: Float32Array, count: number): void {\n const near = this.#nearBox;\n const lodBox = this.#lodBox;\n const lod = this.lodMesh;\n const margin = this.#margin;\n if (count <= 0) {\n writeBox(this.mesh, near, margin);\n if (lod !== null && lodBox !== null) {\n writeBox(lod, lodBox, margin);\n }\n return;\n }\n const union = this.#union;\n unionOfPlacements(matrices, count, near, union);\n writeBox(this.mesh, union, margin);\n if (lod !== null && lodBox !== null) {\n unionOfPlacements(matrices, count, lodBox, union);\n writeBox(lod, union, margin);\n }\n }\n\n /**\n * Widens both meshes for a vertex stage that moves vertices up to `displacement` metres: the GPU\n * culler pads every instance's sphere, and the bounds published for a shadow frustum grow too.\n *\n * @remarks\n * The culling pad is world-space already. The bounds are object-local, so each axis is divided by\n * the entity's world scale along it. A change clears `state.hasAppliedBounds`, so the next\n * {@link InstancedMeshInstance.sync} re-publishes them.\n *\n * @param state - The component's upload state.\n * @param displacement - The material's displacement, in world metres.\n * @param transform - The entity's transform, whose world scale the meshes inherit.\n */\n applyDisplacement(state: InstancedUploadState, displacement: number, transform: Transform): void {\n if (displacement !== this.#displacement) {\n this.#displacement = displacement;\n // Only the near mesh runs the culling pass; the partner draws from its output.\n setThinInstanceCullBoundsPad(this.mesh, displacement);\n }\n const scale = this.#scale;\n if (displacement > 0) {\n transform.lossyScaleToRef(scale);\n }\n const x = objectMargin(displacement, scale.x);\n const y = objectMargin(displacement, scale.y);\n const z = objectMargin(displacement, scale.z);\n const margin = this.#margin;\n if (x !== margin.x || y !== margin.y || z !== margin.z) {\n margin.set(x, y, z);\n state.hasAppliedBounds = false;\n }\n }\n\n /**\n * Writes everything the component changed since the last frame onto both meshes.\n *\n * @param state - The component's upload state, mutated in place.\n * @param material - The material both meshes draw with.\n * @param receiveShadows - Whether shadow maps darken them.\n * @param renderOrder - The sort key within the phase.\n * @param pickable - Whether picking considers them.\n * @param lod - The LOD record, whose `distance` and `band` Lite re-applies live; `null` for none.\n * @param matrices - The caller-owned matrix slab.\n * @param count - How many instances draw.\n * @param colors - Four floats per instance, or `null`.\n * @param castShadows - Whether the union bounds have to be published for a shadow frustum.\n * @param visible - `entity.activeInHierarchy && component.enabled`.\n * @returns `true` when the compiled pipeline has to change, which only a colour slab arriving or\n * leaving does.\n */\n sync(\n state: InstancedUploadState,\n material: LiteMaterial,\n receiveShadows: boolean,\n renderOrder: number,\n pickable: boolean,\n lod: InstancedLodFields | null,\n matrices: Float32Array,\n count: number,\n colors: Float32Array | null,\n castShadows: boolean,\n visible: boolean,\n ): boolean {\n this.applyMaterial(material);\n this.applyFlags(receiveShadows, renderOrder, pickable);\n if (lod !== null) {\n this.applyLod(lod.distance, lod.band);\n }\n let renderablesChanged = false;\n let placementsMoved = false;\n if (state.isSlabDirty) {\n state.isSlabDirty = false;\n state.isRangeDirty = false;\n this.applySlab(state.appliedCapacity, matrices, count, colors);\n state.appliedCount = count;\n placementsMoved = true;\n const hasColors = colors !== null;\n renderablesChanged = hasColors !== state.hadColors;\n state.hadColors = hasColors;\n } else {\n if (state.isRangeDirty) {\n state.isRangeDirty = false;\n this.flush(colors);\n placementsMoved = true;\n }\n if (count !== state.appliedCount) {\n state.appliedCount = count;\n this.applyCount(count);\n placementsMoved = true;\n }\n }\n // Only a caster pays the `O(count)` bounds pass, and only in a frame whose placements moved.\n if (castShadows && (placementsMoved || !state.hasAppliedBounds)) {\n state.hasAppliedBounds = true;\n this.applyBounds(matrices, count);\n }\n this.applyVisible(visible);\n return renderablesChanged;\n }\n\n /**\n * Appends both meshes to a shadow caster list, when the renderer casts and they are drawn.\n *\n * @param castShadows - Whether the renderer casts.\n * @param out - The caster list being built.\n */\n collectCasters(castShadows: boolean, out: LiteMesh[]): void {\n if (!castShadows || !this.#visible) {\n return;\n }\n out.push(this.mesh);\n const lod = this.lodMesh;\n if (lod !== null) {\n out.push(lod);\n }\n }\n\n /**\n * Dissolves the LOD pairing and removes both meshes from the scene, releasing their share of the\n * templates' buffers.\n *\n * @param scene - The render scene.\n */\n destroy(scene: LiteScene): void {\n const lod = this.#lod;\n if (lod !== null) {\n clearThinInstanceLodPartner(this.mesh);\n removeMeshFromScene(scene, lod);\n }\n removeMeshFromScene(scene, this.clone);\n }\n\n /**\n * Runs a per-mesh Lite setter over the near mesh and the partner.\n *\n * @typeParam T - The setter's value type.\n * @param write - The adapter function to call.\n * @param value - What to write.\n */\n #eachMesh<T>(write: (mesh: LiteMesh, value: T) => void, value: T): void {\n write(this.mesh, value);\n const lod = this.lodMesh;\n if (lod !== null) {\n write(lod, value);\n }\n }\n}\n\n/**\n * Builds the live meshes, filling in the LOD pairing when both templates exist.\n *\n * @param scene - The render scene.\n * @param template - The near mesh's template.\n * @param lodTemplate - The coarse template, or `null`.\n * @param lod - The LOD record the component declares, or `null`.\n * @param parent - The entity's transform node.\n * @param tag - The owning entity and component, for picking.\n * @param meshId - The string id Lite's light include/exclude sets match on.\n * @param material - The material both meshes draw with.\n * @param capacity - The largest instance count the meshes will ever draw.\n * @param gpuCulling - Whether the compute culling pass runs.\n * @param matrices - The matrix slab.\n * @param count - How many instances draw.\n * @param colors - Four floats per instance, or `null`.\n * @returns The instance.\n *\n * @internal\n */\nexport function createInstancedMesh(\n scene: LiteScene,\n template: LiteMesh,\n lodTemplate: LiteMesh | null,\n lod: InstancedLodFields | null,\n parent: LiteSceneNode,\n tag: NodeTag,\n meshId: string,\n material: LiteMaterial,\n capacity: number,\n gpuCulling: boolean,\n matrices: Float32Array,\n count: number,\n colors: Float32Array | null,\n): InstancedMeshInstance {\n const pairing: InstancedLodConfig | null =\n lodTemplate === null || lod === null ? null : { template: lodTemplate, distance: lod.distance, band: lod.band };\n return new InstancedMeshInstance(\n scene,\n template,\n parent,\n tag,\n meshId,\n material,\n { capacity, gpuCulling, lod: pairing },\n matrices,\n count,\n colors,\n );\n}\n\n/**\n * Removes the meshes from the scene, when there are any.\n *\n * @param instance - The live meshes, or `null`.\n * @param scene - The render scene.\n * @returns `true` when something left the scene.\n *\n * @internal\n */\nexport function releaseInstancedMesh(instance: InstancedMeshInstance | null, scene: LiteScene): boolean {\n if (instance === null) {\n return false;\n }\n instance.destroy(scene);\n return true;\n}\n\n/**\n * Gives one mesh its thin instances in the order Lite requires, at a fixed capacity.\n *\n * @remarks\n * `setThinInstances` is handed the **capacity** so that `_capacity` — and the GPU buffer it sizes —\n * never moves; the active count is then lowered in the same breath, before any frame can read the\n * range in between (`src/lite/gpu/thin-instances.ts`).\n *\n * @param mesh - The mesh to instance.\n * @param capacity - The capacity to fix.\n * @param matrices - The slab, caller-owned.\n * @param count - How many instances draw.\n * @param colors - Four floats per instance, or `null`.\n */\nfunction installThinInstances(\n mesh: LiteMesh,\n capacity: number,\n matrices: Float32Array,\n count: number,\n colors: Float32Array | null,\n): void {\n setThinInstances(mesh, matrices, capacity);\n setThinInstanceCount(mesh, count);\n setThinInstanceColors(mesh, colors);\n enableThinInstanceWorldBounds(mesh);\n}\n\n/**\n * Changes one mesh's active count without re-uploading when Lite allows it, and with a re-upload\n * when it does not.\n *\n * @param mesh - The instanced mesh.\n * @param count - The active count.\n */\nfunction applyMeshCount(mesh: LiteMesh, count: number): void {\n if (!trySetThinInstanceDrawCount(mesh, count)) {\n setThinInstanceCount(mesh, count);\n }\n}\n\n/**\n * Reads a mesh's object-local box into six numbers.\n *\n * @remarks\n * A mesh built by any Lite factory carries bounds; the fallback half-metre cube is the same default\n * `computeDirectionalLightMatrix` uses for a mesh that does not\n * (`lib/shadow/shadow-base.js` 62).\n *\n * @param mesh - The mesh to read.\n * @returns `minX, minY, minZ, maxX, maxY, maxZ`.\n */\nfunction readBox(mesh: LiteMesh): Float64Array {\n const min = mesh.boundMin ?? [-0.5, -0.5, -0.5];\n const max = mesh.boundMax ?? [0.5, 0.5, 0.5];\n return Float64Array.of(min[0], min[1], min[2], max[0], max[1], max[2]);\n}\n\n/**\n * Writes a six-number box back onto a mesh, grown by a margin on every side.\n *\n * @param mesh - The mesh to re-bound.\n * @param box - `minX, minY, minZ, maxX, maxY, maxZ`.\n * @param margin - How far to grow each axis, in object units.\n */\nfunction writeBox(mesh: LiteMesh, box: Float64Array, margin: Vec3): void {\n setMeshBounds(\n mesh,\n (box[0] ?? 0) - margin.x,\n (box[1] ?? 0) - margin.y,\n (box[2] ?? 0) - margin.z,\n (box[3] ?? 0) + margin.x,\n (box[4] ?? 0) + margin.y,\n (box[5] ?? 0) + margin.z,\n );\n}\n\n/**\n * Converts a world-space margin into the object-space margin along one axis.\n *\n * @param margin - The margin, in world metres.\n * @param scale - The entity's world scale along the axis.\n * @returns The margin in object units; `0` for no margin or a collapsed axis.\n */\nfunction objectMargin(margin: number, scale: number): number {\n return margin > 0 && scale > 1e-9 ? margin / scale : 0;\n}\n\n/**\n * The axis-aligned union of a prototype box placed under every live instance matrix.\n *\n * @remarks\n * The same oriented-box-to-AABB composition Lite's own\n * `expandThinInstanceWorldBounds` uses, minus the world matrix — because `Mesh.boundMin`/`boundMax`\n * are documented to be **object-local**, the frame `worldMatrix` maps out of. Degenerate matrices\n * are skipped, exactly as Lite skips them, so a slot that has not been written yet does not drag\n * the box to the origin.\n *\n * @param matrices - The slab, 16 column-major floats per instance.\n * @param count - How many instances to consider.\n * @param box - The prototype's own box.\n * @param out - Receives `minX, minY, minZ, maxX, maxY, maxZ`.\n */\nfunction unionOfPlacements(matrices: Float32Array, count: number, box: Float64Array, out: Float64Array): void {\n const centreX = ((box[0] ?? 0) + (box[3] ?? 0)) * 0.5;\n const centreY = ((box[1] ?? 0) + (box[4] ?? 0)) * 0.5;\n const centreZ = ((box[2] ?? 0) + (box[5] ?? 0)) * 0.5;\n const extentX = ((box[3] ?? 0) - (box[0] ?? 0)) * 0.5;\n const extentY = ((box[4] ?? 0) - (box[1] ?? 0)) * 0.5;\n const extentZ = ((box[5] ?? 0) - (box[2] ?? 0)) * 0.5;\n out[0] = Number.POSITIVE_INFINITY;\n out[1] = Number.POSITIVE_INFINITY;\n out[2] = Number.POSITIVE_INFINITY;\n out[3] = Number.NEGATIVE_INFINITY;\n out[4] = Number.NEGATIVE_INFINITY;\n out[5] = Number.NEGATIVE_INFINITY;\n const usable = Math.min(count, Math.floor(matrices.length / 16));\n let placed = 0;\n for (let index = 0; index < usable; index += 1) {\n const base = index * 16;\n let scale = 0;\n for (let element = 0; element < 12; element += 1) {\n if (element % 4 !== 3) {\n scale += Math.abs(matrices[base + element] ?? 0);\n }\n }\n if (scale < 1e-9) {\n continue;\n }\n placed += 1;\n for (let row = 0; row < 3; row += 1) {\n const m0 = matrices[base + row] ?? 0;\n const m1 = matrices[base + 4 + row] ?? 0;\n const m2 = matrices[base + 8 + row] ?? 0;\n const centre = (matrices[base + 12 + row] ?? 0) + m0 * centreX + m1 * centreY + m2 * centreZ;\n const radius = Math.abs(m0) * extentX + Math.abs(m1) * extentY + Math.abs(m2) * extentZ;\n const low = centre - radius;\n const high = centre + radius;\n if (low < (out[row] ?? 0)) {\n out[row] = low;\n }\n if (high > (out[row + 3] ?? 0)) {\n out[row + 3] = high;\n }\n }\n }\n if (placed === 0) {\n out.set(box);\n }\n}\n\n/**\n * Narrows a cloned subtree root to a mesh.\n *\n * @remarks\n * The same boundary assertion `MeshInstance` makes, for the same reason: `cloneTransformNode` is\n * typed as returning the wider `SceneNode` because it also clones plain transform nodes, and the\n * clone of a mesh is a mesh (coding standards §5.2).\n *\n * @param node - The clone.\n * @returns The same object, typed as a mesh.\n */\nfunction asMesh(node: LiteSceneNode): LiteMesh {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- see the note above.\n return node as LiteMesh;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,SAAgBA,mBAAiB,MAAY,UAAwB,UAAwB;CAC3F,iBAAqB,MAAM,UAAU,QAAQ;AAC/C;;;;;;;;;;;;;AAcA,SAAgBC,uBAAqB,MAAY,OAAqB;CACpE,qBAAyB,MAAM,KAAK;AACtC;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,4BAA4B,MAAY,OAAwB;CAC9E,IAAI;EACF,yBAA6B,MAAM,KAAK;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AI,EAAE,IAAI,UAAU,KAAK,IAAI,EAAE,IAAI,UAAU,KAAK,IAAI,EAAE,IAAI;GAChF,MAAM,MAAM,SAAS;GACrB,MAAM,OAAO,SAAS;GACtB,IAAI,OAAO,IAAI,QAAQ,IACrB,IAAI,OAAO;GAEb,IAAI,QAAQ,IAAI,MAAM,MAAM,IAC1B,IAAI,MAAM,KAAK;EAEnB;CACF;CACA,IAAI,WAAW,GACb,IAAI,IAAI,GAAG;AAEf;;;;;;;;;;;;AAaA,SAAS,OAAO,MAA+B;CAE7C,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"light-probe-asset-BqfSrJe9.js","names":[],"sources":["../src/render/light-probe-asset.ts"],"sourcesContent":["import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { IgnifxError } from \"../errors/ignifx-error.js\";\nimport type { App } from \"../app/types.js\";\nimport type { AssetHandle } from \"../assets/types.js\";\nimport type { Vec3Like } from \"../math/types.js\";\n\n/**\n * Light probes (`docs/plan/2026-11-gi-phase-2-execution-plan.md`, step B2): a regular grid of baked\n * irradiance samples that a `LightProbeVolume` lights PBR materials with, in place of the scene\n * environment's diffuse light. Everything here is plain data and runs in Node.\n *\n * Each probe stores four RGB coefficients of first-order spherical harmonics, already convolved and\n * scaled the way Babylon Lite's environment harmonics are, so the diffuse light a white surface with\n * normal `n` receives is `c0 + c1·n.y + c2·n.z + c3·n.x` (Lite's `environmentIrradiance`, L1 part).\n */\n\n/**\n * The asset type light-probe grids are registered under.\n *\n * @public\n */\nexport const LIGHT_PROBE_ASSET_TYPE = \"lightprobes\";\n\n/**\n * The address extensions that select the light-probe loader.\n *\n * @public\n */\nexport const LIGHT_PROBE_FILE_EXTENSIONS: readonly string[] = Object.freeze([\".probes.json\"]);\n\n/**\n * The `format` header every `.probes.json` carries.\n *\n * @public\n */\nexport const LIGHT_PROBE_FILE_FORMAT = \"ignifx-probes\";\n\n/**\n * The `formatVersion` this engine reads and writes.\n *\n * @public\n */\nexport const LIGHT_PROBE_FORMAT_VERSION = 1;\n\n/** Floats per probe: four RGB coefficients. */\nconst FLOATS_PER_PROBE = 12;\n\n/** The largest grid side along X (the texture is four times as wide) and the largest Y·Z product. */\nconst MAX_X = 1024;\nconst MAX_YZ = 4096;\n\n/** The bounds that keep the generated shader constants valid 32-bit floats. */\nconst MAX_COORDINATE = 1e20;\nconst MIN_CELL = 1e-30;\n\n/**\n * A grid of light probes, as a `.probes.json` stores it.\n *\n * @remarks\n * Probe `(i, j, k)` sits at `origin + (i, j, k) · cellSize`. `coefficients` holds 12 floats per probe,\n * probes ordered X fastest, then Y, then Z (`index = i + countX·(j + countY·k)`); each probe's floats\n * are `c0.rgb, c1.rgb, c2.rgb, c3.rgb` in linear RGB (see the module remarks).\n *\n * @public\n */\nexport interface LightProbeData {\n /** The world position of probe `(0, 0, 0)`. */\n readonly origin: Vec3Like;\n /** The distance between neighbouring probes along each axis, in metres. */\n readonly cellSize: Vec3Like;\n /** How many probes along X, Y and Z; each at least 1. */\n readonly counts: { readonly x: number; readonly y: number; readonly z: number };\n /** 12 floats per probe, `countX · countY · countZ · 12` in all. */\n readonly coefficients: readonly number[];\n}\n\n/**\n * A loaded light-probe grid.\n *\n * @example\n * ```ts\n * const probes = await app.assets.loadAsync<LightProbeAsset>(\"lighting/hall.probes.json\");\n * world.createEntity(\"Probes\").addComponent(LightProbeVolume, { probes });\n * ```\n *\n * @beta\n */\nexport class LightProbeAsset {\n /** The type name the asset service registers light-probe grids under. */\n static assetType: string = LIGHT_PROBE_ASSET_TYPE;\n\n /** The grid. */\n readonly data: LightProbeData;\n\n /**\n * Wraps a checked grid. Use the loader or {@link createLightProbeAsset}.\n *\n * @param data - The grid, already checked by `readLightProbeData`.\n *\n * @internal\n */\n constructor(data: LightProbeData) {\n this.data = data;\n }\n}\n\n/**\n * Publishes a grid built in code, such as the result of a bake, as an asset.\n *\n * @param app - The app.\n * @param data - The grid.\n * @returns A handle a `LightProbeVolume` can take.\n * @throws IgnifxError with code `IGX-0709` when the grid is malformed.\n *\n * @beta\n */\nexport function createLightProbeAsset(app: App, data: LightProbeData): AssetHandle<LightProbeAsset> {\n return app.assets.register(new LightProbeAsset(readLightProbeData(data, \"light probe data\")), {\n type: LIGHT_PROBE_ASSET_TYPE,\n });\n}\n\n/**\n * Turns a grid into the JSON a `.probes.json` file holds.\n *\n * @param data - The grid.\n * @returns The file contents, with the format header.\n *\n * @beta\n */\nexport function writeLightProbeFile(data: LightProbeData): Record<string, unknown> {\n return {\n format: LIGHT_PROBE_FILE_FORMAT,\n formatVersion: LIGHT_PROBE_FORMAT_VERSION,\n origin: { x: data.origin.x, y: data.origin.y, z: data.origin.z },\n cellSize: { x: data.cellSize.x, y: data.cellSize.y, z: data.cellSize.z },\n counts: { x: data.counts.x, y: data.counts.y, z: data.counts.z },\n coefficients: [...data.coefficients],\n };\n}\n\n/**\n * Reads a parsed `.probes.json`.\n *\n * @param parsed - The parsed JSON.\n * @param address - The file's address, for the error.\n * @returns The grid.\n * @throws IgnifxError with code `IGX-0709` when the header, a field or the coefficient count is wrong.\n *\n * @internal\n */\nexport function readLightProbeFile(parsed: unknown, address: string): LightProbeData {\n const file = asRecord(parsed);\n if (\n file === null ||\n file[\"format\"] !== LIGHT_PROBE_FILE_FORMAT ||\n file[\"formatVersion\"] !== LIGHT_PROBE_FORMAT_VERSION\n ) {\n throw invalid(address, `it must start with { \"format\": \"${LIGHT_PROBE_FILE_FORMAT}\", \"formatVersion\": 1 }`);\n }\n return readLightProbeData(file, address);\n}\n\n/**\n * Checks a grid's fields.\n *\n * @param value - The candidate grid.\n * @param address - Where it came from, for the error.\n * @returns A grid with copied, checked fields.\n * @throws IgnifxError with code `IGX-0709` on a malformed field.\n *\n * @internal\n */\nexport function readLightProbeData(value: unknown, address: string): LightProbeData {\n const record = asRecord(value);\n if (record === null) {\n throw invalid(address, \"it is not an object\");\n }\n const grid = readLightProbeGrid(record);\n if (typeof grid === \"string\") {\n throw invalid(address, grid);\n }\n const { origin, cellSize, counts } = grid;\n const coefficients = record[\"coefficients\"];\n const expected = counts.x * counts.y * counts.z * FLOATS_PER_PROBE;\n if (\n !Array.isArray(coefficients) ||\n coefficients.length !== expected ||\n !coefficients.every((n) => Number.isFinite(n))\n ) {\n throw invalid(address, `coefficients must be ${String(expected)} finite numbers (12 per probe)`);\n }\n return { origin, cellSize, counts, coefficients: coefficients.map(Number) };\n}\n\n/**\n * The grid part of a light-probe grid: where it is, how far apart the probes are, and how many.\n *\n * @internal\n */\nexport interface LightProbeGrid {\n readonly origin: { x: number; y: number; z: number };\n readonly cellSize: { x: number; y: number; z: number };\n readonly counts: { x: number; y: number; z: number };\n}\n\n/**\n * Checks the grid fields of a candidate grid, for a file and for a bake alike.\n *\n * @remarks\n * Besides the format's count limits, `origin` stays below 1e20 in size and `cellSize` between\n * 1e-30 and 1e20, so the constants the shader is generated with stay valid 32-bit floats.\n *\n * @param record - An object with `origin`, `cellSize` and `counts`.\n * @returns The checked copies, or what is wrong with them.\n *\n * @internal\n */\nexport function readLightProbeGrid(record: Readonly<Record<string, unknown>>): LightProbeGrid | string {\n const origin = readVec3(record[\"origin\"], (n) => Number.isFinite(n) && Math.abs(n) < MAX_COORDINATE);\n const cellSize = readVec3(record[\"cellSize\"], (n) => Number.isFinite(n) && n > MIN_CELL && n < MAX_COORDINATE);\n const counts = readVec3(record[\"counts\"], (n) => Number.isSafeInteger(n) && n >= 1);\n if (origin === null || cellSize === null || counts === null) {\n return \"origin (finite, below 1e20), cellSize (from 1e-30 to 1e20) and counts (whole, at least 1) must each be { x, y, z }\";\n }\n if (counts.x > MAX_X || counts.y * counts.z > MAX_YZ) {\n return `counts.x must be at most ${String(MAX_X)} and counts.y × counts.z at most ${String(MAX_YZ)}`;\n }\n return { origin, cellSize, counts };\n}\n\n/**\n * The diffuse light a white surface receives at a point, read from the grid on the CPU the same way\n * the shader reads it: trilinear between the eight surrounding probes, clamped at the grid's edges.\n *\n * @param data - The grid.\n * @param x - World X.\n * @param y - World Y.\n * @param z - World Z.\n * @param normal - The surface normal, unit length.\n * @returns Linear RGB.\n *\n * @beta\n */\nexport function sampleLightProbes(\n data: LightProbeData,\n x: number,\n y: number,\n z: number,\n normal: Vec3Like,\n): [number, number, number] {\n const { counts } = data;\n const gx = gridCoordinate(x, data.origin.x, data.cellSize.x, counts.x);\n const gy = gridCoordinate(y, data.origin.y, data.cellSize.y, counts.y);\n const gz = gridCoordinate(z, data.origin.z, data.cellSize.z, counts.z);\n const out: [number, number, number] = [0, 0, 0];\n for (let corner = 0; corner < 8; corner += 1) {\n const ix = corner & 1 ? gx.high : gx.low;\n const iy = corner & 2 ? gy.high : gy.low;\n const iz = corner & 4 ? gz.high : gz.low;\n const weight = (corner & 1 ? gx.t : 1 - gx.t) * (corner & 2 ? gy.t : 1 - gy.t) * (corner & 4 ? gz.t : 1 - gz.t);\n const base = (ix + counts.x * (iy + counts.y * iz)) * FLOATS_PER_PROBE;\n for (let channel = 0; channel < 3; channel += 1) {\n const c = (index: number): number => data.coefficients[base + index * 3 + channel] ?? 0;\n out[channel] = (out[channel] ?? 0) + weight * (c(0) + c(1) * normal.y + c(2) * normal.z + c(3) * normal.x);\n }\n }\n return out;\n}\n\n/**\n * Packs a grid into the half-float RGBA texels the shader reads: probe `(i, j, k)`'s coefficient `c`\n * at texel `(i + countX·c, j + countY·k)`.\n *\n * @param data - The grid.\n * @returns The width, height and texels (four half floats each, alpha 1).\n *\n * @internal\n */\nexport function packLightProbeTexels(data: LightProbeData): { width: number; height: number; texels: Uint16Array } {\n const { x: nx, y: ny, z: nz } = data.counts;\n const width = nx * 4;\n const height = ny * nz;\n const texels = new Uint16Array(width * height * 4);\n const one = toHalfFloat(1);\n for (let k = 0; k < nz; k += 1) {\n for (let j = 0; j < ny; j += 1) {\n for (let i = 0; i < nx; i += 1) {\n const base = (i + nx * (j + ny * k)) * FLOATS_PER_PROBE;\n for (let c = 0; c < 4; c += 1) {\n const texel = (i + nx * c + width * (j + ny * k)) * 4;\n for (let channel = 0; channel < 3; channel += 1) {\n texels[texel + channel] = toHalfFloat(data.coefficients[base + c * 3 + channel] ?? 0);\n }\n texels[texel + 3] = one;\n }\n }\n }\n }\n return { width, height, texels };\n}\n\n/**\n * Converts a number to IEEE 754 half precision, rounding to nearest and saturating to ±65504.\n *\n * @param value - The number.\n * @returns The 16 bits.\n *\n * @internal\n */\nexport function toHalfFloat(value: number): number {\n if (Number.isNaN(value)) {\n return 0x7e00;\n }\n const sign = value < 0 || Object.is(value, -0) ? 0x8000 : 0;\n const magnitude = Math.min(Math.abs(value), 65504);\n if (magnitude < 2 ** -24) {\n return sign;\n }\n if (magnitude < 2 ** -14) {\n return sign | Math.round(magnitude / 2 ** -24);\n }\n const exponent = Math.floor(Math.log2(magnitude));\n const mantissa = Math.round((magnitude / 2 ** exponent - 1) * 1024);\n // A mantissa that rounds up to 1024 carries into the exponent.\n return sign | (((exponent + 15) << 10) + mantissa);\n}\n\n/** A grid axis lookup: the two probe indices around a point and the blend between them. */\ninterface AxisCell {\n readonly low: number;\n readonly high: number;\n readonly t: number;\n}\n\n/**\n * Finds the probes around a coordinate on one axis.\n *\n * @param value - The world coordinate.\n * @param origin - The grid origin on this axis.\n * @param cell - The cell size on this axis.\n * @param count - The probe count on this axis.\n * @returns The cell.\n */\nfunction gridCoordinate(value: number, origin: number, cell: number, count: number): AxisCell {\n const g = Math.min(Math.max((value - origin) / cell, 0), count - 1);\n const low = Math.min(Math.floor(g), Math.max(count - 2, 0));\n const high = Math.min(low + 1, count - 1);\n return { low, high, t: g - low };\n}\n\n/**\n * Reads `{ x, y, z }` whose components all pass a check.\n *\n * @param value - The candidate.\n * @param check - The per-component test.\n * @returns A copy, or `null`.\n */\nfunction readVec3(value: unknown, check: (n: number) => boolean): { x: number; y: number; z: number } | null {\n const record = asRecord(value);\n if (record === null) {\n return null;\n }\n const { x, y, z } = record;\n if (typeof x !== \"number\" || typeof y !== \"number\" || typeof z !== \"number\" || ![x, y, z].every(check)) {\n return null;\n }\n return { x, y, z };\n}\n\n/**\n * Narrows a value to a plain record.\n *\n * @param value - The candidate.\n * @returns The record, or `null` for anything else.\n */\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n // Boundary narrowing of parsed JSON (coding standards §5.2).\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as Record<string, unknown>;\n}\n\n/**\n * The error for a malformed grid.\n *\n * @param address - Where it came from.\n * @param problem - What is wrong.\n * @returns The error.\n */\nfunction invalid(address: string, problem: string): IgnifxError {\n return new IgnifxError(CoreErrorCode.invalidAssetFile, `${address} is not an ${LIGHT_PROBE_FILE_FORMAT} file.`, {\n context: { file: address, format: LIGHT_PROBE_FILE_FORMAT },\n hint: `Fix the file: ${problem}.`,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqBA,MAAa,yBAAyB;;;;;;AAOtC,MAAa,8BAAiD,OAAO,OAAO,CAAC,cAAc,CAAC;;;;;;AAO5F,MAAa,0BAA0B;;;;;;AAOvC,MAAa,6BAA6B;;AAG1C,MAAM,mBAAmB;;AAGzB,MAAM,QAAQ;AACd,MAAM,SAAS;;AAGf,MAAM,iBAAiB;AACvB,MAAM,WAAW;;;;;;;;;;;;AAkCjB,IAAa,kBAAb,MAA6B;;CAE3B,OAAO,YAAoB;;CAG3B;;;;;;;;CASA,YAAY,MAAsB;EAChC,KAAK,OAAO;CACd;AACF;;;;;;;;;;;AAYA,SAAgB,sBAAsB,KAAU,MAAoD;CAClG,OAAO,IAAI,OAAO,SAAS,IAAI,gBAAgB,mBAAmB,MAAM,kBAAkB,CAAC,GAAG,EAC5F,MAAM,uBACR,CAAC;AACH;;;;;;;;;AAUA,SAAgB,oBAAoB,MAA+C;CACjF,OAAO;EACL,QAAQ;EACR,eAAA;EACA,QAAQ;GAAE,GAAG,KAAK,OAAO;GAAG,GAAG,KAAK,OAAO;GAAG,GAAG,KAAK,OAAO;EAAE;EAC/D,UAA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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,MAAM,SAA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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 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"material-plugin-DapJNj04.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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BpB,SAAgB,qBAAqB,YAAoE;CACvG,MAAM,OAAO,WAAW;CACxB,IAAI,CAAC,YAAY,KAAK,IAAI,GACxB,MAAM,IAAI,YACR,cAAc,sBACd,GAAG,KAAK,UAAU,IAAI,EAAE,wCAC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AAEL"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"overlay-CjVgsfrm.js","names":[],"sources":["../src/lite/gpu/overlay.ts"],"sourcesContent":["import {\n addTask,\n addToScene,\n buildFrameGraphTask,\n createHemisphericLight,\n createRenderTarget,\n createRenderTask,\n createSceneContext,\n disposeScene,\n getFrameGraph,\n getRenderingContexts,\n onBeforeRender,\n registerScene,\n unregisterScene,\n} from \"@babylonjs/lite\";\nimport type { EngineContext, RenderTask, SceneContext } from \"@babylonjs/lite\";\n\n/**\n * The render overlay (`docs/architecture/07-rendering.md` §2.10, ADR-0031): a second Lite scene drawn\n * over the finished frame, for an editor's gizmos, selection outlines and other helpers.\n *\n * Everything here needs a device.\n *\n * ## Why core does not call `createUtilityLayer`\n *\n * `createUtilityLayer` (`index.d.ts` 4109) builds its scene with Lite's default render task, and\n * `registerScene` (11268) then fixes that task up against the **last** registered rendering\n * context (`lib/scene/swapchain-overlay.js` 11). Two things go wrong in an ignifx app (editor spike\n * S0.2 §3.2):\n *\n * - When `@ignifx/ui`'s text renderer or `@ignifx/2d`'s sprite renderer was registered after the\n * render scene, it is the last context. It has no frame graph, so Lite configures nothing and the\n * layer's task clears the frame to transparent black.\n * - With MSAA on, Lite borrows the base scene's multisampled colour view, and switches the layer\n * off unless that scene resolves straight into the swapchain (`swapchain-overlay.js` 19-27). With\n * `rendering.features.postProcessing` the render scene resolves into an offscreen target, so the\n * layer never draws.\n *\n * ## What this module builds instead\n *\n * Only public Lite calls:\n *\n * 1. A scene with no default render task (`createSceneContext`, 3663) that shares the render\n * scene's camera, plus the hemispheric light `createUtilityLayer` would add, so Lite's gizmo\n * materials look the same.\n * 2. `registerScene` while its frame graph is **empty**. Lite's fix-up looks for a task that targets\n * the swapchain (`swapchain-overlay.js` 5-7), finds none, and changes nothing.\n * 3. One render task (`createRenderTask`, 3620) added afterwards and recorded with\n * `buildFrameGraphTask` (1501). It draws into the swapchain with `clr: false`, so it keeps the\n * frame's colour, and `sharedRt: true`, so it never builds or frees the swapchain target\n * (`RenderTaskConfig`, 11635). It has a single-sample depth target of its own, which it clears,\n * so helpers draw on top of the scene. It never touches the scene's targets, so the scene's MSAA\n * setting and render path do not matter: it reads whatever the frame's last pass presented.\n *\n * ## Staying last\n *\n * Lite renders the contexts in registration order (`renderFrame`, `lib/engine/engine.js` 246-251),\n * and the 2D and UI extensions register theirs lazily, when the first sprite or text appears. A\n * sprite renderer in `\"sprite\"` mode clears the frame, so one registered after the overlay would\n * erase it. Each frame the overlay checks `getRenderingContexts` (6921); when a context other than\n * another overlay follows it, it moves itself to the end after the frame: unregister, drop its task\n * so the re-registration again finds no swapchain task, register, and build a fresh task. The frame\n * in between draws no overlay. A move that fails (a lost device, a pipeline that does not compile) is\n * reported and tried again on the next animation frame, {@link MOVE_ATTEMPTS} times in all; after\n * that the overlay stays detached until it is disposed.\n *\n * A screenshot is taken after every context has recorded (`_captureService`, same function), so it\n * includes the overlay.\n */\n\n/** The depth/stencil format Lite's own single-sample scene task uses (`lib/scene/scene-core.js` 76-77). */\nconst DEPTH_STENCIL_FORMAT: GPUTextureFormat = \"depth24plus-stencil8\";\n\n/** The name the overlay's task carries in Lite's frame graph and in per-task GPU timings. */\nexport const OVERLAY_TASK_NAME = \"ignifx:overlay\";\n\n/** The light `createUtilityLayer` adds by default (`lib/gizmo/utility-layer.js` 24-36). */\nconst LIGHT_INTENSITY = 2;\n\n/** The ground colour of that light. */\nconst LIGHT_GROUND = 0.5;\n\n/** How many times a move to the end of the context list is tried before the overlay gives up. */\nconst MOVE_ATTEMPTS = 3;\n\n/**\n * What an overlay reports to its owner.\n *\n * @internal\n */\nexport interface OverlayCallbacks {\n /**\n * Answers whether a rendering context is another overlay, which may follow this one.\n *\n * @param context - A registered rendering context.\n * @returns `true` for another overlay.\n */\n isPeer(context: object): boolean;\n /**\n * Called once when the overlay is disposed.\n *\n * @param scene - The overlay's scene.\n */\n onDispose(scene: object): void;\n /**\n * Receives a failed move to the end of the context list.\n *\n * @param error - What `registerScene` rejected with.\n */\n onError(error: unknown): void;\n}\n\n/**\n * The overlay scene and the render scene, in the shape Lite's gizmo constructors take as a\n * `UtilityLayer` (`index.d.ts` 15747).\n *\n * @internal\n */\nexport interface OverlaySceneHandles {\n /** The overlay scene. Add helpers to it. */\n readonly scene: SceneContext;\n /** The render scene, whose camera the overlay scene follows. */\n readonly mainScene: SceneContext;\n}\n\n/**\n * An open overlay scene.\n *\n * @internal\n */\nexport interface OverlayScene {\n /** The Lite scenes. */\n readonly lite: OverlaySceneHandles;\n /** Unregisters and disposes the overlay scene, its task and its depth target. Idempotent. */\n dispose(): void;\n}\n\n/**\n * Builds an overlay scene and registers it after every rendering context on the surface.\n *\n * @remarks\n * Call it only after the render scene is registered: the overlay draws after it because it is\n * registered after it.\n *\n * @param engine - The WebGPU engine, which is also the primary surface.\n * @param mainScene - The render scene whose camera the overlay follows.\n * @param callbacks - The owner's peer test, disposal hook and error sink.\n * @returns The overlay, drawing from the next frame.\n * @throws Whatever the first `registerScene` rejects with; the overlay is disposed first.\n *\n * @example\n * ```ts\n * const overlay = await openOverlayScene(engine, scene, {\n * isPeer: () => false,\n * onDispose: () => {},\n * onError: (error) => console.error(error),\n * });\n * overlay.dispose();\n * ```\n *\n * @internal\n */\nexport async function openOverlayScene(\n engine: EngineContext,\n mainScene: SceneContext,\n callbacks: OverlayCallbacks,\n): Promise<OverlayScene> {\n const overlay = new LiteOverlayScene(engine, mainScene, callbacks);\n try {\n await overlay.attach();\n } catch (error) {\n overlay.dispose();\n throw error;\n }\n return overlay;\n}\n\n/** The overlay scene, its registration and its place in the context list. */\nclass LiteOverlayScene implements OverlayScene {\n readonly lite: OverlaySceneHandles;\n\n readonly #engine: EngineContext;\n\n readonly #scene: SceneContext;\n\n readonly #callbacks: OverlayCallbacks;\n\n #isDisposed = false;\n\n #isMoving = false;\n\n /**\n * Creates the scene, with the light `createUtilityLayer` would add, following the render scene's\n * camera. It is not registered yet.\n *\n * @param engine - The WebGPU engine.\n * @param mainScene - The render scene.\n * @param callbacks - The owner's peer test, disposal hook and error sink.\n */\n constructor(engine: EngineContext, mainScene: SceneContext, callbacks: OverlayCallbacks) {\n const scene = createSceneContext(engine, { defaultRenderTask: false });\n scene.name = OVERLAY_TASK_NAME;\n scene.camera = mainScene.camera;\n const light = createHemisphericLight([0, 1, 0], LIGHT_INTENSITY);\n light.groundColor = [LIGHT_GROUND, LIGHT_GROUND, LIGHT_GROUND];\n addToScene(scene, light);\n this.lite = { scene, mainScene };\n this.#engine = engine;\n this.#scene = scene;\n this.#callbacks = callbacks;\n onBeforeRender(scene, () => {\n // The render scene's camera can change from frame to frame (the highest-priority `Camera` wins).\n if (scene.camera !== mainScene.camera) {\n scene.camera = mainScene.camera;\n }\n this.#keepLast();\n });\n }\n\n /**\n * Registers the scene at the end of the context list and builds its task.\n *\n * @returns A promise that settles once the overlay draws from the next frame.\n */\n async attach(): Promise<void> {\n // Registered while its frame graph is empty, so Lite's swapchain fix-up finds nothing to change.\n await registerScene(this.#scene);\n if (this.#isDisposed) {\n return;\n }\n const task = createOverlayTask(this.#engine, this.#scene);\n addTask(this.#scene, task);\n buildFrameGraphTask(getFrameGraph(this.#scene), task);\n }\n\n dispose(): void {\n if (this.#isDisposed) {\n return;\n }\n this.#isDisposed = true;\n unregisterScene(this.#scene);\n disposeScene(this.#scene);\n this.#callbacks.onDispose(this.#scene);\n }\n\n /** Schedules a move to the end of the context list when a context that is not an overlay follows. */\n #keepLast(): void {\n if (this.#isMoving || !this.#isFollowed()) {\n return;\n }\n // Not now: Lite is walking the context list. The microtask runs once the frame has been submitted.\n this.#isMoving = true;\n queueMicrotask(() => {\n this.#move(MOVE_ATTEMPTS);\n });\n }\n\n /**\n * Moves the overlay to the end, reporting a failure and trying again on the next animation frame.\n *\n * @param attemptsLeft - How many attempts remain, this one included.\n */\n #move(attemptsLeft: number): void {\n this.#moveToEnd().then(\n () => {\n this.#isMoving = false;\n },\n (error: unknown) => {\n this.#callbacks.onError(error);\n if (attemptsLeft > 1 && !this.#isDisposed) {\n // The overlay is unregistered now, so its own frame callback no longer runs to retry.\n requestAnimationFrame(() => {\n this.#move(attemptsLeft - 1);\n });\n return;\n }\n this.#isMoving = false;\n },\n );\n }\n\n /**\n * Whether a rendering context other than another overlay is registered after this one.\n *\n * @returns `true` when the overlay has to move.\n */\n #isFollowed(): boolean {\n const contexts = getRenderingContexts(this.#engine);\n for (let index = contexts.indexOf(this.#scene) + 1; index < contexts.length; index += 1) {\n const context = contexts[index];\n if (context !== undefined && !this.#callbacks.isPeer(context)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Re-registers the overlay at the end of the context list.\n *\n * @returns A promise that settles once it draws last.\n */\n async #moveToEnd(): Promise<void> {\n if (this.#isDisposed) {\n return;\n }\n unregisterScene(this.#scene);\n // Disposing the graph drops the task, which also frees its depth target.\n getFrameGraph(this.#scene).dispose();\n await this.attach();\n }\n}\n\n/**\n * Creates the overlay's render task: into the swapchain, keeping its colour, over a depth buffer of\n * its own that it clears.\n *\n * @param engine - The engine.\n * @param scene - The overlay scene.\n * @returns The task, not yet added to a frame graph.\n */\nfunction createOverlayTask(engine: EngineContext, scene: SceneContext): RenderTask {\n return createRenderTask(\n {\n name: OVERLAY_TASK_NAME,\n rt: engine.scRT,\n sharedRt: true,\n depth: createRenderTarget({\n lbl: \"ignifx:overlay-depth\",\n dFormat: DEPTH_STENCIL_FORMAT,\n samples: 1,\n size: engine,\n }),\n clr: false,\n },\n engine,\n scene,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,MAAM,uBAAyC;;AAG/C,MAAa,oBAAoB;;AAGjC,MAAM,kBAAkB;;AAGxB,MAAM,eAAe;;AAGrB,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;AA+EtB,eAAsB,iBACpB,QACA,WACA,WACuB;CACvB,MAAM,UAAU,IAAI,iBAAiB,QAAQ,WAAW,SAA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K,YAAY;EACnB,IACC,UAAmB;GAClB,KAAK,WAAW,QAAQ,KAAK;GAC7B,IAAI,eAAe,KAAK,CAAC,KAAK,aAAa;IAEzC,4BAA4B;KAC1B,KAAK,MAAM,eAAe,CAAC;IAC7B,CAAC;IACD;GACF;GACA,KAAK,YAAY;EACnB,CACF;CACF;;;;;;CAOA,cAAuB;EACrB,MAAM,WAAW,qBAAqB,KAAK,OAAO;EAClD,KAAK,IAAI,QAAQ,SAAS,QAAQ,KAAK,MAAM,IAAI,GAAG,QAAQ,SAAS,QAAQ,SAAS,GAAG;GACvF,MAAM,UAAU,SAAS;GACzB,IAAI,YAAY,KAAA,KAAa,CAAC,KAAK,WAAW,OAAO,OAAO,GAC1D,OAAO;EAEX;EACA,OAAO;CACT;;;;;;CAOA,MAAM,aAA4B;EAChC,IAAI,KAAK,aACP;EAEF,gBAAgB,KAAK,MAAM;EAE3B,cAAc,KAAK,MAAM,CAAC,CAAC,QAAQ;EACnC,MAAM,KAAK,OAAO;CACpB;AACF;;;;;;;;;AAUA,SAAS,kBAAkB,QAAuB,OAAiC;CACjF,OAAO,iBACL;EACE,MAAM;EACN,IAAI,OAAO;EACX,UAAU;EACV,OAAO,mBAAmB;GACxB,KAAK;GACL,SAAS;GACT,SAAS;GACT,MAAM;EACR,CAAC;EACD,KAAK;CACP,GACA,QACA,KACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"post-effect-Cu3Enpz7.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":";;;;;;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O;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 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"post-effect-compiler-cCq9lcHt.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,YAAY,SAAS,QAAQ,YAAY,CAAC,qBAAqB,QAAQ,IAAI,CAAC;CACpG,MAAM,SAAS,eAAe,CAC5B,GAAG,8BACH,GAAG,SAAS,KAAK,aAAa;EAAE,MAAM,QAAQ;EAAM,MAAM,QAAQ;CAAK,EAAE,CAC3E,CAAC;CACD,MAAM,yBAAS,IAAI,IAAoC;CACvD,KAAK,MAAM,SAAS,OAAO,QACzB,OAAO,IAAI,MAAM,MAAM,KAAK;CAE9B,OAAO;EACL,SAAS,OAAO;EAChB,cAAc,oBAAoB,QAAQ,OAAO,MAAM;EACvD,UAAU,OAAO;EACjB;EACA,mBAAmB,OAA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