@threenative/core 0.3.11 → 0.3.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1988 -204
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  5. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  6. package/dist/chunk-4SRAQFTU.js +133 -0
  7. package/dist/chunk-CFGTPFUH.js +231 -0
  8. package/dist/chunk-DIPIJICH.js +8916 -0
  9. package/dist/chunk-EEABDLUC.js +2237 -0
  10. package/dist/chunk-EFWZWLPY.js +1895 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-GYUZJQ7U.js +280 -0
  13. package/dist/chunk-H4J6IAJE.js +504 -0
  14. package/dist/chunk-KIRUKTBQ.js +187 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-SV4QVUTQ.js +31 -0
  17. package/dist/chunk-U4YHUKKL.js +615 -0
  18. package/dist/chunk-VP43GIWW.js +18 -0
  19. package/dist/chunk-XDTZ4QMO.js +160 -0
  20. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  21. package/dist/{game-DzMcitDO.d.ts → game-k8K3hZai.d.ts} +85 -9
  22. package/dist/hot.d.ts +5 -4
  23. package/dist/hot.js +5 -52
  24. package/dist/index.d.ts +633 -1351
  25. package/dist/index.js +12873 -23068
  26. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-DPTzeCcD.d.ts} +35 -3
  27. package/dist/playtest.d.ts +5 -4
  28. package/dist/playtest.js +25 -75
  29. package/dist/quality-BYqKGAwo.d.ts +868 -0
  30. package/dist/react-css.js +1 -215
  31. package/dist/react.d.ts +3 -2
  32. package/dist/render-environment.d.ts +170 -0
  33. package/dist/render-environment.js +352 -0
  34. package/dist/{renderer-rZm0hVqq.d.ts → renderer-BtOSseYf.d.ts} +42 -35
  35. package/dist/spells/index.d.ts +643 -0
  36. package/dist/spells/index.js +1558 -0
  37. package/dist/spells/ultra/index.d.ts +1600 -0
  38. package/dist/spells/ultra/index.js +6804 -0
  39. package/dist/terrain-jobs-worker.js +1 -123
  40. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  41. package/dist/ui-layer.js +6 -384
  42. package/dist/worker.js +13 -43
  43. package/dist/world.d.ts +988 -268
  44. package/dist/world.js +17464 -18290
  45. package/mcp/animation-server.mjs +1 -1
  46. package/mcp/animation.mjs +2 -3
  47. package/mcp/engine-server.mjs +245 -52
  48. package/mcp/servers.mjs +10 -3
  49. package/mcp/terrain.mjs +8 -0
  50. package/package.json +19 -7
  51. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  52. package/patches/three@0.187.0.patch +2004 -407
  53. package/src/animation-batch.ts +193 -0
  54. package/src/animation-layers.ts +7 -3
  55. package/src/animation.ts +209 -29
  56. package/src/asset-cache.ts +3 -3
  57. package/src/asset-memo.ts +202 -0
  58. package/src/assets.ts +437 -125
  59. package/src/auto-batch.ts +190 -44
  60. package/src/card-lod.ts +152 -0
  61. package/src/compressed-texture-preparation.ts +1008 -0
  62. package/src/compute-driven.ts +1 -1
  63. package/src/config.ts +8 -0
  64. package/src/debug.ts +103 -22
  65. package/src/dev-global.ts +54 -0
  66. package/src/engine-hooks.ts +37 -0
  67. package/src/frame-budget.ts +50 -23
  68. package/src/game-boot-phase.ts +269 -0
  69. package/src/game-dev-tools.ts +86 -0
  70. package/src/game-frame-loop.ts +958 -0
  71. package/src/game-renderer-metrics.ts +77 -0
  72. package/src/game-startup.ts +1076 -0
  73. package/src/game-ui.ts +84 -0
  74. package/src/game-validate.ts +70 -0
  75. package/src/game.ts +198 -2264
  76. package/src/gamepad-mappings.ts +269 -0
  77. package/src/generated/console-markers.ts +13 -0
  78. package/src/geometry-capture.ts +28 -4
  79. package/src/gpu-readings.ts +98 -0
  80. package/src/gpu-scene-bvh.ts +149 -36
  81. package/src/hot.ts +4 -7
  82. package/src/index.ts +141 -9
  83. package/src/input.ts +237 -25
  84. package/src/instanced-batch-lod.ts +3 -8
  85. package/src/interpolation.ts +171 -40
  86. package/src/launch-diagnostics.ts +22 -12
  87. package/src/look/ao-admission.ts +25 -0
  88. package/src/look/auto-exposure.ts +5 -16
  89. package/src/look/default-tone-mapping.ts +41 -5
  90. package/src/look/filmic-tone-mapping.ts +15 -13
  91. package/src/look/local-exposure.ts +2 -7
  92. package/src/look/look-diagnostics.ts +3 -3
  93. package/src/look/quad-pass.ts +21 -0
  94. package/src/look/quality.ts +14 -5
  95. package/src/look/unreal-bloom.ts +4 -13
  96. package/src/look/world-environment.ts +113 -103
  97. package/src/loop.ts +29 -0
  98. package/src/merge-parts.ts +20 -24
  99. package/src/model-lod.ts +139 -17
  100. package/src/particle-kinds.ts +515 -0
  101. package/src/particle-significance.ts +12 -0
  102. package/src/particles.ts +19 -10
  103. package/src/picking.ts +17 -3
  104. package/src/platform.ts +23 -4
  105. package/src/playtest.ts +27 -1
  106. package/src/profiling/FrameStages.ts +5 -6
  107. package/src/profiling/Spans.ts +3 -17
  108. package/src/profiling/debug-telemetry.ts +2 -6
  109. package/src/profiling/render-list-validate.ts +6 -15
  110. package/src/projection-apply.ts +4 -1
  111. package/src/projection-marker.ts +2 -1
  112. package/src/projection-plan.ts +9 -6
  113. package/src/quiet-markers.ts +3 -10
  114. package/src/render/cpu-bvh.ts +100 -0
  115. package/src/render/depth-pyramid.ts +6 -14
  116. package/src/render/environment/environmentContribution.ts +202 -0
  117. package/src/render/environment/environmentRadiance.ts +44 -0
  118. package/src/render/environment/environmentSampleCache.ts +56 -0
  119. package/src/render/environment/environmentSampling.ts +201 -0
  120. package/src/render/environment/environmentSnapshot.ts +71 -0
  121. package/src/render/environment/gate.ts +57 -0
  122. package/src/render/mesh-pool.ts +4 -20
  123. package/src/render/probe-trace.ts +872 -0
  124. package/src/render/probe-volume.ts +780 -34
  125. package/src/render/radiance-cache.ts +17 -0
  126. package/src/render/resolution-subrect.ts +2 -0
  127. package/src/render/rough-diffuse.ts +46 -12
  128. package/src/render/soft-shadow.ts +27 -12
  129. package/src/render/virtual-shadow-adaptive.ts +55 -0
  130. package/src/render/virtual-shadow-casters.ts +175 -0
  131. package/src/render/virtual-shadow-layers.ts +76 -0
  132. package/src/render/virtual-shadow-level.ts +224 -0
  133. package/src/render/virtual-shadow-markers.ts +193 -0
  134. package/src/render/virtual-shadow-options.ts +370 -0
  135. package/src/render/virtual-shadow-pages.ts +5 -0
  136. package/src/render/virtual-shadow-partial.ts +13 -0
  137. package/src/render/virtual-shadow.ts +231 -1008
  138. package/src/render/world-impostor-surface.ts +402 -40
  139. package/src/render/world-impostor.ts +5 -2
  140. package/src/render-camera-cull.ts +98 -3
  141. package/src/render-environment.ts +41 -0
  142. package/src/render-pass-budget.ts +34 -7
  143. package/src/renderProjection.ts +22 -0
  144. package/src/renderer-config.ts +36 -0
  145. package/src/renderer-facts.ts +37 -0
  146. package/src/renderer.ts +144 -65
  147. package/src/resolution-scaler.ts +3 -2
  148. package/src/scene-entry-inspectors.ts +61 -0
  149. package/src/snow-field.ts +2 -1
  150. package/src/spells/cast-pool.ts +361 -0
  151. package/src/spells/index.ts +177 -0
  152. package/src/spells/mechanisms.ts +295 -0
  153. package/src/spells/reaction-field.ts +415 -0
  154. package/src/spells/spell-lights.ts +139 -0
  155. package/src/spells/spell-world.ts +187 -0
  156. package/src/spells/spell.ts +397 -0
  157. package/src/spells/spells.ts +283 -0
  158. package/src/spells/ultra/engine/camera.ts +184 -0
  159. package/src/spells/ultra/engine/quality.ts +96 -0
  160. package/src/spells/ultra/index.ts +52 -0
  161. package/src/spells/ultra/main.ts +305 -0
  162. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  163. package/src/spells/ultra/spells/cast.ts +233 -0
  164. package/src/spells/ultra/spells/fire.ts +1267 -0
  165. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  166. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  167. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  168. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  169. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  170. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  171. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  172. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  173. package/src/spells/ultra/vfx/common.ts +1195 -0
  174. package/src/spells/ultra/vfx/noise.ts +441 -0
  175. package/src/startup-offscreen-bytes.ts +78 -0
  176. package/src/startup-readiness.ts +128 -34
  177. package/src/static-transform.ts +25 -19
  178. package/src/streamed-textures.ts +112 -0
  179. package/src/streaming.ts +68 -4
  180. package/src/texture-streaming.ts +331 -0
  181. package/src/version.ts +1 -1
  182. package/src/warmup.ts +56 -8
  183. package/src/water-surface.ts +9 -3
  184. package/src/worker.ts +12 -2
  185. package/src/world-bundle-safety.ts +446 -0
  186. package/src/world-cell-batches.ts +1178 -0
  187. package/src/world-cell-chunks.ts +1128 -0
  188. package/src/world-cell-data.ts +995 -0
  189. package/src/world-cell-impostors.ts +1461 -0
  190. package/src/world-cell-lod-bias.ts +151 -0
  191. package/src/world-cell-models.ts +1074 -0
  192. package/src/world-cell-options.ts +177 -0
  193. package/src/world-cell-placements.ts +798 -0
  194. package/src/world-cell-prewarm.ts +592 -0
  195. package/src/world-cell-readiness.ts +357 -0
  196. package/src/world-cell-records.ts +401 -0
  197. package/src/world-cell-render-bundles.ts +459 -0
  198. package/src/world-cell-render-gpu-dress.ts +710 -0
  199. package/src/world-cell-render-main-cull.ts +540 -0
  200. package/src/world-cell-render-shadow-claims.ts +198 -0
  201. package/src/world-cell-render-util.ts +259 -0
  202. package/src/world-cell-render.ts +1501 -0
  203. package/src/world-cell-residency.ts +754 -0
  204. package/src/world-cell-stale.ts +238 -0
  205. package/src/world-cells.ts +1335 -10418
  206. package/src/world-chunk-shadow.ts +308 -0
  207. package/src/world-collar.ts +315 -0
  208. package/src/world-gpu-flags.ts +131 -0
  209. package/src/world-gpu-readback.ts +881 -0
  210. package/src/world-gpu-reference.ts +524 -0
  211. package/src/world-gpu-scene.ts +256 -2286
  212. package/src/world-gpu-shadow.ts +203 -0
  213. package/src/world-gpu-types.ts +409 -0
  214. package/src/world-gpu-validation.ts +518 -0
  215. package/src/world-heightfield.ts +802 -0
  216. package/src/world-load-limiter.ts +111 -0
  217. package/src/world-model-sections.ts +80 -0
  218. package/src/world-noise.ts +241 -0
  219. package/src/world-package.ts +42 -0
  220. package/src/world-region.ts +1 -1
  221. package/src/world-river-ribbon.ts +282 -0
  222. package/src/world-root-frame.ts +39 -0
  223. package/src/world-shore-field.ts +91 -0
  224. package/src/world-static-pose.ts +163 -0
  225. package/src/world-surface-sampler.ts +48 -0
  226. package/src/world-terrain-splat.ts +361 -153
  227. package/src/world-tile-budget.ts +249 -0
  228. package/src/world-tile-geometry.ts +469 -0
  229. package/src/world-tile-lod.ts +408 -0
  230. package/src/world-tile-observation.ts +566 -0
  231. package/src/world-tile-stitch.ts +166 -0
  232. package/src/world-tiles.ts +247 -1755
  233. package/src/world-validate.ts +6 -14
  234. package/src/world-warm.ts +51 -0
  235. package/src/world-water-bodies.ts +359 -0
  236. package/src/world.ts +48 -741
@@ -1,10 +1,25 @@
1
+ import {
2
+ edgeVertexHeight,
3
+ edgeVertexIndex,
4
+ opposingEdge,
5
+ pushBridgeState,
6
+ pushLevelState,
7
+ renderedLevel,
8
+ sameState,
9
+ seamObservation,
10
+ seamState,
11
+ tileEdgeFrame,
12
+ validateBridgeTriangleTopology,
13
+ } from "./world-tile-observation.js";
14
+
1
15
  import {
2
16
  Box3,
3
- BufferAttribute,
17
+ type BufferAttribute,
4
18
  BufferGeometry,
5
19
  type Camera,
20
+ Frustum,
6
21
  LOD,
7
- type Matrix4,
22
+ Matrix4,
8
23
  Mesh,
9
24
  Object3D,
10
25
  Sphere,
@@ -16,8 +31,8 @@ import type { IComputeDriven } from "./compute-driven.js";
16
31
  import {
17
32
  type ILodView,
18
33
  type IModelLodPolicy,
19
- conservativeViewDepth,
20
34
  projectedLodError,
35
+ selectLodFor,
21
36
  selectLodLevel,
22
37
  worldSphere,
23
38
  } from "./model-lod.js";
@@ -35,16 +50,76 @@ import {
35
50
  createTerrainJobRunner,
36
51
  edgeWorldPoint,
37
52
  } from "./terrain-jobs.js";
38
- import { summarizeWorldTopology } from "./world-topology.js";
39
- import { terrainValidationRequested } from "./world-validate.js";
40
53
  import {
41
54
  Heightfield,
42
55
  type IHeightfieldOrigin,
43
56
  type IHeightfieldSamplerOptions,
44
57
  type IHeightfieldWorldPassOptions,
45
- } from "./world.js";
58
+ } from "./world-heightfield.js";
59
+ import {
60
+ CONSTRUCTION_CHUNK_SAMPLES,
61
+ EmptyCollider,
62
+ LOD_POP_THRESHOLD,
63
+ LOD_TRANSITION_FRAMES,
64
+ MAX_RAW_TOPOLOGY_SAMPLES,
65
+ TERRAIN_MERGE_BLOCK,
66
+ TERRAIN_TILE_MARKER_MS,
67
+ TerrainTileBudgetError,
68
+ blockCoordinates,
69
+ blockKeyFor,
70
+ estimatedLevelBytes,
71
+ estimatedTileBytes,
72
+ finite,
73
+ integerAtLeast,
74
+ keyFor,
75
+ lodLevelForDistance,
76
+ positive,
77
+ resolutionFor,
78
+ settleJob,
79
+ terrainMergeOptedOut,
80
+ timedSpan,
81
+ validateTopologyObservation,
82
+ } from "./world-tile-budget.js";
83
+ import { summarizeWorldTopology } from "./world-topology.js";
84
+ import { terrainValidationRequested } from "./world-validate.js";
46
85
 
47
- type MeshSurface = NonNullable<ConstructorParameters<typeof Mesh>[1]>;
86
+ export { TerrainTileBudgetError } from "./world-tile-budget.js";
87
+ // The four seams `world-tile-seams.spec.ts` pins stay reachable from this module so a consumer of the
88
+ // old path keeps working: they moved to the leaf modules with the code that reads them (PRD-797).
89
+ export { neighborPairs, neighborBridgeRequest } from "./world-tile-stitch.js";
90
+ export { interpolatedLevelHeight, surfaceDeltaFromSamples } from "./world-tile-lod.js";
91
+ import type { MeshSurface } from "./world-tile-geometry.js";
92
+ import {
93
+ buildLevel,
94
+ fieldHeightGrid,
95
+ geometryBytes,
96
+ mergeJob,
97
+ mergedBlockGeometry,
98
+ restoreLevelEdge,
99
+ restoreLevelSurface,
100
+ terrainMesh,
101
+ updateStitchBridge,
102
+ } from "./world-tile-geometry.js";
103
+ import {
104
+ buildLodMorphTargets,
105
+ coarsestSelectableLevel,
106
+ surfaceDeltaFromSamples,
107
+ surfaceHeights,
108
+ updateLodMorph,
109
+ updateLodTransitionGeometry,
110
+ widenLevelBoundsForBlend,
111
+ } from "./world-tile-lod.js";
112
+ import type { IStitchRequest } from "./world-tile-stitch.js";
113
+ import {
114
+ collectNeighborPairs,
115
+ coordinatedLevels,
116
+ hasPendingTarget,
117
+ neighborBridgeRequest,
118
+ neighborLodCorrection,
119
+ neighborPairKey,
120
+ newStitchBridge,
121
+ setManualLodLevel,
122
+ } from "./world-tile-stitch.js";
48
123
 
49
124
  export interface IWorldTileCollider {
50
125
  dispose(): void;
@@ -130,6 +205,24 @@ export interface IWorldTilesOptions {
130
205
  readonly residentByteBudget: number;
131
206
  readonly residentTileBudget: number;
132
207
  readonly sampleHeight: IHeightfieldSamplerOptions["sampleHeight"];
208
+ /** The ground's footprint in tile-local metres: a tile wholly outside it is never meshed (it only repeats the edge sample). */
209
+ readonly extent?: {
210
+ readonly maxX: number;
211
+ readonly maxZ: number;
212
+ readonly minX: number;
213
+ readonly minZ: number;
214
+ };
215
+ /**
216
+ * A region another surface already draws and collides, in tile-local metres: a tile wholly inside
217
+ * it is never meshed and gets no collider. A tile that only overlaps it is meshed whole; the game
218
+ * hides the overlap in its own surface.
219
+ */
220
+ readonly hole?: {
221
+ readonly maxX: number;
222
+ readonly maxZ: number;
223
+ readonly minX: number;
224
+ readonly minZ: number;
225
+ };
133
226
  /** How deep each edge skirt extends below its surface. Defaults to one tile width. */
134
227
  readonly skirtDepth?: number;
135
228
  /** Square tile neighborhood to consider around the followed point. Defaults to 1. */
@@ -162,7 +255,7 @@ export interface IWorldTilesOptions {
162
255
  readonly topologyObservation?: IWorldTilesTopologyObservation;
163
256
  }
164
257
 
165
- interface ILevelGeometry {
258
+ export interface ILevelGeometry {
166
259
  surfaceError: number;
167
260
  readonly edgeSamples: IEdgeSamples;
168
261
  geometry: BufferGeometry;
@@ -172,14 +265,14 @@ interface ILevelGeometry {
172
265
  readonly skirtVertexCount: number;
173
266
  }
174
267
 
175
- interface IEdgeSamples {
268
+ export interface IEdgeSamples {
176
269
  readonly east: Float32Array;
177
270
  readonly north: Float32Array;
178
271
  readonly south: Float32Array;
179
272
  readonly west: Float32Array;
180
273
  }
181
274
 
182
- interface IResidentTile extends Omit<IWorldTile, "lodLevel"> {
275
+ export interface IResidentTile extends Omit<IWorldTile, "lodLevel"> {
183
276
  readonly assetKey?: string;
184
277
  collider: IWorldTileCollider | undefined;
185
278
  readonly levels: readonly ILevelGeometry[];
@@ -192,14 +285,14 @@ interface IResidentTile extends Omit<IWorldTile, "lodLevel"> {
192
285
  readonly skirts: number;
193
286
  }
194
287
 
195
- interface ILodTransition {
288
+ export interface ILodTransition {
196
289
  readonly from: number;
197
290
  readonly to: number;
198
291
  elapsedFrames: number;
199
292
  remainingFrames: number;
200
293
  }
201
294
 
202
- interface IStitchBridge {
295
+ export interface IStitchBridge {
203
296
  readonly keys: readonly [string, string];
204
297
  geometry: BufferGeometry;
205
298
  readonly mesh: Mesh;
@@ -240,1739 +333,7 @@ interface ISeamObservation {
240
333
  seenPlain: number;
241
334
  }
242
335
 
243
- const MAX_RAW_TOPOLOGY_SAMPLES = 10_000;
244
- const LOD_POP_THRESHOLD = 16;
245
- const LOD_TRANSITION_FRAMES = 3;
246
- /** Maximum sampled vertices or quads in one terrain-construction admission unit. */
247
- const CONSTRUCTION_CHUNK_SAMPLES = 256;
248
- /** Tiles per side in a merged super-tile block. Small, because a block is culled as one object. */
249
- const TERRAIN_MERGE_BLOCK = 4;
250
- const TERRAIN_MERGE_FLAG = "TN_TERRAIN_MERGE";
251
- const TERRAIN_TILE_MARKER_MS = 5_000;
252
- const BRIDGE_COORDINATE_EPSILON = 1e-4;
253
-
254
- /**
255
- * Whether this launch asked for terrain tile merging to be turned off.
256
- *
257
- * The merge is on by default, so this only has to hear the three ways every other launch switch is
258
- * read: a native launch sets the environment variable, a browser asks with the query string, and a
259
- * test or harness sets the global. Only `0` and `false` count, so a URL that never mentioned the
260
- * switch — or one that still carries the `=1` that used to ask for the merge — stays on.
261
- */
262
- function terrainMergeOptedOut(): boolean {
263
- const host = globalThis as { process?: { env?: Record<string, unknown> } } & Record<
264
- string,
265
- unknown
266
- >;
267
- const fromEnv = host.process?.env?.[TERRAIN_MERGE_FLAG];
268
- if (fromEnv === "0" || fromEnv === "false") return true;
269
- const query = globalThis.location?.search;
270
- if (typeof query === "string" && /[?&]tnTerrainMerge=(?:0|false)(?:&|$)/u.test(query))
271
- return true;
272
- return (
273
- host.__tnTerrainMerge === false || host.__tnTerrainMerge === 0 || host.__tnTerrainMerge === "0"
274
- );
275
- }
276
-
277
- /** A block's key: its LOD tier and which K×K cell of the tile grid it covers. */
278
- function blockKeyFor(lod: number, tileX: number, tileZ: number): string {
279
- return `${String(lod)}:${String(Math.floor(tileX / TERRAIN_MERGE_BLOCK))},${String(
280
- Math.floor(tileZ / TERRAIN_MERGE_BLOCK),
281
- )}`;
282
- }
283
-
284
- function blockCoordinates(key: string): { lod: number; blockX: number; blockZ: number } {
285
- const separator = key.indexOf(":");
286
- const comma = key.indexOf(",", separator + 1);
287
- return {
288
- lod: Number(key.slice(0, separator)),
289
- blockX: Number(key.slice(separator + 1, comma)),
290
- blockZ: Number(key.slice(comma + 1)),
291
- };
292
- }
293
- const BRIDGE_COORDINATE_RELATIVE_EPSILON = 2 ** -22;
294
- const BRIDGE_STRIP_INDEX_PATTERN = [0, 1, 2, 2, 1, 3, 2, 1, 0, 3, 1, 2] as const;
295
- type PositionAttribute = BufferAttribute | InterleavedBufferAttribute;
296
-
297
- function bridgeCoordinateMatches(actual: number, expected: number): boolean {
298
- return (
299
- Math.abs(actual - expected) <=
300
- Math.max(
301
- BRIDGE_COORDINATE_EPSILON,
302
- Math.max(1, Math.abs(actual), Math.abs(expected)) * BRIDGE_COORDINATE_RELATIVE_EPSILON,
303
- )
304
- );
305
- }
306
-
307
- class EmptyCollider implements IWorldTileCollider {
308
- #disposed = false;
309
-
310
- get disposed(): boolean {
311
- return this.#disposed;
312
- }
313
-
314
- dispose(): void {
315
- this.#disposed = true;
316
- }
317
- }
318
-
319
- /**
320
- * The one throw a hard cap produces, so a caller composing `TerrainTiles` can tell "a tile no longer
321
- * fits" from a defect in game-owned input by `instanceof` rather than by a name any error can borrow.
322
- * Not re-exported from `world.ts`: the cap's condition is the caller's to absorb, not to handle.
323
- */
324
- export class TerrainTileBudgetError extends Error {
325
- constructor(message: string) {
326
- super(message);
327
- this.name = "TerrainTileBudgetError";
328
- }
329
- }
330
-
331
- function finite(value: number, name: string): number {
332
- if (!Number.isFinite(value)) throw new Error(`TerrainTiles ${name} must be finite.`);
333
- return value;
334
- }
335
-
336
- function positive(value: number, name: string): number {
337
- finite(value, name);
338
- if (value <= 0) throw new Error(`TerrainTiles ${name} must be greater than zero.`);
339
- return value;
340
- }
341
-
342
- function integerAtLeast(value: number, minimum: number, name: string): number {
343
- if (!Number.isInteger(value) || value < minimum)
344
- throw new Error(`TerrainTiles ${name} must be an integer of at least ${minimum}.`);
345
- return value;
346
- }
347
-
348
- function keyFor(tileX: number, tileZ: number): string {
349
- return `${String(tileX)}:${String(tileZ)}`;
350
- }
351
-
352
- function lodLevelForDistance(distance: number, thresholds: readonly number[]): number {
353
- let level = 0;
354
- for (const threshold of thresholds) {
355
- if (distance < threshold) break;
356
- level += 1;
357
- }
358
- return level;
359
- }
360
-
361
- function resolutionFor(tileResolution: number, factor: number): number {
362
- const cells = (tileResolution - 1) / factor;
363
- if (!Number.isInteger(cells))
364
- throw new Error("TerrainTiles tileResolution minus one must divide every lod factor.");
365
- return cells + 1;
366
- }
367
-
368
- function morphBytes(resolution: number, targets: number): number {
369
- const vertices = resolution * resolution + resolution * 4;
370
- // Stock Three packs both vec3 deltas into RGBA32F: retain its CPU texture and GPU copy too.
371
- const texels = vertices * 2;
372
- // Any row width pads to < 2 * texels; admission precedes renderer-limit discovery.
373
- const packedTexels = texels * 2;
374
- return targets * (vertices * 3 * 4 * 2 + packedTexels * 4 * 4 * 2);
375
- }
376
-
377
- function estimatedLevelBytes(resolution: number, targets = 0): number {
378
- const vertices = resolution * resolution + resolution * 4;
379
- const triangles = (resolution - 1) * (resolution - 1) + (resolution - 1) * 4;
380
- const edgeSampleBytes = resolution * 4 * Float32Array.BYTES_PER_ELEMENT;
381
- return (
382
- vertices * 3 * Float32Array.BYTES_PER_ELEMENT * 2 +
383
- triangles * 6 * Uint32Array.BYTES_PER_ELEMENT +
384
- edgeSampleBytes +
385
- morphBytes(resolution, targets)
386
- );
387
- }
388
-
389
- function estimatedFieldBytes(
390
- tileResolution: number,
391
- worldPasses: IHeightfieldWorldPassOptions | undefined,
392
- ): number {
393
- const sampleBytes = tileResolution * tileResolution * Float32Array.BYTES_PER_ELEMENT;
394
- if (worldPasses === undefined) return sampleBytes * 2;
395
- // The GPU path retains the canonical/collider values plus several ping-pong storage buffers.
396
- // Admission is deliberately conservative so backend allocation overhead cannot break the cap.
397
- return sampleBytes * (worldPasses.gpu === false ? 4 : 24);
398
- }
399
-
400
- function estimatedTileBytes(
401
- tileResolution: number,
402
- factors: readonly number[],
403
- worldPasses: IHeightfieldWorldPassOptions | undefined,
404
- validate: boolean,
405
- ): number {
406
- return factors.reduce(
407
- (total, factor) =>
408
- total +
409
- estimatedLevelBytes(
410
- resolutionFor(tileResolution, factor),
411
- validate ? 0 : factors.filter((candidate) => candidate >= factor).length - 1,
412
- ),
413
- estimatedFieldBytes(tileResolution, worldPasses),
414
- );
415
- }
416
-
417
- function tiledObservationResolution(
418
- extent: number,
419
- tileSize: number,
420
- tileResolution: number,
421
- axis: string,
422
- ): number {
423
- const tileCount = extent / tileSize;
424
- if (!Number.isInteger(tileCount) || tileCount < 1)
425
- throw new Error(
426
- `TerrainTiles topologyObservation ${axis} must cover a positive whole number of rendered tiles.`,
427
- );
428
- return tileCount * (tileResolution - 1) + 1;
429
- }
430
-
431
- function validateTopologyObservation(
432
- observation: IWorldTilesTopologyObservation,
433
- tileSize: number,
434
- tileResolution: number,
435
- ): void {
436
- const expectedColumns = tiledObservationResolution(
437
- observation.width,
438
- tileSize,
439
- tileResolution,
440
- "width",
441
- );
442
- const expectedRows = tiledObservationResolution(
443
- observation.depth,
444
- tileSize,
445
- tileResolution,
446
- "depth",
447
- );
448
- if (observation.columns !== expectedColumns)
449
- throw new Error(
450
- `TerrainTiles topologyObservation columns must match the rendered tile grid (expected ${String(expectedColumns)}, received ${String(observation.columns)}).`,
451
- );
452
- if (observation.rows !== expectedRows)
453
- throw new Error(
454
- `TerrainTiles topologyObservation rows must match the rendered tile grid (expected ${String(expectedRows)}, received ${String(observation.rows)}).`,
455
- );
456
- }
457
-
458
- function edgeSamplesFor(values: readonly number[], resolution: number): IEdgeSamples {
459
- const north = new Float32Array(resolution);
460
- const south = new Float32Array(resolution);
461
- const west = new Float32Array(resolution);
462
- const east = new Float32Array(resolution);
463
- for (let index = 0; index < resolution; index += 1) {
464
- north[index] = values[index] as number;
465
- south[index] = values[(resolution - 1) * resolution + index] as number;
466
- west[index] = values[index * resolution] as number;
467
- east[index] = values[index * resolution + resolution - 1] as number;
468
- }
469
- return { east, north, south, west };
470
- }
471
-
472
- /** One field's own rectangle and side, which is all a world point along an edge needs. */
473
- function tileEdgeFrame(field: Heightfield, side: keyof IEdgeSamples): ITerrainEdgeFrame {
474
- return { depth: field.depth, origin: field.origin, side, width: field.width };
475
- }
476
-
477
- /**
478
- * Apply a job's result, whenever it arrives. An inline host resolves inside the call, so the caller
479
- * keeps the synchronous shape it always had; a worker host applies in its reply. A reply that throws
480
- * rejects the promise instead of returning, so a budget overflow off this thread is a loud failure
481
- * rather than a swallowed one.
482
- */
483
- function settleJob<T>(result: T | Promise<T>, apply: (value: T) => void): void {
484
- if (result instanceof Promise) result.then(apply);
485
- else apply(result);
486
- }
487
-
488
- /**
489
- * Runs one unit of main-thread terrain work and charges it to a frame span.
490
- *
491
- * Added, not bracketed: a worker host's block swap arrives in a job reply and an inline host's runs
492
- * inside the same `follow`, so `begin`/`end` at both call sites would nest and count one unit twice.
493
- * `addSpan` accumulates whatever runs on this thread with no nesting to get wrong, and costs one
494
- * guarded return when spans are off — no clock read, no allocation. The frame-span table's
495
- * `TN_FRAME_SPANS` report is where the number surfaces; nothing here decides anything.
496
- */
497
- function timedSpan<T>(id: SpanId, run: () => T): T {
498
- if (spanRecorder() === undefined) return run();
499
- const start = spanNow();
500
- try {
501
- return run();
502
- } finally {
503
- addSpan(id, spanNow() - start);
504
- }
505
- }
506
-
507
- function edgeVertexIndex(level: ILevelGeometry, side: keyof IEdgeSamples, index: number): number {
508
- const row = side === "north" ? 0 : side === "south" ? level.resolution - 1 : index;
509
- const column = side === "west" ? 0 : side === "east" ? level.resolution - 1 : index;
510
- return row * level.resolution + column;
511
- }
512
-
513
- function appendQuad(
514
- indices: number[],
515
- topLeft: number,
516
- bottomLeft: number,
517
- topRight: number,
518
- bottomRight: number,
519
- ): void {
520
- indices.push(topLeft, bottomLeft, topRight, topRight, bottomLeft, bottomRight);
521
- }
522
-
523
- /**
524
- * The field's own sample heights, once, with a ring of clamped neighbours around them.
525
- *
526
- * `normalAt` reads the height at the point and at its four field-cell neighbours, so a level built
527
- * vertex by vertex asked the field six times per vertex — 33,800 `heightAt` calls for a 65x65 tile
528
- * and every coarser level with it (46 ms + 46 ms a streaming frame). This is the same set of samples
529
- * read once, and the ring repeats the edge sample, which is exactly the clamp `normalAt` applies at
530
- * the field's own border. One grid serves every level of the tile, because a level's vertices are
531
- * every `lodFactor`-th of the field's.
532
- */
533
- function* fieldHeightGrid(field: Heightfield, chunked: boolean): Generator<void, Float32Array> {
534
- const columns = field.columns + 2;
535
- const cellWidth = field.width / (field.columns - 1);
536
- const cellDepth = field.depth / (field.rows - 1);
537
- const minimumX = field.origin.x - field.width / 2;
538
- const minimumZ = field.origin.z - field.depth / 2;
539
- const grid = new Float32Array(columns * (field.rows + 2));
540
- for (let row = 0; row < field.rows + 2; row += 1) {
541
- const z = minimumZ + Math.min(field.rows - 1, Math.max(0, row - 1)) * cellDepth;
542
- for (let column = 0; column < columns; column += 1) {
543
- const x = minimumX + Math.min(field.columns - 1, Math.max(0, column - 1)) * cellWidth;
544
- grid[row * columns + column] = field.heightAt(x, z);
545
- if (chunked && (row * columns + column + 1) % CONSTRUCTION_CHUNK_SAMPLES === 0) yield;
546
- }
547
- }
548
- return grid;
549
- }
550
-
551
- /**
552
- * How many field samples a level's vertices are apart. An integer by `resolutionFor`'s own check,
553
- * and the reason one grid serves every level: vertex column `n` sits on field sample `n * step`.
554
- */
555
- function fieldStep(field: Heightfield, resolution: number): number {
556
- const step = (field.columns - 1) / (resolution - 1);
557
- if (!Number.isInteger(step) || step < 1)
558
- throw new Error("TerrainTiles level vertices must land on the field's own sample grid.");
559
- return step;
560
- }
561
-
562
- /**
563
- * Tags a mesh as terrain, so the frame budget counts its main-pass draw under `terrain` instead of
564
- * under the `other` every mesh no world system claimed lands in. Every mesh this file creates goes
565
- * through here — a tile level, a stitch bridge and a merged block — because a source that is tagged
566
- * at three of the four places it exists is a split nobody can reconcile.
567
- */
568
- function terrainMesh(mesh: Mesh): Mesh {
569
- mesh.userData.tnDrawSource = "terrain";
570
- // Visibility only swaps this mesh with a twin over the same ground (its merged block, or the
571
- // neighbouring LOD level), so a cached shadow map need not redraw for it; see `casterFlag`.
572
- mesh.userData.tnShadowSwap = true;
573
- return mesh;
574
- }
575
-
576
- /** Three's box/sphere arithmetic, over the same float32 positions, in admission-sized scans. */
577
- function* levelBounds(
578
- positions: Float32Array,
579
- chunked: boolean,
580
- ): Generator<void, { box: Box3; sphere: Sphere }> {
581
- const box = new Box3();
582
- const point = new Vector3();
583
- for (let index = 0; index < positions.length; index += 3) {
584
- point.fromArray(positions, index);
585
- box.expandByPoint(point);
586
- if (chunked && (index / 3 + 1) % CONSTRUCTION_CHUNK_SAMPLES === 0) yield;
587
- }
588
- const sphere = new Sphere();
589
- box.getCenter(sphere.center);
590
- let radiusSquared = 0;
591
- for (let index = 0; index < positions.length; index += 3) {
592
- point.fromArray(positions, index);
593
- radiusSquared = Math.max(radiusSquared, sphere.center.distanceToSquared(point));
594
- if (chunked && (index / 3 + 1) % CONSTRUCTION_CHUNK_SAMPLES === 0) yield;
595
- }
596
- sphere.radius = Math.sqrt(radiusSquared);
597
- return { box, sphere };
598
- }
599
-
600
- function* buildLevel(
601
- field: Heightfield,
602
- resolution: number,
603
- skirtDepth: number,
604
- surface: MeshSurface,
605
- grid: Float32Array,
606
- chunked: boolean,
607
- ): Generator<void, ILevelGeometry> {
608
- const positions: number[] = [];
609
- const normals: number[] = [];
610
- const heights: number[] = [];
611
- const minimumX = field.origin.x - field.width / 2;
612
- const minimumZ = field.origin.z - field.depth / 2;
613
- const cellWidth = field.width / (resolution - 1);
614
- const cellDepth = field.depth / (resolution - 1);
615
- const fieldCellWidth = field.width / (field.columns - 1);
616
- const fieldCellDepth = field.depth / (field.rows - 1);
617
- const gridColumns = field.columns + 2;
618
- const step = fieldStep(field, resolution);
619
- const normal = new Vector3();
620
- for (let row = 0; row < resolution; row += 1) {
621
- const z = minimumZ + row * cellDepth;
622
- const fieldRow = row * step;
623
- const gridRow = fieldRow + 1;
624
- for (let column = 0; column < resolution; column += 1) {
625
- const x = minimumX + column * cellWidth;
626
- const fieldColumn = column * step;
627
- const at = gridRow * gridColumns + fieldColumn + 1;
628
- const height = grid[at] as number;
629
- heights.push(height);
630
- positions.push(x - field.origin.x, height, z - field.origin.z);
631
- // `normalAt`'s stencil, off the same grid: a field cell either side, clamped at the border,
632
- // over the distance those two samples really are apart.
633
- const column0 = Math.min(field.columns - 1, Math.max(0, fieldColumn - 1));
634
- const column1 = Math.min(field.columns - 1, fieldColumn + 1);
635
- const row0 = Math.min(field.rows - 1, Math.max(0, fieldRow - 1));
636
- const row1 = Math.min(field.rows - 1, fieldRow + 1);
637
- const slopeX =
638
- ((grid[gridRow * gridColumns + column1 + 1] as number) -
639
- (grid[gridRow * gridColumns + column0 + 1] as number)) /
640
- ((column1 - column0) * fieldCellWidth);
641
- const slopeZ =
642
- ((grid[(row1 + 1) * gridColumns + fieldColumn + 1] as number) -
643
- (grid[(row0 + 1) * gridColumns + fieldColumn + 1] as number)) /
644
- ((row1 - row0) * fieldCellDepth);
645
- normal.set(-slopeX, 1, -slopeZ).normalize();
646
- normals.push(normal.x, normal.y, normal.z);
647
- if (chunked && (row * resolution + column + 1) % CONSTRUCTION_CHUNK_SAMPLES === 0) yield;
648
- }
649
- }
650
- const indices: number[] = [];
651
- for (let row = 0; row < resolution - 1; row += 1) {
652
- for (let column = 0; column < resolution - 1; column += 1) {
653
- const topLeft = row * resolution + column;
654
- appendQuad(indices, topLeft, topLeft + resolution, topLeft + 1, topLeft + resolution + 1);
655
- if (chunked && (row * (resolution - 1) + column + 1) % CONSTRUCTION_CHUNK_SAMPLES === 0)
656
- yield;
657
- }
658
- }
659
-
660
- const edges = [
661
- (index: number) => index,
662
- (index: number) => (resolution - 1) * resolution + index,
663
- (index: number) => index * resolution,
664
- (index: number) => index * resolution + resolution - 1,
665
- ];
666
- for (const edge of edges) {
667
- const bottom = positions.length / 3;
668
- for (let index = 0; index < resolution; index += 1) {
669
- const top = edge(index);
670
- positions.push(
671
- positions[top * 3] as number,
672
- (positions[top * 3 + 1] as number) - skirtDepth,
673
- positions[top * 3 + 2] as number,
674
- );
675
- normals.push(0, 1, 0);
676
- }
677
- for (let index = 0; index < resolution - 1; index += 1) {
678
- const topLeft = edge(index);
679
- const topRight = edge(index + 1);
680
- appendQuad(indices, topLeft, bottom + index, topRight, bottom + index + 1);
681
- }
682
- }
683
-
684
- const positionArray = Float32Array.from(positions);
685
- const bounds = yield* levelBounds(positionArray, chunked);
686
- const geometry = new BufferGeometry();
687
- geometry.morphTargetsRelative = true;
688
- geometry.setAttribute("position", new BufferAttribute(positionArray, 3));
689
- geometry.setAttribute("normal", new BufferAttribute(Float32Array.from(normals), 3));
690
- geometry.setIndex(new BufferAttribute(Uint32Array.from(indices), 1));
691
- geometry.boundingBox = bounds.box;
692
- geometry.boundingSphere = bounds.sphere;
693
- const skirt = inspectSkirtGeometry(geometry, resolution, edges);
694
- return {
695
- surfaceError: 0,
696
- edgeSamples: edgeSamplesFor(heights, resolution),
697
- geometry,
698
- mesh: terrainMesh(new Mesh(geometry, surface)),
699
- resolution,
700
- skirtDepth: skirt.depth,
701
- skirtVertexCount: skirt.vertexCount,
702
- };
703
- }
704
-
705
- /**
706
- * A block's merged attributes, as the geometry the main thread swaps in. The concatenation itself
707
- * is `mergeBlockAttributes`, which runs in a worker wherever a host has one; this is the part that
708
- * cannot leave the main thread — a `BufferGeometry` and its bounds.
709
- */
710
- function mergedBlockGeometry(result: ITerrainMergeResult): BufferGeometry {
711
- const geometry = new BufferGeometry();
712
- geometry.setAttribute("position", new BufferAttribute(result.positions, 3));
713
- geometry.setAttribute("normal", new BufferAttribute(result.normals, 3));
714
- geometry.setIndex(new BufferAttribute(result.indices, 1));
715
- geometry.computeBoundingBox();
716
- geometry.computeBoundingSphere();
717
- return geometry;
718
- }
719
-
720
- /** One settled tile level's attributes, as the merge job reads them. */
721
- function mergeJob(
722
- parts: readonly { readonly geometry: BufferGeometry; readonly origin: IHeightfieldOrigin }[],
723
- blockOrigin: IHeightfieldOrigin,
724
- ): ITerrainMergeJob {
725
- return {
726
- blockOrigin,
727
- kind: "merge",
728
- parts: parts.map(({ geometry, origin }) => {
729
- const index = geometry.getIndex();
730
- if (index === null)
731
- throw new Error("TerrainTiles merged block geometry needs an index buffer.");
732
- return {
733
- indices: index.array as Uint32Array,
734
- normals: (geometry.getAttribute("normal") as BufferAttribute).array as Float32Array,
735
- origin,
736
- positions: (geometry.getAttribute("position") as BufferAttribute).array as Float32Array,
737
- };
738
- }),
739
- };
740
- }
741
-
742
- function inspectSkirtGeometry(
743
- geometry: BufferGeometry,
744
- resolution: number,
745
- edges: readonly ((index: number) => number)[],
746
- ): { depth: number; vertexCount: number } {
747
- const position = geometry.getAttribute("position");
748
- const surfaceVertexCount = resolution * resolution;
749
- const vertexCount = position.count - surfaceVertexCount;
750
- if (vertexCount < 0 || vertexCount % edges.length !== 0)
751
- throw new Error("TerrainTiles generated skirt geometry has an invalid vertex count.");
752
- if (vertexCount === 0) return { depth: 0, vertexCount: 0 };
753
- const edgeVertexCount = vertexCount / edges.length;
754
- let depth = Number.POSITIVE_INFINITY;
755
- for (const [edgeIndex, edge] of edges.entries()) {
756
- for (let index = 0; index < edgeVertexCount; index += 1) {
757
- const top = edge(index);
758
- const bottom = surfaceVertexCount + edgeIndex * edgeVertexCount + index;
759
- depth = Math.min(depth, position.getY(top) - position.getY(bottom));
760
- }
761
- }
762
- if (!Number.isFinite(depth) || depth < 0)
763
- throw new Error("TerrainTiles generated skirt geometry has an invalid depth.");
764
- return { depth, vertexCount };
765
- }
766
-
767
- function opposingEdge(
768
- a: IResidentTile,
769
- b: IResidentTile,
770
- ): [keyof IEdgeSamples, keyof IEdgeSamples] {
771
- if (a.tileX < b.tileX) return ["east", "west"];
772
- if (a.tileX > b.tileX) return ["west", "east"];
773
- if (a.tileZ < b.tileZ) return ["south", "north"];
774
- return ["north", "south"];
775
- }
776
-
777
- function renderedLevel(tile: IResidentTile): ILevelGeometry | undefined {
778
- return tile.levels.find(({ mesh }) => mesh.visible) ?? tile.levels[tile.lodLevel];
779
- }
780
-
781
- /**
782
- * An attribute's vertex count while every component it draws is finite, `NaN` once one is not.
783
- * Every writer this package owns goes through `needsUpdate`, which bumps `version`, so a version
784
- * alone cannot see a writer that reached past the attribute — and `NaN` never compares equal to the
785
- * finite state the last reconcile recorded, so a settled seam still fails closed on it. The scan is
786
- * the cost of that, against the per-sample walk it keeps off a settled frame, so it is validation:
787
- * with `validate` off the count alone is compared, and a writer that reached past `needsUpdate`
788
- * leaves a geometry the next reconcile reads the same way it always did.
789
- */
790
- function positionFingerprint(position: BufferAttribute | undefined, validate: boolean): number {
791
- if (position === undefined) return -1;
792
- if (!validate) return position.count;
793
- const values = position.array;
794
- for (let index = 0; index < values.length; index += 1)
795
- if (!Number.isFinite(values[index])) return Number.NaN;
796
- return position.count;
797
- }
798
-
799
- /**
800
- * What a pair's seam was reconciled against: each side's rendered level, its buffers and where its
801
- * mesh sits. Every writer to a level sets `needsUpdate`, which bumps the version, so an unchanged
802
- * state means neither facing edge can have moved since — and an edge is sampled through
803
- * `level.mesh.matrixWorld`, so a level mesh moved from outside changed what the observation reads
804
- * without touching a single version. Its own transform is what that matrix composes from, and it is
805
- * what any outside writer moves: an ancestor of it is either the tiles group, whose own movement the
806
- * bridge state already observes, or the LOD this package owns and never moves, and a seam exists
807
- * only where a bridge is. Numbers, not a string, and pushed rather than returned: this runs for
808
- * every resident pair every frame (544 pairs on a 289-tile ring) into a reused buffer, and the
809
- * intermediate array per level and per bridge was itself the cost the settled ring was measured on.
810
- */
811
- function pushLevelState(state: number[], level: ILevelGeometry): void {
812
- const geometry = level.geometry;
813
- const { mesh } = level;
814
- state.push(
815
- geometry.id,
816
- (geometry.getAttribute("position") as BufferAttribute).version,
817
- (geometry.getAttribute("normal") as BufferAttribute).version,
818
- mesh.position.x,
819
- mesh.position.y,
820
- mesh.position.z,
821
- mesh.quaternion.x,
822
- mesh.quaternion.y,
823
- mesh.quaternion.z,
824
- mesh.quaternion.w,
825
- mesh.scale.x,
826
- mesh.scale.y,
827
- mesh.scale.z,
828
- );
829
- }
830
-
831
- /** Whether both sides of a pair have a rendered level, which is what its state needs to exist. */
832
- function pushPairState(state: number[], pair: NeighborPair): boolean {
833
- const aLevel = renderedLevel(pair[0]);
834
- const bLevel = renderedLevel(pair[1]);
835
- if (aLevel === undefined || bLevel === undefined) return false;
836
- pushLevelState(state, aLevel);
837
- pushLevelState(state, bLevel);
838
- return true;
839
- }
840
-
841
- /**
842
- * Everything a seam observation reads: the pair's state plus the bridge's placement, parent, draw
843
- * range and buffers. A diagnostic exists to catch a bridge moved, detached, emptied or rewritten,
844
- * so each of those has to change this state and force a fresh observation.
845
- */
846
- function pushBridgeState(state: number[], bridge: IStitchBridge, validate: boolean): void {
847
- const { mesh } = bridge;
848
- // The mesh's own geometry rather than the record's: a bridge retargeted to foreign geometry reads
849
- // perfectly well from the record, and `bridgeCoverageContext` is the only thing that rejects it.
850
- const geometry = mesh.geometry;
851
- const position = geometry.getAttribute("position") as BufferAttribute | undefined;
852
- const normal = geometry.getAttribute("normal") as BufferAttribute | undefined;
853
- const index = geometry.getIndex();
854
- mesh.updateMatrixWorld();
855
- state.push(mesh.id, mesh.parent?.id ?? -1, mesh.visible ? 1 : 0);
856
- const elements = mesh.matrixWorld.elements;
857
- for (let element = 0; element < elements.length; element += 1)
858
- state.push(elements[element] as number);
859
- state.push(
860
- geometry.id,
861
- position?.version ?? -1,
862
- positionFingerprint(position, validate),
863
- normal?.id ?? -1,
864
- index?.id ?? -1,
865
- index?.version ?? -1,
866
- geometry.drawRange.start,
867
- geometry.drawRange.count,
868
- );
869
- }
870
-
871
- function seamState(
872
- pair: NeighborPair,
873
- bridge: IStitchBridge | undefined,
874
- validate: boolean,
875
- ): number[] | undefined {
876
- const state: number[] = [];
877
- if (!pushPairState(state, pair)) return undefined;
878
- if (bridge !== undefined) pushBridgeState(state, bridge, validate);
879
- return state;
880
- }
881
-
882
- function sameState(a: readonly number[] | undefined, b: readonly number[] | undefined): boolean {
883
- if (a === undefined || b === undefined || a.length !== b.length) return false;
884
- for (let index = 0; index < a.length; index += 1) if (a[index] !== b[index]) return false;
885
- return true;
886
- }
887
-
888
- function edgeVertexHeight(level: ILevelGeometry, side: keyof IEdgeSamples, index: number): number {
889
- const value = level.geometry.getAttribute("position").getY(edgeVertexIndex(level, side, index));
890
- if (!Number.isFinite(value))
891
- throw new Error("TerrainTiles seam diagnostic edge height must be finite.");
892
- return value;
893
- }
894
-
895
- function edgeWorldVertexHeight(
896
- level: ILevelGeometry,
897
- side: keyof IEdgeSamples,
898
- index: number,
899
- target: Vector3,
900
- ): number {
901
- const position = level.geometry.getAttribute("position");
902
- const vertex = edgeVertexIndex(level, side, index);
903
- const localX = position.getX(vertex);
904
- const localY = position.getY(vertex);
905
- const localZ = position.getZ(vertex);
906
- if (!Number.isFinite(localX) || !Number.isFinite(localY) || !Number.isFinite(localZ))
907
- throw new Error("TerrainTiles seam diagnostic bridge coordinates must be finite.");
908
- target.set(localX, localY, localZ).applyMatrix4(level.mesh.matrixWorld);
909
- if (!Number.isFinite(target.x) || !Number.isFinite(target.y) || !Number.isFinite(target.z))
910
- throw new Error("TerrainTiles seam diagnostic bridge world coordinates must be finite.");
911
- return target.y;
912
- }
913
-
914
- function edgeWorldHeight(
915
- level: ILevelGeometry,
916
- side: keyof IEdgeSamples,
917
- normalized: number,
918
- target: Vector3,
919
- ): number {
920
- const position = Math.max(0, Math.min(1, normalized)) * (level.resolution - 1);
921
- const lower = Math.floor(position);
922
- const upper = Math.min(level.resolution - 1, lower + 1);
923
- const mix = position - lower;
924
- return (
925
- edgeWorldVertexHeight(level, side, lower, target) * (1 - mix) +
926
- edgeWorldVertexHeight(level, side, upper, target) * mix
927
- );
928
- }
929
-
930
- function bridgeEndpointWorldHeight(
931
- position: PositionAttribute,
932
- matrixWorld: Matrix4,
933
- vertex: number,
934
- expectedX: number,
935
- expectedY: number,
936
- expectedZ: number,
937
- worldPosition: Vector3,
938
- ): number {
939
- const localX = position.getX(vertex);
940
- const localY = position.getY(vertex);
941
- const localZ = position.getZ(vertex);
942
- if (!Number.isFinite(localX) || !Number.isFinite(localY) || !Number.isFinite(localZ))
943
- throw new Error("TerrainTiles seam diagnostic bridge coordinates must be finite.");
944
- worldPosition.set(localX, localY, localZ).applyMatrix4(matrixWorld);
945
- if (
946
- !Number.isFinite(worldPosition.x) ||
947
- !Number.isFinite(worldPosition.y) ||
948
- !Number.isFinite(worldPosition.z)
949
- )
950
- throw new Error("TerrainTiles seam diagnostic bridge world coordinates must be finite.");
951
- if (
952
- !Number.isFinite(expectedX) ||
953
- !Number.isFinite(expectedY) ||
954
- !Number.isFinite(expectedZ) ||
955
- !bridgeCoordinateMatches(worldPosition.x, expectedX) ||
956
- !bridgeCoordinateMatches(worldPosition.y, expectedY) ||
957
- !bridgeCoordinateMatches(worldPosition.z, expectedZ)
958
- )
959
- throw new Error(
960
- "TerrainTiles seam diagnostic bridge topology does not match current neighboring edges.",
961
- );
962
- return worldPosition.y;
963
- }
964
-
965
- function bridgeEndpointHeight(
966
- bridge: IStitchBridge,
967
- position: PositionAttribute,
968
- sample: number,
969
- endpoint: number,
970
- tile: IResidentTile,
971
- side: keyof IEdgeSamples,
972
- level: ILevelGeometry,
973
- worldPosition: Vector3,
974
- expectedWorldPosition: Vector3,
975
- ): number {
976
- const sampleNormalized = sample / (bridge.resolution - 1);
977
- const [expectedX, , expectedZ] = edgeWorldPoint(
978
- tileEdgeFrame(tile.field, side),
979
- sampleNormalized,
980
- 0,
981
- );
982
- const expectedY = edgeWorldHeight(level, side, sampleNormalized, expectedWorldPosition);
983
- return bridgeEndpointWorldHeight(
984
- position,
985
- bridge.mesh.matrixWorld,
986
- sample * 2 + endpoint,
987
- expectedX,
988
- expectedY,
989
- expectedZ,
990
- worldPosition,
991
- );
992
- }
993
-
994
- interface IBridgeEndpoint {
995
- readonly level: ILevelGeometry;
996
- readonly side: keyof IEdgeSamples;
997
- readonly tile: IResidentTile;
998
- }
999
-
1000
- function bridgeEndpointPair(
1001
- a: IResidentTile,
1002
- aSide: keyof IEdgeSamples,
1003
- b: IResidentTile,
1004
- bSide: keyof IEdgeSamples,
1005
- ): readonly [IBridgeEndpoint, IBridgeEndpoint] {
1006
- const aLevel = renderedLevel(a);
1007
- const bLevel = renderedLevel(b);
1008
- if (aLevel === undefined || bLevel === undefined)
1009
- throw new Error(
1010
- "TerrainTiles seam diagnostic bridge topology has no rendered neighboring edge.",
1011
- );
1012
- const aEndpoint = { level: aLevel, side: aSide, tile: a };
1013
- const bEndpoint = { level: bLevel, side: bSide, tile: b };
1014
- return aLevel.resolution > bLevel.resolution ? [aEndpoint, bEndpoint] : [bEndpoint, aEndpoint];
1015
- }
1016
-
1017
- function refreshEdgeSamples(level: ILevelGeometry): void {
1018
- for (const side of ["east", "north", "south", "west"] as const) {
1019
- const samples = level.edgeSamples[side];
1020
- for (let index = 0; index < level.resolution; index += 1)
1021
- samples[index] = edgeVertexHeight(level, side, index);
1022
- }
1023
- }
1024
-
1025
- /**
1026
- * A level mid-blend already carries the union of both levels' bounds, widened once when the
1027
- * transition started, and the canonical edge this writes is inside it. So the blend's three frames
1028
- * restore the edge and leave the bounds alone: recomputing them walked the level's ~4,500
1029
- * positions per seam per frame, which is the `setFromBufferAttribute` + `computeBoundingSphere` +
1030
- * `computeBoundingBox` + `expandByPoint` the six-second walk spent inside a transition.
1031
- */
1032
- function restoreLevelEdge(
1033
- tile: IResidentTile,
1034
- level: ILevelGeometry,
1035
- side: keyof IEdgeSamples,
1036
- ): boolean {
1037
- const field = tile.field;
1038
- const position = level.geometry.getAttribute("position");
1039
- const normalAttribute = level.geometry.getAttribute("normal");
1040
- const normal = new Vector3();
1041
- const frame = tileEdgeFrame(field, side);
1042
- let changed = false;
1043
- for (let index = 0; index < level.resolution; index += 1) {
1044
- const normalized = index / (level.resolution - 1);
1045
- const [x, , z] = edgeWorldPoint(frame, normalized, 0);
1046
- const vertex = edgeVertexIndex(level, side, index);
1047
- // Compared at float32, the precision the attributes store: a float64 sample never equals its
1048
- // stored copy, so an exact compare reported every edge changed on every call and recomputed
1049
- // the whole tile's bounds per seam per frame (~39 ms/frame on a 25-tile ring).
1050
- const height = Math.fround(field.heightAt(x, z));
1051
- field.normalAt(x, z, normal);
1052
- if (position.getY(vertex) !== height) {
1053
- position.setY(vertex, height);
1054
- changed = true;
1055
- }
1056
- if (
1057
- normalAttribute.getX(vertex) !== Math.fround(normal.x) ||
1058
- normalAttribute.getY(vertex) !== Math.fround(normal.y) ||
1059
- normalAttribute.getZ(vertex) !== Math.fround(normal.z)
1060
- ) {
1061
- normalAttribute.setXYZ(vertex, normal.x, normal.y, normal.z);
1062
- changed = true;
1063
- }
1064
- }
1065
- if (!changed) return false;
1066
- updateLevelSkirts(level);
1067
- refreshEdgeSamples(level);
1068
- position.needsUpdate = true;
1069
- normalAttribute.needsUpdate = true;
1070
- if (tile.lodTransition === undefined) {
1071
- level.geometry.computeBoundingBox();
1072
- level.geometry.computeBoundingSphere();
1073
- }
1074
- return true;
1075
- }
1076
-
1077
- /** One level's edge as the bridge job reads it: the row's own heights, copied out of the level. */
1078
- function edgeJob(
1079
- tile: IResidentTile,
1080
- level: ILevelGeometry,
1081
- side: keyof IEdgeSamples,
1082
- ): ITerrainEdgeJob {
1083
- return {
1084
- depth: tile.field.depth,
1085
- origin: tile.field.origin,
1086
- samples: level.edgeSamples[side].slice(),
1087
- side,
1088
- width: tile.field.width,
1089
- };
1090
- }
1091
-
1092
- /** The same edge with the resolution the fine side of a bridge needs. */
1093
- function fineEdgeJob(
1094
- tile: IResidentTile,
1095
- level: ILevelGeometry,
1096
- side: keyof IEdgeSamples,
1097
- ): ITerrainFineEdgeJob {
1098
- return { ...edgeJob(tile, level, side), resolution: level.resolution };
1099
- }
1100
-
1101
- function stitchGeometry(data: ITerrainBridgeAttributes): BufferGeometry {
1102
- const geometry = new BufferGeometry();
1103
- geometry.setAttribute("position", new BufferAttribute(data.positions, 3));
1104
- geometry.setAttribute("normal", new BufferAttribute(data.normals, 3));
1105
- geometry.setIndex(new BufferAttribute(data.indices, 1));
1106
- geometry.computeBoundingBox();
1107
- geometry.computeBoundingSphere();
1108
- return geometry;
1109
- }
1110
-
1111
- function geometryBytes(geometry: BufferGeometry): number {
1112
- const index = geometry.getIndex();
1113
- return (
1114
- geometry.getAttribute("position").array.byteLength +
1115
- geometry.getAttribute("normal").array.byteLength +
1116
- (index?.array.byteLength ?? 0)
1117
- );
1118
- }
1119
-
1120
- function validateBridgeTriangleTopology(
1121
- geometry: BufferGeometry,
1122
- expectedVertexCount?: number,
1123
- ): PositionAttribute {
1124
- const position = geometry.getAttribute("position");
1125
- const index = geometry.getIndex();
1126
- const drawRange = geometry.drawRange;
1127
- const positionArray = position?.array;
1128
- if (
1129
- position === undefined ||
1130
- position.itemSize !== 3 ||
1131
- !Number.isInteger(position.count) ||
1132
- position.count < 6 ||
1133
- position.count % 2 !== 0 ||
1134
- positionArray === undefined ||
1135
- positionArray.length < position.count * position.itemSize ||
1136
- (expectedVertexCount !== undefined && position.count !== expectedVertexCount) ||
1137
- index === null ||
1138
- index.itemSize !== 1 ||
1139
- !Number.isInteger(index.count) ||
1140
- index.array.length !== index.count ||
1141
- !(index.array instanceof Uint16Array || index.array instanceof Uint32Array) ||
1142
- !Number.isInteger(drawRange.start) ||
1143
- drawRange.start !== 0 ||
1144
- (drawRange.count !== Number.POSITIVE_INFINITY &&
1145
- (!Number.isInteger(drawRange.count) ||
1146
- drawRange.count < index.count ||
1147
- drawRange.count % 3 !== 0))
1148
- )
1149
- throw new Error(
1150
- "TerrainTiles seam diagnostic bridge topology has invalid rendered triangle data.",
1151
- );
1152
- const vertexCount = position.count;
1153
- const stripResolution = vertexCount / 2;
1154
- const expectedIndexCount = (stripResolution - 1) * BRIDGE_STRIP_INDEX_PATTERN.length;
1155
- if (index.count !== expectedIndexCount)
1156
- throw new Error(
1157
- "TerrainTiles seam diagnostic bridge topology has invalid rendered triangle data.",
1158
- );
1159
- for (let vertex = 0; vertex < vertexCount; vertex += 1) {
1160
- if (
1161
- !Number.isFinite(position.getX(vertex)) ||
1162
- !Number.isFinite(position.getY(vertex)) ||
1163
- !Number.isFinite(position.getZ(vertex))
1164
- )
1165
- throw new Error("TerrainTiles seam diagnostic bridge coordinates must be finite.");
1166
- }
1167
- for (let offset = 0; offset < index.count; offset += 1) {
1168
- const segment = Math.floor(offset / BRIDGE_STRIP_INDEX_PATTERN.length);
1169
- const pair = segment * 2;
1170
- const expected =
1171
- pair + (BRIDGE_STRIP_INDEX_PATTERN[offset % BRIDGE_STRIP_INDEX_PATTERN.length] as number);
1172
- const vertex = index.getX(offset);
1173
- if (vertex !== expected)
1174
- throw new Error("TerrainTiles seam diagnostic bridge topology has invalid index data.");
1175
- }
1176
- return position;
1177
- }
1178
-
1179
- function updateStitchBridge(bridge: IStitchBridge, data: ITerrainBridgeAttributes): void {
1180
- const position = validateBridgeTriangleTopology(bridge.geometry, bridge.resolution * 2);
1181
- if (bridge.resolution !== data.positions.length / 6) {
1182
- const previous = bridge.geometry;
1183
- bridge.geometry = stitchGeometry(data);
1184
- bridge.mesh.geometry = bridge.geometry;
1185
- bridge.resolution = data.positions.length / 6;
1186
- bridge.bytes = geometryBytes(bridge.geometry);
1187
- previous.dispose();
1188
- } else {
1189
- const normal = bridge.geometry.getAttribute("normal");
1190
- const index = bridge.geometry.getIndex();
1191
- if (
1192
- normal === undefined ||
1193
- normal.itemSize !== 3 ||
1194
- normal.count !== position.count ||
1195
- index === null
1196
- )
1197
- throw new Error(
1198
- "TerrainTiles seam diagnostic bridge topology has invalid rendered triangle data.",
1199
- );
1200
- position.array.set(data.positions);
1201
- normal.array.set(data.normals);
1202
- index.array.set(data.indices);
1203
- position.needsUpdate = true;
1204
- normal.needsUpdate = true;
1205
- index.needsUpdate = true;
1206
- bridge.geometry.computeBoundingBox();
1207
- bridge.geometry.computeBoundingSphere();
1208
- }
1209
- bridge.coverageDepth = data.coverageDepth;
1210
- }
1211
-
1212
- /**
1213
- * The position attribute is passed in rather than looked up per sample: these run four times a
1214
- * vertex for a blend and four times a sample for the pop measurement — 33,800 `getAttribute` map
1215
- * lookups a transition frame on a 65x65 tile, for a name that cannot change while the level is
1216
- * being written.
1217
- */
1218
- function levelHeight(
1219
- position: BufferAttribute,
1220
- resolution: number,
1221
- row: number,
1222
- column: number,
1223
- ): number {
1224
- const value = position.getY(row * resolution + column);
1225
- if (!Number.isFinite(value)) throw new Error("TerrainTiles LOD geometry has an invalid height.");
1226
- return value;
1227
- }
1228
-
1229
- function interpolatedLevelHeight(
1230
- level: ILevelGeometry,
1231
- position: BufferAttribute,
1232
- x: number,
1233
- z: number,
1234
- ): number {
1235
- const column = Math.max(0, Math.min(1, x)) * (level.resolution - 1);
1236
- const row = Math.max(0, Math.min(1, z)) * (level.resolution - 1);
1237
- const column0 = Math.floor(column);
1238
- const row0 = Math.floor(row);
1239
- const column1 = Math.min(level.resolution - 1, column0 + 1);
1240
- const row1 = Math.min(level.resolution - 1, row0 + 1);
1241
- const columnMix = column - column0;
1242
- const rowMix = row - row0;
1243
- const upperLeft = levelHeight(position, level.resolution, row0, column0);
1244
- const upperRight = levelHeight(position, level.resolution, row0, column1);
1245
- const lowerLeft = levelHeight(position, level.resolution, row1, column0);
1246
- const lowerRight = levelHeight(position, level.resolution, row1, column1);
1247
- const upper = upperLeft + (upperRight - upperLeft) * columnMix;
1248
- const lower = lowerLeft + (lowerRight - lowerLeft) * columnMix;
1249
- return upper + (lower - upper) * rowMix;
1250
- }
1251
-
1252
- function interpolatedLevelNormal(
1253
- level: ILevelGeometry,
1254
- normal: BufferAttribute,
1255
- x: number,
1256
- z: number,
1257
- target: Vector3,
1258
- ): Vector3 {
1259
- const column = Math.max(0, Math.min(1, x)) * (level.resolution - 1);
1260
- const row = Math.max(0, Math.min(1, z)) * (level.resolution - 1);
1261
- const column0 = Math.floor(column);
1262
- const row0 = Math.floor(row);
1263
- const column1 = Math.min(level.resolution - 1, column0 + 1);
1264
- const row1 = Math.min(level.resolution - 1, row0 + 1);
1265
- const columnMix = column - column0;
1266
- const rowMix = row - row0;
1267
- const upperLeft = row0 * level.resolution + column0;
1268
- const upperRight = row0 * level.resolution + column1;
1269
- const lowerLeft = row1 * level.resolution + column0;
1270
- const lowerRight = row1 * level.resolution + column1;
1271
- const blend = (upper: number, lower: number): number => upper + (lower - upper) * rowMix;
1272
- const interpolate = (
1273
- topLeft: number,
1274
- topRight: number,
1275
- bottomLeft: number,
1276
- bottomRight: number,
1277
- ) =>
1278
- blend(
1279
- topLeft + (topRight - topLeft) * columnMix,
1280
- bottomLeft + (bottomRight - bottomLeft) * columnMix,
1281
- );
1282
- return target
1283
- .set(
1284
- interpolate(
1285
- normal.getX(upperLeft),
1286
- normal.getX(upperRight),
1287
- normal.getX(lowerLeft),
1288
- normal.getX(lowerRight),
1289
- ),
1290
- interpolate(
1291
- normal.getY(upperLeft),
1292
- normal.getY(upperRight),
1293
- normal.getY(lowerLeft),
1294
- normal.getY(lowerRight),
1295
- ),
1296
- interpolate(
1297
- normal.getZ(upperLeft),
1298
- normal.getZ(upperRight),
1299
- normal.getZ(lowerLeft),
1300
- normal.getZ(lowerRight),
1301
- ),
1302
- )
1303
- .normalize();
1304
- }
1305
-
1306
- /** Immutable stock morph buffers; shared sides keep the canonical surface used by seam jobs. */
1307
- function* buildLodMorphTargets(
1308
- finer: ILevelGeometry,
1309
- coarserLevels: readonly ILevelGeometry[],
1310
- sharedEdges: number,
1311
- chunked: boolean,
1312
- ): Generator<void> {
1313
- const position = finer.geometry.getAttribute("position");
1314
- const normal = finer.geometry.getAttribute("normal");
1315
- const positions: BufferAttribute[] = [];
1316
- const normals: BufferAttribute[] = [];
1317
- const coarseNormal = new Vector3();
1318
- const last = finer.resolution - 1;
1319
- for (const coarser of coarserLevels) {
1320
- const deltaPosition = new BufferAttribute(new Float32Array(position.count * 3), 3);
1321
- const deltaNormal = new BufferAttribute(new Float32Array(position.count * 3), 3);
1322
- const coarsePosition = coarser.geometry.getAttribute("position") as BufferAttribute;
1323
- const coarseNormals = coarser.geometry.getAttribute("normal") as BufferAttribute;
1324
- for (let row = 0; row <= last; row += 1) {
1325
- for (let column = 0; column <= last; column += 1) {
1326
- const index = row * finer.resolution + column;
1327
- const pinned =
1328
- (row === 0 && sharedEdges & 1) ||
1329
- (row === last && sharedEdges & 2) ||
1330
- (column === 0 && sharedEdges & 4) ||
1331
- (column === last && sharedEdges & 8);
1332
- if (!pinned) {
1333
- deltaPosition.setY(
1334
- index,
1335
- interpolatedLevelHeight(coarser, coarsePosition, column / last, row / last) -
1336
- position.getY(index),
1337
- );
1338
- interpolatedLevelNormal(coarser, coarseNormals, column / last, row / last, coarseNormal);
1339
- deltaNormal.setXYZ(
1340
- index,
1341
- coarseNormal.x - normal.getX(index),
1342
- coarseNormal.y - normal.getY(index),
1343
- coarseNormal.z - normal.getZ(index),
1344
- );
1345
- }
1346
- if (chunked && (index + 1) % (CONSTRUCTION_CHUNK_SAMPLES / 2) === 0) yield;
1347
- }
1348
- }
1349
- const edges = [
1350
- (index: number) => index,
1351
- (index: number) => last * finer.resolution + index,
1352
- (index: number) => index * finer.resolution,
1353
- (index: number) => index * finer.resolution + last,
1354
- ];
1355
- for (const [edgeIndex, edge] of edges.entries())
1356
- for (let index = 0; index <= last; index += 1)
1357
- deltaPosition.setY(
1358
- finer.resolution ** 2 + edgeIndex * finer.resolution + index,
1359
- deltaPosition.getY(edge(index)),
1360
- );
1361
- positions.push(deltaPosition);
1362
- normals.push(deltaNormal);
1363
- }
1364
- finer.geometry.morphAttributes.position = positions;
1365
- finer.geometry.morphAttributes.normal = normals;
1366
- }
1367
-
1368
- function updateLodMorph(tile: IResidentTile, transition: ILodTransition, progress: number): void {
1369
- const from = tile.levels[transition.from];
1370
- const to = tile.levels[transition.to];
1371
- if (from === undefined || to === undefined)
1372
- throw new Error("TerrainTiles LOD transition references a missing level.");
1373
- const finer = from.resolution >= to.resolution ? from : to;
1374
- const coarser = finer === from ? to : from;
1375
- const target = tile.levels
1376
- .filter((level) => level !== finer && level.resolution <= finer.resolution)
1377
- .indexOf(coarser);
1378
- const influences = finer.mesh.morphTargetInfluences;
1379
- if (influences === undefined || influences[target] === undefined)
1380
- throw new Error("TerrainTiles LOD transition references a missing morph target.");
1381
- influences.fill(0);
1382
- influences[target] = finer === from ? progress : 1 - progress;
1383
- }
1384
-
1385
- function updateLevelSkirts(level: ILevelGeometry): void {
1386
- const position = level.geometry.getAttribute("position");
1387
- const normal = level.geometry.getAttribute("normal");
1388
- const surfaceVertexCount = level.resolution * level.resolution;
1389
- const edges = [
1390
- (index: number) => index,
1391
- (index: number) => (level.resolution - 1) * level.resolution + index,
1392
- (index: number) => index * level.resolution,
1393
- (index: number) => index * level.resolution + level.resolution - 1,
1394
- ];
1395
- for (const [edgeIndex, edge] of edges.entries()) {
1396
- for (let index = 0; index < level.resolution; index += 1) {
1397
- const top = edge(index);
1398
- const bottom = surfaceVertexCount + edgeIndex * level.resolution + index;
1399
- position.setY(bottom, position.getY(top) - level.skirtDepth);
1400
- normal.setXYZ(bottom, 0, 1, 0);
1401
- }
1402
- }
1403
- }
1404
-
1405
- function restoreLevelSurface(field: Heightfield, level: ILevelGeometry): void {
1406
- const position = level.geometry.getAttribute("position");
1407
- const normalAttribute = level.geometry.getAttribute("normal");
1408
- const minimumX = field.origin.x - field.width / 2;
1409
- const minimumZ = field.origin.z - field.depth / 2;
1410
- const cellWidth = field.width / (level.resolution - 1);
1411
- const cellDepth = field.depth / (level.resolution - 1);
1412
- const normal = new Vector3();
1413
- for (let row = 0; row < level.resolution; row += 1) {
1414
- const z = minimumZ + row * cellDepth;
1415
- for (let column = 0; column < level.resolution; column += 1) {
1416
- const x = minimumX + column * cellWidth;
1417
- const index = row * level.resolution + column;
1418
- position.setY(index, field.heightAt(x, z));
1419
- field.normalAt(x, z, normal);
1420
- normalAttribute.setXYZ(index, normal.x, normal.y, normal.z);
1421
- }
1422
- }
1423
- updateLevelSkirts(level);
1424
- refreshEdgeSamples(level);
1425
- position.needsUpdate = true;
1426
- normalAttribute.needsUpdate = true;
1427
- level.geometry.computeBoundingBox();
1428
- level.geometry.computeBoundingSphere();
1429
- }
1430
-
1431
- /**
1432
- * A blend only ever moves a vertex between the two levels' surfaces, so the union of the two
1433
- * known bounds holds every frame of it. Widened once when the transition starts instead of
1434
- * recomputed per blend frame: `computeBoundingBox` + `computeBoundingSphere` walked the finer
1435
- * level's ~8,600 positions every frame of every transition (56 + 45 + 27 + 29 ms over a six-second
1436
- * walk). `#restoreLodTransition` puts the finer level's own bounds back when the blend ends.
1437
- */
1438
- function widenLevelBoundsForBlend(finer: ILevelGeometry, coarser: ILevelGeometry): void {
1439
- const box = finer.geometry.boundingBox;
1440
- const sphere = finer.geometry.boundingSphere;
1441
- const coarserBox = coarser.geometry.boundingBox;
1442
- if (box === null || sphere === null || coarserBox === null)
1443
- throw new Error("TerrainTiles LOD transition needs both levels' bounds to be known.");
1444
- box.union(coarserBox);
1445
- box.getBoundingSphere(sphere);
1446
- }
1447
-
1448
- function updateLodTransitionGeometry(
1449
- tile: IResidentTile,
1450
- transition: ILodTransition,
1451
- progress: number,
1452
- ): void {
1453
- const from = tile.levels[transition.from];
1454
- const to = tile.levels[transition.to];
1455
- if (from === undefined || to === undefined)
1456
- throw new Error("TerrainTiles LOD transition references a missing level.");
1457
- const finer = from.resolution >= to.resolution ? from : to;
1458
- const coarser = finer === from ? to : from;
1459
- const fromIsFiner = finer === from;
1460
- const position = finer.geometry.getAttribute("position");
1461
- const normalAttribute = finer.geometry.getAttribute("normal");
1462
- const coarsePosition = coarser.geometry.getAttribute("position") as BufferAttribute;
1463
- const coarseNormalAttribute = coarser.geometry.getAttribute("normal") as BufferAttribute;
1464
- const minimumX = tile.field.origin.x - tile.field.width / 2;
1465
- const minimumZ = tile.field.origin.z - tile.field.depth / 2;
1466
- const cellWidth = tile.field.width / (finer.resolution - 1);
1467
- const cellDepth = tile.field.depth / (finer.resolution - 1);
1468
- const fineNormal = new Vector3();
1469
- const coarseNormal = new Vector3();
1470
- const blendedNormal = new Vector3();
1471
- for (let row = 0; row < finer.resolution; row += 1) {
1472
- const z = minimumZ + row * cellDepth;
1473
- const normalizedZ = row / (finer.resolution - 1);
1474
- for (let column = 0; column < finer.resolution; column += 1) {
1475
- const x = minimumX + column * cellWidth;
1476
- const normalizedX = column / (finer.resolution - 1);
1477
- const index = row * finer.resolution + column;
1478
- const fineHeight = tile.field.heightAt(x, z);
1479
- const coarseHeight = interpolatedLevelHeight(
1480
- coarser,
1481
- coarsePosition,
1482
- normalizedX,
1483
- normalizedZ,
1484
- );
1485
- const startHeight = fromIsFiner ? fineHeight : coarseHeight;
1486
- const endHeight = fromIsFiner ? coarseHeight : fineHeight;
1487
- position.setY(index, startHeight + (endHeight - startHeight) * progress);
1488
-
1489
- tile.field.normalAt(x, z, fineNormal);
1490
- interpolatedLevelNormal(
1491
- coarser,
1492
- coarseNormalAttribute,
1493
- normalizedX,
1494
- normalizedZ,
1495
- coarseNormal,
1496
- );
1497
- const startNormal = fromIsFiner ? fineNormal : coarseNormal;
1498
- const endNormal = fromIsFiner ? coarseNormal : fineNormal;
1499
- blendedNormal
1500
- .set(
1501
- startNormal.x + (endNormal.x - startNormal.x) * progress,
1502
- startNormal.y + (endNormal.y - startNormal.y) * progress,
1503
- startNormal.z + (endNormal.z - startNormal.z) * progress,
1504
- )
1505
- .normalize();
1506
- normalAttribute.setXYZ(index, blendedNormal.x, blendedNormal.y, blendedNormal.z);
1507
- }
1508
- }
1509
- updateLevelSkirts(finer);
1510
- refreshEdgeSamples(finer);
1511
- position.needsUpdate = true;
1512
- normalAttribute.needsUpdate = true;
1513
- }
1514
-
1515
- function* surfaceHeightChunks(
1516
- level: ILevelGeometry,
1517
- chunked: boolean,
1518
- ): Generator<void, Float32Array> {
1519
- const position = level.geometry.getAttribute("position");
1520
- const heights = new Float32Array(level.resolution * level.resolution);
1521
- for (let index = 0; index < heights.length; index += 1) {
1522
- heights[index] = position.getY(index);
1523
- if (chunked && (index + 1) % CONSTRUCTION_CHUNK_SAMPLES === 0) yield;
1524
- }
1525
- return heights;
1526
- }
1527
-
1528
- function surfaceHeights(level: ILevelGeometry): Float32Array {
1529
- return surfaceHeightChunks(level, false).next().value as Float32Array;
1530
- }
1531
-
1532
- function interpolatedSamplesHeight(
1533
- samples: Float32Array,
1534
- resolution: number,
1535
- x: number,
1536
- z: number,
1537
- ): number {
1538
- const column = Math.max(0, Math.min(1, x)) * (resolution - 1);
1539
- const row = Math.max(0, Math.min(1, z)) * (resolution - 1);
1540
- const column0 = Math.floor(column);
1541
- const row0 = Math.floor(row);
1542
- const column1 = Math.min(resolution - 1, column0 + 1);
1543
- const row1 = Math.min(resolution - 1, row0 + 1);
1544
- const columnMix = column - column0;
1545
- const rowMix = row - row0;
1546
- const upperLeft = samples[row0 * resolution + column0] as number;
1547
- const upperRight = samples[row0 * resolution + column1] as number;
1548
- const lowerLeft = samples[row1 * resolution + column0] as number;
1549
- const lowerRight = samples[row1 * resolution + column1] as number;
1550
- const upper = upperLeft + (upperRight - upperLeft) * columnMix;
1551
- const lower = lowerLeft + (lowerRight - lowerLeft) * columnMix;
1552
- return upper + (lower - upper) * rowMix;
1553
- }
1554
-
1555
- function* surfaceDeltaChunks(
1556
- samples: Float32Array,
1557
- resolution: number,
1558
- level: ILevelGeometry,
1559
- chunked: boolean,
1560
- ): Generator<void, number> {
1561
- const sampleCount = Math.max(resolution, level.resolution);
1562
- const position = level.geometry.getAttribute("position") as BufferAttribute;
1563
- let maximum = 0;
1564
- for (let row = 0; row < sampleCount; row += 1) {
1565
- for (let column = 0; column < sampleCount; column += 1) {
1566
- const x = column / (sampleCount - 1);
1567
- const z = row / (sampleCount - 1);
1568
- maximum = Math.max(
1569
- maximum,
1570
- Math.abs(
1571
- interpolatedSamplesHeight(samples, resolution, x, z) -
1572
- interpolatedLevelHeight(level, position, x, z),
1573
- ),
1574
- );
1575
- if (chunked && (row * sampleCount + column + 1) % CONSTRUCTION_CHUNK_SAMPLES === 0) yield;
1576
- }
1577
- }
1578
- return maximum;
1579
- }
1580
-
1581
- function surfaceDeltaFromSamples(
1582
- samples: Float32Array,
1583
- resolution: number,
1584
- level: ILevelGeometry,
1585
- ): number {
1586
- return surfaceDeltaChunks(samples, resolution, level, false).next().value as number;
1587
- }
1588
-
1589
- /**
1590
- * The coarsest level a tile may ever show. A level is selectable only when its height error
1591
- * against *every* finer level fits the pop bound, which is what keeps the per-frame displacement
1592
- * inside it: a transition walks one LOD_TRANSITION_FRAMES-th of the way between two levels, and
1593
- * an interrupted transition snaps back to a level endpoint, which is never further from the
1594
- * surface it replaced than the bound between any two selectable levels. A cliff therefore keeps
1595
- * its tile at a finer level instead of throwing out of the frame.
1596
- */
1597
- function* coarsestSelectableLevel(
1598
- levels: readonly ILevelGeometry[],
1599
- chunked: boolean,
1600
- ): Generator<void, number> {
1601
- let coarsest = 0;
1602
- for (let index = 1; index < levels.length; index += 1) {
1603
- const level = levels[index];
1604
- if (level === undefined) break;
1605
- let error = 0;
1606
- for (let finerIndex = 0; finerIndex < index; finerIndex += 1) {
1607
- const finer = levels[finerIndex];
1608
- if (finer === undefined) break;
1609
- error = Math.max(
1610
- error,
1611
- yield* surfaceDeltaChunks(
1612
- yield* surfaceHeightChunks(finer, chunked),
1613
- finer.resolution,
1614
- level,
1615
- chunked,
1616
- ),
1617
- );
1618
- }
1619
- level.surfaceError = error;
1620
- if (error > LOD_POP_THRESHOLD) break;
1621
- coarsest = index;
1622
- }
1623
- return coarsest;
1624
- }
1625
-
1626
- function seamCoverageDepth(a: IResidentTile, b: IResidentTile): number {
1627
- const aLevel = a.levels[a.lodLevel];
1628
- const bLevel = b.levels[b.lodLevel];
1629
- if (aLevel === undefined || bLevel === undefined) return 0;
1630
- return Math.min(aLevel.skirtDepth, bLevel.skirtDepth);
1631
- }
1632
-
1633
- /**
1634
- * One edge of one level, addressed in the position buffer directly.
1635
- *
1636
- * The seam diagnostic reads two edges once per sample of every pair, four times a frame, so the
1637
- * per-read cost is the per-frame cost: resolving the attribute and calling `getY` per vertex was
1638
- * ~40% of a settled 289-tile frame. The Y of edge vertex `index` sits at `first + index * span`
1639
- * in the interleaved array, and stepping an edge by one vertex steps the array by `span`.
1640
- */
1641
- interface IEdgeWalk {
1642
- readonly first: number;
1643
- readonly heights: Float32Array;
1644
- readonly resolution: number;
1645
- readonly span: number;
1646
- }
1647
-
1648
- function edgeWalk(level: ILevelGeometry, side: keyof IEdgeSamples): IEdgeWalk {
1649
- const position = level.geometry.getAttribute("position");
1650
- const array = position.array as Float32Array;
1651
- const last = level.resolution - 1;
1652
- const first =
1653
- side === "north" ? 0 : side === "south" ? last * level.resolution : side === "west" ? 0 : last;
1654
- return {
1655
- first: first * 3 + 1,
1656
- heights: array,
1657
- resolution: level.resolution,
1658
- span: (side === "north" || side === "south" ? 1 : level.resolution) * 3,
1659
- };
1660
- }
1661
-
1662
- function edgeWalkHeight(walk: IEdgeWalk, index: number): number {
1663
- const lower = walk.heights[walk.first + index * walk.span] as number;
1664
- if (!Number.isFinite(lower))
1665
- throw new Error("TerrainTiles seam diagnostic edge height must be finite.");
1666
- return lower;
1667
- }
1668
-
1669
- /** The walk's height at `normalized`, interpolating exactly as `edgeHeight` does. */
1670
- function edgeWalkAt(walk: IEdgeWalk, normalized: number): number {
1671
- const position = normalized * (walk.resolution - 1);
1672
- const lower = Math.floor(position);
1673
- const mix = position - lower;
1674
- const lowerValue = edgeWalkHeight(walk, lower);
1675
- if (mix === 0) return lowerValue;
1676
- return (
1677
- lowerValue * (1 - mix) + edgeWalkHeight(walk, Math.min(walk.resolution - 1, lower + 1)) * mix
1678
- );
1679
- }
1680
-
1681
- /** A pair's bridge, validated and placed once so the per-sample loop only measures. */
1682
- interface IBridgeCoverage {
1683
- readonly bridge: IStitchBridge;
1684
- readonly coarser: IBridgeEndpoint;
1685
- readonly finer: IBridgeEndpoint;
1686
- readonly position: PositionAttribute;
1687
- }
1688
-
1689
- function bridgeCoverageContext(
1690
- bridge: IStitchBridge,
1691
- a: IResidentTile,
1692
- aSide: keyof IEdgeSamples,
1693
- b: IResidentTile,
1694
- bSide: keyof IEdgeSamples,
1695
- ): IBridgeCoverage {
1696
- if (bridge.mesh.geometry !== bridge.geometry)
1697
- throw new Error("TerrainTiles seam diagnostic bridge geometry is not attached to its mesh.");
1698
- if (!Number.isInteger(bridge.resolution) || bridge.resolution < 2)
1699
- throw new Error("TerrainTiles seam diagnostic bridge resolution is invalid.");
1700
- if (
1701
- bridge.keys[0] !== (a.key < b.key ? a.key : b.key) ||
1702
- bridge.keys[1] !== (a.key < b.key ? b.key : a.key)
1703
- )
1704
- throw new Error("TerrainTiles seam diagnostic bridge topology does not match its tile pair.");
1705
- const position = validateBridgeTriangleTopology(bridge.mesh.geometry, bridge.resolution * 2);
1706
- if (position.count !== bridge.resolution * 2)
1707
- throw new Error("TerrainTiles seam diagnostic bridge topology has invalid coverage.");
1708
- const [finer, coarser] = bridgeEndpointPair(a, aSide, b, bSide);
1709
- // Nothing inside the sample loop moves these, so deriving them per sample only repeated work:
1710
- // three world-matrix updates and a full revalidation of the bridge's own topology for every
1711
- // edge vertex of every pair, four times a frame.
1712
- bridge.mesh.updateWorldMatrix(true, false);
1713
- finer.level.mesh.updateWorldMatrix(true, false);
1714
- coarser.level.mesh.updateWorldMatrix(true, false);
1715
- return { bridge, coarser, finer, position };
1716
- }
1717
-
1718
- function bridgeCoverageAt(
1719
- coverage: IBridgeCoverage,
1720
- normalized: number,
1721
- worldPosition: Vector3,
1722
- expectedWorldPosition: Vector3,
1723
- ): number {
1724
- if (!Number.isFinite(normalized))
1725
- throw new Error("TerrainTiles seam diagnostic bridge sample coordinate must be finite.");
1726
- const { bridge, coarser, finer, position } = coverage;
1727
- const samplePosition = Math.max(0, Math.min(1, normalized)) * (bridge.resolution - 1);
1728
- const lower = Math.floor(samplePosition);
1729
- const upper = Math.min(bridge.resolution - 1, lower + 1);
1730
- const mix = samplePosition - lower;
1731
- const fine =
1732
- bridgeEndpointHeight(
1733
- bridge,
1734
- position,
1735
- lower,
1736
- 0,
1737
- finer.tile,
1738
- finer.side,
1739
- finer.level,
1740
- worldPosition,
1741
- expectedWorldPosition,
1742
- ) *
1743
- (1 - mix) +
1744
- bridgeEndpointHeight(
1745
- bridge,
1746
- position,
1747
- upper,
1748
- 0,
1749
- finer.tile,
1750
- finer.side,
1751
- finer.level,
1752
- worldPosition,
1753
- expectedWorldPosition,
1754
- ) *
1755
- mix;
1756
- const coarse =
1757
- bridgeEndpointHeight(
1758
- bridge,
1759
- position,
1760
- lower,
1761
- 1,
1762
- coarser.tile,
1763
- coarser.side,
1764
- coarser.level,
1765
- worldPosition,
1766
- expectedWorldPosition,
1767
- ) *
1768
- (1 - mix) +
1769
- bridgeEndpointHeight(
1770
- bridge,
1771
- position,
1772
- upper,
1773
- 1,
1774
- coarser.tile,
1775
- coarser.side,
1776
- coarser.level,
1777
- worldPosition,
1778
- expectedWorldPosition,
1779
- ) *
1780
- mix;
1781
- const covered = Math.abs(fine - coarse);
1782
- if (!Number.isFinite(covered))
1783
- throw new Error("TerrainTiles seam diagnostic bridge coverage must be finite.");
1784
- return covered;
1785
- }
1786
-
1787
- function seamObservation(
1788
- a: IResidentTile,
1789
- b: IResidentTile,
1790
- bridge: IStitchBridge | undefined,
1791
- owner: Object3D,
1792
- includeBridgeCoverage: boolean,
1793
- ): { gap: number; visualGap: number } {
1794
- const [aSide, bSide] = opposingEdge(a, b);
1795
- const aLevel = renderedLevel(a);
1796
- const bLevel = renderedLevel(b);
1797
- if (aLevel === undefined || bLevel === undefined)
1798
- throw new Error("TerrainTiles seam diagnostic observation has no rendered level.");
1799
- const samples = Math.max(aLevel.resolution, bLevel.resolution);
1800
- const aWalk = edgeWalk(aLevel, aSide);
1801
- const bWalk = edgeWalk(bLevel, bSide);
1802
- const coverage =
1803
- includeBridgeCoverage &&
1804
- bridge !== undefined &&
1805
- bridge.mesh.parent === owner &&
1806
- bridge.mesh.visible
1807
- ? bridgeCoverageContext(bridge, a, aSide, b, bSide)
1808
- : undefined;
1809
- const skirt = seamCoverageDepth(a, b);
1810
- const worldPosition = new Vector3();
1811
- const expectedWorldPosition = new Vector3();
1812
- let gap = 0;
1813
- let visualGap = 0;
1814
- for (let index = 0; index < samples; index += 1) {
1815
- const normalized = samples === 1 ? 0 : index / (samples - 1);
1816
- const currentGap = Math.abs(edgeWalkAt(aWalk, normalized) - edgeWalkAt(bWalk, normalized));
1817
- if (!Number.isFinite(currentGap))
1818
- throw new Error("TerrainTiles seam diagnostic observation must be finite.");
1819
- gap = Math.max(gap, currentGap);
1820
- const covered =
1821
- coverage === undefined
1822
- ? 0
1823
- : bridgeCoverageAt(coverage, normalized, worldPosition, expectedWorldPosition);
1824
- visualGap = Math.max(visualGap, Math.max(0, currentGap - Math.max(skirt, covered)));
1825
- }
1826
- if (!Number.isFinite(visualGap))
1827
- throw new Error("TerrainTiles visual seam diagnostic observation must be finite.");
1828
- return { gap, visualGap };
1829
- }
1830
-
1831
- type NeighborPair = readonly [IResidentTile, IResidentTile];
1832
-
1833
- /**
1834
- * One pair's bridge, as the seam job carries it: the two edges it is made of, and what the bridge it
1835
- * produces is called and keyed by.
1836
- */
1837
- interface IStitchRequest {
1838
- readonly coarse: ITerrainEdgeJob;
1839
- readonly fine: ITerrainFineEdgeJob;
1840
- readonly keys: [string, string];
1841
- readonly resolution: number;
1842
- }
1843
-
1844
- function neighborPairKey(pair: NeighborPair): string {
1845
- const [a, b] = pair;
1846
- return a.key < b.key ? `${a.key}|${b.key}` : `${b.key}|${a.key}`;
1847
- }
1848
-
1849
- /**
1850
- * Every facing pair of the resident set, from the residency key map rather than from a scan of
1851
- * every tile against every other tile.
1852
- *
1853
- * `follow` and `process` each want this list, four times a frame, and the scan was quadratic in
1854
- * the resident count: 41k comparisons for the 289-tile ring a `streamRadius: 8` game streams,
1855
- * which is the whole per-frame regression. A tile's east and south neighbors are its only
1856
- * unfaced-inward partners, so two map lookups per tile enumerate each pair exactly once.
1857
- */
1858
- function neighborPairs(tiles: ReadonlyMap<string, IResidentTile>): NeighborPair[] {
1859
- const pairs: NeighborPair[] = [];
1860
- collectNeighborPairs(tiles, pairs);
1861
- return pairs;
1862
- }
1863
-
1864
- /** `neighborPairs` into a buffer the caller already owns, so a frame allocates no pair arrays. */
1865
- function collectNeighborPairs(
1866
- tiles: ReadonlyMap<string, IResidentTile>,
1867
- into: NeighborPair[],
1868
- ): NeighborPair[] {
1869
- into.length = 0;
1870
- for (const tile of tiles.values()) {
1871
- const east = tiles.get(keyFor(tile.tileX + 1, tile.tileZ));
1872
- if (east !== undefined) into.push([tile, east]);
1873
- const south = tiles.get(keyFor(tile.tileX, tile.tileZ + 1));
1874
- if (south !== undefined) into.push([tile, south]);
1875
- }
1876
- return into;
1877
- }
1878
-
1879
- function hasPendingTarget(targets: ReadonlyMap<IResidentTile, number>): boolean {
1880
- for (const [tile, target] of targets)
1881
- if (Math.min(target, tile.maxLodLevel) !== tile.lodLevel) return true;
1882
- return false;
1883
- }
1884
-
1885
- /** Each resident tile's target level after the neighbour rule: no two neighbours two levels apart. */
1886
- function coordinatedLevels(
1887
- resident: ReadonlyMap<string, IResidentTile>,
1888
- targets: ReadonlyMap<IResidentTile, number>,
1889
- ): Map<IResidentTile, number> {
1890
- const levels = new Map<IResidentTile, number>();
1891
- for (const tile of resident.values())
1892
- levels.set(tile, Math.min(targets.get(tile) ?? tile.lodLevel, tile.maxLodLevel));
1893
- const pairs = neighborPairs(resident);
1894
- let changed = true;
1895
- while (changed) {
1896
- changed = false;
1897
- for (const [a, b] of pairs) {
1898
- const aLevel = levels.get(a) as number;
1899
- const bLevel = levels.get(b) as number;
1900
- if (Math.abs(aLevel - bLevel) <= 1) continue;
1901
- if (aLevel > bLevel) levels.set(a, bLevel + 1);
1902
- else levels.set(b, aLevel + 1);
1903
- changed = true;
1904
- }
1905
- }
1906
- return levels;
1907
- }
1908
-
1909
- function neighborLodCorrection(
1910
- pair: NeighborPair,
1911
- ): { coarser: IResidentTile; level: number } | undefined {
1912
- const [a, b] = pair;
1913
- if (Math.abs(a.lodLevel - b.lodLevel) <= 1) return undefined;
1914
- const finer = a.lodLevel < b.lodLevel ? a : b;
1915
- const coarser = finer === a ? b : a;
1916
- return { coarser, level: finer.lodLevel + 1 };
1917
- }
1918
-
1919
- /**
1920
- * One neighbor pair's bridge request, or `undefined` when the pair needs no bridge.
1921
- *
1922
- * The two edges are restored here — that reads the game's field sampler, which cannot cross into a
1923
- * worker — and everything the bridge strip is made of is copied out as numbers. The strip itself is
1924
- * built wherever the jobs run, so the main thread only swaps the attributes it gets back.
1925
- */
1926
- function neighborBridgeRequest(pair: NeighborPair): IStitchRequest | undefined {
1927
- const [a, b] = pair;
1928
- const [aSide, bSide] = opposingEdge(a, b);
1929
- const aLevel = renderedLevel(a);
1930
- const bLevel = renderedLevel(b);
1931
- if (aLevel === undefined || bLevel === undefined)
1932
- throw new Error("TerrainTiles cannot reconcile a neighbor with no rendered LOD level.");
1933
- restoreLevelEdge(a, aLevel, aSide);
1934
- restoreLevelEdge(b, bLevel, bSide);
1935
- if (aLevel.resolution === bLevel.resolution) return undefined;
1936
- const finerLevel = aLevel.resolution > bLevel.resolution ? aLevel : bLevel;
1937
- return {
1938
- coarse: edgeJob(
1939
- finerLevel === aLevel ? b : a,
1940
- finerLevel === aLevel ? bLevel : aLevel,
1941
- finerLevel === aLevel ? bSide : aSide,
1942
- ),
1943
- fine: fineEdgeJob(
1944
- finerLevel === aLevel ? a : b,
1945
- finerLevel,
1946
- finerLevel === aLevel ? aSide : bSide,
1947
- ),
1948
- keys: [a.key, b.key].sort() as [string, string],
1949
- resolution: finerLevel.resolution,
1950
- };
1951
- }
1952
-
1953
- function newStitchBridge(
1954
- request: IStitchRequest,
1955
- data: ITerrainBridgeAttributes,
1956
- surface: MeshSurface,
1957
- ): IStitchBridge {
1958
- const geometry = stitchGeometry(data);
1959
- const mesh = terrainMesh(new Mesh(geometry, surface));
1960
- mesh.frustumCulled = true;
1961
- return {
1962
- bytes: geometryBytes(geometry),
1963
- coverageDepth: data.coverageDepth,
1964
- geometry,
1965
- keys: request.keys,
1966
- mesh,
1967
- resolution: request.resolution,
1968
- };
1969
- }
1970
-
1971
- function setManualLodLevel(lod: LOD, level: number): void {
1972
- // Three's renderer reads `autoUpdate`, and its update method owns this private-ish marker. Keep
1973
- // that marker aligned with the visible child for callers that inspect the composed LOD.
1974
- (lod as LOD & { _currentLevel: number })._currentLevel = level;
1975
- }
336
+ export type NeighborPair = readonly [IResidentTile, IResidentTile];
1976
337
 
1977
338
  /**
1978
339
  * Stream a bounded square of game-authored heightfields and keep their render and physics units
@@ -1982,6 +343,8 @@ function setManualLodLevel(lod: LOD, level: number): void {
1982
343
  * @situation stream terrain without cracks
1983
344
  * @situation keep generated terrain resident around a moving player
1984
345
  * @situation put a generated terrain tile into a game-owned physics world
346
+ * @situation a hole or a flicker where streamed terrain tiles are still building (`settledHalf`)
347
+ * @situation split the ground between streamed tiles and a far mesh around the player (`settledHalf`)
1985
348
  * @alias stream terrain across chunks
1986
349
  * @constraint sampleHeight and surface are required game choices; no landform or surface preset is installed
1987
350
  * @constraint residentTileBudget and residentByteBudget are hard caps; a tile that cannot fit throws
@@ -2008,6 +371,8 @@ export class TerrainTiles extends Object3D implements IComputeDriven {
2008
371
  readonly #surface: MeshSurface;
2009
372
  readonly #sampleHeight: IWorldTilesOptions["sampleHeight"];
2010
373
  readonly #streamRadius: number;
374
+ readonly #extent: IWorldTilesOptions["extent"];
375
+ readonly #hole: IWorldTilesOptions["hole"];
2011
376
  /** Diagnostics outlive construction; their canonical field is never used by resident tiles. */
2012
377
  #topology:
2013
378
  | (Pick<Heightfield, "columns" | "depth" | "origin" | "rows" | "width"> & {
@@ -2110,6 +475,8 @@ export class TerrainTiles extends Object3D implements IComputeDriven {
2110
475
  this.residentByteBudget = integerAtLeast(options.residentByteBudget, 1, "residentByteBudget");
2111
476
  this.skirtDepth = positive(options.skirtDepth ?? this.tileSize, "skirtDepth");
2112
477
  this.#streamRadius = integerAtLeast(options.streamRadius ?? 1, 0, "streamRadius");
478
+ this.#extent = options.extent;
479
+ this.#hole = options.hole;
2113
480
  this.#receiveShadow = options.receiveShadow === true;
2114
481
  this.#colliderRadius = integerAtLeast(
2115
482
  options.colliderRadius ?? this.#streamRadius,
@@ -2121,6 +488,9 @@ export class TerrainTiles extends Object3D implements IComputeDriven {
2121
488
  throw new Error("TerrainTiles surface is required and must be game-owned.");
2122
489
  this.#validate = options.validate ?? terrainValidationRequested();
2123
490
  this.#mergeTiles = options.mergeTiles ?? !terrainMergeOptedOut();
491
+ // Streamed ground batches itself into blocks; `AutoBatch` merging those again hid the live
492
+ // terrain from every ray walk of this subtree and re-merged on each stream step.
493
+ this.userData.batch = "off";
2124
494
  this.#sampleHeight = options.sampleHeight;
2125
495
  if (typeof options.sampleHeight !== "function")
2126
496
  throw new Error("TerrainTiles sampleHeight is required.");
@@ -2369,6 +739,42 @@ export class TerrainTiles extends Object3D implements IComputeDriven {
2369
739
  return this.#resident.get(key);
2370
740
  }
2371
741
 
742
+ /**
743
+ * Half-width, in metres, of the largest square of tiles around `position`'s tile that is fully
744
+ * settled: each tile in it is resident, or is one the stream never draws (wholly inside `hole` or
745
+ * past `extent`). Zero while the tile under `position` is still building. A game that draws other
746
+ * ground where the tiles have not arrived (a collar, a far mesh) clips it to this square, so a tile
747
+ * still building shows that ground, never a hole.
748
+ *
749
+ * @situation a hole or a flicker where streamed terrain tiles are still building
750
+ * @situation split the ground between streamed tiles and a far mesh around the player
751
+ * @constraint reads residency only; call it after `follow` in the same frame
752
+ * @example split.half.value = tiles.settledHalf(player.position);
753
+ */
754
+ settledHalf(position: Pick<Vector3, "x" | "z">): number {
755
+ const centerX = Math.floor(
756
+ (finite(position.x, "settled x") + this.tileSize / 2) / this.tileSize,
757
+ );
758
+ const centerZ = Math.floor(
759
+ (finite(position.z, "settled z") + this.tileSize / 2) / this.tileSize,
760
+ );
761
+ const settled = (tileX: number, tileZ: number): boolean =>
762
+ this.#resident.has(keyFor(tileX, tileZ)) || !this.#touchesExtent(tileX, tileZ);
763
+ let ring = -1;
764
+ for (let k = 0; k <= this.#streamRadius; k += 1) {
765
+ for (let d = -k; d <= k; d += 1)
766
+ if (
767
+ !settled(centerX + d, centerZ - k) ||
768
+ !settled(centerX + d, centerZ + k) ||
769
+ !settled(centerX - k, centerZ + d) ||
770
+ !settled(centerX + k, centerZ + d)
771
+ )
772
+ return ring < 0 ? 0 : (ring + 0.5) * this.tileSize;
773
+ ring = k;
774
+ }
775
+ return (ring + 0.5) * this.tileSize;
776
+ }
777
+
2372
778
  /**
2373
779
  * Move residency to the followed point: admit, evict and re-level every tile.
2374
780
  *
@@ -2406,6 +812,7 @@ export class TerrainTiles extends Object3D implements IComputeDriven {
2406
812
  tileX <= centerX + this.#streamRadius;
2407
813
  tileX += 1
2408
814
  ) {
815
+ if (!this.#touchesExtent(tileX, tileZ)) continue;
2409
816
  const tileCenterX = tileX * this.tileSize;
2410
817
  const tileCenterZ = tileZ * this.tileSize;
2411
818
  wanted.push({
@@ -2571,6 +978,55 @@ export class TerrainTiles extends Object3D implements IComputeDriven {
2571
978
  return { required, loaded };
2572
979
  }
2573
980
 
981
+ /** Loaded selected tiles intersecting the camera; bounds include terrain heights before admission. */
982
+ readinessInView(
983
+ camera: Camera,
984
+ heightBounds: readonly [number, number],
985
+ ): { required: number; loaded: number } {
986
+ if (
987
+ heightBounds.length !== 2 ||
988
+ !Number.isFinite(heightBounds[0]) ||
989
+ !Number.isFinite(heightBounds[1]) ||
990
+ heightBounds[0] > heightBounds[1]
991
+ )
992
+ throw new Error("TerrainTiles visible readiness requires finite ordered height bounds.");
993
+ camera.updateWorldMatrix(true, false);
994
+ this.updateWorldMatrix(true, false);
995
+ const frustum = new Frustum().setFromProjectionMatrix(
996
+ new Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse),
997
+ camera.coordinateSystem,
998
+ );
999
+ const focus = this.#focus ?? this.worldToLocal(camera.getWorldPosition(new Vector3()));
1000
+ const centerX = Math.floor((focus.x + this.tileSize / 2) / this.tileSize);
1001
+ const centerZ = Math.floor((focus.z + this.tileSize / 2) / this.tileSize);
1002
+ const wanted: Array<{ x: number; z: number; distance: number }> = [];
1003
+ for (let z = centerZ - this.#streamRadius; z <= centerZ + this.#streamRadius; z++)
1004
+ for (let x = centerX - this.#streamRadius; x <= centerX + this.#streamRadius; x++)
1005
+ if (this.#touchesExtent(x, z))
1006
+ wanted.push({
1007
+ x,
1008
+ z,
1009
+ distance: Math.hypot(focus.x - x * this.tileSize, focus.z - z * this.tileSize),
1010
+ });
1011
+ wanted.sort((a, b) => a.distance - b.distance || a.z - b.z || a.x - b.x);
1012
+ const bounds = new Box3();
1013
+ let required = 0;
1014
+ let loaded = 0;
1015
+ for (const { x, z } of wanted.slice(0, this.residentTileBudget)) {
1016
+ bounds.min.set(
1017
+ (x - 0.5) * this.tileSize,
1018
+ heightBounds[0] - this.skirtDepth,
1019
+ (z - 0.5) * this.tileSize,
1020
+ );
1021
+ bounds.max.set((x + 0.5) * this.tileSize, heightBounds[1], (z + 0.5) * this.tileSize);
1022
+ bounds.applyMatrix4(this.matrixWorld);
1023
+ if (!frustum.intersectsBox(bounds)) continue;
1024
+ required++;
1025
+ if (!this.#released && this.#resident.has(keyFor(x, z))) loaded++;
1026
+ }
1027
+ return { required, loaded };
1028
+ }
1029
+
2574
1030
  debug(): Record<string, unknown> {
2575
1031
  const topology = this.#topology;
2576
1032
  const view = this.#lodView;
@@ -2590,19 +1046,22 @@ export class TerrainTiles extends Object3D implements IComputeDriven {
2590
1046
  if (view !== undefined && next !== undefined && finest !== undefined && bounds != null) {
2591
1047
  finest.mesh.updateWorldMatrix(true, false);
2592
1048
  const sphere = worldSphere(bounds, finest.mesh);
2593
- const depth = conservativeViewDepth(
1049
+ const { degenerate, depth } = selectLodFor(
2594
1050
  view.camera,
2595
- sphere.center,
2596
- sphere.radius,
1051
+ sphere,
2597
1052
  (view.camera as Camera & { near?: number }).near ?? 0,
2598
1053
  );
2599
1054
  const errorPixels = projectedLodError(
2600
1055
  next.surfaceError * finest.mesh.matrixWorld.getMaxScaleOnAxis(),
2601
1056
  view.camera,
2602
1057
  view.viewportHeight,
2603
- depth.depth,
1058
+ depth,
2604
1059
  );
2605
- projection = { ...depth, ...(Number.isFinite(errorPixels) ? { errorPixels } : {}) };
1060
+ projection = {
1061
+ degenerate,
1062
+ depth,
1063
+ ...(Number.isFinite(errorPixels) ? { errorPixels } : {}),
1064
+ };
2606
1065
  }
2607
1066
  return {
2608
1067
  key: tile.key,
@@ -2974,6 +1433,31 @@ export class TerrainTiles extends Object3D implements IComputeDriven {
2974
1433
  this.#setLodLevel(tile, this.#targetLod(tile, distance), countTransition);
2975
1434
  }
2976
1435
 
1436
+ /**
1437
+ * Whether the tile's square overlaps the ground at all and is not wholly inside the hole; always
1438
+ * true when neither was given.
1439
+ */
1440
+ #touchesExtent(tileX: number, tileZ: number): boolean {
1441
+ const half = this.tileSize / 2;
1442
+ const hole = this.#hole;
1443
+ if (
1444
+ hole !== undefined &&
1445
+ tileX * this.tileSize - half >= hole.minX &&
1446
+ tileX * this.tileSize + half <= hole.maxX &&
1447
+ tileZ * this.tileSize - half >= hole.minZ &&
1448
+ tileZ * this.tileSize + half <= hole.maxZ
1449
+ )
1450
+ return false;
1451
+ const extent = this.#extent;
1452
+ if (extent === undefined) return true;
1453
+ return (
1454
+ tileX * this.tileSize + half > extent.minX &&
1455
+ tileX * this.tileSize - half < extent.maxX &&
1456
+ tileZ * this.tileSize + half > extent.minZ &&
1457
+ tileZ * this.tileSize - half < extent.maxZ
1458
+ );
1459
+ }
1460
+
2977
1461
  #setLodView(view: IWorldTilesLodView | undefined): void {
2978
1462
  if (
2979
1463
  view !== undefined &&
@@ -3001,10 +1485,11 @@ export class TerrainTiles extends Object3D implements IComputeDriven {
3001
1485
  if (finest === undefined || bounds == null) return 0;
3002
1486
  finest.mesh.updateWorldMatrix(true, false);
3003
1487
  const sphere = worldSphere(bounds, finest.mesh);
3004
- const depth = conservativeViewDepth(
1488
+ // The raw depth, deliberately: terrain selection never took the adaptive LOD bias, and passing
1489
+ // `biased` here moved a tile's level whenever `setLodBias` raised it.
1490
+ const { depth, degenerate } = selectLodFor(
3005
1491
  view.camera,
3006
- sphere.center,
3007
- sphere.radius,
1492
+ sphere,
3008
1493
  (view.camera as Camera & { near?: number }).near ?? 0,
3009
1494
  );
3010
1495
  const scale = finest.mesh.matrixWorld.getMaxScaleOnAxis();
@@ -3013,7 +1498,7 @@ export class TerrainTiles extends Object3D implements IComputeDriven {
3013
1498
  this.#lodErrors[index] = (tile.levels[index] as ILevelGeometry).surfaceError * scale;
3014
1499
  this.#lodErrors.length = floor + 1;
3015
1500
  return selectLodLevel(this.#lodErrors, tile.lodLevel, view.maxPixelError, view.hysteresis, [
3016
- { ...view, ...depth },
1501
+ { ...view, degenerate, depth },
3017
1502
  ]);
3018
1503
  }
3019
1504
 
@@ -3040,7 +1525,14 @@ export class TerrainTiles extends Object3D implements IComputeDriven {
3040
1525
  geometry.boundingSphere = previous.boundingSphere?.clone() ?? null;
3041
1526
  const influences = level.mesh.morphTargetInfluences?.slice();
3042
1527
  // Three caches morph textures by geometry, ignoring attribute versions; retire that cache.
3043
- for (const _ of buildLodMorphTargets({ ...level, geometry }, coarser, shared, false)) {
1528
+ geometry.morphAttributes = { ...previous.morphAttributes };
1529
+ for (const _ of buildLodMorphTargets(
1530
+ { ...level, geometry },
1531
+ coarser,
1532
+ shared,
1533
+ false,
1534
+ previous,
1535
+ )) {
3044
1536
  }
3045
1537
  level.geometry = geometry;
3046
1538
  level.mesh.geometry = geometry;