@ignifx/core 0.14.0 → 0.16.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/decoders/draco3dgltf.LICENSE.md +201 -0
- package/decoders/draco_decoder.js +116 -0
- package/decoders/draco_decoder_gltf.wasm +0 -0
- package/decoders/vendored.json +22 -0
- package/dist/agx-tone-mapping-Cgt844j6.js +53 -0
- package/dist/agx-tone-mapping-Cgt844j6.js.map +1 -0
- package/dist/auto-exposure-uzPn0beO.js +246 -0
- package/dist/auto-exposure-uzPn0beO.js.map +1 -0
- package/dist/bloom-hdr-CLtQj-oY.js +315 -0
- package/dist/bloom-hdr-CLtQj-oY.js.map +1 -0
- package/dist/contact-shadows-T523EXaP.js +84 -0
- package/dist/contact-shadows-T523EXaP.js.map +1 -0
- package/dist/{decoders-CHJ7vduE.js → decoders-BUQrlS8U.js} +3 -2
- package/dist/decoders-BUQrlS8U.js.map +1 -0
- package/dist/{environment-Cq2BmA96.js → environment-DPi0_0SP.js} +18 -4
- package/dist/environment-DPi0_0SP.js.map +1 -0
- package/dist/gtao-_nr0b6-E.js +630 -0
- package/dist/gtao-_nr0b6-E.js.map +1 -0
- package/dist/hdr-output-BrUvpAsE.js +525 -0
- package/dist/hdr-output-BrUvpAsE.js.map +1 -0
- package/dist/index.d.ts +509 -24
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1522 -512
- package/dist/index.js.map +1 -1
- package/dist/{instanced-mesh-instance-DYwH0vLi.js → instanced-mesh-instance-NnODkvqK.js} +2 -2
- package/dist/{instanced-mesh-instance-DYwH0vLi.js.map → instanced-mesh-instance-NnODkvqK.js.map} +1 -1
- package/dist/mat4-D6exvAuO.js +949 -0
- package/dist/mat4-D6exvAuO.js.map +1 -0
- package/dist/{render-path-Dx0learj.js → render-path-Be7WgN7r.js} +35 -4
- package/dist/render-path-Be7WgN7r.js.map +1 -0
- package/dist/{render-texture-IuR0iFVa.js → render-texture-C_TnaSz2.js} +28 -2
- package/dist/render-texture-C_TnaSz2.js.map +1 -0
- package/dist/scene-color-passes-DlNr-qyZ.js +65 -0
- package/dist/scene-color-passes-DlNr-qyZ.js.map +1 -0
- package/dist/scene-inputs-BxGOsnIZ.js +318 -0
- package/dist/scene-inputs-BxGOsnIZ.js.map +1 -0
- package/dist/{shader-material-CDQ0Y5kN.js → shader-material-B6p66wB8.js} +17 -6
- package/dist/shader-material-B6p66wB8.js.map +1 -0
- package/dist/{shader-material-BPb_oEZQ.js → shader-material-C0TAUr4t.js} +102 -4
- package/dist/shader-material-C0TAUr4t.js.map +1 -0
- package/dist/ssgi-Dm-maZrc.js +113 -0
- package/dist/ssgi-Dm-maZrc.js.map +1 -0
- package/dist/{surface-shader-CwQ03yHG.js → surface-shader-BaK0kvBB.js} +2 -2
- package/dist/{surface-shader-CwQ03yHG.js.map → surface-shader-BaK0kvBB.js.map} +1 -1
- package/dist/taa-BwBZLy11.js +480 -0
- package/dist/taa-BwBZLy11.js.map +1 -0
- package/dist/{vec3-T2PasQZv.js → vec3-D-0Y2mzE.js} +4 -948
- package/dist/vec3-D-0Y2mzE.js.map +1 -0
- package/package.json +4 -2
- package/dist/decoders-CHJ7vduE.js.map +0 -1
- package/dist/environment-Cq2BmA96.js.map +0 -1
- package/dist/hdr-output-DDpIo4Q5.js +0 -300
- package/dist/hdr-output-DDpIo4Q5.js.map +0 -1
- package/dist/render-path-Dx0learj.js.map +0 -1
- package/dist/render-texture-IuR0iFVa.js.map +0 -1
- package/dist/shader-material-BPb_oEZQ.js.map +0 -1
- package/dist/shader-material-CDQ0Y5kN.js.map +0 -1
- package/dist/vec3-T2PasQZv.js.map +0 -1
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import { addComputeDispatch, addTask, computeStorageBufferBinding, computeStorageTextureBinding, computeTextureBinding, computeUniformBufferBinding, createComputeBindingSet, createComputeDispatch, createComputeShader, createComputeStorageTexture2D, createComputeTask, createComputeTextureResource, createStorageBuffer, createUniformBuffer, updateUniformBuffer } from "@babylonjs/lite";
|
|
2
|
+
//#region src/lite/gpu/auto-exposure.ts
|
|
3
|
+
/**
|
|
4
|
+
* The fraction of counted texels dropped at each end of the histogram before averaging.
|
|
5
|
+
*
|
|
6
|
+
* @internal
|
|
7
|
+
*/
|
|
8
|
+
const AUTO_EXPOSURE_PERCENTILES = {
|
|
9
|
+
low: .1,
|
|
10
|
+
high: .9
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* The `log2` luminance range the histogram covers; bins 1–255 split it evenly.
|
|
14
|
+
*
|
|
15
|
+
* @internal
|
|
16
|
+
*/
|
|
17
|
+
const AUTO_EXPOSURE_LOG_RANGE = {
|
|
18
|
+
min: -12,
|
|
19
|
+
max: 12
|
|
20
|
+
};
|
|
21
|
+
/** The task's name in the frame graph. */
|
|
22
|
+
const TASK_NAME = "ignifx:auto-exposure";
|
|
23
|
+
/** The edge of the sample grid: 64×64 texels, four workgroups of 16×16 a side. */
|
|
24
|
+
const GRID = 64;
|
|
25
|
+
/** The workgroup edge of the histogram pass. */
|
|
26
|
+
const WORKGROUP_EDGE = 16;
|
|
27
|
+
/** The bin count; also the average pass's workgroup size. */
|
|
28
|
+
const BINS = 256;
|
|
29
|
+
/** Floats in the parameter block: dt, minEv, maxEv, speedUp, speedDown, compensation, low, high. */
|
|
30
|
+
const PARAM_FLOATS = 8;
|
|
31
|
+
/** The longest frame the adaptation integrates, in seconds, so a stall does not jump the exposure. */
|
|
32
|
+
const MAX_DELTA_SECONDS = .25;
|
|
33
|
+
/**
|
|
34
|
+
* The WGSL shared by both passes.
|
|
35
|
+
*
|
|
36
|
+
* @returns The parameter struct and the histogram constants.
|
|
37
|
+
*/
|
|
38
|
+
function sharedWgsl() {
|
|
39
|
+
return [
|
|
40
|
+
"struct Params{dt:f32,minEv:f32,maxEv:f32,speedUp:f32,speedDown:f32,compensation:f32,low:f32,high:f32};",
|
|
41
|
+
`const BINS:u32=${String(BINS)}u;`,
|
|
42
|
+
`const LOG_MIN:f32=${AUTO_EXPOSURE_LOG_RANGE.min.toFixed(1)};`,
|
|
43
|
+
`const LOG_MAX:f32=${AUTO_EXPOSURE_LOG_RANGE.max.toFixed(1)};`
|
|
44
|
+
].join("\n");
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Builds the histogram pass: one texel per invocation, binned in workgroup memory and then added to
|
|
48
|
+
* the global bins.
|
|
49
|
+
*
|
|
50
|
+
* @returns The WGSL, entry point `main`.
|
|
51
|
+
*
|
|
52
|
+
* @internal
|
|
53
|
+
*/
|
|
54
|
+
function autoExposureHistogramWgsl() {
|
|
55
|
+
return [
|
|
56
|
+
sharedWgsl(),
|
|
57
|
+
`const GRID:f32=${GRID.toFixed(1)};`,
|
|
58
|
+
"@group(0)@binding(0)var hdrColor:texture_2d<f32>;",
|
|
59
|
+
"@group(0)@binding(1)var<storage,read_write>histogram:array<atomic<u32>,256>;",
|
|
60
|
+
"var<workgroup>localBins:array<atomic<u32>,256>;",
|
|
61
|
+
"fn binOf(luminance:f32)->u32{",
|
|
62
|
+
"if(luminance<exp2(LOG_MIN)){return 0u;}",
|
|
63
|
+
"let t=clamp((log2(luminance)-LOG_MIN)/(LOG_MAX-LOG_MIN),0.0,1.0);",
|
|
64
|
+
"return min(1u+u32(t*f32(BINS-2u)+0.5),BINS-1u);",
|
|
65
|
+
"}",
|
|
66
|
+
`@compute @workgroup_size(${String(WORKGROUP_EDGE)},${String(WORKGROUP_EDGE)})`,
|
|
67
|
+
"fn main(@builtin(global_invocation_id)id:vec3<u32>,@builtin(local_invocation_index)localIndex:u32){",
|
|
68
|
+
"atomicStore(&localBins[localIndex],0u);",
|
|
69
|
+
"workgroupBarrier();",
|
|
70
|
+
"let size=textureDimensions(hdrColor);",
|
|
71
|
+
"let pixel=vec2<u32>((vec2<f32>(id.xy)+0.5)/GRID*vec2<f32>(size));",
|
|
72
|
+
"let texel=textureLoad(hdrColor,min(pixel,size-vec2<u32>(1u)),0).rgb;",
|
|
73
|
+
"let luminance=dot(max(texel,vec3<f32>(0.0)),vec3<f32>(0.2126,0.7152,0.0722));",
|
|
74
|
+
"atomicAdd(&localBins[binOf(luminance)],1u);",
|
|
75
|
+
"workgroupBarrier();",
|
|
76
|
+
"let count=atomicLoad(&localBins[localIndex]);",
|
|
77
|
+
"if(count>0u){atomicAdd(&histogram[localIndex],count);}",
|
|
78
|
+
"}"
|
|
79
|
+
].join("\n");
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Builds the average-and-adapt pass: 256 invocations load and clear the bins, then the first one
|
|
83
|
+
* walks them once.
|
|
84
|
+
*
|
|
85
|
+
* @returns The WGSL, entry point `main`.
|
|
86
|
+
*
|
|
87
|
+
* @internal
|
|
88
|
+
*/
|
|
89
|
+
function autoExposureAverageWgsl() {
|
|
90
|
+
return [
|
|
91
|
+
sharedWgsl(),
|
|
92
|
+
"@group(0)@binding(0)var<uniform>params:Params;",
|
|
93
|
+
"@group(0)@binding(1)var<storage,read_write>histogram:array<atomic<u32>,256>;",
|
|
94
|
+
"@group(0)@binding(2)var<storage,read_write>state:array<f32,4>;",
|
|
95
|
+
"@group(0)@binding(3)var exposure:texture_storage_2d<r32float,write>;",
|
|
96
|
+
"var<workgroup>bins:array<u32,256>;",
|
|
97
|
+
`@compute @workgroup_size(${String(BINS)})`,
|
|
98
|
+
"fn main(@builtin(local_invocation_index)localIndex:u32){",
|
|
99
|
+
"bins[localIndex]=atomicExchange(&histogram[localIndex],0u);",
|
|
100
|
+
"workgroupBarrier();",
|
|
101
|
+
"if(localIndex!=0u){return;}",
|
|
102
|
+
"var total=0.0;",
|
|
103
|
+
"for(var i=1u;i<BINS;i++){total+=f32(bins[i]);}",
|
|
104
|
+
"var current=state[0];",
|
|
105
|
+
"var goal=current;",
|
|
106
|
+
"if(total>0.0){",
|
|
107
|
+
"let lowCut=total*params.low;",
|
|
108
|
+
"let highCut=total*params.high;",
|
|
109
|
+
"var seen=0.0;var sum=0.0;var weight=0.0;",
|
|
110
|
+
"for(var i=1u;i<BINS;i++){",
|
|
111
|
+
"let count=f32(bins[i]);",
|
|
112
|
+
"let kept=clamp(seen+count,lowCut,highCut)-clamp(seen,lowCut,highCut);",
|
|
113
|
+
"seen+=count;",
|
|
114
|
+
"let binLog=LOG_MIN+(f32(i)-1.0)/f32(BINS-2u)*(LOG_MAX-LOG_MIN);",
|
|
115
|
+
"sum+=kept*binLog;weight+=kept;",
|
|
116
|
+
"}",
|
|
117
|
+
"if(weight>0.0){goal=clamp(sum/weight,params.minEv,params.maxEv);}",
|
|
118
|
+
"}",
|
|
119
|
+
"if(state[1]<0.5){",
|
|
120
|
+
"if(total>0.0){current=goal;state[1]=1.0;}",
|
|
121
|
+
"}else{",
|
|
122
|
+
"let speed=select(params.speedDown,params.speedUp,goal>current);",
|
|
123
|
+
"current+=(goal-current)*(1.0-exp(-params.dt*max(speed,0.0)));",
|
|
124
|
+
"}",
|
|
125
|
+
"state[0]=current;",
|
|
126
|
+
"let value=select(0.0,log2(0.18)+params.compensation-current,state[1]>0.5);",
|
|
127
|
+
"textureStore(exposure,vec2<i32>(0,0),vec4<f32>(value,0.0,0.0,1.0));",
|
|
128
|
+
"}"
|
|
129
|
+
].join("\n");
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Builds the auto exposure passes over the HDR scene target and appends them to the frame graph.
|
|
133
|
+
*
|
|
134
|
+
* @remarks
|
|
135
|
+
* Call it after the scene task and before the output tasks, so the frame meters the colour it is
|
|
136
|
+
* about to present. The HDR texture's compute view is validated asynchronously by Lite
|
|
137
|
+
* (`createComputeTextureResource`), so the dispatches join the task once that settles; until then
|
|
138
|
+
* the exposure texture reads 0 and the output pass multiplies by 1. A resize swaps the texture
|
|
139
|
+
* behind the facade, which Lite's compute bindings notice by themselves
|
|
140
|
+
* (`lib/compute/compute-texture-resource.js`, `_validateComputeTextureResource`).
|
|
141
|
+
*
|
|
142
|
+
* @param engine - The engine.
|
|
143
|
+
* @param scene - The scene whose frame graph gets the task.
|
|
144
|
+
* @param hdrTexture - The linear scene colour, `rgba16float`.
|
|
145
|
+
* @param options - The knobs.
|
|
146
|
+
* @returns The exposure texture and the per-frame update.
|
|
147
|
+
*
|
|
148
|
+
* @internal
|
|
149
|
+
*/
|
|
150
|
+
function installAutoExposure(engine, scene, hdrTexture, options) {
|
|
151
|
+
const task = createComputeTask(engine, TASK_NAME);
|
|
152
|
+
addTask(scene, task);
|
|
153
|
+
const histogram = createStorageBuffer(engine, BINS * 4, {
|
|
154
|
+
label: "ignifx:auto-exposure-histogram",
|
|
155
|
+
writable: true
|
|
156
|
+
});
|
|
157
|
+
const state = createStorageBuffer(engine, 16, {
|
|
158
|
+
label: "ignifx:auto-exposure-state",
|
|
159
|
+
writable: true
|
|
160
|
+
});
|
|
161
|
+
const exposure = createComputeStorageTexture2D(engine, {
|
|
162
|
+
width: 1,
|
|
163
|
+
height: 1,
|
|
164
|
+
format: "r32float",
|
|
165
|
+
label: "ignifx:auto-exposure"
|
|
166
|
+
});
|
|
167
|
+
const params = new Float32Array(PARAM_FLOATS);
|
|
168
|
+
params[1] = options.minEv;
|
|
169
|
+
params[2] = options.maxEv;
|
|
170
|
+
params[3] = options.speedUp;
|
|
171
|
+
params[4] = options.speedDown;
|
|
172
|
+
params[5] = options.compensation;
|
|
173
|
+
params[6] = AUTO_EXPOSURE_PERCENTILES.low;
|
|
174
|
+
params[7] = AUTO_EXPOSURE_PERCENTILES.high;
|
|
175
|
+
const uniforms = createUniformBuffer(engine, params, { label: "ignifx:auto-exposure-params" });
|
|
176
|
+
const histogramShader = createComputeShader(engine, {
|
|
177
|
+
name: "ignifx:auto-exposure-histogram",
|
|
178
|
+
computeSource: autoExposureHistogramWgsl(),
|
|
179
|
+
entryPoint: "main",
|
|
180
|
+
bindings: [computeTextureBinding("hdrColor", {
|
|
181
|
+
group: 0,
|
|
182
|
+
binding: 0,
|
|
183
|
+
sampleType: "unfilterable-float"
|
|
184
|
+
}), computeStorageBufferBinding("histogram", {
|
|
185
|
+
group: 0,
|
|
186
|
+
binding: 1,
|
|
187
|
+
access: "read-write"
|
|
188
|
+
})]
|
|
189
|
+
});
|
|
190
|
+
const averageShader = createComputeShader(engine, {
|
|
191
|
+
name: "ignifx:auto-exposure-average",
|
|
192
|
+
computeSource: autoExposureAverageWgsl(),
|
|
193
|
+
entryPoint: "main",
|
|
194
|
+
bindings: [
|
|
195
|
+
computeUniformBufferBinding("params", {
|
|
196
|
+
group: 0,
|
|
197
|
+
binding: 0
|
|
198
|
+
}),
|
|
199
|
+
computeStorageBufferBinding("histogram", {
|
|
200
|
+
group: 0,
|
|
201
|
+
binding: 1,
|
|
202
|
+
access: "read-write"
|
|
203
|
+
}),
|
|
204
|
+
computeStorageBufferBinding("state", {
|
|
205
|
+
group: 0,
|
|
206
|
+
binding: 2,
|
|
207
|
+
access: "read-write"
|
|
208
|
+
}),
|
|
209
|
+
computeStorageTextureBinding("exposure", {
|
|
210
|
+
group: 0,
|
|
211
|
+
binding: 3,
|
|
212
|
+
format: "r32float"
|
|
213
|
+
})
|
|
214
|
+
]
|
|
215
|
+
});
|
|
216
|
+
createComputeTextureResource(engine, hdrTexture, { sampleType: "unfilterable-float" }).then((hdrColor) => {
|
|
217
|
+
const groups = GRID / WORKGROUP_EDGE;
|
|
218
|
+
addComputeDispatch(task, createComputeDispatch(histogramShader, createComputeBindingSet(histogramShader, {
|
|
219
|
+
hdrColor,
|
|
220
|
+
histogram
|
|
221
|
+
}), { size: {
|
|
222
|
+
x: groups,
|
|
223
|
+
y: groups
|
|
224
|
+
} }));
|
|
225
|
+
addComputeDispatch(task, createComputeDispatch(averageShader, createComputeBindingSet(averageShader, {
|
|
226
|
+
params: uniforms,
|
|
227
|
+
histogram,
|
|
228
|
+
state,
|
|
229
|
+
exposure
|
|
230
|
+
}), { size: { x: 1 } }));
|
|
231
|
+
});
|
|
232
|
+
let last = -1;
|
|
233
|
+
return {
|
|
234
|
+
exposureTexture: exposure.sampledTexture,
|
|
235
|
+
update() {
|
|
236
|
+
const now = performance.now();
|
|
237
|
+
params[0] = last < 0 ? 0 : Math.min(Math.max((now - last) / 1e3, 0), MAX_DELTA_SECONDS);
|
|
238
|
+
last = now;
|
|
239
|
+
updateUniformBuffer(engine, uniforms, params);
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
//#endregion
|
|
244
|
+
export { AUTO_EXPOSURE_LOG_RANGE, AUTO_EXPOSURE_PERCENTILES, autoExposureAverageWgsl, autoExposureHistogramWgsl, installAutoExposure };
|
|
245
|
+
|
|
246
|
+
//# sourceMappingURL=auto-exposure-uzPn0beO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auto-exposure-uzPn0beO.js","names":[],"sources":["../src/lite/gpu/auto-exposure.ts"],"sourcesContent":["import {\n addComputeDispatch,\n addTask,\n computeStorageBufferBinding,\n computeStorageTextureBinding,\n computeTextureBinding,\n computeUniformBufferBinding,\n createComputeBindingSet,\n createComputeDispatch,\n createComputeShader,\n createComputeStorageTexture2D,\n createComputeTask,\n createComputeTextureResource,\n createStorageBuffer,\n createUniformBuffer,\n updateUniformBuffer,\n} from \"@babylonjs/lite\";\nimport type { EngineContext, SceneContext, Texture2D } from \"@babylonjs/lite\";\n\n/**\n * Auto exposure for the HDR render path (`docs/plan/2026-11-gi-phase-1-execution-plan.md`, step G14).\n * Its own chunk: `../engine.ts` imports it only when `rendering.hdr` and\n * `rendering.autoExposure.enabled` are both on (`CONSTITUTION.md` §2.5).\n *\n * ```text\n * scene ─→ hdr ─→ [histogram] ─→ [average + adapt] ─→ exposure (1×1 r32float) ─→ output pass\n * ```\n *\n * - **Histogram.** A 64×64 grid of texels, spread over the whole target whatever its size, is\n * binned by `log2` luminance into 256 bins; bin 0 takes everything darker than the range, such as\n * a black clear, and is left out of the average.\n * - **Average.** One workgroup reads the bins (and zeroes them for the next frame), drops the\n * darkest and brightest {@link AUTO_EXPOSURE_PERCENTILES} of the counted texels, and averages the\n * rest in `log2` space: the scene's metered EV.\n * - **Adaptation.** The metered EV is clamped to `[minEv, maxEv]` and the current EV eases towards\n * it, `speedUp` when the scene got brighter and `speedDown` when it got darker; the first frame\n * snaps. The pass writes `log2` of the multiplier that maps the current EV to middle grey (0.18),\n * plus `compensation`, so an unwritten texture (0) means \"×1\".\n * - **The output pass** multiplies the linear colour by `exp2` of that texel before the\n * `Environment`'s exposure and curve (`./hdr-output.ts`).\n */\n\n/**\n * The auto exposure knobs, in EV (stops, `log2` units) and per-second rates.\n *\n * @internal\n */\nexport interface AutoExposureOptions {\n /** The darkest metered EV the exposure follows: darker scenes are not brightened further. */\n readonly minEv: number;\n /** The brightest metered EV the exposure follows: brighter scenes are not darkened further. */\n readonly maxEv: number;\n /** Adaptation rate, per second, when the scene gets brighter. */\n readonly speedUp: number;\n /** Adaptation rate, per second, when the scene gets darker. */\n readonly speedDown: number;\n /** Stops added to the computed exposure; positive is brighter. */\n readonly compensation: number;\n}\n\n/**\n * What {@link installAutoExposure} hands the output pass.\n *\n * @internal\n */\nexport interface AutoExposurePass {\n /** A 1×1 `r32float` texture holding `log2` of the exposure multiplier; 0 until the first run. */\n readonly exposureTexture: Texture2D;\n /** The per-frame work: uploads the frame's delta time with the knobs. */\n update(): void;\n}\n\n/**\n * The fraction of counted texels dropped at each end of the histogram before averaging.\n *\n * @internal\n */\nexport const AUTO_EXPOSURE_PERCENTILES = { low: 0.1, high: 0.9 } as const;\n\n/**\n * The `log2` luminance range the histogram covers; bins 1–255 split it evenly.\n *\n * @internal\n */\nexport const AUTO_EXPOSURE_LOG_RANGE = { min: -12, max: 12 } as const;\n\n/** The task's name in the frame graph. */\nconst TASK_NAME = \"ignifx:auto-exposure\";\n\n/** The edge of the sample grid: 64×64 texels, four workgroups of 16×16 a side. */\nconst GRID = 64;\n\n/** The workgroup edge of the histogram pass. */\nconst WORKGROUP_EDGE = 16;\n\n/** The bin count; also the average pass's workgroup size. */\nconst BINS = 256;\n\n/** Floats in the parameter block: dt, minEv, maxEv, speedUp, speedDown, compensation, low, high. */\nconst PARAM_FLOATS = 8;\n\n/** The longest frame the adaptation integrates, in seconds, so a stall does not jump the exposure. */\nconst MAX_DELTA_SECONDS = 0.25;\n\n/**\n * The WGSL shared by both passes.\n *\n * @returns The parameter struct and the histogram constants.\n */\nfunction sharedWgsl(): string {\n return [\n \"struct Params{dt:f32,minEv:f32,maxEv:f32,speedUp:f32,speedDown:f32,compensation:f32,low:f32,high:f32};\",\n `const BINS:u32=${String(BINS)}u;`,\n `const LOG_MIN:f32=${AUTO_EXPOSURE_LOG_RANGE.min.toFixed(1)};`,\n `const LOG_MAX:f32=${AUTO_EXPOSURE_LOG_RANGE.max.toFixed(1)};`,\n ].join(\"\\n\");\n}\n\n/**\n * Builds the histogram pass: one texel per invocation, binned in workgroup memory and then added to\n * the global bins.\n *\n * @returns The WGSL, entry point `main`.\n *\n * @internal\n */\nexport function autoExposureHistogramWgsl(): string {\n return [\n sharedWgsl(),\n `const GRID:f32=${GRID.toFixed(1)};`,\n \"@group(0)@binding(0)var hdrColor:texture_2d<f32>;\",\n \"@group(0)@binding(1)var<storage,read_write>histogram:array<atomic<u32>,256>;\",\n \"var<workgroup>localBins:array<atomic<u32>,256>;\",\n \"fn binOf(luminance:f32)->u32{\",\n \"if(luminance<exp2(LOG_MIN)){return 0u;}\",\n \"let t=clamp((log2(luminance)-LOG_MIN)/(LOG_MAX-LOG_MIN),0.0,1.0);\",\n \"return min(1u+u32(t*f32(BINS-2u)+0.5),BINS-1u);\",\n \"}\",\n `@compute @workgroup_size(${String(WORKGROUP_EDGE)},${String(WORKGROUP_EDGE)})`,\n \"fn main(@builtin(global_invocation_id)id:vec3<u32>,@builtin(local_invocation_index)localIndex:u32){\",\n \"atomicStore(&localBins[localIndex],0u);\",\n \"workgroupBarrier();\",\n \"let size=textureDimensions(hdrColor);\",\n \"let pixel=vec2<u32>((vec2<f32>(id.xy)+0.5)/GRID*vec2<f32>(size));\",\n \"let texel=textureLoad(hdrColor,min(pixel,size-vec2<u32>(1u)),0).rgb;\",\n \"let luminance=dot(max(texel,vec3<f32>(0.0)),vec3<f32>(0.2126,0.7152,0.0722));\",\n \"atomicAdd(&localBins[binOf(luminance)],1u);\",\n \"workgroupBarrier();\",\n \"let count=atomicLoad(&localBins[localIndex]);\",\n \"if(count>0u){atomicAdd(&histogram[localIndex],count);}\",\n \"}\",\n ].join(\"\\n\");\n}\n\n/**\n * Builds the average-and-adapt pass: 256 invocations load and clear the bins, then the first one\n * walks them once.\n *\n * @returns The WGSL, entry point `main`.\n *\n * @internal\n */\nexport function autoExposureAverageWgsl(): string {\n return [\n sharedWgsl(),\n \"@group(0)@binding(0)var<uniform>params:Params;\",\n \"@group(0)@binding(1)var<storage,read_write>histogram:array<atomic<u32>,256>;\",\n \"@group(0)@binding(2)var<storage,read_write>state:array<f32,4>;\",\n \"@group(0)@binding(3)var exposure:texture_storage_2d<r32float,write>;\",\n \"var<workgroup>bins:array<u32,256>;\",\n `@compute @workgroup_size(${String(BINS)})`,\n \"fn main(@builtin(local_invocation_index)localIndex:u32){\",\n \"bins[localIndex]=atomicExchange(&histogram[localIndex],0u);\",\n \"workgroupBarrier();\",\n \"if(localIndex!=0u){return;}\",\n \"var total=0.0;\",\n \"for(var i=1u;i<BINS;i++){total+=f32(bins[i]);}\",\n \"var current=state[0];\",\n \"var goal=current;\",\n \"if(total>0.0){\",\n \"let lowCut=total*params.low;\",\n \"let highCut=total*params.high;\",\n \"var seen=0.0;var sum=0.0;var weight=0.0;\",\n \"for(var i=1u;i<BINS;i++){\",\n \"let count=f32(bins[i]);\",\n \"let kept=clamp(seen+count,lowCut,highCut)-clamp(seen,lowCut,highCut);\",\n \"seen+=count;\",\n \"let binLog=LOG_MIN+(f32(i)-1.0)/f32(BINS-2u)*(LOG_MAX-LOG_MIN);\",\n \"sum+=kept*binLog;weight+=kept;\",\n \"}\",\n \"if(weight>0.0){goal=clamp(sum/weight,params.minEv,params.maxEv);}\",\n \"}\",\n \"if(state[1]<0.5){\",\n \"if(total>0.0){current=goal;state[1]=1.0;}\",\n \"}else{\",\n \"let speed=select(params.speedDown,params.speedUp,goal>current);\",\n \"current+=(goal-current)*(1.0-exp(-params.dt*max(speed,0.0)));\",\n \"}\",\n \"state[0]=current;\",\n \"let value=select(0.0,log2(0.18)+params.compensation-current,state[1]>0.5);\",\n \"textureStore(exposure,vec2<i32>(0,0),vec4<f32>(value,0.0,0.0,1.0));\",\n \"}\",\n ].join(\"\\n\");\n}\n\n/**\n * Builds the auto exposure passes over the HDR scene target and appends them to the frame graph.\n *\n * @remarks\n * Call it after the scene task and before the output tasks, so the frame meters the colour it is\n * about to present. The HDR texture's compute view is validated asynchronously by Lite\n * (`createComputeTextureResource`), so the dispatches join the task once that settles; until then\n * the exposure texture reads 0 and the output pass multiplies by 1. A resize swaps the texture\n * behind the facade, which Lite's compute bindings notice by themselves\n * (`lib/compute/compute-texture-resource.js`, `_validateComputeTextureResource`).\n *\n * @param engine - The engine.\n * @param scene - The scene whose frame graph gets the task.\n * @param hdrTexture - The linear scene colour, `rgba16float`.\n * @param options - The knobs.\n * @returns The exposure texture and the per-frame update.\n *\n * @internal\n */\nexport function installAutoExposure(\n engine: EngineContext,\n scene: SceneContext,\n hdrTexture: Texture2D,\n options: AutoExposureOptions,\n): AutoExposurePass {\n const task = createComputeTask(engine, TASK_NAME);\n addTask(scene, task);\n const histogram = createStorageBuffer(engine, BINS * 4, { label: \"ignifx:auto-exposure-histogram\", writable: true });\n const state = createStorageBuffer(engine, 16, { label: \"ignifx:auto-exposure-state\", writable: true });\n const exposure = createComputeStorageTexture2D(engine, {\n width: 1,\n height: 1,\n format: \"r32float\",\n label: \"ignifx:auto-exposure\",\n });\n const params = new Float32Array(PARAM_FLOATS);\n params[1] = options.minEv;\n params[2] = options.maxEv;\n params[3] = options.speedUp;\n params[4] = options.speedDown;\n params[5] = options.compensation;\n params[6] = AUTO_EXPOSURE_PERCENTILES.low;\n params[7] = AUTO_EXPOSURE_PERCENTILES.high;\n const uniforms = createUniformBuffer(engine, params, { label: \"ignifx:auto-exposure-params\" });\n\n const histogramShader = createComputeShader(engine, {\n name: \"ignifx:auto-exposure-histogram\",\n computeSource: autoExposureHistogramWgsl(),\n entryPoint: \"main\",\n bindings: [\n computeTextureBinding(\"hdrColor\", { group: 0, binding: 0, sampleType: \"unfilterable-float\" }),\n computeStorageBufferBinding(\"histogram\", { group: 0, binding: 1, access: \"read-write\" }),\n ],\n });\n const averageShader = createComputeShader(engine, {\n name: \"ignifx:auto-exposure-average\",\n computeSource: autoExposureAverageWgsl(),\n entryPoint: \"main\",\n bindings: [\n computeUniformBufferBinding(\"params\", { group: 0, binding: 0 }),\n computeStorageBufferBinding(\"histogram\", { group: 0, binding: 1, access: \"read-write\" }),\n computeStorageBufferBinding(\"state\", { group: 0, binding: 2, access: \"read-write\" }),\n computeStorageTextureBinding(\"exposure\", { group: 0, binding: 3, format: \"r32float\" }),\n ],\n });\n\n void createComputeTextureResource(engine, hdrTexture, { sampleType: \"unfilterable-float\" }).then((hdrColor) => {\n const groups = GRID / WORKGROUP_EDGE;\n addComputeDispatch(\n task,\n createComputeDispatch(histogramShader, createComputeBindingSet(histogramShader, { hdrColor, histogram }), {\n size: { x: groups, y: groups },\n }),\n );\n addComputeDispatch(\n task,\n createComputeDispatch(\n averageShader,\n createComputeBindingSet(averageShader, { params: uniforms, histogram, state, exposure }),\n { size: { x: 1 } },\n ),\n );\n });\n\n let last = -1;\n return {\n exposureTexture: exposure.sampledTexture,\n update(): void {\n const now = performance.now();\n params[0] = last < 0 ? 0 : Math.min(Math.max((now - last) / 1000, 0), MAX_DELTA_SECONDS);\n last = now;\n updateUniformBuffer(engine, uniforms, params);\n },\n };\n}\n"],"mappings":";;;;;;;AA6EA,MAAa,4BAA4B;CAAE,KAAK;CAAK,MAAM;AAAI;;;;;;AAO/D,MAAa,0BAA0B;CAAE,KAAK;CAAK,KAAK;AAAG;;AAG3D,MAAM,YAAY;;AAGlB,MAAM,OAAO;;AAGb,MAAM,iBAAiB;;A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F,EAAE,MAAM,EAAE,GAAG,EAAE,EAAE,CACnB,CACF;CACF,CAAC;CAED,IAAI,OAAO;CACX,OAAO;EACL,iBAAiB,SAAS;EAC1B,SAAe;GACb,MAAM,MAAM,YAAY,IAAI;GAC5B,OAAO,KAAK,OAAO,IAAI,IAAI,KAAK,IAAI,KAAK,KAAK,MAAM,QAAQ,KAAM,CAAC,GAAG,iBAAiB;GACvF,OAAO;GACP,oBAAoB,QAAQ,UAAU,MAAM;EAC9C;CACF;AACF"}
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import { createEffectRenderTask, createEffectWrapper, createSurfaceRenderTargetTexture, disposeEffectWrapper, disposeRenderTargetTexture, onRenderTargetTextureResize, setEffectTexture, setEffectUniforms } from "@babylonjs/lite";
|
|
2
|
+
//#region src/lite/gpu/bloom-hdr.ts
|
|
3
|
+
/**
|
|
4
|
+
* HDR bloom (`docs/plan/2026-11-gi-phase-1-execution-plan.md`, step G12): a downsample/upsample
|
|
5
|
+
* chain on the linear `rgba16float` scene target, recorded before the HDR output pass so the glow
|
|
6
|
+
* is tone mapped with the rest of the frame. Its own chunk: `../../render/hdr-bloom-support.ts`
|
|
7
|
+
* imports it only when a `PostProcessStack` asks for bloom under `rendering.hdr`
|
|
8
|
+
* (`CONSTITUTION.md` §2.5).
|
|
9
|
+
*
|
|
10
|
+
* ```text
|
|
11
|
+
* scene → hdr ─ down₀ → mip₀ ─ down₁ → mip₁ … → mip₅
|
|
12
|
+
* mip₄ += up(mip₅) … mip₀ += up(mip₁)
|
|
13
|
+
* hdr = mix(hdr, up(mip₀), intensity) ──→ output pass
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* - **Downsample** is the 13-tap filter of Jimenez, "Next generation post processing in Call of
|
|
17
|
+
* Duty: Advanced Warfare" (SIGGRAPH 2014): five overlapping 2×2 boxes, the centre one weighted
|
|
18
|
+
* 0.5. The first level weights each box by `1 / (1 + luma)` (Karis average), so one very bright
|
|
19
|
+
* texel cannot flicker into a frame-sized blob, and applies the optional soft-knee threshold.
|
|
20
|
+
* - **Upsample** is a 9-tap tent, blended into the next larger mip as
|
|
21
|
+
* `mip = mix(mip, tent(smaller), radius)`, so `radius` decides how much of the wide, low mips
|
|
22
|
+
* reaches the image while the weights still sum to one.
|
|
23
|
+
* - **Composite** writes into the HDR target itself through the blend unit, so the output pass's
|
|
24
|
+
* input never changes and nothing is rebound: `hdr = mix(hdr, bloom, intensity)` with no
|
|
25
|
+
* threshold (energy-conserving: the image is redistributed, not brightened), `hdr += bloom ·
|
|
26
|
+
* intensity` with one.
|
|
27
|
+
* - Each mip is a surface-scaled target (`{ surface, scale }`), so a resize reallocates it with
|
|
28
|
+
* the frame graph; the resize callbacks rebind the readers' bind groups.
|
|
29
|
+
* - Lite has no task removal, so {@link HdrBloom.dispose} disables the tasks and makes their
|
|
30
|
+
* `record` a no-op: a later frame-graph rebuild still walks them.
|
|
31
|
+
*/
|
|
32
|
+
/**
|
|
33
|
+
* How many mips the chain builds: half resolution down to 1/64.
|
|
34
|
+
*
|
|
35
|
+
* @internal
|
|
36
|
+
*/
|
|
37
|
+
const HDR_BLOOM_MIP_COUNT = 6;
|
|
38
|
+
/**
|
|
39
|
+
* The format of every mip; the same as the scene target, so values above 1 survive.
|
|
40
|
+
*
|
|
41
|
+
* @internal
|
|
42
|
+
*/
|
|
43
|
+
const HDR_BLOOM_FORMAT = "rgba16float";
|
|
44
|
+
/** Uniform floats per pass: one `vec4`. */
|
|
45
|
+
const UNIFORM_FLOATS = 4;
|
|
46
|
+
/** The blend that turns a pass's `vec4(rgb, a)` into `dst·(1 − a) + rgb`. */
|
|
47
|
+
const MIX_BLEND = {
|
|
48
|
+
color: {
|
|
49
|
+
operation: "add",
|
|
50
|
+
srcFactor: "one",
|
|
51
|
+
dstFactor: "one-minus-src-alpha"
|
|
52
|
+
},
|
|
53
|
+
alpha: {
|
|
54
|
+
operation: "add",
|
|
55
|
+
srcFactor: "zero",
|
|
56
|
+
dstFactor: "one"
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* The uniform block, texture, sampler and helpers every pass declares.
|
|
61
|
+
*
|
|
62
|
+
* @returns The WGSL.
|
|
63
|
+
*/
|
|
64
|
+
function passHeaderWgsl() {
|
|
65
|
+
return [
|
|
66
|
+
"struct BloomUniforms{params:vec4<f32>};",
|
|
67
|
+
"@group(0)@binding(0)var<uniform>bloom:BloomUniforms;",
|
|
68
|
+
"@group(0)@binding(1)var source:texture_2d<f32>;",
|
|
69
|
+
"@group(0)@binding(2)var sourceSampler:sampler;",
|
|
70
|
+
"fn bloomUv(fragment:EffectVertexOutput)->vec2<f32>{return vec2<f32>(fragment.uv.x,1.0-fragment.uv.y);}",
|
|
71
|
+
"fn tap(uv:vec2<f32>,offset:vec2<f32>,texel:vec2<f32>)->vec3<f32>{",
|
|
72
|
+
"let c=textureSampleLevel(source,sourceSampler,uv+offset*texel,0.0).rgb;",
|
|
73
|
+
"return min(max(c,vec3<f32>(0.0)),vec3<f32>(65000.0));",
|
|
74
|
+
"}"
|
|
75
|
+
].join("\n");
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* The downsample pass: 13 taps, a Karis average and the soft-knee threshold on the first level.
|
|
79
|
+
*
|
|
80
|
+
* @remarks
|
|
81
|
+
* `params` is `(threshold, knee, isFirstLevel, unused)`.
|
|
82
|
+
*
|
|
83
|
+
* @returns The WGSL, with Lite's `effectFragment` entry point.
|
|
84
|
+
*
|
|
85
|
+
* @internal
|
|
86
|
+
*/
|
|
87
|
+
function bloomDownsampleWgsl() {
|
|
88
|
+
return [
|
|
89
|
+
passHeaderWgsl(),
|
|
90
|
+
"fn boxWeight(c:vec3<f32>,first:bool)->f32{",
|
|
91
|
+
"if(!first){return 1.0;}",
|
|
92
|
+
"return 1.0/(1.0+dot(c,vec3<f32>(0.2126,0.7152,0.0722)));",
|
|
93
|
+
"}",
|
|
94
|
+
"fn knee(c:vec3<f32>,threshold:f32,soft:f32)->vec3<f32>{",
|
|
95
|
+
"if(threshold<=0.0){return c;}",
|
|
96
|
+
"let b=max(c.r,max(c.g,c.b));",
|
|
97
|
+
"var s=clamp(b-threshold+soft,0.0,2.0*soft);",
|
|
98
|
+
"s=s*s/(4.0*soft+1e-5);",
|
|
99
|
+
"return c*(max(s,b-threshold)/max(b,1e-5));",
|
|
100
|
+
"}",
|
|
101
|
+
"@fragment fn effectFragment(fragment:EffectVertexOutput)->@location(0)vec4<f32>{",
|
|
102
|
+
"let uv=bloomUv(fragment);",
|
|
103
|
+
"let texel=1.0/vec2<f32>(textureDimensions(source,0));",
|
|
104
|
+
"let first=bloom.params.z>0.5;",
|
|
105
|
+
"let a=tap(uv,vec2<f32>(-2.0,-2.0),texel);let b=tap(uv,vec2<f32>(0.0,-2.0),texel);",
|
|
106
|
+
"let c=tap(uv,vec2<f32>(2.0,-2.0),texel);let d=tap(uv,vec2<f32>(-2.0,0.0),texel);",
|
|
107
|
+
"let e=tap(uv,vec2<f32>(0.0,0.0),texel);let f=tap(uv,vec2<f32>(2.0,0.0),texel);",
|
|
108
|
+
"let g=tap(uv,vec2<f32>(-2.0,2.0),texel);let h=tap(uv,vec2<f32>(0.0,2.0),texel);",
|
|
109
|
+
"let i=tap(uv,vec2<f32>(2.0,2.0),texel);let j=tap(uv,vec2<f32>(-1.0,-1.0),texel);",
|
|
110
|
+
"let k=tap(uv,vec2<f32>(1.0,-1.0),texel);let l=tap(uv,vec2<f32>(-1.0,1.0),texel);",
|
|
111
|
+
"let m=tap(uv,vec2<f32>(1.0,1.0),texel);",
|
|
112
|
+
"let g0=(j+k+l+m)*0.25;let g1=(a+b+d+e)*0.25;let g2=(b+c+e+f)*0.25;",
|
|
113
|
+
"let g3=(d+e+g+h)*0.25;let g4=(e+f+h+i)*0.25;",
|
|
114
|
+
"let w0=0.5*boxWeight(g0,first);let w1=0.125*boxWeight(g1,first);let w2=0.125*boxWeight(g2,first);",
|
|
115
|
+
"let w3=0.125*boxWeight(g3,first);let w4=0.125*boxWeight(g4,first);",
|
|
116
|
+
"var color=(g0*w0+g1*w1+g2*w2+g3*w3+g4*w4)/(w0+w1+w2+w3+w4);",
|
|
117
|
+
"if(first){color=knee(color,bloom.params.x,bloom.params.y);}",
|
|
118
|
+
"return vec4<f32>(color,1.0);",
|
|
119
|
+
"}"
|
|
120
|
+
].join("\n");
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* The upsample and composite pass: a 9-tap tent of the smaller mip, scaled, with the blend weight
|
|
124
|
+
* in alpha.
|
|
125
|
+
*
|
|
126
|
+
* @remarks
|
|
127
|
+
* `params` is `(scale, alpha, unused, unused)`; with {@link MIX_BLEND} the target becomes
|
|
128
|
+
* `target·(1 − alpha) + tent·scale`.
|
|
129
|
+
*
|
|
130
|
+
* @returns The WGSL, with Lite's `effectFragment` entry point.
|
|
131
|
+
*
|
|
132
|
+
* @internal
|
|
133
|
+
*/
|
|
134
|
+
function bloomUpsampleWgsl() {
|
|
135
|
+
return [
|
|
136
|
+
passHeaderWgsl(),
|
|
137
|
+
"@fragment fn effectFragment(fragment:EffectVertexOutput)->@location(0)vec4<f32>{",
|
|
138
|
+
"let uv=bloomUv(fragment);",
|
|
139
|
+
"let texel=1.0/vec2<f32>(textureDimensions(source,0));",
|
|
140
|
+
"var color=tap(uv,vec2<f32>(0.0,0.0),texel)*4.0;",
|
|
141
|
+
"color+=(tap(uv,vec2<f32>(-1.0,0.0),texel)+tap(uv,vec2<f32>(1.0,0.0),texel)",
|
|
142
|
+
"+tap(uv,vec2<f32>(0.0,-1.0),texel)+tap(uv,vec2<f32>(0.0,1.0),texel))*2.0;",
|
|
143
|
+
"color+=tap(uv,vec2<f32>(-1.0,-1.0),texel)+tap(uv,vec2<f32>(1.0,-1.0),texel)",
|
|
144
|
+
"+tap(uv,vec2<f32>(-1.0,1.0),texel)+tap(uv,vec2<f32>(1.0,1.0),texel);",
|
|
145
|
+
"return vec4<f32>(color*(bloom.params.x/16.0),bloom.params.y);",
|
|
146
|
+
"}"
|
|
147
|
+
].join("\n");
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Writes every pass's uniforms for a tuning.
|
|
151
|
+
*
|
|
152
|
+
* @remarks
|
|
153
|
+
* Laid out as `HDR_BLOOM_MIP_COUNT` downsample blocks, then `HDR_BLOOM_MIP_COUNT − 1` upsample
|
|
154
|
+
* blocks (smallest first), then the composite: the order the tasks run in. Values are clamped to
|
|
155
|
+
* their documented ranges, so an inspector typo cannot blow the frame up.
|
|
156
|
+
*
|
|
157
|
+
* @param tuning - The values.
|
|
158
|
+
* @param out - `(2 · HDR_BLOOM_MIP_COUNT) · 4` floats, overwritten.
|
|
159
|
+
*
|
|
160
|
+
* @internal
|
|
161
|
+
*/
|
|
162
|
+
function writeHdrBloomUniforms(tuning, out) {
|
|
163
|
+
const threshold = Math.max(0, tuning.threshold);
|
|
164
|
+
const radius = Math.min(1, Math.max(0, tuning.radius));
|
|
165
|
+
const intensity = Math.max(0, tuning.intensity);
|
|
166
|
+
out.fill(0);
|
|
167
|
+
for (let level = 0; level < 6; level += 1) {
|
|
168
|
+
const base = level * UNIFORM_FLOATS;
|
|
169
|
+
out[base] = threshold;
|
|
170
|
+
out[base + 1] = threshold * .5;
|
|
171
|
+
out[base + 2] = level === 0 ? 1 : 0;
|
|
172
|
+
}
|
|
173
|
+
for (let step = 0; step < 5; step += 1) {
|
|
174
|
+
const base = (6 + step) * UNIFORM_FLOATS;
|
|
175
|
+
out[base] = radius;
|
|
176
|
+
out[base + 1] = radius;
|
|
177
|
+
}
|
|
178
|
+
const composite = 44;
|
|
179
|
+
out[composite] = intensity;
|
|
180
|
+
out[45] = threshold > 0 ? 0 : Math.min(1, intensity);
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Builds the HDR bloom chain and inserts it before the HDR output pass.
|
|
184
|
+
*
|
|
185
|
+
* @remarks
|
|
186
|
+
* Before the scene is registered the tasks are only inserted, and `registerScene`'s build records
|
|
187
|
+
* them in order; after, each is recorded on the spot (`buildFrameGraphTask`), as
|
|
188
|
+
* `appendPostProcessTask` in `./post-process.ts` does.
|
|
189
|
+
*
|
|
190
|
+
* @param engine - The engine, which is also the primary surface.
|
|
191
|
+
* @param scene - The scene whose frame graph holds the HDR output pass.
|
|
192
|
+
* @param hdr - The HDR half of the scene's presenter.
|
|
193
|
+
* @param isFrameGraphBuilt - Whether the scene has been registered.
|
|
194
|
+
* @returns The chain, enabled, with zero tuning until {@link HdrBloom.apply} runs.
|
|
195
|
+
*
|
|
196
|
+
* @internal
|
|
197
|
+
*/
|
|
198
|
+
function installHdrBloom(engine, scene, hdr, isFrameGraphBuilt) {
|
|
199
|
+
const mips = [];
|
|
200
|
+
for (let level = 0; level < 6; level += 1) mips.push(createSurfaceRenderTargetTexture(engine, {
|
|
201
|
+
lbl: `ignifx:bloom-mip-${String(level)}`,
|
|
202
|
+
format: HDR_BLOOM_FORMAT,
|
|
203
|
+
samples: 1,
|
|
204
|
+
size: {
|
|
205
|
+
surface: engine,
|
|
206
|
+
scale: .5 ** (level + 1)
|
|
207
|
+
}
|
|
208
|
+
}));
|
|
209
|
+
const mipAt = (level) => {
|
|
210
|
+
const mip = mips[level];
|
|
211
|
+
if (mip === void 0) throw new RangeError(`HDR bloom has no mip ${String(level)}.`);
|
|
212
|
+
return mip;
|
|
213
|
+
};
|
|
214
|
+
const downsample = bloomDownsampleWgsl();
|
|
215
|
+
const upsample = bloomUpsampleWgsl();
|
|
216
|
+
const passes = [];
|
|
217
|
+
const addPass = (name, fragmentWGSL, source, target) => {
|
|
218
|
+
const blended = fragmentWGSL === upsample;
|
|
219
|
+
const effect = createEffectWrapper(engine, {
|
|
220
|
+
name,
|
|
221
|
+
fragmentWGSL,
|
|
222
|
+
bindings: [
|
|
223
|
+
{
|
|
224
|
+
name: "bloom",
|
|
225
|
+
binding: 0,
|
|
226
|
+
kind: "uniform",
|
|
227
|
+
uniformByteLength: 16
|
|
228
|
+
},
|
|
229
|
+
{
|
|
230
|
+
name: "source",
|
|
231
|
+
binding: 1,
|
|
232
|
+
kind: "texture"
|
|
233
|
+
},
|
|
234
|
+
{
|
|
235
|
+
name: "sourceSampler",
|
|
236
|
+
binding: 2,
|
|
237
|
+
kind: "sampler",
|
|
238
|
+
textureBinding: 1
|
|
239
|
+
}
|
|
240
|
+
],
|
|
241
|
+
...blended ? { blend: MIX_BLEND } : {}
|
|
242
|
+
});
|
|
243
|
+
setEffectTexture(effect, 1, source());
|
|
244
|
+
setEffectUniforms(effect, new Float32Array(UNIFORM_FLOATS));
|
|
245
|
+
const task = createEffectRenderTask({
|
|
246
|
+
name,
|
|
247
|
+
effect,
|
|
248
|
+
target,
|
|
249
|
+
clear: !blended
|
|
250
|
+
}, engine, scene);
|
|
251
|
+
passes.push({
|
|
252
|
+
effect,
|
|
253
|
+
task,
|
|
254
|
+
source
|
|
255
|
+
});
|
|
256
|
+
};
|
|
257
|
+
for (let level = 0; level < 6; level += 1) {
|
|
258
|
+
const source = level === 0 ? () => hdr.sceneTargetTexture.texture : () => mipAt(level - 1).texture;
|
|
259
|
+
addPass(`ignifx:bloom-down-${String(level)}`, downsample, source, mipAt(level).rt);
|
|
260
|
+
}
|
|
261
|
+
for (let level = 4; level >= 0; level -= 1) addPass(`ignifx:bloom-up-${String(level)}`, upsample, () => mipAt(level + 1).texture, mipAt(level).rt);
|
|
262
|
+
addPass("ignifx:bloom-composite", upsample, () => mipAt(0).texture, hdr.sceneTargetTexture.rt);
|
|
263
|
+
for (const pass of passes) hdr.insertLinearTask(pass.task, isFrameGraphBuilt);
|
|
264
|
+
const rebind = () => {
|
|
265
|
+
for (const pass of passes) setEffectTexture(pass.effect, 1, pass.source());
|
|
266
|
+
};
|
|
267
|
+
const unsubscribe = [hdr.sceneTargetTexture, ...mips].map((target) => onRenderTargetTextureResize(target, rebind));
|
|
268
|
+
const uniforms = new Float32Array(passes.length * UNIFORM_FLOATS);
|
|
269
|
+
const scratch = new Float32Array(UNIFORM_FLOATS);
|
|
270
|
+
let isDisposed = false;
|
|
271
|
+
let applied = {
|
|
272
|
+
intensity: NaN,
|
|
273
|
+
radius: NaN,
|
|
274
|
+
threshold: NaN
|
|
275
|
+
};
|
|
276
|
+
return {
|
|
277
|
+
mips: mips.map((mip) => mip.texture),
|
|
278
|
+
taskCount: passes.length,
|
|
279
|
+
setEnabled(enabled) {
|
|
280
|
+
for (const pass of passes) pass.task.executionEnabled = enabled && !isDisposed;
|
|
281
|
+
},
|
|
282
|
+
apply(tuning) {
|
|
283
|
+
if (isDisposed || applied.intensity === tuning.intensity && applied.radius === tuning.radius && applied.threshold === tuning.threshold) return;
|
|
284
|
+
applied = {
|
|
285
|
+
intensity: tuning.intensity,
|
|
286
|
+
radius: tuning.radius,
|
|
287
|
+
threshold: tuning.threshold
|
|
288
|
+
};
|
|
289
|
+
writeHdrBloomUniforms(tuning, uniforms);
|
|
290
|
+
for (let index = 0; index < passes.length; index += 1) {
|
|
291
|
+
const pass = passes[index];
|
|
292
|
+
if (pass === void 0) continue;
|
|
293
|
+
scratch.set(uniforms.subarray(index * UNIFORM_FLOATS, (index + 1) * UNIFORM_FLOATS));
|
|
294
|
+
setEffectUniforms(pass.effect, scratch);
|
|
295
|
+
}
|
|
296
|
+
},
|
|
297
|
+
dispose() {
|
|
298
|
+
if (isDisposed) return;
|
|
299
|
+
isDisposed = true;
|
|
300
|
+
for (const stop of unsubscribe) stop();
|
|
301
|
+
for (const pass of passes) {
|
|
302
|
+
pass.task.executionEnabled = false;
|
|
303
|
+
pass.task.record = inertRecord;
|
|
304
|
+
disposeEffectWrapper(pass.effect);
|
|
305
|
+
}
|
|
306
|
+
for (const mip of mips) disposeRenderTargetTexture(mip);
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
/** What a disposed pass records: nothing. */
|
|
311
|
+
function inertRecord() {}
|
|
312
|
+
//#endregion
|
|
313
|
+
export { HDR_BLOOM_FORMAT, HDR_BLOOM_MIP_COUNT, bloomDownsampleWgsl, bloomUpsampleWgsl, installHdrBloom, writeHdrBloomUniforms };
|
|
314
|
+
|
|
315
|
+
//# sourceMappingURL=bloom-hdr-CLtQj-oY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bloom-hdr-CLtQj-oY.js","names":[],"sources":["../src/lite/gpu/bloom-hdr.ts"],"sourcesContent":["import {\n createEffectRenderTask,\n createEffectWrapper,\n createSurfaceRenderTargetTexture,\n disposeEffectWrapper,\n disposeRenderTargetTexture,\n onRenderTargetTextureResize,\n setEffectTexture,\n setEffectUniforms,\n} from \"@babylonjs/lite\";\nimport type { HdrOutputHandle } from \"./render-path.js\";\nimport type {\n EffectWrapper,\n EngineContext,\n RenderTarget,\n RenderTargetTextureResult,\n SceneContext,\n Task,\n Texture2D,\n} from \"@babylonjs/lite\";\n\n/**\n * HDR bloom (`docs/plan/2026-11-gi-phase-1-execution-plan.md`, step G12): a downsample/upsample\n * chain on the linear `rgba16float` scene target, recorded before the HDR output pass so the glow\n * is tone mapped with the rest of the frame. Its own chunk: `../../render/hdr-bloom-support.ts`\n * imports it only when a `PostProcessStack` asks for bloom under `rendering.hdr`\n * (`CONSTITUTION.md` §2.5).\n *\n * ```text\n * scene → hdr ─ down₀ → mip₀ ─ down₁ → mip₁ … → mip₅\n * mip₄ += up(mip₅) … mip₀ += up(mip₁)\n * hdr = mix(hdr, up(mip₀), intensity) ──→ output pass\n * ```\n *\n * - **Downsample** is the 13-tap filter of Jimenez, \"Next generation post processing in Call of\n * Duty: Advanced Warfare\" (SIGGRAPH 2014): five overlapping 2×2 boxes, the centre one weighted\n * 0.5. The first level weights each box by `1 / (1 + luma)` (Karis average), so one very bright\n * texel cannot flicker into a frame-sized blob, and applies the optional soft-knee threshold.\n * - **Upsample** is a 9-tap tent, blended into the next larger mip as\n * `mip = mix(mip, tent(smaller), radius)`, so `radius` decides how much of the wide, low mips\n * reaches the image while the weights still sum to one.\n * - **Composite** writes into the HDR target itself through the blend unit, so the output pass's\n * input never changes and nothing is rebound: `hdr = mix(hdr, bloom, intensity)` with no\n * threshold (energy-conserving: the image is redistributed, not brightened), `hdr += bloom ·\n * intensity` with one.\n * - Each mip is a surface-scaled target (`{ surface, scale }`), so a resize reallocates it with\n * the frame graph; the resize callbacks rebind the readers' bind groups.\n * - Lite has no task removal, so {@link HdrBloom.dispose} disables the tasks and makes their\n * `record` a no-op: a later frame-graph rebuild still walks them.\n */\n\n/**\n * How many mips the chain builds: half resolution down to 1/64.\n *\n * @internal\n */\nexport const HDR_BLOOM_MIP_COUNT = 6;\n\n/**\n * The format of every mip; the same as the scene target, so values above 1 survive.\n *\n * @internal\n */\nexport const HDR_BLOOM_FORMAT: GPUTextureFormat = \"rgba16float\";\n\n/** Uniform floats per pass: one `vec4`. */\nconst UNIFORM_FLOATS = 4;\n\n/**\n * The tuning a `PostProcessStack`'s `bloom` record feeds the chain.\n *\n * @internal\n */\nexport interface HdrBloomTuning {\n /** How much glow is mixed in, 0–1. */\n readonly intensity: number;\n /** How far the glow spreads, 0–1: the weight of each lower mip when it is upsampled. */\n readonly radius: number;\n /** The linear luminance below which nothing glows; `0` lets every pixel contribute. */\n readonly threshold: number;\n}\n\n/**\n * A recorded HDR bloom chain.\n *\n * @internal\n */\nexport interface HdrBloom {\n /** The mip chain, largest first. */\n readonly mips: readonly Texture2D[];\n /** How many frame-graph tasks it recorded. */\n readonly taskCount: number;\n /**\n * Switches every task of the chain on or off.\n *\n * @param enabled - `false` to skip the chain; the HDR target then reaches the output pass as is.\n */\n setEnabled(enabled: boolean): void;\n /**\n * Uploads the tuning, when it changed.\n *\n * @param tuning - The values.\n */\n apply(tuning: HdrBloomTuning): void;\n /** Disables the tasks, makes them inert to a rebuild, and frees the mips and effects. */\n dispose(): void;\n}\n\n/** The blend that turns a pass's `vec4(rgb, a)` into `dst·(1 − a) + rgb`. */\nconst MIX_BLEND: GPUBlendState = {\n color: { operation: \"add\", srcFactor: \"one\", dstFactor: \"one-minus-src-alpha\" },\n alpha: { operation: \"add\", srcFactor: \"zero\", dstFactor: \"one\" },\n};\n\n/**\n * The uniform block, texture, sampler and helpers every pass declares.\n *\n * @returns The WGSL.\n */\nfunction passHeaderWgsl(): string {\n return [\n \"struct BloomUniforms{params:vec4<f32>};\",\n \"@group(0)@binding(0)var<uniform>bloom:BloomUniforms;\",\n \"@group(0)@binding(1)var source:texture_2d<f32>;\",\n \"@group(0)@binding(2)var sourceSampler:sampler;\",\n // Lite's fullscreen triangle puts uv (0,0) at the bottom left; textures start at the top left.\n \"fn bloomUv(fragment:EffectVertexOutput)->vec2<f32>{return vec2<f32>(fragment.uv.x,1.0-fragment.uv.y);}\",\n \"fn tap(uv:vec2<f32>,offset:vec2<f32>,texel:vec2<f32>)->vec3<f32>{\",\n \"let c=textureSampleLevel(source,sourceSampler,uv+offset*texel,0.0).rgb;\",\n \"return min(max(c,vec3<f32>(0.0)),vec3<f32>(65000.0));\",\n \"}\",\n ].join(\"\\n\");\n}\n\n/**\n * The downsample pass: 13 taps, a Karis average and the soft-knee threshold on the first level.\n *\n * @remarks\n * `params` is `(threshold, knee, isFirstLevel, unused)`.\n *\n * @returns The WGSL, with Lite's `effectFragment` entry point.\n *\n * @internal\n */\nexport function bloomDownsampleWgsl(): string {\n return [\n passHeaderWgsl(),\n \"fn boxWeight(c:vec3<f32>,first:bool)->f32{\",\n \"if(!first){return 1.0;}\",\n \"return 1.0/(1.0+dot(c,vec3<f32>(0.2126,0.7152,0.0722)));\",\n \"}\",\n \"fn knee(c:vec3<f32>,threshold:f32,soft:f32)->vec3<f32>{\",\n \"if(threshold<=0.0){return c;}\",\n \"let b=max(c.r,max(c.g,c.b));\",\n \"var s=clamp(b-threshold+soft,0.0,2.0*soft);\",\n \"s=s*s/(4.0*soft+1e-5);\",\n \"return c*(max(s,b-threshold)/max(b,1e-5));\",\n \"}\",\n \"@fragment fn effectFragment(fragment:EffectVertexOutput)->@location(0)vec4<f32>{\",\n \"let uv=bloomUv(fragment);\",\n \"let texel=1.0/vec2<f32>(textureDimensions(source,0));\",\n \"let first=bloom.params.z>0.5;\",\n \"let a=tap(uv,vec2<f32>(-2.0,-2.0),texel);let b=tap(uv,vec2<f32>(0.0,-2.0),texel);\",\n \"let c=tap(uv,vec2<f32>(2.0,-2.0),texel);let d=tap(uv,vec2<f32>(-2.0,0.0),texel);\",\n \"let e=tap(uv,vec2<f32>(0.0,0.0),texel);let f=tap(uv,vec2<f32>(2.0,0.0),texel);\",\n \"let g=tap(uv,vec2<f32>(-2.0,2.0),texel);let h=tap(uv,vec2<f32>(0.0,2.0),texel);\",\n \"let i=tap(uv,vec2<f32>(2.0,2.0),texel);let j=tap(uv,vec2<f32>(-1.0,-1.0),texel);\",\n \"let k=tap(uv,vec2<f32>(1.0,-1.0),texel);let l=tap(uv,vec2<f32>(-1.0,1.0),texel);\",\n \"let m=tap(uv,vec2<f32>(1.0,1.0),texel);\",\n \"let g0=(j+k+l+m)*0.25;let g1=(a+b+d+e)*0.25;let g2=(b+c+e+f)*0.25;\",\n \"let g3=(d+e+g+h)*0.25;let g4=(e+f+h+i)*0.25;\",\n \"let w0=0.5*boxWeight(g0,first);let w1=0.125*boxWeight(g1,first);let w2=0.125*boxWeight(g2,first);\",\n \"let w3=0.125*boxWeight(g3,first);let w4=0.125*boxWeight(g4,first);\",\n \"var color=(g0*w0+g1*w1+g2*w2+g3*w3+g4*w4)/(w0+w1+w2+w3+w4);\",\n \"if(first){color=knee(color,bloom.params.x,bloom.params.y);}\",\n \"return vec4<f32>(color,1.0);\",\n \"}\",\n ].join(\"\\n\");\n}\n\n/**\n * The upsample and composite pass: a 9-tap tent of the smaller mip, scaled, with the blend weight\n * in alpha.\n *\n * @remarks\n * `params` is `(scale, alpha, unused, unused)`; with {@link MIX_BLEND} the target becomes\n * `target·(1 − alpha) + tent·scale`.\n *\n * @returns The WGSL, with Lite's `effectFragment` entry point.\n *\n * @internal\n */\nexport function bloomUpsampleWgsl(): string {\n return [\n passHeaderWgsl(),\n \"@fragment fn effectFragment(fragment:EffectVertexOutput)->@location(0)vec4<f32>{\",\n \"let uv=bloomUv(fragment);\",\n \"let texel=1.0/vec2<f32>(textureDimensions(source,0));\",\n \"var color=tap(uv,vec2<f32>(0.0,0.0),texel)*4.0;\",\n \"color+=(tap(uv,vec2<f32>(-1.0,0.0),texel)+tap(uv,vec2<f32>(1.0,0.0),texel)\",\n \"+tap(uv,vec2<f32>(0.0,-1.0),texel)+tap(uv,vec2<f32>(0.0,1.0),texel))*2.0;\",\n \"color+=tap(uv,vec2<f32>(-1.0,-1.0),texel)+tap(uv,vec2<f32>(1.0,-1.0),texel)\",\n \"+tap(uv,vec2<f32>(-1.0,1.0),texel)+tap(uv,vec2<f32>(1.0,1.0),texel);\",\n \"return vec4<f32>(color*(bloom.params.x/16.0),bloom.params.y);\",\n \"}\",\n ].join(\"\\n\");\n}\n\n/**\n * Writes every pass's uniforms for a tuning.\n *\n * @remarks\n * Laid out as `HDR_BLOOM_MIP_COUNT` downsample blocks, then `HDR_BLOOM_MIP_COUNT − 1` upsample\n * blocks (smallest first), then the composite: the order the tasks run in. Values are clamped to\n * their documented ranges, so an inspector typo cannot blow the frame up.\n *\n * @param tuning - The values.\n * @param out - `(2 · HDR_BLOOM_MIP_COUNT) · 4` floats, overwritten.\n *\n * @internal\n */\nexport function writeHdrBloomUniforms(tuning: HdrBloomTuning, out: Float32Array): void {\n const threshold = Math.max(0, tuning.threshold);\n const radius = Math.min(1, Math.max(0, tuning.radius));\n const intensity = Math.max(0, tuning.intensity);\n out.fill(0);\n for (let level = 0; level < HDR_BLOOM_MIP_COUNT; level += 1) {\n const base = level * UNIFORM_FLOATS;\n out[base] = threshold;\n out[base + 1] = threshold * 0.5;\n out[base + 2] = level === 0 ? 1 : 0;\n }\n for (let step = 0; step < HDR_BLOOM_MIP_COUNT - 1; step += 1) {\n const base = (HDR_BLOOM_MIP_COUNT + step) * UNIFORM_FLOATS;\n out[base] = radius;\n out[base + 1] = radius;\n }\n const composite = (2 * HDR_BLOOM_MIP_COUNT - 1) * UNIFORM_FLOATS;\n out[composite] = intensity;\n // With a threshold only the highlights are in the chain, so the glow is added; without one the\n // chain holds the whole image and mixing keeps the frame's energy.\n out[composite + 1] = threshold > 0 ? 0 : Math.min(1, intensity);\n}\n\n/** One pass of the chain: its effect, the texture it reads and its task. */\ninterface BloomPass {\n readonly effect: EffectWrapper;\n readonly task: Task;\n readonly source: () => Texture2D;\n}\n\n/**\n * Builds the HDR bloom chain and inserts it before the HDR output pass.\n *\n * @remarks\n * Before the scene is registered the tasks are only inserted, and `registerScene`'s build records\n * them in order; after, each is recorded on the spot (`buildFrameGraphTask`), as\n * `appendPostProcessTask` in `./post-process.ts` does.\n *\n * @param engine - The engine, which is also the primary surface.\n * @param scene - The scene whose frame graph holds the HDR output pass.\n * @param hdr - The HDR half of the scene's presenter.\n * @param isFrameGraphBuilt - Whether the scene has been registered.\n * @returns The chain, enabled, with zero tuning until {@link HdrBloom.apply} runs.\n *\n * @internal\n */\nexport function installHdrBloom(\n engine: EngineContext,\n scene: SceneContext,\n hdr: HdrOutputHandle,\n isFrameGraphBuilt: boolean,\n): HdrBloom {\n const mips: RenderTargetTextureResult[] = [];\n for (let level = 0; level < HDR_BLOOM_MIP_COUNT; level += 1) {\n mips.push(\n createSurfaceRenderTargetTexture(engine, {\n lbl: `ignifx:bloom-mip-${String(level)}`,\n format: HDR_BLOOM_FORMAT,\n samples: 1,\n size: { surface: engine, scale: 0.5 ** (level + 1) },\n }),\n );\n }\n const mipAt = (level: number): RenderTargetTextureResult => {\n const mip = mips[level];\n if (mip === undefined) {\n throw new RangeError(`HDR bloom has no mip ${String(level)}.`);\n }\n return mip;\n };\n const downsample = bloomDownsampleWgsl();\n const upsample = bloomUpsampleWgsl();\n const passes: BloomPass[] = [];\n const addPass = (name: string, fragmentWGSL: string, source: () => Texture2D, target: RenderTarget): void => {\n const blended = fragmentWGSL === upsample;\n const effect = createEffectWrapper(engine, {\n name,\n fragmentWGSL,\n bindings: [\n { name: \"bloom\", binding: 0, kind: \"uniform\", uniformByteLength: UNIFORM_FLOATS * 4 },\n { name: \"source\", binding: 1, kind: \"texture\" },\n { name: \"sourceSampler\", binding: 2, kind: \"sampler\", textureBinding: 1 },\n ],\n ...(blended ? { blend: MIX_BLEND } : {}),\n });\n setEffectTexture(effect, 1, source());\n setEffectUniforms(effect, new Float32Array(UNIFORM_FLOATS));\n const task = createEffectRenderTask({ name, effect, target, clear: !blended }, engine, scene);\n passes.push({ effect, task, source });\n };\n for (let level = 0; level < HDR_BLOOM_MIP_COUNT; level += 1) {\n const source =\n level === 0 ? (): Texture2D => hdr.sceneTargetTexture.texture : (): Texture2D => mipAt(level - 1).texture;\n addPass(`ignifx:bloom-down-${String(level)}`, downsample, source, mipAt(level).rt);\n }\n for (let level = HDR_BLOOM_MIP_COUNT - 2; level >= 0; level -= 1) {\n addPass(`ignifx:bloom-up-${String(level)}`, upsample, () => mipAt(level + 1).texture, mipAt(level).rt);\n }\n addPass(\"ignifx:bloom-composite\", upsample, () => mipAt(0).texture, hdr.sceneTargetTexture.rt);\n\n // After every linear task already in place (TAA among them), right before the output pass.\n for (const pass of passes) {\n hdr.insertLinearTask(pass.task, isFrameGraphBuilt);\n }\n\n // A resize swaps the textures behind the facades; a wrapper's cached bind group keeps the old\n // view until a texture write marks it dirty.\n const rebind = (): void => {\n for (const pass of passes) {\n setEffectTexture(pass.effect, 1, pass.source());\n }\n };\n const unsubscribe = [hdr.sceneTargetTexture, ...mips].map((target) => onRenderTargetTextureResize(target, rebind));\n\n const uniforms = new Float32Array(passes.length * UNIFORM_FLOATS);\n const scratch = new Float32Array(UNIFORM_FLOATS);\n let isDisposed = false;\n let applied: HdrBloomTuning = { intensity: Number.NaN, radius: Number.NaN, threshold: Number.NaN };\n return {\n mips: mips.map((mip) => mip.texture),\n taskCount: passes.length,\n setEnabled(enabled: boolean): void {\n for (const pass of passes) {\n pass.task.executionEnabled = enabled && !isDisposed;\n }\n },\n apply(tuning: HdrBloomTuning): void {\n if (\n isDisposed ||\n (applied.intensity === tuning.intensity &&\n applied.radius === tuning.radius &&\n applied.threshold === tuning.threshold)\n ) {\n return;\n }\n applied = { intensity: tuning.intensity, radius: tuning.radius, threshold: tuning.threshold };\n writeHdrBloomUniforms(tuning, uniforms);\n for (let index = 0; index < passes.length; index += 1) {\n const pass = passes[index];\n if (pass === undefined) {\n continue;\n }\n scratch.set(uniforms.subarray(index * UNIFORM_FLOATS, (index + 1) * UNIFORM_FLOATS));\n setEffectUniforms(pass.effect, scratch);\n }\n },\n dispose(): void {\n if (isDisposed) {\n return;\n }\n isDisposed = true;\n for (const stop of unsubscribe) {\n stop();\n }\n for (const pass of passes) {\n pass.task.executionEnabled = false;\n // Lite cannot remove a task, and a frame-graph rebuild records every task, disabled or not.\n pass.task.record = inertRecord;\n disposeEffectWrapper(pass.effect);\n }\n for (const mip of mips) {\n disposeRenderTargetTexture(mip);\n }\n },\n };\n}\n\n/** What a disposed pass records: nothing. */\nfunction inertRecord(): void {\n // Intentionally empty; see `HdrBloom.dispose`.\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,MAAa,sBAAsB;;;;;;AAOnC,MAAa,mBAAqC;;AAGlD,MAAM,iBAAiB;;AA2CvB,MAAM,YAA2B;CAC/B,OAAO;EAAE,WAAW;EAAO,WAAW;EAAO,WAAW;CAAsB;CAC9E,OAAO;EAAE,WAAW;EAAO,WAAW;EAAQ,WAAW;CAAM;AACjE;;;;;;AAOA,SAAS,iBAAyB;CAChC,OAAO;EACL;EACA;EACA;EACA;EAEA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,IAAI;AACb;;;;;;;;;;;AAYA,SAAgB,sBAA8B;CAC5C,OAAO;EACL,eAAe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,CA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