@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,1132 @@
1
+ import {
2
+ Box3,
3
+ type BufferGeometry,
4
+ type Camera,
5
+ InstancedMesh,
6
+ Material,
7
+ Matrix4,
8
+ Mesh,
9
+ Object3D,
10
+ } from "three";
11
+ import { markEngineRenderHook } from "./engine-render-hook.js";
12
+ import { mergeByMaterial } from "./merge-parts.js";
13
+ import {
14
+ conservativeViewDepth,
15
+ isLodJoinProxy,
16
+ lodChainOf,
17
+ setModelLodLayers,
18
+ } from "./model-lod.js";
19
+ import { displacesVertices } from "./projection-plan.js";
20
+ import type { IRendererLike } from "./renderer.js";
21
+ import { markStatic } from "./static-transform.js";
22
+ import { addInSlices, loadAll } from "./streaming.js";
23
+ import { warmUpScene, warmUpSceneWithCompletion, yieldToHost } from "./warmup.js";
24
+ import type { SharedBatch } from "./world-cell-batches.js";
25
+ import type { ICellProxyState, IResidentCell } from "./world-cell-data.js";
26
+ import type { IAssetState } from "./world-cell-models.js";
27
+ import {
28
+ CellProxySelection,
29
+ cellProxyGeometrySafe,
30
+ cellProxyMaterialMatches,
31
+ cellProxyMaterialSafe,
32
+ cellProxySourceSafe,
33
+ cellProxyWorldScale,
34
+ measureCellProxy,
35
+ prepareCellProxy,
36
+ } from "./world-cell-proxy.js";
37
+ import {
38
+ CHUNK_NAME,
39
+ VIRTUAL_SHADOW_CASTER_LAYER,
40
+ VIRTUAL_SHADOW_WIDE_CASTER_LAYER,
41
+ buildChunkShadowProxies,
42
+ } from "./world-chunk-shadow.js";
43
+ import type { IWorldCell } from "./world-package.js";
44
+ import type { IAdmissionBudget } from "./world-tiles.js";
45
+
46
+ interface ICellChunksOptions {
47
+ readonly loadModel: ((url: string) => Promise<Object3D>) | undefined;
48
+ readonly byteBudget: number;
49
+ readonly logicalBase: string;
50
+ readonly receiveShadow: boolean;
51
+ readonly placementReach: Float32Array | undefined;
52
+ readonly autoLodMaxPixelError: number;
53
+ readonly chunkMergeMaxTriangles: number;
54
+ readonly castShadowLevels: number;
55
+ readonly bundlesWanted: boolean;
56
+ }
57
+
58
+ export interface ICellChunksHost {
59
+ disposeProxyModel(state: ICellProxyState): void;
60
+ disposeLoaded(model: Object3D | undefined): number;
61
+ releaseModelPaths(paths: string[]): void;
62
+ retainModelPaths(paths: readonly string[], into: string[]): void;
63
+ addFailures(count: number): void;
64
+ sourceBytes(): number;
65
+ load(path: string, wanted: () => boolean): Promise<Object3D | undefined>;
66
+ cellLive(cell: IResidentCell, generation: number): boolean;
67
+ add(object: Object3D): void;
68
+ intersectsObject(mesh: Mesh): boolean;
69
+ gpuSceneOn(): boolean;
70
+ asset(id: string): IAssetState | undefined;
71
+ invalidateBundles(key: string): void;
72
+ worldSphere(
73
+ bounds: Parameters<typeof import("./model-lod.js").worldSphere>[0],
74
+ ): ReturnType<typeof import("./model-lod.js").worldSphere>;
75
+ reportCellFailure(
76
+ stage: "asset" | "attach" | "chunk",
77
+ key: string,
78
+ paths: readonly string[],
79
+ error: unknown,
80
+ ): void;
81
+ parent(): Object3D | null;
82
+ /** The scene this world sits in, or `undefined` while it is in none: nothing projects it then. */
83
+ targetScene(): Object3D | undefined;
84
+ addChunk(cell: IResidentCell, object: Object3D): void;
85
+ publishChunkBounds(cell: IResidentCell, box: Box3 | undefined, proxies: number): void;
86
+ }
87
+
88
+ /**
89
+ * Bytes one merged chunk group may hold: 4 MiB, which is where a single first-draw upload stops
90
+ * being a few milliseconds and becomes a frame.
91
+ *
92
+ * The 228.8 MB of `createAttribute` buffers a browser walk measured — 826 buffers, 33 over 1 MB,
93
+ * the largest 23.2 / 18.1 / 17.2 / 16.4 MB — all arrived on the first draw of a merged chunk mesh,
94
+ * and that first draw took up to 230 ms. A group is split rather than grown, so each of those
95
+ * uploads is bounded and none of them is a stall.
96
+ */
97
+ const CHUNK_MERGE_MAX_BYTES = 4 * 1024 * 1024;
98
+ /** Position (12) + normal (12) + uv (8) in float32: the three channels a merged group keeps. */
99
+ const CHUNK_MERGE_BYTES_PER_VERTEX = 32;
100
+ /** Vertices in 4 MiB of the above. The budget a chunk's material group is split on. */
101
+ const CHUNK_MERGE_MAX_VERTICES = CHUNK_MERGE_MAX_BYTES / CHUNK_MERGE_BYTES_PER_VERTEX;
102
+ /**
103
+ * Triangles a chunk's merged material group may reach before one of its `InstancedMesh` is left
104
+ * instanced instead. A merged group is one draw; past this many triangles the instanced draw is the
105
+ * cheaper of the two, so the mesh is kept rather than expanded. It is the same 4 MiB counted in the
106
+ * worst case, a de-indexed triangle of three 32-byte vertices, so the cap and the vertex budget above
107
+ * are the one size read in two units. See `IWorldCellsLoadOptions.chunkMergeMaxTriangles`.
108
+ */
109
+ export const CHUNK_MERGE_MAX_TRIANGLES = Math.floor(
110
+ CHUNK_MERGE_MAX_BYTES / (3 * CHUNK_MERGE_BYTES_PER_VERTEX),
111
+ );
112
+ /**
113
+ * How long one chunk's warm-up may take before the chunk is attached uncompiled. The engine's own
114
+ * loading-screen bound for a single pipeline is 2,000 ms. A cell proxy that times out is refused;
115
+ * its staged geometry remains owned until the original compile settles.
116
+ */
117
+ const CHUNK_WARM_TIMEOUT_MS = 2000;
118
+
119
+ /** GPU resources already handed to a `dispose`, so no second path can tear the same one down. */
120
+ const tornDown = new WeakSet<object>();
121
+
122
+ /**
123
+ * Release one GPU resource: at most once per resource, and never by throwing.
124
+ *
125
+ * Exactly once is the streaming contract: an asset's geometry is shared by every cell batch drawn
126
+ * from it, so several residency paths can reach the same object, and a second teardown is the
127
+ * renderer's problem, not the game's.
128
+ *
129
+ * Never throwing is the other half. Three disposes a geometry by deleting each of its attributes,
130
+ * and `WebGPUAttributeUtils.destroyAttribute` reads the GPU buffer off the attribute and calls
131
+ * `destroy` on it with no guard — so disposing a geometry whose upload never produced that buffer
132
+ * throws `TypeError: Cannot read properties of undefined (reading 'destroy')` from wherever the
133
+ * teardown was called. A cell leaving range is the most ordinary thing a streaming world does, so
134
+ * that has to land as a counted failure here, not as a dead frame.
135
+ *
136
+ * @returns `true` when the teardown itself threw, for the caller to count.
137
+ */
138
+ export function release(target: { dispose: () => void } | undefined): boolean {
139
+ if (target === undefined || tornDown.has(target)) return false;
140
+ tornDown.add(target);
141
+ try {
142
+ target.dispose();
143
+ } catch {
144
+ return true;
145
+ }
146
+ return false;
147
+ }
148
+
149
+ export function resolveRelative(baseUrl: string, relative: string): string {
150
+ if (/^(?:[a-z]+:)?\/\//iu.test(relative) || relative.startsWith("data:")) return relative;
151
+ return `${baseUrl}${relative.replace(/^\//u, "")}`;
152
+ }
153
+
154
+ /** What one chunk's merge did, for `TN_WORLD_CHUNK_MERGE`. */
155
+ interface IChunkMerge {
156
+ /** Meshes the chunk held before, and the ones its subtree submits after. */
157
+ readonly meshes: number;
158
+ readonly draws: number;
159
+ /**
160
+ * Bytes the merged groups hold: exactly what the first draw of those meshes uploads, and the
161
+ * number this merge exists to keep small.
162
+ */
163
+ readonly bytes: number;
164
+ /** Instanced meshes baked into a material's group, and the ones left instanced. */
165
+ readonly expanded: number;
166
+ readonly keptInstanced: number;
167
+ /** Teardowns of the consumed shapes that threw, for the caller to count. */
168
+ readonly failed: number;
169
+ /** Shadow-only proxies, per side for merged and retained parts; 0 when nothing casts. */
170
+ readonly shadowDraws: number;
171
+ /**
172
+ * The opaque meshes a proxy covers. They keep drawing the main pass and keep receiving, and
173
+ * they stop casting: the depth pass reads positions, not materials, so it reads the proxy instead.
174
+ */
175
+ readonly shadowCovered: readonly Mesh[];
176
+ }
177
+
178
+ function meshesOf(root: Object3D): number {
179
+ let meshes = 0;
180
+ root.traverse((object) => {
181
+ if ((object as Mesh).isMesh === true) meshes += 1;
182
+ });
183
+ return meshes;
184
+ }
185
+
186
+ /**
187
+ * One chunk's static meshes merged by material, in place, before the chunk is added.
188
+ *
189
+ * A hand-placed chunk is a bridge or a yard, not a prop: its mesh nodes are packed a few dozen to a
190
+ * few hundred per file over a handful of materials, and each one is its own draw — in the main pass
191
+ * and again in every shadow level that redraws it. Merging by material is what the cook already did
192
+ * for repeated meshes (hence the `InstancedMesh`es in a loaded chunk), so this is the same fix one
193
+ * step further out: one draw per material per chunk instead of one per node.
194
+ *
195
+ * Nothing here decides how anything looks. The merged mesh draws the game's own material and holds
196
+ * the geometry exactly as authored, baked into the chunk root's space; what changes is how many
197
+ * calls it takes to draw. `mergeByMaterial` does the bake and owns the refusals, so a group it
198
+ * cannot merge (a material whose meshes disagree about `uv`) leaves the whole chunk as it was and is
199
+ * counted as a failure — a chunk never disappears over a draw-call saving.
200
+ *
201
+ * Left alone: a skinned mesh (posed per frame), one carrying morph targets (the bake drops them), a
202
+ * multi-material mesh (one draw per material already), and anything carrying a baked AutoLOD chain,
203
+ * whose own `ModelLod` swaps its geometry and would be swapped for nothing. No chunk node is
204
+ * animation-targeted: the chunk path takes `gltf.scene` and never a clip list.
205
+ *
206
+ * `disposeSources` says who owns the shapes the bake consumed. The merged buffers are the chunk's
207
+ * own and are released with it on eviction; a shape nothing draws any more is released here, unless
208
+ * the loader cache still holds it — `createAssetLoader` keys models by path and hands the same scene
209
+ * back on the next load, so a cached shape is not this world's to tear down. A geometry a kept mesh
210
+ * still draws is never released either way.
211
+ *
212
+ * `castShadow` says the chunk's shadow bill exists at all — the same answer the caller hands the
213
+ * chunk's nodes — and only then is it worth one position-only proxy per `side`. See
214
+ * `buildChunkShadowProxies`, which draws every side of every chunk with the world's one material for
215
+ * that side.
216
+ *
217
+ * @returns what the merge did, or `undefined` when the bake refused the whole chunk.
218
+ */
219
+ function mergeChunk(
220
+ chunk: Object3D,
221
+ maxTriangles: number,
222
+ disposeSources: boolean,
223
+ castShadow: boolean,
224
+ proxyMaterials: Map<number, Material>,
225
+ ): IChunkMerge | undefined {
226
+ chunk.updateMatrixWorld(true);
227
+ const meshes: Mesh[] = [];
228
+ const skipped = new Set<Mesh>();
229
+ let instanced = 0;
230
+ chunk.traverse((object) => {
231
+ const mesh = object as Mesh & { isInstancedMesh?: boolean };
232
+ if (mesh.isMesh !== true) return;
233
+ meshes.push(mesh);
234
+ // A chain is baked into the geometry the mesh draws, so a merged buffer would carry a `ModelLod`
235
+ // that has nothing to swap: the mesh keeps its own geometry and its own level selection.
236
+ if (lodChainOf(mesh.geometry) !== undefined) {
237
+ skipped.add(mesh);
238
+ return;
239
+ }
240
+ if (Object.keys(mesh.geometry.morphAttributes).length > 0) {
241
+ skipped.add(mesh);
242
+ return;
243
+ }
244
+ if (mesh.isInstancedMesh === true) instanced += 1;
245
+ });
246
+ const before = meshes.length;
247
+ let result: Mesh[];
248
+ try {
249
+ result = mergeByMaterial(chunk, {
250
+ expandInstancedUnderTriangles: maxTriangles,
251
+ label: `world chunk ${chunk.name}`,
252
+ maxGroupVertices: CHUNK_MERGE_MAX_VERTICES,
253
+ skip: (mesh) => skipped.has(mesh),
254
+ });
255
+ } catch {
256
+ return undefined;
257
+ }
258
+ const kept = new Set(skipped);
259
+ let keptInstanced = 0;
260
+ for (const mesh of result) {
261
+ if ((mesh as Mesh & { isInstancedMesh?: boolean }).isInstancedMesh !== true) continue;
262
+ kept.add(mesh);
263
+ keptInstanced += 1;
264
+ }
265
+ const held = new Set<BufferGeometry>();
266
+ for (const mesh of kept) held.add(mesh.geometry);
267
+ let failed = 0;
268
+ // Only what the bake consumed leaves its place; a kept mesh draws the same either way, so it is
269
+ // not re-parented and the chunk's authored hierarchy survives around the merged groups.
270
+ for (const mesh of meshes) {
271
+ if (kept.has(mesh)) continue;
272
+ if (disposeSources && !held.has(mesh.geometry) && release(mesh.geometry)) failed += 1;
273
+ mesh.removeFromParent();
274
+ }
275
+ for (const mesh of result)
276
+ if (!(mesh as Mesh & { isInstancedMesh?: boolean }).isInstancedMesh === true) chunk.add(mesh);
277
+ // Only what the bake produced is covered: a kept mesh was never merged, so it still holds its own
278
+ // per-material draw and its own materials the proxy knows nothing about.
279
+ const shadow = castShadow
280
+ ? buildChunkShadowProxies(
281
+ chunk,
282
+ result.filter((mesh) => !kept.has(mesh)),
283
+ `world chunk ${chunk.name}`,
284
+ proxyMaterials,
285
+ )
286
+ : undefined;
287
+ // AutoLOD and morphs remain their own draws. Only unmodified static instance silhouettes qualify.
288
+ const toRoot = chunk.matrixWorld.clone().invert();
289
+ const retained = castShadow
290
+ ? buildChunkShadowProxies(
291
+ chunk,
292
+ [...kept].filter(
293
+ (mesh) =>
294
+ mesh instanceof InstancedMesh &&
295
+ mesh.count > 0 &&
296
+ mesh.layers.isEnabled(0) &&
297
+ lodChainOf(mesh.geometry) === undefined &&
298
+ Object.keys(mesh.geometry.morphAttributes).length === 0 &&
299
+ mesh.morphTexture === null &&
300
+ mesh.customDepthMaterial === undefined &&
301
+ mesh.customDistanceMaterial === undefined &&
302
+ mesh.onBeforeRender === Object3D.prototype.onBeforeRender &&
303
+ !Array.isArray(mesh.material) &&
304
+ !displacesVertices(mesh.material) &&
305
+ mesh.material.visible &&
306
+ mesh.material.allowOverride &&
307
+ mesh.material.onBeforeCompile === Material.prototype.onBeforeCompile &&
308
+ Reflect.get(mesh.material, "isShaderMaterial") !== true &&
309
+ mesh.material.shadowSide === null &&
310
+ (mesh.material.clippingPlanes?.length ?? 0) === 0 &&
311
+ Reflect.get(mesh.material, "vertexNode") == null &&
312
+ Reflect.get(mesh.material, "depthNode") == null &&
313
+ Reflect.get(mesh.material, "castShadowNode") == null &&
314
+ Reflect.get(mesh.material, "wireframe") !== true &&
315
+ Reflect.get(mesh.geometry, "indirect") == null &&
316
+ Reflect.get(mesh, "casterInstanceScale") == null &&
317
+ new Matrix4().multiplyMatrices(toRoot, mesh.matrixWorld).determinant() >= 0,
318
+ ),
319
+ `world chunk ${chunk.name} retained`,
320
+ proxyMaterials,
321
+ true,
322
+ )
323
+ : undefined;
324
+ return {
325
+ bytes: mergedBytes(result, kept),
326
+ draws: meshesOf(chunk),
327
+ expanded: instanced - keptInstanced,
328
+ failed,
329
+ keptInstanced,
330
+ meshes: before,
331
+ shadowCovered: [...(shadow?.covered ?? []), ...(retained?.covered ?? [])],
332
+ shadowDraws: (shadow?.proxies.length ?? 0) + (retained?.proxies.length ?? 0),
333
+ };
334
+ }
335
+
336
+ /**
337
+ * Bytes the bake's own meshes hold, indices included: the upload their first draw would have paid.
338
+ * A kept mesh is not one of them — it was never merged, and it draws the same either way.
339
+ */
340
+ function mergedBytes(merged: readonly Mesh[], kept: ReadonlySet<Mesh>): number {
341
+ let bytes = 0;
342
+ for (const mesh of merged) {
343
+ if (kept.has(mesh)) continue;
344
+ for (const attribute of Object.values(mesh.geometry.attributes))
345
+ bytes += attribute.array.byteLength;
346
+ const index = mesh.geometry.getIndex();
347
+ if (index !== null) bytes += index.array.byteLength;
348
+ }
349
+ return bytes;
350
+ }
351
+
352
+ /** Triangles one geometry submits; the count the `TN_WORLD_LOD_CHAIN` marker reports per level. */
353
+ export function levelTriangles(geometry: BufferGeometry): number {
354
+ const drawn = geometry.index?.count ?? geometry.getAttribute("position")?.count ?? 0;
355
+ return Math.floor(drawn / 3);
356
+ }
357
+
358
+ export class CellChunks {
359
+ #camera: Camera | undefined;
360
+ /**
361
+ * The renderer and camera of the last frame that ran, kept so a chunk streamed in between frames
362
+ * can be compiled before it is attached. `update(renderer, camera)` is the only place either is
363
+ * known, and the admission that loads a chunk is not a place that has them.
364
+ */
365
+ #renderer: IRendererLike | undefined;
366
+
367
+ readonly #hlod: boolean;
368
+ readonly #cellProxies = new Set<ICellProxyState>();
369
+ #hlodBytes = 0;
370
+ #hlodRefused = 0;
371
+ #hlodReason = "";
372
+ #hlodFailures = 0;
373
+ /**
374
+ * Per-side surfaces shared world-wide, separately for merged and retained proxies. See
375
+ * `worldOwned`: a chunk teardown must not release another chunk's shadow surface.
376
+ */
377
+ readonly #proxyMaterials = new Map<number, Material>();
378
+
379
+ #proxyObserved(state: ICellProxyState): boolean {
380
+ return state.prepared !== undefined && state.observed.size === state.prepared.meshes.length;
381
+ }
382
+
383
+ releaseCellProxy(state: ICellProxyState): void {
384
+ if (!this.#cellProxies.delete(state)) return;
385
+ state.prepared?.root.removeFromParent();
386
+ for (const mesh of state.prepared?.meshes ?? []) {
387
+ mesh.onBeforeRender = Mesh.prototype.onBeforeRender;
388
+ mesh.onAfterRender = Mesh.prototype.onAfterRender;
389
+ this.#host.addFailures(release(mesh.geometry) ? 1 : 0);
390
+ }
391
+ // Cached model ownership uses the same global path holders as chunks and source LODs.
392
+ // A compilation never races this release: cancellation retains everything until settlement.
393
+ this.#host.disposeProxyModel(state);
394
+ this.#host.releaseModelPaths(state.retainedPaths);
395
+ this.#hlodBytes -= state.bytes;
396
+ state.bytes = 0;
397
+ }
398
+
399
+ #beginCellProxy(cell: IResidentCell): void {
400
+ const proxy = cell.cell.proxy;
401
+ if (proxy === undefined) return;
402
+ // Reserve resident headroom before IO; decoded source and fixed copies must fit it.
403
+ // Temporary pressure retries through the existing admission loop.
404
+ const reserve = Math.min(
405
+ CHUNK_MERGE_MAX_BYTES * 2,
406
+ this.#byteBudget - this.#host.sourceBytes() - this.#hlodBytes,
407
+ );
408
+ if (reserve <= 0) return;
409
+ const state: ICellProxyState = {
410
+ cell,
411
+ selector: new CellProxySelection(proxy),
412
+ retainedPaths: [],
413
+ pending: true,
414
+ compiling: false,
415
+ cancelled: false,
416
+ compiled: false,
417
+ active: false,
418
+ bytes: 0,
419
+ observed: new Set(),
420
+ hidden: new Map(),
421
+ mainMasks: new Map(),
422
+ };
423
+ const source = this.#cellProxySource(state);
424
+ // A retained neighboring key or a cheaper source LOD cannot benefit. Reconsider after later
425
+ // residency changes without allocating another copy or running a proxy load meanwhile.
426
+ if (
427
+ !source.compatible ||
428
+ proxy.triangles >= source.triangles ||
429
+ proxy.materialGroups > source.draws
430
+ )
431
+ return;
432
+ cell.proxy = state;
433
+ state.bytes = reserve;
434
+ this.#hlodBytes += reserve;
435
+ this.#cellProxies.add(state);
436
+ const path = resolveRelative(this.#logicalBase, proxy.glb);
437
+ if (this.#loadModel === undefined) this.#host.retainModelPaths([path], state.retainedPaths);
438
+ void this.#host
439
+ .load(path, () => this.#host.cellLive(cell, cell.generation))
440
+ .then(
441
+ (model) => {
442
+ state.pending = false;
443
+ state.model = model;
444
+ if (
445
+ !this.#host.cellLive(cell, cell.generation) ||
446
+ state.cancelled ||
447
+ model === undefined
448
+ ) {
449
+ state.cancelled = true;
450
+ this.releaseCellProxy(state);
451
+ return;
452
+ }
453
+ try {
454
+ if (measureCellProxy(model, proxy, true) > state.bytes)
455
+ throw new Error("Cell proxy exceeds its reserved decoded budget.");
456
+ } catch (error) {
457
+ this.#hlodReason = `${state.cell.key}: ${String(error instanceof Error ? error.message : error).slice(0, 160)}`;
458
+ state.cancelled = true;
459
+ this.#hlodRefused++;
460
+ this.releaseCellProxy(state);
461
+ return;
462
+ }
463
+ // Preparation waits for an admission unit on a rendered update.
464
+ },
465
+ () => {
466
+ state.pending = false;
467
+ state.cancelled = true;
468
+ this.#hlodFailures++;
469
+ this.releaseCellProxy(state);
470
+ },
471
+ );
472
+ }
473
+
474
+ #prepareCellProxy(state: ICellProxyState): void {
475
+ try {
476
+ const prepared = prepareCellProxy(
477
+ state.model as Object3D,
478
+ state.cell.cell.proxy as NonNullable<IWorldCell["proxy"]>,
479
+ state.bytes,
480
+ );
481
+ state.prepared = prepared;
482
+ if (prepared.bytes > state.bytes)
483
+ throw new Error("Cell proxy exceeds its reserved decoded budget.");
484
+ this.#hlodBytes += prepared.bytes - state.bytes;
485
+ state.bytes = prepared.bytes;
486
+ prepared.root.name = `world-cell-proxy:${state.cell.key}`;
487
+ for (const mesh of prepared.meshes) mesh.receiveShadow = this.#receiveShadow;
488
+ this.#host.add(prepared.root);
489
+ } catch (error) {
490
+ this.#hlodReason = `${state.cell.key}: ${String(error instanceof Error ? error.message : error).slice(0, 160)}`;
491
+ state.cancelled = true;
492
+ this.#hlodRefused++;
493
+ this.releaseCellProxy(state);
494
+ }
495
+ }
496
+
497
+ #compileCellProxy(state: ICellProxyState, renderer: IRendererLike, camera: Camera): void {
498
+ const prepared = state.prepared;
499
+ if (prepared === undefined) return;
500
+ const targetScene = this.#host.targetScene();
501
+ if (targetScene === undefined) return;
502
+ state.compiling = true;
503
+ // No timeout counts as cancellation. This original promise owns every staged resource until it
504
+ // settles, even if the cell/world has already left. Refusal keeps source and releases afterward.
505
+ void Promise.resolve()
506
+ .then(() =>
507
+ warmUpSceneWithCompletion(renderer, prepared.root, camera, {
508
+ budgetMs: CHUNK_WARM_TIMEOUT_MS,
509
+ renderPasses: false,
510
+ targetScene,
511
+ }),
512
+ )
513
+ .then(
514
+ async ({ report, completion }) => {
515
+ if (
516
+ report.unsupported ||
517
+ report.timedOut ||
518
+ report.abandoned > 0 ||
519
+ (renderer.warmUpWorldPass !== undefined && report.passes?.includes("main") !== true)
520
+ ) {
521
+ // The report honors the 2 s budget, but Three may still be compiling a pipeline. Keep
522
+ // the staged geometry and its reservation alive until that original promise settles.
523
+ state.cancelled = true;
524
+ this.#hlodFailures++;
525
+ await completion.catch(() => undefined);
526
+ state.compiling = false;
527
+ this.releaseCellProxy(state);
528
+ return;
529
+ }
530
+ await completion;
531
+ renderer.warmUpScopeSettled?.(
532
+ `cell:${state.cell.key}:${String(state.cell.generation)}`,
533
+ prepared.root,
534
+ );
535
+ state.compiling = false;
536
+ if (state.cancelled || !this.#host.cellLive(state.cell, state.cell.generation)) {
537
+ state.cancelled = true;
538
+ this.releaseCellProxy(state);
539
+ return;
540
+ }
541
+ this.#uploadAttributes(prepared.root);
542
+ state.compiled = true;
543
+ // Three calls render hooks during compile too, and may swallow pipeline errors. Observe a
544
+ // matching main-camera backend submission only AFTER this compile settles. Zero-count
545
+ // submission proves readiness of that route, not full-triangle execution or visual quality.
546
+ for (const mesh of prepared.meshes) {
547
+ let before: number | undefined;
548
+ const calls = (): number | undefined => {
549
+ try {
550
+ const info = renderer.info as { render?: { drawCalls?: number; calls?: number } };
551
+ const value = info.render?.drawCalls ?? info.render?.calls;
552
+ return Number.isSafeInteger(value) && (value as number) >= 0 ? value : undefined;
553
+ } catch {
554
+ return undefined;
555
+ }
556
+ };
557
+ mesh.onBeforeRender = (_raw, _scene, drawnCamera) => {
558
+ before =
559
+ drawnCamera === this.#camera && renderer.compiling !== true ? calls() : undefined;
560
+ };
561
+ markEngineRenderHook(mesh.onBeforeRender);
562
+ mesh.onAfterRender = (_raw, _scene, drawnCamera) => {
563
+ const after = calls();
564
+ if (
565
+ drawnCamera === this.#camera &&
566
+ renderer.compiling !== true &&
567
+ before !== undefined &&
568
+ after !== undefined &&
569
+ after > before
570
+ )
571
+ state.observed.add(mesh);
572
+ before = undefined;
573
+ };
574
+ markEngineRenderHook(mesh.onAfterRender);
575
+ }
576
+ },
577
+ () => {
578
+ state.compiling = false;
579
+ state.cancelled = true;
580
+ this.#hlodFailures++;
581
+ this.releaseCellProxy(state);
582
+ },
583
+ )
584
+ .catch(() => {
585
+ state.compiling = false;
586
+ state.cancelled = true;
587
+ this.#hlodFailures++;
588
+ this.releaseCellProxy(state);
589
+ });
590
+ }
591
+
592
+ #cellSourceDrawn(mesh: Mesh): boolean {
593
+ if (
594
+ this.#camera === undefined ||
595
+ (mesh instanceof InstancedMesh && mesh.count === 0) ||
596
+ !this.#camera.layers.test(mesh.layers) ||
597
+ Array.isArray(mesh.material) ||
598
+ !mesh.material.visible
599
+ )
600
+ return false;
601
+ for (let object: Object3D | null = mesh; object !== null; object = object.parent)
602
+ if (!object.visible) return false;
603
+ if (mesh.frustumCulled && !this.#host.intersectsObject(mesh)) return false;
604
+ return true;
605
+ }
606
+
607
+ #cellProxySource(state: ICellProxyState): {
608
+ compatible: boolean;
609
+ triangles: number;
610
+ draws: number;
611
+ meshes: Mesh[];
612
+ } {
613
+ const cell = state.cell;
614
+ const meshes = [...cell.mainChunkMeshes];
615
+ for (const chunk of cell.chunks)
616
+ chunk.traverse((node) => {
617
+ if (node instanceof Mesh && isLodJoinProxy(node)) meshes.push(node);
618
+ });
619
+ const materials = new Set<Material>();
620
+ const staticInstances = new Set<Mesh>();
621
+ for (const [mesh, baseline] of cell.chunkInstances)
622
+ if (
623
+ mesh.instanceMatrix === baseline.matrix &&
624
+ mesh.instanceMatrix.version === baseline.version &&
625
+ mesh.count === baseline.count
626
+ )
627
+ staticInstances.add(mesh);
628
+ let triangles = 0;
629
+ let draws = 0;
630
+ let compatible =
631
+ cellLoaded(cell) && (state.cell.cell.proxy?.scope !== "cell" || !this.#host.gpuSceneOn());
632
+ for (const mesh of meshes) {
633
+ if (
634
+ !cellProxySourceSafe(mesh, staticInstances) ||
635
+ Array.isArray(mesh.material) ||
636
+ !cellProxyGeometrySafe(mesh.geometry) ||
637
+ !cellProxyMaterialSafe(mesh.material as Material)
638
+ )
639
+ compatible = false;
640
+ else materials.add(mesh.material as Material);
641
+ if (this.#cellSourceDrawn(mesh)) {
642
+ triangles +=
643
+ levelTriangles(mesh.geometry) * (mesh instanceof InstancedMesh ? mesh.count : 1);
644
+ draws++;
645
+ }
646
+ }
647
+ if (state.cell.cell.proxy?.scope === "cell") {
648
+ const counts = new Map<SharedBatch, number>();
649
+ const costs = new Map<SharedBatch, number>();
650
+ for (const run of cell.cell.runs) {
651
+ const asset = this.#host.asset(run.asset);
652
+ if (
653
+ asset === undefined ||
654
+ !asset.hlodSafe ||
655
+ asset.impostor !== undefined ||
656
+ asset.definition.maxDistance !== undefined ||
657
+ this.#placementReach !== undefined
658
+ ) {
659
+ compatible = false;
660
+ continue;
661
+ }
662
+ for (const [part, shape] of (asset.levels[0] ?? []).entries()) {
663
+ const entries = cell.batches.filter((entry) => entry.run === run && entry.part === part);
664
+ if (
665
+ entries.length !== 1 ||
666
+ entries[0]?.level !== 0 ||
667
+ entries[0]?.batch.count !== run.count ||
668
+ !cellProxyMaterialSafe(shape.material)
669
+ ) {
670
+ compatible = false;
671
+ continue;
672
+ }
673
+ materials.add(shape.material);
674
+ }
675
+ }
676
+ for (const entry of cell.batches) {
677
+ if (entry.shared === undefined || entry.segment < 0 || entry.level !== 0) {
678
+ compatible = false;
679
+ continue;
680
+ }
681
+ counts.set(entry.shared, (counts.get(entry.shared) ?? 0) + entry.batch.count);
682
+ costs.set(
683
+ entry.shared,
684
+ (costs.get(entry.shared) ?? 0) + levelTriangles(entry.batch.geometry) * entry.batch.count,
685
+ );
686
+ }
687
+ for (const [shared, count] of counts) {
688
+ // Retain the segment, hence near restoration is a flag write with no budget dependency.
689
+ // A neighboring holder keeps this key drawn; such a key cannot be retired for this cell.
690
+ if (shared.live !== count) compatible = false;
691
+ else {
692
+ if (this.#cellSourceDrawn(shared.mesh)) {
693
+ draws++;
694
+ triangles += costs.get(shared) ?? 0;
695
+ }
696
+ meshes.push(shared.mesh);
697
+ }
698
+ }
699
+ }
700
+ for (const mesh of state.prepared?.meshes ?? []) {
701
+ if (
702
+ ![...materials].some((material) =>
703
+ cellProxyMaterialMatches(mesh.material as Material, material),
704
+ )
705
+ )
706
+ compatible = false;
707
+ }
708
+ return { compatible, triangles, draws, meshes };
709
+ }
710
+
711
+ restoreCellProxySource(state: ICellProxyState): void {
712
+ for (const [mesh, visible] of state.hidden) mesh.visible = visible;
713
+ state.hidden.clear();
714
+ for (const [mesh, mask] of state.mainMasks) setModelLodLayers(mesh, mask);
715
+ state.mainMasks.clear();
716
+ }
717
+
718
+ showCellProxy(state: ICellProxyState, active: boolean, meshes?: readonly Mesh[]): void {
719
+ const prepared = state.prepared;
720
+ if (prepared === undefined) return;
721
+ const changed = state.active !== active;
722
+ // AutoLOD owns chunk visibility. Retire only its main pass, retaining the selected source
723
+ // geometry as a caster; joined rungs inherit this same pass ownership on activation.
724
+ this.restoreCellProxySource(state);
725
+ if (active)
726
+ for (const mesh of meshes ?? this.#cellProxySource(state).meshes) {
727
+ if (mesh.layers.isEnabled(0)) {
728
+ if (state.cell.mainChunkMeshes.includes(mesh) || isLodJoinProxy(mesh)) {
729
+ state.mainMasks.set(mesh, mesh.layers.mask);
730
+ let mask = mesh.layers.mask & ~1;
731
+ if (mesh.castShadow)
732
+ mask |= (1 << VIRTUAL_SHADOW_CASTER_LAYER) | (1 << VIRTUAL_SHADOW_WIDE_CASTER_LAYER);
733
+ setModelLodLayers(mesh, mask);
734
+ } else {
735
+ state.hidden.set(mesh, mesh.visible);
736
+ mesh.visible = false;
737
+ }
738
+ }
739
+ }
740
+ prepared.root.visible = active || !this.#proxyObserved(state);
741
+ prepared.meshes.forEach((mesh, index) => {
742
+ const range = prepared.ranges[index];
743
+ if (range !== undefined) mesh.geometry.setDrawRange(range.start, active ? range.count : 0);
744
+ });
745
+ state.active = active;
746
+ if (changed) {
747
+ this.#host.invalidateBundles(state.cell.key);
748
+ }
749
+ }
750
+
751
+ stepCellProxies(
752
+ cells: Iterable<IResidentCell>,
753
+ matrixWorld: Matrix4,
754
+ budget: IAdmissionBudget,
755
+ renderer?: IRendererLike,
756
+ camera?: Camera,
757
+ ): void {
758
+ if (!this.#hlod) return;
759
+ for (const cell of cells) {
760
+ if (cell.cell.proxy === undefined) continue;
761
+ if (cell.proxy === undefined) {
762
+ if (cellLoaded(cell)) budget.admit(() => this.#beginCellProxy(cell));
763
+ continue;
764
+ }
765
+ const state = cell.proxy;
766
+ if (state.cancelled || state.pending) continue;
767
+ if (state.model !== undefined && state.prepared === undefined)
768
+ budget.admit(() => this.#prepareCellProxy(state));
769
+ if (state.cancelled || state.prepared === undefined) continue;
770
+ if (!state.compiled && !state.compiling && renderer !== undefined && camera !== undefined)
771
+ budget.admit(() => this.#compileCellProxy(state, renderer, camera));
772
+ this.restoreCellProxySource(state);
773
+ const source = this.#cellProxySource(state);
774
+ const scale = cellProxyWorldScale(matrixWorld);
775
+ const sphere = this.#host.worldSphere(state.prepared.bounds);
776
+ sphere.radius = state.prepared.bounds.radius * scale;
777
+ const view =
778
+ camera === undefined
779
+ ? undefined
780
+ : conservativeViewDepth(
781
+ camera,
782
+ sphere.center,
783
+ sphere.radius,
784
+ Reflect.get(camera, "near") ?? 0.1,
785
+ );
786
+ const height = renderer?.domElement.height;
787
+ const selected = state.selector.select({
788
+ sourceReady: cellLoaded(cell),
789
+ proxyReady: state.compiled && this.#proxyObserved(state),
790
+ sourceCompatible: source.compatible && scale > 0,
791
+ sourceTriangles: source.triangles,
792
+ replaceableSourceDraws: source.draws,
793
+ views:
794
+ camera !== undefined &&
795
+ height !== undefined &&
796
+ Number.isFinite(height) &&
797
+ height > 0 &&
798
+ view !== undefined
799
+ ? [
800
+ {
801
+ camera,
802
+ viewportHeight: height,
803
+ ...view,
804
+ finest: Reflect.get(camera, "isOrthographicCamera") === true || view.degenerate,
805
+ },
806
+ ]
807
+ : [],
808
+ // Collapsing a valid Three transform retains detail; a zero error scale cannot select LOD.
809
+ errorScale: scale === 0 ? 1 : scale,
810
+ maxPixelError: this.#autoLodMaxPixelError,
811
+ });
812
+ this.showCellProxy(state, selected === "proxy", source.meshes);
813
+ }
814
+ }
815
+
816
+ startChunkLoad(cell: IResidentCell): void {
817
+ const generation = cell.generation;
818
+ const paths: string[] = [];
819
+ for (const chunk of cell.cell.chunks ?? [])
820
+ paths.push(resolveRelative(this.#logicalBase, chunk));
821
+ // A chunk's source is the same loader cache entry an asset's level would be: held while this
822
+ // cell is resident and handed back with the last cell naming the path, through the one
823
+ // `#modelPaths` map. A `loadModel` override parses per load and reaches no cache, so it owns
824
+ // nothing here either; see `#releaseModelPaths`.
825
+ if (this.#loadModel === undefined) this.#host.retainModelPaths(paths, cell.retainedModelPaths);
826
+ loadAll(paths, (path) => this.#host.load(path, () => this.#host.cellLive(cell, generation)), {
827
+ marker: false,
828
+ }).then(
829
+ (models) => {
830
+ void this.#attachChunks(
831
+ cell,
832
+ generation,
833
+ models.filter((model): model is Object3D => model !== undefined),
834
+ );
835
+ },
836
+ (error: unknown) => {
837
+ cell.chunkFailed = true;
838
+ this.#host.addFailures(1);
839
+ this.#host.reportCellFailure("chunk", cell.key, paths, error);
840
+ },
841
+ );
842
+ }
843
+
844
+ /**
845
+ * Hand the chunk's own buffers to the renderer now, and report how many it took.
846
+ *
847
+ * A compile builds pipelines, not geometry, so the bake's new attributes reached the device on
848
+ * whichever frame first drew them — 826 buffers and 228.8 MB on an 8 s walk, 33 of them over a
849
+ * megabyte, lining up exactly with the p95 and max frame spikes. The backend's own attribute
850
+ * creation is idempotent, so this is a move rather than a second upload, and a renderer with no
851
+ * such seam answers 0 and behaves as it did.
852
+ */
853
+ #uploadAttributes(chunk: Object3D): number {
854
+ const upload = this.#renderer?.uploadAttributes;
855
+ if (upload === undefined) return 0;
856
+ const geometries = new Set<BufferGeometry>();
857
+ chunk.traverse((object) => {
858
+ const mesh = object as Mesh;
859
+ if (mesh.isMesh === true) geometries.add(mesh.geometry);
860
+ });
861
+ return upload(geometries);
862
+ }
863
+
864
+ /**
865
+ * Hand this chunk's own textures to the device now, and report how many it took.
866
+ *
867
+ * The same argument as the buffers above, one resource class over: a compile builds pipelines, not
868
+ * pixels, so the bake's textures reached the device inside `_renderObjectDirect` on the frame the
869
+ * chunk first drew — 87 ms of a 94 ms first draw in one frame of a Machinefall map-walk, and 79 ms
870
+ * of 131 ms in another. A texture the world already shares with what is on screen is one early
871
+ * return inside three and no work here.
872
+ */
873
+ #uploadTextures(chunk: Object3D): number {
874
+ const upload = this.#renderer?.uploadTextures;
875
+ if (upload === undefined) return 0;
876
+ return upload(chunk);
877
+ }
878
+
879
+ /**
880
+ * Compile a merged chunk before anything can draw it, and report whether the compile came back.
881
+ *
882
+ * A chunk's first draw is the most expensive frame a streaming world has: its own first draw built
883
+ * nodes and a render pipeline synchronously, and one chunk cost **248 ms of a 291 ms walk** in the
884
+ * census that found it. The engine already owns this work — `warmUpScene` drives the renderer's
885
+ * own `compileAsync`, and this is that same call with the world as the target scene, so the chunk's
886
+ * materials resolve the same lights, environment and clipping the real frame will resolve them
887
+ * against. A pipeline compiled against no lights would be a different pipeline, and the frame would
888
+ * still pay for it.
889
+ *
890
+ * It is bounded by `within`, the warm-up's own bound: a compile that never settles is abandoned and
891
+ * the chunk is attached anyway, because a missing chunk is worse than a slow frame. A world that is
892
+ * in no scene is skipped outright — nothing projects it, so a compile would build nothing, which is
893
+ * the same answer `load()` gets, where the loading screen is about to draw it anyway.
894
+ */
895
+ async #warmChunk(chunk: Object3D, scopeLabel: string): Promise<boolean> {
896
+ const renderer = this.#renderer;
897
+ const camera = this.#camera;
898
+ if (renderer === undefined || camera === undefined || this.#host.parent() === null)
899
+ return false;
900
+ const targetScene = this.#host.targetScene();
901
+ if (targetScene === undefined) return false;
902
+ // The rejected compile is a pipeline this warm-up could not build, not a reason to fail the
903
+ // admission: the frame that needs it will try again and fail there, where the error belongs.
904
+ return warmUpScene(renderer, chunk, camera, {
905
+ budgetMs: CHUNK_WARM_TIMEOUT_MS,
906
+ renderPasses: false,
907
+ targetScene,
908
+ yieldFrame: yieldToHost,
909
+ }).then(
910
+ (report) => {
911
+ const settled =
912
+ !report.unsupported &&
913
+ report.observed.status === "complete" &&
914
+ !report.timedOut &&
915
+ report.abandoned === 0 &&
916
+ (renderer.warmUpWorldPass === undefined || report.passes?.includes("main") === true);
917
+ if (settled) renderer.warmUpScopeSettled?.(scopeLabel, chunk);
918
+ return settled;
919
+ },
920
+ () => false,
921
+ );
922
+ }
923
+
924
+ async #attachChunks(
925
+ cell: IResidentCell,
926
+ generation: number,
927
+ models: readonly Object3D[],
928
+ ): Promise<void> {
929
+ const live = (): boolean => this.#host.cellLive(cell, generation);
930
+ let attached = 0;
931
+ // Merged and shaped, not yet in the world: the compile below runs between the two, and a cell
932
+ // that left the ring in the middle takes its prepared chunks with it.
933
+ const prepared: { readonly object: Object3D; readonly proxies: number }[] = [];
934
+ try {
935
+ const report = await addInSlices(
936
+ models,
937
+ (object) => {
938
+ if (!live()) return;
939
+ object.name = CHUNK_NAME;
940
+ // One draw per material before the chunk is ever added, so the main pass and every shadow
941
+ // level that redraws it submit the chunk's materials rather than its nodes. A refusal
942
+ // leaves the chunk exactly as authored and is counted: it never costs the chunk itself.
943
+ const merge = mergeChunk(
944
+ object,
945
+ this.#chunkMergeMaxTriangles,
946
+ // A `loadModel` override parses per load, so a chunk's shapes are this world's to
947
+ // release; `assets.model` caches by path and hands the same scene back, so they are not.
948
+ this.#loadModel !== undefined,
949
+ this.#castShadowLevels > 0,
950
+ this.#proxyMaterials,
951
+ );
952
+ // Where the frame budget counts this chunk's main-pass draws (`RenderPassBudget`). Written
953
+ // after the bake and over the whole subtree, because that is the only point where all three
954
+ // outcomes exist at once: a merged group, an instanced mesh the bake kept, and a chunk it
955
+ // refused whole are all one chunk's draws. The proxies the bake built are off layer 0 and
956
+ // keep the `proxies` origin they were given.
957
+ object.traverse((node) => {
958
+ if ((node as Mesh).isMesh !== true || node.layers.isEnabled(0) === false) return;
959
+ node.userData.tnDrawSource = "chunks";
960
+ });
961
+ // The buffers the bake just made, uploaded here rather than on the chunk's first draw,
962
+ // which is the frame that uploads them today: 228.8 MB over 826 `createAttribute` calls
963
+ // in a browser walk, and up to 230 ms inside the frames that first submitted them.
964
+ // `addInSlices` is the admission budget, so this is one chunk per update, never a batch.
965
+ const uploaded = this.#uploadAttributes(object);
966
+ this.#uploadTextures(object);
967
+ if (merge === undefined) this.#host.addFailures(1);
968
+ else {
969
+ this.#host.addFailures(merge.failed);
970
+ console.info(
971
+ `TN_WORLD_CHUNK_MERGE meshes=${String(merge.meshes)} draws=${String(merge.draws)} ` +
972
+ `bytes=${String(merge.bytes)} uploaded=${String(uploaded)} ` +
973
+ `instancedExpanded=${String(merge.expanded)} keptInstanced=${String(merge.keptInstanced)} ` +
974
+ `shadowDraws=${String(merge.shadowDraws)}`,
975
+ );
976
+ }
977
+ // Hand-placed chunks are the buildings and set dressing: full shape, so they cast with the
978
+ // near scatter and receive like everything else when the game asks for shadows. A merged
979
+ // opaque mesh the proxy covers keeps receiving and stops casting: the depth pass reads the
980
+ // proxy, so casting from both would pay the bill the proxy was built to remove. The proxy
981
+ // itself is off layer 0 and already carries what the level cameras need of it.
982
+ if (this.#castShadowLevels > 0 || this.#receiveShadow) {
983
+ const covered = new Set(merge?.shadowCovered);
984
+ object.traverse((node) => {
985
+ if (node.layers.isEnabled(0) === false) return;
986
+ node.castShadow = this.#castShadowLevels > 0 && !covered.has(node as Mesh);
987
+ node.receiveShadow = this.#receiveShadow;
988
+ });
989
+ }
990
+ prepared.push({ object, proxies: merge?.shadowDraws ?? 0 });
991
+ },
992
+ { marker: false, while: live },
993
+ );
994
+ if (report.stopped)
995
+ for (let i = report.added; i < models.length; i += 1)
996
+ this.#host.addFailures(this.#host.disposeLoaded(models[i] as Object3D));
997
+ for (const { object, proxies } of prepared) {
998
+ // The compile is the whole point of the wait, and the wait is the only thing between the
999
+ // merge and the attach. Everything the world does not own is released when the cell that
1000
+ // asked for the chunk is gone, so a chunk that arrives after its cell left is torn down here
1001
+ // rather than compiled and thrown at a world that is not looking.
1002
+ if (live())
1003
+ await this.#warmChunk(object, `chunk:${cell.key}:${String(cell.chunks.length)}`);
1004
+ if (!live()) {
1005
+ this.#host.addFailures(this.#host.disposeLoaded(object));
1006
+ continue;
1007
+ }
1008
+ cell.chunks.push(object);
1009
+ object.traverse((node) => {
1010
+ if (node instanceof Mesh && node.layers.isEnabled(0)) cell.mainChunkMeshes.push(node);
1011
+ if (node instanceof InstancedMesh && node.layers.isEnabled(0))
1012
+ cell.chunkInstances.set(node, {
1013
+ matrix: node.instanceMatrix,
1014
+ version: node.instanceMatrix.version,
1015
+ count: node.count,
1016
+ });
1017
+ });
1018
+ // The chunk's own box, from the merged geometry's boxes rather than its vertices: a chunk
1019
+ // is loaded once and both consumers of it are only asked to be no wider than the chunk. Read
1020
+ // before `#addChunk`, which may hand part of the subtree to a cell's record and leave the
1021
+ // rest behind, so the box is the chunk's whatever ends up where.
1022
+ const box =
1023
+ proxies > 0 || this.#bundlesWanted ? new Box3().setFromObject(object, false) : undefined;
1024
+ this.#host.addChunk(cell, object);
1025
+ // A loaded chunk is placed once and never rewritten: its transforms, geometry and material
1026
+ // are the ones the export gave it, so it is the one subtree here with nothing to announce.
1027
+ markStatic(object);
1028
+ // The proxies' shadow pipelines are the one thing a compile cannot build — three creates a
1029
+ // shadow variant on the first pass that draws the caster, and the pass is the levels'. So
1030
+ // the levels are told a caster arrived, exactly as a prewarmed caster cluster tells them:
1031
+ // the first level whose window covers the chunk submits the proxy and builds it. With one
1032
+ // material per `side` world-wide, that is one pipeline for the world's first chunk of each
1033
+ // side and a node binding for every chunk after it, not a compile per chunk.
1034
+ this.#host.publishChunkBounds(cell, box, proxies);
1035
+ attached += 1;
1036
+ }
1037
+ } catch (error) {
1038
+ cell.chunkFailed = true;
1039
+ this.#host.addFailures(1);
1040
+ this.#host.reportCellFailure(
1041
+ "attach",
1042
+ cell.key,
1043
+ Array.from(cell.cell.chunks ?? [], (chunk) => resolveRelative(this.#logicalBase, chunk)),
1044
+ error,
1045
+ );
1046
+ for (let i = attached; i < models.length; i += 1)
1047
+ this.#host.addFailures(this.#host.disposeLoaded(models[i] as Object3D));
1048
+ }
1049
+ if (this.#host.cellLive(cell, generation) && !cell.chunkFailed) cell.chunksLoaded = true;
1050
+ }
1051
+ get renderer(): IRendererLike | undefined {
1052
+ return this.#renderer;
1053
+ }
1054
+ set renderer(value: IRendererLike | undefined) {
1055
+ this.#renderer = value;
1056
+ }
1057
+ get camera(): Camera | undefined {
1058
+ return this.#camera;
1059
+ }
1060
+ set camera(value: Camera | undefined) {
1061
+ this.#camera = value;
1062
+ }
1063
+ readonly #host: ICellChunksHost;
1064
+ readonly #loadModel: ((url: string) => Promise<Object3D>) | undefined;
1065
+ readonly #byteBudget: number;
1066
+ readonly #logicalBase: string;
1067
+ readonly #receiveShadow: boolean;
1068
+ readonly #placementReach: Float32Array | undefined;
1069
+ readonly #autoLodMaxPixelError: number;
1070
+ readonly #chunkMergeMaxTriangles: number;
1071
+ readonly #castShadowLevels: number;
1072
+ readonly #bundlesWanted: boolean;
1073
+ constructor(hlod: boolean, options: ICellChunksOptions, host: ICellChunksHost) {
1074
+ this.#hlod = hlod;
1075
+ this.#host = host;
1076
+ this.#loadModel = options.loadModel;
1077
+ this.#byteBudget = options.byteBudget;
1078
+ this.#logicalBase = options.logicalBase;
1079
+ this.#receiveShadow = options.receiveShadow;
1080
+ this.#placementReach = options.placementReach;
1081
+ this.#autoLodMaxPixelError = options.autoLodMaxPixelError;
1082
+ this.#chunkMergeMaxTriangles = options.chunkMergeMaxTriangles;
1083
+ this.#castShadowLevels = options.castShadowLevels;
1084
+ this.#bundlesWanted = options.bundlesWanted;
1085
+ }
1086
+ get bytes(): number {
1087
+ return this.#hlodBytes;
1088
+ }
1089
+ restoreSources(): void {
1090
+ for (const state of this.#cellProxies) this.restoreCellProxySource(state);
1091
+ }
1092
+ releaseMaterials(): void {
1093
+ for (const material of this.#proxyMaterials.values())
1094
+ this.#host.addFailures(release(material) ? 1 : 0);
1095
+ this.#proxyMaterials.clear();
1096
+ }
1097
+ stats() {
1098
+ return {
1099
+ on: this.#hlod,
1100
+ loaded: [...this.#cellProxies].filter(
1101
+ (state) => state.prepared !== undefined && !state.cancelled,
1102
+ ).length,
1103
+ compiled: [...this.#cellProxies].filter((state) => state.compiled && !state.cancelled).length,
1104
+ observed: [...this.#cellProxies].filter(
1105
+ (state) => this.#proxyObserved(state) && !state.cancelled,
1106
+ ).length,
1107
+ active: [...this.#cellProxies].filter((state) => state.active).length,
1108
+ pending: [...this.#cellProxies].filter(
1109
+ (state) =>
1110
+ state.pending ||
1111
+ state.compiling ||
1112
+ (!state.cancelled && !state.compiled && state.prepared !== undefined),
1113
+ ).length,
1114
+ bytes: this.#hlodBytes,
1115
+ refused: this.#hlodRefused,
1116
+ reason: this.#hlodReason,
1117
+ failures: this.#hlodFailures,
1118
+ };
1119
+ }
1120
+ evictProxy(cell: IResidentCell): void {
1121
+ if (cell.proxy !== undefined) {
1122
+ this.showCellProxy(cell.proxy, false);
1123
+ cell.proxy.cancelled = true;
1124
+ cell.proxy.prepared?.root.removeFromParent();
1125
+ if (!cell.proxy.pending && !cell.proxy.compiling) this.releaseCellProxy(cell.proxy);
1126
+ }
1127
+ }
1128
+ }
1129
+
1130
+ export function cellLoaded(cell: IResidentCell): boolean {
1131
+ return cell.chunksLoaded && cell.completedRuns.size === cell.cell.runs.length;
1132
+ }