@threenative/three-native 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threenative/three-native",
3
- "version": "0.3.11",
3
+ "version": "0.3.13",
4
4
  "license": "MIT",
5
5
  "description": "The native engine's machine-readable compatibility catalog and the generators that adapt it to TypeScript declarations and the C binding ABI.",
6
6
  "keywords": [
@@ -12,7 +12,7 @@
12
12
  ],
13
13
  "repository": {
14
14
  "type": "git",
15
- "url": "git+https://github.com/ThreeNativeHQ/threenative.git",
15
+ "url": "git+https://github.com/ThreeNativeHQ/threenative-engine.git",
16
16
  "directory": "packages/three-native"
17
17
  },
18
18
  "type": "module",
@@ -0,0 +1,170 @@
1
+ /**
2
+ * `three/addons/animation/CCDIKSolver.js` as the engine back ends provide it: three's CCD solver,
3
+ * ported from three r187 examples/jsm/animation/CCDIKSolver.js (MIT), over whichever engine `three`
4
+ * names in this build, the V8 facade or the Wasm entry. Every call it makes is a bound engine method.
5
+ * The scratch values are per solver, not module-level, so importing the addon creates no engine object.
6
+ * CCDIKHelper is not ported: `createHelper` refuses by name.
7
+ */
8
+ import { type Bone, Matrix4, Quaternion, type SkinnedMesh, Vector3 } from "three";
9
+
10
+ export interface IIkLink {
11
+ index: number;
12
+ enabled?: boolean;
13
+ limitation?: Vector3;
14
+ rotationMin?: Vector3;
15
+ rotationMax?: Vector3;
16
+ }
17
+
18
+ export interface IIkChain {
19
+ target: number;
20
+ effector: number;
21
+ links: IIkLink[];
22
+ iteration?: number;
23
+ minAngle?: number;
24
+ maxAngle?: number;
25
+ blendFactor?: number;
26
+ }
27
+
28
+ // MathUtils.euclideanModulo.
29
+ const modulo = (n: number, m: number) => ((n % m) + m) % m;
30
+
31
+ export class CCDIKSolver {
32
+ readonly #quaternion = new Quaternion();
33
+ readonly #targetPos = new Vector3();
34
+ readonly #targetVec = new Vector3();
35
+ readonly #effectorPos = new Vector3();
36
+ readonly #effectorVec = new Vector3();
37
+ readonly #linkPos = new Vector3();
38
+ readonly #invLinkQ = new Quaternion();
39
+ readonly #linkScale = new Vector3();
40
+ readonly #axis = new Vector3();
41
+ readonly #vector = new Vector3();
42
+ readonly #center = new Vector3();
43
+ readonly #workingQuaternion = new Quaternion();
44
+ readonly #initialQuaternions: Quaternion[][];
45
+
46
+ constructor(
47
+ readonly mesh: SkinnedMesh,
48
+ readonly iks: IIkChain[] = [],
49
+ ) {
50
+ this.#initialQuaternions = iks.map((ik) => ik.links.map(() => new Quaternion()));
51
+ this.#valid();
52
+ }
53
+
54
+ update(globalBlendFactor = 1.0): this {
55
+ for (const ik of this.iks) this.updateOne(ik, globalBlendFactor);
56
+ return this;
57
+ }
58
+
59
+ updateOne(ik: IIkChain, overrideBlend = 1.0): this {
60
+ const chainBlend = ik.blendFactor ?? overrideBlend;
61
+ const bones = this.mesh.skeleton.bones;
62
+ const initialQuaternions = this.#initialQuaternions[this.iks.indexOf(ik)] ?? [];
63
+ const effector = bones[ik.effector] as Bone;
64
+ const target = bones[ik.target] as Bone;
65
+ // three reads matrixWorld, not getWorldPosition(), which updates the world matrices first.
66
+ this.#targetPos.setFromMatrixPosition(target.matrixWorld);
67
+ const links = ik.links;
68
+ if (chainBlend < 1.0)
69
+ for (const [j, link] of links.entries())
70
+ initialQuaternions[j]?.copy((bones[link.index] as Bone).quaternion);
71
+ for (let i = 0; i < (ik.iteration ?? 1); i++) if (!this.#iterate(ik, bones, effector)) break;
72
+ if (chainBlend < 1.0) this.#blend(links, bones, initialQuaternions, chainBlend);
73
+ return this;
74
+ }
75
+
76
+ createHelper(): never {
77
+ throw new Error(
78
+ "TN_NATIVE_UNSUPPORTED_CCDIKHELPER: CCDIKSolver.createHelper needs three's CCDIKHelper, which the engine does not bind; draw the chain from skeleton.bones instead.",
79
+ );
80
+ }
81
+
82
+ // One pass over the chain; false when no link turned, which ends the solve.
83
+ #iterate(ik: IIkChain, bones: Bone[], effector: Bone): boolean {
84
+ let rotated = false;
85
+ for (const entry of ik.links) {
86
+ // An off link stops the chain here.
87
+ if (entry.enabled === false) break;
88
+ if (this.#rotateLink(ik, entry, bones[entry.index] as Bone, effector)) rotated = true;
89
+ }
90
+ return rotated;
91
+ }
92
+
93
+ // A chain blend under 1 slerps each link from its pose before the solve toward the solved pose.
94
+ #blend(links: IIkLink[], bones: Bone[], initial: Quaternion[], chainBlend: number): void {
95
+ for (const [j, entry] of links.entries()) {
96
+ const link = bones[entry.index] as Bone;
97
+ this.#workingQuaternion.copy(initial[j] as Quaternion).slerp(link.quaternion, chainBlend);
98
+ link.quaternion.copy(this.#workingQuaternion);
99
+ link.updateMatrixWorld(true);
100
+ }
101
+ }
102
+
103
+ // One CCD step on one link: rotate it so the effector points at the target. False when the angle
104
+ // is too small to turn, which three skips to prevent bone vibration.
105
+ #rotateLink(ik: IIkChain, entry: IIkLink, link: Bone, effector: Bone): boolean {
106
+ link.matrixWorld.decompose(this.#linkPos, this.#invLinkQ, this.#linkScale);
107
+ this.#invLinkQ.invert();
108
+ this.#effectorPos.setFromMatrixPosition(effector.matrixWorld);
109
+ // Work in the link's world frame.
110
+ this.#effectorVec
111
+ .subVectors(this.#effectorPos, this.#linkPos)
112
+ .applyQuaternion(this.#invLinkQ)
113
+ .normalize();
114
+ this.#targetVec
115
+ .subVectors(this.#targetPos, this.#linkPos)
116
+ .applyQuaternion(this.#invLinkQ)
117
+ .normalize();
118
+ let angle = Math.acos(Math.min(1, Math.max(-1, this.#targetVec.dot(this.#effectorVec))));
119
+ if (angle < 1e-5) return false;
120
+ if (ik.minAngle !== undefined && angle < ik.minAngle) angle = ik.minAngle;
121
+ if (ik.maxAngle !== undefined && angle > ik.maxAngle) angle = ik.maxAngle;
122
+ this.#axis.crossVectors(this.#effectorVec, this.#targetVec).normalize();
123
+ this.#quaternion.setFromAxisAngle(this.#axis, angle);
124
+ link.quaternion.multiply(this.#quaternion);
125
+ this.#limit(entry, link);
126
+ link.updateMatrixWorld(true);
127
+ return true;
128
+ }
129
+
130
+ // three's link limits: a hinge axis, then Euler angle bounds.
131
+ #limit(entry: IIkLink, link: Bone): void {
132
+ const { limitation, rotationMin, rotationMax } = entry;
133
+ if (limitation !== undefined) {
134
+ const q = link.quaternion;
135
+ const c = Math.min(q.w, 1.0);
136
+ // Keep the sign of the rotation along the limitation axis; else a negative turn mirrors.
137
+ const dot = q.x * limitation.x + q.y * limitation.y + q.z * limitation.z;
138
+ const c2 = (dot < 0 ? -1 : 1) * Math.sqrt(1 - c * c);
139
+ q.set(limitation.x * c2, limitation.y * c2, limitation.z * c2, c);
140
+ }
141
+ if (rotationMin !== undefined || rotationMax !== undefined) {
142
+ const v = this.#vector.setFromEuler(link.rotation);
143
+ if (rotationMin !== undefined && rotationMax !== undefined) {
144
+ // Wrap each angle to within pi of the limits' centre, so a range across +-pi clamps right.
145
+ const c = this.#center.addVectors(rotationMin, rotationMax).multiplyScalar(0.5);
146
+ v.x = c.x + modulo(v.x - c.x + Math.PI, 2 * Math.PI) - Math.PI;
147
+ v.y = c.y + modulo(v.y - c.y + Math.PI, 2 * Math.PI) - Math.PI;
148
+ v.z = c.z + modulo(v.z - c.z + Math.PI, 2 * Math.PI) - Math.PI;
149
+ }
150
+ if (rotationMin !== undefined) v.max(rotationMin);
151
+ if (rotationMax !== undefined) v.min(rotationMax);
152
+ link.rotation.setFromVector3(v);
153
+ }
154
+ }
155
+
156
+ #valid(): void {
157
+ const bones = this.mesh.skeleton.bones;
158
+ for (const ik of this.iks) {
159
+ let child = bones[ik.effector] as Bone;
160
+ for (const entry of ik.links) {
161
+ const parent = bones[entry.index] as Bone;
162
+ if (child.parent !== parent)
163
+ console.warn(
164
+ `THREE.CCDIKSolver: bone ${child.name} is not the child of bone ${parent.name}`,
165
+ );
166
+ child = parent;
167
+ }
168
+ }
169
+ }
170
+ }
@@ -15,10 +15,12 @@ import { __tnLoadGltf } from "three";
15
15
 
16
16
  interface IEngineModel {
17
17
  readonly scene: object;
18
+ /** Every scene in file order: a model can keep each LOD level as a named scene (`fir_lod1`). */
19
+ readonly scenes: readonly object[];
18
20
  readonly animations: readonly object[];
19
21
  }
20
22
 
21
- /** GLTFLoader's result: one default scene, its clips, and the members three's callers read. */
23
+ /** GLTFLoader's result: the default scene, every scene, its clips, and the members three's callers read. */
22
24
  export interface IGltfResult {
23
25
  readonly scene: object;
24
26
  readonly scenes: readonly object[];
@@ -30,7 +32,7 @@ export interface IGltfResult {
30
32
  }
31
33
 
32
34
  const load = __tnLoadGltf as
33
- | ((bytes: Uint8Array, files: ReadonlyMap<string, Uint8Array>) => IEngineModel)
35
+ | ((bytes: Uint8Array, files: ReadonlyMap<string, Uint8Array>) => Promise<IEngineModel>)
34
36
  | undefined;
35
37
 
36
38
  interface IGltfJson {
@@ -42,7 +44,12 @@ interface IGltfJson {
42
44
  sparse?: unknown;
43
45
  type?: string;
44
46
  }[];
45
- bufferViews?: { byteLength?: number; byteOffset?: number; byteStride?: number }[];
47
+ bufferViews?: {
48
+ byteLength?: number;
49
+ byteOffset?: number;
50
+ byteStride?: number;
51
+ extensions?: Record<string, IMeshoptView | undefined>;
52
+ }[];
46
53
  images?: { uri?: unknown }[];
47
54
  meshes?: { primitives?: unknown[] }[];
48
55
  nodes?: { children?: number[]; mesh?: number }[];
@@ -50,6 +57,30 @@ interface IGltfJson {
50
57
  scenes?: { nodes?: number[] }[];
51
58
  }
52
59
 
60
+ /** An EXT/KHR_meshopt_compression buffer view: the compressed stream and how it decodes. */
61
+ interface IMeshoptView {
62
+ buffer?: number;
63
+ byteLength?: number;
64
+ byteOffset?: number;
65
+ byteStride?: number;
66
+ count?: number;
67
+ filter?: string;
68
+ mode?: string;
69
+ }
70
+
71
+ /** three's MeshoptDecoder, as core hands it to `setMeshoptDecoder`. */
72
+ interface IMeshoptDecoder {
73
+ readonly ready: Promise<void>;
74
+ decodeGltfBuffer(
75
+ target: Uint8Array,
76
+ count: number,
77
+ size: number,
78
+ source: Uint8Array,
79
+ mode: string,
80
+ filter?: string,
81
+ ): void;
82
+ }
83
+
53
84
  /** The JSON and, for a GLB, the binary chunk. Throws on a file that is neither. */
54
85
  function readGltf(data: ArrayBuffer | string): { json: IGltfJson; bin: Uint8Array | undefined } {
55
86
  if (typeof data === "string") return { bin: undefined, json: JSON.parse(data) as IGltfJson };
@@ -108,12 +139,48 @@ type PluginFactory = (parser: IEngineParser) => IHostedPlugin;
108
139
 
109
140
  const ELEMENTS = { 5121: Uint8Array, 5123: Uint16Array, 5125: Uint32Array } as const;
110
141
 
142
+ /**
143
+ * A buffer view's bytes from the GLB's binary chunk: as stored, or decoded when the cook
144
+ * meshopt-compressed it (the engine's own loader decodes the mesh; this reads only the LOD chain).
145
+ */
146
+ async function viewBytes(
147
+ view: NonNullable<IGltfJson["bufferViews"]>[number],
148
+ bin: Uint8Array,
149
+ decoder: IMeshoptDecoder | undefined,
150
+ index: number,
151
+ ): Promise<Uint8Array> {
152
+ const meshopt =
153
+ view.extensions?.EXT_meshopt_compression ?? view.extensions?.KHR_meshopt_compression;
154
+ if (meshopt === undefined) return bin.subarray(view.byteOffset ?? 0);
155
+ const { byteLength = 0, byteOffset = 0, byteStride = 0, count = 0, mode = "" } = meshopt;
156
+ if (
157
+ decoder === undefined ||
158
+ (meshopt.buffer ?? 0) !== 0 ||
159
+ byteOffset + byteLength > bin.byteLength
160
+ )
161
+ throw new Error(
162
+ `TN_WASM_GLTF_LOD_ACCESSOR: accessor ${String(index)} is meshopt-compressed ${decoder === undefined ? "and no meshopt decoder was set" : "outside the binary chunk"}`,
163
+ );
164
+ await decoder.ready;
165
+ const decoded = new Uint8Array(count * byteStride);
166
+ decoder.decodeGltfBuffer(
167
+ decoded,
168
+ count,
169
+ byteStride,
170
+ bin.subarray(byteOffset, byteOffset + byteLength),
171
+ mode,
172
+ meshopt.filter,
173
+ );
174
+ return decoded;
175
+ }
176
+
111
177
  /** An index accessor's values, copied out of the GLB's binary chunk. */
112
- function readIndices(
178
+ async function readIndices(
113
179
  json: IGltfJson,
114
180
  bin: Uint8Array | undefined,
115
181
  index: number,
116
- ): { array: ArrayLike<number> } {
182
+ decoder: IMeshoptDecoder | undefined,
183
+ ): Promise<{ array: ArrayLike<number> }> {
117
184
  const accessor = json.accessors?.[index];
118
185
  const view = json.bufferViews?.[accessor?.bufferView ?? -1];
119
186
  const Element = ELEMENTS[accessor?.componentType as keyof typeof ELEMENTS];
@@ -131,13 +198,14 @@ function readIndices(
131
198
  );
132
199
  if (bin === undefined)
133
200
  throw new Error("TN_WASM_GLTF_LOD_ACCESSOR: only a GLB's binary chunk is read for a LOD chain");
134
- const start = (view.byteOffset ?? 0) + (accessor.byteOffset ?? 0);
201
+ const bytes = await viewBytes(view, bin, decoder, index);
202
+ const start = accessor.byteOffset ?? 0;
135
203
  const end = start + accessor.count * Element.BYTES_PER_ELEMENT;
136
- if (!Number.isInteger(start) || end > bin.byteLength)
204
+ if (!Number.isInteger(start) || end > bytes.byteLength)
137
205
  throw new Error(
138
206
  `TN_WASM_GLTF_LOD_ACCESSOR: accessor ${String(index)} reads past the binary chunk`,
139
207
  );
140
- return { array: new Element(bin.slice(start, end).buffer) };
208
+ return { array: new Element(bytes.slice(start, end).buffer) };
141
209
  }
142
210
 
143
211
  /**
@@ -179,13 +247,14 @@ function associate(json: IGltfJson, scene: object, into: IEngineParser["associat
179
247
  function hostPlugins(
180
248
  factories: readonly PluginFactory[],
181
249
  data: ArrayBuffer | string,
250
+ decoder: IMeshoptDecoder | undefined,
182
251
  ): { parser: IEngineParser; plugins: IHostedPlugin[] } | undefined {
183
252
  if (factories.length === 0) return undefined;
184
253
  const { bin, json } = readGltf(data);
185
254
  const parser: IEngineParser = {
186
255
  associations: new Map(),
187
256
  getDependency: async (type, index) => {
188
- if (type === "accessor") return readIndices(json, bin, index);
257
+ if (type === "accessor") return readIndices(json, bin, index, decoder);
189
258
  throw new Error(
190
259
  `TN_WASM_GLTF_DEPENDENCY_UNSUPPORTED: the engine glTF loader returns no '${type}'`,
191
260
  );
@@ -197,11 +266,44 @@ function hostPlugins(
197
266
  return { parser, plugins };
198
267
  }
199
268
 
269
+ /**
270
+ * One fetch per image file while it is in flight: models loaded together that share an image (ten
271
+ * spruce models and their 12 MB atlas in the Strata forest) wait on the same bytes instead of each
272
+ * downloading them. The engine copies the bytes, so sharing them is safe. Nothing is kept once the
273
+ * fetch lands. ponytail: a model loaded later fetches again; keep the bytes if that shows in a load.
274
+ */
275
+ const inFlight = new Map<string, Promise<Uint8Array>>();
276
+ function imageBytes(url: string): Promise<Uint8Array> {
277
+ const key = new URL(url, globalThis.location?.href ?? "http://localhost/").href;
278
+ let pending = inFlight.get(key);
279
+ if (pending === undefined) {
280
+ pending = (async () => {
281
+ const response = await fetch(url);
282
+ if (!response.ok) throw new Error(`TN_WASM_GLTF_FETCH: ${response.status} ${url}`);
283
+ // A dev server answers a missing file with its page and a 200 (Vite's SPA fallback); the
284
+ // engine would refuse those bytes only as "undecoded images", without the file's name.
285
+ if (response.headers.get("content-type")?.startsWith("text/html"))
286
+ throw new Error(`TN_WASM_GLTF_FETCH: text/html ${url}`);
287
+ return new Uint8Array(await response.arrayBuffer());
288
+ })();
289
+ inFlight.set(key, pending);
290
+ const settled = () => inFlight.delete(key);
291
+ pending.then(settled, settled);
292
+ }
293
+ return pending;
294
+ }
295
+
200
296
  export class GLTFLoader {
201
297
  path = "";
298
+ /**
299
+ * Serves one image file's bytes in place of a plain fetch: core hands the resident levels of a
300
+ * KTX2 here (PRD-860). `undefined` from it means "fetch it as usual".
301
+ */
302
+ imageSource: ((url: string) => Promise<Uint8Array | undefined>) | undefined = undefined;
202
303
  /** A plugin defect (a chain the file declares and cannot deliver) rejects the load; core's plugin logs it on stock three. */
203
304
  readonly failClosed = true;
204
305
  readonly #factories: PluginFactory[] = [];
306
+ #meshopt: IMeshoptDecoder | undefined;
205
307
 
206
308
  setPath(path: string): this {
207
309
  this.path = path;
@@ -220,12 +322,18 @@ export class GLTFLoader {
220
322
  return this;
221
323
  }
222
324
 
223
- setKTX2Loader(): never {
224
- return refuse("KTX2");
325
+ /** The engine's loader transcodes KHR_texture_basisu itself (PRD-861), so the JS loader goes unused. */
326
+ setKTX2Loader(_loader?: unknown): this {
327
+ return this;
225
328
  }
226
329
 
227
- setMeshoptDecoder(): never {
228
- return refuse("MESHOPT");
330
+ /**
331
+ * The engine's loader decodes EXT/KHR_meshopt_compression itself (PRD-861); the JS decoder reads
332
+ * only a hosted LOD chain's compressed index views.
333
+ */
334
+ setMeshoptDecoder(decoder?: IMeshoptDecoder): this {
335
+ this.#meshopt = decoder;
336
+ return this;
229
337
  }
230
338
 
231
339
  setDRACOLoader(): never {
@@ -252,11 +360,11 @@ export class GLTFLoader {
252
360
  throw new Error("TN_WASM_GLTF_UNAVAILABLE: this web engine has no glTF loader");
253
361
  const bytes =
254
362
  typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
255
- const hosted = hostPlugins(this.#factories, data);
256
- const model = load(bytes, files);
363
+ const hosted = hostPlugins(this.#factories, data, this.#meshopt);
364
+ const model = await load(bytes, files);
257
365
  result = {
258
366
  scene: model.scene,
259
- scenes: [model.scene],
367
+ scenes: [...model.scenes],
260
368
  animations: [...model.animations],
261
369
  cameras: [],
262
370
  asset: { version: "2.0" },
@@ -280,16 +388,14 @@ export class GLTFLoader {
280
388
  return;
281
389
  }
282
390
  Promise.all(
283
- uris.map(async (uri) => {
284
- const response = await fetch(path + uri);
285
- if (!response.ok) throw new Error(`TN_WASM_GLTF_FETCH: ${response.status} ${path + uri}`);
286
- // A dev server answers a missing file with its page and a 200 (Vite's SPA fallback); the
287
- // engine would refuse those bytes only as "undecoded images", without the file's name.
288
- if (response.headers.get("content-type")?.startsWith("text/html"))
289
- throw new Error(`TN_WASM_GLTF_FETCH: text/html ${path + uri}`);
290
- // The engine loader asks for the uri with its percent escapes decoded.
291
- return [decodeURIComponent(uri), new Uint8Array(await response.arrayBuffer())] as const;
292
- }),
391
+ // The engine loader asks for the uri with its percent escapes decoded.
392
+ uris.map(
393
+ async (uri) =>
394
+ [
395
+ decodeURIComponent(uri),
396
+ (await this.imageSource?.(path + uri)) ?? (await imageBytes(path + uri)),
397
+ ] as const,
398
+ ),
293
399
  ).then(
294
400
  (files) => settle(new Map(files)),
295
401
  (error: unknown) => {
@@ -47,6 +47,7 @@ export interface IScreenSpaceTsl {
47
47
  readonly min: (a: TslNode, b: TslNode) => TslNode;
48
48
  readonly mix: (a: TslNode, b: TslNode, t: TslNode) => TslNode;
49
49
  readonly normalize: (value: TslNode) => TslNode;
50
+ readonly pow: (base: TslNode, exponent: TslNode) => TslNode;
50
51
  readonly reflect: (incident: TslNode, normal: TslNode) => TslNode;
51
52
  readonly rtt: (
52
53
  source: TslNode,
@@ -418,11 +419,15 @@ export interface IScreenSpaceGiOptions {
418
419
  readonly camera: IScreenSpaceCamera;
419
420
  /**
420
421
  * The light a ray that finds nothing on screen would have returned: the tier below the screen traces. It is
421
- * called once per pixel with the pixel's view-space position and unit normal and answers the average incident
422
- * radiance (E / pi) that tier already supplies there. The gather then returns `hit - fallback` for the rays that
423
- * hit, so the two tiers never add the same light twice. Missing means 0, as three's SSGINode (hits add light).
422
+ * called for each ray that hits, with the receiver's view-space position and the ray's unit view-space direction,
423
+ * and answers the radiance that tier supplies along that direction (a cosine-convolved field answers E / pi for the
424
+ * direction as its normal). The gather then returns `hit - fallback` for the rays that hit, so the two tiers never add
425
+ * the same light twice. Lumen samples its radiance cache the same way, per ray direction (EpicGames/UnrealEngine:
426
+ * Engine/Shaders/Private/Lumen/LumenScreenProbeTracing.usf:831, SampleRadianceCacheAndApply with RayWorldDirection).
427
+ * One value per pixel (the cache's mean over the hemisphere) made every hit into a dark corner a loss: its rays find
428
+ * the shadowed walls nearby while its bright directions leave the screen. Missing means 0, as three's SSGINode.
424
429
  */
425
- readonly fallback?: (position: TslNode, normal: TslNode) => TslNode;
430
+ readonly fallback?: (position: TslNode, direction: TslNode, normal: TslNode) => TslNode;
426
431
  /**
427
432
  * Gather with screen probes instead of per-pixel rays (Unreal's ScreenProbeGather): one probe per
428
433
  * `downsampleFactor` pixel tile traces an octahedron of rays, the probe radiance is turned into an irradiance
@@ -470,7 +475,11 @@ const GI_MAX_LUMINANCE = 40;
470
475
  * multiplies it by the receiver's albedo (`mrt({ diffuseColor })`) and adds it to the lit frame.
471
476
  * rgb mean over the rays of hit x (hit radiance - fallback)
472
477
  * a the share of rays that hit
473
- * `getAONode()` answers 1: occlusion is the GTAO stage's, and hits already darken through `hit - fallback`.
478
+ * `getAONode()` answers that share as occlusion, in the form the caller applies: three's SSGINode averages the occluded
479
+ * share of its rays and answers `pow(clamp(1 - occludedShare), aoIntensity)` for the caller to multiply the lit frame
480
+ * by (SSGINode.js:637-638, 651). This answers the same quantity as `pow(clamp(1 - a), aoIntensity)` over rgb. A
481
+ * constant 1 dropped the term: the frame kept the light the occluder blocked and SSGI only added its gather
482
+ * (2026-11-02, PRD-617 AC-7). With a `fallback` tier it answers 1: each hit already replaced the cache along its ray.
474
483
  */
475
484
  export function defineScreenSpaceGi(tsl: IScreenSpaceTsl) {
476
485
  return function ssgi(
@@ -479,8 +488,23 @@ export function defineScreenSpaceGi(tsl: IScreenSpaceTsl) {
479
488
  normalNode: TslNode,
480
489
  cameraOrOptions: IScreenSpaceCamera | IScreenSpaceGiOptions,
481
490
  ): TslNode {
482
- const { Break, Fn, If, Loop, float, int, max, min, normalize, rtt, smoothstep, uniform, uv } =
483
- tsl;
491
+ const {
492
+ Break,
493
+ Fn,
494
+ If,
495
+ Loop,
496
+ clamp,
497
+ float,
498
+ int,
499
+ max,
500
+ min,
501
+ normalize,
502
+ pow,
503
+ rtt,
504
+ smoothstep,
505
+ uniform,
506
+ uv,
507
+ } = tsl;
484
508
  const { vec2, vec3, vec4 } = tsl;
485
509
  const options: IScreenSpaceGiOptions =
486
510
  "camera" in cameraOrOptions ? cameraOrOptions : { camera: cameraOrOptions };
@@ -491,9 +515,20 @@ export function defineScreenSpaceGi(tsl: IScreenSpaceTsl) {
491
515
  const sliceCount = uniform(2);
492
516
  const stepCount = uniform(12);
493
517
  const intensity = uniform(1);
518
+ // three's `aoIntensity`: the power applied to the occlusion (SSGINode.js:129, default 1). The caller reads the
519
+ // occlusion through `.r`, so it is broadcast over rgb for a denoise pass to carry.
520
+ const aoIntensity = uniform(1);
494
521
  const screenEdgeFade = uniform(0.1);
495
522
  const probeJitter = uniform(1);
496
523
  const probeDebug = uniform(0);
524
+ // Over a fallback tier the frame holds no occluded light to remove: a ray that hits returns `hit - fallback`, so
525
+ // the cache along it is already swapped for what the ray found, and the hit share multiplied in again took that
526
+ // light out twice, with the direct light (Lumen's screen probe gather applies no such term over its radiance cache).
527
+ const occlusion = (gather: TslNode): TslNode => {
528
+ if (options.fallback !== undefined) return vec4(1, 1, 1, 1);
529
+ const ao = pow(clamp(float(1).sub(gather.a), float(0), float(1)), aoIntensity);
530
+ return vec4(ao, ao, ao, 1);
531
+ };
497
532
  const { march, shade } = defineGiTrace(tsl, {
498
533
  colorNode,
499
534
  depthNode,
@@ -521,13 +556,14 @@ export function defineScreenSpaceGi(tsl: IScreenSpaceTsl) {
521
556
  sliceCount,
522
557
  stepCount,
523
558
  intensity,
559
+ aoIntensity,
524
560
  screenEdgeFade,
525
561
  probeJitter,
526
562
  probeDebug,
527
563
  }).map(([name, value]) => [name, { value }]),
528
564
  ),
529
565
  getGINode: { value: () => node },
530
- getAONode: { value: () => tsl.vec4(1, 1, 1, 1) },
566
+ getAONode: { value: () => occlusion(node) },
531
567
  resolutionScale: {
532
568
  get: () => node.getResolutionScale(),
533
569
  set: (value: number) => node.setResolutionScale(value),
@@ -544,7 +580,6 @@ export function defineScreenSpaceGi(tsl: IScreenSpaceTsl) {
544
580
  If(centreDepth.lessThan(1).and(centreNormal.dot(centreNormal).greaterThan(0.25)), () => {
545
581
  const position = viewPosition(coordinate, centreDepth);
546
582
  const normal = normalize(centreNormal);
547
- const fallback = options.fallback?.(position, normal) ?? vec3(0, 0, 0);
548
583
  // A frame around the normal, and a per-pixel rotation of the ray set (interleaved gradient noise on a
549
584
  // fixed lattice of the uv: the noise is the denoiser's to remove, not a pattern to see).
550
585
  const helper = normal.y
@@ -587,6 +622,7 @@ export function defineScreenSpaceGi(tsl: IScreenSpaceTsl) {
587
622
  const trace = march(origin, direction, position.z);
588
623
  If(trace.hitDistance.greaterThanEqual(0), () => {
589
624
  const hit = shade(trace.hitCoordinate, trace.hitDistance, direction);
625
+ const fallback = options.fallback?.(position, direction, normal) ?? vec3(0, 0, 0);
590
626
  gathered.assign(gathered.add(hit.radiance.sub(fallback).mul(hit.weight)));
591
627
  hits.assign(hits.add(hit.weight));
592
628
  });
@@ -598,13 +634,21 @@ export function defineScreenSpaceGi(tsl: IScreenSpaceTsl) {
598
634
  })();
599
635
 
600
636
  const node = rtt(graph, null, null, { type: HALF_FLOAT_TYPE, gpuStage: GI_STAGE });
601
- const uniformObjects = { radius, thickness, sliceCount, stepCount, intensity, screenEdgeFade };
637
+ const uniformObjects = {
638
+ radius,
639
+ thickness,
640
+ sliceCount,
641
+ stepCount,
642
+ intensity,
643
+ aoIntensity,
644
+ screenEdgeFade,
645
+ };
602
646
  return Object.defineProperties(node, {
603
647
  ...Object.fromEntries(
604
648
  Object.entries(uniformObjects).map(([name, value]) => [name, { value }]),
605
649
  ),
606
650
  getGINode: { value: () => node },
607
- getAONode: { value: () => vec4(1, 1, 1, 1) },
651
+ getAONode: { value: () => occlusion(node) },
608
652
  resolutionScale: {
609
653
  get: () => node.getResolutionScale(),
610
654
  set: (value: number) => node.setResolutionScale(value),
@@ -648,7 +692,7 @@ function octahedronEncode(tsl: IScreenSpaceTsl, direction: TslNode): TslNode {
648
692
  * 1. trace one texel per ray: a probe per tile traces an `n x n` octahedron of rays (view space) and keeps the lit
649
693
  * colour each hit found and its weight.
650
694
  * 2. filter each probe turns its rays into an irradiance octahedron: per direction, the cosine-weighted mean of
651
- * `hit - fallback` over every ray, as the per-pixel gather returns it, so a ray that leaves the screen keeps
695
+ * `hit - fallback` (the trace subtracts the cache along each ray), so a ray that leaves the screen keeps
652
696
  * the cache. A pixel then reads one bilinear tap instead of 64 rays.
653
697
  * 3. gather each pixel blends the four nearest probes by position, depth-plane distance and normal agreement, and
654
698
  * reads each probe's irradiance along the pixel normal. A pixel no probe can see gets the cache alone.
@@ -728,9 +772,10 @@ function defineScreenProbes(
728
772
  const origin = position.add(normal.mul(max(0.01, position.z.negate().mul(0.004))));
729
773
  const trace = march(origin, direction, position.z);
730
774
  If(trace.hitDistance.greaterThanEqual(0), () => {
731
- // The lit colour the ray found and its weight; the filter subtracts what the cache believes about the receiver.
775
+ // What the lit colour the ray found adds over the cache along the same ray, and its weight.
732
776
  const hit = shade(trace.hitCoordinate, trace.hitDistance, direction);
733
- result.assign(vec4(hit.radiance.mul(hit.weight), hit.weight));
777
+ const believed = options.fallback?.(position, direction, normal) ?? vec3(0, 0, 0);
778
+ result.assign(vec4(hit.radiance.sub(believed).mul(hit.weight), hit.weight));
734
779
  });
735
780
  });
736
781
  return result;
@@ -759,17 +804,9 @@ function defineScreenProbes(
759
804
  sum.assign(sum.add(found.mul(weight)));
760
805
  weights.assign(weights.add(weight));
761
806
  });
762
- // The per-pixel gather's convention, once per probe direction instead of once per pixel: the rays that hit return
763
- // `hit - cache` over every ray, so the two tiers never add the same light twice.
764
- const probeUv = tile.add(0.5).div(tiles).min(vec2(1, 1));
765
- const depth = depthNode.sample(probeUv).r;
766
- const rawNormal = normalNode.sample(probeUv).xyz;
767
- const believed = valid(depth, rawNormal).select(
768
- options.fallback?.(viewPosition(probeUv, depth), normal) ?? vec3(0, 0, 0),
769
- vec3(0, 0, 0),
770
- );
807
+ // The trace already holds `hit - cache` along each ray, so the two tiers never add the same light twice.
771
808
  const total = max(weights, float(1e-4));
772
- return vec4(sum.rgb.sub(believed.mul(sum.a)).div(total), sum.a.div(total));
809
+ return vec4(sum.rgb.div(total), sum.a.div(total));
773
810
  })();
774
811
  const filtered = rtt(filterGraph, tilesX * IRRADIANCE_SIDE, tilesY * IRRADIANCE_SIDE, {
775
812
  type: HALF_FLOAT_TYPE,