@ignifx/core 0.19.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.
- package/dist/{gtao-_nr0b6-E.js → gtao-Bpu5-0Ne.js} +2 -2
- package/dist/{gtao-_nr0b6-E.js.map → gtao-Bpu5-0Ne.js.map} +1 -1
- package/dist/{hdr-output-Dbv0lhFl.js → hdr-output-DBQwMphy.js} +2 -2
- package/dist/{hdr-output-Dbv0lhFl.js.map → hdr-output-DBQwMphy.js.map} +1 -1
- package/dist/index.d.ts +181 -21
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1616 -174
- package/dist/index.js.map +1 -1
- package/dist/{instanced-mesh-instance-BMhREEfx.js → instanced-mesh-instance-B-fXKSrY.js} +2 -2
- package/dist/{instanced-mesh-instance-BMhREEfx.js.map → instanced-mesh-instance-B-fXKSrY.js.map} +1 -1
- package/dist/{light-probes-DyLapYX9.js → light-probes-DDojYajw.js} +2 -2
- package/dist/{light-probes-DyLapYX9.js.map → light-probes-DDojYajw.js.map} +1 -1
- package/dist/lightmaps-BUUIIkt9.js +230 -0
- package/dist/lightmaps-BUUIIkt9.js.map +1 -0
- package/dist/{material-CGk5mAah.js → material-myMbl9mW.js} +37 -2
- package/dist/{material-CGk5mAah.js.map → material-myMbl9mW.js.map} +1 -1
- package/dist/{post-effect-CaiqDlhW.js → post-effect-Cu3Enpz7.js} +2 -2
- package/dist/{post-effect-CaiqDlhW.js.map → post-effect-Cu3Enpz7.js.map} +1 -1
- package/dist/{post-effect-compiler-jSvOVe0U.js → post-effect-compiler-cCq9lcHt.js} +2 -2
- package/dist/{post-effect-compiler-jSvOVe0U.js.map → post-effect-compiler-cCq9lcHt.js.map} +1 -1
- package/dist/{prefab-overrides-DRP2DcnC.js → prefab-overrides-C2GsgOQc.js} +24 -7
- package/dist/prefab-overrides-C2GsgOQc.js.map +1 -0
- package/dist/{prefab-overrides-CS8_cG66.d.ts → prefab-overrides-htDc_5Po.d.ts} +53 -12
- package/dist/prefab-overrides-htDc_5Po.d.ts.map +1 -0
- package/dist/prefab.d.ts +1 -1
- package/dist/prefab.js +1 -1
- package/dist/{reflection-probe-AS8d4uKv.js → reflection-probe-QkD1Fo_d.js} +79 -3
- package/dist/{reflection-probe-AS8d4uKv.js.map → reflection-probe-QkD1Fo_d.js.map} +1 -1
- package/dist/{reflection-probes-CUZcOjNW.js → reflection-probes-CAzSuqf8.js} +298 -21
- package/dist/reflection-probes-CAzSuqf8.js.map +1 -0
- package/dist/{shader-material-CuwK9tWC.js → shader-material-TM4f8eKA.js} +2 -2
- package/dist/{shader-material-CuwK9tWC.js.map → shader-material-TM4f8eKA.js.map} +1 -1
- package/dist/{ssgi-Dm-maZrc.js → ssgi-DSnhqotl.js} +2 -2
- package/dist/{ssgi-Dm-maZrc.js.map → ssgi-DSnhqotl.js.map} +1 -1
- package/dist/{surface-shader-DY9_aC9L.js → surface-shader-rpPpeosD.js} +4 -4
- package/dist/{surface-shader-DY9_aC9L.js.map → surface-shader-rpPpeosD.js.map} +1 -1
- package/dist/{vec3-Cc19wl4r.js → vec3-2C3LBZnt.js} +55 -3
- package/dist/vec3-2C3LBZnt.js.map +1 -0
- package/package.json +1 -1
- package/dist/lightmaps-LO6Ygtwe.js +0 -137
- package/dist/lightmaps-LO6Ygtwe.js.map +0 -1
- package/dist/prefab-overrides-CS8_cG66.d.ts.map +0 -1
- package/dist/prefab-overrides-DRP2DcnC.js.map +0 -1
- package/dist/reflection-probes-CUZcOjNW.js.map +0 -1
- package/dist/vec3-Cc19wl4r.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { o as rebuildMaterialPipelines } from "./material-
|
|
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-
|
|
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;CACjD,OAAO;;;;;;;;;;;;;sBAaa,OAAO,MAAM,MAAM,EAAE;qBACtB,OAAO,MAAM,KAAK,EAAE;wBACjB,OAAO,MAAM,OAAO,EAAE;qBACzB,MAAM,MAAM,QAAQ,CAAC,EAAE;;;;;;;;;;;;;;;;;;;;2BAoBjB,OAAO,SAAS,EAAE,IAAI,OAAO,SAAS,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4EnE;;;;;;;;AASA,SAAgB,kBAA0B;CACxC,OAAO;;;;;;;;;;;;2BAYkB,OAAO,SAAS,EAAE,IA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;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,MAAM,KAAK,EAAE;wBACjB,OAAO,MAAM,OAAO,EAAE;qBACzB,MAAM,MAAM,QAAQ,CAAC,EAAE;;;;;;;;;;;;;;;;;;;;2BAoBjB,OAAO,SAAS,EAAE,IAAI,OAAO,SAAS,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4EnE;;;;;;;;AASA,SAAgB,kBAA0B;CACxC,OAAO;;;;;;;;;;;;2BAYkB,OAAO,SAAS,EAAE,IAAI,OAAO,SAAS,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BnE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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-
|
|
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-
|
|
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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;C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mB,OAAqB,QAAuB,mBAAkC;CACxG,MAAM,SAAS,MAAM;CACrB,KAAK,IAAI,QAAQ,GAAG,QAAQ,OAAO,QAAQ,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"}
|
|
1
|
+
{"version":3,"file":"hdr-output-DBQwMphy.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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,MAAa,mBAAqC;;;;;;AAOlD,MAAa,4BAA4B;;;;;;AAOzC,MAAa,8BAA8B;;;;;;AAO3C,MAAa,2BAA2B;;;;;AAMxC,MAAM,qBAAqB;;;;;AAM3B,MAAM,kBACJ;;;;;AAUF,MAAM,mBACJ;;;;;;AAQF,MAAa,wBAAwB;CAAE,SAAS;CAA2B,aAAa;AAAoB;;;;;;AAO5G,MAAa,YAAY;CAAE,MAAM;CAAG,UAAU;CAAG,MAAM;CAAG,SAAS;CAAG,KAAK;AAAE;;AAG7E,MAAM,iBAAiB;;;;;;;;;;;;;;AAevB,SAAgB,2BAA2C;CACzD,MAAM,WAAW;EACf,6BAA6B,6CAA6C;EAC1E,8CAA8C;EAC9C,kCAAkC,6BAA6B;CACjE;CACA,OAAO;EACL,MAAM;EACN,UAAU;EACV,gBAAgB,UAAW,UAAU,aAAa,WAAW;CAC/D;AACF;;;;;;;;;;;;;;;AAgBA,SAAgB,0BAA0C;CACxD,MAAM,WAAW;EACf,6BAA6B;EAC7B,kCAAkC,yCAAyC;CAC7E;CACA,OAAO;EACL,MAAM;EACN,UAAU;EACV,gBAAgB,UAAW,UAAU,aAAa,WAA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