@threenative/core 0.3.11 → 0.3.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/capabilities.json +1096 -26
  2. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  3. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-CWuFRT7G.d.ts} +1 -1
  4. package/dist/chunk-2Z44XSI2.js +35 -0
  5. package/dist/chunk-5O73CDMR.js +1849 -0
  6. package/dist/chunk-6KLNISRJ.js +153 -0
  7. package/dist/chunk-7UUT3TY5.js +133 -0
  8. package/dist/chunk-CFGTPFUH.js +231 -0
  9. package/dist/chunk-DBELTTTM.js +615 -0
  10. package/dist/chunk-GMHATRPW.js +7701 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-KIRUKTBQ.js +187 -0
  13. package/dist/chunk-N5LRP4BR.js +220 -0
  14. package/dist/chunk-OKXUCASC.js +2238 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-VAZM36TV.js +497 -0
  17. package/dist/{game-DzMcitDO.d.ts → game-D7pAzZUY.d.ts} +15 -3
  18. package/dist/hot.d.ts +3 -3
  19. package/dist/hot.js +2 -46
  20. package/dist/index.d.ts +329 -302
  21. package/dist/index.js +10566 -22552
  22. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-B6BMqS1r.d.ts} +33 -3
  23. package/dist/playtest.d.ts +3 -3
  24. package/dist/playtest.js +24 -75
  25. package/dist/react-css.js +1 -215
  26. package/dist/react.d.ts +2 -2
  27. package/dist/{renderer-rZm0hVqq.d.ts → renderer-DvFVoAgj.d.ts} +13 -4
  28. package/dist/spells/index.d.ts +643 -0
  29. package/dist/spells/index.js +1558 -0
  30. package/dist/spells/ultra/index.d.ts +1600 -0
  31. package/dist/spells/ultra/index.js +6804 -0
  32. package/dist/terrain-jobs-worker.js +1 -123
  33. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  34. package/dist/ui-layer.js +5 -384
  35. package/dist/worker.js +4 -41
  36. package/dist/world.d.ts +725 -259
  37. package/dist/world.js +16714 -18284
  38. package/mcp/animation-server.mjs +1 -1
  39. package/mcp/animation.mjs +2 -3
  40. package/mcp/engine-server.mjs +142 -47
  41. package/mcp/servers.mjs +9 -2
  42. package/mcp/terrain.mjs +8 -0
  43. package/package.json +14 -6
  44. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  45. package/patches/three@0.187.0.patch +2004 -407
  46. package/src/assets.ts +9 -2
  47. package/src/card-lod.ts +152 -0
  48. package/src/compressed-texture-preparation.ts +1008 -0
  49. package/src/frame-budget.ts +31 -20
  50. package/src/game-dev-tools.ts +93 -0
  51. package/src/game-frame-loop.ts +995 -0
  52. package/src/game-renderer-metrics.ts +77 -0
  53. package/src/game-startup.ts +1001 -0
  54. package/src/game-validate.ts +70 -0
  55. package/src/game.ts +253 -1935
  56. package/src/index.ts +27 -2
  57. package/src/launch-diagnostics.ts +22 -12
  58. package/src/look/ao-admission.ts +24 -0
  59. package/src/look/filmic-tone-mapping.ts +15 -13
  60. package/src/look/look-diagnostics.ts +3 -3
  61. package/src/look/quality.ts +10 -5
  62. package/src/look/world-environment.ts +76 -9
  63. package/src/loop.ts +29 -0
  64. package/src/model-lod.ts +42 -3
  65. package/src/particle-kinds.ts +515 -0
  66. package/src/picking.ts +17 -3
  67. package/src/playtest.ts +27 -1
  68. package/src/projection-apply.ts +4 -1
  69. package/src/projection-plan.ts +9 -6
  70. package/src/render/mesh-pool.ts +1 -1
  71. package/src/render/resolution-subrect.ts +2 -0
  72. package/src/render/rough-diffuse.ts +46 -12
  73. package/src/render/soft-shadow.ts +27 -12
  74. package/src/render/virtual-shadow-adaptive.ts +55 -0
  75. package/src/render/virtual-shadow-casters.ts +175 -0
  76. package/src/render/virtual-shadow-layers.ts +76 -0
  77. package/src/render/virtual-shadow-level.ts +224 -0
  78. package/src/render/virtual-shadow-markers.ts +193 -0
  79. package/src/render/virtual-shadow-options.ts +370 -0
  80. package/src/render/virtual-shadow-pages.ts +5 -0
  81. package/src/render/virtual-shadow.ts +213 -992
  82. package/src/render/world-impostor-surface.ts +293 -34
  83. package/src/render-pass-budget.ts +34 -7
  84. package/src/renderProjection.ts +22 -0
  85. package/src/renderer.ts +92 -37
  86. package/src/snow-field.ts +1 -1
  87. package/src/spells/cast-pool.ts +361 -0
  88. package/src/spells/index.ts +177 -0
  89. package/src/spells/mechanisms.ts +295 -0
  90. package/src/spells/reaction-field.ts +415 -0
  91. package/src/spells/spell-lights.ts +139 -0
  92. package/src/spells/spell-world.ts +187 -0
  93. package/src/spells/spell.ts +397 -0
  94. package/src/spells/spells.ts +283 -0
  95. package/src/spells/ultra/engine/camera.ts +184 -0
  96. package/src/spells/ultra/engine/quality.ts +96 -0
  97. package/src/spells/ultra/index.ts +52 -0
  98. package/src/spells/ultra/main.ts +305 -0
  99. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  100. package/src/spells/ultra/spells/cast.ts +233 -0
  101. package/src/spells/ultra/spells/fire.ts +1267 -0
  102. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  103. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  104. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  105. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  106. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  107. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  108. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  109. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  110. package/src/spells/ultra/vfx/common.ts +1195 -0
  111. package/src/spells/ultra/vfx/noise.ts +441 -0
  112. package/src/startup-readiness.ts +128 -34
  113. package/src/version.ts +1 -1
  114. package/src/warmup.ts +56 -8
  115. package/src/water-surface.ts +9 -3
  116. package/src/world-bundle-safety.ts +401 -0
  117. package/src/world-cell-batches.ts +1216 -0
  118. package/src/world-cell-chunks.ts +1132 -0
  119. package/src/world-cell-data.ts +995 -0
  120. package/src/world-cell-impostors.ts +1449 -0
  121. package/src/world-cell-lod-bias.ts +151 -0
  122. package/src/world-cell-models.ts +1074 -0
  123. package/src/world-cell-options.ts +189 -0
  124. package/src/world-cell-placements.ts +694 -0
  125. package/src/world-cell-prewarm.ts +557 -0
  126. package/src/world-cell-readiness.ts +357 -0
  127. package/src/world-cell-render-bundles.ts +459 -0
  128. package/src/world-cell-render-gpu-dress.ts +714 -0
  129. package/src/world-cell-render-main-cull.ts +484 -0
  130. package/src/world-cell-render-shadow-claims.ts +198 -0
  131. package/src/world-cell-render-util.ts +246 -0
  132. package/src/world-cell-render.ts +1493 -0
  133. package/src/world-cell-residency.ts +745 -0
  134. package/src/world-cells.ts +1318 -10418
  135. package/src/world-chunk-shadow.ts +308 -0
  136. package/src/world-collar.ts +315 -0
  137. package/src/world-gpu-flags.ts +163 -0
  138. package/src/world-gpu-readback.ts +881 -0
  139. package/src/world-gpu-reference.ts +510 -0
  140. package/src/world-gpu-scene.ts +214 -2264
  141. package/src/world-gpu-shadow.ts +190 -0
  142. package/src/world-gpu-types.ts +381 -0
  143. package/src/world-gpu-validation.ts +518 -0
  144. package/src/world-heightfield.ts +802 -0
  145. package/src/world-load-limiter.ts +106 -0
  146. package/src/world-noise.ts +241 -0
  147. package/src/world-package.ts +42 -0
  148. package/src/world-region.ts +1 -1
  149. package/src/world-terrain-splat.ts +365 -149
  150. package/src/world-tile-budget.ts +256 -0
  151. package/src/world-tile-geometry.ts +469 -0
  152. package/src/world-tile-lod.ts +408 -0
  153. package/src/world-tile-observation.ts +566 -0
  154. package/src/world-tile-stitch.ts +166 -0
  155. package/src/world-tiles.ts +170 -1745
  156. package/src/world-water-bodies.ts +359 -0
  157. package/src/world.ts +35 -741
@@ -0,0 +1,694 @@
1
+ import { Box3, Matrix4, Quaternion, Vector3 } from "three";
2
+ import { InstancedBatch } from "./instanced-batch.js";
3
+ import { biasedLodDistance } from "./model-lod.js";
4
+ import {
5
+ type IAssetPart,
6
+ type IBuildJob,
7
+ type IResidentCell,
8
+ type IWorldCellsFollow,
9
+ crossesGate,
10
+ } from "./world-cell-data.js";
11
+ import {
12
+ PLACEMENT_RECORD_BYTES,
13
+ PLACEMENT_RECORD_FLOATS,
14
+ cullDistance,
15
+ } from "./world-cell-impostors.js";
16
+ import type { IAssetState } from "./world-cell-models.js";
17
+ import { LEVEL_REFILTER_STEP_METRES } from "./world-cell-options.js";
18
+ import { levelAtGates } from "./world-gpu-scene.js";
19
+ import {
20
+ type IWorldAsset,
21
+ type IWorldCell,
22
+ type IWorldRun,
23
+ cellPlacements,
24
+ } from "./world-package.js";
25
+
26
+ /**
27
+ * One empty batch per (level, part), so a placement is filtered and drawn together and an emptied
28
+ * level or a part nobody placed costs one missing mesh rather than the whole cell's run.
29
+ */
30
+ export function newBatches(asset: IAssetState): InstancedBatch[][] {
31
+ const batches: InstancedBatch[][] = [];
32
+ for (const parts of asset.levels) {
33
+ const levelBatches: InstancedBatch[] = [];
34
+ for (const part of parts)
35
+ levelBatches.push(new InstancedBatch({ geometry: part.geometry, material: part.material }));
36
+ batches.push(levelBatches);
37
+ }
38
+ return batches;
39
+ }
40
+
41
+ /** How many meshes a build will publish: one per (level, part). */
42
+ export function publishCount(batches: readonly InstancedBatch[][]): number {
43
+ let total = 0;
44
+ for (const levelBatches of batches) total += levelBatches.length;
45
+ return total;
46
+ }
47
+
48
+ /**
49
+ * One empty bounds box per `(level, part)`, beside the batches `addPlacements` measures. Written as a
50
+ * loop because this file is held to a rule that the array method's name is a material's texture
51
+ * property.
52
+ */
53
+ export function newBoxes(batches: readonly InstancedBatch[][]): Box3[][] {
54
+ const boxes: Box3[][] = [];
55
+ for (const levelBatches of batches) {
56
+ const level: Box3[] = [];
57
+ for (const _batch of levelBatches) level.push(new Box3());
58
+ boxes.push(level);
59
+ }
60
+ return boxes;
61
+ }
62
+
63
+ /** What the placement build asks its world for. Every read is the world's own state, not a copy. */
64
+ export interface ICellPlacementsHost {
65
+ extent(): { readonly cellSize: number; readonly minX: number; readonly minZ: number };
66
+ /** The point `placementReach` is measured from. */
67
+ follow(): IWorldCellsFollow;
68
+ /** The point levels and `maxDistance` are measured from this update; see `updateEye`. */
69
+ eye(): Vector3;
70
+ /** Bumped by every admission and eviction, so a residency change owes a refilter. */
71
+ residencyEpoch(): number;
72
+ asset(id: string): IAssetState | undefined;
73
+ canonical(id: string): string;
74
+ queueBuild(asset: IAssetState, cell: IResidentCell, run: IWorldRun, replace?: boolean): void;
75
+ /** The renderer's own switch: the dispatch grades levels itself while it is on. */
76
+ gpuOn(): boolean;
77
+ /** Whether this asset can append a whole-asset impostor, so a placement root is wanted. */
78
+ rootsNeeded(asset: IAssetState): boolean;
79
+ /** The resident ring: what the refilter pass scans. */
80
+ resident(): Iterable<IResidentCell>;
81
+ }
82
+
83
+ /**
84
+ * Where a cell's placement records become drawable batches, and when a walk makes that answer stale.
85
+ *
86
+ * The build is the same build `world-cells.ts` ran: one slice of a run's records at a time, the
87
+ * CPU `maxDistance`/`placementReach` filters at the position the slice started from, the level a
88
+ * shared gate rule picks, the fade a swap stamps, and the per-placement bounds the shadow levels
89
+ * are invalidated by. `refilter` is the pass that queues a rebuild when the follow point has moved
90
+ * a gate, and `stale` says whether it runs at all.
91
+ *
92
+ * The record filters, the published levels, the world's gate list and the refilter points live here;
93
+ * everything else — the renderer's own GPU switch, the resident ring, the build queue — is asked of
94
+ * the host.
95
+ */
96
+ export class CellPlacements {
97
+ readonly #host: ICellPlacementsHost;
98
+ /** The authored placement records, immutable for the world's life. */
99
+ readonly #placements: ArrayBuffer;
100
+ readonly #placementReach: Float32Array | undefined;
101
+ /** Per cell and asset, the reach range the load measured; empty when no reach was authored. */
102
+ readonly #reachRanges: ReadonlyMap<
103
+ IWorldCell,
104
+ Map<string, { min: number; max: number; minY: number; maxY: number }>
105
+ >;
106
+ readonly #lodHysteresis: number;
107
+ readonly #rebuildsPerUpdate: number;
108
+ /** Each record's last published level, kept only when a walking level hysteresis is on. */
109
+ readonly #placementLevels: Uint32Array | undefined;
110
+ /** Each record's last published levels, `(min + 1) | (max + 1) << 4` (0: none yet). */
111
+ readonly #placementRanges: Uint8Array | undefined;
112
+ /** Every distinct gate distance the world's assets have, ascending; see `noteGate`. */
113
+ readonly #gates: number[] = [];
114
+ /** The reused hit list and the reused per-cell seen set; see `#staleIn`. */
115
+ readonly #stale: Array<{
116
+ cell: IResidentCell;
117
+ distance: number;
118
+ id: string;
119
+ }> = [];
120
+ readonly #staleSeen = new Set<string>();
121
+ /** Stale cell-assets the passes found, cumulative; see `IWorldCellsStats.refilterEntries`. */
122
+ #staleEntries = 0;
123
+ /** Refilter passes run, whether or not they queued anything; see `IWorldCellsStats.refilters`. */
124
+ #refilters = 0;
125
+ /** Replacement builds that entered `addPlacements`; initial admission is not CPU refilter work. */
126
+ #levelRefilters = 0;
127
+ /** The follow point the last refilter pass ran for; see `stale`. */
128
+ readonly #refilterPoint = new Vector3(Number.NaN, 0, Number.NaN);
129
+ /** The LOD eye the last refilter pass ran for; see `stale`. */
130
+ readonly #refilterEye = new Vector3(Number.NaN, 0, Number.NaN);
131
+ /** The residency epoch the last refilter pass saw; see `stale`. */
132
+ #refilterEpoch = -1;
133
+ /** The last pass found more stale cell-assets than `rebuildsPerUpdate` could queue. */
134
+ #refilterOwed = false;
135
+ #rebuilds = 0;
136
+ readonly #position = new Vector3();
137
+ readonly #rotation = new Quaternion();
138
+ readonly #scale = new Vector3();
139
+ readonly #matrix = new Matrix4();
140
+ readonly #recordBounds = new Box3();
141
+ readonly #instance = new Matrix4();
142
+ /** The authored bounds' centre, placed: the source sphere's centre. See `addPlacements`. */
143
+ readonly #sourceCentre = new Vector3();
144
+ /** The world grid, read once: a package's origin and cell side do not change for a world's life. */
145
+ #grid: { readonly cellSize: number; readonly minX: number; readonly minZ: number } | undefined;
146
+
147
+ constructor(
148
+ options: {
149
+ readonly placements: ArrayBuffer;
150
+ readonly placementReach: Float32Array | undefined;
151
+ readonly reachRanges: ReadonlyMap<
152
+ IWorldCell,
153
+ Map<string, { min: number; max: number; minY: number; maxY: number }>
154
+ >;
155
+ readonly lodHysteresis: number;
156
+ readonly rebuildsPerUpdate: number;
157
+ },
158
+ host: ICellPlacementsHost,
159
+ ) {
160
+ this.#host = host;
161
+ this.#placements = options.placements;
162
+ this.#placementReach = options.placementReach;
163
+ this.#reachRanges = options.reachRanges;
164
+ this.#lodHysteresis = options.lodHysteresis;
165
+ this.#rebuildsPerUpdate = options.rebuildsPerUpdate;
166
+ this.#placementLevels =
167
+ options.lodHysteresis > 0
168
+ ? new Uint32Array(options.placements.byteLength / PLACEMENT_RECORD_BYTES)
169
+ : undefined;
170
+ this.#placementRanges =
171
+ this.#placementLevels === undefined
172
+ ? undefined
173
+ : new Uint8Array(this.#placementLevels.length);
174
+ }
175
+
176
+ get placementReach(): Float32Array | undefined {
177
+ return this.#placementReach;
178
+ }
179
+ /** Replacement builds that entered `addPlacements`; see `IWorldCellsStats.levelRefilters`. */
180
+ get levelRefilters(): number {
181
+ return this.#levelRefilters;
182
+ }
183
+ /** Rebuilds a refilter pass queued; see `IWorldCellsStats.rebuilds`. */
184
+ get rebuilds(): number {
185
+ return this.#rebuilds;
186
+ }
187
+ /** Refilter passes run, whether or not they queued anything. */
188
+ get refilters(): number {
189
+ return this.#refilters;
190
+ }
191
+ /** Stale cell-assets the passes found, cumulative. */
192
+ get refilterEntries(): number {
193
+ return this.#staleEntries;
194
+ }
195
+ /** Whether the last pass left work it could not queue. */
196
+ get owed(): boolean {
197
+ return this.#refilterOwed;
198
+ }
199
+ /** The far entry of the asset's finest gate, or none: the eye's blend limit. */
200
+ get firstGate(): number {
201
+ return this.#gates[0] ?? Number.POSITIVE_INFINITY;
202
+ }
203
+ /** The next pass owes a rerun even at a standing follow point. */
204
+ owe(): void {
205
+ this.#refilterOwed = true;
206
+ }
207
+
208
+ /** Borrowed scratch box: consume its transformed volume before the next bounds query. */
209
+ #boundsAt(bounds: IWorldAsset["bounds"], matrix: Matrix4): Box3 {
210
+ this.#recordBounds.min.fromArray(bounds.min);
211
+ this.#recordBounds.max.fromArray(bounds.max);
212
+ return this.#recordBounds.applyMatrix4(matrix);
213
+ }
214
+
215
+ /**
216
+ * Does this update have to run the `maxDistance`/`lods` refilter pass?
217
+ *
218
+ * Three things, and the pass runs when any of them holds: the follow point has moved
219
+ * `LEVEL_REFILTER_STEP_METRES` since the last one, so a walk re-derives its brackets every two
220
+ * metres instead of every half; residency changed, because a cell that arrived or left is the
221
+ * bracket the pass is about; and the last pass found more stale cell-assets than
222
+ * `rebuildsPerUpdate` could queue, so the ones it could not queue are still owed and a still
223
+ * follow point has to keep coming back for them. Anything else is the same brackets, so the pass
224
+ * is skipped and the world does nothing for that update.
225
+ */
226
+ followY(): number {
227
+ return this.#placementReach === undefined ? 0 : (this.#host.follow().position.y ?? 0);
228
+ }
229
+
230
+ stepMetres(): number {
231
+ return this.#placementReach === undefined ? LEVEL_REFILTER_STEP_METRES : 0.75;
232
+ }
233
+
234
+ stale(x: number, z: number): boolean {
235
+ if (this.#refilterOwed) return true;
236
+ if (this.#refilterEpoch !== this.#host.residencyEpoch()) return true;
237
+ return (
238
+ Math.hypot(
239
+ x - this.#refilterPoint.x,
240
+ this.followY() - this.#refilterPoint.y,
241
+ z - this.#refilterPoint.z,
242
+ ) >= this.stepMetres() ||
243
+ // The GPU dispatch grades levels from the camera every frame; only the CPU path rebuilds.
244
+ (this.#host.gpuOn() === false &&
245
+ this.#host.eye().distanceTo(this.#refilterEye) >= this.stepMetres())
246
+ );
247
+ }
248
+
249
+ /**
250
+ * Filter one slice of a run's placements into the batches they draw from, applying the CPU
251
+ * maxDistance/reach filters at the build position and switching level where an asset's `lods` say
252
+ * to. GPU admission retains maxDistance candidates for the dispatch; placementReach stays here
253
+ * because it is an explicit per-record source boundary.
254
+ */
255
+ addPlacements(job: IBuildJob, from: number, to: number): void {
256
+ const { asset, filterX, filterZ, lodX, lodY, lodZ } = job;
257
+ if (job.replacement && job.next === 0) this.#levelRefilters += 1;
258
+ if (job.records === undefined) job.records = cellPlacements(this.#placements, job.run);
259
+ const records = job.records;
260
+ const inner = cullDistance(asset.definition.maxDistance);
261
+ // Half the diagonal of the asset's authored bounds: the sphere the dispatch culls this placement
262
+ // with, and the one number about its extent that comes from the package rather than from here.
263
+ const authored = asset.definition.bounds;
264
+ const boundsRadius =
265
+ 0.5 *
266
+ Math.hypot(
267
+ (authored.max[0] as number) - (authored.min[0] as number),
268
+ (authored.max[1] as number) - (authored.min[1] as number),
269
+ (authored.max[2] as number) - (authored.min[2] as number),
270
+ );
271
+ // Decided once per slice, not per placement: the wide half needs the placement root only for an
272
+ // asset that can append a whole-asset impostor. See `ICellBatch.wideRoot`.
273
+ const wantRoots = this.#host.rootsNeeded(asset);
274
+ for (let index = from; index < to; index += 1) {
275
+ const base = index * PLACEMENT_RECORD_FLOATS;
276
+ const x = records[base] as number;
277
+ const y = records[base + 1] as number;
278
+ const z = records[base + 2] as number;
279
+ // Streaming reach from the follow point; level and `maxDistance` from the LOD eye, which is
280
+ // the camera the GPU dispatch measures from too. See `IWorldCellsLoadOptions.lodFrom`.
281
+ const reachDistance =
282
+ this.#placementReach === undefined
283
+ ? Math.hypot(x - filterX, z - filterZ)
284
+ : Math.hypot(x - filterX, y - job.filterY, z - filterZ);
285
+ const distance =
286
+ this.#placementReach === undefined
287
+ ? Math.hypot(x - lodX, z - lodZ)
288
+ : Math.hypot(x - lodX, y - lodY, z - lodZ);
289
+ if (this.#host.gpuOn() === false && inner !== undefined && distance > inner) continue;
290
+ const reach = this.#placementReach?.[job.run.offset + index];
291
+ if (reach !== undefined && reachDistance > reach) continue;
292
+ this.#position.set(x, y, z);
293
+ this.#rotation.set(
294
+ records[base + 3] as number,
295
+ records[base + 4] as number,
296
+ records[base + 5] as number,
297
+ records[base + 6] as number,
298
+ );
299
+ this.#scale.setScalar(records[base + 7] as number);
300
+ this.#matrix.compose(this.#position, this.#rotation, this.#scale);
301
+ const scale = this.#scale.x;
302
+ // The placement transform, then the part's own offset inside the model: a bark primitive at
303
+ // the trunk and a needles primitive higher up both land in the one instance matrix.
304
+ // The level is picked by the shared gate rule: authored world-metre gates directly, and a
305
+ // whole-asset impostor's terminal gate scaled by this placement's own scale. The bias is the
306
+ // same adaptive multiplier the dispatch carries, so a biased walk crosses a switch here too.
307
+ let level = levelAtGates(
308
+ {
309
+ distances: asset.distances,
310
+ impostor: asset.impostor !== undefined && asset.definition.impostorDistance === undefined,
311
+ },
312
+ biasedLodDistance(distance),
313
+ scale,
314
+ );
315
+ if (this.#placementLevels !== undefined && asset.definition.lods !== undefined) {
316
+ const record = job.run.offset + index;
317
+ let previous = this.#placementLevels[record] as number;
318
+ // Outward gates remain authored; returning inward retains the previous level until the margin.
319
+ if (level > previous) previous = level;
320
+ while (
321
+ previous > level &&
322
+ biasedLodDistance(distance) <
323
+ (asset.distances[previous] as number) * (1 - this.#lodHysteresis)
324
+ )
325
+ previous--;
326
+ level = previous;
327
+ this.#placementLevels[record] = level;
328
+ }
329
+ const selected = [level];
330
+ if (this.#lodHysteresis > 0) {
331
+ const d = biasedLodDistance(distance);
332
+ for (let adjacent = 0; adjacent < asset.levels.length; adjacent++) {
333
+ if (adjacent === level) continue;
334
+ const near = asset.distances[adjacent] ?? 0;
335
+ const far = asset.distances[adjacent + 1] ?? Number.POSITIVE_INFINITY;
336
+ const slack =
337
+ Math.max(near, Number.isFinite(far) ? far : near) * this.#lodHysteresis +
338
+ (asset.distances[1] ?? 6) / 8;
339
+ if (d >= near - slack && d <= far + slack) selected.push(adjacent);
340
+ }
341
+ }
342
+ const minPublished = Math.min(...selected);
343
+ const maxPublished = Math.max(...selected);
344
+ // A refilter that lands after the walk entered a dither band would swap a tree's look in one
345
+ // frame. UE 5.8.3 fades every LOD change over `lod.TemporalLag` (0.5 s,
346
+ // Engine/Source/Runtime/Engine/Private/SceneManagement.cpp:28): a record that was one whole
347
+ // level and now publishes two names that level, and the swap stamps when the fade starts.
348
+ let fadeFrom = -1;
349
+ if (this.#placementRanges !== undefined) {
350
+ const record = job.run.offset + index;
351
+ const before = this.#placementRanges[record] as number;
352
+ const beforeMin = (before & 15) - 1;
353
+ const beforeMax = (before >> 4) - 1;
354
+ if (
355
+ before !== 0 &&
356
+ beforeMin === beforeMax &&
357
+ minPublished !== maxPublished &&
358
+ beforeMin >= minPublished &&
359
+ beforeMin <= maxPublished
360
+ )
361
+ fadeFrom = beforeMin;
362
+ this.#placementRanges[record] = (minPublished + 1) | ((maxPublished + 1) << 4);
363
+ }
364
+ // The record's own world bounds: the placement widened by the asset's authored bounds at the
365
+ // scale it is drawn at. Read here because this loop already holds the placement and the scale,
366
+ // and it is the one number the shadow levels' invalidation is tested against — the cell box is
367
+ // 64 m of it, so a level whose window is 48 m wide was redrawing over ground nothing in it.
368
+ const bounds = asset.definition.bounds;
369
+ const placedBox = this.#boundsAt(bounds, this.#matrix);
370
+ job.placed ??= [];
371
+ job.placed.push(
372
+ index,
373
+ placedBox.min.x,
374
+ placedBox.min.y,
375
+ placedBox.min.z,
376
+ placedBox.max.x,
377
+ placedBox.max.y,
378
+ placedBox.max.z,
379
+ );
380
+ // The far shadow of an asset that can bake a whole-asset impostor draws one quad per placement
381
+ // at the placement root: the parts' own offsets are baked into the atlas, so composing a source
382
+ // part's offset again would apply it twice. One root record per placement, beside the per-part
383
+ // batches and read only by the wide half; see `ICellBatch.wideRoot`.
384
+ for (level of selected) {
385
+ if (wantRoots) {
386
+ job.roots ??= [];
387
+ const roots = job.roots;
388
+ let root = roots[level];
389
+ if (root === undefined) {
390
+ const anchor = asset.levels[level]?.[0];
391
+ if (anchor !== undefined) {
392
+ root = new InstancedBatch({ geometry: anchor.geometry, material: anchor.material });
393
+ roots[level] = root;
394
+ }
395
+ }
396
+ root?.add(this.#matrix);
397
+ }
398
+ // The GPU scene's source record for this placement: the placement's own transform, the level it
399
+ // reached, and a sphere the dispatch tests against the camera's planes. The part offset is the
400
+ // key's own, so one record serves every part of the level — see `#placeSources`.
401
+ if (this.#host.gpuOn()) {
402
+ const list = job.sources ?? [];
403
+ job.sources = list;
404
+ // The sphere is the asset's authored bounds *as placed*, centred where the bounds' centre
405
+ // lands under the placement's own transform: a sphere at the placement instead is not a
406
+ // bound of the placement, and every prop whose model does not straddle the origin lost the
407
+ // half of itself that reaches away from it — a post, a stump, a fern, all of them culled at
408
+ // the edge of the view with their bases outside it. The CPU path's own gate is the cell's box
409
+ // over the same widened bounds, and it is conservative in exactly the way this is now. The
410
+ // centre is the matrix applied to the authored centre, so the placement's quaternion rotates
411
+ // it: composing the offsets by hand dropped the rotation and put a turned off-centre prop's
412
+ // sphere where the unturned one would be. The radius is rotation-invariant and takes the
413
+ // scale alone, which is uniform.
414
+ const centre = this.#sourceCentre
415
+ .set(
416
+ ((bounds.min[0] as number) + (bounds.max[0] as number)) * 0.5,
417
+ ((bounds.min[1] as number) + (bounds.max[1] as number)) * 0.5,
418
+ ((bounds.min[2] as number) + (bounds.max[2] as number)) * 0.5,
419
+ )
420
+ .applyMatrix4(this.#matrix);
421
+ list.push({
422
+ level,
423
+ matrix: this.#matrix.clone(),
424
+ // `boundsRadius` is already the asset's authored bounds radius (half the diagonal), so the
425
+ // placement's sphere radius is that times its own uniform scale — halving it again put the
426
+ // sphere inside the prop and culled the half of it that reaches away from the placement.
427
+ radius: boundsRadius * Math.abs(scale),
428
+ // The magnitude, finite-sanitised: the dispatch's impostor gate takes `|scale|` exactly as
429
+ // `levelAtGates` does, so a mirrored placement reaches the atlas the same way.
430
+ scale: Number.isFinite(scale) ? Math.abs(scale) : 1,
431
+ x: centre.x,
432
+ y: centre.y,
433
+ z: centre.z,
434
+ });
435
+ }
436
+ // Authored bounds include model-part offsets; apply the whole placement transform so
437
+ // rotated, mirrored and off-centre casters cannot fall outside visibility/shadow regions.
438
+ this.#boundsAt(bounds, this.#matrix);
439
+ const parts = asset.levels[level] as readonly IAssetPart[];
440
+ const levelBatches = job.batches?.[level] as InstancedBatch[];
441
+ const levelBoxes = job.boxes?.[level] as Box3[] | undefined;
442
+ for (const [part, entry] of parts.entries()) {
443
+ this.#instance.multiplyMatrices(this.#matrix, entry.local);
444
+ (levelBatches[part] as InstancedBatch).add(this.#instance);
445
+ const range = job.lodRanges?.[level]?.[part];
446
+ if (range !== undefined) range.push(minPublished, maxPublished, fadeFrom, 0);
447
+ const box = levelBoxes?.[part];
448
+ if (box === undefined) continue;
449
+ box.union(this.#recordBounds);
450
+ }
451
+ }
452
+ }
453
+ }
454
+
455
+ /**
456
+ * Build one (level, part) batch into a mesh. One mesh is one unit, because this is where every
457
+ * instance matrix is written and the batch's bounds are first computed — the part of admission the
458
+ * renderer pays for again on the frame it first draws the result. The mesh joins the cell in
459
+ * {@link #swap}, with the rest of the job, so it is never half a replacement.
460
+ *
461
+ * ponytail: a hard switch, no crossfade — a placement crosses a level boundary by being rebuilt
462
+ * into the other level's batch, so the swap pops. A blend needs a per-instance mix the
463
+ * InstancedBatch has no slot for; add one when a game's swap is visible enough to pay for it.
464
+ */
465
+ /**
466
+ * Fold one batch's own filter point into the cell's bracket, which only ever widens. See
467
+ * `IResidentCell.filterNear` and `#staleIn`.
468
+ */
469
+ widenFilterRange(cell: IResidentCell, filterX: number, filterZ: number): void {
470
+ const [near, far] = this.#span(cell, filterX, filterZ);
471
+ if (near < cell.filterNear) cell.filterNear = near;
472
+ if (far > cell.filterFar) cell.filterFar = far;
473
+ }
474
+
475
+ buildOne(job: IBuildJob, batches: readonly InstancedBatch[][]): void {
476
+ const { asset } = job;
477
+ const { cell } = job;
478
+ this.widenFilterRange(cell, job.lodX, job.lodZ);
479
+ let part = job.published;
480
+ for (const [level, levelBatches] of batches.entries()) {
481
+ if (part >= levelBatches.length) {
482
+ part -= levelBatches.length;
483
+ continue;
484
+ }
485
+ const box = job.boxes?.[level]?.[part];
486
+ job.fresh.push({
487
+ asset: asset.id,
488
+ batch: levelBatches[part] as InstancedBatch,
489
+ caster: undefined,
490
+ casterSegment: -1,
491
+ gpu: undefined,
492
+ wide: undefined,
493
+ wideSegment: -1,
494
+ wideRoot: job.roots?.[level],
495
+ lastFilterY: job.filterY,
496
+ lastFilterX: job.filterX,
497
+ lastFilterZ: job.filterZ,
498
+ lastLodX: job.lodX,
499
+ lastLodY: job.lodY,
500
+ lastLodZ: job.lodZ,
501
+ level,
502
+ lodRanges: job.lodRanges?.[level]?.[part]?.length
503
+ ? Float32Array.from(job.lodRanges[level]?.[part] ?? [])
504
+ : undefined,
505
+ part,
506
+ run: job.run,
507
+ segment: -1,
508
+ shared: undefined,
509
+ // Where these records are, for the shadow invalidation this entry's swap hands over.
510
+ shadowBounds: box === undefined || box.isEmpty() ? undefined : box,
511
+ threshold: this.#reachRanges.get(cell.cell)?.has(asset.id)
512
+ ? Math.min(asset.threshold ?? Number.POSITIVE_INFINITY, 6)
513
+ : asset.threshold,
514
+ });
515
+ job.published += 1;
516
+ return;
517
+ }
518
+ }
519
+
520
+ /**
521
+ * The `[nearest, farthest]` distance from `(x, z)` to the rectangle a cell's placements lie in.
522
+ *
523
+ * ponytail: the rectangle is the compiler's contract — a run's records belong to the cell they
524
+ * are filed under — so one interval covers every placement in a cell. A hand-edited package that
525
+ * files a placement under a neighbouring cell keeps it at the level its own distance selects; a
526
+ * validator check on the placement buffer is the fix if that ever has to be caught.
527
+ */
528
+ #span(cell: IResidentCell, x: number, z: number): readonly [number, number] {
529
+ this.#grid ??= this.#host.extent();
530
+ const { cellSize, minX, minZ } = this.#grid;
531
+ const left = minX + cell.x * cellSize;
532
+ const near = minZ + cell.z * cellSize;
533
+ const right = left + cellSize;
534
+ const far = near + cellSize;
535
+ return [
536
+ Math.hypot(Math.max(left - x, x - right, 0), Math.max(near - z, z - far, 0)),
537
+ Math.hypot(
538
+ Math.max(Math.abs(x - left), Math.abs(x - right)),
539
+ Math.max(Math.abs(z - near), Math.abs(z - far)),
540
+ ),
541
+ ];
542
+ }
543
+
544
+ /**
545
+ * One entry per asset of `cell` the follow point has moved a gate of, nearest placement first.
546
+ *
547
+ * The cell's own bracket is the caller's: it was derived once for the cell, and every batch of a
548
+ * cell is measured against the same rectangle, so deriving it per batch was the same four
549
+ * `Math.max` and two `Math.hypot` calls as many times as the cell had batches. What is left here is
550
+ * per batch: one moved-point test and, for a batch that moved, its own bracket.
551
+ *
552
+ * Nothing is allocated to find them: the entries go into one reused array, the per-cell "already
553
+ * seen" set into another, and a pass that crossed no gate anywhere pushes nothing at all.
554
+ */
555
+ #staleIn(cell: IResidentCell, x: number, z: number, near: number, far: number): void {
556
+ const seen = this.#staleSeen;
557
+ seen.clear();
558
+ const eye = this.#host.eye();
559
+ const [eyeNear, eyeFar] = this.#span(cell, eye.x, eye.z);
560
+ for (const entry of cell.batches) {
561
+ const reach = this.#reachRanges.get(cell.cell)?.get(entry.asset);
562
+ if ((entry.threshold === undefined && reach === undefined) || seen.has(entry.asset)) continue;
563
+ // Deferred runs of one asset can start at different camera snapshots. Only deduplicate
564
+ // after one entry proves the asset stale: an earlier matching run cannot settle the others.
565
+ const step = (entry.threshold ?? 6) / 8;
566
+ if (
567
+ Math.hypot(
568
+ x - entry.lastFilterX,
569
+ this.followY() - entry.lastFilterY,
570
+ z - entry.lastFilterZ,
571
+ ) <= step &&
572
+ Math.hypot(eye.x - entry.lastLodX, eye.y - entry.lastLodY, eye.z - entry.lastLodZ) <= step
573
+ )
574
+ continue;
575
+ const asset = this.#host.asset(entry.asset);
576
+ if (asset === undefined) continue;
577
+ // GPU dispatch handles maxDistance and LOD gates; placementReach remains a CPU boundary.
578
+ const gates = this.#host.gpuOn() ? [] : asset.gates;
579
+ // Gates bracket the LOD eye's distances, reach the follow point's: see `#addPlacements`.
580
+ const [builtNear, builtFar] = this.#span(cell, entry.lastLodX, entry.lastLodZ);
581
+ let low = Math.min(eyeNear, builtNear);
582
+ // Ends included, so a placement exactly on a gate is one of the reasons to rebuild.
583
+ let high = Math.max(eyeFar, builtFar);
584
+ let reachCrossed = false;
585
+ if (reach !== undefined) {
586
+ const vertical = (y: number): [number, number] => [
587
+ Math.max(reach.minY - y, y - reach.maxY, 0),
588
+ Math.max(Math.abs(y - reach.minY), Math.abs(y - reach.maxY)),
589
+ ];
590
+ const eyeNow = vertical(eye.y);
591
+ const eyeBefore = vertical(entry.lastLodY);
592
+ low = Math.min(Math.hypot(eyeNear, eyeNow[0]), Math.hypot(builtNear, eyeBefore[0]));
593
+ high = Math.max(Math.hypot(eyeFar, eyeNow[1]), Math.hypot(builtFar, eyeBefore[1]));
594
+ const [reachBuiltNear, reachBuiltFar] = this.#span(
595
+ cell,
596
+ entry.lastFilterX,
597
+ entry.lastFilterZ,
598
+ );
599
+ const current = vertical(this.followY());
600
+ const previous = vertical(entry.lastFilterY);
601
+ const reachLow = Math.min(
602
+ Math.hypot(near, current[0]),
603
+ Math.hypot(reachBuiltNear, previous[0]),
604
+ );
605
+ const reachHigh = Math.max(
606
+ Math.hypot(far, current[1]),
607
+ Math.hypot(reachBuiltFar, previous[1]),
608
+ );
609
+ reachCrossed = reach.min <= reachHigh && reach.max >= reachLow;
610
+ }
611
+ if (!reachCrossed && !gates.some((gate) => gate >= low && gate <= high)) continue;
612
+ seen.add(entry.asset);
613
+ this.#stale.push({ cell, distance: eyeNear, id: entry.asset });
614
+ this.#staleEntries += 1;
615
+ }
616
+ }
617
+
618
+ /**
619
+ * Record that one more gate distance exists, keeping the world's list ascending so
620
+ * {@link crossesGate} can binary search it. A gate is never withdrawn: an asset whose ring left
621
+ * still leaves its distances behind, which costs a cell the gate test does not reject and never a
622
+ * rebuild the pass owes.
623
+ */
624
+ noteGate(gate: number): void {
625
+ const gates = this.#gates;
626
+ if (gates.includes(gate)) return;
627
+ let at = gates.length;
628
+ while (at > 0 && (gates[at - 1] as number) > gate) at -= 1;
629
+ gates.splice(at, 0, gate);
630
+ }
631
+
632
+ /**
633
+ * Queue a refilter for every batch whose follow point has moved far enough to have crossed a CPU
634
+ * source-admission boundary: maxDistance/lod gates on the CPU path, or placementReach in either
635
+ * path. GPU maxDistance/lod gates stay in the dispatch, so they do not enter this replacement
636
+ * queue.
637
+ *
638
+ * Two things keep that pass from costing a frame. A cell's placements all sit inside one
639
+ * rectangle, so the two points that matter — where the batch was built and where the follow point
640
+ * is now — bracket every distance a placement of that cell can have had; with no gate of the
641
+ * asset in that span the level and cull answer is the same and the rebuild could change nothing,
642
+ * and the position the batch was built from is kept so the next move is still measured from it.
643
+ * What is genuinely stale is queued nearest cell first, `rebuildsPerUpdate` of them per call, and
644
+ * the queue spends the frame's admission budget on them like any other build — so a refilter that
645
+ * cannot be afforded this frame leaves the cell drawing the level it has, not a hole.
646
+ */
647
+ refilter(x: number, z: number): void {
648
+ this.#refilterPoint.set(x, this.followY(), z);
649
+ this.#refilterEye.copy(this.#host.eye());
650
+ this.#refilterEpoch = this.#host.residencyEpoch();
651
+ this.#refilters += 1;
652
+ const stale = this.#stale;
653
+ stale.length = 0;
654
+ this.#collectStale(x, z);
655
+ // Only what was found, and usually a handful of entries.
656
+ if (stale.length > 1) stale.sort((a, b) => a.distance - b.distance || a.id.localeCompare(b.id));
657
+ // What the cap could not queue is still owed, and `stale` reads that: a standing follow
658
+ // point has to keep coming back for it, or a walk that stopped mid-drain never finished.
659
+ this.#refilterOwed = stale.length > this.#rebuildsPerUpdate;
660
+ for (const job of stale.slice(0, this.#rebuildsPerUpdate)) {
661
+ const asset = this.#host.asset(job.id);
662
+ if (asset === undefined || asset.levels.length === 0) continue;
663
+ // Every run of the group, not just the one that happens to carry the canonical's name: a cell
664
+ // holding two names for one model has two stale answers, and rebuilding only the named one
665
+ // left the other drawing the level its own distance has moved out of.
666
+ for (const run of job.cell.cell.runs) {
667
+ if (this.#host.canonical(run.asset) !== job.id) continue;
668
+ this.#host.queueBuild(asset, job.cell, run, true);
669
+ this.#rebuilds += 1;
670
+ }
671
+ }
672
+ }
673
+
674
+ /**
675
+ * Every resident cell's stale assets, into the reused list, nearest placement first.
676
+ *
677
+ * A cell is gated as a whole before one of its batches is looked at: its own bracket is derived
678
+ * once, unioned with every distance any of its batches was filtered from, and one binary search
679
+ * over the world's gates decides it. No gate in that range means no asset of the cell can have
680
+ * changed side of one, so its batches are not walked at all — which is the whole cost of a pass in
681
+ * which the follow point has not yet reached anything that switches.
682
+ */
683
+ #collectStale(x: number, z: number): void {
684
+ for (const cell of this.#host.resident()) {
685
+ // Gates are measured from the LOD eye, and `filterNear`/`filterFar` hold the eyes built from.
686
+ const [eyeNear, eyeFar] = this.#span(cell, this.#host.eye().x, this.#host.eye().z);
687
+ const low = eyeNear < cell.filterNear ? eyeNear : cell.filterNear;
688
+ const high = eyeFar > cell.filterFar ? eyeFar : cell.filterFar;
689
+ if (!this.#reachRanges.has(cell.cell) && !crossesGate(this.#gates, low, high)) continue;
690
+ const [near, far] = this.#span(cell, x, z);
691
+ this.#staleIn(cell, x, z, near, far);
692
+ }
693
+ }
694
+ }