@threenative/core 0.3.12 → 0.3.15

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 (165) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1047 -44
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/{canvas-layer-CWuFRT7G.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  5. package/dist/{chunk-7UUT3TY5.js → chunk-2GPHICV6.js} +1 -1
  6. package/dist/{chunk-GMHATRPW.js → chunk-GEMQJBY4.js} +1650 -383
  7. package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
  8. package/dist/{chunk-5O73CDMR.js → chunk-QAMSM3Z5.js} +415 -27
  9. package/dist/{chunk-2Z44XSI2.js → chunk-QAQHYOWY.js} +3 -7
  10. package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
  11. package/dist/{chunk-OKXUCASC.js → chunk-VBBYWGAT.js} +3 -4
  12. package/dist/chunk-VP43GIWW.js +18 -0
  13. package/dist/{chunk-N5LRP4BR.js → chunk-VQRPEOKY.js} +66 -3
  14. package/dist/{chunk-6KLNISRJ.js → chunk-XDTZ4QMO.js} +11 -4
  15. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  16. package/dist/{game-D7pAzZUY.d.ts → game-k8K3hZai.d.ts} +72 -8
  17. package/dist/hot.d.ts +5 -4
  18. package/dist/hot.js +5 -8
  19. package/dist/index.d.ts +871 -1018
  20. package/dist/index.js +4786 -1631
  21. package/dist/{model-lod-B6BMqS1r.d.ts → model-lod-DPTzeCcD.d.ts} +4 -2
  22. package/dist/playtest.d.ts +5 -4
  23. package/dist/playtest.js +6 -5
  24. package/dist/quality-BADStsTn.d.ts +868 -0
  25. package/dist/react.d.ts +3 -2
  26. package/dist/render-environment.d.ts +170 -0
  27. package/dist/render-environment.js +352 -0
  28. package/dist/{renderer-DvFVoAgj.d.ts → renderer-BtOSseYf.d.ts} +29 -31
  29. package/dist/spells/index.js +1 -1
  30. package/dist/ui-layer.js +3 -2
  31. package/dist/worker.js +12 -5
  32. package/dist/world.d.ts +280 -16
  33. package/dist/world.js +1529 -642
  34. package/mcp/animation-server.mjs +1 -1
  35. package/mcp/engine-server.mjs +135 -11
  36. package/mcp/servers.mjs +4 -4
  37. package/package.json +10 -6
  38. package/scripts/ensure-mcp.mjs +6 -1
  39. package/src/animation-batch.ts +193 -0
  40. package/src/animation-layers.ts +7 -3
  41. package/src/animation.ts +209 -29
  42. package/src/asset-cache.ts +3 -3
  43. package/src/asset-memo.ts +202 -0
  44. package/src/assets.ts +436 -131
  45. package/src/auto-batch.ts +190 -44
  46. package/src/clustered-batch.ts +146 -3
  47. package/src/clustered-mesh.ts +548 -20
  48. package/src/compute-driven.ts +1 -1
  49. package/src/config.ts +8 -0
  50. package/src/debug.ts +119 -22
  51. package/src/dev-global.ts +54 -0
  52. package/src/displaced-surface.ts +428 -0
  53. package/src/engine-hooks.ts +37 -0
  54. package/src/frame-budget.ts +35 -3
  55. package/src/game-boot-phase.ts +269 -0
  56. package/src/game-dev-tools.ts +7 -14
  57. package/src/game-frame-loop.ts +45 -82
  58. package/src/game-startup.ts +145 -70
  59. package/src/game-ui.ts +84 -0
  60. package/src/game.ts +168 -552
  61. package/src/gamepad-mappings.ts +269 -0
  62. package/src/generated/console-markers.ts +14 -0
  63. package/src/geometry-capture.ts +28 -4
  64. package/src/gpu-readings.ts +98 -0
  65. package/src/gpu-scene-bvh.ts +149 -36
  66. package/src/grass-field.ts +628 -0
  67. package/src/hot.ts +4 -7
  68. package/src/index.ts +227 -8
  69. package/src/input.ts +237 -25
  70. package/src/instanced-batch-lod.ts +3 -8
  71. package/src/interpolation.ts +171 -40
  72. package/src/look/ao-admission.ts +4 -3
  73. package/src/look/auto-exposure.ts +5 -16
  74. package/src/look/default-tone-mapping.ts +41 -5
  75. package/src/look/local-exposure.ts +2 -7
  76. package/src/look/quad-pass.ts +21 -0
  77. package/src/look/quality.ts +4 -0
  78. package/src/look/unreal-bloom.ts +4 -13
  79. package/src/look/world-environment.ts +58 -115
  80. package/src/merge-parts.ts +20 -24
  81. package/src/model-lod.ts +97 -14
  82. package/src/particle-significance.ts +12 -0
  83. package/src/particles.ts +19 -10
  84. package/src/platform.ts +23 -4
  85. package/src/profiling/FrameStages.ts +5 -6
  86. package/src/profiling/Spans.ts +3 -17
  87. package/src/profiling/debug-telemetry.ts +2 -6
  88. package/src/profiling/render-list-validate.ts +6 -15
  89. package/src/projection-marker.ts +2 -1
  90. package/src/quiet-markers.ts +3 -10
  91. package/src/render/cpu-bvh.ts +100 -0
  92. package/src/render/depth-pyramid.ts +6 -14
  93. package/src/render/environment/environmentContribution.ts +202 -0
  94. package/src/render/environment/environmentRadiance.ts +44 -0
  95. package/src/render/environment/environmentSampleCache.ts +56 -0
  96. package/src/render/environment/environmentSampling.ts +201 -0
  97. package/src/render/environment/environmentSnapshot.ts +71 -0
  98. package/src/render/environment/gate.ts +57 -0
  99. package/src/render/material-key.ts +21 -1
  100. package/src/render/mesh-pool.ts +3 -19
  101. package/src/render/probe-trace.ts +872 -0
  102. package/src/render/probe-volume.ts +780 -34
  103. package/src/render/radiance-cache.ts +17 -0
  104. package/src/render/screen-probe-gather.ts +303 -0
  105. package/src/render/short-range-ao.ts +274 -0
  106. package/src/render/virtual-shadow-partial.ts +13 -0
  107. package/src/render/virtual-shadow.ts +18 -16
  108. package/src/render/world-impostor-surface.ts +207 -9
  109. package/src/render/world-impostor.ts +5 -2
  110. package/src/render-camera-cull.ts +105 -4
  111. package/src/render-environment.ts +41 -0
  112. package/src/renderer-config.ts +36 -0
  113. package/src/renderer-facts.ts +37 -0
  114. package/src/renderer.ts +78 -32
  115. package/src/resolution-scaler.ts +3 -2
  116. package/src/scatter-field.ts +496 -0
  117. package/src/scene-entry-inspectors.ts +61 -0
  118. package/src/snow-field.ts +1 -0
  119. package/src/startup-offscreen-bytes.ts +84 -0
  120. package/src/state.ts +16 -3
  121. package/src/static-transform.ts +100 -25
  122. package/src/streamed-textures.ts +112 -0
  123. package/src/streaming.ts +68 -4
  124. package/src/texture-streaming.ts +331 -0
  125. package/src/tile-ring.ts +294 -0
  126. package/src/version.ts +1 -1
  127. package/src/warmup.ts +15 -2
  128. package/src/worker.ts +12 -2
  129. package/src/world-bundle-safety.ts +55 -10
  130. package/src/world-cell-batches.ts +166 -200
  131. package/src/world-cell-chunks.ts +3 -7
  132. package/src/world-cell-data.ts +7 -0
  133. package/src/world-cell-impostors.ts +20 -8
  134. package/src/world-cell-models.ts +36 -8
  135. package/src/world-cell-options.ts +2 -14
  136. package/src/world-cell-placements.ts +194 -90
  137. package/src/world-cell-prewarm.ts +39 -4
  138. package/src/world-cell-records.ts +401 -0
  139. package/src/world-cell-render-bundles.ts +2 -2
  140. package/src/world-cell-render-gpu-dress.ts +17 -19
  141. package/src/world-cell-render-main-cull.ts +73 -17
  142. package/src/world-cell-render-util.ts +18 -5
  143. package/src/world-cell-render.ts +13 -5
  144. package/src/world-cell-residency.ts +15 -6
  145. package/src/world-cell-stale.ts +238 -0
  146. package/src/world-cells.ts +23 -6
  147. package/src/world-gpu-flags.ts +18 -50
  148. package/src/world-gpu-reference.ts +22 -8
  149. package/src/world-gpu-scene.ts +44 -24
  150. package/src/world-gpu-shadow.ts +21 -8
  151. package/src/world-gpu-types.ts +41 -13
  152. package/src/world-load-limiter.ts +5 -0
  153. package/src/world-model-sections.ts +80 -0
  154. package/src/world-river-ribbon.ts +273 -0
  155. package/src/world-root-frame.ts +39 -0
  156. package/src/world-shore-field.ts +91 -0
  157. package/src/world-static-pose.ts +163 -0
  158. package/src/world-surface-sampler.ts +48 -0
  159. package/src/world-terrain-splat.ts +10 -18
  160. package/src/world-tile-budget.ts +4 -11
  161. package/src/world-tiles.ts +79 -12
  162. package/src/world-validate.ts +6 -14
  163. package/src/world-warm.ts +51 -0
  164. package/src/world-water-bodies.ts +113 -3
  165. package/src/world.ts +13 -0
@@ -0,0 +1,872 @@
1
+ // PRD-603: a probe refresh that traces the packed scene instead of drawing it six times.
2
+ //
3
+ // Unreal's radiance cache traces each probe against a scene proxy and reads the lit surface at the hit;
4
+ // it never draws the scene again for a probe (UE 5.8.3: Engine/Shaders/Private/Lumen/LumenSoftwareRayTracing.ush:670-700).
5
+ // Here the proxy is the GPUSceneBVH snapshot and the lit surface is a flat material table: albedo times the
6
+ // sun through one shadow ray, plus emission, plus the previous generation of the field at the hit (the bounce).
7
+ // A miss returns the game's sky radiance. One kernel traces every ray of the selected probes, a second projects
8
+ // each probe's rays onto the L2 basis the atlas already stores, so sampling does not change.
9
+ //
10
+ // The traversal is stackless (a threaded BVH: each node carries the node to visit after it), because the owned
11
+ // engine's TSL has loops and storage buffers but no local arrays, and refuses the upstream WGSL ray query.
12
+ import { Color, type Material, type Texture, Vector3 } from "three";
13
+ import {
14
+ Break,
15
+ Fn,
16
+ If,
17
+ Loop,
18
+ Return,
19
+ abs,
20
+ clamp,
21
+ cross,
22
+ dot,
23
+ float,
24
+ floor,
25
+ instanceIndex,
26
+ int,
27
+ max,
28
+ min,
29
+ normalize,
30
+ pow,
31
+ select,
32
+ sqrt,
33
+ storage,
34
+ uniform,
35
+ vec3,
36
+ vec4,
37
+ } from "three/tsl";
38
+ import { StorageBufferAttribute } from "three/webgpu";
39
+ import type { Node } from "three/webgpu";
40
+
41
+ /** The CPU snapshot a GPUSceneBVH packs, in BVH leaf order, that the probe trace reads. */
42
+ export interface IProbeTraceScene {
43
+ /** three-mesh-bvh serialized root: 8 words per node. */
44
+ readonly nodes: Uint32Array;
45
+ /** World positions, 4 floats per vertex. */
46
+ readonly positions: Float32Array;
47
+ /** Leaf-ordered triangle corners, 3 per triangle. */
48
+ readonly indices: Uint32Array;
49
+ /** Leaf-ordered material slot per triangle, an index into `materials`. */
50
+ readonly triangleMaterials: Uint32Array;
51
+ readonly materials: readonly Material[];
52
+ }
53
+
54
+ /** The sun and sky the game already holds for its daylight; the volume owns no light. */
55
+ export interface IProbeTraceLighting {
56
+ /** World direction toward the sun (the light's position minus its target). */
57
+ readonly direction: Vector3;
58
+ readonly color: Color;
59
+ readonly intensity: number;
60
+ /** Radiance of a ray that leaves the scene. Black for an interior with no sky. */
61
+ readonly sky: Color;
62
+ /**
63
+ * Point lights, at most the count the kernels were built for. Intensity is the irradiance on a surface 1 m
64
+ * from the light that faces it, in the same units as the sun; `distance` closes the attenuation window
65
+ * (three's `getDistanceAttenuation`), 0 for none. A change to a point light needs `requestBake`.
66
+ */
67
+ readonly points?: readonly IProbeTracePoint[];
68
+ }
69
+
70
+ export interface IProbeTracePoint {
71
+ readonly position: Vector3;
72
+ readonly color: Color;
73
+ readonly intensity: number;
74
+ readonly distance?: number;
75
+ }
76
+
77
+ /** What a scene BVH snapshot becomes on the GPU: a threaded node table, triangles and the material table. */
78
+ export interface IThreadedScene {
79
+ /** Two vec4 per node: bounds min, bounds max. */
80
+ readonly bounds: Float32Array;
81
+ /** One ivec4 per node: next node after this one, leaf triangle offset, leaf triangle count, 1 for a leaf. */
82
+ readonly links: Int32Array;
83
+ /** Three vec4 per triangle: the corners, and the first corner's w holds the material slot. */
84
+ readonly triangles: Float32Array;
85
+ /** Two vec4 per material: albedo, emitted radiance. */
86
+ readonly materials: Float32Array;
87
+ readonly nodeCount: number;
88
+ /** Materials whose texture or node graph the flat table cannot read. */
89
+ readonly ignoredTextureMaterials: number;
90
+ }
91
+
92
+ const NODE_WORDS = 8;
93
+ const LEAF_FLAG = 0xffff0000;
94
+ const COUNT_MASK = 0xffff;
95
+
96
+ /**
97
+ * Thread a three-mesh-bvh node buffer: every node gets the node a depth-first walk visits next when it
98
+ * skips this node's subtree (its "miss" link). A walk that follows the left child on a box hit and the miss
99
+ * link otherwise visits every node it must with no stack. `nodeCount` ends the walk.
100
+ */
101
+ export function threadBvh(nodes: Uint32Array): {
102
+ bounds: Float32Array;
103
+ links: Int32Array;
104
+ nodeCount: number;
105
+ } {
106
+ const nodeCount = nodes.length / NODE_WORDS;
107
+ if (!Number.isInteger(nodeCount) || nodeCount < 1)
108
+ throw new Error("threadBvh needs whole 8-word nodes.");
109
+ const floats = new Float32Array(nodes.buffer, nodes.byteOffset, nodes.length);
110
+ const bounds = new Float32Array(nodeCount * 8);
111
+ const links = new Int32Array(nodeCount * 4);
112
+ const stack: number[] = [0, nodeCount];
113
+ while (stack.length > 0) {
114
+ const miss = stack.pop() as number;
115
+ const node = stack.pop() as number;
116
+ const word = node * NODE_WORDS;
117
+ bounds.set(floats.subarray(word, word + 3), node * 8);
118
+ bounds.set(floats.subarray(word + 3, word + 6), node * 8 + 4);
119
+ const info = nodes[word + 7] ?? 0;
120
+ links[node * 4] = miss;
121
+ if ((info & LEAF_FLAG) !== 0) {
122
+ links[node * 4 + 1] = nodes[word + 6] ?? 0;
123
+ links[node * 4 + 2] = info & COUNT_MASK;
124
+ links[node * 4 + 3] = 1;
125
+ continue;
126
+ }
127
+ const right = node + (nodes[word + 6] ?? 0);
128
+ if (right <= node || right >= nodeCount)
129
+ throw new Error(`threadBvh: node ${node} has no valid right child.`);
130
+ stack.push(right, miss, node + 1, right);
131
+ }
132
+ return { bounds, links, nodeCount };
133
+ }
134
+
135
+ /** The radiance a flat material returns: albedo for the lit model, emission, and whether a texture was dropped. */
136
+ export function flatMaterial(material: Material): {
137
+ albedo: Color;
138
+ emission: Color;
139
+ ignored: boolean;
140
+ } {
141
+ const fields = material as Material & {
142
+ color?: Color;
143
+ emissive?: Color;
144
+ emissiveIntensity?: number;
145
+ map?: Texture | null;
146
+ emissiveMap?: Texture | null;
147
+ colorNode?: unknown;
148
+ emissiveNode?: unknown;
149
+ };
150
+ const color = fields.color?.clone() ?? new Color(0.5, 0.5, 0.5);
151
+ const ignored =
152
+ (fields.map ?? null) !== null ||
153
+ (fields.emissiveMap ?? null) !== null ||
154
+ (fields.colorNode ?? null) !== null ||
155
+ (fields.emissiveNode ?? null) !== null;
156
+ // An unlit material shows its colour whatever lights the scene, exactly as a cube capture records it.
157
+ // A node-coloured unlit surface shows computed light (often this very field), not light of its own.
158
+ const unlit = fields as { isMeshBasicMaterial?: boolean; isMeshBasicNodeMaterial?: boolean };
159
+ if (unlit.isMeshBasicMaterial === true || unlit.isMeshBasicNodeMaterial === true) {
160
+ const emission = (fields.colorNode ?? null) === null ? color : new Color(0, 0, 0);
161
+ return { albedo: new Color(0, 0, 0), emission, ignored };
162
+ }
163
+ const emission = (fields.emissive?.clone() ?? new Color(0, 0, 0)).multiplyScalar(
164
+ fields.emissiveIntensity ?? 1,
165
+ );
166
+ return { albedo: color, emission, ignored };
167
+ }
168
+
169
+ /**
170
+ * Write the flat material table into `target` (2 vec4 a material) and count the materials it could not read.
171
+ * Returns whether any value changed, so a lamp switched on in game code restarts the refresh by itself.
172
+ */
173
+ export function writeMaterialTable(
174
+ materials: readonly Material[],
175
+ target: Float32Array,
176
+ ): { changed: boolean; ignored: number } {
177
+ let changed = false;
178
+ let ignored = 0;
179
+ materials.forEach((material, slot) => {
180
+ const flat = flatMaterial(material);
181
+ if (flat.ignored) ignored += 1;
182
+ const values = [
183
+ flat.albedo.r,
184
+ flat.albedo.g,
185
+ flat.albedo.b,
186
+ // The side a ray can hit, three's own numbers: 0 front, 1 back, 2 double. The capture never draws the other side.
187
+ material.side,
188
+ flat.emission.r,
189
+ flat.emission.g,
190
+ flat.emission.b,
191
+ 0,
192
+ ];
193
+ values.forEach((value, offset) => {
194
+ // The table is Float32: compare the value as stored, or a colour float32 cannot hold reads changed forever.
195
+ if (target[slot * 8 + offset] === Math.fround(value)) return;
196
+ target[slot * 8 + offset] = value;
197
+ changed = true;
198
+ });
199
+ });
200
+ return { changed, ignored };
201
+ }
202
+
203
+ /** Lay a BVH snapshot out for the trace kernel. */
204
+ export function threadScene(scene: IProbeTraceScene): IThreadedScene {
205
+ const { bounds, links, nodeCount } = threadBvh(scene.nodes);
206
+ const triangleCount = scene.indices.length / 3;
207
+ const triangles = new Float32Array(Math.max(1, triangleCount) * 12);
208
+ for (let triangle = 0; triangle < triangleCount; triangle += 1) {
209
+ for (let corner = 0; corner < 3; corner += 1) {
210
+ const vertex = scene.indices[triangle * 3 + corner] ?? 0;
211
+ triangles.set(
212
+ scene.positions.subarray(vertex * 4, vertex * 4 + 3),
213
+ triangle * 12 + corner * 4,
214
+ );
215
+ }
216
+ triangles[triangle * 12 + 3] = scene.triangleMaterials[triangle] ?? 0;
217
+ }
218
+ const materials = new Float32Array(Math.max(1, scene.materials.length) * 8);
219
+ const ignoredTextureMaterials = writeMaterialTable(scene.materials, materials).ignored;
220
+ return { bounds, links, materials, nodeCount, triangles, ignoredTextureMaterials };
221
+ }
222
+
223
+ /** Rays per probe on a spherical Fibonacci set: even coverage, fixed order, so a refresh is deterministic. */
224
+ export function probeRayDirections(count: number): Float32Array {
225
+ const directions = new Float32Array(count * 4);
226
+ for (let ray = 0; ray < count; ray += 1) {
227
+ const y = 1 - (2 * (ray + 0.5)) / count;
228
+ const radius = Math.sqrt(Math.max(0, 1 - y * y));
229
+ const phi = ray * 2.399963229728653;
230
+ directions.set([radius * Math.cos(phi), y, radius * Math.sin(phi), 0], ray * 4);
231
+ }
232
+ return directions;
233
+ }
234
+
235
+ type V3 = Node<"vec3">;
236
+ // quality-allow: the kernel is arithmetic over TSL nodes, which three types per swizzle and refuses on storage elements.
237
+ // biome-ignore lint/suspicious/noExplicitAny: three's TSL types refuse the swizzles the trace kernel reads.
238
+ type AnyNode = any;
239
+
240
+ interface IStorageSet {
241
+ readonly bounds: AnyNode;
242
+ readonly links: AnyNode;
243
+ readonly triangles: AnyNode;
244
+ readonly materials: AnyNode;
245
+ }
246
+
247
+ const RAY_EPSILON = 1e-4;
248
+ /**
249
+ * A probe is rejected when more than this share of its rays first meet a surface from behind: it sits inside a solid,
250
+ * or outside the walls looking at their backs. Unreal's GPU Lightmass rejects an irradiance cache record at the same
251
+ * share (UE 5.8.3: Engine/Plugins/Experimental/GPULightmass/Shaders/Private/IrradianceCachingCommon.ush:8,
252
+ * LightmapPathTracing.usf:449-455). The share rides in the `w` of a probe's first coefficient.
253
+ */
254
+ export const BACKFACE_REJECTION_SHARE = 1 / 64;
255
+ const SURFACE_OFFSET = 1e-3;
256
+ const INV_PI = 1 / Math.PI;
257
+
258
+ /**
259
+ * Closest (or, with `anyHit`, first) hit along a ray through the threaded BVH. Builds graph nodes inline. With `back`
260
+ * (a float variable), it also keeps the nearest surface the ray skipped because it arrived on the side that is not drawn.
261
+ */
262
+ function traceRay(
263
+ buffers: IStorageSet,
264
+ nodeCount: AnyNode,
265
+ origin: AnyNode,
266
+ direction: AnyNode,
267
+ far: number | AnyNode,
268
+ anyHit: boolean,
269
+ back?: AnyNode,
270
+ ): { t: AnyNode; triangle: AnyNode } {
271
+ const best = float(far).toVar();
272
+ const hitTriangle = int(-1).toVar();
273
+ const safe = (component: AnyNode) =>
274
+ select(abs(component).lessThan(1e-8), float(1e8), float(1).div(component));
275
+ const inverse = vec3(safe(direction.x), safe(direction.y), safe(direction.z)).toVar();
276
+ const node = int(0).toVar();
277
+ Loop(
278
+ { start: int(0), end: nodeCount.mul(int(2)).add(int(1)), type: "int", condition: "<" },
279
+ () => {
280
+ If(node.greaterThanEqual(nodeCount), () => Break());
281
+ const low = buffers.bounds.element(node.mul(int(2))).xyz;
282
+ const high = buffers.bounds.element(node.mul(int(2)).add(int(1))).xyz;
283
+ const t0 = low.sub(origin).mul(inverse);
284
+ const t1 = high.sub(origin).mul(inverse);
285
+ const near = max(max(min(t0.x, t1.x), min(t0.y, t1.y)), min(t0.z, t1.z));
286
+ const exit = min(min(max(t0.x, t1.x), max(t0.y, t1.y)), max(t0.z, t1.z));
287
+ const boxHit = exit.greaterThanEqual(max(near, 0)).and(near.lessThan(best));
288
+ // The links are float storage read as ints: the owned engine's `ivec4` storage reads back wrong (a node never reads as a leaf).
289
+ const rawLink = buffers.links.element(node);
290
+ const link = { w: int(rawLink.w), x: int(rawLink.x), y: int(rawLink.y), z: int(rawLink.z) };
291
+ If(boxHit.and(link.w.equal(1)), () => {
292
+ Loop(
293
+ { start: int(0), end: link.z, type: "int", condition: "<" },
294
+ ({ i }: { i: AnyNode }) => {
295
+ const triangle = link.y.add(i);
296
+ const a = buffers.triangles.element(triangle.mul(int(3))).xyz;
297
+ const edge1 = buffers.triangles.element(triangle.mul(int(3)).add(int(1))).xyz.sub(a);
298
+ const edge2 = buffers.triangles.element(triangle.mul(int(3)).add(int(2))).xyz.sub(a);
299
+ const p = cross(direction, edge2);
300
+ const det = dot(edge1, p);
301
+ const inverseDet = select(abs(det).greaterThan(1e-12), float(1).div(det), float(0));
302
+ const s = origin.sub(a);
303
+ const u = dot(s, p).mul(inverseDet);
304
+ const q = cross(s, edge1);
305
+ const v = dot(direction, q).mul(inverseDet);
306
+ const t = dot(edge2, q).mul(inverseDet);
307
+ // A one-sided surface is not there for a ray that arrives behind it, as a cube capture would not draw it.
308
+ const side = buffers.materials.element(
309
+ int(buffers.triangles.element(triangle.mul(int(3))).w).mul(int(2)),
310
+ ).w;
311
+ const behind = dot(cross(edge1, edge2), direction).greaterThan(0);
312
+ const culled = side
313
+ .lessThan(0.5)
314
+ .and(behind)
315
+ .or(side.greaterThan(0.5).and(side.lessThan(1.5)).and(behind.not()));
316
+ const crossed = abs(det)
317
+ .greaterThan(1e-12)
318
+ .and(u.greaterThanEqual(0))
319
+ .and(v.greaterThanEqual(0))
320
+ .and(u.add(v).lessThanEqual(1))
321
+ .and(t.greaterThan(RAY_EPSILON))
322
+ .and(t.lessThan(best))
323
+ .toVar();
324
+ If(culled.not().and(crossed), () => {
325
+ best.assign(t);
326
+ hitTriangle.assign(triangle);
327
+ });
328
+ if (back !== undefined)
329
+ If(culled.and(crossed).and(t.lessThan(back)), () => back.assign(t));
330
+ },
331
+ );
332
+ node.assign(link.x);
333
+ if (anyHit) If(hitTriangle.greaterThanEqual(0), () => Break());
334
+ })
335
+ .ElseIf(boxHit, () => {
336
+ node.assign(node.add(int(1)));
337
+ })
338
+ .Else(() => {
339
+ node.assign(link.x);
340
+ });
341
+ },
342
+ );
343
+ return { t: best, triangle: hitTriangle };
344
+ }
345
+
346
+ /** L2 irradiance for a normal from nine RGB coefficients: the same constants `ProbeVolume.sampleNode` uses. */
347
+ function shIrradiance(coefficient: (index: number) => V3, n: V3): V3 {
348
+ return coefficient(0)
349
+ .mul(0.886227)
350
+ .add(coefficient(1).mul(n.y).mul(1.023328))
351
+ .add(coefficient(2).mul(n.z).mul(1.023328))
352
+ .add(coefficient(3).mul(n.x).mul(1.023328))
353
+ .add(coefficient(4).mul(n.x.mul(n.y)).mul(0.858086))
354
+ .add(coefficient(5).mul(n.y.mul(n.z)).mul(0.858086))
355
+ .add(coefficient(6).mul(n.z.mul(n.z).mul(0.743125).sub(0.247708)))
356
+ .add(coefficient(7).mul(n.x.mul(n.z)).mul(0.858086))
357
+ .add(
358
+ coefficient(8)
359
+ .mul(n.x.mul(n.x).sub(n.y.mul(n.y)))
360
+ .mul(0.429043),
361
+ )
362
+ .max(0) as V3;
363
+ }
364
+
365
+ /**
366
+ * The octahedral cell of a unit direction in an R x R map: the sphere folded onto a square through the z axis, the layout
367
+ * Unreal's radiance cache stores per probe (UE 5.8.3: Engine/Shaders/Private/Lumen/LumenRadianceCacheCommon.ush,
368
+ * GetProbeTexelCoordFromDirection, and UnitVectorToOctahedron in Engine/Shaders/Private/OctahedralCommon.ush).
369
+ * Returns `row * R + column`.
370
+ */
371
+ export function octahedralCell(x: number, y: number, z: number, resolution: number): number {
372
+ const l1 = Math.abs(x) + Math.abs(y) + Math.abs(z) || 1;
373
+ let u = x / l1;
374
+ let v = y / l1;
375
+ if (z < 0) {
376
+ const fu = (1 - Math.abs(v)) * (u >= 0 ? 1 : -1);
377
+ v = (1 - Math.abs(u)) * (v >= 0 ? 1 : -1);
378
+ u = fu;
379
+ }
380
+ const column = Math.min(resolution - 1, Math.floor((u * 0.5 + 0.5) * resolution));
381
+ const row = Math.min(resolution - 1, Math.floor((v * 0.5 + 0.5) * resolution));
382
+ return row * resolution + column;
383
+ }
384
+
385
+ /** The unit direction at the centre of an octahedral cell (the inverse fold of `octahedralCell`). */
386
+ function octahedralCellCentre(cell: number, resolution: number): [number, number, number] {
387
+ let u = (((cell % resolution) + 0.5) / resolution) * 2 - 1;
388
+ let v = ((Math.floor(cell / resolution) + 0.5) / resolution) * 2 - 1;
389
+ const z = 1 - Math.abs(u) - Math.abs(v);
390
+ if (z < 0) {
391
+ const fu = (1 - Math.abs(v)) * (u >= 0 ? 1 : -1);
392
+ v = (1 - Math.abs(u)) * (v >= 0 ? 1 : -1);
393
+ u = fu;
394
+ }
395
+ const length = Math.hypot(u, v, z) || 1;
396
+ return [u / length, v / length, z / length];
397
+ }
398
+
399
+ /**
400
+ * Which rays fill each octahedral cell: `rays` lists ray indices cell by cell (one per vec4, in x) and `ranges` holds each
401
+ * cell's first entry and count (x, y). A cell no ray lands in takes the ray nearest its centre, so a map from few rays
402
+ * has no hole.
403
+ */
404
+ export function octahedralRayTable(
405
+ directions: Float32Array,
406
+ count: number,
407
+ resolution: number,
408
+ ): { readonly rays: Float32Array; readonly ranges: Float32Array } {
409
+ const cells = resolution * resolution;
410
+ const members: number[][] = Array.from({ length: cells }, () => []);
411
+ for (let ray = 0; ray < count; ray += 1) {
412
+ const cell = octahedralCell(
413
+ directions[ray * 4] ?? 0,
414
+ directions[ray * 4 + 1] ?? 0,
415
+ directions[ray * 4 + 2] ?? 0,
416
+ resolution,
417
+ );
418
+ members[cell]?.push(ray);
419
+ }
420
+ members.forEach((list, cell) => {
421
+ if (list.length > 0) return;
422
+ const [cx, cy, cz] = octahedralCellCentre(cell, resolution);
423
+ let best = 0;
424
+ let bestDot = Number.NEGATIVE_INFINITY;
425
+ for (let ray = 0; ray < count; ray += 1) {
426
+ const d =
427
+ cx * (directions[ray * 4] ?? 0) +
428
+ cy * (directions[ray * 4 + 1] ?? 0) +
429
+ cz * (directions[ray * 4 + 2] ?? 0);
430
+ if (d > bestDot) [best, bestDot] = [ray, d];
431
+ }
432
+ list.push(best);
433
+ });
434
+ const total = members.reduce((sum, list) => sum + list.length, 0);
435
+ const rays = new Float32Array(total * 4);
436
+ const ranges = new Float32Array(cells * 4);
437
+ let next = 0;
438
+ members.forEach((list, cell) => {
439
+ ranges[cell * 4] = next;
440
+ ranges[cell * 4 + 1] = list.length;
441
+ for (const ray of list) {
442
+ rays[next * 4] = ray;
443
+ next += 1;
444
+ }
445
+ });
446
+ return { rays, ranges };
447
+ }
448
+
449
+ /** The per-volume inputs of the kernels. */
450
+ export interface IProbeTraceGrid {
451
+ readonly min: Vector3;
452
+ readonly size: Vector3;
453
+ readonly resolution: Vector3;
454
+ readonly probeCount: number;
455
+ }
456
+
457
+ /** Everything one volume dispatches: two kernels, their buffers and the uniforms the CPU updates per frame. */
458
+ export interface IProbeTraceKernels {
459
+ readonly trace: AnyNode;
460
+ readonly project: AnyNode;
461
+ /** probeCount * 9 vec4: the field the volume reads back into its atlas. */
462
+ readonly coefficients: StorageBufferAttribute;
463
+ /** The flat material table, rewritten when a material changes. */
464
+ readonly materials: StorageBufferAttribute;
465
+ /** The probe indices one dispatch refreshes. */
466
+ readonly probeList: StorageBufferAttribute;
467
+ readonly batchSize: { value: number };
468
+ readonly sunDirection: { value: Vector3 };
469
+ readonly sunRadiance: { value: Vector3 };
470
+ readonly sky: { value: Vector3 };
471
+ /** One uniform set per point light the kernels were built for. */
472
+ readonly points: readonly {
473
+ position: { value: Vector3 };
474
+ radiance: { value: Vector3 };
475
+ distance: { value: number };
476
+ }[];
477
+ /** 1 once a previous generation exists to bounce from. */
478
+ readonly bounce: { value: number };
479
+ readonly raysPerProbe: number;
480
+ readonly maxBatch: number;
481
+ /**
482
+ * Cells per side of each probe's octahedral radiance map, 0 for none. The map holds the mean radiance of the rays in
483
+ * each cell (`probeCount * R * R` vec4, probe-major), written by `octahedral` after `project`.
484
+ */
485
+ readonly octahedralResolution: number;
486
+ readonly octahedral?: AnyNode;
487
+ readonly radianceMap?: StorageBufferAttribute;
488
+ dispose(): void;
489
+ }
490
+
491
+ /** Build the trace and projection kernels for one volume over one threaded scene. */
492
+ export function createProbeTraceKernels(
493
+ scene: IThreadedScene,
494
+ grid: IProbeTraceGrid,
495
+ raysPerProbe: number,
496
+ maxBatch: number,
497
+ pointCount = 0,
498
+ octahedralResolution = 0,
499
+ ): IProbeTraceKernels {
500
+ const attributes: StorageBufferAttribute[] = [];
501
+ const buffer = (array: Float32Array | Int32Array, itemSize: number) => {
502
+ const attribute = new StorageBufferAttribute(array as never, itemSize);
503
+ attributes.push(attribute);
504
+ return attribute;
505
+ };
506
+ const read = (array: Float32Array | Int32Array, type: "vec4" | "ivec4" | "int"): AnyNode => {
507
+ const itemSize = type === "int" ? 1 : 4;
508
+ return storage(buffer(array, itemSize), type, array.length / itemSize).toReadOnly();
509
+ };
510
+ const materialNode = read(scene.materials, "vec4");
511
+ const buffers: IStorageSet = {
512
+ bounds: read(scene.bounds, "vec4"),
513
+ // Node and triangle indices below 2^24 are exact in a float.
514
+ links: read(Float32Array.from(scene.links), "vec4"),
515
+ materials: materialNode,
516
+ triangles: read(scene.triangles, "vec4"),
517
+ };
518
+ const directions = read(probeRayDirections(raysPerProbe), "vec4");
519
+ // Float storage read as ints: the owned engine's integer storage reads back zero, which sends every ray to probe 0.
520
+ // One probe index per vec4 (x), like every other table here.
521
+ const probeList = buffer(new Float32Array(maxBatch * 4), 4);
522
+ const floatProbes = storage(probeList, "vec4", maxBatch).toReadOnly() as AnyNode;
523
+ const probes = { element: (slot: AnyNode) => int(floatProbes.element(slot).x) };
524
+ const radiance = buffer(new Float32Array(maxBatch * raysPerProbe * 4), 4);
525
+ const radianceNode = storage(radiance, "vec4", maxBatch * raysPerProbe) as AnyNode;
526
+ const coefficients = buffer(new Float32Array(grid.probeCount * 9 * 4), 4);
527
+ const coefficientNode = storage(coefficients, "vec4", grid.probeCount * 9) as AnyNode;
528
+
529
+ const nodeCount = uniform(scene.nodeCount, "int") as AnyNode;
530
+ const batchSize = uniform(0, "int");
531
+ const sunDirection = uniform(new Vector3(0, 1, 0));
532
+ const sunRadiance = uniform(new Vector3());
533
+ const sky = uniform(new Vector3());
534
+ const points = Array.from({ length: pointCount }, () => ({
535
+ distance: uniform(0),
536
+ position: uniform(new Vector3()),
537
+ radiance: uniform(new Vector3()),
538
+ }));
539
+ const bounce = uniform(0);
540
+ const nx = grid.resolution.x;
541
+ const ny = grid.resolution.y;
542
+ const nz = grid.resolution.z;
543
+ const spacing = new Vector3(
544
+ grid.size.x / (nx - 1),
545
+ grid.size.y / (ny - 1),
546
+ grid.size.z / (nz - 1),
547
+ );
548
+ const volumeMin = vec3(grid.min.x, grid.min.y, grid.min.z);
549
+ const far = 4 * Math.max(grid.size.x, grid.size.y, grid.size.z, 1) + 1e4;
550
+
551
+ /**
552
+ * Trilinear L2 irradiance of the previous generation at a world point. A rejected probe (inside a solid, or outside
553
+ * the walls) takes no weight, so a surface between the room and the outside does not bounce the outside's light.
554
+ */
555
+ const previousIrradiance = (point: AnyNode, normal: AnyNode): V3 => {
556
+ const local = clamp(
557
+ point.sub(volumeMin).div(vec3(spacing.x, spacing.y, spacing.z)),
558
+ vec3(0),
559
+ vec3(nx - 1, ny - 1, nz - 1),
560
+ );
561
+ const base = min(floor(local), vec3(nx - 2, ny - 2, nz - 2)).toVar();
562
+ const fraction = local.sub(base);
563
+ let sum: AnyNode = vec3(0);
564
+ let total: AnyNode = float(0);
565
+ for (let corner = 0; corner < 8; corner += 1) {
566
+ const dx = corner & 1;
567
+ const dy = (corner >> 1) & 1;
568
+ const dz = (corner >> 2) & 1;
569
+ const probe = int(base.x.add(dx))
570
+ .add(int(base.y.add(dy)).mul(int(nx)))
571
+ .add(int(base.z.add(dz)).mul(int(nx * ny)));
572
+ const open = select(
573
+ coefficientNode.element(probe.mul(int(9))).w.greaterThan(BACKFACE_REJECTION_SHARE),
574
+ float(0),
575
+ float(1),
576
+ );
577
+ const weight = (dx ? fraction.x : float(1).sub(fraction.x))
578
+ .mul(dy ? fraction.y : float(1).sub(fraction.y))
579
+ .mul(dz ? fraction.z : float(1).sub(fraction.z))
580
+ .mul(open);
581
+ const coefficient = (index: number) =>
582
+ coefficientNode.element(probe.mul(int(9)).add(int(index))).xyz as V3;
583
+ sum = sum.add(shIrradiance(coefficient, normal).mul(weight));
584
+ total = total.add(weight);
585
+ }
586
+ return sum.div(max(total, 1e-4)) as V3;
587
+ };
588
+
589
+ const trace = Fn(() => {
590
+ const slot = int(instanceIndex).div(int(raysPerProbe));
591
+ const ray = int(instanceIndex).sub(slot.mul(int(raysPerProbe)));
592
+ If(slot.greaterThanEqual(batchSize), () => Return());
593
+ const probe = probes.element(slot);
594
+ const ix = probe.mod(int(nx));
595
+ const iy = probe.div(int(nx)).mod(int(ny));
596
+ const iz = probe.div(int(nx * ny));
597
+ const origin = volumeMin
598
+ .add(vec3(float(ix), float(iy), float(iz)).mul(vec3(spacing.x, spacing.y, spacing.z)))
599
+ .toVar();
600
+ const direction = directions.element(ray).xyz.toVar();
601
+ const back = float(far).toVar();
602
+ const hit = traceRay(buffers, nodeCount, origin, direction, far, false, back);
603
+ const result = vec3(sky).toVar();
604
+ If(hit.triangle.greaterThanEqual(0), () => {
605
+ const a = buffers.triangles.element(hit.triangle.mul(int(3)));
606
+ const b = buffers.triangles.element(hit.triangle.mul(int(3)).add(int(1))).xyz;
607
+ const c = buffers.triangles.element(hit.triangle.mul(int(3)).add(int(2))).xyz;
608
+ const facing = normalize(cross(b.sub(a.xyz), c.sub(a.xyz))).toVar();
609
+ // Two-sided: the side the ray arrived from is the side that returns light.
610
+ If(dot(facing, direction).greaterThan(0), () => facing.assign(facing.negate()));
611
+ const material = int(a.w);
612
+ const albedo = buffers.materials.element(material.mul(int(2))).xyz;
613
+ const emission = buffers.materials.element(material.mul(int(2)).add(int(1))).xyz;
614
+ const point = origin.add(direction.mul(hit.t)).add(facing.mul(SURFACE_OFFSET)).toVar();
615
+ const cosine = max(dot(facing, sunDirection), 0).toVar();
616
+ const visible = float(0).toVar();
617
+ If(cosine.greaterThan(0).and(dot(sunRadiance, vec3(1)).greaterThan(0)), () => {
618
+ const shadow = traceRay(buffers, nodeCount, point, sunDirection, far, true);
619
+ visible.assign(select(shadow.triangle.lessThan(0), float(1), float(0)));
620
+ });
621
+ const direct = vec3(sunRadiance).mul(cosine.mul(visible)).toVar();
622
+ for (const light of points) {
623
+ const toLight = light.position.sub(point);
624
+ const squared = max(dot(toLight, toLight), 0.0001);
625
+ const length = sqrt(squared);
626
+ const toward = toLight.div(length);
627
+ const facingLight = max(dot(facing, toward), 0);
628
+ If(facingLight.greaterThan(0), () => {
629
+ const shadow = traceRay(buffers, nodeCount, point, toward, length.sub(0.02), true);
630
+ If(shadow.triangle.lessThan(0), () => {
631
+ const window = select(
632
+ light.distance.greaterThan(0),
633
+ pow(clamp(float(1).sub(pow(length.div(light.distance), 4)), 0, 1), 2),
634
+ float(1),
635
+ );
636
+ direct.addAssign(light.radiance.mul(facingLight.mul(window).div(squared)));
637
+ });
638
+ });
639
+ }
640
+ const irradiance = direct.add(previousIrradiance(point, facing).mul(bounce));
641
+ result.assign(emission.add(albedo.mul(irradiance).mul(INV_PI)));
642
+ });
643
+ // w: the hit distance (`far` on a miss), negative when the ray first met a surface from behind (the probe's rejection
644
+ // share, `BACKFACE_REJECTION_SHARE`). The octahedral map keeps the distance as its depth, as Unreal's radiance cache
645
+ // keeps a depth atlas beside its radiance (UE 5.8.3: Engine/Shaders/Private/Lumen/LumenRadianceCacheInterpolation.ush:215).
646
+ const distance = select(hit.triangle.greaterThanEqual(0), max(hit.t, 0.0001), float(far));
647
+ radianceNode
648
+ .element(instanceIndex)
649
+ .assign(vec4(result, select(back.lessThan(hit.t), distance.negate(), distance)));
650
+ })().compute(maxBatch * raysPerProbe);
651
+
652
+ const project = Fn(() => {
653
+ const slot = int(instanceIndex);
654
+ If(slot.greaterThanEqual(batchSize), () => Return());
655
+ const probe = probes.element(slot);
656
+ const sums = Array.from({ length: 9 }, () => vec3(0).toVar());
657
+ const backfaces = float(0).toVar();
658
+ const add = (index: number, value: AnyNode) => (sums[index] as AnyNode).addAssign(value);
659
+ Loop(
660
+ { start: int(0), end: int(raysPerProbe), type: "int", condition: "<" },
661
+ ({ i }: { i: AnyNode }) => {
662
+ const sample = radianceNode.element(slot.mul(int(raysPerProbe)).add(i));
663
+ const value = sample.xyz;
664
+ backfaces.addAssign(select(sample.w.lessThan(0), float(1), float(0)));
665
+ const d = directions.element(i);
666
+ add(0, value.mul(0.282095));
667
+ add(1, value.mul(d.y.mul(0.488603)));
668
+ add(2, value.mul(d.z.mul(0.488603)));
669
+ add(3, value.mul(d.x.mul(0.488603)));
670
+ add(4, value.mul(d.x.mul(d.y).mul(1.092548)));
671
+ add(5, value.mul(d.y.mul(d.z).mul(1.092548)));
672
+ add(6, value.mul(d.z.mul(d.z).mul(3).sub(1).mul(0.315392)));
673
+ add(7, value.mul(d.x.mul(d.z).mul(1.092548)));
674
+ add(8, value.mul(d.x.mul(d.x).sub(d.y.mul(d.y)).mul(0.546274)));
675
+ },
676
+ );
677
+ const norm = (4 * Math.PI) / raysPerProbe;
678
+ sums.forEach((sum, index) => {
679
+ coefficientNode
680
+ .element(probe.mul(int(9)).add(int(index)))
681
+ .assign(vec4((sum as AnyNode).mul(norm), index === 0 ? backfaces.div(raysPerProbe) : 0));
682
+ });
683
+ })().compute(maxBatch);
684
+
685
+ // Each probe's octahedral radiance map: one work item per (probe, cell) averages the rays the table puts in that cell.
686
+ const cells = octahedralResolution * octahedralResolution;
687
+ let octahedral: AnyNode | undefined;
688
+ let radianceMap: StorageBufferAttribute | undefined;
689
+ if (cells > 0) {
690
+ const table = octahedralRayTable(
691
+ probeRayDirections(raysPerProbe),
692
+ raysPerProbe,
693
+ octahedralResolution,
694
+ );
695
+ const cellRays = read(table.rays, "vec4");
696
+ const cellRanges = read(table.ranges, "vec4");
697
+ radianceMap = buffer(new Float32Array(grid.probeCount * cells * 4), 4);
698
+ const mapNode = storage(radianceMap, "vec4", grid.probeCount * cells) as AnyNode;
699
+ octahedral = Fn(() => {
700
+ const slot = int(instanceIndex).div(int(cells));
701
+ const cell = int(instanceIndex).sub(slot.mul(int(cells)));
702
+ If(slot.greaterThanEqual(batchSize), () => Return());
703
+ const probe = probes.element(slot);
704
+ const range = cellRanges.element(cell);
705
+ const first = int(range.x);
706
+ const count = int(range.y);
707
+ const sum = vec3(0).toVar();
708
+ const depth = float(0).toVar();
709
+ Loop({ start: int(0), end: count, type: "int", condition: "<" }, ({ i }: { i: AnyNode }) => {
710
+ const ray = int(cellRays.element(first.add(i)).x);
711
+ const sample = radianceNode.element(slot.mul(int(raysPerProbe)).add(ray));
712
+ sum.addAssign(sample.xyz);
713
+ depth.addAssign(abs(sample.w));
714
+ });
715
+ // w: the cell's mean hit distance, the depth `ProbeVolume`'s visibility test reads.
716
+ mapNode
717
+ .element(probe.mul(int(cells)).add(cell))
718
+ .assign(vec4(sum.div(float(count)), depth.div(float(count))));
719
+ })().compute(maxBatch * cells);
720
+ }
721
+
722
+ return {
723
+ batchSize,
724
+ bounce,
725
+ coefficients,
726
+ dispose: () => {
727
+ for (const attribute of attributes) (attribute as { dispose?: () => void }).dispose?.();
728
+ },
729
+ materials: materialNode.value as StorageBufferAttribute,
730
+ maxBatch,
731
+ octahedralResolution: cells > 0 ? octahedralResolution : 0,
732
+ ...(octahedral === undefined ? {} : { octahedral }),
733
+ ...(radianceMap === undefined ? {} : { radianceMap }),
734
+ probeList,
735
+ project,
736
+ points,
737
+ raysPerProbe,
738
+ sky,
739
+ sunDirection,
740
+ sunRadiance,
741
+ trace,
742
+ };
743
+ }
744
+
745
+ /**
746
+ * Replace each rejected probe's 27 coefficients (9 SH x RGB) with the mean of its open face neighbours, in rings
747
+ * outward, so a reader that interpolates across a wall never mixes in the light a probe saw from inside it or from
748
+ * behind it. A rejected probe with no open probe anywhere keeps its own value. Returns the number rejected.
749
+ */
750
+ export function fillRejectedProbes(
751
+ coefficients: Float32Array,
752
+ shares: Float32Array,
753
+ resolution: { readonly x: number; readonly y: number; readonly z: number },
754
+ /** Other per-probe arrays to fill the same way (an octahedral radiance map), each with its floats per probe. */
755
+ alongside: readonly { readonly data: Float32Array; readonly stride: number }[] = [],
756
+ ): number {
757
+ const { x: nx, y: ny, z: nz } = resolution;
758
+ const open = Uint8Array.from(shares, (share) => (share > BACKFACE_REJECTION_SHARE ? 0 : 1));
759
+ const rejected = open.length - open.reduce((sum, value) => sum + value, 0);
760
+ let filled = [0];
761
+ while (filled.length > 0) {
762
+ filled = [];
763
+ for (let probe = 0; probe < open.length; probe += 1) {
764
+ const neighbours = open[probe] === 1 ? [] : openNeighbours(probe, open, nx, ny, nz);
765
+ if (neighbours.length === 0) continue;
766
+ meanInto(coefficients, probe, neighbours, 27);
767
+ for (const { data, stride } of alongside) meanInto(data, probe, neighbours, stride);
768
+ filled.push(probe);
769
+ }
770
+ for (const probe of filled) open[probe] = 1;
771
+ }
772
+ return rejected;
773
+ }
774
+
775
+ /** One probe's `stride` floats (27 SH coefficients, or a radiance map) become the mean of its neighbours'. */
776
+ function meanInto(
777
+ coefficients: Float32Array,
778
+ probe: number,
779
+ neighbours: readonly number[],
780
+ stride: number,
781
+ ): void {
782
+ for (let k = 0; k < stride; k += 1) {
783
+ let sum = 0;
784
+ for (const n of neighbours) sum += coefficients[n * stride + k] ?? 0;
785
+ coefficients[probe * stride + k] = sum / neighbours.length;
786
+ }
787
+ }
788
+
789
+ /** The open face neighbours of a probe in an nx x ny x nz grid. */
790
+ function openNeighbours(
791
+ probe: number,
792
+ open: Uint8Array,
793
+ nx: number,
794
+ ny: number,
795
+ nz: number,
796
+ ): number[] {
797
+ const ix = probe % nx;
798
+ const iy = Math.floor(probe / nx) % ny;
799
+ const iz = Math.floor(probe / (nx * ny));
800
+ return [
801
+ ix > 0 ? probe - 1 : -1,
802
+ ix < nx - 1 ? probe + 1 : -1,
803
+ iy > 0 ? probe - nx : -1,
804
+ iy < ny - 1 ? probe + nx : -1,
805
+ iz > 0 ? probe - nx * ny : -1,
806
+ iz < nz - 1 ? probe + nx * ny : -1,
807
+ ].filter((n) => n >= 0 && open[n] === 1);
808
+ }
809
+
810
+ /** A lighting step: where the sun points and how bright the sun and the sky are, at one moment. */
811
+ export interface ILightingKey {
812
+ readonly direction: Vector3;
813
+ readonly sun: number;
814
+ readonly sky: number;
815
+ }
816
+
817
+ /** PRD-603 Phase 3: a step is more than one degree of sun direction, or a 4x change of the brightest channel. */
818
+ const LIGHTING_STEP_RADIANS = Math.PI / 180;
819
+ const LIGHTING_STEP_RATIO = 4;
820
+
821
+ export function lightingKey(lighting: IProbeTraceLighting): ILightingKey {
822
+ const peak = (color: Color, scale: number) => Math.max(color.r, color.g, color.b) * scale;
823
+ return {
824
+ direction: lighting.direction.clone().normalize(),
825
+ sky: peak(lighting.sky, 1),
826
+ sun: peak(lighting.color, lighting.intensity),
827
+ };
828
+ }
829
+
830
+ const ratioStepped = (from: number, to: number): boolean => {
831
+ if (from === to) return false;
832
+ if (from <= 0 || to <= 0) return true;
833
+ const ratio = to / from;
834
+ return ratio > LIGHTING_STEP_RATIO || ratio < 1 / LIGHTING_STEP_RATIO;
835
+ };
836
+
837
+ /**
838
+ * True when `to` differs from `from` by more than the field may serve as a small drift. The direction counts only while
839
+ * the sun lights the scene: an unlit sun has none, and three's `angleTo` reads a zero vector as 90 degrees, so a scene
840
+ * with no sun would restart its bake every frame.
841
+ */
842
+ export function lightingStepped(from: ILightingKey, to: ILightingKey): boolean {
843
+ return (
844
+ (from.sun > 0 && to.sun > 0 && from.direction.angleTo(to.direction) > LIGHTING_STEP_RADIANS) ||
845
+ ratioStepped(from.sun, to.sun) ||
846
+ ratioStepped(from.sky, to.sky)
847
+ );
848
+ }
849
+
850
+ /** Pack the lighting inputs into the kernel uniforms. */
851
+ export function applyTraceLighting(
852
+ kernels: IProbeTraceKernels,
853
+ lighting: IProbeTraceLighting,
854
+ ): void {
855
+ // `set`, not `copy`: the owned engine's uniform vectors take a component write.
856
+ const { x, y, z } = lighting.direction.clone().normalize();
857
+ kernels.sunDirection.value.set(x, y, z);
858
+ kernels.sunRadiance.value
859
+ .set(lighting.color.r, lighting.color.g, lighting.color.b)
860
+ .multiplyScalar(lighting.intensity);
861
+ kernels.sky.value.set(lighting.sky.r, lighting.sky.g, lighting.sky.b);
862
+ kernels.points.forEach((light, index) => {
863
+ const source = lighting.points?.[index];
864
+ light.radiance.value.set(0, 0, 0);
865
+ if (source === undefined) return;
866
+ light.position.value.set(source.position.x, source.position.y, source.position.z);
867
+ light.radiance.value
868
+ .set(source.color.r, source.color.g, source.color.b)
869
+ .multiplyScalar(source.intensity);
870
+ light.distance.value = source.distance ?? 0;
871
+ });
872
+ }