@threenative/core 0.3.4 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/capabilities.json +1505 -79
  2. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  3. package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  4. package/dist/{game-CljaDv4D.d.ts → game-Bj8G1wmD.d.ts} +102 -11
  5. package/dist/hot.d.ts +4 -4
  6. package/dist/index.d.ts +712 -118
  7. package/dist/index.js +12423 -4955
  8. package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
  9. package/dist/playtest.d.ts +6 -10
  10. package/dist/playtest.js +47 -24
  11. package/dist/react-css.d.ts +62 -0
  12. package/dist/react-css.js +591 -0
  13. package/dist/react.d.ts +2 -2
  14. package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
  15. package/dist/terrain-jobs-worker.d.ts +2 -0
  16. package/dist/terrain-jobs-worker.js +130 -0
  17. package/dist/ui-layer.js +59 -8
  18. package/dist/world.d.ts +766 -73
  19. package/dist/world.js +9307 -3543
  20. package/gpl/recipes/export_world.py +18 -1
  21. package/mcp/blender-server.mjs +7 -4
  22. package/mcp/blender.mjs +3 -4
  23. package/mcp/engine-server.mjs +2 -2
  24. package/mcp/servers.mjs +4 -4
  25. package/package.json +15 -9
  26. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  27. package/patches/three@0.185.1.patch +6594 -700
  28. package/scripts/apply-three-patch.mjs +62 -4
  29. package/src/animation-blend.ts +264 -0
  30. package/src/animation-composition.ts +362 -0
  31. package/src/animation-layers.ts +260 -0
  32. package/src/animation-root-motion.ts +283 -0
  33. package/src/animation.ts +896 -0
  34. package/src/assets.ts +1303 -0
  35. package/src/atmosphere/index.ts +335 -0
  36. package/src/atmosphere/luts.ts +298 -0
  37. package/src/atmosphere/params.ts +323 -0
  38. package/src/audio.ts +912 -0
  39. package/src/billboard.ts +124 -0
  40. package/src/bone-lengths.ts +157 -0
  41. package/src/camera-shake.ts +116 -0
  42. package/src/canvas-layer.ts +47 -0
  43. package/src/clip-audit.ts +401 -0
  44. package/src/clustered-batch.ts +492 -0
  45. package/src/clustered-mesh.ts +638 -0
  46. package/src/compute-driven.ts +176 -0
  47. package/src/compute-timing.ts +318 -0
  48. package/src/config.ts +593 -0
  49. package/src/debug.ts +82 -0
  50. package/src/engine-render-hook.ts +25 -0
  51. package/src/entities.ts +79 -0
  52. package/src/entity-snapshot.ts +53 -0
  53. package/src/flight.ts +683 -0
  54. package/src/fluid-field.ts +748 -0
  55. package/src/fluid-particles.ts +1253 -0
  56. package/src/frame-budget.ts +1368 -0
  57. package/src/game.ts +2390 -0
  58. package/src/geometry-capture.ts +1098 -0
  59. package/src/gpu-class.ts +160 -0
  60. package/src/gpu-frame-observation.ts +424 -0
  61. package/src/gpu-readback.ts +143 -0
  62. package/src/gpu-scene-bvh.ts +464 -0
  63. package/src/grounding.ts +100 -0
  64. package/src/hot.ts +161 -0
  65. package/src/import-meta.d.ts +13 -0
  66. package/src/index.ts +1536 -0
  67. package/src/input.ts +690 -0
  68. package/src/instanced-batch-lod.ts +283 -0
  69. package/src/instanced-batch.ts +274 -0
  70. package/src/interpolation.ts +129 -0
  71. package/src/launch-diagnostics.ts +161 -0
  72. package/src/loop.ts +564 -0
  73. package/src/matrix-world.ts +245 -0
  74. package/src/merge-parts.ts +812 -0
  75. package/src/model-lod.ts +1315 -0
  76. package/src/net-protocol.ts +333 -0
  77. package/src/net-session.ts +477 -0
  78. package/src/net.ts +80 -0
  79. package/src/ocean/fft.ts +72 -0
  80. package/src/ocean/spectral.ts +728 -0
  81. package/src/particle-significance.ts +102 -0
  82. package/src/particles.ts +648 -0
  83. package/src/path-follow.ts +175 -0
  84. package/src/picking.ts +250 -0
  85. package/src/pipeline-census.ts +1566 -0
  86. package/src/platform.ts +210 -0
  87. package/src/playtest.ts +839 -0
  88. package/src/pointer-events.ts +411 -0
  89. package/src/pose-measure.ts +435 -0
  90. package/src/profiling/FrameCounters.ts +231 -0
  91. package/src/profiling/Spans.ts +548 -0
  92. package/src/profiling/opacity-convention.ts +21 -0
  93. package/src/profiling/render-list-validate.ts +175 -0
  94. package/src/profiling/render-trap-audit.ts +84 -0
  95. package/src/profiling/scene-warning.ts +190 -0
  96. package/src/profiling/span-probes.ts +191 -0
  97. package/src/profiling/unlit-foliage-warning.ts +149 -0
  98. package/src/projection-apply.ts +1529 -0
  99. package/src/projection-marker.ts +142 -0
  100. package/src/projection-plan.ts +1258 -0
  101. package/src/projection-skinned.ts +419 -0
  102. package/src/projection-stability.ts +409 -0
  103. package/src/projection-uniform.ts +328 -0
  104. package/src/random.ts +41 -0
  105. package/src/react-css.ts +604 -0
  106. package/src/react-glyphs.ts +114 -0
  107. package/src/react-host.ts +576 -0
  108. package/src/react-layout.ts +265 -0
  109. package/src/react.ts +60 -0
  110. package/src/render/alpha-antialiasing.ts +159 -0
  111. package/src/render/batched-velocity.ts +126 -0
  112. package/src/render/chain.ts +1021 -0
  113. package/src/render/daylight.ts +189 -0
  114. package/src/render/depth-pyramid.ts +596 -0
  115. package/src/render/foliage-alpha.ts +166 -0
  116. package/src/render/material-key.ts +60 -0
  117. package/src/render/mesh-pool.ts +144 -0
  118. package/src/render/probe-volume.ts +1668 -0
  119. package/src/render/resolution-subrect.ts +253 -0
  120. package/src/render/velocity.ts +442 -0
  121. package/src/render/virtual-shadow-pages.ts +827 -0
  122. package/src/render/virtual-shadow-partial.ts +174 -0
  123. package/src/render/virtual-shadow.ts +3330 -0
  124. package/src/render/world-impostor-surface.ts +722 -0
  125. package/src/render/world-impostor.ts +558 -0
  126. package/src/render-camera-cull.ts +441 -0
  127. package/src/render-pass-budget.ts +501 -0
  128. package/src/renderProjection.ts +758 -0
  129. package/src/renderer-config.ts +127 -0
  130. package/src/renderer.ts +1847 -0
  131. package/src/replay-protocol.ts +85 -0
  132. package/src/replay.ts +205 -0
  133. package/src/resolution-scaler.ts +819 -0
  134. package/src/rig-preparation.ts +271 -0
  135. package/src/ripple-field.ts +432 -0
  136. package/src/scale.ts +109 -0
  137. package/src/scene.ts +239 -0
  138. package/src/schedule.ts +155 -0
  139. package/src/skeletal-mesh.ts +61 -0
  140. package/src/skeleton.ts +100 -0
  141. package/src/snow-field.ts +744 -0
  142. package/src/softbody-topology.ts +269 -0
  143. package/src/softbody.ts +516 -0
  144. package/src/sprite-animator.ts +222 -0
  145. package/src/startup-readiness.ts +386 -0
  146. package/src/state.ts +66 -0
  147. package/src/static-transform.ts +274 -0
  148. package/src/storage-buffer.ts +253 -0
  149. package/src/streaming.ts +308 -0
  150. package/src/target-fps.ts +92 -0
  151. package/src/terrain-jobs-worker.ts +17 -0
  152. package/src/terrain-jobs.ts +353 -0
  153. package/src/textures.ts +39 -0
  154. package/src/tracers.ts +237 -0
  155. package/src/ui-bridge.ts +368 -0
  156. package/src/ui-hit-regions.ts +380 -0
  157. package/src/ui-layer.ts +83 -0
  158. package/src/ui-state.ts +220 -0
  159. package/src/version.ts +2 -0
  160. package/src/viewport.ts +253 -0
  161. package/src/warmup.ts +1357 -0
  162. package/src/water-surface.ts +384 -0
  163. package/src/wave-field.ts +524 -0
  164. package/src/world-capabilities.ts +131 -0
  165. package/src/world-cell-proxy.ts +392 -0
  166. package/src/world-cells.ts +10564 -0
  167. package/src/world-gpu-scene.ts +3354 -0
  168. package/src/world-heightmap.ts +82 -0
  169. package/src/world-package.ts +469 -0
  170. package/src/world-passes.ts +582 -0
  171. package/src/world-region.ts +17 -0
  172. package/src/world-terrain-splat.ts +564 -0
  173. package/src/world-tiles.ts +3826 -0
  174. package/src/world-topology.ts +370 -0
  175. package/src/world-validate.ts +48 -0
  176. package/src/world.ts +805 -0
@@ -0,0 +1,1668 @@
1
+ import {
2
+ Box2,
3
+ Box3,
4
+ type Camera,
5
+ type CoordinateSystem,
6
+ CubeCamera,
7
+ Mesh,
8
+ Object3D,
9
+ OrthographicCamera,
10
+ PlaneGeometry,
11
+ Scene,
12
+ Vector2,
13
+ Vector3,
14
+ } from "three";
15
+ import {
16
+ Fn,
17
+ clamp,
18
+ cubeTexture,
19
+ float,
20
+ floor,
21
+ int,
22
+ normalWorld,
23
+ normalize,
24
+ positionWorld,
25
+ texture,
26
+ texture3D,
27
+ uniform,
28
+ vec2,
29
+ vec3,
30
+ vec4,
31
+ viewportCoordinate,
32
+ } from "three/tsl";
33
+ import {
34
+ ClampToEdgeWrapping,
35
+ CubeRenderTarget,
36
+ Data3DTexture,
37
+ FloatType,
38
+ HalfFloatType,
39
+ LinearFilter,
40
+ NearestFilter,
41
+ NodeMaterial,
42
+ RGBAFormat,
43
+ RenderTarget,
44
+ RenderTarget3D,
45
+ } from "three/webgpu";
46
+ import type { Node } from "three/webgpu";
47
+ import type { IComputeDriven } from "../compute-driven.js";
48
+ import type { IRendererLike } from "../renderer.js";
49
+
50
+ /** The atlas has one copied edge texel on either side of each packed SH sub-volume. */
51
+ export const ATLAS_PADDING = 1;
52
+
53
+ /** The machine-readable marker emitted whenever the probe state changes. */
54
+ export const PROBE_VOLUME_MARKER = "TN_PROBE_VOLUME";
55
+
56
+ const SH_COEFFICIENT_COUNT = 9;
57
+ const SH_CHANNEL_COUNT = 3;
58
+ const PACKED_SUB_VOLUME_COUNT = 7;
59
+ const CUBE_FACE_COUNT = 6;
60
+ const CAPTURE_WORK_ITEMS_PER_PROBE = CUBE_FACE_COUNT + 2;
61
+ // The upstream shader ABI always samples a one-texel-padded layout. Keeping this independent from
62
+ // the storage constant makes a storage mutation observable at the public sampling boundary.
63
+ const SAMPLE_ATLAS_PADDING = 1;
64
+ const BYTES_PER_FLOAT = Float32Array.BYTES_PER_ELEMENT;
65
+ const BYTES_PER_TEXEL = 4 * BYTES_PER_FLOAT;
66
+ const BAKE_BUDGET_SLACK_MS = 0.5;
67
+ const SCENE_WARMUP_TIMEOUT_MS = 2_000;
68
+
69
+ type IVector3Like = { readonly x: number; readonly y: number; readonly z: number };
70
+ type IProbePosition = Vector3 | Node<"vec3">;
71
+
72
+ /** One RGB L2 spherical-harmonic coefficient, in the upstream probe ordering. */
73
+ export interface IProbeVolumeCoefficient {
74
+ readonly r: number;
75
+ readonly g: number;
76
+ readonly b: number;
77
+ }
78
+
79
+ /** Probe density in probes per world unit, either isotropic or per-axis. */
80
+ export type ProbeVolumeDensity = number | readonly [number, number, number] | IVector3Like;
81
+
82
+ export interface IProbeVolumeOptions {
83
+ /** World-space bounds; the volume does not move with the object after construction. */
84
+ readonly bounds: Box3 | { readonly min: IVector3Like; readonly max: IVector3Like };
85
+ /** Probe spacing expressed as probes per world unit. */
86
+ readonly density: ProbeVolumeDensity;
87
+ /** Optional device limit supplied by a host that knows it before construction. */
88
+ readonly maxTextureDimension3D?: number;
89
+ /** Alias for integrations that expose the WebGPU limit under a device-oriented name. */
90
+ readonly deviceTextureLimit?: number;
91
+ /** Maximum wall-clock work per render phase, in milliseconds. */
92
+ readonly bakeBudgetMs?: number;
93
+ /** Additional guard that keeps a clock-less host from processing an unbounded queue. */
94
+ readonly maxWorkItemsPerFrame?: number;
95
+ /** Resolution of each captured cube face. The static-lighting default is intentionally small. */
96
+ readonly cubemapSize?: number;
97
+ readonly near?: number;
98
+ readonly far?: number;
99
+ /** Additional indirect passes after the direct-light pass. */
100
+ readonly bounces?: number;
101
+ /** Injectable clock for deterministic scheduling tests. */
102
+ readonly now?: () => number;
103
+ readonly report?: (line: string) => void;
104
+ }
105
+
106
+ export interface IProbeVolumeBakeProgress {
107
+ readonly completed: number;
108
+ readonly total: number;
109
+ readonly fraction: number;
110
+ readonly probesCompleted: number;
111
+ readonly probesTotal: number;
112
+ readonly pass: number;
113
+ readonly passes: number;
114
+ }
115
+
116
+ export interface IProbeVolumeObservation {
117
+ readonly marker: typeof PROBE_VOLUME_MARKER;
118
+ readonly status: "unbaked" | "baking" | "ready";
119
+ readonly stale: boolean;
120
+ readonly unbaked: boolean;
121
+ /** `null` means no completed bake has established an age yet. */
122
+ readonly stalenessFrames: number | null;
123
+ readonly probeCount: number;
124
+ readonly atlasBytes: number;
125
+ readonly atlas: { readonly width: number; readonly height: number; readonly depth: number };
126
+ readonly bakeProgress: IProbeVolumeBakeProgress;
127
+ /** Wall-clock time spent by the most recent incremental render-phase slice. */
128
+ readonly bakeCostMs: number;
129
+ readonly bakeBudgetMs: number;
130
+ /** True while pass zero samples a black texture instead of a previous bake. */
131
+ readonly samplingIsolated: boolean;
132
+ }
133
+
134
+ /** Read a complete marker-shaped observation without accepting malformed data. */
135
+ export function readProbeVolumeObservation(value: unknown): IProbeVolumeObservation | undefined {
136
+ return isProbeVolumeObservation(value) ? value : undefined;
137
+ }
138
+
139
+ interface IProbeRenderer {
140
+ readonly autoClear?: boolean;
141
+ readonly compileAsync?: (scene: Object3D, camera: Camera) => Promise<void>;
142
+ readonly coordinateSystem?: CoordinateSystem;
143
+ readonly backend?: {
144
+ readonly device?: { readonly limits?: Record<string, unknown> };
145
+ };
146
+ readonly device?: { readonly limits?: Record<string, unknown> };
147
+ readonly shadowMap?: { autoUpdate: boolean; needsUpdate: boolean };
148
+ readonly toneMapping?: number;
149
+ readonly toneMappingExposure?: number;
150
+ readonly getRenderTarget?: () => unknown;
151
+ readonly getActiveCubeFace?: () => number;
152
+ readonly getActiveMipmapLevel?: () => number;
153
+ readonly reversedDepthBuffer?: boolean;
154
+ readonly clearDepth?: () => void;
155
+ readonly render: (scene: Object3D, camera: Camera) => void;
156
+ readonly copyTextureToTexture?: (
157
+ source: unknown,
158
+ destination: unknown,
159
+ sourceRegion?: unknown,
160
+ destinationPosition?: unknown,
161
+ ) => void;
162
+ readonly setRenderTarget: (
163
+ target: unknown,
164
+ activeCubeFace?: number,
165
+ activeMipmapLevel?: number,
166
+ ) => void;
167
+ readonly xr?: { enabled: boolean };
168
+ }
169
+
170
+ interface IPendingBake {
171
+ readonly scene: Scene;
172
+ passes: number;
173
+ pass: number;
174
+ phase: "capture" | "project" | "copy" | "repack";
175
+ cubeFaceIndex: number;
176
+ probeIndex: number;
177
+ repackIndex: number;
178
+ completedWork: number;
179
+ completedProbes: number;
180
+ totalWork: number;
181
+ }
182
+
183
+ interface IBakePromise {
184
+ readonly promise: Promise<void>;
185
+ readonly resolve: () => void;
186
+ readonly reject: (error: unknown) => void;
187
+ }
188
+
189
+ interface ISceneState {
190
+ readonly scene: Scene;
191
+ readonly matrixWorldAutoUpdate: boolean;
192
+ readonly shadowAutoUpdate?: boolean;
193
+ }
194
+
195
+ const PACKED_CHANNELS: readonly (readonly [number, number] | null)[] = [
196
+ [0, 0],
197
+ [0, 1],
198
+ [0, 2],
199
+ [1, 0],
200
+ [1, 1],
201
+ [1, 2],
202
+ [2, 0],
203
+ [2, 1],
204
+ [2, 2],
205
+ [3, 0],
206
+ [3, 1],
207
+ [3, 2],
208
+ [4, 0],
209
+ [4, 1],
210
+ [4, 2],
211
+ [5, 0],
212
+ [5, 1],
213
+ [5, 2],
214
+ [6, 0],
215
+ [6, 1],
216
+ [6, 2],
217
+ [7, 0],
218
+ [7, 1],
219
+ [7, 2],
220
+ [8, 0],
221
+ [8, 1],
222
+ [8, 2],
223
+ null,
224
+ ];
225
+
226
+ /**
227
+ * A WebGPU irradiance probe volume.
228
+ *
229
+ * The volume owns placement, GPU bake scheduling and a single padded atlas. It owns no light,
230
+ * material or colour: every coefficient comes from the scene rendered by its cube cameras. Add it
231
+ * through `ctx.add()` so `process()` runs in the render phase measured by `FrameBudget`.
232
+ *
233
+ * Bakes are static-lighting-first and explicit. Call `requestBake(scene)` after lights and static
234
+ * geometry are authored; a completed bake is reused until the game requests another one.
235
+ */
236
+ export class ProbeVolume extends Object3D implements IComputeDriven {
237
+ readonly isProbeVolume = true;
238
+ readonly processCadence = "render" as const;
239
+ readonly warmupNodes: readonly unknown[] = [];
240
+ readonly boundingBox: Box3;
241
+ readonly resolution: Vector3;
242
+ readonly #boundsSize: Vector3;
243
+ readonly #density: Vector3;
244
+ readonly #atlasDepth: number;
245
+ readonly #atlasBytes: number;
246
+ readonly #probeCount: number;
247
+ readonly #atlasData: Float32Array;
248
+ readonly #coefficients: Float32Array;
249
+ readonly #atlasNode;
250
+ readonly #emptyAtlasTexture: Data3DTexture;
251
+ readonly #boundsMinNode;
252
+ readonly #boundsSizeNode;
253
+ readonly #report: (line: string) => void;
254
+ readonly #now: () => number;
255
+ readonly #bakeBudgetMs: number;
256
+ readonly #maxWorkItemsPerFrame: number;
257
+ readonly #cubemapSize: number;
258
+ readonly #near: number;
259
+ readonly #far: number;
260
+ readonly #bounces: number;
261
+ #bakePasses: number;
262
+ #atlasTexture: Data3DTexture;
263
+ #renderer: IRendererLike | undefined;
264
+ #cubeRenderTarget: CubeRenderTarget | undefined;
265
+ #cubeCamera: CubeCamera | undefined;
266
+ #projectionTarget: RenderTarget | undefined;
267
+ #batchTarget: RenderTarget | undefined;
268
+ #atlasTarget: RenderTarget3D | undefined;
269
+ #quadScene: Scene | undefined;
270
+ #quadCamera: OrthographicCamera | undefined;
271
+ #quadMesh: Mesh | undefined;
272
+ #projectionMaterial: NodeMaterial | undefined;
273
+ #repackMaterials: NodeMaterial[] | undefined;
274
+ #repackSlice = uniform(0, "int");
275
+ #batchTextureNode: ReturnType<typeof texture> | undefined;
276
+ #gpuWarmupStarted = false;
277
+ #gpuWarmupSettled = true;
278
+ #sceneWarmupStarted = false;
279
+ #sceneWarmupSettled = true;
280
+ #pending: IPendingBake | undefined;
281
+ #bakePromise: IBakePromise | undefined;
282
+ #sceneState: ISceneState | undefined;
283
+ #status: IProbeVolumeObservation["status"] = "unbaked";
284
+ #stalenessFrames: number | null = null;
285
+ #lastBakeCostMs = 0;
286
+ #maxWorkItemCostMs = 0;
287
+ #samplingIsolated = false;
288
+ #lastReported = "";
289
+ #released = false;
290
+
291
+ constructor(options: IProbeVolumeOptions) {
292
+ super();
293
+ this.#report = options.report ?? ((line) => console.info(line));
294
+ this.#now = options.now ?? (() => globalThis.performance?.now() ?? Date.now());
295
+ this.#bakeBudgetMs = positiveNumber(options.bakeBudgetMs ?? 2, "bakeBudgetMs");
296
+ this.#maxWorkItemsPerFrame = positiveInteger(
297
+ options.maxWorkItemsPerFrame ?? 1,
298
+ "maxWorkItemsPerFrame",
299
+ );
300
+ this.#cubemapSize = positiveInteger(options.cubemapSize ?? 8, "cubemapSize");
301
+ this.#near = positiveNumber(options.near ?? 0.1, "near");
302
+ this.#far = positiveNumber(options.far ?? 100, "far");
303
+ if (this.#far <= this.#near) throw new Error("ProbeVolume far must be greater than near.");
304
+ this.#bounces = nonNegativeInteger(options.bounces ?? 0, "bounces");
305
+ this.#bakePasses = this.#bounces + 1;
306
+
307
+ const normalizedBounds = normalizeBounds(options.bounds);
308
+ this.boundingBox = normalizedBounds;
309
+ this.#boundsSize = normalizedBounds.max.clone().sub(normalizedBounds.min);
310
+ this.#density = normalizeDensity(options.density);
311
+ this.resolution = new Vector3(
312
+ resolutionForAxis(this.#boundsSize.x, this.#density.x, "x"),
313
+ resolutionForAxis(this.#boundsSize.y, this.#density.y, "y"),
314
+ resolutionForAxis(this.#boundsSize.z, this.#density.z, "z"),
315
+ );
316
+ this.#atlasDepth = checkedAtlasDepth(this.resolution.z);
317
+ const maximumDimension = Math.max(this.resolution.x, this.resolution.y, this.#atlasDepth);
318
+ const suppliedLimit = options.maxTextureDimension3D ?? options.deviceTextureLimit;
319
+ if (suppliedLimit !== undefined) {
320
+ validateTextureLimit(suppliedLimit);
321
+ assertTextureLimit(maximumDimension, suppliedLimit);
322
+ }
323
+ this.#probeCount = checkedIntegerProduct(
324
+ this.resolution.x,
325
+ this.resolution.y,
326
+ this.resolution.z,
327
+ "probe count",
328
+ );
329
+ const texelCount = checkedIntegerProduct(
330
+ this.resolution.x,
331
+ this.resolution.y,
332
+ this.#atlasDepth,
333
+ "atlas texel count",
334
+ );
335
+ this.#atlasBytes = texelCount * BYTES_PER_TEXEL;
336
+ this.#atlasData = new Float32Array(texelCount * 4);
337
+ this.#coefficients = new Float32Array(
338
+ this.#probeCount * SH_COEFFICIENT_COUNT * SH_CHANNEL_COUNT,
339
+ );
340
+ this.#atlasTexture = createCpuAtlas(this.#atlasData, this.resolution, this.#atlasDepth);
341
+ this.#emptyAtlasTexture = createCpuAtlas(new Float32Array(4), new Vector3(1, 1, 1), 1);
342
+ this.#atlasNode = texture3D(this.#atlasTexture);
343
+ this.#boundsMinNode = uniform(this.boundingBox.min.clone());
344
+ this.#boundsSizeNode = uniform(this.#boundsSize.clone());
345
+ this.#publish(true);
346
+ }
347
+
348
+ get texture(): Data3DTexture {
349
+ return this.#atlasTexture;
350
+ }
351
+
352
+ get atlasDepth(): number {
353
+ return this.#atlasDepth;
354
+ }
355
+
356
+ get atlasBytes(): number {
357
+ return this.#atlasBytes;
358
+ }
359
+
360
+ get probeCount(): number {
361
+ return this.#probeCount;
362
+ }
363
+
364
+ get released(): boolean {
365
+ return this.#released;
366
+ }
367
+
368
+ get atlasData(): Float32Array {
369
+ return this.#atlasData.slice();
370
+ }
371
+
372
+ get observation(): IProbeVolumeObservation {
373
+ const progress = this.#pending;
374
+ const total = progress?.totalWork ?? this.totalWork;
375
+ const completed = progress?.completedWork ?? (this.#status === "ready" ? total : 0);
376
+ return {
377
+ atlas: {
378
+ depth: this.#atlasDepth,
379
+ height: this.resolution.y,
380
+ width: this.resolution.x,
381
+ },
382
+ atlasBytes: this.#atlasBytes,
383
+ bakeBudgetMs: this.#bakeBudgetMs,
384
+ bakeCostMs: this.#lastBakeCostMs,
385
+ bakeProgress: {
386
+ completed,
387
+ fraction: total === 0 ? 1 : completed / total,
388
+ pass: progress?.pass ?? (this.#status === "ready" ? this.#bakePasses - 1 : 0),
389
+ passes: this.#bakePasses,
390
+ probesCompleted:
391
+ progress?.completedProbes ?? (this.#status === "ready" ? this.#probeCount : 0),
392
+ probesTotal: this.#probeCount * this.#bakePasses,
393
+ total,
394
+ },
395
+ marker: PROBE_VOLUME_MARKER,
396
+ probeCount: this.#probeCount,
397
+ samplingIsolated: this.#samplingIsolated,
398
+ stale: this.#status !== "ready",
399
+ stalenessFrames: this.#stalenessFrames,
400
+ status: this.#status,
401
+ unbaked: this.#status === "unbaked",
402
+ };
403
+ }
404
+
405
+ /** Attach the active renderer; only WebGPU has the 3D render-target contract this class needs. */
406
+ attachRenderer(renderer: IRendererLike): void {
407
+ if (this.#released) throw new Error("ProbeVolume.attachRenderer called after detach().");
408
+ if (renderer.kind !== "webgpu") {
409
+ throw new Error(`ProbeVolume requires a WebGPURenderer, received ${renderer.kind}.`);
410
+ }
411
+ if (this.#renderer !== undefined && this.#renderer !== renderer) {
412
+ throw new Error("ProbeVolume cannot attach to two renderers.");
413
+ }
414
+ this.#renderer = renderer;
415
+ const raw = renderer.raw as IProbeRenderer;
416
+ const deviceLimit = readTextureLimit(raw);
417
+ if (deviceLimit !== undefined) assertTextureLimit(this.maximumDimension, deviceLimit);
418
+ this.#ensureGpuResources();
419
+ if (this.#pending !== undefined) this.#prepareBake(this.#pending.scene, this.#pending.passes);
420
+ }
421
+
422
+ /** Start or coalesce an incremental static bake for a scene. */
423
+ requestBake(scene: Scene, options: { readonly bounces?: number } = {}): Promise<void> {
424
+ if (this.#released) throw new Error("ProbeVolume.requestBake called after detach().");
425
+ if (!(scene instanceof Scene)) throw new Error("ProbeVolume.requestBake requires a Scene.");
426
+ const bounces = options.bounces ?? this.#bounces;
427
+ nonNegativeInteger(bounces, "bounces");
428
+ if (this.#pending !== undefined && this.#bakePromise !== undefined)
429
+ return this.#bakePromise.promise;
430
+ this.#bakePasses = bounces + 1;
431
+ this.#maxWorkItemCostMs = 0;
432
+ this.#status = "baking";
433
+ this.#stalenessFrames = this.#stalenessFrames === null ? null : this.#stalenessFrames;
434
+ this.#bakePromise = deferred();
435
+ this.#pending = {
436
+ completedProbes: 0,
437
+ completedWork: 0,
438
+ cubeFaceIndex: 0,
439
+ pass: 0,
440
+ passes: bounces + 1,
441
+ phase: "capture",
442
+ probeIndex: 0,
443
+ repackIndex: 0,
444
+ scene,
445
+ totalWork:
446
+ (bounces + 1) *
447
+ (this.#probeCount * CAPTURE_WORK_ITEMS_PER_PROBE +
448
+ PACKED_SUB_VOLUME_COUNT * this.paddedSlices),
449
+ };
450
+ this.#clearPreviousBake();
451
+ this.#setSamplingIsolated(true);
452
+ this.#publish(true);
453
+ if (this.#renderer !== undefined) this.#prepareBake(scene, bounces + 1);
454
+ return this.#bakePromise.promise;
455
+ }
456
+
457
+ /** Alias that reads naturally at call sites that want an awaitable bake request. */
458
+ bake(scene: Scene, options?: { readonly bounces?: number }): Promise<void>;
459
+ bake(
460
+ renderer: IRendererLike,
461
+ scene: Scene,
462
+ options?: { readonly bounces?: number },
463
+ ): Promise<void>;
464
+ bake(
465
+ rendererOrScene: IRendererLike | Scene,
466
+ sceneOrOptions?: Scene | { readonly bounces?: number },
467
+ suppliedOptions: { readonly bounces?: number } = {},
468
+ ): Promise<void> {
469
+ if (isRendererLike(rendererOrScene)) {
470
+ this.attachRenderer(rendererOrScene);
471
+ return this.requestBake(sceneOrOptions as Scene, suppliedOptions);
472
+ }
473
+ return this.requestBake(
474
+ rendererOrScene,
475
+ (sceneOrOptions as { readonly bounces?: number }) ?? {},
476
+ );
477
+ }
478
+
479
+ /**
480
+ * Return the L2 irradiance node for a world position and world normal.
481
+ *
482
+ * `sample()` with no arguments is the material-friendly form and reads `positionWorld` and
483
+ * `normalWorld`. Passing numeric vectors is reserved for diagnostics and deterministic tests;
484
+ * it evaluates the same SH coefficients held by the atlas packer.
485
+ */
486
+ sample(): Node<"vec3">;
487
+ sample(position: Vector3, normal: Vector3): Vector3;
488
+ sample(position: IProbePosition, normal?: Vector3 | Node<"vec3">): Vector3 | Node<"vec3">;
489
+ sample(
490
+ position: IProbePosition = positionWorld,
491
+ normal: Vector3 | Node<"vec3"> = normalWorld,
492
+ ): Vector3 | Node<"vec3"> {
493
+ if (position instanceof Vector3 && normal instanceof Vector3) {
494
+ return this.sampleIrradiance(position, normal);
495
+ }
496
+ return this.sampleNode(position as Node<"vec3">, normal as Node<"vec3">);
497
+ }
498
+
499
+ sampleIrradiance(position: Vector3, normal: Vector3): Vector3 {
500
+ if (!(position instanceof Vector3) || !(normal instanceof Vector3)) {
501
+ throw new Error("ProbeVolume.sampleIrradiance requires Vector3 position and normal values.");
502
+ }
503
+ const coefficients = this.#samplePackedCoefficients(position);
504
+ const direction = normal.clone().normalize();
505
+ const result = new Vector3();
506
+ result.x = evaluateShChannel(coefficients, 0, direction);
507
+ result.y = evaluateShChannel(coefficients, 1, direction);
508
+ result.z = evaluateShChannel(coefficients, 2, direction);
509
+ return result.max(new Vector3());
510
+ }
511
+
512
+ /** The GPU graph used by `sample`; exposed so generated materials can compose it explicitly. */
513
+ sampleNode(
514
+ position: Node<"vec3"> = positionWorld,
515
+ normal: Node<"vec3"> = normalWorld,
516
+ ): Node<"vec3"> {
517
+ const local = clamp(vec3(position).sub(this.#boundsMinNode).div(this.#boundsSizeNode), 0, 1);
518
+ const atlasX = local.x
519
+ .mul(this.resolution.x - 1)
520
+ .add(0.5)
521
+ .div(this.resolution.x);
522
+ const atlasY = local.y
523
+ .mul(this.resolution.y - 1)
524
+ .add(0.5)
525
+ .div(this.resolution.y);
526
+ const sliceStride = this.resolution.z + 2 * SAMPLE_ATLAS_PADDING;
527
+ const atlasZ = (subVolume: number) =>
528
+ local.z
529
+ .mul(this.resolution.z - 1)
530
+ .add(SAMPLE_ATLAS_PADDING + 0.5 + subVolume * sliceStride)
531
+ .div(this.#atlasDepth);
532
+ const packed = (subVolume: number) =>
533
+ this.#atlasNode.sample(vec3(atlasX, atlasY, atlasZ(subVolume)));
534
+ const packedValues = Array.from({ length: PACKED_SUB_VOLUME_COUNT }, (_, index) =>
535
+ packed(index),
536
+ );
537
+ const packedAt = (index: number) => valueAt(packedValues, index, "packed probe value");
538
+ const coefficients = [
539
+ vec3(packedAt(0).x, packedAt(0).y, packedAt(0).z),
540
+ vec3(packedAt(0).w, packedAt(1).x, packedAt(1).y),
541
+ vec3(packedAt(1).z, packedAt(1).w, packedAt(2).x),
542
+ vec3(packedAt(2).y, packedAt(2).z, packedAt(2).w),
543
+ vec3(packedAt(3).x, packedAt(3).y, packedAt(3).z),
544
+ vec3(packedAt(3).w, packedAt(4).x, packedAt(4).y),
545
+ vec3(packedAt(4).z, packedAt(4).w, packedAt(5).x),
546
+ vec3(packedAt(5).y, packedAt(5).z, packedAt(5).w),
547
+ vec3(packedAt(6).x, packedAt(6).y, packedAt(6).z),
548
+ ];
549
+ const direction = normalize(vec3(normal));
550
+ const coefficientAt = (index: number) => valueAt(coefficients, index, "SH coefficient");
551
+ const irradiance = coefficientAt(0)
552
+ .mul(0.886227)
553
+ .add(coefficientAt(1).mul(direction.y).mul(1.023328))
554
+ .add(coefficientAt(2).mul(direction.z).mul(1.023328))
555
+ .add(coefficientAt(3).mul(direction.x).mul(1.023328))
556
+ .add(coefficientAt(4).mul(direction.x.mul(direction.y)).mul(0.858086))
557
+ .add(coefficientAt(5).mul(direction.y.mul(direction.z)).mul(0.858086))
558
+ .add(coefficientAt(6).mul(direction.z.mul(direction.z).mul(0.743125).sub(0.247708)))
559
+ .add(coefficientAt(7).mul(direction.x.mul(direction.z)).mul(0.858086))
560
+ .add(
561
+ coefficientAt(8)
562
+ .mul(direction.x.mul(direction.x).sub(direction.y.mul(direction.y)))
563
+ .mul(0.429043),
564
+ );
565
+ return irradiance.max(0);
566
+ }
567
+
568
+ /** Internal data seam used by unit/conformance fixtures to seed a known SH atlas without a GPU. */
569
+ setProbeCoefficients(
570
+ ix: number,
571
+ iy: number,
572
+ iz: number,
573
+ coefficients: readonly IProbeVolumeCoefficient[],
574
+ ): void {
575
+ if (this.#pending !== undefined)
576
+ throw new Error("ProbeVolume cannot edit coefficients during a bake.");
577
+ validateProbeIndex(ix, this.resolution.x, "ix");
578
+ validateProbeIndex(iy, this.resolution.y, "iy");
579
+ validateProbeIndex(iz, this.resolution.z, "iz");
580
+ if (coefficients.length !== SH_COEFFICIENT_COUNT) {
581
+ throw new Error(`ProbeVolume coefficients must contain ${SH_COEFFICIENT_COUNT} entries.`);
582
+ }
583
+ const probe = ix + iy * this.resolution.x + iz * this.resolution.x * this.resolution.y;
584
+ const offset = probe * SH_COEFFICIENT_COUNT * SH_CHANNEL_COUNT;
585
+ coefficients.forEach((value, coefficientIndex) => {
586
+ for (let channel = 0; channel < SH_CHANNEL_COUNT; channel += 1) {
587
+ const key = valueAt(["r", "g", "b"] as const, channel, "SH channel");
588
+ const channelValue = value[key];
589
+ if (!Number.isFinite(channelValue)) {
590
+ throw new Error(`ProbeVolume coefficient ${coefficientIndex}.${key} must be finite.`);
591
+ }
592
+ this.#coefficients[offset + coefficientIndex * SH_CHANNEL_COUNT + channel] = channelValue;
593
+ }
594
+ });
595
+ this.#packCpuAtlas();
596
+ this.#setSamplingIsolated(false);
597
+ this.#status = "ready";
598
+ this.#stalenessFrames = 0;
599
+ this.#publish(true);
600
+ }
601
+
602
+ /** One bounded render-phase slice. The game loop calls this through IComputeDriven. */
603
+ process(renderer: IRendererLike): void {
604
+ this.#assertProcessRenderer(renderer);
605
+ if (this.#renderer === undefined) this.attachRenderer(renderer);
606
+ if (this.#renderer !== renderer)
607
+ throw new Error("ProbeVolume.process received a different renderer.");
608
+ if (this.#pending === undefined) {
609
+ this.#publishIdleFrame();
610
+ return;
611
+ }
612
+ if (!this.#gpuWarmupSettled || !this.#sceneWarmupSettled) {
613
+ this.#lastBakeCostMs = 0;
614
+ this.#publish(false);
615
+ return;
616
+ }
617
+ if (this.#sceneState === undefined)
618
+ this.#prepareBake(this.#pending.scene, this.#pending.passes);
619
+ this.#processPending(this.#pending);
620
+ }
621
+
622
+ #assertProcessRenderer(renderer: IRendererLike): void {
623
+ if (this.#released) throw new Error("ProbeVolume.process called after detach().");
624
+ if (renderer.kind !== "webgpu") {
625
+ throw new Error(`ProbeVolume requires a WebGPURenderer, received ${renderer.kind}.`);
626
+ }
627
+ }
628
+
629
+ #publishIdleFrame(): void {
630
+ if (this.#status === "ready" && this.#stalenessFrames !== null) this.#stalenessFrames += 1;
631
+ this.#lastBakeCostMs = 0;
632
+ this.#publish(false);
633
+ }
634
+
635
+ #processPending(pending: IPendingBake): void {
636
+ const started = this.#now();
637
+ let workItems = 0;
638
+ try {
639
+ while (this.#pending !== undefined && workItems < this.#maxWorkItemsPerFrame) {
640
+ const elapsedBefore = Math.max(0, this.#now() - started);
641
+ if (workItems > 0 && elapsedBefore + this.#maxWorkItemCostMs > this.#bakeBudgetMs) break;
642
+ const itemStarted = this.#now();
643
+ this.#runWorkItem(pending);
644
+ const itemCostMs = Math.max(0, this.#now() - itemStarted);
645
+ this.#maxWorkItemCostMs = Math.max(this.#maxWorkItemCostMs, itemCostMs);
646
+ const elapsed = Math.max(0, this.#now() - started);
647
+ if (itemCostMs > this.#bakeBudgetMs + BAKE_BUDGET_SLACK_MS) {
648
+ throw new Error(
649
+ `ProbeVolume bake work item cost ${itemCostMs}ms exceeds bakeBudgetMs ${this.#bakeBudgetMs}ms plus ${BAKE_BUDGET_SLACK_MS}ms scheduling slack.`,
650
+ );
651
+ }
652
+ if (elapsed > this.#bakeBudgetMs + BAKE_BUDGET_SLACK_MS) {
653
+ throw new Error(
654
+ `ProbeVolume bake frame cost ${elapsed}ms exceeds bakeBudgetMs ${this.#bakeBudgetMs}ms plus ${BAKE_BUDGET_SLACK_MS}ms scheduling slack.`,
655
+ );
656
+ }
657
+ workItems += 1;
658
+ if (elapsed >= this.#bakeBudgetMs) break;
659
+ }
660
+ } catch (error) {
661
+ this.#failBake(error);
662
+ throw error;
663
+ }
664
+ this.#lastBakeCostMs = Math.max(0, this.#now() - started);
665
+ this.#publish(true);
666
+ }
667
+
668
+ detach(): void {
669
+ if (this.#released) return;
670
+ this.#released = true;
671
+ if (this.#pending !== undefined) {
672
+ this.#bakePromise?.reject(new Error("ProbeVolume detached while a bake was pending."));
673
+ this.#pending = undefined;
674
+ this.#bakePromise = undefined;
675
+ }
676
+ this.#restoreSceneState();
677
+ this.#cubeRenderTarget?.dispose();
678
+ this.#projectionTarget?.dispose();
679
+ this.#batchTarget?.dispose();
680
+ this.#atlasTarget?.dispose();
681
+ this.#emptyAtlasTexture.dispose();
682
+ this.#projectionMaterial?.dispose();
683
+ for (const material of this.#repackMaterials ?? []) material.dispose();
684
+ this.#quadMesh?.geometry.dispose();
685
+ this.#atlasTexture.dispose();
686
+ this.#cubeRenderTarget = undefined;
687
+ this.#projectionTarget = undefined;
688
+ this.#batchTarget = undefined;
689
+ this.#atlasTarget = undefined;
690
+ this.#projectionMaterial = undefined;
691
+ this.#repackMaterials = undefined;
692
+ this.#atlasTexture = createCpuAtlas(this.#atlasData, this.resolution, this.#atlasDepth);
693
+ }
694
+
695
+ get paddedSlices(): number {
696
+ return this.resolution.z + 2 * ATLAS_PADDING;
697
+ }
698
+
699
+ get maximumDimension(): number {
700
+ return Math.max(this.resolution.x, this.resolution.y, this.#atlasDepth);
701
+ }
702
+
703
+ get totalWork(): number {
704
+ return (
705
+ this.#bakePasses *
706
+ (this.#probeCount * CAPTURE_WORK_ITEMS_PER_PROBE +
707
+ PACKED_SUB_VOLUME_COUNT * this.paddedSlices)
708
+ );
709
+ }
710
+
711
+ #ensureGpuResources(): void {
712
+ if (this.#cubeRenderTarget !== undefined) return;
713
+ this.#cubeRenderTarget = new CubeRenderTarget(this.#cubemapSize, {
714
+ depthBuffer: true,
715
+ generateMipmaps: false,
716
+ magFilter: LinearFilter,
717
+ minFilter: LinearFilter,
718
+ type: HalfFloatType,
719
+ });
720
+ this.#cubeCamera = new CubeCamera(this.#near, this.#far, this.#cubeRenderTarget);
721
+ this.#projectionTarget = new RenderTarget(9, 1, {
722
+ depthBuffer: false,
723
+ generateMipmaps: false,
724
+ magFilter: NearestFilter,
725
+ minFilter: NearestFilter,
726
+ type: FloatType,
727
+ });
728
+ this.#batchTarget = new RenderTarget(9, this.#probeCount, {
729
+ depthBuffer: false,
730
+ generateMipmaps: false,
731
+ magFilter: NearestFilter,
732
+ minFilter: NearestFilter,
733
+ type: FloatType,
734
+ });
735
+ this.#atlasTarget = new RenderTarget3D(this.resolution.x, this.resolution.y, this.#atlasDepth, {
736
+ depthBuffer: false,
737
+ generateMipmaps: false,
738
+ magFilter: LinearFilter,
739
+ minFilter: LinearFilter,
740
+ type: FloatType,
741
+ });
742
+ this.#atlasTexture = this.#atlasTarget.texture as Data3DTexture;
743
+ this.#atlasTexture.format = RGBAFormat;
744
+ this.#setSamplingIsolated(this.#samplingIsolated);
745
+ this.#quadCamera = new OrthographicCamera(-1, 1, 1, -1, 0, 1);
746
+ this.#quadMesh = new Mesh(new PlaneGeometry(2, 2));
747
+ this.#quadScene = new Scene();
748
+ this.#quadScene.add(this.#quadMesh);
749
+ this.#projectionMaterial = createProjectionMaterial(this.#cubeRenderTarget, this.#cubemapSize);
750
+ this.#batchTextureNode = texture(this.#batchTarget.texture);
751
+ this.#repackMaterials = createRepackMaterials(
752
+ this.#batchTextureNode,
753
+ this.#repackSlice,
754
+ this.resolution,
755
+ this.#probeCount,
756
+ );
757
+ this.#startGpuWarmup();
758
+ }
759
+
760
+ /** Compile the private projection/repack graphs outside the presented frame budget. */
761
+ #startGpuWarmup(): void {
762
+ if (this.#gpuWarmupStarted) return;
763
+ const projectionTarget = this.#projectionTarget;
764
+ const projectionMaterial = this.#projectionMaterial;
765
+ const atlasTarget = this.#atlasTarget;
766
+ const repackMaterials = this.#repackMaterials;
767
+ if (
768
+ projectionTarget === undefined ||
769
+ projectionMaterial === undefined ||
770
+ atlasTarget === undefined ||
771
+ repackMaterials === undefined
772
+ )
773
+ throw new Error("ProbeVolume warm-up resources were not initialized.");
774
+ this.#gpuWarmupStarted = true;
775
+ // First-use shader work belongs to scene entry, before bounded bake slices are presented.
776
+ this.#renderQuad(projectionTarget, projectionMaterial);
777
+ repackMaterials.forEach((material, index) => {
778
+ this.#renderQuad(atlasTarget, material, index * this.paddedSlices);
779
+ });
780
+ }
781
+
782
+ /** Compile every scene material through the six cube-camera views before the first capture. */
783
+ #startSceneWarmup(scene: Scene): void {
784
+ if (this.#sceneWarmupStarted) return;
785
+ this.#sceneWarmupStarted = true;
786
+ const renderer = this.#renderer;
787
+ const raw = renderer?.raw as IProbeRenderer | undefined;
788
+ const cubeCamera = this.#cubeCamera;
789
+ if (
790
+ renderer === undefined ||
791
+ typeof renderer.compileAsync !== "function" ||
792
+ cubeCamera === undefined
793
+ )
794
+ return;
795
+ const coordinateSystem = raw?.coordinateSystem;
796
+ if (coordinateSystem !== undefined && cubeCamera.coordinateSystem !== coordinateSystem) {
797
+ cubeCamera.coordinateSystem = coordinateSystem;
798
+ cubeCamera.updateCoordinateSystem();
799
+ }
800
+ const cameras = cubeCamera.children.filter(
801
+ (child): child is Camera => (child as Camera).isCamera === true,
802
+ );
803
+ if (cameras.length === 0) return;
804
+ this.#sceneWarmupSettled = false;
805
+ void (async () => {
806
+ try {
807
+ const compile = (async () => {
808
+ for (const camera of cameras) await renderer.compileAsync(scene, camera);
809
+ })();
810
+ await Promise.race([
811
+ compile,
812
+ new Promise<void>((resolve) => setTimeout(resolve, SCENE_WARMUP_TIMEOUT_MS)),
813
+ ]);
814
+ } catch {
815
+ // A failed warm-up is not a failed bake. The first bounded capture surfaces the renderer
816
+ // error, while a host without a settling compile promise still reaches the same path.
817
+ } finally {
818
+ this.#sceneWarmupSettled = true;
819
+ }
820
+ })();
821
+ }
822
+
823
+ #prepareBake(scene: Scene, passes: number): void {
824
+ if (this.#sceneState !== undefined) return;
825
+ this.#ensureGpuResources();
826
+ const raw = this.#rawRenderer();
827
+ const matrixWorldAutoUpdate = scene.matrixWorldAutoUpdate;
828
+ if (matrixWorldAutoUpdate) {
829
+ scene.updateMatrixWorld(true);
830
+ scene.matrixWorldAutoUpdate = false;
831
+ }
832
+ const shadowAutoUpdate = raw.shadowMap?.autoUpdate;
833
+ if (raw.shadowMap !== undefined) {
834
+ raw.shadowMap.autoUpdate = false;
835
+ raw.shadowMap.needsUpdate = true;
836
+ }
837
+ this.#sceneState = {
838
+ matrixWorldAutoUpdate,
839
+ scene,
840
+ ...(shadowAutoUpdate === undefined ? {} : { shadowAutoUpdate }),
841
+ };
842
+ this.#startSceneWarmup(scene);
843
+ if (this.#pending !== undefined && this.#pending.passes !== passes) {
844
+ throw new Error("ProbeVolume cannot change bake passes after a bake has started.");
845
+ }
846
+ }
847
+
848
+ #runWorkItem(pending: IPendingBake): void {
849
+ if (pending.phase === "capture") {
850
+ this.#runCaptureWorkItem(pending);
851
+ } else if (pending.phase === "project") {
852
+ this.#runProjectWorkItem(pending);
853
+ } else if (pending.phase === "copy") {
854
+ this.#runCopyWorkItem(pending);
855
+ } else if (this.#runRepackWorkItem(pending)) {
856
+ return;
857
+ }
858
+ pending.completedWork += 1;
859
+ }
860
+
861
+ #runCaptureWorkItem(pending: IPendingBake): void {
862
+ this.#captureProbeFace(pending.scene, pending.probeIndex, pending.cubeFaceIndex);
863
+ pending.cubeFaceIndex += 1;
864
+ if (pending.cubeFaceIndex >= CUBE_FACE_COUNT) pending.phase = "project";
865
+ }
866
+
867
+ #runProjectWorkItem(pending: IPendingBake): void {
868
+ this.#projectProbe();
869
+ pending.phase = "copy";
870
+ }
871
+
872
+ #runCopyWorkItem(pending: IPendingBake): void {
873
+ this.#copyProjectedProbe(pending.probeIndex);
874
+ pending.probeIndex += 1;
875
+ pending.completedProbes += 1;
876
+ if (pending.probeIndex >= this.#probeCount) {
877
+ pending.phase = "repack";
878
+ pending.repackIndex = 0;
879
+ } else {
880
+ pending.phase = "capture";
881
+ pending.cubeFaceIndex = 0;
882
+ }
883
+ }
884
+
885
+ #runRepackWorkItem(pending: IPendingBake): boolean {
886
+ this.#repackSliceToAtlas(pending.repackIndex);
887
+ pending.repackIndex += 1;
888
+ if (pending.repackIndex < PACKED_SUB_VOLUME_COUNT * this.paddedSlices) return false;
889
+ if (pending.pass + 1 < pending.passes) {
890
+ pending.pass += 1;
891
+ pending.phase = "capture";
892
+ pending.cubeFaceIndex = 0;
893
+ pending.probeIndex = 0;
894
+ if (pending.pass === 1) this.#setSamplingIsolated(false);
895
+ return false;
896
+ }
897
+ this.#finishBake();
898
+ return true;
899
+ }
900
+
901
+ #captureProbeFace(scene: Scene, probeIndex: number, cubeFaceIndex: number): void {
902
+ const ix = probeIndex % this.resolution.x;
903
+ const iy = Math.floor(probeIndex / this.resolution.x) % this.resolution.y;
904
+ const iz = Math.floor(probeIndex / (this.resolution.x * this.resolution.y));
905
+ const position = this.probePosition(ix, iy, iz);
906
+ const cubeCamera = this.#cubeCamera;
907
+ const cubeTarget = this.#cubeRenderTarget;
908
+ if (cubeCamera === undefined || cubeTarget === undefined) {
909
+ throw new Error("ProbeVolume bake resources were not initialized.");
910
+ }
911
+ cubeCamera.position.copy(position);
912
+ cubeCamera.updateMatrixWorld(true);
913
+ const raw = this.#rawRenderer();
914
+ if (
915
+ raw.coordinateSystem !== undefined &&
916
+ cubeCamera.coordinateSystem !== raw.coordinateSystem
917
+ ) {
918
+ cubeCamera.coordinateSystem = raw.coordinateSystem;
919
+ cubeCamera.updateCoordinateSystem();
920
+ }
921
+ const camera = valueAt(
922
+ cubeCamera.children.filter((child): child is Camera => (child as Camera).isCamera === true),
923
+ cubeFaceIndex,
924
+ "cube camera face",
925
+ );
926
+ const previousTarget = raw.getRenderTarget?.() ?? null;
927
+ const previousFace = raw.getActiveCubeFace?.() ?? 0;
928
+ const previousMip = raw.getActiveMipmapLevel?.() ?? 0;
929
+ const previousXr = raw.xr?.enabled;
930
+ if (raw.xr !== undefined) raw.xr.enabled = false;
931
+ raw.setRenderTarget(cubeTarget, cubeFaceIndex, cubeCamera.activeMipmapLevel);
932
+ try {
933
+ if (raw.reversedDepthBuffer === true && raw.autoClear === false) raw.clearDepth?.();
934
+ raw.render(scene, camera);
935
+ } finally {
936
+ raw.setRenderTarget(previousTarget, previousFace, previousMip);
937
+ if (raw.xr !== undefined && previousXr !== undefined) raw.xr.enabled = previousXr;
938
+ }
939
+ if (cubeFaceIndex === CUBE_FACE_COUNT - 1) cubeTarget.texture.needsPMREMUpdate = true;
940
+ }
941
+
942
+ #projectProbe(): void {
943
+ const projectionTarget = this.#projectionTarget;
944
+ const projectionMaterial = this.#projectionMaterial;
945
+ if (projectionTarget === undefined || projectionMaterial === undefined) {
946
+ throw new Error("ProbeVolume projection resources were not initialized.");
947
+ }
948
+ this.#renderQuad(projectionTarget, projectionMaterial);
949
+ }
950
+
951
+ #copyProjectedProbe(probeIndex: number): void {
952
+ const projectionTarget = this.#projectionTarget;
953
+ const batchTarget = this.#batchTarget;
954
+ if (projectionTarget === undefined || batchTarget === undefined) {
955
+ throw new Error("ProbeVolume copy resources were not initialized.");
956
+ }
957
+ const raw = this.#rawRenderer();
958
+ if (raw.copyTextureToTexture === undefined) {
959
+ throw new Error(
960
+ "ProbeVolume requires WebGPU texture-to-texture copies for its staging rows.",
961
+ );
962
+ }
963
+ raw.copyTextureToTexture(
964
+ projectionTarget.texture,
965
+ batchTarget.texture,
966
+ new Box2(new Vector2(0, 0), new Vector2(9, 1)),
967
+ new Vector2(0, probeIndex),
968
+ );
969
+ }
970
+
971
+ #repackSliceToAtlas(repackIndex: number): void {
972
+ const atlasTarget = this.#atlasTarget;
973
+ const materials = this.#repackMaterials;
974
+ if (atlasTarget === undefined || materials === undefined) {
975
+ throw new Error("ProbeVolume repack resources were not initialized.");
976
+ }
977
+ const subVolume = Math.floor(repackIndex / this.paddedSlices);
978
+ const localSlice = repackIndex % this.paddedSlices;
979
+ const sourceSlice = Math.min(this.resolution.z - 1, Math.max(0, localSlice - ATLAS_PADDING));
980
+ this.#repackSlice.value = sourceSlice;
981
+ atlasTarget.viewport.set(0, 0, this.resolution.x, this.resolution.y);
982
+ atlasTarget.scissorTest = false;
983
+ this.#renderQuad(
984
+ atlasTarget,
985
+ valueAt(materials, subVolume, "repack material"),
986
+ subVolume * this.paddedSlices + localSlice,
987
+ );
988
+ }
989
+
990
+ #renderQuad(target: RenderTarget | RenderTarget3D, material: NodeMaterial, slice?: number): void {
991
+ const raw = this.#rawRenderer();
992
+ const previousTarget = raw.getRenderTarget?.() ?? null;
993
+ const previousFace = raw.getActiveCubeFace?.() ?? 0;
994
+ const previousMip = raw.getActiveMipmapLevel?.() ?? 0;
995
+ const mesh = this.#quadMesh;
996
+ const camera = this.#quadCamera;
997
+ const scene = this.#quadScene;
998
+ if (mesh === undefined || camera === undefined || scene === undefined) {
999
+ throw new Error("ProbeVolume quad resources were not initialized.");
1000
+ }
1001
+ mesh.material = material;
1002
+ raw.setRenderTarget(target, slice ?? 0, 0);
1003
+ try {
1004
+ raw.render(scene, camera);
1005
+ } finally {
1006
+ raw.setRenderTarget(previousTarget, previousFace, previousMip);
1007
+ }
1008
+ }
1009
+
1010
+ #finishBake(): void {
1011
+ this.#restoreSceneState();
1012
+ this.#setSamplingIsolated(false);
1013
+ this.#status = "ready";
1014
+ this.#stalenessFrames = 0;
1015
+ const promise = this.#bakePromise;
1016
+ this.#pending = undefined;
1017
+ this.#bakePromise = undefined;
1018
+ promise?.resolve();
1019
+ }
1020
+
1021
+ #failBake(error: unknown): void {
1022
+ this.#restoreSceneState();
1023
+ this.#pending = undefined;
1024
+ const promise = this.#bakePromise;
1025
+ this.#bakePromise = undefined;
1026
+ promise?.reject(error);
1027
+ this.#status = "unbaked";
1028
+ this.#publish(true);
1029
+ }
1030
+
1031
+ #restoreSceneState(): void {
1032
+ const state = this.#sceneState;
1033
+ if (state === undefined) return;
1034
+ state.scene.matrixWorldAutoUpdate = state.matrixWorldAutoUpdate;
1035
+ const raw = this.#renderer === undefined ? undefined : (this.#renderer.raw as IProbeRenderer);
1036
+ if (raw?.shadowMap !== undefined && state.shadowAutoUpdate !== undefined) {
1037
+ raw.shadowMap.autoUpdate = state.shadowAutoUpdate;
1038
+ }
1039
+ this.#sceneState = undefined;
1040
+ }
1041
+
1042
+ #rawRenderer(): IProbeRenderer {
1043
+ if (this.#renderer === undefined)
1044
+ throw new Error("ProbeVolume needs an attached WebGPURenderer.");
1045
+ return this.#renderer.raw as IProbeRenderer;
1046
+ }
1047
+
1048
+ #clearPreviousBake(): void {
1049
+ this.#coefficients.fill(0);
1050
+ this.#atlasData.fill(0);
1051
+ if (this.#atlasTarget === undefined) this.#atlasTexture.needsUpdate = true;
1052
+ }
1053
+
1054
+ #setSamplingIsolated(isolated: boolean): void {
1055
+ this.#samplingIsolated = isolated;
1056
+ this.#atlasNode.value = isolated ? this.#emptyAtlasTexture : this.#atlasTexture;
1057
+ }
1058
+
1059
+ #publish(force: boolean): void {
1060
+ const observation = this.observation;
1061
+ const line = `${PROBE_VOLUME_MARKER}:${JSON.stringify(observation)}`;
1062
+ if (!force && line === this.#lastReported) return;
1063
+ this.#lastReported = line;
1064
+ this.#report(line);
1065
+ }
1066
+
1067
+ #packCpuAtlas(): void {
1068
+ for (let subVolume = 0; subVolume < PACKED_SUB_VOLUME_COUNT; subVolume += 1) {
1069
+ packCpuSubVolume(
1070
+ this.#atlasData,
1071
+ this.#coefficients,
1072
+ this.resolution,
1073
+ this.paddedSlices,
1074
+ subVolume,
1075
+ );
1076
+ }
1077
+ this.#atlasTexture.image.data = this.#atlasData;
1078
+ this.#atlasTexture.needsUpdate = true;
1079
+ }
1080
+
1081
+ #samplePackedCoefficients(position: Vector3): Float32Array {
1082
+ const local = normalizedPosition(position, this.boundingBox.min, this.#boundsSize);
1083
+ const atlasX = (local.x * (this.resolution.x - 1) + 0.5) / this.resolution.x;
1084
+ const atlasY = (local.y * (this.resolution.y - 1) + 0.5) / this.resolution.y;
1085
+ const sampleStride = this.resolution.z + 2 * SAMPLE_ATLAS_PADDING;
1086
+ const packed = Array.from({ length: PACKED_SUB_VOLUME_COUNT }, (_, subVolume) =>
1087
+ sampleAtlas(
1088
+ this.#atlasData,
1089
+ this.resolution.x,
1090
+ this.resolution.y,
1091
+ this.#atlasDepth,
1092
+ atlasX,
1093
+ atlasY,
1094
+ (local.z * (this.resolution.z - 1) +
1095
+ SAMPLE_ATLAS_PADDING +
1096
+ 0.5 +
1097
+ subVolume * sampleStride) /
1098
+ this.#atlasDepth,
1099
+ ),
1100
+ );
1101
+ const result = new Float32Array(SH_COEFFICIENT_COUNT * SH_CHANNEL_COUNT);
1102
+ for (let subVolume = 0; subVolume < PACKED_SUB_VOLUME_COUNT; subVolume += 1) {
1103
+ const texel = valueAt(packed, subVolume, "sampled atlas sub-volume");
1104
+ for (let channel = 0; channel < 4; channel += 1) {
1105
+ const packedChannel = valueAt(PACKED_CHANNELS, subVolume * 4 + channel, "packed channel");
1106
+ if (packedChannel !== null) {
1107
+ const [coefficient, component] = packedChannel;
1108
+ result[coefficient * SH_CHANNEL_COUNT + component] = valueAt(
1109
+ texel,
1110
+ channel,
1111
+ "sampled atlas channel",
1112
+ );
1113
+ }
1114
+ }
1115
+ }
1116
+ return result;
1117
+ }
1118
+
1119
+ probePosition(ix: number, iy: number, iz: number, target = new Vector3()): Vector3 {
1120
+ return target.set(
1121
+ this.boundingBox.min.x + (ix * this.#boundsSize.x) / (this.resolution.x - 1),
1122
+ this.boundingBox.min.y + (iy * this.#boundsSize.y) / (this.resolution.y - 1),
1123
+ this.boundingBox.min.z + (iz * this.#boundsSize.z) / (this.resolution.z - 1),
1124
+ );
1125
+ }
1126
+ }
1127
+
1128
+ function packCpuSubVolume(
1129
+ atlasData: Float32Array,
1130
+ coefficients: Float32Array,
1131
+ resolution: Vector3,
1132
+ paddedSlices: number,
1133
+ subVolume: number,
1134
+ ): void {
1135
+ const nx = resolution.x;
1136
+ const ny = resolution.y;
1137
+ const nz = resolution.z;
1138
+ const base = subVolume * paddedSlices;
1139
+ for (let z = 0; z < nz; z += 1) {
1140
+ for (let y = 0; y < ny; y += 1) {
1141
+ for (let x = 0; x < nx; x += 1) {
1142
+ const probe = x + y * nx + z * nx * ny;
1143
+ writeAtlasTexel(
1144
+ atlasData,
1145
+ nx,
1146
+ ny,
1147
+ base + ATLAS_PADDING + z,
1148
+ x,
1149
+ y,
1150
+ packedCoefficients(coefficients, probe, subVolume),
1151
+ );
1152
+ }
1153
+ }
1154
+ }
1155
+ for (let y = 0; y < ny; y += 1) {
1156
+ for (let x = 0; x < nx; x += 1) {
1157
+ const first = packedCoefficients(coefficients, x + y * nx, subVolume);
1158
+ const lastProbe = x + y * nx + (nz - 1) * nx * ny;
1159
+ const last = packedCoefficients(coefficients, lastProbe, subVolume);
1160
+ for (let pad = 0; pad < ATLAS_PADDING; pad += 1) {
1161
+ writeAtlasTexel(atlasData, nx, ny, base + pad, x, y, first);
1162
+ writeAtlasTexel(atlasData, nx, ny, base + ATLAS_PADDING + nz + pad, x, y, last);
1163
+ }
1164
+ }
1165
+ }
1166
+ }
1167
+
1168
+ function writeAtlasTexel(
1169
+ atlasData: Float32Array,
1170
+ width: number,
1171
+ height: number,
1172
+ z: number,
1173
+ x: number,
1174
+ y: number,
1175
+ values: readonly number[],
1176
+ ): void {
1177
+ const offset = ((z * height + y) * width + x) * 4;
1178
+ atlasData.set(values, offset);
1179
+ }
1180
+
1181
+ function packedCoefficients(
1182
+ coefficients: Float32Array,
1183
+ probe: number,
1184
+ subVolume: number,
1185
+ ): number[] {
1186
+ const result = [0, 0, 0, 0];
1187
+ for (let channel = 0; channel < 4; channel += 1) {
1188
+ const packedChannel = valueAt(PACKED_CHANNELS, subVolume * 4 + channel, "packed channel");
1189
+ if (packedChannel === null) continue;
1190
+ const [coefficient, component] = packedChannel;
1191
+ result[channel] =
1192
+ coefficients[
1193
+ probe * SH_COEFFICIENT_COUNT * SH_CHANNEL_COUNT + coefficient * SH_CHANNEL_COUNT + component
1194
+ ] ?? 0;
1195
+ }
1196
+ return result;
1197
+ }
1198
+
1199
+ function normalizedPosition(position: Vector3, minimum: Vector3, size: Vector3): Vector3 {
1200
+ const local = position.clone().sub(minimum);
1201
+ local.x = Math.min(1, Math.max(0, local.x / size.x));
1202
+ local.y = Math.min(1, Math.max(0, local.y / size.y));
1203
+ local.z = Math.min(1, Math.max(0, local.z / size.z));
1204
+ return local;
1205
+ }
1206
+
1207
+ function sampleAtlas(
1208
+ data: Float32Array,
1209
+ width: number,
1210
+ height: number,
1211
+ depth: number,
1212
+ u: number,
1213
+ v: number,
1214
+ w: number,
1215
+ ): number[] {
1216
+ const x = clampedTextureCoordinate(u, width);
1217
+ const y = clampedTextureCoordinate(v, height);
1218
+ const z = clampedTextureCoordinate(w, depth);
1219
+ const lowerX = Math.floor(x);
1220
+ const lowerY = Math.floor(y);
1221
+ const lowerZ = Math.floor(z);
1222
+ const upperX = Math.min(width - 1, lowerX + 1);
1223
+ const upperY = Math.min(height - 1, lowerY + 1);
1224
+ const upperZ = Math.min(depth - 1, lowerZ + 1);
1225
+ const result = [0, 0, 0, 0];
1226
+ for (const sampleZ of uniquePair(lowerZ, upperZ)) {
1227
+ for (const sampleY of uniquePair(lowerY, upperY)) {
1228
+ for (const sampleX of uniquePair(lowerX, upperX)) {
1229
+ const weight =
1230
+ interpolationFactor(sampleX, lowerX, upperX, x - lowerX) *
1231
+ interpolationFactor(sampleY, lowerY, upperY, y - lowerY) *
1232
+ interpolationFactor(sampleZ, lowerZ, upperZ, z - lowerZ);
1233
+ const offset = ((sampleZ * height + sampleY) * width + sampleX) * 4;
1234
+ for (let channel = 0; channel < 4; channel += 1) {
1235
+ result[channel] =
1236
+ valueAt(result, channel, "atlas result channel") +
1237
+ (data[offset + channel] ?? 0) * weight;
1238
+ }
1239
+ }
1240
+ }
1241
+ }
1242
+ return result;
1243
+ }
1244
+
1245
+ function clampedTextureCoordinate(value: number, size: number): number {
1246
+ return Math.min(size - 1, Math.max(0, value * size - 0.5));
1247
+ }
1248
+
1249
+ function uniquePair(lower: number, upper: number): readonly number[] {
1250
+ return lower === upper ? [lower] : [lower, upper];
1251
+ }
1252
+
1253
+ function interpolationFactor(
1254
+ sample: number,
1255
+ lower: number,
1256
+ upper: number,
1257
+ fraction: number,
1258
+ ): number {
1259
+ if (lower === upper) return 1;
1260
+ return sample === lower ? 1 - fraction : fraction;
1261
+ }
1262
+
1263
+ function createCpuAtlas(data: Float32Array, resolution: Vector3, depth: number): Data3DTexture {
1264
+ const atlas = new Data3DTexture(data, resolution.x, resolution.y, depth);
1265
+ atlas.type = FloatType;
1266
+ atlas.format = RGBAFormat;
1267
+ atlas.minFilter = LinearFilter;
1268
+ atlas.magFilter = LinearFilter;
1269
+ atlas.wrapR = ClampToEdgeWrapping;
1270
+ atlas.generateMipmaps = false;
1271
+ atlas.needsUpdate = true;
1272
+ return atlas;
1273
+ }
1274
+
1275
+ function createProjectionMaterial(cubeTarget: CubeRenderTarget, cubemapSize: number): NodeMaterial {
1276
+ const environment = cubeTexture(cubeTarget.texture);
1277
+ const coefficientIndex = int(floor(viewportCoordinate.x));
1278
+ const projection = Fn(() => {
1279
+ const accum = Array.from({ length: SH_COEFFICIENT_COUNT }, () => vec3(0).toVar());
1280
+ const accumAt = (index: number) => valueAt(accum, index, "SH accumulation");
1281
+ const totalWeight = float(0).toVar();
1282
+ const pixelSize = 2 / cubemapSize;
1283
+ for (let face = 0; face < 6; face += 1) {
1284
+ for (let iy = 0; iy < cubemapSize; iy += 1) {
1285
+ for (let ix = 0; ix < cubemapSize; ix += 1) {
1286
+ const col = (ix + 0.5) * pixelSize - 1;
1287
+ const row = 1 - (iy + 0.5) * pixelSize;
1288
+ const coordinate = cubeFaceCoordinate(face, col, row);
1289
+ const lengthSquared =
1290
+ coordinate.x * coordinate.x + coordinate.y * coordinate.y + coordinate.z * coordinate.z;
1291
+ const weight = 4 / (Math.sqrt(lengthSquared) * lengthSquared);
1292
+ const direction = new Vector3(coordinate.x, coordinate.y, coordinate.z).normalize();
1293
+ const weighted = environment
1294
+ .sample(vec3(coordinate.x, coordinate.y, coordinate.z))
1295
+ .rgb.mul(weight);
1296
+ totalWeight.addAssign(weight);
1297
+ accumAt(0).addAssign(weighted.mul(0.282095));
1298
+ accumAt(1).addAssign(weighted.mul(0.488603 * direction.y));
1299
+ accumAt(2).addAssign(weighted.mul(0.488603 * direction.z));
1300
+ accumAt(3).addAssign(weighted.mul(0.488603 * direction.x));
1301
+ accumAt(4).addAssign(weighted.mul(1.092548 * direction.x * direction.y));
1302
+ accumAt(5).addAssign(weighted.mul(1.092548 * direction.y * direction.z));
1303
+ accumAt(6).addAssign(weighted.mul(0.315392 * (3 * direction.z * direction.z - 1)));
1304
+ accumAt(7).addAssign(weighted.mul(1.092548 * direction.x * direction.z));
1305
+ accumAt(8).addAssign(
1306
+ weighted.mul(0.546274 * (direction.x * direction.x - direction.y * direction.y)),
1307
+ );
1308
+ }
1309
+ }
1310
+ }
1311
+ const norm = float(4 * Math.PI).div(totalWeight);
1312
+ let selected: Node<"vec3"> = accumAt(8);
1313
+ for (let index = SH_COEFFICIENT_COUNT - 2; index >= 0; index -= 1) {
1314
+ selected = coefficientIndex.equal(index).select(accumAt(index), selected) as Node<"vec3">;
1315
+ }
1316
+ return vec4(selected.mul(norm), 1);
1317
+ })();
1318
+ const material = new NodeMaterial();
1319
+ material.fragmentNode = projection;
1320
+ material.toneMapped = false;
1321
+ material.depthTest = false;
1322
+ material.depthWrite = false;
1323
+ return material;
1324
+ }
1325
+
1326
+ function createRepackMaterials(
1327
+ batchTextureNode: ReturnType<typeof texture>,
1328
+ slice: Node<"int">,
1329
+ dimensions: Vector3,
1330
+ probeCount: number,
1331
+ ): NodeMaterial[] {
1332
+ const ix = floor(viewportCoordinate.x);
1333
+ const iy = floor(viewportCoordinate.y);
1334
+ const probe = ix.add(iy.mul(dimensions.x)).add(int(slice).mul(dimensions.x * dimensions.y));
1335
+ const uv = vec2(probe.add(0.5).div(probeCount), 0);
1336
+ const samples = Array.from({ length: SH_COEFFICIENT_COUNT }, (_, index) =>
1337
+ batchTextureNode.sample(vec2((index + 0.5) / SH_COEFFICIENT_COUNT, uv.x)),
1338
+ );
1339
+ const sampleAt = (index: number) => valueAt(samples, index, "repack sample");
1340
+ const values = [
1341
+ [sampleAt(0).x, sampleAt(0).y, sampleAt(0).z, sampleAt(1).x],
1342
+ [sampleAt(1).y, sampleAt(1).z, sampleAt(2).x, sampleAt(2).y],
1343
+ [sampleAt(2).z, sampleAt(3).x, sampleAt(3).y, sampleAt(3).z],
1344
+ [sampleAt(4).x, sampleAt(4).y, sampleAt(4).z, sampleAt(5).x],
1345
+ [sampleAt(5).y, sampleAt(5).z, sampleAt(6).x, sampleAt(6).y],
1346
+ [sampleAt(6).z, sampleAt(7).x, sampleAt(7).y, sampleAt(7).z],
1347
+ [sampleAt(8).x, sampleAt(8).y, sampleAt(8).z, 0],
1348
+ ];
1349
+ return values.map((value) => {
1350
+ const material = new NodeMaterial();
1351
+ material.fragmentNode = vec4(
1352
+ valueAt(value, 0, "repack red channel"),
1353
+ valueAt(value, 1, "repack green channel"),
1354
+ valueAt(value, 2, "repack blue channel"),
1355
+ valueAt(value, 3, "repack alpha channel"),
1356
+ );
1357
+ material.toneMapped = false;
1358
+ material.depthTest = false;
1359
+ material.depthWrite = false;
1360
+ return material;
1361
+ });
1362
+ }
1363
+
1364
+ function cubeFaceCoordinate(face: number, col: number, row: number): IVector3Like {
1365
+ if (face === 0) return { x: 1, y: row, z: -col };
1366
+ if (face === 1) return { x: -1, y: row, z: col };
1367
+ if (face === 2) return { x: col, y: 1, z: -row };
1368
+ if (face === 3) return { x: col, y: -1, z: row };
1369
+ if (face === 4) return { x: col, y: row, z: 1 };
1370
+ return { x: -col, y: row, z: -1 };
1371
+ }
1372
+
1373
+ function evaluateShChannel(coefficients: Float32Array, channel: number, normal: Vector3): number {
1374
+ const c = (index: number) => coefficients[index * SH_CHANNEL_COUNT + channel] ?? 0;
1375
+ return (
1376
+ c(0) * 0.886227 +
1377
+ c(1) * normal.y * 1.023328 +
1378
+ c(2) * normal.z * 1.023328 +
1379
+ c(3) * normal.x * 1.023328 +
1380
+ c(4) * normal.x * normal.y * 0.858086 +
1381
+ c(5) * normal.y * normal.z * 0.858086 +
1382
+ c(6) * (normal.z * normal.z * 0.743125 - 0.247708) +
1383
+ c(7) * normal.x * normal.z * 0.858086 +
1384
+ c(8) * (normal.x * normal.x - normal.y * normal.y) * 0.429043
1385
+ );
1386
+ }
1387
+
1388
+ function normalizeBounds(value: IProbeVolumeOptions["bounds"]): Box3 {
1389
+ const min = new Vector3(value.min.x, value.min.y, value.min.z);
1390
+ const max = new Vector3(value.max.x, value.max.y, value.max.z);
1391
+ for (const [name, vector] of [
1392
+ ["min", min],
1393
+ ["max", max],
1394
+ ] as const) {
1395
+ if (![vector.x, vector.y, vector.z].every(Number.isFinite)) {
1396
+ throw new Error(`ProbeVolume bounds.${name} must contain finite x, y, and z values.`);
1397
+ }
1398
+ }
1399
+ if (!(min.x < max.x && min.y < max.y && min.z < max.z)) {
1400
+ throw new Error(
1401
+ "ProbeVolume bounds must be non-degenerate and min must be below max on every axis.",
1402
+ );
1403
+ }
1404
+ return new Box3(min, max);
1405
+ }
1406
+
1407
+ function normalizeDensity(value: ProbeVolumeDensity): Vector3 {
1408
+ let density: Vector3;
1409
+ if (typeof value === "number") {
1410
+ density = new Vector3(value, value, value);
1411
+ } else if ("x" in value) {
1412
+ density = new Vector3(value.x, value.y, value.z);
1413
+ } else {
1414
+ density = new Vector3(value[0] ?? Number.NaN, value[1] ?? Number.NaN, value[2] ?? Number.NaN);
1415
+ }
1416
+ if (![density.x, density.y, density.z].every((axis) => Number.isFinite(axis) && axis > 0)) {
1417
+ throw new Error("ProbeVolume density must be finite and greater than zero on every axis.");
1418
+ }
1419
+ return density;
1420
+ }
1421
+
1422
+ function resolutionForAxis(size: number, density: number, axis: string): number {
1423
+ const resolution = Math.ceil(size * density) + 1;
1424
+ if (!Number.isSafeInteger(resolution) || resolution < 2) {
1425
+ throw new Error(`ProbeVolume density on ${axis} produces an invalid probe resolution.`);
1426
+ }
1427
+ return resolution;
1428
+ }
1429
+
1430
+ function checkedAtlasDepth(zResolution: number): number {
1431
+ const depth = PACKED_SUB_VOLUME_COUNT * (zResolution + 2 * ATLAS_PADDING);
1432
+ if (!Number.isSafeInteger(depth)) {
1433
+ throw new Error("ProbeVolume maxTextureDimension3D would be exceeded by the atlas depth.");
1434
+ }
1435
+ return depth;
1436
+ }
1437
+
1438
+ function checkedIntegerProduct(a: number, b: number, c: number, label: string): number {
1439
+ const result = a * b * c;
1440
+ if (!Number.isSafeInteger(result) || result <= 0) {
1441
+ throw new Error(`ProbeVolume ${label} exceeds the device texture limit.`);
1442
+ }
1443
+ return result;
1444
+ }
1445
+
1446
+ function positiveNumber(value: number, name: string): number {
1447
+ if (!Number.isFinite(value) || value <= 0)
1448
+ throw new Error(`ProbeVolume ${name} must be finite and positive.`);
1449
+ return value;
1450
+ }
1451
+
1452
+ function positiveInteger(value: number, name: string): number {
1453
+ if (!Number.isSafeInteger(value) || value <= 0)
1454
+ throw new Error(`ProbeVolume ${name} must be a positive integer.`);
1455
+ return value;
1456
+ }
1457
+
1458
+ function nonNegativeInteger(value: number, name: string): number {
1459
+ if (!Number.isSafeInteger(value) || value < 0)
1460
+ throw new Error(`ProbeVolume ${name} must be a non-negative integer.`);
1461
+ return value;
1462
+ }
1463
+
1464
+ function validateTextureLimit(value: number): void {
1465
+ if (!Number.isSafeInteger(value) || value <= 0) {
1466
+ throw new Error(
1467
+ `ProbeVolume maxTextureDimension3D must be a positive integer, received ${String(value)}.`,
1468
+ );
1469
+ }
1470
+ }
1471
+
1472
+ function assertTextureLimit(dimension: number, limit: number): void {
1473
+ if (dimension > limit) {
1474
+ throw new Error(
1475
+ `ProbeVolume atlas dimension ${dimension} exceeds maxTextureDimension3D device texture limit ${limit}.`,
1476
+ );
1477
+ }
1478
+ }
1479
+
1480
+ function readTextureLimit(renderer: IProbeRenderer): number | undefined {
1481
+ const limit =
1482
+ renderer.backend?.device?.limits?.maxTextureDimension3D ??
1483
+ renderer.device?.limits?.maxTextureDimension3D;
1484
+ return typeof limit === "number" && Number.isSafeInteger(limit) && limit > 0 ? limit : undefined;
1485
+ }
1486
+
1487
+ function isProbeVolumeObservation(value: unknown): value is IProbeVolumeObservation {
1488
+ if (!isRecord(value) || value.marker !== PROBE_VOLUME_MARKER) return false;
1489
+ const atlas = value.atlas;
1490
+ const progress = value.bakeProgress;
1491
+ const status = value.status;
1492
+ const stale = value.stale;
1493
+ const unbaked = value.unbaked;
1494
+ const stalenessFrames = value.stalenessFrames;
1495
+ const probeCount = value.probeCount;
1496
+ const atlasBytes = value.atlasBytes;
1497
+ const bakeCostMs = value.bakeCostMs;
1498
+ const bakeBudgetMs = value.bakeBudgetMs;
1499
+ const samplingIsolated = value.samplingIsolated;
1500
+ if (
1501
+ !isProbeVolumeStatus(status) ||
1502
+ typeof stale !== "boolean" ||
1503
+ typeof unbaked !== "boolean" ||
1504
+ !isStalenessFrames(stalenessFrames) ||
1505
+ !isPositiveIntegerValue(probeCount) ||
1506
+ !isPositiveIntegerValue(atlasBytes) ||
1507
+ !isFiniteNonNegative(bakeCostMs) ||
1508
+ !isFinitePositive(bakeBudgetMs) ||
1509
+ typeof samplingIsolated !== "boolean"
1510
+ )
1511
+ return false;
1512
+ if (!isProbeVolumeAtlas(atlas, probeCount, atlasBytes)) return false;
1513
+ if (!isProbeVolumeBakeProgress(progress, status, probeCount, atlas.depth)) return false;
1514
+ if (stale !== (status !== "ready") || unbaked !== (status === "unbaked")) return false;
1515
+ if (status === "baking" && samplingIsolated !== (progress.pass === 0)) return false;
1516
+ return status !== "ready" || (stalenessFrames !== null && !samplingIsolated);
1517
+ }
1518
+
1519
+ function isProbeVolumeAtlas(
1520
+ value: unknown,
1521
+ probeCount: number,
1522
+ atlasBytes: number,
1523
+ ): value is IProbeVolumeObservation["atlas"] {
1524
+ if (!isRecord(value)) return false;
1525
+ const width = value.width;
1526
+ const height = value.height;
1527
+ const depth = value.depth;
1528
+ if (
1529
+ !isPositiveIntegerValue(width) ||
1530
+ !isPositiveIntegerValue(height) ||
1531
+ !isPositiveIntegerValue(depth) ||
1532
+ width < 2 ||
1533
+ height < 2 ||
1534
+ depth % PACKED_SUB_VOLUME_COUNT !== 0
1535
+ )
1536
+ return false;
1537
+ const paddedSlices = depth / PACKED_SUB_VOLUME_COUNT;
1538
+ const resolutionZ = paddedSlices - 2 * ATLAS_PADDING;
1539
+ if (!isPositiveIntegerValue(resolutionZ) || resolutionZ < 2) return false;
1540
+ const expectedProbeCount = width * height * resolutionZ;
1541
+ const expectedAtlasBytes = width * height * depth * BYTES_PER_TEXEL;
1542
+ return (
1543
+ isPositiveIntegerValue(expectedProbeCount) &&
1544
+ isPositiveIntegerValue(expectedAtlasBytes) &&
1545
+ probeCount === expectedProbeCount &&
1546
+ atlasBytes === expectedAtlasBytes
1547
+ );
1548
+ }
1549
+
1550
+ function isProbeVolumeBakeProgress(
1551
+ value: unknown,
1552
+ status: IProbeVolumeObservation["status"],
1553
+ probeCount: number,
1554
+ atlasDepth: number,
1555
+ ): value is IProbeVolumeBakeProgress {
1556
+ if (!isProbeVolumeBakeProgressShape(value)) return false;
1557
+ const { completed, total, fraction, probesCompleted, probesTotal, pass, passes } = value;
1558
+ const expectedProbesTotal = probeCount * passes;
1559
+ const workPerPass = probeCount * CAPTURE_WORK_ITEMS_PER_PROBE + atlasDepth;
1560
+ const expectedTotal = workPerPass * passes;
1561
+ if (
1562
+ !isPositiveIntegerValue(expectedProbesTotal) ||
1563
+ !isPositiveIntegerValue(workPerPass) ||
1564
+ !isPositiveIntegerValue(expectedTotal) ||
1565
+ total !== expectedTotal ||
1566
+ probesTotal !== expectedProbesTotal ||
1567
+ pass >= passes ||
1568
+ completed > total ||
1569
+ probesCompleted > probesTotal ||
1570
+ fraction !== completed / total
1571
+ )
1572
+ return false;
1573
+ if (status === "ready") {
1574
+ return completed === total && probesCompleted === probesTotal && pass === passes - 1;
1575
+ }
1576
+ if (status === "unbaked") {
1577
+ return completed === 0 && probesCompleted === 0 && pass === 0;
1578
+ }
1579
+ if (completed >= total) return false;
1580
+ const passWorkStart = pass * workPerPass;
1581
+ const passProbesStart = pass * probeCount;
1582
+ if (!Number.isSafeInteger(passWorkStart) || !Number.isSafeInteger(passProbesStart)) return false;
1583
+ const currentWork = completed - passWorkStart;
1584
+ const currentProbes = probesCompleted - passProbesStart;
1585
+ if (
1586
+ currentWork < 0 ||
1587
+ currentWork >= workPerPass ||
1588
+ currentProbes < 0 ||
1589
+ currentProbes > probeCount
1590
+ )
1591
+ return false;
1592
+ if (currentProbes === probeCount) return currentWork >= probeCount * CAPTURE_WORK_ITEMS_PER_PROBE;
1593
+ const minimumWork = currentProbes * CAPTURE_WORK_ITEMS_PER_PROBE;
1594
+ return (
1595
+ currentWork >= minimumWork && currentWork <= minimumWork + CAPTURE_WORK_ITEMS_PER_PROBE - 1
1596
+ );
1597
+ }
1598
+
1599
+ function isProbeVolumeBakeProgressShape(value: unknown): value is IProbeVolumeBakeProgress {
1600
+ if (!isRecord(value)) return false;
1601
+ return (
1602
+ isProgressValue(value.completed) &&
1603
+ isProgressValue(value.total) &&
1604
+ isUnitInterval(value.fraction) &&
1605
+ isProgressValue(value.probesCompleted) &&
1606
+ isProgressValue(value.probesTotal) &&
1607
+ isProgressValue(value.pass) &&
1608
+ isPositiveIntegerValue(value.passes)
1609
+ );
1610
+ }
1611
+
1612
+ function isRecord(value: unknown): value is Record<string, unknown> {
1613
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1614
+ }
1615
+
1616
+ function isProbeVolumeStatus(value: unknown): value is IProbeVolumeObservation["status"] {
1617
+ return value === "unbaked" || value === "baking" || value === "ready";
1618
+ }
1619
+
1620
+ function isStalenessFrames(value: unknown): value is number | null {
1621
+ return value === null || isProgressValue(value);
1622
+ }
1623
+
1624
+ function isPositiveIntegerValue(value: unknown): value is number {
1625
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
1626
+ }
1627
+
1628
+ function isProgressValue(value: unknown): value is number {
1629
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
1630
+ }
1631
+
1632
+ function isUnitInterval(value: unknown): value is number {
1633
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
1634
+ }
1635
+
1636
+ function isFiniteNonNegative(value: unknown): value is number {
1637
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
1638
+ }
1639
+
1640
+ function isFinitePositive(value: unknown): value is number {
1641
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
1642
+ }
1643
+
1644
+ function validateProbeIndex(index: number, length: number, name: string): void {
1645
+ if (!Number.isSafeInteger(index) || index < 0 || index >= length) {
1646
+ throw new Error(`ProbeVolume ${name} must be an integer in [0, ${length - 1}].`);
1647
+ }
1648
+ }
1649
+
1650
+ function valueAt<T>(values: readonly T[], index: number, label: string): T {
1651
+ const value = values[index];
1652
+ if (value === undefined) throw new Error(`ProbeVolume ${label} ${index} is missing.`);
1653
+ return value;
1654
+ }
1655
+
1656
+ function deferred(): IBakePromise {
1657
+ let resolvePromise: () => void = () => undefined;
1658
+ let rejectPromise: (error: unknown) => void = () => undefined;
1659
+ const promise = new Promise<void>((resolve, reject) => {
1660
+ resolvePromise = resolve;
1661
+ rejectPromise = reject;
1662
+ });
1663
+ return { promise, reject: rejectPromise, resolve: resolvePromise };
1664
+ }
1665
+
1666
+ function isRendererLike(value: IRendererLike | Scene): value is IRendererLike {
1667
+ return typeof value === "object" && value !== null && "kind" in value && "raw" in value;
1668
+ }