@threenative/core 0.3.4 → 0.3.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/capabilities.json +1505 -79
- package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
- package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
- package/dist/{game-CljaDv4D.d.ts → game-Jz4Fdoeb.d.ts} +114 -11
- package/dist/hot.d.ts +4 -4
- package/dist/index.d.ts +712 -118
- package/dist/index.js +12437 -4955
- package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
- package/dist/playtest.d.ts +6 -10
- package/dist/playtest.js +57 -24
- package/dist/react-css.d.ts +62 -0
- package/dist/react-css.js +591 -0
- package/dist/react.d.ts +2 -2
- package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
- package/dist/terrain-jobs-worker.d.ts +2 -0
- package/dist/terrain-jobs-worker.js +130 -0
- package/dist/ui-layer.js +59 -8
- package/dist/world.d.ts +766 -73
- package/dist/world.js +9307 -3543
- package/gpl/recipes/export_world.py +18 -1
- package/mcp/blender-server.mjs +7 -4
- package/mcp/blender.mjs +3 -4
- package/mcp/engine-server.mjs +2 -2
- package/mcp/servers.mjs +4 -4
- package/package.json +15 -9
- package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
- package/patches/three@0.185.1.patch +6594 -700
- package/scripts/apply-three-patch.mjs +62 -4
- package/src/animation-blend.ts +264 -0
- package/src/animation-composition.ts +362 -0
- package/src/animation-layers.ts +260 -0
- package/src/animation-root-motion.ts +283 -0
- package/src/animation.ts +896 -0
- package/src/assets.ts +1303 -0
- package/src/atmosphere/index.ts +335 -0
- package/src/atmosphere/luts.ts +298 -0
- package/src/atmosphere/params.ts +323 -0
- package/src/audio.ts +912 -0
- package/src/billboard.ts +124 -0
- package/src/bone-lengths.ts +157 -0
- package/src/camera-shake.ts +116 -0
- package/src/canvas-layer.ts +47 -0
- package/src/clip-audit.ts +401 -0
- package/src/clustered-batch.ts +492 -0
- package/src/clustered-mesh.ts +638 -0
- package/src/compute-driven.ts +176 -0
- package/src/compute-timing.ts +318 -0
- package/src/config.ts +593 -0
- package/src/debug.ts +82 -0
- package/src/engine-render-hook.ts +25 -0
- package/src/entities.ts +79 -0
- package/src/entity-snapshot.ts +53 -0
- package/src/flight.ts +683 -0
- package/src/fluid-field.ts +748 -0
- package/src/fluid-particles.ts +1253 -0
- package/src/frame-budget.ts +1368 -0
- package/src/game.ts +2408 -0
- package/src/geometry-capture.ts +1098 -0
- package/src/gpu-class.ts +160 -0
- package/src/gpu-frame-observation.ts +424 -0
- package/src/gpu-readback.ts +143 -0
- package/src/gpu-scene-bvh.ts +464 -0
- package/src/grounding.ts +100 -0
- package/src/hot.ts +161 -0
- package/src/import-meta.d.ts +13 -0
- package/src/index.ts +1536 -0
- package/src/input.ts +690 -0
- package/src/instanced-batch-lod.ts +283 -0
- package/src/instanced-batch.ts +274 -0
- package/src/interpolation.ts +129 -0
- package/src/launch-diagnostics.ts +161 -0
- package/src/loop.ts +574 -0
- package/src/matrix-world.ts +245 -0
- package/src/merge-parts.ts +812 -0
- package/src/model-lod.ts +1315 -0
- package/src/net-protocol.ts +333 -0
- package/src/net-session.ts +477 -0
- package/src/net.ts +80 -0
- package/src/ocean/fft.ts +72 -0
- package/src/ocean/spectral.ts +728 -0
- package/src/particle-significance.ts +102 -0
- package/src/particles.ts +648 -0
- package/src/path-follow.ts +175 -0
- package/src/picking.ts +250 -0
- package/src/pipeline-census.ts +1566 -0
- package/src/platform.ts +210 -0
- package/src/playtest.ts +850 -0
- package/src/pointer-events.ts +411 -0
- package/src/pose-measure.ts +435 -0
- package/src/profiling/FrameCounters.ts +231 -0
- package/src/profiling/Spans.ts +548 -0
- package/src/profiling/opacity-convention.ts +21 -0
- package/src/profiling/render-list-validate.ts +175 -0
- package/src/profiling/render-trap-audit.ts +84 -0
- package/src/profiling/scene-warning.ts +190 -0
- package/src/profiling/span-probes.ts +191 -0
- package/src/profiling/unlit-foliage-warning.ts +149 -0
- package/src/projection-apply.ts +1529 -0
- package/src/projection-marker.ts +142 -0
- package/src/projection-plan.ts +1258 -0
- package/src/projection-skinned.ts +419 -0
- package/src/projection-stability.ts +409 -0
- package/src/projection-uniform.ts +328 -0
- package/src/random.ts +41 -0
- package/src/react-css.ts +604 -0
- package/src/react-glyphs.ts +114 -0
- package/src/react-host.ts +576 -0
- package/src/react-layout.ts +265 -0
- package/src/react.ts +60 -0
- package/src/render/alpha-antialiasing.ts +159 -0
- package/src/render/batched-velocity.ts +126 -0
- package/src/render/chain.ts +1021 -0
- package/src/render/daylight.ts +189 -0
- package/src/render/depth-pyramid.ts +596 -0
- package/src/render/foliage-alpha.ts +166 -0
- package/src/render/material-key.ts +60 -0
- package/src/render/mesh-pool.ts +144 -0
- package/src/render/probe-volume.ts +1668 -0
- package/src/render/resolution-subrect.ts +253 -0
- package/src/render/velocity.ts +442 -0
- package/src/render/virtual-shadow-pages.ts +827 -0
- package/src/render/virtual-shadow-partial.ts +174 -0
- package/src/render/virtual-shadow.ts +3330 -0
- package/src/render/world-impostor-surface.ts +722 -0
- package/src/render/world-impostor.ts +558 -0
- package/src/render-camera-cull.ts +441 -0
- package/src/render-pass-budget.ts +501 -0
- package/src/renderProjection.ts +758 -0
- package/src/renderer-config.ts +127 -0
- package/src/renderer.ts +1847 -0
- package/src/replay-protocol.ts +85 -0
- package/src/replay.ts +205 -0
- package/src/resolution-scaler.ts +819 -0
- package/src/rig-preparation.ts +271 -0
- package/src/ripple-field.ts +432 -0
- package/src/scale.ts +109 -0
- package/src/scene.ts +239 -0
- package/src/schedule.ts +155 -0
- package/src/skeletal-mesh.ts +61 -0
- package/src/skeleton.ts +100 -0
- package/src/snow-field.ts +744 -0
- package/src/softbody-topology.ts +269 -0
- package/src/softbody.ts +516 -0
- package/src/sprite-animator.ts +222 -0
- package/src/startup-readiness.ts +386 -0
- package/src/state.ts +66 -0
- package/src/static-transform.ts +274 -0
- package/src/storage-buffer.ts +253 -0
- package/src/streaming.ts +308 -0
- package/src/target-fps.ts +92 -0
- package/src/terrain-jobs-worker.ts +17 -0
- package/src/terrain-jobs.ts +353 -0
- package/src/textures.ts +39 -0
- package/src/tracers.ts +237 -0
- package/src/ui-bridge.ts +368 -0
- package/src/ui-hit-regions.ts +380 -0
- package/src/ui-layer.ts +83 -0
- package/src/ui-state.ts +220 -0
- package/src/version.ts +2 -0
- package/src/viewport.ts +253 -0
- package/src/warmup.ts +1357 -0
- package/src/water-surface.ts +384 -0
- package/src/wave-field.ts +524 -0
- package/src/world-capabilities.ts +131 -0
- package/src/world-cell-proxy.ts +392 -0
- package/src/world-cells.ts +10564 -0
- package/src/world-gpu-scene.ts +3354 -0
- package/src/world-heightmap.ts +82 -0
- package/src/world-package.ts +469 -0
- package/src/world-passes.ts +582 -0
- package/src/world-region.ts +17 -0
- package/src/world-terrain-splat.ts +564 -0
- package/src/world-tiles.ts +3826 -0
- package/src/world-topology.ts +370 -0
- package/src/world-validate.ts +48 -0
- package/src/world.ts +805 -0
|
@@ -0,0 +1,3826 @@
|
|
|
1
|
+
import {
|
|
2
|
+
Box3,
|
|
3
|
+
BufferAttribute,
|
|
4
|
+
BufferGeometry,
|
|
5
|
+
type Camera,
|
|
6
|
+
LOD,
|
|
7
|
+
type Matrix4,
|
|
8
|
+
Mesh,
|
|
9
|
+
Object3D,
|
|
10
|
+
Sphere,
|
|
11
|
+
Vector3,
|
|
12
|
+
} from "three";
|
|
13
|
+
import type { InterleavedBufferAttribute } from "three";
|
|
14
|
+
import type { IAssetLoader } from "./assets.js";
|
|
15
|
+
import type { IComputeDriven } from "./compute-driven.js";
|
|
16
|
+
import {
|
|
17
|
+
type ILodView,
|
|
18
|
+
type IModelLodPolicy,
|
|
19
|
+
conservativeViewDepth,
|
|
20
|
+
projectedLodError,
|
|
21
|
+
selectLodLevel,
|
|
22
|
+
worldSphere,
|
|
23
|
+
} from "./model-lod.js";
|
|
24
|
+
import { SPANS, type SpanId, addSpan, spanNow, spanRecorder } from "./profiling/Spans.js";
|
|
25
|
+
import type { IRendererLike } from "./renderer.js";
|
|
26
|
+
import {
|
|
27
|
+
type ITerrainBridgeAttributes,
|
|
28
|
+
type ITerrainEdgeFrame,
|
|
29
|
+
type ITerrainEdgeJob,
|
|
30
|
+
type ITerrainFineEdgeJob,
|
|
31
|
+
type ITerrainJobRunner,
|
|
32
|
+
type ITerrainMergeJob,
|
|
33
|
+
type ITerrainMergeResult,
|
|
34
|
+
type ITerrainSeamJob,
|
|
35
|
+
createTerrainJobRunner,
|
|
36
|
+
edgeWorldPoint,
|
|
37
|
+
} from "./terrain-jobs.js";
|
|
38
|
+
import { summarizeWorldTopology } from "./world-topology.js";
|
|
39
|
+
import { terrainValidationRequested } from "./world-validate.js";
|
|
40
|
+
import {
|
|
41
|
+
Heightfield,
|
|
42
|
+
type IHeightfieldOrigin,
|
|
43
|
+
type IHeightfieldSamplerOptions,
|
|
44
|
+
type IHeightfieldWorldPassOptions,
|
|
45
|
+
} from "./world.js";
|
|
46
|
+
|
|
47
|
+
type MeshSurface = NonNullable<ConstructorParameters<typeof Mesh>[1]>;
|
|
48
|
+
|
|
49
|
+
export interface IWorldTileCollider {
|
|
50
|
+
dispose(): void;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface IWorldTileColliderInput {
|
|
54
|
+
readonly field: Heightfield;
|
|
55
|
+
readonly key: string;
|
|
56
|
+
readonly object: Object3D;
|
|
57
|
+
readonly tileX: number;
|
|
58
|
+
readonly tileZ: number;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* One frame's allowance for admission work — the millisecond budget every path that puts streamed
|
|
63
|
+
* content on screen draws on, spent in bounded units rather than in one lump.
|
|
64
|
+
*
|
|
65
|
+
* `admit` is the whole contract: run one unit and charge the frame for it, or report that there was
|
|
66
|
+
* no room and run nothing. A caller that is refused leaves the work for a later frame instead of
|
|
67
|
+
* dropping it, so the budget decides *when* content is admitted, never *whether*.
|
|
68
|
+
*
|
|
69
|
+
* Nothing here decides what anything looks like; it decides only how much of it a frame may pay for.
|
|
70
|
+
*/
|
|
71
|
+
export interface IAdmissionBudget {
|
|
72
|
+
/**
|
|
73
|
+
* Run one unit of admission work, charging the frame's budget for it. `false` means the budget
|
|
74
|
+
* was spent and `work` was never called, so the caller must stop and resume on a later frame.
|
|
75
|
+
*/
|
|
76
|
+
admit(work: () => void): boolean;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface IWorldTile {
|
|
80
|
+
readonly bytes: number;
|
|
81
|
+
/** `undefined` for a resident tile outside `colliderRadius`, or when no factory was given. */
|
|
82
|
+
readonly collider: IWorldTileCollider | undefined;
|
|
83
|
+
readonly field: Heightfield;
|
|
84
|
+
readonly key: string;
|
|
85
|
+
readonly lod: LOD;
|
|
86
|
+
readonly lodLevel: number;
|
|
87
|
+
readonly object: Object3D;
|
|
88
|
+
readonly skirtVertexCount: number;
|
|
89
|
+
readonly tileX: number;
|
|
90
|
+
readonly tileZ: number;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface IWorldTilesFollowPosition {
|
|
94
|
+
readonly x: number;
|
|
95
|
+
readonly z: number;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Actual render view and the resolved model LOD policy; distance floors still apply. */
|
|
99
|
+
export interface IWorldTilesLodView
|
|
100
|
+
extends Pick<ILodView, "camera" | "viewportHeight">,
|
|
101
|
+
IModelLodPolicy {}
|
|
102
|
+
|
|
103
|
+
export interface IWorldTilesTopologyObservation {
|
|
104
|
+
readonly columns: number;
|
|
105
|
+
readonly depth: number;
|
|
106
|
+
readonly origin: IHeightfieldOrigin;
|
|
107
|
+
readonly rows: number;
|
|
108
|
+
readonly width: number;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export interface IWorldTilesOptions {
|
|
112
|
+
/** Releases a caller-supplied model key when its last tile reference is evicted. */
|
|
113
|
+
readonly assets?: Pick<IAssetLoader, "release">;
|
|
114
|
+
/** A game-owned, already-loaded logical model key, or a key resolver per tile. */
|
|
115
|
+
readonly assetKey?: string | ((tileX: number, tileZ: number) => string);
|
|
116
|
+
/**
|
|
117
|
+
* Chebyshev radius, in tiles from the followed one, that gets a `createCollider` body. Defaults
|
|
118
|
+
* to `streamRadius`, so every resident tile collides. A smaller radius keeps a wide render ring
|
|
119
|
+
* cheap to simulate: a tile crossing the radius has its collider created or disposed as it goes.
|
|
120
|
+
*/
|
|
121
|
+
readonly colliderRadius?: number;
|
|
122
|
+
/** Terrain tiles and seam bridges receive the scene's shadows. Default false. */
|
|
123
|
+
readonly receiveShadow?: boolean;
|
|
124
|
+
/** Creates the physics body from the field's explicit collider-order copy. */
|
|
125
|
+
readonly createCollider?: (input: IWorldTileColliderInput) => IWorldTileCollider;
|
|
126
|
+
/** TSL pass options are game supplied and are forwarded to each resident field. */
|
|
127
|
+
readonly worldPasses?: IHeightfieldWorldPassOptions;
|
|
128
|
+
/** Game-owned surface; this class never creates or mutates it. */
|
|
129
|
+
readonly surface: MeshSurface;
|
|
130
|
+
readonly residentByteBudget: number;
|
|
131
|
+
readonly residentTileBudget: number;
|
|
132
|
+
readonly sampleHeight: IHeightfieldSamplerOptions["sampleHeight"];
|
|
133
|
+
/** How deep each edge skirt extends below its surface. Defaults to one tile width. */
|
|
134
|
+
readonly skirtDepth?: number;
|
|
135
|
+
/** Square tile neighborhood to consider around the followed point. Defaults to 1. */
|
|
136
|
+
readonly streamRadius?: number;
|
|
137
|
+
readonly tileResolution: number;
|
|
138
|
+
readonly tileSize: number;
|
|
139
|
+
/** Vertex decimation factors. Defaults to 1, 2, and 4 over the same field. */
|
|
140
|
+
readonly lodFactors?: readonly number[];
|
|
141
|
+
/** Nearest world-unit distances at which the next LOD may become active; screen error may delay it. */
|
|
142
|
+
readonly lodDistances?: readonly number[];
|
|
143
|
+
/**
|
|
144
|
+
* Re-derive the terrain every frame and assert it: a finiteness scan of every rendered vertex,
|
|
145
|
+
* a seam measurement per resident pair and an LOD pop sample per blending tile. Off by default
|
|
146
|
+
* because it is a measurement and it cost ~270 ms over a six-second walk on a 289-tile ring.
|
|
147
|
+
* `TN_TERRAIN_VALIDATE=1` or `?tnTerrainValidate=1` turns it on for a run; this overrides that.
|
|
148
|
+
*/
|
|
149
|
+
readonly validate?: boolean;
|
|
150
|
+
/**
|
|
151
|
+
* Merge settled same-LOD terrain tiles into super-tiles: one mesh per K×K block, one block rebuilt
|
|
152
|
+
* per frame. It changes how many draws the main pass submits, never how the ground looks — a merged
|
|
153
|
+
* vertex lands on the world position its tile's vertex did, on the same game-owned `surface`.
|
|
154
|
+
*
|
|
155
|
+
* On by default, like `validate`'s measurements are off by default only because they cost a
|
|
156
|
+
* measurement a frame. `mergeTiles: false`, `?tnTerrainMerge=0` or `TN_TERRAIN_MERGE=0` turns it
|
|
157
|
+
* off for a run. A block's bytes are reported as `terrainTiles.blockBytes` and are never charged to
|
|
158
|
+
* `residentByteBudget`, so the merge changes draws and no tile the budget would admit without it.
|
|
159
|
+
*/
|
|
160
|
+
readonly mergeTiles?: boolean;
|
|
161
|
+
/** Explicit game-owned measurement region used by the topology evaluator. */
|
|
162
|
+
readonly topologyObservation?: IWorldTilesTopologyObservation;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
interface ILevelGeometry {
|
|
166
|
+
surfaceError: number;
|
|
167
|
+
readonly edgeSamples: IEdgeSamples;
|
|
168
|
+
geometry: BufferGeometry;
|
|
169
|
+
readonly mesh: Mesh;
|
|
170
|
+
readonly resolution: number;
|
|
171
|
+
readonly skirtDepth: number;
|
|
172
|
+
readonly skirtVertexCount: number;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
interface IEdgeSamples {
|
|
176
|
+
readonly east: Float32Array;
|
|
177
|
+
readonly north: Float32Array;
|
|
178
|
+
readonly south: Float32Array;
|
|
179
|
+
readonly west: Float32Array;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
interface IResidentTile extends Omit<IWorldTile, "lodLevel"> {
|
|
183
|
+
readonly assetKey?: string;
|
|
184
|
+
collider: IWorldTileCollider | undefined;
|
|
185
|
+
readonly levels: readonly ILevelGeometry[];
|
|
186
|
+
lodTransition?: ILodTransition;
|
|
187
|
+
lodLevel: number;
|
|
188
|
+
sharedMorphEdges: number;
|
|
189
|
+
/** Coarsest level whose height error against every finer level stays inside the pop bound. */
|
|
190
|
+
readonly maxLodLevel: number;
|
|
191
|
+
readonly origin: IHeightfieldOrigin;
|
|
192
|
+
readonly skirts: number;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
interface ILodTransition {
|
|
196
|
+
readonly from: number;
|
|
197
|
+
readonly to: number;
|
|
198
|
+
elapsedFrames: number;
|
|
199
|
+
remainingFrames: number;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
interface IStitchBridge {
|
|
203
|
+
readonly keys: readonly [string, string];
|
|
204
|
+
geometry: BufferGeometry;
|
|
205
|
+
readonly mesh: Mesh;
|
|
206
|
+
resolution: number;
|
|
207
|
+
coverageDepth: number;
|
|
208
|
+
bytes: number;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
interface ILodFrameSnapshot {
|
|
212
|
+
readonly heights: Float32Array;
|
|
213
|
+
readonly resolution: number;
|
|
214
|
+
readonly tile: IResidentTile;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** One super-tile: a same-LOD block's settled level geometries held as a single draw. */
|
|
218
|
+
interface IMergedBlock {
|
|
219
|
+
readonly key: string;
|
|
220
|
+
readonly lod: number;
|
|
221
|
+
readonly geometry: BufferGeometry;
|
|
222
|
+
readonly mesh: Mesh;
|
|
223
|
+
/** This block's own geometry bytes, reported through `terrainTiles.blockBytes`. */
|
|
224
|
+
bytes: number;
|
|
225
|
+
/** The tile keys whose current level geometry this block holds, kept equal to what its geometry
|
|
226
|
+
* actually holds: a record the geometry has moved past double-draws the tiles that left and hides
|
|
227
|
+
* the ones that joined. */
|
|
228
|
+
members: Set<string>;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* A pair's observed seam state, one per coverage mode, and the observation pass that last saw each
|
|
233
|
+
* of them. Both modes live in one record so a pass marks what it visited and prunes what it did
|
|
234
|
+
* not without building a `${key}|coverage` string and a Set of them for every resident pair.
|
|
235
|
+
*/
|
|
236
|
+
interface ISeamObservation {
|
|
237
|
+
coverage: number[] | undefined;
|
|
238
|
+
plain: number[] | undefined;
|
|
239
|
+
seenCoverage: number;
|
|
240
|
+
seenPlain: number;
|
|
241
|
+
}
|
|
242
|
+
|
|
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
|
+
}
|
|
1976
|
+
|
|
1977
|
+
/**
|
|
1978
|
+
* Stream a bounded square of game-authored heightfields and keep their render and physics units
|
|
1979
|
+
* together. The class composes ordinary THREE.LOD objects and leaves frustum/projection culling
|
|
1980
|
+
* to the renderer's existing scene path.
|
|
1981
|
+
*
|
|
1982
|
+
* @situation stream terrain without cracks
|
|
1983
|
+
* @situation keep generated terrain resident around a moving player
|
|
1984
|
+
* @situation put a generated terrain tile into a game-owned physics world
|
|
1985
|
+
* @alias stream terrain across chunks
|
|
1986
|
+
* @constraint sampleHeight and surface are required game choices; no landform or surface preset is installed
|
|
1987
|
+
* @constraint residentTileBudget and residentByteBudget are hard caps; a tile that cannot fit throws
|
|
1988
|
+
* @constraint seam gap, LOD pop and the rendered-vertex finiteness scan are measurements that are off by default; TN_TERRAIN_VALIDATE=1, ?tnTerrainValidate=1 or validate: true runs them, and maxSeamGap, maxVisualSeamGap and maxLodPop report undefined while they are off
|
|
1989
|
+
* @override tileSize, tileResolution, lodFactors, lodDistances, skirtDepth, streamRadius, colliderRadius, mergeTiles, validate, and budgets
|
|
1990
|
+
* @example const tiles = new TerrainTiles({ sampleHeight, surface: gameSurface(), tileSize: 256, tileResolution: 129, residentTileBudget: 25, residentByteBudget: 32_000_000 });
|
|
1991
|
+
*/
|
|
1992
|
+
export class TerrainTiles extends Object3D implements IComputeDriven {
|
|
1993
|
+
readonly #options: IWorldTilesOptions;
|
|
1994
|
+
#snapshotChildren: Object3D[] = [];
|
|
1995
|
+
readonly residentTileBudget: number;
|
|
1996
|
+
readonly residentByteBudget: number;
|
|
1997
|
+
readonly skirtDepth: number;
|
|
1998
|
+
readonly tileResolution: number;
|
|
1999
|
+
readonly tileSize: number;
|
|
2000
|
+
readonly processCadence = "render" as const;
|
|
2001
|
+
readonly #assets: Pick<IAssetLoader, "release"> | undefined;
|
|
2002
|
+
readonly #assetKey: IWorldTilesOptions["assetKey"];
|
|
2003
|
+
readonly #colliderRadius: number;
|
|
2004
|
+
readonly #receiveShadow: boolean;
|
|
2005
|
+
readonly #createCollider: IWorldTilesOptions["createCollider"];
|
|
2006
|
+
readonly #factors: readonly number[];
|
|
2007
|
+
readonly #lodDistances: readonly number[];
|
|
2008
|
+
readonly #surface: MeshSurface;
|
|
2009
|
+
readonly #sampleHeight: IWorldTilesOptions["sampleHeight"];
|
|
2010
|
+
readonly #streamRadius: number;
|
|
2011
|
+
/** Diagnostics outlive construction; their canonical field is never used by resident tiles. */
|
|
2012
|
+
#topology:
|
|
2013
|
+
| (Pick<Heightfield, "columns" | "depth" | "origin" | "rows" | "width"> & {
|
|
2014
|
+
heights?: number[];
|
|
2015
|
+
flow?: number[];
|
|
2016
|
+
metrics?: ReturnType<typeof summarizeWorldTopology>;
|
|
2017
|
+
})
|
|
2018
|
+
| undefined;
|
|
2019
|
+
#topologyBytes = 0;
|
|
2020
|
+
readonly #worldPasses: IHeightfieldWorldPassOptions | undefined;
|
|
2021
|
+
readonly #resident = new Map<string, IResidentTile>();
|
|
2022
|
+
#morphEdgesDirty = false;
|
|
2023
|
+
#construction: { key: string; work: Generator<void, IResidentTile> } | undefined;
|
|
2024
|
+
#focus: IWorldTilesFollowPosition | undefined;
|
|
2025
|
+
#lodView: IWorldTilesLodView | undefined;
|
|
2026
|
+
readonly #lodErrors: number[] = [];
|
|
2027
|
+
#peakBytes = 0;
|
|
2028
|
+
#peakTiles = 0;
|
|
2029
|
+
#lodTransitions = 0;
|
|
2030
|
+
readonly #blending = new Set<IResidentTile>();
|
|
2031
|
+
/** Merged super-tiles by block key, and the blocks a LOD or residency change left to rebuild. */
|
|
2032
|
+
readonly #blocks = new Map<string, IMergedBlock>();
|
|
2033
|
+
readonly #dirtyBlocks = new Set<string>();
|
|
2034
|
+
/**
|
|
2035
|
+
* Blocks whose merge job is out. A block re-dirtied while its own merge is in flight stays dirty
|
|
2036
|
+
* and waits: dispatching it again would merge the same block twice, and the older reply would land
|
|
2037
|
+
* first carrying the membership the block had when it was sent — a snapshot that no longer matches
|
|
2038
|
+
* the resident set, so the record claims tiles its geometry does not hold and the second reply has
|
|
2039
|
+
* to correct it. (PRD-478.)
|
|
2040
|
+
*/
|
|
2041
|
+
readonly #mergingBlocks = new Set<string>();
|
|
2042
|
+
/** Tile key -> block key currently hiding it, so a settled member is not drawn twice. */
|
|
2043
|
+
readonly #mergedMembers = new Map<string, string>();
|
|
2044
|
+
#blockRebuilds = 0;
|
|
2045
|
+
/** Merged super-tile bytes, reported beside the tiles they duplicate and never charged to them. */
|
|
2046
|
+
#blockBytes = 0;
|
|
2047
|
+
#tilesToldAt = Number.NEGATIVE_INFINITY;
|
|
2048
|
+
readonly #mergeTiles: boolean;
|
|
2049
|
+
// The last `follow` ran out of admission budget before it wanted everything, so the next one
|
|
2050
|
+
// has to run even if the follow point has not moved. Cleared at the top of `follow`.
|
|
2051
|
+
#deferredAdmissions = 0;
|
|
2052
|
+
#maxLodPop = 0;
|
|
2053
|
+
#maxLodTransitionFrames = 0;
|
|
2054
|
+
// These diagnostics are lifetime maxima for this residency owner. Zero is the deliberate
|
|
2055
|
+
// empty/evicted value; each finite live-geometry observation can only increase it.
|
|
2056
|
+
#maxSeamGap = 0;
|
|
2057
|
+
#maxVisualSeamGap = 0;
|
|
2058
|
+
#stitchedEdges = 0;
|
|
2059
|
+
#stitchBytes = 0;
|
|
2060
|
+
readonly #stitches = new Map<string, IStitchBridge>();
|
|
2061
|
+
/** Each pair's `seamState` as the last reconcile left it, so a settled seam is not redone. */
|
|
2062
|
+
readonly #pairSignatures = new Map<string, number[]>();
|
|
2063
|
+
/** The state each pair was last observed in, per coverage mode, so a settled seam is not re-measured. */
|
|
2064
|
+
readonly #observedSeams = new Map<string, ISeamObservation>();
|
|
2065
|
+
/** Counts the observation passes, so a pass marks what it saw instead of building a live set. */
|
|
2066
|
+
#observationPass = 0;
|
|
2067
|
+
/** The facing pairs a pass walks, reused so a frame allocates no pair arrays. */
|
|
2068
|
+
readonly #pairScratch: NeighborPair[] = [];
|
|
2069
|
+
/** The ring state the last full seam pass left behind; `undefined` until one has run. */
|
|
2070
|
+
#settledRing: number[] | undefined;
|
|
2071
|
+
/**
|
|
2072
|
+
* The buffer a frame measures its ring state into before comparing it, and the one the last pass
|
|
2073
|
+
* settled. Two buffers trade places instead of being reallocated, because a settled 289-tile ring
|
|
2074
|
+
* measures some twenty thousand numbers a frame and building that many arrays was itself the cost
|
|
2075
|
+
* this fast path exists to avoid.
|
|
2076
|
+
*/
|
|
2077
|
+
#ringScratch: number[] = [];
|
|
2078
|
+
/**
|
|
2079
|
+
* Bumped by every writer of the state the ring pass describes, and the epoch the last pass settled
|
|
2080
|
+
* at. The shipped frame's change detector; see {@link #seamPass}. `-1` so the first pass runs.
|
|
2081
|
+
*/
|
|
2082
|
+
#ringEpoch = 0;
|
|
2083
|
+
#seamEpoch = -1;
|
|
2084
|
+
/**
|
|
2085
|
+
* A seam pass whose strips are still being built off this thread, so a frame that arrives before the
|
|
2086
|
+
* reply does not start a second pass over the same pairs and write them twice.
|
|
2087
|
+
*/
|
|
2088
|
+
#seamPending = false;
|
|
2089
|
+
/**
|
|
2090
|
+
* Where the block merges and the seam strips are built. A module worker where the host has one, this
|
|
2091
|
+
* thread where it does not, from the same function either way.
|
|
2092
|
+
*/
|
|
2093
|
+
readonly #jobs: ITerrainJobRunner;
|
|
2094
|
+
#released = false;
|
|
2095
|
+
#renderer: IRendererLike | undefined;
|
|
2096
|
+
/**
|
|
2097
|
+
* Whether the per-frame measurements run. Off by default: they assert what the shipped frame
|
|
2098
|
+
* trusts, and every observation getter below reports `undefined` while they are off, so a caller
|
|
2099
|
+
* can never read an unmeasured zero as a measurement.
|
|
2100
|
+
*/
|
|
2101
|
+
readonly #validate: boolean;
|
|
2102
|
+
|
|
2103
|
+
constructor(options: IWorldTilesOptions) {
|
|
2104
|
+
super();
|
|
2105
|
+
this.#options = { ...options };
|
|
2106
|
+
this.#jobs = createTerrainJobRunner();
|
|
2107
|
+
this.tileSize = positive(options.tileSize, "tileSize");
|
|
2108
|
+
this.tileResolution = integerAtLeast(options.tileResolution, 3, "tileResolution");
|
|
2109
|
+
this.residentTileBudget = integerAtLeast(options.residentTileBudget, 1, "residentTileBudget");
|
|
2110
|
+
this.residentByteBudget = integerAtLeast(options.residentByteBudget, 1, "residentByteBudget");
|
|
2111
|
+
this.skirtDepth = positive(options.skirtDepth ?? this.tileSize, "skirtDepth");
|
|
2112
|
+
this.#streamRadius = integerAtLeast(options.streamRadius ?? 1, 0, "streamRadius");
|
|
2113
|
+
this.#receiveShadow = options.receiveShadow === true;
|
|
2114
|
+
this.#colliderRadius = integerAtLeast(
|
|
2115
|
+
options.colliderRadius ?? this.#streamRadius,
|
|
2116
|
+
0,
|
|
2117
|
+
"colliderRadius",
|
|
2118
|
+
);
|
|
2119
|
+
this.#surface = options.surface;
|
|
2120
|
+
if (options.surface === undefined || options.surface === null)
|
|
2121
|
+
throw new Error("TerrainTiles surface is required and must be game-owned.");
|
|
2122
|
+
this.#validate = options.validate ?? terrainValidationRequested();
|
|
2123
|
+
this.#mergeTiles = options.mergeTiles ?? !terrainMergeOptedOut();
|
|
2124
|
+
this.#sampleHeight = options.sampleHeight;
|
|
2125
|
+
if (typeof options.sampleHeight !== "function")
|
|
2126
|
+
throw new Error("TerrainTiles sampleHeight is required.");
|
|
2127
|
+
this.#factors = [...(options.lodFactors ?? [1, 2, 4])];
|
|
2128
|
+
if (this.#factors.length < 1) throw new Error("TerrainTiles lodFactors must not be empty.");
|
|
2129
|
+
for (const factor of this.#factors) integerAtLeast(factor, 1, "lod factor");
|
|
2130
|
+
for (const factor of this.#factors) resolutionFor(this.tileResolution, factor);
|
|
2131
|
+
this.#lodDistances = [...(options.lodDistances ?? [this.tileSize * 2, this.tileSize * 4])];
|
|
2132
|
+
if (this.#lodDistances.length !== this.#factors.length - 1)
|
|
2133
|
+
throw new Error("TerrainTiles lodDistances must contain one threshold per LOD transition.");
|
|
2134
|
+
this.#lodDistances.forEach((distance, index) => {
|
|
2135
|
+
positive(distance, `lodDistances[${String(index)}]`);
|
|
2136
|
+
if (index > 0 && distance <= (this.#lodDistances[index - 1] as number))
|
|
2137
|
+
throw new Error("TerrainTiles lodDistances must be strictly increasing.");
|
|
2138
|
+
});
|
|
2139
|
+
if (options.assetKey !== undefined && options.assets === undefined)
|
|
2140
|
+
throw new Error("TerrainTiles assetKey requires an assets.release consumer.");
|
|
2141
|
+
this.#assets = options.assets;
|
|
2142
|
+
this.#assetKey = options.assetKey;
|
|
2143
|
+
this.#createCollider = options.createCollider;
|
|
2144
|
+
this.#worldPasses = options.worldPasses;
|
|
2145
|
+
if (options.topologyObservation !== undefined)
|
|
2146
|
+
validateTopologyObservation(options.topologyObservation, this.tileSize, this.tileResolution);
|
|
2147
|
+
const topologyField =
|
|
2148
|
+
options.topologyObservation === undefined
|
|
2149
|
+
? undefined
|
|
2150
|
+
: Heightfield.fromSampler({
|
|
2151
|
+
...options.topologyObservation,
|
|
2152
|
+
sampleHeight: this.#sampleHeight,
|
|
2153
|
+
...(this.#worldPasses === undefined ? {} : { worldPasses: this.#worldPasses }),
|
|
2154
|
+
});
|
|
2155
|
+
if (topologyField !== undefined) {
|
|
2156
|
+
try {
|
|
2157
|
+
// Admission and the peak include the full field before its diagnostic samples are released.
|
|
2158
|
+
this.#topologyBytes = topologyField.memoryBytes;
|
|
2159
|
+
if (this.#topologyBytes > this.residentByteBudget)
|
|
2160
|
+
throw new TerrainTileBudgetError(
|
|
2161
|
+
"TerrainTiles residentByteBudget cannot fit the topology observation.",
|
|
2162
|
+
);
|
|
2163
|
+
this.#recordPeaks();
|
|
2164
|
+
const heights = topologyField.heights;
|
|
2165
|
+
const flow = topologyField.flow;
|
|
2166
|
+
const description = {
|
|
2167
|
+
columns: topologyField.columns,
|
|
2168
|
+
depth: topologyField.depth,
|
|
2169
|
+
origin: topologyField.origin,
|
|
2170
|
+
rows: topologyField.rows,
|
|
2171
|
+
width: topologyField.width,
|
|
2172
|
+
};
|
|
2173
|
+
if (heights.length <= MAX_RAW_TOPOLOGY_SAMPLES) {
|
|
2174
|
+
this.#topology = {
|
|
2175
|
+
...description,
|
|
2176
|
+
heights: Array.from(heights),
|
|
2177
|
+
...(flow === undefined ? {} : { flow: Array.from(flow) }),
|
|
2178
|
+
};
|
|
2179
|
+
// Retained JS number-array payloads use eight bytes per element, not Float32's four.
|
|
2180
|
+
this.#topologyBytes = (heights.length + (flow?.length ?? 0)) * 8;
|
|
2181
|
+
} else {
|
|
2182
|
+
this.#topology = {
|
|
2183
|
+
...description,
|
|
2184
|
+
...(flow === undefined
|
|
2185
|
+
? {}
|
|
2186
|
+
: { metrics: summarizeWorldTopology({ ...description, heights, flow }) }),
|
|
2187
|
+
};
|
|
2188
|
+
this.#topologyBytes = 0;
|
|
2189
|
+
}
|
|
2190
|
+
} catch (error) {
|
|
2191
|
+
this.#jobs.dispose();
|
|
2192
|
+
throw error;
|
|
2193
|
+
} finally {
|
|
2194
|
+
topologyField.detach();
|
|
2195
|
+
}
|
|
2196
|
+
}
|
|
2197
|
+
if (this.#validate) this.#recordSeamDiagnostics();
|
|
2198
|
+
this.frustumCulled = true;
|
|
2199
|
+
}
|
|
2200
|
+
|
|
2201
|
+
/** Fresh residency and colliders; retain the visible tree until follow() regenerates it. */
|
|
2202
|
+
override clone(recursive = true): this {
|
|
2203
|
+
const copy = new TerrainTiles(this.#options).copy(this, false);
|
|
2204
|
+
const streamed = new Set<Object3D>([
|
|
2205
|
+
...this.#snapshotChildren,
|
|
2206
|
+
...[...this.#resident.values()].map((tile) => tile.lod),
|
|
2207
|
+
...[...this.#stitches.values()].map((bridge) => bridge.mesh),
|
|
2208
|
+
...[...this.#blocks.values()].map((block) => block.mesh),
|
|
2209
|
+
]);
|
|
2210
|
+
if (recursive)
|
|
2211
|
+
for (const child of this.children) {
|
|
2212
|
+
const clonedChild = child.clone();
|
|
2213
|
+
copy.add(clonedChild);
|
|
2214
|
+
if (streamed.has(child)) copy.#snapshotChildren.push(clonedChild);
|
|
2215
|
+
}
|
|
2216
|
+
return copy as this;
|
|
2217
|
+
}
|
|
2218
|
+
|
|
2219
|
+
get released(): boolean {
|
|
2220
|
+
return this.#released;
|
|
2221
|
+
}
|
|
2222
|
+
|
|
2223
|
+
get residentTileCount(): number {
|
|
2224
|
+
return this.#resident.size;
|
|
2225
|
+
}
|
|
2226
|
+
|
|
2227
|
+
/**
|
|
2228
|
+
* Every retained terrain byte, against `residentByteBudget`: the resident tiles with their levels
|
|
2229
|
+
* and edge samples, the stitch bridges, and the retained topology.
|
|
2230
|
+
*
|
|
2231
|
+
* A merged super-tile is deliberately absent. A block duplicates the level vertices of the tiles it
|
|
2232
|
+
* covers, and those tiles stay resident because a tile that leaves the block draws its own mesh
|
|
2233
|
+
* again — so charging the copy made a derived artefact evict real terrain detail out of the same
|
|
2234
|
+
* budget the tiles were admitted against, and a budget sized for unmerged terrain held fewer tiles
|
|
2235
|
+
* with the merge on. The copy is reported as `terrainTiles.blockBytes` instead. (PRD-475.)
|
|
2236
|
+
*
|
|
2237
|
+
* ponytail: terrain geometry costs up to ~2x while merged; free the per-tile GPU buffers behind a
|
|
2238
|
+
* block (keep the height field for queries) if that memory ever matters.
|
|
2239
|
+
*/
|
|
2240
|
+
get residentBytes(): number {
|
|
2241
|
+
// Read four times a frame by the residency admission and the peak record, so it accumulates
|
|
2242
|
+
// instead of materialising the resident set.
|
|
2243
|
+
let total = this.#topologyBytes + this.#stitchBytes;
|
|
2244
|
+
for (const tile of this.#resident.values()) total += tile.bytes;
|
|
2245
|
+
return total;
|
|
2246
|
+
}
|
|
2247
|
+
|
|
2248
|
+
get peakResidentTileCount(): number {
|
|
2249
|
+
return this.#peakTiles;
|
|
2250
|
+
}
|
|
2251
|
+
|
|
2252
|
+
get peakResidentBytes(): number {
|
|
2253
|
+
return this.#peakBytes;
|
|
2254
|
+
}
|
|
2255
|
+
|
|
2256
|
+
get residentKeys(): readonly string[] {
|
|
2257
|
+
return [...this.#resident.keys()].sort();
|
|
2258
|
+
}
|
|
2259
|
+
|
|
2260
|
+
get residentColliderKeys(): readonly string[] {
|
|
2261
|
+
return [...this.#resident.values()]
|
|
2262
|
+
.filter((tile) => tile.collider !== undefined)
|
|
2263
|
+
.map((tile) => tile.key)
|
|
2264
|
+
.sort();
|
|
2265
|
+
}
|
|
2266
|
+
|
|
2267
|
+
get lodLevelCount(): number {
|
|
2268
|
+
return this.#factors.length;
|
|
2269
|
+
}
|
|
2270
|
+
|
|
2271
|
+
get lodTransitions(): number {
|
|
2272
|
+
return this.#lodTransitions;
|
|
2273
|
+
}
|
|
2274
|
+
|
|
2275
|
+
/**
|
|
2276
|
+
* What the main pass submits for terrain levels right now: `tiles` surfaces, held as `blocks`
|
|
2277
|
+
* merged super-tiles plus one mesh each for the tiles that are not merged (a lone block member or
|
|
2278
|
+
* a tile mid LOD morph). `draws` is `blocks` plus those individual meshes, so with the merge off
|
|
2279
|
+
* it is exactly the number of visible level meshes — the census the merge exists to cut. `blending`
|
|
2280
|
+
* counts the resident tiles mid LOD morph, which are always among the individual meshes. A block
|
|
2281
|
+
* whose tile just left stops being drawn until its rebuild lands, and those tiles are counted as the
|
|
2282
|
+
* individual meshes they went back to — see `#releaseStaleBlock`.
|
|
2283
|
+
* `rebuilds` counts the block geometries built over this residency owner's life. `blockBytes` is
|
|
2284
|
+
* what the held blocks cost, reported and not charged to `residentByteBudget` — see `residentBytes`.
|
|
2285
|
+
*/
|
|
2286
|
+
get terrainTiles(): {
|
|
2287
|
+
readonly blockBytes: number;
|
|
2288
|
+
readonly blocks: number;
|
|
2289
|
+
readonly blending: number;
|
|
2290
|
+
readonly draws: number;
|
|
2291
|
+
readonly rebuilds: number;
|
|
2292
|
+
readonly tiles: number;
|
|
2293
|
+
} {
|
|
2294
|
+
let individual = 0;
|
|
2295
|
+
for (const tile of this.#resident.values())
|
|
2296
|
+
for (const level of tile.levels) if (level.mesh.visible) individual += 1;
|
|
2297
|
+
let merged = 0;
|
|
2298
|
+
for (const block of this.#blocks.values()) merged += block.members.size;
|
|
2299
|
+
const blocks = this.#blocks.size;
|
|
2300
|
+
return {
|
|
2301
|
+
blockBytes: this.#blockBytes,
|
|
2302
|
+
blocks,
|
|
2303
|
+
blending: this.blendingTiles,
|
|
2304
|
+
draws: individual + blocks,
|
|
2305
|
+
rebuilds: this.#blockRebuilds,
|
|
2306
|
+
tiles: individual + merged,
|
|
2307
|
+
};
|
|
2308
|
+
}
|
|
2309
|
+
|
|
2310
|
+
/**
|
|
2311
|
+
* Resident tiles mid LOD morph right now, so `process` is still owed. A blend is
|
|
2312
|
+
* `LOD_TRANSITION_FRAMES` frames long and only `process` advances it, so a caller that skips
|
|
2313
|
+
* `process` while its follow point is standing still would freeze every blend on frame one.
|
|
2314
|
+
*/
|
|
2315
|
+
get blendingTiles(): number {
|
|
2316
|
+
return this.#blending.size;
|
|
2317
|
+
}
|
|
2318
|
+
|
|
2319
|
+
/**
|
|
2320
|
+
* Maximum per-render-frame displacement of the visible LOD surface during transitions.
|
|
2321
|
+
*
|
|
2322
|
+
* `undefined` when validation is off: the pop is sampled by measuring the rendered surface twice
|
|
2323
|
+
* a frame, and reporting the empty value `0` instead of a measurement would be a lie a caller
|
|
2324
|
+
* could assert on.
|
|
2325
|
+
*/
|
|
2326
|
+
get maxLodPop(): number | undefined {
|
|
2327
|
+
return this.#validate ? this.#maxLodPop : undefined;
|
|
2328
|
+
}
|
|
2329
|
+
|
|
2330
|
+
/** Maximum number of rendered frames during which an LOD transition remained observable. */
|
|
2331
|
+
get maxLodTransitionFrames(): number {
|
|
2332
|
+
return this.#maxLodTransitionFrames;
|
|
2333
|
+
}
|
|
2334
|
+
|
|
2335
|
+
/**
|
|
2336
|
+
* Maximum visible edge gap observed across follow/process calls for this residency owner, or
|
|
2337
|
+
* `undefined` when validation is off — see `maxLodPop`.
|
|
2338
|
+
*/
|
|
2339
|
+
get maxSeamGap(): number | undefined {
|
|
2340
|
+
return this.#validate ? this.#maxSeamGap : undefined;
|
|
2341
|
+
}
|
|
2342
|
+
|
|
2343
|
+
/**
|
|
2344
|
+
* Maximum remaining visible gap after skirt or bridge coverage observed across follow/process
|
|
2345
|
+
* calls, or `undefined` when validation is off — see `maxLodPop`.
|
|
2346
|
+
*/
|
|
2347
|
+
get maxVisualSeamGap(): number | undefined {
|
|
2348
|
+
return this.#validate ? this.#maxVisualSeamGap : undefined;
|
|
2349
|
+
}
|
|
2350
|
+
|
|
2351
|
+
/** Number of mixed-LOD edge reconciliations observed during this residency lifetime. */
|
|
2352
|
+
get stitchedEdgeCount(): number {
|
|
2353
|
+
return this.#stitchedEdges;
|
|
2354
|
+
}
|
|
2355
|
+
|
|
2356
|
+
/**
|
|
2357
|
+
* A tile or a collider the last `follow` wanted and its budget refused, so the next one is owed
|
|
2358
|
+
* work even for an unmoved follow point. `0` once a pass wanted nothing it did not get.
|
|
2359
|
+
*/
|
|
2360
|
+
get deferredAdmissions(): number {
|
|
2361
|
+
return this.#deferredAdmissions;
|
|
2362
|
+
}
|
|
2363
|
+
|
|
2364
|
+
get warmupNodes(): readonly unknown[] {
|
|
2365
|
+
return [...[...this.#resident.values()].flatMap((tile) => tile.field.warmupNodes)];
|
|
2366
|
+
}
|
|
2367
|
+
|
|
2368
|
+
getTile(key: string): IWorldTile | undefined {
|
|
2369
|
+
return this.#resident.get(key);
|
|
2370
|
+
}
|
|
2371
|
+
|
|
2372
|
+
/**
|
|
2373
|
+
* Move residency to the followed point: admit, evict and re-level every tile.
|
|
2374
|
+
*
|
|
2375
|
+
* `budget` caps construction chunks as well as completed admissions. An unfinished tile stays
|
|
2376
|
+
* outside residency and resumes on a later call while it remains wanted. Moving it outside the
|
|
2377
|
+
* selected ring cancels and releases that work. Omitted, a call drains synchronously as before.
|
|
2378
|
+
* `view` shares the resolved model pixel policy; omitted, selection remains distance-only.
|
|
2379
|
+
*/
|
|
2380
|
+
follow(
|
|
2381
|
+
position: IWorldTilesFollowPosition | Pick<Vector3, "x" | "z">,
|
|
2382
|
+
budget?: IAdmissionBudget,
|
|
2383
|
+
view?: IWorldTilesLodView,
|
|
2384
|
+
): void {
|
|
2385
|
+
if (this.#released) throw new Error("TerrainTiles cannot follow after release.");
|
|
2386
|
+
for (const child of this.#snapshotChildren) this.remove(child);
|
|
2387
|
+
this.#snapshotChildren.length = 0;
|
|
2388
|
+
// This pass starts owing nothing; a refusal below sets the flag that owes the next one, so
|
|
2389
|
+
// `deferredAdmissions` is exactly "the last pass did not get everything it wanted".
|
|
2390
|
+
this.#deferredAdmissions = 0;
|
|
2391
|
+
this.#setLodView(view);
|
|
2392
|
+
const x = finite(position.x, "follow x");
|
|
2393
|
+
const z = finite(position.z, "follow z");
|
|
2394
|
+
const hadFocus = this.#focus !== undefined;
|
|
2395
|
+
this.#focus = { x, z };
|
|
2396
|
+
const centerX = Math.floor((x + this.tileSize / 2) / this.tileSize);
|
|
2397
|
+
const centerZ = Math.floor((z + this.tileSize / 2) / this.tileSize);
|
|
2398
|
+
const wanted: Array<{ distance: number; tileX: number; tileZ: number }> = [];
|
|
2399
|
+
for (
|
|
2400
|
+
let tileZ = centerZ - this.#streamRadius;
|
|
2401
|
+
tileZ <= centerZ + this.#streamRadius;
|
|
2402
|
+
tileZ += 1
|
|
2403
|
+
) {
|
|
2404
|
+
for (
|
|
2405
|
+
let tileX = centerX - this.#streamRadius;
|
|
2406
|
+
tileX <= centerX + this.#streamRadius;
|
|
2407
|
+
tileX += 1
|
|
2408
|
+
) {
|
|
2409
|
+
const tileCenterX = tileX * this.tileSize;
|
|
2410
|
+
const tileCenterZ = tileZ * this.tileSize;
|
|
2411
|
+
wanted.push({
|
|
2412
|
+
distance: Math.hypot(x - tileCenterX, z - tileCenterZ),
|
|
2413
|
+
tileX,
|
|
2414
|
+
tileZ,
|
|
2415
|
+
});
|
|
2416
|
+
}
|
|
2417
|
+
}
|
|
2418
|
+
wanted.sort((a, b) => a.distance - b.distance || a.tileZ - b.tileZ || a.tileX - b.tileX);
|
|
2419
|
+
const selected = wanted.slice(0, this.residentTileBudget);
|
|
2420
|
+
const selectedKeys = new Set(selected.map(({ tileX, tileZ }) => keyFor(tileX, tileZ)));
|
|
2421
|
+
if (this.#construction !== undefined && !selectedKeys.has(this.#construction.key))
|
|
2422
|
+
this.#cancelConstruction();
|
|
2423
|
+
for (const tile of [...this.#resident.values()]) {
|
|
2424
|
+
if (!selectedKeys.has(tile.key)) this.#evict(tile);
|
|
2425
|
+
}
|
|
2426
|
+
const targets = new Map<IResidentTile, number>();
|
|
2427
|
+
const missing: typeof selected = [];
|
|
2428
|
+
for (const candidate of selected) {
|
|
2429
|
+
const resident = this.#resident.get(keyFor(candidate.tileX, candidate.tileZ));
|
|
2430
|
+
if (resident !== undefined)
|
|
2431
|
+
targets.set(resident, this.#targetLod(resident, candidate.distance));
|
|
2432
|
+
// A selected tile keeps its construction progress when sub-tile camera motion changes the
|
|
2433
|
+
// distance order. Only leaving the wanted set cancels it; otherwise a jittering camera could
|
|
2434
|
+
// restart two equally near tiles forever.
|
|
2435
|
+
else if (keyFor(candidate.tileX, candidate.tileZ) === this.#construction?.key)
|
|
2436
|
+
missing.unshift(candidate);
|
|
2437
|
+
else missing.push(candidate);
|
|
2438
|
+
}
|
|
2439
|
+
// Even an already-spent allowance advances one chunk of pending work, starting nearest first.
|
|
2440
|
+
// The progress floor closes the ring without forcing an entire tile through one frame.
|
|
2441
|
+
let built = 0;
|
|
2442
|
+
for (const candidate of missing) {
|
|
2443
|
+
const key = keyFor(candidate.tileX, candidate.tileZ);
|
|
2444
|
+
const estimate = estimatedTileBytes(
|
|
2445
|
+
this.tileResolution,
|
|
2446
|
+
this.#factors,
|
|
2447
|
+
this.#worldPasses,
|
|
2448
|
+
this.#validate,
|
|
2449
|
+
);
|
|
2450
|
+
if (this.residentBytes + estimate > this.residentByteBudget) {
|
|
2451
|
+
if (this.#construction?.key === key) this.#cancelConstruction();
|
|
2452
|
+
if (candidate.tileX === centerX && candidate.tileZ === centerZ)
|
|
2453
|
+
throw new TerrainTileBudgetError(
|
|
2454
|
+
"TerrainTiles residentByteBudget cannot fit the followed tile.",
|
|
2455
|
+
);
|
|
2456
|
+
continue;
|
|
2457
|
+
}
|
|
2458
|
+
// Keep incomplete work out of the scene; later calls resume it under the same allowance.
|
|
2459
|
+
const tile = this.#admitCandidate(candidate, centerX, centerZ, budget, built === 0);
|
|
2460
|
+
if (tile === undefined) break;
|
|
2461
|
+
built += 1;
|
|
2462
|
+
if (this.residentBytes + tile.bytes > this.residentByteBudget) {
|
|
2463
|
+
this.#disposeTile(tile);
|
|
2464
|
+
if (candidate.tileX === centerX && candidate.tileZ === centerZ)
|
|
2465
|
+
throw new TerrainTileBudgetError(
|
|
2466
|
+
"TerrainTiles residentByteBudget cannot fit the followed tile.",
|
|
2467
|
+
);
|
|
2468
|
+
continue;
|
|
2469
|
+
}
|
|
2470
|
+
this.#resident.set(tile.key, tile);
|
|
2471
|
+
this.#morphEdgesDirty = true;
|
|
2472
|
+
this.add(tile.lod);
|
|
2473
|
+
this.#selectLod(tile, candidate.distance, false);
|
|
2474
|
+
this.#markTileDirty(tile);
|
|
2475
|
+
this.#ringEpoch += 1;
|
|
2476
|
+
this.#recordPeaks();
|
|
2477
|
+
}
|
|
2478
|
+
this.#recordPeaks();
|
|
2479
|
+
this.#updateColliders(centerX, centerZ, budget);
|
|
2480
|
+
if (!this.#validate && this.#morphEdgesDirty)
|
|
2481
|
+
timedSpan(SPANS.terrainSeam, () => this.#syncMorphEdges());
|
|
2482
|
+
this.#applyLodTargets(targets);
|
|
2483
|
+
// Retargeting already coordinates the resident ring; only newly admitted tiles can owe it.
|
|
2484
|
+
if (built > 0) this.#coordinateNeighborLods(hadFocus);
|
|
2485
|
+
this.#seamPass();
|
|
2486
|
+
// After every LOD target is settled, so a block is built from the levels this pass left behind.
|
|
2487
|
+
this.#rebuildDirtyBlocks(budget);
|
|
2488
|
+
this.#recordPeaks();
|
|
2489
|
+
}
|
|
2490
|
+
|
|
2491
|
+
heightAt(x: number, z: number): number {
|
|
2492
|
+
return this.#fieldAt(x, z).heightAt(x, z);
|
|
2493
|
+
}
|
|
2494
|
+
|
|
2495
|
+
normalAt(x: number, z: number, target = new Vector3()): Vector3 {
|
|
2496
|
+
return this.#fieldAt(x, z).normalAt(x, z, target);
|
|
2497
|
+
}
|
|
2498
|
+
|
|
2499
|
+
sample(channel: string, x: number, z: number): number {
|
|
2500
|
+
if (channel === "slope") return 1 - this.normalAt(x, z).y;
|
|
2501
|
+
return this.#fieldAt(x, z).sample(channel, x, z);
|
|
2502
|
+
}
|
|
2503
|
+
|
|
2504
|
+
attachRenderer(renderer: IRendererLike): void {
|
|
2505
|
+
if (this.#released) throw new Error("TerrainTiles cannot attach after release.");
|
|
2506
|
+
this.#renderer = renderer;
|
|
2507
|
+
for (const tile of this.#resident.values()) tile.field.attachRenderer(renderer);
|
|
2508
|
+
}
|
|
2509
|
+
|
|
2510
|
+
process(
|
|
2511
|
+
renderer = this.#renderer,
|
|
2512
|
+
_camera?: Camera,
|
|
2513
|
+
_covered?: boolean,
|
|
2514
|
+
view = this.#lodView,
|
|
2515
|
+
): void {
|
|
2516
|
+
if (this.#released) return;
|
|
2517
|
+
this.#setLodView(view);
|
|
2518
|
+
if (view !== undefined && this.#focus !== undefined) {
|
|
2519
|
+
const targets = new Map<IResidentTile, number>();
|
|
2520
|
+
for (const tile of this.#resident.values())
|
|
2521
|
+
targets.set(
|
|
2522
|
+
tile,
|
|
2523
|
+
this.#targetLod(
|
|
2524
|
+
tile,
|
|
2525
|
+
Math.hypot(this.#focus.x - tile.origin.x, this.#focus.z - tile.origin.z),
|
|
2526
|
+
),
|
|
2527
|
+
);
|
|
2528
|
+
this.#applyLodTargets(targets);
|
|
2529
|
+
}
|
|
2530
|
+
const lodFrame = this.#validate ? this.#captureLodFrame() : undefined;
|
|
2531
|
+
this.#advanceLodTransitions();
|
|
2532
|
+
if (renderer !== undefined) {
|
|
2533
|
+
for (const tile of this.#resident.values()) {
|
|
2534
|
+
tile.field.attachRenderer(renderer);
|
|
2535
|
+
tile.field.process(renderer);
|
|
2536
|
+
}
|
|
2537
|
+
}
|
|
2538
|
+
this.#seamPass();
|
|
2539
|
+
// View-only retargets still owe the existing admission-budgeted block rebuild in follow.
|
|
2540
|
+
if (view !== undefined && this.#dirtyBlocks.size > 0) this.#deferredAdmissions = 1;
|
|
2541
|
+
if (lodFrame !== undefined) this.#recordLodPopAfterReconciliation(lodFrame);
|
|
2542
|
+
this.#recordPeaks();
|
|
2543
|
+
this.#reportTileMarker();
|
|
2544
|
+
}
|
|
2545
|
+
|
|
2546
|
+
/** Completed render tiles intersecting a square in world metres; pending builds do not count. */
|
|
2547
|
+
readinessAt(
|
|
2548
|
+
position: IWorldTilesFollowPosition,
|
|
2549
|
+
radius = 0,
|
|
2550
|
+
): { required: number; loaded: number } {
|
|
2551
|
+
if (
|
|
2552
|
+
!Number.isFinite(position.x) ||
|
|
2553
|
+
!Number.isFinite(position.z) ||
|
|
2554
|
+
!Number.isFinite(radius) ||
|
|
2555
|
+
radius < 0
|
|
2556
|
+
)
|
|
2557
|
+
throw new Error(
|
|
2558
|
+
"TerrainTiles readiness requires finite coordinates and a nonnegative radius.",
|
|
2559
|
+
);
|
|
2560
|
+
const lowX = Math.floor((position.x - radius + this.tileSize / 2) / this.tileSize);
|
|
2561
|
+
const highX = Math.floor((position.x + radius + this.tileSize / 2) / this.tileSize);
|
|
2562
|
+
const lowZ = Math.floor((position.z - radius + this.tileSize / 2) / this.tileSize);
|
|
2563
|
+
const highZ = Math.floor((position.z + radius + this.tileSize / 2) / this.tileSize);
|
|
2564
|
+
let loaded = 0;
|
|
2565
|
+
const required = (highX - lowX + 1) * (highZ - lowZ + 1);
|
|
2566
|
+
if (!Number.isSafeInteger(required))
|
|
2567
|
+
throw new Error("TerrainTiles readiness region is too large.");
|
|
2568
|
+
for (const tile of this.#resident.values())
|
|
2569
|
+
if (tile.tileX >= lowX && tile.tileX <= highX && tile.tileZ >= lowZ && tile.tileZ <= highZ)
|
|
2570
|
+
loaded++;
|
|
2571
|
+
return { required, loaded };
|
|
2572
|
+
}
|
|
2573
|
+
|
|
2574
|
+
debug(): Record<string, unknown> {
|
|
2575
|
+
const topology = this.#topology;
|
|
2576
|
+
const view = this.#lodView;
|
|
2577
|
+
// Inspection only: retain per-frame selection and sampling costs unchanged.
|
|
2578
|
+
const lodDecisions = [...this.#resident.values()].map((tile) => {
|
|
2579
|
+
const distance =
|
|
2580
|
+
this.#focus === undefined
|
|
2581
|
+
? 0
|
|
2582
|
+
: Math.hypot(
|
|
2583
|
+
this.#focus.x - tile.tileX * this.tileSize,
|
|
2584
|
+
this.#focus.z - tile.tileZ * this.tileSize,
|
|
2585
|
+
);
|
|
2586
|
+
const next = tile.levels[tile.lodLevel + 1];
|
|
2587
|
+
const finest = tile.levels[0];
|
|
2588
|
+
const bounds = finest?.geometry.boundingSphere;
|
|
2589
|
+
let projection: { errorPixels?: number; depth: number; degenerate: boolean } | undefined;
|
|
2590
|
+
if (view !== undefined && next !== undefined && finest !== undefined && bounds != null) {
|
|
2591
|
+
finest.mesh.updateWorldMatrix(true, false);
|
|
2592
|
+
const sphere = worldSphere(bounds, finest.mesh);
|
|
2593
|
+
const depth = conservativeViewDepth(
|
|
2594
|
+
view.camera,
|
|
2595
|
+
sphere.center,
|
|
2596
|
+
sphere.radius,
|
|
2597
|
+
(view.camera as Camera & { near?: number }).near ?? 0,
|
|
2598
|
+
);
|
|
2599
|
+
const errorPixels = projectedLodError(
|
|
2600
|
+
next.surfaceError * finest.mesh.matrixWorld.getMaxScaleOnAxis(),
|
|
2601
|
+
view.camera,
|
|
2602
|
+
view.viewportHeight,
|
|
2603
|
+
depth.depth,
|
|
2604
|
+
);
|
|
2605
|
+
projection = { ...depth, ...(Number.isFinite(errorPixels) ? { errorPixels } : {}) };
|
|
2606
|
+
}
|
|
2607
|
+
return {
|
|
2608
|
+
key: tile.key,
|
|
2609
|
+
lodLevel: tile.lodLevel,
|
|
2610
|
+
distance,
|
|
2611
|
+
distanceLod: lodLevelForDistance(distance, this.#lodDistances),
|
|
2612
|
+
maxLodLevel: tile.maxLodLevel,
|
|
2613
|
+
targetLod: this.#targetLod(tile, distance),
|
|
2614
|
+
...(next === undefined
|
|
2615
|
+
? {}
|
|
2616
|
+
: {
|
|
2617
|
+
nextCoarser: {
|
|
2618
|
+
lodLevel: tile.lodLevel + 1,
|
|
2619
|
+
surfaceError: next.surfaceError,
|
|
2620
|
+
...projection,
|
|
2621
|
+
},
|
|
2622
|
+
}),
|
|
2623
|
+
};
|
|
2624
|
+
});
|
|
2625
|
+
return {
|
|
2626
|
+
lodDecisions,
|
|
2627
|
+
lodPolicy: {
|
|
2628
|
+
lodDistances: [...this.#lodDistances],
|
|
2629
|
+
...(view === undefined
|
|
2630
|
+
? {}
|
|
2631
|
+
: {
|
|
2632
|
+
viewportHeight: view.viewportHeight,
|
|
2633
|
+
maxPixelError: view.maxPixelError,
|
|
2634
|
+
hysteresis: view.hysteresis,
|
|
2635
|
+
coarsenBelowPixels: (1 - view.hysteresis) * view.maxPixelError,
|
|
2636
|
+
}),
|
|
2637
|
+
},
|
|
2638
|
+
...(this.maxSeamGap === undefined ? {} : { maxSeamGap: this.maxSeamGap }),
|
|
2639
|
+
...(this.maxVisualSeamGap === undefined ? {} : { maxVisualSeamGap: this.maxVisualSeamGap }),
|
|
2640
|
+
maxLodTransitionFrames: this.#maxLodTransitionFrames,
|
|
2641
|
+
peakResidentBytes: this.#peakBytes,
|
|
2642
|
+
peakResidentTiles: this.#peakTiles,
|
|
2643
|
+
residentBytes: this.residentBytes,
|
|
2644
|
+
// The shipped frame's change detector, and the ring-state reads it replaced. Both flat: a
|
|
2645
|
+
// settled ring leaves them still.
|
|
2646
|
+
ringEpoch: this.#ringEpoch,
|
|
2647
|
+
ringStateBuilds: this.#ringStateBuilds,
|
|
2648
|
+
residentByteBudget: this.residentByteBudget,
|
|
2649
|
+
residentKeys: this.residentKeys,
|
|
2650
|
+
residentTiles: this.residentTileCount,
|
|
2651
|
+
residentTileBudget: this.residentTileBudget,
|
|
2652
|
+
...(this.#construction === undefined ? {} : { pendingConstruction: this.#construction.key }),
|
|
2653
|
+
topologyBytes: this.#topologyBytes,
|
|
2654
|
+
lodTransitions: this.#lodTransitions,
|
|
2655
|
+
terrainTiles: this.terrainTiles,
|
|
2656
|
+
...(this.maxLodPop === undefined ? {} : { maxLodPop: this.maxLodPop }),
|
|
2657
|
+
stitchedEdges: this.#stitchedEdges,
|
|
2658
|
+
skirtVertexCount: [...this.#resident.values()].reduce(
|
|
2659
|
+
(total, tile) => total + tile.skirtVertexCount,
|
|
2660
|
+
0,
|
|
2661
|
+
),
|
|
2662
|
+
released: this.#released,
|
|
2663
|
+
...(topology === undefined
|
|
2664
|
+
? {}
|
|
2665
|
+
: {
|
|
2666
|
+
topology: {
|
|
2667
|
+
...topology,
|
|
2668
|
+
origin: { ...topology.origin },
|
|
2669
|
+
...(topology.heights === undefined ? {} : { heights: topology.heights.slice() }),
|
|
2670
|
+
...(topology.flow === undefined ? {} : { flow: topology.flow.slice() }),
|
|
2671
|
+
...(topology.metrics === undefined ? {} : { metrics: { ...topology.metrics } }),
|
|
2672
|
+
},
|
|
2673
|
+
}),
|
|
2674
|
+
};
|
|
2675
|
+
}
|
|
2676
|
+
|
|
2677
|
+
detach(): void {
|
|
2678
|
+
this.dispose();
|
|
2679
|
+
}
|
|
2680
|
+
|
|
2681
|
+
dispose(): void {
|
|
2682
|
+
if (this.#released) return;
|
|
2683
|
+
this.#released = true;
|
|
2684
|
+
this.#renderer = undefined;
|
|
2685
|
+
this.#jobs.dispose();
|
|
2686
|
+
this.#cancelConstruction();
|
|
2687
|
+
this.#topology = undefined;
|
|
2688
|
+
this.#topologyBytes = 0;
|
|
2689
|
+
for (const key of [...this.#blocks.keys()]) this.#dissolveBlock(key);
|
|
2690
|
+
for (const tile of [...this.#resident.values()]) this.#evict(tile);
|
|
2691
|
+
this.#resident.clear();
|
|
2692
|
+
this.removeFromParent();
|
|
2693
|
+
}
|
|
2694
|
+
|
|
2695
|
+
*#createField(origin: IHeightfieldOrigin, chunked: boolean): Generator<void, Heightfield> {
|
|
2696
|
+
const sampler: IHeightfieldSamplerOptions = {
|
|
2697
|
+
columns: this.tileResolution,
|
|
2698
|
+
depth: this.tileSize,
|
|
2699
|
+
origin,
|
|
2700
|
+
rows: this.tileResolution,
|
|
2701
|
+
sampleHeight: this.#sampleHeight,
|
|
2702
|
+
width: this.tileSize,
|
|
2703
|
+
...(this.#worldPasses === undefined ? {} : { worldPasses: this.#worldPasses }),
|
|
2704
|
+
};
|
|
2705
|
+
if (!chunked) return Heightfield.fromSampler(sampler);
|
|
2706
|
+
const heights = new Float32Array(this.tileResolution ** 2);
|
|
2707
|
+
const minimumX = origin.x - this.tileSize / 2;
|
|
2708
|
+
const minimumZ = origin.z - this.tileSize / 2;
|
|
2709
|
+
const cellSize = this.tileSize / (this.tileResolution - 1);
|
|
2710
|
+
for (let row = 0; row < this.tileResolution; row += 1) {
|
|
2711
|
+
const z = minimumZ + row * cellSize;
|
|
2712
|
+
for (let column = 0; column < this.tileResolution; column += 1) {
|
|
2713
|
+
const index = row * this.tileResolution + column;
|
|
2714
|
+
heights[index] = finite(
|
|
2715
|
+
this.#sampleHeight(minimumX + column * cellSize, z),
|
|
2716
|
+
"sampleHeight result",
|
|
2717
|
+
);
|
|
2718
|
+
if ((index + 1) % CONSTRUCTION_CHUNK_SAMPLES === 0) yield;
|
|
2719
|
+
}
|
|
2720
|
+
}
|
|
2721
|
+
// The same canonical field as fromSampler; only the sampler loop changes cadence.
|
|
2722
|
+
return new Heightfield({ ...sampler, heights });
|
|
2723
|
+
}
|
|
2724
|
+
|
|
2725
|
+
*#createTile(
|
|
2726
|
+
tileX: number,
|
|
2727
|
+
tileZ: number,
|
|
2728
|
+
distance: number,
|
|
2729
|
+
withCollider: boolean,
|
|
2730
|
+
chunked: boolean,
|
|
2731
|
+
): Generator<void, IResidentTile> {
|
|
2732
|
+
const origin = { x: tileX * this.tileSize, z: tileZ * this.tileSize };
|
|
2733
|
+
const assetKey =
|
|
2734
|
+
this.#assetKey === undefined
|
|
2735
|
+
? undefined
|
|
2736
|
+
: typeof this.#assetKey === "function"
|
|
2737
|
+
? this.#assetKey(tileX, tileZ)
|
|
2738
|
+
: this.#assetKey;
|
|
2739
|
+
if (assetKey !== undefined && (typeof assetKey !== "string" || assetKey.trim().length === 0))
|
|
2740
|
+
throw new Error("TerrainTiles assetKey must resolve to a non-empty string.");
|
|
2741
|
+
let field: Heightfield | undefined;
|
|
2742
|
+
const levels: ILevelGeometry[] = [];
|
|
2743
|
+
let lod: LOD | undefined;
|
|
2744
|
+
let collider: IWorldTileCollider | undefined;
|
|
2745
|
+
let completed = false;
|
|
2746
|
+
try {
|
|
2747
|
+
field = yield* this.#createField(origin, chunked);
|
|
2748
|
+
// One grid of the field's own heights for the whole tile, read before any level is built.
|
|
2749
|
+
const grid = yield* fieldHeightGrid(field, chunked);
|
|
2750
|
+
for (const factor of this.#factors)
|
|
2751
|
+
levels.push(
|
|
2752
|
+
yield* buildLevel(
|
|
2753
|
+
field,
|
|
2754
|
+
resolutionFor(this.tileResolution, factor),
|
|
2755
|
+
this.skirtDepth,
|
|
2756
|
+
this.#surface,
|
|
2757
|
+
grid,
|
|
2758
|
+
chunked,
|
|
2759
|
+
),
|
|
2760
|
+
);
|
|
2761
|
+
lod = new LOD();
|
|
2762
|
+
lod.autoUpdate = false;
|
|
2763
|
+
lod.position.set(origin.x, 0, origin.z);
|
|
2764
|
+
levels.forEach(({ mesh }, index) => {
|
|
2765
|
+
mesh.visible = index === 0;
|
|
2766
|
+
lod?.addLevel(mesh, index === 0 ? 0 : (this.#lodDistances[index - 1] as number));
|
|
2767
|
+
mesh.frustumCulled = true;
|
|
2768
|
+
mesh.receiveShadow = this.#receiveShadow;
|
|
2769
|
+
});
|
|
2770
|
+
const maxLodLevel = yield* coarsestSelectableLevel(levels, chunked);
|
|
2771
|
+
if (!this.#validate)
|
|
2772
|
+
for (const level of levels) {
|
|
2773
|
+
const coarser = levels.filter(
|
|
2774
|
+
(candidate) => candidate !== level && candidate.resolution <= level.resolution,
|
|
2775
|
+
);
|
|
2776
|
+
if (coarser.length === 0) continue;
|
|
2777
|
+
yield* buildLodMorphTargets(level, coarser, 0, chunked);
|
|
2778
|
+
level.mesh.updateMorphTargets();
|
|
2779
|
+
}
|
|
2780
|
+
collider =
|
|
2781
|
+
this.#createCollider === undefined
|
|
2782
|
+
? new EmptyCollider()
|
|
2783
|
+
: withCollider
|
|
2784
|
+
? this.#createCollider({ field, key: keyFor(tileX, tileZ), object: lod, tileX, tileZ })
|
|
2785
|
+
: undefined;
|
|
2786
|
+
const bytes =
|
|
2787
|
+
levels.reduce(
|
|
2788
|
+
(total, level) =>
|
|
2789
|
+
total +
|
|
2790
|
+
estimatedLevelBytes(
|
|
2791
|
+
level.resolution,
|
|
2792
|
+
this.#validate
|
|
2793
|
+
? 0
|
|
2794
|
+
: levels.filter((candidate) => candidate.resolution <= level.resolution).length - 1,
|
|
2795
|
+
),
|
|
2796
|
+
0,
|
|
2797
|
+
) + field.memoryBytes;
|
|
2798
|
+
const tile: IResidentTile = {
|
|
2799
|
+
...(assetKey === undefined ? {} : { assetKey }),
|
|
2800
|
+
bytes,
|
|
2801
|
+
collider,
|
|
2802
|
+
field,
|
|
2803
|
+
key: keyFor(tileX, tileZ),
|
|
2804
|
+
lod,
|
|
2805
|
+
lodLevel: 0,
|
|
2806
|
+
sharedMorphEdges: 0,
|
|
2807
|
+
levels,
|
|
2808
|
+
maxLodLevel,
|
|
2809
|
+
object: lod,
|
|
2810
|
+
origin,
|
|
2811
|
+
skirtVertexCount: levels.reduce((total, level) => total + level.skirtVertexCount, 0),
|
|
2812
|
+
skirts: this.skirtDepth,
|
|
2813
|
+
tileX,
|
|
2814
|
+
tileZ,
|
|
2815
|
+
};
|
|
2816
|
+
this.#selectLod(tile, distance, false);
|
|
2817
|
+
completed = true;
|
|
2818
|
+
return tile;
|
|
2819
|
+
} finally {
|
|
2820
|
+
if (!completed) {
|
|
2821
|
+
collider?.dispose();
|
|
2822
|
+
lod?.removeFromParent();
|
|
2823
|
+
for (const level of levels) level.geometry.dispose();
|
|
2824
|
+
field?.detach();
|
|
2825
|
+
}
|
|
2826
|
+
}
|
|
2827
|
+
}
|
|
2828
|
+
|
|
2829
|
+
/** Whether a tile this far from the followed one is inside `colliderRadius`. */
|
|
2830
|
+
#wantsCollider(tileX: number, tileZ: number, centerX: number, centerZ: number): boolean {
|
|
2831
|
+
return Math.max(Math.abs(tileX - centerX), Math.abs(tileZ - centerZ)) <= this.#colliderRadius;
|
|
2832
|
+
}
|
|
2833
|
+
|
|
2834
|
+
/**
|
|
2835
|
+
* Build one wanted tile, if this frame's admission budget has room for it.
|
|
2836
|
+
*
|
|
2837
|
+
* Large fields, levels, bounds and LOD safety scans yield in chunks. Only a completed tile is
|
|
2838
|
+
* published; a refused chunk remains owned here until a later follow, a move or disposal.
|
|
2839
|
+
* Small tiles fit one unit, and a follow without an allowance drains synchronously as before.
|
|
2840
|
+
*
|
|
2841
|
+
* `forced` grants the first chunk progress even when another system spent the allowance.
|
|
2842
|
+
*/
|
|
2843
|
+
#admitCandidate(
|
|
2844
|
+
candidate: { distance: number; tileX: number; tileZ: number },
|
|
2845
|
+
centerX: number,
|
|
2846
|
+
centerZ: number,
|
|
2847
|
+
budget: IAdmissionBudget | undefined,
|
|
2848
|
+
forced = false,
|
|
2849
|
+
): IResidentTile | undefined {
|
|
2850
|
+
let progressOwed = forced;
|
|
2851
|
+
const key = keyFor(candidate.tileX, candidate.tileZ);
|
|
2852
|
+
if (this.#construction !== undefined && this.#construction.key !== key)
|
|
2853
|
+
this.#cancelConstruction();
|
|
2854
|
+
const construction = this.#construction ?? {
|
|
2855
|
+
key,
|
|
2856
|
+
work: this.#createTile(
|
|
2857
|
+
candidate.tileX,
|
|
2858
|
+
candidate.tileZ,
|
|
2859
|
+
candidate.distance,
|
|
2860
|
+
this.#wantsCollider(candidate.tileX, candidate.tileZ, centerX, centerZ),
|
|
2861
|
+
budget !== undefined && this.tileResolution ** 2 > CONSTRUCTION_CHUNK_SAMPLES,
|
|
2862
|
+
),
|
|
2863
|
+
};
|
|
2864
|
+
this.#construction = construction;
|
|
2865
|
+
let tile: IResidentTile | undefined;
|
|
2866
|
+
const advance = (): void => {
|
|
2867
|
+
try {
|
|
2868
|
+
const result = construction.work.next();
|
|
2869
|
+
if (result.done) {
|
|
2870
|
+
tile = result.value;
|
|
2871
|
+
this.#construction = undefined;
|
|
2872
|
+
}
|
|
2873
|
+
} catch (error) {
|
|
2874
|
+
this.#construction = undefined;
|
|
2875
|
+
throw error;
|
|
2876
|
+
}
|
|
2877
|
+
};
|
|
2878
|
+
while (tile === undefined) {
|
|
2879
|
+
if (budget === undefined) advance();
|
|
2880
|
+
else if (budget.admit(advance)) progressOwed = false;
|
|
2881
|
+
else if (progressOwed) {
|
|
2882
|
+
// Progress is one chunk, never an entire high-resolution tile outside the allowance.
|
|
2883
|
+
advance();
|
|
2884
|
+
progressOwed = false;
|
|
2885
|
+
} else {
|
|
2886
|
+
this.#deferredAdmissions = 1;
|
|
2887
|
+
return undefined;
|
|
2888
|
+
}
|
|
2889
|
+
}
|
|
2890
|
+
return tile;
|
|
2891
|
+
}
|
|
2892
|
+
|
|
2893
|
+
#cancelConstruction(): void {
|
|
2894
|
+
this.#construction?.work.return(undefined as never);
|
|
2895
|
+
this.#construction = undefined;
|
|
2896
|
+
}
|
|
2897
|
+
|
|
2898
|
+
/**
|
|
2899
|
+
* Bring every resident tile's collider in line with `colliderRadius`: a tile that entered it gets
|
|
2900
|
+
* a body, one that left disposes the body it had. That is the whole cost control — a wide
|
|
2901
|
+
* `streamRadius` renders the ground out to the horizon while physics only ever covers the tiles a
|
|
2902
|
+
* player can reach — and it needs no per-tile bookkeeping because residency already walks the
|
|
2903
|
+
* resident set on every `follow`.
|
|
2904
|
+
*
|
|
2905
|
+
* A body the budget refuses is the same deferral as a refused tile: the tile is inside
|
|
2906
|
+
* `colliderRadius` with no body for a frame or two, and the next `follow` still wants one.
|
|
2907
|
+
*
|
|
2908
|
+
* Except under and beside the followed point. One tile build spends the whole 2 ms budget on its
|
|
2909
|
+
* own, so the collider pass behind it was refused every time a tile was admitted — and the
|
|
2910
|
+
* resident set is walked in insertion order, not nearest first, so the tiles the player is
|
|
2911
|
+
* standing on were as likely as any other to be the ones refused. A body under or beside the
|
|
2912
|
+
* walk point is the one thing a deferred admission may not take: a probe under the walk point
|
|
2913
|
+
* asks the physics world for ground that is not there yet. Nine bodies at most, and the ring's
|
|
2914
|
+
* other tiles keep their deferral.
|
|
2915
|
+
*/
|
|
2916
|
+
#updateColliders(centerX: number, centerZ: number, budget?: IAdmissionBudget): void {
|
|
2917
|
+
const createCollider = this.#createCollider;
|
|
2918
|
+
if (createCollider === undefined) return;
|
|
2919
|
+
for (const tile of this.#resident.values()) {
|
|
2920
|
+
const wanted = this.#wantsCollider(tile.tileX, tile.tileZ, centerX, centerZ);
|
|
2921
|
+
if (wanted === (tile.collider !== undefined)) continue;
|
|
2922
|
+
if (!wanted) {
|
|
2923
|
+
tile.collider?.dispose();
|
|
2924
|
+
tile.collider = undefined;
|
|
2925
|
+
this.#ringEpoch += 1;
|
|
2926
|
+
continue;
|
|
2927
|
+
}
|
|
2928
|
+
const created = (): void => {
|
|
2929
|
+
tile.collider = createCollider({
|
|
2930
|
+
field: tile.field,
|
|
2931
|
+
key: tile.key,
|
|
2932
|
+
object: tile.lod,
|
|
2933
|
+
tileX: tile.tileX,
|
|
2934
|
+
tileZ: tile.tileZ,
|
|
2935
|
+
});
|
|
2936
|
+
};
|
|
2937
|
+
// The 3x3 ring around the followed point is never refused; see above.
|
|
2938
|
+
if (
|
|
2939
|
+
budget === undefined ||
|
|
2940
|
+
Math.max(Math.abs(tile.tileX - centerX), Math.abs(tile.tileZ - centerZ)) <= 1
|
|
2941
|
+
) {
|
|
2942
|
+
created();
|
|
2943
|
+
this.#ringEpoch += 1;
|
|
2944
|
+
}
|
|
2945
|
+
// Out of room: the body is owed, and every later `follow` asks for it again.
|
|
2946
|
+
else if (!budget.admit(created)) {
|
|
2947
|
+
this.#deferredAdmissions = 1;
|
|
2948
|
+
}
|
|
2949
|
+
}
|
|
2950
|
+
}
|
|
2951
|
+
|
|
2952
|
+
/**
|
|
2953
|
+
* Move resident tiles to their distance level after the neighbour rule is applied to the targets.
|
|
2954
|
+
*
|
|
2955
|
+
* Setting each tile to its raw distance level and then letting `#coordinateNeighborLods` pull
|
|
2956
|
+
* the coarser side of a two-level jump back flipped those tiles every frame the follow point
|
|
2957
|
+
* stood still: two LOD transitions, a visible morph and whole-tile bounds work, forever. The rule
|
|
2958
|
+
* is the same — a coarser neighbour moves to one level past the finer — but it now shapes the
|
|
2959
|
+
* target, so a settled ring asks for the level it already has.
|
|
2960
|
+
*/
|
|
2961
|
+
#applyLodTargets(targets: ReadonlyMap<IResidentTile, number>): void {
|
|
2962
|
+
// A ring that already holds every level it is asking for has no target to reshape: the
|
|
2963
|
+
// neighbour fixpoint would return the same levels it starts from. Skipping it is what keeps a
|
|
2964
|
+
// still follow point off the per-frame pair walk entirely.
|
|
2965
|
+
if (!hasPendingTarget(targets)) return;
|
|
2966
|
+
const levels = coordinatedLevels(this.#resident, targets);
|
|
2967
|
+
for (const [tile, level] of levels) if (targets.has(tile)) this.#setLodLevel(tile, level);
|
|
2968
|
+
}
|
|
2969
|
+
|
|
2970
|
+
#selectLod(tile: IResidentTile, distance: number, countTransition = true): void {
|
|
2971
|
+
this.#setLodLevel(tile, this.#targetLod(tile, distance), countTransition);
|
|
2972
|
+
}
|
|
2973
|
+
|
|
2974
|
+
#setLodView(view: IWorldTilesLodView | undefined): void {
|
|
2975
|
+
if (
|
|
2976
|
+
view !== undefined &&
|
|
2977
|
+
(!Number.isFinite(view.viewportHeight) ||
|
|
2978
|
+
view.viewportHeight <= 0 ||
|
|
2979
|
+
!Number.isFinite(view.maxPixelError) ||
|
|
2980
|
+
view.maxPixelError <= 0 ||
|
|
2981
|
+
!Number.isFinite(view.hysteresis) ||
|
|
2982
|
+
view.hysteresis < 0 ||
|
|
2983
|
+
view.hysteresis >= 1)
|
|
2984
|
+
)
|
|
2985
|
+
throw new Error(
|
|
2986
|
+
"TerrainTiles needs a positive raster height/pixel budget and hysteresis in [0, 1).",
|
|
2987
|
+
);
|
|
2988
|
+
this.#lodView = view;
|
|
2989
|
+
view?.camera.updateWorldMatrix(true, false);
|
|
2990
|
+
}
|
|
2991
|
+
|
|
2992
|
+
#targetLod(tile: IResidentTile, distance: number): number {
|
|
2993
|
+
const floor = Math.min(lodLevelForDistance(distance, this.#lodDistances), tile.maxLodLevel);
|
|
2994
|
+
const view = this.#lodView;
|
|
2995
|
+
if (view === undefined) return floor;
|
|
2996
|
+
const finest = tile.levels[0];
|
|
2997
|
+
const bounds = finest?.geometry.boundingSphere;
|
|
2998
|
+
if (finest === undefined || bounds == null) return 0;
|
|
2999
|
+
finest.mesh.updateWorldMatrix(true, false);
|
|
3000
|
+
const sphere = worldSphere(bounds, finest.mesh);
|
|
3001
|
+
const depth = conservativeViewDepth(
|
|
3002
|
+
view.camera,
|
|
3003
|
+
sphere.center,
|
|
3004
|
+
sphere.radius,
|
|
3005
|
+
(view.camera as Camera & { near?: number }).near ?? 0,
|
|
3006
|
+
);
|
|
3007
|
+
const scale = finest.mesh.matrixWorld.getMaxScaleOnAxis();
|
|
3008
|
+
// Selection is synchronous; overwrite and truncate before another tile or view reuses these.
|
|
3009
|
+
for (let index = 0; index <= floor; index += 1)
|
|
3010
|
+
this.#lodErrors[index] = (tile.levels[index] as ILevelGeometry).surfaceError * scale;
|
|
3011
|
+
this.#lodErrors.length = floor + 1;
|
|
3012
|
+
return selectLodLevel(this.#lodErrors, tile.lodLevel, view.maxPixelError, view.hysteresis, [
|
|
3013
|
+
{ ...view, ...depth },
|
|
3014
|
+
]);
|
|
3015
|
+
}
|
|
3016
|
+
|
|
3017
|
+
#syncMorphEdges(): void {
|
|
3018
|
+
for (const tile of this.#resident.values()) {
|
|
3019
|
+
const shared =
|
|
3020
|
+
(this.#resident.has(keyFor(tile.tileX, tile.tileZ - 1)) ? 1 : 0) |
|
|
3021
|
+
(this.#resident.has(keyFor(tile.tileX, tile.tileZ + 1)) ? 2 : 0) |
|
|
3022
|
+
(this.#resident.has(keyFor(tile.tileX - 1, tile.tileZ)) ? 4 : 0) |
|
|
3023
|
+
(this.#resident.has(keyFor(tile.tileX + 1, tile.tileZ)) ? 8 : 0);
|
|
3024
|
+
if (shared === tile.sharedMorphEdges) continue;
|
|
3025
|
+
for (const level of tile.levels) {
|
|
3026
|
+
const coarser = tile.levels.filter(
|
|
3027
|
+
(candidate) => candidate !== level && candidate.resolution <= level.resolution,
|
|
3028
|
+
);
|
|
3029
|
+
if (coarser.length === 0) continue;
|
|
3030
|
+
const previous = level.geometry;
|
|
3031
|
+
const geometry = new BufferGeometry();
|
|
3032
|
+
geometry.morphTargetsRelative = true;
|
|
3033
|
+
geometry.setAttribute("position", previous.getAttribute("position"));
|
|
3034
|
+
geometry.setAttribute("normal", previous.getAttribute("normal"));
|
|
3035
|
+
geometry.setIndex(previous.getIndex());
|
|
3036
|
+
geometry.boundingBox = previous.boundingBox?.clone() ?? null;
|
|
3037
|
+
geometry.boundingSphere = previous.boundingSphere?.clone() ?? null;
|
|
3038
|
+
const influences = level.mesh.morphTargetInfluences?.slice();
|
|
3039
|
+
// Three caches morph textures by geometry, ignoring attribute versions; retire that cache.
|
|
3040
|
+
for (const _ of buildLodMorphTargets({ ...level, geometry }, coarser, shared, false)) {
|
|
3041
|
+
}
|
|
3042
|
+
level.geometry = geometry;
|
|
3043
|
+
level.mesh.geometry = geometry;
|
|
3044
|
+
level.mesh.updateMorphTargets();
|
|
3045
|
+
if (influences !== undefined) level.mesh.morphTargetInfluences = influences;
|
|
3046
|
+
previous.dispose();
|
|
3047
|
+
}
|
|
3048
|
+
tile.sharedMorphEdges = shared;
|
|
3049
|
+
}
|
|
3050
|
+
this.#morphEdgesDirty = false;
|
|
3051
|
+
}
|
|
3052
|
+
|
|
3053
|
+
#setLodLevel(tile: IResidentTile, level: number, countTransition = true): void {
|
|
3054
|
+
const selectable = Math.min(level, tile.maxLodLevel);
|
|
3055
|
+
if (selectable === tile.lodLevel) {
|
|
3056
|
+
setManualLodLevel(tile.lod, selectable);
|
|
3057
|
+
return;
|
|
3058
|
+
}
|
|
3059
|
+
const interruptedFrame =
|
|
3060
|
+
!this.#validate || tile.lodTransition === undefined
|
|
3061
|
+
? undefined
|
|
3062
|
+
: this.#captureLodFrameForTile(tile);
|
|
3063
|
+
if (tile.lodTransition !== undefined) this.#finishLodTransition(tile);
|
|
3064
|
+
const previousLevel = tile.lodLevel;
|
|
3065
|
+
const previous = tile.levels[previousLevel];
|
|
3066
|
+
const next = tile.levels[selectable];
|
|
3067
|
+
if (previous === undefined || next === undefined)
|
|
3068
|
+
throw new Error("TerrainTiles LOD transition references a missing level.");
|
|
3069
|
+
// The tile leaves its old level's block and joins the new level's: the old one is now holding
|
|
3070
|
+
// ground this tile is no longer at, and the new one is waiting to be built.
|
|
3071
|
+
this.#releaseStaleBlock(previousLevel, tile.tileX, tile.tileZ);
|
|
3072
|
+
tile.lodLevel = selectable;
|
|
3073
|
+
this.#markBlockDirty(selectable, tile.tileX, tile.tileZ);
|
|
3074
|
+
this.#ringEpoch += 1;
|
|
3075
|
+
if (!countTransition) {
|
|
3076
|
+
setManualLodLevel(tile.lod, selectable);
|
|
3077
|
+
this.#setLodVisibility(tile);
|
|
3078
|
+
this.#recordLodPopAfterRetarget(interruptedFrame);
|
|
3079
|
+
return;
|
|
3080
|
+
}
|
|
3081
|
+
this.#lodTransitions += 1;
|
|
3082
|
+
this.#blending.add(tile);
|
|
3083
|
+
tile.lodTransition = {
|
|
3084
|
+
elapsedFrames: 0,
|
|
3085
|
+
from: previousLevel,
|
|
3086
|
+
remainingFrames: LOD_TRANSITION_FRAMES,
|
|
3087
|
+
to: selectable,
|
|
3088
|
+
};
|
|
3089
|
+
const finerLevel = previous.resolution >= next.resolution ? previousLevel : selectable;
|
|
3090
|
+
const finer = previous.resolution >= next.resolution ? previous : next;
|
|
3091
|
+
setManualLodLevel(tile.lod, finerLevel);
|
|
3092
|
+
widenLevelBoundsForBlend(finer, finer === previous ? next : previous);
|
|
3093
|
+
if (this.#validate) updateLodTransitionGeometry(tile, tile.lodTransition, 0);
|
|
3094
|
+
else updateLodMorph(tile, tile.lodTransition, 0);
|
|
3095
|
+
this.#setLodVisibility(tile, [finerLevel]);
|
|
3096
|
+
this.#recordLodPopAfterRetarget(interruptedFrame);
|
|
3097
|
+
}
|
|
3098
|
+
|
|
3099
|
+
#setLodVisibility(tile: IResidentTile, visibleLevels = [tile.lodLevel]): void {
|
|
3100
|
+
// A block draws this tile's level, so its own mesh must not be submitted on top of it. Only a
|
|
3101
|
+
// tile settled into a block is hidden: a morphing tile is never merged, and a tile whose LOD
|
|
3102
|
+
// just changed is no longer a member of the block its old level lived in.
|
|
3103
|
+
if (
|
|
3104
|
+
this.#mergeTiles &&
|
|
3105
|
+
tile.lodTransition === undefined &&
|
|
3106
|
+
this.#mergedMembers.get(tile.key) === blockKeyFor(tile.lodLevel, tile.tileX, tile.tileZ)
|
|
3107
|
+
) {
|
|
3108
|
+
for (const level of tile.levels) level.mesh.visible = false;
|
|
3109
|
+
return;
|
|
3110
|
+
}
|
|
3111
|
+
const visible = new Set(visibleLevels);
|
|
3112
|
+
tile.levels.forEach(({ mesh }, index) => {
|
|
3113
|
+
mesh.visible = visible.has(index);
|
|
3114
|
+
});
|
|
3115
|
+
}
|
|
3116
|
+
|
|
3117
|
+
#captureLodFrame(): ILodFrameSnapshot[] {
|
|
3118
|
+
const snapshots: ILodFrameSnapshot[] = [];
|
|
3119
|
+
for (const tile of this.#resident.values()) {
|
|
3120
|
+
if (tile.lodTransition === undefined) continue;
|
|
3121
|
+
snapshots.push(this.#captureLodFrameForTile(tile));
|
|
3122
|
+
}
|
|
3123
|
+
return snapshots;
|
|
3124
|
+
}
|
|
3125
|
+
|
|
3126
|
+
#captureLodFrameForTile(tile: IResidentTile): ILodFrameSnapshot {
|
|
3127
|
+
const level = renderedLevel(tile);
|
|
3128
|
+
if (level === undefined)
|
|
3129
|
+
throw new Error("TerrainTiles cannot measure an LOD transition without a visible level.");
|
|
3130
|
+
return { heights: surfaceHeights(level), resolution: level.resolution, tile };
|
|
3131
|
+
}
|
|
3132
|
+
|
|
3133
|
+
#recordLodPopAfterReconciliation(snapshots: readonly ILodFrameSnapshot[]): void {
|
|
3134
|
+
for (const snapshot of snapshots) {
|
|
3135
|
+
const level = renderedLevel(snapshot.tile);
|
|
3136
|
+
if (level === undefined)
|
|
3137
|
+
throw new Error("TerrainTiles cannot measure an LOD frame without a visible level.");
|
|
3138
|
+
this.#recordLodPop(surfaceDeltaFromSamples(snapshot.heights, snapshot.resolution, level));
|
|
3139
|
+
}
|
|
3140
|
+
}
|
|
3141
|
+
|
|
3142
|
+
#recordLodPopAfterRetarget(snapshot: ILodFrameSnapshot | undefined): void {
|
|
3143
|
+
if (snapshot === undefined) return;
|
|
3144
|
+
const level = renderedLevel(snapshot.tile);
|
|
3145
|
+
if (level === undefined)
|
|
3146
|
+
throw new Error(
|
|
3147
|
+
"TerrainTiles cannot measure a retargeted LOD frame without a visible level.",
|
|
3148
|
+
);
|
|
3149
|
+
this.#recordLodPop(surfaceDeltaFromSamples(snapshot.heights, snapshot.resolution, level));
|
|
3150
|
+
}
|
|
3151
|
+
|
|
3152
|
+
#advanceLodTransitions(): void {
|
|
3153
|
+
for (const tile of this.#blending) {
|
|
3154
|
+
const transition = tile.lodTransition;
|
|
3155
|
+
if (transition === undefined) continue;
|
|
3156
|
+
const from = tile.levels[transition.from];
|
|
3157
|
+
if (from === undefined || tile.levels[transition.to] === undefined)
|
|
3158
|
+
throw new Error("TerrainTiles LOD transition references a missing level.");
|
|
3159
|
+
transition.elapsedFrames += 1;
|
|
3160
|
+
transition.remainingFrames -= 1;
|
|
3161
|
+
(this.#validate ? updateLodTransitionGeometry : updateLodMorph)(
|
|
3162
|
+
tile,
|
|
3163
|
+
transition,
|
|
3164
|
+
Math.min(1, transition.elapsedFrames / LOD_TRANSITION_FRAMES),
|
|
3165
|
+
);
|
|
3166
|
+
if (transition.remainingFrames > 0) {
|
|
3167
|
+
// The validating CPU blend moved; GPU morphs keep shared edges canonical.
|
|
3168
|
+
this.#ringEpoch += 1;
|
|
3169
|
+
continue;
|
|
3170
|
+
}
|
|
3171
|
+
this.#ringEpoch += 1;
|
|
3172
|
+
this.#maxLodTransitionFrames = Math.max(
|
|
3173
|
+
this.#maxLodTransitionFrames,
|
|
3174
|
+
transition.elapsedFrames,
|
|
3175
|
+
);
|
|
3176
|
+
this.#restoreLodTransition(tile, transition);
|
|
3177
|
+
tile.lodTransition = undefined;
|
|
3178
|
+
this.#blending.delete(tile);
|
|
3179
|
+
setManualLodLevel(tile.lod, transition.to);
|
|
3180
|
+
this.#setLodVisibility(tile);
|
|
3181
|
+
// The end of a blend is the one moment a tile rejoins its settled block.
|
|
3182
|
+
this.#markTileDirty(tile);
|
|
3183
|
+
}
|
|
3184
|
+
}
|
|
3185
|
+
|
|
3186
|
+
#coordinateNeighborLods(countTransitions: boolean): void {
|
|
3187
|
+
const pairs = collectNeighborPairs(this.#resident, this.#pairScratch);
|
|
3188
|
+
let changed = true;
|
|
3189
|
+
while (changed) {
|
|
3190
|
+
changed = false;
|
|
3191
|
+
for (const pair of pairs) {
|
|
3192
|
+
const correction = neighborLodCorrection(pair);
|
|
3193
|
+
if (correction === undefined) continue;
|
|
3194
|
+
const before = correction.coarser.lodLevel;
|
|
3195
|
+
this.#setLodLevel(correction.coarser, correction.level, countTransitions);
|
|
3196
|
+
if (correction.coarser.lodLevel === before) continue;
|
|
3197
|
+
changed = true;
|
|
3198
|
+
}
|
|
3199
|
+
}
|
|
3200
|
+
}
|
|
3201
|
+
|
|
3202
|
+
/**
|
|
3203
|
+
* Recorded for the pairs this pass reconciled, after every pair is done: reconciling one pair
|
|
3204
|
+
* bumps a tile its other pairs share, and a signature taken mid-pass would mark those pairs
|
|
3205
|
+
* stale. A pair the pass left alone keeps the signature the settled check just compared against
|
|
3206
|
+
* — taking it again would be a second signature per pair per pass for the same answer.
|
|
3207
|
+
*/
|
|
3208
|
+
#recordPairSignatures(
|
|
3209
|
+
pairs: readonly NeighborPair[],
|
|
3210
|
+
reconciled: ReadonlySet<string>,
|
|
3211
|
+
active: ReadonlySet<string>,
|
|
3212
|
+
): void {
|
|
3213
|
+
for (const key of this.#pairSignatures.keys()) {
|
|
3214
|
+
if (!active.has(key)) this.#pairSignatures.delete(key);
|
|
3215
|
+
}
|
|
3216
|
+
for (const pair of pairs) {
|
|
3217
|
+
const key = neighborPairKey(pair);
|
|
3218
|
+
if (!reconciled.has(key)) continue;
|
|
3219
|
+
const state = seamState(pair, this.#stitches.get(key), this.#validate);
|
|
3220
|
+
if (state === undefined) this.#pairSignatures.delete(key);
|
|
3221
|
+
else this.#pairSignatures.set(key, state);
|
|
3222
|
+
}
|
|
3223
|
+
}
|
|
3224
|
+
|
|
3225
|
+
/**
|
|
3226
|
+
* Whether a pair's seam is exactly as the last reconcile left it, bridge included: reconciling
|
|
3227
|
+
* restores both facing edges and then rewrites the bridge, so redoing a settled pair rewrote its
|
|
3228
|
+
* edges and recomputed whole-tile bounds every frame for nothing. A bridge corrupted from outside
|
|
3229
|
+
* changes that state and is reconciled and observed again, never healed silently. A settled
|
|
3230
|
+
* stitch still counts as stitched.
|
|
3231
|
+
*/
|
|
3232
|
+
#settled(key: string, pair: NeighborPair): boolean {
|
|
3233
|
+
if (
|
|
3234
|
+
!sameState(
|
|
3235
|
+
seamState(pair, this.#stitches.get(key), this.#validate),
|
|
3236
|
+
this.#pairSignatures.get(key),
|
|
3237
|
+
)
|
|
3238
|
+
)
|
|
3239
|
+
return false;
|
|
3240
|
+
if (this.#stitches.has(key)) this.#stitchedEdges += 1;
|
|
3241
|
+
return true;
|
|
3242
|
+
}
|
|
3243
|
+
|
|
3244
|
+
/**
|
|
3245
|
+
* Reconcile every seam that moved, then close the pass.
|
|
3246
|
+
*
|
|
3247
|
+
* The strips are built wherever the jobs run — a worker where the host has one, this thread where
|
|
3248
|
+
* it does not — so this loop only restores edges, collects what each bridge is made of, and swaps
|
|
3249
|
+
* in the arrays that come back. An inline host resolves inside the call and the pass closes before
|
|
3250
|
+
* `follow` returns, exactly as it did before the jobs moved; an off-thread host closes the pass in
|
|
3251
|
+
* the reply. Frames keep validating CPU edges canonical while it is pending; a reply whose ring
|
|
3252
|
+
* changed is discarded and reconciled anew, never recorded as settled.
|
|
3253
|
+
*/
|
|
3254
|
+
#reconcileNeighbors(): void {
|
|
3255
|
+
const pairs = collectNeighborPairs(this.#resident, this.#pairScratch);
|
|
3256
|
+
const active = new Set<string>();
|
|
3257
|
+
const reconciled = new Set<string>();
|
|
3258
|
+
const requests: { key: string; previousBytes: number; request: IStitchRequest }[] = [];
|
|
3259
|
+
for (const pair of pairs) {
|
|
3260
|
+
const key = neighborPairKey(pair);
|
|
3261
|
+
active.add(key);
|
|
3262
|
+
if (this.#settled(key, pair)) continue;
|
|
3263
|
+
reconciled.add(key);
|
|
3264
|
+
const previousBytes = this.#stitches.get(key)?.bytes ?? 0;
|
|
3265
|
+
const request = neighborBridgeRequest(pair);
|
|
3266
|
+
if (request === undefined) {
|
|
3267
|
+
this.#removeStitch(key);
|
|
3268
|
+
continue;
|
|
3269
|
+
}
|
|
3270
|
+
requests.push({ key, previousBytes, request });
|
|
3271
|
+
}
|
|
3272
|
+
for (const key of this.#stitches.keys()) {
|
|
3273
|
+
if (!active.has(key)) this.#removeStitch(key);
|
|
3274
|
+
}
|
|
3275
|
+
if (requests.length === 0) {
|
|
3276
|
+
timedSpan(SPANS.terrainSeam, () => this.#settleSeamPass(pairs, reconciled, active));
|
|
3277
|
+
return;
|
|
3278
|
+
}
|
|
3279
|
+
const job: ITerrainSeamJob = {
|
|
3280
|
+
kind: "seam",
|
|
3281
|
+
pairs: requests.map(({ request }) => ({ coarse: request.coarse, fine: request.fine })),
|
|
3282
|
+
};
|
|
3283
|
+
// The scratch array is reused by the next pass, so a reply that lands a frame later reads its
|
|
3284
|
+
// own copy of the pairs and not whatever the next pass left there.
|
|
3285
|
+
const snapshot = [...pairs];
|
|
3286
|
+
const epoch = this.#ringEpoch;
|
|
3287
|
+
const state: number[] = [];
|
|
3288
|
+
this.#seamPending = true;
|
|
3289
|
+
const result = timedSpan(SPANS.terrainSeam, () => this.#jobs.seam(job));
|
|
3290
|
+
if (result instanceof Promise) this.#ringStateInto(state);
|
|
3291
|
+
settleJob(result, (settled) => {
|
|
3292
|
+
if (this.#released) return;
|
|
3293
|
+
if (result instanceof Promise) {
|
|
3294
|
+
const current: number[] = [];
|
|
3295
|
+
this.#ringStateInto(current);
|
|
3296
|
+
if (epoch !== this.#ringEpoch || !sameState(state, current)) {
|
|
3297
|
+
// A non-finite current signature is corruption, not a legitimate superseded request.
|
|
3298
|
+
if (this.#validate && current.some(Number.isNaN)) this.#recordSeamDiagnostics();
|
|
3299
|
+
// Nothing from this reply describes the current ring; leave it unsettled and request it anew.
|
|
3300
|
+
this.#seamPending = false;
|
|
3301
|
+
this.#seamPass();
|
|
3302
|
+
return;
|
|
3303
|
+
}
|
|
3304
|
+
}
|
|
3305
|
+
timedSpan(SPANS.terrainSeam, () => {
|
|
3306
|
+
if (settled.kind !== "seam" || settled.bridges.length !== requests.length)
|
|
3307
|
+
throw new Error("TerrainTiles seam job returned an invalid bridge count.");
|
|
3308
|
+
for (const [index, pending] of requests.entries()) {
|
|
3309
|
+
const data = settled.bridges[index];
|
|
3310
|
+
if (data === undefined)
|
|
3311
|
+
throw new Error("TerrainTiles seam job returned an invalid bridge count.");
|
|
3312
|
+
this.#applyStitch(pending.key, pending.previousBytes, pending.request, data);
|
|
3313
|
+
}
|
|
3314
|
+
this.#settleSeamPass(snapshot, reconciled, active);
|
|
3315
|
+
});
|
|
3316
|
+
});
|
|
3317
|
+
}
|
|
3318
|
+
|
|
3319
|
+
#applyStitch(
|
|
3320
|
+
key: string,
|
|
3321
|
+
previousBytes: number,
|
|
3322
|
+
request: IStitchRequest,
|
|
3323
|
+
data: ITerrainBridgeAttributes,
|
|
3324
|
+
): void {
|
|
3325
|
+
const existing = this.#stitches.get(key);
|
|
3326
|
+
if (existing === undefined) {
|
|
3327
|
+
const bridge = newStitchBridge(request, data, this.#surface);
|
|
3328
|
+
this.#stitches.set(key, bridge);
|
|
3329
|
+
bridge.mesh.receiveShadow = this.#receiveShadow;
|
|
3330
|
+
this.add(bridge.mesh);
|
|
3331
|
+
this.#stitchBytes += bridge.bytes;
|
|
3332
|
+
} else {
|
|
3333
|
+
updateStitchBridge(existing, data);
|
|
3334
|
+
this.#stitchBytes += existing.bytes - previousBytes;
|
|
3335
|
+
}
|
|
3336
|
+
this.#stitchedEdges += 1;
|
|
3337
|
+
}
|
|
3338
|
+
|
|
3339
|
+
/** Everything that closes a seam pass, once every bridge it asked for is in place. */
|
|
3340
|
+
#settleSeamPass(
|
|
3341
|
+
pairs: readonly NeighborPair[],
|
|
3342
|
+
reconciled: ReadonlySet<string>,
|
|
3343
|
+
active: ReadonlySet<string>,
|
|
3344
|
+
): void {
|
|
3345
|
+
this.#seamPending = false;
|
|
3346
|
+
if (this.#validate) this.#recordSeamDiagnostics();
|
|
3347
|
+
this.#recordPairSignatures(pairs, reconciled, active);
|
|
3348
|
+
// Every edge restore and bridge rewrite this pass did is a change the ring state describes; the
|
|
3349
|
+
// pass is the only writer of either, so one bump here covers all of it.
|
|
3350
|
+
this.#ringEpoch += 1;
|
|
3351
|
+
if (this.residentBytes > this.residentByteBudget)
|
|
3352
|
+
throw new TerrainTileBudgetError(
|
|
3353
|
+
"TerrainTiles residentByteBudget cannot fit stitched neighbor geometry.",
|
|
3354
|
+
);
|
|
3355
|
+
if (this.#validate) {
|
|
3356
|
+
// The pass moved geometry, so the settled state is what it left behind, read into the buffer
|
|
3357
|
+
// the compare just filled; the buffer it compared against becomes the next frame's scratch.
|
|
3358
|
+
const scratch = this.#ringScratch;
|
|
3359
|
+
this.#ringScratch = this.#settledRing ?? [];
|
|
3360
|
+
this.#settledRing = scratch;
|
|
3361
|
+
this.#ringStateInto(this.#settledRing);
|
|
3362
|
+
}
|
|
3363
|
+
// Read after the pass, which moved geometry and bumped the epoch itself.
|
|
3364
|
+
this.#seamEpoch = this.#ringEpoch;
|
|
3365
|
+
}
|
|
3366
|
+
|
|
3367
|
+
#finishLodTransition(tile: IResidentTile): void {
|
|
3368
|
+
const transition = tile.lodTransition;
|
|
3369
|
+
if (transition === undefined) return;
|
|
3370
|
+
this.#maxLodTransitionFrames = Math.max(this.#maxLodTransitionFrames, transition.elapsedFrames);
|
|
3371
|
+
this.#restoreLodTransition(tile, transition);
|
|
3372
|
+
tile.lodTransition = undefined;
|
|
3373
|
+
this.#blending.delete(tile);
|
|
3374
|
+
setManualLodLevel(tile.lod, transition.to);
|
|
3375
|
+
this.#setLodVisibility(tile);
|
|
3376
|
+
}
|
|
3377
|
+
|
|
3378
|
+
#restoreLodTransition(tile: IResidentTile, transition: ILodTransition): void {
|
|
3379
|
+
const from = tile.levels[transition.from];
|
|
3380
|
+
const to = tile.levels[transition.to];
|
|
3381
|
+
if (from === undefined || to === undefined) return;
|
|
3382
|
+
const finer = from.resolution >= to.resolution ? from : to;
|
|
3383
|
+
if (this.#validate) restoreLevelSurface(tile.field, finer);
|
|
3384
|
+
else finer.mesh.morphTargetInfluences?.fill(0);
|
|
3385
|
+
}
|
|
3386
|
+
|
|
3387
|
+
#recordLodPop(pop: number): void {
|
|
3388
|
+
if (!Number.isFinite(pop)) throw new Error("TerrainTiles LOD pop observation must be finite.");
|
|
3389
|
+
this.#maxLodPop = Math.max(this.#maxLodPop, pop);
|
|
3390
|
+
if (pop > LOD_POP_THRESHOLD)
|
|
3391
|
+
throw new Error(
|
|
3392
|
+
`TerrainTiles LOD pop threshold ${String(LOD_POP_THRESHOLD)} exceeded by ${String(pop)}.`,
|
|
3393
|
+
);
|
|
3394
|
+
}
|
|
3395
|
+
|
|
3396
|
+
#removeStitch(key: string): void {
|
|
3397
|
+
const bridge = this.#stitches.get(key);
|
|
3398
|
+
if (bridge === undefined) return;
|
|
3399
|
+
this.#stitches.delete(key);
|
|
3400
|
+
this.remove(bridge.mesh);
|
|
3401
|
+
this.#stitchBytes -= bridge.bytes;
|
|
3402
|
+
bridge.geometry.dispose();
|
|
3403
|
+
}
|
|
3404
|
+
|
|
3405
|
+
#removeStitchesForTile(tileKey: string): void {
|
|
3406
|
+
for (const [key, bridge] of this.#stitches) {
|
|
3407
|
+
if (bridge.keys.includes(tileKey)) this.#removeStitch(key);
|
|
3408
|
+
}
|
|
3409
|
+
}
|
|
3410
|
+
|
|
3411
|
+
/**
|
|
3412
|
+
* Reconcile and observe every seam, unless nothing a seam reads changed since the last pass.
|
|
3413
|
+
*
|
|
3414
|
+
* The change detector is `this` class's own epoch, bumped by every writer of the state the ring
|
|
3415
|
+
* pass describes: a tile admitted or evicted, a LOD level set, a transition started, stepped or
|
|
3416
|
+
* finished, a bridge written or an edge restored, a collider created or disposed. A settled
|
|
3417
|
+
* 289-tile ring used to rebuild an array of per-tile levels, geometry ids and attribute versions
|
|
3418
|
+
* and compare it with last frame's — 244 ms of a six-second walk, plus 139 ms of the bridge states
|
|
3419
|
+
* — to be told the same thing the epoch already said.
|
|
3420
|
+
*
|
|
3421
|
+
* The reconcile half always runs when the epoch moved; the observe half is validation, so with
|
|
3422
|
+
* `validate` off a frame pays for this compare and the geometry it changes and nothing else.
|
|
3423
|
+
*
|
|
3424
|
+
* Under validation the full ring-state compare stays, as the extra detector it now is: it is what
|
|
3425
|
+
* catches a writer that reached past this class's own bookkeeping — a buffer overwritten without
|
|
3426
|
+
* `needsUpdate`, a level mesh moved from outside — and the corrupted-buffer specs fail closed on
|
|
3427
|
+
* it. The epoch cannot see those, and the trade is deliberate: the shipped frame trusts the writers
|
|
3428
|
+
* it owns, and the validating frame still checks everything.
|
|
3429
|
+
*/
|
|
3430
|
+
#seamPass(): void {
|
|
3431
|
+
if (this.#seamPending) {
|
|
3432
|
+
// CPU blends move every vertex; shared edges must remain canonical even before a reply arrives.
|
|
3433
|
+
if (this.#validate)
|
|
3434
|
+
for (const [a, b] of collectNeighborPairs(this.#resident, this.#pairScratch)) {
|
|
3435
|
+
const [aSide, bSide] = opposingEdge(a, b);
|
|
3436
|
+
const aLevel = renderedLevel(a);
|
|
3437
|
+
const bLevel = renderedLevel(b);
|
|
3438
|
+
if (aLevel === undefined || bLevel === undefined)
|
|
3439
|
+
throw new Error("TerrainTiles cannot reconcile a neighbor with no rendered LOD level.");
|
|
3440
|
+
restoreLevelEdge(a, aLevel, aSide);
|
|
3441
|
+
restoreLevelEdge(b, bLevel, bSide);
|
|
3442
|
+
}
|
|
3443
|
+
this.#stitchedEdges += this.#stitches.size;
|
|
3444
|
+
return;
|
|
3445
|
+
}
|
|
3446
|
+
if (this.#validate) {
|
|
3447
|
+
this.#ringStateInto(this.#ringScratch);
|
|
3448
|
+
if (sameState(this.#ringScratch, this.#settledRing)) {
|
|
3449
|
+
this.#stitchedEdges += this.#stitches.size;
|
|
3450
|
+
return;
|
|
3451
|
+
}
|
|
3452
|
+
} else if (this.#ringEpoch === this.#seamEpoch) {
|
|
3453
|
+
this.#stitchedEdges += this.#stitches.size;
|
|
3454
|
+
return;
|
|
3455
|
+
}
|
|
3456
|
+
if (this.#validate) this.#recordSeamDiagnostics(false);
|
|
3457
|
+
this.#reconcileNeighbors();
|
|
3458
|
+
}
|
|
3459
|
+
|
|
3460
|
+
/** Counted so a frame that built one is visible; see `#ringStateInto`. */
|
|
3461
|
+
#ringStateBuilds = 0;
|
|
3462
|
+
|
|
3463
|
+
#ringStateInto(state: number[]): void {
|
|
3464
|
+
this.#ringStateBuilds += 1;
|
|
3465
|
+
state.length = 0;
|
|
3466
|
+
for (const tile of this.#resident.values()) {
|
|
3467
|
+
const level = renderedLevel(tile);
|
|
3468
|
+
if (level === undefined) state.push(-1);
|
|
3469
|
+
else pushLevelState(state, level);
|
|
3470
|
+
}
|
|
3471
|
+
for (const bridge of this.#stitches.values()) pushBridgeState(state, bridge, this.#validate);
|
|
3472
|
+
}
|
|
3473
|
+
|
|
3474
|
+
/**
|
|
3475
|
+
* Seam gaps are running maxima, so a pair observed in exactly this state already contributed its
|
|
3476
|
+
* gap: re-measuring every resident pair three times an update cost ~3 ms a frame on a 289-tile
|
|
3477
|
+
* ring for the same numbers. Only pairs whose levels or bridge changed are observed again.
|
|
3478
|
+
*
|
|
3479
|
+
* The pass stamps the pairs it visits and clears the mode of every pair it did not, so it neither
|
|
3480
|
+
* builds the `${key}|coverage` string nor the Set of live keys for each of the ring's 544 pairs
|
|
3481
|
+
* twice a frame — which on this pass was more work than the observations it was pruning for.
|
|
3482
|
+
*/
|
|
3483
|
+
#recordSeamDiagnostics(includeBridgeCoverage = true): void {
|
|
3484
|
+
this.#observationPass += 1;
|
|
3485
|
+
const pass = this.#observationPass;
|
|
3486
|
+
for (const pair of collectNeighborPairs(this.#resident, this.#pairScratch)) {
|
|
3487
|
+
const key = neighborPairKey(pair);
|
|
3488
|
+
const bridge = this.#stitches.get(key);
|
|
3489
|
+
let observed = this.#observedSeams.get(key);
|
|
3490
|
+
if (observed === undefined) {
|
|
3491
|
+
observed = { coverage: undefined, plain: undefined, seenCoverage: 0, seenPlain: 0 };
|
|
3492
|
+
this.#observedSeams.set(key, observed);
|
|
3493
|
+
}
|
|
3494
|
+
if (includeBridgeCoverage) observed.seenCoverage = pass;
|
|
3495
|
+
else observed.seenPlain = pass;
|
|
3496
|
+
const state = seamState(pair, bridge, this.#validate);
|
|
3497
|
+
if (sameState(state, includeBridgeCoverage ? observed.coverage : observed.plain)) continue;
|
|
3498
|
+
if (state === undefined) {
|
|
3499
|
+
if (includeBridgeCoverage) observed.coverage = undefined;
|
|
3500
|
+
else observed.plain = undefined;
|
|
3501
|
+
} else if (includeBridgeCoverage) observed.coverage = state;
|
|
3502
|
+
else observed.plain = state;
|
|
3503
|
+
const { gap, visualGap } = seamObservation(
|
|
3504
|
+
pair[0],
|
|
3505
|
+
pair[1],
|
|
3506
|
+
bridge,
|
|
3507
|
+
this,
|
|
3508
|
+
includeBridgeCoverage,
|
|
3509
|
+
);
|
|
3510
|
+
this.#maxSeamGap = Math.max(this.#maxSeamGap, gap);
|
|
3511
|
+
this.#maxVisualSeamGap = Math.max(this.#maxVisualSeamGap, visualGap);
|
|
3512
|
+
}
|
|
3513
|
+
for (const [key, observed] of this.#observedSeams) {
|
|
3514
|
+
if (includeBridgeCoverage) {
|
|
3515
|
+
if (observed.seenCoverage !== pass) observed.coverage = undefined;
|
|
3516
|
+
} else if (observed.seenPlain !== pass) observed.plain = undefined;
|
|
3517
|
+
if (observed.coverage === undefined && observed.plain === undefined)
|
|
3518
|
+
this.#observedSeams.delete(key);
|
|
3519
|
+
}
|
|
3520
|
+
}
|
|
3521
|
+
|
|
3522
|
+
#fieldAt(x: number, z: number): Heightfield {
|
|
3523
|
+
finite(x, "query x");
|
|
3524
|
+
finite(z, "query z");
|
|
3525
|
+
const tileX = Math.floor((x + this.tileSize / 2) / this.tileSize);
|
|
3526
|
+
const tileZ = Math.floor((z + this.tileSize / 2) / this.tileSize);
|
|
3527
|
+
const tile = this.#resident.get(keyFor(tileX, tileZ));
|
|
3528
|
+
if (tile === undefined)
|
|
3529
|
+
throw new Error(`TerrainTiles query (${x}, ${z}) is outside its resident region.`);
|
|
3530
|
+
return tile.field;
|
|
3531
|
+
}
|
|
3532
|
+
|
|
3533
|
+
/**
|
|
3534
|
+
* Mark the block a tile's level belongs to for rebuild. Off with the merge, and cheap: one string
|
|
3535
|
+
* into a Set that at most holds the blocks a single frame's admissions, evictions and LOD moves
|
|
3536
|
+
* touched — the block geometry is rebuilt once, later, inside a frame's admission budget.
|
|
3537
|
+
*/
|
|
3538
|
+
#markBlockDirty(lod: number, tileX: number, tileZ: number): void {
|
|
3539
|
+
if (!this.#mergeTiles) return;
|
|
3540
|
+
this.#dirtyBlocks.add(blockKeyFor(lod, tileX, tileZ));
|
|
3541
|
+
}
|
|
3542
|
+
|
|
3543
|
+
#markTileDirty(tile: IResidentTile): void {
|
|
3544
|
+
this.#markBlockDirty(tile.lodLevel, tile.tileX, tile.tileZ);
|
|
3545
|
+
}
|
|
3546
|
+
|
|
3547
|
+
/**
|
|
3548
|
+
* Let go of a block one of its tiles has left.
|
|
3549
|
+
*
|
|
3550
|
+
* A departure is the one ring change a rebuild cannot hide: the block's geometry still holds the
|
|
3551
|
+
* tile that just left, so it would draw that ground a second time — at the level the tile has left
|
|
3552
|
+
* — until this frame's one rebuild could replace it, and one rebuild a frame does not arrive before
|
|
3553
|
+
* the next departure. So the block stops being drawn the frame the departure happens, every tile it
|
|
3554
|
+
* still holds goes back to its own mesh, and the rebuild queue brings the block back whole. It is
|
|
3555
|
+
* dirty either way: the block has to be rebuilt whatever this does to it. (PRD-475.)
|
|
3556
|
+
*/
|
|
3557
|
+
#releaseStaleBlock(lod: number, tileX: number, tileZ: number): void {
|
|
3558
|
+
if (!this.#mergeTiles) return;
|
|
3559
|
+
const blockKey = blockKeyFor(lod, tileX, tileZ);
|
|
3560
|
+
this.#markBlockDirty(lod, tileX, tileZ);
|
|
3561
|
+
if (this.#blocks.has(blockKey)) this.#dissolveBlock(blockKey);
|
|
3562
|
+
}
|
|
3563
|
+
|
|
3564
|
+
/**
|
|
3565
|
+
* Rebuild one dirty block, charging it to the frame's admission budget like any other streamed
|
|
3566
|
+
* work. One, per frame, whatever the budget still holds: a rebuild concatenates a K×K block of
|
|
3567
|
+
* settled tile levels, and a follow that paid for every block its own streaming churn left dirty
|
|
3568
|
+
* is the frame-time spike this cap exists to prevent — the plan's `TN_FRAME_SPANS` check watches
|
|
3569
|
+
* for exactly that. A refused rebuild stays dirty and the next `follow` runs it, so N dirty blocks
|
|
3570
|
+
* take N frames and a still follow point converges.
|
|
3571
|
+
*/
|
|
3572
|
+
#rebuildDirtyBlocks(budget: IAdmissionBudget | undefined): void {
|
|
3573
|
+
if (!this.#mergeTiles) return;
|
|
3574
|
+
const dirty = this.#nextDirtyBlock();
|
|
3575
|
+
if (dirty === undefined) return;
|
|
3576
|
+
const run = (): void => {
|
|
3577
|
+
this.#dirtyBlocks.delete(dirty);
|
|
3578
|
+
this.#rebuildBlock(dirty);
|
|
3579
|
+
};
|
|
3580
|
+
if (budget === undefined) {
|
|
3581
|
+
run();
|
|
3582
|
+
return;
|
|
3583
|
+
}
|
|
3584
|
+
if (!budget.admit(run)) this.#deferredAdmissions = 1;
|
|
3585
|
+
}
|
|
3586
|
+
|
|
3587
|
+
/** The lowest block key still waiting for a merge of its own, so the one a frame spends is the same. */
|
|
3588
|
+
#nextDirtyBlock(): string | undefined {
|
|
3589
|
+
let first: string | undefined;
|
|
3590
|
+
for (const candidate of this.#dirtyBlocks) {
|
|
3591
|
+
if (this.#mergingBlocks.has(candidate)) continue;
|
|
3592
|
+
if (first === undefined || candidate < first) first = candidate;
|
|
3593
|
+
}
|
|
3594
|
+
return first;
|
|
3595
|
+
}
|
|
3596
|
+
|
|
3597
|
+
/**
|
|
3598
|
+
* Build, or dissolve, one super-tile from the resident tiles it currently covers.
|
|
3599
|
+
*
|
|
3600
|
+
* Membership is recomputed from the resident set, never patched incrementally: a tile belongs iff
|
|
3601
|
+
* it is resident, settled (`lodTransition` undefined, so a morphing tile stays individual) and at
|
|
3602
|
+
* this block's LOD tier. A block of fewer than two tiles is dissolved rather than drawn — a single
|
|
3603
|
+
* merged mesh for one tile is the same draw with a copied geometry — and every tile that just left
|
|
3604
|
+
* the block has its own mesh restored.
|
|
3605
|
+
*
|
|
3606
|
+
* The concatenation runs as a job, so this thread names the block and the tile levels it covers and
|
|
3607
|
+
* then only swaps the attributes that come back.
|
|
3608
|
+
*/
|
|
3609
|
+
#rebuildBlock(blockKey: string): void {
|
|
3610
|
+
const { lod, blockX, blockZ } = blockCoordinates(blockKey);
|
|
3611
|
+
const { members, parts } = this.#blockMembers(blockKey, lod);
|
|
3612
|
+
if (parts.length < 2) {
|
|
3613
|
+
this.#dissolveBlock(blockKey);
|
|
3614
|
+
// The tiles that remain here (a lone member, or none) draw their own meshes again.
|
|
3615
|
+
for (const key of members) this.#showTile(key, blockKey);
|
|
3616
|
+
return;
|
|
3617
|
+
}
|
|
3618
|
+
const blockOrigin = {
|
|
3619
|
+
x: blockX * TERRAIN_MERGE_BLOCK * this.tileSize,
|
|
3620
|
+
z: blockZ * TERRAIN_MERGE_BLOCK * this.tileSize,
|
|
3621
|
+
};
|
|
3622
|
+
const captured = parts.map(({ geometry, origin }) => ({
|
|
3623
|
+
geometry,
|
|
3624
|
+
originX: origin.x,
|
|
3625
|
+
originZ: origin.z,
|
|
3626
|
+
attributes: [
|
|
3627
|
+
geometry.getAttribute("position") as BufferAttribute,
|
|
3628
|
+
geometry.getAttribute("normal") as BufferAttribute,
|
|
3629
|
+
geometry.getIndex(),
|
|
3630
|
+
].map((attribute) => ({ attribute, version: attribute?.version })),
|
|
3631
|
+
}));
|
|
3632
|
+
this.#mergingBlocks.add(blockKey);
|
|
3633
|
+
const job = timedSpan(SPANS.terrainBlock, () => this.#jobs.merge(mergeJob(parts, blockOrigin)));
|
|
3634
|
+
const apply = (result: ITerrainMergeResult): void => {
|
|
3635
|
+
this.#mergingBlocks.delete(blockKey);
|
|
3636
|
+
if (this.#released) return;
|
|
3637
|
+
// Completed merges cost work even when newer residency makes their result stale.
|
|
3638
|
+
this.#blockRebuilds += 1;
|
|
3639
|
+
if (job instanceof Promise) {
|
|
3640
|
+
const current = this.#blockMembers(blockKey, lod);
|
|
3641
|
+
const superseded =
|
|
3642
|
+
this.#dirtyBlocks.has(blockKey) ||
|
|
3643
|
+
current.members.size !== members.size ||
|
|
3644
|
+
[...members].some((key) => !current.members.has(key)) ||
|
|
3645
|
+
current.parts.length !== captured.length ||
|
|
3646
|
+
current.parts.some(({ geometry, origin }, partIndex) => {
|
|
3647
|
+
const previous = captured[partIndex];
|
|
3648
|
+
const attributes = [
|
|
3649
|
+
geometry.getAttribute("position") as BufferAttribute,
|
|
3650
|
+
geometry.getAttribute("normal") as BufferAttribute,
|
|
3651
|
+
geometry.getIndex(),
|
|
3652
|
+
];
|
|
3653
|
+
return (
|
|
3654
|
+
previous === undefined ||
|
|
3655
|
+
previous.geometry !== geometry ||
|
|
3656
|
+
previous.originX !== origin.x ||
|
|
3657
|
+
previous.originZ !== origin.z ||
|
|
3658
|
+
previous.attributes.some(
|
|
3659
|
+
({ attribute, version }, attributeIndex) =>
|
|
3660
|
+
attribute !== attributes[attributeIndex] ||
|
|
3661
|
+
version !== attributes[attributeIndex]?.version,
|
|
3662
|
+
)
|
|
3663
|
+
);
|
|
3664
|
+
});
|
|
3665
|
+
if (superseded) {
|
|
3666
|
+
this.#dirtyBlocks.add(blockKey);
|
|
3667
|
+
return;
|
|
3668
|
+
}
|
|
3669
|
+
}
|
|
3670
|
+
timedSpan(SPANS.terrainBlock, () =>
|
|
3671
|
+
this.#applyBlock({ blockKey, blockOrigin, lod, members }, result),
|
|
3672
|
+
);
|
|
3673
|
+
};
|
|
3674
|
+
if (job instanceof Promise)
|
|
3675
|
+
job.then(apply, (error: unknown) => {
|
|
3676
|
+
// Free the block for its next mark, and still name the failure.
|
|
3677
|
+
this.#mergingBlocks.delete(blockKey);
|
|
3678
|
+
console.error(`TN_TERRAIN_MERGE_FAILURE block=${blockKey} message=${String(error)}`);
|
|
3679
|
+
});
|
|
3680
|
+
else apply(job);
|
|
3681
|
+
}
|
|
3682
|
+
|
|
3683
|
+
#applyBlock(
|
|
3684
|
+
plan: {
|
|
3685
|
+
readonly blockKey: string;
|
|
3686
|
+
readonly blockOrigin: IHeightfieldOrigin;
|
|
3687
|
+
readonly lod: number;
|
|
3688
|
+
readonly members: Set<string>;
|
|
3689
|
+
},
|
|
3690
|
+
result: ITerrainMergeResult,
|
|
3691
|
+
): void {
|
|
3692
|
+
const { blockKey, blockOrigin, lod, members } = plan;
|
|
3693
|
+
const existing = this.#blocks.get(blockKey);
|
|
3694
|
+
const geometry = mergedBlockGeometry(result);
|
|
3695
|
+
const bytes = geometryBytes(geometry);
|
|
3696
|
+
this.#blockBytes += bytes - (existing?.bytes ?? 0);
|
|
3697
|
+
if (existing === undefined) {
|
|
3698
|
+
const mesh = terrainMesh(new Mesh(geometry, this.#surface));
|
|
3699
|
+
mesh.frustumCulled = true;
|
|
3700
|
+
mesh.name = `tn-terrain-block:${blockKey}`;
|
|
3701
|
+
// The merged geometry is written relative to the block origin, so the mesh carries it. Without
|
|
3702
|
+
// this the block drew a whole `blockOrigin` away from the tiles it replaced: floating slabs and
|
|
3703
|
+
// a hole where the ground is, at any block that is not at (0, 0). (PRD-475.)
|
|
3704
|
+
mesh.position.set(blockOrigin.x, 0, blockOrigin.z);
|
|
3705
|
+
mesh.receiveShadow = this.#receiveShadow;
|
|
3706
|
+
this.#blocks.set(blockKey, { bytes, geometry, key: blockKey, lod, members, mesh });
|
|
3707
|
+
this.add(mesh);
|
|
3708
|
+
} else {
|
|
3709
|
+
const left = existing.members;
|
|
3710
|
+
existing.geometry.dispose();
|
|
3711
|
+
existing.bytes = bytes;
|
|
3712
|
+
existing.mesh.geometry = geometry;
|
|
3713
|
+
// The record follows the geometry: the loop below restores the tiles this rebuild dropped, and
|
|
3714
|
+
// `terrainTiles` counts what the blocks hold, so a stale record here is a tile drawn twice or
|
|
3715
|
+
// not at all (PRD-475).
|
|
3716
|
+
existing.members = members;
|
|
3717
|
+
this.#blocks.set(blockKey, existing);
|
|
3718
|
+
for (const key of left) if (!members.has(key)) this.#showTile(key, blockKey);
|
|
3719
|
+
}
|
|
3720
|
+
for (const key of members) {
|
|
3721
|
+
this.#mergedMembers.set(key, blockKey);
|
|
3722
|
+
const tile = this.#resident.get(key);
|
|
3723
|
+
if (tile !== undefined) this.#setLodVisibility(tile);
|
|
3724
|
+
}
|
|
3725
|
+
}
|
|
3726
|
+
|
|
3727
|
+
/** The resident settled tiles a block covers, and their level geometries to concatenate. */
|
|
3728
|
+
#blockMembers(
|
|
3729
|
+
blockKey: string,
|
|
3730
|
+
lod: number,
|
|
3731
|
+
): { members: Set<string>; parts: { geometry: BufferGeometry; origin: IHeightfieldOrigin }[] } {
|
|
3732
|
+
const parts: { geometry: BufferGeometry; origin: IHeightfieldOrigin }[] = [];
|
|
3733
|
+
const members = new Set<string>();
|
|
3734
|
+
for (const tile of this.#resident.values()) {
|
|
3735
|
+
if (tile.lodLevel !== lod || tile.lodTransition !== undefined) continue;
|
|
3736
|
+
if (blockKeyFor(lod, tile.tileX, tile.tileZ) !== blockKey) continue;
|
|
3737
|
+
const level = tile.levels[lod];
|
|
3738
|
+
if (level === undefined) continue;
|
|
3739
|
+
parts.push({ geometry: level.geometry, origin: tile.origin });
|
|
3740
|
+
members.add(tile.key);
|
|
3741
|
+
}
|
|
3742
|
+
return { members, parts };
|
|
3743
|
+
}
|
|
3744
|
+
|
|
3745
|
+
/** Restore a tile that left, or never joined, a block; a morphing tile keeps its blend visible. */
|
|
3746
|
+
#showTile(key: string, blockKey: string): void {
|
|
3747
|
+
if (this.#mergedMembers.get(key) === blockKey) this.#mergedMembers.delete(key);
|
|
3748
|
+
const tile = this.#resident.get(key);
|
|
3749
|
+
if (tile !== undefined && tile.lodTransition === undefined) this.#setLodVisibility(tile);
|
|
3750
|
+
}
|
|
3751
|
+
|
|
3752
|
+
#dissolveBlock(blockKey: string): void {
|
|
3753
|
+
const block = this.#blocks.get(blockKey);
|
|
3754
|
+
if (block === undefined) return;
|
|
3755
|
+
this.#blocks.delete(blockKey);
|
|
3756
|
+
this.remove(block.mesh);
|
|
3757
|
+
this.#blockBytes -= block.bytes;
|
|
3758
|
+
block.geometry.dispose();
|
|
3759
|
+
for (const key of block.members) this.#showTile(key, blockKey);
|
|
3760
|
+
}
|
|
3761
|
+
|
|
3762
|
+
#now(): number {
|
|
3763
|
+
const host = globalThis as { performance?: { now?: () => number } };
|
|
3764
|
+
return typeof host.performance?.now === "function" ? host.performance.now() : Date.now();
|
|
3765
|
+
}
|
|
3766
|
+
|
|
3767
|
+
/**
|
|
3768
|
+
* `TN_TERRAIN_TILES`, every `TERRAIN_TILE_MARKER_MS`, with the merge on or off: the same census
|
|
3769
|
+
* before and after is the only way to read what the merge cut. A run that asked for validation also
|
|
3770
|
+
* gets the seam and LOD-pop maxima it is paying to measure, so a browser console run prints them
|
|
3771
|
+
* instead of only an in-process accessor ever reading them.
|
|
3772
|
+
*/
|
|
3773
|
+
#reportTileMarker(): void {
|
|
3774
|
+
const now = this.#now();
|
|
3775
|
+
if (now - this.#tilesToldAt < TERRAIN_TILE_MARKER_MS) return;
|
|
3776
|
+
this.#tilesToldAt = now;
|
|
3777
|
+
const stats = this.terrainTiles;
|
|
3778
|
+
const measurements = this.#validate
|
|
3779
|
+
? ` maxSeamGap=${String(this.maxSeamGap)} maxLodPop=${String(this.maxLodPop)} ` +
|
|
3780
|
+
`maxVisualSeamGap=${String(this.maxVisualSeamGap)}`
|
|
3781
|
+
: "";
|
|
3782
|
+
console.info(
|
|
3783
|
+
`TN_TERRAIN_TILES tiles=${String(stats.tiles)} blocks=${String(stats.blocks)} draws=${String(stats.draws)} blending=${String(stats.blending)} rebuilds=${String(stats.rebuilds)} blockBytes=${String(stats.blockBytes)}${measurements}`,
|
|
3784
|
+
);
|
|
3785
|
+
}
|
|
3786
|
+
|
|
3787
|
+
#evict(tile: IResidentTile): void {
|
|
3788
|
+
this.#blending.delete(tile);
|
|
3789
|
+
if (this.#mergeTiles) {
|
|
3790
|
+
this.#releaseStaleBlock(tile.lodLevel, tile.tileX, tile.tileZ);
|
|
3791
|
+
this.#mergedMembers.delete(tile.key);
|
|
3792
|
+
}
|
|
3793
|
+
if (this.#resident.get(tile.key) === tile) {
|
|
3794
|
+
this.#resident.delete(tile.key);
|
|
3795
|
+
this.#morphEdgesDirty = true;
|
|
3796
|
+
}
|
|
3797
|
+
this.#ringEpoch += 1;
|
|
3798
|
+
this.#removeStitchesForTile(tile.key);
|
|
3799
|
+
this.remove(tile.lod);
|
|
3800
|
+
tile.collider?.dispose();
|
|
3801
|
+
tile.field.detach();
|
|
3802
|
+
for (const level of tile.levels) level.geometry.dispose();
|
|
3803
|
+
this.#releaseAsset(tile);
|
|
3804
|
+
}
|
|
3805
|
+
|
|
3806
|
+
#disposeTile(tile: IResidentTile): void {
|
|
3807
|
+
tile.collider?.dispose();
|
|
3808
|
+
tile.field.detach();
|
|
3809
|
+
for (const level of tile.levels) level.geometry.dispose();
|
|
3810
|
+
tile.lod.removeFromParent();
|
|
3811
|
+
this.#releaseAsset(tile);
|
|
3812
|
+
}
|
|
3813
|
+
|
|
3814
|
+
#releaseAsset(tile: IResidentTile): void {
|
|
3815
|
+
if (this.#assets === undefined || tile.assetKey === undefined) return;
|
|
3816
|
+
const stillReferenced = [...this.#resident.values()].some(
|
|
3817
|
+
(resident) => resident !== tile && resident.assetKey === tile.assetKey,
|
|
3818
|
+
);
|
|
3819
|
+
if (!stillReferenced) this.#assets.release("model", tile.assetKey);
|
|
3820
|
+
}
|
|
3821
|
+
|
|
3822
|
+
#recordPeaks(): void {
|
|
3823
|
+
this.#peakTiles = Math.max(this.#peakTiles, this.residentTileCount);
|
|
3824
|
+
this.#peakBytes = Math.max(this.#peakBytes, this.residentBytes);
|
|
3825
|
+
}
|
|
3826
|
+
}
|