@threenative/core 0.3.11 → 0.3.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1988 -204
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  5. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  6. package/dist/chunk-4SRAQFTU.js +133 -0
  7. package/dist/chunk-CFGTPFUH.js +231 -0
  8. package/dist/chunk-DIPIJICH.js +8916 -0
  9. package/dist/chunk-EEABDLUC.js +2237 -0
  10. package/dist/chunk-EFWZWLPY.js +1895 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-GYUZJQ7U.js +280 -0
  13. package/dist/chunk-H4J6IAJE.js +504 -0
  14. package/dist/chunk-KIRUKTBQ.js +187 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-SV4QVUTQ.js +31 -0
  17. package/dist/chunk-U4YHUKKL.js +615 -0
  18. package/dist/chunk-VP43GIWW.js +18 -0
  19. package/dist/chunk-XDTZ4QMO.js +160 -0
  20. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  21. package/dist/{game-DzMcitDO.d.ts → game-k8K3hZai.d.ts} +85 -9
  22. package/dist/hot.d.ts +5 -4
  23. package/dist/hot.js +5 -52
  24. package/dist/index.d.ts +633 -1351
  25. package/dist/index.js +12873 -23068
  26. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-DPTzeCcD.d.ts} +35 -3
  27. package/dist/playtest.d.ts +5 -4
  28. package/dist/playtest.js +25 -75
  29. package/dist/quality-BYqKGAwo.d.ts +868 -0
  30. package/dist/react-css.js +1 -215
  31. package/dist/react.d.ts +3 -2
  32. package/dist/render-environment.d.ts +170 -0
  33. package/dist/render-environment.js +352 -0
  34. package/dist/{renderer-rZm0hVqq.d.ts → renderer-BtOSseYf.d.ts} +42 -35
  35. package/dist/spells/index.d.ts +643 -0
  36. package/dist/spells/index.js +1558 -0
  37. package/dist/spells/ultra/index.d.ts +1600 -0
  38. package/dist/spells/ultra/index.js +6804 -0
  39. package/dist/terrain-jobs-worker.js +1 -123
  40. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  41. package/dist/ui-layer.js +6 -384
  42. package/dist/worker.js +13 -43
  43. package/dist/world.d.ts +988 -268
  44. package/dist/world.js +17464 -18290
  45. package/mcp/animation-server.mjs +1 -1
  46. package/mcp/animation.mjs +2 -3
  47. package/mcp/engine-server.mjs +245 -52
  48. package/mcp/servers.mjs +10 -3
  49. package/mcp/terrain.mjs +8 -0
  50. package/package.json +19 -7
  51. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  52. package/patches/three@0.187.0.patch +2004 -407
  53. package/src/animation-batch.ts +193 -0
  54. package/src/animation-layers.ts +7 -3
  55. package/src/animation.ts +209 -29
  56. package/src/asset-cache.ts +3 -3
  57. package/src/asset-memo.ts +202 -0
  58. package/src/assets.ts +437 -125
  59. package/src/auto-batch.ts +190 -44
  60. package/src/card-lod.ts +152 -0
  61. package/src/compressed-texture-preparation.ts +1008 -0
  62. package/src/compute-driven.ts +1 -1
  63. package/src/config.ts +8 -0
  64. package/src/debug.ts +103 -22
  65. package/src/dev-global.ts +54 -0
  66. package/src/engine-hooks.ts +37 -0
  67. package/src/frame-budget.ts +50 -23
  68. package/src/game-boot-phase.ts +269 -0
  69. package/src/game-dev-tools.ts +86 -0
  70. package/src/game-frame-loop.ts +958 -0
  71. package/src/game-renderer-metrics.ts +77 -0
  72. package/src/game-startup.ts +1076 -0
  73. package/src/game-ui.ts +84 -0
  74. package/src/game-validate.ts +70 -0
  75. package/src/game.ts +198 -2264
  76. package/src/gamepad-mappings.ts +269 -0
  77. package/src/generated/console-markers.ts +13 -0
  78. package/src/geometry-capture.ts +28 -4
  79. package/src/gpu-readings.ts +98 -0
  80. package/src/gpu-scene-bvh.ts +149 -36
  81. package/src/hot.ts +4 -7
  82. package/src/index.ts +141 -9
  83. package/src/input.ts +237 -25
  84. package/src/instanced-batch-lod.ts +3 -8
  85. package/src/interpolation.ts +171 -40
  86. package/src/launch-diagnostics.ts +22 -12
  87. package/src/look/ao-admission.ts +25 -0
  88. package/src/look/auto-exposure.ts +5 -16
  89. package/src/look/default-tone-mapping.ts +41 -5
  90. package/src/look/filmic-tone-mapping.ts +15 -13
  91. package/src/look/local-exposure.ts +2 -7
  92. package/src/look/look-diagnostics.ts +3 -3
  93. package/src/look/quad-pass.ts +21 -0
  94. package/src/look/quality.ts +14 -5
  95. package/src/look/unreal-bloom.ts +4 -13
  96. package/src/look/world-environment.ts +113 -103
  97. package/src/loop.ts +29 -0
  98. package/src/merge-parts.ts +20 -24
  99. package/src/model-lod.ts +139 -17
  100. package/src/particle-kinds.ts +515 -0
  101. package/src/particle-significance.ts +12 -0
  102. package/src/particles.ts +19 -10
  103. package/src/picking.ts +17 -3
  104. package/src/platform.ts +23 -4
  105. package/src/playtest.ts +27 -1
  106. package/src/profiling/FrameStages.ts +5 -6
  107. package/src/profiling/Spans.ts +3 -17
  108. package/src/profiling/debug-telemetry.ts +2 -6
  109. package/src/profiling/render-list-validate.ts +6 -15
  110. package/src/projection-apply.ts +4 -1
  111. package/src/projection-marker.ts +2 -1
  112. package/src/projection-plan.ts +9 -6
  113. package/src/quiet-markers.ts +3 -10
  114. package/src/render/cpu-bvh.ts +100 -0
  115. package/src/render/depth-pyramid.ts +6 -14
  116. package/src/render/environment/environmentContribution.ts +202 -0
  117. package/src/render/environment/environmentRadiance.ts +44 -0
  118. package/src/render/environment/environmentSampleCache.ts +56 -0
  119. package/src/render/environment/environmentSampling.ts +201 -0
  120. package/src/render/environment/environmentSnapshot.ts +71 -0
  121. package/src/render/environment/gate.ts +57 -0
  122. package/src/render/mesh-pool.ts +4 -20
  123. package/src/render/probe-trace.ts +872 -0
  124. package/src/render/probe-volume.ts +780 -34
  125. package/src/render/radiance-cache.ts +17 -0
  126. package/src/render/resolution-subrect.ts +2 -0
  127. package/src/render/rough-diffuse.ts +46 -12
  128. package/src/render/soft-shadow.ts +27 -12
  129. package/src/render/virtual-shadow-adaptive.ts +55 -0
  130. package/src/render/virtual-shadow-casters.ts +175 -0
  131. package/src/render/virtual-shadow-layers.ts +76 -0
  132. package/src/render/virtual-shadow-level.ts +224 -0
  133. package/src/render/virtual-shadow-markers.ts +193 -0
  134. package/src/render/virtual-shadow-options.ts +370 -0
  135. package/src/render/virtual-shadow-pages.ts +5 -0
  136. package/src/render/virtual-shadow-partial.ts +13 -0
  137. package/src/render/virtual-shadow.ts +231 -1008
  138. package/src/render/world-impostor-surface.ts +402 -40
  139. package/src/render/world-impostor.ts +5 -2
  140. package/src/render-camera-cull.ts +98 -3
  141. package/src/render-environment.ts +41 -0
  142. package/src/render-pass-budget.ts +34 -7
  143. package/src/renderProjection.ts +22 -0
  144. package/src/renderer-config.ts +36 -0
  145. package/src/renderer-facts.ts +37 -0
  146. package/src/renderer.ts +144 -65
  147. package/src/resolution-scaler.ts +3 -2
  148. package/src/scene-entry-inspectors.ts +61 -0
  149. package/src/snow-field.ts +2 -1
  150. package/src/spells/cast-pool.ts +361 -0
  151. package/src/spells/index.ts +177 -0
  152. package/src/spells/mechanisms.ts +295 -0
  153. package/src/spells/reaction-field.ts +415 -0
  154. package/src/spells/spell-lights.ts +139 -0
  155. package/src/spells/spell-world.ts +187 -0
  156. package/src/spells/spell.ts +397 -0
  157. package/src/spells/spells.ts +283 -0
  158. package/src/spells/ultra/engine/camera.ts +184 -0
  159. package/src/spells/ultra/engine/quality.ts +96 -0
  160. package/src/spells/ultra/index.ts +52 -0
  161. package/src/spells/ultra/main.ts +305 -0
  162. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  163. package/src/spells/ultra/spells/cast.ts +233 -0
  164. package/src/spells/ultra/spells/fire.ts +1267 -0
  165. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  166. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  167. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  168. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  169. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  170. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  171. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  172. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  173. package/src/spells/ultra/vfx/common.ts +1195 -0
  174. package/src/spells/ultra/vfx/noise.ts +441 -0
  175. package/src/startup-offscreen-bytes.ts +78 -0
  176. package/src/startup-readiness.ts +128 -34
  177. package/src/static-transform.ts +25 -19
  178. package/src/streamed-textures.ts +112 -0
  179. package/src/streaming.ts +68 -4
  180. package/src/texture-streaming.ts +331 -0
  181. package/src/version.ts +1 -1
  182. package/src/warmup.ts +56 -8
  183. package/src/water-surface.ts +9 -3
  184. package/src/worker.ts +12 -2
  185. package/src/world-bundle-safety.ts +446 -0
  186. package/src/world-cell-batches.ts +1178 -0
  187. package/src/world-cell-chunks.ts +1128 -0
  188. package/src/world-cell-data.ts +995 -0
  189. package/src/world-cell-impostors.ts +1461 -0
  190. package/src/world-cell-lod-bias.ts +151 -0
  191. package/src/world-cell-models.ts +1074 -0
  192. package/src/world-cell-options.ts +177 -0
  193. package/src/world-cell-placements.ts +798 -0
  194. package/src/world-cell-prewarm.ts +592 -0
  195. package/src/world-cell-readiness.ts +357 -0
  196. package/src/world-cell-records.ts +401 -0
  197. package/src/world-cell-render-bundles.ts +459 -0
  198. package/src/world-cell-render-gpu-dress.ts +710 -0
  199. package/src/world-cell-render-main-cull.ts +540 -0
  200. package/src/world-cell-render-shadow-claims.ts +198 -0
  201. package/src/world-cell-render-util.ts +259 -0
  202. package/src/world-cell-render.ts +1501 -0
  203. package/src/world-cell-residency.ts +754 -0
  204. package/src/world-cell-stale.ts +238 -0
  205. package/src/world-cells.ts +1335 -10418
  206. package/src/world-chunk-shadow.ts +308 -0
  207. package/src/world-collar.ts +315 -0
  208. package/src/world-gpu-flags.ts +131 -0
  209. package/src/world-gpu-readback.ts +881 -0
  210. package/src/world-gpu-reference.ts +524 -0
  211. package/src/world-gpu-scene.ts +256 -2286
  212. package/src/world-gpu-shadow.ts +203 -0
  213. package/src/world-gpu-types.ts +409 -0
  214. package/src/world-gpu-validation.ts +518 -0
  215. package/src/world-heightfield.ts +802 -0
  216. package/src/world-load-limiter.ts +111 -0
  217. package/src/world-model-sections.ts +80 -0
  218. package/src/world-noise.ts +241 -0
  219. package/src/world-package.ts +42 -0
  220. package/src/world-region.ts +1 -1
  221. package/src/world-river-ribbon.ts +282 -0
  222. package/src/world-root-frame.ts +39 -0
  223. package/src/world-shore-field.ts +91 -0
  224. package/src/world-static-pose.ts +163 -0
  225. package/src/world-surface-sampler.ts +48 -0
  226. package/src/world-terrain-splat.ts +361 -153
  227. package/src/world-tile-budget.ts +249 -0
  228. package/src/world-tile-geometry.ts +469 -0
  229. package/src/world-tile-lod.ts +408 -0
  230. package/src/world-tile-observation.ts +566 -0
  231. package/src/world-tile-stitch.ts +166 -0
  232. package/src/world-tiles.ts +247 -1755
  233. package/src/world-validate.ts +6 -14
  234. package/src/world-warm.ts +51 -0
  235. package/src/world-water-bodies.ts +359 -0
  236. package/src/world.ts +48 -741
@@ -4,12 +4,11 @@ import {
4
4
  type Camera,
5
5
  type DirectionalLight,
6
6
  FrontSide,
7
- Frustum,
8
7
  type InstancedMesh,
9
8
  type Material,
10
9
  Matrix4,
11
10
  type Mesh,
12
- Object3D,
11
+ type Object3D,
13
12
  type OrthographicCamera,
14
13
  PCFShadowMap,
15
14
  PCFSoftShadowMap,
@@ -53,10 +52,79 @@ import {
53
52
  ShadowBaseNode,
54
53
  type UniformNode,
55
54
  } from "three/webgpu";
56
- import { lodChainOf } from "../model-lod.js";
55
+ import { readLaunchFlag } from "../debug.js";
57
56
  import { shadowRedrawGpuMs } from "../render-pass-budget.js";
58
57
  import { DEFAULT_TARGET_FPS } from "../target-fps.js";
58
+ import { frustumPlanes } from "../world-gpu-types.js";
59
59
  import { isLeafReceiver } from "./soft-shadow.js";
60
+ import {
61
+ COST_SMOOTHING,
62
+ COST_WARMUP_RENDERS,
63
+ nextGateScale,
64
+ trailStep,
65
+ } from "./virtual-shadow-adaptive.js";
66
+ import {
67
+ CASTER_STRIDE,
68
+ type ICasterMesh,
69
+ type ICasterMotion,
70
+ type IShadowKeyDispatch,
71
+ MAX_MASS_WINDOW_WIDTHS,
72
+ MOTION_MOVER,
73
+ MOTION_SETTLING,
74
+ MOTION_STATIC,
75
+ POOL_CASTERS,
76
+ POOL_STRIDE,
77
+ casterFlag,
78
+ deforms,
79
+ flagCasts,
80
+ instanceDiameter,
81
+ shadowLod,
82
+ } from "./virtual-shadow-casters.js";
83
+ import {
84
+ DEFAULT_CLIP_EXTENTS,
85
+ DEFAULT_MAX_LEVEL_RATIO,
86
+ VIRTUAL_SHADOW_CASTER_LAYER,
87
+ VIRTUAL_SHADOW_KEY_LAYER,
88
+ VIRTUAL_SHADOW_MOVER_LAYER,
89
+ VIRTUAL_SHADOW_SMALL_CASTER_LAYER,
90
+ VIRTUAL_SHADOW_WIDE_CASTER_LAYER,
91
+ clipLadder,
92
+ } from "./virtual-shadow-layers.js";
93
+ import {
94
+ type ILevel,
95
+ type ILightAxisRange,
96
+ LevelLight,
97
+ REASON_INVALIDATION,
98
+ REASON_MOVE,
99
+ REASON_NONE,
100
+ type RenderReason,
101
+ type ShadowWithFilter,
102
+ registeredOnCreate,
103
+ rendered,
104
+ syncLevelShadowSettings,
105
+ syncShadowSettings,
106
+ } from "./virtual-shadow-level.js";
107
+ import {
108
+ GATE_MARKER_SECONDS,
109
+ REFRESH_MARKER_SECONDS,
110
+ STATS_QUERY_EVERY,
111
+ VIRTUAL_SHADOW_GATE_MARKER,
112
+ VIRTUAL_SHADOW_MARKER,
113
+ VIRTUAL_SHADOW_REFRESH_MARKER,
114
+ } from "./virtual-shadow-markers.js";
115
+ import {
116
+ BASE_INVALIDATION_DELAY,
117
+ DEFAULT_EXPENSIVE_REFRESH_SHARE,
118
+ DEFAULT_MARKER_EVERY,
119
+ DEFAULT_MIN_CASTER_TEXELS,
120
+ DEFAULT_MIN_WINDOW_ASPECT,
121
+ DEFAULT_STATIC_AFTER_FRAMES,
122
+ type IVirtualShadowDrawTally,
123
+ type IVirtualShadowLevelStat,
124
+ type IVirtualShadowOptions,
125
+ type IVirtualShadowStats,
126
+ at,
127
+ } from "./virtual-shadow-options.js";
60
128
  import {
61
129
  DirectionalClipmap,
62
130
  type IBoundsLike,
@@ -79,685 +147,46 @@ import {
79
147
  pixelRect,
80
148
  } from "./virtual-shadow-partial.js";
81
149
 
82
- /** One clipmap axis' view of a world region, as the interval it covers in light space. */
83
- type ILightAxisRange = { low: number; high: number };
84
-
85
- /**
86
- * Why a level owes a render: not at all, a window that moved, or an invalidation that asked and
87
- * waited out its delay. The render it finally takes is counted against this, so a level the frame's
88
- * single budget passed over is not counted twice.
89
- */
90
- type RenderReason = 0 | 1 | 2;
91
- const REASON_NONE: RenderReason = 0;
92
- const REASON_MOVE: RenderReason = 1;
93
- const REASON_INVALIDATION: RenderReason = 2;
150
+ // The layers, the option and stats types, and the marker lines are owned by their own modules now.
151
+ // Re-exported here so a consumer of this module keeps every symbol it had, at the path it had it.
152
+ export {
153
+ VIRTUAL_SHADOW_CASTER_LAYER,
154
+ VIRTUAL_SHADOW_KEY_LAYER,
155
+ VIRTUAL_SHADOW_MOVER_LAYER,
156
+ VIRTUAL_SHADOW_SMALL_CASTER_LAYER,
157
+ VIRTUAL_SHADOW_WIDE_CASTER_LAYER,
158
+ clipLadder,
159
+ } from "./virtual-shadow-layers.js";
160
+ export {
161
+ LAMP_SHADOW_MARKER,
162
+ VIRTUAL_SHADOW_GATE_MARKER,
163
+ VIRTUAL_SHADOW_MARKER,
164
+ VIRTUAL_SHADOW_REFRESH_MARKER,
165
+ lampShadowMarker,
166
+ readLampShadowMarker,
167
+ readVirtualShadowMarker,
168
+ } from "./virtual-shadow-markers.js";
169
+ export type { ILampShadowStats } from "./virtual-shadow-markers.js";
170
+ export type {
171
+ IVirtualShadowDraws,
172
+ IVirtualShadowLevelStat,
173
+ IVirtualShadowOptions,
174
+ IVirtualShadowStats,
175
+ } from "./virtual-shadow-options.js";
94
176
 
95
- /**
96
- * Options for {@link VirtualShadowNode}. Every value is a mechanism parameter; the light's own
97
- * `shadow` keeps bias, normalBias, intensity, map type and filter, exactly as with a stock shadow.
98
- */
99
- export interface IVirtualShadowOptions {
100
- /**
101
- * Half-width of each clip level's window in world units, finest first and strictly
102
- * increasing. Default `[16, 48, 144]`: three windows, each three times wider than the last.
103
- */
104
- readonly clipExtents?: readonly number[];
105
- /**
106
- * Resolution bias in stops, default 0. Mirrors Unreal's
107
- * `r.Shadow.Virtual.ResolutionLodBiasDirectional`; a quality tier sets it. With the default map
108
- * sizes each stop doubles every level's texel: `-1` halves it (twice the resolution), `-1.5` is
109
- * 2.83 times finer, a positive bias coarsens it. With an authored `mapSize` the finest window
110
- * scales by `2 ** bias` instead and every coarser level keeps its extent; a bias that would push
111
- * that window past the next level throws.
112
- */
113
- readonly resolutionLodBiasDirectional?: number;
114
- /**
115
- * Texels per level edge: one number for every level, or one per level, finest first. Default:
116
- * Unreal's clipmap rule, measured on the camera and viewport that first read the shadow, so a
117
- * receiver's texel is at most `2^(1 + bias)` of its own screen pixels (`clipmapMapSizes`). Set it to
118
- * hold fixed sizes.
119
- */
120
- readonly mapSize?: number | readonly number[];
121
- /**
122
- * The page budget of the default map sizes, in 128² pages over all levels, default 4096 (Unreal's
123
- * `r.Shadow.Virtual.MaxPhysicalPages` at Epic). Sizes over it raise the bias until they fit.
124
- */
125
- readonly maxPhysicalPages?: number;
126
- /**
127
- * Texels per edge of each level's mover map — the map tracked casters draw into every frame.
128
- * Default: `mapSize`, the cached levels' own density, so a caster keeps the edge it had at rest
129
- * while it moves and does not pop to a crisper one when it settles. Lower it to buy back fill
130
- * on a weak GPU; the soft edge it costs is on the mover only.
131
- */
132
- readonly moverMapSize?: number;
133
- /**
134
- * Fraction of a level's extent inside which a fragment still selects that level, `(0, 1]`,
135
- * default 0.9 — the outer ring falls through to the next level so the edge is never sampled.
136
- * `selectionGuard` minus `refreshStep`, since a window trails its centre by that much. One value
137
- * for every level, or one per level finest first, the last entry standing in for the rest.
138
- */
139
- readonly selectionGuard?: number | readonly number[];
140
- /**
141
- * Fraction of a level's extent its window may trail the followed centre by before it re-renders,
142
- * `[0, selectionGuard)`, default 0.125 — `refreshStep: 0` keeps the old one-texel step. The step
143
- * is rounded to a whole number of that level's texels, so a walking camera re-renders a level
144
- * ~`1/refreshStep` times less often while the shadow texels stay on one fixed world grid. Costs
145
- * that much of `selectionGuard`, which it is already reduced by, so a window never reaches past
146
- * the trailing edge of a map rendered before the centre moved. One value for every level, or one
147
- * per level finest first, the last entry standing in for the rest — the fine level is the one a
148
- * walking camera re-renders most, so it is the one that wants the larger step.
149
- */
150
- readonly refreshStep?: number | readonly number[];
151
- /**
152
- * Let a level buy itself a wider `refreshStep` out of what its own last render cost, default true.
153
- *
154
- * A level render is a whole scene draw, so the engine cannot know what one is worth until it has
155
- * paid for it: the node measures the draw it just took and smooths that reading, and a level whose
156
- * smoothed cost is a large share of the frame period is re-rendered less often. This is automatic
157
- * because the value it reacts to is a measurement, not a setting — a game sets nothing, and a
158
- * cheap level is never widened and behaves exactly as before. The widened trail is capped by the
159
- * window's own margin, so the camera stays inside the region that level serves and everything that
160
- * level serves stays inside the map; a level with no such margin is never widened at all.
161
- *
162
- * `false` puts every level back on the `refreshStep` it was given, which is also what a harness
163
- * that wants to count today's renders uses.
164
- * `?tnAdaptiveRefresh=0` in the page URL makes the default `false` from the node's first setup.
165
- */
166
- readonly adaptiveRefresh?: boolean;
167
- /**
168
- * Fraction of the display period a level's smoothed render cost may take before its refresh trail
169
- * widens, `(0, 1]`, default 0.4.
170
- *
171
- * The period is the frame's own `deltaTime`, capped at the 60 fps frame (16.7 ms). The cap is what
172
- * keeps the budget honest: the frame that renders an expensive level is itself long because of that
173
- * render, so reading the share against its own inflated delta would count the cost twice and let
174
- * the very level that needs adapting pass its own test. At 60 Hz the cap is the frame itself; on a
175
- * 120 Hz panel the same render is twice the share it is at 60; below 60 the cap holds the budget
176
- * at the 60 fps frame rather than growing with the stall. Below the share nothing changes at all,
177
- * and above it the trail widens in proportion to the overshoot,
178
- * because that is the ratio between what the level costs and what a frame can afford to spend on
179
- * it — a level four times over the share refreshs about four times less often, until the cap
180
- * below it runs out.
181
- */
182
- readonly expensiveRefreshShare?: number;
183
- /**
184
- * Raise the finest level's texel size gate while its own render is too expensive for the frame, default
185
- * true.
186
- *
187
- * The same measurement adaptive refresh reads — the smoothed cost of the level's own last render,
188
- * against the share of the frame it may take — drives a second, independent adaptation: a level
189
- * whose render is over budget sizes its gate up in steps of 1.5 until it is affordable again, up
190
- * to 8 times the configured gate, and halves it back toward 1 once the render is comfortably under
191
- * half the budget. The gate only ever judges a caster by its size (see `minCasterTexels`), so this
192
- * drops the tiniest props first and never a building, and a level that is cheap is never touched:
193
- * it stays at scale 1 and submits exactly what it did before.
194
- *
195
- * Coarse levels always stay at scale 1 so resolved casters survive the handover.
196
- * `false` pins every level at scale 1, which is also what a harness that wants today's draw
197
- * counts uses.
198
- */
199
- readonly adaptiveCasterGate?: boolean;
200
- /**
201
- * How long a level waits after its own last render before an invalidation may re-render it, in
202
- * seconds. One value for every level, or one per level finest first, the last entry standing in
203
- * for the rest. Default `0.25 * extent / finestExtent` — 0.25 s, 1 s and 3.33 s for extents
204
- * 24 / 96 / 320 — and `0` renders on the very next frame, which is what the node did before.
205
- *
206
- * A streamed world invalidates its shadows on every residency update, and a cell admitted at the
207
- * ring edge lands in the coarsest window: the level that redraws for it is the one paying for the
208
- * whole ring's wide casters, ten times a second where movement alone asks for two. A level
209
- * waiting out its delay keeps the map and window it has, which is already right for every static
210
- * caster in it, so only a newly streamed caster is missing — the trade is that a far tree's
211
- * shadow can appear up to the delay late (3.33 s at extent 320, invisible on a level whose texel
212
- * is wider than the tree). A window that moved is never delayed: that is a different reason, and
213
- * it is not this option's.
214
- */
215
- readonly invalidationDelay?: number | readonly number[];
216
- /**
217
- * How far behind the window centre each level camera sits, in world units. Default 200. An
218
- * explicit `lightDistance` *and* `depthRange` switch the level's light-space depth off the derived
219
- * span below and back onto this pair, so a game that knows its own world sizes can still say so.
220
- */
221
- readonly lightDistance?: number;
222
- /**
223
- * Depth range each level camera covers past its centre, in world units. Default 400. Read only
224
- * together with `lightDistance`; on its own the span is still derived.
225
- */
226
- readonly depthRange?: number;
227
- /**
228
- * Texels of a level a caster must cover before it draws into that level, default 1.5. A level's
229
- * texel is `2 * extent / mapSize`, so the finest levels keep everything and the coarse ones keep
230
- * only what they can resolve: a fern is a whole number of texels in a 48 m window and a fraction
231
- * of one in a 640 m window, so it stops being drawn there and the shadow it casts is the ground
232
- * cover's own, not its silhouette's. Set 0 to draw every caster into every level.
233
- */
234
- readonly minCasterTexels?: number;
235
- /** Follow the framed receiving surface when the eye is more than one fine extent above it.
236
- * Default true; false keeps eye follow for every camera. Walking cameras keep eye follow.
237
- */
238
- readonly followViewFocus?: boolean;
239
- /**
240
- * The smallest ratio of a level's light-space height to its width, `(0, 1]`, default 1 (square levels).
241
- * A low sun stretches a shadow texel along the floor by `1 / sin(elevation)`. A value under 1 shrinks
242
- * the height to `sin(elevation)` times the width, never under this value, so a texel covers the same
243
- * floor area at any sun height. The costs: a wall taller than a level's height is read from a wider
244
- * level, a level centred on the eye holds the floor only about `eye height / tan(elevation)` from the
245
- * camera, and a wide filter disc (a source angle near 0.7 degrees) crosses the level's top and bottom
246
- * edge and leaves a lit patch in a thin shadow (PRD-634, sun 4 ramp), so it is an opt-in.
247
- */
248
- readonly minWindowAspect?: number;
249
- /** Measure receiver-plane slope across each level's texel footprint to prevent coarse acne.
250
- * Default true; false preserves only the authored bias. Custom filterNode owns its footprint.
251
- */
252
- readonly receiverPlaneBias?: boolean;
253
- /**
254
- * Draw registered AutoLOD chains with a coarser rung past the finest level, default true. A level
255
- * takes the coarsest rung whose geometric error is within one of its texels, and never a rung
256
- * finer than the main pass shows; where no rung is that accurate the caster keeps its geometry.
257
- * Alpha-tested and transparent casters keep casting on every level that resolves their bounds;
258
- * dropping their whole shadow at the fine window edge loses canopy and fences.
259
- * Geometry swaps are restored before the next level, mover map and main pass.
260
- */
261
- readonly shadowLodBias?: boolean;
262
- /**
263
- * The most error, in texels of a level, that a coarser rung may have on that level, default 1.
264
- * A rung within a texel is as good as the full mesh at that resolution; a larger budget draws
265
- * fewer triangles and shows facets on a shadow's edge, and `Infinity` draws the coarsest rung on
266
- * every level past the finest. Read only with `shadowLodBias`.
267
- */
268
- readonly shadowLodTexels?: number;
269
- /**
270
- * Redraw only the pages an invalidation dirtied, default true. A level whose window did not move
271
- * and whose asks named under half its pages renders those rectangles alone: pages casters were
272
- * removed from are put back to the far plane first, pages casters streamed into are just drawn.
273
- * `false` renders the whole level for every invalidation, as before. A VSM shadow map always
274
- * renders whole, because its blur pass reads the entire map.
275
- */
276
- readonly partialRedraw?: boolean;
277
- /**
278
- * Quiet frames an automatically detected mover must exceed before it goes back into the cached
279
- * levels, default 100 (Unreal's `FramesStaticThreshold`: it settles on quiet frame 101). A caster whose world matrix, instance matrix or
280
- * deformation changed is drawn through the mover maps without a `trackCaster` call; this is how
281
- * long it must hold still before its shadow is baked into the cache again. Positive integer.
282
- */
283
- readonly staticAfterFrames?: number;
284
- /** Print the `TN_VIRTUAL_SHADOW` line every `markerEvery` frames; `false` silences it. Default 300. */
285
- readonly marker?: boolean | number;
286
- }
287
-
288
- /** Per-frame counters, readable any time through {@link VirtualShadowNode.stats}. */
289
- export interface IVirtualShadowStats {
290
- readonly frame: number;
291
- readonly levels: number;
292
- /** Levels whose window moved this frame and were re-rendered. */
293
- readonly moved: number;
294
- /** Levels re-rendered because `invalidateAll()` or explicit tracker invalidation asked for it. */
295
- readonly invalidated: number;
296
- /** Tracked casters, as of this frame. */
297
- readonly movers: number;
298
- /**
299
- * Casters the node classified as movers by measuring them, as of this frame: a world or instance
300
- * matrix that changed, or a deforming mesh. Counted apart from {@link movers}, which is `trackCaster`.
301
- */
302
- readonly autoMovers: number;
303
- /**
304
- * Static-to-mover and mover-to-static changes of those casters over the node's lifetime. Each one
305
- * asks the levels for one region redraw, never a full one.
306
- */
307
- readonly autoTransitions: number;
308
- /**
309
- * Mean JS time of the classification scan per frame, in milliseconds, over the node's lifetime.
310
- * It is the number the scan's 0.05 ms budget is judged against.
311
- */
312
- readonly autoScanMs: number;
313
- /** Mover maps rendered this frame: one per level when at least one caster is tracked. */
314
- readonly moverRenders: number;
315
- /** Levels served from their cached map this frame. */
316
- readonly cached: number;
317
- /** Levels rendered this frame, for any reason. */
318
- readonly rendered: number;
319
- /**
320
- * Levels that wanted a render this frame and did not get one, because the node renders at most
321
- * one level per frame. They keep the map they already have and come due again next frame.
322
- */
323
- readonly deferred: number;
324
- /**
325
- * Levels holding a redraw for an invalidation that is still inside its own `invalidationDelay`,
326
- * so this frame is not the frame they render on. They keep the map they have, which is right for
327
- * every static caster in it: only a caster streamed in since is missing, and the cumulative
328
- * `coalesced` below is what is being waited out.
329
- */
330
- readonly held: number;
331
- /** Fraction of levels served from cache over the node's lifetime. */
332
- readonly reuseRatio: number;
333
- /**
334
- * Level renders over the node's lifetime, for any reason. `byMove` and `byInvalidation` are the two
335
- * the node has — a window that moved, and an invalidation that asked and waited out its delay — and
336
- * they add up to this exactly, because a render the single per-frame budget defers is counted
337
- * against the reason that queued it and not again when it is finally taken.
338
- */
339
- readonly rendersTotal: number;
340
- /** Of those, the renders taken because a level's window moved. */
341
- readonly byMove: number;
342
- /**
343
- * Pages every level's window travelled between its renders, over the node's lifetime: the sum of
344
- * `|ΔminX| + |ΔminY|` at each render. Unlike `byMove` it does not depend on how many frames sampled
345
- * the path, so two runs of one route at different frame rates report the same number.
346
- */
347
- readonly windowSteps: number;
348
- /** Of those, the renders taken because an invalidation asked and its level's delay had passed. */
349
- readonly byInvalidation: number;
350
- /** Of the renders taken for an invalidation (`byInvalidation`), those whose dirty set held only streamed-in casters. */
351
- readonly byAdmission: number;
352
- /** 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. */
353
- readonly byEviction: number;
354
- /** Pages the dirty set held at each render, summed over the node's lifetime. A window move counts the whole level. */
355
- readonly pagesDirty: number;
356
- /** Pages each render actually drew, summed over the node's lifetime. Equals pagesDirty once a partial redraw exists. */
357
- readonly pagesRedrawn: number;
358
- /**
359
- * Invalidation asks that cost no render of their own, over the node's lifetime: absorbed by a
360
- * render the level was taking anyway for its window, or merged into an ask already waiting out
361
- * that level's delay. The two of these are the shape of the win — with the default delays a walk
362
- * asks once a second and renders about that often, and every ask in between is counted here.
363
- */
364
- readonly coalesced: number;
365
- /**
366
- * The same four counters per level, finest first: which window moved, which invalidation asked
367
- * for a redraw, which level took the frame's single render, and which wanted one and did not get
368
- * it. One entry per level per frame, so a harness reading this — or the `TN_VIRTUAL_SHADOW`
369
- * marker line, which carries it — can see which level a walk keeps re-rendering instead of only
370
- * how many.
371
- */
372
- readonly perLevel: readonly IVirtualShadowLevelStat[];
373
- }
374
-
375
- /** One level's row of {@link IVirtualShadowStats}: 1 or 0 per counter, per frame. */
376
- export interface IVirtualShadowLevelStat {
377
- /** The level's clip extent, in world units. */
378
- readonly extent: number;
379
- readonly deferred: number;
380
- readonly invalidated: number;
381
- readonly moved: number;
382
- readonly rendered: number;
383
- /** Caster meshes this level's chosen camera layers submit this frame. Zero if it did not render. */
384
- readonly draws: number;
385
- /** The same bill split by kind; the five parts sum to {@link draws}. */
386
- readonly drawsBy: IVirtualShadowDraws;
387
- /** The adaptive caster gate's scale on this level, 1 when it is not shedding casters. */
388
- readonly gateScale: number;
389
- /** Casters the gate hid on the render this level took this frame; zero if it did not render. */
390
- readonly gateHidden: number;
391
- }
392
-
393
- /** One level's caster draws, by the kind of mesh that submitted them. */
394
- export interface IVirtualShadowDraws {
395
- /** Caster batch meshes on the cluster layer, when the cluster half is the level's choice. */
396
- readonly cluster: number;
397
- /** Key-wide caster meshes on the wide layer, when the wide half is the level's choice. */
398
- readonly wide: number;
399
- /** Small casters, submitted by the finest level and by any level rendering a prewarm. */
400
- readonly small: number;
401
- /** Merged per-chunk shadow proxies (`<name>-shadow`), drawn with either caster half. */
402
- readonly chunkProxy: number;
403
- /** Everything else casting from layer 0 — terrain, props — which every level draws. */
404
- readonly layer0: number;
405
- /**
406
- * GPU-scene keys: one mesh per `asset:level:part` drawn from the level's own twin of the dispatch's
407
- * output, which is the whole of what a keyed map submits of the world. Zero unless a provider
408
- * registered and `?tnShadowGpuKeys=1` asked, and then it replaces {@link cluster} and {@link wide}
409
- * rather than adding to them: the keys draw the placements those two would have.
410
- */
411
- readonly keys: number;
412
- }
413
-
414
- /** The mutable tally `#probe` fills; the public row only ever reads it. */
415
- interface IVirtualShadowDrawTally {
416
- cluster: number;
417
- wide: number;
418
- small: number;
419
- chunkProxy: number;
420
- layer0: number;
421
- keys: number;
422
- }
423
-
424
- export const VIRTUAL_SHADOW_MARKER = "TN_VIRTUAL_SHADOW";
425
- /**
426
- * One line per level whose refresh trail adaptive refresh widened, at most once a second: the level,
427
- * the width of the window it re-renders, the smoothed cost of that render in ms, and the trail it
428
- * bought. A browser run can see which level is being throttled and by how much, which is the only
429
- * way to tell an expensive level from a slow frame.
430
- */
431
- export const VIRTUAL_SHADOW_REFRESH_MARKER = "TN_SHADOW_REFRESH";
432
- /** Seconds between two `TN_SHADOW_REFRESH` lines for the same level. */
433
- const REFRESH_MARKER_SECONDS = 1;
434
- /**
435
- * One line per level whose adaptive caster gate changed, at most once a second: the level, the width
436
- * of the window it re-renders, the smoothed cost of that render, the scale its gate bought, and how
437
- * many casters that gate hid on the render the change was read from. A browser run can see which
438
- * level is shedding its tiniest props and by how much.
439
- */
440
- export const VIRTUAL_SHADOW_GATE_MARKER = "TN_SHADOW_GATE";
441
- /** Seconds between two `TN_SHADOW_GATE` lines for the same level. */
442
- const GATE_MARKER_SECONDS = 1;
443
- /** How much a level's texel gate steps up per over-budget render. */
444
- const GATE_SCALE_RISE = 1.5;
445
- /** The most a level's texel gate may scale up, so a big building is never in reach. */
446
- const GATE_SCALE_CAP = 8;
447
- /** How much the gate steps back toward 1 once the render is comfortably under budget. */
448
- const GATE_SCALE_DECAY = 0.5;
449
- /** Below this share of the affordable budget a level's gate decays; between, it holds. */
450
- const GATE_DECAY_SHARE = 0.5;
451
- /**
452
- * How much of a level's last two render costs the smoothed cost keeps, `(0, 1]`. Half and half, so a
453
- * first draw with a cold pipeline is not the level's price for the rest of the session.
454
- */
455
- const COST_SMOOTHING = 0.5;
456
- /**
457
- * A level's first measured renders are thrown away before its cost is trusted. The first draw of a
458
- * map compiles its shaders and uploads its textures, so it reads tens of milliseconds however cheap
459
- * the level is; seeding the smoothed cost with that warm-up would widen the trail or raise the gate
460
- * for a level that is not actually expensive. Two renders is enough for the pipeline to be warm.
461
- */
462
- const COST_WARMUP_RENDERS = 2;
463
- /**
464
- * The object layer tracked casters are enabled on, so each level's mover camera sees only them.
465
- * Keep it free of other uses; the main camera never needs it (tracked objects keep layer 0).
466
- */
467
- export const VIRTUAL_SHADOW_MOVER_LAYER = 29;
468
- /**
469
- * The object layer a shadow-only caster is put on, so each level's own shadow camera renders it and
470
- * the main camera never sees it. The level cameras have it enabled already; an object that exists
471
- * only as a shadow caster calls `object.layers.set(VIRTUAL_SHADOW_CASTER_LAYER)`.
472
- */
473
- // The layer a shadow-only object is put on: a level's own shadow camera renders it, the main
474
- // camera never sees it. Three skips an object whose layers do not meet the camera's, and it
475
- // overwrites a shadow camera's mask with the main camera's whenever that mask is layer 0 and
476
- // nothing else — so enabling this bit on the level cameras is also what pins their mask, and a
477
- // caster that lives only on it is reachable from the cascade and from nothing else. 28 is below the
478
- // mover layer and off the main camera, which renders layer 0.
479
- export const VIRTUAL_SHADOW_CASTER_LAYER = 28;
480
- /**
481
- * The wide counterpart of {@link VIRTUAL_SHADOW_CASTER_LAYER}: one caster mesh per
482
- * `asset:level:part` holding every resident cell's records, for the levels whose window covers the
483
- * whole resident ring. A level renders exactly one of the two caster layers — whichever submits
484
- * fewer draws, counted off the meshes themselves, because a cluster per square is a draw per square
485
- * for the same pixels once the window holds the ring. `WorldCells` writes both halves of every key,
486
- * so whichever a level picks is there; the main camera renders neither.
487
- */
488
- export const VIRTUAL_SHADOW_WIDE_CASTER_LAYER = 27;
489
- /**
490
- * The wide half of short assets: ferns, grass and bushes. `WorldCells` classifies assets by
491
- * `shadows.smallCasterMetres`; every level then applies its measured texel gate, so a resolved
492
- * shadow survives the fine window's edge. The main camera never draws this internal layer.
493
- */
494
- export const VIRTUAL_SHADOW_SMALL_CASTER_LAYER = 26;
495
- /**
496
- * The counterpart of both caster layers for a GPU-driven map: one mesh per `asset:level:part`
497
- * drawing that key's shadow twin, so a level submits one indirect draw per key instead of one per
498
- * grid square. `WorldCells` mints these instead of the two caster halves when a shadow level draws
499
- * from the GPU scene (`?tnShadowGpuKeys=1`), and every level camera carries this bit, which is why
500
- * it is not one half of a choice: a key is the whole of what a keyed map draws of the world.
501
- */
502
- export const VIRTUAL_SHADOW_KEY_LAYER = 25;
503
- const DEFAULT_CLIP_EXTENTS: readonly number[] = [16, 48, 144];
504
- /** Square levels. A fit to the ground (`0.25`, a 14.5 degree sun is where it ends) is the named override. */
505
- const DEFAULT_MIN_WINDOW_ASPECT = 1;
506
- const DEFAULT_MARKER_EVERY = 300;
507
- /** Frames between markers while `?tnShadowStats=1` is on the URL: about a second a walk is long. */
508
- const STATS_QUERY_EVERY = 60;
509
- /**
510
- * The invalidation delay of the *finest* level, in seconds; every other level's is this times its
511
- * extent over the finest one. A burst of streamed invalidations is paid as one render, and the
512
- * level that pays it is the one whose window is widest.
513
- */
514
- const BASE_INVALIDATION_DELAY = 0.25;
515
177
  /**
516
178
  * Share of GPU time a level's invalidation redraws may take when the game left `invalidationDelay`
517
179
  * to the engine: a redraw that cost `c` ms waits at least `c / share` ms after the last one. A 5 ms
518
180
  * redraw never reaches the base delay; a 300 ms one on an integrated GPU waits 3 s instead of 0.25 s.
519
181
  */
520
182
  const INVALIDATION_GPU_SHARE = 0.1;
521
- const DEFAULT_MIN_CASTER_TEXELS = 1.5;
522
- /** Unreal's `r.Shadow.Virtual.Cache.FramesStaticThreshold`: quiet frames before a mover is static. */
523
- const DEFAULT_STATIC_AFTER_FRAMES = 100;
524
- /**
525
- * The share of the display period a level's render may cost before adaptive refresh widens its
526
- * trail: two frames in five, 6.7 ms of a 60 Hz frame. A draw that big is worth a whole frame of its
527
- * own, and a share rather than a millisecond count is what makes the same number mean the same thing
528
- * on a 120 Hz panel.
529
- */
530
- const DEFAULT_EXPENSIVE_REFRESH_SHARE = 0.4;
183
+
531
184
  /**
532
185
  * The floor on a light's vertical magnitude: a horizontal window's height-to-depth conversion
533
186
  * grows without limit as the sun sets.
534
187
  */
535
188
  const MIN_SUN_COSINE = 0.05;
536
189
 
537
- /**
538
- * World spheres one level render collects: centre, radius, shadow flags, the box's own height
539
- * range, seven numbers each.
540
- */
541
- const POOL_STRIDE = 7;
542
- /**
543
- * How many window widths a caster may be before the window is cut out of it instead. One: an
544
- * object wider than the window it is in is a mass, and only its height reaches the frustum.
545
- */
546
- const MAX_MASS_WINDOW_WIDTHS = 1;
547
- const POOL_CASTERS = 1 << 0;
548
-
549
- /**
550
- * A mesh in the caster table, with the three channels the probe reads off the object rather than off
551
- * the geometry: the bounds three's own cull would use, which `Mesh` does not declare, the
552
- * `casterPrewarmOwed` flag `WorldCells` writes (see `SharedBatch.awaitPrewarmDraw`), and the
553
- * `mainAdmitted` answer it publishes for a caster half (see `SharedBatch.setMainAdmitted`).
554
- */
555
- interface ICasterMesh extends Mesh {
556
- boundingBox?: Box3 | null;
557
- boundingSphere?: Sphere | null;
558
- casterPrewarmOwed?: boolean;
559
- mainAdmitted?: boolean;
560
- chunkShadowProxy?: boolean;
561
- casterMinDiameter?: number;
562
- computeBoundingBox(): void;
563
- computeBoundingSphere(): void;
564
- }
565
-
566
- /**
567
- * One caster's memoised world values, and the inputs they were derived from.
568
- *
569
- * The key is the world matrix plus the local sphere and the local box's two Y values — everything
570
- * `Sphere.applyMatrix4` and `Box3.applyMatrix4` read, and nothing else. Twenty-two doubles compare
571
- * against the pair of matrix applies they replace, and a key that matches cannot have a different
572
- * answer, so this is a memo on the inputs rather than a guess about whether the mesh moved. A
573
- * caster under a frozen subtree, a streamed cell nobody touched and a walking stag are therefore
574
- * the same case: whichever of them changed its world matrix is recomputed, and the rest are not.
575
- *
576
- * A fresh slot is all zeros, which no world matrix can be — its last element is 1 — so the first
577
- * render of a caster always misses and always computes.
578
- */
579
- const CASTER_KEY_STRIDE = 22;
580
- /** World centre and radius, then the box's world height range: what the pool row is written from. */
581
- const CASTER_WORLD_STRIDE = 6;
582
- const CASTER_STRIDE = CASTER_KEY_STRIDE + CASTER_WORLD_STRIDE;
583
-
584
- const MOTION_STATIC = 0;
585
- /** Drawn through the mover maps and kept out of the cached levels. */
586
- const MOTION_MOVER = 1;
587
- /**
588
- * Back in the cached levels, still drawn through the mover maps until every level the redraw asked
589
- * has rendered it, so the shadow never drops out between the two.
590
- */
591
- const MOTION_SETTLING = 2;
592
-
593
- /** What the motion scan remembers of one caster mesh between frames. */
594
- interface ICasterMotion {
595
- /** The 16 world-matrix elements at the last scan: where the cached levels last saw it. */
596
- readonly world: Float64Array;
597
- /** `instanceMatrix.version` at the last scan; unused on a plain mesh. */
598
- instanceVersion: number;
599
- phase: typeof MOTION_STATIC | typeof MOTION_MOVER | typeof MOTION_SETTLING;
600
- /** `pinStatic` named this mesh or an ancestor. */
601
- pinned: boolean;
602
- /** Consecutive scans without movement while a mover. */
603
- quiet: number;
604
- }
605
-
606
- /**
607
- * What a world publishes on its root for a shadow level to draw a map from GPU-scene keys:
608
- * `(renderer, level) => void`, the level's own three numbers and the scene that selects against them.
609
- *
610
- * Engine-internal and duck-typed. `WorldCells` publishes it as `tnShadowGpuKeys`; nothing in a
611
- * template or a manifest names it, and this module cannot import the world package to name the type,
612
- * so the contract is the call and the flag behind it.
613
- */
614
- type IShadowKeyDispatch = (renderer: unknown, level: IShadowLevelNumbers) => void;
615
-
616
- /**
617
- * One shadow map's own three numbers, duck-typed from `world-gpu-scene`'s `IShadowLevel`: the six
618
- * planes of this map's own shadow camera, its texel gate in world metres, and the chain level it
619
- * draws at. Typed here rather than imported for the
620
- * same reason as the dispatch above.
621
- */
622
- interface IShadowLevelNumbers {
623
- readonly planes: Float32Array;
624
- readonly gate: number;
625
- readonly base: number;
626
- }
627
-
628
- /** A placeholder light per level: the stock shadow node reads position and target from it. */
629
- class LevelLight extends Object3D {
630
- readonly target = new Object3D();
631
- shadow: DirectionalLight["shadow"];
632
- override castShadow = true;
633
-
634
- constructor(shadow: DirectionalLight["shadow"]) {
635
- super();
636
- this.shadow = shadow;
637
- }
638
- }
639
-
640
- interface ILevel {
641
- readonly light: LevelLight;
642
- readonly shadow: DirectionalLight["shadow"];
643
- readonly node: ReturnType<typeof shadow>;
644
- /** Same window and placement as `shadow`, rendered every frame with only the tracked casters. */
645
- readonly moverShadow: DirectionalLight["shadow"];
646
- readonly moverNode: ReturnType<typeof shadow>;
647
- readonly extent: number;
648
- readonly extentUniform: UniformNode<"float", number>;
649
- /**
650
- * The light-space depth this level's last render derived: how far behind its window centre the
651
- * camera sat, and the near/far it drew with. Held between renders, because a level that keeps its
652
- * map is placed with the same span it drew that map with.
653
- */
654
- eye: number;
655
- depthNear: number;
656
- depthFar: number;
657
- minX: number;
658
- minY: number;
659
- /** Light-space depth of the window centre when this level's map was last rendered. */
660
- centerW: number;
661
- /**
662
- * 1 once this level's map has been rendered at least once, 0 until then. A fragment never
663
- * samples a map this level has not drawn yet: with one render per frame the coarse levels are
664
- * behind on the frame the fine one comes due, and their targets have no depth in them yet.
665
- */
666
- readonly mapped: UniformNode<"float", number>;
667
- /**
668
- * Set when an invalidation asked for a redraw that has not been rendered yet, 0 until then. The
669
- * ask is held here instead of being consumed on the frame it arrives, so a level can wait out
670
- * `invalidationDelay` and still redraw; a render of any reason clears it.
671
- */
672
- dirty: boolean;
673
- /**
674
- * The pages casters streamed into since this level's last render, in the clipmap's absolute page
675
- * coordinates, or undefined while none did. An added caster only brings depth closer, so these
676
- * pages need no clear. Meaningless while {@link dirtyAll} is set.
677
- */
678
- dirtyAdmit: IPageRect | undefined;
679
- /**
680
- * The pages any other ask touched: a removed caster, a flag change, the tracker's pages. The old
681
- * depth in them can be wrong, so they are put back to the far plane before they are redrawn.
682
- */
683
- dirtyEvict: IPageRect | undefined;
684
- /** An ask named no pages, or none inside the window, so the whole level is dirty. */
685
- dirtyAll: boolean;
686
- /** The rectangle this level is rendering now, set only around a partial redraw. */
687
- pass: IPartialPass | undefined;
688
- /** The caster interval along the light, from the centre, that the derived depth was drawn for. */
689
- drawnSpan: ILightAxisRange;
690
- /**
691
- * The engine frame clock's reading when this level last rendered, in seconds. A dirty level
692
- * re-renders for the invalidation no sooner than `invalidationDelay` after this. `-Infinity`
693
- * until the first render, so a level invalidated before it holds a map is due immediately.
694
- */
695
- lastRender: number;
696
- /**
697
- * Why this level owes a render the frame's single budget did not grant it: {@link REASON_NONE},
698
- * and the reason it was due otherwise. Sticky, so a level that was passed over stays due on the
699
- * next frame instead of waiting for its window to move again — and the render it eventually takes
700
- * is counted against the reason that queued it.
701
- */
702
- pending: RenderReason;
703
- /**
704
- * Smoothed cost of this level's own last render, in milliseconds, and 0 until it has rendered
705
- * once. This is the only measure of what a level's render is worth there is — a level render is a
706
- * whole scene draw — and what it buys is a wider refresh trail; see `adaptiveRefresh`.
707
- */
708
- costMs: number;
709
- /**
710
- * How many of this level's renders have been measured, warm-up included. The first
711
- * {@link COST_WARMUP_RENDERS} are compile and upload, not the level's price, so `costMs` stays 0
712
- * until the counter passes them and nothing adapts before it.
713
- */
714
- costReadings: number;
715
- /**
716
- * The trail this level is actually being stepped with, which is its configured `refreshStep`
717
- * until a measurement widens it. Held so a level that got cheap again is put back rather than
718
- * left on the trail it bought.
719
- */
720
- appliedStep: number;
721
- /** Engine clock of this level's last `TN_SHADOW_REFRESH` line, in seconds. */
722
- lastRefreshNote: number;
723
- /**
724
- * The adaptive caster gate's scale on this level: the factor `minCasterTexels` is multiplied by,
725
- * 1 until a render comes in over budget. See `adaptiveCasterGate`.
726
- */
727
- gateScale: number;
728
- /**
729
- * The texel gate `#probe` last computed for this level, in world metres. Held so the level's own
730
- * dispatch is handed the gate that render decided on, rather than recomputing it and risking the
731
- * two answering about different numbers. 0 until the level has been probed.
732
- */
733
- gateMetres: number;
734
- /**
735
- * Casters the adaptive gate hid on this level's last render, for the `TN_SHADOW_GATE` line. Not
736
- * reset by a frame that did not render: the line reports the render the change was read from.
737
- */
738
- gateHidden: number;
739
- /** Engine clock of this level's last `TN_SHADOW_GATE` line, in seconds. */
740
- lastGateNote: number;
741
- /**
742
- * Engine clock of the render whose cost the gate has already been adapted to. `#adaptiveTrails`
743
- * changes the scale at most once per render, never twice for the same measured cost.
744
- */
745
- gatedRender: number;
746
- /**
747
- * Where this level's *rendered* map sits, relative to the centre the fragment test measures
748
- * from. A level whose re-render was deferred still holds an older window, and its selection has
749
- * to be made against that window rather than the followed centre: the sampler reads through this
750
- * level's own camera, so testing against anything else is what makes a fragment reach past a
751
- * rendered map.
752
- */
753
- readonly offsetU: UniformNode<"float", number>;
754
- readonly offsetV: UniformNode<"float", number>;
755
- /** This level's own guarded extent fraction, for the same reason. */
756
- readonly guardUniform: UniformNode<"float", number>;
757
- }
758
-
759
- type ShadowWithFilter = DirectionalLight["shadow"] & { filterNode?: unknown };
760
-
761
190
  const _direction = new Vector3();
762
191
  const _center = new Vector3();
763
192
  const _sphere = new Sphere();
@@ -768,7 +197,6 @@ const _forward = new Vector3();
768
197
  /** A level's own light frustum, read once per level render and handed to its dispatch. */
769
198
  const _shadowProjection = new Matrix4();
770
199
  const _oldWorld = new Matrix4();
771
- const _shadowFrustum = new Frustum();
772
200
  const _shadowPlanes = new Float32Array(24);
773
201
  /** The depth row a level's map was drawn under, and the one this frame proposes: uploaded float32. */
774
202
  const _drawnDepth = new Float32Array(4);
@@ -779,147 +207,6 @@ const _proposedDepth = new Float32Array(4);
779
207
  */
780
208
  const COARSEST_SHADOW_LEVEL = 1 << 20;
781
209
 
782
- /** The state cached maps depend on: visible, casting, and admitted by the main pass. */
783
- /** A skinned mesh, or one with a morph target weighted above zero: its pixels change with no matrix change. */
784
- function deforms(mesh: Mesh): boolean {
785
- if ((mesh as { isSkinnedMesh?: boolean }).isSkinnedMesh === true) return true;
786
- const influences = mesh.morphTargetInfluences;
787
- if (influences === undefined) return false;
788
- for (const weight of influences) if (weight !== 0) return true;
789
- return false;
790
- }
791
-
792
- function casterFlag(mesh: {
793
- castShadow?: boolean;
794
- mainAdmitted?: boolean;
795
- userData?: { tnShadowSwap?: unknown };
796
- visible?: boolean;
797
- }): number {
798
- // A mesh marked tnShadowSwap trades visibility with a twin over the same ground — terrain's
799
- // tile and merged block, or one LOD level for the next. That flip is not a change the cached map
800
- // must redraw for (it measured ~80 % of a walk's flips); castShadow and mainAdmitted still are,
801
- // and the next window move redraws whatever resolution difference a LOD step left behind.
802
- return (
803
- (mesh.visible === true || mesh.userData?.tnShadowSwap === true ? 1 : 0) |
804
- (mesh.castShadow === true ? 2 : 0) |
805
- (mesh.mainAdmitted === false ? 4 : 0)
806
- );
807
- }
808
-
809
- /** The per-level entry of a scalar-or-array option, the last entry standing in for the rest. */
810
- function at(values: readonly number[], level: number): number {
811
- return values[Math.min(level, values.length - 1)] as number;
812
- }
813
-
814
- /**
815
- * The diameter a shadow level's texel gate judges one caster by: the part's own geometry radius
816
- * times the largest instance scale `WorldCells` placed into this batch, or the mesh's own sphere
817
- * when it publishes no scale (anything the world does not own).
818
- */
819
- function instanceDiameter(mesh: Mesh, sphereRadius: number): number {
820
- const scale = (mesh as Mesh & { casterInstanceScale?: number }).casterInstanceScale;
821
- if (scale === undefined || scale <= 0) return sphereRadius * 2;
822
- const geometry = mesh.geometry;
823
- if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
824
- const radius = geometry.boundingSphere?.radius;
825
- if (radius === undefined || radius <= 0) return sphereRadius * 2;
826
- return radius * 2 * scale;
827
- }
828
-
829
- /**
830
- * The geometry a caster draws into a level past the finest: the coarsest rung of its AutoLOD chain
831
- * whose error stays within `budget` (world units: texels of the level times `shadowLodTexels`), and
832
- * never finer than the rung the main pass shows, which the viewer already cannot tell apart. Where
833
- * no rung is that accurate the mesh keeps what it has. A rung whose error is more than a texel
834
- * draws as a facet on the shadow's edge: the coarsest rung of a sphere, 60 mm out, put straight
835
- * segments on a 7 mm texel. `undefined` leaves the geometry alone.
836
- */
837
- function shadowLod(mesh: Mesh, budget: number): BufferGeometry | undefined {
838
- const chain = lodChainOf(mesh.geometry);
839
- if (chain === undefined) return undefined;
840
- // The largest instance scale `WorldCells` placed into this batch is on top of the mesh's own.
841
- const placed = (mesh as Mesh & { casterInstanceScale?: number }).casterInstanceScale;
842
- const scale =
843
- mesh.matrixWorld.getMaxScaleOnAxis() * (placed !== undefined && placed > 0 ? placed : 1);
844
- const shown = chain.levels.indexOf(mesh.geometry);
845
- for (let rung = chain.levels.length - 1; rung > shown; rung -= 1) {
846
- if ((chain.errors[rung] as number) * scale <= budget) return chain.levels[rung];
847
- }
848
- return undefined;
849
- }
850
-
851
- /** Keep each stock node's source-owned settings aligned with the public light shadow. */
852
- function syncShadowSettings(
853
- source: DirectionalLight["shadow"],
854
- target: DirectionalLight["shadow"],
855
- ): void {
856
- target.bias = source.bias;
857
- target.biasNode = source.biasNode;
858
- target.blurSamples = source.blurSamples;
859
- target.intensity = source.intensity;
860
- target.mapType = source.mapType;
861
- target.normalBias = source.normalBias;
862
- target.radius = source.radius;
863
- (target as ShadowWithFilter).filterNode = (source as ShadowWithFilter).filterNode;
864
- }
865
-
866
- function syncLevelShadowSettings(
867
- source: DirectionalLight["shadow"],
868
- levels: readonly ILevel[],
869
- ): void {
870
- for (const level of levels) {
871
- syncShadowSettings(source, level.shadow);
872
- syncShadowSettings(source, level.moverShadow);
873
- }
874
- }
875
-
876
- /** The stock node's target factory, which three calls once from `setupShadow`. */
877
- interface IStockShadowTarget {
878
- setupRenderTarget(
879
- shadow: unknown,
880
- builder: NodeBuilder,
881
- ): { shadowMap: RenderTarget; depthTexture: unknown };
882
- }
883
-
884
- /**
885
- * Move a receiver input into the render group. The patched renderer skips object-group uploads for
886
- * a settled static object, so a value in that group freezes at whatever the receiver settled with.
887
- */
888
- function rendered<T>(node: T): T {
889
- // quality-allow: three's ReferenceNode has setGroup at runtime; its declaration omits it
890
- return (node as unknown as { setGroup(group: typeof renderGroup): T }).setGroup(renderGroup);
891
- }
892
-
893
- /**
894
- * Register a stock shadow node's render target with the renderer the moment the node creates it,
895
- * inside the material build and before any bind group can sample its depth texture.
896
- *
897
- * three re-versions a target's depth texture on the target's *first* registration — the size
898
- * branch of `Textures.updateRenderTarget`, which finds no recorded size — and when a bind group
899
- * already holds that texture the re-version destroys its GPUTexture. Every submit through that bind
900
- * group then fails with `Destroyed texture [Texture "ShadowDepthTexture"] used in a submit`, and a
901
- * settled static object never rebuilds its bind group, so nothing is presented again. A level whose
902
- * first render comes after the main pass bound its map — every level but the one drawn in the first
903
- * frame, every mover map, and every level a warm-up compile binds — hit it once per scene.
904
- * Registering at creation makes that first registration happen before anything is bound.
905
- */
906
- function registeredOnCreate<T>(node: T): T {
907
- // quality-allow: Three's public node type omits the target setup hook this wrapper must replace
908
- const stock = node as unknown as IStockShadowTarget;
909
- const create = stock.setupRenderTarget.bind(stock);
910
- stock.setupRenderTarget = (lightShadow, builder) => {
911
- const made = create(lightShadow, builder);
912
- // A renderer without three's texture manager (a test double) registers on first render.
913
- // quality-allow: Three's public renderer type hides the manager that must register this target early
914
- const host = builder.renderer as unknown as {
915
- _textures?: { updateRenderTarget?(target: RenderTarget): void };
916
- };
917
- host._textures?.updateRenderTarget?.(made.shadowMap);
918
- return made;
919
- };
920
- return node;
921
- }
922
-
923
210
  /** The stock node's render entry, called here so the mover exclusion brackets exactly one render. */
924
211
  interface IRenderingShadowNode {
925
212
  updateShadow(frame: NodeFrame): void;
@@ -927,8 +214,11 @@ interface IRenderingShadowNode {
927
214
 
928
215
  /** The slot the native bridge fills with its command sink on a core shadow node. */
929
216
  const COMMAND_KEY = Symbol.for("threenative.virtualShadowCommand");
217
+ /** The owned engine runs the clipmap and never calls updateBefore: it answers `settled` here each world render. */
218
+ const ENGINE_SETTLED_KEY = Symbol.for("threenative.virtualShadowSettled");
930
219
  interface ICommandSlot {
931
220
  [COMMAND_KEY]?: (value: object) => void;
221
+ [ENGINE_SETTLED_KEY]?: boolean;
932
222
  }
933
223
 
934
224
  /**
@@ -958,11 +248,13 @@ interface ICommandSlot {
958
248
  * @situation shadow map too coarse over a big terrain
959
249
  * @situation one directional light shadow for a whole open world
960
250
  * @situation shadows shimmer when the camera moves
251
+ * @situation shadow edges, tree lighting or level sharpness change while a third-person camera turns around its hero
961
252
  * @constraint the light must be a DirectionalLight with `castShadow` and a target in the scene
962
253
  * @constraint clipExtents are half-widths in world units, finest first, strictly increasing
963
254
  * @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
964
255
  * @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
965
256
  * @override bias, biasNode, normalBias, intensity, radius, blurSamples, mapType and filterNode stay on `light.shadow`; mapSize and the other options here have defaults
257
+ * @override setFocus(point) centres every window on a subject (a third-person hero) instead of the eye, so an orbiting eye moves no shadow; setFocus(undefined) hands them back
966
258
  * @override followViewFocus: false keeps eye follow; receiverPlaneBias: false uses only authored bias
967
259
  * @override minWindowAspect: below 1, a level is as high as `sin(sun elevation)` times its width, never under this, so a low sun's floor shadows keep the texel density of a high sun's; the default 1 keeps square levels
968
260
  * @example
@@ -1007,6 +299,27 @@ export class VirtualShadowNode extends ShadowBaseNode {
1007
299
  */
1008
300
  readonly tracker: ShadowInvalidationTracker;
1009
301
  #levels: ILevel[] = [];
302
+ /** Core startup cover: drain all due levels without steady-state invalidation delays. */
303
+ startupCovered = false;
304
+ /** Three's type flag; core's startup gate reads it so the game loop never imports this class. */
305
+ readonly isVirtualShadowNode = true;
306
+
307
+ /** Every map is present and no requested/delayed invalidation remains. */
308
+ get settled(): boolean {
309
+ const engine = (this as ICommandSlot)[ENGINE_SETTLED_KEY];
310
+ if (engine !== undefined) return engine;
311
+ return (
312
+ this.#initialised &&
313
+ this.#levels.length > 0 &&
314
+ !this.#invalidateAll &&
315
+ this.#regions.length === 0 &&
316
+ !(this.light as DirectionalLight).shadow.needsUpdate &&
317
+ this.tracker.pending === 0 &&
318
+ this.#levels.every(
319
+ (level) => level.mapped.value === 1 && !level.dirty && level.pending === REASON_NONE,
320
+ )
321
+ );
322
+ }
1010
323
  #invalidateAll = false;
1011
324
  /** Regions handed to `invalidateRegion`, read and cleared by the next `updateBefore`. */
1012
325
  #regions: Array<IBoundsLike & { admission?: true; urgent?: true }> = [];
@@ -1029,6 +342,8 @@ export class VirtualShadowNode extends ShadowBaseNode {
1029
342
  #autoTransitions = 0;
1030
343
  #autoScanTotalMs = 0;
1031
344
  #moverLayerStates = new Map<Object3D, { originallyEnabled: boolean; references: number }>();
345
+ /** The declared subject every window centres on, if any; see {@link setFocus}. */
346
+ #focus: Vector3 | undefined;
1032
347
  #centerU: UniformNode<"float", number> = uniform(0).setGroup(renderGroup);
1033
348
  #centerV: UniformNode<"float", number> = uniform(0).setGroup(renderGroup);
1034
349
  #moversActive: UniformNode<"float", number> = uniform(0).setGroup(renderGroup);
@@ -1158,10 +473,47 @@ export class VirtualShadowNode extends ShadowBaseNode {
1158
473
  }
1159
474
  const authoredExtents = options.clipExtents ?? DEFAULT_CLIP_EXTENTS;
1160
475
  const autoMapSize = options.mapSize === undefined;
476
+ const maxLevelRatio = options.maxLevelRatio ?? DEFAULT_MAX_LEVEL_RATIO;
477
+ if (!(maxLevelRatio > 1)) {
478
+ throw new RangeError(
479
+ `TN_VIRTUAL_SHADOW_INVALID: maxLevelRatio must be greater than 1, got ${String(maxLevelRatio)}.`,
480
+ );
481
+ }
1161
482
  // The rule takes the bias for every level; authored sizes take it on the finest window.
1162
- const clipExtents = authoredExtents.map((extent, level) =>
483
+ const biased = authoredExtents.map((extent, level) =>
1163
484
  level === 0 && !autoMapSize ? extent * 2 ** bias : extent,
1164
485
  );
486
+ const sizes = options.mapSize ?? light.shadow.mapSize.width;
487
+ const sizeOf = (authored: number): number =>
488
+ (typeof sizes === "number" ? sizes : sizes[Math.min(authored, sizes.length - 1)]) as number;
489
+ // Unreal's levels are virtual and page in on demand; ours are resident, so an inserted level
490
+ // must fit the page budget. A ladder that does not keeps the smallest step that does.
491
+ const pageBudget = options.maxPhysicalPages ?? 4096;
492
+ const pagesOf = (source: readonly number[]): number =>
493
+ source.reduce((sum, authored) => sum + Math.ceil(sizeOf(authored) / 128) ** 2, 0);
494
+ let levelRatio = maxLevelRatio;
495
+ let ladder = clipLadder(biased, levelRatio);
496
+ while (ladder.extents.length > biased.length && pagesOf(ladder.source) > pageBudget) {
497
+ levelRatio *= 1.05;
498
+ ladder = clipLadder(biased, levelRatio);
499
+ }
500
+ if (levelRatio > maxLevelRatio) {
501
+ console.info(
502
+ `TN_VIRTUAL_SHADOW_LADDER the ${String(pageBudget)}-page budget keeps a ${levelRatio.toFixed(2)}x level step (asked ${String(maxLevelRatio)}x); raise maxPhysicalPages or lower mapSize for the full ladder.`,
503
+ );
504
+ }
505
+ const widest = Math.max(
506
+ 1,
507
+ ...biased.slice(1).map((extent, i) => extent / (biased[i] as number)),
508
+ );
509
+ if (maxLevelRatio > DEFAULT_MAX_LEVEL_RATIO && widest > DEFAULT_MAX_LEVEL_RATIO) {
510
+ console.info(
511
+ `TN_VIRTUAL_SHADOW_OVERRIDE maxLevelRatio=${String(maxLevelRatio)} keeps a ${widest.toFixed(1)}x level step (default ${String(DEFAULT_MAX_LEVEL_RATIO)}x).`,
512
+ );
513
+ }
514
+ const clipExtents = ladder.extents;
515
+ // A per-level list names authored levels; an inserted level takes the one it leads into.
516
+ const authoredLevel = (level: number): number => ladder.source[level] as number;
1165
517
  if (
1166
518
  bias !== 0 &&
1167
519
  clipExtents.length > 1 &&
@@ -1171,11 +523,7 @@ export class VirtualShadowNode extends ShadowBaseNode {
1171
523
  `TN_VIRTUAL_SHADOW_INVALID: resolutionLodBiasDirectional ${String(bias)} widens the finest level to ${String(clipExtents[0])}, past the next level at ${String(clipExtents[1])}.`,
1172
524
  );
1173
525
  }
1174
- const sizes = options.mapSize ?? light.shadow.mapSize.width;
1175
- const mapSize = clipExtents.map(
1176
- (_, level) =>
1177
- (typeof sizes === "number" ? sizes : sizes[Math.min(level, sizes.length - 1)]) as number,
1178
- );
526
+ const mapSize = clipExtents.map((_, level) => sizeOf(authoredLevel(level)));
1179
527
  for (const size of mapSize) {
1180
528
  if (!Number.isInteger(size) || size <= 0) {
1181
529
  throw new RangeError(
@@ -1264,7 +612,9 @@ export class VirtualShadowNode extends ShadowBaseNode {
1264
612
  // the game handed it, so a caller reading `options` back sees the level it asked for.
1265
613
  return values.length === 1
1266
614
  ? Array.from({ length: clipExtents.length }, () => values[0] as number)
1267
- : values;
615
+ : clipExtents.map(
616
+ (_, level) => values[Math.min(authoredLevel(level), values.length - 1)] as number,
617
+ );
1268
618
  };
1269
619
  const steps = perLevel(
1270
620
  options.refreshStep ?? 0.125,
@@ -1321,6 +671,7 @@ export class VirtualShadowNode extends ShadowBaseNode {
1321
671
  adaptiveCasterGate: options.adaptiveCasterGate ?? true,
1322
672
  adaptiveRefresh: options.adaptiveRefresh ?? true,
1323
673
  clipExtents: [...clipExtents],
674
+ maxLevelRatio,
1324
675
  resolutionLodBiasDirectional: bias,
1325
676
  depthRange: options.depthRange ?? 400,
1326
677
  expensiveRefreshShare,
@@ -1531,6 +882,29 @@ export class VirtualShadowNode extends ShadowBaseNode {
1531
882
  });
1532
883
  }
1533
884
 
885
+ /**
886
+ * Centre every clip window on `point` instead of the camera's eye, or on the eye again with
887
+ * `undefined`. The point is the view's subject: a third-person hero, an orbit pivot. Level
888
+ * selection, blend bands and window pans then depend on the subject alone, so a camera that turns
889
+ * around it (its eye travels the arm's whole circle) moves no shadow edge and re-renders no page.
890
+ * Unreal does the same for a view target (UE 5.8.3: VirtualShadowMapClipmap.cpp:256-295 moves the
891
+ * clipmap WorldOrigin onto it). Call it whenever the subject moves; an unchanged point costs one
892
+ * comparison. The point is copied, so a live `position` can be passed every frame.
893
+ */
894
+ setFocus(point: IVector3Like | undefined): void {
895
+ const same =
896
+ point === undefined
897
+ ? this.#focus === undefined
898
+ : this.#focus?.x === point.x && this.#focus.y === point.y && this.#focus.z === point.z;
899
+ if (same) return;
900
+ // A walking hero moves the focus every frame: reuse the vector, no garbage per frame.
901
+ this.#focus =
902
+ point === undefined
903
+ ? undefined
904
+ : (this.#focus ?? new Vector3()).set(point.x, point.y, point.z);
905
+ this.#nativeCommand("focus", { at: point === undefined ? [] : [point.x, point.y, point.z] });
906
+ }
907
+
1534
908
  /**
1535
909
  * The topmost object above the light: the scene it is lit in, whatever the game nested it under.
1536
910
  * Walked per level render, so a `Daylight` group between the sun and the world is not the boundary
@@ -1672,9 +1046,15 @@ export class VirtualShadowNode extends ShadowBaseNode {
1672
1046
  if (state.phase === MOTION_MOVER) this.#settle(mesh, state);
1673
1047
  continue;
1674
1048
  }
1675
- // A caster that casts nothing, is not drawn, or is not a layer-0 object is no business of
1676
- // this scan: the world's own batches reach the levels through `invalidateRegion` instead.
1677
- if (!mesh.castShadow || !mesh.visible || (mesh.layers.mask & 1) === 0) continue;
1049
+ // WorldCells keeps wide aggregates on layer 0 for the main pass, but their reserved wide bit
1050
+ // marks streamed instances whose shadow changes the world reports through `invalidateRegion`.
1051
+ if (
1052
+ !mesh.castShadow ||
1053
+ !mesh.visible ||
1054
+ (mesh.layers.mask & 1) === 0 ||
1055
+ mesh.layers.isEnabled(VIRTUAL_SHADOW_WIDE_CASTER_LAYER)
1056
+ )
1057
+ continue;
1678
1058
  // `trackCaster` — or the game — put it on the mover layer itself, which pins it as a mover.
1679
1059
  if (state.phase === MOTION_STATIC && mesh.layers.isEnabled(VIRTUAL_SHADOW_MOVER_LAYER))
1680
1060
  continue;
@@ -1803,8 +1183,12 @@ export class VirtualShadowNode extends ShadowBaseNode {
1803
1183
  const mesh = table[entry];
1804
1184
  if (mesh === undefined) continue;
1805
1185
  const flag = casterFlag(mesh);
1806
- if (flags[entry] === flag) continue;
1186
+ const was = flags[entry] ?? 0;
1187
+ if (was === flag) continue;
1807
1188
  flags[entry] = flag;
1189
+ // A mesh that casts in neither state drew nothing into any map either way: a main-pass
1190
+ // batch that empties and hides is not a shadow change.
1191
+ if (!flagCasts(was) && !flagCasts(flag)) continue;
1808
1192
  this.#askAboutCaster(mesh);
1809
1193
  }
1810
1194
  }
@@ -1915,8 +1299,13 @@ export class VirtualShadowNode extends ShadowBaseNode {
1915
1299
  this.#hidden.push(mesh);
1916
1300
  continue;
1917
1301
  }
1918
- // A retained-part proxy applies this gate to each original source at the draw boundary.
1919
- if (mesh.chunkShadowProxy === true) mesh.casterMinDiameter = gate;
1302
+ // A retained-part proxy applies this gate to each original source at the draw boundary, and
1303
+ // keeps one index buffer per level of the ladder it is drawn into: a proxy that held fewer
1304
+ // rewrote a whole index every render (see `selectChunkShadowParts`).
1305
+ if (mesh.chunkShadowProxy === true) {
1306
+ mesh.casterMinDiameter = gate;
1307
+ mesh.casterLevelSlots = this.#levels.length;
1308
+ }
1920
1309
  // Read before the gates below: the level is going to render both caster layers either way, and
1921
1310
  // a caster too small for this level's texels is still one the prewarm owes a draw.
1922
1311
  if (mesh.casterPrewarmOwed === true) prewarming = true;
@@ -2320,15 +1709,8 @@ export class VirtualShadowNode extends ShadowBaseNode {
2320
1709
  shadow.camera.projectionMatrix,
2321
1710
  shadow.camera.matrixWorldInverse,
2322
1711
  );
2323
- _shadowFrustum.setFromProjectionMatrix(_shadowProjection);
2324
1712
  const planes = _shadowPlanes;
2325
- for (const [at, plane] of _shadowFrustum.planes.entries()) {
2326
- const offset = at * 4;
2327
- planes[offset] = plane.normal.x;
2328
- planes[offset + 1] = plane.normal.y;
2329
- planes[offset + 2] = plane.normal.z;
2330
- planes[offset + 3] = plane.constant;
2331
- }
1713
+ frustumPlanes(_shadowProjection, planes);
2332
1714
  // Every compute leaves the one node frame every node shares with its fields at their bare
2333
1715
  // defaults — `scene` among them, which `Nodes.getNodeFrame()` sets with no arguments
2334
1716
  // (three.webgpu.js:56215, reached from `Renderer.compute` at 62235) and nothing puts back; the
@@ -2402,7 +1784,7 @@ export class VirtualShadowNode extends ShadowBaseNode {
2402
1784
  base,
2403
1785
  1 - at(this.options.selectionGuard, index) - 1 / (this.options.mapSize[index] as number),
2404
1786
  );
2405
- const step = Math.min(base * Math.max(1, level.costMs / affordableMs), margin);
1787
+ const step = trailStep(base, level.costMs, affordableMs, margin);
2406
1788
  if (step !== level.appliedStep) {
2407
1789
  this.clipmap.setRefreshStep(index, step);
2408
1790
  level.appliedStep = step;
@@ -2433,12 +1815,7 @@ export class VirtualShadowNode extends ShadowBaseNode {
2433
1815
  if (level.gatedRender === level.lastRender) return;
2434
1816
  level.gatedRender = level.lastRender;
2435
1817
  if (level.costMs <= 0) return;
2436
- let scale = level.gateScale;
2437
- if (level.costMs > affordableMs) {
2438
- scale = Math.min(GATE_SCALE_CAP, scale * GATE_SCALE_RISE);
2439
- } else if (level.costMs < affordableMs * GATE_DECAY_SHARE) {
2440
- scale = Math.max(1, scale * GATE_SCALE_DECAY);
2441
- }
1818
+ const scale = nextGateScale(level.gateScale, level.costMs, affordableMs);
2442
1819
  if (scale === level.gateScale) return;
2443
1820
  level.gateScale = scale;
2444
1821
  if (now - level.lastGateNote < GATE_MARKER_SECONDS) return;
@@ -2798,13 +2175,19 @@ export class VirtualShadowNode extends ShadowBaseNode {
2798
2175
  if (builder.renderer.shadowMap.enabled === false) return null;
2799
2176
  // Read once, like tnShadowStats. Build no diagnostic nodes unless the URL switch is on.
2800
2177
  if (this.#levelsRequested === undefined) {
2801
- const search = globalThis.location?.search ?? "";
2802
- this.#levelsRequested = /[?&]tnShadowLevels=(?!0(?:&|$))(?!false(?:&|$))[^&]/u.test(search);
2178
+ // One read of the URL for both switches: setup runs once, before the shader graph exists.
2179
+ const search = globalThis.location?.search;
2180
+ // Query only, as it always was: no environment variable and no global named these switches.
2181
+ this.#levelsRequested = readLaunchFlag(
2182
+ { environment: "", query: "tnShadowLevels" },
2183
+ "on",
2184
+ search,
2185
+ );
2803
2186
  // Counter runs: a fixed refreshStep, since the adaptive step follows measured render cost and
2804
2187
  // two runs of one route would move their windows at different ticks. Set once, before a frame.
2805
2188
  if (
2806
2189
  this.#adaptiveRefreshGiven === undefined &&
2807
- /[?&]tnAdaptiveRefresh=(?:0|false)(?:&|$)/u.test(search)
2190
+ readLaunchFlag({ environment: "", query: "tnAdaptiveRefresh" }, "off", search)
2808
2191
  ) {
2809
2192
  (this.options as { adaptiveRefresh: boolean }).adaptiveRefresh = false;
2810
2193
  }
@@ -2945,6 +2328,7 @@ export class VirtualShadowNode extends ShadowBaseNode {
2945
2328
 
2946
2329
  /** Aerial windows follow the forward ray's received surface, without changing walking follow. */
2947
2330
  #viewFocus(camera: Camera, eye: Vector3): Vector3 {
2331
+ if (this.#focus !== undefined) return _focus.copy(this.#focus);
2948
2332
  _focus.copy(eye);
2949
2333
  if (!this.options.followViewFocus) return _focus;
2950
2334
  camera.getWorldDirection(_forward);
@@ -3222,7 +2606,9 @@ export class VirtualShadowNode extends ShadowBaseNode {
3222
2606
  // *own* last render, so a burst spanning that delay is one render and a lone ask is one
3223
2607
  // render, and the level keeps the map and window it has in between — already right for
3224
2608
  // every static caster in it, missing only what streamed in since.
3225
- const delay = Math.max(this.options.invalidationDelay[index] ?? 0, gpuDelay);
2609
+ const delay = this.startupCovered
2610
+ ? 0
2611
+ : Math.max(this.options.invalidationDelay[index] ?? 0, gpuDelay);
3226
2612
  const matured = level.dirty && (urgent || now - level.lastRender >= delay);
3227
2613
  let reason: RenderReason = REASON_NONE;
3228
2614
  if (windowMoved) reason = REASON_MOVE;
@@ -3237,7 +2623,7 @@ export class VirtualShadowNode extends ShadowBaseNode {
3237
2623
  // can hide it from. A level that reads part of that spot draws on this frame too, so the
3238
2624
  // blob never stands next to the mover's new shadow. It fires once per caster, on the frame
3239
2625
  // the node classifies it, and at most one render per level.
3240
- const grant = due && (!budgetSpent || (urgentSelected && matured));
2626
+ const grant = due && (this.startupCovered || !budgetSpent || (urgentSelected && matured));
3241
2627
  // The rectangles this render draws, or undefined for the whole level.
3242
2628
  let passes: IPartialPass[] | undefined;
3243
2629
  // The pages this render counted as rectangles, kept for the derived span below that turns
@@ -3465,9 +2851,7 @@ export class VirtualShadowNode extends ShadowBaseNode {
3465
2851
 
3466
2852
  /** Whether `?tnShadowStats=1` is on this launch's URL, read once. */
3467
2853
  #statsWalkRequested(): boolean {
3468
- this.#statsRequested ??= /[?&]tnShadowStats=(?!0(?:&|$))(?!false(?:&|$))[^&]/u.test(
3469
- globalThis.location?.search ?? "",
3470
- );
2854
+ this.#statsRequested ??= readLaunchFlag({ environment: "", query: "tnShadowStats" });
3471
2855
  return this.#statsRequested;
3472
2856
  }
3473
2857
 
@@ -3515,164 +2899,3 @@ export class VirtualShadowNode extends ShadowBaseNode {
3515
2899
  super.dispose();
3516
2900
  }
3517
2901
  }
3518
-
3519
- const VIRTUAL_SHADOW_STAT_FIELDS = [
3520
- "autoMovers",
3521
- "autoScanMs",
3522
- "autoTransitions",
3523
- "byAdmission",
3524
- "byEviction",
3525
- "byInvalidation",
3526
- "byMove",
3527
- "cached",
3528
- "coalesced",
3529
- "deferred",
3530
- "frame",
3531
- "held",
3532
- "invalidated",
3533
- "levels",
3534
- "moved",
3535
- "moverRenders",
3536
- "movers",
3537
- "pagesDirty",
3538
- "pagesRedrawn",
3539
- "rendered",
3540
- "rendersTotal",
3541
- "reuseRatio",
3542
- ] as const;
3543
-
3544
- function isVirtualShadowStats(value: unknown): value is IVirtualShadowStats {
3545
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
3546
- const stats = value as Record<string, unknown>;
3547
- if (
3548
- VIRTUAL_SHADOW_STAT_FIELDS.some(
3549
- (field) => typeof stats[field] !== "number" || !Number.isFinite(stats[field]),
3550
- )
3551
- ) {
3552
- return false;
3553
- }
3554
- // Two fields are measurements, not counts: a ratio and a mean in milliseconds.
3555
- const countFields = VIRTUAL_SHADOW_STAT_FIELDS.filter(
3556
- (field) => field !== "reuseRatio" && field !== "autoScanMs",
3557
- );
3558
- if (
3559
- countFields.some((field) => !Number.isInteger(stats[field]) || (stats[field] as number) < 0)
3560
- ) {
3561
- return false;
3562
- }
3563
- const reuseRatio = stats.reuseRatio as number;
3564
- return reuseRatio >= 0 && reuseRatio <= 1 && (stats.autoScanMs as number) >= 0;
3565
- }
3566
-
3567
- /**
3568
- * Parse a `TN_VIRTUAL_SHADOW` console line back into its complete stats, or `undefined`.
3569
- *
3570
- * @situation inspect virtual shadow cache and mover counters from a renderer log
3571
- * @constraint non-marker lines and markers with incomplete or non-numeric stats return `undefined`
3572
- * @example
3573
- * const stats = readVirtualShadowMarker(line);
3574
- * if (stats !== undefined) console.log(stats.reuseRatio);
3575
- */
3576
- export function readVirtualShadowMarker(line: string): IVirtualShadowStats | undefined {
3577
- if (!line.startsWith(`${VIRTUAL_SHADOW_MARKER}:`)) return undefined;
3578
- try {
3579
- const value: unknown = JSON.parse(line.slice(VIRTUAL_SHADOW_MARKER.length + 1));
3580
- return isVirtualShadowStats(value) ? value : undefined;
3581
- } catch {
3582
- return undefined;
3583
- }
3584
- }
3585
-
3586
- /**
3587
- * One frame's shadow passes on the owned engine with the spot and point light maps apart from the
3588
- * sun's (PRD-650). The sun's draws and the lamps' add up to every shadow draw the renderer submitted.
3589
- */
3590
- export interface ILampShadowStats {
3591
- readonly frame: number;
3592
- readonly shadowDraws: number;
3593
- /** The sun's maps: its virtual levels or its plain map. `gpuMs` is -1 until a GPU sample resolves. */
3594
- readonly sun: { readonly draws: number; readonly gpuMs: number };
3595
- /** The lamp maps the frame redrew (a cube's six faces are one), their draws, and their GPU time. */
3596
- readonly lamps: { readonly redraws: number; readonly draws: number; readonly gpuMs: number };
3597
- }
3598
-
3599
- export const LAMP_SHADOW_MARKER = "TN_LAMP_SHADOW";
3600
-
3601
- interface ILampShadowCounters {
3602
- readonly lampRedraws: number;
3603
- readonly lampDraws: number;
3604
- readonly shadowDraws: number;
3605
- readonly sunGpuMs: number;
3606
- readonly lampGpuMs: number;
3607
- }
3608
-
3609
- const isCount = (n: unknown): n is number => Number.isInteger(n) && (n as number) >= 0;
3610
- const isGpuMs = (n: unknown): n is number => n === -1 || (Number.isFinite(n) && (n as number) >= 0);
3611
-
3612
- function isLampShadowStats(value: unknown): value is ILampShadowStats {
3613
- const stats = value as Partial<Record<keyof ILampShadowStats, Record<string, unknown>>> | null;
3614
- if (typeof stats !== "object" || stats === null) return false;
3615
- const { frame, shadowDraws } = stats as Record<string, unknown>;
3616
- const sun = stats.sun;
3617
- const lamps = stats.lamps;
3618
- return (
3619
- isCount(frame) &&
3620
- isCount(shadowDraws) &&
3621
- typeof sun === "object" &&
3622
- sun !== null &&
3623
- typeof lamps === "object" &&
3624
- lamps !== null &&
3625
- isCount(sun.draws) &&
3626
- isGpuMs(sun.gpuMs) &&
3627
- isCount(lamps.redraws) &&
3628
- isCount(lamps.draws) &&
3629
- isGpuMs(lamps.gpuMs) &&
3630
- sun.draws + lamps.draws === shadowDraws
3631
- );
3632
- }
3633
-
3634
- /**
3635
- * The `TN_LAMP_SHADOW` line for the renderer's last frame, or `undefined` on a renderer that keeps
3636
- * no lamp counters (three's own).
3637
- *
3638
- * @situation log lamp shadow redraws and GPU time apart from the sun's on the owned engine
3639
- * @constraint counters that do not add up to the frame's shadow draws throw TN_LAMP_SHADOW_INVALID
3640
- * @example
3641
- * const line = lampShadowMarker(renderer, frame);
3642
- * if (line !== undefined) console.info(line);
3643
- */
3644
- export function lampShadowMarker(
3645
- renderer: { readonly info?: { readonly engine?: { readonly shadows?: ILampShadowCounters } } },
3646
- frame: number,
3647
- ): string | undefined {
3648
- const counters = renderer.info?.engine?.shadows;
3649
- if (counters === undefined) return undefined;
3650
- const stats: ILampShadowStats = {
3651
- frame,
3652
- shadowDraws: counters.shadowDraws,
3653
- sun: { draws: counters.shadowDraws - counters.lampDraws, gpuMs: counters.sunGpuMs },
3654
- lamps: { redraws: counters.lampRedraws, draws: counters.lampDraws, gpuMs: counters.lampGpuMs },
3655
- };
3656
- if (!isLampShadowStats(stats))
3657
- throw new Error(`TN_LAMP_SHADOW_INVALID: ${JSON.stringify(counters)} at frame ${frame}`);
3658
- return `${LAMP_SHADOW_MARKER}:${JSON.stringify(stats)}`;
3659
- }
3660
-
3661
- /**
3662
- * Parse a `TN_LAMP_SHADOW` line back into its stats, or `undefined`.
3663
- *
3664
- * @situation count lamp shadow redraws from a renderer log, for example a moving-caster run
3665
- * @constraint non-marker lines and markers whose sun and lamp draws do not add up return `undefined`
3666
- * @example
3667
- * const stats = readLampShadowMarker(line);
3668
- * if (stats !== undefined) console.log(stats.lamps.redraws);
3669
- */
3670
- export function readLampShadowMarker(line: string): ILampShadowStats | undefined {
3671
- if (!line.startsWith(`${LAMP_SHADOW_MARKER}:`)) return undefined;
3672
- try {
3673
- const value: unknown = JSON.parse(line.slice(LAMP_SHADOW_MARKER.length + 1));
3674
- return isLampShadowStats(value) ? value : undefined;
3675
- } catch {
3676
- return undefined;
3677
- }
3678
- }