@loaders.gl/tiles 4.2.0-alpha.4 → 4.2.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/constants.js +34 -32
  2. package/dist/dist.dev.js +679 -449
  3. package/dist/dist.min.js +9 -0
  4. package/dist/index.cjs +265 -326
  5. package/dist/index.cjs.map +7 -0
  6. package/dist/index.d.ts +10 -10
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +3 -1
  9. package/dist/tileset/format-3d-tiles/tileset-3d-traverser.d.ts +1 -1
  10. package/dist/tileset/format-3d-tiles/tileset-3d-traverser.d.ts.map +1 -1
  11. package/dist/tileset/format-3d-tiles/tileset-3d-traverser.js +45 -35
  12. package/dist/tileset/format-i3s/i3s-pending-tiles-register.js +38 -22
  13. package/dist/tileset/format-i3s/i3s-tile-manager.d.ts +1 -1
  14. package/dist/tileset/format-i3s/i3s-tile-manager.d.ts.map +1 -1
  15. package/dist/tileset/format-i3s/i3s-tile-manager.js +68 -69
  16. package/dist/tileset/format-i3s/i3s-tileset-traverser.d.ts +2 -2
  17. package/dist/tileset/format-i3s/i3s-tileset-traverser.d.ts.map +1 -1
  18. package/dist/tileset/format-i3s/i3s-tileset-traverser.js +79 -57
  19. package/dist/tileset/helpers/3d-tiles-options.d.ts +1 -1
  20. package/dist/tileset/helpers/3d-tiles-options.d.ts.map +1 -1
  21. package/dist/tileset/helpers/3d-tiles-options.js +3 -4
  22. package/dist/tileset/helpers/bounding-volume.js +269 -128
  23. package/dist/tileset/helpers/frame-state.d.ts +1 -1
  24. package/dist/tileset/helpers/frame-state.d.ts.map +1 -1
  25. package/dist/tileset/helpers/frame-state.js +114 -95
  26. package/dist/tileset/helpers/i3s-lod.d.ts +2 -2
  27. package/dist/tileset/helpers/i3s-lod.d.ts.map +1 -1
  28. package/dist/tileset/helpers/i3s-lod.js +68 -39
  29. package/dist/tileset/helpers/tiles-3d-lod.js +97 -85
  30. package/dist/tileset/helpers/transform-utils.js +45 -44
  31. package/dist/tileset/helpers/zoom.d.ts +1 -1
  32. package/dist/tileset/helpers/zoom.d.ts.map +1 -1
  33. package/dist/tileset/helpers/zoom.js +70 -40
  34. package/dist/tileset/tile-3d.d.ts +7 -6
  35. package/dist/tileset/tile-3d.d.ts.map +1 -1
  36. package/dist/tileset/tile-3d.js +608 -399
  37. package/dist/tileset/tileset-3d.d.ts +7 -6
  38. package/dist/tileset/tileset-3d.d.ts.map +1 -1
  39. package/dist/tileset/tileset-3d.js +739 -597
  40. package/dist/tileset/tileset-cache.d.ts +2 -2
  41. package/dist/tileset/tileset-cache.d.ts.map +1 -1
  42. package/dist/tileset/tileset-cache.js +65 -48
  43. package/dist/tileset/tileset-traverser.d.ts +3 -3
  44. package/dist/tileset/tileset-traverser.d.ts.map +1 -1
  45. package/dist/tileset/tileset-traverser.js +282 -220
  46. package/dist/types.js +0 -1
  47. package/dist/utils/doubly-linked-list-node.js +17 -9
  48. package/dist/utils/doubly-linked-list.d.ts +1 -1
  49. package/dist/utils/doubly-linked-list.d.ts.map +1 -1
  50. package/dist/utils/doubly-linked-list.js +83 -56
  51. package/dist/utils/managed-array.js +140 -76
  52. package/package.json +10 -9
  53. package/src/tileset/tile-3d.ts +1 -1
  54. package/src/tileset/tileset-3d.ts +1 -1
  55. package/dist/constants.js.map +0 -1
  56. package/dist/index.js.map +0 -1
  57. package/dist/tileset/format-3d-tiles/tileset-3d-traverser.js.map +0 -1
  58. package/dist/tileset/format-i3s/i3s-pending-tiles-register.js.map +0 -1
  59. package/dist/tileset/format-i3s/i3s-tile-manager.js.map +0 -1
  60. package/dist/tileset/format-i3s/i3s-tileset-traverser.js.map +0 -1
  61. package/dist/tileset/helpers/3d-tiles-options.js.map +0 -1
  62. package/dist/tileset/helpers/bounding-volume.js.map +0 -1
  63. package/dist/tileset/helpers/frame-state.js.map +0 -1
  64. package/dist/tileset/helpers/i3s-lod.js.map +0 -1
  65. package/dist/tileset/helpers/tiles-3d-lod.js.map +0 -1
  66. package/dist/tileset/helpers/transform-utils.js.map +0 -1
  67. package/dist/tileset/helpers/zoom.js.map +0 -1
  68. package/dist/tileset/tile-3d.js.map +0 -1
  69. package/dist/tileset/tileset-3d.js.map +0 -1
  70. package/dist/tileset/tileset-cache.js.map +0 -1
  71. package/dist/tileset/tileset-traverser.js.map +0 -1
  72. package/dist/types.js.map +0 -1
  73. package/dist/utils/doubly-linked-list-node.js.map +0 -1
  74. package/dist/utils/doubly-linked-list.js.map +0 -1
  75. package/dist/utils/managed-array.js.map +0 -1
@@ -1,3 +1,7 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) vis.gl contributors
3
+ // This file is derived from the Cesium code base under Apache 2 license
4
+ // See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md
1
5
  import { Matrix4, Vector3 } from '@math.gl/core';
2
6
  import { Ellipsoid } from '@math.gl/geospatial';
3
7
  import { Stats } from '@probe.gl/stats';
@@ -9,36 +13,37 @@ import { getZoomFromBoundingVolume, getZoomFromExtent, getZoomFromFullExtent } f
9
13
  import { Tile3D } from "./tile-3d.js";
10
14
  import { TILESET_TYPE } from "../constants.js";
11
15
  import { TilesetTraverser } from "./tileset-traverser.js";
16
+ // TODO - these should be moved into their respective modules
12
17
  import { Tileset3DTraverser } from "./format-3d-tiles/tileset-3d-traverser.js";
13
18
  import { I3STilesetTraverser } from "./format-i3s/i3s-tileset-traverser.js";
14
19
  const DEFAULT_PROPS = {
15
- description: '',
16
- ellipsoid: Ellipsoid.WGS84,
17
- modelMatrix: new Matrix4(),
18
- throttleRequests: true,
19
- maxRequests: 64,
20
- maximumMemoryUsage: 32,
21
- memoryCacheOverflow: 1,
22
- maximumTilesSelected: 0,
23
- debounceTime: 0,
24
- onTileLoad: () => {},
25
- onTileUnload: () => {},
26
- onTileError: () => {},
27
- onTraversalComplete: selectedTiles => selectedTiles,
28
- contentLoader: undefined,
29
- viewDistanceScale: 1.0,
30
- maximumScreenSpaceError: 8,
31
- memoryAdjustedScreenSpaceError: false,
32
- loadTiles: true,
33
- updateTransforms: true,
34
- viewportTraversersMap: null,
35
- loadOptions: {
36
- fetch: {}
37
- },
38
- attributions: [],
39
- basePath: '',
40
- i3s: {}
20
+ description: '',
21
+ ellipsoid: Ellipsoid.WGS84,
22
+ modelMatrix: new Matrix4(),
23
+ throttleRequests: true,
24
+ maxRequests: 64,
25
+ /** Default memory values optimized for viewing mesh-based 3D Tiles on both mobile and desktop devices */
26
+ maximumMemoryUsage: 32,
27
+ memoryCacheOverflow: 1,
28
+ maximumTilesSelected: 0,
29
+ debounceTime: 0,
30
+ onTileLoad: () => { },
31
+ onTileUnload: () => { },
32
+ onTileError: () => { },
33
+ onTraversalComplete: (selectedTiles) => selectedTiles,
34
+ contentLoader: undefined,
35
+ viewDistanceScale: 1.0,
36
+ maximumScreenSpaceError: 8,
37
+ memoryAdjustedScreenSpaceError: false,
38
+ loadTiles: true,
39
+ updateTransforms: true,
40
+ viewportTraversersMap: null,
41
+ loadOptions: { fetch: {} },
42
+ attributions: [],
43
+ basePath: '',
44
+ i3s: {}
41
45
  };
46
+ // Tracked Stats
42
47
  const TILES_TOTAL = 'Tiles In Tileset(s)';
43
48
  const TILES_IN_MEMORY = 'Tiles In Memory';
44
49
  const TILES_IN_VIEW = 'Tiles In View';
@@ -50,578 +55,715 @@ const TILES_LOAD_FAILED = 'Failed Tile Loads';
50
55
  const POINTS_COUNT = 'Points/Vertices';
51
56
  const TILES_GPU_MEMORY = 'Tile Memory Use';
52
57
  const MAXIMUM_SSE = 'Maximum Screen Space Error';
58
+ /**
59
+ * The Tileset loading and rendering flow is as below,
60
+ * A rendered (i.e. deck.gl `Tile3DLayer`) triggers `tileset.update()` after a `tileset` is loaded
61
+ * `tileset` starts traversing the tile tree and update `requestTiles` (tiles of which content need
62
+ * to be fetched) and `selectedTiles` (tiles ready for rendering under the current viewport).
63
+ * `Tile3DLayer` will update rendering based on `selectedTiles`.
64
+ * `Tile3DLayer` also listens to `onTileLoad` callback and trigger another round of `update and then traversal`
65
+ * when new tiles are loaded.
66
+
67
+ * As I3S tileset have stored `tileHeader` file (metadata) and tile content files (geometry, texture, ...) separately.
68
+ * During each traversal, it issues `tilHeader` requests if that `tileHeader` is not yet fetched,
69
+ * after the tile header is fulfilled, it will resume the traversal starting from the tile just fetched (not root).
70
+
71
+ * Tile3DLayer
72
+ * |
73
+ * await load(tileset)
74
+ * |
75
+ * tileset.update()
76
+ * | async load tileHeader
77
+ * tileset.traverse() -------------------------- Queued
78
+ * | resume traversal after fetched |
79
+ * |----------------------------------------|
80
+ * |
81
+ * | async load tile content
82
+ * tilset.requestedTiles ----------------------------- RequestScheduler
83
+ * |
84
+ * tilset.selectedTiles (ready for rendering) |
85
+ * | Listen to |
86
+ * Tile3DLayer ----------- onTileLoad ----------------------|
87
+ * | | notify new tile is available
88
+ * updateLayers |
89
+ * tileset.update // trigger another round of update
90
+ */
53
91
  export class Tileset3D {
54
- constructor(tileset, options) {
55
- this.options = void 0;
56
- this.loadOptions = void 0;
57
- this.type = void 0;
58
- this.tileset = void 0;
59
- this.loader = void 0;
60
- this.url = void 0;
61
- this.basePath = void 0;
62
- this.modelMatrix = void 0;
63
- this.ellipsoid = void 0;
64
- this.lodMetricType = void 0;
65
- this.lodMetricValue = void 0;
66
- this.refine = void 0;
67
- this.root = null;
68
- this.roots = {};
69
- this.asset = {};
70
- this.description = '';
71
- this.properties = void 0;
72
- this.extras = null;
73
- this.attributions = {};
74
- this.credits = {};
75
- this.stats = void 0;
76
- this.contentFormats = {
77
- draco: false,
78
- meshopt: false,
79
- dds: false,
80
- ktx2: false
81
- };
82
- this.cartographicCenter = null;
83
- this.cartesianCenter = null;
84
- this.zoom = 1;
85
- this.boundingVolume = null;
86
- this.dynamicScreenSpaceErrorComputedDensity = 0.0;
87
- this.maximumMemoryUsage = 32;
88
- this.gpuMemoryUsageInBytes = 0;
89
- this.memoryAdjustedScreenSpaceError = 0.0;
90
- this._cacheBytes = 0;
91
- this._cacheOverflowBytes = 0;
92
- this._frameNumber = 0;
93
- this._queryParams = {};
94
- this._extensionsUsed = [];
95
- this._tiles = {};
96
- this._pendingCount = 0;
97
- this.selectedTiles = [];
98
- this.traverseCounter = 0;
99
- this.geometricError = 0;
100
- this.lastUpdatedVieports = null;
101
- this._requestedTiles = [];
102
- this._emptyTiles = [];
103
- this.frameStateData = {};
104
- this._traverser = void 0;
105
- this._cache = new TilesetCache();
106
- this._requestScheduler = void 0;
107
- this.updatePromise = null;
108
- this.tilesetInitializationPromise = void 0;
109
- this.options = {
110
- ...DEFAULT_PROPS,
111
- ...options
112
- };
113
- this.tileset = tileset;
114
- this.loader = tileset.loader;
115
- this.type = tileset.type;
116
- this.url = tileset.url;
117
- this.basePath = tileset.basePath || path.dirname(this.url);
118
- this.modelMatrix = this.options.modelMatrix;
119
- this.ellipsoid = this.options.ellipsoid;
120
- this.lodMetricType = tileset.lodMetricType;
121
- this.lodMetricValue = tileset.lodMetricValue;
122
- this.refine = tileset.root.refine;
123
- this.loadOptions = this.options.loadOptions || {};
124
- this._traverser = this._initializeTraverser();
125
- this._requestScheduler = new RequestScheduler({
126
- throttleRequests: this.options.throttleRequests,
127
- maxRequests: this.options.maxRequests
128
- });
129
- this.memoryAdjustedScreenSpaceError = this.options.maximumScreenSpaceError;
130
- this._cacheBytes = this.options.maximumMemoryUsage * 1024 * 1024;
131
- this._cacheOverflowBytes = this.options.memoryCacheOverflow * 1024 * 1024;
132
- this.stats = new Stats({
133
- id: this.url
134
- });
135
- this._initializeStats();
136
- this.tilesetInitializationPromise = this._initializeTileSet(tileset);
137
- }
138
- destroy() {
139
- this._destroy();
140
- }
141
- isLoaded() {
142
- return this._pendingCount === 0 && this._frameNumber !== 0 && this._requestedTiles.length === 0;
143
- }
144
- get tiles() {
145
- return Object.values(this._tiles);
146
- }
147
- get frameNumber() {
148
- return this._frameNumber;
149
- }
150
- get queryParams() {
151
- return new URLSearchParams(this._queryParams).toString();
152
- }
153
- setProps(props) {
154
- this.options = {
155
- ...this.options,
156
- ...props
157
- };
158
- }
159
- getTileUrl(tilePath) {
160
- const isDataUrl = tilePath.startsWith('data:');
161
- if (isDataUrl) {
162
- return tilePath;
163
- }
164
- let tileUrl = tilePath;
165
- if (this.queryParams.length) {
166
- tileUrl = `${tilePath}${tilePath.includes('?') ? '&' : '?'}${this.queryParams}`;
167
- }
168
- return tileUrl;
169
- }
170
- hasExtension(extensionName) {
171
- return Boolean(this._extensionsUsed.indexOf(extensionName) > -1);
172
- }
173
- update() {
174
- let viewports = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
175
- this.tilesetInitializationPromise.then(() => {
176
- if (!viewports && this.lastUpdatedVieports) {
177
- viewports = this.lastUpdatedVieports;
178
- } else {
179
- this.lastUpdatedVieports = viewports;
180
- }
181
- if (viewports) {
182
- this.doUpdate(viewports);
183
- }
184
- });
185
- }
186
- async selectTiles() {
187
- let viewports = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
188
- await this.tilesetInitializationPromise;
189
- if (viewports) {
190
- this.lastUpdatedVieports = viewports;
191
- }
192
- if (!this.updatePromise) {
193
- this.updatePromise = new Promise(resolve => {
194
- setTimeout(() => {
195
- if (this.lastUpdatedVieports) {
196
- this.doUpdate(this.lastUpdatedVieports);
197
- }
198
- resolve(this._frameNumber);
199
- this.updatePromise = null;
200
- }, this.options.debounceTime);
201
- });
202
- }
203
- return this.updatePromise;
204
- }
205
- adjustScreenSpaceError() {
206
- if (this.gpuMemoryUsageInBytes < this._cacheBytes) {
207
- this.memoryAdjustedScreenSpaceError = Math.max(this.memoryAdjustedScreenSpaceError / 1.02, this.options.maximumScreenSpaceError);
208
- } else if (this.gpuMemoryUsageInBytes > this._cacheBytes + this._cacheOverflowBytes) {
209
- this.memoryAdjustedScreenSpaceError *= 1.02;
210
- }
211
- }
212
- doUpdate(viewports) {
213
- if ('loadTiles' in this.options && !this.options.loadTiles) {
214
- return;
215
- }
216
- if (this.traverseCounter > 0) {
217
- return;
218
- }
219
- const preparedViewports = viewports instanceof Array ? viewports : [viewports];
220
- this._cache.reset();
221
- this._frameNumber++;
222
- this.traverseCounter = preparedViewports.length;
223
- const viewportsToTraverse = [];
224
- for (const viewport of preparedViewports) {
225
- const id = viewport.id;
226
- if (this._needTraverse(id)) {
227
- viewportsToTraverse.push(id);
228
- } else {
92
+ // props: Tileset3DProps;
93
+ options;
94
+ loadOptions;
95
+ type;
96
+ tileset;
97
+ loader;
98
+ url;
99
+ basePath;
100
+ modelMatrix;
101
+ ellipsoid;
102
+ lodMetricType;
103
+ lodMetricValue;
104
+ refine;
105
+ root = null;
106
+ roots = {};
107
+ /** @todo any->unknown */
108
+ asset = {};
109
+ // Metadata for the entire tileset
110
+ description = '';
111
+ properties;
112
+ extras = null;
113
+ attributions = {};
114
+ credits = {};
115
+ stats;
116
+ /** flags that contain information about data types in nested tiles */
117
+ contentFormats = { draco: false, meshopt: false, dds: false, ktx2: false };
118
+ // view props
119
+ cartographicCenter = null;
120
+ cartesianCenter = null;
121
+ zoom = 1;
122
+ boundingVolume = null;
123
+ /** Updated based on the camera position and direction */
124
+ dynamicScreenSpaceErrorComputedDensity = 0.0;
125
+ // METRICS
126
+ /**
127
+ * The maximum amount of GPU memory (in MB) that may be used to cache tiles
128
+ * Tiles not in view are unloaded to enforce private
129
+ */
130
+ maximumMemoryUsage = 32;
131
+ /** The total amount of GPU memory in bytes used by the tileset. */
132
+ gpuMemoryUsageInBytes = 0;
133
+ /**
134
+ * If loading the level of detail required by maximumScreenSpaceError
135
+ * results in the memory usage exceeding maximumMemoryUsage (GPU), level of detail refinement
136
+ * will instead use this (larger) adjusted screen space error to achieve the
137
+ * best possible visual quality within the available memory.
138
+ */
139
+ memoryAdjustedScreenSpaceError = 0.0;
140
+ _cacheBytes = 0;
141
+ _cacheOverflowBytes = 0;
142
+ /** Update tracker. increase in each update cycle. */
143
+ _frameNumber = 0;
144
+ _queryParams = {};
145
+ _extensionsUsed = [];
146
+ _tiles = {};
147
+ /** counter for tracking tiles requests */
148
+ _pendingCount = 0;
149
+ /** Hold traversal results */
150
+ selectedTiles = [];
151
+ // TRAVERSAL
152
+ traverseCounter = 0;
153
+ geometricError = 0;
154
+ lastUpdatedVieports = null;
155
+ _requestedTiles = [];
156
+ _emptyTiles = [];
157
+ frameStateData = {};
158
+ _traverser;
159
+ _cache = new TilesetCache();
160
+ _requestScheduler;
161
+ // Promise tracking
162
+ updatePromise = null;
163
+ tilesetInitializationPromise;
164
+ /**
165
+ * Create a new Tileset3D
166
+ * @param json
167
+ * @param props
168
+ */
169
+ // eslint-disable-next-line max-statements
170
+ constructor(tileset, options) {
171
+ // PUBLIC MEMBERS
172
+ this.options = { ...DEFAULT_PROPS, ...options };
173
+ // raw data
174
+ this.tileset = tileset;
175
+ this.loader = tileset.loader;
176
+ // could be 3d tiles, i3s
177
+ this.type = tileset.type;
178
+ // The url to a tileset JSON file.
179
+ this.url = tileset.url;
180
+ this.basePath = tileset.basePath || path.dirname(this.url);
181
+ this.modelMatrix = this.options.modelMatrix;
182
+ this.ellipsoid = this.options.ellipsoid;
183
+ // Geometric error when the tree is not rendered at all
184
+ this.lodMetricType = tileset.lodMetricType;
185
+ this.lodMetricValue = tileset.lodMetricValue;
186
+ this.refine = tileset.root.refine;
187
+ this.loadOptions = this.options.loadOptions || {};
188
+ // TRAVERSAL
189
+ this._traverser = this._initializeTraverser();
190
+ this._requestScheduler = new RequestScheduler({
191
+ throttleRequests: this.options.throttleRequests,
192
+ maxRequests: this.options.maxRequests
193
+ });
194
+ this.memoryAdjustedScreenSpaceError = this.options.maximumScreenSpaceError;
195
+ this._cacheBytes = this.options.maximumMemoryUsage * 1024 * 1024;
196
+ this._cacheOverflowBytes = this.options.memoryCacheOverflow * 1024 * 1024;
197
+ // METRICS
198
+ // The total amount of GPU memory in bytes used by the tileset.
199
+ this.stats = new Stats({ id: this.url });
200
+ this._initializeStats();
201
+ this.tilesetInitializationPromise = this._initializeTileSet(tileset);
202
+ }
203
+ /** Release resources */
204
+ destroy() {
205
+ this._destroy();
206
+ }
207
+ /** Is the tileset loaded (update needs to have been called at least once) */
208
+ isLoaded() {
209
+ // Check that `_frameNumber !== 0` which means that update was called at least once
210
+ return this._pendingCount === 0 && this._frameNumber !== 0 && this._requestedTiles.length === 0;
211
+ }
212
+ get tiles() {
213
+ return Object.values(this._tiles);
214
+ }
215
+ get frameNumber() {
216
+ return this._frameNumber;
217
+ }
218
+ get queryParams() {
219
+ return new URLSearchParams(this._queryParams).toString();
220
+ }
221
+ setProps(props) {
222
+ this.options = { ...this.options, ...props };
223
+ }
224
+ /** @deprecated */
225
+ // setOptions(options: Tileset3DProps): void {
226
+ // this.options = {...this.options, ...options};
227
+ // }
228
+ /**
229
+ * Return a loadable tile url for a specific tile subpath
230
+ * @param tilePath a tile subpath
231
+ */
232
+ getTileUrl(tilePath) {
233
+ const isDataUrl = tilePath.startsWith('data:');
234
+ if (isDataUrl) {
235
+ return tilePath;
236
+ }
237
+ let tileUrl = tilePath;
238
+ if (this.queryParams.length) {
239
+ tileUrl = `${tilePath}${tilePath.includes('?') ? '&' : '?'}${this.queryParams}`;
240
+ }
241
+ return tileUrl;
242
+ }
243
+ // TODO CESIUM specific
244
+ hasExtension(extensionName) {
245
+ return Boolean(this._extensionsUsed.indexOf(extensionName) > -1);
246
+ }
247
+ /**
248
+ * Update visible tiles relying on a list of viewports
249
+ * @param viewports - list of viewports
250
+ * @deprecated
251
+ */
252
+ update(viewports = null) {
253
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
254
+ this.tilesetInitializationPromise.then(() => {
255
+ if (!viewports && this.lastUpdatedVieports) {
256
+ viewports = this.lastUpdatedVieports;
257
+ }
258
+ else {
259
+ this.lastUpdatedVieports = viewports;
260
+ }
261
+ if (viewports) {
262
+ this.doUpdate(viewports);
263
+ }
264
+ });
265
+ }
266
+ /**
267
+ * Update visible tiles relying on a list of viewports.
268
+ * Do it with debounce delay to prevent update spam
269
+ * @param viewports viewports
270
+ * @returns Promise of new frameNumber
271
+ */
272
+ async selectTiles(viewports = null) {
273
+ await this.tilesetInitializationPromise;
274
+ if (viewports) {
275
+ this.lastUpdatedVieports = viewports;
276
+ }
277
+ if (!this.updatePromise) {
278
+ this.updatePromise = new Promise((resolve) => {
279
+ setTimeout(() => {
280
+ if (this.lastUpdatedVieports) {
281
+ this.doUpdate(this.lastUpdatedVieports);
282
+ }
283
+ resolve(this._frameNumber);
284
+ this.updatePromise = null;
285
+ }, this.options.debounceTime);
286
+ });
287
+ }
288
+ return this.updatePromise;
289
+ }
290
+ adjustScreenSpaceError() {
291
+ if (this.gpuMemoryUsageInBytes < this._cacheBytes) {
292
+ this.memoryAdjustedScreenSpaceError = Math.max(this.memoryAdjustedScreenSpaceError / 1.02, this.options.maximumScreenSpaceError);
293
+ }
294
+ else if (this.gpuMemoryUsageInBytes > this._cacheBytes + this._cacheOverflowBytes) {
295
+ this.memoryAdjustedScreenSpaceError *= 1.02;
296
+ }
297
+ }
298
+ /**
299
+ * Update visible tiles relying on a list of viewports
300
+ * @param viewports viewports
301
+ */
302
+ // eslint-disable-next-line max-statements, complexity
303
+ doUpdate(viewports) {
304
+ if ('loadTiles' in this.options && !this.options.loadTiles) {
305
+ return;
306
+ }
307
+ if (this.traverseCounter > 0) {
308
+ return;
309
+ }
310
+ const preparedViewports = viewports instanceof Array ? viewports : [viewports];
311
+ this._cache.reset();
312
+ this._frameNumber++;
313
+ this.traverseCounter = preparedViewports.length;
314
+ const viewportsToTraverse = [];
315
+ // First loop to decrement traverseCounter
316
+ for (const viewport of preparedViewports) {
317
+ const id = viewport.id;
318
+ if (this._needTraverse(id)) {
319
+ viewportsToTraverse.push(id);
320
+ }
321
+ else {
322
+ this.traverseCounter--;
323
+ }
324
+ }
325
+ // Second loop to traverse
326
+ for (const viewport of preparedViewports) {
327
+ const id = viewport.id;
328
+ if (!this.roots[id]) {
329
+ this.roots[id] = this._initializeTileHeaders(this.tileset, null);
330
+ }
331
+ if (!viewportsToTraverse.includes(id)) {
332
+ continue; // eslint-disable-line no-continue
333
+ }
334
+ const frameState = getFrameState(viewport, this._frameNumber);
335
+ this._traverser.traverse(this.roots[id], frameState, this.options);
336
+ }
337
+ }
338
+ /**
339
+ * Check if traversal is needed for particular viewport
340
+ * @param {string} viewportId - id of a viewport
341
+ * @return {boolean}
342
+ */
343
+ _needTraverse(viewportId) {
344
+ let traverserId = viewportId;
345
+ if (this.options.viewportTraversersMap) {
346
+ traverserId = this.options.viewportTraversersMap[viewportId];
347
+ }
348
+ if (traverserId !== viewportId) {
349
+ return false;
350
+ }
351
+ return true;
352
+ }
353
+ /**
354
+ * The callback to post-process tiles after traversal procedure
355
+ * @param frameState - frame state for tile culling
356
+ */
357
+ _onTraversalEnd(frameState) {
358
+ const id = frameState.viewport.id;
359
+ if (!this.frameStateData[id]) {
360
+ this.frameStateData[id] = { selectedTiles: [], _requestedTiles: [], _emptyTiles: [] };
361
+ }
362
+ const currentFrameStateData = this.frameStateData[id];
363
+ const selectedTiles = Object.values(this._traverser.selectedTiles);
364
+ const [filteredSelectedTiles, unselectedTiles] = limitSelectedTiles(selectedTiles, frameState, this.options.maximumTilesSelected);
365
+ currentFrameStateData.selectedTiles = filteredSelectedTiles;
366
+ for (const tile of unselectedTiles) {
367
+ tile.unselect();
368
+ }
369
+ currentFrameStateData._requestedTiles = Object.values(this._traverser.requestedTiles);
370
+ currentFrameStateData._emptyTiles = Object.values(this._traverser.emptyTiles);
229
371
  this.traverseCounter--;
230
- }
231
- }
232
- for (const viewport of preparedViewports) {
233
- const id = viewport.id;
234
- if (!this.roots[id]) {
235
- this.roots[id] = this._initializeTileHeaders(this.tileset, null);
236
- }
237
- if (!viewportsToTraverse.includes(id)) {
238
- continue;
239
- }
240
- const frameState = getFrameState(viewport, this._frameNumber);
241
- this._traverser.traverse(this.roots[id], frameState, this.options);
242
- }
243
- }
244
- _needTraverse(viewportId) {
245
- let traverserId = viewportId;
246
- if (this.options.viewportTraversersMap) {
247
- traverserId = this.options.viewportTraversersMap[viewportId];
248
- }
249
- if (traverserId !== viewportId) {
250
- return false;
251
- }
252
- return true;
253
- }
254
- _onTraversalEnd(frameState) {
255
- const id = frameState.viewport.id;
256
- if (!this.frameStateData[id]) {
257
- this.frameStateData[id] = {
258
- selectedTiles: [],
259
- _requestedTiles: [],
260
- _emptyTiles: []
261
- };
262
- }
263
- const currentFrameStateData = this.frameStateData[id];
264
- const selectedTiles = Object.values(this._traverser.selectedTiles);
265
- const [filteredSelectedTiles, unselectedTiles] = limitSelectedTiles(selectedTiles, frameState, this.options.maximumTilesSelected);
266
- currentFrameStateData.selectedTiles = filteredSelectedTiles;
267
- for (const tile of unselectedTiles) {
268
- tile.unselect();
269
- }
270
- currentFrameStateData._requestedTiles = Object.values(this._traverser.requestedTiles);
271
- currentFrameStateData._emptyTiles = Object.values(this._traverser.emptyTiles);
272
- this.traverseCounter--;
273
- if (this.traverseCounter > 0) {
274
- return;
275
- }
276
- this._updateTiles();
277
- }
278
- _updateTiles() {
279
- this.selectedTiles = [];
280
- this._requestedTiles = [];
281
- this._emptyTiles = [];
282
- for (const frameStateKey in this.frameStateData) {
283
- const frameStateDataValue = this.frameStateData[frameStateKey];
284
- this.selectedTiles = this.selectedTiles.concat(frameStateDataValue.selectedTiles);
285
- this._requestedTiles = this._requestedTiles.concat(frameStateDataValue._requestedTiles);
286
- this._emptyTiles = this._emptyTiles.concat(frameStateDataValue._emptyTiles);
287
- }
288
- this.selectedTiles = this.options.onTraversalComplete(this.selectedTiles);
289
- for (const tile of this.selectedTiles) {
290
- this._tiles[tile.id] = tile;
291
- }
292
- this._loadTiles();
293
- this._unloadTiles();
294
- this._updateStats();
295
- }
296
- _tilesChanged(oldSelectedTiles, selectedTiles) {
297
- if (oldSelectedTiles.length !== selectedTiles.length) {
298
- return true;
299
- }
300
- const set1 = new Set(oldSelectedTiles.map(t => t.id));
301
- const set2 = new Set(selectedTiles.map(t => t.id));
302
- let changed = oldSelectedTiles.filter(x => !set2.has(x.id)).length > 0;
303
- changed = changed || selectedTiles.filter(x => !set1.has(x.id)).length > 0;
304
- return changed;
305
- }
306
- _loadTiles() {
307
- for (const tile of this._requestedTiles) {
308
- if (tile.contentUnloaded) {
309
- this._loadTile(tile);
310
- }
311
- }
312
- }
313
- _unloadTiles() {
314
- this._cache.unloadTiles(this, (tileset, tile) => tileset._unloadTile(tile));
315
- }
316
- _updateStats() {
317
- let tilesRenderable = 0;
318
- let pointsRenderable = 0;
319
- for (const tile of this.selectedTiles) {
320
- if (tile.contentAvailable && tile.content) {
321
- tilesRenderable++;
322
- if (tile.content.pointCount) {
323
- pointsRenderable += tile.content.pointCount;
324
- } else {
325
- pointsRenderable += tile.content.vertexCount;
326
- }
327
- }
328
- }
329
- this.stats.get(TILES_IN_VIEW).count = this.selectedTiles.length;
330
- this.stats.get(TILES_RENDERABLE).count = tilesRenderable;
331
- this.stats.get(POINTS_COUNT).count = pointsRenderable;
332
- this.stats.get(MAXIMUM_SSE).count = this.memoryAdjustedScreenSpaceError;
333
- }
334
- async _initializeTileSet(tilesetJson) {
335
- if (this.type === TILESET_TYPE.I3S) {
336
- this.calculateViewPropsI3S();
337
- tilesetJson.root = await tilesetJson.root;
338
- }
339
- this.root = this._initializeTileHeaders(tilesetJson, null);
340
- if (this.type === TILESET_TYPE.TILES3D) {
341
- this._initializeTiles3DTileset(tilesetJson);
342
- this.calculateViewPropsTiles3D();
343
- }
344
- if (this.type === TILESET_TYPE.I3S) {
345
- this._initializeI3STileset();
346
- }
347
- }
348
- calculateViewPropsI3S() {
349
- var _this$tileset$store;
350
- const fullExtent = this.tileset.fullExtent;
351
- if (fullExtent) {
352
- const {
353
- xmin,
354
- xmax,
355
- ymin,
356
- ymax,
357
- zmin,
358
- zmax
359
- } = fullExtent;
360
- this.cartographicCenter = new Vector3(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, zmin + (zmax - zmin) / 2);
361
- this.cartesianCenter = new Vector3();
362
- Ellipsoid.WGS84.cartographicToCartesian(this.cartographicCenter, this.cartesianCenter);
363
- this.zoom = getZoomFromFullExtent(fullExtent, this.cartographicCenter, this.cartesianCenter);
364
- return;
365
- }
366
- const extent = (_this$tileset$store = this.tileset.store) === null || _this$tileset$store === void 0 ? void 0 : _this$tileset$store.extent;
367
- if (extent) {
368
- const [xmin, ymin, xmax, ymax] = extent;
369
- this.cartographicCenter = new Vector3(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, 0);
370
- this.cartesianCenter = new Vector3();
371
- Ellipsoid.WGS84.cartographicToCartesian(this.cartographicCenter, this.cartesianCenter);
372
- this.zoom = getZoomFromExtent(extent, this.cartographicCenter, this.cartesianCenter);
373
- return;
374
- }
375
- console.warn('Extent is not defined in the tileset header');
376
- this.cartographicCenter = new Vector3();
377
- this.zoom = 1;
378
- return;
379
- }
380
- calculateViewPropsTiles3D() {
381
- const root = this.root;
382
- const {
383
- center
384
- } = root.boundingVolume;
385
- if (!center) {
386
- console.warn('center was not pre-calculated for the root tile');
387
- this.cartographicCenter = new Vector3();
388
- this.zoom = 1;
389
- return;
390
- }
391
- if (center[0] !== 0 || center[1] !== 0 || center[2] !== 0) {
392
- this.cartographicCenter = new Vector3();
393
- Ellipsoid.WGS84.cartesianToCartographic(center, this.cartographicCenter);
394
- } else {
395
- this.cartographicCenter = new Vector3(0, 0, -Ellipsoid.WGS84.radii[0]);
396
- }
397
- this.cartesianCenter = center;
398
- this.zoom = getZoomFromBoundingVolume(root.boundingVolume, this.cartographicCenter);
399
- }
400
- _initializeStats() {
401
- this.stats.get(TILES_TOTAL);
402
- this.stats.get(TILES_LOADING);
403
- this.stats.get(TILES_IN_MEMORY);
404
- this.stats.get(TILES_IN_VIEW);
405
- this.stats.get(TILES_RENDERABLE);
406
- this.stats.get(TILES_LOADED);
407
- this.stats.get(TILES_UNLOADED);
408
- this.stats.get(TILES_LOAD_FAILED);
409
- this.stats.get(POINTS_COUNT);
410
- this.stats.get(TILES_GPU_MEMORY, 'memory');
411
- this.stats.get(MAXIMUM_SSE);
412
- }
413
- _initializeTileHeaders(tilesetJson, parentTileHeader) {
414
- const rootTile = new Tile3D(this, tilesetJson.root, parentTileHeader);
415
- if (parentTileHeader) {
416
- parentTileHeader.children.push(rootTile);
417
- rootTile.depth = parentTileHeader.depth + 1;
418
- }
419
- if (this.type === TILESET_TYPE.TILES3D) {
420
- const stack = [];
421
- stack.push(rootTile);
422
- while (stack.length > 0) {
423
- const tile = stack.pop();
424
- this.stats.get(TILES_TOTAL).incrementCount();
425
- const children = tile.header.children || [];
426
- for (const childHeader of children) {
427
- var _childTile$contentUrl;
428
- const childTile = new Tile3D(this, childHeader, tile);
429
- if ((_childTile$contentUrl = childTile.contentUrl) !== null && _childTile$contentUrl !== void 0 && _childTile$contentUrl.includes('?session=')) {
430
- const url = new URL(childTile.contentUrl);
431
- const session = url.searchParams.get('session');
432
- if (session) {
433
- this._queryParams.session = session;
372
+ if (this.traverseCounter > 0) {
373
+ return;
374
+ }
375
+ this._updateTiles();
376
+ }
377
+ /**
378
+ * Update tiles relying on data from all traversers
379
+ */
380
+ _updateTiles() {
381
+ this.selectedTiles = [];
382
+ this._requestedTiles = [];
383
+ this._emptyTiles = [];
384
+ for (const frameStateKey in this.frameStateData) {
385
+ const frameStateDataValue = this.frameStateData[frameStateKey];
386
+ this.selectedTiles = this.selectedTiles.concat(frameStateDataValue.selectedTiles);
387
+ this._requestedTiles = this._requestedTiles.concat(frameStateDataValue._requestedTiles);
388
+ this._emptyTiles = this._emptyTiles.concat(frameStateDataValue._emptyTiles);
389
+ }
390
+ this.selectedTiles = this.options.onTraversalComplete(this.selectedTiles);
391
+ for (const tile of this.selectedTiles) {
392
+ this._tiles[tile.id] = tile;
393
+ }
394
+ this._loadTiles();
395
+ this._unloadTiles();
396
+ this._updateStats();
397
+ }
398
+ _tilesChanged(oldSelectedTiles, selectedTiles) {
399
+ if (oldSelectedTiles.length !== selectedTiles.length) {
400
+ return true;
401
+ }
402
+ const set1 = new Set(oldSelectedTiles.map((t) => t.id));
403
+ const set2 = new Set(selectedTiles.map((t) => t.id));
404
+ let changed = oldSelectedTiles.filter((x) => !set2.has(x.id)).length > 0;
405
+ changed = changed || selectedTiles.filter((x) => !set1.has(x.id)).length > 0;
406
+ return changed;
407
+ }
408
+ _loadTiles() {
409
+ // Sort requests by priority before making any requests.
410
+ // This makes it less likely this requests will be cancelled after being issued.
411
+ // requestedTiles.sort((a, b) => a._priority - b._priority);
412
+ for (const tile of this._requestedTiles) {
413
+ if (tile.contentUnloaded) {
414
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
415
+ this._loadTile(tile);
434
416
  }
435
- }
436
- tile.children.push(childTile);
437
- childTile.depth = tile.depth + 1;
438
- stack.push(childTile);
439
- }
440
- }
441
- }
442
- return rootTile;
443
- }
444
- _initializeTraverser() {
445
- let TraverserClass;
446
- const type = this.type;
447
- switch (type) {
448
- case TILESET_TYPE.TILES3D:
449
- TraverserClass = Tileset3DTraverser;
450
- break;
451
- case TILESET_TYPE.I3S:
452
- TraverserClass = I3STilesetTraverser;
453
- break;
454
- default:
455
- TraverserClass = TilesetTraverser;
456
- }
457
- return new TraverserClass({
458
- basePath: this.basePath,
459
- onTraversalEnd: this._onTraversalEnd.bind(this)
460
- });
461
- }
462
- _destroyTileHeaders(parentTile) {
463
- this._destroySubtree(parentTile);
464
- }
465
- async _loadTile(tile) {
466
- let loaded;
467
- try {
468
- this._onStartTileLoading();
469
- loaded = await tile.loadContent();
470
- } catch (error) {
471
- this._onTileLoadError(tile, error instanceof Error ? error : new Error('load failed'));
472
- } finally {
473
- this._onEndTileLoading();
474
- this._onTileLoad(tile, loaded);
475
- }
476
- }
477
- _onTileLoadError(tile, error) {
478
- this.stats.get(TILES_LOAD_FAILED).incrementCount();
479
- const message = error.message || error.toString();
480
- const url = tile.url;
481
- console.error(`A 3D tile failed to load: ${tile.url} ${message}`);
482
- this.options.onTileError(tile, message, url);
483
- }
484
- _onTileLoad(tile, loaded) {
485
- if (!loaded) {
486
- return;
487
- }
488
- if (this.type === TILESET_TYPE.I3S) {
489
- var _this$tileset, _this$tileset$nodePag;
490
- const nodesInNodePages = ((_this$tileset = this.tileset) === null || _this$tileset === void 0 ? void 0 : (_this$tileset$nodePag = _this$tileset.nodePagesTile) === null || _this$tileset$nodePag === void 0 ? void 0 : _this$tileset$nodePag.nodesInNodePages) || 0;
491
- this.stats.get(TILES_TOTAL).reset();
492
- this.stats.get(TILES_TOTAL).addCount(nodesInNodePages);
493
- }
494
- if (tile && tile.content) {
495
- calculateTransformProps(tile, tile.content);
496
- }
497
- this.updateContentTypes(tile);
498
- this._addTileToCache(tile);
499
- this.options.onTileLoad(tile);
500
- }
501
- updateContentTypes(tile) {
502
- if (this.type === TILESET_TYPE.I3S) {
503
- if (tile.header.isDracoGeometry) {
504
- this.contentFormats.draco = true;
505
- }
506
- switch (tile.header.textureFormat) {
507
- case 'dds':
508
- this.contentFormats.dds = true;
509
- break;
510
- case 'ktx2':
511
- this.contentFormats.ktx2 = true;
512
- break;
513
- default:
514
- }
515
- } else if (this.type === TILESET_TYPE.TILES3D) {
516
- var _tile$content;
517
- const {
518
- extensionsRemoved = []
519
- } = ((_tile$content = tile.content) === null || _tile$content === void 0 ? void 0 : _tile$content.gltf) || {};
520
- if (extensionsRemoved.includes('KHR_draco_mesh_compression')) {
521
- this.contentFormats.draco = true;
522
- }
523
- if (extensionsRemoved.includes('EXT_meshopt_compression')) {
524
- this.contentFormats.meshopt = true;
525
- }
526
- if (extensionsRemoved.includes('KHR_texture_basisu')) {
527
- this.contentFormats.ktx2 = true;
528
- }
529
- }
530
- }
531
- _onStartTileLoading() {
532
- this._pendingCount++;
533
- this.stats.get(TILES_LOADING).incrementCount();
534
- }
535
- _onEndTileLoading() {
536
- this._pendingCount--;
537
- this.stats.get(TILES_LOADING).decrementCount();
538
- }
539
- _addTileToCache(tile) {
540
- this._cache.add(this, tile, tileset => tileset._updateCacheStats(tile));
541
- }
542
- _updateCacheStats(tile) {
543
- this.stats.get(TILES_LOADED).incrementCount();
544
- this.stats.get(TILES_IN_MEMORY).incrementCount();
545
- this.gpuMemoryUsageInBytes += tile.gpuMemoryUsageInBytes || 0;
546
- this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
547
- if (this.options.memoryAdjustedScreenSpaceError) {
548
- this.adjustScreenSpaceError();
549
- }
550
- }
551
- _unloadTile(tile) {
552
- this.gpuMemoryUsageInBytes -= tile.gpuMemoryUsageInBytes || 0;
553
- this.stats.get(TILES_IN_MEMORY).decrementCount();
554
- this.stats.get(TILES_UNLOADED).incrementCount();
555
- this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
556
- this.options.onTileUnload(tile);
557
- tile.unloadContent();
558
- }
559
- _destroy() {
560
- const stack = [];
561
- if (this.root) {
562
- stack.push(this.root);
563
- }
564
- while (stack.length > 0) {
565
- const tile = stack.pop();
566
- for (const child of tile.children) {
567
- stack.push(child);
568
- }
569
- this._destroyTile(tile);
570
- }
571
- this.root = null;
572
- }
573
- _destroySubtree(tile) {
574
- const root = tile;
575
- const stack = [];
576
- stack.push(root);
577
- while (stack.length > 0) {
578
- tile = stack.pop();
579
- for (const child of tile.children) {
580
- stack.push(child);
581
- }
582
- if (tile !== root) {
583
- this._destroyTile(tile);
584
- }
585
- }
586
- root.children = [];
587
- }
588
- _destroyTile(tile) {
589
- this._cache.unloadTile(this, tile);
590
- this._unloadTile(tile);
591
- tile.destroy();
592
- }
593
- _initializeTiles3DTileset(tilesetJson) {
594
- if (tilesetJson.queryString) {
595
- const searchParams = new URLSearchParams(tilesetJson.queryString);
596
- const queryParams = Object.fromEntries(searchParams.entries());
597
- this._queryParams = {
598
- ...this._queryParams,
599
- ...queryParams
600
- };
601
- }
602
- this.asset = tilesetJson.asset;
603
- if (!this.asset) {
604
- throw new Error('Tileset must have an asset property.');
605
- }
606
- if (this.asset.version !== '0.0' && this.asset.version !== '1.0' && this.asset.version !== '1.1') {
607
- throw new Error('The tileset must be 3D Tiles version either 0.0 or 1.0 or 1.1.');
608
- }
609
- if ('tilesetVersion' in this.asset) {
610
- this._queryParams.v = this.asset.tilesetVersion;
611
- }
612
- this.credits = {
613
- attributions: this.options.attributions || []
614
- };
615
- this.description = this.options.description || '';
616
- this.properties = tilesetJson.properties;
617
- this.geometricError = tilesetJson.geometricError;
618
- this._extensionsUsed = tilesetJson.extensionsUsed || [];
619
- this.extras = tilesetJson.extras;
620
- }
621
- _initializeI3STileset() {
622
- if (this.loadOptions.i3s && 'token' in this.loadOptions.i3s) {
623
- this._queryParams.token = this.loadOptions.i3s.token;
624
- }
625
- }
417
+ }
418
+ }
419
+ _unloadTiles() {
420
+ // unload tiles from cache when hit maximumMemoryUsage
421
+ this._cache.unloadTiles(this, (tileset, tile) => tileset._unloadTile(tile));
422
+ }
423
+ _updateStats() {
424
+ let tilesRenderable = 0;
425
+ let pointsRenderable = 0;
426
+ for (const tile of this.selectedTiles) {
427
+ if (tile.contentAvailable && tile.content) {
428
+ tilesRenderable++;
429
+ if (tile.content.pointCount) {
430
+ pointsRenderable += tile.content.pointCount;
431
+ }
432
+ else {
433
+ // Calculate vertices for non point cloud tiles.
434
+ pointsRenderable += tile.content.vertexCount;
435
+ }
436
+ }
437
+ }
438
+ this.stats.get(TILES_IN_VIEW).count = this.selectedTiles.length;
439
+ this.stats.get(TILES_RENDERABLE).count = tilesRenderable;
440
+ this.stats.get(POINTS_COUNT).count = pointsRenderable;
441
+ this.stats.get(MAXIMUM_SSE).count = this.memoryAdjustedScreenSpaceError;
442
+ }
443
+ async _initializeTileSet(tilesetJson) {
444
+ if (this.type === TILESET_TYPE.I3S) {
445
+ this.calculateViewPropsI3S();
446
+ tilesetJson.root = await tilesetJson.root;
447
+ }
448
+ this.root = this._initializeTileHeaders(tilesetJson, null);
449
+ if (this.type === TILESET_TYPE.TILES3D) {
450
+ this._initializeTiles3DTileset(tilesetJson);
451
+ this.calculateViewPropsTiles3D();
452
+ }
453
+ if (this.type === TILESET_TYPE.I3S) {
454
+ this._initializeI3STileset();
455
+ }
456
+ }
457
+ /**
458
+ * Called during initialize Tileset to initialize the tileset's cartographic center (longitude, latitude) and zoom.
459
+ * These metrics help apps center view on tileset
460
+ * For I3S there is extent (<1.8 version) or fullExtent (>=1.8 version) to calculate view props
461
+ * @returns
462
+ */
463
+ calculateViewPropsI3S() {
464
+ // for I3S 1.8 try to calculate with fullExtent
465
+ const fullExtent = this.tileset.fullExtent;
466
+ if (fullExtent) {
467
+ const { xmin, xmax, ymin, ymax, zmin, zmax } = fullExtent;
468
+ this.cartographicCenter = new Vector3(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, zmin + (zmax - zmin) / 2);
469
+ this.cartesianCenter = new Vector3();
470
+ Ellipsoid.WGS84.cartographicToCartesian(this.cartographicCenter, this.cartesianCenter);
471
+ this.zoom = getZoomFromFullExtent(fullExtent, this.cartographicCenter, this.cartesianCenter);
472
+ return;
473
+ }
474
+ // for I3S 1.6-1.7 try to calculate with extent
475
+ const extent = this.tileset.store?.extent;
476
+ if (extent) {
477
+ const [xmin, ymin, xmax, ymax] = extent;
478
+ this.cartographicCenter = new Vector3(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, 0);
479
+ this.cartesianCenter = new Vector3();
480
+ Ellipsoid.WGS84.cartographicToCartesian(this.cartographicCenter, this.cartesianCenter);
481
+ this.zoom = getZoomFromExtent(extent, this.cartographicCenter, this.cartesianCenter);
482
+ return;
483
+ }
484
+ // eslint-disable-next-line no-console
485
+ console.warn('Extent is not defined in the tileset header');
486
+ this.cartographicCenter = new Vector3();
487
+ this.zoom = 1;
488
+ return;
489
+ }
490
+ /**
491
+ * Called during initialize Tileset to initialize the tileset's cartographic center (longitude, latitude) and zoom.
492
+ * These metrics help apps center view on tileset.
493
+ * For 3DTiles the root tile data is used to calculate view props.
494
+ * @returns
495
+ */
496
+ calculateViewPropsTiles3D() {
497
+ const root = this.root;
498
+ const { center } = root.boundingVolume;
499
+ // TODO - handle all cases
500
+ if (!center) {
501
+ // eslint-disable-next-line no-console
502
+ console.warn('center was not pre-calculated for the root tile');
503
+ this.cartographicCenter = new Vector3();
504
+ this.zoom = 1;
505
+ return;
506
+ }
507
+ // cartographic coordinates are undefined at the center of the ellipsoid
508
+ if (center[0] !== 0 || center[1] !== 0 || center[2] !== 0) {
509
+ this.cartographicCenter = new Vector3();
510
+ Ellipsoid.WGS84.cartesianToCartographic(center, this.cartographicCenter);
511
+ }
512
+ else {
513
+ this.cartographicCenter = new Vector3(0, 0, -Ellipsoid.WGS84.radii[0]);
514
+ }
515
+ this.cartesianCenter = center;
516
+ this.zoom = getZoomFromBoundingVolume(root.boundingVolume, this.cartographicCenter);
517
+ }
518
+ _initializeStats() {
519
+ this.stats.get(TILES_TOTAL);
520
+ this.stats.get(TILES_LOADING);
521
+ this.stats.get(TILES_IN_MEMORY);
522
+ this.stats.get(TILES_IN_VIEW);
523
+ this.stats.get(TILES_RENDERABLE);
524
+ this.stats.get(TILES_LOADED);
525
+ this.stats.get(TILES_UNLOADED);
526
+ this.stats.get(TILES_LOAD_FAILED);
527
+ this.stats.get(POINTS_COUNT);
528
+ this.stats.get(TILES_GPU_MEMORY, 'memory');
529
+ this.stats.get(MAXIMUM_SSE);
530
+ }
531
+ // Installs the main tileset JSON file or a tileset JSON file referenced from a tile.
532
+ // eslint-disable-next-line max-statements
533
+ _initializeTileHeaders(tilesetJson, parentTileHeader) {
534
+ // A tileset JSON file referenced from a tile may exist in a different directory than the root tileset.
535
+ // Get the basePath relative to the external tileset.
536
+ const rootTile = new Tile3D(this, tilesetJson.root, parentTileHeader); // resource
537
+ // If there is a parentTileHeader, add the root of the currently loading tileset
538
+ // to parentTileHeader's children, and update its depth.
539
+ if (parentTileHeader) {
540
+ parentTileHeader.children.push(rootTile);
541
+ rootTile.depth = parentTileHeader.depth + 1;
542
+ }
543
+ // 3DTiles knows the hierarchy beforehand
544
+ if (this.type === TILESET_TYPE.TILES3D) {
545
+ const stack = [];
546
+ stack.push(rootTile);
547
+ while (stack.length > 0) {
548
+ const tile = stack.pop();
549
+ this.stats.get(TILES_TOTAL).incrementCount();
550
+ const children = tile.header.children || [];
551
+ for (const childHeader of children) {
552
+ const childTile = new Tile3D(this, childHeader, tile);
553
+ // Special handling for Google
554
+ // A session key must be used for all tile requests
555
+ if (childTile.contentUrl?.includes('?session=')) {
556
+ const url = new URL(childTile.contentUrl);
557
+ const session = url.searchParams.get('session');
558
+ // eslint-disable-next-line max-depth
559
+ if (session) {
560
+ this._queryParams.session = session;
561
+ }
562
+ }
563
+ tile.children.push(childTile);
564
+ childTile.depth = tile.depth + 1;
565
+ stack.push(childTile);
566
+ }
567
+ }
568
+ }
569
+ return rootTile;
570
+ }
571
+ _initializeTraverser() {
572
+ let TraverserClass;
573
+ const type = this.type;
574
+ switch (type) {
575
+ case TILESET_TYPE.TILES3D:
576
+ TraverserClass = Tileset3DTraverser;
577
+ break;
578
+ case TILESET_TYPE.I3S:
579
+ TraverserClass = I3STilesetTraverser;
580
+ break;
581
+ default:
582
+ TraverserClass = TilesetTraverser;
583
+ }
584
+ return new TraverserClass({
585
+ basePath: this.basePath,
586
+ onTraversalEnd: this._onTraversalEnd.bind(this)
587
+ });
588
+ }
589
+ _destroyTileHeaders(parentTile) {
590
+ this._destroySubtree(parentTile);
591
+ }
592
+ async _loadTile(tile) {
593
+ let loaded;
594
+ try {
595
+ this._onStartTileLoading();
596
+ loaded = await tile.loadContent();
597
+ }
598
+ catch (error) {
599
+ this._onTileLoadError(tile, error instanceof Error ? error : new Error('load failed'));
600
+ }
601
+ finally {
602
+ this._onEndTileLoading();
603
+ this._onTileLoad(tile, loaded);
604
+ }
605
+ }
606
+ _onTileLoadError(tile, error) {
607
+ this.stats.get(TILES_LOAD_FAILED).incrementCount();
608
+ const message = error.message || error.toString();
609
+ const url = tile.url;
610
+ // TODO - Allow for probe log to be injected instead of console?
611
+ console.error(`A 3D tile failed to load: ${tile.url} ${message}`); // eslint-disable-line
612
+ this.options.onTileError(tile, message, url);
613
+ }
614
+ _onTileLoad(tile, loaded) {
615
+ if (!loaded) {
616
+ return;
617
+ }
618
+ if (this.type === TILESET_TYPE.I3S) {
619
+ // We can't calculate tiles total in I3S in advance so we calculate it dynamically.
620
+ const nodesInNodePages = this.tileset?.nodePagesTile?.nodesInNodePages || 0;
621
+ this.stats.get(TILES_TOTAL).reset();
622
+ this.stats.get(TILES_TOTAL).addCount(nodesInNodePages);
623
+ }
624
+ // add coordinateOrigin and modelMatrix to tile
625
+ if (tile && tile.content) {
626
+ calculateTransformProps(tile, tile.content);
627
+ }
628
+ this.updateContentTypes(tile);
629
+ this._addTileToCache(tile);
630
+ this.options.onTileLoad(tile);
631
+ }
632
+ /**
633
+ * Update information about data types in nested tiles
634
+ * @param tile instance of a nested Tile3D
635
+ */
636
+ updateContentTypes(tile) {
637
+ if (this.type === TILESET_TYPE.I3S) {
638
+ if (tile.header.isDracoGeometry) {
639
+ this.contentFormats.draco = true;
640
+ }
641
+ switch (tile.header.textureFormat) {
642
+ case 'dds':
643
+ this.contentFormats.dds = true;
644
+ break;
645
+ case 'ktx2':
646
+ this.contentFormats.ktx2 = true;
647
+ break;
648
+ default:
649
+ }
650
+ }
651
+ else if (this.type === TILESET_TYPE.TILES3D) {
652
+ const { extensionsRemoved = [] } = tile.content?.gltf || {};
653
+ if (extensionsRemoved.includes('KHR_draco_mesh_compression')) {
654
+ this.contentFormats.draco = true;
655
+ }
656
+ if (extensionsRemoved.includes('EXT_meshopt_compression')) {
657
+ this.contentFormats.meshopt = true;
658
+ }
659
+ if (extensionsRemoved.includes('KHR_texture_basisu')) {
660
+ this.contentFormats.ktx2 = true;
661
+ }
662
+ }
663
+ }
664
+ _onStartTileLoading() {
665
+ this._pendingCount++;
666
+ this.stats.get(TILES_LOADING).incrementCount();
667
+ }
668
+ _onEndTileLoading() {
669
+ this._pendingCount--;
670
+ this.stats.get(TILES_LOADING).decrementCount();
671
+ }
672
+ _addTileToCache(tile) {
673
+ this._cache.add(this, tile, (tileset) => tileset._updateCacheStats(tile));
674
+ }
675
+ _updateCacheStats(tile) {
676
+ this.stats.get(TILES_LOADED).incrementCount();
677
+ this.stats.get(TILES_IN_MEMORY).incrementCount();
678
+ // TODO: Calculate GPU memory usage statistics for a tile.
679
+ this.gpuMemoryUsageInBytes += tile.gpuMemoryUsageInBytes || 0;
680
+ this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
681
+ // Adjust SSE based on cache limits
682
+ if (this.options.memoryAdjustedScreenSpaceError) {
683
+ this.adjustScreenSpaceError();
684
+ }
685
+ }
686
+ _unloadTile(tile) {
687
+ this.gpuMemoryUsageInBytes -= tile.gpuMemoryUsageInBytes || 0;
688
+ this.stats.get(TILES_IN_MEMORY).decrementCount();
689
+ this.stats.get(TILES_UNLOADED).incrementCount();
690
+ this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
691
+ this.options.onTileUnload(tile);
692
+ tile.unloadContent();
693
+ }
694
+ // Traverse the tree and destroy all tiles
695
+ _destroy() {
696
+ const stack = [];
697
+ if (this.root) {
698
+ stack.push(this.root);
699
+ }
700
+ while (stack.length > 0) {
701
+ const tile = stack.pop();
702
+ for (const child of tile.children) {
703
+ stack.push(child);
704
+ }
705
+ this._destroyTile(tile);
706
+ }
707
+ this.root = null;
708
+ }
709
+ // Traverse the tree and destroy all sub tiles
710
+ _destroySubtree(tile) {
711
+ const root = tile;
712
+ const stack = [];
713
+ stack.push(root);
714
+ while (stack.length > 0) {
715
+ tile = stack.pop();
716
+ for (const child of tile.children) {
717
+ stack.push(child);
718
+ }
719
+ if (tile !== root) {
720
+ this._destroyTile(tile);
721
+ }
722
+ }
723
+ root.children = [];
724
+ }
725
+ _destroyTile(tile) {
726
+ this._cache.unloadTile(this, tile);
727
+ this._unloadTile(tile);
728
+ tile.destroy();
729
+ }
730
+ _initializeTiles3DTileset(tilesetJson) {
731
+ if (tilesetJson.queryString) {
732
+ const searchParams = new URLSearchParams(tilesetJson.queryString);
733
+ const queryParams = Object.fromEntries(searchParams.entries());
734
+ this._queryParams = { ...this._queryParams, ...queryParams };
735
+ }
736
+ this.asset = tilesetJson.asset;
737
+ if (!this.asset) {
738
+ throw new Error('Tileset must have an asset property.');
739
+ }
740
+ if (this.asset.version !== '0.0' &&
741
+ this.asset.version !== '1.0' &&
742
+ this.asset.version !== '1.1') {
743
+ throw new Error('The tileset must be 3D Tiles version either 0.0 or 1.0 or 1.1.');
744
+ }
745
+ // Note: `asset.tilesetVersion` is version of the tileset itself (not the version of the 3D TILES standard)
746
+ // We add this version as a `v=1.0` query param to fetch the right version and not get an older cached version
747
+ if ('tilesetVersion' in this.asset) {
748
+ this._queryParams.v = this.asset.tilesetVersion;
749
+ }
750
+ // TODO - ion resources have a credits property we can use for additional attribution.
751
+ this.credits = {
752
+ attributions: this.options.attributions || []
753
+ };
754
+ this.description = this.options.description || '';
755
+ // Gets the tileset's properties dictionary object, which contains metadata about per-feature properties.
756
+ this.properties = tilesetJson.properties;
757
+ this.geometricError = tilesetJson.geometricError;
758
+ this._extensionsUsed = tilesetJson.extensionsUsed || [];
759
+ // Returns the extras property at the top of the tileset JSON (application specific metadata).
760
+ this.extras = tilesetJson.extras;
761
+ }
762
+ _initializeI3STileset() {
763
+ // @ts-expect-error
764
+ if (this.loadOptions.i3s && 'token' in this.loadOptions.i3s) {
765
+ // @ts-ignore
766
+ this._queryParams.token = this.loadOptions.i3s.token;
767
+ }
768
+ }
626
769
  }
627
- //# sourceMappingURL=tileset-3d.js.map