@ignifx/core 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/{environment-DZ6WUHbm.js → environment-Bf4aphSb.js} +2 -2
  2. package/dist/{environment-DZ6WUHbm.js.map → environment-Bf4aphSb.js.map} +1 -1
  3. package/dist/{gtao-_nr0b6-E.js → gtao-Bpu5-0Ne.js} +2 -2
  4. package/dist/{gtao-_nr0b6-E.js.map → gtao-Bpu5-0Ne.js.map} +1 -1
  5. package/dist/{hdr-output-Dbv0lhFl.js → hdr-output-DBQwMphy.js} +2 -2
  6. package/dist/{hdr-output-Dbv0lhFl.js.map → hdr-output-DBQwMphy.js.map} +1 -1
  7. package/dist/{ignifx-error-B8ByiSfJ.js → ignifx-error-DwIZKxA2.js} +4 -1
  8. package/dist/ignifx-error-DwIZKxA2.js.map +1 -0
  9. package/dist/index.d.ts +218 -696
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +2904 -970
  12. package/dist/index.js.map +1 -1
  13. package/dist/{instanced-mesh-instance-BMhREEfx.js → instanced-mesh-instance-B-fXKSrY.js} +2 -2
  14. package/dist/{instanced-mesh-instance-BMhREEfx.js.map → instanced-mesh-instance-B-fXKSrY.js.map} +1 -1
  15. package/dist/{light-probe-asset-B60_X-yN.js → light-probe-asset-BqfSrJe9.js} +2 -2
  16. package/dist/{light-probe-asset-B60_X-yN.js.map → light-probe-asset-BqfSrJe9.js.map} +1 -1
  17. package/dist/{light-probes-DkYN89Qw.js → light-probes-DDojYajw.js} +4 -4
  18. package/dist/{light-probes-DkYN89Qw.js.map → light-probes-DDojYajw.js.map} +1 -1
  19. package/dist/lightmaps-BUUIIkt9.js +230 -0
  20. package/dist/lightmaps-BUUIIkt9.js.map +1 -0
  21. package/dist/{material-CGk5mAah.js → material-myMbl9mW.js} +37 -2
  22. package/dist/{material-CGk5mAah.js.map → material-myMbl9mW.js.map} +1 -1
  23. package/dist/{material-plugin-CiAmriQ_.js → material-plugin-DapJNj04.js} +2 -2
  24. package/dist/{material-plugin-CiAmriQ_.js.map → material-plugin-DapJNj04.js.map} +1 -1
  25. package/dist/{post-effect-CQnlX1RH.js → post-effect-Cu3Enpz7.js} +2 -2
  26. package/dist/{post-effect-CQnlX1RH.js.map → post-effect-Cu3Enpz7.js.map} +1 -1
  27. package/dist/{post-effect-compiler-C_7HTHZy.js → post-effect-compiler-cCq9lcHt.js} +3 -3
  28. package/dist/{post-effect-compiler-C_7HTHZy.js.map → post-effect-compiler-cCq9lcHt.js.map} +1 -1
  29. package/dist/{prefab-overrides-DT-wHHAJ.js → prefab-overrides-C2GsgOQc.js} +467 -30
  30. package/dist/prefab-overrides-C2GsgOQc.js.map +1 -0
  31. package/dist/{prefab-overrides-BLQn5yHS.d.ts → prefab-overrides-htDc_5Po.d.ts} +1370 -246
  32. package/dist/prefab-overrides-htDc_5Po.d.ts.map +1 -0
  33. package/dist/prefab.d.ts +2 -2
  34. package/dist/prefab.js +2 -2
  35. package/dist/{reflection-probe-DlVsl3zJ.js → reflection-probe-QkD1Fo_d.js} +106 -12
  36. package/dist/{reflection-probe-DlVsl3zJ.js.map → reflection-probe-QkD1Fo_d.js.map} +1 -1
  37. package/dist/reflection-probes-CAzSuqf8.js +921 -0
  38. package/dist/reflection-probes-CAzSuqf8.js.map +1 -0
  39. package/dist/{shader-material-CaAkv5nT.js → shader-material-CJIDFvSb.js} +2 -2
  40. package/dist/{shader-material-CaAkv5nT.js.map → shader-material-CJIDFvSb.js.map} +1 -1
  41. package/dist/{shader-material-C2_UCYdO.js → shader-material-TM4f8eKA.js} +4 -4
  42. package/dist/{shader-material-C2_UCYdO.js.map → shader-material-TM4f8eKA.js.map} +1 -1
  43. package/dist/{shader-pragma-DmZpxGUo.js → shader-pragma-ljmAbVc2.js} +2 -2
  44. package/dist/{shader-pragma-DmZpxGUo.js.map → shader-pragma-ljmAbVc2.js.map} +1 -1
  45. package/dist/{ssgi-Dm-maZrc.js → ssgi-DSnhqotl.js} +2 -2
  46. package/dist/{ssgi-Dm-maZrc.js.map → ssgi-DSnhqotl.js.map} +1 -1
  47. package/dist/{surface-shader-BeDRofOV.js → surface-shader-rpPpeosD.js} +6 -6
  48. package/dist/{surface-shader-BeDRofOV.js.map → surface-shader-rpPpeosD.js.map} +1 -1
  49. package/dist/{vec3-Cc19wl4r.js → vec3-2C3LBZnt.js} +55 -3
  50. package/dist/vec3-2C3LBZnt.js.map +1 -0
  51. package/package.json +1 -1
  52. package/dist/ignifx-error-B8ByiSfJ.js.map +0 -1
  53. package/dist/prefab-overrides-BLQn5yHS.d.ts.map +0 -1
  54. package/dist/prefab-overrides-DT-wHHAJ.js.map +0 -1
  55. package/dist/reflection-probes-B8S9WnVX.js +0 -551
  56. package/dist/reflection-probes-B8S9WnVX.js.map +0 -1
  57. package/dist/vec3-Cc19wl4r.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { n as assertNever } from "./ignifx-error-B8ByiSfJ.js";
1
+ import { n as assertNever } from "./ignifx-error-DwIZKxA2.js";
2
2
  import { s as degToRad } from "./math-utils-BcDnL-gi.js";
3
3
  import { t as Color } from "./color-DrR6GFTd.js";
4
4
  import { AcesToneMapping, NeutralToneMapping, StandardToneMapping, loadEnvironment, setEnvironmentBlur, setEnvironmentRotation, setFog, setSceneImageProcessing } from "@babylonjs/lite";
@@ -294,4 +294,4 @@ function toneMappingCurve(name) {
294
294
  //#endregion
295
295
  export { readSceneImageProcessing as a, setSceneEnvironmentRotation as c, readSceneEnvironment as i, setSceneFog as l, installSceneEnvironment as n, setSceneClearColor as o, loadSceneEnvironment as r, setSceneEnvironmentBlur as s, TONE_MAPPING_NAMES as t, setSceneImageProcessingOptions as u };
296
296
 
297
- //# sourceMappingURL=environment-DZ6WUHbm.js.map
297
+ //# sourceMappingURL=environment-Bf4aphSb.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"environment-DZ6WUHbm.js","names":[],"sources":["../src/lite/gpu/environment.ts"],"sourcesContent":["import {\n AcesToneMapping,\n loadEnvironment,\n loadSkybox,\n NeutralToneMapping,\n setEnvironmentBlur,\n setEnvironmentRotation,\n setFog,\n setSceneImageProcessing,\n StandardToneMapping,\n} from \"@babylonjs/lite\";\nimport { assertNever } from \"../../errors/ignifx-error.js\";\nimport { Color } from \"../../math/color.js\";\nimport { degToRad } from \"../../math/math-utils.js\";\nimport type { EnvironmentTextures, SceneContext, ToneMapping } from \"@babylonjs/lite\";\n\n/**\n * Environment half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §2.5): image\n * based lighting, the skybox, fog, image processing, and the clear colour.\n *\n * Everything here is `@internal`. Loading uploads cube maps, so the module is GPU-only.\n *\n * ## The BRDF LUT is mandatory (verified against `@babylonjs/lite@1.27.0`)\n *\n * `loadEnvironment(scene, url, options)` (`index.d.ts` 6779) takes a **required** `brdfUrl`: Lite\n * decodes the split-sum BRDF lookup table from a pre-baked RGBD PNG rather than computing it, \"for\n * pixel-perfect parity\" with Babylon.js (`lib/_chunks/env-helpers-*.js`, `loadBrdfImage`, which\n * `fetch`es the URL and decodes it with `createImageBitmap`). ignifx ships that PNG as\n * `tests/fixtures/assets/brdf-lut.png`, decoded from Babylon.js's own\n * `_environmentBRDFBase64Texture` (`packages/dev/core/src/Misc/brdfTextureTools.ts`, Apache-2.0).\n * It is 256×256 RGBA8 and 23 KB.\n *\n * ## Fog\n *\n * `SceneContext.fog` is `FogConfig | null` (`index.d.ts` 5350) with a numeric `mode`; Lite exports\n * no named constants for it, so {@link FOG_MODES} maps ignifx's names onto the numbers.\n *\n * **Fog has to be installed with `setFog`, not by assigning the field.** `scene.fog` is what the PBR\n * group builder reads to decide whether a material's program gets the fog block at all\n * (`lib/material/pbr/pbr-renderable.js` 140-159, `PBR_HAS_FOG`), but the block it compiles reads\n * `scene.vFogInfos.x` out of the scene uniform buffer — and the only writer of those slots is\n * `writeFogUbo`, which nothing registers except `setFog`\n * (`lib/scene/scene-ubo-extras.js`: `setFog` is `scene.fog = config` **plus**\n * `_registerSceneUboContributor(scene, writeFogUbo)`, and `_writePassSceneUBO` runs\n * `scene._sceneUboContributors` and nothing else, `lib/frame-graph/render-task.js` 372-379).\n * Lite says as much in `index.d.ts` 10471: \"importing `setFog` is what pulls the fog UBO writer into\n * the bundle\". Assigning `scene.fog` alone therefore compiles the fog block into every PBR pipeline\n * and leaves `vFogInfos` zeroed, so `vFogInfos.x > 0.0` is never true and the scene renders with no\n * fog at all — the cost with none of the effect.\n *\n * A **fresh** config object goes in on every change, because a render task caches its scene UBO on\n * the identity of `scene.fog` (`s[1] === fog`, `lib/frame-graph/render-task.js` 355-371): mutating\n * the installed object in place leaves the cache key equal and the new density or colour never\n * reaches the GPU. Turning fog off writes mode `0`, which is what the already-compiled fog block\n * reads as \"no fog\"; dropping the field back to `null` would only stop the writer and leave the last\n * fog standing. A scene that never had fog keeps its `null` and pays nothing.\n *\n * ## Image processing\n *\n * `setSceneImageProcessing` is **async** (`index.d.ts` 10917) because tone mapping is baked into\n * the PBR shaders at `registerScene` time; changing it recompiles the affected pipelines\n * (`rebuildScenePbrPipelines`). Setting exposure or contrast alone still goes through the same\n * call. Note that `loadEnvironment` **overwrites** all three (`toneMappingEnabled = true`,\n * `exposure = 0.8`, `contrast = 1.2`) as a side effect of installing an environment, which is why\n * the `Environment` component re-applies its own image processing after every install.\n *\n * ## Swapping the installed environment: `scene._envTextures`\n *\n * Lite 1.27.0 declares **no** public way to replace, clear, or read back a registered scene's\n * environment. `index.d.ts` has no `scene.environmentTexture`, no `unloadEnvironment`, and no\n * setter of any kind; `loadEnvironment` is the only installer and it fetches, decodes, and uploads\n * a fresh cube map every call. What it actually installs is one field —\n * `scene._envTextures = textures` (`lib/_chunks/env-helpers-CRI1i-A3.js` 24, and the same line in\n * `lib/loader-hdr/load-hdr.js` 23, `lib/loader-env/load-dds-env.js` 177 and\n * `lib/loader-gltf/gltf-ext-lights-image-based.js` 65) — and every consumer reads that field:\n *\n * - the PBR group builder, which bakes the cube view and sampler into each material's bind group\n * (`lib/material/pbr/pbr-material.js` 12 → `lib/material/pbr/pbr-renderable.js`);\n * - the scene-uniform packer, for `lodGenerationScale` (`lib/frame-graph/scene-uniforms-pack.js` 21);\n * - the env UBO contributor, for the diffuse spherical harmonics (`lib/scene/scene-ubo-extras.js` 24);\n * - the blur contributor, for `lodGenerationOffset` (`lib/scene/set-environment-blur.js` 8);\n * - the render task's scene-UBO cache key, which is keyed on the **object identity** of the field\n * (`lib/frame-graph/render-task.js` 358), so a new object re-uploads the harmonics by itself.\n *\n * Lite's own device-lost recovery replaces the field exactly this way\n * (`lib/loader-env/environment-recovery.js` 16 and 38), so {@link installSceneEnvironment} writes it\n * too. Bind groups are the one consumer that does *not* re-read it: they hold the `GPUTextureView`,\n * so a swap only reaches the specular reflection once the material groups have been rebuilt, which\n * `rebuildSceneRenderables` does (`lib/scene/scene-rebuild.js`, `rebuildEachGroup`). The\n * `Environment` component therefore reports an install as a topology change and lets the render-sync\n * system fire its one coalesced rebuild. This is the only place in ignifx that touches a Lite field\n * `index.d.ts` does not declare, which is what the adapter boundary exists for\n * (`CONSTITUTION.md` §3.4, ADR-0002); it is pinned by\n * `packages/core/test/lite/render/environment.browser.test.ts`, which fails loudly if the field is\n * renamed.\n */\n\n/**\n * The GPU-resident image-based-lighting textures `loadEnvironment` resolves to, re-exported under an\n * ignifx name (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteEnvironmentTextures = EnvironmentTextures;\n\n/**\n * ignifx fog mode names mapped to the numbers `FogConfig.mode` uses.\n *\n * @internal\n */\nexport const FOG_MODES = {\n /** No fog. */\n none: 0,\n /** Exponential fog. */\n exp: 1,\n /** Squared-exponential fog. */\n exp2: 2,\n /** Linear fog between `start` and `end`. */\n linear: 3,\n} as const;\n\n/**\n * The union of the fog mode names.\n *\n * @internal\n */\nexport type FogMode = keyof typeof FOG_MODES;\n\n/**\n * The tone-mapping curves `docs/architecture/07-rendering.md` §2.5 exposes. `\"agx\"` is ignifx's\n * own Lite curve (`./agx-tone-mapping.ts`); the others are Lite's built-ins.\n *\n * @public\n */\nexport const TONE_MAPPING_NAMES = [\"none\", \"standard\", \"aces\", \"neutral\", \"agx\"] as const;\n\n/**\n * The `id` of the AgX curve, repeated from `./agx-tone-mapping.ts` so recognising it does not load\n * that chunk.\n */\nconst AGX_TONE_MAPPING_ID = \"ignifx-agx\";\n\n/**\n * The union of the tone-mapping curve names.\n *\n * @internal\n */\nexport type ToneMappingName = (typeof TONE_MAPPING_NAMES)[number];\n\n/**\n * The image processing Lite's PBR shaders apply: exposure, contrast and the tone-mapping curve.\n *\n * @internal\n */\nexport interface ImageProcessingState {\n /** The exposure multiplier. */\n exposure: number;\n /** The contrast multiplier. */\n contrast: number;\n /** The tone-mapping curve, or `\"none\"`. */\n curve: ToneMappingName;\n}\n\n/**\n * How an ignifx `Environment` component configures image based lighting.\n *\n * @internal\n */\nexport interface EnvironmentLoadOptions {\n /** The `.env` file holding the prefiltered specular cube map and its spherical harmonics. */\n readonly url: string;\n /** The RGBD PNG BRDF lookup table. Required by Lite. */\n readonly brdfUrl: string;\n /** A `.dds` or `.env` skybox. Omit for a flat background. */\n readonly skyboxUrl?: string;\n /** The skybox cube's size, in metres. Lite defaults to 20. */\n readonly skyboxSize?: number;\n /** Skip the skybox entirely. */\n readonly skipSkybox?: boolean;\n /** Skip the reflective ground plane Lite would otherwise add. */\n readonly skipGround?: boolean;\n /** A texture for that ground plane. */\n readonly groundTextureUrl?: string;\n}\n\n/**\n * Loads an `.env` environment and installs it on a scene.\n *\n * @param scene - The scene to light.\n * @param options - The environment, BRDF, and skybox URLs.\n * @returns The GPU-resident environment textures, for materials that need them explicitly.\n *\n * @example\n * ```ts\n * await loadSceneEnvironment(scene, {\n * url: \"environments/studio.env\",\n * brdfUrl: \"environments/brdf-lut.png\",\n * });\n * ```\n *\n * @internal\n */\nexport function loadSceneEnvironment(\n scene: SceneContext,\n options: EnvironmentLoadOptions,\n): Promise<EnvironmentTextures> {\n const liteOptions: {\n brdfUrl: string;\n skyboxUrl?: string;\n skyboxSize?: number;\n skipSkybox?: boolean;\n skipGround?: boolean;\n groundTextureUrl?: string;\n } = { brdfUrl: options.brdfUrl };\n if (options.skyboxUrl !== undefined) {\n liteOptions.skyboxUrl = options.skyboxUrl;\n }\n if (options.skyboxSize !== undefined) {\n liteOptions.skyboxSize = options.skyboxSize;\n }\n if (options.skipSkybox !== undefined) {\n liteOptions.skipSkybox = options.skipSkybox;\n }\n if (options.skipGround !== undefined) {\n liteOptions.skipGround = options.skipGround;\n }\n if (options.groundTextureUrl !== undefined) {\n liteOptions.groundTextureUrl = options.groundTextureUrl;\n }\n return loadEnvironment(scene, options.url, liteOptions);\n}\n\n/**\n * The scene fields Babylon Lite 1.27.0 writes for image-based lighting but does not declare in\n * `index.d.ts`. Adapter-internal Lite mirror (coding standards §5.1); see the module header for the\n * `lib/` lines that prove each one.\n */\ninterface SceneEnvironmentSlot {\n /** What `loadEnvironment` installed, or `undefined` on a scene that has never had one. */\n _envTextures?: EnvironmentTextures | undefined;\n}\n\n/**\n * Views a scene through its undeclared environment slot.\n *\n * @param scene - The scene.\n * @returns The same object, typed so the slot is reachable.\n */\nfunction environmentSlotOf(scene: SceneContext): SceneEnvironmentSlot {\n // Boundary assertion (coding standards §5.2): `SceneContext` is a plain object literal Lite\n // creates in `lib/scene/scene-core.js`, and `_envTextures` is one of its own fields — it is\n // absent from `index.d.ts` because it is not part of Lite's declared surface, not because it is\n // a different object. See the module header for every `lib/` line that reads or writes it.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return scene as SceneContext & SceneEnvironmentSlot;\n}\n\n/**\n * Reports which environment textures a scene is currently lit by.\n *\n * @param scene - The scene to inspect.\n * @returns The installed textures, or `null` when no environment has ever been installed.\n *\n * @internal\n */\nexport function readSceneEnvironment(scene: SceneContext): EnvironmentTextures | null {\n // The underscore is Lite's, not ignifx's: coding standards §5.1 reserves `_field` for exactly\n // this, an adapter-internal mirror of a Lite field, and the module header proves the name.\n // oxlint-disable-next-line no-underscore-dangle\n return environmentSlotOf(scene)._envTextures ?? null;\n}\n\n/**\n * Points a scene at an already-loaded set of environment textures, without loading anything.\n *\n * @remarks\n * This is how an `Environment` component swaps environments at runtime: the textures belong to the\n * `EnvironmentAsset` that loaded them and stay alive as long as its handle is retained, so\n * switching between two loaded assets uploads nothing and frees nothing.\n *\n * The specular reflection follows only after the scene's material groups are rebuilt\n * (`rebuildRenderables` in `../shadow.ts`): a PBR bind group holds the cube map's `GPUTextureView`,\n * not the slot. The diffuse harmonics and the LOD scale follow immediately, because the render\n * task's scene-UBO cache is keyed on this object's identity.\n *\n * @param scene - The scene to light.\n * @param textures - The textures to light it with.\n * @returns `true` when the scene was lit by something else and now is not — the caller owes a\n * renderable rebuild; `false` when these textures were already installed and nothing was written.\n *\n * @example\n * ```ts\n * if (installSceneEnvironment(scene, asset.lite.textures)) {\n * await rebuildRenderables(scene);\n * }\n * ```\n *\n * @internal\n */\nexport function installSceneEnvironment(scene: SceneContext, textures: EnvironmentTextures): boolean {\n const slot = environmentSlotOf(scene);\n // As in `readSceneEnvironment`: an adapter-internal Lite mirror (coding standards §5.1).\n // oxlint-disable-next-line no-underscore-dangle\n if (slot._envTextures === textures) {\n return false;\n }\n // oxlint-disable-next-line no-underscore-dangle\n slot._envTextures = textures;\n return true;\n}\n\n/**\n * Loads a six-face cube-map skybox from a base URL.\n *\n * @param scene - The scene to give a background.\n * @param baseUrl - The URL prefix each face name is appended to.\n * @param extension - The face file extension, such as `\".jpg\"`.\n * @param size - The skybox cube's size, in metres.\n * @returns A promise that resolves when the faces are uploaded.\n *\n * @internal\n */\nexport function loadSceneSkybox(scene: SceneContext, baseUrl: string, extension: string, size?: number): Promise<void> {\n return loadSkybox(scene, baseUrl, extension, size);\n}\n\n/**\n * Rotates the environment around the world Y axis.\n *\n * @param scene - The scene to rotate the environment of.\n * @param degrees - The rotation, in degrees.\n *\n * @internal\n */\nexport function setSceneEnvironmentRotation(scene: SceneContext, degrees: number): void {\n setEnvironmentRotation(scene, degToRad(degrees));\n}\n\n/**\n * Blurs the visible skybox. Babylon Lite patches only the skybox shader; no material reads the value.\n *\n * @param scene - The scene to change.\n * @param blur - The blur amount, 0 to 1.\n *\n * @internal\n */\nexport function setSceneEnvironmentBlur(scene: SceneContext, blur: number): void {\n setEnvironmentBlur(scene, blur);\n}\n\n/**\n * Sets the colour the scene is cleared to each frame, so that it presents as the sRGB value given.\n *\n * @remarks\n * Lite stores the clear value into the colour target untouched. Tone mapping, image processing and\n * bloom's threshold never apply to it on the GPU (the renderer applies image processing before this\n * call, `src/render/image-processing-color.ts`), and Lite's own transmission and solid-skybox paths read it\n * as the colour that should come out (`lib/frame-graph/transmission.js` `executeRenderTaskLinear`,\n * `lib/material/pbr/background-solid-skybox.js`). The default surface format is not an sRGB one,\n * so the sRGB value is written unchanged. Only an `*-srgb` surface view (`rendering.srgb: true`)\n * encodes on write; there the value is decoded first, so that the GPU's encoding gives it back.\n * Every target ignifx renders the scene into uses the surface's format (`./render-path.ts`), so\n * the same rule holds on the offscreen path.\n *\n * @param scene - The scene to change.\n * @param r - The sRGB red component, 0 to 1.\n * @param g - The sRGB green component, 0 to 1.\n * @param b - The sRGB blue component, 0 to 1.\n * @param a - The alpha component; only meaningful with a premultiplied canvas alpha mode.\n *\n * @internal\n */\nexport function setSceneClearColor(scene: SceneContext, r: number, g: number, b: number, a: number): void {\n const clear = scene.clearColor;\n const decode = isSrgbEncodingFormat(scene.surface.format);\n clear.r = decode ? Color.srgbToLinear(r) : r;\n clear.g = decode ? Color.srgbToLinear(g) : g;\n clear.b = decode ? Color.srgbToLinear(b) : b;\n clear.a = a;\n}\n\n/**\n * Whether a colour target of this format encodes linear values to sRGB as they are stored.\n *\n * @param format - The target's format. Lite's null engine has none.\n * @returns `true` for an `*-srgb` format.\n *\n * @internal\n */\nexport function isSrgbEncodingFormat(format: string | undefined): boolean {\n return format?.endsWith(\"-srgb\") === true;\n}\n\n/**\n * Configures the scene's fog, or turns it off.\n *\n * @param scene - The scene to change.\n * @param mode - The fog falloff, or `\"none\"` to disable it.\n * @param r - The sRGB red component of the fog colour; Lite's fog block decodes it itself.\n * @param g - The sRGB green component.\n * @param b - The sRGB blue component.\n * @param density - The density, for the exponential modes.\n * @param start - Where linear fog begins, in metres.\n * @param end - Where linear fog reaches full strength, in metres.\n *\n * @internal\n */\nexport function setSceneFog(\n scene: SceneContext,\n mode: FogMode,\n r: number,\n g: number,\n b: number,\n density: number,\n start: number,\n end: number,\n): void {\n if (mode === \"none\" && scene.fog === null) {\n // A scene that never had fog pays nothing: no contributor, no fog block in any PBR pipeline.\n return;\n }\n setFog(scene, { mode: FOG_MODES[mode], density, start, end, color: [r, g, b] });\n}\n\n/**\n * Sets exposure, contrast, and the tone-mapping curve.\n *\n * @remarks\n * Asynchronous by nature: tone mapping is compiled into the PBR shaders, so changing it after\n * `registerScene` recompiles the scene's PBR pipelines. Exposure and contrast alone are uniform\n * values, but Lite routes them through the same call.\n *\n * @param scene - The scene to change.\n * @param exposure - The exposure multiplier.\n * @param contrast - The contrast multiplier.\n * @param toneMapping - The curve, or `\"none\"` to leave the colour untouched.\n * @returns A promise that resolves when any affected pipeline has been rebuilt.\n *\n * @internal\n */\nexport function setSceneImageProcessingOptions(\n scene: SceneContext,\n exposure: number,\n contrast: number,\n toneMapping: ToneMappingName,\n): Promise<void> {\n if (toneMapping === \"none\") {\n return setSceneImageProcessing(scene, { exposure, contrast, toneMappingEnabled: false });\n }\n if (toneMapping === \"agx\") {\n // Its own chunk: a project that never names AgX loads none of its WGSL (CONSTITUTION.md §2.5).\n return import(\"./agx-tone-mapping.js\").then(({ AgxToneMapping }) =>\n setSceneImageProcessing(scene, { exposure, contrast, toneMappingEnabled: true, toneMapping: AgxToneMapping }),\n );\n }\n return setSceneImageProcessing(scene, {\n exposure,\n contrast,\n toneMappingEnabled: true,\n toneMapping: toneMappingCurve(toneMapping),\n });\n}\n\n/**\n * Reads the image processing the scene's PBR shaders currently apply.\n *\n * @remarks\n * Read from Lite rather than from the `Environment` component, because Lite's `loadEnvironment`\n * also writes it (exposure 0.8, contrast 1.2, the standard curve) and the clear colour has to match\n * what the shaders actually do. A custom Lite curve set through `.lite` reads as `\"none\"`.\n *\n * @param scene - The scene.\n * @param out - Receives the exposure, contrast and curve.\n * @returns `out`.\n *\n * @internal\n */\nexport function readSceneImageProcessing(scene: SceneContext, out: ImageProcessingState): ImageProcessingState {\n const processing = scene.imageProcessing;\n out.exposure = processing.exposure;\n out.contrast = processing.contrast;\n out.curve = processing.toneMappingEnabled ? curveName(processing.toneMapping ?? StandardToneMapping) : \"none\";\n return out;\n}\n\n/**\n * Maps a Lite curve object back onto its ignifx name.\n *\n * @param curve - The Lite curve.\n * @returns The name, or `\"none\"` for a curve ignifx does not know.\n */\nfunction curveName(curve: ToneMapping): ToneMappingName {\n switch (curve.id) {\n case StandardToneMapping.id:\n return \"standard\";\n case AcesToneMapping.id:\n return \"aces\";\n case NeutralToneMapping.id:\n return \"neutral\";\n case AGX_TONE_MAPPING_ID:\n return \"agx\";\n default:\n return \"none\";\n }\n}\n\n/**\n * Maps an ignifx tone-mapping name onto the Lite curve object.\n *\n * @param name - The curve name; `\"none\"` and the lazily loaded `\"agx\"` are handled by the caller.\n * @returns The Lite curve.\n */\nfunction toneMappingCurve(name: Exclude<ToneMappingName, \"none\" | \"agx\">): ToneMapping {\n switch (name) {\n case \"standard\":\n return StandardToneMapping;\n case \"aces\":\n return AcesToneMapping;\n case \"neutral\":\n return NeutralToneMapping;\n default:\n return assertNever(name, \"tone mapping\");\n }\n}\n"],"mappings":";;;;;;;;;;AAiHA,MAAa,YAAY;;CAEvB,MAAM;;CAEN,KAAK;;CAEL,MAAM;;CAEN,QAAQ;AACV;;;;;;;AAeA,MAAa,qBAAqB;CAAC;CAAQ;CAAY;CAAQ;CAAW;AAAK;;;;;AAM/E,M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,KAAK,QACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,SACE,OAAO,YAAY,MAAM,cAAc;CAC3C;AACF"}
1
+ {"version":3,"file":"environment-Bf4aphSb.js","names":[],"sources":["../src/lite/gpu/environment.ts"],"sourcesContent":["import {\n AcesToneMapping,\n loadEnvironment,\n loadSkybox,\n NeutralToneMapping,\n setEnvironmentBlur,\n setEnvironmentRotation,\n setFog,\n setSceneImageProcessing,\n StandardToneMapping,\n} from \"@babylonjs/lite\";\nimport { assertNever } from \"../../errors/ignifx-error.js\";\nimport { Color } from \"../../math/color.js\";\nimport { degToRad } from \"../../math/math-utils.js\";\nimport type { EnvironmentTextures, SceneContext, ToneMapping } from \"@babylonjs/lite\";\n\n/**\n * Environment half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §2.5): image\n * based lighting, the skybox, fog, image processing, and the clear colour.\n *\n * Everything here is `@internal`. Loading uploads cube maps, so the module is GPU-only.\n *\n * ## The BRDF LUT is mandatory (verified against `@babylonjs/lite@1.27.0`)\n *\n * `loadEnvironment(scene, url, options)` (`index.d.ts` 6779) takes a **required** `brdfUrl`: Lite\n * decodes the split-sum BRDF lookup table from a pre-baked RGBD PNG rather than computing it, \"for\n * pixel-perfect parity\" with Babylon.js (`lib/_chunks/env-helpers-*.js`, `loadBrdfImage`, which\n * `fetch`es the URL and decodes it with `createImageBitmap`). ignifx ships that PNG as\n * `tests/fixtures/assets/brdf-lut.png`, decoded from Babylon.js's own\n * `_environmentBRDFBase64Texture` (`packages/dev/core/src/Misc/brdfTextureTools.ts`, Apache-2.0).\n * It is 256×256 RGBA8 and 23 KB.\n *\n * ## Fog\n *\n * `SceneContext.fog` is `FogConfig | null` (`index.d.ts` 5350) with a numeric `mode`; Lite exports\n * no named constants for it, so {@link FOG_MODES} maps ignifx's names onto the numbers.\n *\n * **Fog has to be installed with `setFog`, not by assigning the field.** `scene.fog` is what the PBR\n * group builder reads to decide whether a material's program gets the fog block at all\n * (`lib/material/pbr/pbr-renderable.js` 140-159, `PBR_HAS_FOG`), but the block it compiles reads\n * `scene.vFogInfos.x` out of the scene uniform buffer — and the only writer of those slots is\n * `writeFogUbo`, which nothing registers except `setFog`\n * (`lib/scene/scene-ubo-extras.js`: `setFog` is `scene.fog = config` **plus**\n * `_registerSceneUboContributor(scene, writeFogUbo)`, and `_writePassSceneUBO` runs\n * `scene._sceneUboContributors` and nothing else, `lib/frame-graph/render-task.js` 372-379).\n * Lite says as much in `index.d.ts` 10471: \"importing `setFog` is what pulls the fog UBO writer into\n * the bundle\". Assigning `scene.fog` alone therefore compiles the fog block into every PBR pipeline\n * and leaves `vFogInfos` zeroed, so `vFogInfos.x > 0.0` is never true and the scene renders with no\n * fog at all — the cost with none of the effect.\n *\n * A **fresh** config object goes in on every change, because a render task caches its scene UBO on\n * the identity of `scene.fog` (`s[1] === fog`, `lib/frame-graph/render-task.js` 355-371): mutating\n * the installed object in place leaves the cache key equal and the new density or colour never\n * reaches the GPU. Turning fog off writes mode `0`, which is what the already-compiled fog block\n * reads as \"no fog\"; dropping the field back to `null` would only stop the writer and leave the last\n * fog standing. A scene that never had fog keeps its `null` and pays nothing.\n *\n * ## Image processing\n *\n * `setSceneImageProcessing` is **async** (`index.d.ts` 10917) because tone mapping is baked into\n * the PBR shaders at `registerScene` time; changing it recompiles the affected pipelines\n * (`rebuildScenePbrPipelines`). Setting exposure or contrast alone still goes through the same\n * call. Note that `loadEnvironment` **overwrites** all three (`toneMappingEnabled = true`,\n * `exposure = 0.8`, `contrast = 1.2`) as a side effect of installing an environment, which is why\n * the `Environment` component re-applies its own image processing after every install.\n *\n * ## Swapping the installed environment: `scene._envTextures`\n *\n * Lite 1.27.0 declares **no** public way to replace, clear, or read back a registered scene's\n * environment. `index.d.ts` has no `scene.environmentTexture`, no `unloadEnvironment`, and no\n * setter of any kind; `loadEnvironment` is the only installer and it fetches, decodes, and uploads\n * a fresh cube map every call. What it actually installs is one field —\n * `scene._envTextures = textures` (`lib/_chunks/env-helpers-CRI1i-A3.js` 24, and the same line in\n * `lib/loader-hdr/load-hdr.js` 23, `lib/loader-env/load-dds-env.js` 177 and\n * `lib/loader-gltf/gltf-ext-lights-image-based.js` 65) — and every consumer reads that field:\n *\n * - the PBR group builder, which bakes the cube view and sampler into each material's bind group\n * (`lib/material/pbr/pbr-material.js` 12 → `lib/material/pbr/pbr-renderable.js`);\n * - the scene-uniform packer, for `lodGenerationScale` (`lib/frame-graph/scene-uniforms-pack.js` 21);\n * - the env UBO contributor, for the diffuse spherical harmonics (`lib/scene/scene-ubo-extras.js` 24);\n * - the blur contributor, for `lodGenerationOffset` (`lib/scene/set-environment-blur.js` 8);\n * - the render task's scene-UBO cache key, which is keyed on the **object identity** of the field\n * (`lib/frame-graph/render-task.js` 358), so a new object re-uploads the harmonics by itself.\n *\n * Lite's own device-lost recovery replaces the field exactly this way\n * (`lib/loader-env/environment-recovery.js` 16 and 38), so {@link installSceneEnvironment} writes it\n * too. Bind groups are the one consumer that does *not* re-read it: they hold the `GPUTextureView`,\n * so a swap only reaches the specular reflection once the material groups have been rebuilt, which\n * `rebuildSceneRenderables` does (`lib/scene/scene-rebuild.js`, `rebuildEachGroup`). The\n * `Environment` component therefore reports an install as a topology change and lets the render-sync\n * system fire its one coalesced rebuild. This is the only place in ignifx that touches a Lite field\n * `index.d.ts` does not declare, which is what the adapter boundary exists for\n * (`CONSTITUTION.md` §3.4, ADR-0002); it is pinned by\n * `packages/core/test/lite/render/environment.browser.test.ts`, which fails loudly if the field is\n * renamed.\n */\n\n/**\n * The GPU-resident image-based-lighting textures `loadEnvironment` resolves to, re-exported under an\n * ignifx name (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteEnvironmentTextures = EnvironmentTextures;\n\n/**\n * ignifx fog mode names mapped to the numbers `FogConfig.mode` uses.\n *\n * @internal\n */\nexport const FOG_MODES = {\n /** No fog. */\n none: 0,\n /** Exponential fog. */\n exp: 1,\n /** Squared-exponential fog. */\n exp2: 2,\n /** Linear fog between `start` and `end`. */\n linear: 3,\n} as const;\n\n/**\n * The union of the fog mode names.\n *\n * @internal\n */\nexport type FogMode = keyof typeof FOG_MODES;\n\n/**\n * The tone-mapping curves `docs/architecture/07-rendering.md` §2.5 exposes. `\"agx\"` is ignifx's\n * own Lite curve (`./agx-tone-mapping.ts`); the others are Lite's built-ins.\n *\n * @public\n */\nexport const TONE_MAPPING_NAMES = [\"none\", \"standard\", \"aces\", \"neutral\", \"agx\"] as const;\n\n/**\n * The `id` of the AgX curve, repeated from `./agx-tone-mapping.ts` so recognising it does not load\n * that chunk.\n */\nconst AGX_TONE_MAPPING_ID = \"ignifx-agx\";\n\n/**\n * The union of the tone-mapping curve names.\n *\n * @internal\n */\nexport type ToneMappingName = (typeof TONE_MAPPING_NAMES)[number];\n\n/**\n * The image processing Lite's PBR shaders apply: exposure, contrast and the tone-mapping curve.\n *\n * @internal\n */\nexport interface ImageProcessingState {\n /** The exposure multiplier. */\n exposure: number;\n /** The contrast multiplier. */\n contrast: number;\n /** The tone-mapping curve, or `\"none\"`. */\n curve: ToneMappingName;\n}\n\n/**\n * How an ignifx `Environment` component configures image based lighting.\n *\n * @internal\n */\nexport interface EnvironmentLoadOptions {\n /** The `.env` file holding the prefiltered specular cube map and its spherical harmonics. */\n readonly url: string;\n /** The RGBD PNG BRDF lookup table. Required by Lite. */\n readonly brdfUrl: string;\n /** A `.dds` or `.env` skybox. Omit for a flat background. */\n readonly skyboxUrl?: string;\n /** The skybox cube's size, in metres. Lite defaults to 20. */\n readonly skyboxSize?: number;\n /** Skip the skybox entirely. */\n readonly skipSkybox?: boolean;\n /** Skip the reflective ground plane Lite would otherwise add. */\n readonly skipGround?: boolean;\n /** A texture for that ground plane. */\n readonly groundTextureUrl?: string;\n}\n\n/**\n * Loads an `.env` environment and installs it on a scene.\n *\n * @param scene - The scene to light.\n * @param options - The environment, BRDF, and skybox URLs.\n * @returns The GPU-resident environment textures, for materials that need them explicitly.\n *\n * @example\n * ```ts\n * await loadSceneEnvironment(scene, {\n * url: \"environments/studio.env\",\n * brdfUrl: \"environments/brdf-lut.png\",\n * });\n * ```\n *\n * @internal\n */\nexport function loadSceneEnvironment(\n scene: SceneContext,\n options: EnvironmentLoadOptions,\n): Promise<EnvironmentTextures> {\n const liteOptions: {\n brdfUrl: string;\n skyboxUrl?: string;\n skyboxSize?: number;\n skipSkybox?: boolean;\n skipGround?: boolean;\n groundTextureUrl?: string;\n } = { brdfUrl: options.brdfUrl };\n if (options.skyboxUrl !== undefined) {\n liteOptions.skyboxUrl = options.skyboxUrl;\n }\n if (options.skyboxSize !== undefined) {\n liteOptions.skyboxSize = options.skyboxSize;\n }\n if (options.skipSkybox !== undefined) {\n liteOptions.skipSkybox = options.skipSkybox;\n }\n if (options.skipGround !== undefined) {\n liteOptions.skipGround = options.skipGround;\n }\n if (options.groundTextureUrl !== undefined) {\n liteOptions.groundTextureUrl = options.groundTextureUrl;\n }\n return loadEnvironment(scene, options.url, liteOptions);\n}\n\n/**\n * The scene fields Babylon Lite 1.27.0 writes for image-based lighting but does not declare in\n * `index.d.ts`. Adapter-internal Lite mirror (coding standards §5.1); see the module header for the\n * `lib/` lines that prove each one.\n */\ninterface SceneEnvironmentSlot {\n /** What `loadEnvironment` installed, or `undefined` on a scene that has never had one. */\n _envTextures?: EnvironmentTextures | undefined;\n}\n\n/**\n * Views a scene through its undeclared environment slot.\n *\n * @param scene - The scene.\n * @returns The same object, typed so the slot is reachable.\n */\nfunction environmentSlotOf(scene: SceneContext): SceneEnvironmentSlot {\n // Boundary assertion (coding standards §5.2): `SceneContext` is a plain object literal Lite\n // creates in `lib/scene/scene-core.js`, and `_envTextures` is one of its own fields — it is\n // absent from `index.d.ts` because it is not part of Lite's declared surface, not because it is\n // a different object. See the module header for every `lib/` line that reads or writes it.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return scene as SceneContext & SceneEnvironmentSlot;\n}\n\n/**\n * Reports which environment textures a scene is currently lit by.\n *\n * @param scene - The scene to inspect.\n * @returns The installed textures, or `null` when no environment has ever been installed.\n *\n * @internal\n */\nexport function readSceneEnvironment(scene: SceneContext): EnvironmentTextures | null {\n // The underscore is Lite's, not ignifx's: coding standards §5.1 reserves `_field` for exactly\n // this, an adapter-internal mirror of a Lite field, and the module header proves the name.\n // oxlint-disable-next-line no-underscore-dangle\n return environmentSlotOf(scene)._envTextures ?? null;\n}\n\n/**\n * Points a scene at an already-loaded set of environment textures, without loading anything.\n *\n * @remarks\n * This is how an `Environment` component swaps environments at runtime: the textures belong to the\n * `EnvironmentAsset` that loaded them and stay alive as long as its handle is retained, so\n * switching between two loaded assets uploads nothing and frees nothing.\n *\n * The specular reflection follows only after the scene's material groups are rebuilt\n * (`rebuildRenderables` in `../shadow.ts`): a PBR bind group holds the cube map's `GPUTextureView`,\n * not the slot. The diffuse harmonics and the LOD scale follow immediately, because the render\n * task's scene-UBO cache is keyed on this object's identity.\n *\n * @param scene - The scene to light.\n * @param textures - The textures to light it with.\n * @returns `true` when the scene was lit by something else and now is not — the caller owes a\n * renderable rebuild; `false` when these textures were already installed and nothing was written.\n *\n * @example\n * ```ts\n * if (installSceneEnvironment(scene, asset.lite.textures)) {\n * await rebuildRenderables(scene);\n * }\n * ```\n *\n * @internal\n */\nexport function installSceneEnvironment(scene: SceneContext, textures: EnvironmentTextures): boolean {\n const slot = environmentSlotOf(scene);\n // As in `readSceneEnvironment`: an adapter-internal Lite mirror (coding standards §5.1).\n // oxlint-disable-next-line no-underscore-dangle\n if (slot._envTextures === textures) {\n return false;\n }\n // oxlint-disable-next-line no-underscore-dangle\n slot._envTextures = textures;\n return true;\n}\n\n/**\n * Loads a six-face cube-map skybox from a base URL.\n *\n * @param scene - The scene to give a background.\n * @param baseUrl - The URL prefix each face name is appended to.\n * @param extension - The face file extension, such as `\".jpg\"`.\n * @param size - The skybox cube's size, in metres.\n * @returns A promise that resolves when the faces are uploaded.\n *\n * @internal\n */\nexport function loadSceneSkybox(scene: SceneContext, baseUrl: string, extension: string, size?: number): Promise<void> {\n return loadSkybox(scene, baseUrl, extension, size);\n}\n\n/**\n * Rotates the environment around the world Y axis.\n *\n * @param scene - The scene to rotate the environment of.\n * @param degrees - The rotation, in degrees.\n *\n * @internal\n */\nexport function setSceneEnvironmentRotation(scene: SceneContext, degrees: number): void {\n setEnvironmentRotation(scene, degToRad(degrees));\n}\n\n/**\n * Blurs the visible skybox. Babylon Lite patches only the skybox shader; no material reads the value.\n *\n * @param scene - The scene to change.\n * @param blur - The blur amount, 0 to 1.\n *\n * @internal\n */\nexport function setSceneEnvironmentBlur(scene: SceneContext, blur: number): void {\n setEnvironmentBlur(scene, blur);\n}\n\n/**\n * Sets the colour the scene is cleared to each frame, so that it presents as the sRGB value given.\n *\n * @remarks\n * Lite stores the clear value into the colour target untouched. Tone mapping, image processing and\n * bloom's threshold never apply to it on the GPU (the renderer applies image processing before this\n * call, `src/render/image-processing-color.ts`), and Lite's own transmission and solid-skybox paths read it\n * as the colour that should come out (`lib/frame-graph/transmission.js` `executeRenderTaskLinear`,\n * `lib/material/pbr/background-solid-skybox.js`). The default surface format is not an sRGB one,\n * so the sRGB value is written unchanged. Only an `*-srgb` surface view (`rendering.srgb: true`)\n * encodes on write; there the value is decoded first, so that the GPU's encoding gives it back.\n * Every target ignifx renders the scene into uses the surface's format (`./render-path.ts`), so\n * the same rule holds on the offscreen path.\n *\n * @param scene - The scene to change.\n * @param r - The sRGB red component, 0 to 1.\n * @param g - The sRGB green component, 0 to 1.\n * @param b - The sRGB blue component, 0 to 1.\n * @param a - The alpha component; only meaningful with a premultiplied canvas alpha mode.\n *\n * @internal\n */\nexport function setSceneClearColor(scene: SceneContext, r: number, g: number, b: number, a: number): void {\n const clear = scene.clearColor;\n const decode = isSrgbEncodingFormat(scene.surface.format);\n clear.r = decode ? Color.srgbToLinear(r) : r;\n clear.g = decode ? Color.srgbToLinear(g) : g;\n clear.b = decode ? Color.srgbToLinear(b) : b;\n clear.a = a;\n}\n\n/**\n * Whether a colour target of this format encodes linear values to sRGB as they are stored.\n *\n * @param format - The target's format. Lite's null engine has none.\n * @returns `true` for an `*-srgb` format.\n *\n * @internal\n */\nexport function isSrgbEncodingFormat(format: string | undefined): boolean {\n return format?.endsWith(\"-srgb\") === true;\n}\n\n/**\n * Configures the scene's fog, or turns it off.\n *\n * @param scene - The scene to change.\n * @param mode - The fog falloff, or `\"none\"` to disable it.\n * @param r - The sRGB red component of the fog colour; Lite's fog block decodes it itself.\n * @param g - The sRGB green component.\n * @param b - The sRGB blue component.\n * @param density - The density, for the exponential modes.\n * @param start - Where linear fog begins, in metres.\n * @param end - Where linear fog reaches full strength, in metres.\n *\n * @internal\n */\nexport function setSceneFog(\n scene: SceneContext,\n mode: FogMode,\n r: number,\n g: number,\n b: number,\n density: number,\n start: number,\n end: number,\n): void {\n if (mode === \"none\" && scene.fog === null) {\n // A scene that never had fog pays nothing: no contributor, no fog block in any PBR pipeline.\n return;\n }\n setFog(scene, { mode: FOG_MODES[mode], density, start, end, color: [r, g, b] });\n}\n\n/**\n * Sets exposure, contrast, and the tone-mapping curve.\n *\n * @remarks\n * Asynchronous by nature: tone mapping is compiled into the PBR shaders, so changing it after\n * `registerScene` recompiles the scene's PBR pipelines. Exposure and contrast alone are uniform\n * values, but Lite routes them through the same call.\n *\n * @param scene - The scene to change.\n * @param exposure - The exposure multiplier.\n * @param contrast - The contrast multiplier.\n * @param toneMapping - The curve, or `\"none\"` to leave the colour untouched.\n * @returns A promise that resolves when any affected pipeline has been rebuilt.\n *\n * @internal\n */\nexport function setSceneImageProcessingOptions(\n scene: SceneContext,\n exposure: number,\n contrast: number,\n toneMapping: ToneMappingName,\n): Promise<void> {\n if (toneMapping === \"none\") {\n return setSceneImageProcessing(scene, { exposure, contrast, toneMappingEnabled: false });\n }\n if (toneMapping === \"agx\") {\n // Its own chunk: a project that never names AgX loads none of its WGSL (CONSTITUTION.md §2.5).\n return import(\"./agx-tone-mapping.js\").then(({ AgxToneMapping }) =>\n setSceneImageProcessing(scene, { exposure, contrast, toneMappingEnabled: true, toneMapping: AgxToneMapping }),\n );\n }\n return setSceneImageProcessing(scene, {\n exposure,\n contrast,\n toneMappingEnabled: true,\n toneMapping: toneMappingCurve(toneMapping),\n });\n}\n\n/**\n * Reads the image processing the scene's PBR shaders currently apply.\n *\n * @remarks\n * Read from Lite rather than from the `Environment` component, because Lite's `loadEnvironment`\n * also writes it (exposure 0.8, contrast 1.2, the standard curve) and the clear colour has to match\n * what the shaders actually do. A custom Lite curve set through `.lite` reads as `\"none\"`.\n *\n * @param scene - The scene.\n * @param out - Receives the exposure, contrast and curve.\n * @returns `out`.\n *\n * @internal\n */\nexport function readSceneImageProcessing(scene: SceneContext, out: ImageProcessingState): ImageProcessingState {\n const processing = scene.imageProcessing;\n out.exposure = processing.exposure;\n out.contrast = processing.contrast;\n out.curve = processing.toneMappingEnabled ? curveName(processing.toneMapping ?? StandardToneMapping) : \"none\";\n return out;\n}\n\n/**\n * Maps a Lite curve object back onto its ignifx name.\n *\n * @param curve - The Lite curve.\n * @returns The name, or `\"none\"` for a curve ignifx does not know.\n */\nfunction curveName(curve: ToneMapping): ToneMappingName {\n switch (curve.id) {\n case StandardToneMapping.id:\n return \"standard\";\n case AcesToneMapping.id:\n return \"aces\";\n case NeutralToneMapping.id:\n return \"neutral\";\n case AGX_TONE_MAPPING_ID:\n return \"agx\";\n default:\n return \"none\";\n }\n}\n\n/**\n * Maps an ignifx tone-mapping name onto the Lite curve object.\n *\n * @param name - The curve name; `\"none\"` and the lazily loaded `\"agx\"` are handled by the caller.\n * @returns The Lite curve.\n */\nfunction toneMappingCurve(name: Exclude<ToneMappingName, \"none\" | \"agx\">): ToneMapping {\n switch (name) {\n case \"standard\":\n return StandardToneMapping;\n case \"aces\":\n return AcesToneMapping;\n case \"neutral\":\n return NeutralToneMapping;\n default:\n return assertNever(name, \"tone mapping\");\n }\n}\n"],"mappings":";;;;;;;;;;AAiHA,MAAa,Y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AmB,IACtB,OAAO;EACT,KAAK,qBACH,OAAO;EACT,SACE,OAAO;CACX;AACF;;;;;;;AAQA,SAAS,iBAAiB,MAA6D;CACrF,QAAQ,MAAR;EACE,KAAK,YACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,SACE,OAAO,YAAY,MAAM,cAAc;CAC3C;AACF"}
@@ -1,4 +1,4 @@
1
- import { o as rebuildMaterialPipelines } from "./material-CGk5mAah.js";
1
+ import { o as rebuildMaterialPipelines } from "./material-myMbl9mW.js";
2
2
  import { SCENE_INPUT_TASK_NAMES, frameGraphTasks } from "./scene-inputs-BxGOsnIZ.js";
3
3
  import { addComputeDispatch, addTaskAfter, buildFrameGraphTask, computeStorageTextureBinding, computeTextureBinding, computeUniformBufferBinding, createComputeBindingSet, createComputeDispatch, createComputeShader, createComputeStorageTexture2D, createComputeTask, createComputeTextureResource, createUniformBuffer, disposeComputeBindingSet, disposeComputeShader, disposeComputeStorageTexture2D, disposeUniformBuffer, getEffectiveAspectRatio, getFrameGraph, getPbrUnlit, getProjectionMatrix, getViewMatrix, invertMat4, isPbrMaterial, removeComputeDispatch, updateUniformBuffer } from "@babylonjs/lite";
4
4
  //#region src/lite/gpu/gtao.ts
@@ -627,4 +627,4 @@ function rebuildPatchedMaterials(scene, plugin) {
627
627
  //#endregion
628
628
  export { GTAO_PLUGIN_NAME, GTAO_TASK_NAMES, createAmbientOcclusion, createAmbientOcclusionPlugin, gtaoDenoiseWgsl, gtaoPluginWgsl, gtaoShape, gtaoWgsl };
629
629
 
630
- //# sourceMappingURL=gtao-_nr0b6-E.js.map
630
+ //# sourceMappingURL=gtao-Bpu5-0Ne.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"gtao-_nr0b6-E.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,YAAY,SACf;EAAE,OAAO;EAAG,SAAS;EAAG,QAAQ;EAAG,OAAO;CAAE,IAC5C;EAAE,OAAO;EAAG,SAAS;EAAG,QAAQ;EAAG,OAAO;CAAE;AAClD;;;;;;;;;AAyCA,SAAgB,SAAS,OAA0B;CACj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ACA,kBAAkB;EAElB,SAAS,CAAC;EACV,SAAe,CAEf;EACA,UAAkB;GAChB,IAAI;GACJ,OAAO;EACT;EACA,UAAgB,CAEhB;CAEQ;AACZ;;;;;;;;;;;;AAaA,SAAS,aAAa,OAAqB,QAAwB,mBAAkC;CACnG,MAAM,SAAS,MAAM;CACrB,KAAK,IAAI,QAAQ,GAAG,QAAQ,OAAO,QAAQ,SAAS,GAAG;EACrD,MAAM,WAAW,OAAO,MAAM,EAAE;EAGhC,IAAI,aAAa,KAAA,KAAa,aAAa,QAAQ,CAAC,cAAc,QAAQ,GACxE;EAEF,IAAI,YAAY,QAAQ,MAAM,KAAA,GAC5B;EAEF,MAAM,UAAU,SAAS,WAAW,CAAC;EACrC,IAAI,QAAQ,SAAS,MAAM,GACzB;EAEF,SAAS,UAAU,CAAC,GAAG,SAAS,MAAM;EACtC,IAAI,mBACF,yBAAyB,OAAO,QAAQ;CAE5C;AACF;;;;;;;AAQA,SAAS,wBAAwB,OAAqB,QAA8B;CAClF,MAAM,uBAAO,IAAI,IAAc;CAC/B,MAAM,SAAS,MAAM;CACrB,KAAK,IAAI,QAAQ,GAAG,QAAQ,OAAO,QAAQ,SAAS,GAAG;EACrD,MAAM,WAAW,OAAO,MAAM,EAAE;EAEhC,IAAI,aAAa,KAAA,KAAa,aAAa,QAAQ,KAAK,IAAI,QAAQ,KAAK,CAAC,cAAc,QAAQ,GAC9F;EAEF,KAAK,IAAI,QAAQ;EACjB,IAAI,SAAS,SAAS,SAAS,MAAM,MAAM,MACzC,yBAAyB,OAAO,QAAQ;CAE5C;AACF"}
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,YAAY,SACf;EAAE,OAAO;EAAG,SAAS;EAAG,QAAQ;EAAG,OAAO;CAAE,IAC5C;EAAE,OAAO;EAAG,SAAS;EAAG,QAAQ;EAAG,OAAO;CAAE;AAClD;;;;;;;;;AAyCA,SAAgB,SAAS,OAA0B;CACjD,OAAO;;;;;;;;;;;;;sBAaa,OAAO,MAAM,MAAM,EAAE;qBACtB,OAAO,MA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;GACJ,OAAO;EACT;EACA,UAAgB,CAEhB;CAEQ;AACZ;;;;;;;;;;;;AAaA,SAAS,aAAa,OAAqB,QAAwB,mBAAkC;CACnG,MAAM,SAAS,MAAM;CACrB,KAAK,IAAI,QAAQ,GAAG,QAAQ,OAAO,QAAQ,SAAS,GAAG;EACrD,MAAM,WAAW,OAAO,MAAM,EAAE;EAGhC,IAAI,aAAa,KAAA,KAAa,aAAa,QAAQ,CAAC,cAAc,QAAQ,GACxE;EAEF,IAAI,YAAY,QAAQ,MAAM,KAAA,GAC5B;EAEF,MAAM,UAAU,SAAS,WAAW,CAAC;EACrC,IAAI,QAAQ,SAAS,MAAM,GACzB;EAEF,SAAS,UAAU,CAAC,GAAG,SAAS,MAAM;EACtC,IAAI,mBACF,yBAAyB,OAAO,QAAQ;CAE5C;AACF;;;;;;;AAQA,SAAS,wBAAwB,OAAqB,QAA8B;CAClF,MAAM,uBAAO,IAAI,IAAc;CAC/B,MAAM,SAAS,MAAM;CACrB,KAAK,IAAI,QAAQ,GAAG,QAAQ,OAAO,QAAQ,SAAS,GAAG;EACrD,MAAM,WAAW,OAAO,MAAM,EAAE;EAEhC,IAAI,aAAa,KAAA,KAAa,aAAa,QAAQ,KAAK,IAAI,QAAQ,KAAK,CAAC,cAAc,QAAQ,GAC9F;EAEF,KAAK,IAAI,QAAQ;EACjB,IAAI,SAAS,SAAS,SAAS,MAAM,MAAM,MACzC,yBAAyB,OAAO,QAAQ;CAE5C;AACF"}
@@ -1,4 +1,4 @@
1
- import { o as rebuildMaterialPipelines } from "./material-CGk5mAah.js";
1
+ import { o as rebuildMaterialPipelines } from "./material-myMbl9mW.js";
2
2
  import { i as markHdrScene, t as DEPTH_STENCIL_FORMAT } from "./render-path-D11i_7X8.js";
3
3
  import { AGX_CALL_WGSL, AGX_HELPERS_WGSL } from "./agx-tone-mapping-Cgt844j6.js";
4
4
  import { AcesToneMapping, NeutralToneMapping, StandardToneMapping, addTask, addTaskBefore, buildFrameGraphTask, createEffectRenderTask, createEffectWrapper, createRenderTarget, createRenderTask, createSurfaceRenderTargetTexture, enableMaterialPlugins, getFrameGraph, getPbrUnlit, isPbrMaterial, isStandardMaterial, onRenderTargetTextureResize, reconcileMaterialPlugins, setEffectTexture, setEffectUniforms, setEnvironmentRotation, setFog } from "@babylonjs/lite";
@@ -523,4 +523,4 @@ function attachLinearOutput(scene, shared, isSceneRegistered) {
523
523
  //#endregion
524
524
  export { installHdrRenderPath };
525
525
 
526
- //# sourceMappingURL=hdr-output-Dbv0lhFl.js.map
526
+ //# sourceMappingURL=hdr-output-DBQwMphy.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hdr-output-Dbv0lhFl.js","names":[],"sources":["../src/lite/gpu/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":";;;;;;;;;;;;;;;;;;;;;;;;;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../src/lite/gpu/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,MA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AQ,SAAS,GAAG;EACrD,MAAM,WAAW,OAAO,MAAM,EAAE;EAIhC,IAAI,aAAa,KAAA,KAAa,aAAa,MACzC;EAEF,IAAI;EACJ,IAAI,cAAc,QAAQ,GACxB,SAAS,YAAY,QAAQ,MAAM,KAAA,IAAY,OAAO,MAAM,OAAO;OAC9D,IAAI,mBAAmB,QAAQ,GACpC,SAAS,OAAO;OAEhB;EAEF,MAAM,UAAU,SAAS,WAAW,CAAC;EAErC,IAAI,QAA+B;EACnC,IAAI,WAAW,OAAO,KACpB,QAAQ,OAAO;OACV,IAAI,WAAW,OAAO,OAC3B,QAAQ,OAAO;EAEjB,MAAM,WAAW,UAAU,QAAQ,QAAQ,SAAS,KAAK;EACzD,IAAI,QAAQ,SAAS,MAAM,KAAK,CAAC,UAC/B;EAEF,MAAM,OAAO,WAAW,QAAQ,QAAQ,UAAU,UAAU,KAAK,IAAI;EACrE,SAAS,UAAU,KAAK,SAAS,MAAM,IAAI,OAAO,CAAC,GAAG,MAAM,MAAM;EAClE,IAAI,WAAW,OAAO,UAAU;GAG9B,yBAA8B,OAAO,QAAQ;GAC7C;EACF;EACA,IAAI,mBACF,yBAAyB,OAAO,QAAQ;CAE5C;AACF"}
@@ -281,6 +281,8 @@ const CoreErrorCode = {
281
281
  invalidFrameWait: "IGX-0733",
282
282
  /** `bakeLightProbes` was given a grid, ray count or distance it cannot bake. */
283
283
  invalidLightProbeBake: "IGX-0734",
284
+ /** A `MeshRenderer`'s lightmap is not drawn as declared: the entity is not static, the material is not PBR, or the placement is not the identity. */
285
+ lightmapNotApplied: "IGX-0735",
284
286
  /** The host exposes no Web Crypto implementation. */
285
287
  cryptoUnavailable: "IGX-1420",
286
288
  /** A storage namespace name is not a legal namespace segment. */
@@ -408,6 +410,7 @@ const CORE_ERROR_MESSAGES = {
408
410
  "IGX-0732": "renderToTexture() needs a camera attached to an entity.",
409
411
  "IGX-0733": "{member}: maxWaitMs must be a finite number of milliseconds, 0 or more.",
410
412
  "IGX-0734": "bakeLightProbes(): {problem}.",
413
+ "IGX-0735": "{entity}'s MeshRenderer lightmap: {problem}.",
411
414
  "IGX-1420": "This host does not expose Web Crypto.",
412
415
  "IGX-1421": "{namespace} is not a valid storage namespace.",
413
416
  "IGX-1422": "That storage key is empty, too long, or contains a control character.",
@@ -592,4 +595,4 @@ function assertNever(value, what) {
592
595
  //#endregion
593
596
  export { CORE_ERROR_MESSAGES as a, THIRD_PARTY_ERROR_PREFIX as c, isIgnifxError as i, isValidErrorCode as l, assertNever as n, CoreErrorCode as o, formatErrorMessage as r, ErrorRange as s, IgnifxError as t };
594
597
 
595
- //# sourceMappingURL=ignifx-error-B8ByiSfJ.js.map
598
+ //# sourceMappingURL=ignifx-error-DwIZKxA2.js.map