@threenative/core 0.3.10 → 0.3.12

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 (158) hide show
  1. package/capabilities.json +1096 -26
  2. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  3. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-CWuFRT7G.d.ts} +1 -1
  4. package/dist/chunk-2Z44XSI2.js +35 -0
  5. package/dist/chunk-5O73CDMR.js +1849 -0
  6. package/dist/chunk-6KLNISRJ.js +153 -0
  7. package/dist/chunk-7UUT3TY5.js +133 -0
  8. package/dist/chunk-CFGTPFUH.js +231 -0
  9. package/dist/chunk-DBELTTTM.js +615 -0
  10. package/dist/chunk-GMHATRPW.js +7701 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-KIRUKTBQ.js +187 -0
  13. package/dist/chunk-N5LRP4BR.js +220 -0
  14. package/dist/chunk-OKXUCASC.js +2238 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-VAZM36TV.js +497 -0
  17. package/dist/{game-DzMcitDO.d.ts → game-D7pAzZUY.d.ts} +15 -3
  18. package/dist/hot.d.ts +3 -3
  19. package/dist/hot.js +2 -46
  20. package/dist/index.d.ts +329 -302
  21. package/dist/index.js +10565 -22533
  22. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-B6BMqS1r.d.ts} +33 -3
  23. package/dist/playtest.d.ts +3 -3
  24. package/dist/playtest.js +24 -75
  25. package/dist/react-css.js +1 -215
  26. package/dist/react.d.ts +2 -2
  27. package/dist/{renderer-rZm0hVqq.d.ts → renderer-DvFVoAgj.d.ts} +13 -4
  28. package/dist/spells/index.d.ts +643 -0
  29. package/dist/spells/index.js +1558 -0
  30. package/dist/spells/ultra/index.d.ts +1600 -0
  31. package/dist/spells/ultra/index.js +6804 -0
  32. package/dist/terrain-jobs-worker.js +1 -123
  33. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  34. package/dist/ui-layer.js +5 -384
  35. package/dist/worker.js +4 -41
  36. package/dist/world.d.ts +725 -259
  37. package/dist/world.js +16714 -18284
  38. package/mcp/animation-server.mjs +1 -1
  39. package/mcp/animation.mjs +2 -3
  40. package/mcp/engine-server.mjs +142 -47
  41. package/mcp/servers.mjs +9 -2
  42. package/mcp/terrain.mjs +8 -0
  43. package/package.json +14 -6
  44. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  45. package/patches/three@0.187.0.patch +2004 -407
  46. package/src/assets.ts +9 -2
  47. package/src/card-lod.ts +152 -0
  48. package/src/compressed-texture-preparation.ts +1008 -0
  49. package/src/frame-budget.ts +31 -20
  50. package/src/game-dev-tools.ts +93 -0
  51. package/src/game-frame-loop.ts +995 -0
  52. package/src/game-renderer-metrics.ts +77 -0
  53. package/src/game-startup.ts +1001 -0
  54. package/src/game-validate.ts +70 -0
  55. package/src/game.ts +253 -1935
  56. package/src/index.ts +27 -2
  57. package/src/launch-diagnostics.ts +22 -12
  58. package/src/look/ao-admission.ts +24 -0
  59. package/src/look/filmic-tone-mapping.ts +15 -13
  60. package/src/look/look-diagnostics.ts +3 -3
  61. package/src/look/quality.ts +10 -5
  62. package/src/look/world-environment.ts +76 -9
  63. package/src/loop.ts +29 -0
  64. package/src/model-lod.ts +42 -3
  65. package/src/particle-kinds.ts +515 -0
  66. package/src/picking.ts +17 -3
  67. package/src/playtest.ts +27 -1
  68. package/src/projection-apply.ts +4 -1
  69. package/src/projection-plan.ts +9 -6
  70. package/src/render/mesh-pool.ts +1 -1
  71. package/src/render/resolution-subrect.ts +2 -0
  72. package/src/render/rough-diffuse.ts +46 -12
  73. package/src/render/soft-shadow.ts +27 -12
  74. package/src/render/virtual-shadow-adaptive.ts +55 -0
  75. package/src/render/virtual-shadow-casters.ts +175 -0
  76. package/src/render/virtual-shadow-layers.ts +76 -0
  77. package/src/render/virtual-shadow-level.ts +224 -0
  78. package/src/render/virtual-shadow-markers.ts +193 -0
  79. package/src/render/virtual-shadow-options.ts +370 -0
  80. package/src/render/virtual-shadow-pages.ts +5 -0
  81. package/src/render/virtual-shadow.ts +213 -992
  82. package/src/render/world-impostor-surface.ts +293 -34
  83. package/src/render-camera-cull.ts +32 -1
  84. package/src/render-pass-budget.ts +34 -7
  85. package/src/renderProjection.ts +22 -0
  86. package/src/renderer.ts +92 -37
  87. package/src/snow-field.ts +1 -1
  88. package/src/spells/cast-pool.ts +361 -0
  89. package/src/spells/index.ts +177 -0
  90. package/src/spells/mechanisms.ts +295 -0
  91. package/src/spells/reaction-field.ts +415 -0
  92. package/src/spells/spell-lights.ts +139 -0
  93. package/src/spells/spell-world.ts +187 -0
  94. package/src/spells/spell.ts +397 -0
  95. package/src/spells/spells.ts +283 -0
  96. package/src/spells/ultra/engine/camera.ts +184 -0
  97. package/src/spells/ultra/engine/quality.ts +96 -0
  98. package/src/spells/ultra/index.ts +52 -0
  99. package/src/spells/ultra/main.ts +305 -0
  100. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  101. package/src/spells/ultra/spells/cast.ts +233 -0
  102. package/src/spells/ultra/spells/fire.ts +1267 -0
  103. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  104. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  105. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  106. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  107. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  108. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  109. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  110. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  111. package/src/spells/ultra/vfx/common.ts +1195 -0
  112. package/src/spells/ultra/vfx/noise.ts +441 -0
  113. package/src/startup-readiness.ts +128 -34
  114. package/src/version.ts +1 -1
  115. package/src/warmup.ts +56 -8
  116. package/src/water-surface.ts +9 -3
  117. package/src/world-bundle-safety.ts +401 -0
  118. package/src/world-cell-batches.ts +1216 -0
  119. package/src/world-cell-chunks.ts +1132 -0
  120. package/src/world-cell-data.ts +995 -0
  121. package/src/world-cell-impostors.ts +1449 -0
  122. package/src/world-cell-lod-bias.ts +151 -0
  123. package/src/world-cell-models.ts +1074 -0
  124. package/src/world-cell-options.ts +189 -0
  125. package/src/world-cell-placements.ts +694 -0
  126. package/src/world-cell-prewarm.ts +557 -0
  127. package/src/world-cell-readiness.ts +357 -0
  128. package/src/world-cell-render-bundles.ts +459 -0
  129. package/src/world-cell-render-gpu-dress.ts +714 -0
  130. package/src/world-cell-render-main-cull.ts +484 -0
  131. package/src/world-cell-render-shadow-claims.ts +198 -0
  132. package/src/world-cell-render-util.ts +246 -0
  133. package/src/world-cell-render.ts +1493 -0
  134. package/src/world-cell-residency.ts +745 -0
  135. package/src/world-cells.ts +1318 -10418
  136. package/src/world-chunk-shadow.ts +308 -0
  137. package/src/world-collar.ts +315 -0
  138. package/src/world-gpu-flags.ts +163 -0
  139. package/src/world-gpu-readback.ts +881 -0
  140. package/src/world-gpu-reference.ts +510 -0
  141. package/src/world-gpu-scene.ts +214 -2264
  142. package/src/world-gpu-shadow.ts +190 -0
  143. package/src/world-gpu-types.ts +381 -0
  144. package/src/world-gpu-validation.ts +518 -0
  145. package/src/world-heightfield.ts +802 -0
  146. package/src/world-load-limiter.ts +106 -0
  147. package/src/world-noise.ts +241 -0
  148. package/src/world-package.ts +42 -0
  149. package/src/world-region.ts +1 -1
  150. package/src/world-terrain-splat.ts +365 -149
  151. package/src/world-tile-budget.ts +256 -0
  152. package/src/world-tile-geometry.ts +469 -0
  153. package/src/world-tile-lod.ts +408 -0
  154. package/src/world-tile-observation.ts +566 -0
  155. package/src/world-tile-stitch.ts +166 -0
  156. package/src/world-tiles.ts +170 -1745
  157. package/src/world-water-bodies.ts +359 -0
  158. package/src/world.ts +35 -741
@@ -7,7 +7,6 @@ import {
7
7
  type InstancedBufferAttribute,
8
8
  InstancedInterleavedBuffer,
9
9
  type Material,
10
- type Object3D,
11
10
  Sphere,
12
11
  Vector3,
13
12
  } from "three";
@@ -29,6 +28,7 @@ import {
29
28
  element,
30
29
  float,
31
30
  floor,
31
+ fract,
32
32
  instanceIndex,
33
33
  instancedBufferAttribute,
34
34
  instancedDynamicBufferAttribute,
@@ -40,26 +40,43 @@ import {
40
40
  modelWorldMatrix,
41
41
  normalize,
42
42
  positionGeometry,
43
+ screenCoordinate,
43
44
  select,
45
+ sin,
44
46
  storage,
45
47
  texture,
46
48
  transformNormal,
47
49
  uniform,
50
+ varying,
48
51
  varyingProperty,
49
52
  vec2,
50
53
  vec3,
51
54
  vec4,
52
55
  } from "three/tsl";
56
+ import * as threeTsl from "three/tsl";
53
57
  import {
54
58
  EventNode,
55
59
  MeshBasicNodeMaterial,
56
60
  MeshPhysicalNodeMaterial,
57
61
  MeshStandardNodeMaterial,
58
62
  type Node,
63
+ type NodeBuilder,
59
64
  type NodeMaterial,
60
65
  } from "three/webgpu";
61
66
  import { IMPOSTOR_VIEW_GRID, type WorldImpostorAtlas } from "./world-impostor.js";
62
67
 
68
+ type InstanceMatrixFn = () => Node<"mat4">;
69
+ /**
70
+ * The owned engine's drawn-instance matrix, identity for a plain mesh. The engine compiles a node
71
+ * material once per variant, so a `Fn` cannot read `builder.object`; the web engine hands the node over
72
+ * in `__tnTsl`, the V8 player as a `three/tsl` name. Upstream three has neither and keeps the builder
73
+ * path below. Read through `Reflect` so a bundler does not resolve a name upstream does not export.
74
+ */
75
+ const engineInstanceMatrix = (Reflect.get(threeTsl, "instanceMatrix") ??
76
+ (Reflect.get(threeTsl, "__tnTsl") as Record<string, unknown> | undefined)?.instanceMatrix) as
77
+ | InstanceMatrixFn
78
+ | undefined;
79
+
63
80
  /** The surface reconstructs alpha-covered ray/depth crossings in the three neighboring views. */
64
81
  export const IMPOSTOR_SURFACE_PARALLAX = true;
65
82
 
@@ -262,6 +279,8 @@ export function instanceSyncEvent(
262
279
  /**
263
280
  * The per-instance matrix as a `mat4` node, choosing the path by the attribute three installed.
264
281
  *
282
+ * Standard instancing already built the column nodes: reuse those exact nodes and its upload
283
+ * synchronization. Only a custom vertex path without them needs the fallback below.
265
284
  * A `StorageInstancedBufferAttribute` is read through `storage(...).element(instanceIndex)`, which
266
285
  * is the same seam three's own `Instance.js` uses and which includes the indirect draw's
267
286
  * `firstInstance`. A plain CPU `InstancedBufferAttribute` cannot require storage support, so it is
@@ -270,7 +289,41 @@ export function instanceSyncEvent(
270
289
  * derived buffer exactly as `Instance.js` does — a derived buffer nobody re-uploads draws a stale
271
290
  * pose. See {@link instanceSyncEvent}.
272
291
  */
273
- function instanceMatrixNode(attribute: InstancedBufferAttribute): Node<"mat4"> {
292
+ function instanceMatrixNode(
293
+ attribute: InstancedBufferAttribute,
294
+ builder: NodeBuilder,
295
+ ): Node<"mat4"> {
296
+ // Reuse Three's actual column nodes: a second interleaved buffer consumes four more locations.
297
+ // Three 0.187 (048e6bea2) builds each column as a `BufferAttributeNode` over an
298
+ // `InterleavedBufferAttribute` view of the matrix; older Three nodes held an
299
+ // `InstancedInterleavedBuffer` over the same array. Both carry that matrix, so both are reused.
300
+ // On a real renderer r187 binds the matrix per object instead (`referenceAttribute`), and only
301
+ // those columns follow the drawn object: a build is shared by every mesh of the program, and
302
+ // `SharedBatch#resize` swaps a mesh's buffer, so a column over the build-time array draws another
303
+ // mesh's or a 64-record buffer past its end, which invalidates the whole recorded bundle.
304
+ const columns = [...(Reflect.get(builder, "nodes") as Iterable<Node>)].filter((node) => {
305
+ if (Reflect.get(node, "isReferenceBufferAttributeNode") === true)
306
+ return Reflect.get(node, "referenceNode")?.property === "instanceMatrix";
307
+ const value = Reflect.get(node, "value");
308
+ if (value?.isInterleavedBufferAttribute === true) return value.data === attribute;
309
+ return (
310
+ value?.isInstancedInterleavedBuffer === true &&
311
+ value.array === attribute.array &&
312
+ Reflect.get(node, "bufferStride") === 16
313
+ );
314
+ });
315
+ if (columns.length === 4) {
316
+ const offsetOf = (node: Node): number => {
317
+ const value = Reflect.get(node, "value");
318
+ return (
319
+ (value?.isInterleavedBufferAttribute === true
320
+ ? value.offset
321
+ : Reflect.get(node, "bufferOffset")) ?? 0
322
+ );
323
+ };
324
+ columns.sort((a, b) => offsetOf(a) - offsetOf(b));
325
+ return mat4(...(columns as [Node<"vec4">, Node<"vec4">, Node<"vec4">, Node<"vec4">]));
326
+ }
274
327
  const count = Math.max(attribute.count, 1);
275
328
  if (
276
329
  (attribute as { isStorageInstancedBufferAttribute?: boolean })
@@ -286,7 +339,7 @@ function instanceMatrixNode(attribute: InstancedBufferAttribute): Node<"mat4"> {
286
339
  attribute.usage === DynamicDrawUsage
287
340
  ? instancedDynamicBufferAttribute
288
341
  : instancedBufferAttribute;
289
- const columns = [
342
+ const ownColumns = [
290
343
  bufferFn(interleaved, "vec4", 16, 0),
291
344
  bufferFn(interleaved, "vec4", 16, 4),
292
345
  bufferFn(interleaved, "vec4", 16, 8),
@@ -294,17 +347,16 @@ function instanceMatrixNode(attribute: InstancedBufferAttribute): Node<"mat4"> {
294
347
  ];
295
348
  instanceSyncEvent(attribute, interleaved).toStack();
296
349
  return mat4(
297
- columns[0] as Node<"vec4">,
298
- columns[1] as Node<"vec4">,
299
- columns[2] as Node<"vec4">,
300
- columns[3] as Node<"vec4">,
350
+ ownColumns[0] as Node<"vec4">,
351
+ ownColumns[1] as Node<"vec4">,
352
+ ownColumns[2] as Node<"vec4">,
353
+ ownColumns[3] as Node<"vec4">,
301
354
  ) as Node<"mat4">;
302
355
  }
303
356
 
304
357
  /** `cameraViewMatrix * modelWorldMatrix * instanceMatrix`: asset-space to view-space per instance. */
305
- function instanceViewMatrixNode(object: Object3D): Node<"mat4"> {
306
- const attribute = (object as { instanceMatrix?: InstancedBufferAttribute }).instanceMatrix;
307
- const instance = attribute === undefined ? identityMat4() : instanceMatrixNode(attribute);
358
+ function instanceViewMatrixNode(builder: NodeBuilder): Node<"mat4"> {
359
+ const instance = userInstanceMatrix(builder);
308
360
  return cameraViewMatrix.mul(modelWorldMatrix).mul(instance) as Node<"mat4">;
309
361
  }
310
362
 
@@ -318,9 +370,14 @@ function identityMat4(): Node<"mat4"> {
318
370
  ) as Node<"mat4">;
319
371
  }
320
372
 
321
- /** A node twin of a source material: its class and every value it authored, by reference. */
373
+ /** A node twin retaining the source material's authored values and shader nodes. */
322
374
  function cloneLitMaterial(source: Material): NodeMaterial {
323
- if (Reflect.get(source, "isNodeMaterial") === true) return (source as NodeMaterial).clone();
375
+ if (Reflect.get(source, "isNodeMaterial") === true) {
376
+ const twin = (source as NodeMaterial).clone();
377
+ // NodeMaterial.copy skips the inherited alphaTest accessor and its private backing value.
378
+ twin.alphaTest = source.alphaTest;
379
+ return twin;
380
+ }
324
381
  const nodeClass = NODE_CLASSES.get(source.type);
325
382
  if (nodeClass === undefined)
326
383
  throw new Error(`WorldImpostorSurface cannot convert material type '${source.type}'.`);
@@ -390,9 +447,8 @@ export class WorldImpostorSurface {
390
447
  const relVarying = varyingProperty("vec3", `${name}Rel`);
391
448
  const dirVarying = varyingProperty("vec3", `${name}Dir`);
392
449
 
393
- const positionNode = Fn((_inputs: unknown, builder: { readonly object: Object3D }) => {
394
- const object = builder.object;
395
- const instance = userInstanceMatrix(object);
450
+ const positionNode = Fn((_inputs: unknown, builder: NodeBuilder) => {
451
+ const instance = userInstanceMatrix(builder);
396
452
  const view = cameraViewMatrix.mul(modelWorldMatrix).mul(instance);
397
453
  const centerView = view.mul(vec4(centerUniform, 1)).xyz;
398
454
  // The authored cull contract in `world-gpu-scene.ts` `cullAndSelect` measures horizontal
@@ -449,8 +505,8 @@ export class WorldImpostorSurface {
449
505
  material.colorNode = vec4(fragment.albedo, fragment.coverage);
450
506
  material.alphaTestNode = fragment.threshold;
451
507
  material.maskShadowNode = fragment.coverage.greaterThan(fragment.threshold);
452
- material.normalNode = Fn((_inputs: unknown, builder: { readonly object: Object3D }) =>
453
- transformNormal(fragment.normalAsset, instanceViewMatrixNode(builder.object)),
508
+ material.normalNode = Fn((_inputs: unknown, builder: NodeBuilder) =>
509
+ transformNormal(fragment.normalAsset, instanceViewMatrixNode(builder)),
454
510
  )();
455
511
  material.positionNode = positionNode;
456
512
 
@@ -487,11 +543,38 @@ export class WorldImpostorSurface {
487
543
  let surfaceId = 0;
488
544
 
489
545
  /** The attribute node for the position pass; a plain `Mesh` falls back to the identity. */
490
- function userInstanceMatrix(object: Object3D): Node<"mat4"> {
546
+ function userInstanceMatrix(builder: NodeBuilder): Node<"mat4"> {
547
+ if (engineInstanceMatrix !== undefined) return engineInstanceMatrix();
548
+ const object = builder.object;
491
549
  const attribute = (object as { instanceMatrix?: InstancedBufferAttribute }).instanceMatrix;
492
- return attribute === undefined ? identityMat4() : instanceMatrixNode(attribute);
550
+ return attribute === undefined ? identityMat4() : instanceMatrixNode(attribute, builder);
493
551
  }
494
552
 
553
+ /**
554
+ * A random in [0, 1) that stays with its instance, as UE 5.8.3's PerInstanceRandom: hashed from the
555
+ * instance's world origin, never from its draw slot. WorldCells repacks instances on every refilter,
556
+ * main-pass cull and LOD switch, so `instanceIndex` names another tree from one frame to the next; a
557
+ * wind phase hashed from it re-rolled each crown about every 0.7 s of a walk and snapped its top by a
558
+ * median 0.37 m. Parts of one placement share its translation, so its bark and needles read one value.
559
+ *
560
+ * @situation a per-instance random number that stays with each streamed placement as WorldCells repacks
561
+ * @situation replace instanceIndex in a WorldCells part material, which WorldCells refuses
562
+ * @example const phase = instanceRandom().mul(6.2831);
563
+ */
564
+ export function instanceRandom(): Node<"float"> {
565
+ return Fn((_inputs: unknown, builder: NodeBuilder) => {
566
+ const origin = userInstanceMatrix(builder).mul(vec4(0, 0, 0, 1)).xyz;
567
+ // Quantised like `worldLodMaterial`'s origin, so float rounding in a rewritten matrix keeps the hash.
568
+ const snapped = floor(origin.mul(16).add(0.5)).div(16);
569
+ return fract(sin(dot(snapped.xz, vec2(12.9898, 78.233))).mul(43758.5453));
570
+ })() as Node<"float">;
571
+ }
572
+
573
+ /** Coarse ray-march steps across an impostor's depth; see `buildFragmentNodes`. */
574
+ export const IMPOSTOR_MARCH_STEPS = 32;
575
+ /** Bisection steps per crossing: 32 x 1024 places a hit as finely as 128 texel steps x 256 did. */
576
+ export const IMPOSTOR_BISECTION_STEPS = 10;
577
+
495
578
  interface IFragmentNodes {
496
579
  readonly albedo: Node<"vec3">;
497
580
  readonly coverage: Node<"float">;
@@ -545,6 +628,7 @@ function buildFragmentNodes(
545
628
 
546
629
  const colorMap = texture(atlas.color);
547
630
  const normalMap = texture(atlas.normal);
631
+ const steps = Math.min(atlas.pixels, IMPOSTOR_MARCH_STEPS);
548
632
  const uvs: Node<"vec2">[] = [];
549
633
  const colors: Node<"vec4">[] = [];
550
634
  const normals: Node<"vec4">[] = [];
@@ -562,23 +646,38 @@ function buildFragmentNodes(
562
646
  .mul(grid)
563
647
  .add(cellX[index] as Node<"float">)
564
648
  .toInt();
565
- // A crossing must remain covered throughout refinement; alpha holes and depth jumps
566
- // cannot create an interior surface. One march step per baked texel, eight refinements.
649
+ // Positive baked coverage owns ray/depth geometry; the authored cutoff is applied once by the
650
+ // final mip-aware fragment threshold. Alpha holes and depth jumps cannot create an interior
651
+ // surface. A march step every four baked texels at most, ten refinements: one step per texel
652
+ // was ~770 atlas reads a fragment over three frames, 26 ms of a 42 ms walking frame with 383 fir
653
+ // impostors on screen, and two more bisection steps keep each crossing as precise as before.
654
+ // March on the mip the fragment's own footprint resolves: mip 0 under a far tree a few pixels
655
+ // wide reads scattered texels on every step and thrashes the texture cache (24 ms of a 48 ms
656
+ // walking frame on 53k far trees). Depth is coverage-premultiplied, so a mip keeps its meaning.
657
+ // Taken here, in uniform control flow, because derivatives inside the loop are undefined.
658
+ const footUv = vec2(dot(relVarying, basis.right), dot(relVarying, basis.up).negate())
659
+ .div(radiusUniform)
660
+ .mul(0.5)
661
+ .add(0.5);
662
+ const marchLevel = max(
663
+ log2(max(length(dFdx(footUv).mul(atlas.pixels)), length(dFdy(footUv).mul(atlas.pixels)))),
664
+ float(0),
665
+ ).toVar();
567
666
  const hit = Fn(() => {
568
667
  const found = float(0).toVar();
569
668
  const hitUv = vec2(2).toVar();
570
669
  const previousGap = float(0).toVar();
571
670
  const previousAlpha = float(0).toVar();
572
671
  const previousT = radiusUniform.toVar();
573
- Loop({ start: 0, end: atlas.pixels + 1, type: "int" }, ({ i }) => {
574
- const t = float(1).sub(float(i).div(atlas.pixels).mul(2)).mul(radiusUniform);
672
+ Loop({ start: 0, end: steps + 1, type: "int" }, ({ i }) => {
673
+ const t = float(1).sub(float(i).div(steps).mul(2)).mul(radiusUniform);
575
674
  const point = relVarying.add(ray.mul(t));
576
675
  const sampleUv = vec2(dot(point, basis.right), dot(point, basis.up).negate())
577
676
  .div(radiusUniform)
578
677
  .mul(0.5)
579
678
  .add(0.5);
580
- const c = colorMap.depth(layer).sample(sampleUv).level(float(0)).toVar();
581
- const n = normalMap.depth(layer).sample(sampleUv).level(float(0)).toVar();
679
+ const c = colorMap.depth(layer).sample(sampleUv).level(marchLevel).toVar();
680
+ const n = normalMap.depth(layer).sample(sampleUv).level(marchLevel).toVar();
582
681
  const depth = float(1)
583
682
  .sub(
584
683
  float(1)
@@ -591,23 +690,23 @@ function buildFragmentNodes(
591
690
  If(
592
691
  found
593
692
  .equal(0)
594
- .and(previousAlpha.greaterThan(cutoff))
595
- .and(c.a.greaterThan(cutoff))
693
+ .and(previousAlpha.greaterThan(0))
694
+ .and(c.a.greaterThan(0))
596
695
  .and(previousGap.greaterThan(0))
597
696
  .and(gap.lessThanEqual(0)),
598
697
  () => {
599
698
  const front = previousT.toVar();
600
699
  const back = t.toVar();
601
700
  const valid = float(1).toVar();
602
- Loop({ start: 0, end: 8, type: "int" }, () => {
701
+ Loop({ start: 0, end: IMPOSTOR_BISECTION_STEPS, type: "int" }, () => {
603
702
  const mid = front.add(back).mul(0.5).toVar();
604
703
  const p = relVarying.add(ray.mul(mid));
605
704
  const u = vec2(dot(p, basis.right), dot(p, basis.up).negate())
606
705
  .div(radiusUniform)
607
706
  .mul(0.5)
608
707
  .add(0.5);
609
- const mc = colorMap.depth(layer).sample(u).level(float(0)).toVar();
610
- const mn = normalMap.depth(layer).sample(u).level(float(0)).toVar();
708
+ const mc = colorMap.depth(layer).sample(u).level(marchLevel).toVar();
709
+ const mn = normalMap.depth(layer).sample(u).level(marchLevel).toVar();
611
710
  const md = float(1)
612
711
  .sub(
613
712
  float(1)
@@ -617,7 +716,7 @@ function buildFragmentNodes(
617
716
  )
618
717
  .mul(radiusUniform);
619
718
  const mg = dot(p, direction).sub(md);
620
- If(mc.a.lessThanEqual(cutoff), () => {
719
+ If(mc.a.lessThanEqual(0), () => {
621
720
  valid.assign(0);
622
721
  });
623
722
  If(mg.greaterThan(0), () => {
@@ -631,8 +730,8 @@ function buildFragmentNodes(
631
730
  .div(radiusUniform)
632
731
  .mul(0.5)
633
732
  .add(0.5);
634
- const hc = colorMap.depth(layer).sample(u).level(float(0)).toVar();
635
- const hn = normalMap.depth(layer).sample(u).level(float(0)).toVar();
733
+ const hc = colorMap.depth(layer).sample(u).level(marchLevel).toVar();
734
+ const hn = normalMap.depth(layer).sample(u).level(marchLevel).toVar();
636
735
  const hd = float(1)
637
736
  .sub(
638
737
  float(1)
@@ -644,7 +743,7 @@ function buildFragmentNodes(
644
743
  If(
645
744
  valid
646
745
  .equal(1)
647
- .and(hc.a.greaterThan(cutoff))
746
+ .and(hc.a.greaterThan(0))
648
747
  .and(
649
748
  abs(dot(p, direction).sub(hd)).lessThanEqual(
650
749
  radiusUniform.mul(2 / 255).div(max(hc.a, float(0.001))),
@@ -720,3 +819,163 @@ export function impostorFrameUv(
720
819
  v: 0.5 - (relative.dot(basis.up) / radius) * 0.5,
721
820
  };
722
821
  }
822
+
823
+ /**
824
+ * How long a published level change fades, in seconds: UE 5.8.3 `lod.TemporalLag`
825
+ * (Engine/Source/Runtime/Engine/Private/SceneManagement.cpp:28-32).
826
+ */
827
+ export const LOD_TEMPORAL_LAG = 0.5;
828
+
829
+ /**
830
+ * UE 5.8.3's temporal LOD state (Engine/Source/Runtime/Engine/Private/SceneManagement.cpp:113-140):
831
+ * two lagged view origins and the blend between them. LOD is chosen at both and cross-faded by
832
+ * `alpha`, so a placement crossing a gate fades over one `lag` window and none stays mid-fade while
833
+ * the viewer stands still.
834
+ */
835
+ export interface ITemporalLod {
836
+ readonly from: Vector3;
837
+ readonly to: Vector3;
838
+ fromTime: number;
839
+ toTime: number;
840
+ alpha: number;
841
+ }
842
+
843
+ /** Advance {@link ITemporalLod} to `now` seconds with the view at `eye`, as UE's UpdateTemporalLODTransition. */
844
+ export function advanceTemporalLod(
845
+ state: ITemporalLod,
846
+ eye: Vector3,
847
+ now: number,
848
+ lag = LOD_TEMPORAL_LAG,
849
+ ): void {
850
+ if (!Number.isFinite(state.toTime) || now < state.toTime) {
851
+ state.from.copy(eye);
852
+ state.to.copy(eye);
853
+ state.fromTime = now;
854
+ state.toTime = now;
855
+ } else if (state.toTime < now - lag) {
856
+ if (state.fromTime < state.toTime) {
857
+ state.from.copy(state.to);
858
+ state.fromTime = state.toTime;
859
+ }
860
+ state.to.copy(eye);
861
+ state.toTime = now;
862
+ }
863
+ const window = state.toTime - state.fromTime;
864
+ state.alpha = window > 0 ? Math.min(1, Math.max(0, (now - lag - state.fromTime) / window)) : 1;
865
+ }
866
+
867
+ /** Complementary LOD masks over the caller's distance bands, shared by colour and shadow passes. */
868
+ export function worldLodMaterial(
869
+ source: Material,
870
+ local: import("three").Matrix4,
871
+ distances: readonly number[],
872
+ level: number,
873
+ width: number,
874
+ eye: Node<"vec3">,
875
+ distanceBias: Node<"float">,
876
+ spatial: boolean,
877
+ publishedRanges = false,
878
+ clock?: Node<"float">,
879
+ temporal?: {
880
+ readonly from: Node<"vec3">;
881
+ readonly to: Node<"vec3">;
882
+ readonly alpha: Node<"float">;
883
+ },
884
+ shadowFloor = 0,
885
+ ): NodeMaterial {
886
+ const material = cloneLitMaterial(source);
887
+ const inverse = uniform(local.clone().invert());
888
+ const root = Fn(
889
+ (_inputs: unknown, builder: NodeBuilder) =>
890
+ userInstanceMatrix(builder)
891
+ .mul(inverse)
892
+ .mul(vec4(0, 0, 0, 1)).xyz,
893
+ )();
894
+ // Quantise recovered roots so part-local float rounding cannot change the instance hash.
895
+ const origin = varying(floor(root.mul(16).add(0.5)).div(16));
896
+ const distanceTo = (at: Node<"vec3">) =>
897
+ (spatial ? length(origin.sub(at)) : length(origin.xz.sub(at.xz))).mul(distanceBias);
898
+ const distance = distanceTo(eye);
899
+ const random = fract(sin(dot(origin.xz, vec2(12.9898, 78.233))).mul(43758.5453));
900
+ const noise = fract(sin(dot(floor(screenCoordinate.xy), vec2(12.9898, 78.233))).mul(43758.5453));
901
+ // CPU-admitted batches publish the levels their instance currently has beside its matrix. During
902
+ // a queued refilter, an old level outside that set remains whole until the replacement is swapped.
903
+ // LOD indices are categorical; interpolating 2 below 2 can clip an otherwise whole tree.
904
+ // `.zw` is the fade a swap stamped: the level the record was whole at (-1: none) and when.
905
+ const published = publishedRanges
906
+ ? varying(attribute("tnPublishedLodRange", "vec4") as Node<"vec4">).setInterpolation("flat")
907
+ : undefined;
908
+ // The level and the gate distances are uniforms, not constants, so every level of an asset (and
909
+ // every asset with as many gates) is one shader program and one pipeline, as an Unreal material
910
+ // instance shares its parent's shader. Baked, each level was a first-time program that compiled in
911
+ // the frame it first came into view: 14 ms of CPU and a 50 ms frame in a 360-degree turn.
912
+ const lod = uniform(level);
913
+ const gates = distances.map((at) => uniform(at));
914
+ const always = float(1).greaterThan(0);
915
+ // `mixAt(gate)` is how far past the gate this placement is, 0..1; pixels with noise below it draw
916
+ // the coarser level.
917
+ const levelMask = (
918
+ mixAt: (at: Node<"float">, span: Node<"float">) => Node<"float">,
919
+ first = 1,
920
+ ) => {
921
+ let mask = always;
922
+ for (let gate = first; gate < distances.length; gate++) {
923
+ const at = gates[gate] as Node<"float">;
924
+ let span = at.mul(width).min(at.sub(gates[gate - 1] as Node<"float">).mul(width));
925
+ if (gate + 1 < distances.length)
926
+ span = span.min((gates[gate + 1] as Node<"float">).sub(at).mul(width));
927
+ const mix = mixAt(at, span);
928
+ // `gate === level` fades this level in past the gate; `gate === level + 1` fades it out.
929
+ const fadeIn =
930
+ published === undefined
931
+ ? noise.lessThan(mix)
932
+ : select(published.x.lessThan(lod), noise.lessThan(mix), always);
933
+ const fadeOut =
934
+ published === undefined
935
+ ? noise.greaterThanEqual(mix)
936
+ : select(published.y.greaterThan(lod), noise.greaterThanEqual(mix), always);
937
+ mask = mask.and(lod.notEqual(gate).or(fadeIn)).and(lod.notEqual(gate - 1).or(fadeOut));
938
+ }
939
+ return mask;
940
+ };
941
+ const rampAt = (at: Node<"float">, span: Node<"float">) =>
942
+ distance.sub(at).div(span).add(0.5).add(random.sub(0.5).mul(0.5)).clamp(0, 1);
943
+ const mask = levelMask(rampAt);
944
+ // `shadowFloor`: finer placements cast in the floor level's shape (`castLevelOf`), so the floor's
945
+ // shadow covers every distance under its outer gate and a finer level casts nothing.
946
+ const shadow =
947
+ shadowFloor > 0
948
+ ? lod.greaterThanEqual(shadowFloor).and(levelMask(rampAt, shadowFloor + 1))
949
+ : mask;
950
+ // Temporal: the gate is hard in space and the colour pass blends the level seen from the older
951
+ // eye into the level seen from the newer one, as UE's instanced foliage does.
952
+ const past = (eyeAt: Node<"vec3">, at: Node<"float">) =>
953
+ select(distanceTo(eyeAt).greaterThan(at), float(1), float(0));
954
+ const crossFaded =
955
+ temporal === undefined
956
+ ? mask
957
+ : levelMask((at) =>
958
+ past(temporal.from, at)
959
+ .mul(float(1).sub(temporal.alpha))
960
+ .add(past(temporal.to, at).mul(temporal.alpha)),
961
+ );
962
+ // A refilter that lands late turns a whole tree into a dithered pair in one frame. The colour pass
963
+ // keeps the old whole level on a shrinking share of pixels for `LOD_TEMPORAL_LAG`, as UE fades
964
+ // every LOD change in time; the shares stay complementary, so no pixel holds both or neither.
965
+ // Shadows take the new answer at once: a cached shadow page must not keep a frame of the fade.
966
+ let colour = crossFaded;
967
+ if (published !== undefined && clock !== undefined) {
968
+ const progress = clock.sub(published.w).div(LOD_TEMPORAL_LAG);
969
+ const blend = fract(
970
+ sin(dot(floor(screenCoordinate.xy), vec2(39.3468, 11.1353))).mul(24634.6345),
971
+ );
972
+ const holdOld = published.z.greaterThanEqual(0).and(blend.greaterThanEqual(progress));
973
+ colour = select(holdOld, published.z.sub(lod).abs().lessThan(0.5), crossFaded);
974
+ }
975
+ material.maskNode = material.maskNode ? (material.maskNode as Node<"bool">).and(colour) : colour;
976
+ material.maskShadowNode = material.maskShadowNode
977
+ ? (material.maskShadowNode as Node<"bool">).and(shadow)
978
+ : shadow;
979
+ if (publishedRanges) material.userData.tnPublishedLodRange = true;
980
+ return material;
981
+ }
@@ -99,6 +99,15 @@ export interface IAnimationRateState {
99
99
  export const animationRateStates = new WeakMap<Object3D, IAnimationRateState>();
100
100
  /** The roots that may hold a rate state, so the camera pass walks the rigs instead of the scene. */
101
101
  const animationRateRoots = new Set<WeakRef<Object3D>>();
102
+
103
+ /**
104
+ * From this many rigs, each re-measures its rate on its own turn, one frame in {@link RATE_MEASURE_FRAMES}, and
105
+ * holds the rate between turns. The measure is per-part math, 0.75 ms a frame for the stress lab's 120 rigs.
106
+ * A smaller scene measures every frame. The rate is itself a pose period of 1 to 8 frames, so a hold of 3 lags it by
107
+ * no more than one rate 4 period.
108
+ */
109
+ const RATE_HOLD_RIGS = 32;
110
+ const RATE_MEASURE_FRAMES = 4;
102
111
  const animationRateRootRefs = new WeakMap<Object3D, WeakRef<Object3D>>();
103
112
  /** The stand-ins named in {@link animationRateSources}, so the pass can reach them without a scene walk. */
104
113
  const animationRateCarriers = new Set<WeakRef<Object3D>>();
@@ -269,6 +278,8 @@ export class RenderCameraCull {
269
278
  readonly #animatedFrom: (Object3D | IAnimationRateState | number | undefined)[] = [];
270
279
  /** The renderables under each rate root, in walk order, from the same walk as {@link #animated}. */
271
280
  readonly #rigParts = new Map<Object3D, Object3D[]>();
281
+ /** A rig inside a rig: the inner rate comes from the outer walk, so no rig may skip its walk. */
282
+ #nestedRigs = false;
272
283
  #collectingParts: Object3D[] = [];
273
284
  readonly #collectAnimated: (object: Object3D) => void;
274
285
  /** The camera's descendants this frame, so camera attachment needs no walk up the parents. */
@@ -314,6 +325,7 @@ export class RenderCameraCull {
314
325
  this.#collectAnimated = (object) => {
315
326
  if (isRenderable(object)) this.#collectingParts.push(object);
316
327
  const outer = this.#animated.get(object);
328
+ if (outer !== undefined) this.#nestedRigs = true;
317
329
  // A rig nested in another rig answers to both roots.
318
330
  this.#animated.set(
319
331
  object,
@@ -353,6 +365,7 @@ export class RenderCameraCull {
353
365
  this.#animated.clear();
354
366
  this.#animatedFrom.length = 0;
355
367
  this.#rigParts.clear();
368
+ this.#nestedRigs = false;
356
369
  for (const ref of animationRateRoots) {
357
370
  const root = ref.deref() as Object3D;
358
371
  const state = animationRateStates.get(root) as IAnimationRateState;
@@ -405,9 +418,19 @@ export class RenderCameraCull {
405
418
  // Start at each rig and each stand-in that observes one, never at the scene: the walk then visits
406
419
  // the same objects a scene walk would have acted on, and nothing else.
407
420
  const rootShown = this.#isVisibleInWorld(root as Object3D);
421
+ // A stand-in's walk reads the rigs it draws, so with any stand-in every rig keeps its walk.
422
+ const holds =
423
+ rootShown &&
424
+ !this.#nestedRigs &&
425
+ animationRateCarriers.size === 0 &&
426
+ animationRateRoots.size >= RATE_HOLD_RIGS;
427
+ let turn = this.#animationFrame;
408
428
  for (const ref of animationRateRoots) {
409
429
  const rig = ref.deref();
410
- if (rig !== undefined && this.#reaches(rig, root)) this.#visitRig(rig, rootShown);
430
+ if (rig === undefined || !this.#reaches(rig, root)) continue;
431
+ turn += 1;
432
+ if (!holds || turn % RATE_MEASURE_FRAMES === 0 || !this.#holdRate(rig))
433
+ this.#visitRig(rig, rootShown);
411
434
  }
412
435
  for (const ref of animationRateCarriers) {
413
436
  const carrier = ref.deref();
@@ -424,6 +447,14 @@ export class RenderCameraCull {
424
447
  }
425
448
  }
426
449
 
450
+ /** Carries a rig's rate into this frame; false when last frame did not measure or hold it, as for a rig just shown. */
451
+ #holdRate(rig: Object3D): boolean {
452
+ const state = animationRateStates.get(rig);
453
+ if (state?.source !== this || state.frame !== this.#animationFrame - 1) return false;
454
+ state.frame = this.#animationFrame;
455
+ return true;
456
+ }
457
+
427
458
  /**
428
459
  * The rig's visible walk, as `traverseVisible` would make it. Only its renderables act, so on the
429
460
  * native engine, with the walk's root shown, each kept part asks whether it is shown, rather
@@ -223,7 +223,7 @@ function readCounters(target: IRenderPassTarget): { draws: number; triangles: nu
223
223
  return { draws, triangles };
224
224
  }
225
225
 
226
- const installed = new WeakSet<object>();
226
+ const installed = new WeakMap<object, RenderPassBudget>();
227
227
 
228
228
  /**
229
229
  * Resolved frames kept for GPU attribution. A resolve lags the frame it measures by a few frames,
@@ -233,15 +233,25 @@ const installed = new WeakSet<object>();
233
233
  const GPU_UID_FRAME_LIMIT = 64;
234
234
 
235
235
  /**
236
- * Names a render call by what three already calls it: the first camera call is the main pass, and a
237
- * nested call carries the scene name three or the reflector gave it.
236
+ * Names a render call by what three already calls it: a nested call carries the scene name three or
237
+ * the reflector gave it, and outside a scoped `renderWorld` draw the first camera call is the main pass.
238
238
  *
239
239
  * The name is read before the depth because a post pipeline makes its shadow or reflection passes at
240
- * world depth 0 — the composite quad is not a world call, so it does not hold one.
240
+ * world depth 0 — the composite quad is not a world call, so it does not hold one. A draw the game
241
+ * scoped with `renderWorld` names its authored root/camera directly, so three's shadow/reflection
242
+ * names still take priority and a standalone raw render retains the outermost-main convention.
241
243
  */
242
- function passKind(name: string, depth: number): FramePassKind {
244
+ function passKind(
245
+ scene: unknown,
246
+ camera: unknown,
247
+ name: string,
248
+ depth: number,
249
+ world: { scene: unknown; camera: unknown } | undefined,
250
+ ): FramePassKind {
243
251
  if (name.startsWith("Shadow Map")) return "shadow";
244
252
  if (/reflect/iu.test(name)) return "reflection";
253
+ if (world !== undefined)
254
+ return scene === world.scene && camera === world.camera ? "main" : "nested";
245
255
  return depth === 0 ? "main" : "nested";
246
256
  }
247
257
 
@@ -352,6 +362,7 @@ export class RenderPassBudget {
352
362
  readonly #original: (scene: unknown, camera: unknown) => void;
353
363
  readonly #frame: IRenderPassSample[] = [];
354
364
  readonly #stack: IPassFrame[] = [];
365
+ #world: { scene: unknown; camera: unknown } | undefined;
355
366
  /** How many non-quad render calls are open: the depth the camera pass is classified at. */
356
367
  #worldDepth = 0;
357
368
  /** Timestamp uids each render call allocated, keyed by the Three.js frame they belong to. */
@@ -377,7 +388,7 @@ export class RenderPassBudget {
377
388
  childTriangles: 0,
378
389
  entryDraws: counters.draws,
379
390
  entryTriangles: counters.triangles,
380
- kind: quad ? "nested" : passKind(name, this.#worldDepth),
391
+ kind: quad ? "nested" : passKind(scene, camera, name, this.#worldDepth, this.#world),
381
392
  name,
382
393
  };
383
394
  this.#stack.push(frame);
@@ -416,7 +427,7 @@ export class RenderPassBudget {
416
427
  };
417
428
  target.render = instrumented;
418
429
  this.#instrumentDraws(target.info);
419
- installed.add(target);
430
+ installed.set(target, this);
420
431
  }
421
432
 
422
433
  /**
@@ -456,6 +467,22 @@ export class RenderPassBudget {
456
467
  return new RenderPassBudget(target);
457
468
  }
458
469
 
470
+ /** The renderer's authored root/camera, including scene passes nested beneath post processing. */
471
+ static renderWorld(target: object, scene: unknown, camera: unknown, draw: () => void): void {
472
+ const budget = installed.get(target);
473
+ if (budget === undefined) {
474
+ draw();
475
+ return;
476
+ }
477
+ const previous = budget.#world;
478
+ budget.#world = { scene, camera };
479
+ try {
480
+ draw();
481
+ } finally {
482
+ budget.#world = previous;
483
+ }
484
+ }
485
+
459
486
  /**
460
487
  * The kind of the innermost render call currently running, or undefined outside one.
461
488
  *