@threenative/core 0.3.10 → 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 (158) 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 +10565 -22533
  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-camera-cull.ts +32 -1
  84. package/src/render-pass-budget.ts +34 -7
  85. package/src/renderProjection.ts +22 -0
  86. package/src/renderer.ts +92 -37
  87. package/src/snow-field.ts +1 -1
  88. package/src/spells/cast-pool.ts +361 -0
  89. package/src/spells/index.ts +177 -0
  90. package/src/spells/mechanisms.ts +295 -0
  91. package/src/spells/reaction-field.ts +415 -0
  92. package/src/spells/spell-lights.ts +139 -0
  93. package/src/spells/spell-world.ts +187 -0
  94. package/src/spells/spell.ts +397 -0
  95. package/src/spells/spells.ts +283 -0
  96. package/src/spells/ultra/engine/camera.ts +184 -0
  97. package/src/spells/ultra/engine/quality.ts +96 -0
  98. package/src/spells/ultra/index.ts +52 -0
  99. package/src/spells/ultra/main.ts +305 -0
  100. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  101. package/src/spells/ultra/spells/cast.ts +233 -0
  102. package/src/spells/ultra/spells/fire.ts +1267 -0
  103. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  104. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  105. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  106. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  107. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  108. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  109. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  110. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  111. package/src/spells/ultra/vfx/common.ts +1195 -0
  112. package/src/spells/ultra/vfx/noise.ts +441 -0
  113. package/src/startup-readiness.ts +128 -34
  114. package/src/version.ts +1 -1
  115. package/src/warmup.ts +56 -8
  116. package/src/water-surface.ts +9 -3
  117. package/src/world-bundle-safety.ts +401 -0
  118. package/src/world-cell-batches.ts +1216 -0
  119. package/src/world-cell-chunks.ts +1132 -0
  120. package/src/world-cell-data.ts +995 -0
  121. package/src/world-cell-impostors.ts +1449 -0
  122. package/src/world-cell-lod-bias.ts +151 -0
  123. package/src/world-cell-models.ts +1074 -0
  124. package/src/world-cell-options.ts +189 -0
  125. package/src/world-cell-placements.ts +694 -0
  126. package/src/world-cell-prewarm.ts +557 -0
  127. package/src/world-cell-readiness.ts +357 -0
  128. package/src/world-cell-render-bundles.ts +459 -0
  129. package/src/world-cell-render-gpu-dress.ts +714 -0
  130. package/src/world-cell-render-main-cull.ts +484 -0
  131. package/src/world-cell-render-shadow-claims.ts +198 -0
  132. package/src/world-cell-render-util.ts +246 -0
  133. package/src/world-cell-render.ts +1493 -0
  134. package/src/world-cell-residency.ts +745 -0
  135. package/src/world-cells.ts +1318 -10418
  136. package/src/world-chunk-shadow.ts +308 -0
  137. package/src/world-collar.ts +315 -0
  138. package/src/world-gpu-flags.ts +163 -0
  139. package/src/world-gpu-readback.ts +881 -0
  140. package/src/world-gpu-reference.ts +510 -0
  141. package/src/world-gpu-scene.ts +214 -2264
  142. package/src/world-gpu-shadow.ts +190 -0
  143. package/src/world-gpu-types.ts +381 -0
  144. package/src/world-gpu-validation.ts +518 -0
  145. package/src/world-heightfield.ts +802 -0
  146. package/src/world-load-limiter.ts +106 -0
  147. package/src/world-noise.ts +241 -0
  148. package/src/world-package.ts +42 -0
  149. package/src/world-region.ts +1 -1
  150. package/src/world-terrain-splat.ts +365 -149
  151. package/src/world-tile-budget.ts +256 -0
  152. package/src/world-tile-geometry.ts +469 -0
  153. package/src/world-tile-lod.ts +408 -0
  154. package/src/world-tile-observation.ts +566 -0
  155. package/src/world-tile-stitch.ts +166 -0
  156. package/src/world-tiles.ts +170 -1745
  157. package/src/world-water-bodies.ts +359 -0
  158. package/src/world.ts +35 -741
@@ -0,0 +1,1493 @@
1
+ import type { IAssetState } from "./world-cell-models.js";
2
+
3
+ import type {
4
+ IAssetPart,
5
+ IBatchShape,
6
+ IBuildJob,
7
+ ICamera,
8
+ ICellBatch,
9
+ IKeyDescriptor,
10
+ IResidentCell,
11
+ IShadowRegion,
12
+ IWorldCellsBudget,
13
+ IWorldCellsFollow,
14
+ IWorldCellsStats,
15
+ } from "./world-cell-data.js";
16
+ import { PLACEMENT_RECORD_FLOATS, cullDistance, isAlphaFoliage } from "./world-cell-impostors.js";
17
+
18
+ import { PLACED_STRIDE, clusterOf, sameLodRanges } from "./world-cell-data.js";
19
+
20
+ import {
21
+ Box3,
22
+ BufferGeometry,
23
+ type Camera,
24
+ Frustum,
25
+ type InstancedMesh,
26
+ type Material,
27
+ Matrix4,
28
+ type Mesh,
29
+ type Object3D,
30
+ Quaternion,
31
+ Vector3,
32
+ } from "three";
33
+ import { renderGroup, uniform } from "three/tsl";
34
+ import type { BundleGroup } from "three/webgpu";
35
+
36
+ import { lodChainOf, setLodBias } from "./model-lod.js";
37
+ import type { OcclusionMode } from "./render/depth-pyramid.js";
38
+
39
+ import { parkMesh } from "./render/mesh-pool.js";
40
+ import {
41
+ VIRTUAL_SHADOW_KEY_LAYER,
42
+ VIRTUAL_SHADOW_SMALL_CASTER_LAYER,
43
+ } from "./render/virtual-shadow-layers.js";
44
+ import {
45
+ type ITemporalLod,
46
+ advanceTemporalLod,
47
+ worldLodMaterial,
48
+ } from "./render/world-impostor-surface.js";
49
+ import type { IRendererLike } from "./renderer.js";
50
+ import { isStatic, markStatic } from "./static-transform.js";
51
+
52
+ import { CellBundles } from "./world-cell-render-bundles.js";
53
+ import { CellGpuDress } from "./world-cell-render-gpu-dress.js";
54
+ import { CellMainCull } from "./world-cell-render-main-cull.js";
55
+ import {
56
+ type IShadowClaimHost,
57
+ castLevelOf,
58
+ casts,
59
+ claimCaster,
60
+ claimWide,
61
+ clearSegment,
62
+ keysForShadow,
63
+ shadowFloorOf,
64
+ smallCaster,
65
+ wideOwed,
66
+ } from "./world-cell-render-shadow-claims.js";
67
+ import {
68
+ GPU_KEY_SUFFIX,
69
+ MAIN_CULL_MARKER_MS,
70
+ MAIN_CULL_PAD_METRES,
71
+ MAIN_CULL_SQUARE_METRES,
72
+ RETIRED_SHARED_BYTES,
73
+ SHADOW_REGION_CAP,
74
+ UNDITHERED_LOD_WIDTH,
75
+ assertSlotFree,
76
+ chunkDraws,
77
+ freshMeshFor,
78
+ heldBytes,
79
+ indirectView,
80
+ mainShard,
81
+ redressMaterial,
82
+ followCluster as squareOf,
83
+ } from "./world-cell-render-util.js";
84
+
85
+ // The split's constants stay named from this module, which is where every caller imports them.
86
+ export {
87
+ MAIN_CULL_SQUARE_METRES,
88
+ UNDITHERED_LOD_WIDTH,
89
+ mainShard,
90
+ } from "./world-cell-render-util.js";
91
+ import { type ICasterScaleMesh, SharedBatch, sameSquares } from "./world-cell-batches.js";
92
+ import { levelTriangles, release } from "./world-cell-chunks.js";
93
+ import { WIDE_CLUSTER } from "./world-cell-prewarm.js";
94
+ import {
95
+ CHUNK_NAME,
96
+ VIRTUAL_SHADOW_CASTER_LAYER,
97
+ VIRTUAL_SHADOW_WIDE_CASTER_LAYER,
98
+ } from "./world-chunk-shadow.js";
99
+ import {
100
+ DRAW_ARGS_BYTES,
101
+ type IAssetSlot,
102
+ type ILiveAsset,
103
+ type IMeshDraw,
104
+ type IShadowLevel,
105
+ WorldGpuScene,
106
+ gpuSceneValidationRequested,
107
+ liveKeyInstances,
108
+ } from "./world-gpu-scene.js";
109
+
110
+ import {
111
+ type IWorldAsset,
112
+ type IWorldCell,
113
+ type IWorldPackage,
114
+ type IWorldRun,
115
+ cellPlacements,
116
+ } from "./world-package.js";
117
+
118
+ export interface ICellRenderHost {
119
+ asset(id: string): IAssetState | undefined;
120
+ assets(): Iterable<IAssetState>;
121
+ canonical(id: string): string;
122
+ renderer(): IRendererLike | undefined;
123
+ camera(): Camera | undefined;
124
+ now(): number;
125
+ stats(): IWorldCellsStats;
126
+ residentCells(): IterableIterator<IResidentCell>;
127
+ runMax(asset: string): number | undefined;
128
+ widenFilterRange(cell: IResidentCell, x: number, z: number): void;
129
+ addUnchanged(): void;
130
+ disableFar(run: IWorldRun): void;
131
+ deferWide(id: string): void;
132
+ queuedBuilds(): number;
133
+ covered(): boolean;
134
+ prewarmSettled(): boolean;
135
+ awaitDraw(shared: SharedBatch): void;
136
+ carryPrewarm(old: ICasterScaleMesh, next: ICasterScaleMesh): void;
137
+ add(object: Object3D): void;
138
+ isParent(object: Object3D): boolean;
139
+ isBundleHome(shared: SharedBatch): boolean;
140
+ }
141
+ interface ICellRenderSettings {
142
+ readonly mainCullToldAt: number;
143
+ readonly follow: IWorldCellsFollow;
144
+ readonly budgets: IWorldCellsBudget;
145
+ readonly cellSize: number;
146
+ readonly minX: number;
147
+ readonly minZ: number;
148
+ readonly manifest: IWorldPackage;
149
+ readonly placements: ArrayBuffer;
150
+ readonly coveredFreshMeshesPerUpdate: number;
151
+ readonly freshMeshesPerUpdate: number;
152
+ readonly receiveShadow: boolean;
153
+ readonly castShadowLevels: number;
154
+ readonly shadowMinLevel: number;
155
+ readonly extentBounds: Box3;
156
+ readonly preserveAuthoredParts: boolean;
157
+ readonly lodHysteresis: number;
158
+ readonly lodTransition: "band" | "none" | "temporal";
159
+ readonly lodSpatial: boolean;
160
+ readonly cellsPerCluster: number;
161
+ readonly cellsPerCullCell: number;
162
+ readonly smallCasterMetres: number;
163
+ readonly bundlesWanted: boolean;
164
+ readonly bundleReason: string;
165
+ readonly invalidateShadows: ((region?: IShadowRegion) => void) | undefined;
166
+ }
167
+
168
+ export class CellRender {
169
+ readonly #budgets: IWorldCellsBudget;
170
+
171
+ readonly #cellSize: number;
172
+
173
+ readonly #manifest: IWorldPackage;
174
+
175
+ readonly #minX: number;
176
+
177
+ readonly #minZ: number;
178
+
179
+ readonly #placements: ArrayBuffer;
180
+
181
+ readonly #freshMeshesPerUpdate: number;
182
+
183
+ readonly #coveredFreshMeshesPerUpdate: number;
184
+
185
+ /** Fresh meshes created this update, and whether a build waited for next frame's allowance. */
186
+ #freshThisUpdate = 0;
187
+
188
+ #meshStalled = false;
189
+
190
+ /** One shared mesh per `asset:level:part`, holding every resident cell's segment; see SharedBatch. */
191
+ readonly #shared = new Map<string, SharedBatch>();
192
+
193
+ /** Every record the main pass draws through, and the chunk records under each resident cell. */
194
+ readonly #bundles: CellBundles;
195
+
196
+ /** The volumes and windows the main pass culls with; see {@link CellMainCull}. */
197
+ readonly #cull: CellMainCull;
198
+
199
+ /** The mesh a key draws: its shape, its LOD material and its dress against the GPU scene. */
200
+ readonly #dress: CellGpuDress;
201
+
202
+ /**
203
+ * `asset:level:part` -> a released batch kept for the walk back over the same ground, oldest
204
+ * first. `#release` used to throw the mesh away with the asset, so a cell that left the ring and
205
+ * came back drew into a brand new one — a uuid three had never built a node for, in the main pass
206
+ * and in every shadow pass, which is the walk-time frame cost the standing frame rate never pays.
207
+ * The batch is empty by then (`#evict` clears a cell's own block before the refcount reaches
208
+ * zero), so it is handed back whole; only its parts are gone, and `rebind` replaces them.
209
+ */
210
+ readonly #retired = new Map<string, SharedBatch>();
211
+
212
+ #retiredBytes = 0;
213
+
214
+ readonly #extentBounds: Box3;
215
+
216
+ /** How many of an asset's finest levels cast shadows; 0 when the game asked for none. */
217
+ readonly #castShadowLevels: number;
218
+
219
+ /** `shadows.minLevel`: the finest level a placement's shadow draws; see `shadowFloorOf`. */
220
+ readonly #shadowMinLevel: number;
221
+
222
+ readonly #receiveShadow: boolean;
223
+
224
+ /** Asset bounds height under which a wide caster goes on the finest level's layer only. */
225
+ readonly #smallCasterMetres: number;
226
+
227
+ readonly #cellsPerCluster: number;
228
+
229
+ /**
230
+ * Streamed records changed since the shadow levels were last told, and when they were last told.
231
+ * One invalidation batch a second, and only for a game that passed the hook: the companions
232
+ * used to make the hook necessary, and now the levels cull clusters themselves.
233
+ */
234
+ // `true` so the first `update` runs a residency pass: `#residencyStale` reads it, and a fresh
235
+ // world has admitted nothing.
236
+ #shadowMoved = true;
237
+
238
+ #shadowToldAt = Number.NEGATIVE_INFINITY;
239
+
240
+ /**
241
+ * Separate unions of evicted and admitted records since the levels were last told. An unknown
242
+ * region sets `#shadowFull`, so a narrower later change cannot discard the blanket ask.
243
+ */
244
+ /** Changed records' boxes since the last tell, merged only where they overlap; see `shadowRecordsMoved`. */
245
+ readonly #shadowRegions: IShadowRegion[] = [];
246
+ readonly #shadowAdmissions: IShadowRegion[] = [];
247
+ #shadowFull = false;
248
+
249
+ /** World cells per main-cull visibility cell; see `MAIN_CULL_SQUARE_METRES`. */
250
+ readonly #cellsPerCullCell: number;
251
+
252
+ /** The game's hook to refresh the shadow levels after streamed records changed. */
253
+ readonly #invalidateShadows: ((region?: IShadowRegion) => void) | undefined;
254
+
255
+ /**
256
+ * The GPU-driven main pass, and whether the world asked for it. Off is byte-for-byte this class's
257
+ * own CPU path: nothing below reads `on` except the four places the option changes what a frame
258
+ * does. See the `gpuScene` load option and `#cullMainPass`.
259
+ */
260
+ readonly #gpuScene = new WorldGpuScene();
261
+
262
+ /** Every main key this world has minted a shadow twin for, which is what a level's dispatch asks for. */
263
+ readonly #shadowKeyNames = new Set<string>();
264
+
265
+ /** Resident placements per canonical asset, which is the capacity a key of that asset needs. */
266
+ readonly #gpuResident = new Map<string, number>();
267
+
268
+ readonly #preserveAuthoredParts: boolean;
269
+
270
+ readonly #lodHysteresis: number;
271
+ readonly #lodTransition: "band" | "none" | "temporal";
272
+ readonly #lodSpatial: boolean;
273
+
274
+ readonly #lodDistanceBias = uniform(1).setGroup(renderGroup);
275
+
276
+ readonly #lodMaterials = new Map<
277
+ string,
278
+ { readonly source: Material; readonly material: Material }
279
+ >();
280
+
281
+ /** The resident ring has been handed to the scene once; see `#seedGpuSources`. */
282
+ #gpuSeeded = false;
283
+
284
+ /**
285
+ * The render-cadence dispatch. The engine hands the frame's render camera over, and this world's
286
+ * main windows follow it; see {@link #cullMainPass} for why the decision is not the meshes' own.
287
+ */
288
+ /** New batch meshes this update may create: scaled while the startup cover hides the world. */
289
+ freshAllowance(): number {
290
+ return this.#host.covered() ? this.#coveredFreshMeshesPerUpdate : this.#freshMeshesPerUpdate;
291
+ }
292
+
293
+ /**
294
+ * Hand the cell its finished batches and take back the ones they replace, in one step.
295
+ *
296
+ * This is the no-hole rule. Attaching and detaching in the same synchronous block means no frame
297
+ * ever shows the replacement beside the batch it replaces, and a refilter that waits three frames
298
+ * for budget shows the level the cell already had for those three frames rather than nothing.
299
+ */
300
+ swap(job: IBuildJob): boolean {
301
+ const { cell } = job;
302
+ // A refilter that rebuilt byte-for-byte the records the cell already draws must write, clear and
303
+ // move nothing. `#staleIn` queues on the *cell's* distance bracket, which is wider than any one
304
+ // placement's, so a rebuild whose level or cull answer did not move still comes back identical.
305
+ // A matched pair is settled here instead: the outgoing entry keeps its block and its place in
306
+ // the cell, only its filter point moves, so the next gate is measured from where the follow
307
+ // point is now rather than from where it was when the answer was already right. Everything
308
+ // else falls through to the swap below untouched.
309
+ for (let index = job.fresh.length - 1; index >= 0 && job.force === false; index -= 1) {
310
+ const fresh = job.fresh[index] as ICellBatch;
311
+ const at = job.replaced.findIndex(
312
+ (old) =>
313
+ old.level === fresh.level &&
314
+ old.part === fresh.part &&
315
+ old.batch.equals(fresh.batch) &&
316
+ sameLodRanges(old.lodRanges, fresh.lodRanges),
317
+ );
318
+ if (at < 0) continue;
319
+ const same = job.replaced.splice(at, 1)[0] as ICellBatch;
320
+ this.#host.addUnchanged();
321
+ same.lastFilterY = fresh.lastFilterY;
322
+ same.lastFilterX = fresh.lastFilterX;
323
+ same.lastFilterZ = fresh.lastFilterZ;
324
+ same.lastLodX = fresh.lastLodX;
325
+ same.lastLodY = fresh.lastLodY;
326
+ same.lastLodZ = fresh.lastLodZ;
327
+ this.#host.widenFilterRange(cell, fresh.lastLodX, fresh.lastLodZ);
328
+ job.fresh.splice(index, 1);
329
+ // The batch that stays is the one that was already drawing, so its source records are its own
330
+ // — and a cell the ring built before the scene came up has none. This is the only path that
331
+ // hands them over for a rebuild whose records came out identical, which is every one of them:
332
+ // the records are the same, so the fast path is always the one taken.
333
+ if (this.#gpuScene.on && same.gpu === undefined) same.gpu = this.placeSources(job, same);
334
+ }
335
+ // Every segment first, so a frame out of fresh meshes leaves the old batches drawing whole.
336
+ for (const entry of job.fresh) {
337
+ if (entry.batch.count === 0) continue;
338
+ // Both halves for every fresh entry, whether or not a stalled frame already claimed one:
339
+ // skipping an entry that has its main block meant the retry never asked for its cluster, so
340
+ // those records reached the main pass and no shadow map.
341
+ if (entry.segment < 0) {
342
+ const shared = this.sharedFor(job.asset.id, entry);
343
+ const segment =
344
+ shared === undefined
345
+ ? undefined
346
+ : this.segmentIn(shared, entry.batch.count, this.cullCellOf(cell));
347
+ if (shared === undefined || segment === undefined) {
348
+ this.#meshStalled = true;
349
+ return false;
350
+ }
351
+ entry.shared = shared;
352
+ entry.segment = segment;
353
+ }
354
+ // The caster cluster, when this level casts. A frame that runs out of fresh meshes between
355
+ // the main mesh and its cluster leaves the main one drawing whole and takes the cluster next
356
+ // frame, which is the same no-hole rule as above: never half a replacement.
357
+ if (!this.claimCaster(job.asset.id, entry, cell)) {
358
+ this.#meshStalled = true;
359
+ return false;
360
+ }
361
+ // The wide half, by the same no-hole rule: a key with a cluster and no wide caster draws into
362
+ // a level that may already be reading the wide layer with nothing in it.
363
+ if (!this.claimWide(job.asset.id, entry)) {
364
+ this.#meshStalled = true;
365
+ return false;
366
+ }
367
+ }
368
+ for (const entry of job.replaced) {
369
+ const at = cell.batches.indexOf(entry);
370
+ if (at >= 0) cell.batches.splice(at, 1);
371
+ this.clearSegment(entry);
372
+ }
373
+ for (const entry of job.fresh) {
374
+ cell.batches.push(entry);
375
+ // When this answer reached the screen, so a record whose level set grew fades into it.
376
+ const ranges = entry.lodRanges;
377
+ if (ranges !== undefined)
378
+ for (let at = 3; at < ranges.length; at += 4) ranges[at] = this.#dress.clockSeconds;
379
+ if (entry.shared !== undefined)
380
+ entry.shared.write(entry.segment, entry.batch, entry.lodRanges);
381
+ if (this.#gpuScene.on) entry.gpu = this.placeSources(job, entry);
382
+ if (entry.caster !== undefined)
383
+ entry.caster.write(entry.casterSegment, entry.batch, entry.lodRanges);
384
+ // The wide half draws the whole-asset impostor at the placement root when this entry kept one,
385
+ // and the source part shape otherwise; see `ICellBatch.wideRoot`.
386
+ if (entry.wide !== undefined)
387
+ entry.wide.write(entry.wideSegment, entry.wideRoot ?? entry.batch, entry.lodRanges);
388
+ }
389
+ // A batch the walk just wrote to, cleared or compacted holds new records, so the shadow levels
390
+ // that drew the old ones are stale. One flag, told at most once a second.
391
+ this.publishGpuGates(job.asset);
392
+ // A refilter tells the shadow levels only the placements that entered or left this cell's run,
393
+ // each with its own box. A placement that only changed level moved no caster: past `castLevels`
394
+ // a tree keeps casting in the coarsest casting shape (`castLevelOf`). The batch union this told
395
+ // before is the cell, which covers the finest level's whole window, so a walk through the forest
396
+ // redrew whole clip levels for a bush crossing its cull distance 60 m away.
397
+ const before = job.cell.placed?.get(job.run);
398
+ const after = job.placed ?? [];
399
+ job.cell.placed ??= new Map();
400
+ job.cell.placed.set(job.run, after);
401
+ // A first build has no list before it, so every placement it kept is an admission.
402
+ if (!job.replacement || before !== undefined) this.tellPlacementChanges(before ?? [], after);
403
+ else {
404
+ if (job.fresh.some((entry) => entry.batch.count > 0))
405
+ this.shadowRecordsMoved(this.changedBounds(job.fresh), true);
406
+ if (job.replaced.some((entry) => entry.batch.count > 0))
407
+ this.shadowRecordsMoved(this.changedBounds(job.replaced));
408
+ }
409
+ // This run's near representation is attached, so the far mesh stops drawing its original roots in
410
+ // the same synchronous block: a cell is never drawn by both and never by neither. A no-op until
411
+ // the asset's atlas lands; see `#syncFarSegments` for the build-time half and `#restoreFar`.
412
+ this.#host.disableFar(job.run);
413
+ return true;
414
+ }
415
+
416
+ /** Tell each placement in only one of two `PLACED_STRIDE` lists, as an admission when it entered. */
417
+ tellPlacementChanges(before: readonly number[], after: readonly number[]): void {
418
+ const gone = new Map<number, number>();
419
+ for (let at = 0; at < before.length; at += PLACED_STRIDE) gone.set(before[at] as number, at);
420
+ const box = this.#placedBox;
421
+ const tell = (list: readonly number[], at: number, admission: boolean): void => {
422
+ box.min.set(list[at + 1] as number, list[at + 2] as number, list[at + 3] as number);
423
+ box.max.set(list[at + 4] as number, list[at + 5] as number, list[at + 6] as number);
424
+ this.shadowRecordsMoved(box, admission);
425
+ };
426
+ for (let at = 0; at < after.length; at += PLACED_STRIDE)
427
+ if (!gone.delete(after[at] as number)) tell(after, at, true);
428
+ for (const at of gone.values()) tell(before, at, false);
429
+ }
430
+ readonly #placedBox = new Box3();
431
+
432
+ /**
433
+ * The world bounds of these records. A missing bound keeps the tell a blanket one.
434
+ */
435
+ changedBounds(batches: readonly ICellBatch[]): Box3 | undefined {
436
+ let union: Box3 | undefined;
437
+ for (const entry of batches) {
438
+ if (entry.batch.count === 0) continue;
439
+ const box = entry.shadowBounds;
440
+ if (
441
+ box === undefined ||
442
+ box.isEmpty() ||
443
+ ![...box.min.toArray(), ...box.max.toArray()].every(Number.isFinite)
444
+ )
445
+ return undefined;
446
+ if (union === undefined) union = box.clone();
447
+ else union.union(box);
448
+ }
449
+ return union;
450
+ }
451
+
452
+ /**
453
+ * One cell's records changed, so the shadow levels that cover it redraw — at most once a second,
454
+ * and only for a game that passed the hook. The levels cull clusters themselves now, so nothing
455
+ * has to be copied for them; the flag only says "what you last drew is out of date".
456
+ *
457
+ * `bounds` is the records that changed and is kept until the tell, unioned only with the boxes
458
+ * of the same second that it overlaps. A change with no bounds is a blanket one: it has to be, because
459
+ * there is nothing narrower to say.
460
+ */
461
+ shadowRecordsMoved(bounds?: Box3, admission = false): void {
462
+ this.#shadowMoved = true;
463
+ if (
464
+ bounds === undefined ||
465
+ bounds.isEmpty() ||
466
+ ![bounds.min.x, bounds.min.y, bounds.min.z, bounds.max.x, bounds.max.y, bounds.max.z].every(
467
+ Number.isFinite,
468
+ )
469
+ ) {
470
+ this.#shadowFull = true;
471
+ return;
472
+ }
473
+ const regions = admission ? this.#shadowAdmissions : this.#shadowRegions;
474
+ // Boxes stay apart unless they overlap: one union of a bush 60 m north and a tree 150 m south
475
+ // covers the ground under the camera, and every clip level redrew whole for it. Past the cap the
476
+ // region whose ground grows least takes the box, which only widens a redraw and never drops one.
477
+ let into = regions.find(
478
+ (region) =>
479
+ region.min.x <= bounds.max.x &&
480
+ region.max.x >= bounds.min.x &&
481
+ region.min.y <= bounds.max.y &&
482
+ region.max.y >= bounds.min.y &&
483
+ region.min.z <= bounds.max.z &&
484
+ region.max.z >= bounds.min.z,
485
+ );
486
+ if (into === undefined && regions.length >= SHADOW_REGION_CAP) {
487
+ let least = Number.POSITIVE_INFINITY;
488
+ for (const region of regions) {
489
+ const growth =
490
+ (Math.max(region.max.x, bounds.max.x) - Math.min(region.min.x, bounds.min.x)) *
491
+ (Math.max(region.max.z, bounds.max.z) - Math.min(region.min.z, bounds.min.z)) -
492
+ (region.max.x - region.min.x) * (region.max.z - region.min.z);
493
+ if (growth < least) [least, into] = [growth, region];
494
+ }
495
+ }
496
+ if (into === undefined) {
497
+ regions.push({
498
+ ...(admission ? { admission: true } : {}),
499
+ max: { x: bounds.max.x, y: bounds.max.y, z: bounds.max.z },
500
+ min: { x: bounds.min.x, y: bounds.min.y, z: bounds.min.z },
501
+ });
502
+ return;
503
+ }
504
+ into.min.x = Math.min(into.min.x, bounds.min.x);
505
+ into.min.y = Math.min(into.min.y, bounds.min.y);
506
+ into.min.z = Math.min(into.min.z, bounds.min.z);
507
+ into.max.x = Math.max(into.max.x, bounds.max.x);
508
+ into.max.y = Math.max(into.max.y, bounds.max.y);
509
+ into.max.z = Math.max(into.max.z, bounds.max.z);
510
+ }
511
+
512
+ /**
513
+ * Tell the shadow levels one call per kept region; covered loading drains without the walk throttle.
514
+ *
515
+ * The companions used to make this the expensive call it still is; the levels redraw from
516
+ * scratch, so the cadence is the only lever and once a second is the one that keeps a walk's
517
+ * frames off the shadow lane without leaving the ground stale behind a player. The region is
518
+ * what the changed records' own bounds add: a hook that forwards it redraws the levels whose
519
+ * window covers them, which for a streaming world is usually the finest one alone.
520
+ */
521
+ tellShadows(covered = false): void {
522
+ if (!this.#shadowMoved) return;
523
+ // No hook means there is no level to tell, so the flag is discharged here. Leaving it set made
524
+ // `#residencyStale` true forever, and every update ran a full residency pass on a world that had
525
+ // nothing left to do.
526
+ if (this.#invalidateShadows === undefined) {
527
+ this.#shadowMoved = false;
528
+ this.#shadowRegions.length = 0;
529
+ this.#shadowAdmissions.length = 0;
530
+ this.#shadowFull = false;
531
+ return;
532
+ }
533
+ const now = this.#host.now();
534
+ if (!covered && now - this.#shadowToldAt < 1e3) return;
535
+ this.#shadowToldAt = now;
536
+ this.#shadowMoved = false;
537
+ const regions = this.#shadowRegions.splice(0);
538
+ const admissions = this.#shadowAdmissions.splice(0);
539
+ const full = this.#shadowFull;
540
+ this.#shadowFull = false;
541
+ if (full || regions.length + admissions.length === 0) this.#invalidateShadows();
542
+ else for (const region of [...regions, ...admissions]) this.#invalidateShadows(region);
543
+ }
544
+
545
+ resetShadows(): void {
546
+ this.#shadowMoved = false;
547
+ this.#shadowRegions.length = 0;
548
+ this.#shadowAdmissions.length = 0;
549
+ this.#shadowFull = false;
550
+ }
551
+
552
+ /**
553
+ * Publish, on every caster half, whether the main pass will draw the records behind it this frame.
554
+ *
555
+ * A caster whose main counterpart is not drawable casts the shadow of nothing. With the GPU scene
556
+ * on, a dressed main mesh draws from the dispatch's own record, and a batch the scene holds no
557
+ * placement for submits that record and draws none of it — while the caster halves are plain CPU
558
+ * batches whose `#clustered` is false for every role but `main` (see the constructor), so they keep
559
+ * `#drawn`, the whole resident ring, and a shadow level submits all of it. `#seedGpuSources` is
560
+ * what puts the placements in, by queueing a rebuild of the ring behind the admission budget, so
561
+ * the hole lasts as long as that takes to drain and the picture shows canopy on empty ground for
562
+ * every frame of it.
563
+ *
564
+ * Per caster half, which is the granularity the ring is placed at and the only one that cannot draw
565
+ * a shadow for a source the dispatch has not been given: a `@x,z` cluster covers the cells of one
566
+ * world-grid square and a `@*` wide mesh every cell of its asset, so each compares its own placed
567
+ * count (`SharedBatch#gpuPlaced`, kept by `#placeSources` and `#clearSegment`) with its own live
568
+ * records. Per asset was one count too coarse and it showed: near cells of an asset are placed first,
569
+ * so a per-asset rule admitted every far cluster of that asset and its unplaced canopies drew
570
+ * shadows on empty ground — one capture in four showed dozens of them at the start pose.
571
+ *
572
+ * The direction is fail-closed, and the only price is a shadow that arrives with its trees: a half
573
+ * whose sources are still being placed casts nothing this frame, and casts once they are all there.
574
+ *
575
+ * Not the camera's frustum, which is the other narrowing and the wrong one: an off-screen caster
576
+ * the main pass has no reason to draw is the reason a shadow map exists.
577
+ */
578
+ publishCasterAdmission(): void {
579
+ // With the scene off there is no dress to wait for: a main batch draws from its own records and
580
+ // its own cull window, so every caster half is admitted whatever the camera is looking at. One
581
+ // comparison per half, no name work and no allocation: `live` is the records the main pass would
582
+ // have to be drawing for this half to cast at all.
583
+ const gpu = this.#gpuScene.on;
584
+ for (const shared of this.#shared.values()) {
585
+ if (shared.role === "main") continue;
586
+ shared.setMainAdmitted(gpu === false || shared.gpuPlaced >= shared.live);
587
+ }
588
+ }
589
+
590
+ /** The main pass's one mesh for an asset part at a level, covering every resident cell. */
591
+ sharedFor(assetId: string, entry: ICellBatch): SharedBatch | undefined {
592
+ return this.batchFor(assetId, entry, this.keyOf(entry), "main", this.#receiveShadow);
593
+ }
594
+
595
+ /**
596
+ * The shadow-caster cluster for one asset part at one level, or `undefined` when the level does
597
+ * not cast or the frame's fresh allowance is spent.
598
+ *
599
+ * One per `(key, cluster)`, on `VIRTUAL_SHADOW_CASTER_LAYER` and off the main camera, so a level
600
+ * culls the clusters its own window covers while the main pass keeps drawing one mesh per key.
601
+ */
602
+ casterFor(
603
+ assetId: string,
604
+ entry: ICellBatch,
605
+ cell: IResidentCell,
606
+ level = entry.level,
607
+ ): SharedBatch | undefined {
608
+ // A world whose shadow levels draw its keys mints no cluster: the two are the same placements by
609
+ // two routes, and a level's map can only draw one of them.
610
+ if (!this.casts(level) || this.keysForShadow()) return undefined;
611
+ return this.batchFor(
612
+ assetId,
613
+ entry,
614
+ `${this.keyOf(entry, level)}@${this.clusterOf(cell)}`,
615
+ "cluster",
616
+ false,
617
+ level,
618
+ );
619
+ }
620
+
621
+ /**
622
+ * The wide caster for one asset part at one level, or `undefined` when the level does not cast or
623
+ * the frame's fresh allowance is spent.
624
+ *
625
+ * One per key, holding every cell's records, on the wide caster layer: a level whose window
626
+ * covers the whole resident ring pays one draw for the key instead of one per square, and the fine
627
+ * levels that cull clusters never see this layer.
628
+ */
629
+ wideFor(assetId: string, entry: ICellBatch, level = entry.level): SharedBatch | undefined {
630
+ // As `#casterFor`: the key twin replaces both halves, so neither is minted.
631
+ if (!this.casts(level) || this.keysForShadow()) return undefined;
632
+ // A generated whole-asset impostor is one shape for every part and level, so its far shadow is
633
+ // ONE mesh per asset holding root records. Preserved authored parts keep per-key wide casters.
634
+ const impostor =
635
+ !this.#preserveAuthoredParts && this.#host.asset(assetId)?.impostor !== undefined;
636
+ const key = impostor
637
+ ? `${assetId}:*@${WIDE_CLUSTER}`
638
+ : `${this.keyOf(entry, level)}@${WIDE_CLUSTER}`;
639
+ return this.batchFor(assetId, entry, key, "wide", false, level);
640
+ }
641
+
642
+ /** `asset:level:part`, the main pass's one mesh per key. */
643
+ keyOf(entry: ICellBatch, level = entry.level): string {
644
+ return `${entry.asset}:${String(level)}:${String(entry.part)}`;
645
+ }
646
+
647
+ /**
648
+ * The shadow twin of one main key: a second mesh on the key layer, over the shadow twin of the
649
+ * dispatch's output, so a level's map submits one indirect draw for this key instead of one per
650
+ * world-grid square the two caster halves split it into.
651
+ *
652
+ * Its records are never written — the twin buffers are the dispatch's, and this mesh's count is
653
+ * its region's capacity — so it holds no instance buffer of its own and is minted at one slot.
654
+ * Minted for the levels that cast, which is what the caster halves did and what the CPU path
655
+ * already meant: a placement the dispatch routes to a level with no mesh casts nothing here,
656
+ * exactly as it casts nothing from a caster half nobody minted.
657
+ */
658
+ shadowKeyFor(key: IKeyDescriptor, part: IAssetPart): void {
659
+ // Registered here rather than at construction, because it is a question about keys that exist:
660
+ // a level's dispatch asks the provider for the keys a map draws, and the answer is this world's.
661
+ // Without a provider the scene registers nothing, which is what keeps the flag from minting
662
+ // anything at all; see `shadowGpuKeysRequested`.
663
+ this.#gpuScene.shadowKeysFrom(() => this.#shadowKeyNames);
664
+ if (this.keysForShadow() === false || this.casts(key.level) === false) return;
665
+ const name = `${key.key}${GPU_KEY_SUFFIX}`;
666
+ this.#shadowKeyNames.add(key.key);
667
+ let shared = this.#shared.get(name);
668
+ if (shared === undefined) {
669
+ // A released twin keeps its uuid and the node three built for it, for the same reason a
670
+ // caster half's does: rebinding is cheaper than a fresh mesh, and a fresh mesh is a fresh
671
+ // node build inside a shadow pass.
672
+ const released = this.#retired.get(name);
673
+ if (released !== undefined) {
674
+ this.#retired.delete(name);
675
+ this.#retiredBytes -= heldBytes(released);
676
+ shared = released;
677
+ } else {
678
+ // A fresh mesh is charged against the frame's allowance like any other; the walk that runs
679
+ // out of it comes back for this key rather than paying its build inside a shadow render.
680
+ if (this.#freshThisUpdate >= this.freshAllowance()) return;
681
+ this.#freshThisUpdate += 1;
682
+ shared = new SharedBatch(
683
+ part.geometry,
684
+ part.material,
685
+ 1,
686
+ 1,
687
+ name,
688
+ this.#extentBounds,
689
+ "key",
690
+ key.level,
691
+ );
692
+ }
693
+ shared.rebind(part.geometry, part.material);
694
+ shared.mesh.name = name;
695
+ this.dressMesh(shared, false);
696
+ this.#shared.set(name, shared);
697
+ this.attach(shared);
698
+ // Owed a draw, and shown because it is empty: a key is submitted by a shadow level, so the
699
+ // build behind the gate is the prewarm's whole job. Only while the gate is still open — a key
700
+ // streamed in afterwards owes nothing, exactly as a streamed caster half does not.
701
+ if (this.#host.prewarmSettled() === false) this.#host.awaitDraw(shared);
702
+ }
703
+ this.dressShadowKey(shared, key.key);
704
+ }
705
+
706
+ /**
707
+ * Point a shadow key's mesh at the twins, with the same shape and the same reasons as
708
+ * {@link #dressGpu}: the mesh's `instanceMatrix` becomes the scene's twin compaction buffer, its
709
+ * geometry a view carrying this key's twin record over the same attributes, and its whole-mesh
710
+ * frustum test off, because the dispatch tested every instance and the mesh's own bounds are the
711
+ * resident ring. Idempotent, so a settled walk reads one comparison — and so a regrown twin, which
712
+ * is a new attribute and a new pipeline like the main pass's, is re-dressed rather than left
713
+ * pointing at the buffer the dispatch replaced.
714
+ */
715
+ dressShadowKey(shared: SharedBatch, key: string): void {
716
+ const scene = this.#gpuScene;
717
+ // The twin record has to exist before a mesh can be dressed against it: a record minted inside
718
+ // the render it would draw in is one render late for every key. Idempotent, and a no-op without
719
+ // a provider.
720
+ scene.shadowKey(key);
721
+ const region = scene.shadowRegionOf(key);
722
+ const drawn = scene.shadowDrawn;
723
+ const args = scene.shadowArgs;
724
+ const geometry = shared.mesh.geometry;
725
+ if (
726
+ drawn !== undefined &&
727
+ shared.mesh.instanceMatrix === drawn &&
728
+ shared.mesh.frustumCulled === false &&
729
+ shared.gpuCount === region?.capacity &&
730
+ geometry.indirect === args &&
731
+ geometry.indirectOffset === (region?.argsIndex ?? -1) * DRAW_ARGS_BYTES
732
+ )
733
+ return;
734
+ if (region === undefined || drawn === undefined || args === undefined) return;
735
+ // The submission bound: three skips an `InstancedMesh` at count 0 before the GPU reads the
736
+ // record, so a key with no instances of its own is submitted at its region's capacity and the
737
+ // record decides. See `gpuCount`.
738
+ shared.gpuCount = region.capacity;
739
+ const mesh = shared.mesh;
740
+ const view = indirectView(geometry, args, region.argsIndex * DRAW_ARGS_BYTES);
741
+ // A fresh object for the same reason the main pass needs one: three binds the `instanceMatrix`
742
+ // an object held when its node was built and keeps that binding for the object's whole life.
743
+ if (mesh.instanceMatrix !== drawn) {
744
+ const next = freshMeshFor(mesh, view, mesh.count) as ICasterScaleMesh;
745
+ redressMaterial(next);
746
+ this.#host.carryPrewarm(mesh, next);
747
+ this.seat(shared.replaceMesh(next), next);
748
+ next.instanceMatrix = drawn;
749
+ next.frustumCulled = false;
750
+ } else {
751
+ mesh.geometry = view;
752
+ mesh.instanceMatrix = drawn;
753
+ mesh.frustumCulled = false;
754
+ }
755
+ // Shown and submitted whatever the records say: a key's own count is its region's capacity, and
756
+ // the twin record inside is what decides how many instances this map draws of it. See
757
+ // `SharedBatch#publish`. Never bundled — a bundle's record is fixed when it is recorded and only
758
+ // the main pass's draws are replayed from it, so a shadow key in the group would be drawn by the
759
+ // main camera's replay from the wrong buffer. See `#attach`.
760
+ mesh.count = shared.gpuCount;
761
+ mesh.visible = true;
762
+ }
763
+
764
+ /** The `@x,z` half of a caster cluster key, for a resident cell. */
765
+ clusterOf(cell: IResidentCell): string {
766
+ return clusterOf(cell.x, cell.z, this.#cellsPerCluster);
767
+ }
768
+
769
+ /**
770
+ * The `@x,z` half of the main cull's own visibility-cell key, for a resident cell. This is what a
771
+ * main batch's blocks are grouped by and what `#cullMainPass` tests, so it is the granularity the
772
+ * main pass is culled at; the caster clusters above are the shadow levels' and are left alone.
773
+ */
774
+ cullCellOf(cell: IResidentCell): string {
775
+ return clusterOf(cell.x, cell.z, this.#cellsPerCullCell);
776
+ }
777
+
778
+ /**
779
+ * The shared batch for one key, created (a new mesh: counted against the frame's fresh allowance)
780
+ * the first time any cell draws it. `undefined` means the allowance is spent and the caller waits
781
+ * a frame. A caster batch carries the shadow flags and the caster layer; a main batch casts
782
+ * nothing, because its records reach the shadow maps through the caster cluster.
783
+ *
784
+ * The buffer starts with a block per cell that can hold this key, plus the one a refilter holds
785
+ * alongside the blocks it replaces — the cluster's own cells for a caster cluster, the whole ring
786
+ * for the main pass's one mesh per key — not the eight it used to start with. Sizing a main batch
787
+ * by its cluster's cells left it with two blocks for a ring of dozens, so a walk filled the
788
+ * buffer, `grow` minted a fresh mesh — a uuid three had never built a node for, in every shadow
789
+ * pass too — and put the old one in an array nothing ever read. Those two sizes are ceilings, so
790
+ * this is what stops growing. Cost: a main buffer is ring-sized for assets that never fill it;
791
+ * give `residentCells` a smaller value if that outweighs a re-mint.
792
+ */
793
+ batchFor(
794
+ assetId: string,
795
+ entry: ICellBatch,
796
+ key: string,
797
+ role: "cluster" | "key" | "main" | "wide",
798
+ receiveShadow: boolean,
799
+ level = entry.level,
800
+ ): SharedBatch | undefined {
801
+ const existing = this.#shared.get(key);
802
+ if (existing !== undefined && this.#lodHysteresis === 0) return existing;
803
+ const shape = this.shapeFor(entry, role, level);
804
+ if (existing !== undefined) {
805
+ const rebind =
806
+ shape.material.userData.tnPublishedLodRange === true &&
807
+ existing.mesh.geometry.getAttribute("tnPublishedLodRange") === undefined &&
808
+ existing.mesh.count === 0;
809
+ // The same surface on the same buffer: re-recording it on every call re-walked its whole node
810
+ // graph each time a cell asked for the key (3 s of a 25 s Strata trace). The cached check still
811
+ // re-reads the material's shallow state and hooks, and re-records only when its verdict moved.
812
+ if (!rebind && existing.mesh.material === shape.material) {
813
+ this.bundleIn(existing, true);
814
+ return existing;
815
+ }
816
+ if (rebind) existing.rebind(shape.geometry, shape.material);
817
+ else existing.surface(shape.material);
818
+ this.bundleOut(existing);
819
+ this.bundleIn(existing);
820
+ return existing;
821
+ }
822
+ const smallCaster = this.smallCaster(assetId);
823
+ // The batch released when this asset's last cell left the ring is the one to draw into again,
824
+ // so the mesh keeps the uuid and the node three built for it. It costs no fresh allowance,
825
+ // because it is not a fresh mesh.
826
+ const released = this.#retired.get(key);
827
+ if (released !== undefined) {
828
+ this.#retired.delete(key);
829
+ this.#retiredBytes -= heldBytes(released);
830
+ released.rebind(shape.geometry, shape.material);
831
+ released.mesh.name = key;
832
+ released.smallCaster = smallCaster;
833
+ this.dressMesh(released, receiveShadow);
834
+ // A rebind swaps the geometry and may swap the buffer, so the key is dressed again: the indirect
835
+ // record and the shared matrix buffer belong to the mesh, not to the batch.
836
+ this.adoptGpu(released, entry.asset, key, level, entry.part);
837
+ this.#shared.set(key, released);
838
+ this.attach(released);
839
+ return released;
840
+ }
841
+ if (this.#freshThisUpdate >= this.freshAllowance()) return undefined;
842
+ this.#freshThisUpdate += 1;
843
+ const shared = new SharedBatch(
844
+ shape.geometry,
845
+ shape.material,
846
+ this.#host.runMax(assetId) ?? entry.batch.count,
847
+ // A caster cluster's block count is bounded by the cluster's own cells; a wide caster and the
848
+ // main pass's one mesh per key are both bounded by the whole ring, so either way the one a
849
+ // refilter holds beside the block it replaces.
850
+ role === "cluster"
851
+ ? this.#cellsPerCluster * this.#cellsPerCluster + 1
852
+ : this.#budgets.residentCells + 1,
853
+ key,
854
+ this.#extentBounds,
855
+ role,
856
+ level,
857
+ );
858
+ shared.smallCaster = smallCaster;
859
+ this.dressMesh(shared, receiveShadow);
860
+ this.adoptGpu(shared, entry.asset, key, level, entry.part);
861
+ this.#shared.set(key, shared);
862
+ this.attach(shared);
863
+ return shared;
864
+ }
865
+
866
+ /**
867
+ * The source records one swapped-in entry draws from: one per placement, not per part, because the
868
+ * part's own offset is the key's and the dispatch composes it. Every part of the level shares the
869
+ * list, which is why releasing one is idempotent and a whole level's records are handed back by the
870
+ * first of its entries that leaves.
871
+ */
872
+ placeSources(job: IBuildJob, entry: ICellBatch): number[] | undefined {
873
+ const sources = job.sources;
874
+ if (sources === undefined) return undefined;
875
+ const asset = this.#host.asset(entry.asset);
876
+ if (asset === undefined) return undefined;
877
+ const slot = this.#gpuScene.slot(entry.asset, this.gatesOf(entry.asset, asset));
878
+ if (slot < 0) return undefined;
879
+ const byLevel = job.gpuByLevel ?? new Map<number, number[]>();
880
+ job.gpuByLevel = byLevel;
881
+ const held = byLevel.get(entry.level);
882
+ // A sibling part of this level shares the list already placed, and counts its own halves for
883
+ // itself: `#gpuResident` is the asset's, so this half's records are counted here.
884
+ if (held !== undefined) {
885
+ this.countPlaced(entry, held.length);
886
+ return held;
887
+ }
888
+ const records: number[] = [];
889
+ for (const source of sources)
890
+ if (source.level === entry.level) {
891
+ const at = this.#gpuScene.place(
892
+ slot,
893
+ source.matrix,
894
+ source.x,
895
+ source.y,
896
+ source.z,
897
+ source.radius,
898
+ source.scale,
899
+ );
900
+ if (at >= 0) records.push(at);
901
+ }
902
+ byLevel.set(entry.level, records);
903
+ // What a key of this asset has to be able to hold, on any level: see `#dressGpu`.
904
+ this.#gpuResident.set(entry.asset, (this.#gpuResident.get(entry.asset) ?? 0) + records.length);
905
+ this.countPlaced(entry, records.length);
906
+ return records;
907
+ }
908
+
909
+ /**
910
+ * The placed sources one cell's block contributed, carried onto the two caster halves behind it —
911
+ * `gpuPlaced`, the count `#publishCasterAdmission` measures a half against its own live records.
912
+ *
913
+ * One place for both halves and both directions, because `#gpuResident` counts the asset once and a
914
+ * half counts only what its own block contributed: every part of a level shares one list of placed
915
+ * sources and each half needs its own answer. Negative is the release path's way back down.
916
+ */
917
+ countPlaced(entry: ICellBatch, placed: number): void {
918
+ if (entry.caster !== undefined) entry.caster.gpuPlaced += placed;
919
+ if (entry.wide !== undefined) entry.wide.gpuPlaced += placed;
920
+ }
921
+
922
+ /** The world-grid square the follow point is in, as the `@x,z` half of a cluster key. */
923
+ followCluster(): string {
924
+ return squareOf(this.#follow, this.#minX, this.#minZ, this.#cellSize, this.#cellsPerCluster);
925
+ }
926
+
927
+ /**
928
+ * Keeps a released batch for the walk back, or drops it.
929
+ *
930
+ * Empty is the precondition, and `#evict` guarantees it: it clears a cell's own block before the
931
+ * refcount falls, and the refcount is what calls this. A batch that still holds records means the
932
+ * buffer state cannot be trusted, so it goes the same way as one over the byte budget.
933
+ */
934
+ retire(key: string, shared: SharedBatch): void {
935
+ // Live records, not the draw window: a main batch whose squares are all behind the camera still
936
+ // holds its records, and that is not a batch to dispose.
937
+ if (shared.live > 0) {
938
+ shared.mesh.dispose();
939
+ return;
940
+ }
941
+ // Parked before the budget is measured, or the retained set is charged for buffers nothing keeps
942
+ // and the byte budget evicts entries as they arrive — the walk then finds nothing to hand back
943
+ // and mints a second mesh for every key it returns to.
944
+ shared.park();
945
+ const bytes = heldBytes(shared);
946
+ this.#retired.delete(key);
947
+ this.#retired.set(key, shared);
948
+ this.#retiredBytes += bytes;
949
+ for (const [oldest, held] of this.#retired) {
950
+ if (this.#retiredBytes <= RETIRED_SHARED_BYTES) break;
951
+ this.#retired.delete(oldest);
952
+ this.#retiredBytes -= heldBytes(held);
953
+ held.mesh.dispose();
954
+ }
955
+ }
956
+
957
+ /**
958
+ * A block in `shared` for one cell's `count` records, growing the buffer when it is full. `cluster`
959
+ * is the world-grid square the cell sits in, and only a main batch keeps it: its draw window is
960
+ * narrowed per square, and a square is a grouping, not a position.
961
+ */
962
+ segmentIn(shared: SharedBatch, count: number, cluster?: string): number | undefined {
963
+ const segment = shared.allocate(count, cluster);
964
+ if (segment !== undefined) return segment;
965
+ // A dressed batch's grow is logical: it raises the ceiling the GPU scene sizes this key's region
966
+ // from and mints no mesh, so the fresh-mesh allowance — which bounds new pooled meshes and their
967
+ // node builds — does not gate it. A CPU grow is a real replacement mesh and still respects it.
968
+ if (shared.gpu === undefined && this.#freshThisUpdate >= this.freshAllowance())
969
+ return undefined;
970
+ const old = shared.grow();
971
+ // Only a real replacement is a new object to dress, attach and hand to the pool; a logical GPU
972
+ // grow keeps the live mesh, which `#dressGpu` re-points at the grown region before the draw.
973
+ if (old !== undefined) {
974
+ this.#freshThisUpdate += 1;
975
+ // The replacement is a different object, so the layer and the cull hook `grow` copied neither of
976
+ // have to be dressed onto it again — a grown caster that kept layer 0 would be drawn by the main
977
+ // camera and lost to the shadow level, and a grown main batch would stop narrowing at all.
978
+ this.dressMesh(shared, shared.role === "main" && this.#receiveShadow);
979
+ this.attach(shared);
980
+ // The mesh this grow replaced goes back to the pool: a cached shadow level can still replay a
981
+ // draw of it until its window next moves, and the pool keeps the buffer and the uuid rather
982
+ // than letting one array of retired meshes grow without bound.
983
+ parkMesh(old);
984
+ }
985
+ return shared.allocate(count, cluster);
986
+ }
987
+
988
+ /**
989
+ * Move this asset's already-built wide casters into the one whole-asset mesh, with root records.
990
+ *
991
+ * Before the bake landed the far shadow held one wide mesh per (level, part 0), each carrying
992
+ * `placement * part 0 local` for its own level's placements. The whole-asset representation is one
993
+ * root draw per placement, so every one of those segments is dropped and re-claimed from the root
994
+ * records the builds kept (`ICellBatch.wideRoot`) in the single mesh `#wideFor` now names. When a
995
+ * block cannot be taken in this update's fresh-mesh allowance the asset is retried next frame; the
996
+ * old per-level meshes, empty by then, are retired so the far shadow stops submitting them.
997
+ */
998
+ retargetWideCasters(asset: IAssetState): void {
999
+ const impostor = asset.impostor;
1000
+ if (impostor === undefined) return;
1001
+ const globalKey = `${asset.id}:*@${WIDE_CLUSTER}`;
1002
+ for (const cell of this.#host.residentCells())
1003
+ for (const entry of cell.batches) {
1004
+ if (entry.asset !== asset.id) continue;
1005
+ if (entry.wide !== undefined && entry.wide.mesh.name === globalKey) continue;
1006
+ // The old segment's shape and its doubled part offset are both wrong now; hand it back. Its
1007
+ // placed count goes with the records, so the mesh left behind does not read as fully placed
1008
+ // and the global one does not read as unplaced: see `SharedBatch#gpuPlaced`.
1009
+ const placed = entry.gpu?.length ?? 0;
1010
+ if (entry.wide !== undefined && entry.wideSegment >= 0) {
1011
+ entry.wide.gpuPlaced -= placed;
1012
+ entry.wide.clear(entry.wideSegment);
1013
+ }
1014
+ entry.wide = undefined;
1015
+ entry.wideSegment = -1;
1016
+ if (!this.casts(entry.level) || !this.wideOwed(asset.id, entry.part)) continue;
1017
+ const source = entry.wideRoot;
1018
+ if (source === undefined) continue;
1019
+ const wide = this.batchFor(asset.id, entry, globalKey, "wide", false);
1020
+ const at = wide === undefined ? undefined : this.segmentIn(wide, source.count);
1021
+ if (wide === undefined || at === undefined) {
1022
+ this.#host.deferWide(asset.id);
1023
+ continue;
1024
+ }
1025
+ entry.wide = wide;
1026
+ entry.wideSegment = at;
1027
+ wide.gpuPlaced += placed;
1028
+ wide.write(at, source);
1029
+ }
1030
+ this.retireWideKeys(asset.id, globalKey);
1031
+ }
1032
+
1033
+ /** Give the asset's pre-bake per-key wide meshes back, once the handoff has emptied them. */
1034
+ retireWideKeys(assetId: string, keep: string): void {
1035
+ const prefix = `${assetId}:`;
1036
+ for (const [key, shared] of [...this.#shared]) {
1037
+ if (key === keep || shared.role !== "wide" || !key.startsWith(prefix)) continue;
1038
+ if (shared.live > 0) continue;
1039
+ shared.mesh.removeFromParent();
1040
+ this.bundleOut(shared);
1041
+ this.#shared.delete(key);
1042
+ this.retire(key, shared);
1043
+ }
1044
+ }
1045
+
1046
+ /** Releases the shared meshes of one asset (or of every asset), keeping them for the walk back. */
1047
+ drainShared(assetId?: string): number {
1048
+ const failed = 0;
1049
+ for (const [key, shared] of this.#shared) {
1050
+ if (assetId !== undefined && !key.startsWith(`${assetId}:`)) continue;
1051
+ shared.mesh.removeFromParent();
1052
+ // The mesh is out of the world, so it is out of the bundle the world recorded. A key that comes
1053
+ // back is minted or rebound into the group again, and each of those is one re-record.
1054
+ this.bundleOut(shared);
1055
+ this.#shared.delete(key);
1056
+ // Retired, not dropped, so the cell that comes back draws into the same mesh.
1057
+ this.retire(key, shared);
1058
+ }
1059
+ return failed;
1060
+ }
1061
+ readonly #follow: IWorldCellsFollow;
1062
+ readonly #host: ICellRenderHost;
1063
+ constructor(settings: ICellRenderSettings, host: ICellRenderHost) {
1064
+ this.#host = host;
1065
+ this.#follow = settings.follow;
1066
+ this.#budgets = settings.budgets;
1067
+ this.#cellSize = settings.cellSize;
1068
+ this.#minX = settings.minX;
1069
+ this.#minZ = settings.minZ;
1070
+ this.#manifest = settings.manifest;
1071
+ this.#placements = settings.placements;
1072
+ this.#coveredFreshMeshesPerUpdate = settings.coveredFreshMeshesPerUpdate;
1073
+ this.#freshMeshesPerUpdate = settings.freshMeshesPerUpdate;
1074
+ this.#receiveShadow = settings.receiveShadow;
1075
+ this.#castShadowLevels = settings.castShadowLevels;
1076
+ this.#shadowMinLevel = settings.shadowMinLevel;
1077
+ this.#extentBounds = settings.extentBounds;
1078
+ this.#preserveAuthoredParts = settings.preserveAuthoredParts;
1079
+ this.#lodHysteresis = settings.lodHysteresis;
1080
+ this.#lodTransition = settings.lodTransition;
1081
+ this.#lodSpatial = settings.lodSpatial;
1082
+ this.#cellsPerCluster = settings.cellsPerCluster;
1083
+ this.#cellsPerCullCell = settings.cellsPerCullCell;
1084
+ this.#smallCasterMetres = settings.smallCasterMetres;
1085
+ this.#invalidateShadows = settings.invalidateShadows;
1086
+ this.#dress = new CellGpuDress({
1087
+ add: (object) => this.#host.add(object),
1088
+ asset: (id) => this.#host.asset(id),
1089
+ attach: (shared) => this.attach(shared),
1090
+ bumpBundle: (group) => this.bumpBundle(group),
1091
+ bundleIn: (shared, reuseSafety) => this.bundleIn(shared, reuseSafety),
1092
+ bundleOut: (shared) => this.bundleOut(shared),
1093
+ camera: () => this.#host.camera(),
1094
+ canonical: (id) => this.#host.canonical(id),
1095
+ carryPrewarm: (old, next) => this.#host.carryPrewarm(old, next),
1096
+ extentBounds: () => this.#extentBounds,
1097
+ freshAllowance: () => this.freshAllowance(),
1098
+ freshCount: () => this.#freshThisUpdate,
1099
+ gpuScene: () => this.#gpuScene,
1100
+ isBundleHome: (shared) => this.#host.isBundleHome(shared),
1101
+ lodDistanceBias: () => this.#lodDistanceBias,
1102
+ lodHysteresis: () => this.#lodHysteresis,
1103
+ lodMaterials: () => this.#lodMaterials,
1104
+ lodSpatial: () => this.#lodSpatial,
1105
+ lodTransition: () => this.#lodTransition,
1106
+ preserveAuthoredParts: () => this.#preserveAuthoredParts,
1107
+ receiveShadow: () => this.#receiveShadow,
1108
+ renderer: () => this.#host.renderer(),
1109
+ resident: () => this.#gpuResident,
1110
+ retired: () => this.#retired,
1111
+ shadowFloorOf: (assetId) => this.shadowFloorOf(assetId),
1112
+ shadowKeyFor: (key, part) => this.shadowKeyFor(key, part),
1113
+ shared: () => this.#shared,
1114
+ shardOf: (shared) => this.shardOf(shared),
1115
+ visibleSquares: () => this.visibleSquares(),
1116
+ });
1117
+ this.#cull = new CellMainCull(
1118
+ {
1119
+ cellSize: this.#cellSize,
1120
+ cellsPerCullCell: this.#cellsPerCullCell,
1121
+ mainCullToldAt: settings.mainCullToldAt,
1122
+ manifest: this.#manifest,
1123
+ minX: this.#minX,
1124
+ minZ: this.#minZ,
1125
+ placements: this.#placements,
1126
+ },
1127
+ {
1128
+ applyGpuMain: (dressed) => this.applyGpuMain(dressed),
1129
+ beginBundleFrame: () => this.beginBundleFrame(),
1130
+ chunkGroups: () => this.#bundles.chunkGroups(),
1131
+ dressGpu: (shared, key) => this.dressGpu(shared, key),
1132
+ dressShadowKey: (shared, key) => this.dressShadowKey(shared, key),
1133
+ gpuScene: () => this.#gpuScene,
1134
+ gpuSeeded: () => this.#gpuSeeded,
1135
+ recordCpuMain: (shared, outcome) => this.recordCpuMain(shared, outcome),
1136
+ render: () => this.#host,
1137
+ shared: () => this.#shared,
1138
+ },
1139
+ );
1140
+ this.#bundles = new CellBundles(
1141
+ {
1142
+ bundleReason: settings.bundleReason,
1143
+ bundlesWanted: settings.bundlesWanted,
1144
+ cellsPerCullCell: settings.cellsPerCullCell,
1145
+ },
1146
+ {
1147
+ add: (object) => this.#host.add(object),
1148
+ isParent: (object) => this.#host.isParent(object),
1149
+ renderer: () => this.#host.renderer(),
1150
+ shared: () => this.#shared,
1151
+ },
1152
+ );
1153
+ }
1154
+
1155
+ // The record's own answers, named here because this class is the world's one surface: every caller
1156
+ // below asks the facade and never the bundle module.
1157
+
1158
+ bundleIn(shared: SharedBatch, reuseSafety = false): void {
1159
+ this.#bundles.bundleIn(shared, reuseSafety);
1160
+ }
1161
+
1162
+ bundleOut(shared: SharedBatch): void {
1163
+ this.#bundles.bundleOut(shared);
1164
+ }
1165
+
1166
+ ownsBundles(): boolean {
1167
+ return this.#bundles.ownsBundles();
1168
+ }
1169
+
1170
+ bumpBundle(group: BundleGroup): void {
1171
+ this.#bundles.bumpBundle(group);
1172
+ }
1173
+
1174
+ recordCpuMain(shared: SharedBatch, outcome: "settled" | "narrowed" | "repacked"): void {
1175
+ this.#bundles.recordCpuMain(shared, outcome);
1176
+ }
1177
+
1178
+ addChunk(cell: IResidentCell, chunk: Object3D): void {
1179
+ this.#bundles.addChunk(cell, chunk);
1180
+ }
1181
+
1182
+ dropChunkBundles(cell: IResidentCell): void {
1183
+ this.#bundles.dropChunkBundles(cell);
1184
+ }
1185
+
1186
+ shardOf(shared: SharedBatch): BundleGroup {
1187
+ return this.#bundles.shardOf(shared);
1188
+ }
1189
+
1190
+ mainBundleChildren(): number {
1191
+ return this.#bundles.mainBundleChildren();
1192
+ }
1193
+
1194
+ attach(shared: SharedBatch): void {
1195
+ this.#bundles.attach(shared);
1196
+ }
1197
+
1198
+ beginBundleFrame(): void {
1199
+ this.#bundles.beginFrame();
1200
+ }
1201
+
1202
+ invalidateBundles(key: string): void {
1203
+ this.#bundles.invalidateBundles(key);
1204
+ }
1205
+
1206
+ bundleStats(): IWorldCellsStats["bundle"] {
1207
+ return this.#bundles.bundleStats();
1208
+ }
1209
+
1210
+ flushCompiles(renderer: IRendererLike | undefined): void {
1211
+ this.#bundles.flushCompiles(renderer);
1212
+ }
1213
+
1214
+ clearCompileRecords(): void {
1215
+ this.#bundles.clearCompileRecords();
1216
+ }
1217
+
1218
+ /**
1219
+ * What the shadow claims need to see of this renderer: the batches they claim blocks in, the gate
1220
+ * table the caster shape comes from, and the scene that decides whether a level draws keys.
1221
+ */
1222
+ readonly #claimHost: IShadowClaimHost = {
1223
+ castShadowLevels: () => this.#castShadowLevels,
1224
+ casterFor: (assetId, entry, cell, level) => this.casterFor(assetId, entry, cell, level),
1225
+ countPlaced: (entry, placed) => this.countPlaced(entry, placed),
1226
+ freshCount: () => this.#freshThisUpdate,
1227
+ gpuScene: () => this.#gpuScene,
1228
+ manifest: () => this.#manifest,
1229
+ preserveAuthoredParts: () => this.#preserveAuthoredParts,
1230
+ render: () => this.#host,
1231
+ resident: () => this.#gpuResident,
1232
+ segmentIn: (shared, count, cluster) => this.segmentIn(shared, count, cluster),
1233
+ shadowMinLevel: () => this.#shadowMinLevel,
1234
+ smallCasterMetres: () => this.#smallCasterMetres,
1235
+ wideFor: (assetId, entry, level) => this.wideFor(assetId, entry, level),
1236
+ };
1237
+
1238
+ // The claim decisions, named here because this class is the world's one surface.
1239
+
1240
+ casts(level: number): boolean {
1241
+ return casts(this.#claimHost, level);
1242
+ }
1243
+
1244
+ smallCaster(assetId: string): boolean {
1245
+ return smallCaster(this.#claimHost, assetId);
1246
+ }
1247
+
1248
+ wideOwed(assetId: string, part: number): boolean {
1249
+ return wideOwed(this.#claimHost, assetId, part);
1250
+ }
1251
+
1252
+ castLevelOf(entry: ICellBatch): number | undefined {
1253
+ return castLevelOf(this.#claimHost, entry);
1254
+ }
1255
+
1256
+ shadowFloorOf(assetId: string): number {
1257
+ return shadowFloorOf(this.#claimHost, assetId);
1258
+ }
1259
+
1260
+ keysForShadow(): boolean {
1261
+ return keysForShadow(this.#claimHost);
1262
+ }
1263
+
1264
+ claimCaster(assetId: string, entry: ICellBatch, cell: IResidentCell): boolean {
1265
+ return claimCaster(this.#claimHost, assetId, entry, cell);
1266
+ }
1267
+
1268
+ claimWide(assetId: string, entry: ICellBatch): boolean {
1269
+ return claimWide(this.#claimHost, assetId, entry);
1270
+ }
1271
+
1272
+ clearSegment(entry: ICellBatch): void {
1273
+ clearSegment(this.#claimHost, entry);
1274
+ }
1275
+
1276
+ // The dress's own answers, named here because this class is the world's one surface.
1277
+
1278
+ adoptGpu(shared: SharedBatch, assetId: string, key: string, level: number, part: number): void {
1279
+ this.#dress.adoptGpu(shared, assetId, key, level, part);
1280
+ }
1281
+
1282
+ applyGpuMain(dressed: readonly { asset: string; shared: SharedBatch }[]): void {
1283
+ this.#dress.applyGpuMain(dressed);
1284
+ }
1285
+
1286
+ dressGpu(shared: SharedBatch, key: IKeyDescriptor): void {
1287
+ this.#dress.dressGpu(shared, key);
1288
+ }
1289
+
1290
+ dressMesh(shared: SharedBatch, receiveShadow: boolean): void {
1291
+ this.#dress.dressMesh(shared, receiveShadow);
1292
+ }
1293
+
1294
+ seat(old: InstancedMesh, next: InstancedMesh): void {
1295
+ this.#dress.seat(old, next);
1296
+ }
1297
+
1298
+ shapeFor(
1299
+ entry: ICellBatch,
1300
+ role: "cluster" | "key" | "main" | "wide",
1301
+ level?: number,
1302
+ ): IBatchShape {
1303
+ return this.#dress.shapeFor(entry, role, level);
1304
+ }
1305
+
1306
+ wideShape(
1307
+ asset: IAssetState | undefined,
1308
+ level: number,
1309
+ part: number,
1310
+ fallback: IBatchShape,
1311
+ ): IBatchShape {
1312
+ return this.#dress.wideShape(asset, level, part, fallback);
1313
+ }
1314
+
1315
+ updateLodEye(x: number, y: number, z: number): void {
1316
+ this.#dress.updateLodEye(x, y, z);
1317
+ }
1318
+
1319
+ refreshLodMaterials(asset: IAssetState): void {
1320
+ this.#dress.refreshLodMaterials(asset);
1321
+ }
1322
+
1323
+ impostorDrawn(): number {
1324
+ return this.#dress.impostorDrawn();
1325
+ }
1326
+
1327
+ publishGpuGates(asset: IAssetState): void {
1328
+ this.#dress.publishGpuGates(asset);
1329
+ }
1330
+
1331
+ gatesOf(id: string, asset: IAssetState): IAssetSlot {
1332
+ return this.#dress.gatesOf(id, asset);
1333
+ }
1334
+
1335
+ seedGpuKeys(): void {
1336
+ this.#dress.seedGpuKeys();
1337
+ }
1338
+
1339
+ seedGpuKey(shared: SharedBatch): void {
1340
+ this.#dress.seedGpuKey(shared);
1341
+ }
1342
+
1343
+ gpuCensus(): { readonly dressed: number; readonly meshes: number } {
1344
+ return this.#dress.gpuCensus();
1345
+ }
1346
+
1347
+ gpuDraws(): readonly IMeshDraw[] {
1348
+ return this.#dress.gpuDraws();
1349
+ }
1350
+
1351
+ liveGates(): Map<string, ILiveAsset> {
1352
+ return this.#dress.liveGates();
1353
+ }
1354
+
1355
+ // The main cull's own answers, named here because this class is the world's one surface.
1356
+
1357
+ cullMainPass(camera: Camera | undefined): void {
1358
+ this.#cull.cullMainPass(camera);
1359
+ }
1360
+
1361
+ cullResident(cell: IWorldCell): void {
1362
+ this.#cull.cullResident(cell);
1363
+ }
1364
+
1365
+ cullEvicted(cell: IResidentCell): void {
1366
+ this.#cull.cullEvicted(cell);
1367
+ }
1368
+
1369
+ reportMainCull(): void {
1370
+ this.#cull.reportMainCull();
1371
+ }
1372
+
1373
+ mainCullStats(): IWorldCellsStats["mainCull"] {
1374
+ return this.#cull.mainCullStats();
1375
+ }
1376
+
1377
+ /** The squares the last cull kept, at the epoch it kept them for. */
1378
+ visibleSquares(): Set<string> {
1379
+ return this.#cull.visible;
1380
+ }
1381
+
1382
+ get gpuOn(): boolean {
1383
+ return this.#gpuScene.on;
1384
+ }
1385
+ get shadowMoved(): boolean {
1386
+ return this.#shadowMoved;
1387
+ }
1388
+ get meshStalled(): boolean {
1389
+ return this.#meshStalled;
1390
+ }
1391
+ get gpuSeeded(): boolean {
1392
+ return this.#gpuSeeded;
1393
+ }
1394
+ set gpuSeeded(value: boolean) {
1395
+ this.#gpuSeeded = value;
1396
+ }
1397
+ get bundlesWanted(): boolean {
1398
+ return this.#bundles.wanted;
1399
+ }
1400
+ bundleGroup(shard: number): BundleGroup | undefined {
1401
+ return this.#bundles.bundleGroup(shard);
1402
+ }
1403
+ hasShared(key: string): boolean {
1404
+ return this.#shared.has(key);
1405
+ }
1406
+ hasRetired(key: string): boolean {
1407
+ return this.#retired.has(key);
1408
+ }
1409
+ setShared(key: string, shared: SharedBatch): void {
1410
+ this.#shared.set(key, shared);
1411
+ }
1412
+ intersectsObject(mesh: Object3D): boolean {
1413
+ return this.#cull.intersectsObject(mesh);
1414
+ }
1415
+ dispatchShadow(renderer: IRendererLike, level: IShadowLevel): void {
1416
+ this.#gpuScene.dispatchShadow(renderer, level);
1417
+ }
1418
+ setLodBias(bias: number): void {
1419
+ this.#lodDistanceBias.value = Number.isFinite(bias) && bias >= 1 ? bias : 1;
1420
+ this.#gpuScene.setLodBias(bias);
1421
+ }
1422
+ report(): ReturnType<WorldGpuScene["report"]> {
1423
+ return this.#gpuScene.report();
1424
+ }
1425
+ resetFresh(): void {
1426
+ this.#freshThisUpdate = 0;
1427
+ this.#meshStalled = false;
1428
+ }
1429
+ validateGpuFrame(renderer: IRendererLike, frame: number) {
1430
+ return this.#gpuScene.validateCurrentDispatch(renderer, frame);
1431
+ }
1432
+
1433
+ releaseGpu(): void {
1434
+ this.#gpuScene.dispose();
1435
+ this.#dress.release();
1436
+ this.#bundles.release();
1437
+ this.#gpuResident.clear();
1438
+ }
1439
+ releaseLodMaterials(): void {
1440
+ for (const { material } of this.#lodMaterials.values()) material.dispose();
1441
+ this.#lodMaterials.clear();
1442
+ }
1443
+ releaseRetired(): void {
1444
+ for (const shared of this.#retired.values()) shared.mesh.dispose();
1445
+ this.#retired.clear();
1446
+ this.#retiredBytes = 0;
1447
+ }
1448
+ publishChunkBounds(cell: IResidentCell, box: Box3 | undefined, proxies: number): void {
1449
+ if (box !== undefined) {
1450
+ if (proxies > 0) this.shadowRecordsMoved(box, true);
1451
+ // A bundled chunk is drawn or not by its cell's record, and that record is answered from
1452
+ // the cell's cull volume — which is built from the cell's placements. A chunk is a cell's
1453
+ // other half, so a cell holding chunks and no scatter would have an empty volume and never
1454
+ // be drawn at all. Widened here rather than shrunk on eviction: the volume outlives one cell
1455
+ // whenever a neighbour still holds the cluster, and a stale box only ever shows a cell that
1456
+ // is there.
1457
+ if (this.#bundles.wanted)
1458
+ this.#cull
1459
+ .cells()
1460
+ .get(clusterOf(cell.x, cell.z, this.#cellsPerCullCell))
1461
+ ?.box.union(box);
1462
+ }
1463
+ }
1464
+
1465
+ enableGpu(
1466
+ renderer: IRendererLike | undefined,
1467
+ wanted: boolean,
1468
+ validate: boolean | undefined,
1469
+ tally: boolean,
1470
+ occlusion: OcclusionMode,
1471
+ ): void {
1472
+ // The first frame that hands over a renderer is the only one that can answer whether this
1473
+ // backend can run the GPU scene, and it prints its answer once: `enable` reports, then returns
1474
+ // early for the rest of the world's life.
1475
+ if (renderer !== undefined)
1476
+ this.#gpuScene.enable(
1477
+ renderer,
1478
+ wanted,
1479
+ validate ?? gpuSceneValidationRequested(),
1480
+ tally,
1481
+ occlusion,
1482
+ );
1483
+ // The one check the scene cannot make for itself, and the only one that reads this class's own
1484
+ // numbers rather than the scene's tables: a dressed main mesh's own indirect record, against the
1485
+ // instances this path composes for the key that mesh is named. Registered before the keys are
1486
+ // seeded, because the first check is a whole ring's worth of meshes and every one of them is
1487
+ // already dressed by the time it runs.
1488
+ this.#gpuScene.drawsFrom(() => this.gpuDraws());
1489
+ }
1490
+ announceGpu(): void {
1491
+ this.#gpuScene.announce(this.#host.renderer() as IRendererLike, this.gpuCensus());
1492
+ }
1493
+ }