@threenative/core 0.3.4 → 0.3.5

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 (176) hide show
  1. package/capabilities.json +1505 -79
  2. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  3. package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  4. package/dist/{game-CljaDv4D.d.ts → game-Bj8G1wmD.d.ts} +102 -11
  5. package/dist/hot.d.ts +4 -4
  6. package/dist/index.d.ts +712 -118
  7. package/dist/index.js +12423 -4955
  8. package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
  9. package/dist/playtest.d.ts +6 -10
  10. package/dist/playtest.js +47 -24
  11. package/dist/react-css.d.ts +62 -0
  12. package/dist/react-css.js +591 -0
  13. package/dist/react.d.ts +2 -2
  14. package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
  15. package/dist/terrain-jobs-worker.d.ts +2 -0
  16. package/dist/terrain-jobs-worker.js +130 -0
  17. package/dist/ui-layer.js +59 -8
  18. package/dist/world.d.ts +766 -73
  19. package/dist/world.js +9307 -3543
  20. package/gpl/recipes/export_world.py +18 -1
  21. package/mcp/blender-server.mjs +7 -4
  22. package/mcp/blender.mjs +3 -4
  23. package/mcp/engine-server.mjs +2 -2
  24. package/mcp/servers.mjs +4 -4
  25. package/package.json +15 -9
  26. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  27. package/patches/three@0.185.1.patch +6594 -700
  28. package/scripts/apply-three-patch.mjs +62 -4
  29. package/src/animation-blend.ts +264 -0
  30. package/src/animation-composition.ts +362 -0
  31. package/src/animation-layers.ts +260 -0
  32. package/src/animation-root-motion.ts +283 -0
  33. package/src/animation.ts +896 -0
  34. package/src/assets.ts +1303 -0
  35. package/src/atmosphere/index.ts +335 -0
  36. package/src/atmosphere/luts.ts +298 -0
  37. package/src/atmosphere/params.ts +323 -0
  38. package/src/audio.ts +912 -0
  39. package/src/billboard.ts +124 -0
  40. package/src/bone-lengths.ts +157 -0
  41. package/src/camera-shake.ts +116 -0
  42. package/src/canvas-layer.ts +47 -0
  43. package/src/clip-audit.ts +401 -0
  44. package/src/clustered-batch.ts +492 -0
  45. package/src/clustered-mesh.ts +638 -0
  46. package/src/compute-driven.ts +176 -0
  47. package/src/compute-timing.ts +318 -0
  48. package/src/config.ts +593 -0
  49. package/src/debug.ts +82 -0
  50. package/src/engine-render-hook.ts +25 -0
  51. package/src/entities.ts +79 -0
  52. package/src/entity-snapshot.ts +53 -0
  53. package/src/flight.ts +683 -0
  54. package/src/fluid-field.ts +748 -0
  55. package/src/fluid-particles.ts +1253 -0
  56. package/src/frame-budget.ts +1368 -0
  57. package/src/game.ts +2390 -0
  58. package/src/geometry-capture.ts +1098 -0
  59. package/src/gpu-class.ts +160 -0
  60. package/src/gpu-frame-observation.ts +424 -0
  61. package/src/gpu-readback.ts +143 -0
  62. package/src/gpu-scene-bvh.ts +464 -0
  63. package/src/grounding.ts +100 -0
  64. package/src/hot.ts +161 -0
  65. package/src/import-meta.d.ts +13 -0
  66. package/src/index.ts +1536 -0
  67. package/src/input.ts +690 -0
  68. package/src/instanced-batch-lod.ts +283 -0
  69. package/src/instanced-batch.ts +274 -0
  70. package/src/interpolation.ts +129 -0
  71. package/src/launch-diagnostics.ts +161 -0
  72. package/src/loop.ts +564 -0
  73. package/src/matrix-world.ts +245 -0
  74. package/src/merge-parts.ts +812 -0
  75. package/src/model-lod.ts +1315 -0
  76. package/src/net-protocol.ts +333 -0
  77. package/src/net-session.ts +477 -0
  78. package/src/net.ts +80 -0
  79. package/src/ocean/fft.ts +72 -0
  80. package/src/ocean/spectral.ts +728 -0
  81. package/src/particle-significance.ts +102 -0
  82. package/src/particles.ts +648 -0
  83. package/src/path-follow.ts +175 -0
  84. package/src/picking.ts +250 -0
  85. package/src/pipeline-census.ts +1566 -0
  86. package/src/platform.ts +210 -0
  87. package/src/playtest.ts +839 -0
  88. package/src/pointer-events.ts +411 -0
  89. package/src/pose-measure.ts +435 -0
  90. package/src/profiling/FrameCounters.ts +231 -0
  91. package/src/profiling/Spans.ts +548 -0
  92. package/src/profiling/opacity-convention.ts +21 -0
  93. package/src/profiling/render-list-validate.ts +175 -0
  94. package/src/profiling/render-trap-audit.ts +84 -0
  95. package/src/profiling/scene-warning.ts +190 -0
  96. package/src/profiling/span-probes.ts +191 -0
  97. package/src/profiling/unlit-foliage-warning.ts +149 -0
  98. package/src/projection-apply.ts +1529 -0
  99. package/src/projection-marker.ts +142 -0
  100. package/src/projection-plan.ts +1258 -0
  101. package/src/projection-skinned.ts +419 -0
  102. package/src/projection-stability.ts +409 -0
  103. package/src/projection-uniform.ts +328 -0
  104. package/src/random.ts +41 -0
  105. package/src/react-css.ts +604 -0
  106. package/src/react-glyphs.ts +114 -0
  107. package/src/react-host.ts +576 -0
  108. package/src/react-layout.ts +265 -0
  109. package/src/react.ts +60 -0
  110. package/src/render/alpha-antialiasing.ts +159 -0
  111. package/src/render/batched-velocity.ts +126 -0
  112. package/src/render/chain.ts +1021 -0
  113. package/src/render/daylight.ts +189 -0
  114. package/src/render/depth-pyramid.ts +596 -0
  115. package/src/render/foliage-alpha.ts +166 -0
  116. package/src/render/material-key.ts +60 -0
  117. package/src/render/mesh-pool.ts +144 -0
  118. package/src/render/probe-volume.ts +1668 -0
  119. package/src/render/resolution-subrect.ts +253 -0
  120. package/src/render/velocity.ts +442 -0
  121. package/src/render/virtual-shadow-pages.ts +827 -0
  122. package/src/render/virtual-shadow-partial.ts +174 -0
  123. package/src/render/virtual-shadow.ts +3330 -0
  124. package/src/render/world-impostor-surface.ts +722 -0
  125. package/src/render/world-impostor.ts +558 -0
  126. package/src/render-camera-cull.ts +441 -0
  127. package/src/render-pass-budget.ts +501 -0
  128. package/src/renderProjection.ts +758 -0
  129. package/src/renderer-config.ts +127 -0
  130. package/src/renderer.ts +1847 -0
  131. package/src/replay-protocol.ts +85 -0
  132. package/src/replay.ts +205 -0
  133. package/src/resolution-scaler.ts +819 -0
  134. package/src/rig-preparation.ts +271 -0
  135. package/src/ripple-field.ts +432 -0
  136. package/src/scale.ts +109 -0
  137. package/src/scene.ts +239 -0
  138. package/src/schedule.ts +155 -0
  139. package/src/skeletal-mesh.ts +61 -0
  140. package/src/skeleton.ts +100 -0
  141. package/src/snow-field.ts +744 -0
  142. package/src/softbody-topology.ts +269 -0
  143. package/src/softbody.ts +516 -0
  144. package/src/sprite-animator.ts +222 -0
  145. package/src/startup-readiness.ts +386 -0
  146. package/src/state.ts +66 -0
  147. package/src/static-transform.ts +274 -0
  148. package/src/storage-buffer.ts +253 -0
  149. package/src/streaming.ts +308 -0
  150. package/src/target-fps.ts +92 -0
  151. package/src/terrain-jobs-worker.ts +17 -0
  152. package/src/terrain-jobs.ts +353 -0
  153. package/src/textures.ts +39 -0
  154. package/src/tracers.ts +237 -0
  155. package/src/ui-bridge.ts +368 -0
  156. package/src/ui-hit-regions.ts +380 -0
  157. package/src/ui-layer.ts +83 -0
  158. package/src/ui-state.ts +220 -0
  159. package/src/version.ts +2 -0
  160. package/src/viewport.ts +253 -0
  161. package/src/warmup.ts +1357 -0
  162. package/src/water-surface.ts +384 -0
  163. package/src/wave-field.ts +524 -0
  164. package/src/world-capabilities.ts +131 -0
  165. package/src/world-cell-proxy.ts +392 -0
  166. package/src/world-cells.ts +10564 -0
  167. package/src/world-gpu-scene.ts +3354 -0
  168. package/src/world-heightmap.ts +82 -0
  169. package/src/world-package.ts +469 -0
  170. package/src/world-passes.ts +582 -0
  171. package/src/world-region.ts +17 -0
  172. package/src/world-terrain-splat.ts +564 -0
  173. package/src/world-tiles.ts +3826 -0
  174. package/src/world-topology.ts +370 -0
  175. package/src/world-validate.ts +48 -0
  176. package/src/world.ts +805 -0
@@ -0,0 +1,3330 @@
1
+ import {
2
+ Box3,
3
+ type BufferGeometry,
4
+ type Camera,
5
+ type DirectionalLight,
6
+ Frustum,
7
+ type InstancedMesh,
8
+ Matrix4,
9
+ type Mesh,
10
+ Object3D,
11
+ type OrthographicCamera,
12
+ PCFShadowMap,
13
+ PCFSoftShadowMap,
14
+ type RenderTarget,
15
+ Sphere,
16
+ VSMShadowMap,
17
+ Vector3,
18
+ } from "three";
19
+ import {
20
+ Fn,
21
+ If,
22
+ Stack,
23
+ abs,
24
+ and,
25
+ dFdx,
26
+ dFdy,
27
+ float,
28
+ getShadowMaterial,
29
+ length,
30
+ max,
31
+ min,
32
+ mix,
33
+ positionWorld,
34
+ property,
35
+ reference,
36
+ renderGroup,
37
+ shadow,
38
+ shadowPositionWorld,
39
+ smoothstep,
40
+ uniform,
41
+ vec3,
42
+ vec4,
43
+ } from "three/tsl";
44
+ import {
45
+ AssignNode,
46
+ type Node,
47
+ type NodeBuilder,
48
+ type NodeFrame,
49
+ ShadowBaseNode,
50
+ type UniformNode,
51
+ } from "three/webgpu";
52
+ import { lodChainOf } from "../model-lod.js";
53
+ import { shadowRedrawGpuMs } from "../render-pass-budget.js";
54
+ import { DEFAULT_TARGET_FPS } from "../target-fps.js";
55
+ import {
56
+ DirectionalClipmap,
57
+ type IBoundsLike,
58
+ type IClipWindow,
59
+ type IPageRect,
60
+ type IVector3Like,
61
+ ShadowInvalidationTracker,
62
+ containsPages,
63
+ pageArea,
64
+ pageSpan,
65
+ parsePageKey,
66
+ projectBounds,
67
+ unionPageRect,
68
+ } from "./virtual-shadow-pages.js";
69
+ import {
70
+ type IPartialPass,
71
+ type IPartialShadowNode,
72
+ installPartialRender,
73
+ pixelRect,
74
+ } from "./virtual-shadow-partial.js";
75
+
76
+ /** One clipmap axis' view of a world region, as the interval it covers in light space. */
77
+ type ILightAxisRange = { low: number; high: number };
78
+
79
+ /**
80
+ * Why a level owes a render: not at all, a window that moved, or an invalidation that asked and
81
+ * waited out its delay. The render it finally takes is counted against this, so a level the frame's
82
+ * single budget passed over is not counted twice.
83
+ */
84
+ type RenderReason = 0 | 1 | 2;
85
+ const REASON_NONE: RenderReason = 0;
86
+ const REASON_MOVE: RenderReason = 1;
87
+ const REASON_INVALIDATION: RenderReason = 2;
88
+
89
+ /**
90
+ * Options for {@link VirtualShadowNode}. Every value is a mechanism parameter; the light's own
91
+ * `shadow` keeps bias, normalBias, intensity, map type and filter, exactly as with a stock shadow.
92
+ */
93
+ export interface IVirtualShadowOptions {
94
+ /**
95
+ * Half-width of each clip level's window in world units, finest first and strictly
96
+ * increasing. Default `[16, 48, 144]`: three windows, each three times wider than the last.
97
+ */
98
+ readonly clipExtents?: readonly number[];
99
+ /** Texels per level edge. Default: the light's `shadow.mapSize.width`. */
100
+ readonly mapSize?: number;
101
+ /**
102
+ * Texels per edge of each level's mover map — the map tracked casters draw into every frame.
103
+ * Default: `mapSize`, the cached levels' own density, so a caster keeps the edge it had at rest
104
+ * while it moves and does not pop to a crisper one when it settles. Lower it to buy back fill
105
+ * on a weak GPU; the soft edge it costs is on the mover only.
106
+ */
107
+ readonly moverMapSize?: number;
108
+ /**
109
+ * Fraction of a level's extent inside which a fragment still selects that level, `(0, 1]`,
110
+ * default 0.9 — the outer ring falls through to the next level so the edge is never sampled.
111
+ * `selectionGuard` minus `refreshStep`, since a window trails its centre by that much. One value
112
+ * for every level, or one per level finest first, the last entry standing in for the rest.
113
+ */
114
+ readonly selectionGuard?: number | readonly number[];
115
+ /**
116
+ * Fraction of a level's extent its window may trail the followed centre by before it re-renders,
117
+ * `[0, selectionGuard)`, default 0.125 — `refreshStep: 0` keeps the old one-texel step. The step
118
+ * is rounded to a whole number of that level's texels, so a walking camera re-renders a level
119
+ * ~`1/refreshStep` times less often while the shadow texels stay on one fixed world grid. Costs
120
+ * that much of `selectionGuard`, which it is already reduced by, so a window never reaches past
121
+ * the trailing edge of a map rendered before the centre moved. One value for every level, or one
122
+ * per level finest first, the last entry standing in for the rest — the fine level is the one a
123
+ * walking camera re-renders most, so it is the one that wants the larger step.
124
+ */
125
+ readonly refreshStep?: number | readonly number[];
126
+ /**
127
+ * Let a level buy itself a wider `refreshStep` out of what its own last render cost, default true.
128
+ *
129
+ * A level render is a whole scene draw, so the engine cannot know what one is worth until it has
130
+ * paid for it: the node measures the draw it just took and smooths that reading, and a level whose
131
+ * smoothed cost is a large share of the frame period is re-rendered less often. This is automatic
132
+ * because the value it reacts to is a measurement, not a setting — a game sets nothing, and a
133
+ * cheap level is never widened and behaves exactly as before. The widened trail is capped by the
134
+ * window's own margin, so the camera stays inside the region that level serves and everything that
135
+ * level serves stays inside the map; a level with no such margin is never widened at all.
136
+ *
137
+ * `false` puts every level back on the `refreshStep` it was given, which is also what a harness
138
+ * that wants to count today's renders uses.
139
+ * `?tnAdaptiveRefresh=0` in the page URL makes the default `false` from the node's first setup.
140
+ */
141
+ readonly adaptiveRefresh?: boolean;
142
+ /**
143
+ * Fraction of the display period a level's smoothed render cost may take before its refresh trail
144
+ * widens, `(0, 1]`, default 0.4.
145
+ *
146
+ * The period is the frame's own `deltaTime`, capped at the 60 fps frame (16.7 ms). The cap is what
147
+ * keeps the budget honest: the frame that renders an expensive level is itself long because of that
148
+ * render, so reading the share against its own inflated delta would count the cost twice and let
149
+ * the very level that needs adapting pass its own test. At 60 Hz the cap is the frame itself; on a
150
+ * 120 Hz panel the same render is twice the share it is at 60; below 60 the cap holds the budget
151
+ * at the 60 fps frame rather than growing with the stall. Below the share nothing changes at all,
152
+ * and above it the trail widens in proportion to the overshoot,
153
+ * because that is the ratio between what the level costs and what a frame can afford to spend on
154
+ * it — a level four times over the share refreshs about four times less often, until the cap
155
+ * below it runs out.
156
+ */
157
+ readonly expensiveRefreshShare?: number;
158
+ /**
159
+ * Raise the finest level's texel size gate while its own render is too expensive for the frame, default
160
+ * true.
161
+ *
162
+ * The same measurement adaptive refresh reads — the smoothed cost of the level's own last render,
163
+ * against the share of the frame it may take — drives a second, independent adaptation: a level
164
+ * whose render is over budget sizes its gate up in steps of 1.5 until it is affordable again, up
165
+ * to 8 times the configured gate, and halves it back toward 1 once the render is comfortably under
166
+ * half the budget. The gate only ever judges a caster by its size (see `minCasterTexels`), so this
167
+ * drops the tiniest props first and never a building, and a level that is cheap is never touched:
168
+ * it stays at scale 1 and submits exactly what it did before.
169
+ *
170
+ * Coarse levels always stay at scale 1 so resolved casters survive the handover.
171
+ * `false` pins every level at scale 1, which is also what a harness that wants today's draw
172
+ * counts uses.
173
+ */
174
+ readonly adaptiveCasterGate?: boolean;
175
+ /**
176
+ * How long a level waits after its own last render before an invalidation may re-render it, in
177
+ * seconds. One value for every level, or one per level finest first, the last entry standing in
178
+ * for the rest. Default `0.25 * extent / finestExtent` — 0.25 s, 1 s and 3.33 s for extents
179
+ * 24 / 96 / 320 — and `0` renders on the very next frame, which is what the node did before.
180
+ *
181
+ * A streamed world invalidates its shadows on every residency update, and a cell admitted at the
182
+ * ring edge lands in the coarsest window: the level that redraws for it is the one paying for the
183
+ * whole ring's wide casters, ten times a second where movement alone asks for two. A level
184
+ * waiting out its delay keeps the map and window it has, which is already right for every static
185
+ * caster in it, so only a newly streamed caster is missing — the trade is that a far tree's
186
+ * shadow can appear up to the delay late (3.33 s at extent 320, invisible on a level whose texel
187
+ * is wider than the tree). A window that moved is never delayed: that is a different reason, and
188
+ * it is not this option's.
189
+ */
190
+ readonly invalidationDelay?: number | readonly number[];
191
+ /**
192
+ * How far behind the window centre each level camera sits, in world units. Default 200. An
193
+ * explicit `lightDistance` *and* `depthRange` switch the level's light-space depth off the derived
194
+ * span below and back onto this pair, so a game that knows its own world sizes can still say so.
195
+ */
196
+ readonly lightDistance?: number;
197
+ /**
198
+ * Depth range each level camera covers past its centre, in world units. Default 400. Read only
199
+ * together with `lightDistance`; on its own the span is still derived.
200
+ */
201
+ readonly depthRange?: number;
202
+ /**
203
+ * Texels of a level a caster must cover before it draws into that level, default 1.5. A level's
204
+ * texel is `2 * extent / mapSize`, so the finest levels keep everything and the coarse ones keep
205
+ * only what they can resolve: a fern is a whole number of texels in a 48 m window and a fraction
206
+ * of one in a 640 m window, so it stops being drawn there and the shadow it casts is the ground
207
+ * cover's own, not its silhouette's. Set 0 to draw every caster into every level.
208
+ */
209
+ readonly minCasterTexels?: number;
210
+ /** Follow the framed receiving surface when the eye is more than one fine extent above it.
211
+ * Default true; false keeps eye follow for every camera. Walking cameras keep eye follow.
212
+ */
213
+ readonly followViewFocus?: boolean;
214
+ /** Measure receiver-plane slope across each level's texel footprint to prevent coarse acne.
215
+ * Default true; false preserves only the authored bias. Custom filterNode owns its footprint.
216
+ */
217
+ readonly receiverPlaneBias?: boolean;
218
+ /**
219
+ * Draw registered AutoLOD chains with their coarsest geometry past the finest level, default true.
220
+ * Alpha-tested and transparent casters keep casting on every level that resolves their bounds;
221
+ * dropping their whole shadow at the fine window edge loses canopy and fences.
222
+ * Geometry swaps are restored before the next level, mover map and main pass.
223
+ */
224
+ readonly shadowLodBias?: boolean;
225
+ /**
226
+ * Redraw only the pages an invalidation dirtied, default true. A level whose window did not move
227
+ * and whose asks named under half its pages renders those rectangles alone: pages casters were
228
+ * removed from are put back to the far plane first, pages casters streamed into are just drawn.
229
+ * `false` renders the whole level for every invalidation, as before. A VSM shadow map always
230
+ * renders whole, because its blur pass reads the entire map.
231
+ */
232
+ readonly partialRedraw?: boolean;
233
+ /**
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
236
+ * deformation changed is drawn through the mover maps without a `trackCaster` call; this is how
237
+ * long it must hold still before its shadow is baked into the cache again. Positive integer.
238
+ */
239
+ readonly staticAfterFrames?: number;
240
+ /** Print the `TN_VIRTUAL_SHADOW` line every `markerEvery` frames; `false` silences it. Default 300. */
241
+ readonly marker?: boolean | number;
242
+ }
243
+
244
+ /** Per-frame counters, readable any time through {@link VirtualShadowNode.stats}. */
245
+ export interface IVirtualShadowStats {
246
+ readonly frame: number;
247
+ readonly levels: number;
248
+ /** Levels whose window moved this frame and were re-rendered. */
249
+ readonly moved: number;
250
+ /** Levels re-rendered because `invalidateAll()` or explicit tracker invalidation asked for it. */
251
+ readonly invalidated: number;
252
+ /** Tracked casters, as of this frame. */
253
+ readonly movers: number;
254
+ /**
255
+ * Casters the node classified as movers by measuring them, as of this frame: a world or instance
256
+ * matrix that changed, or a deforming mesh. Counted apart from {@link movers}, which is `trackCaster`.
257
+ */
258
+ readonly autoMovers: number;
259
+ /**
260
+ * Static-to-mover and mover-to-static changes of those casters over the node's lifetime. Each one
261
+ * asks the levels for one region redraw, never a full one.
262
+ */
263
+ readonly autoTransitions: number;
264
+ /**
265
+ * Mean JS time of the classification scan per frame, in milliseconds, over the node's lifetime.
266
+ * It is the number the scan's 0.05 ms budget is judged against.
267
+ */
268
+ readonly autoScanMs: number;
269
+ /** Mover maps rendered this frame: one per level when at least one caster is tracked. */
270
+ readonly moverRenders: number;
271
+ /** Levels served from their cached map this frame. */
272
+ readonly cached: number;
273
+ /** Levels rendered this frame, for any reason. */
274
+ readonly rendered: number;
275
+ /**
276
+ * Levels that wanted a render this frame and did not get one, because the node renders at most
277
+ * one level per frame. They keep the map they already have and come due again next frame.
278
+ */
279
+ readonly deferred: number;
280
+ /**
281
+ * Levels holding a redraw for an invalidation that is still inside its own `invalidationDelay`,
282
+ * so this frame is not the frame they render on. They keep the map they have, which is right for
283
+ * every static caster in it: only a caster streamed in since is missing, and the cumulative
284
+ * `coalesced` below is what is being waited out.
285
+ */
286
+ readonly held: number;
287
+ /** Fraction of levels served from cache over the node's lifetime. */
288
+ readonly reuseRatio: number;
289
+ /**
290
+ * Level renders over the node's lifetime, for any reason. `byMove` and `byInvalidation` are the two
291
+ * the node has — a window that moved, and an invalidation that asked and waited out its delay — and
292
+ * they add up to this exactly, because a render the single per-frame budget defers is counted
293
+ * against the reason that queued it and not again when it is finally taken.
294
+ */
295
+ readonly rendersTotal: number;
296
+ /** Of those, the renders taken because a level's window moved. */
297
+ readonly byMove: number;
298
+ /**
299
+ * Pages every level's window travelled between its renders, over the node's lifetime: the sum of
300
+ * `|ΔminX| + |ΔminY|` at each render. Unlike `byMove` it does not depend on how many frames sampled
301
+ * the path, so two runs of one route at different frame rates report the same number.
302
+ */
303
+ readonly windowSteps: number;
304
+ /** Of those, the renders taken because an invalidation asked and its level's delay had passed. */
305
+ readonly byInvalidation: number;
306
+ /** Of the renders taken for an invalidation (`byInvalidation`), those whose dirty set held only streamed-in casters. */
307
+ readonly byAdmission: number;
308
+ /** Of the renders taken for an invalidation, those whose dirty set held anything else: a removed caster, a region-less ask, a caster flag change. */
309
+ readonly byEviction: number;
310
+ /** Pages the dirty set held at each render, summed over the node's lifetime. A window move counts the whole level. */
311
+ readonly pagesDirty: number;
312
+ /** Pages each render actually drew, summed over the node's lifetime. Equals pagesDirty once a partial redraw exists. */
313
+ readonly pagesRedrawn: number;
314
+ /**
315
+ * Invalidation asks that cost no render of their own, over the node's lifetime: absorbed by a
316
+ * render the level was taking anyway for its window, or merged into an ask already waiting out
317
+ * that level's delay. The two of these are the shape of the win — with the default delays a walk
318
+ * asks once a second and renders about that often, and every ask in between is counted here.
319
+ */
320
+ readonly coalesced: number;
321
+ /**
322
+ * The same four counters per level, finest first: which window moved, which invalidation asked
323
+ * for a redraw, which level took the frame's single render, and which wanted one and did not get
324
+ * it. One entry per level per frame, so a harness reading this — or the `TN_VIRTUAL_SHADOW`
325
+ * marker line, which carries it — can see which level a walk keeps re-rendering instead of only
326
+ * how many.
327
+ */
328
+ readonly perLevel: readonly IVirtualShadowLevelStat[];
329
+ }
330
+
331
+ /** One level's row of {@link IVirtualShadowStats}: 1 or 0 per counter, per frame. */
332
+ export interface IVirtualShadowLevelStat {
333
+ /** The level's clip extent, in world units. */
334
+ readonly extent: number;
335
+ readonly deferred: number;
336
+ readonly invalidated: number;
337
+ readonly moved: number;
338
+ readonly rendered: number;
339
+ /** Caster meshes this level's chosen camera layers submit this frame. Zero if it did not render. */
340
+ readonly draws: number;
341
+ /** The same bill split by kind; the five parts sum to {@link draws}. */
342
+ readonly drawsBy: IVirtualShadowDraws;
343
+ /** The adaptive caster gate's scale on this level, 1 when it is not shedding casters. */
344
+ readonly gateScale: number;
345
+ /** Casters the gate hid on the render this level took this frame; zero if it did not render. */
346
+ readonly gateHidden: number;
347
+ }
348
+
349
+ /** One level's caster draws, by the kind of mesh that submitted them. */
350
+ export interface IVirtualShadowDraws {
351
+ /** Caster batch meshes on the cluster layer, when the cluster half is the level's choice. */
352
+ readonly cluster: number;
353
+ /** Key-wide caster meshes on the wide layer, when the wide half is the level's choice. */
354
+ readonly wide: number;
355
+ /** Small casters, submitted by the finest level and by any level rendering a prewarm. */
356
+ readonly small: number;
357
+ /** Merged per-chunk shadow proxies (`<name>-shadow`), drawn with either caster half. */
358
+ readonly chunkProxy: number;
359
+ /** Everything else casting from layer 0 — terrain, props — which every level draws. */
360
+ readonly layer0: number;
361
+ /**
362
+ * GPU-scene keys: one mesh per `asset:level:part` drawn from the level's own twin of the dispatch's
363
+ * output, which is the whole of what a keyed map submits of the world. Zero unless a provider
364
+ * registered and `?tnShadowGpuKeys=1` asked, and then it replaces {@link cluster} and {@link wide}
365
+ * rather than adding to them: the keys draw the placements those two would have.
366
+ */
367
+ readonly keys: number;
368
+ }
369
+
370
+ /** The mutable tally `#probe` fills; the public row only ever reads it. */
371
+ interface IVirtualShadowDrawTally {
372
+ cluster: number;
373
+ wide: number;
374
+ small: number;
375
+ chunkProxy: number;
376
+ layer0: number;
377
+ keys: number;
378
+ }
379
+
380
+ export const VIRTUAL_SHADOW_MARKER = "TN_VIRTUAL_SHADOW";
381
+ /**
382
+ * One line per level whose refresh trail adaptive refresh widened, at most once a second: the level,
383
+ * the width of the window it re-renders, the smoothed cost of that render in ms, and the trail it
384
+ * bought. A browser run can see which level is being throttled and by how much, which is the only
385
+ * way to tell an expensive level from a slow frame.
386
+ */
387
+ export const VIRTUAL_SHADOW_REFRESH_MARKER = "TN_SHADOW_REFRESH";
388
+ /** Seconds between two `TN_SHADOW_REFRESH` lines for the same level. */
389
+ const REFRESH_MARKER_SECONDS = 1;
390
+ /**
391
+ * One line per level whose adaptive caster gate changed, at most once a second: the level, the width
392
+ * of the window it re-renders, the smoothed cost of that render, the scale its gate bought, and how
393
+ * many casters that gate hid on the render the change was read from. A browser run can see which
394
+ * level is shedding its tiniest props and by how much.
395
+ */
396
+ export const VIRTUAL_SHADOW_GATE_MARKER = "TN_SHADOW_GATE";
397
+ /** Seconds between two `TN_SHADOW_GATE` lines for the same level. */
398
+ const GATE_MARKER_SECONDS = 1;
399
+ /** How much a level's texel gate steps up per over-budget render. */
400
+ const GATE_SCALE_RISE = 1.5;
401
+ /** The most a level's texel gate may scale up, so a big building is never in reach. */
402
+ const GATE_SCALE_CAP = 8;
403
+ /** How much the gate steps back toward 1 once the render is comfortably under budget. */
404
+ const GATE_SCALE_DECAY = 0.5;
405
+ /** Below this share of the affordable budget a level's gate decays; between, it holds. */
406
+ const GATE_DECAY_SHARE = 0.5;
407
+ /**
408
+ * How much of a level's last two render costs the smoothed cost keeps, `(0, 1]`. Half and half, so a
409
+ * first draw with a cold pipeline is not the level's price for the rest of the session.
410
+ */
411
+ const COST_SMOOTHING = 0.5;
412
+ /**
413
+ * A level's first measured renders are thrown away before its cost is trusted. The first draw of a
414
+ * map compiles its shaders and uploads its textures, so it reads tens of milliseconds however cheap
415
+ * the level is; seeding the smoothed cost with that warm-up would widen the trail or raise the gate
416
+ * for a level that is not actually expensive. Two renders is enough for the pipeline to be warm.
417
+ */
418
+ const COST_WARMUP_RENDERS = 2;
419
+ /**
420
+ * The object layer tracked casters are enabled on, so each level's mover camera sees only them.
421
+ * Keep it free of other uses; the main camera never needs it (tracked objects keep layer 0).
422
+ */
423
+ export const VIRTUAL_SHADOW_MOVER_LAYER = 29;
424
+ /**
425
+ * The object layer a shadow-only caster is put on, so each level's own shadow camera renders it and
426
+ * the main camera never sees it. The level cameras have it enabled already; an object that exists
427
+ * only as a shadow caster calls `object.layers.set(VIRTUAL_SHADOW_CASTER_LAYER)`.
428
+ */
429
+ // The layer a shadow-only object is put on: a level's own shadow camera renders it, the main
430
+ // camera never sees it. Three skips an object whose layers do not meet the camera's, and it
431
+ // overwrites a shadow camera's mask with the main camera's whenever that mask is layer 0 and
432
+ // nothing else — so enabling this bit on the level cameras is also what pins their mask, and a
433
+ // caster that lives only on it is reachable from the cascade and from nothing else. 28 is below the
434
+ // mover layer and off the main camera, which renders layer 0.
435
+ export const VIRTUAL_SHADOW_CASTER_LAYER = 28;
436
+ /**
437
+ * The wide counterpart of {@link VIRTUAL_SHADOW_CASTER_LAYER}: one caster mesh per
438
+ * `asset:level:part` holding every resident cell's records, for the levels whose window covers the
439
+ * whole resident ring. A level renders exactly one of the two caster layers — whichever submits
440
+ * fewer draws, counted off the meshes themselves, because a cluster per square is a draw per square
441
+ * for the same pixels once the window holds the ring. `WorldCells` writes both halves of every key,
442
+ * so whichever a level picks is there; the main camera renders neither.
443
+ */
444
+ export const VIRTUAL_SHADOW_WIDE_CASTER_LAYER = 27;
445
+ /**
446
+ * The wide half of short assets: ferns, grass and bushes. `WorldCells` classifies assets by
447
+ * `shadows.smallCasterMetres`; every level then applies its measured texel gate, so a resolved
448
+ * shadow survives the fine window's edge. The main camera never draws this internal layer.
449
+ */
450
+ export const VIRTUAL_SHADOW_SMALL_CASTER_LAYER = 26;
451
+ /**
452
+ * The counterpart of both caster layers for a GPU-driven map: one mesh per `asset:level:part`
453
+ * drawing that key's shadow twin, so a level submits one indirect draw per key instead of one per
454
+ * grid square. `WorldCells` mints these instead of the two caster halves when a shadow level draws
455
+ * from the GPU scene (`?tnShadowGpuKeys=1`), and every level camera carries this bit, which is why
456
+ * it is not one half of a choice: a key is the whole of what a keyed map draws of the world.
457
+ */
458
+ export const VIRTUAL_SHADOW_KEY_LAYER = 25;
459
+ const DEFAULT_CLIP_EXTENTS: readonly number[] = [16, 48, 144];
460
+ const DEFAULT_MARKER_EVERY = 300;
461
+ /** Frames between markers while `?tnShadowStats=1` is on the URL: about a second a walk is long. */
462
+ const STATS_QUERY_EVERY = 60;
463
+ /**
464
+ * The invalidation delay of the *finest* level, in seconds; every other level's is this times its
465
+ * extent over the finest one. A burst of streamed invalidations is paid as one render, and the
466
+ * level that pays it is the one whose window is widest.
467
+ */
468
+ const BASE_INVALIDATION_DELAY = 0.25;
469
+ /**
470
+ * Share of GPU time a level's invalidation redraws may take when the game left `invalidationDelay`
471
+ * to the engine: a redraw that cost `c` ms waits at least `c / share` ms after the last one. A 5 ms
472
+ * redraw never reaches the base delay; a 300 ms one on an integrated GPU waits 3 s instead of 0.25 s.
473
+ */
474
+ const INVALIDATION_GPU_SHARE = 0.1;
475
+ const DEFAULT_MIN_CASTER_TEXELS = 1.5;
476
+ /** Unreal's `r.Shadow.Virtual.Cache.FramesStaticThreshold`: quiet frames before a mover is static. */
477
+ const DEFAULT_STATIC_AFTER_FRAMES = 100;
478
+ /**
479
+ * The share of the display period a level's render may cost before adaptive refresh widens its
480
+ * trail: two frames in five, 6.7 ms of a 60 Hz frame. A draw that big is worth a whole frame of its
481
+ * own, and a share rather than a millisecond count is what makes the same number mean the same thing
482
+ * on a 120 Hz panel.
483
+ */
484
+ const DEFAULT_EXPENSIVE_REFRESH_SHARE = 0.4;
485
+ /**
486
+ * The floor on a light's vertical magnitude: a horizontal window's height-to-depth conversion
487
+ * grows without limit as the sun sets.
488
+ */
489
+ const MIN_SUN_COSINE = 0.05;
490
+
491
+ /**
492
+ * World spheres one level render collects: centre, radius, shadow flags, the box's own height
493
+ * range, seven numbers each.
494
+ */
495
+ const POOL_STRIDE = 7;
496
+ /**
497
+ * How many window widths a caster may be before the window is cut out of it instead. One: an
498
+ * object wider than the window it is in is a mass, and only its height reaches the frustum.
499
+ */
500
+ const MAX_MASS_WINDOW_WIDTHS = 1;
501
+ const POOL_CASTERS = 1 << 0;
502
+
503
+ /**
504
+ * A mesh in the caster table, with the three channels the probe reads off the object rather than off
505
+ * the geometry: the bounds three's own cull would use, which `Mesh` does not declare, the
506
+ * `casterPrewarmOwed` flag `WorldCells` writes (see `SharedBatch.awaitPrewarmDraw`), and the
507
+ * `mainAdmitted` answer it publishes for a caster half (see `SharedBatch.setMainAdmitted`).
508
+ */
509
+ interface ICasterMesh extends Mesh {
510
+ boundingBox?: Box3 | null;
511
+ boundingSphere?: Sphere | null;
512
+ casterPrewarmOwed?: boolean;
513
+ mainAdmitted?: boolean;
514
+ chunkShadowProxy?: boolean;
515
+ casterMinDiameter?: number;
516
+ computeBoundingBox(): void;
517
+ computeBoundingSphere(): void;
518
+ }
519
+
520
+ /**
521
+ * One caster's memoised world values, and the inputs they were derived from.
522
+ *
523
+ * The key is the world matrix plus the local sphere and the local box's two Y values — everything
524
+ * `Sphere.applyMatrix4` and `Box3.applyMatrix4` read, and nothing else. Twenty-two doubles compare
525
+ * against the pair of matrix applies they replace, and a key that matches cannot have a different
526
+ * answer, so this is a memo on the inputs rather than a guess about whether the mesh moved. A
527
+ * caster under a frozen subtree, a streamed cell nobody touched and a walking stag are therefore
528
+ * the same case: whichever of them changed its world matrix is recomputed, and the rest are not.
529
+ *
530
+ * A fresh slot is all zeros, which no world matrix can be — its last element is 1 — so the first
531
+ * render of a caster always misses and always computes.
532
+ */
533
+ const CASTER_KEY_STRIDE = 22;
534
+ /** World centre and radius, then the box's world height range: what the pool row is written from. */
535
+ const CASTER_WORLD_STRIDE = 6;
536
+ const CASTER_STRIDE = CASTER_KEY_STRIDE + CASTER_WORLD_STRIDE;
537
+
538
+ const MOTION_STATIC = 0;
539
+ /** Drawn through the mover maps and kept out of the cached levels. */
540
+ const MOTION_MOVER = 1;
541
+ /**
542
+ * Back in the cached levels, still drawn through the mover maps until every level the redraw asked
543
+ * has rendered it, so the shadow never drops out between the two.
544
+ */
545
+ const MOTION_SETTLING = 2;
546
+
547
+ /** What the motion scan remembers of one caster mesh between frames. */
548
+ interface ICasterMotion {
549
+ /** The 16 world-matrix elements at the last scan: where the cached levels last saw it. */
550
+ readonly world: Float64Array;
551
+ /** `instanceMatrix.version` at the last scan; unused on a plain mesh. */
552
+ instanceVersion: number;
553
+ phase: typeof MOTION_STATIC | typeof MOTION_MOVER | typeof MOTION_SETTLING;
554
+ /** `pinStatic` named this mesh or an ancestor. */
555
+ pinned: boolean;
556
+ /** Consecutive scans without movement while a mover. */
557
+ quiet: number;
558
+ }
559
+
560
+ /**
561
+ * What a world publishes on its root for a shadow level to draw a map from GPU-scene keys:
562
+ * `(renderer, level) => void`, the level's own three numbers and the scene that selects against them.
563
+ *
564
+ * Engine-internal and duck-typed. `WorldCells` publishes it as `tnShadowGpuKeys`; nothing in a
565
+ * template or a manifest names it, and this module cannot import the world package to name the type,
566
+ * so the contract is the call and the flag behind it.
567
+ */
568
+ type IShadowKeyDispatch = (renderer: unknown, level: IShadowLevelNumbers) => void;
569
+
570
+ /**
571
+ * One shadow map's own three numbers, duck-typed from `world-gpu-scene`'s `IShadowLevel`: the six
572
+ * planes of this map's own shadow camera, its texel gate in world metres, and the chain level it
573
+ * draws at. Typed here rather than imported for the
574
+ * same reason as the dispatch above.
575
+ */
576
+ interface IShadowLevelNumbers {
577
+ readonly planes: Float32Array;
578
+ readonly gate: number;
579
+ readonly base: number;
580
+ }
581
+
582
+ /** A placeholder light per level: the stock shadow node reads position and target from it. */
583
+ class LevelLight extends Object3D {
584
+ readonly target = new Object3D();
585
+ shadow: DirectionalLight["shadow"];
586
+ override castShadow = true;
587
+
588
+ constructor(shadow: DirectionalLight["shadow"]) {
589
+ super();
590
+ this.shadow = shadow;
591
+ }
592
+ }
593
+
594
+ interface ILevel {
595
+ readonly light: LevelLight;
596
+ readonly shadow: DirectionalLight["shadow"];
597
+ readonly node: ReturnType<typeof shadow>;
598
+ /** Same window and placement as `shadow`, rendered every frame with only the tracked casters. */
599
+ readonly moverShadow: DirectionalLight["shadow"];
600
+ readonly moverNode: ReturnType<typeof shadow>;
601
+ readonly extent: number;
602
+ readonly extentUniform: UniformNode<"float", number>;
603
+ /**
604
+ * The light-space depth this level's last render derived: how far behind its window centre the
605
+ * camera sat, and the near/far it drew with. Held between renders, because a level that keeps its
606
+ * map is placed with the same span it drew that map with.
607
+ */
608
+ eye: number;
609
+ depthNear: number;
610
+ depthFar: number;
611
+ minX: number;
612
+ minY: number;
613
+ /** Light-space depth of the window centre when this level's map was last rendered. */
614
+ centerW: number;
615
+ /**
616
+ * 1 once this level's map has been rendered at least once, 0 until then. A fragment never
617
+ * samples a map this level has not drawn yet: with one render per frame the coarse levels are
618
+ * behind on the frame the fine one comes due, and their targets have no depth in them yet.
619
+ */
620
+ readonly mapped: UniformNode<"float", number>;
621
+ /**
622
+ * Set when an invalidation asked for a redraw that has not been rendered yet, 0 until then. The
623
+ * ask is held here instead of being consumed on the frame it arrives, so a level can wait out
624
+ * `invalidationDelay` and still redraw; a render of any reason clears it.
625
+ */
626
+ dirty: boolean;
627
+ /**
628
+ * The pages casters streamed into since this level's last render, in the clipmap's absolute page
629
+ * coordinates, or undefined while none did. An added caster only brings depth closer, so these
630
+ * pages need no clear. Meaningless while {@link dirtyAll} is set.
631
+ */
632
+ dirtyAdmit: IPageRect | undefined;
633
+ /**
634
+ * The pages any other ask touched: a removed caster, a flag change, the tracker's pages. The old
635
+ * depth in them can be wrong, so they are put back to the far plane before they are redrawn.
636
+ */
637
+ dirtyEvict: IPageRect | undefined;
638
+ /** An ask named no pages, or none inside the window, so the whole level is dirty. */
639
+ dirtyAll: boolean;
640
+ /** The rectangle this level is rendering now, set only around a partial redraw. */
641
+ pass: IPartialPass | undefined;
642
+ /** The caster interval along the light, from the centre, that the derived depth was drawn for. */
643
+ drawnSpan: ILightAxisRange;
644
+ /**
645
+ * The engine frame clock's reading when this level last rendered, in seconds. A dirty level
646
+ * re-renders for the invalidation no sooner than `invalidationDelay` after this. `-Infinity`
647
+ * until the first render, so a level invalidated before it holds a map is due immediately.
648
+ */
649
+ lastRender: number;
650
+ /**
651
+ * Why this level owes a render the frame's single budget did not grant it: {@link REASON_NONE},
652
+ * and the reason it was due otherwise. Sticky, so a level that was passed over stays due on the
653
+ * next frame instead of waiting for its window to move again — and the render it eventually takes
654
+ * is counted against the reason that queued it.
655
+ */
656
+ pending: RenderReason;
657
+ /**
658
+ * Smoothed cost of this level's own last render, in milliseconds, and 0 until it has rendered
659
+ * once. This is the only measure of what a level's render is worth there is — a level render is a
660
+ * whole scene draw — and what it buys is a wider refresh trail; see `adaptiveRefresh`.
661
+ */
662
+ costMs: number;
663
+ /**
664
+ * How many of this level's renders have been measured, warm-up included. The first
665
+ * {@link COST_WARMUP_RENDERS} are compile and upload, not the level's price, so `costMs` stays 0
666
+ * until the counter passes them and nothing adapts before it.
667
+ */
668
+ costReadings: number;
669
+ /**
670
+ * The trail this level is actually being stepped with, which is its configured `refreshStep`
671
+ * until a measurement widens it. Held so a level that got cheap again is put back rather than
672
+ * left on the trail it bought.
673
+ */
674
+ appliedStep: number;
675
+ /** Engine clock of this level's last `TN_SHADOW_REFRESH` line, in seconds. */
676
+ lastRefreshNote: number;
677
+ /**
678
+ * The adaptive caster gate's scale on this level: the factor `minCasterTexels` is multiplied by,
679
+ * 1 until a render comes in over budget. See `adaptiveCasterGate`.
680
+ */
681
+ gateScale: number;
682
+ /**
683
+ * The texel gate `#probe` last computed for this level, in world metres. Held so the level's own
684
+ * dispatch is handed the gate that render decided on, rather than recomputing it and risking the
685
+ * two answering about different numbers. 0 until the level has been probed.
686
+ */
687
+ gateMetres: number;
688
+ /**
689
+ * Casters the adaptive gate hid on this level's last render, for the `TN_SHADOW_GATE` line. Not
690
+ * reset by a frame that did not render: the line reports the render the change was read from.
691
+ */
692
+ gateHidden: number;
693
+ /** Engine clock of this level's last `TN_SHADOW_GATE` line, in seconds. */
694
+ lastGateNote: number;
695
+ /**
696
+ * Engine clock of the render whose cost the gate has already been adapted to. `#adaptiveTrails`
697
+ * changes the scale at most once per render, never twice for the same measured cost.
698
+ */
699
+ gatedRender: number;
700
+ /**
701
+ * Where this level's *rendered* map sits, relative to the centre the fragment test measures
702
+ * from. A level whose re-render was deferred still holds an older window, and its selection has
703
+ * to be made against that window rather than the followed centre: the sampler reads through this
704
+ * level's own camera, so testing against anything else is what makes a fragment reach past a
705
+ * rendered map.
706
+ */
707
+ readonly offsetU: UniformNode<"float", number>;
708
+ readonly offsetV: UniformNode<"float", number>;
709
+ /** This level's own guarded extent fraction, for the same reason. */
710
+ readonly guardUniform: UniformNode<"float", number>;
711
+ }
712
+
713
+ type ShadowWithFilter = DirectionalLight["shadow"] & { filterNode?: unknown };
714
+
715
+ const _direction = new Vector3();
716
+ const _center = new Vector3();
717
+ const _sphere = new Sphere();
718
+ const _box = new Box3();
719
+ const _size = new Vector3();
720
+ const _focus = new Vector3();
721
+ const _forward = new Vector3();
722
+ /** A level's own light frustum, read once per level render and handed to its dispatch. */
723
+ const _shadowProjection = new Matrix4();
724
+ const _oldWorld = new Matrix4();
725
+ const _shadowFrustum = new Frustum();
726
+ const _shadowPlanes = new Float32Array(24);
727
+ /** The depth row a level's map was drawn under, and the one this frame proposes: uploaded float32. */
728
+ const _drawnDepth = new Float32Array(4);
729
+ const _proposedDepth = new Float32Array(4);
730
+ /**
731
+ * `world-gpu-scene`'s `COARSEST_SHADOW_LEVEL`, duplicated rather than imported: this module must not
732
+ * know the world package, and the value is a level index the far side clamps to each asset's own.
733
+ */
734
+ const COARSEST_SHADOW_LEVEL = 1 << 20;
735
+
736
+ /** The state cached maps depend on: visible, casting, and admitted by the main pass. */
737
+ /** A skinned mesh, or one with a morph target weighted above zero: its pixels change with no matrix change. */
738
+ function deforms(mesh: Mesh): boolean {
739
+ if ((mesh as { isSkinnedMesh?: boolean }).isSkinnedMesh === true) return true;
740
+ const influences = mesh.morphTargetInfluences;
741
+ if (influences === undefined) return false;
742
+ for (const weight of influences) if (weight !== 0) return true;
743
+ return false;
744
+ }
745
+
746
+ function casterFlag(mesh: {
747
+ castShadow?: boolean;
748
+ mainAdmitted?: boolean;
749
+ userData?: { tnShadowSwap?: unknown };
750
+ visible?: boolean;
751
+ }): number {
752
+ // A mesh marked tnShadowSwap trades visibility with a twin over the same ground — terrain's
753
+ // tile and merged block, or one LOD level for the next. That flip is not a change the cached map
754
+ // must redraw for (it measured ~80 % of a walk's flips); castShadow and mainAdmitted still are,
755
+ // and the next window move redraws whatever resolution difference a LOD step left behind.
756
+ return (
757
+ (mesh.visible === true || mesh.userData?.tnShadowSwap === true ? 1 : 0) |
758
+ (mesh.castShadow === true ? 2 : 0) |
759
+ (mesh.mainAdmitted === false ? 4 : 0)
760
+ );
761
+ }
762
+
763
+ /** The per-level entry of a scalar-or-array option, the last entry standing in for the rest. */
764
+ function at(values: readonly number[], level: number): number {
765
+ return values[Math.min(level, values.length - 1)] as number;
766
+ }
767
+
768
+ /**
769
+ * The diameter a shadow level's texel gate judges one caster by: the part's own geometry radius
770
+ * times the largest instance scale `WorldCells` placed into this batch, or the mesh's own sphere
771
+ * when it publishes no scale (anything the world does not own).
772
+ */
773
+ function instanceDiameter(mesh: Mesh, sphereRadius: number): number {
774
+ const scale = (mesh as Mesh & { casterInstanceScale?: number }).casterInstanceScale;
775
+ if (scale === undefined || scale <= 0) return sphereRadius * 2;
776
+ const geometry = mesh.geometry;
777
+ if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
778
+ const radius = geometry.boundingSphere?.radius;
779
+ if (radius === undefined || radius <= 0) return sphereRadius * 2;
780
+ return radius * 2 * scale;
781
+ }
782
+
783
+ /** Keep each stock node's source-owned settings aligned with the public light shadow. */
784
+ function syncShadowSettings(
785
+ source: DirectionalLight["shadow"],
786
+ target: DirectionalLight["shadow"],
787
+ ): void {
788
+ target.bias = source.bias;
789
+ target.biasNode = source.biasNode;
790
+ target.blurSamples = source.blurSamples;
791
+ target.intensity = source.intensity;
792
+ target.mapType = source.mapType;
793
+ target.normalBias = source.normalBias;
794
+ target.radius = source.radius;
795
+ (target as ShadowWithFilter).filterNode = (source as ShadowWithFilter).filterNode;
796
+ }
797
+
798
+ function syncLevelShadowSettings(
799
+ source: DirectionalLight["shadow"],
800
+ levels: readonly ILevel[],
801
+ ): void {
802
+ for (const level of levels) {
803
+ syncShadowSettings(source, level.shadow);
804
+ syncShadowSettings(source, level.moverShadow);
805
+ }
806
+ }
807
+
808
+ /** The stock node's target factory, which three calls once from `setupShadow`. */
809
+ interface IStockShadowTarget {
810
+ setupRenderTarget(
811
+ shadow: unknown,
812
+ builder: NodeBuilder,
813
+ ): { shadowMap: RenderTarget; depthTexture: unknown };
814
+ }
815
+
816
+ /**
817
+ * Move a receiver input into the render group. The patched renderer skips object-group uploads for
818
+ * a settled static object, so a value in that group freezes at whatever the receiver settled with.
819
+ */
820
+ function rendered<T>(node: T): T {
821
+ // quality-allow: three's ReferenceNode has setGroup at runtime; its declaration omits it
822
+ return (node as unknown as { setGroup(group: typeof renderGroup): T }).setGroup(renderGroup);
823
+ }
824
+
825
+ /**
826
+ * Register a stock shadow node's render target with the renderer the moment the node creates it,
827
+ * inside the material build and before any bind group can sample its depth texture.
828
+ *
829
+ * three re-versions a target's depth texture on the target's *first* registration — the size
830
+ * branch of `Textures.updateRenderTarget`, which finds no recorded size — and when a bind group
831
+ * already holds that texture the re-version destroys its GPUTexture. Every submit through that bind
832
+ * group then fails with `Destroyed texture [Texture "ShadowDepthTexture"] used in a submit`, and a
833
+ * settled static object never rebuilds its bind group, so nothing is presented again. A level whose
834
+ * first render comes after the main pass bound its map — every level but the one drawn in the first
835
+ * frame, every mover map, and every level a warm-up compile binds — hit it once per scene.
836
+ * Registering at creation makes that first registration happen before anything is bound.
837
+ */
838
+ function registeredOnCreate<T>(node: T): T {
839
+ // quality-allow: Three's public node type omits the target setup hook this wrapper must replace
840
+ const stock = node as unknown as IStockShadowTarget;
841
+ const create = stock.setupRenderTarget.bind(stock);
842
+ stock.setupRenderTarget = (lightShadow, builder) => {
843
+ const made = create(lightShadow, builder);
844
+ // A renderer without three's texture manager (a test double) registers on first render.
845
+ // quality-allow: Three's public renderer type hides the manager that must register this target early
846
+ const host = builder.renderer as unknown as {
847
+ _textures?: { updateRenderTarget?(target: RenderTarget): void };
848
+ };
849
+ host._textures?.updateRenderTarget?.(made.shadowMap);
850
+ return made;
851
+ };
852
+ return node;
853
+ }
854
+
855
+ /** The stock node's render entry, called here so the mover exclusion brackets exactly one render. */
856
+ interface IRenderingShadowNode {
857
+ updateShadow(frame: NodeFrame): void;
858
+ }
859
+
860
+ /**
861
+ * One directional shadow for a whole open world: camera-centred clip levels, each snapped to its
862
+ * own texel grid and re-rendered only when its window moves. Movers never touch that cache: a
863
+ * tracked caster draws into a second, per-level mover map every frame, and a fragment takes the
864
+ * darker of the two — so a walking stag costs one small render of itself, not a render of the wood.
865
+ *
866
+ * Plugs into three's own slot, so every material in the scene receives it with no other change:
867
+ * `light.shadow.shadowNode = new VirtualShadowNode(light, { clipExtents: [16, 48, 144] })`.
868
+ *
869
+ * What it owns is mechanism: level windows, texel snapping, per-level caching, invalidation,
870
+ * level selection and the statistics. The light's `shadow` keeps bias, normal bias, intensity,
871
+ * map type and filter, and those source settings are mirrored into each stock level node before
872
+ * rendering. Per-level map sizes, cameras, `autoUpdate` and `needsUpdate` are owned by this node.
873
+ * Each level is rendered by the stock {@link ShadowNode} through the renderer's shadow-map type,
874
+ * so the look is the same code path a plain shadow uses. At most one level renders per frame,
875
+ * finest first — a level render is a whole scene draw, and a level passed over keeps the map and
876
+ * window it has, so a fragment only ever samples a map that level drew.
877
+ *
878
+ * Ported from the virtual-shadow-map prototype's clipmap and invalidation; the sparse page atlas
879
+ * is deliberately not the first cut — a page needs the scene rendered once per page, and on a
880
+ * forest of hundreds of instanced meshes three level renders are cheaper than twenty-four page
881
+ * renders. The page pool and demand pass in `virtual-shadow-pages.ts` stay ready for it.
882
+ *
883
+ * @situation crisp shadows close to the player across a large outdoor level
884
+ * @situation shadow map too coarse over a big terrain
885
+ * @situation one directional light shadow for a whole open world
886
+ * @situation shadows shimmer when the camera moves
887
+ * @constraint the light must be a DirectionalLight with `castShadow` and a target in the scene
888
+ * @constraint clipExtents are half-widths in world units, finest first, strictly increasing
889
+ * @constraint movers sort themselves: a layer-0 caster whose world matrix, instance matrix or deformation changed draws through the mover maps and leaves the cached levels, and returns to them after `staticAfterFrames` quiet frames; the cache redraws only the region it left
890
+ * @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
+ * @override bias, biasNode, normalBias, intensity, radius, blurSamples, mapType and filterNode stay on `light.shadow`; mapSize and the other options here have defaults
892
+ * @override followViewFocus: false keeps eye follow; receiverPlaneBias: false uses only authored bias
893
+ * @example
894
+ * const sun = new DirectionalLight(0xffffff, 3);
895
+ * sun.castShadow = true;
896
+ * sun.shadow.shadowNode = new VirtualShadowNode(sun, { clipExtents: [12, 40, 120] });
897
+ */
898
+ export class VirtualShadowNode extends ShadowBaseNode {
899
+ static get type(): string {
900
+ return "VirtualShadowNode";
901
+ }
902
+
903
+ readonly options: Required<
904
+ Omit<IVirtualShadowOptions, "marker" | "refreshStep" | "selectionGuard" | "invalidationDelay">
905
+ > & {
906
+ readonly markerEvery: number;
907
+ /** Per level, finest first; the last entry stands in for every level past it. */
908
+ readonly refreshStep: readonly number[];
909
+ /** The per-level `selectionGuard` each level's own window is drawn with. */
910
+ readonly selectionGuard: readonly number[];
911
+ /**
912
+ * Per level, finest first: the seconds a dirty level waits after its own last render before an
913
+ * invalidation may re-render it. Already scaled by that level's extent, so the fine levels
914
+ * answer a streamed caster promptly and the coarse ones let a burst merge into one render.
915
+ */
916
+ readonly invalidationDelay: readonly number[];
917
+ };
918
+ readonly clipmap: DirectionalClipmap;
919
+ /**
920
+ * Compatibility handle for explicit page invalidation. Automatic caster motion uses mover maps;
921
+ * callers that already update this tracker still invalidate the affected cached levels.
922
+ */
923
+ readonly tracker: ShadowInvalidationTracker;
924
+ #levels: ILevel[] = [];
925
+ #invalidateAll = false;
926
+ /** Regions handed to `invalidateRegion`, read and cleared by the next `updateBefore`. */
927
+ #regions: Array<IBoundsLike & { admission?: true; urgent?: true }> = [];
928
+ /** The same regions, resolved onto the clipmap's axes; scratch, so a frame allocates nothing. */
929
+ #projectedRegions:
930
+ | { admission: boolean; u: ILightAxisRange; urgent: boolean; v: ILightAxisRange }[]
931
+ | undefined;
932
+ #casters = new Map<string, Object3D>();
933
+ #casterChildren = new Map<string, Set<Object3D>>();
934
+ /** Per caster mesh, what the motion scan remembers; entries live as long as the mesh does. */
935
+ #motionOf = new WeakMap<Object3D, ICasterMotion>();
936
+ /** Parallel to `#casterTable`, so the per-frame scan indexes an array rather than a map. */
937
+ #motion: ICasterMotion[] = [];
938
+ /** Meshes in `MOTION_MOVER`: drawn through the mover maps, kept out of the cached levels. */
939
+ #autoMovers = new Set<ICasterMesh>();
940
+ /** Meshes in `MOTION_SETTLING`, waiting for the levels their return redraw asked. */
941
+ #autoSettling = new Set<ICasterMesh>();
942
+ /** Roots `pinStatic` was called on; resolved onto their meshes whenever the table is rebuilt. */
943
+ #pinnedRoots = new Set<Object3D>();
944
+ #autoTransitions = 0;
945
+ #autoScanTotalMs = 0;
946
+ #moverLayerStates = new Map<Object3D, { originallyEnabled: boolean; references: number }>();
947
+ #centerU: UniformNode<"float", number> = uniform(0).setGroup(renderGroup);
948
+ #centerV: UniformNode<"float", number> = uniform(0).setGroup(renderGroup);
949
+ #moversActive: UniformNode<"float", number> = uniform(0).setGroup(renderGroup);
950
+ #basisU: UniformNode<"vec3", Vector3> = uniform(new Vector3(1, 0, 0)).setGroup(renderGroup);
951
+ #basisV: UniformNode<"vec3", Vector3> = uniform(new Vector3(0, 0, 1)).setGroup(renderGroup);
952
+ #basisW: UniformNode<"vec3", Vector3> = uniform(new Vector3(0, 1, 0)).setGroup(renderGroup);
953
+ #receiverSlope = property("float", `virtualShadowReceiverSlope${String(this.id)}`);
954
+ #frame = 0;
955
+ /** 1 while this node is inside `#updateFrame`; a level render re-enters `updateBefore`. */
956
+ #updating = false;
957
+ /** Per-level counters, rebuilt each frame; see `IVirtualShadowStats.perLevel`. */
958
+ #perLevel: IVirtualShadowLevelStat[] = [];
959
+ #rendered = 0;
960
+ #served = 0;
961
+ /** Cumulative level renders and the reason each took one; see `IVirtualShadowStats`. */
962
+ #rendersTotal = 0;
963
+ #byMove = 0;
964
+ #windowSteps = 0;
965
+ #byInvalidation = 0;
966
+ #byAdmission = 0;
967
+ #byEviction = 0;
968
+ #pagesDirty = 0;
969
+ #pagesRedrawn = 0;
970
+ #coalesced = 0;
971
+ /** Read from the URL once, for the `?tnShadowStats=1` marker cadence. */
972
+ #statsRequested: boolean | undefined;
973
+ /** URL-only, web-only diagnostic; native hosts have no URL switch or alternate path. */
974
+ #levelsRequested: boolean | undefined;
975
+ /** The game's own `adaptiveRefresh`, so the URL switch read at setup never overrides it. */
976
+ readonly #adaptiveRefreshGiven: boolean | undefined;
977
+ /** Whether the game set `invalidationDelay`; only an engine-chosen delay stretches with GPU cost. */
978
+ readonly #invalidationDelayGiven: boolean;
979
+ /**
980
+ * The diagnostic's tint, one per material build, keyed weakly by the builder that owns it.
981
+ *
982
+ * It cannot live on the builder's own node cache: three replaces that cache for the duration of
983
+ * every `flowStagesNode` build, so a tint written during `setup` and read while the stock
984
+ * samplers run would be two different objects. Nor can it live on this node — one shadow node
985
+ * feeds every material compiled against it, and a `var` the first material declared is not the
986
+ * next one's.
987
+ */
988
+ #levelTints = new WeakMap<NodeBuilder, Node<"vec3">>();
989
+ #stats: IVirtualShadowStats;
990
+ #initialised = false;
991
+ #onLightRemoved = (): void => this.dispose();
992
+ /** 1 when each level derives its own light-space depth, 0 when `lightDistance`/`depthRange` pin it. */
993
+ #autoDepth = true;
994
+ /**
995
+ * Every shadow-relevant world sphere one level render collected, seven numbers each. The depth
996
+ * derivation reads it in two passes after the one pass that filled it, and it is reused
997
+ * between renders, so a level render allocates nothing for it.
998
+ */
999
+ #pool = new Float64Array(POOL_STRIDE * 256);
1000
+ #poolCount = 0;
1001
+ /**
1002
+ * The meshes under the light's root, in the order the tree walks them. Rebuilt only when the tree
1003
+ * itself changed (see `#ensureCasters`); `castShadow`, the layers and `visible` are re-read on
1004
+ * every render, because a game flips those without touching the tree.
1005
+ */
1006
+ #casterTable: ICasterMesh[] = [];
1007
+ /** Every object the table was built over, so its tree listeners can come off on the next build. */
1008
+ #casterObjects: Object3D[] = [];
1009
+ #heightSources: (Object3D & { heightAt(x: number, z: number): number })[] = [];
1010
+ /**
1011
+ * The world that can hand this node a set of keys to draw instead of its caster meshes, found on
1012
+ * the caster walk and read on the render. `undefined` unless something published
1013
+ * `tnShadowGpuKeys`, which only happens with `?tnShadowGpuKeys=1`; every level below then reads
1014
+ * exactly what it read before.
1015
+ */
1016
+ #gpuKeys: IShadowKeyDispatch | undefined;
1017
+ /** The root `#casterTable` was walked from; a re-parented light changes it. */
1018
+ #casterRoot: Object3D | null = null;
1019
+ /** Set by `childadded` / `childremoved`, which three dispatches on the object that changed. */
1020
+ #casterStale = false;
1021
+ /** The memo described by `CASTER_KEY_STRIDE`: per caster, the key it was computed from and the answer. */
1022
+ #casterMemo = new Float64Array(CASTER_STRIDE * 128);
1023
+ /**
1024
+ * What `#pollCasters` last read off each table entry: 1 for `visible`, 2 for `castShadow`,
1025
+ * 4 for withheld admission. Filled by `#ensureCasters` after polling the old table.
1026
+ */
1027
+ #casterFlags = new Uint8Array(0);
1028
+ /**
1029
+ * `childadded` and `childremoved` on every object the table was built over, which is how the table
1030
+ * learns the tree changed without walking it to find out. Shared by every object so the build
1031
+ * allocates one listener rather than one per mesh.
1032
+ *
1033
+ * The change is also an ask, not only a rebuild: a level that keeps its map across a caster
1034
+ * arriving or leaving keeps the shadow of geometry the world no longer holds, which is the ghost a
1035
+ * camera jump leaves behind when the cells under it were evicted. Marking the table stale only
1036
+ * decides what the *next* render reads, and a level that never renders is the whole problem. So the
1037
+ * child is measured and the levels covering it are asked, on the same event.
1038
+ */
1039
+ #onTreeChanged = (event: { child?: Object3D; type?: string }): void => {
1040
+ this.#casterStale = true;
1041
+ const child = event.child;
1042
+ if (child === undefined) return;
1043
+ // A removed caster's world matrix is the one it last drew with — the one the stale maps hold —
1044
+ // so it is read as it stands. An added one has not been composed into its parent yet.
1045
+ if (event.type !== "childremoved") child.updateWorldMatrix(true, false);
1046
+ // A mesh that casts nothing cannot change a map by arriving or leaving, and terrain's swap twin
1047
+ // (`tnShadowSwap`) only replaces ground already drawn. A streamed world adds and removes both on
1048
+ // every rebuild: on one walk they were most of the region invalidations that redrew the level
1049
+ // four times a second. A later `castShadow` flip is still the poll's to see.
1050
+ const mesh = child as {
1051
+ isMesh?: boolean;
1052
+ castShadow?: boolean;
1053
+ userData?: { tnShadowSwap?: unknown };
1054
+ };
1055
+ if (mesh.isMesh === true && (mesh.castShadow !== true || mesh.userData?.tnShadowSwap === true))
1056
+ return;
1057
+ this.#askAboutCaster(child, event.type === "childadded");
1058
+ };
1059
+ /** Casters the current level's size gate hid, restored the moment that render is over. */
1060
+ #hidden: Object3D[] = [];
1061
+ /** Chained meshes `#probe` put on their coarsest chain level, and the geometry each was holding. */
1062
+ #coarsened: { mesh: Mesh; geometry: BufferGeometry }[] = [];
1063
+
1064
+ constructor(light: DirectionalLight, options: IVirtualShadowOptions = {}) {
1065
+ 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) {
1069
+ throw new RangeError(
1070
+ `TN_VIRTUAL_SHADOW_INVALID: mapSize must be a positive integer, got ${String(mapSize)}.`,
1071
+ );
1072
+ }
1073
+ const moverMapSize = options.moverMapSize ?? mapSize;
1074
+ if (!Number.isInteger(moverMapSize) || moverMapSize <= 0) {
1075
+ throw new RangeError(
1076
+ `TN_VIRTUAL_SHADOW_INVALID: moverMapSize must be a positive integer, got ${String(moverMapSize)}.`,
1077
+ );
1078
+ }
1079
+ for (const [name, value] of [
1080
+ ["lightDistance", options.lightDistance ?? 200],
1081
+ ["depthRange", options.depthRange ?? 400],
1082
+ ] as const) {
1083
+ if (!Number.isFinite(value) || value <= 0) {
1084
+ throw new RangeError(
1085
+ `TN_VIRTUAL_SHADOW_INVALID: ${name} must be positive, got ${String(value)}.`,
1086
+ );
1087
+ }
1088
+ }
1089
+ const minCasterTexels = options.minCasterTexels ?? DEFAULT_MIN_CASTER_TEXELS;
1090
+ if (!Number.isFinite(minCasterTexels) || minCasterTexels < 0) {
1091
+ throw new RangeError(
1092
+ `TN_VIRTUAL_SHADOW_INVALID: minCasterTexels must be zero or positive, got ${String(minCasterTexels)}.`,
1093
+ );
1094
+ }
1095
+ const staticAfterFrames = options.staticAfterFrames ?? DEFAULT_STATIC_AFTER_FRAMES;
1096
+ if (!Number.isInteger(staticAfterFrames) || staticAfterFrames <= 0) {
1097
+ throw new RangeError(
1098
+ `TN_VIRTUAL_SHADOW_INVALID: staticAfterFrames must be a positive integer, got ${String(staticAfterFrames)}.`,
1099
+ );
1100
+ }
1101
+ const expensiveRefreshShare = options.expensiveRefreshShare ?? DEFAULT_EXPENSIVE_REFRESH_SHARE;
1102
+ if (
1103
+ !Number.isFinite(expensiveRefreshShare) ||
1104
+ expensiveRefreshShare <= 0 ||
1105
+ expensiveRefreshShare > 1
1106
+ ) {
1107
+ throw new RangeError(
1108
+ `TN_VIRTUAL_SHADOW_INVALID: expensiveRefreshShare must be in the range (0, 1], got ${String(expensiveRefreshShare)}.`,
1109
+ );
1110
+ }
1111
+ // Both halves or neither: one of the two alone cannot place a camera, so a half-specified
1112
+ // override is read as no override at all and the span is derived.
1113
+ this.#autoDepth = options.lightDistance === undefined || options.depthRange === undefined;
1114
+ // A page is a texel here: the clipmap's page snapping is exactly texel snapping.
1115
+ // The window now trails its followed centre by up to `refreshStep` extents, so the selection
1116
+ // guard gives exactly that much back: a window only reaches `1 - refreshStep` extents past the
1117
+ // centre, and `selectionGuard - refreshStep <= 1 - refreshStep` always holds.
1118
+ // Both are scalar-or-per-level, finest first, the last entry standing in for every level past
1119
+ // it — one level re-rendering on a different cadence is the whole point.
1120
+ const perLevel = (
1121
+ value: number | readonly number[],
1122
+ valid: (v: number) => boolean,
1123
+ complaint: string,
1124
+ ): number[] => {
1125
+ const values = Array.isArray(value) ? [...(value as readonly number[])] : [value as number];
1126
+ for (const entry of values) {
1127
+ if (!valid(entry)) {
1128
+ throw new RangeError(`TN_VIRTUAL_SHADOW_INVALID: ${complaint}, got ${String(entry)}.`);
1129
+ }
1130
+ }
1131
+ // One value for every level, filled in: what the node keeps is one entry per level whatever
1132
+ // the game handed it, so a caller reading `options` back sees the level it asked for.
1133
+ return values.length === 1
1134
+ ? Array.from({ length: clipExtents.length }, () => values[0] as number)
1135
+ : values;
1136
+ };
1137
+ const steps = perLevel(
1138
+ options.refreshStep ?? 0.125,
1139
+ (v) => Number.isFinite(v) && v >= 0 && v < 1,
1140
+ "refreshStep must be in the range [0, 1)",
1141
+ );
1142
+ const guards = perLevel(
1143
+ options.selectionGuard ?? 0.9,
1144
+ (v) => Number.isFinite(v) && v > 0 && v <= 1,
1145
+ "selectionGuard must be in the range (0, 1]",
1146
+ );
1147
+ for (let level = 0; level < steps.length; level += 1) {
1148
+ if ((steps[level] as number) >= (guards[level] as number)) {
1149
+ throw new RangeError(
1150
+ `TN_VIRTUAL_SHADOW_INVALID: refreshStep must be in the range [0, ${String(guards[level])}), got ${String(steps[level])}.`,
1151
+ );
1152
+ }
1153
+ }
1154
+ // The finest level's delay is the unit the rest are multiples of: a level whose window is `n`
1155
+ // times wider redraws `n` times more of the world, so it is the one that merges the most asks
1156
+ // into one render. 0.25 s on the fine levels keeps a streamed tree's shadow arriving with the
1157
+ // player; 3.33 s on the coarsest is invisible, because a texel there is wider than the tree.
1158
+ // One number is the finest level's delay and every level scales it by its own extent; a
1159
+ // per-level list is each level's own seconds, taken as it stands.
1160
+ const finest = clipExtents[0] as number;
1161
+ const validDelay = (v: number): boolean => Number.isFinite(v) && v >= 0;
1162
+ const asked = options.invalidationDelay;
1163
+ const invalidationDelay = Array.isArray(asked)
1164
+ ? perLevel(
1165
+ asked as readonly number[],
1166
+ validDelay,
1167
+ "invalidationDelay must be zero or positive",
1168
+ )
1169
+ : clipExtents.map(
1170
+ (extent) =>
1171
+ ((asked as number | undefined) ?? BASE_INVALIDATION_DELAY) * (extent / finest),
1172
+ );
1173
+ const at = (values: readonly number[], level: number): number =>
1174
+ values[Math.min(level, values.length - 1)] as number;
1175
+ const guardedExtent = clipExtents.map((_, level) => at(guards, level) - at(steps, level));
1176
+ this.clipmap = new DirectionalClipmap({
1177
+ clipExtents,
1178
+ direction: { x: 0, y: 1, z: 0 },
1179
+ pagesPerAxis: mapSize,
1180
+ refreshStep: steps,
1181
+ selectionGuard: guardedExtent,
1182
+ });
1183
+ this.tracker = new ShadowInvalidationTracker(this.clipmap);
1184
+ const marker = options.marker ?? DEFAULT_MARKER_EVERY;
1185
+ this.#adaptiveRefreshGiven = options.adaptiveRefresh;
1186
+ this.#invalidationDelayGiven = options.invalidationDelay !== undefined;
1187
+ this.options = {
1188
+ adaptiveCasterGate: options.adaptiveCasterGate ?? true,
1189
+ adaptiveRefresh: options.adaptiveRefresh ?? true,
1190
+ clipExtents: [...clipExtents],
1191
+ depthRange: options.depthRange ?? 400,
1192
+ expensiveRefreshShare,
1193
+ invalidationDelay,
1194
+ lightDistance: options.lightDistance ?? 200,
1195
+ mapSize,
1196
+ minCasterTexels,
1197
+ moverMapSize,
1198
+ markerEvery: marker === false ? 0 : marker === true ? DEFAULT_MARKER_EVERY : marker,
1199
+ refreshStep: steps,
1200
+ selectionGuard: guardedExtent,
1201
+ shadowLodBias: options.shadowLodBias ?? true,
1202
+ partialRedraw: options.partialRedraw ?? true,
1203
+ staticAfterFrames,
1204
+ followViewFocus: options.followViewFocus ?? true,
1205
+ receiverPlaneBias: options.receiverPlaneBias ?? true,
1206
+ };
1207
+ this.#stats = {
1208
+ byAdmission: 0,
1209
+ byEviction: 0,
1210
+ byInvalidation: 0,
1211
+ byMove: 0,
1212
+ cached: 0,
1213
+ coalesced: 0,
1214
+ deferred: 0,
1215
+ frame: 0,
1216
+ held: 0,
1217
+ invalidated: 0,
1218
+ levels: clipExtents.length,
1219
+ moved: 0,
1220
+ moverRenders: 0,
1221
+ movers: 0,
1222
+ autoMovers: 0,
1223
+ autoScanMs: 0,
1224
+ autoTransitions: 0,
1225
+ pagesDirty: 0,
1226
+ pagesRedrawn: 0,
1227
+ perLevel: this.#perLevel,
1228
+ rendered: 0,
1229
+ rendersTotal: 0,
1230
+ reuseRatio: 1,
1231
+ windowSteps: 0,
1232
+ };
1233
+ }
1234
+
1235
+ /** The per-frame counters, as of the last `updateBefore`. */
1236
+ get stats(): IVirtualShadowStats {
1237
+ return this.#stats;
1238
+ }
1239
+
1240
+ /** The stock shadow nodes behind each level, for diagnostics. */
1241
+ get levelNodes(): readonly Node[] {
1242
+ return this.#levels.map((level) => level.node);
1243
+ }
1244
+
1245
+ /** The stock shadow nodes behind each level's mover map, for diagnostics. */
1246
+ get moverNodes(): readonly Node[] {
1247
+ return this.#levels.map((level) => level.moverNode);
1248
+ }
1249
+
1250
+ /** The placeholder lights, one per level; exposed for tests and debug views. */
1251
+ get levelLights(): readonly Object3D[] {
1252
+ return this.#levels.map((level) => level.light);
1253
+ }
1254
+
1255
+ #rememberMoverChildren(object: Object3D): void {
1256
+ let children = this.#casterChildren.get(object.uuid);
1257
+ if (children === undefined) {
1258
+ children = new Set<Object3D>();
1259
+ this.#casterChildren.set(object.uuid, children);
1260
+ }
1261
+ object.traverse((child) => {
1262
+ if (children.has(child)) return;
1263
+ children.add(child);
1264
+ this.#holdMoverLayer(child);
1265
+ });
1266
+ }
1267
+
1268
+ /** One more reason for `object` to be on the mover layer; the layer's first state is restored on the last. */
1269
+ #holdMoverLayer(object: Object3D): void {
1270
+ const state = this.#moverLayerStates.get(object);
1271
+ if (state === undefined) {
1272
+ this.#moverLayerStates.set(object, {
1273
+ originallyEnabled: object.layers.isEnabled(VIRTUAL_SHADOW_MOVER_LAYER),
1274
+ references: 1,
1275
+ });
1276
+ } else {
1277
+ state.references += 1;
1278
+ }
1279
+ object.layers.enable(VIRTUAL_SHADOW_MOVER_LAYER);
1280
+ }
1281
+
1282
+ #dropMoverLayer(object: Object3D): void {
1283
+ const state = this.#moverLayerStates.get(object);
1284
+ if (state === undefined) return;
1285
+ state.references -= 1;
1286
+ if (state.references > 0) return;
1287
+ if (state.originallyEnabled) object.layers.enable(VIRTUAL_SHADOW_MOVER_LAYER);
1288
+ else object.layers.disable(VIRTUAL_SHADOW_MOVER_LAYER);
1289
+ this.#moverLayerStates.delete(object);
1290
+ }
1291
+
1292
+ #restoreMoverChildren(id: string): void {
1293
+ const children = this.#casterChildren.get(id);
1294
+ if (children === undefined) return;
1295
+ for (const child of children) this.#dropMoverLayer(child);
1296
+ this.#casterChildren.delete(id);
1297
+ }
1298
+
1299
+ /**
1300
+ * Make an object a mover: it leaves the cached level maps and draws into every level's mover
1301
+ * map each frame, so its shadow follows it without a level render. Static geometry never
1302
+ * needs this — a level re-renders whenever its window moves anyway.
1303
+ */
1304
+ trackCaster(object: Object3D): string {
1305
+ const previous = this.#casters.get(object.uuid);
1306
+ if (previous === object) {
1307
+ this.#rememberMoverChildren(object);
1308
+ return object.uuid;
1309
+ }
1310
+ if (previous !== undefined && previous !== object) this.#restoreMoverChildren(object.uuid);
1311
+ this.#casters.set(object.uuid, object);
1312
+ this.#rememberMoverChildren(object);
1313
+ // It leaves the cached levels from here on: only the ones around it redraw without it.
1314
+ this.#askAboutCaster(object);
1315
+ return object.uuid;
1316
+ }
1317
+
1318
+ untrackCaster(objectOrId: Object3D | string): boolean {
1319
+ const id = typeof objectOrId === "string" ? objectOrId : objectOrId.uuid;
1320
+ const object = this.#casters.get(id);
1321
+ if (object === undefined) return false;
1322
+ this.#restoreMoverChildren(id);
1323
+ this.tracker.remove(id);
1324
+ const removed = this.#casters.delete(id);
1325
+ if (removed) this.#askAboutCaster(object);
1326
+ return removed;
1327
+ }
1328
+
1329
+ /**
1330
+ * Keep an object and its descendants out of automatic mover detection: they are static casters
1331
+ * whatever their transforms do, so a game that moves one takes on the stale shadow itself, or
1332
+ * calls `invalidateRegion`. Takes effect from the next frame.
1333
+ */
1334
+ pinStatic(object: Object3D): void {
1335
+ this.#pinnedRoots.add(object);
1336
+ // The table is rebuilt on the next frame, which is where the pin reaches each mesh.
1337
+ this.#casterStale = true;
1338
+ }
1339
+
1340
+ /** Force every level to re-render on the next frame — a tree fell, a door opened. */
1341
+ invalidateAll(): void {
1342
+ this.#invalidateAll = true;
1343
+ this.#regions.length = 0;
1344
+ this.tracker.invalidateAll();
1345
+ }
1346
+
1347
+ /**
1348
+ * Force only the levels whose current window covers `bounds`, on the next frame. A streamed world
1349
+ * that hands its shadow casters over has a moving near set, and a blanket `invalidateAll()` on
1350
+ * every refresh redrew all three levels for a change that lands in one corner of one of them. A
1351
+ * level whose window does not cover the region draws the same thing either way, so skipping it is
1352
+ * the same frame with fewer draws in it.
1353
+ *
1354
+ * `bounds` is `{ min: {x,y,z}, max: {x,y,z} }`, a plain object so a game can hand one over without
1355
+ * importing three. Regions are consumed by the next `updateBefore`; one that arrives before the
1356
+ * levels exist is dropped, because their first frame renders all of them anyway.
1357
+ *
1358
+ * `admission` says the region only gained casters. An added caster can only bring a texel's depth
1359
+ * closer, so a redraw for admissions alone never has to clear what the map already holds. The
1360
+ * default reads `bounds.admission === true`; an explicit second argument overrides it.
1361
+ */
1362
+ invalidateRegion(
1363
+ bounds: IBoundsLike & { admission?: boolean },
1364
+ admission = bounds.admission === true,
1365
+ ): void {
1366
+ if (this.#levels.length === 0) return;
1367
+ this.#regions.push({
1368
+ ...(admission ? { admission: true as const } : {}),
1369
+ max: { x: bounds.max.x, y: bounds.max.y, z: bounds.max.z },
1370
+ min: { x: bounds.min.x, y: bounds.min.y, z: bounds.min.z },
1371
+ });
1372
+ }
1373
+
1374
+ /**
1375
+ * The topmost object above the light: the scene it is lit in, whatever the game nested it under.
1376
+ * Walked per level render, so a `Daylight` group between the sun and the world is not the boundary
1377
+ * that hides every tree from the span below.
1378
+ */
1379
+ #root(): Object3D {
1380
+ let root = this.light as Object3D;
1381
+ while (root.parent !== null) root = root.parent;
1382
+ return root;
1383
+ }
1384
+
1385
+ /**
1386
+ * The caster set this render reads, rebuilt only when the tree it came from changed.
1387
+ *
1388
+ * `childadded` and `childremoved` are three's own events, dispatched on the parent that gained or
1389
+ * lost the object, so this is told when the tree changed rather than guessing from a version or a
1390
+ * child count — a streamed cell admitted and an evicted one in the same frame cancel out in any
1391
+ * checksum, and the shadow a level then derives is a shadow cast by geometry it never saw. A
1392
+ * re-parented light changes the root, which is compared outright. Everything a game can change
1393
+ * about a caster *without* touching the tree — `visible`, `castShadow`, the layers, its material,
1394
+ * and where it stands — is re-read on the render itself rather than held here.
1395
+ *
1396
+ * The listeners come off the previous walk before the new one starts, so an object that has left
1397
+ * the tree cannot keep marking this stale for whatever it is parented to now.
1398
+ */
1399
+ #ensureCasters(): void {
1400
+ const root = this.#root();
1401
+ if (this.#casterRoot === root && this.#casterStale === false) return;
1402
+ // A streaming arrival can coincide with an older half's admission flip. Poll the old
1403
+ // table before reseeding its flags, or that change disappears without invalidating its map.
1404
+ this.#pollCasters();
1405
+ this.#casterRoot = root;
1406
+ this.#casterStale = false;
1407
+ for (const object of this.#casterObjects) {
1408
+ object.removeEventListener("childadded", this.#onTreeChanged);
1409
+ object.removeEventListener("childremoved", this.#onTreeChanged);
1410
+ }
1411
+ this.#casterObjects.length = 0;
1412
+ this.#heightSources.length = 0;
1413
+ this.#casterTable.length = 0;
1414
+ this.#gpuKeys = undefined;
1415
+ root.traverse((object) => {
1416
+ object.addEventListener("childadded", this.#onTreeChanged);
1417
+ object.addEventListener("childremoved", this.#onTreeChanged);
1418
+ this.#casterObjects.push(object);
1419
+ if (typeof (object as { heightAt?: unknown }).heightAt === "function")
1420
+ this.#heightSources.push(object as Object3D & { heightAt(x: number, z: number): number });
1421
+ // The one place a shadow level learns that a world in this scene can hand it a set of keys to
1422
+ // draw instead of its caster meshes: a function published on the world's own root, read off
1423
+ // the same walk and on the same cadence as everything else here. Duck-typed rather than
1424
+ // imported — this module must not know the world package, and no template or manifest names it.
1425
+ // The last publisher wins, as the last height source does.
1426
+ const keys = (object as { tnShadowGpuKeys?: unknown }).tnShadowGpuKeys;
1427
+ if (typeof keys === "function") this.#gpuKeys = keys as IShadowKeyDispatch;
1428
+ if ((object as { isMesh?: unknown }).isMesh === true)
1429
+ this.#casterTable.push(object as ICasterMesh);
1430
+ });
1431
+ const wanted = this.#casterTable.length * CASTER_STRIDE;
1432
+ if (wanted > this.#casterMemo.length) {
1433
+ let size = this.#casterMemo.length;
1434
+ while (size < wanted) size *= 2;
1435
+ const grown = new Float64Array(size);
1436
+ grown.set(this.#casterMemo);
1437
+ this.#casterMemo = grown;
1438
+ }
1439
+ // Filled from what the build just read, so the first `#pollCasters` after it reports only what
1440
+ // changed since — a caster that arrived asked already, on the event that added it.
1441
+ this.#casterFlags = new Uint8Array(this.#casterTable.length);
1442
+ for (let entry = 0; entry < this.#casterTable.length; entry += 1) {
1443
+ const mesh = this.#casterTable[entry];
1444
+ if (mesh === undefined) continue;
1445
+ this.#casterFlags[entry] = casterFlag(mesh);
1446
+ }
1447
+ this.#rebuildMotion();
1448
+ }
1449
+
1450
+ /** One motion record per table entry, carried over for every mesh the previous table held. */
1451
+ #rebuildMotion(): void {
1452
+ const table = this.#casterTable;
1453
+ this.#motion.length = 0;
1454
+ for (const mesh of table) {
1455
+ let state = this.#motionOf.get(mesh);
1456
+ if (state === undefined) {
1457
+ // Seeded from where the mesh stands now: an arrival is asked about by the event that added
1458
+ // it, so its first scan has to report no movement.
1459
+ state = {
1460
+ instanceVersion: (mesh as Partial<InstancedMesh>).instanceMatrix?.version ?? 0,
1461
+ phase: MOTION_STATIC,
1462
+ pinned: false,
1463
+ quiet: 0,
1464
+ world: Float64Array.from(mesh.matrixWorld.elements),
1465
+ };
1466
+ this.#motionOf.set(mesh, state);
1467
+ }
1468
+ state.pinned = false;
1469
+ this.#motion.push(state);
1470
+ }
1471
+ for (const root of this.#pinnedRoots) {
1472
+ root.traverse((child) => {
1473
+ const state = this.#motionOf.get(child);
1474
+ if (state !== undefined) state.pinned = true;
1475
+ });
1476
+ }
1477
+ if (this.#autoMovers.size + this.#autoSettling.size === 0) return;
1478
+ // A mover whose mesh left the tree is a removed primitive: its state resets, as Unreal's does.
1479
+ const present = new Set<Object3D>(table);
1480
+ for (const set of [this.#autoMovers, this.#autoSettling]) {
1481
+ for (const mesh of set) {
1482
+ if (present.has(mesh)) continue;
1483
+ set.delete(mesh);
1484
+ this.#dropMoverLayer(mesh);
1485
+ this.#motionOf.delete(mesh);
1486
+ }
1487
+ }
1488
+ }
1489
+
1490
+ /**
1491
+ * Sort every layer-0 caster into static and moving by measuring it, once a frame, after three has
1492
+ * composed the world matrices. Movement is exact: the 16 world-matrix elements, an instance
1493
+ * matrix's version, or a deforming mesh. A wrong answer costs one region redraw — the next frame
1494
+ * that moves a caster makes it a mover again in that same frame — never a stale shadow.
1495
+ *
1496
+ * A caster that moved leaves the cached levels (the mover exclusion in `#updateFrame` reads
1497
+ * `#autoMovers`) and the levels around where they last saw it redraw at once. A mover that held
1498
+ * still for `staticAfterFrames` goes back into them with one ordinary redraw, and keeps its mover
1499
+ * map draw until every level that redraw asked has taken it, so its shadow does not drop out.
1500
+ */
1501
+ #classifyCasters(): void {
1502
+ const started = performance.now();
1503
+ this.#ensureCasters();
1504
+ const table = this.#casterTable;
1505
+ const motion = this.#motion;
1506
+ const quietFrames = this.options.staticAfterFrames;
1507
+ for (let entry = 0; entry < table.length; entry += 1) {
1508
+ const mesh = table[entry];
1509
+ const state = motion[entry];
1510
+ if (mesh === undefined || state === undefined) continue;
1511
+ if (state.pinned) {
1512
+ if (state.phase === MOTION_MOVER) this.#settle(mesh, state);
1513
+ continue;
1514
+ }
1515
+ // A caster that casts nothing, is not drawn, or is not a layer-0 object is no business of
1516
+ // this scan: the world's own batches reach the levels through `invalidateRegion` instead.
1517
+ if (!mesh.castShadow || !mesh.visible || (mesh.layers.mask & 1) === 0) continue;
1518
+ // `trackCaster` — or the game — put it on the mover layer itself, which pins it as a mover.
1519
+ if (state.phase === MOTION_STATIC && mesh.layers.isEnabled(VIRTUAL_SHADOW_MOVER_LAYER))
1520
+ continue;
1521
+ const world = state.world;
1522
+ const elements = mesh.matrixWorld.elements;
1523
+ let moved = false;
1524
+ for (let at = 0; at < 16; at += 1) {
1525
+ if (world[at] !== elements[at]) {
1526
+ moved = true;
1527
+ break;
1528
+ }
1529
+ }
1530
+ const instanced = (mesh as { isInstancedMesh?: boolean }).isInstancedMesh === true;
1531
+ if (instanced) {
1532
+ const version = (mesh as Partial<InstancedMesh>).instanceMatrix?.version ?? 0;
1533
+ if (version !== state.instanceVersion) {
1534
+ moved = true;
1535
+ state.instanceVersion = version;
1536
+ }
1537
+ }
1538
+ if (!moved && !deforms(mesh)) {
1539
+ if (state.phase === MOTION_MOVER) {
1540
+ state.quiet += 1;
1541
+ if (state.quiet >= quietFrames) this.#settle(mesh, state);
1542
+ }
1543
+ continue;
1544
+ }
1545
+ state.quiet = 0;
1546
+ if (state.phase !== MOTION_MOVER) {
1547
+ // Where the cached levels last saw it, and so what must redraw without it. An instanced
1548
+ // mesh's instances have already moved with no old extents to read, so it asks for all.
1549
+ let bounds: IBoundsLike | undefined;
1550
+ if (!instanced) {
1551
+ if (mesh.geometry.boundingSphere === null) mesh.geometry.computeBoundingSphere();
1552
+ _oldWorld.fromArray(world);
1553
+ bounds = this.#casterBounds(mesh, _oldWorld);
1554
+ }
1555
+ // Urgent: this ask is made once per caster and not by a streamed burst, so the level does
1556
+ // not wait out `invalidationDelay` with the old shadow still standing in its map.
1557
+ if (this.#levels.length === 0) {
1558
+ // The first render draws every level anyway.
1559
+ } else if (bounds === undefined) {
1560
+ this.invalidateAll();
1561
+ } else {
1562
+ this.#regions.push({ ...bounds, urgent: true });
1563
+ }
1564
+ if (state.phase === MOTION_STATIC) this.#holdMoverLayer(mesh);
1565
+ else this.#autoSettling.delete(mesh);
1566
+ state.phase = MOTION_MOVER;
1567
+ this.#autoMovers.add(mesh);
1568
+ this.#autoTransitions += 1;
1569
+ }
1570
+ world.set(elements);
1571
+ }
1572
+ this.#autoScanTotalMs += performance.now() - started;
1573
+ }
1574
+
1575
+ /** A mover goes back into the cached levels: one redraw around where it stands now. */
1576
+ #settle(mesh: ICasterMesh, state: ICasterMotion): void {
1577
+ state.phase = MOTION_SETTLING;
1578
+ state.quiet = 0;
1579
+ this.#autoMovers.delete(mesh);
1580
+ this.#autoSettling.add(mesh);
1581
+ this.#autoTransitions += 1;
1582
+ this.#askAboutCaster(mesh);
1583
+ }
1584
+
1585
+ /**
1586
+ * The world box a changed caster occupies, in the shape `invalidateRegion` takes. Its own bounds
1587
+ * where it publishes any — a world cluster's sphere is its whole grid square, which is the only
1588
+ * thing that measures where an evicted cell's instances stood — and its geometry's otherwise. A
1589
+ * caster that measures as nothing (a bare group) has no region to name, and asks every level.
1590
+ */
1591
+ #casterBounds(object: Object3D, world?: Matrix4): IBoundsLike | undefined {
1592
+ const mesh = object as ICasterMesh;
1593
+ const own = mesh.isMesh === true ? mesh.boundingSphere : undefined;
1594
+ const sphere = own ?? (mesh as Partial<Mesh>).geometry?.boundingSphere;
1595
+ if (sphere === null || sphere === undefined) {
1596
+ // A group, or a mesh whose geometry nobody measured: the long way, once per change.
1597
+ _box.setFromObject(object, false);
1598
+ if (_box.isEmpty()) return undefined;
1599
+ } else {
1600
+ _sphere.copy(sphere).applyMatrix4(world ?? mesh.matrixWorld);
1601
+ // The sphere's *diameter* is the box, not its radius: a half-radius box stops at the sphere's
1602
+ // own centre, so a caster straddling a level edge drew nothing of it into the level whose
1603
+ // window the far half of the sphere reaches, and that level kept the shadow of geometry the
1604
+ // world had just dropped.
1605
+ _box.setFromCenterAndSize(_sphere.center, _size.setScalar(_sphere.radius * 2));
1606
+ }
1607
+ return {
1608
+ max: { x: _box.max.x, y: _box.max.y, z: _box.max.z },
1609
+ min: { x: _box.min.x, y: _box.min.y, z: _box.min.z },
1610
+ };
1611
+ }
1612
+
1613
+ /** Ask the levels covering one changed caster to redraw. */
1614
+ #askAboutCaster(object: Object3D, admission = false): void {
1615
+ if (this.#levels.length === 0) return;
1616
+ // Nothing that casts: the level lights this node parents into the scene are `Object3D`s with a
1617
+ // shadow slot and no geometry, and asking for all three levels redraws on their arrival. A group
1618
+ // is asked — its children arrive on their own events, so a group added empty and filled after is
1619
+ // still asked about each mesh that lands in it.
1620
+ if ((object as { isMesh?: boolean }).isMesh !== true && object.children.length === 0) return;
1621
+ const bounds = this.#casterBounds(object);
1622
+ if (bounds === undefined) this.invalidateAll();
1623
+ else this.invalidateRegion(bounds, admission);
1624
+ }
1625
+
1626
+ /**
1627
+ * A caster can change visibility, casting or main-pass admission without touching the tree.
1628
+ * A cached map must redraw when any of them flips, or it retains a removed shadow or omits a
1629
+ * newly admitted one. Read per frame off the memoised table — one flag word per caster, no
1630
+ * matrix and no bounds —
1631
+ * and a change asks for the levels covering that caster. The table is what cut 2 made cheap; this
1632
+ * reads it, it does not walk the world.
1633
+ *
1634
+ * It runs before `#probe`'s own writes (`#restoreHidden` and the mover exclusion both set these
1635
+ * flags and put them back inside the same call), so what it compares is what the game last said.
1636
+ */
1637
+ #pollCasters(): void {
1638
+ const table = this.#casterTable;
1639
+ const flags = this.#casterFlags;
1640
+ if (flags.length !== table.length) return;
1641
+ for (let entry = 0; entry < table.length; entry += 1) {
1642
+ const mesh = table[entry];
1643
+ if (mesh === undefined) continue;
1644
+ const flag = casterFlag(mesh);
1645
+ if (flags[entry] === flag) continue;
1646
+ flags[entry] = flag;
1647
+ this.#askAboutCaster(mesh);
1648
+ }
1649
+ }
1650
+
1651
+ /** Drops the table and its listeners, which is what a disposed node owes the scene it read. */
1652
+ #dropCasters(): void {
1653
+ for (const object of this.#casterObjects) {
1654
+ object.removeEventListener("childadded", this.#onTreeChanged);
1655
+ object.removeEventListener("childremoved", this.#onTreeChanged);
1656
+ }
1657
+ this.#casterObjects.length = 0;
1658
+ this.#heightSources.length = 0;
1659
+ this.#casterTable.length = 0;
1660
+ this.#casterFlags = new Uint8Array(0);
1661
+ this.#casterRoot = null;
1662
+ this.#casterStale = false;
1663
+ }
1664
+
1665
+ /**
1666
+ * One pass over the caster set for four automatic fixes: the world bounding sphere of every
1667
+ * shadow-relevant mesh goes into the pool, every caster too small for this level's texel grid is
1668
+ * hidden until the level's render is over, every level past the finest one draws less of what it
1669
+ * can (see `shadowLodBias`), and the level's caster granularity is chosen from the two bills it
1670
+ * could pay. Mirrors the sphere three's own cull reads, so the gate drops exactly the volumes that
1671
+ * cull would have kept and the depth below measures the same boxes it will draw.
1672
+ *
1673
+ * It is a pass over the memoised caster set rather than a walk of the world: the set is rebuilt
1674
+ * only when the tree changed (see `#ensureCasters`) and each caster's world sphere is derived
1675
+ * again only when the numbers it is derived from changed (see `CASTER_KEY_STRIDE`). On the
1676
+ * reference game's map-walk that walk was 3.9% of the CPU render phase, spent re-deriving a caster
1677
+ * set that a walking camera does not change.
1678
+ *
1679
+ * Both halves of every key are on the caster-only layers, so the bill is counted off the meshes
1680
+ * themselves rather than configured: the clusters whose square the level's window holds, against
1681
+ * the key-wide meshes waiting for it. A cluster's own sphere is its whole grid square, so the
1682
+ * window test is on its centre, which is where the records actually are.
1683
+ */
1684
+ #probe(
1685
+ level: ILevel,
1686
+ centre: IVector3Like,
1687
+ index: number,
1688
+ stat: { draws: number; drawsBy: IVirtualShadowDrawTally; gateHidden: number },
1689
+ ): void {
1690
+ // The base texel gate, times the level's own adaptive scale: a level whose render is over
1691
+ // budget raises the size a caster must be before it draws here, so it sheds its tiniest props
1692
+ // first. The scale starts and usually stays at 1, so a cheap level's gate — and every count
1693
+ // 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;
1696
+ let gateHidden = 0;
1697
+ const clusterLayer = 1 << VIRTUAL_SHADOW_CASTER_LAYER;
1698
+ const wideLayer = 1 << VIRTUAL_SHADOW_WIDE_CASTER_LAYER;
1699
+ const smallLayer = 1 << VIRTUAL_SHADOW_SMALL_CASTER_LAYER;
1700
+ // A square inside the level's window is within a half-diagonal of its centre whichever way the
1701
+ // light is turned, so this is the bound that holds for every sun angle.
1702
+ const window = level.extent * Math.SQRT2;
1703
+ this.#poolCount = 0;
1704
+ this.#hidden.length = 0;
1705
+ this.#coarsened.length = 0;
1706
+ // Past the finest level, every level draws less of what it can. Set on the world here, on the
1707
+ // pass that is already reading this window's casters, and put back by `#restoreHidden` when
1708
+ // the render is over — so the mover maps and the main pass see every mesh as it was authored.
1709
+ const biased = index >= 1 && this.options.shadowLodBias;
1710
+ let clusterDraws = 0;
1711
+ let wideDraws = 0;
1712
+ // The level's bill by kind, tallied on the same pass and summed by the chosen halves once the
1713
+ // choice is known. Numbers, not objects: a frame allocates nothing for this.
1714
+ let nCluster = 0;
1715
+ let nWide = 0;
1716
+ let nSmall = 0;
1717
+ let nChunk = 0;
1718
+ let nChunkBoth = 0;
1719
+ let nLayer0 = 0;
1720
+ // A world that hands this node its GPU-scene keys draws them, not its caster meshes: one mesh
1721
+ // per key for every placement the two halves would have drawn between them. The gate below, the
1722
+ // halves' choice and their bills are the cluster path's own and do not apply — the per-placement
1723
+ // decisions are the dispatch's, made in the twin buffers this render is about to submit.
1724
+ let nKeys = 0;
1725
+ // A caster still owed its prewarm draw (see `SharedBatch.awaitPrewarmDraw`): its shadow-context
1726
+ // node is built by the next shadow render that draws it, so the level that draws it here is
1727
+ // what moves the build off the render. Both layers are therefore rendered while one is owed, since
1728
+ // the choice below would leave the other half's casters unbuilt until the level's own window
1729
+ // move. The flag is on the mesh rather than a module-level signal because the world chunk does
1730
+ // not import this one — the same channel as the `casterInstanceScale` read below.
1731
+ let prewarming = false;
1732
+ this.#ensureCasters();
1733
+ const table = this.#casterTable;
1734
+ // A launch flag can publish a provider before the backend can mint any keys. Keep the
1735
+ // fallback's wide/small layers until there are actual key meshes to replace them.
1736
+ const keyed =
1737
+ this.#gpuKeys !== undefined &&
1738
+ table.some(
1739
+ (mesh) =>
1740
+ mesh.visible &&
1741
+ mesh.castShadow &&
1742
+ (mesh.layers.mask & (1 << VIRTUAL_SHADOW_KEY_LAYER)) !== 0,
1743
+ );
1744
+ const memo = this.#casterMemo;
1745
+ for (let entry = 0; entry < table.length; entry += 1) {
1746
+ const mesh = table[entry];
1747
+ if (mesh === undefined) continue;
1748
+ if (mesh.visible !== true) continue;
1749
+ // Admission must gate the render, not just its bill: three still traverses a visible
1750
+ // caster omitted below. Reuse the texel gate's restore buffer for each level render.
1751
+ // This is placement admission, so an admitted off-frustum caster still casts.
1752
+ if (mesh.mainAdmitted === false) {
1753
+ mesh.visible = false;
1754
+ this.#hidden.push(mesh);
1755
+ continue;
1756
+ }
1757
+ // A retained-part proxy applies this gate to each original source at the draw boundary.
1758
+ if (mesh.chunkShadowProxy === true) mesh.casterMinDiameter = gate;
1759
+ // Read before the gates below: the level is going to render both caster layers either way, and
1760
+ // a caster too small for this level's texels is still one the prewarm owes a draw.
1761
+ if (mesh.casterPrewarmOwed === true) prewarming = true;
1762
+ // Reduce geometry, never the caster's presence: alpha cutouts carry canopy and fences.
1763
+ 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) {
1767
+ this.#coarsened.push({ geometry: mesh.geometry, mesh });
1768
+ mesh.geometry = coarsest;
1769
+ }
1770
+ }
1771
+ // The same two spheres three's cull uses: an instanced mesh's own, over its instances, or the
1772
+ // geometry's. `boundingSphere` is `null` on a fresh instanced mesh and undefined on a `Mesh`.
1773
+ const own = mesh.boundingSphere;
1774
+ let sphere: Sphere | null | undefined;
1775
+ if (own === undefined) {
1776
+ if (mesh.geometry.boundingSphere === null) mesh.geometry.computeBoundingSphere();
1777
+ sphere = mesh.geometry.boundingSphere;
1778
+ } else if (own === null || own.radius < 0) {
1779
+ mesh.computeBoundingSphere();
1780
+ sphere = mesh.boundingSphere;
1781
+ } else {
1782
+ sphere = own;
1783
+ }
1784
+ if (sphere === null || sphere === undefined) continue;
1785
+ // The box too, and for the same reason: a sphere has to cover a 128 m tile's diagonal, so its
1786
+ // height range is the tile's diagonal rather than the tile's relief, and the window's ground
1787
+ // is then read as 180 m of cliff.
1788
+ const ownBox = mesh.boundingBox;
1789
+ let box: Box3 | null | undefined;
1790
+ if (ownBox === undefined) {
1791
+ if (mesh.geometry.boundingBox === null) mesh.geometry.computeBoundingBox();
1792
+ box = mesh.geometry.boundingBox;
1793
+ } else if (ownBox === null) {
1794
+ mesh.computeBoundingBox();
1795
+ box = mesh.boundingBox;
1796
+ } else {
1797
+ box = ownBox;
1798
+ }
1799
+ // A mesh with no box of its own stands in its world sphere, which the world matrix and the
1800
+ // sphere already determine, so its two placeholders are never compared against anything.
1801
+ const boxYLow = box === null || box === undefined ? 0 : box.min.y;
1802
+ const boxYHigh = box === null || box === undefined ? 0 : box.max.y;
1803
+ // Two matrix applies per caster per render is what this memo replaces, and what it is keyed
1804
+ // on is what those two read: the world matrix, the local sphere, and the local box's height
1805
+ // range. A key that matches cannot have a different answer, so a mesh under a frozen subtree
1806
+ // and a stag that walked all skip and compute respectively — with nothing in the memo deciding
1807
+ // which is which. Only the box's Y is kept: `#probe` reads no other component of it, and the
1808
+ // two world spheres it does read are put back whole.
1809
+ const memoAt = entry * CASTER_STRIDE;
1810
+ const elements = mesh.matrixWorld.elements;
1811
+ let memoised = true;
1812
+ for (let e = 0; e < 16; e += 1) {
1813
+ if (memo[memoAt + e] !== elements[e]) {
1814
+ memoised = false;
1815
+ break;
1816
+ }
1817
+ }
1818
+ if (
1819
+ memoised &&
1820
+ (memo[memoAt + 16] !== sphere.center.x ||
1821
+ memo[memoAt + 17] !== sphere.center.y ||
1822
+ memo[memoAt + 18] !== sphere.center.z ||
1823
+ memo[memoAt + 19] !== sphere.radius ||
1824
+ memo[memoAt + 20] !== boxYLow ||
1825
+ memo[memoAt + 21] !== boxYHigh)
1826
+ )
1827
+ memoised = false;
1828
+ if (memoised) {
1829
+ _sphere.center.set(
1830
+ memo[memoAt + 22] as number,
1831
+ memo[memoAt + 23] as number,
1832
+ memo[memoAt + 24] as number,
1833
+ );
1834
+ _sphere.radius = memo[memoAt + 25] as number;
1835
+ _box.min.y = memo[memoAt + 26] as number;
1836
+ _box.max.y = memo[memoAt + 27] as number;
1837
+ } else {
1838
+ _sphere.copy(sphere).applyMatrix4(mesh.matrixWorld);
1839
+ if (box === null || box === undefined) {
1840
+ _box.min.set(_sphere.center.x, _sphere.center.y - _sphere.radius, _sphere.center.z);
1841
+ _box.max.set(_sphere.center.x, _sphere.center.y + _sphere.radius, _sphere.center.z);
1842
+ } else {
1843
+ _box.copy(box).applyMatrix4(mesh.matrixWorld);
1844
+ }
1845
+ for (let e = 0; e < 16; e += 1) memo[memoAt + e] = elements[e] as number;
1846
+ memo[memoAt + 16] = sphere.center.x;
1847
+ memo[memoAt + 17] = sphere.center.y;
1848
+ memo[memoAt + 18] = sphere.center.z;
1849
+ memo[memoAt + 19] = sphere.radius;
1850
+ memo[memoAt + 20] = boxYLow;
1851
+ memo[memoAt + 21] = boxYHigh;
1852
+ memo[memoAt + 22] = _sphere.center.x;
1853
+ memo[memoAt + 23] = _sphere.center.y;
1854
+ memo[memoAt + 24] = _sphere.center.z;
1855
+ memo[memoAt + 25] = _sphere.radius;
1856
+ memo[memoAt + 26] = _box.min.y;
1857
+ memo[memoAt + 27] = _box.max.y;
1858
+ }
1859
+ const at = this.#poolCount * POOL_STRIDE;
1860
+ if (at + POOL_STRIDE > this.#pool.length) {
1861
+ const grown = new Float64Array(this.#pool.length * 2);
1862
+ grown.set(this.#pool);
1863
+ this.#pool = grown;
1864
+ }
1865
+ const pool = this.#pool;
1866
+ pool[at] = _sphere.center.x;
1867
+ pool[at + 1] = _sphere.center.y;
1868
+ pool[at + 2] = _sphere.center.z;
1869
+ pool[at + 3] = _sphere.radius;
1870
+ pool[at + 4] = mesh.castShadow ? POOL_CASTERS : 0;
1871
+ pool[at + 5] = _box.min.y;
1872
+ pool[at + 6] = _box.max.y;
1873
+ this.#poolCount += 1;
1874
+ // A key is one submission for the whole world-grid square the two caster halves split into,
1875
+ // so every per-mesh decision below is the wrong unit for it: the texel gate would hide the
1876
+ // world's entire forest because the key's own geometry is small, and the halves' bills count
1877
+ // meshes this level does not draw at all. The dispatch applies this level's own gate per
1878
+ // placement, which is the decision that has an instance to make it about. Pooled like any
1879
+ // other caster — its bounds are the resident ring, exactly as a wide half's are — so the depth
1880
+ // span this level derives still covers what the keys can cast.
1881
+ if (keyed && (mesh.layers.mask & (1 << VIRTUAL_SHADOW_KEY_LAYER)) !== 0) {
1882
+ nKeys += 1;
1883
+ continue;
1884
+ }
1885
+ // Sub-texel: a caster the level cannot resolve draws no shadow a fragment could tell from
1886
+ // ground cover, so it is hidden for this render and put back immediately after it.
1887
+ //
1888
+ // On the part's own radius, not the cluster's. A world batch is one `InstancedMesh` per grid
1889
+ // square, so its sphere is ~24 m of square whatever it holds and every cluster cleared every
1890
+ // level's texel budget — the gate dropped nothing at all. `WorldCells` publishes the largest
1891
+ // instance scale it actually placed (`casterInstanceScale`), and the part's geometry radius
1892
+ // times that is the diameter a shadow map really has to resolve. A mesh without it — anything
1893
+ // but a world batch — is gated on its own sphere, exactly as before.
1894
+ // A bundled mesh is skipped by the gate: its render list is fixed when the bundle records it,
1895
+ // and a `visible = false` here would take it out of every record after the next re-record
1896
+ // while the replay still drew it this frame. See WorldCells `bundled`.
1897
+ if (
1898
+ mesh.castShadow &&
1899
+ mesh.chunkShadowProxy !== true &&
1900
+ mesh.userData.tnBundled !== true &&
1901
+ instanceDiameter(mesh, _sphere.radius) < gate
1902
+ ) {
1903
+ mesh.visible = false;
1904
+ this.#hidden.push(mesh);
1905
+ gateHidden += 1;
1906
+ continue;
1907
+ }
1908
+ // What this level would submit from each half, counted as it goes: a hidden caster submits
1909
+ // nothing, so it is not in either bill. A key-wide mesh spans the whole ring, so the level
1910
+ // keeps it whether or not the window reaches it — the cull, not the choice, decides that one.
1911
+ // A retained chunk proxy belongs to both halves and costs the same whichever one is chosen.
1912
+ const bothHalves =
1913
+ (mesh.layers.mask & (clusterLayer | wideLayer)) === (clusterLayer | wideLayer);
1914
+ if (!bothHalves && (mesh.layers.mask & clusterLayer) !== 0) {
1915
+ if (Math.hypot(_sphere.center.x - centre.x, _sphere.center.z - centre.z) <= window)
1916
+ clusterDraws += 1;
1917
+ } else if (!bothHalves && (mesh.layers.mask & wideLayer) !== 0) {
1918
+ wideDraws += 1;
1919
+ }
1920
+ // The same bill by kind, for what the level's chosen layers end up submitting. Only a caster
1921
+ // counts, and the per-chunk proxies — named `<name>-shadow`, on both caster halves —
1922
+ // are bucketed apart from the batches they stand in for so they are not counted twice. The
1923
+ // small layer and layer 0's own casters take no part in the cluster/wide choice above.
1924
+ if (mesh.castShadow === true) {
1925
+ if (mesh.name.endsWith("-shadow")) {
1926
+ if (bothHalves) nChunkBoth += 1;
1927
+ else nChunk += 1;
1928
+ } else if ((mesh.layers.mask & smallLayer) !== 0) nSmall += 1;
1929
+ else if ((mesh.layers.mask & clusterLayer) !== 0) nCluster += 1;
1930
+ else if ((mesh.layers.mask & wideLayer) !== 0) nWide += 1;
1931
+ else if ((mesh.layers.mask & 1) !== 0) nLayer0 += 1;
1932
+ }
1933
+ }
1934
+ // One of the two caster layers, never both, and the cheaper bill: clusters when the squares the
1935
+ // window covers are fewer than the keys waiting on the wide layer, one mesh per key when they are
1936
+ // not. A fraction of the ring's radius was the rule before, and a 192 m window over a 640 m ring
1937
+ // is 36% of it — clustered, at one draw per square where one per key would do. Layer 0 stays on,
1938
+ // because the terrain and everything else in the world casts from it, and a world with no caster
1939
+ // batch at all counts zero of both and takes the wide layer for nothing. A level rendering while
1940
+ // a caster is still owed its prewarm draw takes both, which is the only way the half it did not
1941
+ // pick gets its node built before the pass.
1942
+ const clustered = clusterDraws < wideDraws;
1943
+ level.shadow.camera.layers.set(0);
1944
+ // A keyed world draws its keys on their own layer, which every level camera carries: there is no
1945
+ // half to choose and no small-caster layer, because the dispatch's per-placement selection
1946
+ // answers both questions in the twin buffers this render is about to submit. The cluster layer
1947
+ // stays on for what is not the world's own keys — merged chunk proxies, and any caster a game put
1948
+ // on the caster layer itself, neither of which the GPU scene knows about.
1949
+ if (keyed) {
1950
+ level.shadow.camera.layers.enable(VIRTUAL_SHADOW_KEY_LAYER);
1951
+ level.shadow.camera.layers.enable(VIRTUAL_SHADOW_CASTER_LAYER);
1952
+ } else {
1953
+ level.shadow.camera.layers.enable(
1954
+ clustered || prewarming ? VIRTUAL_SHADOW_CASTER_LAYER : VIRTUAL_SHADOW_WIDE_CASTER_LAYER,
1955
+ );
1956
+ if (prewarming) level.shadow.camera.layers.enable(VIRTUAL_SHADOW_WIDE_CASTER_LAYER);
1957
+ // Small casters use the same texel gate as every other layer; their authored height is
1958
+ // not a reason to lose a resolved shadow when the fine window ends.
1959
+ level.shadow.camera.layers.enable(VIRTUAL_SHADOW_SMALL_CASTER_LAYER);
1960
+ }
1961
+ // Proxies belong to both halves: their covered originals no longer cast.
1962
+ // A keyed level's camera carries the key layer *and* the cluster layer, so the cluster bill is what
1963
+ // it submits from that layer whether or not the world minted keys: a keyed world mints no caster
1964
+ // half and counts zero, and a world whose keys the GPU scene could not mint keeps the halves it did
1965
+ // mint — and zeroing that bill is how a level reported 330 draws while submitting the forest's
1966
+ // cluster meshes as well. The wide and small layers are not carried by a keyed camera, so their
1967
+ // meshes are not submitted and stay at zero.
1968
+ const chosenCluster = keyed === false ? clustered || prewarming : true;
1969
+ const chosenWide = keyed === false && (!clustered || prewarming);
1970
+ const chosenSmall = keyed === false;
1971
+ const by = stat.drawsBy;
1972
+ by.cluster = chosenCluster ? nCluster : 0;
1973
+ by.chunkProxy = nChunkBoth + (chosenCluster || keyed ? nChunk : 0);
1974
+ by.wide = chosenWide ? nWide : 0;
1975
+ by.small = chosenSmall ? nSmall : 0;
1976
+ by.layer0 = nLayer0;
1977
+ by.keys = nKeys;
1978
+ stat.draws = by.cluster + by.wide + by.small + by.chunkProxy + by.layer0 + by.keys;
1979
+ stat.gateHidden = gateHidden;
1980
+ level.gateHidden = gateHidden;
1981
+ level.gateMetres = gate;
1982
+ }
1983
+
1984
+ /**
1985
+ * Put back every caster `#probe` changed: the ones its texel gate hid and the geometry
1986
+ * it swapped for a coarser chain level. The next camera
1987
+ * — the next level's map, a mover map, the main pass — sees the world as it was authored.
1988
+ */
1989
+ #restoreHidden(): void {
1990
+ for (const object of this.#hidden) object.visible = true;
1991
+ for (const held of this.#coarsened) held.mesh.geometry = held.geometry;
1992
+ this.#hidden.length = 0;
1993
+ this.#coarsened.length = 0;
1994
+ }
1995
+
1996
+ /**
1997
+ * Render one level's map — cached or mover — as the stock shadow node draws it. What a coarse
1998
+ * level draws less of is set on the world by `#probe` and put back by `#restoreHidden`, which is
1999
+ * the same seam the texel gate has always used: three hands `renderObject` the geometry but the
2000
+ * cached render object re-reads `object.geometry` itself, so only what the object holds can change
2001
+ * what a draw submits, and the renderer's own per-draw function is not ours to wrap.
2002
+ */
2003
+ #renderLevel(frame: NodeFrame, level: ILevel, mover: boolean, index = 0): void {
2004
+ // quality-allow: Three exposes updateShadow only on its internal rendering shadow node.
2005
+ const node = (mover ? level.moverNode : level.node) as unknown as IRenderingShadowNode;
2006
+ // The level's own keys, selected against this map's own three numbers, before the render that
2007
+ // submits them. A mover map is never keyed: it draws the tracked casters and nothing else, so
2008
+ // a dispatch there would put the whole world into a 256² map of one moving object.
2009
+ if (mover === false) {
2010
+ if (level.pass !== undefined) this.#aim(level, level.pass, index);
2011
+ this.#dispatchKeys(frame, level, index);
2012
+ }
2013
+ // What a level's own render costs, measured around the draw and smoothed over the reading
2014
+ // before it. A mover map is a handful of tracked casters and is never scheduled against, so it
2015
+ // is not measured, and with both adaptive refresh and the adaptive caster gate off nothing is:
2016
+ // the reading buys a wider trail and a raised gate, and is what those two switches gate. What
2017
+ // the reading buys is set on the next frame, by `#adaptiveTrails`.
2018
+ // A partial redraw is not the level's price either: the reading steers how far a window trails
2019
+ // before a whole-level render, so a rectangle's cost would widen the trail for nothing.
2020
+ if (
2021
+ mover ||
2022
+ level.pass !== undefined ||
2023
+ !(this.options.adaptiveRefresh || this.options.adaptiveCasterGate)
2024
+ ) {
2025
+ node.updateShadow(frame);
2026
+ return;
2027
+ }
2028
+ const started = performance.now();
2029
+ try {
2030
+ node.updateShadow(frame);
2031
+ } finally {
2032
+ const measured = performance.now() - started;
2033
+ level.costReadings += 1;
2034
+ // A level's first renders carry shader compilation and texture upload, not the level's
2035
+ // ongoing price; trusting them would widen a cheap level's trail or raise its gate before the
2036
+ // pipeline is warm. The cost stays 0 until the counter passes them, so nothing adapts yet.
2037
+ if (level.costReadings > COST_WARMUP_RENDERS) {
2038
+ level.costMs =
2039
+ level.costMs <= 0 ? measured : level.costMs + (measured - level.costMs) * COST_SMOOTHING;
2040
+ }
2041
+ }
2042
+ }
2043
+
2044
+ /**
2045
+ * The rectangles an invalidation-only render draws, or undefined when it draws the whole level:
2046
+ * a disabled switch, more than half the pages dirty, or a blur pass that reads the whole map.
2047
+ * Pages casters were removed from are put back to the far plane first. Pages casters streamed
2048
+ * into are only drawn, because an added caster can only bring a texel's depth closer.
2049
+ */
2050
+ #planPasses(level: ILevel, levelPages: number, frame: NodeFrame): IPartialPass[] | undefined {
2051
+ if (!this.options.partialRedraw) return undefined;
2052
+ const renderer = (frame as { renderer?: { shadowMap?: { type?: number } } }).renderer;
2053
+ if (renderer?.shadowMap?.type === VSMShadowMap) return undefined;
2054
+ if (this.#dirtyPages(level) * 2 > levelPages) return undefined;
2055
+ const passes: IPartialPass[] = [];
2056
+ const { dirtyAdmit, dirtyEvict } = level;
2057
+ if (dirtyEvict !== undefined) passes.push({ pixels: undefined, rect: dirtyEvict, reset: true });
2058
+ if (dirtyAdmit !== undefined && !containsPages(dirtyEvict, dirtyAdmit)) {
2059
+ passes.push({ pixels: undefined, rect: dirtyAdmit, reset: false });
2060
+ }
2061
+ return passes.length > 0 ? passes : undefined;
2062
+ }
2063
+
2064
+ /** Pages the level's dirty rectangles hold, the overlap of two counted twice. */
2065
+ #dirtyPages(level: ILevel): number {
2066
+ const { dirtyAdmit, dirtyEvict } = level;
2067
+ return (
2068
+ (dirtyEvict === undefined ? 0 : pageArea(dirtyEvict)) +
2069
+ (dirtyAdmit === undefined || containsPages(dirtyEvict, dirtyAdmit) ? 0 : pageArea(dirtyAdmit))
2070
+ );
2071
+ }
2072
+
2073
+ /**
2074
+ * Aim the level's shadow camera at one pass: bake the receivers' matrix from the full projection,
2075
+ * then narrow the camera to the rectangle so its depths are the whole map's and its frustum, and
2076
+ * the keys culled against it, are the rectangle's. Always from the full projection, because
2077
+ * `updateMatrices` reads whatever offset the camera still holds.
2078
+ */
2079
+ #aim(level: ILevel, pass: IPartialPass, index: number): void {
2080
+ const camera = level.shadow.camera;
2081
+ camera.clearViewOffset();
2082
+ // quality-allow: the light's own shadow owns this update, and the stock node calls it too.
2083
+ level.shadow.updateMatrices(level.light as unknown as DirectionalLight);
2084
+ const size = this.options.mapSize;
2085
+ const pageSize = this.clipmap.pageWorldSize(index);
2086
+ const { rect } = pass;
2087
+ const corners = [
2088
+ [rect.minX, rect.minY],
2089
+ [rect.maxX + 1, rect.minY],
2090
+ [rect.minX, rect.maxY + 1],
2091
+ [rect.maxX + 1, rect.maxY + 1],
2092
+ ].map(([x, y]) => {
2093
+ const at = this.clipmap.unproject({
2094
+ u: (x as number) * pageSize,
2095
+ v: (y as number) * pageSize,
2096
+ w: level.centerW,
2097
+ });
2098
+ return new Vector3(at.x, at.y, at.z);
2099
+ });
2100
+ const pixels = pixelRect(camera, size, corners);
2101
+ camera.setViewOffset(size, size, pixels.x, pixels.y, pixels.width, pixels.height);
2102
+ pass.pixels = pixels;
2103
+ }
2104
+
2105
+ /** Put the level's shadow camera back on the whole map after a partial redraw. */
2106
+ #endPartial(level: ILevel): void {
2107
+ if (level.pass === undefined) return;
2108
+ level.pass = undefined;
2109
+ level.shadow.camera.clearViewOffset();
2110
+ }
2111
+
2112
+ /**
2113
+ * Hand this level's set to whatever published keys on the world's root, in the three numbers that
2114
+ * are the map's own and not the main camera's: its own light frustum, the window centre its map
2115
+ * was rendered with, the texel gate `#probe` just decided on, and the chain level it draws at.
2116
+ *
2117
+ * A no-op without a publisher, which is the flag's whole off state. The frustum comes from
2118
+ * `updateMatrices`, which is what the stock node calls inside `updateShadow` and which positions
2119
+ * this level's own shadow camera from its light — so the planes are the ones the render about to
2120
+ * happen is made with, rather than last render's, and are read before it rather than after.
2121
+ *
2122
+ * `base` mirrors `#probe`: past the finest level every caster here is drawn coarsened, so the
2123
+ * dispatch floors every asset at its own coarsest chain level. Past-the-end is clamped per asset
2124
+ * on the far side, because no asset in this scene has told this node how long its chain is.
2125
+ */
2126
+ #dispatchKeys(frame: NodeFrame, level: ILevel, index: number): void {
2127
+ const keys = this.#gpuKeys;
2128
+ if (keys === undefined) return;
2129
+ const shadow = level.shadow;
2130
+ // #aim already baked the full receiver matrix before narrowing a partial camera.
2131
+ // quality-allow: the light's own shadow owns this update, and the stock node calls it too.
2132
+ if (level.pass === undefined) shadow.updateMatrices(level.light as unknown as DirectionalLight);
2133
+ _shadowProjection.multiplyMatrices(
2134
+ shadow.camera.projectionMatrix,
2135
+ shadow.camera.matrixWorldInverse,
2136
+ );
2137
+ _shadowFrustum.setFromProjectionMatrix(_shadowProjection);
2138
+ const planes = _shadowPlanes;
2139
+ for (const [at, plane] of _shadowFrustum.planes.entries()) {
2140
+ const offset = at * 4;
2141
+ planes[offset] = plane.normal.x;
2142
+ planes[offset + 1] = plane.normal.y;
2143
+ planes[offset + 2] = plane.normal.z;
2144
+ planes[offset + 3] = plane.constant;
2145
+ }
2146
+ // Every compute leaves the one node frame every node shares with its fields at their bare
2147
+ // defaults — `scene` among them, which `Nodes.getNodeFrame()` sets with no arguments
2148
+ // (three.webgpu.js:56215, reached from `Renderer.compute` at 62235) and nothing puts back; the
2149
+ // restore at 62249 is `renderId` and nothing else. Three re-establishes that frame per draw
2150
+ // (56224), which is why a compute *outside* a render is harmless — but this one is inside the
2151
+ // draw `updateShadow` is about to run in, and it reads the scene off the frame it is handed
2152
+ // (45602) to save the scene state before rendering it. So the render's own frame is put back
2153
+ // around the dispatch, which is all the kernel needed it for.
2154
+ const { camera, material, object, scene } = frame;
2155
+ try {
2156
+ keys(frame.renderer, {
2157
+ base: index >= 1 && this.options.shadowLodBias ? COARSEST_SHADOW_LEVEL : 0,
2158
+ gate: level.gateMetres,
2159
+ planes,
2160
+ });
2161
+ } finally {
2162
+ frame.camera = camera;
2163
+ frame.material = material;
2164
+ frame.object = object;
2165
+ frame.scene = scene;
2166
+ }
2167
+ }
2168
+
2169
+ /**
2170
+ * Step each level's window with the trail its own render cost can afford, before the clipmap
2171
+ * computes this frame's windows. Nothing here runs unless adaptive refresh is on, and a level
2172
+ * under the share comes out of it with the step it was configured with — the same number, so the
2173
+ * same window, so the same counts.
2174
+ *
2175
+ * The widening is proportional to the overshoot: a level costing `n` times the share refreshs
2176
+ * about `n` times less often, because that is the ratio between what the level costs and what a
2177
+ * frame can afford to spend on it. It is then capped by the window's own margin, which is what
2178
+ * makes it safe rather than merely useful:
2179
+ *
2180
+ * ```
2181
+ * trail ≤ extent − extent × guard = extent × (1 − guard)
2182
+ * ```
2183
+ *
2184
+ * `extent` is the rendered window's half-width, and `extent × guard` is the half-width around that
2185
+ * window's own centre within which a fragment is served by this level at all — the camera's own
2186
+ * surroundings, measured from the map rather than from the centre being followed, which is what
2187
+ * the selection's offsets are for. The inequality says the window may trail the camera by
2188
+ * everything that region does not already use, so the camera stays inside the region its own level
2189
+ * serves, and everything the level serves stays inside the map it is served from. A level with no
2190
+ * margin left (`guard: 1`, or a step already at it) is never widened at all.
2191
+ */
2192
+ #adaptiveTrails(frame: NodeFrame, now: number): void {
2193
+ const trails = this.options.adaptiveRefresh;
2194
+ const gates = this.options.adaptiveCasterGate;
2195
+ if (!trails && !gates) return;
2196
+ // The period is the frame's own, so the share is read against the panel this is running on —
2197
+ // but never longer than the 60 fps frame. The frame that renders a costly level is long because
2198
+ // of that very render, so its own delta would inflate the budget by the cost being judged and
2199
+ // the level would pass its own test; capping at 16.7 ms keeps a 120 Hz frame stricter and stops
2200
+ // a stall from widening the budget with it. A frame that carries no clock — a harness, a held
2201
+ // frame — is just the cap.
2202
+ const delta = (frame as { deltaTime?: number }).deltaTime ?? 0;
2203
+ const periodMs = Math.min(
2204
+ delta > 0 ? delta * 1000 : Number.POSITIVE_INFINITY,
2205
+ 1000 / DEFAULT_TARGET_FPS,
2206
+ );
2207
+ const affordableMs = this.options.expensiveRefreshShare * periodMs;
2208
+ this.#levels.forEach((level, index) => {
2209
+ if (trails) {
2210
+ const base = at(this.options.refreshStep, index);
2211
+ // What is left of that margin once the clipmap has rounded the step to a whole number of
2212
+ // texels: it rounds up by at most half of one, and one of those is `extent / mapSize` of
2213
+ // extent, so the trail it actually steps by is still inside the margin. A level with no such
2214
+ // margin left is held at the step it was given and is not widened at all.
2215
+ const margin = Math.max(
2216
+ base,
2217
+ 1 - at(this.options.selectionGuard, index) - 1 / this.options.mapSize,
2218
+ );
2219
+ const step = Math.min(base * Math.max(1, level.costMs / affordableMs), margin);
2220
+ if (step !== level.appliedStep) {
2221
+ this.clipmap.setRefreshStep(index, step);
2222
+ level.appliedStep = step;
2223
+ if (step > base && now - level.lastRefreshNote >= REFRESH_MARKER_SECONDS) {
2224
+ level.lastRefreshNote = now;
2225
+ console.info(
2226
+ `${VIRTUAL_SHADOW_REFRESH_MARKER} level=${String(index)} width=${String(2 * level.extent)} ms=${level.costMs.toFixed(1)} trail=${step.toFixed(3)}`,
2227
+ );
2228
+ }
2229
+ }
2230
+ }
2231
+ if (gates) this.#adaptGate(level, index, affordableMs, now);
2232
+ });
2233
+ }
2234
+
2235
+ /**
2236
+ * Step one level's adaptive caster gate from the cost of the render it just took, at most once per
2237
+ * render. A level over the affordable share raises its gate by half until it is affordable or the
2238
+ * cap is reached; one comfortably under half the share halves its gate back toward 1. Between the
2239
+ * two it holds — that band is the hysteresis, so a level on the budget does not oscillate. A level
2240
+ * that has not rendered has no reading and is never touched.
2241
+ */
2242
+ #adaptGate(level: ILevel, index: number, affordableMs: number, now: number): void {
2243
+ // A coarse texel is already the resolution gate. Cost must not raise it to 12 texels
2244
+ // (15 m at 320@512), which erases resolved canopy when the fine map hands over.
2245
+ if (index > 0) return;
2246
+ if (level.lastRender === Number.NEGATIVE_INFINITY) return;
2247
+ if (level.gatedRender === level.lastRender) return;
2248
+ level.gatedRender = level.lastRender;
2249
+ if (level.costMs <= 0) return;
2250
+ let scale = level.gateScale;
2251
+ if (level.costMs > affordableMs) {
2252
+ scale = Math.min(GATE_SCALE_CAP, scale * GATE_SCALE_RISE);
2253
+ } else if (level.costMs < affordableMs * GATE_DECAY_SHARE) {
2254
+ scale = Math.max(1, scale * GATE_SCALE_DECAY);
2255
+ }
2256
+ if (scale === level.gateScale) return;
2257
+ level.gateScale = scale;
2258
+ if (now - level.lastGateNote < GATE_MARKER_SECONDS) return;
2259
+ level.lastGateNote = now;
2260
+ console.info(
2261
+ `${VIRTUAL_SHADOW_GATE_MARKER} level=${String(index)} width=${String(2 * level.extent)} ms=${level.costMs.toFixed(1)} scale=${scale.toFixed(3)} hidden=${String(level.gateHidden)}`,
2262
+ );
2263
+ }
2264
+
2265
+ /**
2266
+ * The light-space depth one level needs, from what can actually shadow its window: every caster
2267
+ * whose own extent reaches the window, turned into light space along the sun. A caster and its
2268
+ * receiver share u/v, so overlap on those axes is sufficient, regardless of the centre's depth.
2269
+ *
2270
+ * The u/v box is what bounds the window sideways, so the depth is the only free axis, and every
2271
+ * object that overlaps that box has already been found: the pool is the whole candidate set and
2272
+ * this pass over it costs no second walk of the world. The height comes from each box rather than each
2273
+ * sphere, because a sphere has to cover a 128 m tile's diagonal and would report 180 m of cliff
2274
+ * where the tile has 15 m of it.
2275
+ */
2276
+ #deriveDepth(level: ILevel, centre: IVector3Like): ILightAxisRange | undefined {
2277
+ const pool = this.#pool;
2278
+ const count = this.#poolCount;
2279
+ const { basisU, basisV, basisW } = this.clipmap;
2280
+ const extent = level.extent;
2281
+ // The box's own reach, in each of the three light axes: sideways is bounded, so a point in the
2282
+ // window is at most this far along either of them.
2283
+ const side = extent * Math.SQRT2;
2284
+ // A caster wider than the window is not standing in it, it is a mass the window is cut out of:
2285
+ // its own span along the light is the whole world's, and the only part of it this frustum can
2286
+ // ever hold is the height of its box.
2287
+ const fits = extent * 2 * MAX_MASS_WINDOW_WIDTHS;
2288
+ const sin = basisW.y;
2289
+ // A sun on or below the horizon needs the fallback span rather than division by almost zero.
2290
+ if (sin < MIN_SUN_COSINE) return undefined;
2291
+ const heightReach = extent * (Math.abs(basisU.y) + Math.abs(basisV.y));
2292
+ // Everything that writes depth: the casters whose bounding sphere reaches into the window's
2293
+ // u/v box. A receiver writes no depth, so a piece of ground that only receives is not in the
2294
+ // frustum at all, however tall it is — that is the whole reason this is not a fixed range.
2295
+ let low = Number.POSITIVE_INFINITY;
2296
+ let high = Number.NEGATIVE_INFINITY;
2297
+ for (let index = 0; index < count; index += 1) {
2298
+ const at = index * POOL_STRIDE;
2299
+ if (((pool[at + 4] as number) & POOL_CASTERS) === 0) continue;
2300
+ const radius = pool[at + 3] as number;
2301
+ const dx = (pool[at] as number) - centre.x;
2302
+ const dy = (pool[at + 1] as number) - centre.y;
2303
+ const dz = (pool[at + 2] as number) - centre.z;
2304
+ const u = Math.abs(dx * basisU.x + dy * basisU.y + dz * basisU.z);
2305
+ const v = Math.abs(dx * basisV.x + dy * basisV.y + dz * basisV.z);
2306
+ if (u > side + radius || v > side + radius) continue;
2307
+ const along = dx * basisW.x + dy * basisW.y + dz * basisW.z;
2308
+ const boxLow = pool[at + 5] as number;
2309
+ const boxHigh = pool[at + 6] as number;
2310
+ if (radius * 2 > fits) {
2311
+ // A mass, not a caster in the window: the only part of it this frustum can hold is the
2312
+ // height of its box. Solve y = centre.y + u*U.y + v*V.y + w*W.y across the window;
2313
+ // multiplying by W.y instead clips tall instances inside a wide batch at low sun angles.
2314
+ const from = (boxLow - centre.y - heightReach) / sin;
2315
+ const to = (boxHigh - centre.y + heightReach) / sin;
2316
+ if (from < low) low = from;
2317
+ if (to > high) high = to;
2318
+ continue;
2319
+ }
2320
+ // The u/v overlap already includes every caster in a receiver's light-space column.
2321
+ if (along - radius < low) low = along - radius;
2322
+ if (along + radius > high) high = along + radius;
2323
+ }
2324
+ if (!Number.isFinite(low)) return undefined;
2325
+ const span = high - low;
2326
+ if (!(span > 0)) return undefined;
2327
+ // Two per cent of slack, and never less than a metre: the pool holds bounding spheres, which
2328
+ // round up, and a caster a shadow-map texel taller than the window's own ground must still draw.
2329
+ const margin = Math.max(1, span * 0.02);
2330
+ level.eye = high + margin;
2331
+ level.depthNear = margin;
2332
+ level.depthFar = margin + span;
2333
+ return { high, low };
2334
+ }
2335
+
2336
+ /**
2337
+ * Derive a level's depth, or keep the depth its map was drawn with. The span is always measured;
2338
+ * a rectangle whose casters all fit inside the drawn span keeps the drawn camera, so the texels it
2339
+ * does not redraw still decode as they were written. Only a caster beyond that span moves the
2340
+ * encoding, and the depth-row check then makes the render whole.
2341
+ */
2342
+ #measureDepth(level: ILevel, centre: IVector3Like, keep: boolean): void {
2343
+ const { eye, depthNear, depthFar, drawnSpan } = level;
2344
+ const measured = this.#deriveDepth(level, centre);
2345
+ if (measured === undefined) return;
2346
+ if (keep && measured.low >= drawnSpan.low && measured.high <= drawnSpan.high) {
2347
+ level.eye = eye;
2348
+ level.depthNear = depthNear;
2349
+ level.depthFar = depthFar;
2350
+ return;
2351
+ }
2352
+ drawnSpan.low = measured.low;
2353
+ drawnSpan.high = measured.high;
2354
+ }
2355
+
2356
+ /** Put a level's camera on its window with the depth it last derived, and hold both maps to it. */
2357
+ #place(level: ILevel, centre: IVector3Like): void {
2358
+ const { basisW } = this.clipmap;
2359
+ level.light.position.set(
2360
+ centre.x + basisW.x * level.eye,
2361
+ centre.y + basisW.y * level.eye,
2362
+ centre.z + basisW.z * level.eye,
2363
+ );
2364
+ level.light.updateMatrixWorld(true);
2365
+ this.#setDepth(level.shadow.camera, level);
2366
+ // The mover map is the same window with the tracked casters in it, so it is the same column.
2367
+ this.#setDepth(level.moverShadow.camera, level);
2368
+ }
2369
+
2370
+ /** Hand a level's own cameras the depth it derived, when it is not the depth they already hold. */
2371
+ #setDepth(camera: OrthographicCamera, level: ILevel): void {
2372
+ if (camera.near === level.depthNear && camera.far === level.depthFar) return;
2373
+ camera.near = level.depthNear;
2374
+ camera.far = level.depthFar;
2375
+ camera.updateProjectionMatrix();
2376
+ }
2377
+
2378
+ /** Read the uploaded depth row without recomposing the camera that drew retained texels. */
2379
+ #readDepthRow(level: ILevel, into: Float32Array): void {
2380
+ const row = level.shadow.matrix.elements;
2381
+ for (let at = 0; at < 4; at += 1) into[at] = row[2 + at * 4] as number;
2382
+ }
2383
+
2384
+ #init(): void {
2385
+ if (this.#initialised) return;
2386
+ this.#initialised = true;
2387
+ const source = this.light as DirectionalLight;
2388
+ source.addEventListener("removed", this.#onLightRemoved);
2389
+ let shadowColor: ReturnType<typeof getShadowMaterial>["colorNode"] = null;
2390
+ this.options.clipExtents.forEach((extent, index) => {
2391
+ const levelShadow = source.shadow.clone();
2392
+ syncShadowSettings(source.shadow, levelShadow);
2393
+ levelShadow.mapSize.set(this.options.mapSize, this.options.mapSize);
2394
+ levelShadow.camera.left = -extent;
2395
+ levelShadow.camera.right = extent;
2396
+ levelShadow.camera.top = extent;
2397
+ levelShadow.camera.bottom = -extent;
2398
+ levelShadow.camera.near = 1;
2399
+ levelShadow.camera.far = this.options.lightDistance + this.options.depthRange;
2400
+ levelShadow.camera.updateProjectionMatrix();
2401
+ // The caster-only layer, so a mesh that exists to be a shadow caster draws into this level's
2402
+ // map and not into the main pass. It also fixes this camera's layer mask, which three would
2403
+ // otherwise take from the main camera.
2404
+ levelShadow.camera.layers.enable(VIRTUAL_SHADOW_CASTER_LAYER);
2405
+ // The same pin for the key layer a GPU-driven map draws on, which `#probe` re-asserts on
2406
+ // every render it takes; enabling it here means a level's mask is never layer 0 alone, which
2407
+ // three overwrites with the main camera's.
2408
+ levelShadow.camera.layers.enable(VIRTUAL_SHADOW_KEY_LAYER);
2409
+ // Cached: the stock node renders only when asked — and not before this node has placed
2410
+ // the level, which happens in `updateBefore`. A render requested here would run on the
2411
+ // first frame from an unplaced light, and three's per-frame guard would then keep that
2412
+ // blank map as the frame's answer.
2413
+ levelShadow.autoUpdate = false;
2414
+ levelShadow.needsUpdate = false;
2415
+ const moverShadow = levelShadow.clone();
2416
+ syncShadowSettings(source.shadow, moverShadow);
2417
+ moverShadow.mapSize.set(this.options.moverMapSize, this.options.moverMapSize);
2418
+ moverShadow.camera.updateProjectionMatrix();
2419
+ moverShadow.autoUpdate = false;
2420
+ moverShadow.needsUpdate = false;
2421
+ // Only the tracked casters: the stock node keeps a camera's own layer mask when it names
2422
+ // any layer but the default.
2423
+ moverShadow.camera.layers.set(VIRTUAL_SHADOW_MOVER_LAYER);
2424
+ const light = new LevelLight(levelShadow);
2425
+ light.name = `VirtualShadowLevel${String(index)}`;
2426
+ // quality-allow: the stock shadow node reads only position, target and shadow off its light
2427
+ const node = registeredOnCreate(shadow(light as unknown as DirectionalLight, levelShadow));
2428
+ const moverNode = registeredOnCreate(
2429
+ shadow(light as unknown as DirectionalLight, moverShadow), // quality-allow: the stock node reads only position, target and shadow
2430
+ );
2431
+ if (this.options.receiverPlaneBias) {
2432
+ for (const entry of [
2433
+ { node, map: levelShadow },
2434
+ { node: moverNode, map: moverShadow },
2435
+ ]) {
2436
+ const stock = entry.node as typeof node & {
2437
+ setupShadowFilter: (
2438
+ builder: NodeBuilder,
2439
+ inputs: { shadowCoord: ReturnType<typeof vec3> },
2440
+ ) => Node;
2441
+ };
2442
+ const filter = stock.setupShadowFilter;
2443
+ stock.setupShadowFilter = (builder, inputs) => {
2444
+ // A custom filter owns its sampling footprint; leave it and all authored biases intact.
2445
+ if ((entry.map as ShadowWithFilter).filterNode)
2446
+ return filter.call(stock, builder, inputs);
2447
+ const type = builder.renderer.shadowMap.type;
2448
+ const footprint =
2449
+ type === PCFSoftShadowMap
2450
+ ? float(2)
2451
+ : type === PCFShadowMap
2452
+ ? max(rendered(reference("radius", "float", entry.map)), 0).add(1)
2453
+ : float(0.5);
2454
+ const span = rendered(reference("far", "float", entry.map.camera)).sub(
2455
+ rendered(reference("near", "float", entry.map.camera)),
2456
+ );
2457
+ const bias = this.#receiverSlope
2458
+ .mul(2 * extent)
2459
+ .div(rendered(reference("mapSize", "vec2", entry.map)).x)
2460
+ .div(span)
2461
+ .mul(footprint);
2462
+ const coord = inputs.shadowCoord;
2463
+ return filter.call(stock, builder, {
2464
+ ...inputs,
2465
+ shadowCoord: vec3(
2466
+ coord.xy,
2467
+ builder.renderer.reversedDepthBuffer ? coord.z.add(bias) : coord.z.sub(bias),
2468
+ ),
2469
+ });
2470
+ };
2471
+ }
2472
+ }
2473
+ if (this.#levelsRequested) {
2474
+ // Observe the stock sampler's actual coordinate, including normal bias and any received
2475
+ // shadow position override. Selection-space u/v cannot diagnose a projection mismatch.
2476
+ const stock = node as typeof node & {
2477
+ setupShadowFilter: (
2478
+ builder: NodeBuilder,
2479
+ inputs: { shadowCoord: ReturnType<typeof vec3> },
2480
+ ) => Node;
2481
+ };
2482
+ const filter = stock.setupShadowFilter;
2483
+ stock.setupShadowFilter = (builder, inputs) => {
2484
+ const levelTint = this.#levelTints.get(builder);
2485
+ const uv = inputs.shadowCoord;
2486
+ const inside = and(
2487
+ and(uv.x.greaterThanEqual(0), uv.x.lessThanEqual(1)),
2488
+ and(uv.y.greaterThanEqual(0), uv.y.lessThanEqual(1)),
2489
+ );
2490
+ const colour =
2491
+ index === 0
2492
+ ? vec3(1, 0, 0)
2493
+ : index === 1
2494
+ ? vec3(0, 1, 0)
2495
+ : index === 2
2496
+ ? vec3(0, 0, 1)
2497
+ : vec3(1, 1, 0);
2498
+ // No tint recorded yet means this build is not one the diagnostic set up; the stock
2499
+ // shadow then stands alone rather than reading a declaration that is not there.
2500
+ if (levelTint === undefined) return filter.call(stock, builder, inputs);
2501
+ Stack(new AssignNode(levelTint, inside.select(colour, vec3(1, 0, 1))));
2502
+ return filter.call(stock, builder, inputs);
2503
+ };
2504
+ }
2505
+ // Stock shadow colours are identical, but their node identities split the shader cache.
2506
+ // Share only that constant; each level keeps its material, camera and render bindings.
2507
+ const material = getShadowMaterial(node.light);
2508
+ shadowColor ??= material.colorNode;
2509
+ material.colorNode = shadowColor;
2510
+ const entry: ILevel = {
2511
+ appliedStep: at(this.options.refreshStep, index),
2512
+ costMs: 0,
2513
+ costReadings: 0,
2514
+ gatedRender: Number.NEGATIVE_INFINITY,
2515
+ gateHidden: 0,
2516
+ gateScale: 1,
2517
+ gateMetres: 0,
2518
+ lastGateNote: Number.NEGATIVE_INFINITY,
2519
+ depthFar: this.options.lightDistance + this.options.depthRange,
2520
+ depthNear: 1,
2521
+ dirty: false,
2522
+ dirtyAdmit: undefined,
2523
+ dirtyAll: false,
2524
+ dirtyEvict: undefined,
2525
+ drawnSpan: { high: Number.NaN, low: Number.NaN },
2526
+ pass: undefined,
2527
+ eye: this.options.lightDistance,
2528
+ extent,
2529
+ extentUniform: uniform(extent).setGroup(renderGroup),
2530
+ lastRender: Number.NEGATIVE_INFINITY,
2531
+ lastRefreshNote: Number.NEGATIVE_INFINITY,
2532
+ light,
2533
+ mapped: uniform(0).setGroup(renderGroup),
2534
+ minX: Number.NaN,
2535
+ minY: Number.NaN,
2536
+ centerW: Number.NaN,
2537
+ pending: REASON_NONE,
2538
+ offsetU: uniform(0).setGroup(renderGroup),
2539
+ offsetV: uniform(0).setGroup(renderGroup),
2540
+ guardUniform: uniform(
2541
+ this.options.selectionGuard[index] ?? this.options.selectionGuard.at(-1) ?? 0,
2542
+ ).setGroup(renderGroup),
2543
+ moverShadow,
2544
+ // One placeholder light serves both maps: the stock node reads only its placement.
2545
+ moverNode,
2546
+ node,
2547
+ shadow: levelShadow,
2548
+ };
2549
+ this.#levels.push(entry);
2550
+ // quality-allow: Three's public node type omits the render method this wrapper replaces
2551
+ installPartialRender(node as unknown as IPartialShadowNode, () => entry.pass);
2552
+ });
2553
+ }
2554
+
2555
+ override setup(builder: NodeBuilder): Node | null | undefined {
2556
+ if (builder.renderer.shadowMap.enabled === false) return null;
2557
+ // Read once, like tnShadowStats. Build no diagnostic nodes unless the URL switch is on.
2558
+ if (this.#levelsRequested === undefined) {
2559
+ const search = globalThis.location?.search ?? "";
2560
+ this.#levelsRequested = /[?&]tnShadowLevels=(?!0(?:&|$))(?!false(?:&|$))[^&]/u.test(search);
2561
+ // Counter runs: a fixed refreshStep, since the adaptive step follows measured render cost and
2562
+ // two runs of one route would move their windows at different ticks. Set once, before a frame.
2563
+ if (
2564
+ this.#adaptiveRefreshGiven === undefined &&
2565
+ /[?&]tnAdaptiveRefresh=(?:0|false)(?:&|$)/u.test(search)
2566
+ ) {
2567
+ (this.options as { adaptiveRefresh: boolean }).adaptiveRefresh = false;
2568
+ }
2569
+ }
2570
+ this.#init();
2571
+ const levels = this.#levels;
2572
+ const centerU = this.#centerU;
2573
+ const centerV = this.#centerV;
2574
+ const moversActive = this.#moversActive;
2575
+ const basisU = this.#basisU;
2576
+ const basisV = this.#basisV;
2577
+ let tint: Node<"vec3"> | undefined;
2578
+ if (this.#levelsRequested) {
2579
+ // Declared here, outside the returned function, because three runs that function's body at
2580
+ // the setup stage — which is the only stage at which the lighting stack below is still
2581
+ // accepting nodes. A `var` declared inside it lands after every use of it.
2582
+ tint = vec3(0, 1, 1).toVar(`virtualShadowLevelTint${String(this.id)}`);
2583
+ this.#levelTints.set(builder, tint);
2584
+ const outgoing = (builder.context as { outgoingLight?: Node<"vec3"> }).outgoingLight;
2585
+ if (outgoing !== undefined) {
2586
+ // Three has assembled the lighting stack before building this shadow dependency. Append
2587
+ // after its final assignments so the overlay retains every light and the shadow result.
2588
+ const stack = (
2589
+ builder as NodeBuilder & { getActiveStack(): { nodes: Node[] } | undefined }
2590
+ ).getActiveStack();
2591
+ stack?.nodes.push(new AssignNode(outgoing, mix(outgoing, tint, 0.5)));
2592
+ }
2593
+ }
2594
+ return Fn(() => {
2595
+ this.setupShadowPosition(builder);
2596
+ if (this.options.receiverPlaneBias) {
2597
+ // Derivatives must execute before the non-uniform level branches. A shared geometric
2598
+ // receiver plane supplies world-depth slope; each map scales it by its own texel and span.
2599
+ const received = vec3(shadowPositionWorld as never);
2600
+ const normal = dFdx(received).cross(dFdy(received)).toVar();
2601
+ const along = max(abs(normal.dot(this.#basisW)), max(length(normal).mul(0.0001), 1e-12));
2602
+ this.#receiverSlope.assign(
2603
+ abs(normal.dot(basisU))
2604
+ .add(abs(normal.dot(basisV)))
2605
+ .div(along),
2606
+ );
2607
+ }
2608
+ const u = positionWorld.dot(vec3(basisU as never)).sub(centerU as never);
2609
+ const v = positionWorld.dot(vec3(basisV as never)).sub(centerV as never);
2610
+ const coarsest = levels[levels.length - 1];
2611
+ if (coarsest === undefined) return vec4(1, 1, 1, 1);
2612
+ const moverResult = (level: ILevel) =>
2613
+ moversActive.greaterThan(0).select(vec4(level.moverNode as never), vec4(1, 1, 1, 1));
2614
+ // Cyan is the answer for a fragment no level sampled, so the default is written here rather
2615
+ // than left to whichever level branch a fragment happens to take.
2616
+ if (tint !== undefined) tint.assign(vec3(0, 1, 1));
2617
+ // The coarsest fallback can be unmapped; finer unmapped levels never win selection.
2618
+ // Every level is read through its own `mapped` gate. A level whose map this node has not
2619
+ // drawn yet contributes nothing rather than being sampled: with one level rendered per frame
2620
+ // the coarse levels trail the fine one, and their targets hold nothing to compare against.
2621
+ const result = vec4(1, 1, 1, 1).toVar("virtualShadowValue");
2622
+ If(coarsest.mapped.greaterThan(0), () => {
2623
+ result.assign(min(vec4(coarsest.node as never), moverResult(coarsest)));
2624
+ });
2625
+ // Coarse to fine, so the finest containing level assigns last and wins.
2626
+ for (let index = levels.length - 2; index >= 0; index -= 1) {
2627
+ const level = levels[index];
2628
+ if (level === undefined) continue;
2629
+ // This level's own window, so a level holding an older window still selects the map it
2630
+ // actually has. `u`/`v` are measured from the followed centre; `offsetU`/`offsetV` carry the
2631
+ // difference back to the rendered window's centre.
2632
+ const distance = max(abs(u.add(level.offsetU)), abs(v.add(level.offsetV))).toVar(
2633
+ `virtualShadowDistance${String(index)}`,
2634
+ );
2635
+ If(
2636
+ and(
2637
+ level.mapped.greaterThan(0),
2638
+ distance.lessThanEqual(level.extentUniform.mul(level.guardUniform)),
2639
+ ),
2640
+ () => {
2641
+ const edge = level.extentUniform.mul(level.guardUniform);
2642
+ // Use the existing unused map margin, with at least two texels for guard=1.
2643
+ const band = max(
2644
+ level.extentUniform.sub(edge),
2645
+ level.extentUniform.mul(4 / this.options.mapSize),
2646
+ );
2647
+ const weight = smoothstep(edge.sub(band), edge, distance).oneMinus();
2648
+ result.assign(mix(result, min(vec4(level.node as never), moverResult(level)), weight));
2649
+ },
2650
+ );
2651
+ }
2652
+ return result;
2653
+ // quality-allow: Three's Fn invocation loses the concrete node type.
2654
+ })() as unknown as Node;
2655
+ }
2656
+
2657
+ override updateBefore(frame: NodeFrame): undefined {
2658
+ // Three calls this once per `render()`, and a level render *is* a `render()`: the draw the
2659
+ // budget grants below re-enters this method with a new render id. Without this guard the
2660
+ // one-level-per-frame budget resets on that re-entry, so a frame with every level due draws
2661
+ // all of them — measured on `?scene=map-walk`, where the levels are re-rendered as a group
2662
+ // every time a residency update invalidates them.
2663
+ if (this.#updating) return undefined;
2664
+ this.#updating = true;
2665
+ // Three runs this from the draw of the first object that uses the node, and that draw can be the
2666
+ // first object of a `BundleGroup` the main pass is recording. Three keeps that bundle in
2667
+ // `_currentRenderBundle` and does not save it across the nested `render()` a level is: the
2668
+ // level's draws would be filed under the main bundle, and the level's own bundles leave the
2669
+ // field `null`, so the main bundle's remaining draws are recorded but never listed — a replay
2670
+ // refreshes only listed draws, so those keep the camera they were recorded with. On Machinefall
2671
+ // that froze a cell's chunk forest on screen for twenty walk steps. The levels render outside
2672
+ // the record, and the record gets its bundle back.
2673
+ // quality-allow: three 0.185 does not expose the bundle it is recording.
2674
+ const host = frame.renderer as unknown as { _currentRenderBundle?: unknown };
2675
+ const recording = host._currentRenderBundle;
2676
+ if (recording !== undefined) host._currentRenderBundle = null;
2677
+ try {
2678
+ this.#updateFrame(frame);
2679
+ } finally {
2680
+ this.#updating = false;
2681
+ if (recording !== undefined) host._currentRenderBundle = recording;
2682
+ }
2683
+ return undefined;
2684
+ }
2685
+
2686
+ /** Resident numerical terrain owns elevation; an unloaded region is not a zero-height plane. */
2687
+ #heightAt(x: number, z: number): number | undefined {
2688
+ for (const source of this.#heightSources) {
2689
+ try {
2690
+ const height = source.heightAt(x, z);
2691
+ if (!Number.isFinite(height))
2692
+ throw new Error("Virtual shadow focus received non-finite terrain height.");
2693
+ return height;
2694
+ } catch (error) {
2695
+ if (!(error instanceof Error) || !error.message.endsWith("is outside its resident region."))
2696
+ throw error;
2697
+ }
2698
+ }
2699
+ return undefined;
2700
+ }
2701
+
2702
+ /** Aerial windows follow the forward ray's received surface, without changing walking follow. */
2703
+ #viewFocus(camera: Camera, eye: Vector3): Vector3 {
2704
+ _focus.copy(eye);
2705
+ if (!this.options.followViewFocus) return _focus;
2706
+ camera.getWorldDirection(_forward);
2707
+ if (_forward.y >= 0) return _focus;
2708
+ this.#ensureCasters();
2709
+ let height = this.#heightAt(eye.x, eye.z);
2710
+ // Generic received geometry has no numerical height API. Bounds only decide whether the
2711
+ // camera is aerial; the forward ray below measures its actual surface, not a box plane.
2712
+ if (height === undefined) {
2713
+ for (const mesh of this.#casterTable) {
2714
+ if (!mesh.visible || !mesh.receiveShadow) continue;
2715
+ if (mesh.geometry.boundingBox === null) mesh.geometry.computeBoundingBox();
2716
+ if (mesh.geometry.boundingBox === null) continue;
2717
+ _box.copy(mesh.geometry.boundingBox).applyMatrix4(mesh.matrixWorld);
2718
+ if (eye.x < _box.min.x || eye.x > _box.max.x || eye.z < _box.min.z || eye.z > _box.max.z)
2719
+ continue;
2720
+ height = Math.max(height ?? Number.NEGATIVE_INFINITY, _box.max.y);
2721
+ }
2722
+ }
2723
+ if (height === undefined || eye.y - height <= (this.options.clipExtents[0] ?? 0)) return _focus;
2724
+ const far = (camera as Camera & { far?: number }).far ?? Number.POSITIVE_INFINITY;
2725
+ // Solve against the stored height, including terrain relief along the ray. Flat terrain
2726
+ // converges in one query; a bounded iteration avoids scanning terrain triangles every frame.
2727
+ // Never raycast received triangles here: a streamed world holds thousands of receiving
2728
+ // meshes, and a per-frame scan of them blocked the main thread for seconds. The windows carry
2729
+ // guard bands, so the ray's hit on the received height (or the plane under the eye where no
2730
+ // numerical height exists) is focus enough.
2731
+ let distance = Math.min((height - eye.y) / _forward.y, far);
2732
+ if (!(distance > 0)) return _focus;
2733
+ _focus.copy(eye).addScaledVector(_forward, distance);
2734
+ for (let step = 0; step < 16; step += 1) {
2735
+ const received = this.#heightAt(_focus.x, _focus.z);
2736
+ if (received === undefined || Math.abs(_focus.y - received) <= 0.001) break;
2737
+ const next = (received - eye.y) / _forward.y;
2738
+ if (!(next > 0) || next > far) break;
2739
+ distance = next;
2740
+ _focus.copy(eye).addScaledVector(_forward, distance);
2741
+ }
2742
+ return _focus;
2743
+ }
2744
+
2745
+ #updateFrame(frame: NodeFrame): undefined {
2746
+ if (!this.#initialised) return undefined;
2747
+ const camera = frame.camera as Camera | null;
2748
+ if (camera === null) return undefined;
2749
+ const source = this.light as DirectionalLight;
2750
+ syncLevelShadowSettings(source.shadow, this.#levels);
2751
+ const parent = source.parent;
2752
+ for (const level of this.#levels) {
2753
+ if (level.light.parent === null && parent !== null) {
2754
+ parent.add(level.light.target);
2755
+ parent.add(level.light);
2756
+ }
2757
+ }
2758
+ source.updateWorldMatrix(true, false);
2759
+ source.target.updateWorldMatrix(true, false);
2760
+ // Toward the source: the clipmap's W axis points at the light.
2761
+ _direction
2762
+ .setFromMatrixPosition(source.matrixWorld)
2763
+ .sub(source.target.getWorldPosition(_center));
2764
+ if (_direction.lengthSq() === 0) _direction.set(0, 1, 0);
2765
+ const directionChanged = this.clipmap.setDirection({
2766
+ x: _direction.x,
2767
+ y: _direction.y,
2768
+ z: _direction.z,
2769
+ });
2770
+ camera.updateMatrixWorld(true);
2771
+ const cameraPosition = _center.setFromMatrixPosition(camera.matrixWorld);
2772
+ // The engine's own frame clock, in seconds. This is what a level's invalidation delay is
2773
+ // measured against, so a test drives time instead of frames and a 3.33 s delay means 3.33 s
2774
+ // whatever the frame rate is. Read once, here, because the levels below all measure against it.
2775
+ const now = (frame as { time?: number }).time ?? 0;
2776
+ this.#adaptiveTrails(frame, now);
2777
+ const windows = this.clipmap.updateCenter(this.#viewFocus(camera, cameraPosition));
2778
+ this.#centerU.value = this.clipmap.centerLight.u;
2779
+ this.#centerV.value = this.clipmap.centerLight.v;
2780
+ 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);
2782
+ this.#basisW.value.set(this.clipmap.basisW.x, this.clipmap.basisW.y, this.clipmap.basisW.z);
2783
+ // A caster that stopped casting, or stopped being visible, changed what the levels hold without
2784
+ // changing the tree, so nothing else on the frame would say so. Asked here, before this frame's
2785
+ // own writes to those flags, which is what `#probe` and the mover exclusion below both do.
2786
+ this.#pollCasters();
2787
+ this.#classifyCasters();
2788
+ const moverSources = this.#casters.size + this.#autoMovers.size + this.#autoSettling.size;
2789
+ this.#moversActive.value = moverSources > 0 ? 1 : 0;
2790
+
2791
+ // Movers leave the cached maps and are drawn into the mover maps below. A child attached
2792
+ // after `trackCaster` — a loaded mesh under a placeholder group — picks up the layer here.
2793
+ const excluded: Array<{ object: Object3D; castShadow: boolean }> = [];
2794
+ if (this.#casters.size > 0) {
2795
+ for (const object of this.#casters.values()) {
2796
+ this.#rememberMoverChildren(object);
2797
+ object.traverse((child) => {
2798
+ if (child.castShadow) {
2799
+ excluded.push({ castShadow: child.castShadow, object: child });
2800
+ child.castShadow = false;
2801
+ }
2802
+ });
2803
+ }
2804
+ }
2805
+ // The ones the scan measured moving are out of the cached levels the same way.
2806
+ for (const mesh of this.#autoMovers) {
2807
+ if (!mesh.castShadow) continue;
2808
+ excluded.push({ castShadow: true, object: mesh });
2809
+ mesh.castShadow = false;
2810
+ }
2811
+ const invalidateAll = this.#invalidateAll;
2812
+ const invalidatedKeys = this.tracker.consumeInvalidatedKeys();
2813
+ const invalidatedLevels = new Set<number>();
2814
+ // The tracker's pages, per level, as the one rectangle that holds them.
2815
+ const keyedPages = new Map<number, IPageRect>();
2816
+ for (const key of invalidatedKeys) {
2817
+ const { level, x, y } = parsePageKey(key);
2818
+ invalidatedLevels.add(level);
2819
+ keyedPages.set(
2820
+ level,
2821
+ unionPageRect(keyedPages.get(level), { maxX: x, maxY: y, minX: x, minY: y }),
2822
+ );
2823
+ }
2824
+ // The regions `invalidateRegion` was handed, resolved once onto the two axes every level's
2825
+ // window is built on. The per-level test below is then four comparisons, not a projection per
2826
+ // level per region per frame.
2827
+ this.#projectedRegions ??= [];
2828
+ const projected = this.#projectedRegions;
2829
+ projected.length = 0;
2830
+ for (const region of this.#regions) {
2831
+ projected.push({
2832
+ admission: region.admission === true,
2833
+ u: projectBounds(region, this.clipmap.basisU),
2834
+ urgent: region.urgent === true,
2835
+ v: projectBounds(region, this.clipmap.basisV),
2836
+ });
2837
+ }
2838
+ this.#regions.length = 0;
2839
+ const canRender = (frame as { renderer?: unknown }).renderer !== undefined;
2840
+ // An engine-chosen delay also waits out the GPU cost of the last redraw, so a redraw that is a
2841
+ // visible stall on a weak GPU is spaced to a share of the time instead of queued behind every
2842
+ // streamed cell. Measured, so a fast GPU never reaches it; off with adaptive refresh.
2843
+ const redrawMs =
2844
+ this.#invalidationDelayGiven || !this.options.adaptiveRefresh
2845
+ ? undefined
2846
+ : shadowRedrawGpuMs((frame as { renderer?: unknown }).renderer);
2847
+ const gpuDelay = redrawMs === undefined ? 0 : redrawMs / INVALIDATION_GPU_SHARE / 1000;
2848
+
2849
+ let moved = 0;
2850
+ let invalidated = 0;
2851
+ let rendered = 0;
2852
+ let deferred = 0;
2853
+ let waiting = 0;
2854
+ // Per level, finest first: which window moved, which invalidation asked, and which of the four
2855
+ // took the frame's single render. One object per level per frame, so a harness reading the
2856
+ // marker can see *which* level a walk keeps re-rendering.
2857
+ const perLevel = this.#perLevel;
2858
+ perLevel.length = 0;
2859
+ // One level render per frame, finest first: a level render is a whole scene draw, and three of
2860
+ // them in one frame is the long task a fly-through cannot absorb. A level the budget skipped
2861
+ // holds the map it has and is due again on the next frame.
2862
+ let budgetSpent = false;
2863
+ try {
2864
+ const half = this.clipmap.pagesPerAxis / 2;
2865
+ // The window each level's map was actually rendered with. A level that does not get this
2866
+ // frame's window keeps this one, and `level.minX/minY` stays put, so it is still "moved" next
2867
+ // 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
+ });
2872
+ const finer: { cu: number; cv: number; half: number }[] = [];
2873
+ this.#levels.forEach((level, index) => {
2874
+ const window = windows[index];
2875
+ if (window === undefined) return;
2876
+ const windowMoved =
2877
+ directionChanged || window.minX !== level.minX || window.minY !== level.minY;
2878
+ const { cu, cv } = centreOf(window);
2879
+ // This level's own window against the regions handed to `invalidateRegion`. A window that
2880
+ // does not reach a region draws the same shadow either way.
2881
+ let regionDirty = false;
2882
+ // An ask the node made about a caster it just measured moving, which no delay should hold.
2883
+ let urgent = false;
2884
+ // The same ask, when a fragment of the old spot is read from *this* level: a finer level's
2885
+ // guarded window did not take all of it, so the finer map being redrawn does not clear it.
2886
+ let urgentSelected = false;
2887
+ // The pages the regions that reach this level cover, clipped to its window: those casters
2888
+ // streamed into, which need no clear, and those of any other ask.
2889
+ let regionAdmit: IPageRect | undefined;
2890
+ let regionEvict: IPageRect | undefined;
2891
+ let regionWhole = false;
2892
+ const clip = (rect: IPageRect): IPageRect | undefined => {
2893
+ const clipped = {
2894
+ maxX: Math.min(rect.maxX, window.maxX - 1),
2895
+ maxY: Math.min(rect.maxY, window.maxY - 1),
2896
+ minX: Math.max(rect.minX, window.minX),
2897
+ minY: Math.max(rect.minY, window.minY),
2898
+ };
2899
+ return clipped.minX <= clipped.maxX && clipped.minY <= clipped.maxY ? clipped : undefined;
2900
+ };
2901
+ for (const region of projected) {
2902
+ if (
2903
+ region.u.low <= cu + level.extent &&
2904
+ region.u.high >= cu - level.extent &&
2905
+ region.v.low <= cv + level.extent &&
2906
+ region.v.high >= cv - level.extent
2907
+ ) {
2908
+ regionDirty = true;
2909
+ const spanX = pageSpan(region.u.low, region.u.high, window.pageWorldSize);
2910
+ const spanY = pageSpan(region.v.low, region.v.high, window.pageWorldSize);
2911
+ const pages = clip({
2912
+ maxX: spanX.max,
2913
+ maxY: spanY.max,
2914
+ minX: spanX.min,
2915
+ minY: spanY.min,
2916
+ });
2917
+ if (pages === undefined) regionWhole = true;
2918
+ else if (region.admission) regionAdmit = unionPageRect(regionAdmit, pages);
2919
+ else regionEvict = unionPageRect(regionEvict, pages);
2920
+ if (region.urgent) {
2921
+ urgent = true;
2922
+ urgentSelected ||= !finer.some(
2923
+ (held) =>
2924
+ region.u.low >= held.cu - held.half &&
2925
+ region.u.high <= held.cu + held.half &&
2926
+ region.v.low >= held.cv - held.half &&
2927
+ region.v.high <= held.cv + held.half,
2928
+ );
2929
+ }
2930
+ }
2931
+ }
2932
+ finer.push({
2933
+ cu,
2934
+ cv,
2935
+ half: level.extent * (this.options.selectionGuard[index] ?? 0),
2936
+ });
2937
+ const asked =
2938
+ invalidateAll || invalidatedLevels.has(index) || regionDirty || source.shadow.needsUpdate;
2939
+ if (windowMoved) moved += 1;
2940
+ if (asked) {
2941
+ invalidated += 1;
2942
+ // An ask that lands on a level already dirty merges into the one waiting out that
2943
+ // level's delay instead of queueing a render of its own. This is the counter that says
2944
+ // how much a streaming world's once-a-second invalidation actually cost.
2945
+ if (level.dirty) this.#coalesced += 1;
2946
+ level.dirty = true;
2947
+ // Which pages the ask named. An ask that names none inside the window dirties them all,
2948
+ // and so does one the tracker or `needsUpdate` made, which carry no admission claim.
2949
+ const keyed = keyedPages.get(index);
2950
+ const keyedPagesInWindow = keyed === undefined ? undefined : clip(keyed);
2951
+ if (
2952
+ invalidateAll ||
2953
+ source.shadow.needsUpdate ||
2954
+ regionWhole ||
2955
+ (keyed !== undefined && keyedPagesInWindow === undefined)
2956
+ ) {
2957
+ level.dirtyAll = true;
2958
+ }
2959
+ if (regionAdmit !== undefined)
2960
+ level.dirtyAdmit = unionPageRect(level.dirtyAdmit, regionAdmit);
2961
+ for (const pages of [regionEvict, keyedPagesInWindow]) {
2962
+ if (pages !== undefined) level.dirtyEvict = unionPageRect(level.dirtyEvict, pages);
2963
+ }
2964
+ if (level.dirtyAdmit === undefined && level.dirtyEvict === undefined)
2965
+ level.dirtyAll = true;
2966
+ }
2967
+ // A window that moved is never delayed. A dirty level waits `invalidationDelay` after its
2968
+ // *own* last render, so a burst spanning that delay is one render and a lone ask is one
2969
+ // render, and the level keeps the map and window it has in between — already right for
2970
+ // every static caster in it, missing only what streamed in since.
2971
+ const delay = Math.max(this.options.invalidationDelay[index] ?? 0, gpuDelay);
2972
+ const matured = level.dirty && (urgent || now - level.lastRender >= delay);
2973
+ let reason: RenderReason = REASON_NONE;
2974
+ if (windowMoved) reason = REASON_MOVE;
2975
+ else if (matured) reason = REASON_INVALIDATION;
2976
+ else if (level.pending !== REASON_NONE) reason = level.pending;
2977
+ else if (level.dirty) waiting += 1;
2978
+ const due = canRender && reason !== REASON_NONE;
2979
+ // Finest first: the loop walks the levels in that order, so the first due level takes the
2980
+ // frame's single render and every other due level is deferred behind it.
2981
+ // One exception: a caster that has just been measured moving leaves its old shadow in every
2982
+ // map that selects it, and the frame's first mover render is the only one the mover layer
2983
+ // can hide it from. A level that reads part of that spot draws on this frame too, so the
2984
+ // blob never stands next to the mover's new shadow. It fires once per caster, on the frame
2985
+ // the node classifies it, and at most one render per level.
2986
+ const grant = due && (!budgetSpent || (urgentSelected && matured));
2987
+ // The rectangles this render draws, or undefined for the whole level.
2988
+ let passes: IPartialPass[] | undefined;
2989
+ // The pages this render counted as rectangles, kept for the derived span below that turns
2990
+ // them into the whole level and has to say so in the counters it already spent.
2991
+ let countedPages = 0;
2992
+ // A rectangle with a derived span keeps the camera its map was drawn from while the casters
2993
+ // still fit, so kept texels decode as written and a shrunk span no longer moves them.
2994
+ let keepsDepth = false;
2995
+ if (grant) {
2996
+ const sameWindow =
2997
+ level.mapped.value === 1 && window.minX === level.minX && window.minY === level.minY;
2998
+ // A level's first render places its window; only later renders are travel.
2999
+ if (Number.isFinite(level.minX)) {
3000
+ this.#windowSteps +=
3001
+ Math.abs(window.minX - level.minX) + Math.abs(window.minY - level.minY);
3002
+ }
3003
+ level.minX = window.minX;
3004
+ level.minY = window.minY;
3005
+ level.mapped.value = 1;
3006
+ level.pending = REASON_NONE;
3007
+ level.lastRender = now;
3008
+ this.#rendersTotal += 1;
3009
+ // A window that moved, a region-less ask, or more than half the pages dirty is the whole
3010
+ // level; anything else is the rectangles the asks named.
3011
+ const levelPages = this.clipmap.pagesPerAxis ** 2;
3012
+ passes =
3013
+ reason === REASON_MOVE || level.dirtyAll
3014
+ ? undefined
3015
+ : this.#planPasses(level, levelPages, frame);
3016
+ const dirtyPages = this.#dirtyPages(level);
3017
+ this.#pagesDirty +=
3018
+ reason === REASON_MOVE || level.dirtyAll || dirtyPages * 2 > levelPages
3019
+ ? levelPages
3020
+ : dirtyPages;
3021
+ this.#pagesRedrawn += passes === undefined ? levelPages : dirtyPages;
3022
+ countedPages = dirtyPages;
3023
+ keepsDepth = passes !== undefined && sameWindow && this.#autoDepth;
3024
+ if (!keepsDepth) level.centerW = this.clipmap.centerLight.w;
3025
+ if (reason === REASON_MOVE) {
3026
+ this.#byMove += 1;
3027
+ // The render was already going to happen for the window, so the invalidation rode
3028
+ // along on it: one ask, one render, and it is counted as absorbed.
3029
+ if (level.dirty) this.#coalesced += 1;
3030
+ } else {
3031
+ this.#byInvalidation += 1;
3032
+ if (level.dirtyEvict === undefined && !level.dirtyAll) this.#byAdmission += 1;
3033
+ else this.#byEviction += 1;
3034
+ }
3035
+ // A render of any reason answers whatever asked, so a movement render clears the dirty
3036
+ // flag too and the coalesced level is not redrawn a frame later for nothing.
3037
+ level.dirty = false;
3038
+ level.dirtyAdmit = undefined;
3039
+ level.dirtyAll = false;
3040
+ level.dirtyEvict = undefined;
3041
+ rendered += 1;
3042
+ budgetSpent = true;
3043
+ } else if (due) {
3044
+ deferred += 1;
3045
+ level.pending = reason;
3046
+ } else {
3047
+ level.pending = REASON_NONE;
3048
+ }
3049
+ const stat = {
3050
+ deferred: due && !grant ? 1 : 0,
3051
+ // Filled by `#probe` on the frame's granted render, from the meshes it read; a level
3052
+ // that keeps its map submits no caster draws of its own, so it reports none.
3053
+ draws: 0,
3054
+ drawsBy: { chunkProxy: 0, cluster: 0, keys: 0, layer0: 0, small: 0, wide: 0 },
3055
+ extent: level.extent,
3056
+ gateHidden: 0,
3057
+ gateScale: level.gateScale,
3058
+ invalidated: asked ? 1 : 0,
3059
+ moved: windowMoved ? 1 : 0,
3060
+ rendered: grant ? 1 : 0,
3061
+ };
3062
+ perLevel.push(stat);
3063
+ // The level camera sits on the window its map was rendered with, deferred or not. A level
3064
+ // that has never rendered takes this frame's: it has no map to hold, and `mapped` keeps
3065
+ // every fragment out of it until it does.
3066
+ const held =
3067
+ level.mapped.value === 1 && !grant
3068
+ ? { minX: level.minX, minY: level.minY, pageWorldSize: window.pageWorldSize }
3069
+ : window;
3070
+ const { cu: hu, cv: hv } = centreOf(held as IClipWindow);
3071
+ // Hold all three coordinates of the rendered centre: its derived depth and the mover
3072
+ // map's shared sampling matrix are relative to this depth, not the followed camera's.
3073
+ const centre = this.clipmap.unproject({
3074
+ u: hu,
3075
+ v: hv,
3076
+ w: level.mapped.value === 1 ? level.centerW : this.clipmap.centerLight.w,
3077
+ });
3078
+ level.offsetU.value = this.clipmap.centerLight.u - hu;
3079
+ level.offsetV.value = this.clipmap.centerLight.v - hv;
3080
+ level.light.target.position.set(centre.x, centre.y, centre.z);
3081
+ level.light.target.updateMatrixWorld(true);
3082
+ if (grant) {
3083
+ // The two automatic fixes, off one pass over the world this window can see: the depth
3084
+ // the level needs to cover what can actually shadow it, and the casters too small for its
3085
+ // texels. Both are undone the moment the render is over — by `#restoreHidden`, which the
3086
+ // mover maps and the main pass both need back.
3087
+ this.#probe(level, centre, index, stat);
3088
+ // A rectangle redraws only the pages it names and keeps every other texel, and a kept
3089
+ // texel holds its depth as the camera that drew it encoded it: an absolute distance along
3090
+ // the light, measured from that camera's own origin. A span this render derived moves
3091
+ // both, and a camera that moved moves the encoding even when near, far and the width
3092
+ // between them are the same numbers the map already holds: a level whose casters all
3093
+ // translate along the sun, or an authored span whose camera travels with a window that
3094
+ // did not move. Either way the level draws whole instead of leaving numbers no camera the
3095
+ // map was not drawn from can read. What decides it is the encoding itself — the depth row
3096
+ // the kept texels are read through, in the float32 three uploads it — read from the map
3097
+ // the level still holds and from the one this render proposes.
3098
+ const drawnNear = level.depthNear;
3099
+ const drawnFar = level.depthFar;
3100
+ this.#readDepthRow(level, _drawnDepth);
3101
+ if (this.#autoDepth) this.#measureDepth(level, centre, keepsDepth);
3102
+ this.#place(level, centre);
3103
+ if (passes !== undefined) {
3104
+ // quality-allow: the light's own shadow owns this update, and the stock node calls it too.
3105
+ level.shadow.updateMatrices(level.light as unknown as DirectionalLight);
3106
+ this.#readDepthRow(level, _proposedDepth);
3107
+ if (
3108
+ level.depthNear !== drawnNear ||
3109
+ level.depthFar !== drawnFar ||
3110
+ _proposedDepth[0] !== _drawnDepth[0] ||
3111
+ _proposedDepth[1] !== _drawnDepth[1] ||
3112
+ _proposedDepth[2] !== _drawnDepth[2] ||
3113
+ _proposedDepth[3] !== _drawnDepth[3]
3114
+ ) {
3115
+ const whole = this.clipmap.pagesPerAxis ** 2 - countedPages;
3116
+ this.#pagesDirty += whole;
3117
+ this.#pagesRedrawn += whole;
3118
+ passes = undefined;
3119
+ }
3120
+ }
3121
+ try {
3122
+ // Rendered here, not by flagging `needsUpdate`, so the mover exclusion above brackets it.
3123
+ if (passes === undefined) {
3124
+ this.#renderLevel(frame, level, false, index);
3125
+ } else {
3126
+ for (const pass of passes) {
3127
+ level.pass = pass;
3128
+ this.#renderLevel(frame, level, false, index);
3129
+ }
3130
+ }
3131
+ } finally {
3132
+ this.#endPartial(level);
3133
+ this.#restoreHidden();
3134
+ }
3135
+ } else {
3136
+ // A level that keeps its map is placed with the span that map was drawn with, so the next
3137
+ // fragment it is sampled through reads the depth it actually holds.
3138
+ this.#place(level, centre);
3139
+ }
3140
+ });
3141
+ source.shadow.needsUpdate = false;
3142
+ this.#invalidateAll = false;
3143
+ } finally {
3144
+ for (const { castShadow, object } of excluded) object.castShadow = castShadow;
3145
+ }
3146
+ // Every level the return redraw asked has rendered the caster, so its mover map draw can go.
3147
+ if (
3148
+ this.#autoSettling.size > 0 &&
3149
+ this.#levels.every((level) => !level.dirty && level.pending === REASON_NONE)
3150
+ ) {
3151
+ for (const mesh of this.#autoSettling) {
3152
+ this.#dropMoverLayer(mesh);
3153
+ const state = this.#motionOf.get(mesh);
3154
+ if (state !== undefined) state.phase = MOTION_STATIC;
3155
+ }
3156
+ this.#autoSettling.clear();
3157
+ }
3158
+ // An untracked node keeps a neutral mover contribution in the shader and does no mover work.
3159
+ let moverRenders = 0;
3160
+ if (this.#casters.size + this.#autoMovers.size + this.#autoSettling.size > 0) {
3161
+ for (const level of this.#levels) {
3162
+ // A mover map draws only the tracked casters on layer 29, in a 256² map over the level's own
3163
+ // window, so it keeps full detail: every level's world changes were already put back above.
3164
+ if (canRender) this.#renderLevel(frame, level, true);
3165
+ moverRenders += 1;
3166
+ }
3167
+ }
3168
+ this.#frame += 1;
3169
+ this.#rendered += rendered;
3170
+ this.#served += this.#levels.length - rendered;
3171
+ const total = this.#rendered + this.#served;
3172
+ this.#stats = {
3173
+ byAdmission: this.#byAdmission,
3174
+ byEviction: this.#byEviction,
3175
+ byInvalidation: this.#byInvalidation,
3176
+ byMove: this.#byMove,
3177
+ cached: this.#levels.length - rendered,
3178
+ coalesced: this.#coalesced,
3179
+ deferred,
3180
+ frame: this.#frame,
3181
+ held: waiting,
3182
+ invalidated,
3183
+ levels: this.#levels.length,
3184
+ moved,
3185
+ moverRenders,
3186
+ movers: this.#casters.size,
3187
+ autoMovers: this.#autoMovers.size,
3188
+ autoScanMs: this.#autoScanTotalMs / this.#frame,
3189
+ autoTransitions: this.#autoTransitions,
3190
+ pagesDirty: this.#pagesDirty,
3191
+ pagesRedrawn: this.#pagesRedrawn,
3192
+ perLevel: this.#perLevel,
3193
+ rendered,
3194
+ rendersTotal: this.#rendersTotal,
3195
+ reuseRatio: total === 0 ? 1 : this.#served / total,
3196
+ windowSteps: this.#windowSteps,
3197
+ };
3198
+ const every = this.options.markerEvery;
3199
+ // `?tnShadowStats=1` is the walk's own switch: a 10 s walk is ~600 frames, and a marker every
3200
+ // 60 of them is a hundred lines that say which level is re-rendering and why. It prints on top
3201
+ // of `markerEvery` rather than instead of it, so a run can turn it on without a rebuild.
3202
+ const walk = this.#statsWalkRequested() ? STATS_QUERY_EVERY : 0;
3203
+ if (
3204
+ (every > 0 && (this.#frame === 1 || this.#frame % every === 0)) ||
3205
+ (walk > 0 && this.#frame % walk === 0)
3206
+ ) {
3207
+ console.info(`${VIRTUAL_SHADOW_MARKER}:${JSON.stringify(this.#stats)}`);
3208
+ }
3209
+ return undefined;
3210
+ }
3211
+
3212
+ /** Whether `?tnShadowStats=1` is on this launch's URL, read once. */
3213
+ #statsWalkRequested(): boolean {
3214
+ this.#statsRequested ??= /[?&]tnShadowStats=(?!0(?:&|$))(?!false(?:&|$))[^&]/u.test(
3215
+ globalThis.location?.search ?? "",
3216
+ );
3217
+ return this.#statsRequested;
3218
+ }
3219
+
3220
+ override dispose(): void {
3221
+ this.light.removeEventListener("removed", this.#onLightRemoved);
3222
+ this.#regions.length = 0;
3223
+ this.#dropCasters();
3224
+ for (const level of this.#levels) {
3225
+ level.light.removeFromParent();
3226
+ level.light.target.removeFromParent();
3227
+ for (const entry of [
3228
+ { node: level.node, map: level.shadow },
3229
+ { node: level.moverNode, map: level.moverShadow },
3230
+ ]) {
3231
+ const stock = entry.node as typeof entry.node & {
3232
+ shadowMap?: RenderTarget | null;
3233
+ vsmShadowMapVertical?: RenderTarget | null;
3234
+ vsmShadowMapHorizontal?: RenderTarget | null;
3235
+ };
3236
+ // Stock setup aliases shadow.map to node.shadowMap. The node owns that target and
3237
+ // its VSM passes; LightShadow only owns any remaining non-aliased map/mapPass.
3238
+ const owned = [stock.shadowMap, stock.vsmShadowMapVertical, stock.vsmShadowMapHorizontal];
3239
+ entry.node.dispose();
3240
+ if (owned.includes(entry.map.map)) entry.map.map = null;
3241
+ if (owned.includes(entry.map.mapPass)) entry.map.mapPass = null;
3242
+ entry.map.dispose();
3243
+ entry.map.map = null;
3244
+ entry.map.mapPass = null;
3245
+ }
3246
+ }
3247
+ this.#levels = [];
3248
+ for (const mesh of this.#autoMovers) this.#dropMoverLayer(mesh);
3249
+ for (const mesh of this.#autoSettling) this.#dropMoverLayer(mesh);
3250
+ this.#autoMovers.clear();
3251
+ this.#autoSettling.clear();
3252
+ this.#motion.length = 0;
3253
+ this.#pinnedRoots.clear();
3254
+ for (const id of this.#casters.keys()) this.#restoreMoverChildren(id);
3255
+ for (const object of this.#casters.values()) {
3256
+ this.tracker.remove(object.uuid);
3257
+ }
3258
+ this.#casters.clear();
3259
+ this.tracker.clear();
3260
+ this.#initialised = false;
3261
+ super.dispose();
3262
+ }
3263
+ }
3264
+
3265
+ const VIRTUAL_SHADOW_STAT_FIELDS = [
3266
+ "autoMovers",
3267
+ "autoScanMs",
3268
+ "autoTransitions",
3269
+ "byAdmission",
3270
+ "byEviction",
3271
+ "byInvalidation",
3272
+ "byMove",
3273
+ "cached",
3274
+ "coalesced",
3275
+ "deferred",
3276
+ "frame",
3277
+ "held",
3278
+ "invalidated",
3279
+ "levels",
3280
+ "moved",
3281
+ "moverRenders",
3282
+ "movers",
3283
+ "pagesDirty",
3284
+ "pagesRedrawn",
3285
+ "rendered",
3286
+ "rendersTotal",
3287
+ "reuseRatio",
3288
+ ] as const;
3289
+
3290
+ function isVirtualShadowStats(value: unknown): value is IVirtualShadowStats {
3291
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
3292
+ const stats = value as Record<string, unknown>;
3293
+ if (
3294
+ VIRTUAL_SHADOW_STAT_FIELDS.some(
3295
+ (field) => typeof stats[field] !== "number" || !Number.isFinite(stats[field]),
3296
+ )
3297
+ ) {
3298
+ return false;
3299
+ }
3300
+ // Two fields are measurements, not counts: a ratio and a mean in milliseconds.
3301
+ const countFields = VIRTUAL_SHADOW_STAT_FIELDS.filter(
3302
+ (field) => field !== "reuseRatio" && field !== "autoScanMs",
3303
+ );
3304
+ if (
3305
+ countFields.some((field) => !Number.isInteger(stats[field]) || (stats[field] as number) < 0)
3306
+ ) {
3307
+ return false;
3308
+ }
3309
+ const reuseRatio = stats.reuseRatio as number;
3310
+ return reuseRatio >= 0 && reuseRatio <= 1 && (stats.autoScanMs as number) >= 0;
3311
+ }
3312
+
3313
+ /**
3314
+ * Parse a `TN_VIRTUAL_SHADOW` console line back into its complete stats, or `undefined`.
3315
+ *
3316
+ * @situation inspect virtual shadow cache and mover counters from a renderer log
3317
+ * @constraint non-marker lines and markers with incomplete or non-numeric stats return `undefined`
3318
+ * @example
3319
+ * const stats = readVirtualShadowMarker(line);
3320
+ * if (stats !== undefined) console.log(stats.reuseRatio);
3321
+ */
3322
+ export function readVirtualShadowMarker(line: string): IVirtualShadowStats | undefined {
3323
+ if (!line.startsWith(`${VIRTUAL_SHADOW_MARKER}:`)) return undefined;
3324
+ try {
3325
+ const value: unknown = JSON.parse(line.slice(VIRTUAL_SHADOW_MARKER.length + 1));
3326
+ return isVirtualShadowStats(value) ? value : undefined;
3327
+ } catch {
3328
+ return undefined;
3329
+ }
3330
+ }