@ignifx/core 0.20.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.
Files changed (88) hide show
  1. package/README.md +22 -0
  2. package/dist/{agx-tone-mapping-Cgt844j6.js → agx-tone-mapping-CCdGk_ly.js} +2 -2
  3. package/dist/agx-tone-mapping-CCdGk_ly.js.map +1 -0
  4. package/dist/auto-exposure-uzPn0beO.js.map +1 -1
  5. package/dist/{bloom-hdr-CLtQj-oY.js → bloom-hdr-xPwkIdHG.js} +5 -6
  6. package/dist/bloom-hdr-xPwkIdHG.js.map +1 -0
  7. package/dist/contact-shadows-T523EXaP.js.map +1 -1
  8. package/dist/effect-task-CMbuO6Kb.js.map +1 -1
  9. package/dist/{environment-Bf4aphSb.js → environment-7fJbN402.js} +2 -2
  10. package/dist/{environment-Bf4aphSb.js.map → environment-7fJbN402.js.map} +1 -1
  11. package/dist/{gtao-Bpu5-0Ne.js → gtao-BmdrXXJz.js} +10 -11
  12. package/dist/gtao-BmdrXXJz.js.map +1 -0
  13. package/dist/{hdr-output-DBQwMphy.js → hdr-output-_2TU-jWy.js} +8 -8
  14. package/dist/hdr-output-_2TU-jWy.js.map +1 -0
  15. package/dist/index.d.ts +40 -42
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +104 -108
  18. package/dist/index.js.map +1 -1
  19. package/dist/{instanced-mesh-instance-B-fXKSrY.js → instanced-mesh-instance-BLdAJTj8.js} +3 -3
  20. package/dist/instanced-mesh-instance-BLdAJTj8.js.map +1 -0
  21. package/dist/{light-probe-asset-BqfSrJe9.js → light-probe-asset-DGNIwKNb.js} +2 -2
  22. package/dist/light-probe-asset-DGNIwKNb.js.map +1 -0
  23. package/dist/{light-probes-DDojYajw.js → light-probes-C8jharz9.js} +6 -6
  24. package/dist/light-probes-C8jharz9.js.map +1 -0
  25. package/dist/lightmaps-BUUIIkt9.js.map +1 -1
  26. package/dist/material-myMbl9mW.js.map +1 -1
  27. package/dist/{material-plugin-DapJNj04.js → material-plugin-BBxIy6eo.js} +4 -4
  28. package/dist/material-plugin-BBxIy6eo.js.map +1 -0
  29. package/dist/{overlay-CjVgsfrm.js → overlay-DokHzP6_.js} +2 -3
  30. package/dist/overlay-DokHzP6_.js.map +1 -0
  31. package/dist/{post-effect-Cu3Enpz7.js → post-effect-DEZD-r0I.js} +3 -3
  32. package/dist/post-effect-DEZD-r0I.js.map +1 -0
  33. package/dist/{post-effect-compiler-cCq9lcHt.js → post-effect-compiler-unDD3hod.js} +4 -4
  34. package/dist/post-effect-compiler-unDD3hod.js.map +1 -0
  35. package/dist/{prefab-overrides-C2GsgOQc.js → prefab-overrides-Bb7jVm7A.js} +3 -3
  36. package/dist/prefab-overrides-Bb7jVm7A.js.map +1 -0
  37. package/dist/{prefab-overrides-htDc_5Po.d.ts → prefab-overrides-DwrPDVVt.d.ts} +61 -63
  38. package/dist/{prefab-overrides-htDc_5Po.d.ts.map → prefab-overrides-DwrPDVVt.d.ts.map} +1 -1
  39. package/dist/prefab.d.ts +1 -1
  40. package/dist/prefab.js +1 -1
  41. package/dist/{reflection-probe-QkD1Fo_d.js → reflection-probe-C2jcreI1.js} +5 -5
  42. package/dist/reflection-probe-C2jcreI1.js.map +1 -0
  43. package/dist/{reflection-probes-CAzSuqf8.js → reflection-probes-BMVQfbhm.js} +10 -10
  44. package/dist/reflection-probes-BMVQfbhm.js.map +1 -0
  45. package/dist/{render-path-D11i_7X8.js → render-path-CWXHrRa2.js} +2 -2
  46. package/dist/render-path-CWXHrRa2.js.map +1 -0
  47. package/dist/{scene-color-passes-B93qTOka.js → scene-color-passes-DgXJ45Ql.js} +2 -2
  48. package/dist/scene-color-passes-DgXJ45Ql.js.map +1 -0
  49. package/dist/{scene-inputs-BxGOsnIZ.js → scene-inputs-_0j2Hi6L.js} +9 -8
  50. package/dist/scene-inputs-_0j2Hi6L.js.map +1 -0
  51. package/dist/{shader-declaration-5q__jycG.js → shader-declaration-BGprFBLq.js} +4 -4
  52. package/dist/shader-declaration-BGprFBLq.js.map +1 -0
  53. package/dist/{shader-material-TM4f8eKA.js → shader-material-C9sYMGWw.js} +8 -9
  54. package/dist/shader-material-C9sYMGWw.js.map +1 -0
  55. package/dist/{shader-material-CJIDFvSb.js → shader-material-vmkJ25II.js} +3 -3
  56. package/dist/shader-material-vmkJ25II.js.map +1 -0
  57. package/dist/{shader-pragma-ljmAbVc2.js → shader-pragma-D0MjCOIg.js} +3 -3
  58. package/dist/shader-pragma-D0MjCOIg.js.map +1 -0
  59. package/dist/ssgi-DSnhqotl.js.map +1 -1
  60. package/dist/{surface-shader-rpPpeosD.js → surface-shader-BfADq9Wx.js} +6 -6
  61. package/dist/surface-shader-BfADq9Wx.js.map +1 -0
  62. package/dist/{taa-BwBZLy11.js → taa-nxVA78Ur.js} +5 -6
  63. package/dist/taa-nxVA78Ur.js.map +1 -0
  64. package/dist/vec3-2C3LBZnt.js.map +1 -1
  65. package/package.json +1 -1
  66. package/dist/agx-tone-mapping-Cgt844j6.js.map +0 -1
  67. package/dist/bloom-hdr-CLtQj-oY.js.map +0 -1
  68. package/dist/gtao-Bpu5-0Ne.js.map +0 -1
  69. package/dist/hdr-output-DBQwMphy.js.map +0 -1
  70. package/dist/instanced-mesh-instance-B-fXKSrY.js.map +0 -1
  71. package/dist/light-probe-asset-BqfSrJe9.js.map +0 -1
  72. package/dist/light-probes-DDojYajw.js.map +0 -1
  73. package/dist/material-plugin-DapJNj04.js.map +0 -1
  74. package/dist/overlay-CjVgsfrm.js.map +0 -1
  75. package/dist/post-effect-Cu3Enpz7.js.map +0 -1
  76. package/dist/post-effect-compiler-cCq9lcHt.js.map +0 -1
  77. package/dist/prefab-overrides-C2GsgOQc.js.map +0 -1
  78. package/dist/reflection-probe-QkD1Fo_d.js.map +0 -1
  79. package/dist/reflection-probes-CAzSuqf8.js.map +0 -1
  80. package/dist/render-path-D11i_7X8.js.map +0 -1
  81. package/dist/scene-color-passes-B93qTOka.js.map +0 -1
  82. package/dist/scene-inputs-BxGOsnIZ.js.map +0 -1
  83. package/dist/shader-declaration-5q__jycG.js.map +0 -1
  84. package/dist/shader-material-CJIDFvSb.js.map +0 -1
  85. package/dist/shader-material-TM4f8eKA.js.map +0 -1
  86. package/dist/shader-pragma-ljmAbVc2.js.map +0 -1
  87. package/dist/surface-shader-rpPpeosD.js.map +0 -1
  88. package/dist/taa-BwBZLy11.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"vec3-2C3LBZnt.js","names":["updateMeshPositions","updateMeshNormals","updateMeshUvs","updateMeshColors"],"sources":["../src/lite/gpu/mesh.ts","../src/math/vec3.ts"],"sourcesContent":["import {\n addToScene,\n cloneTransformNode,\n createBox,\n createCapsule,\n createCylinder,\n createGround,\n createMeshFromData,\n createPlane,\n createSphere,\n createTorus,\n getMaterialFamily,\n getMeshTriangles,\n removeFromScene,\n setSubtreeVisible,\n updateMeshColors as liteUpdateMeshColors,\n updateMeshNormals as liteUpdateMeshNormals,\n updateMeshPositions as liteUpdateMeshPositions,\n updateMeshUvs as liteUpdateMeshUvs,\n} from \"@babylonjs/lite\";\nimport type {\n BoxOptions,\n CapsuleOptions,\n CylinderOptions,\n EngineContext,\n GroundOptions,\n Material,\n Mesh,\n PbrMaterialProps,\n PlaneOptions,\n SceneContext,\n SceneNode,\n SphereOptions,\n StandardMaterialProps,\n TorusOptions,\n} from \"@babylonjs/lite\";\n\n/**\n * Mesh half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §2.3). Every function\n * here needs a WebGPU device — `createMeshFromData` uploads four vertex buffers through\n * `engine._device` (`lib/mesh/mesh.js`, `uploadMeshToGPU`) and the null engine has no `_device` —\n * so the whole module lives under `src/lite/gpu/` and is covered by the browser test project.\n *\n * Everything here is `@internal`.\n *\n * ## Ownership, cloning, and disposal (verified against `@babylonjs/lite@1.27.0`)\n *\n * - `cloneTransformNode(mesh)` (`index.d.ts` 1776, `lib/scene/transform-node.js`) shallow-clones a\n * mesh: the clone gets a fresh transform and **the same `_gpu` wrapper object**, with\n * `retain(_gpu)` bumping a reference count. So N clones of one template share exactly one set of\n * GPU buffers — that is spike S2.4's \"instancing shares GPU buffers\", and it is provable by\n * object identity rather than by measuring memory.\n * - Disposal is driven entirely by scene membership. `removeFromScene` calls `unregisterMeshScene`,\n * and only when the mesh has left its **last** scene does it queue `disposeMeshGpu`, which calls\n * `release(_gpu)` and destroys the buffers only when the count drops to one\n * (`lib/scene/scene-remove.js`, `lib/mesh/mesh-dispose.js`, `lib/resource/ref-count.js`). A\n * template that is never added to a scene therefore keeps its buffers alive no matter how many\n * clones come and go — which is what `docs/architecture/07-rendering.md` §2.3 means by \"the\n * template's buffers stay alive while the asset is retained\".\n * - The flip side is that Lite exports **no** mesh disposer. The only public way to release a\n * template's buffers is {@link disposeMeshTemplate}: add it to a scene and take it out again.\n * - `removeFromScene` also recursively removes a mesh's `children` and nulls its `parent`, so\n * removing a `Model`'s root removes the whole instantiated subtree in one call.\n * - Hiding is `setSubtreeVisible` (exported as `setMeshVisible` too, `index.d.ts` 11199): it\n * cascades `visible` down the subtree and bumps a global visibility epoch. Never remove a mesh\n * from the scene to hide it — that disposes it.\n *\n * ## Updating a mesh's vertices (verified against `lib/mesh/mesh-factories.js`)\n *\n * `updateMesh*` writes the GPU buffer and **nothing else**. Three consequences, all of them\n * surprising enough to be worth stating where the calls are:\n *\n * 1. **The retained CPU arrays are not replaced.** `createMeshFromData` keeps `_cpuPositions`,\n * `_cpuNormals`, `_cpuUvs` and `_cpuIndices` — the arrays it was handed — and Lite's CPU ray\n * pick reads them (`lib/picking/ray-pick.js`). Only `updateMeshGeometry`/`resizeMeshGeometry`\n * re-retain, through `retainMeshGeometry`. So an update that hands over a *different* array\n * leaves picking looking at the old geometry, while an update after mutating the retained array\n * in place leaves picking exact. `MeshAsset` keeps its own copy in step for that reason.\n * 2. **Bounds are not recomputed.** `retainMeshGeometry` is what calls `computeAabb` and writes\n * `boundMin`/`boundMax`; the partial updaters do not. `Mesh`'s own declaration says a consumer\n * \"MAY overwrite these with a wider hand-computed box\", so {@link setMeshBounds} exists and\n * `MeshAsset.updatePositions` uses it.\n * 3. **A cloned template cannot be updated at all.** `writeVertexAttributeRange` throws\n * (`ThrowLiteError(360)`) when `mesh._gpu._refCount > 1`, and cloning a mesh retains that very\n * wrapper. A `MeshAsset` a `MeshRenderer` has drawn is therefore frozen; a mesh meant to be\n * edited is a renderable of its own, which is the shape the terrain chunk adapter uses.\n */\n\n/**\n * The Babylon Lite mesh a `MeshAsset` template and a `MeshRenderer` clone are, re-exported under an\n * ignifx name so feature code can name the type without importing `@babylonjs/lite`\n * (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * @remarks\n * Unstable: it is Lite's own type, reachable only through documented `.lite` escape hatches, and it\n * is excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteMesh = Mesh;\n\n/**\n * Creates a box template.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - A uniform size, or per-axis dimensions.\n * @returns The mesh. It belongs to no scene yet.\n *\n * @example\n * ```ts\n * const template = createBoxMesh(engine, { size: 2 });\n * const instance = cloneMeshUnderNode(template, entityNode);\n * addMeshToScene(scene, instance);\n * ```\n *\n * @internal\n */\nexport function createBoxMesh(engine: EngineContext, options?: number | BoxOptions): Mesh {\n return createBox(engine, options);\n}\n\n/**\n * Creates a sphere template.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Segment count and diameters.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createSphereMesh(engine: EngineContext, options?: SphereOptions): Mesh {\n return createSphere(engine, options);\n}\n\n/**\n * Creates a plane template in the XY plane.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Size, or width and height.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createPlaneMesh(engine: EngineContext, options?: PlaneOptions): Mesh {\n return createPlane(engine, options);\n}\n\n/**\n * Creates a subdivided ground template in the XZ plane.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Width, height, subdivisions, and UV scale.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createGroundMesh(engine: EngineContext, options?: GroundOptions): Mesh {\n return createGround(engine, options);\n}\n\n/**\n * Creates a cylinder template along the Y axis.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Height, diameters, and tessellation.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createCylinderMesh(engine: EngineContext, options?: CylinderOptions): Mesh {\n return createCylinder(engine, options);\n}\n\n/**\n * Creates a capsule template along the Y axis.\n *\n * @remarks\n * `height` is the **total** height including both caps (`index.d.ts` 1523), which is the same\n * convention `@ignifx/physics`'s capsule collider uses, so a renderer and a collider built from one\n * pair of numbers line up.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Height, radius, and tessellation.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createCapsuleMesh(engine: EngineContext, options?: CapsuleOptions): Mesh {\n return createCapsule(engine, options);\n}\n\n/**\n * Creates a torus template in the XZ plane.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Diameter, thickness, and tessellation.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createTorusMesh(engine: EngineContext, options?: TorusOptions): Mesh {\n return createTorus(engine, options);\n}\n\n/**\n * Creates a mesh from raw vertex data.\n *\n * @remarks\n * Lite keeps a reference to the arrays that are handed in — it does not copy them — and uses them\n * for CPU ray picking and bounds (`lib/mesh/mesh-factories.js`). Callers must not mutate them\n * afterwards.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param name - A debug name.\n * @param positions - Three floats per vertex.\n * @param normals - Three floats per vertex.\n * @param indices - Three indices per triangle.\n * @param uvs - Two floats per vertex, or omitted.\n * @param uvs2 - Two floats per vertex for the second UV set, or omitted.\n * @param tangents - Four floats per vertex, or omitted.\n * @param colors - Four floats per vertex, or omitted.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createMeshFromGeometry(\n engine: EngineContext,\n name: string,\n positions: Float32Array,\n normals: Float32Array,\n indices: Uint32Array,\n uvs?: Float32Array,\n uvs2?: Float32Array,\n tangents?: Float32Array,\n colors?: Float32Array,\n): Mesh {\n return createMeshFromData(engine, name, positions, normals, indices, uvs, uvs2, tangents, colors);\n}\n\n/**\n * Re-uploads part of a mesh's position buffer.\n *\n * @remarks\n * A no-op range is accepted; an out-of-range one, or a mesh whose GPU geometry has co-owners,\n * throws a Lite error (see the module note). It does **not** refresh the CPU picking geometry or\n * the bounds.\n *\n * @param engine - The engine that owns the buffer.\n * @param mesh - The mesh to update.\n * @param positions - Three floats per vertex, read from index 0.\n * @param vertexOffset - The first destination vertex to overwrite.\n * @param vertexCount - How many vertices to write.\n *\n * @internal\n */\nexport function updateMeshPositions(\n engine: EngineContext,\n mesh: Mesh,\n positions: Float32Array,\n vertexOffset: number,\n vertexCount: number,\n): void {\n liteUpdateMeshPositions(engine, mesh, positions, vertexOffset, vertexCount);\n}\n\n/**\n * Re-uploads part of a mesh's normal buffer.\n *\n * @param engine - The engine that owns the buffer.\n * @param mesh - The mesh to update.\n * @param normals - Three floats per vertex.\n * @param vertexOffset - The first destination vertex to overwrite.\n * @param vertexCount - How many vertices to write.\n *\n * @internal\n */\nexport function updateMeshNormals(\n engine: EngineContext,\n mesh: Mesh,\n normals: Float32Array,\n vertexOffset: number,\n vertexCount: number,\n): void {\n liteUpdateMeshNormals(engine, mesh, normals, vertexOffset, vertexCount);\n}\n\n/**\n * Re-uploads part of a mesh's UV buffer.\n *\n * @remarks\n * Lite makes it a no-op when the mesh was created without UVs, rather than an error.\n *\n * @param engine - The engine that owns the buffer.\n * @param mesh - The mesh to update.\n * @param uvs - Two floats per vertex.\n * @param vertexOffset - The first destination vertex to overwrite.\n * @param vertexCount - How many vertices to write.\n *\n * @internal\n */\nexport function updateMeshUvs(\n engine: EngineContext,\n mesh: Mesh,\n uvs: Float32Array,\n vertexOffset: number,\n vertexCount: number,\n): void {\n liteUpdateMeshUvs(engine, mesh, uvs, vertexOffset, vertexCount);\n}\n\n/**\n * Re-uploads part of a mesh's vertex-colour buffer.\n *\n * @remarks\n * The colour attribute is `vec4`, and Lite makes the call a no-op when the mesh was created without\n * colours.\n *\n * @param engine - The engine that owns the buffer.\n * @param mesh - The mesh to update.\n * @param colors - Four floats per vertex.\n * @param vertexOffset - The first destination vertex to overwrite.\n * @param vertexCount - How many vertices to write.\n *\n * @internal\n */\nexport function updateMeshColors(\n engine: EngineContext,\n mesh: Mesh,\n colors: Float32Array,\n vertexOffset: number,\n vertexCount: number,\n): void {\n liteUpdateMeshColors(engine, mesh, colors, vertexOffset, vertexCount);\n}\n\n/**\n * Writes a mesh's object-local bounding box.\n *\n * @remarks\n * `Mesh.boundMin`/`boundMax` are declared consumer-writable, and writing them is the only way to\n * keep the shadow fit, the thin-instance culler and the Havok shape extents honest after a partial\n * vertex update — none of the partial updaters recomputes them. The existing arrays are mutated in\n * place when they are there, so repeated sculpting allocates nothing.\n *\n * @param mesh - The mesh to re-bound.\n * @param minX - The smallest X.\n * @param minY - The smallest Y.\n * @param minZ - The smallest Z.\n * @param maxX - The largest X.\n * @param maxY - The largest Y.\n * @param maxZ - The largest Z.\n *\n * @internal\n */\nexport function setMeshBounds(\n mesh: Mesh,\n minX: number,\n minY: number,\n minZ: number,\n maxX: number,\n maxY: number,\n maxZ: number,\n): void {\n const boundMin = mesh.boundMin;\n if (boundMin === undefined) {\n mesh.boundMin = [minX, minY, minZ];\n } else {\n boundMin[0] = minX;\n boundMin[1] = minY;\n boundMin[2] = minZ;\n }\n const boundMax = mesh.boundMax;\n if (boundMax === undefined) {\n mesh.boundMax = [maxX, maxY, maxZ];\n } else {\n boundMax[0] = maxX;\n boundMax[1] = maxY;\n boundMax[2] = maxZ;\n }\n}\n\n/**\n * Gives a cloned mesh bounding-box arrays of its own.\n *\n * @remarks\n * `cloneMeshNode` shallow-spreads the template (`lib/scene/transform-node.js`), so a clone starts\n * out sharing the template's `boundMin`/`boundMax` arrays and {@link setMeshBounds} — which mutates\n * in place — would write through to the template and to every other clone. Any caller that re-bounds\n * one clone alone has to call this first.\n *\n * @param mesh - The clone.\n *\n * @internal\n */\nexport function detachMeshBounds(mesh: Mesh): void {\n const boundMin = mesh.boundMin;\n if (boundMin !== undefined) {\n mesh.boundMin = [boundMin[0], boundMin[1], boundMin[2]];\n }\n const boundMax = mesh.boundMax;\n if (boundMax !== undefined) {\n mesh.boundMax = [boundMax[0], boundMax[1], boundMax[2]];\n }\n}\n\n/**\n * Recomputes a mesh's object-local bounding box from a position array and writes it.\n *\n * @remarks\n * The partial vertex updaters leave `boundMin`/`boundMax` alone (see the module note), and every\n * consumer that fits a shadow cascade, culls a thin instance, or measures a Havok shape reads them.\n * One linear pass, no allocation. A position array too short to hold one vertex leaves the bounds\n * as they were.\n *\n * @param mesh - The mesh to re-bound.\n * @param positions - Three floats per vertex.\n *\n * @internal\n */\nexport function recomputeMeshBounds(mesh: Mesh, positions: Float32Array): void {\n if (positions.length < 3) {\n return;\n }\n let minX = Number.POSITIVE_INFINITY;\n let minY = Number.POSITIVE_INFINITY;\n let minZ = Number.POSITIVE_INFINITY;\n let maxX = Number.NEGATIVE_INFINITY;\n let maxY = Number.NEGATIVE_INFINITY;\n let maxZ = Number.NEGATIVE_INFINITY;\n for (let index = 0; index + 2 < positions.length; index += 3) {\n const x = positions[index] ?? 0;\n const y = positions[index + 1] ?? 0;\n const z = positions[index + 2] ?? 0;\n minX = x < minX ? x : minX;\n minY = y < minY ? y : minY;\n minZ = z < minZ ? z : minZ;\n maxX = x > maxX ? x : maxX;\n maxY = y > maxY ? y : maxY;\n maxZ = z > maxZ ? z : maxZ;\n }\n setMeshBounds(mesh, minX, minY, minZ, maxX, maxY, maxZ);\n}\n\n/**\n * Clones a template — mesh or transform-node subtree — and parents the clone under an entity node.\n *\n * @remarks\n * The clone shares the template's GPU buffers (see the module note). Cloning a mesh whose buffers\n * were already released throws, which is Lite's way of telling you the template outlived its asset.\n *\n * Only the `parent` link is written; the clone is deliberately **not** pushed into the parent's\n * `children` array, for the same reason cameras and lights are not (`./camera.ts`): ignifx\n * transform nodes are never added to a Lite scene, so nothing in Lite walks their children, and\n * `removeFromScene` nulls a removed mesh's `parent` without touching the array it was listed in —\n * so maintaining it would only create a stale entry to clean up.\n *\n * @param template - The mesh or subtree to clone.\n * @param parent - The entity's transform node, or `null` for world space.\n * @returns The cloned root. Add it to the scene with {@link addMeshToScene}.\n *\n * @internal\n */\nexport function cloneMeshUnderNode(template: SceneNode, parent: SceneNode | null): SceneNode {\n const clone = cloneTransformNode(template);\n clone.parent = parent;\n return clone;\n}\n\n/**\n * Adds a mesh — or a transform-node subtree containing meshes — to a render scene.\n *\n * @remarks\n * `addToScene` recurses into `children` and re-parents each one, so a whole instantiated model goes\n * in with one call. When the scene is already registered, the mesh joins Lite's runtime\n * material-swap queue and appears once its material family's renderable has been rebuilt\n * (`docs/architecture/07-rendering.md` §1.1 and ADR-0014).\n *\n * @param scene - The render scene.\n * @param node - The mesh or subtree root to add.\n *\n * @internal\n */\nexport function addMeshToScene(scene: SceneContext, node: SceneNode): void {\n addToScene(scene, node);\n}\n\n/**\n * Removes a mesh — and everything under it — from a render scene, releasing its GPU buffers when it\n * has left its last scene.\n *\n * @remarks\n * This is destruction, not hiding: use {@link setMeshSubtreeVisible} to hide.\n *\n * @param scene - The render scene.\n * @param node - The mesh or subtree root to remove.\n *\n * @internal\n */\nexport function removeMeshFromScene(scene: SceneContext, node: SceneNode): void {\n removeFromScene(scene, node);\n}\n\n/**\n * Shows or hides a mesh and everything under it.\n *\n * @param node - The subtree root.\n * @param visible - `true` to show it, `false` to hide it.\n *\n * @internal\n */\nexport function setMeshSubtreeVisible(node: SceneNode, visible: boolean): void {\n setSubtreeVisible(node, visible);\n}\n\n/**\n * Assigns a mesh's material.\n *\n * @remarks\n * `Mesh.material` is an accessor once the mesh has joined a scene: writing it queues a material\n * swap on every scene the mesh belongs to (`lib/scene/mesh-scene-registry.js`,\n * `installMaterialSetter`). Assigning the material the mesh already has is a no-op.\n *\n * @param mesh - The mesh to change.\n * @param material - The material to draw it with.\n *\n * @internal\n */\nexport function setMeshMaterial(mesh: Mesh, material: Material): void {\n mesh.material = material;\n}\n\n/**\n * Sets whether a mesh is darkened by shadow maps.\n *\n * @param mesh - The mesh to change.\n * @param receiveShadows - `true` to sample shadow maps on this mesh.\n *\n * @internal\n */\nexport function setMeshReceiveShadows(mesh: Mesh, receiveShadows: boolean): void {\n mesh.receiveShadows = receiveShadows;\n}\n\n/**\n * Sets a mesh's sort key within its phase. Lower values are drawn first.\n *\n * @param mesh - The mesh to change.\n * @param renderOrder - The sort key; it only orders within the opaque or the transparent phase.\n *\n * @internal\n */\nexport function setMeshRenderOrder(mesh: Mesh, renderOrder: number): void {\n mesh.renderOrder = renderOrder;\n}\n\n/**\n * Sets whether picking considers a mesh at all.\n *\n * @remarks\n * `pickable === false` removes the mesh from both the GPU picker's candidate list and the CPU ray\n * test, so it neither occludes nor returns a hit (`index.d.ts` 7214, `lib/picking/ray-pick.js`).\n *\n * @param mesh - The mesh to change.\n * @param pickable - `true` to allow picking.\n *\n * @internal\n */\nexport function setMeshPickable(mesh: Mesh, pickable: boolean): void {\n mesh.pickable = pickable;\n}\n\n/**\n * Gives a mesh the string id Lite's light include/exclude sets match on.\n *\n * @param mesh - The mesh to name.\n * @param id - The id. It should be unique within the scene.\n *\n * @internal\n */\nexport function setMeshId(mesh: Mesh, id: string): void {\n mesh.id = id;\n}\n\n/**\n * Replaces the materials of every mesh in a subtree whose current material carries one of the given\n * names.\n *\n * @remarks\n * `Material.name` is \"populated by loaders from the source asset (e.g. the glTF material name) so\n * callers can look a material up by name\" (`index.d.ts`), which is the identifier\n * `docs/architecture/07-rendering.md` §2.4 means by \"by material name\". Assigning `Mesh.material`\n * queues a material swap on every scene the mesh belongs to; assigning the material a mesh already\n * has is a no-op, so re-running this is cheap.\n *\n * @param node - The subtree root.\n * @param overrides - Source material name to replacement material.\n * @returns How many meshes were re-materialled.\n *\n * @internal\n */\nexport function overrideSubtreeMaterials(node: SceneNode, overrides: ReadonlyMap<string, Material>): number {\n let changed = 0;\n if (\"material\" in node) {\n // A scene node that carries `material` is a mesh —\n // the same structural test Lite's own scene walk uses.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const mesh = node as Mesh;\n const name = mesh.material.name;\n const replacement = name === undefined ? undefined : overrides.get(name);\n if (replacement !== undefined && replacement !== mesh.material) {\n mesh.material = replacement;\n changed += 1;\n }\n }\n const children = node.children;\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (child !== undefined) {\n changed += overrideSubtreeMaterials(child, overrides);\n }\n }\n return changed;\n}\n\n/**\n * Releases a template mesh's GPU buffers.\n *\n * @remarks\n * Lite exports no mesh disposer: a mesh's buffers are freed only when it leaves its last scene\n * (`lib/scene/scene-remove.js`). A template that was never added to a scene therefore has to be\n * added and removed to be released, which is exactly what this does. Two consequences the caller\n * must respect:\n *\n * 1. The template must carry no material, or the round trip will build and immediately tear down a\n * renderable for it. Templates created by the factories above start with none.\n * 2. Any clone still alive keeps the shared buffers: the reference count only reaches zero when the\n * last co-owner has gone. Releasing the template while clones are in a scene is safe, but the\n * template can no longer be cloned afterwards.\n *\n * @param scene - Any scene on the template's engine; it is used only as the round trip's vehicle.\n * @param template - The template to release.\n *\n * @internal\n */\nexport function disposeMeshTemplate(scene: SceneContext, template: Mesh): void {\n addToScene(scene, template);\n removeFromScene(scene, template);\n}\n\n/**\n * Collects every mesh in a subtree — the root included — in depth-first order.\n *\n * @remarks\n * A scene node that carries `material` is a mesh: the same structural test\n * {@link overrideSubtreeMaterials} and Lite's own scene walk use (`index.d.ts` 7156 declares\n * `material` on `Mesh` and nowhere on `SceneNode`, 10104).\n *\n * Call it **once**, when the subtree is instantiated. The clone tree `instantiateContainer` built\n * never changes shape afterwards, so walking it again every frame would put a recursion on the\n * render path for an answer that cannot have moved (coding standards §7).\n *\n * @param node - The subtree root.\n * @param out - The list the meshes are appended to; it is not cleared first.\n *\n * @internal\n */\nexport function collectSubtreeMeshes(node: SceneNode, out: Mesh[]): void {\n if (\"material\" in node) {\n // See the note above.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n out.push(node as Mesh);\n }\n const children = node.children;\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (child !== undefined) {\n collectSubtreeMeshes(child, out);\n }\n }\n}\n\n/**\n * What the light-probe bake reads of one drawn mesh: its CPU triangles, in the mesh's own space, its\n * material's name, and its flat diffuse colour.\n *\n * @internal\n */\nexport interface MeshBakeSurface {\n /** Three floats per vertex. */\n readonly positions: Float32Array;\n /** Three indices per triangle. */\n readonly indices: Uint32Array;\n /** The material's name (a glTF material's name in the file), or `null`. */\n readonly materialName: string | null;\n /**\n * The material's linear diffuse colour: a PBR material's `baseColorFactor` times\n * `1 − metallicFactor` (no metallic when an ORM texture drives it), a Standard material's\n * `diffuseColor`; `null` for any other family, and for a PBR material without a factor (Lite\n * bakes an untextured glTF material's colour into a texture).\n */\n readonly albedo: readonly [number, number, number] | null;\n}\n\n/**\n * Reads a drawn mesh for the light-probe bake, through Lite's `getMeshTriangles` (`index.d.ts`\n * 6798), which copies the positions and indices a mesh retains on the CPU. A glTF load retains them\n * on every mesh (`lib/loader-gltf/load-gltf.js`, `gltf-interleave.js`), and a clone spreads the\n * template's fields, so a `Model` instance's meshes answer too.\n *\n * @param mesh - The mesh.\n * @returns Its surface, or `null` when Lite kept no CPU triangles for it.\n *\n * @internal\n */\nexport function readMeshBakeSurface(mesh: Mesh): MeshBakeSurface | null {\n const triangles = getMeshTriangles(mesh);\n if (triangles === null) {\n return null;\n }\n const material: Material = mesh.material;\n const family = getMaterialFamily(material);\n let albedo: readonly [number, number, number] | null = null;\n if (family === \"pbr\") {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the family says it is a PBR material.\n const pbr = material as PbrMaterialProps;\n // An untextured glTF material's factor lives in a 1×1 texture, not here\n // (`lib/loader-gltf/gltf-pbr-builder.js`): without a factor the colour is unknown.\n const base = pbr.baseColorFactor;\n if (base !== undefined) {\n const keep = 1 - (pbr.ormTexture === undefined ? clamp01(pbr.metallicFactor ?? 1) : 0);\n albedo = [clamp01(base[0]) * keep, clamp01(base[1]) * keep, clamp01(base[2]) * keep];\n }\n } else if (family === \"standard\") {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the family says it is a Standard material.\n const standard = material as StandardMaterialProps;\n albedo = [clamp01(standard.diffuseColor[0]), clamp01(standard.diffuseColor[1]), clamp01(standard.diffuseColor[2])];\n }\n return {\n positions: triangles.positions,\n indices: triangles.indices,\n materialName: material.name ?? null,\n albedo,\n };\n}\n\n/**\n * Clamps a colour channel to `[0, 1]`, `NaN` to 0.\n *\n * @param value - The channel.\n * @returns It, clamped.\n */\nfunction clamp01(value: number): number {\n return Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : 0;\n}\n","import { Mat4 } from \"./mat4.js\";\nimport { EPSILON, lerp } from \"./math-utils.js\";\nimport type { Mat4Like, MutableVec3, Vec3Like } from \"./types.js\";\n\n/**\n * A 3-component vector: a position or a direction in metres, or a per-axis scale. ignifx is\n * left-handed with Y up and +Z forward (ADR-0011), so {@link Vec3.forward} is `(0, 0, 1)` and\n * {@link Vec3.right} is `(1, 0, 0)`.\n *\n * The fields are plain mutable numbers, which is what makes a `Vec3` interchangeable with Babylon\n * Lite's `{ x, y, z }` vectors and with the live {@link MutableVec3} views a `Transform` exposes.\n *\n * Three families of operations, and the names say which is which:\n *\n * - instance methods mutate the receiver and return `this` (`a.add(b)` means `a += b`);\n * - `ToRef` statics write into a final `out` argument, allocate nothing, and are safe when `out`\n * aliases an input — these are what per-frame code uses (coding standards section 7);\n * - the remaining statics return a fresh vector and are documented as allocating.\n *\n * @example\n * ```ts\n * // convenience code\n * const offset = Vec3.add(position, Vec3.scale(direction, distance));\n *\n * // per-frame code: no allocation\n * Vec3.scaleToRef(direction, distance, scratch);\n * Vec3.addToRef(position, scratch, position);\n * ```\n *\n * @public\n */\nexport class Vec3 {\n /** The X component; positive is right. */\n x: number;\n /** The Y component; positive is up. */\n y: number;\n /** The Z component; positive is forward. */\n z: number;\n\n /**\n * Creates a vector.\n *\n * @param x - The X component. Defaults to 0.\n * @param y - The Y component. Defaults to 0.\n * @param z - The Z component. Defaults to 0.\n */\n constructor(x: number = 0, y: number = 0, z: number = 0) {\n this.x = x;\n this.y = y;\n this.z = z;\n }\n\n /**\n * Assigns every component at once.\n *\n * @param x - The new X component.\n * @param y - The new Y component.\n * @param z - The new Z component.\n * @returns This vector.\n */\n set(x: number, y: number, z: number): this {\n this.x = x;\n this.y = y;\n this.z = z;\n return this;\n }\n\n /**\n * Copies every component from another vector.\n *\n * @param v - The vector to read.\n * @returns This vector.\n */\n copyFrom(v: Vec3Like): this {\n this.x = v.x;\n this.y = v.y;\n this.z = v.z;\n return this;\n }\n\n /**\n * Copies this vector into a new one.\n *\n * @returns A new vector. **Allocates.**\n */\n clone(): Vec3 {\n return new Vec3(this.x, this.y, this.z);\n }\n\n /**\n * Adds another vector to this one.\n *\n * @param v - The vector to add.\n * @returns This vector.\n */\n add(v: Vec3Like): this {\n this.x += v.x;\n this.y += v.y;\n this.z += v.z;\n return this;\n }\n\n /**\n * Adds a scaled vector to this one — the \"move by velocity times delta time\" step, without a\n * temporary.\n *\n * @param v - The vector to add.\n * @param scale - The factor to multiply `v` by first.\n * @returns This vector.\n *\n * @example\n * ```ts\n * position.addScaled(velocity, time.deltaTime);\n * ```\n */\n addScaled(v: Vec3Like, scale: number): this {\n this.x += v.x * scale;\n this.y += v.y * scale;\n this.z += v.z * scale;\n return this;\n }\n\n /**\n * Subtracts another vector from this one.\n *\n * @param v - The vector to subtract.\n * @returns This vector.\n */\n subtract(v: Vec3Like): this {\n this.x -= v.x;\n this.y -= v.y;\n this.z -= v.z;\n return this;\n }\n\n /**\n * Multiplies this vector by another component by component.\n *\n * @param v - The vector to multiply by.\n * @returns This vector.\n */\n multiply(v: Vec3Like): this {\n this.x *= v.x;\n this.y *= v.y;\n this.z *= v.z;\n return this;\n }\n\n /**\n * Multiplies every component by a number.\n *\n * @param scale - The factor.\n * @returns This vector.\n */\n scale(scale: number): this {\n this.x *= scale;\n this.y *= scale;\n this.z *= scale;\n return this;\n }\n\n /**\n * Flips this vector to point the other way.\n *\n * @returns This vector.\n */\n negate(): this {\n this.x = -this.x;\n this.y = -this.y;\n this.z = -this.z;\n return this;\n }\n\n /**\n * Scales this vector to unit length. A zero-length vector is left at zero rather than becoming\n * `NaN`, so callers can normalize an unchecked direction safely.\n *\n * @returns This vector.\n */\n normalize(): this {\n const length = Math.hypot(this.x, this.y, this.z);\n if (length === 0) {\n return this;\n }\n return this.scale(1 / length);\n }\n\n /**\n * Replaces this vector with its cross product with another (`this = this x v`).\n *\n * @param v - The right-hand vector.\n * @returns This vector.\n */\n cross(v: Vec3Like): this {\n return Vec3.crossToRef(this, v, this);\n }\n\n /**\n * Moves this vector towards a target by an interpolant.\n *\n * @param target - The vector reached at `t === 1`.\n * @param t - The interpolant; not clamped.\n * @returns This vector.\n */\n lerp(target: Vec3Like, t: number): this {\n return Vec3.lerpToRef(this, target, t, this);\n }\n\n /**\n * The dot product of this vector with another.\n *\n * @param v - The other vector.\n * @returns The dot product.\n */\n dot(v: Vec3Like): number {\n return this.x * v.x + this.y * v.y + this.z * v.z;\n }\n\n /**\n * The length of this vector, in metres.\n *\n * @returns The length.\n */\n length(): number {\n return Math.hypot(this.x, this.y, this.z);\n }\n\n /**\n * The squared length of this vector. Prefer it over `length()` when comparing distances:\n * it skips the square root.\n *\n * @returns The squared length.\n */\n lengthSquared(): number {\n return this.x * this.x + this.y * this.y + this.z * this.z;\n }\n\n /**\n * The distance from this vector to another, in metres.\n *\n * @param v - The other position.\n * @returns The distance.\n */\n distance(v: Vec3Like): number {\n return Math.hypot(this.x - v.x, this.y - v.y, this.z - v.z);\n }\n\n /**\n * The squared distance from this vector to another.\n *\n * @param v - The other position.\n * @returns The squared distance.\n */\n distanceSquared(v: Vec3Like): number {\n return Vec3.distanceSquared(this, v);\n }\n\n /**\n * Compares this vector with another, component by component, with a tolerance.\n *\n * @param v - The vector to compare against.\n * @param epsilon - The largest per-component difference still considered equal.\n * @returns `true` when every component matches within `epsilon`.\n */\n equalsWithEpsilon(v: Vec3Like, epsilon: number = EPSILON): boolean {\n return Vec3.equalsWithEpsilon(this, v, epsilon);\n }\n\n /**\n * Writes this vector into a `Float32Array`, for GPU upload. The output comes first to mirror\n * Babylon Lite's `ObservableVec3.toArray`, the shape the adapter has to interoperate with.\n *\n * @param out - The array to write into.\n * @param offset - The index of the X component. Defaults to 0.\n * @returns `out`.\n */\n toArray(out: Float32Array, offset: number = 0): Float32Array {\n out[offset] = this.x;\n out[offset + 1] = this.y;\n out[offset + 2] = this.z;\n return out;\n }\n\n /**\n * The zero vector.\n *\n * @returns A new `(0, 0, 0)`. **Allocates**; use {@link VEC3_ZERO} when a read-only value will do.\n */\n static zero(): Vec3 {\n return new Vec3(0, 0, 0);\n }\n\n /**\n * The vector whose components are all one.\n *\n * @returns A new `(1, 1, 1)`. **Allocates.**\n */\n static one(): Vec3 {\n return new Vec3(1, 1, 1);\n }\n\n /**\n * The world up direction.\n *\n * @returns A new `(0, 1, 0)`. **Allocates**; see {@link VEC3_UP}.\n */\n static up(): Vec3 {\n return new Vec3(0, 1, 0);\n }\n\n /**\n * The world down direction.\n *\n * @returns A new `(0, -1, 0)`. **Allocates.**\n */\n static down(): Vec3 {\n return new Vec3(0, -1, 0);\n }\n\n /**\n * The world right direction.\n *\n * @returns A new `(1, 0, 0)`. **Allocates**; see {@link VEC3_RIGHT}.\n */\n static right(): Vec3 {\n return new Vec3(1, 0, 0);\n }\n\n /**\n * The world left direction.\n *\n * @returns A new `(-1, 0, 0)`. **Allocates.**\n */\n static left(): Vec3 {\n return new Vec3(-1, 0, 0);\n }\n\n /**\n * The world forward direction. ignifx is left-handed, so forward is **+Z** (ADR-0011).\n *\n * @returns A new `(0, 0, 1)`. **Allocates**; see {@link VEC3_FORWARD}.\n */\n static forward(): Vec3 {\n return new Vec3(0, 0, 1);\n }\n\n /**\n * The world backward direction.\n *\n * @returns A new `(0, 0, -1)`. **Allocates.**\n */\n static backward(): Vec3 {\n return new Vec3(0, 0, -1);\n }\n\n /**\n * Copies any vector-shaped value into a `Vec3`.\n *\n * @param v - The vector to copy.\n * @returns A new vector. **Allocates.**\n *\n * @example\n * ```ts\n * const position = Vec3.from(node.position); // snapshot of a live Lite view\n * ```\n */\n static from(v: Vec3Like): Vec3 {\n return new Vec3(v.x, v.y, v.z);\n }\n\n /**\n * Adds two vectors.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @returns A new vector. **Allocates**; use {@link Vec3.addToRef} in per-frame code.\n */\n static add(a: Vec3Like, b: Vec3Like): Vec3 {\n return Vec3.addToRef(a, b, new Vec3());\n }\n\n /**\n * Subtracts one vector from another.\n *\n * @param a - The vector to subtract from.\n * @param b - The vector to subtract.\n * @returns A new vector holding `a - b`. **Allocates.**\n */\n static subtract(a: Vec3Like, b: Vec3Like): Vec3 {\n return Vec3.subtractToRef(a, b, new Vec3());\n }\n\n /**\n * Multiplies a vector by a number.\n *\n * @param v - The vector to scale.\n * @param scale - The factor.\n * @returns A new vector. **Allocates.**\n */\n static scale(v: Vec3Like, scale: number): Vec3 {\n return Vec3.scaleToRef(v, scale, new Vec3());\n }\n\n /**\n * The cross product of two vectors.\n *\n * @param a - The left-hand vector.\n * @param b - The right-hand vector.\n * @returns A new vector holding `a x b`. **Allocates.**\n */\n static cross(a: Vec3Like, b: Vec3Like): Vec3 {\n return Vec3.crossToRef(a, b, new Vec3());\n }\n\n /**\n * A unit-length copy of a vector.\n *\n * @param v - The vector to normalize.\n * @returns A new vector. **Allocates.**\n */\n static normalize(v: Vec3Like): Vec3 {\n return Vec3.normalizeToRef(v, new Vec3());\n }\n\n /**\n * Linearly interpolates between two vectors.\n *\n * @param a - The vector returned at `t === 0`.\n * @param b - The vector returned at `t === 1`.\n * @param t - The interpolant; not clamped.\n * @returns A new vector. **Allocates.**\n */\n static lerp(a: Vec3Like, b: Vec3Like, t: number): Vec3 {\n return Vec3.lerpToRef(a, b, t, new Vec3());\n }\n\n /**\n * Writes `a + b` into `out`.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static addToRef<TOut extends MutableVec3>(a: Vec3Like, b: Vec3Like, out: TOut): TOut {\n out.set(a.x + b.x, a.y + b.y, a.z + b.z);\n return out;\n }\n\n /**\n * Writes `a - b` into `out`.\n *\n * @param a - The vector to subtract from.\n * @param b - The vector to subtract.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static subtractToRef<TOut extends MutableVec3>(a: Vec3Like, b: Vec3Like, out: TOut): TOut {\n out.set(a.x - b.x, a.y - b.y, a.z - b.z);\n return out;\n }\n\n /**\n * Writes the component-wise product `a * b` into `out`.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static multiplyToRef<TOut extends MutableVec3>(a: Vec3Like, b: Vec3Like, out: TOut): TOut {\n out.set(a.x * b.x, a.y * b.y, a.z * b.z);\n return out;\n }\n\n /**\n * Writes `v * scale` into `out`.\n *\n * @param v - The vector to scale.\n * @param scale - The factor.\n * @param out - The vector to write; may alias `v`.\n * @returns `out`.\n */\n static scaleToRef<TOut extends MutableVec3>(v: Vec3Like, scale: number, out: TOut): TOut {\n out.set(v.x * scale, v.y * scale, v.z * scale);\n return out;\n }\n\n /**\n * Writes `-v` into `out`.\n *\n * @param v - The vector to flip.\n * @param out - The vector to write; may alias `v`.\n * @returns `out`.\n */\n static negateToRef<TOut extends MutableVec3>(v: Vec3Like, out: TOut): TOut {\n out.set(-v.x, -v.y, -v.z);\n return out;\n }\n\n /**\n * Writes a unit-length copy of `v` into `out`. A zero-length input is written as zero rather than\n * `NaN`.\n *\n * @param v - The vector to normalize.\n * @param out - The vector to write; may alias `v`.\n * @returns `out`.\n */\n static normalizeToRef<TOut extends MutableVec3>(v: Vec3Like, out: TOut): TOut {\n const length = Math.hypot(v.x, v.y, v.z);\n if (length === 0) {\n out.set(0, 0, 0);\n return out;\n }\n const inv = 1 / length;\n out.set(v.x * inv, v.y * inv, v.z * inv);\n return out;\n }\n\n /**\n * Writes `a x b` into `out`.\n *\n * @param a - The left-hand vector.\n * @param b - The right-hand vector.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static crossToRef<TOut extends MutableVec3>(a: Vec3Like, b: Vec3Like, out: TOut): TOut {\n const ax = a.x;\n const ay = a.y;\n const az = a.z;\n const bx = b.x;\n const by = b.y;\n const bz = b.z;\n out.set(ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx);\n return out;\n }\n\n /**\n * Writes the interpolation of `a` and `b` into `out`.\n *\n * @param a - The vector written at `t === 0`.\n * @param b - The vector written at `t === 1`.\n * @param t - The interpolant; not clamped.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static lerpToRef<TOut extends MutableVec3>(a: Vec3Like, b: Vec3Like, t: number, out: TOut): TOut {\n out.set(lerp(a.x, b.x, t), lerp(a.y, b.y, t), lerp(a.z, b.z, t));\n return out;\n }\n\n /**\n * Writes the component-wise minimum of two vectors into `out`.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static minToRef<TOut extends MutableVec3>(a: Vec3Like, b: Vec3Like, out: TOut): TOut {\n out.set(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.min(a.z, b.z));\n return out;\n }\n\n /**\n * Writes the component-wise maximum of two vectors into `out`.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static maxToRef<TOut extends MutableVec3>(a: Vec3Like, b: Vec3Like, out: TOut): TOut {\n out.set(Math.max(a.x, b.x), Math.max(a.y, b.y), Math.max(a.z, b.z));\n return out;\n }\n\n /**\n * Transforms a **position** by a matrix into `out`: the matrix's translation is applied and the\n * result is divided by w, so a projection matrix gives clip-space coordinates.\n *\n * @param v - The position to transform, in metres.\n * @param m - The transformation, column-major.\n * @param out - The vector to write; may alias `v`.\n * @returns `out`.\n *\n * @example\n * ```ts\n * Vec3.transformCoordinatesToRef(localPoint, node.worldMatrix, worldPoint);\n * ```\n */\n static transformCoordinatesToRef<TOut extends MutableVec3>(v: Vec3Like, m: Mat4Like, out: TOut): TOut {\n return Mat4.transformPointToRef(m, v, out);\n }\n\n /**\n * Transforms a **direction** by a matrix into `out`, ignoring the matrix's translation.\n *\n * @param v - The direction to transform.\n * @param m - The transformation, column-major.\n * @param out - The vector to write; may alias `v`.\n * @returns `out`.\n */\n static transformNormalToRef<TOut extends MutableVec3>(v: Vec3Like, m: Mat4Like, out: TOut): TOut {\n return Mat4.transformDirectionToRef(m, v, out);\n }\n\n /**\n * The dot product of two vectors.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @returns The dot product.\n */\n static dot(a: Vec3Like, b: Vec3Like): number {\n return a.x * b.x + a.y * b.y + a.z * b.z;\n }\n\n /**\n * The length of a vector, in metres.\n *\n * @param v - The vector to measure.\n * @returns The length.\n */\n static length(v: Vec3Like): number {\n return Math.hypot(v.x, v.y, v.z);\n }\n\n /**\n * The squared length of a vector.\n *\n * @param v - The vector to measure.\n * @returns The squared length.\n */\n static lengthSquared(v: Vec3Like): number {\n return v.x * v.x + v.y * v.y + v.z * v.z;\n }\n\n /**\n * The distance between two positions, in metres.\n *\n * @param a - The first position.\n * @param b - The second position.\n * @returns The distance.\n */\n static distance(a: Vec3Like, b: Vec3Like): number {\n return Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);\n }\n\n /**\n * The squared distance between two positions. Compare squared distances to avoid a square root.\n *\n * @param a - The first position.\n * @param b - The second position.\n * @returns The squared distance.\n */\n static distanceSquared(a: Vec3Like, b: Vec3Like): number {\n const dx = a.x - b.x;\n const dy = a.y - b.y;\n const dz = a.z - b.z;\n return dx * dx + dy * dy + dz * dz;\n }\n\n /**\n * Compares two vectors component by component, with a tolerance.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @param epsilon - The largest per-component difference still considered equal.\n * @returns `true` when every component matches within `epsilon`.\n */\n static equalsWithEpsilon(a: Vec3Like, b: Vec3Like, epsilon: number = EPSILON): boolean {\n return Math.abs(a.x - b.x) <= epsilon && Math.abs(a.y - b.y) <= epsilon && Math.abs(a.z - b.z) <= epsilon;\n }\n}\n\n/**\n * The frozen zero vector, `(0, 0, 0)`. Read-only: pass it anywhere a {@link Vec3Like} is wanted, and\n * call {@link Vec3.zero} when you need a vector you can write to.\n *\n * @public\n */\nexport const VEC3_ZERO: Vec3Like = Object.freeze({ x: 0, y: 0, z: 0 });\n\n/**\n * The frozen vector whose components are all one, `(1, 1, 1)` — the identity scale.\n *\n * @public\n */\nexport const VEC3_ONE: Vec3Like = Object.freeze({ x: 1, y: 1, z: 1 });\n\n/**\n * The frozen world up direction, `(0, 1, 0)`.\n *\n * @public\n */\nexport const VEC3_UP: Vec3Like = Object.freeze({ x: 0, y: 1, z: 0 });\n\n/**\n * The frozen world down direction, `(0, -1, 0)`.\n *\n * @public\n */\nexport const VEC3_DOWN: Vec3Like = Object.freeze({ x: 0, y: -1, z: 0 });\n\n/**\n * The frozen world right direction, `(1, 0, 0)`.\n *\n * @public\n */\nexport const VEC3_RIGHT: Vec3Like = Object.freeze({ x: 1, y: 0, z: 0 });\n\n/**\n * The frozen world left direction, `(-1, 0, 0)`.\n *\n * @public\n */\nexport const VEC3_LEFT: Vec3Like = Object.freeze({ x: -1, y: 0, z: 0 });\n\n/**\n * The frozen world forward direction, `(0, 0, 1)`. ignifx is left-handed, so forward is +Z\n * (ADR-0011).\n *\n * @public\n */\nexport const VEC3_FORWARD: Vec3Like = Object.freeze({ x: 0, y: 0, z: 1 });\n\n/**\n * The frozen world backward direction, `(0, 0, -1)`.\n *\n * @public\n */\nexport const VEC3_BACKWARD: Vec3Like = Object.freeze({ x: 0, y: 0, z: -1 });\n"],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AAO,OAAO;CAAE,GAAG;CAAG,GAAG;CAAG,GAAG;AAAG,CAAC"}
1
+ {"version":3,"file":"vec3-2C3LBZnt.js","names":["updateMeshPositions","updateMeshNormals","updateMeshUvs","updateMeshColors"],"sources":["../src/lite/gpu/mesh.ts","../src/math/vec3.ts"],"sourcesContent":["import {\n addToScene,\n cloneTransformNode,\n createBox,\n createCapsule,\n createCylinder,\n createGround,\n createMeshFromData,\n createPlane,\n createSphere,\n createTorus,\n getMaterialFamily,\n getMeshTriangles,\n removeFromScene,\n setSubtreeVisible,\n updateMeshColors as liteUpdateMeshColors,\n updateMeshNormals as liteUpdateMeshNormals,\n updateMeshPositions as liteUpdateMeshPositions,\n updateMeshUvs as liteUpdateMeshUvs,\n} from \"@babylonjs/lite\";\nimport type {\n BoxOptions,\n CapsuleOptions,\n CylinderOptions,\n EngineContext,\n GroundOptions,\n Material,\n Mesh,\n PbrMaterialProps,\n PlaneOptions,\n SceneContext,\n SceneNode,\n SphereOptions,\n StandardMaterialProps,\n TorusOptions,\n} from \"@babylonjs/lite\";\n\n/**\n * Mesh half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §2.3). Every function\n * here needs a WebGPU device — `createMeshFromData` uploads four vertex buffers through\n * `engine._device` (`lib/mesh/mesh.js`, `uploadMeshToGPU`) and the null engine has no `_device` —\n * so the whole module lives under `src/lite/gpu/` and is covered by the browser test project.\n *\n * Everything here is `@internal`.\n *\n * ## Ownership, cloning, and disposal (verified against `@babylonjs/lite@1.27.0`)\n *\n * - `cloneTransformNode(mesh)` (`index.d.ts` 1776, `lib/scene/transform-node.js`) shallow-clones a\n * mesh: the clone gets a fresh transform and **the same `_gpu` wrapper object**, with\n * `retain(_gpu)` bumping a reference count. So N clones of one template share exactly one set of\n * GPU buffers — instancing shares GPU buffers, and that is provable by\n * object identity rather than by measuring memory.\n * - Disposal is driven entirely by scene membership. `removeFromScene` calls `unregisterMeshScene`,\n * and only when the mesh has left its **last** scene does it queue `disposeMeshGpu`, which calls\n * `release(_gpu)` and destroys the buffers only when the count drops to one\n * (`lib/scene/scene-remove.js`, `lib/mesh/mesh-dispose.js`, `lib/resource/ref-count.js`). A\n * template that is never added to a scene therefore keeps its buffers alive no matter how many\n * clones come and go — which is what `docs/architecture/07-rendering.md` §2.3 means by \"the\n * template's buffers stay alive while the asset is retained\".\n * - The flip side is that Lite exports **no** mesh disposer. The only public way to release a\n * template's buffers is {@link disposeMeshTemplate}: add it to a scene and take it out again.\n * - `removeFromScene` also recursively removes a mesh's `children` and nulls its `parent`, so\n * removing a `Model`'s root removes the whole instantiated subtree in one call.\n * - Hiding is `setSubtreeVisible` (exported as `setMeshVisible` too, `index.d.ts` 11199): it\n * cascades `visible` down the subtree and bumps a global visibility epoch. Never remove a mesh\n * from the scene to hide it — that disposes it.\n *\n * ## Updating a mesh's vertices (verified against `lib/mesh/mesh-factories.js`)\n *\n * `updateMesh*` writes the GPU buffer and **nothing else**. Three consequences, all of them\n * surprising enough to be worth stating where the calls are:\n *\n * 1. **The retained CPU arrays are not replaced.** `createMeshFromData` keeps `_cpuPositions`,\n * `_cpuNormals`, `_cpuUvs` and `_cpuIndices` — the arrays it was handed — and Lite's CPU ray\n * pick reads them (`lib/picking/ray-pick.js`). Only `updateMeshGeometry`/`resizeMeshGeometry`\n * re-retain, through `retainMeshGeometry`. So an update that hands over a *different* array\n * leaves picking looking at the old geometry, while an update after mutating the retained array\n * in place leaves picking exact. `MeshAsset` keeps its own copy in step for that reason.\n * 2. **Bounds are not recomputed.** `retainMeshGeometry` is what calls `computeAabb` and writes\n * `boundMin`/`boundMax`; the partial updaters do not. `Mesh`'s own declaration says a consumer\n * \"MAY overwrite these with a wider hand-computed box\", so {@link setMeshBounds} exists and\n * `MeshAsset.updatePositions` uses it.\n * 3. **A cloned template cannot be updated at all.** `writeVertexAttributeRange` throws\n * (`ThrowLiteError(360)`) when `mesh._gpu._refCount > 1`, and cloning a mesh retains that very\n * wrapper. A `MeshAsset` a `MeshRenderer` has drawn is therefore frozen; a mesh meant to be\n * edited is a renderable of its own, which is the shape the terrain chunk adapter uses.\n */\n\n/**\n * The Babylon Lite mesh a `MeshAsset` template and a `MeshRenderer` clone are, re-exported under an\n * ignifx name so feature code can name the type without importing `@babylonjs/lite`\n * (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * @remarks\n * Unstable: it is Lite's own type, reachable only through documented `.lite` escape hatches, and it\n * is excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteMesh = Mesh;\n\n/**\n * Creates a box template.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - A uniform size, or per-axis dimensions.\n * @returns The mesh. It belongs to no scene yet.\n *\n * @example\n * ```ts\n * const template = createBoxMesh(engine, { size: 2 });\n * const instance = cloneMeshUnderNode(template, entityNode);\n * addMeshToScene(scene, instance);\n * ```\n *\n * @internal\n */\nexport function createBoxMesh(engine: EngineContext, options?: number | BoxOptions): Mesh {\n return createBox(engine, options);\n}\n\n/**\n * Creates a sphere template.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Segment count and diameters.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createSphereMesh(engine: EngineContext, options?: SphereOptions): Mesh {\n return createSphere(engine, options);\n}\n\n/**\n * Creates a plane template in the XY plane.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Size, or width and height.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createPlaneMesh(engine: EngineContext, options?: PlaneOptions): Mesh {\n return createPlane(engine, options);\n}\n\n/**\n * Creates a subdivided ground template in the XZ plane.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Width, height, subdivisions, and UV scale.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createGroundMesh(engine: EngineContext, options?: GroundOptions): Mesh {\n return createGround(engine, options);\n}\n\n/**\n * Creates a cylinder template along the Y axis.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Height, diameters, and tessellation.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createCylinderMesh(engine: EngineContext, options?: CylinderOptions): Mesh {\n return createCylinder(engine, options);\n}\n\n/**\n * Creates a capsule template along the Y axis.\n *\n * @remarks\n * `height` is the **total** height including both caps (`index.d.ts` 1523), which is the same\n * convention `@ignifx/physics`'s capsule collider uses, so a renderer and a collider built from one\n * pair of numbers line up.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Height, radius, and tessellation.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createCapsuleMesh(engine: EngineContext, options?: CapsuleOptions): Mesh {\n return createCapsule(engine, options);\n}\n\n/**\n * Creates a torus template in the XZ plane.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param options - Diameter, thickness, and tessellation.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createTorusMesh(engine: EngineContext, options?: TorusOptions): Mesh {\n return createTorus(engine, options);\n}\n\n/**\n * Creates a mesh from raw vertex data.\n *\n * @remarks\n * Lite keeps a reference to the arrays that are handed in — it does not copy them — and uses them\n * for CPU ray picking and bounds (`lib/mesh/mesh-factories.js`). Callers must not mutate them\n * afterwards.\n *\n * @param engine - The engine that owns the GPU buffers.\n * @param name - A debug name.\n * @param positions - Three floats per vertex.\n * @param normals - Three floats per vertex.\n * @param indices - Three indices per triangle.\n * @param uvs - Two floats per vertex, or omitted.\n * @param uvs2 - Two floats per vertex for the second UV set, or omitted.\n * @param tangents - Four floats per vertex, or omitted.\n * @param colors - Four floats per vertex, or omitted.\n * @returns The mesh.\n *\n * @internal\n */\nexport function createMeshFromGeometry(\n engine: EngineContext,\n name: string,\n positions: Float32Array,\n normals: Float32Array,\n indices: Uint32Array,\n uvs?: Float32Array,\n uvs2?: Float32Array,\n tangents?: Float32Array,\n colors?: Float32Array,\n): Mesh {\n return createMeshFromData(engine, name, positions, normals, indices, uvs, uvs2, tangents, colors);\n}\n\n/**\n * Re-uploads part of a mesh's position buffer.\n *\n * @remarks\n * A no-op range is accepted; an out-of-range one, or a mesh whose GPU geometry has co-owners,\n * throws a Lite error (see the module note). It does **not** refresh the CPU picking geometry or\n * the bounds.\n *\n * @param engine - The engine that owns the buffer.\n * @param mesh - The mesh to update.\n * @param positions - Three floats per vertex, read from index 0.\n * @param vertexOffset - The first destination vertex to overwrite.\n * @param vertexCount - How many vertices to write.\n *\n * @internal\n */\nexport function updateMeshPositions(\n engine: EngineContext,\n mesh: Mesh,\n positions: Float32Array,\n vertexOffset: number,\n vertexCount: number,\n): void {\n liteUpdateMeshPositions(engine, mesh, positions, vertexOffset, vertexCount);\n}\n\n/**\n * Re-uploads part of a mesh's normal buffer.\n *\n * @param engine - The engine that owns the buffer.\n * @param mesh - The mesh to update.\n * @param normals - Three floats per vertex.\n * @param vertexOffset - The first destination vertex to overwrite.\n * @param vertexCount - How many vertices to write.\n *\n * @internal\n */\nexport function updateMeshNormals(\n engine: EngineContext,\n mesh: Mesh,\n normals: Float32Array,\n vertexOffset: number,\n vertexCount: number,\n): void {\n liteUpdateMeshNormals(engine, mesh, normals, vertexOffset, vertexCount);\n}\n\n/**\n * Re-uploads part of a mesh's UV buffer.\n *\n * @remarks\n * Lite makes it a no-op when the mesh was created without UVs, rather than an error.\n *\n * @param engine - The engine that owns the buffer.\n * @param mesh - The mesh to update.\n * @param uvs - Two floats per vertex.\n * @param vertexOffset - The first destination vertex to overwrite.\n * @param vertexCount - How many vertices to write.\n *\n * @internal\n */\nexport function updateMeshUvs(\n engine: EngineContext,\n mesh: Mesh,\n uvs: Float32Array,\n vertexOffset: number,\n vertexCount: number,\n): void {\n liteUpdateMeshUvs(engine, mesh, uvs, vertexOffset, vertexCount);\n}\n\n/**\n * Re-uploads part of a mesh's vertex-colour buffer.\n *\n * @remarks\n * The colour attribute is `vec4`, and Lite makes the call a no-op when the mesh was created without\n * colours.\n *\n * @param engine - The engine that owns the buffer.\n * @param mesh - The mesh to update.\n * @param colors - Four floats per vertex.\n * @param vertexOffset - The first destination vertex to overwrite.\n * @param vertexCount - How many vertices to write.\n *\n * @internal\n */\nexport function updateMeshColors(\n engine: EngineContext,\n mesh: Mesh,\n colors: Float32Array,\n vertexOffset: number,\n vertexCount: number,\n): void {\n liteUpdateMeshColors(engine, mesh, colors, vertexOffset, vertexCount);\n}\n\n/**\n * Writes a mesh's object-local bounding box.\n *\n * @remarks\n * `Mesh.boundMin`/`boundMax` are declared consumer-writable, and writing them is the only way to\n * keep the shadow fit, the thin-instance culler and the Havok shape extents honest after a partial\n * vertex update — none of the partial updaters recomputes them. The existing arrays are mutated in\n * place when they are there, so repeated sculpting allocates nothing.\n *\n * @param mesh - The mesh to re-bound.\n * @param minX - The smallest X.\n * @param minY - The smallest Y.\n * @param minZ - The smallest Z.\n * @param maxX - The largest X.\n * @param maxY - The largest Y.\n * @param maxZ - The largest Z.\n *\n * @internal\n */\nexport function setMeshBounds(\n mesh: Mesh,\n minX: number,\n minY: number,\n minZ: number,\n maxX: number,\n maxY: number,\n maxZ: number,\n): void {\n const boundMin = mesh.boundMin;\n if (boundMin === undefined) {\n mesh.boundMin = [minX, minY, minZ];\n } else {\n boundMin[0] = minX;\n boundMin[1] = minY;\n boundMin[2] = minZ;\n }\n const boundMax = mesh.boundMax;\n if (boundMax === undefined) {\n mesh.boundMax = [maxX, maxY, maxZ];\n } else {\n boundMax[0] = maxX;\n boundMax[1] = maxY;\n boundMax[2] = maxZ;\n }\n}\n\n/**\n * Gives a cloned mesh bounding-box arrays of its own.\n *\n * @remarks\n * `cloneMeshNode` shallow-spreads the template (`lib/scene/transform-node.js`), so a clone starts\n * out sharing the template's `boundMin`/`boundMax` arrays and {@link setMeshBounds} — which mutates\n * in place — would write through to the template and to every other clone. Any caller that re-bounds\n * one clone alone has to call this first.\n *\n * @param mesh - The clone.\n *\n * @internal\n */\nexport function detachMeshBounds(mesh: Mesh): void {\n const boundMin = mesh.boundMin;\n if (boundMin !== undefined) {\n mesh.boundMin = [boundMin[0], boundMin[1], boundMin[2]];\n }\n const boundMax = mesh.boundMax;\n if (boundMax !== undefined) {\n mesh.boundMax = [boundMax[0], boundMax[1], boundMax[2]];\n }\n}\n\n/**\n * Recomputes a mesh's object-local bounding box from a position array and writes it.\n *\n * @remarks\n * The partial vertex updaters leave `boundMin`/`boundMax` alone (see the module note), and every\n * consumer that fits a shadow cascade, culls a thin instance, or measures a Havok shape reads them.\n * One linear pass, no allocation. A position array too short to hold one vertex leaves the bounds\n * as they were.\n *\n * @param mesh - The mesh to re-bound.\n * @param positions - Three floats per vertex.\n *\n * @internal\n */\nexport function recomputeMeshBounds(mesh: Mesh, positions: Float32Array): void {\n if (positions.length < 3) {\n return;\n }\n let minX = Number.POSITIVE_INFINITY;\n let minY = Number.POSITIVE_INFINITY;\n let minZ = Number.POSITIVE_INFINITY;\n let maxX = Number.NEGATIVE_INFINITY;\n let maxY = Number.NEGATIVE_INFINITY;\n let maxZ = Number.NEGATIVE_INFINITY;\n for (let index = 0; index + 2 < positions.length; index += 3) {\n const x = positions[index] ?? 0;\n const y = positions[index + 1] ?? 0;\n const z = positions[index + 2] ?? 0;\n minX = x < minX ? x : minX;\n minY = y < minY ? y : minY;\n minZ = z < minZ ? z : minZ;\n maxX = x > maxX ? x : maxX;\n maxY = y > maxY ? y : maxY;\n maxZ = z > maxZ ? z : maxZ;\n }\n setMeshBounds(mesh, minX, minY, minZ, maxX, maxY, maxZ);\n}\n\n/**\n * Clones a template — mesh or transform-node subtree — and parents the clone under an entity node.\n *\n * @remarks\n * The clone shares the template's GPU buffers (see the module note). Cloning a mesh whose buffers\n * were already released throws, which is Lite's way of telling you the template outlived its asset.\n *\n * Only the `parent` link is written; the clone is deliberately **not** pushed into the parent's\n * `children` array, for the same reason cameras and lights are not (`./camera.ts`): ignifx\n * transform nodes are never added to a Lite scene, so nothing in Lite walks their children, and\n * `removeFromScene` nulls a removed mesh's `parent` without touching the array it was listed in —\n * so maintaining it would only create a stale entry to clean up.\n *\n * @param template - The mesh or subtree to clone.\n * @param parent - The entity's transform node, or `null` for world space.\n * @returns The cloned root. Add it to the scene with {@link addMeshToScene}.\n *\n * @internal\n */\nexport function cloneMeshUnderNode(template: SceneNode, parent: SceneNode | null): SceneNode {\n const clone = cloneTransformNode(template);\n clone.parent = parent;\n return clone;\n}\n\n/**\n * Adds a mesh — or a transform-node subtree containing meshes — to a render scene.\n *\n * @remarks\n * `addToScene` recurses into `children` and re-parents each one, so a whole instantiated model goes\n * in with one call. When the scene is already registered, the mesh joins Lite's runtime\n * material-swap queue and appears once its material family's renderable has been rebuilt\n * (`docs/architecture/07-rendering.md` §1.1 and ADR-0014).\n *\n * @param scene - The render scene.\n * @param node - The mesh or subtree root to add.\n *\n * @internal\n */\nexport function addMeshToScene(scene: SceneContext, node: SceneNode): void {\n addToScene(scene, node);\n}\n\n/**\n * Removes a mesh — and everything under it — from a render scene, releasing its GPU buffers when it\n * has left its last scene.\n *\n * @remarks\n * This is destruction, not hiding: use {@link setMeshSubtreeVisible} to hide.\n *\n * @param scene - The render scene.\n * @param node - The mesh or subtree root to remove.\n *\n * @internal\n */\nexport function removeMeshFromScene(scene: SceneContext, node: SceneNode): void {\n removeFromScene(scene, node);\n}\n\n/**\n * Shows or hides a mesh and everything under it.\n *\n * @param node - The subtree root.\n * @param visible - `true` to show it, `false` to hide it.\n *\n * @internal\n */\nexport function setMeshSubtreeVisible(node: SceneNode, visible: boolean): void {\n setSubtreeVisible(node, visible);\n}\n\n/**\n * Assigns a mesh's material.\n *\n * @remarks\n * `Mesh.material` is an accessor once the mesh has joined a scene: writing it queues a material\n * swap on every scene the mesh belongs to (`lib/scene/mesh-scene-registry.js`,\n * `installMaterialSetter`). Assigning the material the mesh already has is a no-op.\n *\n * @param mesh - The mesh to change.\n * @param material - The material to draw it with.\n *\n * @internal\n */\nexport function setMeshMaterial(mesh: Mesh, material: Material): void {\n mesh.material = material;\n}\n\n/**\n * Sets whether a mesh is darkened by shadow maps.\n *\n * @param mesh - The mesh to change.\n * @param receiveShadows - `true` to sample shadow maps on this mesh.\n *\n * @internal\n */\nexport function setMeshReceiveShadows(mesh: Mesh, receiveShadows: boolean): void {\n mesh.receiveShadows = receiveShadows;\n}\n\n/**\n * Sets a mesh's sort key within its phase. Lower values are drawn first.\n *\n * @param mesh - The mesh to change.\n * @param renderOrder - The sort key; it only orders within the opaque or the transparent phase.\n *\n * @internal\n */\nexport function setMeshRenderOrder(mesh: Mesh, renderOrder: number): void {\n mesh.renderOrder = renderOrder;\n}\n\n/**\n * Sets whether picking considers a mesh at all.\n *\n * @remarks\n * `pickable === false` removes the mesh from both the GPU picker's candidate list and the CPU ray\n * test, so it neither occludes nor returns a hit (`index.d.ts` 7214, `lib/picking/ray-pick.js`).\n *\n * @param mesh - The mesh to change.\n * @param pickable - `true` to allow picking.\n *\n * @internal\n */\nexport function setMeshPickable(mesh: Mesh, pickable: boolean): void {\n mesh.pickable = pickable;\n}\n\n/**\n * Gives a mesh the string id Lite's light include/exclude sets match on.\n *\n * @param mesh - The mesh to name.\n * @param id - The id. It should be unique within the scene.\n *\n * @internal\n */\nexport function setMeshId(mesh: Mesh, id: string): void {\n mesh.id = id;\n}\n\n/**\n * Replaces the materials of every mesh in a subtree whose current material carries one of the given\n * names.\n *\n * @remarks\n * `Material.name` is \"populated by loaders from the source asset (e.g. the glTF material name) so\n * callers can look a material up by name\" (`index.d.ts`), which is the identifier\n * `docs/architecture/07-rendering.md` §2.4 means by \"by material name\". Assigning `Mesh.material`\n * queues a material swap on every scene the mesh belongs to; assigning the material a mesh already\n * has is a no-op, so re-running this is cheap.\n *\n * @param node - The subtree root.\n * @param overrides - Source material name to replacement material.\n * @returns How many meshes were re-materialled.\n *\n * @internal\n */\nexport function overrideSubtreeMaterials(node: SceneNode, overrides: ReadonlyMap<string, Material>): number {\n let changed = 0;\n if (\"material\" in node) {\n // A scene node that carries `material` is a mesh —\n // the same structural test Lite's own scene walk uses.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const mesh = node as Mesh;\n const name = mesh.material.name;\n const replacement = name === undefined ? undefined : overrides.get(name);\n if (replacement !== undefined && replacement !== mesh.material) {\n mesh.material = replacement;\n changed += 1;\n }\n }\n const children = node.children;\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (child !== undefined) {\n changed += overrideSubtreeMaterials(child, overrides);\n }\n }\n return changed;\n}\n\n/**\n * Releases a template mesh's GPU buffers.\n *\n * @remarks\n * Lite exports no mesh disposer: a mesh's buffers are freed only when it leaves its last scene\n * (`lib/scene/scene-remove.js`). A template that was never added to a scene therefore has to be\n * added and removed to be released, which is exactly what this does. Two consequences the caller\n * must respect:\n *\n * 1. The template must carry no material, or the round trip will build and immediately tear down a\n * renderable for it. Templates created by the factories above start with none.\n * 2. Any clone still alive keeps the shared buffers: the reference count only reaches zero when the\n * last co-owner has gone. Releasing the template while clones are in a scene is safe, but the\n * template can no longer be cloned afterwards.\n *\n * @param scene - Any scene on the template's engine; it is used only as the round trip's vehicle.\n * @param template - The template to release.\n *\n * @internal\n */\nexport function disposeMeshTemplate(scene: SceneContext, template: Mesh): void {\n addToScene(scene, template);\n removeFromScene(scene, template);\n}\n\n/**\n * Collects every mesh in a subtree — the root included — in depth-first order.\n *\n * @remarks\n * A scene node that carries `material` is a mesh: the same structural test\n * {@link overrideSubtreeMaterials} and Lite's own scene walk use (`index.d.ts` 7156 declares\n * `material` on `Mesh` and nowhere on `SceneNode`, 10104).\n *\n * Call it **once**, when the subtree is instantiated. The clone tree `instantiateContainer` built\n * never changes shape afterwards, so walking it again every frame would put a recursion on the\n * render path for an answer that cannot have moved (coding standards §7).\n *\n * @param node - The subtree root.\n * @param out - The list the meshes are appended to; it is not cleared first.\n *\n * @internal\n */\nexport function collectSubtreeMeshes(node: SceneNode, out: Mesh[]): void {\n if (\"material\" in node) {\n // See the note above.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n out.push(node as Mesh);\n }\n const children = node.children;\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (child !== undefined) {\n collectSubtreeMeshes(child, out);\n }\n }\n}\n\n/**\n * What the light-probe bake reads of one drawn mesh: its CPU triangles, in the mesh's own space, its\n * material's name, and its flat diffuse colour.\n *\n * @internal\n */\nexport interface MeshBakeSurface {\n /** Three floats per vertex. */\n readonly positions: Float32Array;\n /** Three indices per triangle. */\n readonly indices: Uint32Array;\n /** The material's name (a glTF material's name in the file), or `null`. */\n readonly materialName: string | null;\n /**\n * The material's linear diffuse colour: a PBR material's `baseColorFactor` times\n * `1 − metallicFactor` (no metallic when an ORM texture drives it), a Standard material's\n * `diffuseColor`; `null` for any other family, and for a PBR material without a factor (Lite\n * bakes an untextured glTF material's colour into a texture).\n */\n readonly albedo: readonly [number, number, number] | null;\n}\n\n/**\n * Reads a drawn mesh for the light-probe bake, through Lite's `getMeshTriangles` (`index.d.ts`\n * 6798), which copies the positions and indices a mesh retains on the CPU. A glTF load retains them\n * on every mesh (`lib/loader-gltf/load-gltf.js`, `gltf-interleave.js`), and a clone spreads the\n * template's fields, so a `Model` instance's meshes answer too.\n *\n * @param mesh - The mesh.\n * @returns Its surface, or `null` when Lite kept no CPU triangles for it.\n *\n * @internal\n */\nexport function readMeshBakeSurface(mesh: Mesh): MeshBakeSurface | null {\n const triangles = getMeshTriangles(mesh);\n if (triangles === null) {\n return null;\n }\n const material: Material = mesh.material;\n const family = getMaterialFamily(material);\n let albedo: readonly [number, number, number] | null = null;\n if (family === \"pbr\") {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the family says it is a PBR material.\n const pbr = material as PbrMaterialProps;\n // An untextured glTF material's factor lives in a 1×1 texture, not here\n // (`lib/loader-gltf/gltf-pbr-builder.js`): without a factor the colour is unknown.\n const base = pbr.baseColorFactor;\n if (base !== undefined) {\n const keep = 1 - (pbr.ormTexture === undefined ? clamp01(pbr.metallicFactor ?? 1) : 0);\n albedo = [clamp01(base[0]) * keep, clamp01(base[1]) * keep, clamp01(base[2]) * keep];\n }\n } else if (family === \"standard\") {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the family says it is a Standard material.\n const standard = material as StandardMaterialProps;\n albedo = [clamp01(standard.diffuseColor[0]), clamp01(standard.diffuseColor[1]), clamp01(standard.diffuseColor[2])];\n }\n return {\n positions: triangles.positions,\n indices: triangles.indices,\n materialName: material.name ?? null,\n albedo,\n };\n}\n\n/**\n * Clamps a colour channel to `[0, 1]`, `NaN` to 0.\n *\n * @param value - The channel.\n * @returns It, clamped.\n */\nfunction clamp01(value: number): number {\n return Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : 0;\n}\n","import { Mat4 } from \"./mat4.js\";\nimport { EPSILON, lerp } from \"./math-utils.js\";\nimport type { Mat4Like, MutableVec3, Vec3Like } from \"./types.js\";\n\n/**\n * A 3-component vector: a position or a direction in metres, or a per-axis scale. ignifx is\n * left-handed with Y up and +Z forward (ADR-0011), so {@link Vec3.forward} is `(0, 0, 1)` and\n * {@link Vec3.right} is `(1, 0, 0)`.\n *\n * The fields are plain mutable numbers, which is what makes a `Vec3` interchangeable with Babylon\n * Lite's `{ x, y, z }` vectors and with the live {@link MutableVec3} views a `Transform` exposes.\n *\n * Three families of operations, and the names say which is which:\n *\n * - instance methods mutate the receiver and return `this` (`a.add(b)` means `a += b`);\n * - `ToRef` statics write into a final `out` argument, allocate nothing, and are safe when `out`\n * aliases an input — these are what per-frame code uses (coding standards section 7);\n * - the remaining statics return a fresh vector and are documented as allocating.\n *\n * @example\n * ```ts\n * // convenience code\n * const offset = Vec3.add(position, Vec3.scale(direction, distance));\n *\n * // per-frame code: no allocation\n * Vec3.scaleToRef(direction, distance, scratch);\n * Vec3.addToRef(position, scratch, position);\n * ```\n *\n * @public\n */\nexport class Vec3 {\n /** The X component; positive is right. */\n x: number;\n /** The Y component; positive is up. */\n y: number;\n /** The Z component; positive is forward. */\n z: number;\n\n /**\n * Creates a vector.\n *\n * @param x - The X component. Defaults to 0.\n * @param y - The Y component. Defaults to 0.\n * @param z - The Z component. Defaults to 0.\n */\n constructor(x: number = 0, y: number = 0, z: number = 0) {\n this.x = x;\n this.y = y;\n this.z = z;\n }\n\n /**\n * Assigns every component at once.\n *\n * @param x - The new X component.\n * @param y - The new Y component.\n * @param z - The new Z component.\n * @returns This vector.\n */\n set(x: number, y: number, z: number): this {\n this.x = x;\n this.y = y;\n this.z = z;\n return this;\n }\n\n /**\n * Copies every component from another vector.\n *\n * @param v - The vector to read.\n * @returns This vector.\n */\n copyFrom(v: Vec3Like): this {\n this.x = v.x;\n this.y = v.y;\n this.z = v.z;\n return this;\n }\n\n /**\n * Copies this vector into a new one.\n *\n * @returns A new vector. **Allocates.**\n */\n clone(): Vec3 {\n return new Vec3(this.x, this.y, this.z);\n }\n\n /**\n * Adds another vector to this one.\n *\n * @param v - The vector to add.\n * @returns This vector.\n */\n add(v: Vec3Like): this {\n this.x += v.x;\n this.y += v.y;\n this.z += v.z;\n return this;\n }\n\n /**\n * Adds a scaled vector to this one — the \"move by velocity times delta time\" step, without a\n * temporary.\n *\n * @param v - The vector to add.\n * @param scale - The factor to multiply `v` by first.\n * @returns This vector.\n *\n * @example\n * ```ts\n * position.addScaled(velocity, time.deltaTime);\n * ```\n */\n addScaled(v: Vec3Like, scale: number): this {\n this.x += v.x * scale;\n this.y += v.y * scale;\n this.z += v.z * scale;\n return this;\n }\n\n /**\n * Subtracts another vector from this one.\n *\n * @param v - The vector to subtract.\n * @returns This vector.\n */\n subtract(v: Vec3Like): this {\n this.x -= v.x;\n this.y -= v.y;\n this.z -= v.z;\n return this;\n }\n\n /**\n * Multiplies this vector by another component by component.\n *\n * @param v - The vector to multiply by.\n * @returns This vector.\n */\n multiply(v: Vec3Like): this {\n this.x *= v.x;\n this.y *= v.y;\n this.z *= v.z;\n return this;\n }\n\n /**\n * Multiplies every component by a number.\n *\n * @param scale - The factor.\n * @returns This vector.\n */\n scale(scale: number): this {\n this.x *= scale;\n this.y *= scale;\n this.z *= scale;\n return this;\n }\n\n /**\n * Flips this vector to point the other way.\n *\n * @returns This vector.\n */\n negate(): this {\n this.x = -this.x;\n this.y = -this.y;\n this.z = -this.z;\n return this;\n }\n\n /**\n * Scales this vector to unit length. A zero-length vector is left at zero rather than becoming\n * `NaN`, so callers can normalize an unchecked direction safely.\n *\n * @returns This vector.\n */\n normalize(): this {\n const length = Math.hypot(this.x, this.y, this.z);\n if (length === 0) {\n return this;\n }\n return this.scale(1 / length);\n }\n\n /**\n * Replaces this vector with its cross product with another (`this = this x v`).\n *\n * @param v - The right-hand vector.\n * @returns This vector.\n */\n cross(v: Vec3Like): this {\n return Vec3.crossToRef(this, v, this);\n }\n\n /**\n * Moves this vector towards a target by an interpolant.\n *\n * @param target - The vector reached at `t === 1`.\n * @param t - The interpolant; not clamped.\n * @returns This vector.\n */\n lerp(target: Vec3Like, t: number): this {\n return Vec3.lerpToRef(this, target, t, this);\n }\n\n /**\n * The dot product of this vector with another.\n *\n * @param v - The other vector.\n * @returns The dot product.\n */\n dot(v: Vec3Like): number {\n return this.x * v.x + this.y * v.y + this.z * v.z;\n }\n\n /**\n * The length of this vector, in metres.\n *\n * @returns The length.\n */\n length(): number {\n return Math.hypot(this.x, this.y, this.z);\n }\n\n /**\n * The squared length of this vector. Prefer it over `length()` when comparing distances:\n * it skips the square root.\n *\n * @returns The squared length.\n */\n lengthSquared(): number {\n return this.x * this.x + this.y * this.y + this.z * this.z;\n }\n\n /**\n * The distance from this vector to another, in metres.\n *\n * @param v - The other position.\n * @returns The distance.\n */\n distance(v: Vec3Like): number {\n return Math.hypot(this.x - v.x, this.y - v.y, this.z - v.z);\n }\n\n /**\n * The squared distance from this vector to another.\n *\n * @param v - The other position.\n * @returns The squared distance.\n */\n distanceSquared(v: Vec3Like): number {\n return Vec3.distanceSquared(this, v);\n }\n\n /**\n * Compares this vector with another, component by component, with a tolerance.\n *\n * @param v - The vector to compare against.\n * @param epsilon - The largest per-component difference still considered equal.\n * @returns `true` when every component matches within `epsilon`.\n */\n equalsWithEpsilon(v: Vec3Like, epsilon: number = EPSILON): boolean {\n return Vec3.equalsWithEpsilon(this, v, epsilon);\n }\n\n /**\n * Writes this vector into a `Float32Array`, for GPU upload. The output comes first to mirror\n * Babylon Lite's `ObservableVec3.toArray`, the shape the adapter has to interoperate with.\n *\n * @param out - The array to write into.\n * @param offset - The index of the X component. Defaults to 0.\n * @returns `out`.\n */\n toArray(out: Float32Array, offset: number = 0): Float32Array {\n out[offset] = this.x;\n out[offset + 1] = this.y;\n out[offset + 2] = this.z;\n return out;\n }\n\n /**\n * The zero vector.\n *\n * @returns A new `(0, 0, 0)`. **Allocates**; use {@link VEC3_ZERO} when a read-only value will do.\n */\n static zero(): Vec3 {\n return new Vec3(0, 0, 0);\n }\n\n /**\n * The vector whose components are all one.\n *\n * @returns A new `(1, 1, 1)`. **Allocates.**\n */\n static one(): Vec3 {\n return new Vec3(1, 1, 1);\n }\n\n /**\n * The world up direction.\n *\n * @returns A new `(0, 1, 0)`. **Allocates**; see {@link VEC3_UP}.\n */\n static up(): Vec3 {\n return new Vec3(0, 1, 0);\n }\n\n /**\n * The world down direction.\n *\n * @returns A new `(0, -1, 0)`. **Allocates.**\n */\n static down(): Vec3 {\n return new Vec3(0, -1, 0);\n }\n\n /**\n * The world right direction.\n *\n * @returns A new `(1, 0, 0)`. **Allocates**; see {@link VEC3_RIGHT}.\n */\n static right(): Vec3 {\n return new Vec3(1, 0, 0);\n }\n\n /**\n * The world left direction.\n *\n * @returns A new `(-1, 0, 0)`. **Allocates.**\n */\n static left(): Vec3 {\n return new Vec3(-1, 0, 0);\n }\n\n /**\n * The world forward direction. ignifx is left-handed, so forward is **+Z** (ADR-0011).\n *\n * @returns A new `(0, 0, 1)`. **Allocates**; see {@link VEC3_FORWARD}.\n */\n static forward(): Vec3 {\n return new Vec3(0, 0, 1);\n }\n\n /**\n * The world backward direction.\n *\n * @returns A new `(0, 0, -1)`. **Allocates.**\n */\n static backward(): Vec3 {\n return new Vec3(0, 0, -1);\n }\n\n /**\n * Copies any vector-shaped value into a `Vec3`.\n *\n * @param v - The vector to copy.\n * @returns A new vector. **Allocates.**\n *\n * @example\n * ```ts\n * const position = Vec3.from(node.position); // snapshot of a live Lite view\n * ```\n */\n static from(v: Vec3Like): Vec3 {\n return new Vec3(v.x, v.y, v.z);\n }\n\n /**\n * Adds two vectors.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @returns A new vector. **Allocates**; use {@link Vec3.addToRef} in per-frame code.\n */\n static add(a: Vec3Like, b: Vec3Like): Vec3 {\n return Vec3.addToRef(a, b, new Vec3());\n }\n\n /**\n * Subtracts one vector from another.\n *\n * @param a - The vector to subtract from.\n * @param b - The vector to subtract.\n * @returns A new vector holding `a - b`. **Allocates.**\n */\n static subtract(a: Vec3Like, b: Vec3Like): Vec3 {\n return Vec3.subtractToRef(a, b, new Vec3());\n }\n\n /**\n * Multiplies a vector by a number.\n *\n * @param v - The vector to scale.\n * @param scale - The factor.\n * @returns A new vector. **Allocates.**\n */\n static scale(v: Vec3Like, scale: number): Vec3 {\n return Vec3.scaleToRef(v, scale, new Vec3());\n }\n\n /**\n * The cross product of two vectors.\n *\n * @param a - The left-hand vector.\n * @param b - The right-hand vector.\n * @returns A new vector holding `a x b`. **Allocates.**\n */\n static cross(a: Vec3Like, b: Vec3Like): Vec3 {\n return Vec3.crossToRef(a, b, new Vec3());\n }\n\n /**\n * A unit-length copy of a vector.\n *\n * @param v - The vector to normalize.\n * @returns A new vector. **Allocates.**\n */\n static normalize(v: Vec3Like): Vec3 {\n return Vec3.normalizeToRef(v, new Vec3());\n }\n\n /**\n * Linearly interpolates between two vectors.\n *\n * @param a - The vector returned at `t === 0`.\n * @param b - The vector returned at `t === 1`.\n * @param t - The interpolant; not clamped.\n * @returns A new vector. **Allocates.**\n */\n static lerp(a: Vec3Like, b: Vec3Like, t: number): Vec3 {\n return Vec3.lerpToRef(a, b, t, new Vec3());\n }\n\n /**\n * Writes `a + b` into `out`.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static addToRef<TOut extends MutableVec3>(a: Vec3Like, b: Vec3Like, out: TOut): TOut {\n out.set(a.x + b.x, a.y + b.y, a.z + b.z);\n return out;\n }\n\n /**\n * Writes `a - b` into `out`.\n *\n * @param a - The vector to subtract from.\n * @param b - The vector to subtract.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static subtractToRef<TOut extends MutableVec3>(a: Vec3Like, b: Vec3Like, out: TOut): TOut {\n out.set(a.x - b.x, a.y - b.y, a.z - b.z);\n return out;\n }\n\n /**\n * Writes the component-wise product `a * b` into `out`.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static multiplyToRef<TOut extends MutableVec3>(a: Vec3Like, b: Vec3Like, out: TOut): TOut {\n out.set(a.x * b.x, a.y * b.y, a.z * b.z);\n return out;\n }\n\n /**\n * Writes `v * scale` into `out`.\n *\n * @param v - The vector to scale.\n * @param scale - The factor.\n * @param out - The vector to write; may alias `v`.\n * @returns `out`.\n */\n static scaleToRef<TOut extends MutableVec3>(v: Vec3Like, scale: number, out: TOut): TOut {\n out.set(v.x * scale, v.y * scale, v.z * scale);\n return out;\n }\n\n /**\n * Writes `-v` into `out`.\n *\n * @param v - The vector to flip.\n * @param out - The vector to write; may alias `v`.\n * @returns `out`.\n */\n static negateToRef<TOut extends MutableVec3>(v: Vec3Like, out: TOut): TOut {\n out.set(-v.x, -v.y, -v.z);\n return out;\n }\n\n /**\n * Writes a unit-length copy of `v` into `out`. A zero-length input is written as zero rather than\n * `NaN`.\n *\n * @param v - The vector to normalize.\n * @param out - The vector to write; may alias `v`.\n * @returns `out`.\n */\n static normalizeToRef<TOut extends MutableVec3>(v: Vec3Like, out: TOut): TOut {\n const length = Math.hypot(v.x, v.y, v.z);\n if (length === 0) {\n out.set(0, 0, 0);\n return out;\n }\n const inv = 1 / length;\n out.set(v.x * inv, v.y * inv, v.z * inv);\n return out;\n }\n\n /**\n * Writes `a x b` into `out`.\n *\n * @param a - The left-hand vector.\n * @param b - The right-hand vector.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static crossToRef<TOut extends MutableVec3>(a: Vec3Like, b: Vec3Like, out: TOut): TOut {\n const ax = a.x;\n const ay = a.y;\n const az = a.z;\n const bx = b.x;\n const by = b.y;\n const bz = b.z;\n out.set(ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx);\n return out;\n }\n\n /**\n * Writes the interpolation of `a` and `b` into `out`.\n *\n * @param a - The vector written at `t === 0`.\n * @param b - The vector written at `t === 1`.\n * @param t - The interpolant; not clamped.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static lerpToRef<TOut extends MutableVec3>(a: Vec3Like, b: Vec3Like, t: number, out: TOut): TOut {\n out.set(lerp(a.x, b.x, t), lerp(a.y, b.y, t), lerp(a.z, b.z, t));\n return out;\n }\n\n /**\n * Writes the component-wise minimum of two vectors into `out`.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static minToRef<TOut extends MutableVec3>(a: Vec3Like, b: Vec3Like, out: TOut): TOut {\n out.set(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.min(a.z, b.z));\n return out;\n }\n\n /**\n * Writes the component-wise maximum of two vectors into `out`.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @param out - The vector to write; may alias `a` or `b`.\n * @returns `out`.\n */\n static maxToRef<TOut extends MutableVec3>(a: Vec3Like, b: Vec3Like, out: TOut): TOut {\n out.set(Math.max(a.x, b.x), Math.max(a.y, b.y), Math.max(a.z, b.z));\n return out;\n }\n\n /**\n * Transforms a **position** by a matrix into `out`: the matrix's translation is applied and the\n * result is divided by w, so a projection matrix gives clip-space coordinates.\n *\n * @param v - The position to transform, in metres.\n * @param m - The transformation, column-major.\n * @param out - The vector to write; may alias `v`.\n * @returns `out`.\n *\n * @example\n * ```ts\n * Vec3.transformCoordinatesToRef(localPoint, node.worldMatrix, worldPoint);\n * ```\n */\n static transformCoordinatesToRef<TOut extends MutableVec3>(v: Vec3Like, m: Mat4Like, out: TOut): TOut {\n return Mat4.transformPointToRef(m, v, out);\n }\n\n /**\n * Transforms a **direction** by a matrix into `out`, ignoring the matrix's translation.\n *\n * @param v - The direction to transform.\n * @param m - The transformation, column-major.\n * @param out - The vector to write; may alias `v`.\n * @returns `out`.\n */\n static transformNormalToRef<TOut extends MutableVec3>(v: Vec3Like, m: Mat4Like, out: TOut): TOut {\n return Mat4.transformDirectionToRef(m, v, out);\n }\n\n /**\n * The dot product of two vectors.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @returns The dot product.\n */\n static dot(a: Vec3Like, b: Vec3Like): number {\n return a.x * b.x + a.y * b.y + a.z * b.z;\n }\n\n /**\n * The length of a vector, in metres.\n *\n * @param v - The vector to measure.\n * @returns The length.\n */\n static length(v: Vec3Like): number {\n return Math.hypot(v.x, v.y, v.z);\n }\n\n /**\n * The squared length of a vector.\n *\n * @param v - The vector to measure.\n * @returns The squared length.\n */\n static lengthSquared(v: Vec3Like): number {\n return v.x * v.x + v.y * v.y + v.z * v.z;\n }\n\n /**\n * The distance between two positions, in metres.\n *\n * @param a - The first position.\n * @param b - The second position.\n * @returns The distance.\n */\n static distance(a: Vec3Like, b: Vec3Like): number {\n return Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);\n }\n\n /**\n * The squared distance between two positions. Compare squared distances to avoid a square root.\n *\n * @param a - The first position.\n * @param b - The second position.\n * @returns The squared distance.\n */\n static distanceSquared(a: Vec3Like, b: Vec3Like): number {\n const dx = a.x - b.x;\n const dy = a.y - b.y;\n const dz = a.z - b.z;\n return dx * dx + dy * dy + dz * dz;\n }\n\n /**\n * Compares two vectors component by component, with a tolerance.\n *\n * @param a - The first vector.\n * @param b - The second vector.\n * @param epsilon - The largest per-component difference still considered equal.\n * @returns `true` when every component matches within `epsilon`.\n */\n static equalsWithEpsilon(a: Vec3Like, b: Vec3Like, epsilon: number = EPSILON): boolean {\n return Math.abs(a.x - b.x) <= epsilon && Math.abs(a.y - b.y) <= epsilon && Math.abs(a.z - b.z) <= epsilon;\n }\n}\n\n/**\n * The frozen zero vector, `(0, 0, 0)`. Read-only: pass it anywhere a {@link Vec3Like} is wanted, and\n * call {@link Vec3.zero} when you need a vector you can write to.\n *\n * @public\n */\nexport const VEC3_ZERO: Vec3Like = Object.freeze({ x: 0, y: 0, z: 0 });\n\n/**\n * The frozen vector whose components are all one, `(1, 1, 1)` — the identity scale.\n *\n * @public\n */\nexport const VEC3_ONE: Vec3Like = Object.freeze({ x: 1, y: 1, z: 1 });\n\n/**\n * The frozen world up direction, `(0, 1, 0)`.\n *\n * @public\n */\nexport const VEC3_UP: Vec3Like = Object.freeze({ x: 0, y: 1, z: 0 });\n\n/**\n * The frozen world down direction, `(0, -1, 0)`.\n *\n * @public\n */\nexport const VEC3_DOWN: Vec3Like = Object.freeze({ x: 0, y: -1, z: 0 });\n\n/**\n * The frozen world right direction, `(1, 0, 0)`.\n *\n * @public\n */\nexport const VEC3_RIGHT: Vec3Like = Object.freeze({ x: 1, y: 0, z: 0 });\n\n/**\n * The frozen world left direction, `(-1, 0, 0)`.\n *\n * @public\n */\nexport const VEC3_LEFT: Vec3Like = Object.freeze({ x: -1, y: 0, z: 0 });\n\n/**\n * The frozen world forward direction, `(0, 0, 1)`. ignifx is left-handed, so forward is +Z\n * (ADR-0011).\n *\n * @public\n */\nexport const VEC3_FORWARD: Vec3Like = Object.freeze({ x: 0, y: 0, z: 1 });\n\n/**\n * The frozen world backward direction, `(0, 0, -1)`.\n *\n * @public\n */\nexport const VEC3_BACKWARD: Vec3Like = Object.freeze({ x: 0, y: 0, z: -1 });\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAqHA,SAAgB,cAAc,QAAuB,SAAqC;CACxF,OAAO,UAAU,QAAQ,OAAO;AAClC;;;;;;;;;;AAWA,SAAgB,iBAAiB,QAAuB,SAA+B;CACrF,OAAO,aAAa,QAAQ,OAAO;AACrC;;;;;;;;;;AAWA,SAAgB,gBAAgB,QAAuB,SA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AAM,KAAK,EAAE,IAAI,EAAE;EACnB,MAAM,KAAK,EAAE,IAAI,EAAE;EACnB,MAAM,KAAK,EAAE,IAAI,EAAE;EACnB,OAAO,KAAK,KAAK,KAAK,KAAK,KAAK;CAClC;;;;;;;;;CAUA,OAAO,kBAAkB,GAAa,GAAa,UAAkB,SAAkB;EACrF,OAAO,KAAK,IAAI,EAAE,IAAI,EAAE,CAAC,KAAK,WAAW,KAAK,IAAI,EAAE,IAAI,EAAE,CAAC,KAAK,WAAW,KAAK,IAAI,EAAE,IAAI,EAAE,CAAC,KAAK;CACpG;AACF;;;;;;;AAQA,MAAa,YAAsB,OAAO,OAAO;CAAE,GAAG;CAAG,GAAG;CAAG,GAAG;AAAE,CAAC;;;;;;AAOrE,MAAa,WAAqB,OAAO,OAAO;CAAE,GAAG;CAAG,GAAG;CAAG,GAAG;AAAE,CAAC;;;;;;AAOpE,MAAa,UAAoB,OAAO,OAAO;CAAE,GAAG;CAAG,GAAG;CAAG,GAAG;AAAE,CAAC;;;;;;AAOnE,MAAa,YAAsB,OAAO,OAAO;CAAE,GAAG;CAAG,GAAG;CAAI,GAAG;AAAE,CAAC;;;;;;AAOtE,MAAa,aAAuB,OAAO,OAAO;CAAE,GAAG;CAAG,GAAG;CAAG,GAAG;AAAE,CAAC;;;;;;AAOtE,MAAa,YAAsB,OAAO,OAAO;CAAE,GAAG;CAAI,GAAG;CAAG,GAAG;AAAE,CAAC;;;;;;;AAQtE,MAAa,eAAyB,OAAO,OAAO;CAAE,GAAG;CAAG,GAAG;CAAG,GAAG;AAAE,CAAC;;;;;;AAOxE,MAAa,gBAA0B,OAAO,OAAO;CAAE,GAAG;CAAG,GAAG;CAAG,GAAG;AAAG,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ignifx/core",
3
- "version": "0.20.0",
3
+ "version": "0.21.1",
4
4
  "description": "ignifx core: app, world, entities, components, scripts, and the Babylon Lite adapter boundary.",
5
5
  "homepage": "https://ignifx.com",
6
6
  "license": "Apache-2.0",
@@ -1 +0,0 @@
1
- {"version":3,"file":"agx-tone-mapping-Cgt844j6.js","names":[],"sources":["../src/lite/gpu/agx-tone-mapping.ts"],"sourcesContent":["import type { ToneMapping } from \"@babylonjs/lite\";\n\n/**\n * AgX as a Babylon Lite custom `ToneMapping` (`index.d.ts`, `interface ToneMapping`), for the\n * `\"agx\"` tone-mapping name (`docs/plan/2026-11-gi-phase-1-execution-plan.md`, step G13).\n *\n * The formulation is Benjamin Wendt's \"Minimal AgX implementation\" (iolite engine, 2023,\n * https://iolite-engine.com/blog_posts/minimal_agx_implementation), a fit of Troy Sobotka's AgX\n * (https://github.com/sobotka/AgX) as Blender 4.0 ships it under \"AgX Base\": the inset matrix, a\n * log2 encode between -12.47393 and +4.026069 EV, a sixth-order polynomial for the default contrast\n * sigmoid, then the outset matrix. Only the base look is used; Wendt's \"golden\" and \"punchy\" looks\n * are not exposed. The sigmoid's output is display-encoded, so the call raises it to the power 2.2:\n * Lite's PBR template, and the HDR output pass after it, encode with `pow(1/2.2)` next.\n *\n * Its own chunk: `./environment.ts` imports it only when a scene asks for `\"agx\"`, and\n * `./hdr-output.ts`, itself a chunk, imports it for the HDR path. `image-processing-color.ts`\n * carries the same numbers on the CPU for the clear colour.\n */\n\n/**\n * The curve's `id`, Lite's cache key and change check. Prefixed so a future Lite AgX is not taken\n * for this one. `./environment.ts` repeats the literal rather than importing it, which would put\n * this chunk on the entry path; a unit test keeps the two equal.\n *\n * @internal\n */\nexport const AGX_TONE_MAPPING_ID = \"ignifx-agx\";\n\n/**\n * The module-scope WGSL: the matrices and the two functions. Names carry an `ignifx` prefix so\n * they cannot collide with Lite's own helpers in the PBR template.\n *\n * @internal\n */\nexport const AGX_HELPERS_WGSL: string =\n \"const ignifxAgxInset=mat3x3<f32>(\" +\n \"vec3<f32>(0.842479062253094,0.0423282422610123,0.0423756549057051),\" +\n \"vec3<f32>(0.0784335999999992,0.878468636469772,0.0784336),\" +\n \"vec3<f32>(0.0792237451477643,0.0791661274605434,0.879142973793104));\" +\n \"const ignifxAgxOutset=mat3x3<f32>(\" +\n \"vec3<f32>(1.19687900512017,-0.0528968517574562,-0.0529716355144438),\" +\n \"vec3<f32>(-0.0980208811401368,1.15190312990417,-0.0980434501171241),\" +\n \"vec3<f32>(-0.0990297440797205,-0.0989611768448433,1.15107367264116));\" +\n \"const ignifxAgxMinEv:f32=-12.47393;\" +\n \"const ignifxAgxMaxEv:f32=4.026069;\" +\n \"fn ignifxAgxContrast(x:vec3<f32>)->vec3<f32>{let x2=x*x;let x4=x2*x2;\" +\n \"return 15.5*x4*x2-40.14*x4*x+31.96*x4-6.868*x2*x+0.4298*x2+0.1191*x-0.00232;}\" +\n \"fn ignifxAgx(c:vec3<f32>)->vec3<f32>{\" +\n \"var v=max(ignifxAgxInset*c,vec3<f32>(1e-10));\" +\n \"v=clamp(log2(v),vec3<f32>(ignifxAgxMinEv),vec3<f32>(ignifxAgxMaxEv));\" +\n \"v=(v-ignifxAgxMinEv)/(ignifxAgxMaxEv-ignifxAgxMinEv);\" +\n \"v=ignifxAgxOutset*ignifxAgxContrast(v);\" +\n \"return pow(max(v,vec3<f32>(0.0)),vec3<f32>(2.2));}\";\n\n/**\n * The per-fragment WGSL: the exposure first, as Lite's contract for `callWGSL` requires, then the\n * curve on the working `color`.\n *\n * @internal\n */\nexport const AGX_CALL_WGSL: string = \"color*=scene.vImageInfos.x;color=ignifxAgx(color);\";\n\n/**\n * The AgX curve object Lite bakes into PBR shaders.\n *\n * @internal\n */\nexport const AgxToneMapping: ToneMapping = {\n id: AGX_TONE_MAPPING_ID,\n helpersWGSL: AGX_HELPERS_WGSL,\n callWGSL: AGX_CALL_WGSL,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,sBAAsB;;;;;;;AAQnC,MAAa,mBACX;;;;;;;AAyBF,MAAa,gBAAwB;;;;;;AAOrC,MAAa,iBAA8B;CACzC,IAAI;CACJ,aAAa;CACb,UAAU;AACZ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"bloom-hdr-CLtQj-oY.js","names":[],"sources":["../src/lite/gpu/bloom-hdr.ts"],"sourcesContent":["import {\n createEffectRenderTask,\n createEffectWrapper,\n createSurfaceRenderTargetTexture,\n disposeEffectWrapper,\n disposeRenderTargetTexture,\n onRenderTargetTextureResize,\n setEffectTexture,\n setEffectUniforms,\n} from \"@babylonjs/lite\";\nimport type { HdrOutputHandle } from \"./render-path.js\";\nimport type {\n EffectWrapper,\n EngineContext,\n RenderTarget,\n RenderTargetTextureResult,\n SceneContext,\n Task,\n Texture2D,\n} from \"@babylonjs/lite\";\n\n/**\n * HDR bloom (`docs/plan/2026-11-gi-phase-1-execution-plan.md`, step G12): a downsample/upsample\n * chain on the linear `rgba16float` scene target, recorded before the HDR output pass so the glow\n * is tone mapped with the rest of the frame. Its own chunk: `../../render/hdr-bloom-support.ts`\n * imports it only when a `PostProcessStack` asks for bloom under `rendering.hdr`\n * (`CONSTITUTION.md` §2.5).\n *\n * ```text\n * scene → hdr ─ down₀ → mip₀ ─ down₁ → mip₁ … → mip₅\n * mip₄ += up(mip₅) … mip₀ += up(mip₁)\n * hdr = mix(hdr, up(mip₀), intensity) ──→ output pass\n * ```\n *\n * - **Downsample** is the 13-tap filter of Jimenez, \"Next generation post processing in Call of\n * Duty: Advanced Warfare\" (SIGGRAPH 2014): five overlapping 2×2 boxes, the centre one weighted\n * 0.5. The first level weights each box by `1 / (1 + luma)` (Karis average), so one very bright\n * texel cannot flicker into a frame-sized blob, and applies the optional soft-knee threshold.\n * - **Upsample** is a 9-tap tent, blended into the next larger mip as\n * `mip = mix(mip, tent(smaller), radius)`, so `radius` decides how much of the wide, low mips\n * reaches the image while the weights still sum to one.\n * - **Composite** writes into the HDR target itself through the blend unit, so the output pass's\n * input never changes and nothing is rebound: `hdr = mix(hdr, bloom, intensity)` with no\n * threshold (energy-conserving: the image is redistributed, not brightened), `hdr += bloom ·\n * intensity` with one.\n * - Each mip is a surface-scaled target (`{ surface, scale }`), so a resize reallocates it with\n * the frame graph; the resize callbacks rebind the readers' bind groups.\n * - Lite has no task removal, so {@link HdrBloom.dispose} disables the tasks and makes their\n * `record` a no-op: a later frame-graph rebuild still walks them.\n */\n\n/**\n * How many mips the chain builds: half resolution down to 1/64.\n *\n * @internal\n */\nexport const HDR_BLOOM_MIP_COUNT = 6;\n\n/**\n * The format of every mip; the same as the scene target, so values above 1 survive.\n *\n * @internal\n */\nexport const HDR_BLOOM_FORMAT: GPUTextureFormat = \"rgba16float\";\n\n/** Uniform floats per pass: one `vec4`. */\nconst UNIFORM_FLOATS = 4;\n\n/**\n * The tuning a `PostProcessStack`'s `bloom` record feeds the chain.\n *\n * @internal\n */\nexport interface HdrBloomTuning {\n /** How much glow is mixed in, 0–1. */\n readonly intensity: number;\n /** How far the glow spreads, 0–1: the weight of each lower mip when it is upsampled. */\n readonly radius: number;\n /** The linear luminance below which nothing glows; `0` lets every pixel contribute. */\n readonly threshold: number;\n}\n\n/**\n * A recorded HDR bloom chain.\n *\n * @internal\n */\nexport interface HdrBloom {\n /** The mip chain, largest first. */\n readonly mips: readonly Texture2D[];\n /** How many frame-graph tasks it recorded. */\n readonly taskCount: number;\n /**\n * Switches every task of the chain on or off.\n *\n * @param enabled - `false` to skip the chain; the HDR target then reaches the output pass as is.\n */\n setEnabled(enabled: boolean): void;\n /**\n * Uploads the tuning, when it changed.\n *\n * @param tuning - The values.\n */\n apply(tuning: HdrBloomTuning): void;\n /** Disables the tasks, makes them inert to a rebuild, and frees the mips and effects. */\n dispose(): void;\n}\n\n/** The blend that turns a pass's `vec4(rgb, a)` into `dst·(1 − a) + rgb`. */\nconst MIX_BLEND: GPUBlendState = {\n color: { operation: \"add\", srcFactor: \"one\", dstFactor: \"one-minus-src-alpha\" },\n alpha: { operation: \"add\", srcFactor: \"zero\", dstFactor: \"one\" },\n};\n\n/**\n * The uniform block, texture, sampler and helpers every pass declares.\n *\n * @returns The WGSL.\n */\nfunction passHeaderWgsl(): string {\n return [\n \"struct BloomUniforms{params:vec4<f32>};\",\n \"@group(0)@binding(0)var<uniform>bloom:BloomUniforms;\",\n \"@group(0)@binding(1)var source:texture_2d<f32>;\",\n \"@group(0)@binding(2)var sourceSampler:sampler;\",\n // Lite's fullscreen triangle puts uv (0,0) at the bottom left; textures start at the top left.\n \"fn bloomUv(fragment:EffectVertexOutput)->vec2<f32>{return vec2<f32>(fragment.uv.x,1.0-fragment.uv.y);}\",\n \"fn tap(uv:vec2<f32>,offset:vec2<f32>,texel:vec2<f32>)->vec3<f32>{\",\n \"let c=textureSampleLevel(source,sourceSampler,uv+offset*texel,0.0).rgb;\",\n \"return min(max(c,vec3<f32>(0.0)),vec3<f32>(65000.0));\",\n \"}\",\n ].join(\"\\n\");\n}\n\n/**\n * The downsample pass: 13 taps, a Karis average and the soft-knee threshold on the first level.\n *\n * @remarks\n * `params` is `(threshold, knee, isFirstLevel, unused)`.\n *\n * @returns The WGSL, with Lite's `effectFragment` entry point.\n *\n * @internal\n */\nexport function bloomDownsampleWgsl(): string {\n return [\n passHeaderWgsl(),\n \"fn boxWeight(c:vec3<f32>,first:bool)->f32{\",\n \"if(!first){return 1.0;}\",\n \"return 1.0/(1.0+dot(c,vec3<f32>(0.2126,0.7152,0.0722)));\",\n \"}\",\n \"fn knee(c:vec3<f32>,threshold:f32,soft:f32)->vec3<f32>{\",\n \"if(threshold<=0.0){return c;}\",\n \"let b=max(c.r,max(c.g,c.b));\",\n \"var s=clamp(b-threshold+soft,0.0,2.0*soft);\",\n \"s=s*s/(4.0*soft+1e-5);\",\n \"return c*(max(s,b-threshold)/max(b,1e-5));\",\n \"}\",\n \"@fragment fn effectFragment(fragment:EffectVertexOutput)->@location(0)vec4<f32>{\",\n \"let uv=bloomUv(fragment);\",\n \"let texel=1.0/vec2<f32>(textureDimensions(source,0));\",\n \"let first=bloom.params.z>0.5;\",\n \"let a=tap(uv,vec2<f32>(-2.0,-2.0),texel);let b=tap(uv,vec2<f32>(0.0,-2.0),texel);\",\n \"let c=tap(uv,vec2<f32>(2.0,-2.0),texel);let d=tap(uv,vec2<f32>(-2.0,0.0),texel);\",\n \"let e=tap(uv,vec2<f32>(0.0,0.0),texel);let f=tap(uv,vec2<f32>(2.0,0.0),texel);\",\n \"let g=tap(uv,vec2<f32>(-2.0,2.0),texel);let h=tap(uv,vec2<f32>(0.0,2.0),texel);\",\n \"let i=tap(uv,vec2<f32>(2.0,2.0),texel);let j=tap(uv,vec2<f32>(-1.0,-1.0),texel);\",\n \"let k=tap(uv,vec2<f32>(1.0,-1.0),texel);let l=tap(uv,vec2<f32>(-1.0,1.0),texel);\",\n \"let m=tap(uv,vec2<f32>(1.0,1.0),texel);\",\n \"let g0=(j+k+l+m)*0.25;let g1=(a+b+d+e)*0.25;let g2=(b+c+e+f)*0.25;\",\n \"let g3=(d+e+g+h)*0.25;let g4=(e+f+h+i)*0.25;\",\n \"let w0=0.5*boxWeight(g0,first);let w1=0.125*boxWeight(g1,first);let w2=0.125*boxWeight(g2,first);\",\n \"let w3=0.125*boxWeight(g3,first);let w4=0.125*boxWeight(g4,first);\",\n \"var color=(g0*w0+g1*w1+g2*w2+g3*w3+g4*w4)/(w0+w1+w2+w3+w4);\",\n \"if(first){color=knee(color,bloom.params.x,bloom.params.y);}\",\n \"return vec4<f32>(color,1.0);\",\n \"}\",\n ].join(\"\\n\");\n}\n\n/**\n * The upsample and composite pass: a 9-tap tent of the smaller mip, scaled, with the blend weight\n * in alpha.\n *\n * @remarks\n * `params` is `(scale, alpha, unused, unused)`; with {@link MIX_BLEND} the target becomes\n * `target·(1 − alpha) + tent·scale`.\n *\n * @returns The WGSL, with Lite's `effectFragment` entry point.\n *\n * @internal\n */\nexport function bloomUpsampleWgsl(): string {\n return [\n passHeaderWgsl(),\n \"@fragment fn effectFragment(fragment:EffectVertexOutput)->@location(0)vec4<f32>{\",\n \"let uv=bloomUv(fragment);\",\n \"let texel=1.0/vec2<f32>(textureDimensions(source,0));\",\n \"var color=tap(uv,vec2<f32>(0.0,0.0),texel)*4.0;\",\n \"color+=(tap(uv,vec2<f32>(-1.0,0.0),texel)+tap(uv,vec2<f32>(1.0,0.0),texel)\",\n \"+tap(uv,vec2<f32>(0.0,-1.0),texel)+tap(uv,vec2<f32>(0.0,1.0),texel))*2.0;\",\n \"color+=tap(uv,vec2<f32>(-1.0,-1.0),texel)+tap(uv,vec2<f32>(1.0,-1.0),texel)\",\n \"+tap(uv,vec2<f32>(-1.0,1.0),texel)+tap(uv,vec2<f32>(1.0,1.0),texel);\",\n \"return vec4<f32>(color*(bloom.params.x/16.0),bloom.params.y);\",\n \"}\",\n ].join(\"\\n\");\n}\n\n/**\n * Writes every pass's uniforms for a tuning.\n *\n * @remarks\n * Laid out as `HDR_BLOOM_MIP_COUNT` downsample blocks, then `HDR_BLOOM_MIP_COUNT − 1` upsample\n * blocks (smallest first), then the composite: the order the tasks run in. Values are clamped to\n * their documented ranges, so an inspector typo cannot blow the frame up.\n *\n * @param tuning - The values.\n * @param out - `(2 · HDR_BLOOM_MIP_COUNT) · 4` floats, overwritten.\n *\n * @internal\n */\nexport function writeHdrBloomUniforms(tuning: HdrBloomTuning, out: Float32Array): void {\n const threshold = Math.max(0, tuning.threshold);\n const radius = Math.min(1, Math.max(0, tuning.radius));\n const intensity = Math.max(0, tuning.intensity);\n out.fill(0);\n for (let level = 0; level < HDR_BLOOM_MIP_COUNT; level += 1) {\n const base = level * UNIFORM_FLOATS;\n out[base] = threshold;\n out[base + 1] = threshold * 0.5;\n out[base + 2] = level === 0 ? 1 : 0;\n }\n for (let step = 0; step < HDR_BLOOM_MIP_COUNT - 1; step += 1) {\n const base = (HDR_BLOOM_MIP_COUNT + step) * UNIFORM_FLOATS;\n out[base] = radius;\n out[base + 1] = radius;\n }\n const composite = (2 * HDR_BLOOM_MIP_COUNT - 1) * UNIFORM_FLOATS;\n out[composite] = intensity;\n // With a threshold only the highlights are in the chain, so the glow is added; without one the\n // chain holds the whole image and mixing keeps the frame's energy.\n out[composite + 1] = threshold > 0 ? 0 : Math.min(1, intensity);\n}\n\n/** One pass of the chain: its effect, the texture it reads and its task. */\ninterface BloomPass {\n readonly effect: EffectWrapper;\n readonly task: Task;\n readonly source: () => Texture2D;\n}\n\n/**\n * Builds the HDR bloom chain and inserts it before the HDR output pass.\n *\n * @remarks\n * Before the scene is registered the tasks are only inserted, and `registerScene`'s build records\n * them in order; after, each is recorded on the spot (`buildFrameGraphTask`), as\n * `appendPostProcessTask` in `./post-process.ts` does.\n *\n * @param engine - The engine, which is also the primary surface.\n * @param scene - The scene whose frame graph holds the HDR output pass.\n * @param hdr - The HDR half of the scene's presenter.\n * @param isFrameGraphBuilt - Whether the scene has been registered.\n * @returns The chain, enabled, with zero tuning until {@link HdrBloom.apply} runs.\n *\n * @internal\n */\nexport function installHdrBloom(\n engine: EngineContext,\n scene: SceneContext,\n hdr: HdrOutputHandle,\n isFrameGraphBuilt: boolean,\n): HdrBloom {\n const mips: RenderTargetTextureResult[] = [];\n for (let level = 0; level < HDR_BLOOM_MIP_COUNT; level += 1) {\n mips.push(\n createSurfaceRenderTargetTexture(engine, {\n lbl: `ignifx:bloom-mip-${String(level)}`,\n format: HDR_BLOOM_FORMAT,\n samples: 1,\n size: { surface: engine, scale: 0.5 ** (level + 1) },\n }),\n );\n }\n const mipAt = (level: number): RenderTargetTextureResult => {\n const mip = mips[level];\n if (mip === undefined) {\n throw new RangeError(`HDR bloom has no mip ${String(level)}.`);\n }\n return mip;\n };\n const downsample = bloomDownsampleWgsl();\n const upsample = bloomUpsampleWgsl();\n const passes: BloomPass[] = [];\n const addPass = (name: string, fragmentWGSL: string, source: () => Texture2D, target: RenderTarget): void => {\n const blended = fragmentWGSL === upsample;\n const effect = createEffectWrapper(engine, {\n name,\n fragmentWGSL,\n bindings: [\n { name: \"bloom\", binding: 0, kind: \"uniform\", uniformByteLength: UNIFORM_FLOATS * 4 },\n { name: \"source\", binding: 1, kind: \"texture\" },\n { name: \"sourceSampler\", binding: 2, kind: \"sampler\", textureBinding: 1 },\n ],\n ...(blended ? { blend: MIX_BLEND } : {}),\n });\n setEffectTexture(effect, 1, source());\n setEffectUniforms(effect, new Float32Array(UNIFORM_FLOATS));\n const task = createEffectRenderTask({ name, effect, target, clear: !blended }, engine, scene);\n passes.push({ effect, task, source });\n };\n for (let level = 0; level < HDR_BLOOM_MIP_COUNT; level += 1) {\n const source =\n level === 0 ? (): Texture2D => hdr.sceneTargetTexture.texture : (): Texture2D => mipAt(level - 1).texture;\n addPass(`ignifx:bloom-down-${String(level)}`, downsample, source, mipAt(level).rt);\n }\n for (let level = HDR_BLOOM_MIP_COUNT - 2; level >= 0; level -= 1) {\n addPass(`ignifx:bloom-up-${String(level)}`, upsample, () => mipAt(level + 1).texture, mipAt(level).rt);\n }\n addPass(\"ignifx:bloom-composite\", upsample, () => mipAt(0).texture, hdr.sceneTargetTexture.rt);\n\n // After every linear task already in place (TAA among them), right before the output pass.\n for (const pass of passes) {\n hdr.insertLinearTask(pass.task, isFrameGraphBuilt);\n }\n\n // A resize swaps the textures behind the facades; a wrapper's cached bind group keeps the old\n // view until a texture write marks it dirty.\n const rebind = (): void => {\n for (const pass of passes) {\n setEffectTexture(pass.effect, 1, pass.source());\n }\n };\n const unsubscribe = [hdr.sceneTargetTexture, ...mips].map((target) => onRenderTargetTextureResize(target, rebind));\n\n const uniforms = new Float32Array(passes.length * UNIFORM_FLOATS);\n const scratch = new Float32Array(UNIFORM_FLOATS);\n let isDisposed = false;\n let applied: HdrBloomTuning = { intensity: Number.NaN, radius: Number.NaN, threshold: Number.NaN };\n return {\n mips: mips.map((mip) => mip.texture),\n taskCount: passes.length,\n setEnabled(enabled: boolean): void {\n for (const pass of passes) {\n pass.task.executionEnabled = enabled && !isDisposed;\n }\n },\n apply(tuning: HdrBloomTuning): void {\n if (\n isDisposed ||\n (applied.intensity === tuning.intensity &&\n applied.radius === tuning.radius &&\n applied.threshold === tuning.threshold)\n ) {\n return;\n }\n applied = { intensity: tuning.intensity, radius: tuning.radius, threshold: tuning.threshold };\n writeHdrBloomUniforms(tuning, uniforms);\n for (let index = 0; index < passes.length; index += 1) {\n const pass = passes[index];\n if (pass === undefined) {\n continue;\n }\n scratch.set(uniforms.subarray(index * UNIFORM_FLOATS, (index + 1) * UNIFORM_FLOATS));\n setEffectUniforms(pass.effect, scratch);\n }\n },\n dispose(): void {\n if (isDisposed) {\n return;\n }\n isDisposed = true;\n for (const stop of unsubscribe) {\n stop();\n }\n for (const pass of passes) {\n pass.task.executionEnabled = false;\n // Lite cannot remove a task, and a frame-graph rebuild records every task, disabled or not.\n pass.task.record = inertRecord;\n disposeEffectWrapper(pass.effect);\n }\n for (const mip of mips) {\n disposeRenderTargetTexture(mip);\n }\n },\n };\n}\n\n/** What a disposed pass records: nothing. */\nfunction inertRecord(): void {\n // Intentionally empty; see `HdrBloom.dispose`.\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,MAAa,sBAAsB;;;;;;AAOnC,MAAa,mBAAqC;;AAGlD,MAAM,iBAAiB;;AA2CvB,MAAM,YAA2B;CAC/B,OAAO;EAAE,WAAW;EAAO,WAAW;EAAO,WAAW;CAAsB;CAC9E,OAAO;EAAE,WAAW;EAAO,WAAW;EAAQ,WAAW;CAAM;AACjE;;;;;;AAOA,SAAS,iBAAyB;CAChC,OAAO;EACL;EACA;EACA;EACA;EAEA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,IAAI;AACb;;;;;;;;;;;AAYA,SAAgB,sBAA8B;CAC5C,OAAO;EACL,eAAe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,IAAI;AACb;;;;;;;;;;;;;AAcA,SAAgB,oBAA4B;CAC1C,OAAO;EACL,eAAe;EACf;EACA;EACA;E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1
- {"version":3,"file":"gtao-Bpu5-0Ne.js","names":[],"sources":["../src/lite/gpu/gtao.ts"],"sourcesContent":["import {\n addComputeDispatch,\n addTaskAfter,\n buildFrameGraphTask,\n computeTextureBinding,\n computeStorageTextureBinding,\n computeUniformBufferBinding,\n createComputeBindingSet,\n createComputeDispatch,\n createComputeShader,\n createComputeStorageTexture2D,\n createComputeTask,\n createComputeTextureResource,\n createUniformBuffer,\n disposeComputeBindingSet,\n disposeComputeShader,\n disposeComputeStorageTexture2D,\n disposeUniformBuffer,\n getEffectiveAspectRatio,\n getFrameGraph,\n getPbrUnlit,\n getProjectionMatrix,\n getViewMatrix,\n invertMat4,\n isPbrMaterial,\n removeComputeDispatch,\n updateUniformBuffer,\n} from \"@babylonjs/lite\";\nimport { rebuildMaterialPipelines } from \"../material.js\";\nimport { frameGraphTasks, SCENE_INPUT_TASK_NAMES } from \"./scene-inputs.js\";\nimport type { SceneInputs } from \"./scene-inputs.js\";\nimport type {\n ComputeDispatch,\n ComputeShader,\n ComputeStorageTexture2D,\n ComputeTask,\n EngineContext,\n Mat4,\n Material,\n MaterialPlugin,\n SceneContext,\n Task,\n UniformBuffer,\n} from \"@babylonjs/lite\";\n\n/**\n * Ground-truth ambient occlusion (`docs/plan/2026-11-gi-phase-1-execution-plan.md`, steps G8 and G9;\n * `docs/architecture/07-rendering.md` §2.14). Its own chunk: the renderer imports it only when\n * `rendering.ambientOcclusion.enabled` is on, so a project without it loads none of it and its frame\n * graph has none of these tasks (`CONSTITUTION.md` §2.5).\n *\n * ```text\n * … depth pyramid → gtao params → gtao (compute: horizons, then depth-aware blur) → scene → …\n * └─ AO texture ─→ every lit PBR material's `occlusion`\n * ```\n *\n * - **GTAO** (Jimenez et al. 2016, after XeGTAO): per pixel, a few screen-space slices through the\n * view vector; along each, the highest horizon on either side within `radius`, then the cosine-\n * weighted visible arc between them against the normal projected into the slice. Depth comes from\n * the scene inputs' depth pyramid (level 1 at half resolution, coarser levels for far taps), normals\n * from the scene inputs' world normals, rotated into view space. Slice angle and step offset are\n * jittered per pixel with interleaved gradient noise.\n * - **Denoise.** A 5×5 blur weighted by view-depth similarity, in the same compute pass.\n * - **Indirect light only (spike S3).** {@link createAmbientOcclusionPlugin} multiplies Lite's PBR\n * `occlusion` variable, which scales the environment's irradiance and specular occlusion and\n * nothing else (`lib/material/pbr/fragments/ibl-fragment.js`), by the AO texture at the\n * fragment's screen position. Every lit PBR variant declares `occlusion` before that slot: the\n * template's `occlusionDefault`, or the reflectance extension's own `AT` code\n * (`lib/material/pbr/fragments/reflectance-fragment.js` line 146). Standard materials, unlit PBR and\n * custom shaders are left alone.\n * - **Camera matrices** are written by a tiny task that runs inside the frame graph, after Lite has\n * updated world matrices for the frame, so the AO never lags a moving camera.\n * - **Resize and device loss.** The scene inputs' `onChange` disables the pass, rebuilds the\n * textures and bindings, swaps them in, and rebuilds the patched materials, whose bind groups hold\n * the AO texture's view. The old textures are disposed a few frames later, once no in-flight bind\n * group can still name them.\n * - **TAA.** `rendering.taa` (G5) filters the final colour, AO included; a dedicated AO history is\n * not wired. It would accumulate {@link AmbientOcclusion.texture} before the plugin reads it.\n */\n\n/**\n * The frame-graph task names, in the order they run after the scene inputs.\n *\n * @internal\n */\nexport const GTAO_TASK_NAMES = { params: \"ignifx:gtao-params\", compute: \"ignifx:gtao\" } as const;\n\n/**\n * The name the material plugin carries; part of Lite's pipeline cache key.\n *\n * @internal\n */\nexport const GTAO_PLUGIN_NAME = \"ignifx-gtao\";\n\n/** The uniform block: three matrices, the sizes, the settings. */\nconst UNIFORM_FLOATS = 16 * 3 + 4 + 4;\n\n/** Frames an old texture set outlives its replacement. */\nconst RETIRE_FRAMES = 8;\n\n/** The workgroup edge both shaders use. */\nconst WORKGROUP = 8;\n\n/**\n * What the GTAO pass is asked for.\n *\n * @internal\n */\nexport interface AmbientOcclusionOptions {\n /** `\"half\"` or `\"full\"` resolution. */\n readonly quality: \"half\" | \"full\";\n /** World-space radius. */\n readonly radius: number;\n /** Exponent on the visibility. */\n readonly intensity: number;\n /** Fraction of the radius over which occluders fade. */\n readonly falloff: number;\n /** Where an asynchronous rebuild's failure goes. */\n readonly onError: (error: unknown) => void;\n}\n\n/**\n * The slice and step counts and the resolution divisor of a quality.\n *\n * @internal\n */\nexport interface GtaoShape {\n /** Full-resolution pixels per AO pixel along each axis: 2 or 1. */\n readonly scale: number;\n /** The depth-pyramid level the centre depth is read from. */\n readonly baseMip: number;\n /** Screen-space slices per pixel. */\n readonly slices: number;\n /** Steps along each side of a slice. */\n readonly steps: number;\n}\n\n/**\n * The shape of a quality: `\"half\"` is 2 slices × 4 steps at half resolution, `\"full\"` 3 × 6 at full.\n *\n * @param quality - The quality.\n * @returns The shape.\n *\n * @internal\n */\nexport function gtaoShape(quality: \"half\" | \"full\"): GtaoShape {\n return quality === \"full\"\n ? { scale: 1, baseMip: 0, slices: 3, steps: 6 }\n : { scale: 2, baseMip: 1, slices: 2, steps: 4 };\n}\n\n/**\n * A running GTAO pass.\n *\n * @internal\n */\nexport interface AmbientOcclusion {\n /** The denoised AO texture, `rgba8unorm`, AO in every colour channel; replaced on resize. */\n readonly texture: ComputeStorageTexture2D;\n /**\n * Attaches the plugin to lit PBR materials that lack it and retires old textures. Once a frame.\n *\n * @param isSceneRegistered - Whether a patched material's pipelines must be rebuilt.\n */\n update(isSceneRegistered: boolean): void;\n /** Removes the tasks, frees every GPU object and releases the scene-inputs lease. Idempotent. */\n dispose(): void;\n}\n\n/** One device's worth of GPU objects, rebuilt on resize and device recovery. */\ninterface GpuSet {\n readonly uniforms: UniformBuffer;\n readonly raw: ComputeStorageTexture2D;\n readonly out: ComputeStorageTexture2D;\n readonly shaders: readonly ComputeShader[];\n readonly gtao: ComputeDispatch;\n readonly denoise: ComputeDispatch;\n /** Full-resolution width and height the set was built for. */\n readonly width: number;\n readonly height: number;\n}\n\n/**\n * Builds the GTAO compute shader.\n *\n * @param shape - The quality's shape, baked in as constants.\n * @returns The WGSL.\n *\n * @internal\n */\nexport function gtaoWgsl(shape: GtaoShape): string {\n return `\nstruct GtaoParams {\n proj: mat4x4<f32>,\n invProj: mat4x4<f32>,\n view: mat4x4<f32>,\n size: vec4<f32>,\n settings: vec4<f32>,\n};\n@group(0) @binding(0) var<uniform> params: GtaoParams;\n@group(0) @binding(1) var depthPyramid: texture_2d<f32>;\n@group(0) @binding(2) var normals: texture_2d<f32>;\n@group(0) @binding(3) var aoOut: texture_storage_2d<rgba16float, write>;\n\nconst SLICES: u32 = ${String(shape.slices)}u;\nconst STEPS: u32 = ${String(shape.steps)}u;\nconst BASE_MIP: i32 = ${String(shape.baseMip)};\nconst SCALE: f32 = ${shape.scale.toFixed(1)};\nconst PI: f32 = 3.14159265;\nconst HALF_PI: f32 = 1.57079633;\n\nfn loadDepth(pixel: vec2<f32>, mip: i32) -> f32 {\n let dims = vec2<i32>(textureDimensions(depthPyramid, mip));\n let coord = clamp(vec2<i32>(floor(pixel / f32(1 << u32(mip)))), vec2<i32>(0), dims - 1);\n return textureLoad(depthPyramid, coord, mip).r;\n}\n\nfn viewPosition(pixel: vec2<f32>, depth: f32) -> vec3<f32> {\n let uv = pixel / params.size.xy;\n let p = params.invProj * vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);\n return p.xyz / p.w;\n}\n\nfn ign(p: vec2<f32>) -> f32 {\n return fract(52.9829189 * fract(dot(p, vec2<f32>(0.06711056, 0.00583715))));\n}\n\n@compute @workgroup_size(${String(WORKGROUP)}, ${String(WORKGROUP)})\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n if (f32(id.x) >= params.size.z || f32(id.y) >= params.size.w) {\n return;\n }\n let pixel = (vec2<f32>(id.xy) + 0.5) * SCALE;\n let depth = loadDepth(pixel, BASE_MIP);\n if (depth <= 0.0) {\n textureStore(aoOut, vec2<i32>(id.xy), vec4<f32>(1.0, 0.0, 0.0, 1.0));\n return;\n }\n let P = viewPosition(pixel, depth);\n let V = normalize(viewPosition(pixel, 1.0) - P);\n let full = vec2<i32>(params.size.xy) - 1;\n let stored = textureLoad(normals, clamp(vec2<i32>(pixel), vec2<i32>(0), full), 0).xyz;\n let N = normalize((params.view * vec4<f32>(stored * 2.0 - 1.0, 0.0)).xyz);\n\n let radius = params.settings.x;\n let falloffRange = max(params.settings.y * radius, 0.0001);\n let c0 = params.proj * vec4<f32>(P, 1.0);\n let c1 = params.proj * vec4<f32>(P + vec3<f32>(radius, 0.0, 0.0), 1.0);\n let screenRadius = min(abs(c1.x / c1.w - c0.x / c0.w) * 0.5 * params.size.x, 0.3 * max(params.size.x, params.size.y));\n if (screenRadius < SCALE) {\n textureStore(aoOut, vec2<i32>(id.xy), vec4<f32>(1.0, abs(P.z), 0.0, 1.0));\n return;\n }\n let maxMip = i32(textureNumLevels(depthPyramid)) - 1;\n let noiseSlice = ign(vec2<f32>(id.xy));\n let noiseStep = ign(vec2<f32>(id.xy) + vec2<f32>(17.0, 59.0));\n\n var visibility = 0.0;\n for (var slice = 0u; slice < SLICES; slice++) {\n let phi = (f32(slice) + noiseSlice) * PI / f32(SLICES);\n let omega = vec2<f32>(cos(phi), -sin(phi));\n let direction = vec3<f32>(omega.x, -omega.y, 0.0);\n let orthoDirection = direction - dot(direction, V) * V;\n let axis = normalize(cross(orthoDirection, V));\n let projected = N - axis * dot(N, axis);\n let projectedLength = length(projected);\n let signN = sign(dot(orthoDirection, projected));\n let cosN = clamp(dot(projected, V) / max(projectedLength, 0.0001), 0.0, 1.0);\n let n = signN * acos(cosN);\n let low0 = cos(n + HALF_PI);\n let low1 = cos(n - HALF_PI);\n var horizon0 = low0;\n var horizon1 = low1;\n for (var step = 0u; step < STEPS; step++) {\n let t = (f32(step) + noiseStep) / f32(STEPS);\n let offsetLength = mix(SCALE, screenRadius, t * t);\n let mip = clamp(i32(floor(log2(offsetLength))) - 3, BASE_MIP, max(maxMip, BASE_MIP));\n let offset = omega * offsetLength;\n let d0 = loadDepth(pixel + offset, mip);\n let d1 = loadDepth(pixel - offset, mip);\n let s0 = viewPosition(pixel + offset, max(d0, 0.000001)) - P;\n let s1 = viewPosition(pixel - offset, max(d1, 0.000001)) - P;\n let l0 = length(s0);\n let l1 = length(s1);\n let w0 = select(0.0, clamp((radius - l0) / falloffRange, 0.0, 1.0), d0 > 0.0);\n let w1 = select(0.0, clamp((radius - l1) / falloffRange, 0.0, 1.0), d1 > 0.0);\n horizon0 = max(horizon0, mix(low0, dot(s0 / max(l0, 0.00001), V), w0));\n horizon1 = max(horizon1, mix(low1, dot(s1 / max(l1, 0.00001), V), w1));\n }\n var h0 = -acos(clamp(horizon1, -1.0, 1.0));\n var h1 = acos(clamp(horizon0, -1.0, 1.0));\n h0 = n + clamp(h0 - n, -HALF_PI, HALF_PI);\n h1 = n + clamp(h1 - n, -HALF_PI, HALF_PI);\n let sinN = sin(n);\n let arc0 = (cosN + 2.0 * h0 * sinN - cos(2.0 * h0 - n)) * 0.25;\n let arc1 = (cosN + 2.0 * h1 * sinN - cos(2.0 * h1 - n)) * 0.25;\n visibility += projectedLength * (arc0 + arc1);\n }\n visibility = clamp(visibility / f32(SLICES), 0.03, 1.0);\n let ao = pow(visibility, params.settings.z);\n textureStore(aoOut, vec2<i32>(id.xy), vec4<f32>(ao, abs(P.z), 0.0, 1.0));\n}\n`;\n}\n\n/**\n * Builds the denoise shader: a 5×5 Gaussian weighted by view-depth similarity.\n *\n * @returns The WGSL.\n *\n * @internal\n */\nexport function gtaoDenoiseWgsl(): string {\n return `\nstruct GtaoParams {\n proj: mat4x4<f32>,\n invProj: mat4x4<f32>,\n view: mat4x4<f32>,\n size: vec4<f32>,\n settings: vec4<f32>,\n};\n@group(0) @binding(0) var<uniform> params: GtaoParams;\n@group(0) @binding(1) var rawAo: texture_2d<f32>;\n@group(0) @binding(2) var aoOut: texture_storage_2d<rgba8unorm, write>;\n\n@compute @workgroup_size(${String(WORKGROUP)}, ${String(WORKGROUP)})\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n if (f32(id.x) >= params.size.z || f32(id.y) >= params.size.w) {\n return;\n }\n let dims = vec2<i32>(textureDimensions(rawAo)) - 1;\n let at = vec2<i32>(id.xy);\n let centre = textureLoad(rawAo, at, 0);\n if (centre.y <= 0.0) {\n textureStore(aoOut, at, vec4<f32>(centre.x, centre.x, centre.x, 1.0));\n return;\n }\n let tolerance = max(centre.y * 0.05, 0.0001);\n var sum = 0.0;\n var weights = 0.0;\n for (var y = -2; y <= 2; y++) {\n for (var x = -2; x <= 2; x++) {\n let tap = textureLoad(rawAo, clamp(at + vec2<i32>(x, y), vec2<i32>(0), dims), 0);\n let spatial = exp(-f32(x * x + y * y) / 4.5);\n let similar = max(0.0, 1.0 - abs(tap.y - centre.y) / tolerance);\n let weight = spatial * similar;\n sum += tap.x * weight;\n weights += weight;\n }\n }\n let ao = sum / max(weights, 0.0001);\n textureStore(aoOut, at, vec4<f32>(ao, ao, ao, 1.0));\n}\n`;\n}\n\n/**\n * The plugin code that multiplies a PBR fragment's `occlusion` by the AO texture.\n *\n * @remarks\n * At half resolution the AO texel under the fragment is blended bilinearly from four loads rather\n * than through a sampler, so the result does not depend on the storage texture's sampler. The block\n * scope keeps its names out of the shader's. `input.clipPos` is the fragment's `@builtin(position)`\n * (spike S3).\n *\n * @param scale - Full-resolution pixels per AO pixel.\n * @returns The WGSL for `CUSTOM_FRAGMENT_BEFORE_LIGHTS`.\n *\n * @internal\n */\nexport function gtaoPluginWgsl(scale: number): string {\n if (scale === 1) {\n return (\n \"{let igxAoMax=vec2<i32>(textureDimensions(ignifxAo))-1;\" +\n \"occlusion*=textureLoad(ignifxAo,clamp(vec2<i32>(input.clipPos.xy),vec2<i32>(0),igxAoMax),0).r;}\"\n );\n }\n return (\n \"{let igxAoMax=vec2<i32>(textureDimensions(ignifxAo))-1;\" +\n `let igxAoF=input.clipPos.xy/${scale.toFixed(1)}-0.5;` +\n \"let igxAoB=vec2<i32>(floor(igxAoF));let igxAoT=fract(igxAoF);\" +\n \"let igxAo00=textureLoad(ignifxAo,clamp(igxAoB,vec2<i32>(0),igxAoMax),0).r;\" +\n \"let igxAo10=textureLoad(ignifxAo,clamp(igxAoB+vec2<i32>(1,0),vec2<i32>(0),igxAoMax),0).r;\" +\n \"let igxAo01=textureLoad(ignifxAo,clamp(igxAoB+vec2<i32>(0,1),vec2<i32>(0),igxAoMax),0).r;\" +\n \"let igxAo11=textureLoad(ignifxAo,clamp(igxAoB+vec2<i32>(1,1),vec2<i32>(0),igxAoMax),0).r;\" +\n \"occlusion*=mix(mix(igxAo00,igxAo10,igxAoT.x),mix(igxAo01,igxAo11,igxAoT.x),igxAoT.y);}\"\n );\n}\n\n/**\n * Builds the material plugin that applies the AO texture to indirect light (spike S3).\n *\n * @param scale - Full-resolution pixels per AO pixel.\n * @param texture - Reads the current AO texture; it changes on resize.\n * @returns The plugin, shared by every lit PBR material.\n *\n * @internal\n */\nexport function createAmbientOcclusionPlugin(scale: number, texture: () => ComputeStorageTexture2D): MaterialPlugin {\n const fragment = { CUSTOM_FRAGMENT_BEFORE_LIGHTS: gtaoPluginWgsl(scale) };\n return {\n name: GTAO_PLUGIN_NAME,\n priority: 600,\n getSamplers: () => [{ texture: \"ignifxAo\", sampler: \"ignifxAoSampler\" }],\n // No `getActiveTextures`: the texture is the pass's own, and a material holding a pool reference\n // would stop it from being disposed on resize.\n bindTextures: (out) => {\n out.push({ texture: texture().sampledTexture });\n },\n getCustomCode: (stage) => (stage === \"fragment\" ? fragment : null),\n };\n}\n\n/**\n * Builds the GTAO pass, splices its tasks in after the scene inputs, and returns its handle.\n *\n * @remarks\n * Called once, from the renderer, with a scene-inputs lease the handle now owns. Before the scene is\n * registered (`isFrameGraphBuilt` `false`) `registerScene` records the tasks; afterwards they are\n * recorded here.\n *\n * @param engine - The engine.\n * @param scene - The render scene.\n * @param inputs - A scene-inputs lease; released by {@link AmbientOcclusion.dispose}.\n * @param options - The resolved settings.\n * @param isFrameGraphBuilt - Whether the scene is registered.\n * @returns The handle.\n *\n * @internal\n */\nexport async function createAmbientOcclusion(\n engine: EngineContext,\n scene: SceneContext,\n inputs: SceneInputs,\n options: AmbientOcclusionOptions,\n isFrameGraphBuilt: boolean,\n): Promise<AmbientOcclusion> {\n const shape = gtaoShape(options.quality);\n let current = await buildGpuSet(engine, inputs, shape);\n const retired: { set: GpuSet; frames: number }[] = [];\n const data = new Float32Array(UNIFORM_FLOATS);\n let isDisposed = false;\n let generation = 0;\n\n const compute: ComputeTask = createComputeTask(engine, GTAO_TASK_NAMES.compute);\n addComputeDispatch(compute, current.gtao);\n addComputeDispatch(compute, current.denoise);\n const params = createExecuteTask(engine, scene, GTAO_TASK_NAMES.params, () => {\n const enabled = writeParams(scene, current, shape, options, data);\n current.gtao.enabled = enabled;\n current.denoise.enabled = enabled;\n if (enabled) {\n updateUniformBuffer(engine, current.uniforms, data);\n }\n });\n const tasks: readonly Task[] = [params, compute];\n const pyramid = frameGraphTasks(scene)?.find((task) => task.name === SCENE_INPUT_TASK_NAMES.depthPyramid);\n if (pyramid === undefined) {\n disposeGpuSet(current);\n inputs.release();\n throw new Error(\"GTAO needs the scene inputs' depth pyramid task in the frame graph.\");\n }\n addTaskAfter(scene, params, pyramid);\n addTaskAfter(scene, compute, params);\n if (isFrameGraphBuilt) {\n const graph = getFrameGraph(scene);\n for (const task of tasks) {\n buildFrameGraphTask(graph, task);\n }\n }\n\n const plugin = createAmbientOcclusionPlugin(shape.scale, () => current.out);\n const stopWatch = inputs.onChange(() => {\n generation += 1;\n const mine = generation;\n // The pyramid and the input textures were replaced; the bindings name freed ones.\n compute.executionEnabled = false;\n buildGpuSet(engine, inputs, shape).then(\n (next) => {\n if (isDisposed || mine !== generation) {\n disposeGpuSet(next);\n return;\n }\n removeComputeDispatch(compute, current.gtao);\n removeComputeDispatch(compute, current.denoise);\n addComputeDispatch(compute, next.gtao);\n addComputeDispatch(compute, next.denoise);\n retired.push({ set: current, frames: RETIRE_FRAMES });\n current = next;\n compute.executionEnabled = true;\n rebuildPatchedMaterials(scene, plugin);\n },\n (error: unknown) => {\n options.onError(error);\n },\n );\n });\n\n return {\n get texture(): ComputeStorageTexture2D {\n return current.out;\n },\n update(isSceneRegistered: boolean): void {\n if (isDisposed) {\n return;\n }\n attachPlugin(scene, plugin, isSceneRegistered);\n for (let index = retired.length - 1; index >= 0; index -= 1) {\n const entry = retired[index];\n if (entry !== undefined && --entry.frames <= 0) {\n disposeGpuSet(entry.set);\n retired.splice(index, 1);\n }\n }\n },\n dispose(): void {\n if (isDisposed) {\n return;\n }\n isDisposed = true;\n stopWatch();\n const list = frameGraphTasks(scene);\n for (const task of tasks) {\n // Disable first: a disposed task that still executes is a use-after-free.\n task.executionEnabled = false;\n const index = list?.indexOf(task) ?? -1;\n if (list !== null && index >= 0) {\n list.splice(index, 1);\n }\n task.dispose();\n }\n disposeGpuSet(current);\n for (const entry of retired) {\n disposeGpuSet(entry.set);\n }\n retired.length = 0;\n inputs.release();\n },\n };\n}\n\n/**\n * Writes this frame's uniforms from the scene's camera.\n *\n * @param scene - The scene.\n * @param set - The current GPU set, for its sizes.\n * @param shape - The quality's shape.\n * @param options - The settings.\n * @param out - The uniform floats.\n * @returns `false` when there is no camera or its projection does not invert, so the pass skips.\n */\nfunction writeParams(\n scene: SceneContext,\n set: GpuSet,\n shape: GtaoShape,\n options: AmbientOcclusionOptions,\n out: Float32Array,\n): boolean {\n const camera = scene.camera;\n if (camera === null) {\n return false;\n }\n const projection = getProjectionMatrix(camera, getEffectiveAspectRatio(camera, set.width, set.height));\n const inverse = invertMat4(projection);\n if (inverse === null) {\n return false;\n }\n copyMat4(projection, out, 0);\n copyMat4(inverse, out, 16);\n copyMat4(getViewMatrix(camera), out, 32);\n out[48] = set.width;\n out[49] = set.height;\n out[50] = set.raw.width;\n out[51] = set.raw.height;\n out[52] = options.radius;\n out[53] = options.falloff;\n out[54] = options.intensity;\n out[55] = shape.slices;\n return true;\n}\n\n/**\n * Copies a Lite matrix into a float array.\n *\n * @param matrix - The matrix, column-major.\n * @param out - The destination.\n * @param offset - Where the 16 floats start.\n */\nfunction copyMat4(matrix: Mat4, out: Float32Array, offset: number): void {\n for (let index = 0; index < 16; index += 1) {\n out[offset + index] = matrix[index] ?? 0;\n }\n}\n\n/**\n * Creates the textures, shaders and bindings for the current surface size and device.\n *\n * @param engine - The engine.\n * @param inputs - The scene-inputs lease.\n * @param shape - The quality's shape.\n * @returns The set.\n */\nasync function buildGpuSet(engine: EngineContext, inputs: SceneInputs, shape: GtaoShape): Promise<GpuSet> {\n const width = inputs.depth.width;\n const height = inputs.depth.height;\n const aoWidth = Math.max(1, Math.ceil(width / shape.scale));\n const aoHeight = Math.max(1, Math.ceil(height / shape.scale));\n const [pyramid, normals] = await Promise.all([\n createComputeTextureResource(engine, inputs.depthPyramid, { sampleType: \"unfilterable-float\" }),\n createComputeTextureResource(engine, inputs.normals, { sampleType: \"unfilterable-float\" }),\n ]);\n const uniforms = createUniformBuffer(engine, UNIFORM_FLOATS * 4, { label: \"ignifx:gtao-params\" });\n const raw = createComputeStorageTexture2D(engine, {\n width: aoWidth,\n height: aoHeight,\n format: \"rgba16float\",\n label: \"ignifx:gtao-raw\",\n invertY: false,\n });\n const out = createComputeStorageTexture2D(engine, {\n width: aoWidth,\n height: aoHeight,\n format: \"rgba8unorm\",\n label: \"ignifx:gtao\",\n invertY: false,\n });\n const gtaoShader = createComputeShader(engine, {\n name: \"ignifx:gtao\",\n computeSource: gtaoWgsl(shape),\n bindings: [\n computeUniformBufferBinding(\"params\", { group: 0, binding: 0 }),\n computeTextureBinding(\"depthPyramid\", { group: 0, binding: 1, sampleType: \"unfilterable-float\" }),\n computeTextureBinding(\"normals\", { group: 0, binding: 2, sampleType: \"unfilterable-float\" }),\n computeStorageTextureBinding(\"aoOut\", { group: 0, binding: 3, format: \"rgba16float\" }),\n ],\n });\n const denoiseShader = createComputeShader(engine, {\n name: \"ignifx:gtao-denoise\",\n computeSource: gtaoDenoiseWgsl(),\n bindings: [\n computeUniformBufferBinding(\"params\", { group: 0, binding: 0 }),\n computeTextureBinding(\"rawAo\", { group: 0, binding: 1, sampleType: \"float\" }),\n computeStorageTextureBinding(\"aoOut\", { group: 0, binding: 2, format: \"rgba8unorm\" }),\n ],\n });\n const size = { x: Math.ceil(aoWidth / WORKGROUP), y: Math.ceil(aoHeight / WORKGROUP) };\n const gtao = createComputeDispatch(\n gtaoShader,\n createComputeBindingSet(gtaoShader, { params: uniforms, depthPyramid: pyramid, normals, aoOut: raw }),\n { size, enabled: false },\n );\n const denoise = createComputeDispatch(\n denoiseShader,\n createComputeBindingSet(denoiseShader, { params: uniforms, rawAo: raw.computeTexture, aoOut: out }),\n { size, enabled: false },\n );\n return { uniforms, raw, out, shaders: [gtaoShader, denoiseShader], gtao, denoise, width, height };\n}\n\n/**\n * Frees a set's GPU objects.\n *\n * @param set - The set.\n */\nfunction disposeGpuSet(set: GpuSet): void {\n set.gtao.enabled = false;\n set.denoise.enabled = false;\n disposeComputeBindingSet(set.gtao.bindings);\n disposeComputeBindingSet(set.denoise.bindings);\n for (const shader of set.shaders) {\n disposeComputeShader(shader);\n }\n disposeComputeStorageTexture2D(set.raw);\n disposeComputeStorageTexture2D(set.out);\n disposeUniformBuffer(set.uniforms);\n}\n\n/**\n * Creates a frame-graph task that runs a callback each frame, inside the frame graph.\n *\n * @remarks\n * Lite runs a task's `execute()` fast path instead of its recorded passes\n * (`lib/frame-graph/frame-graph.js`); `record()` and `build()` clear and walk `_passes`, which such\n * a task leaves empty. It runs after Lite's per-frame world-matrix update, unlike `onBeforeRender`.\n *\n * @param engine - The engine.\n * @param scene - The scene.\n * @param name - The task name.\n * @param run - The callback.\n * @returns The task.\n */\nfunction createExecuteTask(engine: EngineContext, scene: SceneContext, name: string, run: () => void): Task {\n const task = {\n name,\n engine,\n scene,\n executionEnabled: true,\n // oxlint-disable-next-line no-underscore-dangle\n _passes: [] as unknown[],\n record(): void {\n // Nothing to record: the work happens in `execute`.\n },\n execute(): number {\n run();\n return 0;\n },\n dispose(): void {\n // Owns nothing.\n },\n };\n return task;\n}\n\n/**\n * Gives every lit PBR material in the scene the AO plugin, once.\n *\n * @remarks\n * A walk, for the reasons `./hdr-output.ts`'s `attachLinearOutput` gives: materials come from many\n * places, and a surface shader replaces a material's plugin list.\n *\n * @param scene - The scene.\n * @param plugin - The shared plugin.\n * @param isSceneRegistered - Whether a patched material's pipelines must be rebuilt.\n */\nfunction attachPlugin(scene: SceneContext, plugin: MaterialPlugin, isSceneRegistered: boolean): 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 (getPbrUnlit(material) !== undefined) {\n continue;\n }\n const current = material.plugins ?? [];\n if (current.includes(plugin)) {\n continue;\n }\n material.plugins = [...current, plugin];\n if (isSceneRegistered) {\n rebuildMaterialPipelines(scene, material);\n }\n }\n}\n\n/**\n * Rebuilds every material that carries the plugin, so its bind group names the new AO texture.\n *\n * @param scene - The scene.\n * @param plugin - The shared plugin.\n */\nfunction rebuildPatchedMaterials(scene: SceneContext, plugin: MaterialPlugin): void {\n const seen = new Set<Material>();\n const meshes = scene.meshes;\n for (let index = 0; index < meshes.length; index += 1) {\n const material = meshes[index]?.material;\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n if (material === undefined || material === null || seen.has(material) || !isPbrMaterial(material)) {\n continue;\n }\n seen.add(material);\n if (material.plugins?.includes(plugin) === true) {\n rebuildMaterialPipelines(scene, material);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqFA,MAAa,kBAAkB;CAAE,QAAQ;CAAsB,SAAS;AAAc;;;;;;AAOtF,MAAa,mBAAmB;;AAGhC,MAAM,iBAAiB;;AAGvB,MAAM,gBAAgB;;AAGtB,MAAM,YAAY;;;;;;;;;AA4ClB,SAAgB,UAAU,SAAqC;CAC7D,OAAO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pu/hdr-output.ts"],"sourcesContent":["import {\n AcesToneMapping,\n addTask,\n addTaskBefore,\n buildFrameGraphTask,\n createEffectRenderTask,\n createEffectWrapper,\n createRenderTarget,\n createRenderTask,\n createSurfaceRenderTargetTexture,\n enableMaterialPlugins,\n getFrameGraph,\n getPbrUnlit,\n isPbrMaterial,\n isStandardMaterial,\n NeutralToneMapping,\n onRenderTargetTextureResize,\n reconcileMaterialPlugins,\n setEffectTexture,\n setEffectUniforms,\n setEnvironmentRotation,\n setFog,\n StandardToneMapping,\n} from \"@babylonjs/lite\";\nimport { rebuildMaterialPipelines } from \"../material.js\";\nimport { AGX_CALL_WGSL, AGX_HELPERS_WGSL, AGX_TONE_MAPPING_ID } from \"./agx-tone-mapping.js\";\nimport { DEPTH_STENCIL_FORMAT, markHdrScene } from \"./render-path.js\";\nimport type { AutoExposurePass } from \"./auto-exposure.js\";\nimport type { HdrOutputHandle, ScenePresenter } from \"./render-path.js\";\nimport type {\n EffectWrapper,\n EngineContext,\n FogConfig,\n ImageProcessingConfig,\n MaterialPlugin,\n RenderTarget,\n SceneContext,\n Task,\n Texture2D,\n} from \"@babylonjs/lite\";\n\n/**\n * The HDR render path (`docs/plan/2026-11-gi-phase-1-execution-plan.md`, step G2): the frame graph\n * a scene gets when the project declares `rendering.hdr`. Its own chunk: `../engine.ts` imports it\n * only when the setting is on, so a project without HDR loads none of it (`CONSTITUTION.md` §2.5).\n *\n * ```text\n * [shadow] → scene ──→ hdr (rgba16float) ─ [custom effects, linear] ─→ output ──→ swapchain\n * └──→ sceneColor ─ (built-in effects)\n * ```\n *\n * - **Linear colour.** Lite's PBR shader ends every fragment with fog, exposure, the curve, a\n * `pow(1/2.2)` encode, a clamp and contrast (`lib/material/pbr/pbr-template.js` line 171), so an\n * `rgba16float` target alone still holds values ≤ 1. {@link createLinearOutputPlugin} saves the\n * colour before that block and restores it before the fragment is written (spike S1).\n * - **The output pass** applies the scene's `imageProcessing` — exposure, contrast and the curve\n * the `Environment` set, or `loadEnvironment` set — then the same encode, clamp and contrast,\n * so a PBR-only scene presents the same bytes as without HDR, within half-float rounding.\n * - **Two output tasks.** A task cannot change its target once recorded, so there is one that\n * writes the swapchain and one that writes `sceneColor`, an ordinary colour target a\n * `PostProcessStack` chain reads. {@link ScenePresenter.setPresentEnabled} switches between them,\n * so the frame runs exactly one.\n *\n * - **Every other colour writer (step G3).** The restore re-applies the PBR fog, so a fogged scene\n * keeps its fog. A Standard material (and a surface shader on one) gets\n * {@link createStandardLinearPlugin}, which decodes its display colour; a surface shader on a PBR\n * host is caught by the PBR plugin, because its composite runs before the save. Lite's environment\n * skyboxes (`.env`, `.dds`) are patched to return the cube map's linear colour\n * ({@link linearSkyboxFragment}). Custom `.wgsl` materials (particles, foliage) are wrapped by\n * `./shader-material.ts`, which asks {@link markHdrScene}'s record. Sprites need nothing: a\n * `SpriteRenderer` draws its own pass onto the swapchain after the scene, so it never passes\n * through the output pass. Under HDR, Standard and custom-shader colour now gets the scene's\n * exposure, curve and contrast like everything else; with Lite's defaults (exposure 1, contrast 1,\n * no curve) that is the identity and the image matches the plain path.\n * - **Fog colour.** The scene's fog colour is stored decoded here, so the Standard fog block blends\n * in linear space and the PBR restore can use it as is.\n * - **Custom effects first.** A `PostProcessStack`'s custom effects ordered before any built-in one\n * are inserted before the output pass ({@link HdrOutputHandle.insertLinearTask}) and the output\n * pass reads the last one's result ({@link HdrOutputHandle.setOutputSource}). Bloom, SMAA and\n * Lite's image-processing task stay after it: they expect display colour and 8-bit targets.\n *\n * Not covered: Lite's six-face `loadSkybox` cube and its solid-colour and ground backgrounds, which\n * have fixed shaders with no patch point; they still encode twice under HDR.\n */\n\n/**\n * The colour format of the HDR scene target.\n *\n * @internal\n */\nexport const HDR_SCENE_FORMAT: GPUTextureFormat = \"rgba16float\";\n\n/**\n * The name the linear-output plugin carries; part of Lite's pipeline cache key.\n *\n * @internal\n */\nexport const LINEAR_OUTPUT_PLUGIN_NAME = \"ignifx-hdr-linear-output\";\n\n/**\n * The name the Standard material's decode plugin carries.\n *\n * @internal\n */\nexport const STANDARD_LINEAR_PLUGIN_NAME = \"ignifx-hdr-linear-standard\";\n\n/**\n * The name the unlit PBR material's plugin carries.\n *\n * @internal\n */\nexport const UNLIT_LINEAR_PLUGIN_NAME = \"ignifx-hdr-linear-unlit\";\n\n/**\n * Where the skybox patch sits in Lite's skybox patch list: after rotation (0) and blur (1)\n * (`lib/scene/set-environment-rotation.js`, `lib/scene/set-environment-blur.js`).\n */\nconst SKYBOX_PATCH_ORDER = 8;\n\n/**\n * Lite's fog factor (`lib/shader/wgsl-fog.js`) under an ignifx name: the PBR shader declares\n * `calcFogFactor` only when the scene has fog, and the plugin code must compile either way.\n */\nconst FOG_FACTOR_WGSL =\n \"fn ignifxFogFactor(d:vec3<f32>)->f32{var k:f32=1.0;let mode=scene.vFogInfos.x;let dist=length(d);\" +\n \"if(mode==3.0){k=(scene.vFogInfos.z-dist)/(scene.vFogInfos.z-scene.vFogInfos.y);}\" +\n \"else if(mode==1.0){k=1.0/pow(2.71828,dist*scene.vFogInfos.w);}\" +\n \"else if(mode==2.0){k=1.0/pow(2.71828,dist*dist*scene.vFogInfos.w*scene.vFogInfos.w);}\" +\n \"return clamp(k,0.0,1.0);}\";\n\n/**\n * The PBR fog block (`lib/material/pbr/pbr-fog-wgsl.js`) on the restored colour, except that the\n * fog colour is already linear: the HDR path stores it decoded.\n */\nconst FOG_RESTORE_WGSL =\n \"if(scene.vFogInfos.x>0.0){color=mix(scene.vFogColor.rgb,color,\" +\n \"pow(ignifxFogFactor((scene.view*vec4<f32>(input.worldPos,1.0)).xyz),2.2));}\";\n\n/**\n * The frame-graph task names, in the order they run after `\"scene\"`.\n *\n * @internal\n */\nexport const HDR_OUTPUT_TASK_NAMES = { toChain: \"ignifx:hdr-output-chain\", toSwapchain: \"ignifx:hdr-output\" } as const;\n\n/**\n * The curve numbers the output shader branches on.\n *\n * @internal\n */\nexport const HDR_CURVE = { none: 0, standard: 1, aces: 2, neutral: 3, agx: 4 } as const;\n\n/** The output pass's uniform block: exposure, contrast, curve, padding. */\nconst UNIFORM_FLOATS = 4;\n\n/**\n * Builds the material plugin that keeps a PBR fragment's colour linear.\n *\n * @remarks\n * `CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION` is injected at two slots (`AI`, `NI`;\n * `lib/material/plugin/plugin-bridge-shared.js` line 13), so the save is an assignment, never a\n * `let`; the second one, after indirect light, wins. Priority 0 puts the restore ahead of any other\n * plugin's `CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR` code, which then works on linear colour.\n *\n * @returns The plugin. Plain data, so one object can be shared by every material.\n *\n * @internal\n */\nexport function createLinearOutputPlugin(): MaterialPlugin {\n const fragment = {\n CUSTOM_FRAGMENT_DEFINITIONS: `var<private> ignifxLinearColor: vec3<f32>;${FOG_FACTOR_WGSL}`,\n CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION: \"ignifxLinearColor = color;\",\n CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR: `color = ignifxLinearColor;${FOG_RESTORE_WGSL}`,\n };\n return {\n name: LINEAR_OUTPUT_PLUGIN_NAME,\n priority: 0,\n getCustomCode: (stage) => (stage === \"fragment\" ? fragment : null),\n };\n}\n\n/**\n * Builds the plugin that keeps an unlit PBR material's colour linear.\n *\n * @remarks\n * With no environment, Lite's unlit fragment assigns its colour at the `NI` slot\n * (`lib/material/pbr/fragments/unlit-fragment.js`), after the linear-output plugin's save there, so\n * the save would hold the lit colour. This plugin recomputes the unlit colour instead\n * (`baseColor * material.unlitColor`, both in scope before the fragment is written), then applies\n * the fog the restore would.\n *\n * @returns The plugin, shared by every unlit PBR material.\n *\n * @internal\n */\nexport function createUnlitLinearPlugin(): MaterialPlugin {\n const fragment = {\n CUSTOM_FRAGMENT_DEFINITIONS: FOG_FACTOR_WGSL,\n CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR: `color = baseColor*material.unlitColor;${FOG_RESTORE_WGSL}`,\n };\n return {\n name: UNLIT_LINEAR_PLUGIN_NAME,\n priority: 0,\n getCustomCode: (stage) => (stage === \"fragment\" ? fragment : null),\n };\n}\n\n/**\n * Builds the plugin that turns a Standard material's colour linear.\n *\n * @remarks\n * Lite's Standard shader does no image processing and no encode: what it writes is the colour that\n * is displayed. The plugin decodes it with the exact inverse of the output pass's encode\n * (`pow(c, 2.2)`), so the output pass gives it back. It runs at the `BC` slot, before Lite's Standard fog\n * block (the `BA` slot), which then mixes in the decoded fog colour. Priority 1000 puts it after any\n * surface shader's own `CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR` code.\n *\n * @returns The plugin, shared by every Standard material.\n *\n * @internal\n */\nexport function createStandardLinearPlugin(): MaterialPlugin {\n const fragment = {\n CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR: \"color=vec4<f32>(pow(max(color.rgb,vec3<f32>(0.0)),vec3<f32>(2.2)),color.a);\",\n };\n return {\n name: STANDARD_LINEAR_PLUGIN_NAME,\n priority: 1000,\n getCustomCode: (stage) => (stage === \"fragment\" ? fragment : null),\n };\n}\n\n/**\n * Makes one of Lite's environment skybox shaders return the cube map's linear colour.\n *\n * @remarks\n * The `.env` (`\"hdr\"`) and `.dds` skyboxes multiply by `mesh.exposureLinear`, then encode, clamp\n * and apply contrast themselves (`lib/material/pbr/background-hdr-skybox.js`,\n * `lib/_chunks/background-dds-skybox-*.js`), and Lite gives them no material plugin point. The patch\n * returns the colour just before that multiply, so the output pass applies exposure, the curve and\n * the encode once. Code after the inserted `return` is unreachable, which WGSL accepts. A shader the\n * pattern does not match is returned unchanged.\n *\n * @param fragment - The skybox fragment WGSL, after Lite's own rotation and blur patches.\n * @returns The patched WGSL.\n *\n * @internal\n */\nexport function linearSkyboxFragment(fragment: string): string {\n const match = /\\b([A-Za-z_]\\w*)\\*=mesh\\.exposureLinear;/u.exec(fragment);\n if (match === null) {\n return fragment;\n }\n return `${fragment.slice(0, match.index)}return vec4<f32>(${match[1] ?? \"\"},1.0);${fragment.slice(match.index)}`;\n}\n\n/**\n * A fog configuration with its colour decoded the way Lite's PBR fog block decodes it.\n *\n * @param fog - The configuration the `Environment` installed, colour in sRGB.\n * @returns A fresh configuration, colour linear.\n *\n * @internal\n */\nexport function linearFogConfig(fog: FogConfig): FogConfig {\n return {\n mode: fog.mode,\n density: fog.density,\n start: fog.start,\n end: fog.end,\n color: [fog.color[0] ** 2.2, fog.color[1] ** 2.2, fog.color[2] ** 2.2],\n };\n}\n\n/**\n * Builds the output pass's fragment shader.\n *\n * @remarks\n * The curves are Lite's own WGSL (`ToneMapping.helpersWGSL`/`callWGSL`) and ignifx's AgX in the\n * same form (`./agx-tone-mapping.ts`, so both paths run one function), which read the exposure\n * from `scene.vImageInfos.x`; naming the uniform block `scene` lets them drop in unchanged. One\n * shader holds all of them and branches on a uniform, so a curve change uploads 16 bytes instead\n * of compiling a pipeline. The encode, clamp and contrast copy the PBR template's tail.\n *\n * @param autoExposure - Whether binding 2 holds the auto exposure texel (`./auto-exposure.ts`),\n * `log2` of a multiplier applied before the curve.\n * @returns The WGSL, with Lite's `effectFragment` entry point.\n *\n * @internal\n */\nexport function hdrOutputFragmentWgsl(autoExposure = false): string {\n return [\n AcesToneMapping.helpersWGSL,\n NeutralToneMapping.helpersWGSL,\n AGX_HELPERS_WGSL,\n \"struct HdrOutputUniforms{vImageInfos:vec4<f32>};\",\n \"@group(0)@binding(0)var<uniform>scene:HdrOutputUniforms;\",\n \"@group(0)@binding(1)var hdrColor:texture_2d<f32>;\",\n autoExposure ? \"@group(0)@binding(2)var autoExposure:texture_2d<f32>;\" : \"\",\n \"@fragment fn effectFragment(fragment:EffectVertexOutput)->@location(0)vec4<f32>{\",\n \"let texel=textureLoad(hdrColor,vec2<i32>(fragment.position.xy),0);\",\n \"var color=max(texel.rgb,vec3<f32>(0.0));\",\n autoExposure ? \"color*=exp2(textureLoad(autoExposure,vec2<i32>(0,0),0).r);\" : \"\",\n \"let curve=i32(scene.vImageInfos.z+0.5);\",\n `if(curve==${String(HDR_CURVE.standard)}){${StandardToneMapping.callWGSL}}`,\n `else if(curve==${String(HDR_CURVE.aces)}){${AcesToneMapping.callWGSL}}`,\n `else if(curve==${String(HDR_CURVE.neutral)}){${NeutralToneMapping.callWGSL}}`,\n `else if(curve==${String(HDR_CURVE.agx)}){${AGX_CALL_WGSL}}`,\n \"else{color*=scene.vImageInfos.x;}\",\n \"color=pow(color,vec3<f32>(1.0/2.2));\",\n \"color=clamp(color,vec3<f32>(0.0),vec3<f32>(1.0));\",\n \"let highContrast=color*color*(3.0-2.0*color);\",\n \"if(scene.vImageInfos.y<1.0){color=mix(vec3<f32>(0.5),color,scene.vImageInfos.y);}\",\n \"else{color=mix(color,highContrast,scene.vImageInfos.y-1.0);}\",\n \"color=max(color,vec3<f32>(0.0));\",\n \"return vec4<f32>(color,texel.a);\",\n \"}\",\n ].join(\"\\n\");\n}\n\n/**\n * The curve number for a scene's image processing.\n *\n * @remarks\n * Tone mapping switched on with no curve named is Lite's standard curve (`pbr-renderable.js`). A\n * custom Lite curve the output pass does not know falls back to the standard one.\n *\n * @param processing - The scene's image processing.\n * @returns One of {@link HDR_CURVE}.\n *\n * @internal\n */\nexport function hdrCurveOf(processing: Pick<ImageProcessingConfig, \"toneMappingEnabled\" | \"toneMapping\">): number {\n if (!processing.toneMappingEnabled) {\n return HDR_CURVE.none;\n }\n const id = processing.toneMapping?.id;\n if (id === AcesToneMapping.id) {\n return HDR_CURVE.aces;\n }\n if (id === AGX_TONE_MAPPING_ID) {\n return HDR_CURVE.agx;\n }\n return id === NeutralToneMapping.id ? HDR_CURVE.neutral : HDR_CURVE.standard;\n}\n\n/**\n * Writes the output pass's uniforms and says whether they changed.\n *\n * @param processing - The scene's image processing.\n * @param out - The four floats: exposure, contrast, curve, padding.\n * @returns `true` when `out` now differs from what it held.\n *\n * @internal\n */\nexport function writeHdrOutputUniforms(processing: ImageProcessingConfig, out: Float32Array): boolean {\n const curve = hdrCurveOf(processing);\n if (out[0] === processing.exposure && out[1] === processing.contrast && out[2] === curve) {\n return false;\n }\n out[0] = processing.exposure;\n out[1] = processing.contrast;\n out[2] = curve;\n return true;\n}\n\n/**\n * Builds the HDR render path and appends it to the scene's frame graph.\n *\n * @remarks\n * The same contract as `installOffscreenRenderPath` in `./render-path.ts`: call it right after\n * `createSceneContext(engine, { defaultRenderTask: false })` and before `registerScene`. It also\n * installs Lite's material-plugin bridges, which the linear-output plugin needs before the scene is\n * registered. With MSAA on, the scene draws into a multisampled `rgba16float` target that resolves\n * into the sampled one.\n *\n * @param engine - The engine, which is also the primary surface.\n * @param scene - The scene created with no default render task.\n * @param installAutoExposure - Builds the auto exposure passes over the HDR texture, between the\n * scene task and the output tasks (`./auto-exposure.ts`); omitted when auto exposure is off.\n * @returns The presenter, with its {@link ScenePresenter.hdr} handle set.\n *\n * @internal\n */\nexport function installHdrRenderPath(\n engine: EngineContext,\n scene: SceneContext,\n installAutoExposure?: (hdrTexture: Texture2D) => AutoExposurePass,\n): ScenePresenter {\n enableMaterialPlugins(scene);\n markHdrScene(scene);\n installLinearSkybox(scene);\n const hdr = createSurfaceRenderTargetTexture(engine, {\n lbl: \"ignifx:scene-hdr\",\n format: HDR_SCENE_FORMAT,\n samples: 1,\n size: engine,\n });\n const isMultisampled = engine.msaaSamples > 1;\n const config: { name: string; rt: RenderTarget; rst?: RenderTarget; depth?: RenderTarget } = {\n name: \"scene\",\n rt: hdr.rt,\n };\n if (isMultisampled) {\n config.rt = createRenderTarget({\n lbl: \"ignifx:scene-hdr-msaa\",\n format: HDR_SCENE_FORMAT,\n dFormat: DEPTH_STENCIL_FORMAT,\n samples: engine.msaaSamples,\n size: engine,\n });\n config.rst = hdr.rt;\n } else {\n config.depth = createRenderTarget({\n lbl: \"ignifx:scene-depth\",\n dFormat: DEPTH_STENCIL_FORMAT,\n samples: 1,\n size: engine,\n });\n }\n const sceneTask: Task = createRenderTask(config, engine, scene);\n addTask(scene, sceneTask);\n const autoExposure = installAutoExposure?.(hdr.texture) ?? null;\n\n const effect: EffectWrapper = createEffectWrapper(engine, {\n name: \"ignifx:hdr-output\",\n fragmentWGSL: hdrOutputFragmentWgsl(autoExposure !== null),\n bindings: [\n { name: \"hdrOutput\", binding: 0, kind: \"uniform\", uniformByteLength: UNIFORM_FLOATS * 4 },\n { name: \"hdrColor\", binding: 1, kind: \"texture\" },\n ...(autoExposure === null\n ? []\n : [\n {\n name: \"autoExposure\",\n binding: 2,\n kind: \"texture\" as const,\n textureSampleType: \"unfilterable-float\" as const,\n },\n ]),\n ],\n });\n setEffectTexture(effect, 1, hdr.texture);\n if (autoExposure !== null) {\n setEffectTexture(effect, 2, autoExposure.exposureTexture);\n }\n // What the output pass reads: the scene, or the last linear effect a PostProcessStack put first.\n let outputSource: Texture2D | null = null;\n // A resize swaps the texture behind the facade; the wrapper's cached bind group still holds the\n // old view until a texture write marks it dirty.\n onRenderTargetTextureResize(hdr, () => {\n setEffectTexture(effect, 1, outputSource ?? hdr.texture);\n });\n const uniforms = new Float32Array(UNIFORM_FLOATS);\n uniforms[0] = Number.NaN;\n writeHdrOutputUniforms(scene.imageProcessing, uniforms);\n setEffectUniforms(effect, uniforms);\n\n const sceneColor = createRenderTarget({ lbl: \"ignifx:scene-color\", format: engine.format, samples: 1, size: engine });\n const toChain: Task = createEffectRenderTask(\n { name: HDR_OUTPUT_TASK_NAMES.toChain, effect, target: sceneColor, clear: true },\n engine,\n scene,\n );\n const toSwapchain: Task = createEffectRenderTask(\n { name: HDR_OUTPUT_TASK_NAMES.toSwapchain, effect, target: engine.scRT, clear: true },\n engine,\n scene,\n );\n addTask(scene, toChain);\n addTask(scene, toSwapchain);\n toChain.executionEnabled = false;\n\n const plugins: LinearPlugins = {\n pbr: createLinearOutputPlugin(),\n unlit: createUnlitLinearPlugin(),\n standard: createStandardLinearPlugin(),\n };\n let linearFog: FogConfig | null = null;\n const handle: HdrOutputHandle = {\n sceneTexture: hdr.texture,\n exposureTexture: autoExposure?.exposureTexture ?? null,\n sceneTarget: hdr.rt,\n sceneTask,\n sceneTargetTexture: hdr,\n update(isSceneRegistered: boolean): void {\n autoExposure?.update();\n if (writeHdrOutputUniforms(scene.imageProcessing, uniforms)) {\n setEffectUniforms(effect, uniforms);\n }\n // The `Environment` installs a fresh sRGB config on every change; it is swapped for a decoded\n // copy once, before the frame reads it (`setFog` re-registers nothing it already has).\n const fog = scene.fog;\n if (fog !== null && fog !== linearFog) {\n linearFog = linearFogConfig(fog);\n setFog(scene, linearFog);\n }\n attachLinearOutput(scene, plugins, isSceneRegistered);\n },\n insertLinearTask(task: Task, isFrameGraphBuilt: boolean): void {\n addTaskBefore(scene, task, toChain);\n if (isFrameGraphBuilt) {\n buildFrameGraphTask(getFrameGraph(scene), task);\n }\n },\n setOutputSource(texture: Texture2D | null): void {\n if (texture === outputSource) {\n return;\n }\n outputSource = texture;\n setEffectTexture(effect, 1, texture ?? hdr.texture);\n },\n };\n let isPresentEnabled = true;\n return {\n sceneColor,\n swapchain: engine.scRT,\n setPresentEnabled(enabled: boolean): void {\n isPresentEnabled = enabled;\n toSwapchain.executionEnabled = enabled;\n toChain.executionEnabled = !enabled;\n },\n get isPresentEnabled(): boolean {\n return isPresentEnabled;\n },\n hdr: handle,\n scenePass: { task: sceneTask, target: hdr.rt, format: HDR_SCENE_FORMAT, isTargetWritable: true },\n };\n}\n\n/** The two shared plugins the per-frame walk hands out. */\ninterface LinearPlugins {\n /** The save, restore and fog for PBR materials, PBR skyboxes included. */\n readonly pbr: MaterialPlugin;\n /** The recompute and fog for unlit PBR materials. */\n readonly unlit: MaterialPlugin;\n /** The decode for Standard materials. */\n readonly standard: MaterialPlugin;\n}\n\n/**\n * Makes Lite's environment skyboxes write linear colour (see {@link linearSkyboxFragment}).\n *\n * @remarks\n * Lite composes a skybox's fragment through `scene._environmentSkyboxShaderComposer`, which runs the\n * loaders in `scene._environmentSkyboxShaderPatchLoaders` in order\n * (`lib/material/pbr/environment-skybox-shader-composer.js`). Neither field is declared in\n * `index.d.ts`, and the composer is created only by Lite's own registration, which also prepends\n * the scene uniforms the `.env` skybox needs. `setEnvironmentRotation(scene, 0)` is that\n * registration with no visible effect (rotation 0 is what the scene has); the `Environment`\n * overwrites it with its own rotation later. The patch is installed before any environment loads,\n * and pinned by `test/render/hdr-coverage.browser.test.ts`.\n *\n * @param scene - The HDR scene.\n */\nfunction installLinearSkybox(scene: SceneContext): void {\n setEnvironmentRotation(scene, 0);\n // Boundary assertion (coding standards §5.2): the loader list is a plain array Lite keeps on the\n // scene object it created; see the remarks for the `lib/` file that reads it.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const slots = scene as SceneContext & SkyboxPatchSlots;\n // oxlint-disable-next-line no-underscore-dangle\n const loaders = (slots._environmentSkyboxShaderPatchLoaders ??= []);\n loaders[SKYBOX_PATCH_ORDER] = () => Promise.resolve({ _apply: linearSkyboxFragment });\n}\n\n/** The undeclared Lite scene field the skybox patch writes (adapter-internal mirror, standards §5.1). */\ninterface SkyboxPatchSlots {\n /** Lite's skybox shader patches, by order; each resolves to an object whose `_apply` edits the WGSL. */\n _environmentSkyboxShaderPatchLoaders?: (SkyboxPatchLoader | undefined)[];\n}\n\n/** One entry of Lite's skybox patch list. */\ntype SkyboxPatchLoader = () => Promise<{ readonly _apply: (fragment: string, kind: string) => string }>;\n\n/**\n * Gives every PBR and Standard material in the scene its linear-output plugin, once.\n *\n * @remarks\n * A walk rather than a hook at material creation, because materials come from several places\n * (material assets, glTF models, `.lite` code) and a surface shader replaces a material's whole\n * plugin list; a material that lost the plugin gets it back on the next frame. A PBR skybox\n * (`setPbrSkybox`) is a PBR material and gets the PBR plugin. Lite's mesh factories leave\n * `material` `null` until one is assigned.\n *\n * @param scene - The scene to walk.\n * @param shared - The shared plugins.\n * @param isSceneRegistered - Whether a patched material's pipelines must be rebuilt.\n */\nfunction attachLinearOutput(scene: SceneContext, shared: LinearPlugins, isSceneRegistered: boolean): 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 // (`lib/mesh/mesh-factories.js`), and `isPbrMaterial(null)` throws.\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n if (material === undefined || material === null) {\n continue;\n }\n let plugin: MaterialPlugin;\n if (isPbrMaterial(material)) {\n plugin = getPbrUnlit(material) === undefined ? shared.pbr : shared.unlit;\n } else if (isStandardMaterial(material)) {\n plugin = shared.standard;\n } else {\n continue;\n }\n const current = material.plugins ?? [];\n // A PBR material that became unlit, or stopped being so, swaps one plugin for the other.\n let stale: MaterialPlugin | null = null;\n if (plugin === shared.pbr) {\n stale = shared.unlit;\n } else if (plugin === shared.unlit) {\n stale = shared.pbr;\n }\n const hasStale = stale !== null && current.includes(stale);\n if (current.includes(plugin) && !hasStale) {\n continue;\n }\n const kept = hasStale ? current.filter((other) => other !== stale) : current;\n material.plugins = kept.includes(plugin) ? kept : [...kept, plugin];\n if (plugin === shared.standard) {\n // The Standard bridge bakes a plugin signature per material, which only happens for meshes it\n // saw at `enableMaterialPlugins` or at a material change; this bakes and rebuilds it now.\n void reconcileMaterialPlugins(scene, material);\n continue;\n }\n if (isSceneRegistered) {\n rebuildMaterialPipelines(scene, material);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,MAAa,mBAAqC;;;;;;AAOlD,MAAa,4BAA4B;;;;;;AAOzC,MAAa,8BAA8B;;;;;;AAO3C,MAAa,2BAA2B;;;;;AAMxC,MAAM,qBAAqB;;;;;AAM3B,MAAM,kBACJ;;;;;AAUF,MAAM,mBACJ;;;;;;AAQF,MAAa,wBAAwB;CAAE,SAAS;CAA2B,aAAa;AAAoB;;;;;;AAO5G,MAAa,YAAY;CAAE,MAAM;CAAG,UAAU;CAAG,MAAM;CAAG,SAAS;CAAG,KAAK;AAAE;;AAG7E,MAAM,iBAAiB;;;;;;;;;;;;;;AAevB,SAAgB,2BAA2C;CACzD,MAAM,WAAW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