@threenative/core 0.3.6 → 0.3.8

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 (137) hide show
  1. package/README.md +3 -5
  2. package/capabilities.json +739 -50
  3. package/dist/{assets-CqvE429w.d.ts → assets-YUbXa3-Y.d.ts} +101 -2
  4. package/dist/{canvas-layer-C1-5CviZ.d.ts → canvas-layer-vCtanIeB.d.ts} +1 -1
  5. package/dist/{game-Jz4Fdoeb.d.ts → game-cb99J-YE.d.ts} +100 -31
  6. package/dist/hot.d.ts +4 -4
  7. package/dist/hot.js +23 -5
  8. package/dist/index.d.ts +1742 -29
  9. package/dist/index.js +22443 -12423
  10. package/dist/{model-lod-BDAUYgsS.d.ts → model-lod-CTpZ6imz.d.ts} +1 -1
  11. package/dist/net.js +39 -12
  12. package/dist/playtest.d.ts +4 -4
  13. package/dist/playtest.js +48 -9
  14. package/dist/react-css.js +23 -0
  15. package/dist/react.d.ts +2 -2
  16. package/dist/{renderer-9yEo9hPa.d.ts → renderer-rZm0hVqq.d.ts} +178 -5
  17. package/dist/ui-layer.d.ts +11 -2
  18. package/dist/ui-layer.js +76 -4
  19. package/dist/worker.d.ts +36 -0
  20. package/dist/worker.js +1088 -0
  21. package/dist/world.d.ts +11 -3
  22. package/dist/world.js +1117 -197
  23. package/mcp/animation-server.mjs +265 -0
  24. package/mcp/animation.mjs +22 -0
  25. package/mcp/call.mjs +105 -0
  26. package/mcp/devtools.mjs +5 -0
  27. package/mcp/engine-server.mjs +713 -37
  28. package/mcp/launch.mjs +3 -2
  29. package/mcp/servers.d.mts +2 -0
  30. package/mcp/servers.mjs +33 -8
  31. package/package.json +12 -8
  32. package/patches/three@0.185.1-prd269-upgrade.patch +308 -0
  33. package/patches/three@0.185.1.patch +481 -272
  34. package/src/animation-packet-state.ts +88 -0
  35. package/src/animation-pose-packet.ts +537 -0
  36. package/src/animation.ts +779 -31
  37. package/src/asset-cache.ts +719 -0
  38. package/src/assets.ts +521 -152
  39. package/src/audio.ts +29 -3
  40. package/src/auto-batch.ts +792 -0
  41. package/src/config.ts +2 -0
  42. package/src/frame-budget.ts +268 -2
  43. package/src/game.ts +525 -105
  44. package/src/grounding.ts +7 -6
  45. package/src/hot.ts +19 -5
  46. package/src/index.ts +381 -6
  47. package/src/input.ts +21 -2
  48. package/src/interpolation.ts +19 -1
  49. package/src/launch-diagnostics.ts +7 -2
  50. package/src/look/ao-multibounce.ts +29 -0
  51. package/src/look/ao-reach.ts +39 -0
  52. package/src/look/auto-exposure.ts +264 -0
  53. package/src/look/default-tone-mapping.ts +44 -0
  54. package/src/look/exposure-graph.ts +208 -0
  55. package/src/look/exposure-readback.ts +97 -0
  56. package/src/look/exposure-settings.ts +132 -0
  57. package/src/look/filmic-tone-mapping.ts +852 -0
  58. package/src/look/gi-registry.ts +55 -0
  59. package/src/look/local-exposure.ts +507 -0
  60. package/src/look/look-diagnostics.ts +24 -0
  61. package/src/look/motion-blur.ts +42 -0
  62. package/src/look/quality.ts +309 -0
  63. package/src/look/reflection-trace.ts +344 -0
  64. package/src/look/unreal-bloom.ts +295 -0
  65. package/src/look/vignette.ts +14 -0
  66. package/src/look/world-environment.ts +2033 -0
  67. package/src/loop.ts +25 -1
  68. package/src/merge-parts.ts +25 -10
  69. package/src/model-lod.ts +14 -0
  70. package/src/net-session.ts +58 -14
  71. package/src/ocean/spectral.ts +41 -7
  72. package/src/picking.ts +72 -5
  73. package/src/platform.ts +29 -1
  74. package/src/playtest.ts +54 -8
  75. package/src/profiling/FrameCounters.ts +166 -5
  76. package/src/profiling/FrameStages.ts +289 -0
  77. package/src/profiling/Spans.ts +39 -25
  78. package/src/profiling/debug-telemetry.ts +312 -0
  79. package/src/profiling/scene-warning.ts +42 -6
  80. package/src/projection-apply.ts +11 -3
  81. package/src/projection-content.ts +189 -0
  82. package/src/projection-marker.ts +6 -2
  83. package/src/projection-plan.ts +279 -28
  84. package/src/projection-skinned.ts +620 -5
  85. package/src/projection-stability.ts +16 -0
  86. package/src/projection-uniform.ts +5 -1
  87. package/src/quiet-markers.ts +56 -0
  88. package/src/render/budget-ladder.ts +256 -0
  89. package/src/render/chain.ts +89 -7
  90. package/src/render/exposure-units.ts +59 -0
  91. package/src/render/frame-time-budget.ts +162 -0
  92. package/src/render/gi-budget.ts +231 -0
  93. package/src/render/gi-visualize.ts +49 -0
  94. package/src/render/material-key.ts +1 -0
  95. package/src/render/probe-volume.ts +196 -36
  96. package/src/render/rough-diffuse.ts +177 -0
  97. package/src/render/scene-trace.ts +532 -0
  98. package/src/render/shadow-filter-budget.ts +237 -0
  99. package/src/render/sky-capture.ts +194 -0
  100. package/src/render/soft-shadow.ts +607 -0
  101. package/src/render/surface-cache.ts +418 -0
  102. package/src/render/traced-reflections.ts +408 -0
  103. package/src/render/two-sided-foliage.ts +120 -0
  104. package/src/render/virtual-shadow-pages.ts +112 -12
  105. package/src/render/virtual-shadow.ts +386 -38
  106. package/src/render-camera-cull.ts +536 -31
  107. package/src/render-pass-budget.ts +140 -22
  108. package/src/renderProjection.ts +65 -9
  109. package/src/renderer-config.ts +3 -2
  110. package/src/renderer.ts +289 -14
  111. package/src/resolution-scaler.ts +65 -7
  112. package/src/skeletal-mesh.ts +4 -0
  113. package/src/snow-field.ts +46 -0
  114. package/src/softbody.ts +6 -5
  115. package/src/startup-offscreen-bytes.ts +168 -0
  116. package/src/startup-readiness.ts +137 -2
  117. package/src/ui-bridge.ts +38 -0
  118. package/src/ui-hit-regions.ts +6 -2
  119. package/src/ui-layer.ts +1 -0
  120. package/src/ui-state.ts +32 -3
  121. package/src/version.ts +1 -1
  122. package/src/viewport.ts +8 -5
  123. package/src/warmup.ts +76 -10
  124. package/src/worker-audio.ts +579 -0
  125. package/src/worker.ts +842 -0
  126. package/src/world-cells.ts +4 -1
  127. package/gpl/LICENSE.GPL +0 -117
  128. package/gpl/convert.py +0 -192
  129. package/gpl/fixtures/make_world_fixture.py +0 -184
  130. package/gpl/recipes/_common.py +0 -180
  131. package/gpl/recipes/bake_ao.py +0 -111
  132. package/gpl/recipes/decimate.py +0 -70
  133. package/gpl/recipes/export_world.py +0 -699
  134. package/gpl/recipes/retarget.py +0 -131
  135. package/gpl/recipes/unwrap.py +0 -71
  136. package/mcp/blender-server.mjs +0 -689
  137. package/mcp/blender.mjs +0 -26
@@ -0,0 +1,408 @@
1
+ import type { Mesh, Object3D } from "three";
2
+ import {
3
+ Break,
4
+ Fn,
5
+ If,
6
+ Loop,
7
+ abs,
8
+ clamp,
9
+ cross,
10
+ dot,
11
+ float,
12
+ floor,
13
+ int,
14
+ ivec2,
15
+ max,
16
+ min,
17
+ smoothstep,
18
+ texture,
19
+ textureLoad,
20
+ uniform,
21
+ vec3,
22
+ vec4,
23
+ } from "three/tsl";
24
+ import type { Node } from "three/webgpu";
25
+ import {
26
+ EDGE_TOLERANCE,
27
+ type ITraceScene,
28
+ type ITraceSceneReport,
29
+ MATERIAL_TEXELS,
30
+ NODE_TEXELS,
31
+ TRACE_TEXTURE_WIDTH,
32
+ TRIANGLE_TEXELS,
33
+ packTraceScene,
34
+ } from "./scene-trace.js";
35
+
36
+ export interface ITracedReflectionsOptions {
37
+ /** Which meshes a ray can hit. Default: every mesh under a visible parent chain. */
38
+ readonly include?: (mesh: Mesh) => boolean;
39
+ /** Surfaces rougher than this take no traced reflection. Unreal's `LumenMaxRoughnessToTrace`: 0.4. */
40
+ readonly maxRoughnessToTrace?: number;
41
+ /** The weight falls from 1 to 0 over this much roughness, ending at `maxRoughnessToTrace`: 0.1. */
42
+ readonly roughnessFadeLength?: number;
43
+ /**
44
+ * Surfaces rougher than this take the diffuse GI for specular, not the radiance cache. Unreal's
45
+ * `MaxRoughnessToEvaluateRoughSpecular`: 0.8.
46
+ */
47
+ readonly maxRoughnessToEvaluateRoughSpecular?: number;
48
+ /** The share of diffuse GI rises from 0 to 1 over this much roughness, ending at the limit above: 0.2. */
49
+ readonly roughSpecularFadeLength?: number;
50
+ /**
51
+ * Most nodes one ray visits before it stops walking with the nearest surface found so far, which may be the
52
+ * wrong one. A walk visits each node at most once, so the default, the tree's node count up to 2048, never
53
+ * cuts a ray short in a scene of up to 2048 nodes.
54
+ */
55
+ readonly maxSteps?: number;
56
+ /** False silences the TN_TRACED_REFLECTIONS line, not the report. */
57
+ readonly marker?: boolean;
58
+ }
59
+
60
+ /**
61
+ * Where a surface's specular comes from, as shares that add to 1: the traced ray, the radiance cache read along the
62
+ * reflected direction (a rough lobe), or the diffuse GI (a surface too rough for a lobe).
63
+ */
64
+ export interface IReflectionRoute<T> {
65
+ readonly traced: T;
66
+ readonly roughSpecular: T;
67
+ readonly diffuse: T;
68
+ }
69
+
70
+ /** One ray's answer, as nodes. Every field is meaningful only where `hit` is 1. */
71
+ export interface ITracedHit {
72
+ /** 1 where the ray found a surface, else 0. */
73
+ readonly hit: Node<"float">;
74
+ /** Metres along the (unit) ray, or -1 on a miss. */
75
+ readonly distance: Node<"float">;
76
+ readonly position: Node<"vec3">;
77
+ /** The interpolated vertex normal, flipped to face the ray. */
78
+ readonly normal: Node<"vec3">;
79
+ /** The hit triangle's index in the pack's leaf order. */
80
+ readonly triangle: Node<"float">;
81
+ /** The hit material's colour, roughness, emissive (times intensity) and metalness, from the pack's table. */
82
+ readonly albedo: Node<"vec3">;
83
+ readonly roughness: Node<"float">;
84
+ readonly emissive: Node<"vec3">;
85
+ readonly metalness: Node<"float">;
86
+ /** The index into `TracedReflections.scene.materials`: a game that needs a map or a node looks the material up. */
87
+ readonly material: Node<"float">;
88
+ }
89
+
90
+ export interface ITracedRay {
91
+ readonly origin: Node<"vec3">;
92
+ /** Unit length. */
93
+ readonly direction: Node<"vec3">;
94
+ /** Closest hit allowed, in metres. Default 0.001. */
95
+ readonly near?: Node<"float"> | number;
96
+ /** Farthest hit allowed, in metres. Default 1e4. */
97
+ readonly far?: Node<"float"> | number;
98
+ /**
99
+ * Stop at the first surface found, which need not be the nearest: the answer for a shadow ray, which only asks
100
+ * whether anything is in the way. `distance`, `position` and the material then describe that surface.
101
+ */
102
+ readonly anyHit?: boolean;
103
+ }
104
+
105
+ const DEFAULT_NEAR = 0.001;
106
+ const DEFAULT_FAR = 1e4;
107
+ /** A direction component below this is nudged to it, so the slab test never divides by zero. */
108
+ const TINY = 1e-8;
109
+ /** Determinant below which a ray counts as parallel to a triangle. */
110
+ const PARALLEL = 1e-9;
111
+ /**
112
+ * The most nodes a ray may visit by default. A ray that grazes a long, thin mesh (a capsule's wall) crosses several
113
+ * hundred overlapping boxes, and the walk is not ordered by distance, so a ray cut short at 192 reported the far
114
+ * wall of the capsule: 3% of the pixels of a 13 000-triangle scene. The cap keeps one pathological ray from
115
+ * stalling the GPU.
116
+ */
117
+ const MAX_AUTO_STEPS = 2048;
118
+
119
+ /**
120
+ * Ray queries against the scene's triangles for reflections, in the engine's own TSL: the pack is float
121
+ * textures and the walk is a loop, so the kernel needs no storage buffer and no WGSL of its own.
122
+ *
123
+ * Unreal's Lumen reflections trace what the screen cannot see through a software scene (mesh SDFs, or hardware
124
+ * rays) for surfaces smoother than a roughness cut-off, and fall back to a cached radiance below it. This is
125
+ * the scene half of that: `trace()` answers "what does this ray hit" and the material at the hit. How the hit
126
+ * is lit, what a miss sees and how the result joins the frame stay in the game's `src/render/` code.
127
+ */
128
+ export class TracedReflections {
129
+ /** The packed triangles; `scene.materials[hit.material]` is the three material of a hit. */
130
+ readonly scene: ITraceScene;
131
+ readonly maxRoughnessToTrace: number;
132
+ readonly roughnessFadeLength: number;
133
+ readonly maxRoughnessToEvaluateRoughSpecular: number;
134
+ readonly roughSpecularFadeLength: number;
135
+ readonly maxSteps: number;
136
+ readonly #nodes: ReturnType<typeof texture>;
137
+ readonly #triangles: ReturnType<typeof texture>;
138
+ readonly #materials: ReturnType<typeof texture>;
139
+
140
+ constructor(root: Object3D, options: ITracedReflectionsOptions = {}) {
141
+ const maxRoughnessToTrace = options.maxRoughnessToTrace ?? 0.4;
142
+ const roughnessFadeLength = options.roughnessFadeLength ?? 0.1;
143
+ const maxSteps = options.maxSteps;
144
+ const maxRoughnessToEvaluateRoughSpecular = options.maxRoughnessToEvaluateRoughSpecular ?? 0.8;
145
+ const roughSpecularFadeLength = options.roughSpecularFadeLength ?? 0.2;
146
+ if (!(maxRoughnessToTrace > 0 && maxRoughnessToTrace <= 1))
147
+ throw new RangeError("TN_TRACED_REFLECTIONS: maxRoughnessToTrace must be in (0, 1]");
148
+ if (!(roughnessFadeLength >= 0 && roughnessFadeLength <= maxRoughnessToTrace))
149
+ throw new RangeError(
150
+ "TN_TRACED_REFLECTIONS: roughnessFadeLength must be in [0, maxRoughnessToTrace]",
151
+ );
152
+ if (
153
+ !(
154
+ maxRoughnessToEvaluateRoughSpecular >= maxRoughnessToTrace &&
155
+ maxRoughnessToEvaluateRoughSpecular <= 1
156
+ )
157
+ )
158
+ throw new RangeError(
159
+ "TN_TRACED_REFLECTIONS: maxRoughnessToEvaluateRoughSpecular must be in [maxRoughnessToTrace, 1]",
160
+ );
161
+ if (
162
+ !(
163
+ roughSpecularFadeLength >= 0 &&
164
+ roughSpecularFadeLength <= maxRoughnessToEvaluateRoughSpecular
165
+ )
166
+ )
167
+ throw new RangeError(
168
+ "TN_TRACED_REFLECTIONS: roughSpecularFadeLength must be in [0, maxRoughnessToEvaluateRoughSpecular]",
169
+ );
170
+ if (maxSteps !== undefined && !(Number.isInteger(maxSteps) && maxSteps > 0))
171
+ throw new RangeError("TN_TRACED_REFLECTIONS: maxSteps must be a positive whole number");
172
+ this.maxRoughnessToTrace = maxRoughnessToTrace;
173
+ this.roughnessFadeLength = roughnessFadeLength;
174
+ this.maxRoughnessToEvaluateRoughSpecular = maxRoughnessToEvaluateRoughSpecular;
175
+ this.roughSpecularFadeLength = roughSpecularFadeLength;
176
+ this.scene = packTraceScene(
177
+ root,
178
+ options.include === undefined ? {} : { include: options.include },
179
+ );
180
+ this.maxSteps = maxSteps ?? Math.max(1, Math.min(this.scene.report.nodes, MAX_AUTO_STEPS));
181
+ this.#nodes = texture(this.scene.nodes);
182
+ this.#triangles = texture(this.scene.triangles);
183
+ this.#materials = texture(this.scene.materialTable);
184
+ if (options.marker !== false)
185
+ console.info(`TN_TRACED_REFLECTIONS ${JSON.stringify(this.report)}`);
186
+ }
187
+
188
+ get report(): ITraceSceneReport & { readonly bytes: number } {
189
+ const { nodes, triangles, materialTable, report } = this.scene;
190
+ const bytes = [nodes, triangles, materialTable].reduce(
191
+ (sum, t) => sum + t.image.width * t.image.height * 16,
192
+ 0,
193
+ );
194
+ return { ...report, bytes };
195
+ }
196
+
197
+ /**
198
+ * 1 for a surface at least as smooth as the cut-off minus the fade, falling to 0 at `maxRoughnessToTrace`.
199
+ * Multiply a traced reflection by it so a rough surface never shows a trace's noise.
200
+ */
201
+ weight(roughness: Node<"float">): Node<"float"> {
202
+ return float(1).sub(
203
+ smoothstep(
204
+ this.maxRoughnessToTrace - this.roughnessFadeLength,
205
+ this.maxRoughnessToTrace,
206
+ roughness,
207
+ ),
208
+ );
209
+ }
210
+
211
+ /** `weight` for one roughness on the CPU: a surface rougher than `maxRoughnessToTrace` casts no ray. */
212
+ weightAt(roughness: number): number {
213
+ const edge = this.maxRoughnessToTrace - this.roughnessFadeLength;
214
+ const t = Math.min(1, Math.max(0, (roughness - edge) / (this.roughnessFadeLength || 1)));
215
+ return roughness >= this.maxRoughnessToTrace ? 0 : 1 - t * t * (3 - 2 * t);
216
+ }
217
+
218
+ /**
219
+ * Where a surface's specular comes from (Unreal: `LumenCombineReflectionsAlpha` picks the ray, and
220
+ * `RoughReflectionsDiffuseLerp` in `LumenReflectionsCombine.ush` fades the rest from the gather's rough specular to
221
+ * the diffuse GI). The ray's share is `weight`; of the rest, the diffuse share rises from 0 at the limit minus the
222
+ * fade to 1 at the limit, and the radiance cache answers for what is left.
223
+ */
224
+ route(roughness: Node<"float">): IReflectionRoute<Node<"float">> {
225
+ const traced = this.weight(roughness);
226
+ const rest = float(1).sub(traced);
227
+ const toDiffuse = clamp(
228
+ roughness
229
+ .sub(this.maxRoughnessToEvaluateRoughSpecular - this.roughSpecularFadeLength)
230
+ .div(Math.max(this.roughSpecularFadeLength, 1e-6)),
231
+ 0,
232
+ 1,
233
+ );
234
+ return {
235
+ traced,
236
+ roughSpecular: rest.mul(float(1).sub(toDiffuse)),
237
+ diffuse: rest.mul(toDiffuse),
238
+ };
239
+ }
240
+
241
+ /** `route` for one roughness on the CPU. */
242
+ routeAt(roughness: number): IReflectionRoute<number> {
243
+ const traced = this.weightAt(roughness);
244
+ const edge = this.maxRoughnessToEvaluateRoughSpecular - this.roughSpecularFadeLength;
245
+ const toDiffuse = Math.min(
246
+ 1,
247
+ Math.max(0, (roughness - edge) / Math.max(this.roughSpecularFadeLength, 1e-6)),
248
+ );
249
+ return {
250
+ traced,
251
+ roughSpecular: (1 - traced) * (1 - toDiffuse),
252
+ diffuse: (1 - traced) * toDiffuse,
253
+ };
254
+ }
255
+
256
+ /** The texel at `index` of a row-major pack texture, `TRACE_TEXTURE_WIDTH` wide. */
257
+ #fetch(source: ReturnType<typeof texture>, index: Node<"float">): Node<"vec4"> {
258
+ const row = floor(index.div(TRACE_TEXTURE_WIDTH));
259
+ const column = index.sub(row.mul(TRACE_TEXTURE_WIDTH));
260
+ return textureLoad(source, ivec2(int(column), int(row)));
261
+ }
262
+
263
+ /**
264
+ * The nearest surface along a ray, with its normal and material. The walk is the depth-first, skip-pointer one
265
+ * `traceScene` runs on the CPU: a node's box is tested, a miss jumps to the node after the subtree, a hit on an
266
+ * inner node steps to its left child, a leaf tests its triangles in a loop.
267
+ */
268
+ trace(ray: ITracedRay): ITracedHit {
269
+ const near =
270
+ typeof ray.near === "number" || ray.near === undefined
271
+ ? float(ray.near ?? DEFAULT_NEAR)
272
+ : ray.near;
273
+ const far =
274
+ typeof ray.far === "number" || ray.far === undefined
275
+ ? float(ray.far ?? DEFAULT_FAR)
276
+ : ray.far;
277
+ const fetchNode = (index: Node<"float">) => this.#fetch(this.#nodes, index);
278
+ const fetchTriangle = (index: Node<"float">) => this.#fetch(this.#triangles, index);
279
+ const fetchMaterial = (index: Node<"float">) => this.#fetch(this.#materials, index);
280
+ // A runtime trip count, so a driver's compiler cannot unroll the walk into a program too large to compile.
281
+ const steps = uniform(this.maxSteps);
282
+ const walk = Fn(
283
+ ([origin, direction, nearT, farT]: [
284
+ Node<"vec3">,
285
+ Node<"vec3">,
286
+ Node<"float">,
287
+ Node<"float">,
288
+ ]) => {
289
+ // Zero is a valid direction component: nudge it so 1 / d stays finite, as the CPU walk does.
290
+ const safe = vec3(
291
+ direction.x.abs().lessThan(TINY).select(float(TINY), direction.x),
292
+ direction.y.abs().lessThan(TINY).select(float(TINY), direction.y),
293
+ direction.z.abs().lessThan(TINY).select(float(TINY), direction.z),
294
+ );
295
+ const inverse = vec3(1).div(safe);
296
+ const best = farT.toVar();
297
+ const found = float(-1).toVar();
298
+ const foundU = float(0).toVar();
299
+ const foundV = float(0).toVar();
300
+ const node = float(0).toVar();
301
+ Loop({ start: int(0), end: int(steps), type: "int", condition: "<" }, () => {
302
+ If(node.lessThan(0), () => {
303
+ Break();
304
+ });
305
+ const low = fetchNode(node.mul(NODE_TEXELS));
306
+ const high = fetchNode(node.mul(NODE_TEXELS).add(1));
307
+ const t0 = low.xyz.sub(origin).mul(inverse);
308
+ const t1 = high.xyz.sub(origin).mul(inverse);
309
+ const enter = max(max(min(t0.x, t1.x), min(t0.y, t1.y)), max(min(t0.z, t1.z), nearT));
310
+ const leave = min(min(max(t0.x, t1.x), max(t0.y, t1.y)), min(max(t0.z, t1.z), best));
311
+ If(leave.lessThan(enter), () => {
312
+ node.assign(low.w);
313
+ }).Else(() => {
314
+ If(high.w.lessThan(0), () => {
315
+ node.addAssign(1);
316
+ }).Else(() => {
317
+ const first = floor(high.w.div(16));
318
+ const count = high.w.sub(first.mul(16));
319
+ Loop({ start: int(0), end: int(count), type: "int", condition: "<" }, ({ i }) => {
320
+ const index = first.add(float(i));
321
+ const base = index.mul(TRIANGLE_TEXELS);
322
+ const a = fetchTriangle(base);
323
+ const b = fetchTriangle(base.add(1));
324
+ const c = fetchTriangle(base.add(2));
325
+ const edge1 = b.xyz.sub(a.xyz);
326
+ const edge2 = c.xyz.sub(a.xyz);
327
+ // Moller-Trumbore. A positive determinant is a hit on the front face.
328
+ const p = cross(safe, edge2);
329
+ const det = dot(edge1, p);
330
+ const side = b.w;
331
+ const facing = side
332
+ .greaterThan(1.5)
333
+ .select(
334
+ abs(det).greaterThan(PARALLEL),
335
+ side.lessThan(0.5).select(det.greaterThan(PARALLEL), det.lessThan(-PARALLEL)),
336
+ );
337
+ If(facing, () => {
338
+ const inverseDet = float(1).div(det);
339
+ const s = origin.sub(a.xyz);
340
+ const u = dot(s, p).mul(inverseDet);
341
+ const q = cross(s, edge1);
342
+ const v = dot(safe, q).mul(inverseDet);
343
+ const t = dot(edge2, q).mul(inverseDet);
344
+ If(
345
+ u
346
+ .greaterThanEqual(-EDGE_TOLERANCE)
347
+ .and(u.lessThanEqual(1 + EDGE_TOLERANCE))
348
+ .and(v.greaterThanEqual(-EDGE_TOLERANCE))
349
+ .and(u.add(v).lessThanEqual(1 + EDGE_TOLERANCE))
350
+ .and(t.greaterThan(nearT))
351
+ .and(t.lessThan(best)),
352
+ () => {
353
+ best.assign(t);
354
+ found.assign(index);
355
+ foundU.assign(u);
356
+ foundV.assign(v);
357
+ },
358
+ );
359
+ });
360
+ });
361
+ // A shadow ray ends with its first hit: jump past the end of the tree.
362
+ node.assign(
363
+ ray.anyHit === true ? found.greaterThanEqual(0).select(float(-1), low.w) : low.w,
364
+ );
365
+ });
366
+ });
367
+ });
368
+ return vec4(best, foundU, foundV, found);
369
+ },
370
+ );
371
+ const result = walk(ray.origin, ray.direction, near, far);
372
+ const triangle = result.w;
373
+ const hit = triangle.greaterThanEqual(0).select(float(1), float(0));
374
+ // A miss reads triangle 0 (a valid texel) and is discarded by `hit`.
375
+ const base = max(triangle, float(0)).mul(TRIANGLE_TEXELS);
376
+ const corner = fetchTriangle(base);
377
+ const weights = vec3(float(1).sub(result.y).sub(result.z), result.y, result.z);
378
+ const normalA = fetchTriangle(base.add(3)).xyz;
379
+ const normalB = fetchTriangle(base.add(4)).xyz;
380
+ const normalC = fetchTriangle(base.add(5)).xyz;
381
+ const interpolated = normalA
382
+ .mul(weights.x)
383
+ .add(normalB.mul(weights.y))
384
+ .add(normalC.mul(weights.z));
385
+ const lengthSquared = max(dot(interpolated, interpolated), float(1e-12));
386
+ const unit = interpolated.div(lengthSquared.sqrt());
387
+ const normal = dot(unit, ray.direction).greaterThan(0).select(unit.negate(), unit);
388
+ const material = corner.w;
389
+ const albedo = fetchMaterial(material.mul(MATERIAL_TEXELS));
390
+ const emission = fetchMaterial(material.mul(MATERIAL_TEXELS).add(1));
391
+ return {
392
+ hit,
393
+ distance: hit.greaterThan(0).select(result.x, float(-1)),
394
+ position: ray.origin.add(ray.direction.mul(result.x)),
395
+ normal,
396
+ triangle,
397
+ albedo: albedo.xyz,
398
+ roughness: albedo.w,
399
+ emissive: emission.xyz,
400
+ metalness: emission.w,
401
+ material,
402
+ };
403
+ }
404
+
405
+ dispose(): void {
406
+ this.scene.dispose();
407
+ }
408
+ }
@@ -0,0 +1,120 @@
1
+ import type { Color, Material } from "three";
2
+ import {
3
+ float,
4
+ materialEmissive,
5
+ normalView,
6
+ positionViewDirection,
7
+ uniform,
8
+ vec3,
9
+ } from "three/tsl";
10
+ import type { Node } from "three/webgpu";
11
+
12
+ declare module "three" {
13
+ // quality-allow: declaration merging needs three's own interface name, and the naming rule would demand an I prefix
14
+ // biome-ignore lint/style/useNamingConvention: a module augmentation keeps three's own class name.
15
+ interface Material {
16
+ /**
17
+ * The colour a Two Sided Foliage leaf returns from light that reaches its other face (PRD-643). Unreal's
18
+ * `SubsurfaceColor`. Read only where `twoSidedFoliage` is true: a material without it gets no back term
19
+ * and lets no sun through.
20
+ */
21
+ subsurfaceColor?: Color;
22
+ /**
23
+ * Marks a Two Sided Foliage leaf (PRD-651). Declared here too, with the type that soft-shadow.ts gives it, so that a
24
+ * declaration build whose entry reaches this file through `renderer.ts` and not through `soft-shadow.ts` still sees it.
25
+ */
26
+ twoSidedFoliage?: boolean;
27
+ }
28
+ }
29
+
30
+ /**
31
+ * The light a Two Sided Foliage leaf takes through its back face: `subsurfaceColor` times the irradiance
32
+ * (E / pi, the unit of `irradianceNode`) that arrives along the opposite of the normal the viewer sees.
33
+ * Unreal adds the same product to the diffuse indirect light at Epic and Cinematic gather quality
34
+ * (UE 5.8.3: `Engine/Shaders/Private/DiffuseIndirectComposite.usf`, the `SHADINGMODELID_TWOSIDED_FOLIAGE` branch).
35
+ * The game reads its own cache along `normal.negate()` and passes the result; this adds it to the material's
36
+ * `emissiveNode`, which both engines evaluate, so the leaf keeps its colours and the engine owns none of them.
37
+ * @situation add bounce light to the far face of a two sided foliage leaf
38
+ * @constraint the material needs `twoSidedFoliage = true` and a `subsurfaceColor`, or nothing is added and false is returned; backIrradiance is a vec3 node in the unit of `irradianceNode`; call once per material
39
+ * @example addFoliageBackLight(leaf, cache.irradianceAt(positionWorld, normalWorld.negate()));
40
+ */
41
+ export function addFoliageBackLight(material: Material, backIrradiance: Node<"vec3">): boolean {
42
+ const colour = material.subsurfaceColor;
43
+ if (material.twoSidedFoliage !== true || colour === undefined) return false;
44
+ const back = vec3(colour.r, colour.g, colour.b).mul(backIrradiance);
45
+ const target = material as { emissiveNode?: Node<"vec3"> | null };
46
+ target.emissiveNode = (target.emissiveNode ?? materialEmissive).add(back);
47
+ return true;
48
+ }
49
+
50
+ /**
51
+ * The light a Two Sided Foliage leaf lets through from behind, per direct light (PRD-643): subsurfaceColor times a
52
+ * wrapped -N.L (wrap 0.5, over (1 + wrap)^2) times a GGX lobe of alpha 0.6 around the light seen through the leaf,
53
+ * times the light's colour with its shadow. No N.L and no 1/pi: Unreal adds it to the diffuse light as it is
54
+ * (UE 5.8.3: `Engine/Shaders/Private/Substrate/SubstrateEvaluation.ush:881-899`, the `SSS_TYPE_TWO_SIDED_WRAP`
55
+ * branch). The owned engine evaluates the same term in its light loop (`runtime-native` `standard.cpp`).
56
+ */
57
+ export function foliageTransmission(
58
+ lightDirection: Node<"vec3">,
59
+ lightColor: Node<"vec3">,
60
+ subsurface: Node<"vec3">,
61
+ ): Node<"vec3"> {
62
+ const wrap = normalView.dot(lightDirection).negate().add(0.5).div(2.25).clamp();
63
+ // D_GGX with alpha^2 = 0.36 at saturate(-V.L), written out: the owned engine binds no D_GGX node, and this
64
+ // module is bundled for both engines.
65
+ const cosine = positionViewDirection.dot(lightDirection).negate().clamp();
66
+ const denominator = float(1).sub(cosine.mul(cosine).mul(0.64));
67
+ const scatter = float(0.36 / Math.PI).div(denominator.mul(denominator));
68
+ return lightColor.mul(wrap.mul(scatter)).mul(subsurface);
69
+ }
70
+
71
+ interface ILightingModelLike {
72
+ direct(
73
+ input: {
74
+ lightDirection: Node<"vec3">;
75
+ lightColor: Node<"vec3">;
76
+ reflectedLight: { directDiffuse: Node<"vec3"> };
77
+ },
78
+ builder: unknown,
79
+ ): void;
80
+ }
81
+ type LitPrototype = {
82
+ setupLightingModel?: (this: Material, builder: unknown) => ILightingModelLike;
83
+ };
84
+ const PATCHED = Symbol.for("threenative.foliageTransmission");
85
+
86
+ /**
87
+ * Gives three's standard and physical node materials the Two Sided Foliage sun transmission, so a material marked
88
+ * `twoSidedFoliage` with a `subsurfaceColor` lets the sun through on the `engine: "threejs"` path as it does on the
89
+ * owned engine. Idempotent; a class without `setupLightingModel` is left alone. Returns how many classes it patched.
90
+ */
91
+ export function installFoliageTransmission(classes: Readonly<Record<string, unknown>>): number {
92
+ let patched = 0;
93
+ for (const name of ["MeshStandardNodeMaterial", "MeshPhysicalNodeMaterial"]) {
94
+ const prototype = (
95
+ classes[name] as { prototype?: LitPrototype & { [PATCHED]?: true } } | undefined
96
+ )?.prototype;
97
+ const setup = prototype?.setupLightingModel;
98
+ // Own property only: the physical class inherits the standard one's mark but keeps its own lighting model.
99
+ if (prototype === undefined || typeof setup !== "function" || Object.hasOwn(prototype, PATCHED))
100
+ continue;
101
+ prototype.setupLightingModel = function (this: Material, builder: unknown) {
102
+ const model = setup.call(this, builder);
103
+ if (this.twoSidedFoliage !== true || this.subsurfaceColor === undefined) return model;
104
+ const direct = model.direct.bind(model);
105
+ // The material's own Color object: an edit of its r, g or b reaches the uniform.
106
+ // quality-allow: a colour uniform is read as a vec3 colour node, and three 0.185 types the two as unrelated
107
+ const subsurface = uniform(this.subsurfaceColor) as unknown as Node<"vec3">;
108
+ model.direct = (input, inner) => {
109
+ direct(input, inner);
110
+ input.reflectedLight.directDiffuse.addAssign(
111
+ foliageTransmission(input.lightDirection, input.lightColor, subsurface),
112
+ );
113
+ };
114
+ return model;
115
+ };
116
+ prototype[PATCHED] = true;
117
+ patched++;
118
+ }
119
+ return patched;
120
+ }