@threenative/core 0.3.4 → 0.3.6

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-Jz4Fdoeb.d.ts} +114 -11
  5. package/dist/hot.d.ts +4 -4
  6. package/dist/index.d.ts +712 -118
  7. package/dist/index.js +12437 -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 +57 -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 +2408 -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 +574 -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 +850 -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,827 @@
1
+ /**
2
+ * Renderer-independent bookkeeping for virtual shadow pages.
3
+ *
4
+ * Four pieces, none of which know a GPU exists: stable virtual page addresses and a bounded
5
+ * physical page pool with LRU eviction (`PhysicalPagePool`), camera-centred clip windows snapped
6
+ * to whole pages in a light-space basis (`DirectionalClipmap`), the pages a frame needs from
7
+ * receiver points and visible caster bounds (`ReceiverDemandPass`), and the pages a moving caster
8
+ * dirties (`ShadowInvalidationTracker`). `VirtualShadowNode` in `virtual-shadow.ts` is the only
9
+ * consumer; everything here is pure so its rules are provable in a node-environment spec.
10
+ *
11
+ * Fail closed: malformed input throws at the boundary instead of producing a page that samples
12
+ * nothing.
13
+ */
14
+
15
+ const EPSILON = 1e-9;
16
+
17
+ /** A plain `{x, y, z}` triple; three's `Vector3` satisfies it without a copy. */
18
+ export interface IVector3Like {
19
+ readonly x: number;
20
+ readonly y: number;
21
+ readonly z: number;
22
+ }
23
+
24
+ /** An axis-aligned world-space box as two corners. */
25
+ export interface IBoundsLike {
26
+ readonly min: IVector3Like;
27
+ readonly max: IVector3Like;
28
+ }
29
+
30
+ /** A point in the light-space basis: `u` and `v` across the light, `w` toward it. */
31
+ export interface ILightSpacePoint {
32
+ readonly u: number;
33
+ readonly v: number;
34
+ readonly w: number;
35
+ }
36
+
37
+ /** The address of one virtual page: a clip level and integer page coordinates. */
38
+ export interface IVirtualPageAddress {
39
+ readonly level: number;
40
+ readonly x: number;
41
+ readonly y: number;
42
+ readonly key: string;
43
+ }
44
+
45
+ function assertInteger(name: string, value: number): void {
46
+ if (!Number.isInteger(value)) {
47
+ throw new TypeError(`${name} must be an integer; received ${String(value)}`);
48
+ }
49
+ }
50
+
51
+ function assertPositiveInteger(name: string, value: number): void {
52
+ if (!Number.isInteger(value) || value <= 0) {
53
+ throw new TypeError(`${name} must be a positive integer; received ${String(value)}`);
54
+ }
55
+ }
56
+
57
+ function assertFiniteVector(name: string, vector: IVector3Like | null | undefined): void {
58
+ if (
59
+ !vector ||
60
+ !Number.isFinite(vector.x) ||
61
+ !Number.isFinite(vector.y) ||
62
+ !Number.isFinite(vector.z)
63
+ ) {
64
+ throw new TypeError(`${name} must contain finite x, y and z values`);
65
+ }
66
+ }
67
+
68
+ /** Build the string key of a virtual page. */
69
+ export function makePageKey(level: number, x: number, y: number): string {
70
+ assertInteger("level", level);
71
+ assertInteger("x", x);
72
+ assertInteger("y", y);
73
+ return `${level}:${x}:${y}`;
74
+ }
75
+
76
+ /** Parse a key produced by {@link makePageKey}; throws on anything else. */
77
+ export function parsePageKey(key: string): { level: number; x: number; y: number } {
78
+ if (typeof key !== "string") throw new TypeError("page key must be a string");
79
+ const parts = key.split(":").map(Number);
80
+ if (parts.length !== 3 || parts.some((value) => !Number.isInteger(value))) {
81
+ throw new TypeError(`invalid page key: ${key}`);
82
+ }
83
+ return { level: parts[0] as number, x: parts[1] as number, y: parts[2] as number };
84
+ }
85
+
86
+ /** One resident physical page. `slot` is the atlas layer that holds it. */
87
+ export interface IPhysicalPageEntry {
88
+ readonly key: string;
89
+ readonly slot: number;
90
+ pinned: boolean;
91
+ dirty: boolean;
92
+ readonly generation: number;
93
+ lastUsedFrame: number;
94
+ }
95
+
96
+ export interface IPhysicalPageAllocation {
97
+ readonly entry: IPhysicalPageEntry;
98
+ readonly reused: boolean;
99
+ readonly evictedKey: string | null;
100
+ }
101
+
102
+ /**
103
+ * A bounded set of physical page slots with deterministic least-recently-used eviction.
104
+ *
105
+ * Pinned entries and entries named in `protectedKeys` are never evicted; when nothing else can
106
+ * go, `allocate` returns `null` and counts an overflow rather than silently reusing a page.
107
+ */
108
+ export class PhysicalPagePool {
109
+ readonly capacity: number;
110
+ evictions = 0;
111
+ overflow = 0;
112
+ #generation = 0;
113
+ readonly #resident = new Map<string, IPhysicalPageEntry>();
114
+ #freeSlots: number[];
115
+
116
+ constructor(capacity: number) {
117
+ assertPositiveInteger("capacity", capacity);
118
+ this.capacity = capacity;
119
+ this.#freeSlots = Array.from({ length: capacity }, (_, slot) => slot);
120
+ }
121
+
122
+ get size(): number {
123
+ return this.#resident.size;
124
+ }
125
+
126
+ has(key: string): boolean {
127
+ return this.#resident.has(key);
128
+ }
129
+
130
+ get(key: string): IPhysicalPageEntry | undefined {
131
+ return this.#resident.get(key);
132
+ }
133
+
134
+ /** Resident entries ordered by slot. */
135
+ entries(): IPhysicalPageEntry[] {
136
+ return [...this.#resident.values()].sort((a, b) => a.slot - b.slot);
137
+ }
138
+
139
+ allocate(
140
+ key: string,
141
+ {
142
+ frame = 0,
143
+ pinned = false,
144
+ protectedKeys = new Set<string>(),
145
+ }: { frame?: number; pinned?: boolean; protectedKeys?: ReadonlySet<string> } = {},
146
+ ): IPhysicalPageAllocation | null {
147
+ assertInteger("frame", frame);
148
+ const resident = this.#resident.get(key);
149
+ if (resident) {
150
+ resident.lastUsedFrame = frame;
151
+ resident.pinned ||= pinned;
152
+ return { entry: resident, reused: true, evictedKey: null };
153
+ }
154
+
155
+ let slot = this.#freeSlots.shift();
156
+ let evictedKey: string | null = null;
157
+ if (slot === undefined) {
158
+ const candidate = this.entries()
159
+ .filter((entry) => !entry.pinned && !protectedKeys.has(entry.key))
160
+ .sort((a, b) => a.lastUsedFrame - b.lastUsedFrame || a.slot - b.slot)[0];
161
+ if (!candidate) {
162
+ this.overflow += 1;
163
+ return null;
164
+ }
165
+ slot = candidate.slot;
166
+ evictedKey = candidate.key;
167
+ this.#resident.delete(candidate.key);
168
+ this.evictions += 1;
169
+ }
170
+
171
+ this.#generation += 1;
172
+ const entry: IPhysicalPageEntry = {
173
+ key,
174
+ slot,
175
+ pinned,
176
+ dirty: true,
177
+ generation: this.#generation,
178
+ lastUsedFrame: frame,
179
+ };
180
+ this.#resident.set(key, entry);
181
+ return { entry, reused: false, evictedKey };
182
+ }
183
+
184
+ touch(key: string, frame: number): boolean {
185
+ assertInteger("frame", frame);
186
+ const entry = this.#resident.get(key);
187
+ if (!entry) return false;
188
+ entry.lastUsedFrame = frame;
189
+ return true;
190
+ }
191
+
192
+ markDirty(key: string): boolean {
193
+ const entry = this.#resident.get(key);
194
+ if (!entry) return false;
195
+ entry.dirty = true;
196
+ return true;
197
+ }
198
+
199
+ /** Dirty every resident page; returns how many there were. */
200
+ markAllDirty(): number {
201
+ for (const entry of this.#resident.values()) entry.dirty = true;
202
+ return this.#resident.size;
203
+ }
204
+
205
+ release(key: string): boolean {
206
+ const entry = this.#resident.get(key);
207
+ if (!entry) return false;
208
+ this.#resident.delete(key);
209
+ this.#freeSlots.push(entry.slot);
210
+ this.#freeSlots.sort((a, b) => a - b);
211
+ return true;
212
+ }
213
+
214
+ clear(): void {
215
+ this.#resident.clear();
216
+ this.#freeSlots = Array.from({ length: this.capacity }, (_, slot) => slot);
217
+ }
218
+ }
219
+
220
+ /** One clip level's window of `pagesPerAxis²` virtual pages around the centre. */
221
+ export interface IClipWindow {
222
+ readonly level: number;
223
+ readonly extent: number;
224
+ readonly pageWorldSize: number;
225
+ /** Pages a window trails its followed centre by before it moves and re-renders. */
226
+ readonly refreshPages: number;
227
+ readonly minX: number;
228
+ readonly minY: number;
229
+ readonly maxX: number;
230
+ readonly maxY: number;
231
+ }
232
+
233
+ export interface IDirectionalClipmapOptions {
234
+ /** Unit-free direction *toward* the source; normalised here. */
235
+ readonly direction: IVector3Like;
236
+ /** Half-width of each level's window in world units, finest first. */
237
+ readonly clipExtents: readonly number[];
238
+ readonly pagesPerAxis: number;
239
+ /**
240
+ * Fraction of an extent inside which a point selects that level, `(0, 1]`, default 0.9. One value
241
+ * for every level, or one per level finest first, the last entry standing in for the rest.
242
+ */
243
+ readonly selectionGuard?: number | readonly number[];
244
+ /**
245
+ * Fraction of an extent a level's window may trail its followed centre by before it re-renders,
246
+ * `[0, 1)`, default 0.125. Rounded to whole texels with one texel reserved for a deferred render;
247
+ * `0` keeps the old one-texel step. Larger steps re-render a level less often as the camera walks. One value
248
+ * for every level, or one per level finest first, the last entry standing in for the rest.
249
+ */
250
+ readonly refreshStep?: number | readonly number[];
251
+ }
252
+
253
+ function dot(a: IVector3Like, b: IVector3Like): number {
254
+ return a.x * b.x + a.y * b.y + a.z * b.z;
255
+ }
256
+
257
+ function cross(a: IVector3Like, b: IVector3Like): IVector3Like {
258
+ return { x: a.y * b.z - a.z * b.y, y: a.z * b.x - a.x * b.z, z: a.x * b.y - a.y * b.x };
259
+ }
260
+
261
+ function normalize(vector: IVector3Like): IVector3Like {
262
+ const magnitude = Math.sqrt(dot(vector, vector));
263
+ if (magnitude <= EPSILON) throw new RangeError("direction must have non-zero length");
264
+ return { x: vector.x / magnitude, y: vector.y / magnitude, z: vector.z / magnitude };
265
+ }
266
+
267
+ function cornersOfBounds(bounds: IBoundsLike): IVector3Like[] {
268
+ if (!bounds?.min || !bounds?.max) throw new TypeError("bounds must provide min and max vectors");
269
+ assertFiniteVector("bounds.min", bounds.min);
270
+ assertFiniteVector("bounds.max", bounds.max);
271
+ const corners: IVector3Like[] = [];
272
+ for (const x of [bounds.min.x, bounds.max.x]) {
273
+ for (const y of [bounds.min.y, bounds.max.y]) {
274
+ for (const z of [bounds.min.z, bounds.max.z]) corners.push({ x, y, z });
275
+ }
276
+ }
277
+ return corners;
278
+ }
279
+
280
+ /**
281
+ * Camera-centred clip windows in a light-space basis, snapped to whole pages.
282
+ *
283
+ * The basis is right-handed (`U × V = W`). A page camera placed along `+W` with `up = V` then
284
+ * renders screen X = `V × W` = `+U`, which is the axis the sampler reads the atlas along. The
285
+ * prototype this was ported from built `V = U × W` and every page came out mirrored.
286
+ */
287
+ export class DirectionalClipmap {
288
+ readonly clipExtents: readonly number[];
289
+ readonly pagesPerAxis: number;
290
+ /**
291
+ * Per level, finest first; the last entry stands in for every level past it. Mutable through
292
+ * {@link setRefreshStep} so a level whose own render is expensive can be stepped further, which
293
+ * is fewer grid positions for its window rather than a different grid.
294
+ */
295
+ refreshStep: number[];
296
+ /** Per level, finest first; the last entry stands in for every level past it. */
297
+ readonly selectionGuard: readonly number[];
298
+ readonly levelCount: number;
299
+ basisU: IVector3Like;
300
+ basisV: IVector3Like;
301
+ basisW: IVector3Like;
302
+ centerWorld: IVector3Like = { x: 0, y: 0, z: 0 };
303
+ centerLight: ILightSpacePoint = { u: 0, v: 0, w: 0 };
304
+ #windows: IClipWindow[] = [];
305
+
306
+ /** The per-level entry of a scalar-or-array option, the last entry standing in. */
307
+ #perLevel(values: readonly number[], level: number): number {
308
+ return values[Math.min(level, values.length - 1)] as number;
309
+ }
310
+
311
+ constructor({
312
+ direction,
313
+ clipExtents,
314
+ pagesPerAxis,
315
+ selectionGuard = 0.9,
316
+ refreshStep = 0.125,
317
+ }: IDirectionalClipmapOptions) {
318
+ assertFiniteVector("direction", direction);
319
+ assertPositiveInteger("pagesPerAxis", pagesPerAxis);
320
+ if (!Array.isArray(clipExtents) || clipExtents.length === 0) {
321
+ throw new TypeError("clipExtents must be a non-empty array");
322
+ }
323
+ if (clipExtents.some((extent) => !Number.isFinite(extent) || extent <= 0)) {
324
+ throw new RangeError("every clip extent must be positive");
325
+ }
326
+ for (let level = 1; level < clipExtents.length; level += 1) {
327
+ if ((clipExtents[level] as number) <= (clipExtents[level - 1] as number)) {
328
+ throw new RangeError("clipExtents must increase from the finest level to the coarsest");
329
+ }
330
+ }
331
+ // `selectionGuard` and `refreshStep` take one value per level, finest first, the last entry
332
+ // standing in for every level past it. One step for all of them spends the hysteresis the fine
333
+ // level can least afford on the coarse one, and the fine level is the one a walking camera
334
+ // re-renders most: at 20 m/s over 24/96/320 m extents a shared 0.125 re-rendered the fine window
335
+ // about 9 times a second to hold a shadow the eye reads at 1/8 of its own width.
336
+ const perLevel = (
337
+ value: number | readonly number[],
338
+ name: string,
339
+ valid: (v: number) => boolean,
340
+ ) => {
341
+ const values = Array.isArray(value) ? [...(value as readonly number[])] : [value as number];
342
+ for (const entry of values) {
343
+ if (!valid(entry)) {
344
+ throw new RangeError(`every ${name} must satisfy ${String(valid)}, got ${String(entry)}`);
345
+ }
346
+ }
347
+ return values;
348
+ };
349
+ const guards = perLevel(
350
+ selectionGuard,
351
+ "selectionGuard",
352
+ (v) => Number.isFinite(v) && v > 0 && v <= 1,
353
+ );
354
+ const steps = perLevel(
355
+ refreshStep,
356
+ "refreshStep",
357
+ (v) => Number.isFinite(v) && v >= 0 && v < 1,
358
+ );
359
+ for (let level = 0; level < guards.length; level += 1) {
360
+ if ((steps[level] as number) >= (guards[level] as number)) {
361
+ throw new RangeError(
362
+ `refreshStep must stay below selectionGuard, got ${String(steps[level])} >= ${String(guards[level])}`,
363
+ );
364
+ }
365
+ }
366
+ this.clipExtents = [...clipExtents];
367
+ this.pagesPerAxis = pagesPerAxis;
368
+ this.refreshStep = clipExtents.map((_, level) => this.#perLevel(steps, level));
369
+ this.selectionGuard = guards;
370
+ this.levelCount = clipExtents.length;
371
+ this.basisW = normalize(direction);
372
+ this.basisU = { x: 1, y: 0, z: 0 };
373
+ this.basisV = { x: 0, y: 0, z: 1 };
374
+ this.setDirection(direction);
375
+ }
376
+
377
+ /** Re-orient the basis; returns true when it changed enough that cached pages are stale. */
378
+ setDirection(direction: IVector3Like): boolean {
379
+ assertFiniteVector("direction", direction);
380
+ const nextW = normalize(direction);
381
+ const unchanged = this.#windows.length > 0 && Math.abs(dot(nextW, this.basisW) - 1) <= 1e-9;
382
+ this.basisW = nextW;
383
+ const reference: IVector3Like =
384
+ Math.abs(this.basisW.y) > 0.95 ? { x: 0, y: 0, z: 1 } : { x: 0, y: 1, z: 0 };
385
+ this.basisU = normalize(cross(this.basisW, reference));
386
+ this.basisV = normalize(cross(this.basisW, this.basisU));
387
+ if (!unchanged) this.#windows = [];
388
+ this.updateCenter(this.centerWorld);
389
+ return !unchanged;
390
+ }
391
+
392
+ project(worldPoint: IVector3Like): ILightSpacePoint {
393
+ assertFiniteVector("worldPoint", worldPoint);
394
+ return {
395
+ u: dot(worldPoint, this.basisU),
396
+ v: dot(worldPoint, this.basisV),
397
+ w: dot(worldPoint, this.basisW),
398
+ };
399
+ }
400
+
401
+ unproject({ u, v, w = 0 }: { u: number; v: number; w?: number }): IVector3Like {
402
+ if (![u, v, w].every(Number.isFinite)) {
403
+ throw new TypeError("light-space coordinates must be finite");
404
+ }
405
+ return {
406
+ x: this.basisU.x * u + this.basisV.x * v + this.basisW.x * w,
407
+ y: this.basisU.y * u + this.basisV.y * v + this.basisW.y * w,
408
+ z: this.basisU.z * u + this.basisV.z * v + this.basisW.z * w,
409
+ };
410
+ }
411
+
412
+ /** Re-step one level's window: the trail its followed centre may move before it re-renders. */
413
+ setRefreshStep(level: number, step: number): void {
414
+ assertInteger("level", level);
415
+ if (level < 0 || level >= this.levelCount) throw new RangeError(`invalid clip level: ${level}`);
416
+ if (!Number.isFinite(step) || step < 0 || step >= 1) {
417
+ throw new RangeError(`refreshStep must stay in the range [0, 1), got ${String(step)}`);
418
+ }
419
+ this.refreshStep[level] = step;
420
+ }
421
+
422
+ updateCenter(worldPoint: IVector3Like): readonly IClipWindow[] {
423
+ assertFiniteVector("worldPoint", worldPoint);
424
+ const previousCenter = this.centerLight;
425
+ this.centerWorld = { x: worldPoint.x, y: worldPoint.y, z: worldPoint.z };
426
+ this.centerLight = this.project(worldPoint);
427
+ const halfPages = Math.floor(this.pagesPerAxis / 2);
428
+ this.#windows = this.clipExtents.map((extent, level) => {
429
+ const pageWorldSize = (extent * 2) / this.pagesPerAxis;
430
+ // The step is a drift threshold, never the grid spacing. Changing it alone cannot move a
431
+ // stationary window. When either axis crosses the threshold, recenter the whole window on
432
+ // this level's fixed texel grid; `refreshStep: 0` keeps the old one-page floor addressing.
433
+ const step = this.#perLevel(this.refreshStep, level);
434
+ // Begin the refresh one texel inside the trail: the node grants one level render per frame,
435
+ // so a coarse window may wait behind the fine one while the followed centre keeps moving.
436
+ const refreshPages =
437
+ step === 0 ? 1 : Math.max(1, Math.round((step * extent) / pageWorldSize) - 1);
438
+ const previous = this.#windows[level];
439
+ const minX = Math.floor(this.centerLight.u / pageWorldSize) - halfPages;
440
+ const minY = Math.floor(this.centerLight.v / pageWorldSize) - halfPages;
441
+ if (
442
+ previous &&
443
+ ((this.centerLight.u === previousCenter.u && this.centerLight.v === previousCenter.v) ||
444
+ (Math.max(Math.abs(minX - previous.minX), Math.abs(minY - previous.minY)) <
445
+ refreshPages &&
446
+ Math.max(
447
+ Math.abs(this.centerLight.u - (previous.minX + halfPages) * pageWorldSize),
448
+ Math.abs(this.centerLight.v - (previous.minY + halfPages) * pageWorldSize),
449
+ ) <
450
+ refreshPages * pageWorldSize))
451
+ ) {
452
+ return { ...previous, refreshPages };
453
+ }
454
+ return {
455
+ level,
456
+ extent,
457
+ pageWorldSize,
458
+ refreshPages,
459
+ minX,
460
+ minY,
461
+ maxX: minX + this.pagesPerAxis,
462
+ maxY: minY + this.pagesPerAxis,
463
+ };
464
+ });
465
+ return this.#windows;
466
+ }
467
+
468
+ getWindow(level: number): IClipWindow {
469
+ const window = this.#windows[level];
470
+ if (!window) throw new RangeError(`invalid clip level: ${level}`);
471
+ return { ...window };
472
+ }
473
+
474
+ pageWorldSize(level: number): number {
475
+ return this.getWindow(level).pageWorldSize;
476
+ }
477
+
478
+ containsPage(level: number, x: number, y: number): boolean {
479
+ const window = this.#windows[level];
480
+ return (
481
+ window !== undefined &&
482
+ x >= window.minX &&
483
+ x < window.maxX &&
484
+ y >= window.minY &&
485
+ y < window.maxY
486
+ );
487
+ }
488
+
489
+ worldToPage(worldPoint: IVector3Like, level: number): IVirtualPageAddress {
490
+ const window = this.#windows[level];
491
+ if (!window) throw new RangeError(`invalid clip level: ${level}`);
492
+ const projected = this.project(worldPoint);
493
+ const x = Math.floor(projected.u / window.pageWorldSize);
494
+ const y = Math.floor(projected.v / window.pageWorldSize);
495
+ return { level, x, y, key: makePageKey(level, x, y) };
496
+ }
497
+
498
+ /** The finest level whose guarded extent contains the point, else the coarsest. */
499
+ selectLevel(worldPoint: IVector3Like): number {
500
+ const projected = this.project(worldPoint);
501
+ const distance = Math.max(
502
+ Math.abs(projected.u - this.centerLight.u),
503
+ Math.abs(projected.v - this.centerLight.v),
504
+ );
505
+ for (let level = 0; level < this.levelCount; level += 1) {
506
+ if (
507
+ distance <=
508
+ (this.clipExtents[level] as number) * this.#perLevel(this.selectionGuard, level)
509
+ )
510
+ return level;
511
+ }
512
+ return this.levelCount - 1;
513
+ }
514
+
515
+ /** Light-space extent and world centre (at `w = 0`) of one page. */
516
+ pageBounds(level: number, x: number, y: number) {
517
+ const pageWorldSize = this.pageWorldSize(level);
518
+ const minU = x * pageWorldSize;
519
+ const minV = y * pageWorldSize;
520
+ const centerU = minU + pageWorldSize * 0.5;
521
+ const centerV = minV + pageWorldSize * 0.5;
522
+ return {
523
+ level,
524
+ x,
525
+ y,
526
+ minU,
527
+ minV,
528
+ maxU: minU + pageWorldSize,
529
+ maxV: minV + pageWorldSize,
530
+ centerU,
531
+ centerV,
532
+ pageWorldSize,
533
+ centerWorld: this.unproject({ u: centerU, v: centerV, w: 0 }),
534
+ };
535
+ }
536
+
537
+ boundsToPageRange(bounds: IBoundsLike, level: number) {
538
+ const window = this.#windows[level];
539
+ if (!window) throw new RangeError(`invalid clip level: ${level}`);
540
+ const projected = cornersOfBounds(bounds).map((corner) => this.project(corner));
541
+ const minU = Math.min(...projected.map(({ u }) => u));
542
+ const maxU = Math.max(...projected.map(({ u }) => u));
543
+ const minV = Math.min(...projected.map(({ v }) => v));
544
+ const maxV = Math.max(...projected.map(({ v }) => v));
545
+ const pageSize = window.pageWorldSize;
546
+ return {
547
+ minX: Math.floor(minU / pageSize),
548
+ maxX: Math.floor((maxU - EPSILON) / pageSize),
549
+ minY: Math.floor(minV / pageSize),
550
+ maxY: Math.floor((maxV - EPSILON) / pageSize),
551
+ };
552
+ }
553
+
554
+ boundsToPageKeys(bounds: IBoundsLike, level: number): string[] {
555
+ const range = this.boundsToPageRange(bounds, level);
556
+ const keys: string[] = [];
557
+ for (let x = range.minX; x <= range.maxX; x += 1) {
558
+ for (let y = range.minY; y <= range.maxY; y += 1) keys.push(makePageKey(level, x, y));
559
+ }
560
+ return keys;
561
+ }
562
+
563
+ windowPages(level: number): IVirtualPageAddress[] {
564
+ const window = this.#windows[level];
565
+ if (!window) throw new RangeError(`invalid clip level: ${level}`);
566
+ const pages: IVirtualPageAddress[] = [];
567
+ for (let x = window.minX; x < window.maxX; x += 1) {
568
+ for (let y = window.minY; y < window.maxY; y += 1) {
569
+ pages.push({ level, x, y, key: makePageKey(level, x, y) });
570
+ }
571
+ }
572
+ return pages;
573
+ }
574
+ }
575
+
576
+ /** One page a frame asks for, ordered by pin, level and distance from the camera. */
577
+ export interface IPageRequest extends IVirtualPageAddress {
578
+ readonly pinned: boolean;
579
+ readonly priority: number;
580
+ }
581
+
582
+ export interface IReceiverDemandInput {
583
+ readonly cameraPosition: IVector3Like;
584
+ /** World points a receiver is known to occupy on screen, e.g. from screen-grid rays. */
585
+ readonly receiverPoints: readonly IVector3Like[];
586
+ /** Bounds of casters inside the view, so their pages are resident before they are seen. */
587
+ readonly visibleBounds: readonly IBoundsLike[];
588
+ readonly clipmap: DirectionalClipmap;
589
+ }
590
+
591
+ function boundsSamplePoints(bounds: IBoundsLike): IVector3Like[] {
592
+ const { min, max } = bounds;
593
+ return [
594
+ { x: (min.x + max.x) * 0.5, y: (min.y + max.y) * 0.5, z: (min.z + max.z) * 0.5 },
595
+ ...cornersOfBounds(bounds),
596
+ ];
597
+ }
598
+
599
+ /**
600
+ * Turn the points a frame can see into page requests: each point selects its finest level,
601
+ * requests its page and a guard band around it, and the coarsest window is pinned in full so
602
+ * every fragment has a page to fall back to.
603
+ */
604
+ export class ReceiverDemandPass {
605
+ readonly guardBand: number;
606
+
607
+ constructor({ guardBand = 1 }: { guardBand?: number } = {}) {
608
+ if (!Number.isInteger(guardBand) || guardBand < 0) {
609
+ throw new TypeError("guardBand must be a non-negative integer");
610
+ }
611
+ this.guardBand = guardBand;
612
+ }
613
+
614
+ collect({
615
+ cameraPosition,
616
+ receiverPoints,
617
+ visibleBounds,
618
+ clipmap,
619
+ }: IReceiverDemandInput): IPageRequest[] {
620
+ assertFiniteVector("cameraPosition", cameraPosition);
621
+ const requests = new Map<string, { -readonly [K in keyof IPageRequest]: IPageRequest[K] }>();
622
+ const cameraLight = clipmap.project(cameraPosition);
623
+
624
+ const addRequest = (
625
+ { level, x, y, key }: IVirtualPageAddress,
626
+ { pinned = false, priority = 0 }: { pinned?: boolean; priority?: number } = {},
627
+ ) => {
628
+ if (!clipmap.containsPage(level, x, y)) return;
629
+ const existing = requests.get(key);
630
+ if (!existing) {
631
+ requests.set(key, { key, level, x, y, pinned, priority });
632
+ return;
633
+ }
634
+ existing.pinned ||= pinned;
635
+ existing.priority = Math.min(existing.priority, priority);
636
+ };
637
+
638
+ const addPoint = (point: IVector3Like) => {
639
+ const level = clipmap.selectLevel(point);
640
+ const page = clipmap.worldToPage(point, level);
641
+ const projected = clipmap.project(point);
642
+ const du = projected.u - cameraLight.u;
643
+ const dv = projected.v - cameraLight.v;
644
+ const basePriority = du * du + dv * dv;
645
+ for (let dx = -this.guardBand; dx <= this.guardBand; dx += 1) {
646
+ for (let dy = -this.guardBand; dy <= this.guardBand; dy += 1) {
647
+ const x = page.x + dx;
648
+ const y = page.y + dy;
649
+ addRequest(
650
+ { level, x, y, key: makePageKey(level, x, y) },
651
+ { priority: basePriority + (dx * dx + dy * dy) * 0.001 },
652
+ );
653
+ }
654
+ }
655
+ };
656
+
657
+ for (const point of receiverPoints) addPoint(point);
658
+ for (const bounds of visibleBounds) {
659
+ for (const point of boundsSamplePoints(bounds)) addPoint(point);
660
+ }
661
+ for (const page of clipmap.windowPages(clipmap.levelCount - 1)) {
662
+ addRequest(page, { pinned: true, priority: -1 });
663
+ }
664
+
665
+ return [...requests.values()].sort(
666
+ (a, b) =>
667
+ Number(b.pinned) - Number(a.pinned) ||
668
+ a.level - b.level ||
669
+ a.priority - b.priority ||
670
+ a.x - b.x ||
671
+ a.y - b.y,
672
+ );
673
+ }
674
+ }
675
+
676
+ function copyBounds(bounds: IBoundsLike): IBoundsLike {
677
+ return { min: { ...bounds.min }, max: { ...bounds.max } };
678
+ }
679
+
680
+ function boundsEqual(a: IBoundsLike, b: IBoundsLike, epsilon = 1e-6): boolean {
681
+ return (["x", "y", "z"] as const).every(
682
+ (axis) =>
683
+ Math.abs(a.min[axis] - b.min[axis]) <= epsilon &&
684
+ Math.abs(a.max[axis] - b.max[axis]) <= epsilon,
685
+ );
686
+ }
687
+
688
+ /**
689
+ * A world AABB resolved onto one clipmap basis axis, as the interval that axis sees. Exact for a
690
+ * box: the extreme points along `axis` are the centre offset by half the box's own size, weighted
691
+ * by the absolute value of each component of the axis, so no corner has to be walked.
692
+ */
693
+ export function projectBounds(
694
+ bounds: IBoundsLike,
695
+ axis: IVector3Like,
696
+ ): { low: number; high: number } {
697
+ const halfX = (bounds.max.x - bounds.min.x) / 2;
698
+ const halfY = (bounds.max.y - bounds.min.y) / 2;
699
+ const halfZ = (bounds.max.z - bounds.min.z) / 2;
700
+ const centreX = (bounds.max.x + bounds.min.x) / 2;
701
+ const centreY = (bounds.max.y + bounds.min.y) / 2;
702
+ const centreZ = (bounds.max.z + bounds.min.z) / 2;
703
+ const reach = Math.abs(axis.x) * halfX + Math.abs(axis.y) * halfY + Math.abs(axis.z) * halfZ;
704
+ const middle = centreX * axis.x + centreY * axis.y + centreZ * axis.z;
705
+ return { low: middle - reach, high: middle + reach };
706
+ }
707
+
708
+ /** An inclusive rectangle of pages on one level, in the clipmap's absolute page coordinates. */
709
+ export interface IPageRect {
710
+ maxX: number;
711
+ maxY: number;
712
+ minX: number;
713
+ minY: number;
714
+ }
715
+
716
+ /**
717
+ * The inclusive pages an interval on one light axis covers, never fewer than one. The same
718
+ * arithmetic as {@link DirectionalClipmap.boundsToPageRange}, applied to a projected interval.
719
+ */
720
+ export function pageSpan(
721
+ low: number,
722
+ high: number,
723
+ pageWorldSize: number,
724
+ ): { max: number; min: number } {
725
+ const min = Math.floor(low / pageWorldSize);
726
+ return { max: Math.max(min, Math.floor((high - EPSILON) / pageWorldSize)), min };
727
+ }
728
+
729
+ /** Pages in a rectangle. */
730
+ export function pageArea(rect: IPageRect): number {
731
+ return (rect.maxX - rect.minX + 1) * (rect.maxY - rect.minY + 1);
732
+ }
733
+
734
+ /** Whether `outer` holds every page of `inner`; false when there is no `outer`. */
735
+ export function containsPages(outer: IPageRect | undefined, inner: IPageRect): boolean {
736
+ return (
737
+ outer !== undefined &&
738
+ outer.minX <= inner.minX &&
739
+ outer.minY <= inner.minY &&
740
+ outer.maxX >= inner.maxX &&
741
+ outer.maxY >= inner.maxY
742
+ );
743
+ }
744
+
745
+ /** Grow `into` to hold `rect`, or become a copy of it. Returns the grown rectangle. */
746
+ export function unionPageRect(into: IPageRect | undefined, rect: IPageRect): IPageRect {
747
+ if (into === undefined) return { ...rect };
748
+ into.minX = Math.min(into.minX, rect.minX);
749
+ into.minY = Math.min(into.minY, rect.minY);
750
+ into.maxX = Math.max(into.maxX, rect.maxX);
751
+ into.maxY = Math.max(into.maxY, rect.maxY);
752
+ return into;
753
+ }
754
+
755
+ /**
756
+ * Remembers each tracked caster's last bounds and dirties every page the old and new bounds
757
+ * cover on every level when they change. Unchanged bounds dirty nothing.
758
+ */
759
+ export class ShadowInvalidationTracker {
760
+ readonly clipmap: DirectionalClipmap;
761
+ readonly #tracked = new Map<number | string, IBoundsLike>();
762
+ readonly #invalidated = new Set<string>();
763
+
764
+ constructor(clipmap: DirectionalClipmap) {
765
+ if (!clipmap) throw new TypeError("clipmap is required");
766
+ this.clipmap = clipmap;
767
+ }
768
+
769
+ get trackedCount(): number {
770
+ return this.#tracked.size;
771
+ }
772
+
773
+ #invalidateBounds(bounds: IBoundsLike): void {
774
+ for (let level = 0; level < this.clipmap.levelCount; level += 1) {
775
+ for (const key of this.clipmap.boundsToPageKeys(bounds, level)) this.#invalidated.add(key);
776
+ }
777
+ }
778
+
779
+ /** Record a caster's current bounds; returns true when pages were dirtied. */
780
+ update(id: number | string, bounds: IBoundsLike): boolean {
781
+ if (id === undefined || id === null) throw new TypeError("tracked caster id is required");
782
+ const previous = this.#tracked.get(id);
783
+ if (previous && boundsEqual(previous, bounds)) return false;
784
+ if (previous) this.#invalidateBounds(previous);
785
+ this.#invalidateBounds(bounds);
786
+ this.#tracked.set(id, copyBounds(bounds));
787
+ return true;
788
+ }
789
+
790
+ has(id: number | string): boolean {
791
+ return this.#tracked.has(id);
792
+ }
793
+
794
+ remove(id: number | string): boolean {
795
+ const previous = this.#tracked.get(id);
796
+ if (!previous) return false;
797
+ this.#invalidateBounds(previous);
798
+ this.#tracked.delete(id);
799
+ return true;
800
+ }
801
+
802
+ /** Dirty the current coverage of every tracked caster; returns the pending key count. */
803
+ invalidateAll(): number {
804
+ for (const bounds of this.#tracked.values()) this.#invalidateBounds(bounds);
805
+ return this.#invalidated.size;
806
+ }
807
+
808
+ /** Drop trackers whose id is not in `liveIds`, dirtying the pages they covered. */
809
+ prune(liveIds: ReadonlySet<number | string>): number {
810
+ let removed = 0;
811
+ for (const id of [...this.#tracked.keys()]) {
812
+ if (!liveIds.has(id) && this.remove(id)) removed += 1;
813
+ }
814
+ return removed;
815
+ }
816
+
817
+ consumeInvalidatedKeys(): Set<string> {
818
+ const result = new Set(this.#invalidated);
819
+ this.#invalidated.clear();
820
+ return result;
821
+ }
822
+
823
+ clear(): void {
824
+ this.#tracked.clear();
825
+ this.#invalidated.clear();
826
+ }
827
+ }