@threenative/core 0.3.11 → 0.3.13

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 (236) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1988 -204
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  5. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  6. package/dist/chunk-4SRAQFTU.js +133 -0
  7. package/dist/chunk-CFGTPFUH.js +231 -0
  8. package/dist/chunk-DIPIJICH.js +8916 -0
  9. package/dist/chunk-EEABDLUC.js +2237 -0
  10. package/dist/chunk-EFWZWLPY.js +1895 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-GYUZJQ7U.js +280 -0
  13. package/dist/chunk-H4J6IAJE.js +504 -0
  14. package/dist/chunk-KIRUKTBQ.js +187 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-SV4QVUTQ.js +31 -0
  17. package/dist/chunk-U4YHUKKL.js +615 -0
  18. package/dist/chunk-VP43GIWW.js +18 -0
  19. package/dist/chunk-XDTZ4QMO.js +160 -0
  20. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  21. package/dist/{game-DzMcitDO.d.ts → game-k8K3hZai.d.ts} +85 -9
  22. package/dist/hot.d.ts +5 -4
  23. package/dist/hot.js +5 -52
  24. package/dist/index.d.ts +633 -1351
  25. package/dist/index.js +12873 -23068
  26. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-DPTzeCcD.d.ts} +35 -3
  27. package/dist/playtest.d.ts +5 -4
  28. package/dist/playtest.js +25 -75
  29. package/dist/quality-BYqKGAwo.d.ts +868 -0
  30. package/dist/react-css.js +1 -215
  31. package/dist/react.d.ts +3 -2
  32. package/dist/render-environment.d.ts +170 -0
  33. package/dist/render-environment.js +352 -0
  34. package/dist/{renderer-rZm0hVqq.d.ts → renderer-BtOSseYf.d.ts} +42 -35
  35. package/dist/spells/index.d.ts +643 -0
  36. package/dist/spells/index.js +1558 -0
  37. package/dist/spells/ultra/index.d.ts +1600 -0
  38. package/dist/spells/ultra/index.js +6804 -0
  39. package/dist/terrain-jobs-worker.js +1 -123
  40. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  41. package/dist/ui-layer.js +6 -384
  42. package/dist/worker.js +13 -43
  43. package/dist/world.d.ts +988 -268
  44. package/dist/world.js +17464 -18290
  45. package/mcp/animation-server.mjs +1 -1
  46. package/mcp/animation.mjs +2 -3
  47. package/mcp/engine-server.mjs +245 -52
  48. package/mcp/servers.mjs +10 -3
  49. package/mcp/terrain.mjs +8 -0
  50. package/package.json +19 -7
  51. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  52. package/patches/three@0.187.0.patch +2004 -407
  53. package/src/animation-batch.ts +193 -0
  54. package/src/animation-layers.ts +7 -3
  55. package/src/animation.ts +209 -29
  56. package/src/asset-cache.ts +3 -3
  57. package/src/asset-memo.ts +202 -0
  58. package/src/assets.ts +437 -125
  59. package/src/auto-batch.ts +190 -44
  60. package/src/card-lod.ts +152 -0
  61. package/src/compressed-texture-preparation.ts +1008 -0
  62. package/src/compute-driven.ts +1 -1
  63. package/src/config.ts +8 -0
  64. package/src/debug.ts +103 -22
  65. package/src/dev-global.ts +54 -0
  66. package/src/engine-hooks.ts +37 -0
  67. package/src/frame-budget.ts +50 -23
  68. package/src/game-boot-phase.ts +269 -0
  69. package/src/game-dev-tools.ts +86 -0
  70. package/src/game-frame-loop.ts +958 -0
  71. package/src/game-renderer-metrics.ts +77 -0
  72. package/src/game-startup.ts +1076 -0
  73. package/src/game-ui.ts +84 -0
  74. package/src/game-validate.ts +70 -0
  75. package/src/game.ts +198 -2264
  76. package/src/gamepad-mappings.ts +269 -0
  77. package/src/generated/console-markers.ts +13 -0
  78. package/src/geometry-capture.ts +28 -4
  79. package/src/gpu-readings.ts +98 -0
  80. package/src/gpu-scene-bvh.ts +149 -36
  81. package/src/hot.ts +4 -7
  82. package/src/index.ts +141 -9
  83. package/src/input.ts +237 -25
  84. package/src/instanced-batch-lod.ts +3 -8
  85. package/src/interpolation.ts +171 -40
  86. package/src/launch-diagnostics.ts +22 -12
  87. package/src/look/ao-admission.ts +25 -0
  88. package/src/look/auto-exposure.ts +5 -16
  89. package/src/look/default-tone-mapping.ts +41 -5
  90. package/src/look/filmic-tone-mapping.ts +15 -13
  91. package/src/look/local-exposure.ts +2 -7
  92. package/src/look/look-diagnostics.ts +3 -3
  93. package/src/look/quad-pass.ts +21 -0
  94. package/src/look/quality.ts +14 -5
  95. package/src/look/unreal-bloom.ts +4 -13
  96. package/src/look/world-environment.ts +113 -103
  97. package/src/loop.ts +29 -0
  98. package/src/merge-parts.ts +20 -24
  99. package/src/model-lod.ts +139 -17
  100. package/src/particle-kinds.ts +515 -0
  101. package/src/particle-significance.ts +12 -0
  102. package/src/particles.ts +19 -10
  103. package/src/picking.ts +17 -3
  104. package/src/platform.ts +23 -4
  105. package/src/playtest.ts +27 -1
  106. package/src/profiling/FrameStages.ts +5 -6
  107. package/src/profiling/Spans.ts +3 -17
  108. package/src/profiling/debug-telemetry.ts +2 -6
  109. package/src/profiling/render-list-validate.ts +6 -15
  110. package/src/projection-apply.ts +4 -1
  111. package/src/projection-marker.ts +2 -1
  112. package/src/projection-plan.ts +9 -6
  113. package/src/quiet-markers.ts +3 -10
  114. package/src/render/cpu-bvh.ts +100 -0
  115. package/src/render/depth-pyramid.ts +6 -14
  116. package/src/render/environment/environmentContribution.ts +202 -0
  117. package/src/render/environment/environmentRadiance.ts +44 -0
  118. package/src/render/environment/environmentSampleCache.ts +56 -0
  119. package/src/render/environment/environmentSampling.ts +201 -0
  120. package/src/render/environment/environmentSnapshot.ts +71 -0
  121. package/src/render/environment/gate.ts +57 -0
  122. package/src/render/mesh-pool.ts +4 -20
  123. package/src/render/probe-trace.ts +872 -0
  124. package/src/render/probe-volume.ts +780 -34
  125. package/src/render/radiance-cache.ts +17 -0
  126. package/src/render/resolution-subrect.ts +2 -0
  127. package/src/render/rough-diffuse.ts +46 -12
  128. package/src/render/soft-shadow.ts +27 -12
  129. package/src/render/virtual-shadow-adaptive.ts +55 -0
  130. package/src/render/virtual-shadow-casters.ts +175 -0
  131. package/src/render/virtual-shadow-layers.ts +76 -0
  132. package/src/render/virtual-shadow-level.ts +224 -0
  133. package/src/render/virtual-shadow-markers.ts +193 -0
  134. package/src/render/virtual-shadow-options.ts +370 -0
  135. package/src/render/virtual-shadow-pages.ts +5 -0
  136. package/src/render/virtual-shadow-partial.ts +13 -0
  137. package/src/render/virtual-shadow.ts +231 -1008
  138. package/src/render/world-impostor-surface.ts +402 -40
  139. package/src/render/world-impostor.ts +5 -2
  140. package/src/render-camera-cull.ts +98 -3
  141. package/src/render-environment.ts +41 -0
  142. package/src/render-pass-budget.ts +34 -7
  143. package/src/renderProjection.ts +22 -0
  144. package/src/renderer-config.ts +36 -0
  145. package/src/renderer-facts.ts +37 -0
  146. package/src/renderer.ts +144 -65
  147. package/src/resolution-scaler.ts +3 -2
  148. package/src/scene-entry-inspectors.ts +61 -0
  149. package/src/snow-field.ts +2 -1
  150. package/src/spells/cast-pool.ts +361 -0
  151. package/src/spells/index.ts +177 -0
  152. package/src/spells/mechanisms.ts +295 -0
  153. package/src/spells/reaction-field.ts +415 -0
  154. package/src/spells/spell-lights.ts +139 -0
  155. package/src/spells/spell-world.ts +187 -0
  156. package/src/spells/spell.ts +397 -0
  157. package/src/spells/spells.ts +283 -0
  158. package/src/spells/ultra/engine/camera.ts +184 -0
  159. package/src/spells/ultra/engine/quality.ts +96 -0
  160. package/src/spells/ultra/index.ts +52 -0
  161. package/src/spells/ultra/main.ts +305 -0
  162. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  163. package/src/spells/ultra/spells/cast.ts +233 -0
  164. package/src/spells/ultra/spells/fire.ts +1267 -0
  165. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  166. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  167. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  168. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  169. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  170. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  171. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  172. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  173. package/src/spells/ultra/vfx/common.ts +1195 -0
  174. package/src/spells/ultra/vfx/noise.ts +441 -0
  175. package/src/startup-offscreen-bytes.ts +78 -0
  176. package/src/startup-readiness.ts +128 -34
  177. package/src/static-transform.ts +25 -19
  178. package/src/streamed-textures.ts +112 -0
  179. package/src/streaming.ts +68 -4
  180. package/src/texture-streaming.ts +331 -0
  181. package/src/version.ts +1 -1
  182. package/src/warmup.ts +56 -8
  183. package/src/water-surface.ts +9 -3
  184. package/src/worker.ts +12 -2
  185. package/src/world-bundle-safety.ts +446 -0
  186. package/src/world-cell-batches.ts +1178 -0
  187. package/src/world-cell-chunks.ts +1128 -0
  188. package/src/world-cell-data.ts +995 -0
  189. package/src/world-cell-impostors.ts +1461 -0
  190. package/src/world-cell-lod-bias.ts +151 -0
  191. package/src/world-cell-models.ts +1074 -0
  192. package/src/world-cell-options.ts +177 -0
  193. package/src/world-cell-placements.ts +798 -0
  194. package/src/world-cell-prewarm.ts +592 -0
  195. package/src/world-cell-readiness.ts +357 -0
  196. package/src/world-cell-records.ts +401 -0
  197. package/src/world-cell-render-bundles.ts +459 -0
  198. package/src/world-cell-render-gpu-dress.ts +710 -0
  199. package/src/world-cell-render-main-cull.ts +540 -0
  200. package/src/world-cell-render-shadow-claims.ts +198 -0
  201. package/src/world-cell-render-util.ts +259 -0
  202. package/src/world-cell-render.ts +1501 -0
  203. package/src/world-cell-residency.ts +754 -0
  204. package/src/world-cell-stale.ts +238 -0
  205. package/src/world-cells.ts +1335 -10418
  206. package/src/world-chunk-shadow.ts +308 -0
  207. package/src/world-collar.ts +315 -0
  208. package/src/world-gpu-flags.ts +131 -0
  209. package/src/world-gpu-readback.ts +881 -0
  210. package/src/world-gpu-reference.ts +524 -0
  211. package/src/world-gpu-scene.ts +256 -2286
  212. package/src/world-gpu-shadow.ts +203 -0
  213. package/src/world-gpu-types.ts +409 -0
  214. package/src/world-gpu-validation.ts +518 -0
  215. package/src/world-heightfield.ts +802 -0
  216. package/src/world-load-limiter.ts +111 -0
  217. package/src/world-model-sections.ts +80 -0
  218. package/src/world-noise.ts +241 -0
  219. package/src/world-package.ts +42 -0
  220. package/src/world-region.ts +1 -1
  221. package/src/world-river-ribbon.ts +282 -0
  222. package/src/world-root-frame.ts +39 -0
  223. package/src/world-shore-field.ts +91 -0
  224. package/src/world-static-pose.ts +163 -0
  225. package/src/world-surface-sampler.ts +48 -0
  226. package/src/world-terrain-splat.ts +361 -153
  227. package/src/world-tile-budget.ts +249 -0
  228. package/src/world-tile-geometry.ts +469 -0
  229. package/src/world-tile-lod.ts +408 -0
  230. package/src/world-tile-observation.ts +566 -0
  231. package/src/world-tile-stitch.ts +166 -0
  232. package/src/world-tiles.ts +247 -1755
  233. package/src/world-validate.ts +6 -14
  234. package/src/world-warm.ts +51 -0
  235. package/src/world-water-bodies.ts +359 -0
  236. package/src/world.ts +48 -741
@@ -2,8 +2,11 @@ import {
2
2
  Box2,
3
3
  Box3,
4
4
  type Camera,
5
+ type Color,
5
6
  type CoordinateSystem,
6
7
  CubeCamera,
8
+ Frustum,
9
+ Matrix4,
7
10
  Mesh,
8
11
  Object3D,
9
12
  OrthographicCamera,
@@ -14,14 +17,17 @@ import {
14
17
  } from "three";
15
18
  import {
16
19
  Fn,
20
+ abs,
17
21
  clamp,
18
22
  cubeTexture,
19
23
  float,
20
24
  floor,
21
25
  int,
26
+ length,
22
27
  normalWorld,
23
28
  normalize,
24
29
  positionWorld,
30
+ select,
25
31
  texture,
26
32
  texture3D,
27
33
  uniform,
@@ -34,6 +40,7 @@ import {
34
40
  ClampToEdgeWrapping,
35
41
  CubeRenderTarget,
36
42
  Data3DTexture,
43
+ DataTexture,
37
44
  FloatType,
38
45
  HalfFloatType,
39
46
  LinearFilter,
@@ -46,6 +53,20 @@ import {
46
53
  import type { Node, TextureNode } from "three/webgpu";
47
54
  import type { IComputeDriven } from "../compute-driven.js";
48
55
  import type { IRendererLike } from "../renderer.js";
56
+ import {
57
+ BACKFACE_REJECTION_SHARE,
58
+ type ILightingKey,
59
+ type IProbeTraceKernels,
60
+ type IProbeTraceLighting,
61
+ type IProbeTraceScene,
62
+ applyTraceLighting,
63
+ createProbeTraceKernels,
64
+ fillRejectedProbes,
65
+ lightingKey,
66
+ lightingStepped,
67
+ threadScene,
68
+ writeMaterialTable,
69
+ } from "./probe-trace.js";
49
70
 
50
71
  /** The atlas has one copied edge texel on either side of each packed SH sub-volume. */
51
72
  export const ATLAS_PADDING = 1;
@@ -63,6 +84,8 @@ const CAPTURE_WORK_ITEMS_PER_PROBE = CUBE_FACE_COUNT + 2;
63
84
  const SAMPLE_ATLAS_PADDING = 1;
64
85
  const BYTES_PER_FLOAT = Float32Array.BYTES_PER_ELEMENT;
65
86
  const BYTES_PER_TEXEL = 4 * BYTES_PER_FLOAT;
87
+ /** A traced refresh starts at the PRD-603 gate's 16 probes a frame, then follows the measured GPU cost. */
88
+ const TRACE_START_PROBES = 16;
66
89
  const BAKE_BUDGET_SLACK_MS = 0.5;
67
90
  const SCENE_WARMUP_TIMEOUT_MS = 2_000;
68
91
 
@@ -110,6 +133,58 @@ export interface IProbeVolumeOptions {
110
133
  /** Injectable clock for deterministic scheduling tests. */
111
134
  readonly now?: () => number;
112
135
  readonly report?: (line: string) => void;
136
+ /**
137
+ * Refresh probes by tracing a GPUSceneBVH (PRD-603) instead of drawing the scene six times per probe.
138
+ * The default is `trace` when `trace` inputs are given and `capture` otherwise. `capture` is the named
139
+ * override for scenes that need textured albedo or local lights in their bounce.
140
+ */
141
+ readonly update?: "capture" | "trace";
142
+ /** The traced refresh's inputs: the packed scene, and the sun and sky the game already holds. */
143
+ readonly trace?: IProbeVolumeTrace;
144
+ /** Most probes one frame traces (Unreal's r.Lumen.RadianceCache.NumProbesToTraceBudget, 100). */
145
+ readonly numProbesToTraceBudget?: number;
146
+ /**
147
+ * A fixed batch: probes traced a frame, up to `numProbesToTraceBudget`, whatever the GPU reports. Unset, the batch follows
148
+ * the measured GPU time toward `bakeBudgetMs` and stays at 16 where the adapter reports none (the owned engine today). A
149
+ * capture that must trace a whole field before its frame sets it; a game leaves it unset.
150
+ */
151
+ readonly probesPerFrame?: number;
152
+ /**
153
+ * Rays per probe along one side: `probeResolution` squared rays. The default is 8 (64 rays), the cost gate's
154
+ * figure: an Intel Xe traces about 0.09 ms a probe at 8 and 0.41 ms at 32 (1,024 rays, Unreal's radiance-cache
155
+ * ProbeResolution). A small emitter far from a probe needs the larger value to be hit at all.
156
+ */
157
+ readonly probeResolution?: number;
158
+ /**
159
+ * Cells per side of an octahedral radiance map per probe, beside the SH: the traced rays binned by direction, as
160
+ * Unreal's radiance cache stores 32 x 32 radiance per probe (UE 5.8.3:
161
+ * Engine/Source/Runtime/Renderer/Private/Lumen/LumenScreenProbeGather.cpp:641, GRadianceCacheProbeResolution).
162
+ * `sampleRadianceNode` then reads the map, sharp where SH L2 smears a coloured wall across the sphere. 0 (the default)
163
+ * keeps SH only. Traced refresh only.
164
+ */
165
+ readonly radianceProbeResolution?: number;
166
+ /**
167
+ * Weight each of the eight probes a read blends by Unreal's depth test: a probe whose map depth toward the read point is
168
+ * shorter than the point's distance sees a surface first, so it sits behind a wall and drops out (UE 5.8.3:
169
+ * Engine/Shaders/Private/Lumen/LumenRadianceCacheInterpolation.ush:390, `StepHitDistanceFromProbe` against
170
+ * `StepRayDistanceFromProbeSq`). Stops light leaking through a wall thinner than a probe spacing. Needs
171
+ * `radianceProbeResolution`. Off by default.
172
+ */
173
+ readonly probeVisibility?: boolean;
174
+ }
175
+
176
+ /** What a traced refresh reads. Every value is the game's: the volume owns no light and no colour. */
177
+ export interface IProbeVolumeTrace {
178
+ /** A GPUSceneBVH, or anything with its CPU snapshot and version. */
179
+ readonly bvh: { readonly traceScene: IProbeTraceScene; readonly version: number };
180
+ /** World direction toward the sun, its linear colour and its intensity; read every frame. */
181
+ readonly sun: { readonly direction: Vector3; readonly color: Color; readonly intensity: number };
182
+ /** Radiance of a ray that leaves the scene; black for a closed interior. Read every frame. */
183
+ readonly sky: Color;
184
+ /** Point lights read every frame; the first `points.length` at build are traced (see `IProbeTraceLighting`). */
185
+ readonly points?: IProbeTraceLighting["points"];
186
+ /** The view whose frustum marks probes as in use, so they refresh first. Absent: none ranks first. */
187
+ readonly camera?: Camera;
113
188
  }
114
189
 
115
190
  export interface IProbeVolumeBakeProgress {
@@ -138,6 +213,16 @@ export interface IProbeVolumeObservation {
138
213
  readonly bakeBudgetMs: number;
139
214
  /** True while pass zero samples a black texture instead of a previous bake. */
140
215
  readonly samplingIsolated: boolean;
216
+ /** Which refresh ran: `capture` (six scene draws a probe) or `trace` (one dispatch). Absent means capture. */
217
+ readonly update?: "capture" | "trace";
218
+ /** Trace path: probes traced in the last frame. */
219
+ readonly probesTraced?: number;
220
+ /** Trace path: probes of the last field that sat inside a solid or behind a wall, filled from open neighbours. */
221
+ readonly probesRejected?: number;
222
+ /** Trace path: frames since the least recently traced probe was traced, `null` while one never was. */
223
+ readonly oldestProbeAgeFrames?: number | null;
224
+ /** Trace path: materials whose texture or node graph the flat material table ignored. */
225
+ readonly ignoredTextureMaterials?: number;
141
226
  }
142
227
 
143
228
  /** Read a complete marker-shaped observation without accepting malformed data. */
@@ -307,6 +392,43 @@ export class ProbeVolume extends Object3D implements IComputeDriven {
307
392
  #samplingIsolated = false;
308
393
  #lastReported = "";
309
394
  #released = false;
395
+ // The traced refresh (PRD-603). Undefined on a capture volume.
396
+ readonly #trace: IProbeVolumeTrace | undefined;
397
+ readonly #traceBudget: number;
398
+ /** Probes traced a frame now: it follows the measured GPU cost toward `bakeBudgetMs`, up to the budget. */
399
+ #traceRate = 0;
400
+ /** `probesPerFrame` was set: the GPU reading never moves the batch. */
401
+ readonly #fixedTraceRate: boolean;
402
+ /** The last four batch sizes: a timestamp arrives frames late, so a reading is charged to the smallest of them. */
403
+ #recentBatches: number[] = [];
404
+ readonly #raysPerProbe: number;
405
+ readonly #mapResolution: number;
406
+ readonly #visibility: boolean;
407
+ #radianceMapTexture?: DataTexture;
408
+ #kernels: IProbeTraceKernels | undefined;
409
+ #kernelVersion = -1;
410
+ #ignoredTextureMaterials = 0;
411
+ /** Per probe: 1 while it waits for a trace. */
412
+ #lightingKey: ILightingKey | undefined;
413
+ #traceStale: Uint8Array;
414
+ /** Per probe: the frame of its last trace, -1 before the first. */
415
+ #lastTraced: Int32Array;
416
+ /** Per probe: the last frame it sat inside the camera frustum, -1 before. */
417
+ #lastUsed: Int32Array;
418
+ #frame = 0;
419
+ #probesTraced = 0;
420
+ #tracePass = 0;
421
+ #tracePasses = 1;
422
+ #traceCompleted = 0;
423
+ #generations = 0;
424
+ #dispatchSerial = 0;
425
+ #readbackSerial = 0;
426
+ /** Probes of the last traced field that sat inside a solid or behind a wall, filled from their open neighbours. */
427
+ #probesRejected = 0;
428
+ #readbackInFlight = false;
429
+ #passSerial = -1;
430
+ readonly #frustum = new Frustum();
431
+ readonly #viewProjection = new Matrix4();
310
432
 
311
433
  constructor(options: IProbeVolumeOptions) {
312
434
  super();
@@ -324,6 +446,36 @@ export class ProbeVolume extends Object3D implements IComputeDriven {
324
446
  if (this.#far <= this.#near) throw new Error("ProbeVolume far must be greater than near.");
325
447
  this.#bounces = nonNegativeInteger(options.bounces ?? 0, "bounces");
326
448
  this.#bakePasses = this.#bounces + 1;
449
+ const update = options.update ?? (options.trace === undefined ? "capture" : "trace");
450
+ if (update !== "capture" && update !== "trace")
451
+ throw new Error(
452
+ `ProbeVolume update must be "capture" or "trace", received ${String(update)}.`,
453
+ );
454
+ if (update === "trace" && options.trace === undefined)
455
+ throw new Error('ProbeVolume update "trace" needs trace inputs: { bvh, sun, sky }.');
456
+ this.#trace = update === "trace" ? options.trace : undefined;
457
+ this.#traceBudget = positiveInteger(
458
+ options.numProbesToTraceBudget ?? 100,
459
+ "numProbesToTraceBudget",
460
+ );
461
+ this.#fixedTraceRate = options.probesPerFrame !== undefined;
462
+ this.#traceRate = Math.min(
463
+ this.#traceBudget,
464
+ options.probesPerFrame === undefined
465
+ ? TRACE_START_PROBES
466
+ : positiveInteger(options.probesPerFrame, "probesPerFrame"),
467
+ );
468
+ const probeResolution = positiveInteger(options.probeResolution ?? 8, "probeResolution");
469
+ this.#raysPerProbe = probeResolution * probeResolution;
470
+ this.#mapResolution =
471
+ options.radianceProbeResolution === undefined || options.radianceProbeResolution === 0
472
+ ? 0
473
+ : positiveInteger(options.radianceProbeResolution, "radianceProbeResolution");
474
+ this.#visibility = options.probeVisibility === true;
475
+ if (this.#visibility && this.#mapResolution === 0)
476
+ throw new Error(
477
+ "ProbeVolume probeVisibility needs radianceProbeResolution (the map holds the depth).",
478
+ );
327
479
 
328
480
  const normalizedBounds = normalizeBounds(options.bounds);
329
481
  this.boundingBox = normalizedBounds;
@@ -361,6 +513,9 @@ export class ProbeVolume extends Object3D implements IComputeDriven {
361
513
  this.#atlasTexture = createCpuAtlas(this.#atlasData, this.resolution, this.#atlasDepth);
362
514
  this.#emptyAtlasTexture = createCpuAtlas(new Float32Array(4), new Vector3(1, 1, 1), 1);
363
515
  this.#atlasNode = texture3D(this.#atlasTexture);
516
+ this.#traceStale = new Uint8Array(this.#probeCount);
517
+ this.#lastTraced = new Int32Array(this.#probeCount).fill(-1);
518
+ this.#lastUsed = new Int32Array(this.#probeCount).fill(-1);
364
519
  this.#boundsMinNode = uniform(this.boundingBox.min.clone());
365
520
  this.#boundsSizeNode = uniform(this.#boundsSize.clone());
366
521
  this.#publish(true);
@@ -396,6 +551,7 @@ export class ProbeVolume extends Object3D implements IComputeDriven {
396
551
  }
397
552
 
398
553
  get observation(): IProbeVolumeObservation {
554
+ if (this.#trace !== undefined) return this.#traceObservation();
399
555
  const progress = this.#pending;
400
556
  const total = progress?.totalWork ?? this.totalWork;
401
557
  const completed = progress?.completedWork ?? (this.#status === "ready" ? total : 0);
@@ -428,6 +584,55 @@ export class ProbeVolume extends Object3D implements IComputeDriven {
428
584
  };
429
585
  }
430
586
 
587
+ #traceObservation(): IProbeVolumeObservation {
588
+ const perPass = this.#probeCount + 1;
589
+ const passes = this.#tracePasses;
590
+ const ready = this.#status === "ready";
591
+ const baking = this.#status === "baking";
592
+ const pass = ready ? passes - 1 : baking ? this.#tracePass : 0;
593
+ const total = passes * perPass;
594
+ const completed = ready ? total : baking ? pass * perPass + this.#traceCompleted : 0;
595
+ let oldest: number | null = 0;
596
+ for (const traced of this.#lastTraced) {
597
+ if (traced < 0) {
598
+ oldest = null;
599
+ break;
600
+ }
601
+ oldest = Math.max(oldest, this.#frame - traced);
602
+ }
603
+ return {
604
+ atlas: { depth: this.#atlasDepth, height: this.resolution.y, width: this.resolution.x },
605
+ atlasBytes: this.#atlasBytes,
606
+ bakeBudgetMs: this.#bakeBudgetMs,
607
+ bakeCostMs: this.#lastBakeCostMs,
608
+ bakeProgress: {
609
+ completed,
610
+ fraction: completed / total,
611
+ pass,
612
+ passes,
613
+ probesCompleted: ready
614
+ ? this.#probeCount * passes
615
+ : baking
616
+ ? pass * this.#probeCount + this.#traceCompleted
617
+ : 0,
618
+ probesTotal: this.#probeCount * passes,
619
+ total,
620
+ },
621
+ ignoredTextureMaterials: this.#ignoredTextureMaterials,
622
+ marker: PROBE_VOLUME_MARKER,
623
+ oldestProbeAgeFrames: oldest,
624
+ probeCount: this.#probeCount,
625
+ probesRejected: this.#probesRejected,
626
+ probesTraced: this.#probesTraced,
627
+ samplingIsolated: false,
628
+ stale: !ready,
629
+ stalenessFrames: this.#stalenessFrames,
630
+ status: this.#status,
631
+ unbaked: this.#status === "unbaked",
632
+ update: "trace",
633
+ };
634
+ }
635
+
431
636
  /** Attach the active renderer; only WebGPU has the 3D render-target contract this class needs. */
432
637
  attachRenderer(renderer: IRendererLike): void {
433
638
  if (this.#released) throw new Error("ProbeVolume.attachRenderer called after detach().");
@@ -441,6 +646,8 @@ export class ProbeVolume extends Object3D implements IComputeDriven {
441
646
  const raw = renderer.raw as IProbeRenderer;
442
647
  const deviceLimit = readTextureLimit(raw);
443
648
  if (deviceLimit !== undefined) assertTextureLimit(this.maximumDimension, deviceLimit);
649
+ // The traced refresh writes the CPU atlas: no cube camera, no render target, no repack draw.
650
+ if (this.#trace !== undefined) return;
444
651
  this.#startAtlasProbe(raw);
445
652
  this.#ensureGpuResources();
446
653
  if (this.#pending !== undefined) this.#prepareBake(this.#pending.scene, this.#pending.passes);
@@ -452,6 +659,7 @@ export class ProbeVolume extends Object3D implements IComputeDriven {
452
659
  if (!(scene instanceof Scene)) throw new Error("ProbeVolume.requestBake requires a Scene.");
453
660
  const bounces = options.bounces ?? this.#bounces;
454
661
  nonNegativeInteger(bounces, "bounces");
662
+ if (this.#trace !== undefined) return this.#requestTrace(bounces + 1);
455
663
  if (this.#pending !== undefined && this.#bakePromise !== undefined)
456
664
  return this.#bakePromise.promise;
457
665
  this.#bakePasses = bounces + 1;
@@ -524,15 +732,28 @@ export class ProbeVolume extends Object3D implements IComputeDriven {
524
732
  }
525
733
 
526
734
  sampleIrradiance(position: Vector3, normal: Vector3): Vector3 {
735
+ return this.#evaluateCpu(position, normal, SH_IRRADIANCE_WEIGHTS, "sampleIrradiance");
736
+ }
737
+
738
+ /**
739
+ * The radiance arriving along `direction` (the SH itself, not convolved with a cosine lobe), clamped at zero. A
740
+ * screen gather subtracts this per ray, because a hit replaces the cache's radiance along that ray: Lumen reads its
741
+ * radiance cache per ray direction (UE 5.8.3: Engine/Shaders/Private/Lumen/LumenScreenProbeTracing.usf:831).
742
+ */
743
+ sampleRadiance(position: Vector3, direction: Vector3): Vector3 {
744
+ return this.#evaluateCpu(position, direction, SH_RADIANCE_WEIGHTS, "sampleRadiance");
745
+ }
746
+
747
+ #evaluateCpu(position: Vector3, normal: Vector3, weights: IShWeights, name: string): Vector3 {
527
748
  if (!(position instanceof Vector3) || !(normal instanceof Vector3)) {
528
- throw new Error("ProbeVolume.sampleIrradiance requires Vector3 position and normal values.");
749
+ throw new Error(`ProbeVolume.${name} requires Vector3 position and normal values.`);
529
750
  }
530
751
  const coefficients = this.#samplePackedCoefficients(position);
531
752
  const direction = normal.clone().normalize();
532
753
  const result = new Vector3();
533
- result.x = evaluateShChannel(coefficients, 0, direction);
534
- result.y = evaluateShChannel(coefficients, 1, direction);
535
- result.z = evaluateShChannel(coefficients, 2, direction);
754
+ result.x = evaluateShChannel(coefficients, 0, direction, weights);
755
+ result.y = evaluateShChannel(coefficients, 1, direction, weights);
756
+ result.z = evaluateShChannel(coefficients, 2, direction, weights);
536
757
  return result.max(new Vector3());
537
758
  }
538
759
 
@@ -585,8 +806,159 @@ export class ProbeVolume extends Object3D implements IComputeDriven {
585
806
  position: Node<"vec3"> = positionWorld,
586
807
  normal: Node<"vec3"> = normalWorld,
587
808
  ): Node<"vec3"> {
809
+ return this.#shNode(position, normal, SH_IRRADIANCE_WEIGHTS);
810
+ }
811
+
812
+ /** The GPU graph of `sampleRadiance`: the radiance arriving along `direction`, clamped at zero. */
813
+ sampleRadianceNode(
814
+ position: Node<"vec3"> = positionWorld,
815
+ direction: Node<"vec3"> = normalWorld,
816
+ ): Node<"vec3"> {
817
+ return this.#mapResolution > 0
818
+ ? this.#radianceMapNode(position, direction)
819
+ : this.#shNode(position, direction, SH_RADIANCE_WEIGHTS);
820
+ }
821
+
822
+ /**
823
+ * The octahedral maps laid out as one 2D texture: probe (x, y, z) holds the R x R block at column x and row z * ny + y.
824
+ * Rejected probes hold their open neighbours' maps (`fillRejectedProbes`), so a reader weights all eight corners.
825
+ */
826
+ #packRadianceMap(map: Float32Array, shares: Float32Array): void {
827
+ const r = this.#mapResolution;
828
+ // A rejected probe sits inside a solid: depth 0, so the visibility test never weights it.
829
+ for (let probe = 0; probe < this.#probeCount; probe += 1)
830
+ if ((shares[probe] ?? 0) > BACKFACE_REJECTION_SHARE)
831
+ for (let cell = 0; cell < r * r; cell += 1) map[(probe * r * r + cell) * 4 + 3] = 0;
832
+ const { x: nx, y: ny } = this.resolution;
833
+ const width = nx * r;
834
+ const texture = this.#ensureRadianceMapTexture();
835
+ const data = texture.image.data as Float32Array;
836
+ for (let probe = 0; probe < this.#probeCount; probe += 1) {
837
+ const ix = probe % nx;
838
+ const iy = Math.floor(probe / nx) % ny;
839
+ const iz = Math.floor(probe / (nx * ny));
840
+ for (let cell = 0; cell < r * r; cell += 1) {
841
+ const column = ix * r + (cell % r);
842
+ const row = (iz * ny + iy) * r + Math.floor(cell / r);
843
+ const source = (probe * r * r + cell) * 4;
844
+ data.set(map.subarray(source, source + 4), (row * width + column) * 4);
845
+ }
846
+ }
847
+ texture.needsUpdate = true;
848
+ }
849
+
850
+ #ensureRadianceMapTexture(): DataTexture {
851
+ if (this.#radianceMapTexture !== undefined) return this.#radianceMapTexture;
852
+ const r = this.#mapResolution;
853
+ const { x: nx, y: ny, z: nz } = this.resolution;
854
+ const map = new DataTexture(
855
+ new Float32Array(nx * r * ny * nz * r * 4),
856
+ nx * r,
857
+ ny * nz * r,
858
+ RGBAFormat,
859
+ FloatType,
860
+ );
861
+ map.minFilter = NearestFilter;
862
+ map.magFilter = NearestFilter;
863
+ map.generateMipmaps = false;
864
+ map.needsUpdate = true;
865
+ this.#radianceMapTexture = map;
866
+ return map;
867
+ }
868
+
869
+ /** The (column, row) of a direction's cell in an R x R octahedral map, as `octahedralCell` folds it on the CPU. */
870
+ #octahedralCellNode(direction: Node<"vec3">): Node<"vec2"> {
871
+ const r = this.#mapResolution;
872
+ const d = normalize(vec3(direction));
873
+ const flat = d.xy.div(abs(d.x).add(abs(d.y)).add(abs(d.z)));
874
+ const sign = (v: Node<"float">) => select(v.greaterThanEqual(0), float(1), float(-1));
875
+ const folded = vec2(
876
+ float(1).sub(abs(flat.y)).mul(sign(flat.x)),
877
+ float(1).sub(abs(flat.x)).mul(sign(flat.y)),
878
+ );
879
+ const octahedron = select(d.z.lessThan(0), folded, flat);
880
+ return clamp(floor(octahedron.mul(0.5).add(0.5).mul(r)), vec2(0), vec2(r - 1));
881
+ }
882
+
883
+ /** The map texel of `cell` in probe `probe` (grid index), as a texture coordinate. */
884
+ #mapTexelNode(probe: Node<"vec3">, cell: Node<"vec2">): Node<"vec2"> {
885
+ const r = this.#mapResolution;
886
+ const { x: nx, y: ny, z: nz } = this.resolution;
887
+ return vec2(probe.x.mul(r).add(cell.x), probe.z.mul(ny).add(probe.y).mul(r).add(cell.y))
888
+ .add(0.5)
889
+ .div(vec2(nx * r, ny * nz * r));
890
+ }
891
+
892
+ /**
893
+ * The eight probes around `position`: each one's grid index and weight, trilinear and, with `probeVisibility`, times
894
+ * the depth test (a floor of 1e-3 keeps a point that every probe fails lit by plain trilinear). `total` is the sum.
895
+ */
896
+ #cornersNode(position: Node<"vec3">): {
897
+ readonly corners: readonly { readonly probe: Node<"vec3">; readonly weight: Node<"float"> }[];
898
+ readonly total: Node<"float">;
899
+ } {
900
+ const { x: nx, y: ny, z: nz } = this.resolution;
901
+ const min = this.boundingBox.min;
902
+ const size = this.#boundsSize;
903
+ const spacing = [
904
+ size.x / Math.max(1, nx - 1),
905
+ size.y / Math.max(1, ny - 1),
906
+ size.z / Math.max(1, nz - 1),
907
+ ] as const;
908
+ const step = vec3(...spacing);
909
+ const origin = vec3(min.x, min.y, min.z);
910
+ const top = vec3(Math.max(0, nx - 1), Math.max(0, ny - 1), Math.max(0, nz - 1));
911
+ const local = clamp(vec3(position).sub(origin).div(step), vec3(0), top);
912
+ const base = clamp(
913
+ floor(local),
914
+ vec3(0),
915
+ vec3(Math.max(0, nx - 2), Math.max(0, ny - 2), Math.max(0, nz - 2)),
916
+ );
917
+ const fraction = clamp(local.sub(base), vec3(0), vec3(1));
918
+ // The depth test's soft band: a quarter of the smallest spacing past the stored depth fades the probe out.
919
+ const band = 0.25 * Math.max(1e-4, Math.min(...spacing));
920
+ const map = this.#visibility ? this.#ensureRadianceMapTexture() : undefined;
921
+ let total: Node<"float"> = float(0);
922
+ const corners = Array.from({ length: 8 }, (_, corner) => {
923
+ const dx = corner & 1;
924
+ const dy = (corner >> 1) & 1;
925
+ const dz = (corner >> 2) & 1;
926
+ const probe = clamp(base.add(vec3(dx, dy, dz)), vec3(0), top);
927
+ let weight: Node<"float"> = (dx ? fraction.x : float(1).sub(fraction.x))
928
+ .mul(dy ? fraction.y : float(1).sub(fraction.y))
929
+ .mul(dz ? fraction.z : float(1).sub(fraction.z));
930
+ if (map !== undefined) {
931
+ const toPoint = vec3(position).sub(origin.add(probe.mul(step)));
932
+ const distance = length(toPoint);
933
+ const depth = texture(
934
+ map,
935
+ this.#mapTexelNode(probe, this.#octahedralCellNode(toPoint.add(vec3(1e-5, 2e-5, 3e-5)))),
936
+ ).a;
937
+ const visible = clamp(depth.add(band).sub(distance).div(band), 0, 1);
938
+ weight = weight.mul(visible.max(1e-3));
939
+ }
940
+ total = total.add(weight);
941
+ return { probe, weight };
942
+ });
943
+ return { corners, total };
944
+ }
945
+
946
+ /** The map's radiance along `direction`: the direction's cell in each of the eight probes around `position`. */
947
+ #radianceMapNode(position: Node<"vec3">, direction: Node<"vec3">): Node<"vec3"> {
948
+ const map = this.#ensureRadianceMapTexture();
949
+ const cell = this.#octahedralCellNode(direction);
950
+ const { corners, total } = this.#cornersNode(position);
951
+ let sum: Node<"vec3"> = vec3(0);
952
+ for (const { probe, weight } of corners)
953
+ sum = sum.add(texture(map, this.#mapTexelNode(probe, cell)).rgb.mul(weight));
954
+ return sum.div(total.max(1e-6)).max(0);
955
+ }
956
+
957
+ #shNode(position: Node<"vec3">, normal: Node<"vec3">, w: IShWeights): Node<"vec3"> {
588
958
  const atlasAt = this.#atlasAt(position);
589
- const packed = (subVolume: number) => this.#atlasNode.sample(atlasAt(subVolume));
959
+ const packed = this.#visibility
960
+ ? this.#visiblePacked(position)
961
+ : (subVolume: number) => this.#atlasNode.sample(atlasAt(subVolume));
590
962
  const packedValues = Array.from({ length: PACKED_SUB_VOLUME_COUNT }, (_, index) =>
591
963
  packed(index),
592
964
  );
@@ -604,21 +976,50 @@ export class ProbeVolume extends Object3D implements IComputeDriven {
604
976
  ];
605
977
  const direction = normalize(vec3(normal));
606
978
  const coefficientAt = (index: number) => valueAt(coefficients, index, "SH coefficient");
607
- const irradiance = coefficientAt(0)
608
- .mul(0.886227)
609
- .add(coefficientAt(1).mul(direction.y).mul(1.023328))
610
- .add(coefficientAt(2).mul(direction.z).mul(1.023328))
611
- .add(coefficientAt(3).mul(direction.x).mul(1.023328))
612
- .add(coefficientAt(4).mul(direction.x.mul(direction.y)).mul(0.858086))
613
- .add(coefficientAt(5).mul(direction.y.mul(direction.z)).mul(0.858086))
614
- .add(coefficientAt(6).mul(direction.z.mul(direction.z).mul(0.743125).sub(0.247708)))
615
- .add(coefficientAt(7).mul(direction.x.mul(direction.z)).mul(0.858086))
979
+ const value = coefficientAt(0)
980
+ .mul(w.l0)
981
+ .add(coefficientAt(1).mul(direction.y).mul(w.l1))
982
+ .add(coefficientAt(2).mul(direction.z).mul(w.l1))
983
+ .add(coefficientAt(3).mul(direction.x).mul(w.l1))
984
+ .add(coefficientAt(4).mul(direction.x.mul(direction.y)).mul(w.l2))
985
+ .add(coefficientAt(5).mul(direction.y.mul(direction.z)).mul(w.l2))
986
+ .add(coefficientAt(6).mul(direction.z.mul(direction.z).mul(w.l20).sub(w.l20Offset)))
987
+ .add(coefficientAt(7).mul(direction.x.mul(direction.z)).mul(w.l2))
616
988
  .add(
617
989
  coefficientAt(8)
618
990
  .mul(direction.x.mul(direction.x).sub(direction.y.mul(direction.y)))
619
- .mul(0.429043),
991
+ .mul(w.l22),
620
992
  );
621
- return irradiance.max(0);
993
+ return value.max(0);
994
+ }
995
+
996
+ /**
997
+ * The packed SH at `position` blended over the eight corner probes with the depth-tested weights: each corner's texel
998
+ * centre (where the atlas's linear filter returns that probe alone), weighted and renormalised.
999
+ */
1000
+ #visiblePacked(position: Node<"vec3">): (subVolume: number) => Node<"vec4"> {
1001
+ const { x: nx, y: ny, z: nz } = this.resolution;
1002
+ const sliceStride = nz + 2 * SAMPLE_ATLAS_PADDING;
1003
+ const { corners, total } = this.#cornersNode(position);
1004
+ const inverse = float(1).div(total.max(1e-6));
1005
+ return (subVolume) => {
1006
+ let sum: Node<"vec4"> = vec4(0);
1007
+ for (const { probe, weight } of corners)
1008
+ sum = sum.add(
1009
+ this.#atlasNode
1010
+ .sample(
1011
+ vec3(
1012
+ probe.x.add(0.5).div(nx),
1013
+ probe.y.add(0.5).div(ny),
1014
+ probe.z
1015
+ .add(SAMPLE_ATLAS_PADDING + 0.5 + subVolume * sliceStride)
1016
+ .div(this.#atlasDepth),
1017
+ ),
1018
+ )
1019
+ .mul(weight),
1020
+ );
1021
+ return sum.mul(inverse);
1022
+ };
622
1023
  }
623
1024
 
624
1025
  /** Internal data seam used by unit/conformance fixtures to seed a known SH atlas without a GPU. */
@@ -661,6 +1062,10 @@ export class ProbeVolume extends Object3D implements IComputeDriven {
661
1062
  if (this.#renderer === undefined) this.attachRenderer(renderer);
662
1063
  if (this.#renderer !== renderer)
663
1064
  throw new Error("ProbeVolume.process received a different renderer.");
1065
+ if (this.#trace !== undefined) {
1066
+ this.#processTrace(renderer, this.#trace);
1067
+ return;
1068
+ }
664
1069
  if (this.#pending === undefined) {
665
1070
  this.#publishIdleFrame();
666
1071
  return;
@@ -725,6 +1130,281 @@ export class ProbeVolume extends Object3D implements IComputeDriven {
725
1130
  this.#publish(true);
726
1131
  }
727
1132
 
1133
+ /**
1134
+ * Mark every probe stale for `passes` full refreshes. The old field stays readable until each probe is
1135
+ * replaced, and a request made while one runs restarts its passes under the same promise.
1136
+ */
1137
+ #requestTrace(passes: number): Promise<void> {
1138
+ this.#bakePromise ??= deferred();
1139
+ this.#startTracePasses(passes);
1140
+ this.#publish(true);
1141
+ return this.#bakePromise.promise;
1142
+ }
1143
+
1144
+ #startTracePasses(passes: number): void {
1145
+ this.#tracePasses = passes;
1146
+ this.#tracePass = 0;
1147
+ this.#traceCompleted = 0;
1148
+ this.#passSerial = -1;
1149
+ this.#traceStale.fill(1);
1150
+ this.#status = "baking";
1151
+ }
1152
+
1153
+ #processTrace(renderer: IRendererLike, trace: IProbeVolumeTrace): void {
1154
+ this.#frame += 1;
1155
+ this.#probesTraced = 0;
1156
+ let started = this.#now();
1157
+ try {
1158
+ const kernels = this.#ensureKernels(trace, renderer);
1159
+ started = this.#now();
1160
+ const lighting = {
1161
+ color: trace.sun.color,
1162
+ direction: trace.sun.direction,
1163
+ intensity: trace.sun.intensity,
1164
+ sky: trace.sky,
1165
+ points: trace.points,
1166
+ };
1167
+ applyTraceLighting(kernels, lighting);
1168
+ this.#watchLighting(lighting);
1169
+ this.#refreshMaterials(trace, kernels);
1170
+ this.#markUsed(trace.camera);
1171
+ if (this.#status === "baking") this.#dispatchTrace(renderer, kernels);
1172
+ this.#startReadback(renderer, kernels);
1173
+ } catch (error) {
1174
+ this.#failTrace(error);
1175
+ throw error;
1176
+ }
1177
+ if (this.#status === "ready" && this.#stalenessFrames !== null) this.#stalenessFrames += 1;
1178
+ this.#lastBakeCostMs = Math.max(0, this.#now() - started);
1179
+ this.#publish(this.#probesTraced > 0);
1180
+ }
1181
+
1182
+ /**
1183
+ * A small sun drift is served by the old field. The first step past the threshold, measured from the last
1184
+ * step, marks every probe stale: the budget stays, and the old values stay readable until replaced.
1185
+ */
1186
+ #watchLighting(lighting: IProbeTraceLighting): void {
1187
+ const key = lightingKey(lighting);
1188
+ const previous = this.#lightingKey;
1189
+ if (previous === undefined) {
1190
+ this.#lightingKey = key;
1191
+ return;
1192
+ }
1193
+ if (this.#status === "unbaked" || !lightingStepped(previous, key)) return;
1194
+ this.#lightingKey = key;
1195
+ this.#startTracePasses(this.#tracePasses);
1196
+ }
1197
+
1198
+ #ensureKernels(trace: IProbeVolumeTrace, renderer: IRendererLike): IProbeTraceKernels {
1199
+ const version = trace.bvh.version;
1200
+ if (this.#kernels !== undefined && this.#kernelVersion === version) return this.#kernels;
1201
+ const previous = this.#kernels;
1202
+ const threaded = threadScene(trace.bvh.traceScene);
1203
+ this.#ignoredTextureMaterials = threaded.ignoredTextureMaterials;
1204
+ this.#kernels = createProbeTraceKernels(
1205
+ threaded,
1206
+ {
1207
+ min: this.boundingBox.min,
1208
+ probeCount: this.#probeCount,
1209
+ resolution: this.resolution,
1210
+ size: this.#boundsSize,
1211
+ },
1212
+ this.#raysPerProbe,
1213
+ Math.min(this.#traceBudget, this.#probeCount),
1214
+ trace.points?.length ?? 0,
1215
+ this.#mapResolution,
1216
+ );
1217
+ // Carry the field across a scene rebuild, so the new kernels bounce from the old light.
1218
+ if (previous !== undefined) {
1219
+ (this.#kernels.coefficients.array as Float32Array).set(
1220
+ previous.coefficients.array as Float32Array,
1221
+ );
1222
+ if (previous.radianceMap !== undefined)
1223
+ (this.#kernels.radianceMap?.array as Float32Array | undefined)?.set(
1224
+ previous.radianceMap.array as Float32Array,
1225
+ );
1226
+ previous.dispose();
1227
+ }
1228
+ if (this.#kernelVersion >= 0 && this.#status !== "unbaked")
1229
+ this.#startTracePasses(this.#tracePasses);
1230
+ this.#kernelVersion = version;
1231
+ // First-use pipeline work belongs to scene entry, not to a bounded refresh slice: an empty dispatch builds both.
1232
+ this.#kernels.batchSize.value = 0;
1233
+ renderer.compute(this.#kernels.trace);
1234
+ renderer.compute(this.#kernels.project);
1235
+ if (this.#kernels.octahedral !== undefined) renderer.compute(this.#kernels.octahedral);
1236
+ return this.#kernels;
1237
+ }
1238
+
1239
+ /** A material the game changed (a lamp switched on) re-uploads the table and refreshes every probe. */
1240
+ #refreshMaterials(trace: IProbeVolumeTrace, kernels: IProbeTraceKernels): void {
1241
+ // ponytail: every material each frame; a dirty flag from the game when scenes carry thousands.
1242
+ const table = writeMaterialTable(
1243
+ trace.bvh.traceScene.materials,
1244
+ kernels.materials.array as Float32Array,
1245
+ );
1246
+ this.#ignoredTextureMaterials = table.ignored;
1247
+ if (!table.changed) return;
1248
+ kernels.materials.needsUpdate = true;
1249
+ if (this.#status !== "unbaked") this.#startTracePasses(this.#tracePasses);
1250
+ }
1251
+
1252
+ /** A probe is in use while it sits inside the camera frustum: Unreal's last-used frame. */
1253
+ #markUsed(camera: Camera | undefined): void {
1254
+ if (camera === undefined) return;
1255
+ camera.updateMatrixWorld();
1256
+ this.#viewProjection.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
1257
+ this.#frustum.setFromProjectionMatrix(this.#viewProjection, camera.coordinateSystem);
1258
+ const point = new Vector3();
1259
+ for (let probe = 0; probe < this.#probeCount; probe += 1) {
1260
+ this.#probeAt(probe, point);
1261
+ if (this.#frustum.containsPoint(point)) this.#lastUsed[probe] = this.#frame;
1262
+ }
1263
+ }
1264
+
1265
+ #probeAt(probe: number, target: Vector3): Vector3 {
1266
+ const nx = this.resolution.x;
1267
+ const ny = this.resolution.y;
1268
+ return this.probePosition(
1269
+ probe % nx,
1270
+ Math.floor(probe / nx) % ny,
1271
+ Math.floor(probe / (nx * ny)),
1272
+ target,
1273
+ );
1274
+ }
1275
+
1276
+ /**
1277
+ * The stale probes this frame traces, at most the budget: never-traced first, then the largest gap between
1278
+ * last use and last trace (Unreal's priority, UE 5.8.3: LumenRadianceCacheUpdate.usf:221-241), then index.
1279
+ */
1280
+ selectStaleProbes(): number[] {
1281
+ const candidates: number[] = [];
1282
+ for (let probe = 0; probe < this.#probeCount; probe += 1) {
1283
+ if (this.#traceStale[probe] === 1) candidates.push(probe);
1284
+ }
1285
+ // ponytail: a full sort per frame; a bucketed partial selection when volumes reach 1e5 probes.
1286
+ const priority = (probe: number) =>
1287
+ (this.#lastTraced[probe] ?? 0) < 0
1288
+ ? Number.POSITIVE_INFINITY
1289
+ : (this.#lastUsed[probe] ?? -1) - (this.#lastTraced[probe] ?? 0);
1290
+ candidates.sort((a, b) => priority(b) - priority(a) || a - b);
1291
+ return candidates.slice(0, Math.min(this.#traceRate, this.#probeCount));
1292
+ }
1293
+
1294
+ /**
1295
+ * One frame traces the probes its GPU compute time allows: the measured cost of the last batch, per probe,
1296
+ * against `bakeBudgetMs`. A slow adapter shrinks the batch at once; a fast one doubles it a frame, so a stale
1297
+ * reading cannot jump the cost. With no timestamp reading the batch stays at its start of 16 probes.
1298
+ */
1299
+ #adaptTraceRate(renderer: IRendererLike): void {
1300
+ if (this.#fixedTraceRate) return;
1301
+ const gpuMs = (renderer as { gpuComputeMs?: () => number | undefined }).gpuComputeMs?.();
1302
+ if (gpuMs === undefined || !(gpuMs > 0) || this.#recentBatches.length === 0) return;
1303
+ const fit = Math.floor((this.#bakeBudgetMs * Math.min(...this.#recentBatches)) / gpuMs);
1304
+ const ceiling = Math.min(this.#traceBudget, this.#probeCount);
1305
+ const next = fit > this.#traceRate ? Math.min(fit, this.#traceRate * 2) : fit;
1306
+ this.#traceRate = Math.max(1, Math.min(ceiling, next));
1307
+ }
1308
+
1309
+ #dispatchTrace(renderer: IRendererLike, kernels: IProbeTraceKernels): void {
1310
+ this.#adaptTraceRate(renderer);
1311
+ const batch = this.selectStaleProbes();
1312
+ if (batch.length > 0) {
1313
+ batch.forEach((probe, slot) => {
1314
+ (kernels.probeList.array as Float32Array)[slot * 4] = probe;
1315
+ });
1316
+ kernels.probeList.needsUpdate = true;
1317
+ kernels.batchSize.value = batch.length;
1318
+ kernels.bounce.value = this.#generations > 0 ? 1 : 0;
1319
+ renderer.compute(kernels.trace);
1320
+ renderer.compute(kernels.project);
1321
+ if (kernels.octahedral !== undefined) renderer.compute(kernels.octahedral);
1322
+ for (const probe of batch) {
1323
+ this.#traceStale[probe] = 0;
1324
+ this.#lastTraced[probe] = this.#frame;
1325
+ }
1326
+ this.#probesTraced = batch.length;
1327
+ this.#recentBatches = [...this.#recentBatches, batch.length].slice(-4);
1328
+ this.#traceCompleted += batch.length;
1329
+ this.#dispatchSerial += 1;
1330
+ }
1331
+ if (this.#traceCompleted < this.#probeCount) return;
1332
+ // Every probe of this pass is dispatched. The next pass bounces from it; the last waits for its readback.
1333
+ if (this.#tracePass + 1 < this.#tracePasses) {
1334
+ this.#generations += 1;
1335
+ this.#tracePass += 1;
1336
+ this.#traceCompleted = 0;
1337
+ this.#traceStale.fill(1);
1338
+ return;
1339
+ }
1340
+ if (this.#passSerial < 0) this.#passSerial = this.#dispatchSerial;
1341
+ }
1342
+
1343
+ /** Copy the field back into the CPU atlas: one readback at a time, so the atlas never holds half a refresh. */
1344
+ #startReadback(renderer: IRendererLike, kernels: IProbeTraceKernels): void {
1345
+ if (this.#readbackInFlight || this.#readbackSerial >= this.#dispatchSerial) return;
1346
+ const serial = this.#dispatchSerial;
1347
+ this.#readbackInFlight = true;
1348
+ Promise.all([
1349
+ renderer.readback(kernels.coefficients),
1350
+ kernels.radianceMap === undefined ? undefined : renderer.readback(kernels.radianceMap),
1351
+ ]).then(
1352
+ ([bytes, map]) => {
1353
+ this.#readbackInFlight = false;
1354
+ if (this.#released || this.#kernels !== kernels) return;
1355
+ this.#acceptReadback(
1356
+ new Float32Array(bytes),
1357
+ serial,
1358
+ map === undefined ? undefined : new Float32Array(map),
1359
+ );
1360
+ },
1361
+ (error: unknown) => {
1362
+ this.#readbackInFlight = false;
1363
+ this.#failTrace(error);
1364
+ },
1365
+ );
1366
+ }
1367
+
1368
+ #acceptReadback(field: Float32Array, serial: number, map?: Float32Array): void {
1369
+ for (let index = 0; index < this.#probeCount * SH_COEFFICIENT_COUNT; index += 1) {
1370
+ for (let channel = 0; channel < SH_CHANNEL_COUNT; channel += 1) {
1371
+ this.#coefficients[index * SH_CHANNEL_COUNT + channel] = field[index * 4 + channel] ?? 0;
1372
+ }
1373
+ }
1374
+ // The first coefficient's w is the share of the probe's rays that met a surface from behind.
1375
+ const shares = new Float32Array(this.#probeCount);
1376
+ for (let probe = 0; probe < this.#probeCount; probe += 1)
1377
+ shares[probe] = field[probe * SH_COEFFICIENT_COUNT * 4 + 3] ?? 0;
1378
+ const cells = this.#mapResolution * this.#mapResolution;
1379
+ const radianceMap = map?.slice(0, this.#probeCount * cells * 4);
1380
+ this.#probesRejected = fillRejectedProbes(
1381
+ this.#coefficients,
1382
+ shares,
1383
+ this.resolution,
1384
+ radianceMap === undefined ? [] : [{ data: radianceMap, stride: cells * 4 }],
1385
+ );
1386
+ if (radianceMap !== undefined) this.#packRadianceMap(radianceMap, shares);
1387
+ this.#packCpuAtlas();
1388
+ this.#readbackSerial = serial;
1389
+ if (this.#passSerial < 0 || serial < this.#passSerial || this.#status !== "baking") return;
1390
+ this.#generations += 1;
1391
+ this.#status = "ready";
1392
+ this.#stalenessFrames = 0;
1393
+ this.#passSerial = -1;
1394
+ const promise = this.#bakePromise;
1395
+ this.#bakePromise = undefined;
1396
+ this.#publish(true);
1397
+ promise?.resolve();
1398
+ }
1399
+
1400
+ #failTrace(error: unknown): void {
1401
+ const promise = this.#bakePromise;
1402
+ this.#bakePromise = undefined;
1403
+ this.#status = "unbaked";
1404
+ this.#publish(true);
1405
+ promise?.reject(error);
1406
+ }
1407
+
728
1408
  detach(): void {
729
1409
  if (this.#released) return;
730
1410
  this.#released = true;
@@ -733,6 +1413,11 @@ export class ProbeVolume extends Object3D implements IComputeDriven {
733
1413
  this.#pending = undefined;
734
1414
  this.#bakePromise = undefined;
735
1415
  }
1416
+ if (this.#trace !== undefined)
1417
+ this.#bakePromise?.reject(new Error("ProbeVolume detached while a bake was pending."));
1418
+ this.#bakePromise = undefined;
1419
+ this.#kernels?.dispose();
1420
+ this.#kernels = undefined;
736
1421
  this.#restoreSceneState();
737
1422
  this.#cubeRenderTarget?.dispose();
738
1423
  this.#projectionTarget?.dispose();
@@ -744,6 +1429,8 @@ export class ProbeVolume extends Object3D implements IComputeDriven {
744
1429
  for (const material of this.#repackMaterials ?? []) material.dispose();
745
1430
  this.#quadMesh?.geometry.dispose();
746
1431
  this.#atlasTexture.dispose();
1432
+ this.#radianceMapTexture?.dispose();
1433
+ this.#radianceMapTexture = undefined;
747
1434
  this.#cubeRenderTarget = undefined;
748
1435
  this.#projectionTarget = undefined;
749
1436
  this.#batchTarget = undefined;
@@ -763,6 +1450,7 @@ export class ProbeVolume extends Object3D implements IComputeDriven {
763
1450
  }
764
1451
 
765
1452
  get totalWork(): number {
1453
+ if (this.#trace !== undefined) return this.#tracePasses * (this.#probeCount + 1);
766
1454
  return (
767
1455
  this.#bakePasses *
768
1456
  (this.#probeCount * CAPTURE_WORK_ITEMS_PER_PROBE +
@@ -1530,18 +2218,53 @@ function cubeFaceCoordinate(face: number, col: number, row: number): IVector3Lik
1530
2218
  return { x: -col, y: row, z: -1 };
1531
2219
  }
1532
2220
 
1533
- function evaluateShChannel(coefficients: Float32Array, channel: number, normal: Vector3): number {
2221
+ /** The SH L2 basis constants per band, times each band's lobe weight. */
2222
+ interface IShWeights {
2223
+ readonly l0: number;
2224
+ readonly l1: number;
2225
+ readonly l2: number;
2226
+ readonly l20: number;
2227
+ readonly l20Offset: number;
2228
+ readonly l22: number;
2229
+ }
2230
+
2231
+ /** The basis convolved with a cosine lobe (bands times pi, 2 pi / 3 and pi / 4): irradiance E for a normal. */
2232
+ const SH_IRRADIANCE_WEIGHTS: IShWeights = {
2233
+ l0: 0.886227,
2234
+ l1: 1.023328,
2235
+ l2: 0.858086,
2236
+ l20: 0.743125,
2237
+ l20Offset: 0.247708,
2238
+ l22: 0.429043,
2239
+ };
2240
+
2241
+ /** The bare basis: the radiance arriving along a direction. */
2242
+ const SH_RADIANCE_WEIGHTS: IShWeights = {
2243
+ l0: 0.282095,
2244
+ l1: 0.488603,
2245
+ l2: 1.092548,
2246
+ l20: 0.946176,
2247
+ l20Offset: 0.315392,
2248
+ l22: 0.546274,
2249
+ };
2250
+
2251
+ function evaluateShChannel(
2252
+ coefficients: Float32Array,
2253
+ channel: number,
2254
+ normal: Vector3,
2255
+ w: IShWeights,
2256
+ ): number {
1534
2257
  const c = (index: number) => coefficients[index * SH_CHANNEL_COUNT + channel] ?? 0;
1535
2258
  return (
1536
- c(0) * 0.886227 +
1537
- c(1) * normal.y * 1.023328 +
1538
- c(2) * normal.z * 1.023328 +
1539
- c(3) * normal.x * 1.023328 +
1540
- c(4) * normal.x * normal.y * 0.858086 +
1541
- c(5) * normal.y * normal.z * 0.858086 +
1542
- c(6) * (normal.z * normal.z * 0.743125 - 0.247708) +
1543
- c(7) * normal.x * normal.z * 0.858086 +
1544
- c(8) * (normal.x * normal.x - normal.y * normal.y) * 0.429043
2259
+ c(0) * w.l0 +
2260
+ c(1) * normal.y * w.l1 +
2261
+ c(2) * normal.z * w.l1 +
2262
+ c(3) * normal.x * w.l1 +
2263
+ c(4) * normal.x * normal.y * w.l2 +
2264
+ c(5) * normal.y * normal.z * w.l2 +
2265
+ c(6) * (normal.z * normal.z * w.l20 - w.l20Offset) +
2266
+ c(7) * normal.x * normal.z * w.l2 +
2267
+ c(8) * (normal.x * normal.x - normal.y * normal.y) * w.l22
1545
2268
  );
1546
2269
  }
1547
2270
 
@@ -1670,12 +2393,35 @@ function isProbeVolumeObservation(value: unknown): value is IProbeVolumeObservat
1670
2393
  )
1671
2394
  return false;
1672
2395
  if (!isProbeVolumeAtlas(atlas, probeCount, atlasBytes)) return false;
1673
- if (!isProbeVolumeBakeProgress(progress, status, probeCount, atlas.depth)) return false;
2396
+ const trace = observationUpdate(value);
2397
+ if (trace === undefined) return false;
2398
+ if (!isProbeVolumeBakeProgress(progress, status, probeCount, atlas.depth, trace)) return false;
1674
2399
  if (stale !== (status !== "ready") || unbaked !== (status === "unbaked")) return false;
1675
- if (status === "baking" && samplingIsolated !== (progress.pass === 0)) return false;
2400
+ // A traced refresh never isolates: the old field serves until each probe is replaced.
2401
+ if (trace ? samplingIsolated : status === "baking" && samplingIsolated !== (progress.pass === 0))
2402
+ return false;
1676
2403
  return status !== "ready" || (stalenessFrames !== null && !samplingIsolated);
1677
2404
  }
1678
2405
 
2406
+ /** `true` for a complete trace observation, `false` for a capture one, `undefined` for a malformed one. */
2407
+ function observationUpdate(value: Record<string, unknown>): boolean | undefined {
2408
+ const { update, probesTraced, oldestProbeAgeFrames, ignoredTextureMaterials } = value;
2409
+ if (update === undefined || update === "capture") return false;
2410
+ if (update !== "trace") return undefined;
2411
+ const complete =
2412
+ isProgressValue(probesTraced) &&
2413
+ isProgressValue(ignoredTextureMaterials) &&
2414
+ (oldestProbeAgeFrames === null || isProgressValue(oldestProbeAgeFrames));
2415
+ return complete ? true : undefined;
2416
+ }
2417
+
2418
+ /** Work items a probe costs, and the work that closes a pass: the repack slices, or one readback. */
2419
+ function passWork(trace: boolean, atlasDepth: number): { perProbe: number; tail: number } {
2420
+ return trace
2421
+ ? { perProbe: 1, tail: 1 }
2422
+ : { perProbe: CAPTURE_WORK_ITEMS_PER_PROBE, tail: atlasDepth };
2423
+ }
2424
+
1679
2425
  function isProbeVolumeAtlas(
1680
2426
  value: unknown,
1681
2427
  probeCount: number,
@@ -1712,11 +2458,13 @@ function isProbeVolumeBakeProgress(
1712
2458
  status: IProbeVolumeObservation["status"],
1713
2459
  probeCount: number,
1714
2460
  atlasDepth: number,
2461
+ trace = false,
1715
2462
  ): value is IProbeVolumeBakeProgress {
1716
2463
  if (!isProbeVolumeBakeProgressShape(value)) return false;
1717
2464
  const { completed, total, fraction, probesCompleted, probesTotal, pass, passes } = value;
1718
2465
  const expectedProbesTotal = probeCount * passes;
1719
- const workPerPass = probeCount * CAPTURE_WORK_ITEMS_PER_PROBE + atlasDepth;
2466
+ const { perProbe: itemsPerProbe, tail } = passWork(trace, atlasDepth);
2467
+ const workPerPass = probeCount * itemsPerProbe + tail;
1720
2468
  const expectedTotal = workPerPass * passes;
1721
2469
  if (
1722
2470
  !isPositiveIntegerValue(expectedProbesTotal) ||
@@ -1749,11 +2497,9 @@ function isProbeVolumeBakeProgress(
1749
2497
  currentProbes > probeCount
1750
2498
  )
1751
2499
  return false;
1752
- if (currentProbes === probeCount) return currentWork >= probeCount * CAPTURE_WORK_ITEMS_PER_PROBE;
1753
- const minimumWork = currentProbes * CAPTURE_WORK_ITEMS_PER_PROBE;
1754
- return (
1755
- currentWork >= minimumWork && currentWork <= minimumWork + CAPTURE_WORK_ITEMS_PER_PROBE - 1
1756
- );
2500
+ if (currentProbes === probeCount) return currentWork >= probeCount * itemsPerProbe;
2501
+ const minimumWork = currentProbes * itemsPerProbe;
2502
+ return currentWork >= minimumWork && currentWork <= minimumWork + itemsPerProbe - 1;
1757
2503
  }
1758
2504
 
1759
2505
  function isProbeVolumeBakeProgressShape(value: unknown): value is IProbeVolumeBakeProgress {