@spacexr/3d-tiles-runtime 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +93 -2
  3. package/dist/chunk-AI6NWGCA.js +316 -0
  4. package/dist/chunk-AI6NWGCA.js.map +1 -0
  5. package/dist/chunk-G7YVZYMR.js +24 -0
  6. package/dist/chunk-G7YVZYMR.js.map +1 -0
  7. package/dist/chunk-PJIVVIOF.js +205 -0
  8. package/dist/chunk-PJIVVIOF.js.map +1 -0
  9. package/dist/chunk-Q2AL6LWU.js +3 -0
  10. package/dist/chunk-Q2AL6LWU.js.map +1 -0
  11. package/dist/chunk-Q35HKP5V.js +249 -0
  12. package/dist/chunk-Q35HKP5V.js.map +1 -0
  13. package/dist/chunk-URZDM4BH.js +488 -0
  14. package/dist/chunk-URZDM4BH.js.map +1 -0
  15. package/dist/implicit/index.d.ts +64 -0
  16. package/dist/implicit/index.js +4 -0
  17. package/dist/implicit/index.js.map +1 -0
  18. package/dist/index-CNnPRQZc.d.ts +350 -0
  19. package/dist/index.d.ts +713 -0
  20. package/dist/index.js +3074 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/metadata/index.d.ts +12 -0
  23. package/dist/metadata/index.js +3 -0
  24. package/dist/metadata/index.js.map +1 -0
  25. package/dist/pipeline/index.d.ts +5 -0
  26. package/dist/pipeline/index.js +3 -0
  27. package/dist/pipeline/index.js.map +1 -0
  28. package/dist/ports/index.d.ts +62 -0
  29. package/dist/ports/index.js +4 -0
  30. package/dist/ports/index.js.map +1 -0
  31. package/dist/resource-DH72MRMN.d.ts +34 -0
  32. package/dist/spatial/index.d.ts +402 -0
  33. package/dist/spatial/index.js +3 -0
  34. package/dist/spatial/index.js.map +1 -0
  35. package/dist/spatial-3IDPbyv4.d.ts +28 -0
  36. package/dist/types-Dn5i8Uqg.d.ts +78 -0
  37. package/dist/types-ri64XfSE.d.ts +237 -0
  38. package/package.json +102 -5
  39. package/src/implicit/availability.ts +55 -0
  40. package/src/implicit/coordinates.ts +193 -0
  41. package/src/implicit/dense-subtree-loader.ts +23 -0
  42. package/src/implicit/index.ts +6 -0
  43. package/src/implicit/standard-subtree-loader.ts +71 -0
  44. package/src/implicit/tile-data-source.ts +120 -0
  45. package/src/implicit/types.ts +156 -0
  46. package/src/index.ts +6 -0
  47. package/src/metadata/index.ts +2 -0
  48. package/src/metadata/metadata-resolver.ts +308 -0
  49. package/src/metadata/types.ts +91 -0
  50. package/src/pipeline/index.ts +4 -0
  51. package/src/pipeline/metadata-store.ts +44 -0
  52. package/src/pipeline/ports.ts +62 -0
  53. package/src/pipeline/states.ts +56 -0
  54. package/src/pipeline/tile-3d.ts +165 -0
  55. package/src/ports/camera.ts +12 -0
  56. package/src/ports/content.ts +71 -0
  57. package/src/ports/glyph.ts +13 -0
  58. package/src/ports/index.ts +32 -0
  59. package/src/ports/resource.ts +54 -0
  60. package/src/ports/spatial.ts +28 -0
  61. package/src/ports/telemetry.ts +44 -0
  62. package/src/runtime/cache.ts +112 -0
  63. package/src/runtime/contracts.ts +77 -0
  64. package/src/runtime/events.ts +57 -0
  65. package/src/runtime/hooks.ts +99 -0
  66. package/src/runtime/index.ts +7 -0
  67. package/src/runtime/instrumentation.ts +163 -0
  68. package/src/runtime/priority-scheduler.ts +88 -0
  69. package/src/runtime/quadtree-balance.ts +215 -0
  70. package/src/runtime/tile-runtime.ts +3508 -0
  71. package/src/spatial/bounding-volumes.ts +159 -0
  72. package/src/spatial/ecef-types.ts +110 -0
  73. package/src/spatial/ecef.ts +196 -0
  74. package/src/spatial/index.ts +6 -0
  75. package/src/spatial/utm-bounds.ts +151 -0
  76. package/src/spatial/utm-types.ts +83 -0
  77. package/src/spatial/vertical-scale.ts +125 -0
  78. package/src/spatial/view-metrics.ts +132 -0
@@ -0,0 +1,3508 @@
1
+ import type { IBoundingVolume, IContent, IMetadataSchema, ITile } from "@spacexr/3d-tiles-core";
2
+
3
+ import type { ITileTopology } from "@spacexr/tiles";
4
+ import { LoadedSubtreeAvailability } from "../implicit/availability";
5
+ import {
6
+ computeImplicitTile,
7
+ expandImplicitTemplate,
8
+ implicitBranchingFactor,
9
+ implicitChildCoordinates,
10
+ implicitLocalCoordinates,
11
+ } from "../implicit/coordinates";
12
+ import type {
13
+ IImplicitCoordinates,
14
+ IImplicitSubtreeGraft,
15
+ IImplicitTileResolver,
16
+ ILoadedImplicitSubtree,
17
+ IRuntimeImplicitContext,
18
+ IRuntimeImplicitSubtree,
19
+ IRuntimeImplicitTile,
20
+ } from "../implicit/types";
21
+ import { MetadataResolver } from "../metadata/metadata-resolver";
22
+ import type { IMetadataAncestorInput, IMetadataDiagnostic, IMetadataSnapshot } from "../metadata/types";
23
+ import { RuntimeMetadataStore } from "../pipeline/metadata-store";
24
+ import type { ITilePresentationContext, ITileReadinessPort } from "../pipeline/ports";
25
+ import {
26
+ CameraChangeFlags,
27
+ NO_METADATA,
28
+ TileContentKind,
29
+ TileMetadataState,
30
+ TilePresentationState,
31
+ TileReadinessState,
32
+ TileRefinementMode,
33
+ TileSelectionState,
34
+ } from "../pipeline/states";
35
+ import { Tile3D, Tile3DContent } from "../pipeline/tile-3d";
36
+ import type {
37
+ ContentLoadResult,
38
+ IContentLoadContext,
39
+ IContentPresentationContext,
40
+ IGlyphPublicationContext,
41
+ ILoadedTileset,
42
+ IRuntimeAdapter,
43
+ IRuntimeMetric,
44
+ IRuntimeSubscription,
45
+ IRuntimeUriResolver,
46
+ } from "../ports";
47
+ import { StandardUriResolver } from "../ports";
48
+ import type { RuntimeMetricName } from "../ports/telemetry";
49
+ import type { VerticalScale } from "../spatial/vertical-scale";
50
+ import type {
51
+ IResolvedRuntimeCacheOptions,
52
+ IRuntimeCacheCounters,
53
+ IRuntimeCacheEviction,
54
+ IRuntimeCacheOptions,
55
+ RuntimeCacheEvictionReason,
56
+ } from "./cache";
57
+ import { resolveRuntimeCacheOptions } from "./cache";
58
+ import type {
59
+ IRuntimeContent,
60
+ IRuntimeFrameResult,
61
+ IRuntimeTile,
62
+ IRuntimeTilesetDocument,
63
+ ITileContext,
64
+ RuntimeTilePredicate,
65
+ } from "./contracts";
66
+ import { RuntimeEventHub } from "./events";
67
+ import type {
68
+ HookResult,
69
+ ICacheEvictionHookContext,
70
+ IContentHookContext,
71
+ IFrameHookContext,
72
+ IMetadataHookContext,
73
+ IRuntimeErrorHookContext,
74
+ IRuntimeHooks,
75
+ ISubtreeHookContext,
76
+ ITileHookContext,
77
+ ITilesetLoadHookContext,
78
+ ITilesetLoadedHookContext,
79
+ } from "./hooks";
80
+ import type { IRuntimeInstrumentationOptions, IRuntimeStateStatistics } from "./instrumentation";
81
+ import { RuntimeInstrumentation } from "./instrumentation";
82
+ import { PriorityScheduler } from "./priority-scheduler";
83
+ import {
84
+ quadtreeBalanceRefinements,
85
+ quadtreeImbalances,
86
+ quadtreeTileKey,
87
+ quadtreeTouches,
88
+ refineQuadtreeCut,
89
+ type IQuadtreeCutTile,
90
+ type IQuadtreeImbalance,
91
+ type IQuadtreeTileLocation,
92
+ } from "./quadtree-balance";
93
+
94
+ export interface ITileRuntimeOptions<TCamera, TSpatial, TContentHandle, TGlyphHandle> {
95
+ id: string;
96
+ uri: string;
97
+ adapter: IRuntimeAdapter<TCamera, TSpatial, TContentHandle, TGlyphHandle>;
98
+ /**
99
+ * Selection policy shared by every content type and renderer. The base policy traverses visible tiles only,
100
+ * waits for the replacement front, and closes its ready quadtree cut before presentation. The active policy is
101
+ * retained for integrations not yet migrated. Defaults to active.
102
+ */
103
+ selectionStrategy?: "base" | "active";
104
+ /**
105
+ * How a tile with nothing to present refines. With "always", such a tile is a structural node: it refines whatever its
106
+ * screen-space error. With "geometric-error", its geometric error applies, as 3D Tiles 1.1 does for every tile: an
107
+ * explicit tile whose contents are all known empty and ready, a tile without content included, refines only when its
108
+ * screen-space error requires it. Otherwise it presents nothing, its descendants are not loaded, and under REPLACE it
109
+ * still completes the replacement of its parent. A tile with an external tileset, with a content not loaded yet, or an
110
+ * implicit tile always refines. Defaults to "always".
111
+ */
112
+ emptyTileRefinement?: "always" | "geometric-error";
113
+ maxScreenSpaceError?: number;
114
+ maxScreenSpaceErrorForDepth?: (depth: number, defaultValue: number) => number;
115
+ /**
116
+ * Fraction of the SSE threshold retained while coarsening. A value of
117
+ * `0.1` refines above the configured threshold and coarsens only below
118
+ * 90 percent of it. This prevents LOD oscillation near the threshold.
119
+ */
120
+ refinementHysteresisRatio?: number;
121
+ /**
122
+ * Factor on the threshold above which a tile not yet refined refines, read at each frame, at least 1. A renderer can
123
+ * raise it while its camera moves fast: tiles already refined still coarsen against the threshold itself, and a
124
+ * refinement required by the quadtree balance always happens, so that it only holds back new detail. When the factor
125
+ * drops while the camera is still, call {@link TileRuntime.requestFrame}. Defaults to 1.
126
+ */
127
+ refinementThresholdScale?: () => number;
128
+ /**
129
+ * Time a refined tile stays refined once nothing requires its refinement any more, neither its screen-space error
130
+ * nor the quadtree balance, without interruption. A refinement then survives a neighbour leaving the view for a
131
+ * moment, or a screen-space error dipping under the threshold while the camera turns. When it expires,
132
+ * {@link TileRuntime.hasPendingWork} asks for a frame, even with a still camera. Defaults to 300; 0 coarsens at once.
133
+ */
134
+ coarseningDelayMilliseconds?: number;
135
+ /**
136
+ * Keeps already selected descendants while their coarser replacement is
137
+ * loading, or as a last-resort fallback when no ready renderable ancestor
138
+ * exists. Correct visual coverage never depends on the cache. Defaults to
139
+ * true.
140
+ */
141
+ stableReplacementCut?: boolean;
142
+ /**
143
+ * Loads the children of a refined tile that lie outside the view, with a
144
+ * lower priority than visible tiles. A refined tile is replaced by its
145
+ * children only once every visible child is ready; without preloading, a
146
+ * child entering the view as the camera turns is not ready, and the whole
147
+ * refined area falls back to the coarser tile until it loads. Defaults to
148
+ * true; false saves the loads of tiles that may never enter the view.
149
+ */
150
+ preloadSiblings?: boolean;
151
+ /**
152
+ * Keeps the displayed tiles of implicit QUADTREE tilesets within one level
153
+ * of detail of their edge neighbours (2:1 balance), or within
154
+ * `maxLevelDifference` levels. A tile that would be displayed further from
155
+ * a neighbour is refined in the same frame, even when its screen-space
156
+ * error does not require it, and the loads it needs come first. While they
157
+ * load, the displayed finer tiles are kept, and a refinement that the
158
+ * neighbour cannot follow yet waits. Terrain grids can then connect every
159
+ * edge with junctions of that many levels.
160
+ *
161
+ * Neighbours are found across implicit tilesets when the implicit resolver
162
+ * provides `addressOf`; `wrapX` then also connects the antimeridian of a
163
+ * global pyramid. Defaults to false.
164
+ */
165
+ quadtreeBalance?: boolean | IQuadtreeBalanceOptions;
166
+ /** Vertical scale of the scene. Its changes derive the spatial state of every tile again. */
167
+ verticalScale?: VerticalScale;
168
+ maxConcurrentLoads?: number;
169
+ maxLoadAttempts?: number;
170
+ cache?: IRuntimeCacheOptions | false;
171
+ /** Clock of the cache retention, in milliseconds. Defaults to `performance.now`. */
172
+ clock?: () => number;
173
+ instrumentation?: boolean | IRuntimeInstrumentationOptions;
174
+ hooks?: readonly IRuntimeHooks<TCamera, TSpatial, TContentHandle, TGlyphHandle>[];
175
+ }
176
+
177
+ /** Bounds the traversal passes of the quadtree balance; one pass per level is always enough. */
178
+ const MAX_BALANCE_PASSES = 32;
179
+
180
+ /** Share of its screen-space error used as the load priority of a sibling preloaded outside the view. */
181
+ const PRELOAD_PRIORITY_SCALE = 0.25;
182
+
183
+ /** Load priority of the tiles the quadtree balance waits for, above any screen-space error. */
184
+ const BALANCE_LOAD_PRIORITY = Number.MAX_SAFE_INTEGER;
185
+
186
+ export interface IQuadtreeBalanceOptions {
187
+ /** Wraps columns around the antimeridian for addresses from `IImplicitTileResolver.addressOf`. Defaults to false. */
188
+ wrapX?: boolean;
189
+ /** How addresses from `IImplicitTileResolver.addressOf` connect, for example across configured local frames, in place of `wrapX`. */
190
+ topology?: ITileTopology;
191
+ /**
192
+ * Largest difference of level allowed between edge neighbours. Defaults to 1, the 2:1 balance. A renderer whose
193
+ * junctions join tiles further apart, for example by moving the edge vertices of the fine tile onto the coarse edge,
194
+ * may allow 2 or more: the balance then refines fewer tiles.
195
+ */
196
+ maxLevelDifference?: number;
197
+ }
198
+
199
+ interface IContentCacheEntry<TSpatial, TContentHandle, TGlyphHandle> {
200
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>;
201
+ content: IRuntimeContent<TContentHandle> & { handle: TContentHandle };
202
+ }
203
+
204
+ interface ISubtreeCacheEntry<TSpatial, TContentHandle, TGlyphHandle> {
205
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>;
206
+ subtree: IRuntimeImplicitSubtree;
207
+ users: Array<IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>;
208
+ }
209
+
210
+ /** Reload of a stale content, from its request to the swap of its handle. */
211
+ interface IContentRefresh<TContentHandle> {
212
+ /** Invalidation the reload answers; a later one leaves the content stale. */
213
+ serial: number;
214
+ /** Reported result, swapped in at the start of the next frame. */
215
+ result?: ContentLoadResult<TContentHandle>;
216
+ }
217
+
218
+ type ReadyContent<TContentHandle> = IRuntimeContent<TContentHandle> & { handle: TContentHandle };
219
+
220
+ export class TileRuntime<TCamera, TSpatial, TContentHandle = unknown, TGlyphHandle = unknown> {
221
+ public readonly id: string;
222
+ public readonly uri: string;
223
+ public readonly adapter: IRuntimeAdapter<TCamera, TSpatial, TContentHandle, TGlyphHandle>;
224
+ public readonly events = new RuntimeEventHub<TSpatial, TContentHandle, TGlyphHandle>();
225
+ public readonly instrumentation: RuntimeInstrumentation;
226
+ public readonly metadataStore = new RuntimeMetadataStore();
227
+
228
+ private readonly selectionStrategy: "base" | "active";
229
+ private readonly emptyTileRefinement: "always" | "geometric-error";
230
+ private readonly maxScreenSpaceError: number;
231
+ private readonly maxScreenSpaceErrorForDepth: ((depth: number, defaultValue: number) => number) | undefined;
232
+ private readonly refinementHysteresisRatio: number;
233
+ private readonly refinementThresholdScale: (() => number) | undefined;
234
+ private readonly stableReplacementCut: boolean;
235
+ private readonly preloadSiblings: boolean;
236
+ private readonly coarseningDelayMilliseconds: number;
237
+ /** Since when each refined tile has no longer required its refinement, and the last frame that saw it so. */
238
+ private readonly coarseningSince = new Map<string, { since: number; frame: number }>();
239
+ /** When the first delayed coarsening of the last frame expires. */
240
+ private nextCoarseningAt: number | undefined;
241
+ /** Priority asked in the current frame for each queued load, whose passes may ask several. */
242
+ private readonly queuedPriorities = new Map<string, number>();
243
+ private queuedPrioritiesFrame = -1;
244
+ private readonly quadtreeBalance: (IQuadtreeBalanceOptions & { maxLevelDifference: number }) | undefined;
245
+ /** Keys of the tiles that must refine to keep the quadtree balanced in the current frame. */
246
+ private balanceRefinements = new Set<string>();
247
+ /**
248
+ * Refinements the balance of the last published cut required, from which the next frame starts: a tile refined by the
249
+ * balance alone stays required from the first pass, instead of starting a coarsening delay that a later pass cancels.
250
+ */
251
+ private publishedBalanceRefinements = new Set<string>();
252
+ /** Visible selected quadtree tiles of the last traversal, whose neighbours stay active. */
253
+ private visibleTiles = new Set<string>();
254
+ /** Tiles whose refinement waits in the current frame, because a neighbour cannot follow yet. */
255
+ private readonly balanceHolds = new Set<string>();
256
+ private unbalancedCount = 0;
257
+ private readonly maxLoadAttempts: number;
258
+ private readonly cacheOptions: IResolvedRuntimeCacheOptions;
259
+ private readonly cacheCounters: IRuntimeCacheCounters = {
260
+ sweeps: 0,
261
+ contentEvictions: 0,
262
+ subtreeEvictions: 0,
263
+ implicitBranchPrunes: 0,
264
+ prunedNodes: 0,
265
+ releasedCpuBytes: 0,
266
+ releasedGpuBytes: 0,
267
+ };
268
+ private readonly hooks: readonly IRuntimeHooks<TCamera, TSpatial, TContentHandle, TGlyphHandle>[];
269
+ private readonly uriResolver: IRuntimeUriResolver;
270
+ private readonly metadataResolver = new MetadataResolver();
271
+ private readonly scheduler: PriorityScheduler;
272
+ private readonly lifecycleController = new AbortController();
273
+ private readonly nodes = new Map<string, IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>();
274
+ /** Latest invalidation of each stale content, and the failed reloads since. */
275
+ private readonly staleContents = new Map<IRuntimeContent<TContentHandle>, { serial: number; failures: number }>();
276
+ private readonly refreshes = new Map<IRuntimeContent<TContentHandle>, IContentRefresh<TContentHandle>>();
277
+ /** Ready contents reported as provisional: stale, and reloaded only while their tile is a leaf of the cut. */
278
+ private readonly provisionalContents = new Set<IRuntimeContent<TContentHandle>>();
279
+ private invalidations = 0;
280
+ private readonly refiningNodes = new Set<string>();
281
+ private readonly replacementFrontNodes = new Set<string>();
282
+ private readonly activeThisFrame = new Set<string>();
283
+ private selectedAtFrameStart: Array<IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>> = [];
284
+ private baseReplacementBlocked = false;
285
+
286
+ private rootNode?: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>;
287
+ private rootDocument?: IRuntimeTilesetDocument;
288
+ private cameraSubscription: IRuntimeSubscription | undefined;
289
+ private startPromise?: Promise<void>;
290
+ private updateChain: Promise<void> = Promise.resolve();
291
+ private lastCamera?: TCamera;
292
+ private pendingCamera: TCamera | undefined;
293
+ private pendingCameraChanges = CameraChangeFlags.None;
294
+ private currentCameraChanges = CameraChangeFlags.None;
295
+ private readonly unsubscribeVerticalScale: (() => void) | undefined;
296
+ private spatialStale = false;
297
+ private cameraDirty = false;
298
+ private frame = 0;
299
+ /** Start time of the recent frames, oldest first; older frames are beyond the cache retention. */
300
+ private readonly frameTimes = new Map<number, number>();
301
+ private readonly clock: () => number;
302
+ private disposed = false;
303
+ private refreshNeeded = false;
304
+
305
+ public constructor(options: ITileRuntimeOptions<TCamera, TSpatial, TContentHandle, TGlyphHandle>) {
306
+ this.id = options.id;
307
+ this.uri = options.uri;
308
+ this.adapter = options.adapter;
309
+ if (!options.adapter.content && !options.adapter.activation) {
310
+ throw new Error("A content adapter or a tile activation adapter is required.");
311
+ }
312
+ if (!options.adapter.content && !options.adapter.presentation) {
313
+ throw new Error("A content adapter or a tile presentation adapter is required.");
314
+ }
315
+ this.selectionStrategy = options.selectionStrategy ?? "active";
316
+ if (this.selectionStrategy !== "base" && this.selectionStrategy !== "active") throw new RangeError("Unknown selection strategy.");
317
+ this.emptyTileRefinement = options.emptyTileRefinement ?? "always";
318
+ if (this.emptyTileRefinement !== "always" && this.emptyTileRefinement !== "geometric-error")
319
+ throw new RangeError("Unknown empty tile refinement.");
320
+ this.maxScreenSpaceError = options.maxScreenSpaceError ?? 16;
321
+ this.maxScreenSpaceErrorForDepth = options.maxScreenSpaceErrorForDepth;
322
+ this.refinementHysteresisRatio = options.refinementHysteresisRatio ?? 0.1;
323
+ if (!Number.isFinite(this.refinementHysteresisRatio) || this.refinementHysteresisRatio < 0 || this.refinementHysteresisRatio >= 1) {
324
+ throw new RangeError("refinementHysteresisRatio must be in the interval [0, 1).");
325
+ }
326
+ this.refinementThresholdScale = options.refinementThresholdScale;
327
+ this.stableReplacementCut = options.stableReplacementCut ?? true;
328
+ this.preloadSiblings = options.preloadSiblings ?? true;
329
+ this.coarseningDelayMilliseconds = Math.max(0, options.coarseningDelayMilliseconds ?? 300);
330
+ this.clock = options.clock ?? (() => performance.now());
331
+ this.frameTimes.set(0, this.clock());
332
+ const balance = typeof options.quadtreeBalance === "object" ? options.quadtreeBalance : {};
333
+ const maxLevelDifference = balance.maxLevelDifference ?? 1;
334
+ if (!Number.isInteger(maxLevelDifference) || maxLevelDifference < 1)
335
+ throw new RangeError("quadtreeBalance.maxLevelDifference must be an integer of at least 1.");
336
+ this.quadtreeBalance = options.quadtreeBalance
337
+ ? {
338
+ wrapX: balance.wrapX === true,
339
+ maxLevelDifference,
340
+ ...(balance.topology ? { topology: balance.topology } : {}),
341
+ }
342
+ : undefined;
343
+ this.maxLoadAttempts = Math.max(1, Math.floor(options.maxLoadAttempts ?? 3));
344
+ this.cacheOptions = resolveRuntimeCacheOptions(options.cache);
345
+ this.hooks = options.hooks ?? [];
346
+ this.uriResolver = options.adapter.uri ?? new StandardUriResolver();
347
+ this.scheduler = new PriorityScheduler(options.maxConcurrentLoads ?? 4);
348
+ this.instrumentation = new RuntimeInstrumentation(options.instrumentation, this.id, () => this.collectStatistics());
349
+ this.unsubscribeVerticalScale = options.verticalScale?.subscribe(() => {
350
+ this.spatialStale = true;
351
+ this.refreshNeeded = true;
352
+ });
353
+ }
354
+
355
+ public get root(): IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle> | undefined {
356
+ return this.rootNode;
357
+ }
358
+
359
+ public get document(): IRuntimeTilesetDocument | undefined {
360
+ return this.rootDocument;
361
+ }
362
+
363
+ public get pendingLoads(): number {
364
+ return this.scheduler.size;
365
+ }
366
+
367
+ /** True when settled asynchronous state still needs a caller-driven frame. */
368
+ public get hasPendingWork(): boolean {
369
+ // Queued and in-flight fetches run independently. Pumping traversal
370
+ // frames while they are unresolved only ages the cache and repeats the
371
+ // same cut. Their settlement calls markDirty(), which requests exactly
372
+ // one new frame.
373
+ return this.refreshNeeded || this.cameraDirty || (this.nextCoarseningAt !== undefined && this.clock() >= this.nextCoarseningAt);
374
+ }
375
+
376
+ public get selectedTiles(): readonly IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>[] {
377
+ return [...this.nodes.values()].filter((node) => node.selected);
378
+ }
379
+
380
+ public get cameraChanges(): CameraChangeFlags {
381
+ return this.currentCameraChanges;
382
+ }
383
+
384
+ /** Immediately applies cache budgets. With force=true, every inactive cache entry is released. */
385
+ public trimCache(force = false): Promise<void> {
386
+ const operation = this.updateChain.then(async () => {
387
+ if (this.disposed) return;
388
+ await this.sweepCache(force);
389
+ this.instrumentation.publish();
390
+ });
391
+ this.updateChain = operation.then(
392
+ () => undefined,
393
+ () => undefined,
394
+ );
395
+ return operation;
396
+ }
397
+
398
+ /**
399
+ * Marks the loaded contents of the tiles a predicate selects as stale, such as the tiles whose region crosses an
400
+ * area whose data changed, and reloads them. Each keeps its current handle presented until its reload is ready:
401
+ * the swap happens between two frames, so the view never shows a hole. Stale contents reload while their tile is
402
+ * in the working set; the others reload when it comes back, and meanwhile still serve as they are.
403
+ *
404
+ * The reload goes through the activation adapter, with `refresh` set, or through the legacy content adapter.
405
+ *
406
+ * @returns The number of tiles invalidated.
407
+ */
408
+ public invalidate(predicate: RuntimeTilePredicate<TSpatial, TContentHandle, TGlyphHandle>): Promise<number> {
409
+ const operation = this.updateChain.then(() => {
410
+ if (this.disposed) return 0;
411
+ const serial = ++this.invalidations;
412
+ let tiles = 0;
413
+ for (const node of this.nodes.values()) {
414
+ // A content still loading may read the data from before the invalidation: it reloads once ready.
415
+ const contents = node.contents.filter(
416
+ (content) =>
417
+ (content.kind === TileContentKind.Unknown || content.kind === TileContentKind.Renderable) &&
418
+ (content.status === TileReadinessState.Ready || content.status === TileReadinessState.Preparing),
419
+ );
420
+ if (contents.length === 0 || !predicate(node)) continue;
421
+ tiles++;
422
+ for (const content of contents) {
423
+ content.stale = true;
424
+ this.staleContents.set(content, { serial, failures: 0 });
425
+ this.events.emit({ type: "content-state", tile: node, content });
426
+ }
427
+ }
428
+ if (tiles > 0) this.markDirty();
429
+ return tiles;
430
+ });
431
+ this.updateChain = operation.then(
432
+ () => undefined,
433
+ () => undefined,
434
+ );
435
+ return operation;
436
+ }
437
+
438
+ public async start(): Promise<void> {
439
+ if (this.disposed) throw new Error("The runtime has been disposed.");
440
+ if (this.startPromise) return this.startPromise;
441
+ this.startPromise = this.initializeRoot();
442
+ return this.startPromise;
443
+ }
444
+
445
+ public update(camera: TCamera): Promise<IRuntimeFrameResult<TSpatial, TContentHandle, TGlyphHandle>> {
446
+ this.pendingCamera = undefined;
447
+ this.pendingCameraChanges = CameraChangeFlags.None;
448
+ this.cameraDirty = false;
449
+ return this.enqueueUpdate(camera, CameraChangeFlags.All);
450
+ }
451
+
452
+ private enqueueUpdate(
453
+ camera: TCamera,
454
+ changes: CameraChangeFlags,
455
+ ): Promise<IRuntimeFrameResult<TSpatial, TContentHandle, TGlyphHandle>> {
456
+ const operation = this.updateChain.then(async () => {
457
+ await this.start();
458
+ this.currentCameraChanges = changes;
459
+ if (this.spatialStale) this.refreshSpatialStates();
460
+ try {
461
+ return await this.performUpdate(camera);
462
+ } finally {
463
+ this.currentCameraChanges = CameraChangeFlags.None;
464
+ }
465
+ });
466
+ this.updateChain = operation.then(
467
+ () => undefined,
468
+ () => undefined,
469
+ );
470
+ return operation;
471
+ }
472
+
473
+ /** Asks for one more frame with the latest camera, when something the selection reads has changed. */
474
+ public requestFrame(): void {
475
+ this.markDirty();
476
+ }
477
+
478
+ /** Stores the latest immutable camera frame without starting a traversal. */
479
+ public onCameraChanged(camera: TCamera, changes: CameraChangeFlags = CameraChangeFlags.All): void {
480
+ this.pendingCamera = camera;
481
+ this.pendingCameraChanges |= changes;
482
+ this.cameraDirty = true;
483
+ }
484
+
485
+ /** Consumes the latest camera snapshot and runs at most one serialized pipeline frame. */
486
+ public processFrame(): Promise<IRuntimeFrameResult<TSpatial, TContentHandle, TGlyphHandle>> {
487
+ const camera = this.pendingCamera ?? this.lastCamera;
488
+ if (camera === undefined) throw new Error("A camera frame must be provided before processing the runtime pipeline.");
489
+ const changes = this.pendingCameraChanges;
490
+ this.pendingCamera = undefined;
491
+ this.pendingCameraChanges = CameraChangeFlags.None;
492
+ this.cameraDirty = false;
493
+ return this.enqueueUpdate(camera, changes);
494
+ }
495
+
496
+ public async whenIdle(): Promise<void> {
497
+ while (!this.disposed) {
498
+ await this.scheduler.whenIdle();
499
+ await this.updateChain;
500
+ if (this.scheduler.size > 0) continue;
501
+ const camera = this.lastCamera;
502
+ if (!this.refreshNeeded || camera === undefined) return;
503
+ await this.update(camera);
504
+ }
505
+ }
506
+
507
+ public async dispose(): Promise<void> {
508
+ if (this.disposed) return;
509
+ this.disposed = true;
510
+ this.cameraSubscription?.unsubscribe();
511
+ this.cameraSubscription = undefined;
512
+ this.unsubscribeVerticalScale?.();
513
+ this.lifecycleController.abort();
514
+ this.scheduler.dispose();
515
+ await this.updateChain;
516
+ const selected = [...this.nodes.values()].filter((node) => node.selected).sort((left, right) => right.depth - left.depth);
517
+ for (const node of selected) await this.deactivateNode(node);
518
+ for (const node of [...this.nodes.values()].sort((left, right) => right.depth - left.depth)) await this.disposeNodeContent(node);
519
+ this.refreshes.clear();
520
+ this.staleContents.clear();
521
+ this.provisionalContents.clear();
522
+ this.nodes.clear();
523
+ this.refiningNodes.clear();
524
+ this.coarseningSince.clear();
525
+ this.replacementFrontNodes.clear();
526
+ this.selectedAtFrameStart = [];
527
+ this.activeThisFrame.clear();
528
+ this.metadataStore.clear();
529
+ this.events.clear();
530
+ this.instrumentation.clear();
531
+ }
532
+
533
+ protected async performUpdate(camera: TCamera): Promise<IRuntimeFrameResult<TSpatial, TContentHandle, TGlyphHandle>> {
534
+ if (this.disposed) throw new Error("The runtime has been disposed.");
535
+ const startedAt = this.startTiming();
536
+ const root = this.rootNode;
537
+ if (!root) throw new Error("The root tileset is not initialized.");
538
+ this.lastCamera = camera;
539
+ // A frame consumes the state accumulated by completed asynchronous
540
+ // work. Loads that settle during this traversal set the flag again and
541
+ // are consumed by the next caller-driven frame.
542
+ this.refreshNeeded = false;
543
+ const currentFrame = ++this.frame;
544
+ this.recordFrameTime(currentFrame);
545
+ const beforeContext: IFrameHookContext<TCamera, TSpatial, TContentHandle, TGlyphHandle> = {
546
+ runtimeId: this.id,
547
+ frame: currentFrame,
548
+ camera,
549
+ };
550
+ await this.invokeHooks("beforeFrame", (hook) => hook.beforeFrame?.(beforeContext));
551
+ await this.applyRefreshes();
552
+
553
+ const desired = new Map<string, IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>();
554
+ const requested: IRuntimeContent<TContentHandle>[] = [];
555
+ const refiningAtFrameStart = new Set(this.refiningNodes);
556
+ this.nextCoarseningAt = undefined;
557
+ this.selectedAtFrameStart = [...this.nodes.values()].filter((node) => node.selected);
558
+ if (this.selectionStrategy === "base") {
559
+ this.baseReplacementBlocked = false;
560
+ this.replacementFrontNodes.clear();
561
+ this.activeThisFrame.clear();
562
+ for (const node of this.nodes.values()) {
563
+ node.visible = false;
564
+ node.active = false;
565
+ }
566
+ this.visitBase(root, camera, desired, requested);
567
+ if (this.baseReplacementBlocked) this.retainBaseCut(camera, desired, requested);
568
+ this.closeBaseQuadtreeCut(camera, desired, requested);
569
+ this.protectBaseCoverageAncestors(desired, requested);
570
+ // Hysteresis and public transition metrics follow the published cut, not rejected refinement attempts.
571
+ this.refiningNodes.clear();
572
+ for (const node of desired.values()) {
573
+ for (let parent = node.parent; parent; parent = parent.parent) this.refiningNodes.add(parent.id);
574
+ }
575
+ } else {
576
+ // The quadtree balance starts from the screen-space error selection of this frame and repeats the
577
+ // traversal until no further refinement is required, so that no frame presents an unbalanced cut.
578
+ // A transition that would still unbalance the cut, because the neighbours it needs are not ready, waits.
579
+ this.balanceRefinements = new Set(this.publishedBalanceRefinements);
580
+ this.balanceHolds.clear();
581
+ // The working set is that of every pass: a load that one pass requests and a later one does not reach, under
582
+ // a held refinement, goes on instead of being cancelled at the end of each frame and queued again.
583
+ this.replacementFrontNodes.clear();
584
+ this.activeThisFrame.clear();
585
+ for (let pass = 1; ; pass++) {
586
+ desired.clear();
587
+ requested.length = 0;
588
+ // Only the delays of the published pass may wake the runtime: an earlier pass may start one that it cancels.
589
+ this.nextCoarseningAt = undefined;
590
+ for (const node of this.nodes.values()) {
591
+ node.visible = false;
592
+ node.active = false;
593
+ }
594
+ this.visit(root, camera, desired, requested);
595
+ if (pass >= MAX_BALANCE_PASSES) break;
596
+ if (this.extendQuadtreeBalance(desired)) continue;
597
+ if (!this.holdUnbalancedRefinements(desired)) break;
598
+ }
599
+ this.updateVisibleTiles(desired);
600
+ this.publishedBalanceRefinements = this.quadtreeBalance
601
+ ? quadtreeBalanceRefinements(this.visibleQuadtreeLocations(desired), this.quadtreeBalance.maxLevelDifference)
602
+ : new Set();
603
+ }
604
+ await this.deactivatePipelineTilesOutsideWorkingSet();
605
+
606
+ const entering = [...desired.values()].filter((node) => !node.selected).sort((left, right) => left.depth - right.depth);
607
+ const staying = [...desired.values()].filter((node) => node.selected);
608
+ for (const node of [...entering, ...staying]) await this.activateNode(node);
609
+
610
+ const leaving = [...this.nodes.values()]
611
+ .filter((node) => node.selected && !desired.has(node.id))
612
+ .sort((left, right) => right.depth - left.depth);
613
+ for (const node of leaving) await this.deactivateNode(node);
614
+ this.recordCutChanges(refiningAtFrameStart, entering.length, leaving.length);
615
+ await this.sweepCache();
616
+
617
+ const unbalanced = this.quadtreeBalance
618
+ ? this.findImbalances(desired).map(({ fine, coarseLod }) => ({ tile: fine, coarseLod }))
619
+ : [];
620
+ this.unbalancedCount = unbalanced.length;
621
+ const result: IRuntimeFrameResult<TSpatial, TContentHandle, TGlyphHandle> = {
622
+ frame: currentFrame,
623
+ selected: [...desired.values()],
624
+ requested,
625
+ pendingLoads: this.scheduler.size,
626
+ unbalanced,
627
+ };
628
+ if (unbalanced.length > 0) this.events.emit({ type: "quadtree-imbalance", frame: currentFrame, imbalances: unbalanced });
629
+ this.events.emit({ type: "frame", result });
630
+ this.recordMetric({
631
+ name: "frame",
632
+ value: 1,
633
+ unit: "count",
634
+ tags: { runtime: this.id, requested: requested.length, pending: this.scheduler.size },
635
+ });
636
+ this.recordMetric({
637
+ name: "frame.selected",
638
+ value: desired.size,
639
+ unit: "count",
640
+ tags: { runtime: this.id },
641
+ });
642
+ const afterContext: IFrameHookContext<TCamera, TSpatial, TContentHandle, TGlyphHandle> = {
643
+ ...beforeContext,
644
+ result,
645
+ };
646
+ await this.invokeHooks("afterFrame", (hook) => hook.afterFrame?.(afterContext));
647
+ this.recordDuration("frame.duration", startedAt, { runtime: this.id });
648
+ this.instrumentation.publish();
649
+ return result;
650
+ }
651
+
652
+ /** Visible traversal shared by explicit tiles, implicit tiles and both rendering backends. */
653
+ private visitBase(
654
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
655
+ camera: TCamera,
656
+ desired: Map<string, IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>,
657
+ requested: IRuntimeContent<TContentHandle>[],
658
+ ): void {
659
+ if (this.hasSelectedReplacementAncestor(node, desired)) return;
660
+ node.visible = this.adapter.spatial.isVisible(node.spatial, camera);
661
+ node.active = node.visible;
662
+ if (!node.visible) {
663
+ this.preloadBasePeriphery(node, camera, requested);
664
+ return;
665
+ }
666
+ this.touchBaseTile(node, camera);
667
+ const potential = node.contents.some(
668
+ (content) => content.kind === TileContentKind.Unknown || content.kind === TileContentKind.Renderable,
669
+ );
670
+ if (potential) {
671
+ // A ready ancestor remains available while its descendants render, including under tight cache budgets.
672
+ this.replacementFrontNodes.add(node.id);
673
+ this.requestNodeContents(node, node.screenSpaceError, requested);
674
+ }
675
+ if (node.implicit && node.implicit.subtree.status !== TileReadinessState.Ready) {
676
+ this.requestImplicitSubtree(node, node.screenSpaceError);
677
+ this.selectBaseCoverage(node, camera, desired, requested);
678
+ return;
679
+ }
680
+ const wasRefining = this.refiningNodes.has(node.id);
681
+ const effective = this.refinementThreshold(node, wasRefining);
682
+ const required =
683
+ (!potential && !this.obeysGeometricError(node)) || node.screenSpaceError > effective || this.isBalanceRefinementRequired(node);
684
+ const delayed = this.isCoarseningDelayed(node, wasRefining, required);
685
+ if (required || delayed) this.materializeImplicitChildren(node);
686
+ const refining = (required || delayed) && node.children.length > 0;
687
+ this.setRefinementState(node, refining);
688
+ if (!refining) {
689
+ // A known empty leaf, or a known empty tile under its threshold, is an empty part of the replacement, not missing coverage.
690
+ if (!potential) return;
691
+ this.selectBaseCoverage(node, camera, desired, requested);
692
+ this.requestRefresh(node, node.screenSpaceError, true);
693
+ return;
694
+ }
695
+ this.cancelProvisionalRefresh(node);
696
+ if (node.refinementMode === TileRefinementMode.Add) {
697
+ if (this.isNodePresentationReady(node)) this.selectBaseTile(node, desired, requested);
698
+ for (const child of node.children) this.visitBase(child, camera, desired, requested);
699
+ return;
700
+ }
701
+ // Every available child's first content front belongs to the same replacement transaction. Hidden siblings
702
+ // are prepared once, without recursively refining their hierarchy by SSE or by a peripheral camera.
703
+ const ready = node.children
704
+ .map((child) => this.collectBaseReplacementFront(child, camera, requested, node.screenSpaceError))
705
+ .every(Boolean);
706
+ if (!ready) {
707
+ this.selectBaseCoverage(node, camera, desired, requested, true);
708
+ return;
709
+ }
710
+ for (const child of node.children) this.visitBase(child, camera, desired, requested);
711
+ }
712
+
713
+ /**
714
+ * Loads a tile of the periphery of the view, and its descendants down to the threshold, without selecting them: a
715
+ * place that enters the view then finds its tile ready.
716
+ */
717
+ private preloadBasePeriphery(
718
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
719
+ camera: TCamera,
720
+ requested: IRuntimeContent<TContentHandle>[],
721
+ ): void {
722
+ if (this.adapter.spatial.isInPeriphery?.(node.spatial, camera) !== true) return;
723
+ node.active = true;
724
+ this.touchBaseTile(node, camera);
725
+ // Below every load of the view, whose priorities are errors of zero or more, and in the order of the error.
726
+ const priority = -1 / (1 + node.screenSpaceError);
727
+ const potential = node.contents.some(
728
+ (content) => content.kind === TileContentKind.Unknown || content.kind === TileContentKind.Renderable,
729
+ );
730
+ if (potential) this.requestNodeContents(node, priority, requested);
731
+ if (node.implicit && node.implicit.subtree.status !== TileReadinessState.Ready) {
732
+ this.requestImplicitSubtree(node, priority);
733
+ return;
734
+ }
735
+ const threshold = this.maxScreenSpaceErrorForDepth?.(node.depth, this.maxScreenSpaceError) ?? this.maxScreenSpaceError;
736
+ if (
737
+ (potential || this.obeysGeometricError(node)) &&
738
+ node.screenSpaceError <= threshold * Math.max(1, this.refinementThresholdScale?.() ?? 1)
739
+ )
740
+ return;
741
+ this.materializeImplicitChildren(node);
742
+ for (const child of node.children) this.preloadBasePeriphery(child, camera, requested);
743
+ }
744
+
745
+ private touchBaseTile(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>, camera: TCamera): void {
746
+ node.lastTouchedFrame = this.frame;
747
+ if (node.implicit) node.implicit.subtree.lastTouchedFrame = this.frame;
748
+ node.screenSpaceError = this.adapter.spatial.screenSpaceError({
749
+ camera,
750
+ spatial: node.spatial,
751
+ tile: node.source,
752
+ depth: node.depth,
753
+ });
754
+ }
755
+
756
+ private collectBaseReplacementFront(
757
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
758
+ camera: TCamera,
759
+ requested: IRuntimeContent<TContentHandle>[],
760
+ priorityFloor: number,
761
+ ): boolean {
762
+ node.visible = this.adapter.spatial.isVisible(node.spatial, camera);
763
+ node.active = node.visible;
764
+ this.touchBaseTile(node, camera);
765
+ const priority = Math.max(node.screenSpaceError, priorityFloor);
766
+ if (node.implicit && node.implicit.subtree.status !== TileReadinessState.Ready) {
767
+ this.requestImplicitSubtree(node, priority);
768
+ return false;
769
+ }
770
+ const potential = node.contents.some(
771
+ (content) => content.kind === TileContentKind.Unknown || content.kind === TileContentKind.Renderable,
772
+ );
773
+ if (potential) {
774
+ this.replacementFrontNodes.add(node.id);
775
+ this.requestNodeContents(node, priority, requested);
776
+ return this.isNodePresentationReady(node);
777
+ }
778
+ // A known empty tile that its error does not refine presents nothing: it completes the front as it is.
779
+ if (this.isSatisfiedEmpty(node)) return true;
780
+ // Empty structural nodes are not content: resolve their first available content front.
781
+ this.materializeImplicitChildren(node);
782
+ return node.children.map((child) => this.collectBaseReplacementFront(child, camera, requested, priority)).every(Boolean);
783
+ }
784
+
785
+ private hasSelectedReplacementAncestor(
786
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
787
+ desired: ReadonlyMap<string, IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>,
788
+ ): boolean {
789
+ for (let parent = node.parent; parent; parent = parent.parent) {
790
+ if (parent.refinementMode === TileRefinementMode.Add) return false;
791
+ if (desired.has(parent.id)) return true;
792
+ }
793
+ return false;
794
+ }
795
+
796
+ private selectBaseTile(
797
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
798
+ desired: Map<string, IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>,
799
+ requested: IRuntimeContent<TContentHandle>[],
800
+ ): void {
801
+ if (this.hasSelectedReplacementAncestor(node, desired)) return;
802
+ if (node.refinementMode === TileRefinementMode.Replace) {
803
+ for (const tile of desired.values()) if (this.isDescendantOf(tile, node)) desired.delete(tile.id);
804
+ }
805
+ this.selectNode(node, desired, requested);
806
+ }
807
+
808
+ private selectBaseCoverage(
809
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
810
+ camera: TCamera,
811
+ desired: Map<string, IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>,
812
+ requested: IRuntimeContent<TContentHandle>[],
813
+ retainRefinedCoverage = false,
814
+ ): void {
815
+ const ready = this.isNodePresentationReady(node);
816
+ if (this.stableReplacementCut && (retainRefinedCoverage || !ready) && this.selectedDescendantsCover(node, camera)) {
817
+ for (const child of this.selectedAtFrameStart) {
818
+ if (
819
+ !this.isDescendantOf(child, node) ||
820
+ !this.adapter.spatial.isVisible(child.spatial, camera) ||
821
+ !this.isNodePresentationReady(child)
822
+ )
823
+ continue;
824
+ child.visible = true;
825
+ child.active = true;
826
+ this.touchBaseTile(child, camera);
827
+ this.selectBaseTile(child, desired, requested);
828
+ }
829
+ return;
830
+ }
831
+ if (
832
+ retainRefinedCoverage &&
833
+ this.selectedAtFrameStart.some(
834
+ (child) =>
835
+ this.isDescendantOf(child, node) &&
836
+ this.adapter.spatial.isVisible(child.spatial, camera) &&
837
+ this.isNodePresentationReady(child),
838
+ )
839
+ ) {
840
+ // A newly visible cold branch cannot replace already published detail through its shared ancestor.
841
+ this.baseReplacementBlocked = true;
842
+ return;
843
+ }
844
+ if (ready) {
845
+ this.selectBaseTile(node, desired, requested);
846
+ return;
847
+ }
848
+ // A known empty tile that obeys its error covers its place with nothing, as before it refined: its parent stays replaced.
849
+ if (this.obeysGeometricError(node)) return;
850
+ for (let parent = node.parent; parent; parent = parent.parent) {
851
+ if (parent.refinementMode === TileRefinementMode.Add) break;
852
+ if (!this.isNodePresentationReady(parent)) continue;
853
+ this.selectBaseTile(parent, desired, requested);
854
+ return;
855
+ }
856
+ // No ready coverage exists during bootstrap. Keep requesting it without publishing an unready tile.
857
+ }
858
+
859
+ private closeBaseQuadtreeCut(
860
+ camera: TCamera,
861
+ desired: Map<string, IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>,
862
+ requested: IRuntimeContent<TContentHandle>[],
863
+ ): void {
864
+ if (!this.quadtreeBalance) return;
865
+ const displayed = new Set(this.selectedAtFrameStart);
866
+ // Keep the support requested by the desired detail and every ready split performed by this local closure.
867
+ const support: Array<IQuadtreeCutTile<IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>> = [];
868
+ for (;;) {
869
+ const entries = this.baseQuadtreeEntries(desired);
870
+ support.push(...entries);
871
+ const involved = new Set<IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>();
872
+ const balanced = this.refineBaseQuadtreeCut(camera, entries, support, requested, (tiles) => {
873
+ for (const { value } of tiles) involved.add(value);
874
+ });
875
+ if (balanced) {
876
+ const kept = new Set(balanced.map(({ value }) => value));
877
+ for (const { value } of entries) if (!kept.has(value)) desired.delete(value.id);
878
+ for (const { value } of balanced) this.selectBaseTile(value, desired, requested);
879
+ break;
880
+ }
881
+ // A ready tile is displayable only within one level of its neighbours. A new tile that is not keeps what
882
+ // was displayed in its place, and the rest of the list goes on.
883
+ const undisplayable = [...involved].filter((node) => !displayed.has(node));
884
+ if (undisplayable.length === 0) {
885
+ // Only displayed tiles are involved: nothing local can wait, the previous list stays.
886
+ this.retainBaseCut(camera, desired, requested);
887
+ support.push(...this.baseQuadtreeEntries(desired));
888
+ break;
889
+ }
890
+ for (const node of undisplayable) this.keepDisplayedInPlaceOf(node, displayed, camera, desired, requested);
891
+ }
892
+ const requirements = quadtreeBalanceRefinements(
893
+ support.map(({ location }) => location),
894
+ this.quadtreeBalance.maxLevelDifference,
895
+ );
896
+ if (requirements.size !== this.balanceRefinements.size || [...requirements].some((key) => !this.balanceRefinements.has(key)))
897
+ this.requestFrame();
898
+ this.balanceRefinements = requirements;
899
+ }
900
+
901
+ private baseQuadtreeEntries(
902
+ desired: ReadonlyMap<string, IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>,
903
+ ): Array<IQuadtreeCutTile<IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>> {
904
+ return [...desired.values()].flatMap((value) => {
905
+ const location = value.refinementMode === TileRefinementMode.Replace ? this.quadtreeLocation(value) : undefined;
906
+ return location ? [{ location, value }] : [];
907
+ });
908
+ }
909
+
910
+ private refineBaseQuadtreeCut(
911
+ camera: TCamera,
912
+ entries: Array<IQuadtreeCutTile<IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>>,
913
+ support: Array<IQuadtreeCutTile<IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>>,
914
+ requested: IRuntimeContent<TContentHandle>[],
915
+ blocked: (involved: readonly IQuadtreeCutTile<IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>[]) => void,
916
+ ): Array<IQuadtreeCutTile<IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>> | undefined {
917
+ return refineQuadtreeCut(
918
+ entries,
919
+ (coarse) => {
920
+ this.materializeImplicitChildren(coarse.value);
921
+ if (coarse.value.children.length === 0) return undefined;
922
+ const ready = coarse.value.children
923
+ .map((child) => this.collectBaseReplacementFront(child, camera, requested, BALANCE_LOAD_PRIORITY))
924
+ .every(Boolean);
925
+ if (!ready) return undefined;
926
+ const front: typeof entries = [];
927
+ const collect = (node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): boolean => {
928
+ if (!node.visible) return true;
929
+ if (this.isNodePresentationReady(node)) {
930
+ const location = node.refinementMode === TileRefinementMode.Replace ? this.quadtreeLocation(node) : undefined;
931
+ if (!location) return false;
932
+ front.push({ location, value: node });
933
+ return true;
934
+ }
935
+ return node.children.map(collect).every(Boolean);
936
+ };
937
+ if (!coarse.value.children.map(collect).every(Boolean)) return undefined;
938
+ support.push(...front);
939
+ return front;
940
+ },
941
+ blocked,
942
+ this.quadtreeBalance?.maxLevelDifference,
943
+ );
944
+ }
945
+
946
+ /**
947
+ * Gives back the place of a new tile to what was displayed there: the displayed ancestor that it refines, or the
948
+ * displayed tiles under it that it would coarsen. A place that displayed nothing stays empty until it is ready.
949
+ */
950
+ private keepDisplayedInPlaceOf(
951
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
952
+ displayed: ReadonlySet<IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>,
953
+ camera: TCamera,
954
+ desired: Map<string, IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>,
955
+ requested: IRuntimeContent<TContentHandle>[],
956
+ ): void {
957
+ let place = node;
958
+ for (let parent = node.parent; parent; parent = parent.parent) {
959
+ if (!displayed.has(parent)) continue;
960
+ place = parent;
961
+ break;
962
+ }
963
+ const within = (tile: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): boolean =>
964
+ tile === place || this.isDescendantOf(tile, place);
965
+ for (const tile of [...desired.values()]) if (within(tile)) desired.delete(tile.id);
966
+ for (const tile of displayed) {
967
+ if (!within(tile) || !this.isNodePresentationReady(tile)) continue;
968
+ tile.visible = this.adapter.spatial.isVisible(tile.spatial, camera);
969
+ tile.active = tile.visible;
970
+ this.touchBaseTile(tile, camera);
971
+ this.selectNode(tile, desired, requested);
972
+ }
973
+ }
974
+
975
+ private retainBaseCut(
976
+ camera: TCamera,
977
+ desired: Map<string, IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>,
978
+ requested: IRuntimeContent<TContentHandle>[],
979
+ ): void {
980
+ desired.clear();
981
+ for (const node of this.selectedAtFrameStart) {
982
+ if (!this.isNodePresentationReady(node)) continue;
983
+ node.visible = this.adapter.spatial.isVisible(node.spatial, camera);
984
+ node.active = node.visible;
985
+ this.touchBaseTile(node, camera);
986
+ this.selectNode(node, desired, requested);
987
+ }
988
+ }
989
+
990
+ private protectBaseCoverageAncestors(
991
+ desired: ReadonlyMap<string, IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>,
992
+ requested: IRuntimeContent<TContentHandle>[],
993
+ ): void {
994
+ const seen = new Set<string>();
995
+ for (const tile of desired.values()) {
996
+ for (let parent = tile.parent; parent && !seen.has(parent.id); parent = parent.parent) {
997
+ seen.add(parent.id);
998
+ this.replacementFrontNodes.add(parent.id);
999
+ parent.lastTouchedFrame = this.frame;
1000
+ if (parent.implicit) parent.implicit.subtree.lastTouchedFrame = this.frame;
1001
+ this.requestNodeContents(parent, this.loadPriority(parent), requested);
1002
+ }
1003
+ }
1004
+ }
1005
+
1006
+ protected visit(
1007
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
1008
+ camera: TCamera,
1009
+ desired: Map<string, IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>,
1010
+ requested: IRuntimeContent<TContentHandle>[],
1011
+ ): void {
1012
+ if (!this.updateActivity(node, camera)) return;
1013
+ node.lastTouchedFrame = this.frame;
1014
+ if (node.implicit) node.implicit.subtree.lastTouchedFrame = this.frame;
1015
+ node.screenSpaceError = this.adapter.spatial.screenSpaceError({
1016
+ camera,
1017
+ spatial: node.spatial,
1018
+ tile: node.source,
1019
+ depth: node.depth,
1020
+ });
1021
+ if (node.implicit && node.implicit.subtree.status !== TileReadinessState.Ready) {
1022
+ this.requestImplicitSubtree(node, node.screenSpaceError);
1023
+ this.selectNode(node, desired, requested);
1024
+ return;
1025
+ }
1026
+ const hasPotentialPresentation = node.contents.some(
1027
+ (content) => content.kind === TileContentKind.Unknown || content.kind === TileContentKind.Renderable,
1028
+ );
1029
+ const wasRefining = this.refiningNodes.has(node.id);
1030
+ const effectiveThreshold = this.refinementThreshold(node, wasRefining);
1031
+ const balanceRequested = this.isBalanceRefinementRequired(node);
1032
+ const held = hasPotentialPresentation && this.balanceHolds.has(node.id);
1033
+ const required =
1034
+ node.screenSpaceError > effectiveThreshold ||
1035
+ (!hasPotentialPresentation && !this.obeysGeometricError(node)) ||
1036
+ balanceRequested;
1037
+ // Always evaluated: a required refinement also starts the delay again.
1038
+ const coarseningDelayed = this.isCoarseningDelayed(node, wasRefining, required);
1039
+ const refinementRequested = !held && (required || coarseningDelayed);
1040
+ if (refinementRequested) this.materializeImplicitChildren(node);
1041
+ // Outside the view, a tile refines only into children that stay active, and merges back otherwise.
1042
+ const wantsRefinement =
1043
+ refinementRequested &&
1044
+ node.children.length > 0 &&
1045
+ (node.visible || node.children.map((child) => this.updateActivity(child, camera)).some(Boolean));
1046
+ this.setRefinementState(node, wantsRefinement);
1047
+
1048
+ if (!wantsRefinement) {
1049
+ // A coarse tile may have been evicted while its descendants were
1050
+ // selected. Never remove those descendants before the parent is
1051
+ // renderable, otherwise zooming out exposes the clear colour for
1052
+ // one or more load cycles. Correctness must not depend on cache.
1053
+ if (hasPotentialPresentation && !this.isNodePresentationReady(node)) {
1054
+ this.requestNodeContents(node, this.loadPriority(node), requested);
1055
+ if (this.stableReplacementCut && this.retainVisibleSelectedDescendants(node, camera, desired)) return;
1056
+ // Only what the camera sees may bring a coarser tile into the view.
1057
+ if (!node.visible) return;
1058
+ if (this.selectReadyCoverageAncestor(node.parent, desired, requested)) return;
1059
+ }
1060
+ this.selectNode(node, desired, requested);
1061
+ this.requestRefresh(node, this.loadPriority(node), true);
1062
+ return;
1063
+ }
1064
+ this.cancelProvisionalRefresh(node);
1065
+
1066
+ if (node.refinementMode === TileRefinementMode.Add) {
1067
+ this.selectNode(node, desired, requested);
1068
+ for (const child of node.children) this.visit(child, camera, desired, requested);
1069
+ return;
1070
+ }
1071
+
1072
+ // The balance waits for these children: load them before tiles chosen by screen-space error alone.
1073
+ const priorityFloor = balanceRequested ? BALANCE_LOAD_PRIORITY : 0;
1074
+ // Every child is collected, so that siblings load together rather than one after another.
1075
+ const replacementReady = node.children
1076
+ .map((child) => this.collectReplacementFront(child, camera, requested, priorityFloor))
1077
+ .every(Boolean);
1078
+ if (replacementReady) {
1079
+ for (const child of node.children) this.visit(child, camera, desired, requested);
1080
+ } else {
1081
+ // A refinement required by the quadtree balance keeps the finer
1082
+ // descendants already displayed: falling back to a coarser ready
1083
+ // tile would display it next to a tile two or more levels finer.
1084
+ // Unless they leave part of the tile empty, which is worse than an edge waiting for its balance.
1085
+ if (
1086
+ balanceRequested &&
1087
+ this.stableReplacementCut &&
1088
+ this.selectedDescendantsCover(node, camera) &&
1089
+ this.retainVisibleSelectedDescendants(node, camera, desired)
1090
+ )
1091
+ return;
1092
+ // A ready ancestor provides complete coverage for every visible
1093
+ // child branch. Previously selected descendants are retained only
1094
+ // when no such ancestor is currently available.
1095
+ // A known empty tile that obeys its error covers its place with nothing, as before it refined: its parent stays replaced.
1096
+ if (!this.obeysGeometricError(node) && this.selectReadyCoverageAncestor(node, desired, requested)) return;
1097
+ if (this.stableReplacementCut && this.retainVisibleSelectedDescendants(node, camera, desired)) return;
1098
+ this.selectNode(node, desired, requested);
1099
+ }
1100
+ }
1101
+
1102
+ protected collectReplacementFront(
1103
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
1104
+ camera: TCamera,
1105
+ requested: IRuntimeContent<TContentHandle>[],
1106
+ priorityFloor = 0,
1107
+ ): boolean {
1108
+ this.updateActivity(node, camera);
1109
+ // A child in the margin of the view is drawn as soon as the camera turns, before the next frame publishes its
1110
+ // cut: the replacement waits for it as for a visible child, otherwise its place stays empty in the cut.
1111
+ const inMargin = !node.visible && this.adapter.spatial.isInPeriphery?.(node.spatial, camera) === true;
1112
+ if (!node.visible && !inMargin) {
1113
+ if (this.preloadSiblings || node.active) this.preloadSibling(node, camera, requested);
1114
+ return true;
1115
+ }
1116
+ node.lastTouchedFrame = this.frame;
1117
+ if (node.implicit) node.implicit.subtree.lastTouchedFrame = this.frame;
1118
+ node.screenSpaceError = this.adapter.spatial.screenSpaceError({
1119
+ camera,
1120
+ spatial: node.spatial,
1121
+ tile: node.source,
1122
+ depth: node.depth,
1123
+ });
1124
+ const priority = Math.max(node.screenSpaceError, priorityFloor);
1125
+ if (node.implicit && node.implicit.subtree.status !== TileReadinessState.Ready) {
1126
+ this.requestImplicitSubtree(node, priority);
1127
+ return false;
1128
+ }
1129
+ const potential = node.contents.filter(
1130
+ (content) => content.kind === TileContentKind.Unknown || content.kind === TileContentKind.Renderable,
1131
+ );
1132
+ if (potential.length > 0) {
1133
+ for (const content of potential) content.lastTouchedFrame = this.frame;
1134
+ this.replacementFrontNodes.add(node.id);
1135
+ this.requestNodeContents(node, priority, requested);
1136
+ return potential.every((content) => content.kind === TileContentKind.Renderable && content.status === TileReadinessState.Ready);
1137
+ }
1138
+ // A known empty tile that its error does not refine presents nothing: it completes the front as it is.
1139
+ if (this.isSatisfiedEmpty(node)) return true;
1140
+ // Only a tile without content needs its children for the front: others would create a level nothing asked for.
1141
+ this.materializeImplicitChildren(node);
1142
+ if (node.children.length === 0) return true;
1143
+ return node.children.map((child) => this.collectReplacementFront(child, camera, requested, priorityFloor)).every(Boolean);
1144
+ }
1145
+
1146
+ /**
1147
+ * Loads a child outside the view in the background, so that it is ready when the camera turns towards it. It
1148
+ * never blocks the replacement of its parent, and its descendants are not loaded.
1149
+ */
1150
+ private preloadSibling(
1151
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
1152
+ camera: TCamera,
1153
+ requested: IRuntimeContent<TContentHandle>[],
1154
+ ): void {
1155
+ node.lastTouchedFrame = this.frame;
1156
+ if (node.implicit) node.implicit.subtree.lastTouchedFrame = this.frame;
1157
+ const screenSpaceError = this.adapter.spatial.screenSpaceError({
1158
+ camera,
1159
+ spatial: node.spatial,
1160
+ tile: node.source,
1161
+ depth: node.depth,
1162
+ });
1163
+ const priority = screenSpaceError * PRELOAD_PRIORITY_SCALE;
1164
+ if (node.implicit && node.implicit.subtree.status !== TileReadinessState.Ready) {
1165
+ this.requestImplicitSubtree(node, priority);
1166
+ return;
1167
+ }
1168
+ const potential = node.contents.filter(
1169
+ (content) => content.kind === TileContentKind.Unknown || content.kind === TileContentKind.Renderable,
1170
+ );
1171
+ if (potential.length === 0) return;
1172
+ for (const content of potential) content.lastTouchedFrame = this.frame;
1173
+ this.requestNodeContents(node, priority, requested);
1174
+ }
1175
+
1176
+ /** Screen-space error above which a tile refines: lowered by the hysteresis once refined, scaled by the factor before. */
1177
+ private refinementThreshold(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>, wasRefining: boolean): number {
1178
+ const threshold = this.maxScreenSpaceErrorForDepth?.(node.depth, this.maxScreenSpaceError) ?? this.maxScreenSpaceError;
1179
+ return wasRefining
1180
+ ? threshold * (1 - this.refinementHysteresisRatio)
1181
+ : threshold * Math.max(1, this.refinementThresholdScale?.() ?? 1);
1182
+ }
1183
+
1184
+ /**
1185
+ * Whether a tile is explicit and every content it has, if any, is known empty and ready. A tile with an external
1186
+ * tileset, with a content not loaded yet, or an implicit tile is not.
1187
+ */
1188
+ private isKnownEmpty(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): boolean {
1189
+ return (
1190
+ !node.implicit &&
1191
+ node.contents.every((content) => content.kind === TileContentKind.Empty && content.status === TileReadinessState.Ready)
1192
+ );
1193
+ }
1194
+
1195
+ /** Whether a tile with nothing to present refines by its screen-space error, see `emptyTileRefinement`. */
1196
+ private obeysGeometricError(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): boolean {
1197
+ return this.emptyTileRefinement === "geometric-error" && this.isKnownEmpty(node);
1198
+ }
1199
+
1200
+ /** Whether a known empty tile that obeys its error stays under its threshold, with its error of the current frame. */
1201
+ private isSatisfiedEmpty(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): boolean {
1202
+ return this.obeysGeometricError(node) && node.screenSpaceError <= this.refinementThreshold(node, this.refiningNodes.has(node.id));
1203
+ }
1204
+
1205
+ /** Whether a refined tile that no longer requires its refinement still waits before coarsening. */
1206
+ private isCoarseningDelayed(
1207
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
1208
+ wasRefining: boolean,
1209
+ required: boolean,
1210
+ ): boolean {
1211
+ if (required || !wasRefining || this.coarseningDelayMilliseconds === 0) {
1212
+ this.coarseningSince.delete(node.id);
1213
+ return false;
1214
+ }
1215
+ const now = this.clock();
1216
+ const known = this.coarseningSince.get(node.id);
1217
+ // A tile the last frames did not see, for example outside the view, starts again.
1218
+ const since = known && known.frame >= this.frame - 1 ? known.since : now;
1219
+ const expires = since + this.coarseningDelayMilliseconds;
1220
+ // An expired delay stays recorded: a cold parent keeps the finer cut displayed without starting a new delay.
1221
+ this.coarseningSince.set(node.id, { since, frame: this.frame });
1222
+ if (now >= expires) return false;
1223
+ this.nextCoarseningAt = Math.min(this.nextCoarseningAt ?? expires, expires);
1224
+ return true;
1225
+ }
1226
+
1227
+ /** Location of an implicit quadtree tile for balancing, or `undefined` when balancing does not apply. */
1228
+ private quadtreeLocation(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): IQuadtreeTileLocation | undefined {
1229
+ const implicit = node.implicit;
1230
+ if (!this.quadtreeBalance || !implicit || implicit.context.implicitTiling.subdivisionScheme !== "QUADTREE") return undefined;
1231
+ const { context, coordinates } = implicit;
1232
+ const address = this.implicitResolver(context)?.addressOf?.({
1233
+ documentUri: node.document.uri,
1234
+ rootTile: context.rootTile,
1235
+ implicitTiling: context.implicitTiling,
1236
+ coordinates,
1237
+ });
1238
+ if (address) {
1239
+ const { wrapX = false, topology } = this.quadtreeBalance;
1240
+ return { namespace: "", address, wrapX, ...(topology ? { topology } : {}) };
1241
+ }
1242
+ // Without a shared pyramid, each implicit tileset is balanced on its own coordinates.
1243
+ return { namespace: `${context.id}:`, address: { lod: coordinates.level, x: coordinates.x, y: coordinates.y }, wrapX: false };
1244
+ }
1245
+
1246
+ private isBalanceRefinementRequired(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): boolean {
1247
+ if (this.balanceRefinements.size === 0) return false;
1248
+ const location = this.quadtreeLocation(node);
1249
+ return location !== undefined && this.balanceRefinements.has(quadtreeTileKey(location.namespace, location.address));
1250
+ }
1251
+
1252
+ /**
1253
+ * Adds the refinements that balance a selection. Refinements only
1254
+ * accumulate within a frame, so repeating the traversal converges: each
1255
+ * pass can only make the cut finer, and a refinement that unbalances
1256
+ * further neighbours is resolved by the next pass.
1257
+ *
1258
+ * @returns Whether a refinement was added, which requires another pass.
1259
+ */
1260
+ private extendQuadtreeBalance(desired: ReadonlyMap<string, IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>): boolean {
1261
+ if (!this.quadtreeBalance) return false;
1262
+ let added = false;
1263
+ for (const key of quadtreeBalanceRefinements(this.visibleQuadtreeLocations(desired), this.quadtreeBalance.maxLevelDifference)) {
1264
+ if (this.balanceRefinements.has(key)) continue;
1265
+ this.balanceRefinements.add(key);
1266
+ added = true;
1267
+ }
1268
+ return added;
1269
+ }
1270
+
1271
+ /** Visible selected quadtree tiles: a tile outside the view, even active, neither requires nor holds back what the camera sees. */
1272
+ private visibleQuadtreeLocations(
1273
+ desired: ReadonlyMap<string, IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>,
1274
+ ): IQuadtreeTileLocation[] {
1275
+ const locations: IQuadtreeTileLocation[] = [];
1276
+ for (const node of desired.values()) {
1277
+ if (!node.visible) continue;
1278
+ const location = this.quadtreeLocation(node);
1279
+ if (location) locations.push(location);
1280
+ }
1281
+ return locations;
1282
+ }
1283
+
1284
+ /** Visible selected quadtree tiles next to a visible selected tile coarser by more than `maxLevelDifference` levels. */
1285
+ private findImbalances(
1286
+ desired: ReadonlyMap<string, IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>,
1287
+ ): IQuadtreeImbalance<IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>[] {
1288
+ const displayed: Array<{ location: IQuadtreeTileLocation; value: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle> }> = [];
1289
+ for (const node of desired.values()) {
1290
+ if (!node.visible) continue;
1291
+ const location = this.quadtreeLocation(node);
1292
+ if (location) displayed.push({ location, value: node });
1293
+ }
1294
+ return quadtreeImbalances(displayed, this.quadtreeBalance?.maxLevelDifference);
1295
+ }
1296
+
1297
+ /**
1298
+ * Holds the refinement that brought a tile next to a neighbour coarser by
1299
+ * more than `maxLevelDifference` levels, when that neighbour cannot refine
1300
+ * yet. An ancestor of the fine tile stays displayed instead: the finest one
1301
+ * within `maxLevelDifference` levels of the neighbour that is ready. The
1302
+ * refinement resumes once the neighbour's children load.
1303
+ *
1304
+ * Only new refinements are held. A refinement already displayed at the
1305
+ * start of the frame is kept, because coarsening it would flicker: the
1306
+ * neighbour typically comes into view while the camera turns, and its
1307
+ * children load first since the balance requires them. The edge stays
1308
+ * reported as unbalanced meanwhile.
1309
+ *
1310
+ * @returns Whether a refinement was held, which requires another pass.
1311
+ */
1312
+ private holdUnbalancedRefinements(desired: ReadonlyMap<string, IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>): boolean {
1313
+ if (!this.quadtreeBalance) return false;
1314
+ let held = false;
1315
+ // Ancestors of the tiles displayed at the start of the frame: their refinement is already shown.
1316
+ const refinedAtFrameStart = new Set<string>();
1317
+ for (const node of this.selectedAtFrameStart) {
1318
+ for (let ancestor = node.parent; ancestor && !refinedAtFrameStart.has(ancestor.id); ancestor = ancestor.parent)
1319
+ refinedAtFrameStart.add(ancestor.id);
1320
+ }
1321
+ for (const { fine, coarseLod } of this.findImbalances(desired)) {
1322
+ for (let ancestor = fine.parent; ancestor; ancestor = ancestor.parent) {
1323
+ const lod = this.quadtreeLocation(ancestor)?.address.lod;
1324
+ if (lod === undefined || lod < coarseLod) break;
1325
+ if (lod > coarseLod + this.quadtreeBalance.maxLevelDifference || !this.isNodePresentationReady(ancestor)) continue;
1326
+ if (refinedAtFrameStart.has(ancestor.id)) break;
1327
+ if (!this.balanceHolds.has(ancestor.id)) {
1328
+ this.balanceHolds.add(ancestor.id);
1329
+ held = true;
1330
+ }
1331
+ break;
1332
+ }
1333
+ }
1334
+ return held;
1335
+ }
1336
+
1337
+ private isNodePresentationReady(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): boolean {
1338
+ const potential = node.contents.filter(
1339
+ (content) => content.kind === TileContentKind.Unknown || content.kind === TileContentKind.Renderable,
1340
+ );
1341
+ return (
1342
+ potential.length > 0 &&
1343
+ potential.every(
1344
+ (content) =>
1345
+ content.kind === TileContentKind.Renderable &&
1346
+ content.status === TileReadinessState.Ready &&
1347
+ content.handle !== undefined,
1348
+ )
1349
+ );
1350
+ }
1351
+
1352
+ private selectReadyCoverageAncestor(
1353
+ start: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle> | undefined,
1354
+ desired: Map<string, IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>,
1355
+ requested: IRuntimeContent<TContentHandle>[],
1356
+ ): boolean {
1357
+ let candidate = start;
1358
+ while (candidate) {
1359
+ if (this.isNodePresentationReady(candidate)) {
1360
+ this.selectNode(candidate, desired, requested);
1361
+ return true;
1362
+ }
1363
+ candidate = candidate.parent;
1364
+ }
1365
+ return false;
1366
+ }
1367
+
1368
+ /**
1369
+ * Updates whether a tile is visible and active. A visible tile is always active. An active tile need not be visible: it
1370
+ * may lie in the periphery of the view or, with `preloadSiblings`, be the neighbour of a visible tile. It refines and
1371
+ * merges like a visible one, and stays selected when it leaves the view, so that the selection does not change with
1372
+ * each small move of the camera. The traversal stops at a tile that is not active: its whole hierarchy goes with it,
1373
+ * and its ancestors do not depend on it.
1374
+ *
1375
+ * @returns Whether the tile is active.
1376
+ */
1377
+ private updateActivity(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>, camera: TCamera): boolean {
1378
+ const { spatial } = this.adapter;
1379
+ node.visible = spatial.isVisible(node.spatial, camera);
1380
+ node.active =
1381
+ node.visible ||
1382
+ spatial.isInPeriphery?.(node.spatial, camera) === true ||
1383
+ (this.preloadSiblings && this.isNeighbourOfVisible(node));
1384
+ return node.active;
1385
+ }
1386
+
1387
+ private isNeighbourOfVisible(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): boolean {
1388
+ const location = this.quadtreeLocation(node);
1389
+ return location !== undefined && quadtreeTouches(location, this.visibleTiles);
1390
+ }
1391
+
1392
+ /** Keeps the visible selected tiles of a frame, for their neighbours in the next one. It asks for that frame when they changed. */
1393
+ private updateVisibleTiles(desired: ReadonlyMap<string, IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>): void {
1394
+ const tiles = new Set<string>();
1395
+ for (const node of desired.values()) {
1396
+ if (!node.visible) continue;
1397
+ const location = this.quadtreeLocation(node);
1398
+ if (location) tiles.add(quadtreeTileKey(location.namespace, location.address));
1399
+ }
1400
+ const changed = tiles.size !== this.visibleTiles.size || [...tiles].some((tile) => !this.visibleTiles.has(tile));
1401
+ this.visibleTiles = tiles;
1402
+ if (changed) this.requestFrame();
1403
+ }
1404
+
1405
+ /** What the camera sees loads first. */
1406
+ private loadPriority(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): number {
1407
+ return node.visible ? node.screenSpaceError : node.screenSpaceError * PRELOAD_PRIORITY_SCALE;
1408
+ }
1409
+
1410
+ /** Whether the tiles selected at the start of the frame cover every visible part of a tile. */
1411
+ private selectedDescendantsCover(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>, camera: TCamera): boolean {
1412
+ const selected = new Set(this.selectedAtFrameStart);
1413
+ const covered = (tile: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): boolean => {
1414
+ if (selected.has(tile) || !this.adapter.spatial.isVisible(tile.spatial, camera)) return true;
1415
+ if (
1416
+ this.selectionStrategy === "base" &&
1417
+ tile.children.length === 0 &&
1418
+ tile.contents.every((content) => content.kind === TileContentKind.Empty && content.status === TileReadinessState.Ready) &&
1419
+ (!tile.implicit || (tile.implicit.subtree.status === TileReadinessState.Ready && tile.implicit.childrenMaterialized))
1420
+ ) {
1421
+ // An available empty leaf intentionally contributes no geometry to the retained replacement cut.
1422
+ return true;
1423
+ }
1424
+ // So does a known empty tile that its error did not refine.
1425
+ if (this.obeysGeometricError(tile) && !this.refiningNodes.has(tile.id)) return true;
1426
+ return tile.children.length > 0 && tile.children.every(covered);
1427
+ };
1428
+ return node.children.length > 0 && node.children.every(covered);
1429
+ }
1430
+
1431
+ private retainVisibleSelectedDescendants(
1432
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
1433
+ camera: TCamera,
1434
+ desired: Map<string, IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>,
1435
+ ): boolean {
1436
+ let retained = false;
1437
+ for (const candidate of this.selectedAtFrameStart) {
1438
+ if (!this.isDescendantOf(candidate, node)) continue;
1439
+ if (!this.updateActivity(candidate, camera)) continue;
1440
+ candidate.lastTouchedFrame = this.frame;
1441
+ if (candidate.implicit) candidate.implicit.subtree.lastTouchedFrame = this.frame;
1442
+ candidate.screenSpaceError = this.adapter.spatial.screenSpaceError({
1443
+ camera,
1444
+ spatial: candidate.spatial,
1445
+ tile: candidate.source,
1446
+ depth: candidate.depth,
1447
+ });
1448
+ desired.set(candidate.id, candidate);
1449
+ // Still presented, so still in the working set: its activation is neither cancelled nor started again.
1450
+ this.activeThisFrame.add(candidate.id);
1451
+ for (const content of candidate.contents) content.lastTouchedFrame = this.frame;
1452
+ retained = true;
1453
+ }
1454
+ return retained;
1455
+ }
1456
+
1457
+ private isDescendantOf(
1458
+ candidate: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
1459
+ ancestor: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
1460
+ ): boolean {
1461
+ let parent = candidate.parent;
1462
+ while (parent) {
1463
+ if (parent === ancestor) return true;
1464
+ parent = parent.parent;
1465
+ }
1466
+ return false;
1467
+ }
1468
+
1469
+ private setRefinementState(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>, refining: boolean): void {
1470
+ const wasRefining = this.refiningNodes.has(node.id);
1471
+ if (wasRefining === refining) return;
1472
+ if (refining) this.refiningNodes.add(node.id);
1473
+ else this.refiningNodes.delete(node.id);
1474
+ // An attempt of one pass: the balance repeats its traversal, and a frame may undo it. See `recordCutChanges`.
1475
+ this.recordMetric({
1476
+ name: refining ? "tile.refine.attempt" : "tile.coarsen.attempt",
1477
+ value: 1,
1478
+ unit: "count",
1479
+ tags: {
1480
+ runtime: this.id,
1481
+ tile: node.id,
1482
+ depth: node.depth,
1483
+ screenSpaceError: node.screenSpaceError,
1484
+ },
1485
+ });
1486
+ }
1487
+
1488
+ /** What a frame really changed: refinements and coarsenings once its passes are over, and tiles of the cut. */
1489
+ private recordCutChanges(refiningAtFrameStart: ReadonlySet<string>, entered: number, left: number): void {
1490
+ const record = (name: RuntimeMetricName, value: number): void => {
1491
+ for (let i = 0; i < value; i++) this.recordMetric({ name, value: 1, unit: "count", tags: { runtime: this.id } });
1492
+ };
1493
+ let refined = 0;
1494
+ for (const id of this.refiningNodes) if (!refiningAtFrameStart.has(id)) refined++;
1495
+ let coarsened = 0;
1496
+ for (const id of refiningAtFrameStart) if (!this.refiningNodes.has(id)) coarsened++;
1497
+ record("tile.refine", refined);
1498
+ record("tile.coarsen", coarsened);
1499
+ record("cut.entered", entered);
1500
+ record("cut.left", left);
1501
+ }
1502
+
1503
+ protected selectNode(
1504
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
1505
+ desired: Map<string, IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>>,
1506
+ requested: IRuntimeContent<TContentHandle>[],
1507
+ ): void {
1508
+ desired.set(node.id, node);
1509
+ node.lastTouchedFrame = this.frame;
1510
+ for (const content of node.contents) content.lastTouchedFrame = this.frame;
1511
+ this.requestNodeContents(node, this.loadPriority(node), requested);
1512
+ }
1513
+
1514
+ protected requestNodeContents(
1515
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
1516
+ priority: number,
1517
+ requested: IRuntimeContent<TContentHandle>[],
1518
+ ): void {
1519
+ if (node.contents.length === 0) return;
1520
+ this.activeThisFrame.add(node.id);
1521
+ const entering = node.selectionState !== TileSelectionState.Active;
1522
+ if (entering) {
1523
+ node.selectionState = TileSelectionState.Active;
1524
+ node.activationId++;
1525
+ this.events.emit({ type: "tile-activated", tile: node });
1526
+ }
1527
+
1528
+ if (this.adapter.activation) {
1529
+ if (node.contents.some((content) => content.status === TileReadinessState.Queued))
1530
+ this.followQueuedPriority(this.pipelineActivationKey(node), priority);
1531
+ this.requestPipelineActivation(node, priority, requested, entering);
1532
+ this.requestRefresh(node, priority);
1533
+ return;
1534
+ }
1535
+
1536
+ for (const content of node.contents) {
1537
+ if (content.kind !== TileContentKind.Unknown && content.kind !== TileContentKind.Renderable) continue;
1538
+ if (content.status === TileReadinessState.Queued) this.followQueuedPriority(content.id, priority);
1539
+ if (
1540
+ content.status !== TileReadinessState.Idle &&
1541
+ content.status !== TileReadinessState.Failed &&
1542
+ content.status !== TileReadinessState.Cancelled
1543
+ )
1544
+ continue;
1545
+ if (content.attempts >= this.maxLoadAttempts) continue;
1546
+ content.status = TileReadinessState.Queued;
1547
+ const added = this.scheduler.enqueue(content.id, priority, (signal) => this.loadContent(node, content, signal));
1548
+ if (added) {
1549
+ requested.push(content);
1550
+ this.events.emit({ type: "content-state", tile: node, content });
1551
+ }
1552
+ }
1553
+ this.refreshNodeReadiness(node);
1554
+ this.requestRefresh(node, priority);
1555
+ }
1556
+
1557
+ /** A waiting load follows the priority of the current frame, up or down: the highest its balance passes asked. */
1558
+ private followQueuedPriority(key: string, priority: number): void {
1559
+ if (this.queuedPrioritiesFrame !== this.frame) {
1560
+ this.queuedPriorities.clear();
1561
+ this.queuedPrioritiesFrame = this.frame;
1562
+ }
1563
+ const highest = Math.max(this.queuedPriorities.get(key) ?? priority, priority);
1564
+ this.queuedPriorities.set(key, highest);
1565
+ this.scheduler.reprioritize(key, highest);
1566
+ }
1567
+
1568
+ private requestPipelineActivation(
1569
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
1570
+ priority: number,
1571
+ requested: IRuntimeContent<TContentHandle>[],
1572
+ notifyEvenWhenReady: boolean,
1573
+ ): void {
1574
+ const pending = node.contents.filter(
1575
+ (content) =>
1576
+ (content.kind === TileContentKind.Unknown || content.kind === TileContentKind.Renderable) &&
1577
+ (content.status === TileReadinessState.Idle ||
1578
+ content.status === TileReadinessState.Failed ||
1579
+ content.status === TileReadinessState.Cancelled) &&
1580
+ content.attempts < this.maxLoadAttempts,
1581
+ );
1582
+ if (pending.length === 0 && !notifyEvenWhenReady) return;
1583
+ const previous = pending.map((content) => content.status);
1584
+ for (const content of pending) content.status = TileReadinessState.Queued;
1585
+ const key = this.pipelineActivationKey(node);
1586
+ const added = this.scheduler.enqueue(key, priority, (signal) => this.activatePipelineTile(node, pending, priority, signal));
1587
+ if (!added) {
1588
+ // An activation of the tile is already queued or running without these contents: request them again later.
1589
+ pending.forEach((content, index) => (content.status = previous[index]!));
1590
+ return;
1591
+ }
1592
+ this.refreshNodeReadiness(node);
1593
+ for (const content of pending) {
1594
+ requested.push(content);
1595
+ this.events.emit({ type: "content-state", tile: node, content });
1596
+ }
1597
+ }
1598
+
1599
+ private async activatePipelineTile(
1600
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
1601
+ pending: readonly IRuntimeContent<TContentHandle>[],
1602
+ priority: number,
1603
+ signal: AbortSignal,
1604
+ ): Promise<void> {
1605
+ const activation = this.adapter.activation;
1606
+ if (!activation) return;
1607
+ const activationId = node.activationId;
1608
+ const unsettled = new Set(pending.map((content) => content.id));
1609
+ let settleActivation: (() => void) | undefined;
1610
+ const settled = new Promise<void>((resolve) => {
1611
+ settleActivation = resolve;
1612
+ });
1613
+ const finish = (contentId: string): void => {
1614
+ unsettled.delete(contentId);
1615
+ if (unsettled.size === 0) settleActivation?.();
1616
+ };
1617
+ const findPending = (contentId: string): IRuntimeContent<TContentHandle> | undefined =>
1618
+ pending.find((content) => content.id === contentId);
1619
+
1620
+ for (const content of pending) {
1621
+ content.attempts++;
1622
+ content.status = TileReadinessState.Preparing;
1623
+ content.lastTouchedFrame = this.frame;
1624
+ this.events.emit({ type: "content-state", tile: node, content });
1625
+ }
1626
+ this.refreshNodeReadiness(node);
1627
+
1628
+ const readiness: ITileReadinessPort<TContentHandle> = {
1629
+ tileId: node.id,
1630
+ activationId,
1631
+ signal,
1632
+ ready: async (contentId, result) => {
1633
+ const content = findPending(contentId);
1634
+ if (!content || !unsettled.has(contentId) || signal.aborted || node.activationId !== activationId) return false;
1635
+ await this.acceptContentResult(node, content, result);
1636
+ content.status = TileReadinessState.Ready;
1637
+ content.readyFrame = this.frame;
1638
+ content.lastTouchedFrame = this.frame;
1639
+ delete content.error;
1640
+ this.events.emit({ type: "content-state", tile: node, content });
1641
+ this.refreshNodeReadiness(node);
1642
+ finish(contentId);
1643
+ this.markDirty();
1644
+ return true;
1645
+ },
1646
+ failed: async (contentId, error) => {
1647
+ const content = findPending(contentId);
1648
+ if (!content || !unsettled.has(contentId) || node.activationId !== activationId) return;
1649
+ content.error = error;
1650
+ content.status = TileReadinessState.Failed;
1651
+ this.events.emit({ type: "content-state", tile: node, content });
1652
+ this.refreshNodeReadiness(node);
1653
+ await this.reportError("content.prepare", error, node, content);
1654
+ finish(contentId);
1655
+ this.markDirty();
1656
+ },
1657
+ cancelled: async (contentId) => {
1658
+ const content = findPending(contentId);
1659
+ // Once settled, its contents may belong to a newer activation.
1660
+ if (!content || !unsettled.has(contentId)) return;
1661
+ // A cancelled attempt did not fail: it does not count against maxLoadAttempts.
1662
+ content.attempts = Math.max(0, content.attempts - 1);
1663
+ content.status = TileReadinessState.Cancelled;
1664
+ this.recordMetric({ name: "content.cancelled", value: 1, unit: "count", tags: { runtime: this.id, tile: node.id } });
1665
+ this.events.emit({ type: "content-state", tile: node, content });
1666
+ this.refreshNodeReadiness(node);
1667
+ finish(contentId);
1668
+ this.markDirty();
1669
+ },
1670
+ };
1671
+
1672
+ // A cancelled activation gives its load slot back at once, whatever the adapter still waits for: a shared
1673
+ // load may outlive it. What it reports later is ignored.
1674
+ let abandon: () => void = () => undefined;
1675
+ const abandoned = new Promise<void>((resolve) => {
1676
+ abandon = resolve;
1677
+ });
1678
+ const abort = (): void => {
1679
+ for (const contentId of [...unsettled]) void readiness.cancelled(contentId);
1680
+ abandon();
1681
+ };
1682
+ signal.addEventListener("abort", abort, { once: true });
1683
+ try {
1684
+ await Promise.race([
1685
+ activation.activate({
1686
+ runtimeId: this.id,
1687
+ tile: node,
1688
+ pendingContents: pending,
1689
+ priority,
1690
+ activationId,
1691
+ signal,
1692
+ readiness,
1693
+ }),
1694
+ abandoned,
1695
+ ]);
1696
+ if (unsettled.size > 0) await settled;
1697
+ } catch (error) {
1698
+ for (const contentId of [...unsettled]) await readiness.failed(contentId, error);
1699
+ } finally {
1700
+ signal.removeEventListener("abort", abort);
1701
+ // Its tile may have come back in the meantime, and been refused while this activation held its key.
1702
+ if (signal.aborted) this.markDirty();
1703
+ }
1704
+ }
1705
+
1706
+ private refreshKey(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): string {
1707
+ return `refresh:${node.id}`;
1708
+ }
1709
+
1710
+ /**
1711
+ * Reloads the stale ready contents of a tile of the working set, one reload of a tile at a time. Provisional
1712
+ * contents reload only for a leaf of the cut: a tile the descent goes through never loads its own content.
1713
+ */
1714
+ private requestRefresh(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>, priority: number, leaf = false): void {
1715
+ const stale = node.contents.filter(
1716
+ (content): content is ReadyContent<TContentHandle> =>
1717
+ content.stale && content.ready && !this.refreshes.has(content) && (leaf || !this.provisionalContents.has(content)),
1718
+ );
1719
+ if (stale.length === 0) return;
1720
+ const records = stale.map((content) => ({ content, refresh: { serial: this.staleContents.get(content)?.serial ?? 0 } }));
1721
+ // Recorded first: the scheduler may start the reload at once, and an adapter may settle it synchronously.
1722
+ for (const { content, refresh } of records) this.refreshes.set(content, refresh);
1723
+ const added = this.scheduler.enqueue(this.refreshKey(node), priority, (signal) =>
1724
+ this.refreshTile(node, records, priority, signal),
1725
+ );
1726
+ if (!added) for (const { content } of records) this.refreshes.delete(content);
1727
+ }
1728
+
1729
+ /** Stops the reload of the provisional contents of a tile that refines again: its children replace it. */
1730
+ private cancelProvisionalRefresh(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): void {
1731
+ const pending = node.contents.some((content) => {
1732
+ const refresh = this.refreshes.get(content);
1733
+ return this.provisionalContents.has(content) && refresh !== undefined && refresh.result === undefined;
1734
+ });
1735
+ if (pending) this.cancelRefresh(node);
1736
+ }
1737
+
1738
+ /** Stops the reloads of a tile leaving the working set; the results already reported are still swapped in. */
1739
+ private cancelRefresh(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): void {
1740
+ this.scheduler.cancel(this.refreshKey(node));
1741
+ for (const content of node.contents) {
1742
+ const refresh = this.refreshes.get(content);
1743
+ if (refresh && !refresh.result) this.refreshes.delete(content);
1744
+ }
1745
+ }
1746
+
1747
+ private async refreshTile(
1748
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
1749
+ records: readonly { content: ReadyContent<TContentHandle>; refresh: IContentRefresh<TContentHandle> }[],
1750
+ priority: number,
1751
+ signal: AbortSignal,
1752
+ ): Promise<void> {
1753
+ const unsettled = new Set(records.map(({ content }) => content.id));
1754
+ // A record replaced or dropped since, by an eviction or a deactivation, ignores what the adapter reports.
1755
+ const current = (contentId: string): (typeof records)[number] | undefined => {
1756
+ const record = records.find(({ content }) => content.id === contentId);
1757
+ return record && unsettled.has(contentId) && this.refreshes.get(record.content) === record.refresh ? record : undefined;
1758
+ };
1759
+ const settle = (contentId: string, record: (typeof records)[number] | undefined, keep: boolean): void => {
1760
+ unsettled.delete(contentId);
1761
+ if (record && !keep) this.refreshes.delete(record.content);
1762
+ this.markDirty();
1763
+ };
1764
+ const readiness: ITileReadinessPort<TContentHandle> = {
1765
+ tileId: node.id,
1766
+ activationId: node.activationId,
1767
+ signal,
1768
+ ready: async (contentId, result) => {
1769
+ const record = current(contentId);
1770
+ if (!record || signal.aborted) return false;
1771
+ record.refresh.result = result;
1772
+ settle(contentId, record, true);
1773
+ return true;
1774
+ },
1775
+ failed: async (contentId, error) => {
1776
+ const record = current(contentId);
1777
+ if (!record) return;
1778
+ settle(contentId, record, false);
1779
+ // The previous handle stays presented; after too many failures, it is kept as it is.
1780
+ const stale = this.staleContents.get(record.content);
1781
+ if (stale && ++stale.failures >= this.maxLoadAttempts) this.markFresh(record.content, stale.serial);
1782
+ await this.reportError("content.refresh", error, node, record.content);
1783
+ },
1784
+ cancelled: async (contentId) => {
1785
+ if (unsettled.has(contentId)) settle(contentId, current(contentId), false);
1786
+ },
1787
+ };
1788
+ const abort = (): void => {
1789
+ for (const contentId of [...unsettled]) void readiness.cancelled(contentId);
1790
+ };
1791
+ signal.addEventListener("abort", abort, { once: true });
1792
+ try {
1793
+ const activation = this.adapter.activation;
1794
+ if (activation) {
1795
+ await activation.activate({
1796
+ runtimeId: this.id,
1797
+ tile: node,
1798
+ pendingContents: records.map(({ content }) => content),
1799
+ priority,
1800
+ activationId: node.activationId,
1801
+ signal,
1802
+ readiness,
1803
+ refresh: true,
1804
+ });
1805
+ } else {
1806
+ const contentAdapter = this.adapter.content;
1807
+ if (!contentAdapter) throw new Error("The legacy content adapter is not configured.");
1808
+ for (const { content } of records) {
1809
+ if (signal.aborted) break;
1810
+ try {
1811
+ const result = await contentAdapter.load(this.contentLoadContext(node, content), signal);
1812
+ const accepted = await readiness.ready(content.id, result);
1813
+ if (!accepted && result.kind === "renderable" && result.handle !== content.handle)
1814
+ await this.releaseHandle(node, content, result.handle);
1815
+ } catch (error) {
1816
+ if (signal.aborted) await readiness.cancelled(content.id);
1817
+ else await readiness.failed(content.id, error);
1818
+ }
1819
+ }
1820
+ }
1821
+ } catch (error) {
1822
+ for (const contentId of [...unsettled]) await readiness.failed(contentId, error);
1823
+ } finally {
1824
+ signal.removeEventListener("abort", abort);
1825
+ // What the adapter left unsettled counts as a failed reload, so that an adapter ignoring reloads ends them.
1826
+ for (const contentId of [...unsettled]) {
1827
+ if (signal.aborted) await readiness.cancelled(contentId);
1828
+ else await readiness.failed(contentId, new Error("The activation adapter settled no reload of this content."));
1829
+ }
1830
+ }
1831
+ }
1832
+
1833
+ /** Clears the stale flag, unless the content was invalidated again after its reload started. */
1834
+ private markFresh(content: IRuntimeContent<TContentHandle>, serial: number): void {
1835
+ const stale = this.staleContents.get(content);
1836
+ if (stale && stale.serial > serial) return;
1837
+ this.staleContents.delete(content);
1838
+ content.stale = false;
1839
+ }
1840
+
1841
+ /** Swaps the reloaded handles in, before the traversal of a frame. */
1842
+ private async applyRefreshes(): Promise<void> {
1843
+ if (this.refreshes.size === 0) return;
1844
+ for (const node of this.nodes.values()) {
1845
+ for (const content of node.contents) {
1846
+ const refresh = this.refreshes.get(content);
1847
+ if (!refresh?.result) continue;
1848
+ this.refreshes.delete(content);
1849
+ await this.swapContent(node, content, refresh.result, refresh.serial);
1850
+ }
1851
+ }
1852
+ }
1853
+
1854
+ /**
1855
+ * Replaces the handle of a content with its reload. A presented content is hidden and released, then the tile is
1856
+ * presented again with the new handle, all before the next render: the view never shows a hole.
1857
+ */
1858
+ private async swapContent(
1859
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
1860
+ content: IRuntimeContent<TContentHandle>,
1861
+ result: ContentLoadResult<TContentHandle>,
1862
+ serial: number,
1863
+ ): Promise<void> {
1864
+ const previous = content.handle;
1865
+ if (previous === undefined || !content.ready) {
1866
+ // Released in the meantime: nothing to replace.
1867
+ if (result.kind === "renderable" && result.handle !== previous) await this.releaseHandle(node, content, result.handle);
1868
+ return;
1869
+ }
1870
+ this.markFresh(content, serial);
1871
+ content.lastTouchedFrame = this.frame;
1872
+ if (result.kind !== "renderable") {
1873
+ await this.reportError("content.refresh", new Error("A reloaded content must stay renderable."), node, content);
1874
+ return;
1875
+ }
1876
+ if (result.handle === previous) {
1877
+ // Refreshed in place by the adapter.
1878
+ this.events.emit({ type: "content-state", tile: node, content });
1879
+ return;
1880
+ }
1881
+ const presented = content.attached && node.selected;
1882
+ const old = content as ReadyContent<TContentHandle>;
1883
+ const presentation = this.adapter.presentation;
1884
+ const contentAdapter = this.adapter.content;
1885
+ try {
1886
+ if (presented) {
1887
+ if (presentation) await presentation.hide(this.pipelinePresentationContext(node, [old]));
1888
+ else await contentAdapter?.detach(this.presentationContext(node, old, await this.contentSnapshot(node, old)));
1889
+ }
1890
+ } catch (error) {
1891
+ await this.reportError("content.hide", error, node, content);
1892
+ }
1893
+ await this.releaseHandle(node, content, previous);
1894
+ content.attached = false;
1895
+ this.metadataStore.release(content.metadataHandle);
1896
+ if (content.featureMetadataHandle !== content.metadataHandle) this.metadataStore.release(content.featureMetadataHandle);
1897
+ content.metadataHandle = NO_METADATA;
1898
+ content.featureMetadataHandle = NO_METADATA;
1899
+ node.metadataSnapshots = node.metadataSnapshots.filter((snapshot) => snapshot.content !== content.descriptor);
1900
+ await this.acceptContentResult(node, content, result);
1901
+ content.readyFrame = this.frame;
1902
+ this.events.emit({ type: "content-state", tile: node, content });
1903
+ if (!presented) return;
1904
+ const fresh = content as ReadyContent<TContentHandle>;
1905
+ try {
1906
+ const snapshot = await this.resolveMetadata(node, fresh.descriptor, fresh.featureMetadata);
1907
+ node.metadataSnapshots = [...node.metadataSnapshots, snapshot];
1908
+ if (presentation) {
1909
+ const ready = node.contents.filter((candidate): candidate is ReadyContent<TContentHandle> => candidate.ready);
1910
+ await presentation.present(this.pipelinePresentationContext(node, ready));
1911
+ for (const candidate of ready) candidate.attached = true;
1912
+ } else if (contentAdapter) {
1913
+ await contentAdapter.attach(this.presentationContext(node, fresh, snapshot));
1914
+ fresh.attached = true;
1915
+ }
1916
+ } catch (error) {
1917
+ await this.reportError("content.present", error, node, content);
1918
+ }
1919
+ }
1920
+
1921
+ /** Releases a handle of a content that is not, or no longer, its current handle. */
1922
+ private async releaseHandle(
1923
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
1924
+ content: IRuntimeContent<TContentHandle>,
1925
+ handle: TContentHandle,
1926
+ ): Promise<void> {
1927
+ const presentation = this.adapter.presentation;
1928
+ const contentAdapter = this.adapter.content;
1929
+ const resource: ReadyContent<TContentHandle> = Object.assign(
1930
+ Object.create(Object.getPrototypeOf(content) as object) as object,
1931
+ content,
1932
+ {
1933
+ handle,
1934
+ },
1935
+ );
1936
+ try {
1937
+ if (presentation?.release) await presentation.release(this.pipelinePresentationContext(node, [resource]));
1938
+ else if (contentAdapter?.dispose)
1939
+ await contentAdapter.dispose(this.presentationContext(node, resource, await this.contentSnapshot(node, resource)));
1940
+ } catch (error) {
1941
+ await this.reportError("content.dispose", error, node, content);
1942
+ }
1943
+ }
1944
+
1945
+ private async contentSnapshot(
1946
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
1947
+ content: IRuntimeContent<TContentHandle>,
1948
+ ): Promise<IMetadataSnapshot> {
1949
+ return (
1950
+ node.metadataSnapshots.find((candidate) => candidate.content === content.descriptor) ??
1951
+ (await this.resolveMetadata(node, content.descriptor))
1952
+ );
1953
+ }
1954
+
1955
+ private pipelineActivationKey(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): string {
1956
+ return `activation:${node.id}`;
1957
+ }
1958
+
1959
+ private async deactivatePipelineTilesOutsideWorkingSet(): Promise<void> {
1960
+ for (const node of this.nodes.values()) {
1961
+ if (node.selectionState !== TileSelectionState.Active || this.activeThisFrame.has(node.id)) continue;
1962
+ const activationId = node.activationId;
1963
+ node.activationId++;
1964
+ node.selectionState = TileSelectionState.Inactive;
1965
+ this.scheduler.cancel(this.pipelineActivationKey(node));
1966
+ this.cancelRefresh(node);
1967
+ // An activation that left the queue before it started never settles its contents: they become idle again.
1968
+ let requeue = false;
1969
+ for (const content of node.contents) {
1970
+ if (content.status !== TileReadinessState.Queued) continue;
1971
+ content.status = TileReadinessState.Idle;
1972
+ requeue = true;
1973
+ }
1974
+ if (requeue) this.refreshNodeReadiness(node);
1975
+ if (this.adapter.activation) {
1976
+ await this.adapter.activation.deactivate({ runtimeId: this.id, tile: node, activationId });
1977
+ }
1978
+ this.events.emit({ type: "tile-deactivated", tile: node });
1979
+ }
1980
+ }
1981
+
1982
+ protected async loadContent(
1983
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
1984
+ content: IRuntimeContent<TContentHandle>,
1985
+ signal: AbortSignal,
1986
+ ): Promise<void> {
1987
+ const startedAt = this.startTiming();
1988
+ content.attempts++;
1989
+ content.status = TileReadinessState.Preparing;
1990
+ content.lastTouchedFrame = this.frame;
1991
+ this.refreshNodeReadiness(node);
1992
+ this.events.emit({ type: "content-state", tile: node, content });
1993
+ const hookContext: IContentHookContext<TSpatial, TContentHandle, TGlyphHandle> = { runtimeId: this.id, tile: node, content };
1994
+ await this.invokeHooks("beforeContentLoad", (hook) => hook.beforeContentLoad?.(hookContext), node, content);
1995
+ try {
1996
+ const contentAdapter = this.adapter.content;
1997
+ if (!contentAdapter) throw new Error("The legacy content adapter is not configured.");
1998
+ const result = await contentAdapter.load(this.contentLoadContext(node, content), signal);
1999
+ if (signal.aborted) {
2000
+ content.attempts = Math.max(0, content.attempts - 1);
2001
+ content.status = TileReadinessState.Cancelled;
2002
+ return;
2003
+ }
2004
+ await this.acceptContentResult(node, content, result);
2005
+ content.status = TileReadinessState.Ready;
2006
+ content.readyFrame = this.frame;
2007
+ content.lastTouchedFrame = this.frame;
2008
+ delete content.error;
2009
+ this.recordMetric({
2010
+ name: "content.load",
2011
+ value: 1,
2012
+ unit: "count",
2013
+ tags: { runtime: this.id, tile: node.id, kind: content.kind },
2014
+ });
2015
+ this.recordDuration("content.load.duration", startedAt, {
2016
+ runtime: this.id,
2017
+ tile: node.id,
2018
+ kind: content.kind,
2019
+ });
2020
+ if (content.cost?.networkBytes !== undefined) {
2021
+ this.recordMetric({
2022
+ name: "content.load.network-bytes",
2023
+ value: content.cost.networkBytes,
2024
+ unit: "byte",
2025
+ tags: { runtime: this.id, tile: node.id },
2026
+ });
2027
+ }
2028
+ await this.invokeHooks("afterContentLoad", (hook) => hook.afterContentLoad?.({ ...hookContext, result }), node, content);
2029
+ } catch (error) {
2030
+ content.error = error;
2031
+ content.status = signal.aborted ? TileReadinessState.Cancelled : TileReadinessState.Failed;
2032
+ if (signal.aborted) content.attempts = Math.max(0, content.attempts - 1);
2033
+ await this.reportError("content.load", error, node, content);
2034
+ } finally {
2035
+ this.refreshNodeReadiness(node);
2036
+ this.events.emit({ type: "content-state", tile: node, content });
2037
+ this.markDirty();
2038
+ }
2039
+ }
2040
+
2041
+ protected async acceptContentResult(
2042
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
2043
+ content: IRuntimeContent<TContentHandle>,
2044
+ result: ContentLoadResult<TContentHandle>,
2045
+ ): Promise<void> {
2046
+ if (result.kind === "renderable") {
2047
+ content.kind = TileContentKind.Renderable;
2048
+ content.handle = result.handle;
2049
+ if (result.cacheKey) content.cacheKey = result.cacheKey;
2050
+ else delete content.cacheKey;
2051
+ if (result.cost) content.cost = result.cost;
2052
+ else delete content.cost;
2053
+ if (result.featureMetadata) content.featureMetadata = result.featureMetadata;
2054
+ else delete content.featureMetadata;
2055
+ node.contentHeights = result.tileHeightRange;
2056
+ if (result.tileBoundingVolume) {
2057
+ const measured = result.tileBoundingVolume;
2058
+ this.refineTileBoundingVolume(node, typeof measured === "function" ? measured : () => measured);
2059
+ }
2060
+ this.refreshImplicitChildBounds(node);
2061
+ if (result.provisional) {
2062
+ this.provisionalContents.add(content);
2063
+ content.stale = true;
2064
+ if (!this.staleContents.has(content)) this.staleContents.set(content, { serial: this.invalidations, failures: 0 });
2065
+ } else this.provisionalContents.delete(content);
2066
+ return;
2067
+ }
2068
+ if (result.kind === "external-tileset") {
2069
+ content.kind = TileContentKind.ExternalTileset;
2070
+ const documentUri = result.documentUri ?? content.uri;
2071
+ const loaded: ILoadedTileset = {
2072
+ tileset: result.tileset,
2073
+ ...(result.baseUri ? { baseUri: result.baseUri } : {}),
2074
+ };
2075
+ const document = await this.createDocument(`${node.document.id}/${content.id}`, documentUri, loaded);
2076
+ const child = this.createNode(document.tileset.root, document, node, `external-${node.contents.indexOf(content)}`);
2077
+ node.children.push(child);
2078
+ const hookContext: ITilesetLoadedHookContext = {
2079
+ runtimeId: this.id,
2080
+ uri: documentUri,
2081
+ parentDocumentUri: node.document.uri,
2082
+ loaded,
2083
+ document,
2084
+ };
2085
+ await this.invokeHooks("afterTilesetLoad", (hook) => hook.afterTilesetLoad?.(hookContext), node, content);
2086
+ return;
2087
+ }
2088
+ content.kind = TileContentKind.Empty;
2089
+ }
2090
+
2091
+ /**
2092
+ * Re-derives the spatial state of a tile from a bounding volume measured on its content.
2093
+ * The serialized tile stays unchanged; only the runtime state uses the measured volume.
2094
+ */
2095
+ private refineTileBoundingVolume(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>, measured: () => IBoundingVolume): void {
2096
+ node.contentBounds = measured;
2097
+ const heightRange = node.contentHeights?.();
2098
+ node.spatial = this.adapter.spatial.derive({
2099
+ tile: { ...node.source, boundingVolume: measured() },
2100
+ ...(node.parent ? { parent: node.parent.spatial } : {}),
2101
+ ...(heightRange ? { heightRange } : {}),
2102
+ });
2103
+ node.contentBoundsRefined = true;
2104
+ this.events.emit({ type: "tile-bounds-refined", tile: node, origin: "content" });
2105
+ }
2106
+
2107
+ /**
2108
+ * Resolves the bounding volumes of materialized implicit children again once their parent content is ready.
2109
+ *
2110
+ * An implicit resolver may derive child volumes from the parent content, for example the quadrant height ranges
2111
+ * of a DEM. Children materialized before that content arrived would otherwise keep their initial volume, be culled
2112
+ * and never load. Children whose own content already reported a measured volume are left unchanged.
2113
+ */
2114
+ private refreshImplicitChildBounds(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): void {
2115
+ for (const child of node.children) {
2116
+ if (!child.implicit || child.contentBoundsRefined || !this.implicitResolver(child.implicit.context)) continue;
2117
+ const resolved = this.createImplicitTileSource(child.implicit, child.document);
2118
+ child.spatial = this.adapter.spatial.derive({
2119
+ tile: { ...child.source, boundingVolume: resolved.boundingVolume },
2120
+ parent: node.spatial,
2121
+ ...(child.implicit.heightRange ? { heightRange: child.implicit.heightRange } : {}),
2122
+ });
2123
+ this.events.emit({ type: "tile-bounds-refined", tile: child, origin: "parent-content" });
2124
+ }
2125
+ }
2126
+
2127
+ /** Derives every tile again, parents first, after a change of the vertical scale. */
2128
+ private refreshSpatialStates(): void {
2129
+ this.spatialStale = false;
2130
+ const visit = (node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): void => {
2131
+ const boundingVolume =
2132
+ node.contentBounds?.() ??
2133
+ (node.implicit && this.implicitResolver(node.implicit.context)
2134
+ ? this.createImplicitTileSource(node.implicit, node.document).boundingVolume
2135
+ : node.source.boundingVolume);
2136
+ const heightRange = node.contentHeights?.() ?? node.implicit?.heightRange;
2137
+ node.spatial = this.adapter.spatial.derive({
2138
+ tile: { ...node.source, boundingVolume },
2139
+ ...(node.parent ? { parent: node.parent.spatial } : {}),
2140
+ ...(heightRange ? { heightRange } : {}),
2141
+ });
2142
+ this.events.emit({ type: "tile-bounds-refined", tile: node, origin: "vertical-scale" });
2143
+ for (const child of node.children) visit(child);
2144
+ };
2145
+ if (this.root) visit(this.root);
2146
+ }
2147
+
2148
+ private refreshNodeReadiness(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): void {
2149
+ if (node.contents.length === 0) {
2150
+ node.readinessState = TileReadinessState.Idle;
2151
+ return;
2152
+ }
2153
+ if (node.contents.every((content) => content.status === TileReadinessState.Ready)) {
2154
+ node.readinessState = TileReadinessState.Ready;
2155
+ return;
2156
+ }
2157
+ if (node.contents.some((content) => content.status === TileReadinessState.Preparing)) {
2158
+ node.readinessState = TileReadinessState.Preparing;
2159
+ return;
2160
+ }
2161
+ if (node.contents.some((content) => content.status === TileReadinessState.Queued)) {
2162
+ node.readinessState = TileReadinessState.Queued;
2163
+ return;
2164
+ }
2165
+ if (node.contents.every((content) => content.status === TileReadinessState.Cancelled)) {
2166
+ node.readinessState = TileReadinessState.Cancelled;
2167
+ return;
2168
+ }
2169
+ if (
2170
+ node.contents.every(
2171
+ (content) => content.status === TileReadinessState.Failed || content.status === TileReadinessState.Cancelled,
2172
+ )
2173
+ ) {
2174
+ node.readinessState = TileReadinessState.Failed;
2175
+ return;
2176
+ }
2177
+ node.readinessState = TileReadinessState.Idle;
2178
+ }
2179
+
2180
+ protected async activateNode(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): Promise<void> {
2181
+ const wasSelected = node.selected;
2182
+ const readyContents = node.contents.filter(
2183
+ (content): content is IRuntimeContent<TContentHandle> & { handle: TContentHandle } =>
2184
+ content.kind === TileContentKind.Renderable && content.status === TileReadinessState.Ready && content.handle !== undefined,
2185
+ );
2186
+ const hasNewContent = readyContents.some((content) => !content.attached);
2187
+ if (wasSelected && !hasNewContent) return;
2188
+
2189
+ const tileSnapshot = await this.resolveMetadata(node);
2190
+ const snapshots: IMetadataSnapshot[] = [];
2191
+ for (const content of readyContents) {
2192
+ const snapshot = await this.resolveMetadata(node, content.descriptor, content.featureMetadata);
2193
+ snapshots.push(snapshot);
2194
+ }
2195
+ if (snapshots.length === 0) snapshots.push(tileSnapshot);
2196
+ node.metadataSnapshots = snapshots;
2197
+
2198
+ if (this.adapter.presentation) {
2199
+ if (!wasSelected || hasNewContent) {
2200
+ node.presentationState = TilePresentationState.Presenting;
2201
+ try {
2202
+ await this.adapter.presentation.present(this.pipelinePresentationContext(node, readyContents));
2203
+ for (const content of readyContents) {
2204
+ content.attached = true;
2205
+ content.lastTouchedFrame = this.frame;
2206
+ }
2207
+ } catch (error) {
2208
+ node.presentationState = TilePresentationState.Hidden;
2209
+ await this.reportError("content.present", error, node);
2210
+ return;
2211
+ }
2212
+ }
2213
+ } else {
2214
+ const contentAdapter = this.adapter.content;
2215
+ if (!contentAdapter) throw new Error("The legacy content adapter is not configured.");
2216
+ for (const content of readyContents) {
2217
+ if (content.attached) continue;
2218
+ const snapshot = this.metadataStore.get(content.metadataHandle);
2219
+ const presentation = this.presentationContext(node, content, snapshot);
2220
+ const hookContext: IContentHookContext<TSpatial, TContentHandle, TGlyphHandle> = {
2221
+ runtimeId: this.id,
2222
+ tile: node,
2223
+ content,
2224
+ metadata: snapshot,
2225
+ };
2226
+ await this.invokeHooks("beforeContentAttach", (hook) => hook.beforeContentAttach?.(hookContext), node, content);
2227
+ try {
2228
+ await contentAdapter.attach(presentation);
2229
+ content.attached = true;
2230
+ content.lastTouchedFrame = this.frame;
2231
+ this.recordMetric({
2232
+ name: "tile.attach",
2233
+ value: 1,
2234
+ unit: "count",
2235
+ tags: { runtime: this.id, tile: node.id },
2236
+ });
2237
+ await this.invokeHooks("afterContentAttach", (hook) => hook.afterContentAttach?.(hookContext), node, content);
2238
+ } catch (error) {
2239
+ await this.reportError("content.attach", error, node, content);
2240
+ }
2241
+ }
2242
+ }
2243
+
2244
+ if (this.adapter.glyphs) {
2245
+ if (node.glyphHandles.length > 0) await this.revokeGlyphs(node);
2246
+ const tileHookContext: ITileHookContext<TSpatial, TContentHandle, TGlyphHandle> = { runtimeId: this.id, tile: node };
2247
+ await this.invokeHooks("beforeGlyphPublish", (hook) => hook.beforeGlyphPublish?.(tileHookContext), node);
2248
+ try {
2249
+ const handles = await this.adapter.glyphs.publish(this.glyphContext(node));
2250
+ node.glyphHandles = [...handles];
2251
+ await this.invokeHooks("afterGlyphPublish", (hook) => hook.afterGlyphPublish?.(tileHookContext), node);
2252
+ } catch (error) {
2253
+ await this.reportError("glyph.publish", error, node);
2254
+ }
2255
+ }
2256
+
2257
+ node.selected = true;
2258
+ if (!wasSelected) {
2259
+ const context: ITileHookContext<TSpatial, TContentHandle, TGlyphHandle> = { runtimeId: this.id, tile: node };
2260
+ await this.invokeHooks("onTileSelected", (hook) => hook.onTileSelected?.(context), node);
2261
+ this.events.emit({ type: "tile-selected", tile: node });
2262
+ }
2263
+ }
2264
+
2265
+ protected async deactivateNode(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): Promise<void> {
2266
+ if (!node.selected) return;
2267
+ await this.revokeGlyphs(node);
2268
+ const attached = node.contents.filter(
2269
+ (content): content is IRuntimeContent<TContentHandle> & { handle: TContentHandle } =>
2270
+ content.attached && content.handle !== undefined,
2271
+ );
2272
+ if (this.adapter.presentation) {
2273
+ node.presentationState = TilePresentationState.Hiding;
2274
+ try {
2275
+ await this.adapter.presentation.hide(this.pipelinePresentationContext(node, attached));
2276
+ for (const content of attached) {
2277
+ content.attached = false;
2278
+ content.lastTouchedFrame = this.frame;
2279
+ }
2280
+ } catch (error) {
2281
+ await this.reportError("content.hide", error, node);
2282
+ }
2283
+ } else {
2284
+ const contentAdapter = this.adapter.content;
2285
+ if (!contentAdapter) throw new Error("The legacy content adapter is not configured.");
2286
+ for (const content of attached) {
2287
+ const snapshot =
2288
+ node.metadataSnapshots.find((candidate) => candidate.content === content.descriptor) ??
2289
+ (await this.resolveMetadata(node, content.descriptor));
2290
+ const presentation = this.presentationContext(node, content, snapshot);
2291
+ const hookContext: IContentHookContext<TSpatial, TContentHandle, TGlyphHandle> = {
2292
+ runtimeId: this.id,
2293
+ tile: node,
2294
+ content,
2295
+ metadata: snapshot,
2296
+ };
2297
+ await this.invokeHooks("beforeContentDetach", (hook) => hook.beforeContentDetach?.(hookContext), node, content);
2298
+ try {
2299
+ await contentAdapter.detach(presentation);
2300
+ content.attached = false;
2301
+ content.lastTouchedFrame = this.frame;
2302
+ this.recordMetric({
2303
+ name: "tile.detach",
2304
+ value: 1,
2305
+ unit: "count",
2306
+ tags: { runtime: this.id, tile: node.id },
2307
+ });
2308
+ await this.invokeHooks("afterContentDetach", (hook) => hook.afterContentDetach?.(hookContext), node, content);
2309
+ } catch (error) {
2310
+ await this.reportError("content.detach", error, node, content);
2311
+ }
2312
+ }
2313
+ }
2314
+ node.selected = false;
2315
+ const context: ITileHookContext<TSpatial, TContentHandle, TGlyphHandle> = { runtimeId: this.id, tile: node };
2316
+ await this.invokeHooks("onTileDeselected", (hook) => hook.onTileDeselected?.(context), node);
2317
+ this.events.emit({ type: "tile-deselected", tile: node });
2318
+ }
2319
+
2320
+ protected async resolveMetadata(
2321
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
2322
+ content?: IContent,
2323
+ features?: IRuntimeContent<TContentHandle>["featureMetadata"],
2324
+ ): Promise<IMetadataSnapshot> {
2325
+ const runtimeContent = content ? node.contents.find((candidate) => candidate.descriptor === content) : undefined;
2326
+ const existingHandle = runtimeContent?.metadataHandle ?? node.metadataHandle;
2327
+ const existing = this.metadataStore.tryGet(existingHandle);
2328
+ if (existing) return existing;
2329
+ node.metadataState = TileMetadataState.Resolving;
2330
+ const tileContext: ITileHookContext<TSpatial, TContentHandle, TGlyphHandle> = { runtimeId: this.id, tile: node };
2331
+ await this.invokeHooks("beforeMetadataResolve", (hook) => hook.beforeMetadataResolve?.(tileContext), node);
2332
+ const ancestors: IMetadataAncestorInput[] = [];
2333
+ let parent = node.parent;
2334
+ while (parent) {
2335
+ ancestors.unshift({ id: parent.id, tile: parent.source, document: parent.document.metadata });
2336
+ parent = parent.parent;
2337
+ }
2338
+ let snapshot: IMetadataSnapshot;
2339
+ try {
2340
+ snapshot = this.metadataResolver.resolve({
2341
+ document: node.document.metadata,
2342
+ tileId: node.id,
2343
+ tile: node.source,
2344
+ ancestors,
2345
+ ...(node.implicit?.subtree.loaded?.subtree.subtreeMetadata
2346
+ ? {
2347
+ subtree: {
2348
+ id: node.implicit.subtree.uri,
2349
+ entity: node.implicit.subtree.loaded.subtree.subtreeMetadata,
2350
+ documentUri: node.implicit.subtree.uri,
2351
+ },
2352
+ }
2353
+ : {}),
2354
+ ...(content ? { content } : {}),
2355
+ ...(features ? { features } : {}),
2356
+ });
2357
+ } catch (error) {
2358
+ node.metadataState = TileMetadataState.Failed;
2359
+ throw error;
2360
+ }
2361
+ const metadataHandle = this.metadataStore.register(snapshot);
2362
+ if (content) {
2363
+ if (runtimeContent) {
2364
+ runtimeContent.metadataHandle = metadataHandle;
2365
+ if (features && features.length > 0) runtimeContent.featureMetadataHandle = metadataHandle;
2366
+ }
2367
+ } else {
2368
+ node.metadataHandle = metadataHandle;
2369
+ }
2370
+ node.metadataState = TileMetadataState.Ready;
2371
+ for (const diagnostic of snapshot.diagnostics) {
2372
+ this.recordMetric({
2373
+ name: "metadata.diagnostic",
2374
+ value: 1,
2375
+ unit: "count",
2376
+ tags: { runtime: this.id, tile: node.id, code: diagnostic.code, severity: diagnostic.severity },
2377
+ });
2378
+ }
2379
+ const hookContext: IMetadataHookContext<TSpatial, TContentHandle, TGlyphHandle> = { ...tileContext, snapshot };
2380
+ await this.invokeHooks("afterMetadataResolve", (hook) => hook.afterMetadataResolve?.(hookContext), node);
2381
+ this.events.emit({ type: "metadata-resolved", tile: node, snapshot });
2382
+ return snapshot;
2383
+ }
2384
+
2385
+ private async initializeRoot(): Promise<void> {
2386
+ const hookContext: ITilesetLoadHookContext = { runtimeId: this.id, uri: this.uri };
2387
+ await this.invokeHooks("beforeTilesetLoad", (hook) => hook.beforeTilesetLoad?.(hookContext));
2388
+ const startedAt = this.startTiming();
2389
+ try {
2390
+ const loaded = await this.adapter.tilesets.load({ uri: this.uri, signal: this.lifecycleController.signal });
2391
+ const document = await this.createDocument(this.id, this.uri, loaded);
2392
+ this.rootDocument = document;
2393
+ this.rootNode = this.createNode(document.tileset.root, document, undefined, "root");
2394
+ this.recordMetric({
2395
+ name: "tileset.load",
2396
+ value: this.elapsed(startedAt),
2397
+ unit: "millisecond",
2398
+ tags: { runtime: this.id, document: this.uri },
2399
+ });
2400
+ const loadedContext: ITilesetLoadedHookContext = { ...hookContext, loaded, document };
2401
+ await this.invokeHooks("afterTilesetLoad", (hook) => hook.afterTilesetLoad?.(loadedContext));
2402
+ this.events.emit({ type: "tileset-ready", document });
2403
+ const cameraSubscription = this.adapter.camera?.subscribe((camera) => {
2404
+ this.onCameraChanged(camera);
2405
+ void this.processFrame().catch((error) => this.reportError("camera.update", error));
2406
+ });
2407
+ if (cameraSubscription) this.cameraSubscription = cameraSubscription;
2408
+ const currentCamera = this.adapter.camera?.current?.();
2409
+ if (currentCamera !== undefined)
2410
+ queueMicrotask(() => void this.update(currentCamera).catch((error) => this.reportError("camera.update", error)));
2411
+ } catch (error) {
2412
+ await this.reportError("tileset.load", error);
2413
+ throw error;
2414
+ }
2415
+ }
2416
+
2417
+ private async createDocument(id: string, uri: string, loaded: ILoadedTileset): Promise<IRuntimeTilesetDocument> {
2418
+ const baseUri = loaded.baseUri ?? this.uriResolver.baseOf(uri);
2419
+ const diagnostics: IMetadataDiagnostic[] = [];
2420
+ let schema: IMetadataSchema | undefined = loaded.tileset.schema;
2421
+ let schemaUri: string | undefined;
2422
+ if (loaded.tileset.schemaUri) {
2423
+ schemaUri = this.uriResolver.resolve(loaded.tileset.schemaUri, baseUri);
2424
+ if (this.adapter.metadataSchemas) {
2425
+ try {
2426
+ schema = await this.adapter.metadataSchemas.load({
2427
+ uri: schemaUri,
2428
+ documentUri: uri,
2429
+ signal: this.lifecycleController.signal,
2430
+ });
2431
+ } catch (error) {
2432
+ diagnostics.push({
2433
+ code: "METADATA_SCHEMA_LOAD_FAILED",
2434
+ severity: "error",
2435
+ message: `Could not load metadata schema "${schemaUri}": ${String(error)}`,
2436
+ path: "$.schemaUri",
2437
+ documentUri: uri,
2438
+ });
2439
+ }
2440
+ } else {
2441
+ diagnostics.push({
2442
+ code: "METADATA_SCHEMA_LOADER_MISSING",
2443
+ severity: "warning",
2444
+ message: `A metadata schema loader is required for "${schemaUri}".`,
2445
+ path: "$.schemaUri",
2446
+ documentUri: uri,
2447
+ });
2448
+ }
2449
+ }
2450
+ const metadata = {
2451
+ uri,
2452
+ tileset: loaded.tileset,
2453
+ ...(schema ? { schema } : {}),
2454
+ ...(schemaUri ? { schemaUri } : {}),
2455
+ diagnostics,
2456
+ };
2457
+ return {
2458
+ id,
2459
+ uri,
2460
+ baseUri,
2461
+ tileset: loaded.tileset,
2462
+ metadata,
2463
+ };
2464
+ }
2465
+
2466
+ private createNode(
2467
+ tile: ITile,
2468
+ document: IRuntimeTilesetDocument,
2469
+ parent: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle> | undefined,
2470
+ segment: string,
2471
+ implicit?: IRuntimeImplicitTile,
2472
+ ): IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle> {
2473
+ const id = parent ? `${parent.id}/${segment}` : `${this.id}/${segment}`;
2474
+ let source = tile;
2475
+ let implicitState = implicit;
2476
+ if (tile.implicitTiling && !implicitState) {
2477
+ const contentTemplates = tile.contents ? [...tile.contents] : tile.content ? [tile.content] : [];
2478
+ const context: IRuntimeImplicitContext = {
2479
+ id,
2480
+ rootTile: tile,
2481
+ implicitTiling: tile.implicitTiling,
2482
+ contentTemplates,
2483
+ };
2484
+ const coordinates: IImplicitCoordinates = {
2485
+ level: 0,
2486
+ x: 0,
2487
+ y: 0,
2488
+ ...(tile.implicitTiling.subdivisionScheme === "OCTREE" ? { z: 0 } : {}),
2489
+ };
2490
+ const subtree = this.createImplicitSubtree(context, coordinates, document);
2491
+ implicitState = {
2492
+ context,
2493
+ coordinates,
2494
+ localCoordinates: coordinates,
2495
+ subtree,
2496
+ childrenMaterialized: false,
2497
+ metadataApplied: false,
2498
+ };
2499
+ source = this.createImplicitTileSource(implicitState, document, true);
2500
+ }
2501
+ const spatial = this.adapter.spatial.derive({
2502
+ tile: source,
2503
+ ...(parent ? { parent: parent.spatial } : {}),
2504
+ ...(implicitState?.heightRange ? { heightRange: implicitState.heightRange } : {}),
2505
+ });
2506
+ const descriptors = implicitState ? [] : source.contents ? [...source.contents] : source.content ? [source.content] : [];
2507
+ const refinementMode =
2508
+ source.refine === "ADD"
2509
+ ? TileRefinementMode.Add
2510
+ : source.refine === "REPLACE"
2511
+ ? TileRefinementMode.Replace
2512
+ : (parent?.refinementMode ?? TileRefinementMode.Replace);
2513
+ const contents = descriptors.map(
2514
+ (descriptor, index) =>
2515
+ new Tile3DContent<TContentHandle>(
2516
+ `${id}/content-${index}`,
2517
+ descriptor,
2518
+ this.uriResolver.resolve(descriptor.uri, document.baseUri),
2519
+ this.frame,
2520
+ ),
2521
+ );
2522
+ const node = new Tile3D<TSpatial, TContentHandle, TGlyphHandle>({
2523
+ id,
2524
+ source,
2525
+ document,
2526
+ ...(parent ? { parent } : {}),
2527
+ ...(implicitState ? { implicit: implicitState } : {}),
2528
+ depth: parent ? parent.depth + 1 : 0,
2529
+ refinementMode,
2530
+ spatial,
2531
+ contents,
2532
+ frame: this.frame,
2533
+ });
2534
+ this.nodes.set(id, node);
2535
+ if (implicitState?.subtree.status === TileReadinessState.Ready) this.applyImplicitContents(node);
2536
+ for (let index = 0; index < (source.children?.length ?? 0); index++) {
2537
+ const child = source.children?.[index];
2538
+ if (child) node.children.push(this.createNode(child, document, node, String(index)));
2539
+ }
2540
+ return node;
2541
+ }
2542
+
2543
+ private createImplicitSubtree(
2544
+ context: IRuntimeImplicitContext,
2545
+ coordinates: IImplicitCoordinates,
2546
+ document: IRuntimeTilesetDocument,
2547
+ ): IRuntimeImplicitSubtree {
2548
+ const reference = expandImplicitTemplate(context.implicitTiling.subtrees.uri, coordinates);
2549
+ return {
2550
+ uri: this.uriResolver.resolve(reference, document.baseUri),
2551
+ coordinates,
2552
+ status: TileReadinessState.Idle,
2553
+ attempts: 0,
2554
+ estimatedBytes: 0,
2555
+ lastTouchedFrame: this.frame,
2556
+ };
2557
+ }
2558
+
2559
+ private createImplicitTileSource(implicit: IRuntimeImplicitTile, document: IRuntimeTilesetDocument, root = false): ITile {
2560
+ const computed = computeImplicitTile(implicit.context.rootTile, implicit.context.implicitTiling, implicit.coordinates);
2561
+ const override = this.implicitResolver(implicit.context)?.resolve({
2562
+ documentUri: document.uri,
2563
+ rootTile: implicit.context.rootTile,
2564
+ implicitTiling: implicit.context.implicitTiling,
2565
+ coordinates: implicit.coordinates,
2566
+ computedBoundingVolume: computed.boundingVolume,
2567
+ computedGeometricError: computed.geometricError,
2568
+ computedContents: computed.contents,
2569
+ });
2570
+ if (override?.heightRange) implicit.heightRange = override.heightRange;
2571
+ else delete implicit.heightRange;
2572
+ return {
2573
+ boundingVolume: override?.boundingVolume ?? computed.boundingVolume,
2574
+ geometricError: override?.geometricError ?? computed.geometricError,
2575
+ refine: implicit.context.rootTile.refine ?? "REPLACE",
2576
+ ...(root && implicit.context.rootTile.transform ? { transform: implicit.context.rootTile.transform } : {}),
2577
+ ...(override?.metadata ? { metadata: override.metadata } : {}),
2578
+ };
2579
+ }
2580
+
2581
+ private implicitContents(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): readonly IContent[] {
2582
+ const implicit = node.implicit;
2583
+ if (!implicit) return [];
2584
+ const computed = computeImplicitTile(implicit.context.rootTile, implicit.context.implicitTiling, implicit.coordinates);
2585
+ const override = this.implicitResolver(implicit.context)?.resolve({
2586
+ documentUri: node.document.uri,
2587
+ rootTile: implicit.context.rootTile,
2588
+ implicitTiling: implicit.context.implicitTiling,
2589
+ coordinates: implicit.coordinates,
2590
+ computedBoundingVolume: computed.boundingVolume,
2591
+ computedGeometricError: computed.geometricError,
2592
+ computedContents: computed.contents,
2593
+ });
2594
+ return override?.contents ?? computed.contents;
2595
+ }
2596
+
2597
+ private applyImplicitContents(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): void {
2598
+ const implicit = node.implicit;
2599
+ const availability = implicit?.subtree.availability;
2600
+ const loaded = implicit?.subtree.loaded;
2601
+ if (!implicit || !availability || !loaded || node.contents.length > 0) return;
2602
+ const decoded = this.adapter.implicitMetadata?.decode({
2603
+ loaded,
2604
+ availability,
2605
+ ...(node.document.metadata.schema ? { schema: node.document.metadata.schema } : {}),
2606
+ implicitTiling: implicit.context.implicitTiling,
2607
+ coordinates: implicit.coordinates,
2608
+ localCoordinates: implicit.localCoordinates,
2609
+ contentCount: implicit.context.contentTemplates.length,
2610
+ });
2611
+ if (!implicit.metadataApplied) {
2612
+ if (decoded?.tileMetadata) node.source.metadata = decoded.tileMetadata;
2613
+ implicit.metadataApplied = true;
2614
+ }
2615
+ const available = this.implicitContents(node)
2616
+ .map((descriptor, index) => ({
2617
+ descriptor: decoded?.contentMetadata?.[index] ? { ...descriptor, metadata: decoded.contentMetadata[index] } : descriptor,
2618
+ index,
2619
+ }))
2620
+ .filter(({ index }) => availability.isContentAvailable(index, implicit.localCoordinates));
2621
+ if (available.length === 0) return;
2622
+ if (implicit.context.contentTemplates.length === 1) node.source.content = available[0]!.descriptor;
2623
+ else node.source.contents = available.map(({ descriptor }) => descriptor) as [IContent, ...IContent[]];
2624
+ for (const { descriptor, index } of available) {
2625
+ node.contents.push(
2626
+ new Tile3DContent<TContentHandle>(
2627
+ `${node.id}/content-${index}`,
2628
+ descriptor,
2629
+ this.uriResolver.resolve(descriptor.uri, node.document.baseUri),
2630
+ this.frame,
2631
+ ),
2632
+ );
2633
+ }
2634
+ this.refreshNodeReadiness(node);
2635
+ }
2636
+
2637
+ private requestImplicitSubtree(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>, priority: number): void {
2638
+ const implicit = node.implicit;
2639
+ if (!implicit) return;
2640
+ const subtree = implicit.subtree;
2641
+ const key = `subtree:${implicit.context.id}:${subtree.coordinates.level}:${subtree.coordinates.x}:${subtree.coordinates.y}:${subtree.coordinates.z ?? 0}`;
2642
+ // A waiting subtree follows the priority of the current frame, like contents: the view outranks its periphery.
2643
+ if (subtree.status === TileReadinessState.Queued) this.followQueuedPriority(key, priority);
2644
+ if (
2645
+ subtree.status !== TileReadinessState.Idle &&
2646
+ subtree.status !== TileReadinessState.Failed &&
2647
+ subtree.status !== TileReadinessState.Cancelled
2648
+ )
2649
+ return;
2650
+ if (subtree.attempts >= this.maxLoadAttempts) return;
2651
+ subtree.status = TileReadinessState.Queued;
2652
+ subtree.lastTouchedFrame = this.frame;
2653
+ this.events.emit({ type: "subtree-state", tile: node, subtree });
2654
+ this.scheduler.enqueue(key, priority, async (signal) => {
2655
+ const startedAt = this.startTiming();
2656
+ subtree.status = TileReadinessState.Preparing;
2657
+ subtree.attempts++;
2658
+ this.events.emit({ type: "subtree-state", tile: node, subtree });
2659
+ const hookContext: ISubtreeHookContext<TSpatial, TContentHandle, TGlyphHandle> = {
2660
+ runtimeId: this.id,
2661
+ tile: node,
2662
+ subtree,
2663
+ };
2664
+ try {
2665
+ await this.invokeHooks("beforeSubtreeLoad", (hook) => hook.beforeSubtreeLoad?.(hookContext), node);
2666
+ const loader = implicit.context.subtrees ?? this.adapter.subtrees;
2667
+ if (!loader) throw new Error(`Implicit subtree loader is required for ${subtree.uri}.`);
2668
+ const loaded = await loader.load({
2669
+ uri: subtree.uri,
2670
+ documentUri: node.document.uri,
2671
+ coordinates: subtree.coordinates,
2672
+ implicitTiling: implicit.context.implicitTiling,
2673
+ contentCount: implicit.context.contentTemplates.length,
2674
+ signal,
2675
+ });
2676
+ if (signal.aborted) {
2677
+ subtree.status = TileReadinessState.Cancelled;
2678
+ return;
2679
+ }
2680
+ const availability = new LoadedSubtreeAvailability(loaded, implicit.context.implicitTiling);
2681
+ const rootCoordinates: IImplicitCoordinates = {
2682
+ level: 0,
2683
+ x: 0,
2684
+ y: 0,
2685
+ ...(implicit.context.implicitTiling.subdivisionScheme === "OCTREE" ? { z: 0 } : {}),
2686
+ };
2687
+ if (!availability.isTileAvailable(rootCoordinates))
2688
+ throw new Error(`Subtree ${subtree.uri} does not make its root tile available.`);
2689
+ subtree.loaded = loaded;
2690
+ subtree.availability = availability;
2691
+ subtree.estimatedBytes = this.estimateSubtreeBytes(loaded);
2692
+ subtree.lastTouchedFrame = this.frame;
2693
+ subtree.status = TileReadinessState.Ready;
2694
+ delete subtree.error;
2695
+ this.applyImplicitContents(node);
2696
+ await this.invokeHooks("afterSubtreeLoad", (hook) => hook.afterSubtreeLoad?.({ ...hookContext, loaded }), node);
2697
+ this.recordMetric({
2698
+ name: "subtree.load",
2699
+ value: 1,
2700
+ unit: "count",
2701
+ tags: { runtime: this.id, tile: node.id },
2702
+ });
2703
+ this.recordDuration("subtree.load.duration", startedAt, { runtime: this.id, tile: node.id });
2704
+ this.recordMetric({
2705
+ name: "subtree.load.bytes",
2706
+ value: subtree.estimatedBytes,
2707
+ unit: "byte",
2708
+ tags: { runtime: this.id, tile: node.id },
2709
+ });
2710
+ } catch (error) {
2711
+ subtree.error = error;
2712
+ subtree.status = signal.aborted ? TileReadinessState.Cancelled : TileReadinessState.Failed;
2713
+ await this.reportError("subtree.load", error, node);
2714
+ } finally {
2715
+ this.events.emit({ type: "subtree-state", tile: node, subtree });
2716
+ this.markDirty();
2717
+ }
2718
+ });
2719
+ }
2720
+
2721
+ private materializeImplicitChildren(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): void {
2722
+ const implicit = node.implicit;
2723
+ if (
2724
+ !implicit ||
2725
+ implicit.childrenMaterialized ||
2726
+ implicit.subtree.status !== TileReadinessState.Ready ||
2727
+ !implicit.subtree.availability
2728
+ )
2729
+ return;
2730
+ implicit.subtree.lastTouchedFrame = this.frame;
2731
+ implicit.childrenMaterialized = true;
2732
+ const tiling = implicit.context.implicitTiling;
2733
+ if (implicit.coordinates.level + 1 >= tiling.availableLevels) return;
2734
+ const childCount = implicitBranchingFactor(tiling);
2735
+ for (let index = 0; index < childCount; index++) {
2736
+ const coordinates = implicitChildCoordinates(implicit.coordinates, index, tiling.subdivisionScheme);
2737
+ const localCoordinates = implicitLocalCoordinates(coordinates, implicit.subtree.coordinates);
2738
+ const subtreeRoot = localCoordinates.level >= tiling.subtreeLevels;
2739
+ const available = subtreeRoot
2740
+ ? implicit.subtree.availability!.isChildSubtreeAvailable(localCoordinates)
2741
+ : implicit.subtree.availability!.isTileAvailable(localCoordinates);
2742
+ if (!available) continue;
2743
+ const graft = this.implicitResolver(implicit.context)?.subtreeAt?.({
2744
+ documentUri: node.document.uri,
2745
+ rootTile: implicit.context.rootTile,
2746
+ implicitTiling: tiling,
2747
+ coordinates,
2748
+ });
2749
+ if (graft) {
2750
+ node.children.push(this.createGraftedNode(node, graft, `implicit-${index}`));
2751
+ continue;
2752
+ }
2753
+ let subtree = implicit.subtree;
2754
+ let childLocal = localCoordinates;
2755
+ if (subtreeRoot) {
2756
+ subtree = this.createImplicitSubtree(implicit.context, coordinates, node.document);
2757
+ childLocal = {
2758
+ level: 0,
2759
+ x: 0,
2760
+ y: 0,
2761
+ ...(tiling.subdivisionScheme === "OCTREE" ? { z: 0 } : {}),
2762
+ };
2763
+ }
2764
+ const childImplicit: IRuntimeImplicitTile = {
2765
+ context: implicit.context,
2766
+ coordinates,
2767
+ localCoordinates: childLocal,
2768
+ subtree,
2769
+ childrenMaterialized: false,
2770
+ metadataApplied: false,
2771
+ };
2772
+ const source = this.createImplicitTileSource(childImplicit, node.document);
2773
+ node.children.push(this.createNode(source, node.document, node, `implicit-${index}`, childImplicit));
2774
+ }
2775
+ }
2776
+
2777
+ /** Resolver of the tiles of an implicit context: the resolver of its registered subtree, or that of the adapter. */
2778
+ private implicitResolver(context: IRuntimeImplicitContext): IImplicitTileResolver | undefined {
2779
+ return context.resolver ?? this.adapter.implicitTiles;
2780
+ }
2781
+
2782
+ /**
2783
+ * Creates the root of a registered implicit subtree in place of an implicit tile: a new implicit context with
2784
+ * the tiling, contents, resolver and subtree loader of the subtree, rooted at the tile.
2785
+ */
2786
+ private createGraftedNode(
2787
+ parent: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
2788
+ graft: IImplicitSubtreeGraft,
2789
+ segment: string,
2790
+ ): IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle> {
2791
+ const tiling = graft.tile.implicitTiling;
2792
+ if (!tiling) throw new Error(`The subtree registered under ${parent.id} has no implicitTiling.`);
2793
+ const context: IRuntimeImplicitContext = {
2794
+ id: `${parent.id}/${segment}`,
2795
+ rootTile: graft.tile,
2796
+ implicitTiling: tiling,
2797
+ contentTemplates: graft.tile.contents ? [...graft.tile.contents] : graft.tile.content ? [graft.tile.content] : [],
2798
+ ...(graft.resolver
2799
+ ? { resolver: graft.resolver }
2800
+ : parent.implicit?.context.resolver
2801
+ ? { resolver: parent.implicit.context.resolver }
2802
+ : {}),
2803
+ ...(graft.subtrees
2804
+ ? { subtrees: graft.subtrees }
2805
+ : parent.implicit?.context.subtrees
2806
+ ? { subtrees: parent.implicit.context.subtrees }
2807
+ : {}),
2808
+ };
2809
+ const coordinates: IImplicitCoordinates = {
2810
+ level: 0,
2811
+ x: 0,
2812
+ y: 0,
2813
+ ...(tiling.subdivisionScheme === "OCTREE" ? { z: 0 } : {}),
2814
+ };
2815
+ const implicit: IRuntimeImplicitTile = {
2816
+ context,
2817
+ coordinates,
2818
+ localCoordinates: coordinates,
2819
+ subtree: this.createImplicitSubtree(context, coordinates, parent.document),
2820
+ childrenMaterialized: false,
2821
+ metadataApplied: false,
2822
+ };
2823
+ const source = this.createImplicitTileSource(implicit, parent.document, true);
2824
+ return this.createNode(source, parent.document, parent, segment, implicit);
2825
+ }
2826
+
2827
+ private tileContext(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): ITileContext<TSpatial> {
2828
+ return {
2829
+ runtimeId: this.id,
2830
+ tileId: node.id,
2831
+ depth: node.depth,
2832
+ tile: node.source,
2833
+ document: node.document,
2834
+ spatial: node.spatial,
2835
+ ...(node.implicit ? { implicitCoordinates: node.implicit.coordinates } : {}),
2836
+ };
2837
+ }
2838
+
2839
+ private contentLoadContext(
2840
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
2841
+ content: IRuntimeContent<TContentHandle>,
2842
+ ): IContentLoadContext<TSpatial> {
2843
+ return {
2844
+ ...this.tileContext(node),
2845
+ contentId: content.id,
2846
+ content: content.descriptor,
2847
+ uri: content.uri,
2848
+ };
2849
+ }
2850
+
2851
+ private presentationContext(
2852
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
2853
+ content: IRuntimeContent<TContentHandle> & { handle: TContentHandle },
2854
+ metadata: IMetadataSnapshot,
2855
+ ): IContentPresentationContext<TSpatial, TContentHandle> {
2856
+ return { ...this.contentLoadContext(node, content), handle: content.handle, metadata };
2857
+ }
2858
+
2859
+ private pipelinePresentationContext(
2860
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
2861
+ contents: readonly (IRuntimeContent<TContentHandle> & { handle: TContentHandle })[],
2862
+ ): ITilePresentationContext<TSpatial, TContentHandle, TGlyphHandle> {
2863
+ return {
2864
+ runtimeId: this.id,
2865
+ tile: node,
2866
+ resources: contents.map((content) => ({
2867
+ content,
2868
+ handle: content.handle,
2869
+ metadataHandle: content.metadataHandle,
2870
+ })),
2871
+ tileMetadataHandle: node.metadataHandle,
2872
+ metadataStore: this.metadataStore,
2873
+ };
2874
+ }
2875
+
2876
+ private glyphContext(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): IGlyphPublicationContext<TSpatial, TContentHandle> {
2877
+ return {
2878
+ ...this.tileContext(node),
2879
+ metadata: node.metadataSnapshots,
2880
+ contentHandles: node.contents
2881
+ .filter(
2882
+ (content): content is IRuntimeContent<TContentHandle> & { handle: TContentHandle } =>
2883
+ content.attached && content.handle !== undefined,
2884
+ )
2885
+ .map((content) => content.handle),
2886
+ };
2887
+ }
2888
+
2889
+ private async revokeGlyphs(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): Promise<void> {
2890
+ if (!this.adapter.glyphs || node.glyphHandles.length === 0) return;
2891
+ const context: ITileHookContext<TSpatial, TContentHandle, TGlyphHandle> = { runtimeId: this.id, tile: node };
2892
+ await this.invokeHooks("beforeGlyphRevoke", (hook) => hook.beforeGlyphRevoke?.(context), node);
2893
+ try {
2894
+ await this.adapter.glyphs.revoke(node.glyphHandles, this.glyphContext(node));
2895
+ node.glyphHandles = [];
2896
+ await this.invokeHooks("afterGlyphRevoke", (hook) => hook.afterGlyphRevoke?.(context), node);
2897
+ } catch (error) {
2898
+ await this.reportError("glyph.revoke", error, node);
2899
+ }
2900
+ }
2901
+
2902
+ private async sweepCache(force = false): Promise<void> {
2903
+ if (!this.cacheOptions.enabled) return;
2904
+ const startedAt = this.startTiming();
2905
+ this.cacheCounters.sweeps++;
2906
+ await this.sweepContentCache(force);
2907
+ await this.sweepSubtreeCache(force);
2908
+ await this.sweepImplicitBranches(force);
2909
+ if (this.instrumentation.enabled) {
2910
+ const state = this.collectStatistics();
2911
+ this.recordMetric({ name: "cache.content.entries", value: state.contents.cached, unit: "count" });
2912
+ this.recordMetric({ name: "cache.content.cpu-bytes", value: state.contents.cpuBytes, unit: "byte" });
2913
+ this.recordMetric({ name: "cache.content.gpu-bytes", value: state.contents.gpuBytes, unit: "byte" });
2914
+ this.recordMetric({ name: "cache.subtree.entries", value: state.subtrees.cached, unit: "count" });
2915
+ this.recordMetric({ name: "cache.subtree.bytes", value: state.subtrees.bytes, unit: "byte" });
2916
+ }
2917
+ this.recordDuration("cache.sweep.duration", startedAt, { runtime: this.id });
2918
+ }
2919
+
2920
+ private async sweepContentCache(force: boolean): Promise<void> {
2921
+ const candidates: Array<IContentCacheEntry<TSpatial, TContentHandle, TGlyphHandle>> = [];
2922
+ let entries = 0;
2923
+ let cpuBytes = 0;
2924
+ let gpuBytes = 0;
2925
+ for (const node of this.nodes.values()) {
2926
+ for (const candidate of node.contents) {
2927
+ if (
2928
+ candidate.handle === undefined ||
2929
+ candidate.kind !== TileContentKind.Renderable ||
2930
+ candidate.status !== TileReadinessState.Ready
2931
+ )
2932
+ continue;
2933
+ entries++;
2934
+ cpuBytes += candidate.cost?.cpuBytes ?? 0;
2935
+ gpuBytes += candidate.cost?.gpuBytes ?? 0;
2936
+ // A ready but gated REPLACE-front tile is intentionally not
2937
+ // selected yet. It is nevertheless required for the atomic
2938
+ // swap and must not be evicted while the current traversal is
2939
+ // waiting for its siblings.
2940
+ if (node.selected || candidate.attached || this.replacementFrontNodes.has(node.id)) continue;
2941
+ // A resource can settle during an awaited phase of the same
2942
+ // traversal that requested it. Keep it until the next cut can
2943
+ // consume it, otherwise a tight cache budget causes an
2944
+ // immediate load, evict, reload loop.
2945
+ if (candidate.readyFrame === this.frame) continue;
2946
+ candidates.push({
2947
+ node,
2948
+ content: candidate as IRuntimeContent<TContentHandle> & { handle: TContentHandle },
2949
+ });
2950
+ }
2951
+ }
2952
+ candidates.sort((left, right) => left.content.lastTouchedFrame - right.content.lastTouchedFrame);
2953
+ const entryBudget = this.contentEntryBudget();
2954
+ for (const candidate of candidates) {
2955
+ const reason = this.contentEvictionReason(candidate.content, entries, cpuBytes, gpuBytes, force, entryBudget);
2956
+ if (!reason) continue;
2957
+ const releasedCpuBytes = candidate.content.cost?.cpuBytes ?? 0;
2958
+ const releasedGpuBytes = candidate.content.cost?.gpuBytes ?? 0;
2959
+ await this.evictContent(candidate.node, candidate.content, reason);
2960
+ entries--;
2961
+ cpuBytes -= releasedCpuBytes;
2962
+ gpuBytes -= releasedGpuBytes;
2963
+ }
2964
+ }
2965
+
2966
+ /** Records the start time of a frame and forgets the frames older than the cache retention. */
2967
+ private recordFrameTime(frame: number): void {
2968
+ const now = this.clock();
2969
+ this.frameTimes.set(frame, now);
2970
+ for (const [oldFrame, startedAt] of this.frameTimes) {
2971
+ if (now - startedAt <= this.cacheOptions.unusedRetentionMilliseconds) break;
2972
+ this.frameTimes.delete(oldFrame);
2973
+ }
2974
+ }
2975
+
2976
+ /**
2977
+ * Whether a resource last used in a frame has been unused for longer than the cache retention: the retention time,
2978
+ * or the deprecated frame count when the application set one. A frame no longer recorded is older than the
2979
+ * retention time.
2980
+ */
2981
+ private isUnusedTooLong(lastTouchedFrame: number): boolean {
2982
+ const frames = this.cacheOptions.unusedFrameRetention;
2983
+ if (frames !== undefined) return this.frame - lastTouchedFrame > frames;
2984
+ const touchedAt = this.frameTimes.get(lastTouchedFrame);
2985
+ return touchedAt === undefined || this.clock() - touchedAt > this.cacheOptions.unusedRetentionMilliseconds;
2986
+ }
2987
+
2988
+ /** Budget of content entries, grown to what the view selects when the budgets are adaptive. */
2989
+ private contentEntryBudget(): number {
2990
+ const { maxContentEntries, workingSetFactor } = this.cacheOptions;
2991
+ if (workingSetFactor <= 0) return maxContentEntries;
2992
+ let selected = 0;
2993
+ for (const node of this.nodes.values()) if (node.selected) selected++;
2994
+ return Math.max(maxContentEntries, selected * workingSetFactor);
2995
+ }
2996
+
2997
+ /** Budget of materialized tiles, grown to what the traversal visits when the budgets are adaptive. */
2998
+ private materializedTileBudget(): number {
2999
+ const { maxMaterializedTiles, workingSetFactor } = this.cacheOptions;
3000
+ if (workingSetFactor <= 0) return maxMaterializedTiles;
3001
+ let visited = 0;
3002
+ for (const node of this.nodes.values()) if (node.lastTouchedFrame === this.frame) visited++;
3003
+ return Math.max(maxMaterializedTiles, visited * workingSetFactor);
3004
+ }
3005
+
3006
+ private contentEvictionReason(
3007
+ content: IRuntimeContent<TContentHandle>,
3008
+ entries: number,
3009
+ cpuBytes: number,
3010
+ gpuBytes: number,
3011
+ force: boolean,
3012
+ entryBudget: number,
3013
+ ): RuntimeCacheEvictionReason | undefined {
3014
+ if (force || this.isUnusedTooLong(content.lastTouchedFrame)) return "stale";
3015
+ if (entries > entryBudget) return "entry-budget";
3016
+ if (cpuBytes > this.cacheOptions.maxContentCpuBytes) return "cpu-budget";
3017
+ if (gpuBytes > this.cacheOptions.maxContentGpuBytes) return "gpu-budget";
3018
+ return undefined;
3019
+ }
3020
+
3021
+ private async evictContent(
3022
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
3023
+ content: IRuntimeContent<TContentHandle> & { handle: TContentHandle },
3024
+ reason: RuntimeCacheEvictionReason,
3025
+ ): Promise<void> {
3026
+ const eviction: IRuntimeCacheEviction = {
3027
+ kind: "content",
3028
+ reason,
3029
+ tileId: node.id,
3030
+ resourceId: content.cacheKey ?? content.uri,
3031
+ releasedCpuBytes: content.cost?.cpuBytes ?? 0,
3032
+ releasedGpuBytes: content.cost?.gpuBytes ?? 0,
3033
+ releasedEntries: 1,
3034
+ };
3035
+ const hookContext: ICacheEvictionHookContext<TSpatial, TContentHandle, TGlyphHandle> = {
3036
+ runtimeId: this.id,
3037
+ eviction,
3038
+ tile: node,
3039
+ content,
3040
+ };
3041
+ await this.invokeHooks("beforeCacheEviction", (hook) => hook.beforeCacheEviction?.(hookContext), node, content);
3042
+ await this.disposeContentHandle(node, content);
3043
+ node.metadataSnapshots = node.metadataSnapshots.filter((snapshot) => snapshot.content !== content.descriptor);
3044
+ this.cacheCounters.contentEvictions++;
3045
+ this.cacheCounters.releasedCpuBytes += eviction.releasedCpuBytes;
3046
+ this.cacheCounters.releasedGpuBytes += eviction.releasedGpuBytes;
3047
+ this.events.emit({ type: "cache-eviction", eviction });
3048
+ this.recordMetric({
3049
+ name: "content.cache.evict",
3050
+ value: 1,
3051
+ unit: "count",
3052
+ tags: { runtime: this.id, tile: node.id, reason },
3053
+ });
3054
+ await this.invokeHooks("afterCacheEviction", (hook) => hook.afterCacheEviction?.(hookContext), node, content);
3055
+ }
3056
+
3057
+ private async sweepSubtreeCache(force: boolean): Promise<void> {
3058
+ const bySubtree = new Map<IRuntimeImplicitSubtree, ISubtreeCacheEntry<TSpatial, TContentHandle, TGlyphHandle>>();
3059
+ for (const node of this.nodes.values()) {
3060
+ const subtree = node.implicit?.subtree;
3061
+ if (!subtree) continue;
3062
+ const existing = bySubtree.get(subtree);
3063
+ if (existing) existing.users.push(node);
3064
+ else bySubtree.set(subtree, { node, subtree, users: [node] });
3065
+ }
3066
+ const loaded = [...bySubtree.values()].filter(
3067
+ (entry) => entry.subtree.status === TileReadinessState.Ready && entry.subtree.loaded !== undefined,
3068
+ );
3069
+ let entries = loaded.length;
3070
+ let bytes = loaded.reduce((total, entry) => total + entry.subtree.estimatedBytes, 0);
3071
+ const candidates = loaded
3072
+ .filter((entry) => !this.isSubtreeProtected(entry))
3073
+ .sort((left, right) => left.subtree.lastTouchedFrame - right.subtree.lastTouchedFrame);
3074
+ for (const candidate of candidates) {
3075
+ const stale = this.isUnusedTooLong(candidate.subtree.lastTouchedFrame);
3076
+ let reason: RuntimeCacheEvictionReason | undefined;
3077
+ if (force || stale) reason = "stale";
3078
+ else if (entries > this.cacheOptions.maxSubtreeEntries) reason = "entry-budget";
3079
+ else if (bytes > this.cacheOptions.maxSubtreeBytes) reason = "byte-budget";
3080
+ if (!reason) continue;
3081
+ const releasedBytes = candidate.subtree.estimatedBytes;
3082
+ await this.evictSubtree(candidate, reason);
3083
+ entries--;
3084
+ bytes -= releasedBytes;
3085
+ }
3086
+ }
3087
+
3088
+ private isSubtreeProtected(entry: ISubtreeCacheEntry<TSpatial, TContentHandle, TGlyphHandle>): boolean {
3089
+ if (entry.subtree.status === TileReadinessState.Queued || entry.subtree.status === TileReadinessState.Preparing) return true;
3090
+ return entry.users.some(
3091
+ (node) =>
3092
+ node.selected ||
3093
+ node.lastTouchedFrame === this.frame ||
3094
+ node.glyphHandles.length > 0 ||
3095
+ node.contents.some(
3096
+ (content) =>
3097
+ content.attached || content.status === TileReadinessState.Queued || content.status === TileReadinessState.Preparing,
3098
+ ),
3099
+ );
3100
+ }
3101
+
3102
+ private async evictSubtree(
3103
+ entry: ISubtreeCacheEntry<TSpatial, TContentHandle, TGlyphHandle>,
3104
+ reason: RuntimeCacheEvictionReason,
3105
+ ): Promise<void> {
3106
+ const eviction: IRuntimeCacheEviction = {
3107
+ kind: "subtree",
3108
+ reason,
3109
+ tileId: entry.node.id,
3110
+ resourceId: entry.subtree.uri,
3111
+ releasedCpuBytes: entry.subtree.estimatedBytes,
3112
+ releasedGpuBytes: 0,
3113
+ releasedEntries: 1,
3114
+ };
3115
+ const hookContext: ICacheEvictionHookContext<TSpatial, TContentHandle, TGlyphHandle> = {
3116
+ runtimeId: this.id,
3117
+ eviction,
3118
+ tile: entry.node,
3119
+ subtree: entry.subtree,
3120
+ };
3121
+ await this.invokeHooks("beforeCacheEviction", (hook) => hook.beforeCacheEviction?.(hookContext), entry.node);
3122
+ delete entry.subtree.loaded;
3123
+ delete entry.subtree.availability;
3124
+ delete entry.subtree.error;
3125
+ entry.subtree.status = TileReadinessState.Idle;
3126
+ entry.subtree.attempts = 0;
3127
+ entry.subtree.estimatedBytes = 0;
3128
+ this.cacheCounters.subtreeEvictions++;
3129
+ this.cacheCounters.releasedCpuBytes += eviction.releasedCpuBytes;
3130
+ this.events.emit({ type: "cache-eviction", eviction });
3131
+ this.recordMetric({
3132
+ name: "subtree.cache.evict",
3133
+ value: 1,
3134
+ unit: "count",
3135
+ tags: { runtime: this.id, tile: entry.node.id, reason },
3136
+ });
3137
+ await this.invokeHooks("afterCacheEviction", (hook) => hook.afterCacheEviction?.(hookContext), entry.node);
3138
+ }
3139
+
3140
+ private async sweepImplicitBranches(force: boolean): Promise<void> {
3141
+ const tileBudget = this.materializedTileBudget();
3142
+ const candidates = [...this.nodes.values()]
3143
+ .filter((node) => this.isImplicitBranchRoot(node))
3144
+ .sort((left, right) => {
3145
+ const age = this.oldestChildFrame(left) - this.oldestChildFrame(right);
3146
+ return age !== 0 ? age : right.depth - left.depth;
3147
+ });
3148
+ for (const parent of candidates) {
3149
+ if (!this.isImplicitBranchRoot(parent)) continue;
3150
+ const descendants = this.branchDescendants(parent);
3151
+ if (descendants.length === 0 || this.isBranchProtected(descendants)) continue;
3152
+ const stale = descendants.every((node) => this.isUnusedTooLong(node.lastTouchedFrame));
3153
+ let reason: RuntimeCacheEvictionReason | undefined;
3154
+ if (force || stale) reason = "stale";
3155
+ else if (this.nodes.size > tileBudget) reason = "node-budget";
3156
+ if (!reason) continue;
3157
+ await this.pruneImplicitBranch(parent, descendants, reason);
3158
+ }
3159
+ }
3160
+
3161
+ private isImplicitBranchRoot(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): boolean {
3162
+ const context = node.implicit?.context;
3163
+ return (
3164
+ context !== undefined &&
3165
+ node.implicit?.childrenMaterialized === true &&
3166
+ node.children.length > 0 &&
3167
+ node.children.every((child) => child.implicit?.context === context)
3168
+ );
3169
+ }
3170
+
3171
+ private oldestChildFrame(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): number {
3172
+ return node.children.reduce((oldest, child) => Math.min(oldest, child.lastTouchedFrame), Number.POSITIVE_INFINITY);
3173
+ }
3174
+
3175
+ private branchDescendants(
3176
+ parent: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
3177
+ ): Array<IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>> {
3178
+ const descendants: Array<IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>> = [];
3179
+ const pending = [...parent.children];
3180
+ while (pending.length > 0) {
3181
+ const node = pending.pop();
3182
+ if (!node) continue;
3183
+ descendants.push(node);
3184
+ pending.push(...node.children);
3185
+ }
3186
+ return descendants;
3187
+ }
3188
+
3189
+ private isBranchProtected(nodes: readonly IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>[]): boolean {
3190
+ return nodes.some(
3191
+ (node) =>
3192
+ node.selected ||
3193
+ node.lastTouchedFrame === this.frame ||
3194
+ node.glyphHandles.length > 0 ||
3195
+ node.contents.some(
3196
+ (content) =>
3197
+ content.attached || content.status === TileReadinessState.Queued || content.status === TileReadinessState.Preparing,
3198
+ ),
3199
+ );
3200
+ }
3201
+
3202
+ private async pruneImplicitBranch(
3203
+ parent: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
3204
+ descendants: readonly IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>[],
3205
+ reason: RuntimeCacheEvictionReason,
3206
+ ): Promise<void> {
3207
+ const releasedCpuBytes = descendants.reduce(
3208
+ (total, node) => total + node.contents.reduce((sum, content) => sum + (content.cost?.cpuBytes ?? 0), 0),
3209
+ 0,
3210
+ );
3211
+ const releasedGpuBytes = descendants.reduce(
3212
+ (total, node) => total + node.contents.reduce((sum, content) => sum + (content.cost?.gpuBytes ?? 0), 0),
3213
+ 0,
3214
+ );
3215
+ const eviction: IRuntimeCacheEviction = {
3216
+ kind: "implicit-branch",
3217
+ reason,
3218
+ tileId: parent.id,
3219
+ resourceId: `${parent.id}/children`,
3220
+ releasedCpuBytes,
3221
+ releasedGpuBytes,
3222
+ releasedEntries: descendants.length,
3223
+ };
3224
+ const hookContext: ICacheEvictionHookContext<TSpatial, TContentHandle, TGlyphHandle> = {
3225
+ runtimeId: this.id,
3226
+ eviction,
3227
+ tile: parent,
3228
+ };
3229
+ await this.invokeHooks("beforeCacheEviction", (hook) => hook.beforeCacheEviction?.(hookContext), parent);
3230
+ for (const node of [...descendants].sort((left, right) => right.depth - left.depth)) {
3231
+ await this.disposeNodeContent(node);
3232
+ this.refiningNodes.delete(node.id);
3233
+ this.coarseningSince.delete(node.id);
3234
+ this.replacementFrontNodes.delete(node.id);
3235
+ this.nodes.delete(node.id);
3236
+ }
3237
+ parent.children = [];
3238
+ if (parent.implicit) parent.implicit.childrenMaterialized = false;
3239
+ this.cacheCounters.implicitBranchPrunes++;
3240
+ this.cacheCounters.prunedNodes += descendants.length;
3241
+ this.cacheCounters.releasedCpuBytes += releasedCpuBytes;
3242
+ this.cacheCounters.releasedGpuBytes += releasedGpuBytes;
3243
+ this.events.emit({ type: "cache-eviction", eviction });
3244
+ this.recordMetric({
3245
+ name: "tile.node.prune",
3246
+ value: descendants.length,
3247
+ unit: "count",
3248
+ tags: { runtime: this.id, tile: parent.id, reason },
3249
+ });
3250
+ await this.invokeHooks("afterCacheEviction", (hook) => hook.afterCacheEviction?.(hookContext), parent);
3251
+ }
3252
+
3253
+ private async disposeNodeContent(node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>): Promise<void> {
3254
+ for (const content of node.contents) {
3255
+ if (content.handle === undefined) continue;
3256
+ await this.disposeContentHandle(node, content as IRuntimeContent<TContentHandle> & { handle: TContentHandle });
3257
+ }
3258
+ }
3259
+
3260
+ private async disposeContentHandle(
3261
+ node: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
3262
+ content: IRuntimeContent<TContentHandle> & { handle: TContentHandle },
3263
+ ): Promise<void> {
3264
+ // A released content loads afresh: its pending reload is dropped.
3265
+ const refresh = this.refreshes.get(content);
3266
+ this.refreshes.delete(content);
3267
+ this.staleContents.delete(content);
3268
+ this.provisionalContents.delete(content);
3269
+ content.stale = false;
3270
+ if (refresh?.result?.kind === "renderable" && refresh.result.handle !== content.handle) {
3271
+ await this.releaseHandle(node, content, refresh.result.handle);
3272
+ }
3273
+ try {
3274
+ const presentationAdapter = this.adapter.presentation;
3275
+ const contentAdapter = this.adapter.content;
3276
+ if (presentationAdapter?.release) {
3277
+ await presentationAdapter.release(this.pipelinePresentationContext(node, [content]));
3278
+ } else if (contentAdapter?.dispose) {
3279
+ const snapshot =
3280
+ node.metadataSnapshots.find((candidate) => candidate.content === content.descriptor) ??
3281
+ (await this.resolveMetadata(node, content.descriptor));
3282
+ await contentAdapter.dispose(this.presentationContext(node, content, snapshot));
3283
+ }
3284
+ } catch (error) {
3285
+ await this.reportError("content.dispose", error, node, content);
3286
+ } finally {
3287
+ const releasedContent: IRuntimeContent<TContentHandle> = content;
3288
+ delete releasedContent.handle;
3289
+ delete releasedContent.featureMetadata;
3290
+ delete releasedContent.cacheKey;
3291
+ delete releasedContent.cost;
3292
+ delete releasedContent.error;
3293
+ this.metadataStore.release(releasedContent.metadataHandle);
3294
+ if (releasedContent.featureMetadataHandle !== releasedContent.metadataHandle) {
3295
+ this.metadataStore.release(releasedContent.featureMetadataHandle);
3296
+ }
3297
+ releasedContent.metadataHandle = NO_METADATA;
3298
+ releasedContent.featureMetadataHandle = NO_METADATA;
3299
+ releasedContent.status = TileReadinessState.Idle;
3300
+ releasedContent.kind = TileContentKind.Unknown;
3301
+ releasedContent.attempts = 0;
3302
+ releasedContent.attached = false;
3303
+ releasedContent.readyFrame = -1;
3304
+ this.refreshNodeReadiness(node);
3305
+ }
3306
+ }
3307
+
3308
+ private estimateSubtreeBytes(loaded: ILoadedImplicitSubtree): number {
3309
+ const bufferBytes = loaded.buffers?.reduce((total, buffer) => total + buffer.byteLength, 0) ?? 0;
3310
+ try {
3311
+ return bufferBytes + new TextEncoder().encode(JSON.stringify(loaded.subtree)).byteLength;
3312
+ } catch {
3313
+ return bufferBytes;
3314
+ }
3315
+ }
3316
+
3317
+ private collectStatistics(): IRuntimeStateStatistics {
3318
+ const nodes = [...this.nodes.values()];
3319
+ const nodeStatistics = {
3320
+ total: nodes.length,
3321
+ explicit: nodes.filter((node) => !node.implicit).length,
3322
+ implicit: nodes.filter((node) => node.implicit !== undefined).length,
3323
+ selected: nodes.filter((node) => node.selected).length,
3324
+ visible: nodes.filter((node) => node.visible).length,
3325
+ unbalanced: this.unbalancedCount,
3326
+ };
3327
+ const contentStatistics = {
3328
+ total: 0,
3329
+ idle: 0,
3330
+ queued: 0,
3331
+ loading: 0,
3332
+ ready: 0,
3333
+ error: 0,
3334
+ cancelled: 0,
3335
+ attached: 0,
3336
+ cached: 0,
3337
+ cpuBytes: 0,
3338
+ gpuBytes: 0,
3339
+ networkBytes: 0,
3340
+ };
3341
+ for (const node of nodes) {
3342
+ for (const content of node.contents) {
3343
+ contentStatistics.total++;
3344
+ switch (content.status) {
3345
+ case TileReadinessState.Idle:
3346
+ contentStatistics.idle++;
3347
+ break;
3348
+ case TileReadinessState.Queued:
3349
+ contentStatistics.queued++;
3350
+ break;
3351
+ case TileReadinessState.Preparing:
3352
+ contentStatistics.loading++;
3353
+ break;
3354
+ case TileReadinessState.Ready:
3355
+ contentStatistics.ready++;
3356
+ break;
3357
+ case TileReadinessState.Failed:
3358
+ contentStatistics.error++;
3359
+ break;
3360
+ case TileReadinessState.Cancelled:
3361
+ contentStatistics.cancelled++;
3362
+ break;
3363
+ }
3364
+ if (content.attached) contentStatistics.attached++;
3365
+ if (content.handle !== undefined) contentStatistics.cached++;
3366
+ contentStatistics.cpuBytes += content.cost?.cpuBytes ?? 0;
3367
+ contentStatistics.gpuBytes += content.cost?.gpuBytes ?? 0;
3368
+ contentStatistics.networkBytes += content.cost?.networkBytes ?? 0;
3369
+ }
3370
+ }
3371
+ const subtrees = new Set<IRuntimeImplicitSubtree>();
3372
+ for (const node of nodes) if (node.implicit) subtrees.add(node.implicit.subtree);
3373
+ const subtreeStatistics = {
3374
+ total: subtrees.size,
3375
+ idle: 0,
3376
+ queued: 0,
3377
+ loading: 0,
3378
+ ready: 0,
3379
+ error: 0,
3380
+ cancelled: 0,
3381
+ cached: 0,
3382
+ bytes: 0,
3383
+ };
3384
+ for (const subtree of subtrees) {
3385
+ switch (subtree.status) {
3386
+ case TileReadinessState.Idle:
3387
+ subtreeStatistics.idle++;
3388
+ break;
3389
+ case TileReadinessState.Queued:
3390
+ subtreeStatistics.queued++;
3391
+ break;
3392
+ case TileReadinessState.Preparing:
3393
+ subtreeStatistics.loading++;
3394
+ break;
3395
+ case TileReadinessState.Ready:
3396
+ subtreeStatistics.ready++;
3397
+ break;
3398
+ case TileReadinessState.Failed:
3399
+ subtreeStatistics.error++;
3400
+ break;
3401
+ case TileReadinessState.Cancelled:
3402
+ subtreeStatistics.cancelled++;
3403
+ break;
3404
+ }
3405
+ if (subtree.loaded) subtreeStatistics.cached++;
3406
+ subtreeStatistics.bytes += subtree.estimatedBytes;
3407
+ }
3408
+ return {
3409
+ frame: this.frame,
3410
+ pendingLoads: this.scheduler.size,
3411
+ nodes: nodeStatistics,
3412
+ contents: contentStatistics,
3413
+ subtrees: subtreeStatistics,
3414
+ cache: {
3415
+ enabled: this.cacheOptions.enabled,
3416
+ limits: { ...this.cacheOptions },
3417
+ ...this.cacheCounters,
3418
+ },
3419
+ };
3420
+ }
3421
+
3422
+ private startTiming(): number | undefined {
3423
+ return this.instrumentation.enabled ? performance.now() : undefined;
3424
+ }
3425
+
3426
+ private elapsed(startedAt: number | undefined): number {
3427
+ return startedAt === undefined ? 0 : performance.now() - startedAt;
3428
+ }
3429
+
3430
+ private recordDuration(name: IRuntimeMetric["name"], startedAt: number | undefined, tags?: IRuntimeMetric["tags"]): void {
3431
+ if (startedAt === undefined) return;
3432
+ this.recordMetric({ name, value: this.elapsed(startedAt), unit: "millisecond", ...(tags ? { tags } : {}) });
3433
+ }
3434
+
3435
+ private recordMetric(metric: IRuntimeMetric): void {
3436
+ if (!this.instrumentation.enabled) return;
3437
+ this.instrumentation.record(metric);
3438
+ try {
3439
+ this.adapter.telemetry?.record(metric);
3440
+ } catch {
3441
+ // Monitoring backends must not interrupt traversal or cache enforcement.
3442
+ }
3443
+ }
3444
+
3445
+ private markDirty(): void {
3446
+ if (!this.disposed) this.refreshNeeded = true;
3447
+ }
3448
+
3449
+ private async invokeHooks(
3450
+ phase: string,
3451
+ invoke: (hook: IRuntimeHooks<TCamera, TSpatial, TContentHandle, TGlyphHandle>) => HookResult | undefined,
3452
+ tile?: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
3453
+ content?: IRuntimeContent<TContentHandle>,
3454
+ ): Promise<void> {
3455
+ for (const hook of this.hooks) {
3456
+ try {
3457
+ await invoke(hook);
3458
+ } catch (error) {
3459
+ await this.reportError(`hook.${phase}`, error, tile, content, true);
3460
+ }
3461
+ }
3462
+ }
3463
+
3464
+ private async reportError(
3465
+ phase: string,
3466
+ error: unknown,
3467
+ tile?: IRuntimeTile<TSpatial, TContentHandle, TGlyphHandle>,
3468
+ content?: IRuntimeContent<TContentHandle>,
3469
+ fromHook = false,
3470
+ ): Promise<void> {
3471
+ this.events.emit({
3472
+ type: "error",
3473
+ phase,
3474
+ error,
3475
+ ...(tile ? { tileId: tile.id } : {}),
3476
+ ...(content ? { contentId: content.id } : {}),
3477
+ });
3478
+ this.recordMetric({
3479
+ name: "runtime.error",
3480
+ value: 1,
3481
+ unit: "count",
3482
+ tags: { runtime: this.id, phase, ...(tile ? { tile: tile.id } : {}) },
3483
+ });
3484
+ if (phase.startsWith("content.")) {
3485
+ this.recordMetric({
3486
+ name: "content.error",
3487
+ value: 1,
3488
+ unit: "count",
3489
+ tags: { runtime: this.id, phase, ...(tile ? { tile: tile.id } : {}) },
3490
+ });
3491
+ }
3492
+ if (fromHook) return;
3493
+ const context: IRuntimeErrorHookContext<TSpatial, TContentHandle, TGlyphHandle> = {
3494
+ runtimeId: this.id,
3495
+ phase,
3496
+ error,
3497
+ ...(tile ? { tile } : {}),
3498
+ ...(content ? { content } : {}),
3499
+ };
3500
+ for (const hook of this.hooks) {
3501
+ try {
3502
+ await hook.onError?.(context);
3503
+ } catch {
3504
+ // Error hooks are terminal observers. Their failures are ignored to avoid recursion.
3505
+ }
3506
+ }
3507
+ }
3508
+ }