@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
@@ -3,8 +3,10 @@ import {
3
3
  type BufferGeometry,
4
4
  type Camera,
5
5
  type DirectionalLight,
6
+ FrontSide,
6
7
  Frustum,
7
8
  type InstancedMesh,
9
+ type Material,
8
10
  Matrix4,
9
11
  type Mesh,
10
12
  Object3D,
@@ -14,6 +16,7 @@ import {
14
16
  type RenderTarget,
15
17
  Sphere,
16
18
  VSMShadowMap,
19
+ Vector2,
17
20
  Vector3,
18
21
  } from "three";
19
22
  import {
@@ -27,9 +30,11 @@ import {
27
30
  float,
28
31
  getShadowMaterial,
29
32
  length,
33
+ lightShadowMatrix,
30
34
  max,
31
35
  min,
32
36
  mix,
37
+ normalWorld,
33
38
  positionWorld,
34
39
  property,
35
40
  reference,
@@ -52,6 +57,7 @@ import {
52
57
  import { lodChainOf } from "../model-lod.js";
53
58
  import { shadowRedrawGpuMs } from "../render-pass-budget.js";
54
59
  import { DEFAULT_TARGET_FPS } from "../target-fps.js";
60
+ import { isLeafReceiver } from "./soft-shadow.js";
55
61
  import {
56
62
  DirectionalClipmap,
57
63
  type IBoundsLike,
@@ -59,6 +65,7 @@ import {
59
65
  type IPageRect,
60
66
  type IVector3Like,
61
67
  ShadowInvalidationTracker,
68
+ clipmapMapSizes,
62
69
  containsPages,
63
70
  pageArea,
64
71
  pageSpan,
@@ -96,8 +103,27 @@ export interface IVirtualShadowOptions {
96
103
  * increasing. Default `[16, 48, 144]`: three windows, each three times wider than the last.
97
104
  */
98
105
  readonly clipExtents?: readonly number[];
99
- /** Texels per level edge. Default: the light's `shadow.mapSize.width`. */
100
- readonly mapSize?: number;
106
+ /**
107
+ * Resolution bias in stops, default 0. Mirrors Unreal's
108
+ * `r.Shadow.Virtual.ResolutionLodBiasDirectional`; a quality tier sets it. With the default map
109
+ * sizes each stop doubles every level's texel: `-1` halves it (twice the resolution), `-1.5` is
110
+ * 2.83 times finer, a positive bias coarsens it. With an authored `mapSize` the finest window
111
+ * scales by `2 ** bias` instead and every coarser level keeps its extent; a bias that would push
112
+ * that window past the next level throws.
113
+ */
114
+ readonly resolutionLodBiasDirectional?: number;
115
+ /**
116
+ * Texels per level edge: one number for every level, or one per level, finest first. Default:
117
+ * Unreal's clipmap rule, measured on the camera and viewport that first read the shadow, so a
118
+ * receiver's texel is at most `2^(1 + bias)` of its own screen pixels (`clipmapMapSizes`). Set it to
119
+ * hold fixed sizes.
120
+ */
121
+ readonly mapSize?: number | readonly number[];
122
+ /**
123
+ * The page budget of the default map sizes, in 128² pages over all levels, default 4096 (Unreal's
124
+ * `r.Shadow.Virtual.MaxPhysicalPages` at Epic). Sizes over it raise the bias until they fit.
125
+ */
126
+ readonly maxPhysicalPages?: number;
101
127
  /**
102
128
  * Texels per edge of each level's mover map — the map tracked casters draw into every frame.
103
129
  * Default: `mapSize`, the cached levels' own density, so a caster keeps the edge it had at rest
@@ -211,17 +237,36 @@ export interface IVirtualShadowOptions {
211
237
  * Default true; false keeps eye follow for every camera. Walking cameras keep eye follow.
212
238
  */
213
239
  readonly followViewFocus?: boolean;
240
+ /**
241
+ * The smallest ratio of a level's light-space height to its width, `(0, 1]`, default 1 (square levels).
242
+ * A low sun stretches a shadow texel along the floor by `1 / sin(elevation)`. A value under 1 shrinks
243
+ * the height to `sin(elevation)` times the width, never under this value, so a texel covers the same
244
+ * floor area at any sun height. The costs: a wall taller than a level's height is read from a wider
245
+ * level, a level centred on the eye holds the floor only about `eye height / tan(elevation)` from the
246
+ * camera, and a wide filter disc (a source angle near 0.7 degrees) crosses the level's top and bottom
247
+ * edge and leaves a lit patch in a thin shadow (PRD-634, sun 4 ramp), so it is an opt-in.
248
+ */
249
+ readonly minWindowAspect?: number;
214
250
  /** Measure receiver-plane slope across each level's texel footprint to prevent coarse acne.
215
251
  * Default true; false preserves only the authored bias. Custom filterNode owns its footprint.
216
252
  */
217
253
  readonly receiverPlaneBias?: boolean;
218
254
  /**
219
- * Draw registered AutoLOD chains with their coarsest geometry past the finest level, default true.
255
+ * Draw registered AutoLOD chains with a coarser rung past the finest level, default true. A level
256
+ * takes the coarsest rung whose geometric error is within one of its texels, and never a rung
257
+ * finer than the main pass shows; where no rung is that accurate the caster keeps its geometry.
220
258
  * Alpha-tested and transparent casters keep casting on every level that resolves their bounds;
221
259
  * dropping their whole shadow at the fine window edge loses canopy and fences.
222
260
  * Geometry swaps are restored before the next level, mover map and main pass.
223
261
  */
224
262
  readonly shadowLodBias?: boolean;
263
+ /**
264
+ * The most error, in texels of a level, that a coarser rung may have on that level, default 1.
265
+ * A rung within a texel is as good as the full mesh at that resolution; a larger budget draws
266
+ * fewer triangles and shows facets on a shadow's edge, and `Infinity` draws the coarsest rung on
267
+ * every level past the finest. Read only with `shadowLodBias`.
268
+ */
269
+ readonly shadowLodTexels?: number;
225
270
  /**
226
271
  * Redraw only the pages an invalidation dirtied, default true. A level whose window did not move
227
272
  * and whose asks named under half its pages renders those rectangles alone: pages casters were
@@ -231,8 +276,8 @@ export interface IVirtualShadowOptions {
231
276
  */
232
277
  readonly partialRedraw?: boolean;
233
278
  /**
234
- * Quiet frames before an automatically detected mover goes back into the cached levels, default
235
- * 100 (Unreal's `FramesStaticThreshold`). A caster whose world matrix, instance matrix or
279
+ * Quiet frames an automatically detected mover must exceed before it goes back into the cached
280
+ * levels, default 100 (Unreal's `FramesStaticThreshold`: it settles on quiet frame 101). A caster whose world matrix, instance matrix or
236
281
  * deformation changed is drawn through the mover maps without a `trackCaster` call; this is how
237
282
  * long it must hold still before its shadow is baked into the cache again. Positive integer.
238
283
  */
@@ -457,6 +502,8 @@ export const VIRTUAL_SHADOW_SMALL_CASTER_LAYER = 26;
457
502
  */
458
503
  export const VIRTUAL_SHADOW_KEY_LAYER = 25;
459
504
  const DEFAULT_CLIP_EXTENTS: readonly number[] = [16, 48, 144];
505
+ /** Square levels. A fit to the ground (`0.25`, a 14.5 degree sun is where it ends) is the named override. */
506
+ const DEFAULT_MIN_WINDOW_ASPECT = 1;
460
507
  const DEFAULT_MARKER_EVERY = 300;
461
508
  /** Frames between markers while `?tnShadowStats=1` is on the URL: about a second a walk is long. */
462
509
  const STATS_QUERY_EVERY = 60;
@@ -780,6 +827,28 @@ function instanceDiameter(mesh: Mesh, sphereRadius: number): number {
780
827
  return radius * 2 * scale;
781
828
  }
782
829
 
830
+ /**
831
+ * The geometry a caster draws into a level past the finest: the coarsest rung of its AutoLOD chain
832
+ * whose error stays within `budget` (world units: texels of the level times `shadowLodTexels`), and
833
+ * never finer than the rung the main pass shows, which the viewer already cannot tell apart. Where
834
+ * no rung is that accurate the mesh keeps what it has. A rung whose error is more than a texel
835
+ * draws as a facet on the shadow's edge: the coarsest rung of a sphere, 60 mm out, put straight
836
+ * segments on a 7 mm texel. `undefined` leaves the geometry alone.
837
+ */
838
+ function shadowLod(mesh: Mesh, budget: number): BufferGeometry | undefined {
839
+ const chain = lodChainOf(mesh.geometry);
840
+ if (chain === undefined) return undefined;
841
+ // The largest instance scale `WorldCells` placed into this batch is on top of the mesh's own.
842
+ const placed = (mesh as Mesh & { casterInstanceScale?: number }).casterInstanceScale;
843
+ const scale =
844
+ mesh.matrixWorld.getMaxScaleOnAxis() * (placed !== undefined && placed > 0 ? placed : 1);
845
+ const shown = chain.levels.indexOf(mesh.geometry);
846
+ for (let rung = chain.levels.length - 1; rung > shown; rung -= 1) {
847
+ if ((chain.errors[rung] as number) * scale <= budget) return chain.levels[rung];
848
+ }
849
+ return undefined;
850
+ }
851
+
783
852
  /** Keep each stock node's source-owned settings aligned with the public light shadow. */
784
853
  function syncShadowSettings(
785
854
  source: DirectionalLight["shadow"],
@@ -857,6 +926,12 @@ interface IRenderingShadowNode {
857
926
  updateShadow(frame: NodeFrame): void;
858
927
  }
859
928
 
929
+ /** The slot the native bridge fills with its command sink on a core shadow node. */
930
+ const COMMAND_KEY = Symbol.for("threenative.virtualShadowCommand");
931
+ interface ICommandSlot {
932
+ [COMMAND_KEY]?: (value: object) => void;
933
+ }
934
+
860
935
  /**
861
936
  * One directional shadow for a whole open world: camera-centred clip levels, each snapped to its
862
937
  * own texel grid and re-rendered only when its window moves. Movers never touch that cache: a
@@ -890,6 +965,7 @@ interface IRenderingShadowNode {
890
965
  * @constraint `trackCaster(object)` is the override that pins an object as a mover for good (it enables layer `VIRTUAL_SHADOW_MOVER_LAYER` on the object and its descendants), and `pinStatic(object)` opts an object out of detection; tracking or untracking refreshes only that object's region
891
966
  * @override bias, biasNode, normalBias, intensity, radius, blurSamples, mapType and filterNode stay on `light.shadow`; mapSize and the other options here have defaults
892
967
  * @override followViewFocus: false keeps eye follow; receiverPlaneBias: false uses only authored bias
968
+ * @override minWindowAspect: below 1, a level is as high as `sin(sun elevation)` times its width, never under this, so a low sun's floor shadows keep the texel density of a high sun's; the default 1 keeps square levels
893
969
  * @example
894
970
  * const sun = new DirectionalLight(0xffffff, 3);
895
971
  * sun.castShadow = true;
@@ -901,9 +977,19 @@ export class VirtualShadowNode extends ShadowBaseNode {
901
977
  }
902
978
 
903
979
  readonly options: Required<
904
- Omit<IVirtualShadowOptions, "marker" | "refreshStep" | "selectionGuard" | "invalidationDelay">
980
+ Omit<
981
+ IVirtualShadowOptions,
982
+ "marker" | "refreshStep" | "selectionGuard" | "invalidationDelay" | "mapSize"
983
+ >
905
984
  > & {
906
985
  readonly markerEvery: number;
986
+ /**
987
+ * Texels per level edge, one per level. With `autoMapSize` the node measures them on the first
988
+ * camera that reads the shadow; until then each level holds the light's `shadow.mapSize.width`.
989
+ */
990
+ readonly mapSize: readonly number[];
991
+ /** The sizes follow Unreal's texel-per-pixel rule, because no `mapSize` was authored. */
992
+ readonly autoMapSize: boolean;
907
993
  /** Per level, finest first; the last entry stands in for every level past it. */
908
994
  readonly refreshStep: readonly number[];
909
995
  /** The per-level `selectionGuard` each level's own window is drawn with. */
@@ -951,6 +1037,8 @@ export class VirtualShadowNode extends ShadowBaseNode {
951
1037
  #basisV: UniformNode<"vec3", Vector3> = uniform(new Vector3(0, 0, 1)).setGroup(renderGroup);
952
1038
  #basisW: UniformNode<"vec3", Vector3> = uniform(new Vector3(0, 1, 0)).setGroup(renderGroup);
953
1039
  #receiverSlope = property("float", `virtualShadowReceiverSlope${String(this.id)}`);
1040
+ /** The window height ratio the level cameras were last fitted to. */
1041
+ #frustumScale = 1;
954
1042
  #frame = 0;
955
1043
  /** 1 while this node is inside `#updateFrame`; a level render re-enters `updateBefore`. */
956
1044
  #updating = false;
@@ -1063,14 +1151,53 @@ export class VirtualShadowNode extends ShadowBaseNode {
1063
1151
 
1064
1152
  constructor(light: DirectionalLight, options: IVirtualShadowOptions = {}) {
1065
1153
  super(light);
1066
- const clipExtents = options.clipExtents ?? DEFAULT_CLIP_EXTENTS;
1067
- const mapSize = options.mapSize ?? light.shadow.mapSize.width;
1068
- if (!Number.isInteger(mapSize) || mapSize <= 0) {
1154
+ const bias = options.resolutionLodBiasDirectional ?? 0;
1155
+ if (!Number.isFinite(bias)) {
1156
+ throw new RangeError(
1157
+ `TN_VIRTUAL_SHADOW_INVALID: resolutionLodBiasDirectional must be finite, got ${String(bias)}.`,
1158
+ );
1159
+ }
1160
+ const authoredExtents = options.clipExtents ?? DEFAULT_CLIP_EXTENTS;
1161
+ const autoMapSize = options.mapSize === undefined;
1162
+ // The rule takes the bias for every level; authored sizes take it on the finest window.
1163
+ const clipExtents = authoredExtents.map((extent, level) =>
1164
+ level === 0 && !autoMapSize ? extent * 2 ** bias : extent,
1165
+ );
1166
+ if (
1167
+ bias !== 0 &&
1168
+ clipExtents.length > 1 &&
1169
+ (clipExtents[0] as number) >= (clipExtents[1] as number)
1170
+ ) {
1069
1171
  throw new RangeError(
1070
- `TN_VIRTUAL_SHADOW_INVALID: mapSize must be a positive integer, got ${String(mapSize)}.`,
1172
+ `TN_VIRTUAL_SHADOW_INVALID: resolutionLodBiasDirectional ${String(bias)} widens the finest level to ${String(clipExtents[0])}, past the next level at ${String(clipExtents[1])}.`,
1071
1173
  );
1072
1174
  }
1073
- const moverMapSize = options.moverMapSize ?? mapSize;
1175
+ const sizes = options.mapSize ?? light.shadow.mapSize.width;
1176
+ const mapSize = clipExtents.map(
1177
+ (_, level) =>
1178
+ (typeof sizes === "number" ? sizes : sizes[Math.min(level, sizes.length - 1)]) as number,
1179
+ );
1180
+ for (const size of mapSize) {
1181
+ if (!Number.isInteger(size) || size <= 0) {
1182
+ throw new RangeError(
1183
+ `TN_VIRTUAL_SHADOW_INVALID: mapSize must be a positive integer, got ${String(size)}.`,
1184
+ );
1185
+ }
1186
+ }
1187
+ const maxPhysicalPages = options.maxPhysicalPages ?? 4096;
1188
+ if (!Number.isInteger(maxPhysicalPages) || maxPhysicalPages <= 0) {
1189
+ throw new RangeError(
1190
+ `TN_VIRTUAL_SHADOW_INVALID: maxPhysicalPages must be a positive integer, got ${String(maxPhysicalPages)}.`,
1191
+ );
1192
+ }
1193
+ const shadowLodTexels = options.shadowLodTexels ?? 1;
1194
+ if (!(shadowLodTexels > 0)) {
1195
+ throw new RangeError(
1196
+ `TN_VIRTUAL_SHADOW_INVALID: shadowLodTexels must be a positive number, got ${String(shadowLodTexels)}.`,
1197
+ );
1198
+ }
1199
+ const moverMapSize =
1200
+ options.moverMapSize ?? (autoMapSize ? light.shadow.mapSize.width : (mapSize[0] as number));
1074
1201
  if (!Number.isInteger(moverMapSize) || moverMapSize <= 0) {
1075
1202
  throw new RangeError(
1076
1203
  `TN_VIRTUAL_SHADOW_INVALID: moverMapSize must be a positive integer, got ${String(moverMapSize)}.`,
@@ -1092,6 +1219,12 @@ export class VirtualShadowNode extends ShadowBaseNode {
1092
1219
  `TN_VIRTUAL_SHADOW_INVALID: minCasterTexels must be zero or positive, got ${String(minCasterTexels)}.`,
1093
1220
  );
1094
1221
  }
1222
+ const minWindowAspect = options.minWindowAspect ?? DEFAULT_MIN_WINDOW_ASPECT;
1223
+ if (!Number.isFinite(minWindowAspect) || minWindowAspect <= 0 || minWindowAspect > 1) {
1224
+ throw new RangeError(
1225
+ `TN_VIRTUAL_SHADOW_INVALID: minWindowAspect must be in the range (0, 1], got ${String(minWindowAspect)}.`,
1226
+ );
1227
+ }
1095
1228
  const staticAfterFrames = options.staticAfterFrames ?? DEFAULT_STATIC_AFTER_FRAMES;
1096
1229
  if (!Number.isInteger(staticAfterFrames) || staticAfterFrames <= 0) {
1097
1230
  throw new RangeError(
@@ -1179,6 +1312,7 @@ export class VirtualShadowNode extends ShadowBaseNode {
1179
1312
  pagesPerAxis: mapSize,
1180
1313
  refreshStep: steps,
1181
1314
  selectionGuard: guardedExtent,
1315
+ minAspect: minWindowAspect,
1182
1316
  });
1183
1317
  this.tracker = new ShadowInvalidationTracker(this.clipmap);
1184
1318
  const marker = options.marker ?? DEFAULT_MARKER_EVERY;
@@ -1188,17 +1322,22 @@ export class VirtualShadowNode extends ShadowBaseNode {
1188
1322
  adaptiveCasterGate: options.adaptiveCasterGate ?? true,
1189
1323
  adaptiveRefresh: options.adaptiveRefresh ?? true,
1190
1324
  clipExtents: [...clipExtents],
1325
+ resolutionLodBiasDirectional: bias,
1191
1326
  depthRange: options.depthRange ?? 400,
1192
1327
  expensiveRefreshShare,
1193
1328
  invalidationDelay,
1194
1329
  lightDistance: options.lightDistance ?? 200,
1195
1330
  mapSize,
1331
+ autoMapSize,
1332
+ maxPhysicalPages,
1196
1333
  minCasterTexels,
1334
+ minWindowAspect,
1197
1335
  moverMapSize,
1198
1336
  markerEvery: marker === false ? 0 : marker === true ? DEFAULT_MARKER_EVERY : marker,
1199
1337
  refreshStep: steps,
1200
1338
  selectionGuard: guardedExtent,
1201
1339
  shadowLodBias: options.shadowLodBias ?? true,
1340
+ shadowLodTexels,
1202
1341
  partialRedraw: options.partialRedraw ?? true,
1203
1342
  staticAfterFrames,
1204
1343
  followViewFocus: options.followViewFocus ?? true,
@@ -1232,6 +1371,21 @@ export class VirtualShadowNode extends ShadowBaseNode {
1232
1371
  };
1233
1372
  }
1234
1373
 
1374
+ /** Engine bridge: preserve whether depth was authored, rather than mistaking fallback values for overrides. */
1375
+ get [Symbol.for("threenative.virtualShadow")](): object {
1376
+ return {
1377
+ ...this.options,
1378
+ autoDepth: this.#autoDepth,
1379
+ pinnedStatic: [...this.#pinnedRoots].map((root) => root.id),
1380
+ trackedCasters: [...this.#casters.values()].map((root) => root.id),
1381
+ };
1382
+ }
1383
+
1384
+ #nativeCommand(command: string, data: object = {}): void {
1385
+ const dispatch = (this as ICommandSlot)[COMMAND_KEY];
1386
+ dispatch?.({ command, ...data });
1387
+ }
1388
+
1235
1389
  /** The per-frame counters, as of the last `updateBefore`. */
1236
1390
  get stats(): IVirtualShadowStats {
1237
1391
  return this.#stats;
@@ -1308,6 +1462,7 @@ export class VirtualShadowNode extends ShadowBaseNode {
1308
1462
  return object.uuid;
1309
1463
  }
1310
1464
  if (previous !== undefined && previous !== object) this.#restoreMoverChildren(object.uuid);
1465
+ this.#nativeCommand("track", { id: object.id });
1311
1466
  this.#casters.set(object.uuid, object);
1312
1467
  this.#rememberMoverChildren(object);
1313
1468
  // It leaves the cached levels from here on: only the ones around it redraw without it.
@@ -1319,6 +1474,7 @@ export class VirtualShadowNode extends ShadowBaseNode {
1319
1474
  const id = typeof objectOrId === "string" ? objectOrId : objectOrId.uuid;
1320
1475
  const object = this.#casters.get(id);
1321
1476
  if (object === undefined) return false;
1477
+ this.#nativeCommand("untrack", { id: object.id });
1322
1478
  this.#restoreMoverChildren(id);
1323
1479
  this.tracker.remove(id);
1324
1480
  const removed = this.#casters.delete(id);
@@ -1332,6 +1488,7 @@ export class VirtualShadowNode extends ShadowBaseNode {
1332
1488
  * calls `invalidateRegion`. Takes effect from the next frame.
1333
1489
  */
1334
1490
  pinStatic(object: Object3D): void {
1491
+ this.#nativeCommand("pin", { id: object.id });
1335
1492
  this.#pinnedRoots.add(object);
1336
1493
  // The table is rebuilt on the next frame, which is where the pin reaches each mesh.
1337
1494
  this.#casterStale = true;
@@ -1339,6 +1496,7 @@ export class VirtualShadowNode extends ShadowBaseNode {
1339
1496
 
1340
1497
  /** Force every level to re-render on the next frame — a tree fell, a door opened. */
1341
1498
  invalidateAll(): void {
1499
+ this.#nativeCommand("invalidateAll");
1342
1500
  this.#invalidateAll = true;
1343
1501
  this.#regions.length = 0;
1344
1502
  this.tracker.invalidateAll();
@@ -1363,6 +1521,9 @@ export class VirtualShadowNode extends ShadowBaseNode {
1363
1521
  bounds: IBoundsLike & { admission?: boolean },
1364
1522
  admission = bounds.admission === true,
1365
1523
  ): void {
1524
+ this.#nativeCommand("invalidateRegion", {
1525
+ bounds: [bounds.min.x, bounds.min.y, bounds.min.z, bounds.max.x, bounds.max.y, bounds.max.z],
1526
+ });
1366
1527
  if (this.#levels.length === 0) return;
1367
1528
  this.#regions.push({
1368
1529
  ...(admission ? { admission: true as const } : {}),
@@ -1538,7 +1699,8 @@ export class VirtualShadowNode extends ShadowBaseNode {
1538
1699
  if (!moved && !deforms(mesh)) {
1539
1700
  if (state.phase === MOTION_MOVER) {
1540
1701
  state.quiet += 1;
1541
- if (state.quiet >= quietFrames) this.#settle(mesh, state);
1702
+ // UE 5.8.3 UpdateCachePrimitiveAsDynamic: static once the invalidation age is MORE than the threshold.
1703
+ if (state.quiet > quietFrames) this.#settle(mesh, state);
1542
1704
  }
1543
1705
  continue;
1544
1706
  }
@@ -1691,8 +1853,8 @@ export class VirtualShadowNode extends ShadowBaseNode {
1691
1853
  // budget raises the size a caster must be before it draws here, so it sheds its tiniest props
1692
1854
  // first. The scale starts and usually stays at 1, so a cheap level's gate — and every count
1693
1855
  // taken through it — is byte-identical to the configured one.
1694
- const gate =
1695
- ((this.options.minCasterTexels * 2 * level.extent) / this.options.mapSize) * level.gateScale;
1856
+ const texel = (2 * level.extent) / (this.options.mapSize[index] as number);
1857
+ const gate = this.options.minCasterTexels * texel * level.gateScale;
1696
1858
  let gateHidden = 0;
1697
1859
  const clusterLayer = 1 << VIRTUAL_SHADOW_CASTER_LAYER;
1698
1860
  const wideLayer = 1 << VIRTUAL_SHADOW_WIDE_CASTER_LAYER;
@@ -1761,11 +1923,10 @@ export class VirtualShadowNode extends ShadowBaseNode {
1761
1923
  if (mesh.casterPrewarmOwed === true) prewarming = true;
1762
1924
  // Reduce geometry, never the caster's presence: alpha cutouts carry canopy and fences.
1763
1925
  if (biased && mesh.castShadow === true) {
1764
- const chain = lodChainOf(mesh.geometry);
1765
- const coarsest = chain?.levels[chain.levels.length - 1];
1766
- if (coarsest !== undefined && coarsest !== mesh.geometry) {
1926
+ const coarse = shadowLod(mesh, texel * this.options.shadowLodTexels);
1927
+ if (coarse !== undefined) {
1767
1928
  this.#coarsened.push({ geometry: mesh.geometry, mesh });
1768
- mesh.geometry = coarsest;
1929
+ mesh.geometry = coarse;
1769
1930
  }
1770
1931
  }
1771
1932
  // The same two spheres three's cull uses: an instanced mesh's own, over its instances, or the
@@ -2001,6 +2162,32 @@ export class VirtualShadowNode extends ShadowBaseNode {
2001
2162
  * what a draw submits, and the renderer's own per-draw function is not ours to wrap.
2002
2163
  */
2003
2164
  #renderLevel(frame: NodeFrame, level: ILevel, mover: boolean, index = 0): void {
2165
+ // A front-sided caster with no shadowSide of its own draws its front faces into a virtual page,
2166
+ // as Unreal's sun does. three derives BackSide for it, and the back face of a wall box is the
2167
+ // room's own inner surface: the stored depth sat on the receiver and the sun leaked along every
2168
+ // inner seam. The material is put back once the level has drawn, so the main pass and a
2169
+ // classic lamp see it as authored; a shadowSide the author set is never touched.
2170
+ const claimed: Material[] = [];
2171
+ for (const mesh of this.#casterTable) {
2172
+ const material = mesh.material;
2173
+ if (
2174
+ mesh.castShadow === false ||
2175
+ Array.isArray(material) ||
2176
+ material.shadowSide !== null ||
2177
+ material.side !== FrontSide
2178
+ )
2179
+ continue;
2180
+ material.shadowSide = FrontSide;
2181
+ claimed.push(material);
2182
+ }
2183
+ try {
2184
+ this.#drawLevel(frame, level, mover, index);
2185
+ } finally {
2186
+ for (const material of claimed) material.shadowSide = null;
2187
+ }
2188
+ }
2189
+
2190
+ #drawLevel(frame: NodeFrame, level: ILevel, mover: boolean, index = 0): void {
2004
2191
  // quality-allow: Three exposes updateShadow only on its internal rendering shadow node.
2005
2192
  const node = (mover ? level.moverNode : level.node) as unknown as IRenderingShadowNode;
2006
2193
  // The level's own keys, selected against this map's own three numbers, before the render that
@@ -2081,7 +2268,7 @@ export class VirtualShadowNode extends ShadowBaseNode {
2081
2268
  camera.clearViewOffset();
2082
2269
  // quality-allow: the light's own shadow owns this update, and the stock node calls it too.
2083
2270
  level.shadow.updateMatrices(level.light as unknown as DirectionalLight);
2084
- const size = this.options.mapSize;
2271
+ const size = this.options.mapSize[index] as number;
2085
2272
  const pageSize = this.clipmap.pageWorldSize(index);
2086
2273
  const { rect } = pass;
2087
2274
  const corners = [
@@ -2214,7 +2401,7 @@ export class VirtualShadowNode extends ShadowBaseNode {
2214
2401
  // margin left is held at the step it was given and is not widened at all.
2215
2402
  const margin = Math.max(
2216
2403
  base,
2217
- 1 - at(this.options.selectionGuard, index) - 1 / this.options.mapSize,
2404
+ 1 - at(this.options.selectionGuard, index) - 1 / (this.options.mapSize[index] as number),
2218
2405
  );
2219
2406
  const step = Math.min(base * Math.max(1, level.costMs / affordableMs), margin);
2220
2407
  if (step !== level.appliedStep) {
@@ -2353,6 +2540,20 @@ export class VirtualShadowNode extends ShadowBaseNode {
2353
2540
  drawnSpan.high = measured.high;
2354
2541
  }
2355
2542
 
2543
+ /** A level's cameras are as wide as its extent and as high as the window's ratio makes them. */
2544
+ #fitFrusta(): void {
2545
+ const scale = this.clipmap.vScale;
2546
+ if (scale === this.#frustumScale) return;
2547
+ this.#frustumScale = scale;
2548
+ for (const level of this.#levels) {
2549
+ for (const map of [level.shadow, level.moverShadow]) {
2550
+ map.camera.top = level.extent * scale;
2551
+ map.camera.bottom = -level.extent * scale;
2552
+ map.camera.updateProjectionMatrix();
2553
+ }
2554
+ }
2555
+ }
2556
+
2356
2557
  /** Put a level's camera on its window with the depth it last derived, and hold both maps to it. */
2357
2558
  #place(level: ILevel, centre: IVector3Like): void {
2358
2559
  const { basisW } = this.clipmap;
@@ -2367,6 +2568,30 @@ export class VirtualShadowNode extends ShadowBaseNode {
2367
2568
  this.#setDepth(level.moverShadow.camera, level);
2368
2569
  }
2369
2570
 
2571
+ /**
2572
+ * Unreal's texel-per-pixel rule (`clipmapMapSizes`) on the camera and viewport that first read the
2573
+ * shadow. Without a perspective camera or a drawing buffer the levels keep the light's map size.
2574
+ */
2575
+ #measureMapSizes(builder: NodeBuilder): void {
2576
+ // quality-allow: three's NodeBuilder declares no camera, but setup runs with the receiver's camera set
2577
+ const camera = (builder as unknown as { camera?: Camera & { isPerspectiveCamera?: boolean } })
2578
+ .camera;
2579
+ const renderer = builder.renderer as { getDrawingBufferSize?(target: Vector2): Vector2 };
2580
+ if (camera?.isPerspectiveCamera !== true || renderer.getDrawingBufferSize === undefined) return;
2581
+ // ponytail: measured once. A resized map re-versions its texture under bound groups (see
2582
+ // registeredOnCreate), so a later fov or viewport change keeps these sizes; resize when that is safe.
2583
+ const sizes = clipmapMapSizes({
2584
+ clipExtents: this.options.clipExtents,
2585
+ selectionGuard: this.options.selectionGuard,
2586
+ resolutionLodBias: this.options.resolutionLodBiasDirectional,
2587
+ tanHalfFov: 1 / (camera.projectionMatrix.elements[0] as number),
2588
+ viewportWidth: renderer.getDrawingBufferSize(new Vector2()).x,
2589
+ maxPhysicalPages: this.options.maxPhysicalPages,
2590
+ });
2591
+ (this.options as { mapSize: readonly number[] }).mapSize = sizes;
2592
+ this.clipmap.setPagesPerAxis(sizes);
2593
+ }
2594
+
2370
2595
  /** Hand a level's own cameras the depth it derived, when it is not the depth they already hold. */
2371
2596
  #setDepth(camera: OrthographicCamera, level: ILevel): void {
2372
2597
  if (camera.near === level.depthNear && camera.far === level.depthFar) return;
@@ -2381,20 +2606,22 @@ export class VirtualShadowNode extends ShadowBaseNode {
2381
2606
  for (let at = 0; at < 4; at += 1) into[at] = row[2 + at * 4] as number;
2382
2607
  }
2383
2608
 
2384
- #init(): void {
2609
+ #init(builder: NodeBuilder): void {
2385
2610
  if (this.#initialised) return;
2386
2611
  this.#initialised = true;
2612
+ if (this.options.autoMapSize) this.#measureMapSizes(builder);
2387
2613
  const source = this.light as DirectionalLight;
2388
2614
  source.addEventListener("removed", this.#onLightRemoved);
2389
2615
  let shadowColor: ReturnType<typeof getShadowMaterial>["colorNode"] = null;
2390
2616
  this.options.clipExtents.forEach((extent, index) => {
2391
2617
  const levelShadow = source.shadow.clone();
2392
2618
  syncShadowSettings(source.shadow, levelShadow);
2393
- levelShadow.mapSize.set(this.options.mapSize, this.options.mapSize);
2619
+ const size = this.options.mapSize[index] as number;
2620
+ levelShadow.mapSize.set(size, size);
2394
2621
  levelShadow.camera.left = -extent;
2395
2622
  levelShadow.camera.right = extent;
2396
- levelShadow.camera.top = extent;
2397
- levelShadow.camera.bottom = -extent;
2623
+ levelShadow.camera.top = extent * this.clipmap.vScale;
2624
+ levelShadow.camera.bottom = -extent * this.clipmap.vScale;
2398
2625
  levelShadow.camera.near = 1;
2399
2626
  levelShadow.camera.far = this.options.lightDistance + this.options.depthRange;
2400
2627
  levelShadow.camera.updateProjectionMatrix();
@@ -2428,6 +2655,21 @@ export class VirtualShadowNode extends ShadowBaseNode {
2428
2655
  const moverNode = registeredOnCreate(
2429
2656
  shadow(light as unknown as DirectionalLight, moverShadow), // quality-allow: the stock node reads only position, target and shadow
2430
2657
  );
2658
+ // A receiver marked twoSidedFoliage looks its shadow up where it stands: the normal bias is
2659
+ // taken back out of the shadow position, in this level's map and in its mover map (PRD-651).
2660
+ for (const stockNode of [node, moverNode]) {
2661
+ const stock = stockNode as typeof node & {
2662
+ setupShadowCoord: (builder: NodeBuilder, position: Node<"vec4">) => Node<"vec3">;
2663
+ };
2664
+ const coord = stock.setupShadowCoord;
2665
+ stock.setupShadowCoord = (builder, position) => {
2666
+ if (!isLeafReceiver(builder.material as Parameters<typeof isLeafReceiver>[0]))
2667
+ return coord.call(stock, builder, position);
2668
+ const bias = rendered(reference("normalBias", "float", levelShadow));
2669
+ const offset = lightShadowMatrix(light as never).mul(vec4(normalWorld.mul(bias), 0));
2670
+ return coord.call(stock, builder, position.sub(offset));
2671
+ };
2672
+ }
2431
2673
  if (this.options.receiverPlaneBias) {
2432
2674
  for (const entry of [
2433
2675
  { node, map: levelShadow },
@@ -2567,7 +2809,7 @@ export class VirtualShadowNode extends ShadowBaseNode {
2567
2809
  (this.options as { adaptiveRefresh: boolean }).adaptiveRefresh = false;
2568
2810
  }
2569
2811
  }
2570
- this.#init();
2812
+ this.#init(builder);
2571
2813
  const levels = this.#levels;
2572
2814
  const centerU = this.#centerU;
2573
2815
  const centerV = this.#centerV;
@@ -2599,9 +2841,11 @@ export class VirtualShadowNode extends ShadowBaseNode {
2599
2841
  const received = vec3(shadowPositionWorld as never);
2600
2842
  const normal = dFdx(received).cross(dFdy(received)).toVar();
2601
2843
  const along = max(abs(normal.dot(this.#basisW)), max(length(normal).mul(0.0001), 1e-12));
2844
+ // `basisV` is the unit V over the window ratio, and a texel is that ratio shorter along V,
2845
+ // so the depth change across one texel along V is |n.V| * ratio = |n.basisV| * ratio^2.
2602
2846
  this.#receiverSlope.assign(
2603
2847
  abs(normal.dot(basisU))
2604
- .add(abs(normal.dot(basisV)))
2848
+ .add(abs(normal.dot(basisV)).div(basisV.dot(basisV)))
2605
2849
  .div(along),
2606
2850
  );
2607
2851
  }
@@ -2642,7 +2886,7 @@ export class VirtualShadowNode extends ShadowBaseNode {
2642
2886
  // Use the existing unused map margin, with at least two texels for guard=1.
2643
2887
  const band = max(
2644
2888
  level.extentUniform.sub(edge),
2645
- level.extentUniform.mul(4 / this.options.mapSize),
2889
+ level.extentUniform.mul(4 / (this.options.mapSize[index] as number)),
2646
2890
  );
2647
2891
  const weight = smoothstep(edge.sub(band), edge, distance).oneMinus();
2648
2892
  result.assign(mix(result, min(vec4(level.node as never), moverResult(level)), weight));
@@ -2767,6 +3011,7 @@ export class VirtualShadowNode extends ShadowBaseNode {
2767
3011
  y: _direction.y,
2768
3012
  z: _direction.z,
2769
3013
  });
3014
+ this.#fitFrusta();
2770
3015
  camera.updateMatrixWorld(true);
2771
3016
  const cameraPosition = _center.setFromMatrixPosition(camera.matrixWorld);
2772
3017
  // The engine's own frame clock, in seconds. This is what a level's invalidation delay is
@@ -2778,7 +3023,10 @@ export class VirtualShadowNode extends ShadowBaseNode {
2778
3023
  this.#centerU.value = this.clipmap.centerLight.u;
2779
3024
  this.#centerV.value = this.clipmap.centerLight.v;
2780
3025
  this.#basisU.value.set(this.clipmap.basisU.x, this.clipmap.basisU.y, this.clipmap.basisU.z);
2781
- this.#basisV.value.set(this.clipmap.basisV.x, this.clipmap.basisV.y, this.clipmap.basisV.z);
3026
+ // The axis whose dot product is `v`: the unit V stretched by the window's height ratio.
3027
+ const vScale = this.clipmap.vScale;
3028
+ const basisV = this.clipmap.basisV;
3029
+ this.#basisV.value.set(basisV.x / vScale, basisV.y / vScale, basisV.z / vScale);
2782
3030
  this.#basisW.value.set(this.clipmap.basisW.x, this.clipmap.basisW.y, this.clipmap.basisW.z);
2783
3031
  // A caster that stopped casting, or stopped being visible, changed what the levels hold without
2784
3032
  // changing the tree, so nothing else on the frame would say so. Asked here, before this frame's
@@ -2832,7 +3080,11 @@ export class VirtualShadowNode extends ShadowBaseNode {
2832
3080
  admission: region.admission === true,
2833
3081
  u: projectBounds(region, this.clipmap.basisU),
2834
3082
  urgent: region.urgent === true,
2835
- v: projectBounds(region, this.clipmap.basisV),
3083
+ v: projectBounds(region, {
3084
+ x: basisV.x / vScale,
3085
+ y: basisV.y / vScale,
3086
+ z: basisV.z / vScale,
3087
+ }),
2836
3088
  });
2837
3089
  }
2838
3090
  this.#regions.length = 0;
@@ -2861,21 +3113,23 @@ export class VirtualShadowNode extends ShadowBaseNode {
2861
3113
  // holds the map it has and is due again on the next frame.
2862
3114
  let budgetSpent = false;
2863
3115
  try {
2864
- const half = this.clipmap.pagesPerAxis / 2;
2865
3116
  // The window each level's map was actually rendered with. A level that does not get this
2866
3117
  // frame's window keeps this one, and `level.minX/minY` stays put, so it is still "moved" next
2867
3118
  // frame and still due.
2868
- const centreOf = (window: IClipWindow): { cu: number; cv: number } => ({
2869
- cu: (window.minX + half) * window.pageWorldSize,
2870
- cv: (window.minY + half) * window.pageWorldSize,
2871
- });
3119
+ const centreOf = (window: IClipWindow, level: number): { cu: number; cv: number } => {
3120
+ const half = this.clipmap.pagesAt(level) / 2;
3121
+ return {
3122
+ cu: (window.minX + half) * window.pageWorldSize,
3123
+ cv: (window.minY + half) * window.pageWorldSize,
3124
+ };
3125
+ };
2872
3126
  const finer: { cu: number; cv: number; half: number }[] = [];
2873
3127
  this.#levels.forEach((level, index) => {
2874
3128
  const window = windows[index];
2875
3129
  if (window === undefined) return;
2876
3130
  const windowMoved =
2877
3131
  directionChanged || window.minX !== level.minX || window.minY !== level.minY;
2878
- const { cu, cv } = centreOf(window);
3132
+ const { cu, cv } = centreOf(window, index);
2879
3133
  // This level's own window against the regions handed to `invalidateRegion`. A window that
2880
3134
  // does not reach a region draws the same shadow either way.
2881
3135
  let regionDirty = false;
@@ -3008,7 +3262,7 @@ export class VirtualShadowNode extends ShadowBaseNode {
3008
3262
  this.#rendersTotal += 1;
3009
3263
  // A window that moved, a region-less ask, or more than half the pages dirty is the whole
3010
3264
  // level; anything else is the rectangles the asks named.
3011
- const levelPages = this.clipmap.pagesPerAxis ** 2;
3265
+ const levelPages = this.clipmap.pagesAt(index) ** 2;
3012
3266
  passes =
3013
3267
  reason === REASON_MOVE || level.dirtyAll
3014
3268
  ? undefined
@@ -3067,7 +3321,7 @@ export class VirtualShadowNode extends ShadowBaseNode {
3067
3321
  level.mapped.value === 1 && !grant
3068
3322
  ? { minX: level.minX, minY: level.minY, pageWorldSize: window.pageWorldSize }
3069
3323
  : window;
3070
- const { cu: hu, cv: hv } = centreOf(held as IClipWindow);
3324
+ const { cu: hu, cv: hv } = centreOf(held as IClipWindow, index);
3071
3325
  // Hold all three coordinates of the rendered centre: its derived depth and the mover
3072
3326
  // map's shared sampling matrix are relative to this depth, not the followed camera's.
3073
3327
  const centre = this.clipmap.unproject({
@@ -3112,7 +3366,7 @@ export class VirtualShadowNode extends ShadowBaseNode {
3112
3366
  _proposedDepth[2] !== _drawnDepth[2] ||
3113
3367
  _proposedDepth[3] !== _drawnDepth[3]
3114
3368
  ) {
3115
- const whole = this.clipmap.pagesPerAxis ** 2 - countedPages;
3369
+ const whole = this.clipmap.pagesAt(index) ** 2 - countedPages;
3116
3370
  this.#pagesDirty += whole;
3117
3371
  this.#pagesRedrawn += whole;
3118
3372
  passes = undefined;
@@ -3328,3 +3582,97 @@ export function readVirtualShadowMarker(line: string): IVirtualShadowStats | und
3328
3582
  return undefined;
3329
3583
  }
3330
3584
  }
3585
+
3586
+ /**
3587
+ * One frame's shadow passes on the owned engine with the spot and point light maps apart from the
3588
+ * sun's (PRD-650). The sun's draws and the lamps' add up to every shadow draw the renderer submitted.
3589
+ */
3590
+ export interface ILampShadowStats {
3591
+ readonly frame: number;
3592
+ readonly shadowDraws: number;
3593
+ /** The sun's maps: its virtual levels or its plain map. `gpuMs` is -1 until a GPU sample resolves. */
3594
+ readonly sun: { readonly draws: number; readonly gpuMs: number };
3595
+ /** The lamp maps the frame redrew (a cube's six faces are one), their draws, and their GPU time. */
3596
+ readonly lamps: { readonly redraws: number; readonly draws: number; readonly gpuMs: number };
3597
+ }
3598
+
3599
+ export const LAMP_SHADOW_MARKER = "TN_LAMP_SHADOW";
3600
+
3601
+ interface ILampShadowCounters {
3602
+ readonly lampRedraws: number;
3603
+ readonly lampDraws: number;
3604
+ readonly shadowDraws: number;
3605
+ readonly sunGpuMs: number;
3606
+ readonly lampGpuMs: number;
3607
+ }
3608
+
3609
+ const isCount = (n: unknown): n is number => Number.isInteger(n) && (n as number) >= 0;
3610
+ const isGpuMs = (n: unknown): n is number => n === -1 || (Number.isFinite(n) && (n as number) >= 0);
3611
+
3612
+ function isLampShadowStats(value: unknown): value is ILampShadowStats {
3613
+ const stats = value as Partial<Record<keyof ILampShadowStats, Record<string, unknown>>> | null;
3614
+ if (typeof stats !== "object" || stats === null) return false;
3615
+ const { frame, shadowDraws } = stats as Record<string, unknown>;
3616
+ const sun = stats.sun;
3617
+ const lamps = stats.lamps;
3618
+ return (
3619
+ isCount(frame) &&
3620
+ isCount(shadowDraws) &&
3621
+ typeof sun === "object" &&
3622
+ sun !== null &&
3623
+ typeof lamps === "object" &&
3624
+ lamps !== null &&
3625
+ isCount(sun.draws) &&
3626
+ isGpuMs(sun.gpuMs) &&
3627
+ isCount(lamps.redraws) &&
3628
+ isCount(lamps.draws) &&
3629
+ isGpuMs(lamps.gpuMs) &&
3630
+ sun.draws + lamps.draws === shadowDraws
3631
+ );
3632
+ }
3633
+
3634
+ /**
3635
+ * The `TN_LAMP_SHADOW` line for the renderer's last frame, or `undefined` on a renderer that keeps
3636
+ * no lamp counters (three's own).
3637
+ *
3638
+ * @situation log lamp shadow redraws and GPU time apart from the sun's on the owned engine
3639
+ * @constraint counters that do not add up to the frame's shadow draws throw TN_LAMP_SHADOW_INVALID
3640
+ * @example
3641
+ * const line = lampShadowMarker(renderer, frame);
3642
+ * if (line !== undefined) console.info(line);
3643
+ */
3644
+ export function lampShadowMarker(
3645
+ renderer: { readonly info?: { readonly engine?: { readonly shadows?: ILampShadowCounters } } },
3646
+ frame: number,
3647
+ ): string | undefined {
3648
+ const counters = renderer.info?.engine?.shadows;
3649
+ if (counters === undefined) return undefined;
3650
+ const stats: ILampShadowStats = {
3651
+ frame,
3652
+ shadowDraws: counters.shadowDraws,
3653
+ sun: { draws: counters.shadowDraws - counters.lampDraws, gpuMs: counters.sunGpuMs },
3654
+ lamps: { redraws: counters.lampRedraws, draws: counters.lampDraws, gpuMs: counters.lampGpuMs },
3655
+ };
3656
+ if (!isLampShadowStats(stats))
3657
+ throw new Error(`TN_LAMP_SHADOW_INVALID: ${JSON.stringify(counters)} at frame ${frame}`);
3658
+ return `${LAMP_SHADOW_MARKER}:${JSON.stringify(stats)}`;
3659
+ }
3660
+
3661
+ /**
3662
+ * Parse a `TN_LAMP_SHADOW` line back into its stats, or `undefined`.
3663
+ *
3664
+ * @situation count lamp shadow redraws from a renderer log, for example a moving-caster run
3665
+ * @constraint non-marker lines and markers whose sun and lamp draws do not add up return `undefined`
3666
+ * @example
3667
+ * const stats = readLampShadowMarker(line);
3668
+ * if (stats !== undefined) console.log(stats.lamps.redraws);
3669
+ */
3670
+ export function readLampShadowMarker(line: string): ILampShadowStats | undefined {
3671
+ if (!line.startsWith(`${LAMP_SHADOW_MARKER}:`)) return undefined;
3672
+ try {
3673
+ const value: unknown = JSON.parse(line.slice(LAMP_SHADOW_MARKER.length + 1));
3674
+ return isLampShadowStats(value) ? value : undefined;
3675
+ } catch {
3676
+ return undefined;
3677
+ }
3678
+ }