forked from heremaps/harp.gl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tile.ts
1194 lines (1066 loc) · 38.3 KB
/
Tile.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2023- XYZ maps contributors
* Copyright (C) 2019-2021 HERE Europe B.V.
* Licensed under Apache 2.0, see full license in LICENSE
* SPDX-License-Identifier: Apache-2.0
*/
import {
DecodedTile,
GeometryKindSet,
GeometryType,
TextPathGeometry
} from "@xyzmaps/harp-datasource-protocol";
import { GeoBox, OrientedBox3, Projection, TileKey, TileKeyUtils } from "@xyzmaps/harp-geoutils";
import { assert, CachedResource, chainCallbacks, LoggerManager } from "@xyzmaps/harp-utils";
import * as THREE from "three";
import { CopyrightInfo } from "./copyrights/CopyrightInfo";
import { DataSource } from "./DataSource";
import { ElevationRange } from "./ElevationRangeSource";
import { LodMesh } from "./geometry/LodMesh";
import { Object3DUtils } from "./geometry/Object3DUtils";
import { TileGeometryLoader } from "./geometry/TileGeometryLoader";
import { ITileLoader, TileLoaderState } from "./ITileLoader";
import { MapView } from "./MapView";
import { PathBlockingElement } from "./PathBlockingElement";
import { PerformanceStatistics } from "./Statistics";
import { TextElement } from "./text/TextElement";
import { TextElementGroup } from "./text/TextElementGroup";
import { TextElementGroupPriorityList } from "./text/TextElementGroupPriorityList";
import { TileTextStyleCache } from "./text/TileTextStyleCache";
const logger = LoggerManager.instance.create("Tile");
export type TileObject = THREE.Object3D & {
/**
* Distance of this object from the {@link Tile}'s center.
*/
displacement?: THREE.Vector3;
};
interface DisposableObject {
geometry?: THREE.BufferGeometry;
geometries?: THREE.BufferGeometry[];
material?: THREE.Material[] | THREE.Material;
}
/**
* An interface for optional feature data that is saved in a `THREE.Object3D`'s `userData`
* property.
*/
export interface TileFeatureData {
/**
* The original type of geometry.
*/
geometryType?: GeometryType;
/**
* An optional array of sorted indices into geometry where the feature starts. The lists of IDs
* and starting indices (starts) must have the same size.
* Feature i starts at starts[i] and ends at starts[i+1]-1, except for the last feature, which
* ends at the last index in the object's geometry.
*/
starts?: number[];
/**
* An optional object containing properties defined by the developer. It has the same size as
* the list of IDs and the starting indices (starts).
*/
objInfos?: Array<{} | undefined>;
}
/**
* Minimum estimated size of a JS object.
*/
const MINIMUM_SMALL_OBJECT_SIZE_ESTIMATION = 16;
const MINIMUM_OBJECT_SIZE_ESTIMATION = 100;
/**
* Compute the memory footprint of `TileFeatureData`.
*
* @internal
*/
export function getFeatureDataSize(featureData: TileFeatureData): number {
let numBytes = MINIMUM_OBJECT_SIZE_ESTIMATION;
if (featureData.starts !== undefined) {
numBytes += featureData.starts.length * 8;
}
if (featureData.objInfos !== undefined) {
// 16 (estimated) bytes per objInfos
numBytes += featureData.objInfos.length * MINIMUM_SMALL_OBJECT_SIZE_ESTIMATION;
}
return numBytes;
}
/**
* An object that contains information about resources used by a tile.
*/
export interface TileResourceUsage {
/**
* The estimated memory usage, in bytes.
*/
estimatedMemoryUsage: number;
/**
* The amount of vertices used by a tile.
*/
numVertices: number;
/**
* The amount of colors used by a tile.
*/
numColors: number;
/**
* The amount of objects used by a tile.
*/
numObjects: number;
/**
* The amount of geometries used by a tile.
*/
numGeometries: number;
/**
* The amount of materials used by a tile.
*/
numMaterials: number;
}
/**
* Simple information about resource usage by the {@link Tile}.
*
* @remarks
* Heap and GPU information are
* estimations.
*/
export interface TileResourceInfo {
/**
* Estimated number of bytes used on the heap.
*/
heapSize: number;
/**
* Estimated number of bytes used on the GPU.
*/
gpuSize: number;
/**
* Number of [[THREE.Object3D]] in this tile.
*/
num3dObjects: number;
/**
* Number of {@link TextElement}s in this tile.
*/
numTextElements: number;
/**
* @deprecated This counter has been merged with numTextElements.
* Number of user {@link TextElement}s in this tile.
*/
numUserTextElements: number;
}
/**
* @internal
*/
export interface TextElementIndex {
groupIndex: number;
elementIndex: number;
}
type TileCallback = (tile: Tile) => void;
/**
* The class that holds the tiled data for a {@link DataSource}.
*/
export class Tile implements CachedResource {
/**
* A list of the THREE.js objects stored in this `Tile`.
*/
readonly objects: TileObject[] = [];
/**
* The optional list of HERE TileKeys of tiles with geometries that cross the boundaries of this
* `Tile`.
*/
readonly dependencies: TileKey[] = [];
/**
* The bounding box of this `Tile` in geocoordinates.
*/
readonly geoBox: GeoBox;
/**
* Copyright information of this `Tile`'s data.
*/
copyrightInfo?: CopyrightInfo[];
/**
* Keeping some stats for the individual {@link Tile}s to analyze caching behavior.
*
* The frame the {@link Tile} was last requested. This is
* required to know when the given {@link Tile}
* can be removed from the cache.
*/
frameNumLastRequested: number = -1;
/**
* The frame the `Tile` was first visible.
*/
frameNumVisible: number = -1;
/**
* The last frame this `Tile` has been rendered (or was in the visible set). Used to determine
* visibility of `Tile` at the end of a frame, if the number is the current frame number, it is
* visible.
*/
frameNumLastVisible: number = -1;
/**
* After removing from cache, this is the number of frames the `Tile` was visible.
*/
numFramesVisible: number = 0;
/**
* Version stamp of the visibility set in the [[TileManager]]. If the counter is different, the
* visibility of the Tile's objects has to be calculated. Optimization to reduce overhead of
* computing visibility.
*/
visibilityCounter: number = -1;
/**
* @hidden
*
* Used to tell if the Tile is used temporarily as a fallback tile.
*
* levelOffset is in in the range [-quadTreeSearchDistanceUp,
* quadTreeSearchDistanceDown], where these values come from the
* {@link VisibleTileSetOptions}
*/
levelOffset: number = 0;
/**
* If the tile should not be rendered, this is used typically when the tile in question
* is completely covered by another tile and therefore can be skipped without any visual
* impact. Setting this value directly affects the [[willRender]] method, unless
* overriden by deriving classes.
*/
skipRendering: boolean = false;
/**
* If the tile should not yet be rendered, this is used typically when the tile in question
* does not fit into the gpu upload limit of the current frame.
* Setting this value directly affects the [[willRender]] method, unless
* overriden by deriving classes.
*/
delayRendering = false;
/**
* @hidden
*
* Prepared text geometries optimized for display.
*/
protected preparedTextPaths: TextPathGeometry[] | undefined;
protected readonly m_tileGeometryLoader?: TileGeometryLoader;
/**
* The bounding box of this `Tile` in world coordinates.
*/
private readonly m_boundingBox = new OrientedBox3();
private m_disposed: boolean = false;
private m_disposeCallback?: TileCallback;
private readonly m_localTangentSpace: boolean;
private m_forceHasGeometry: boolean | undefined = undefined;
private m_tileLoader?: ITileLoader;
private m_decodedTile?: DecodedTile;
// Used for {@link TextElement}s that are stored in the data, and that are placed explicitly,
// fading in and out.
private m_textElementGroups = new TextElementGroupPriorityList();
// Blocks other labels from showing.
private readonly m_pathBlockingElements: PathBlockingElement[] = [];
// If `true`, the text content of the {@link Tile} changed after the last time it was rendered.
// It's `Undefined` when no text content has been added yet.
private m_textElementsChanged: boolean | undefined;
// Center of the tile's un-elevated bounding box world coordinates.
private readonly m_worldCenter = new THREE.Vector3();
private m_visibleArea: number = 0;
// Tile elevation range in meters
private readonly m_elevationRange: ElevationRange = { minElevation: 0, maxElevation: 0 };
// Maximum height of geometry on this tile above ground level.
private m_maxGeometryHeight?: number;
// Minimum height of geometry on this tile below ground level. Should be negative for values
// below ground.
private m_minGeometryHeight?: number;
private m_resourceInfo: TileResourceInfo | undefined;
// List of owned textures for disposal
private readonly m_ownedTextures: WeakSet<THREE.Texture> = new WeakSet();
private readonly m_textStyleCache: TileTextStyleCache;
private m_uniqueKey: number;
private m_offset: number;
/**
* Creates a new {@link Tile}.
*
* @param dataSource - The {@link DataSource} that created this {@link Tile}.
* @param tileKey - The unique identifier for this {@link Tile}.
* Currently only up to level 24 is
* supported, because of the use of the upper bits for the offset.
* @param offset - The optional offset, this is an integer which represents what multiple of 360
* degrees to shift, only useful for flat projections, hence optional.
* @param localTangentSpace - Whether the tile geometry is in local tangent space or not.
*/
constructor(
readonly dataSource: DataSource,
readonly tileKey: TileKey,
offset: number = 0,
localTangentSpace?: boolean
) {
this.geoBox = this.dataSource.getTilingScheme().getGeoBox(this.tileKey);
this.updateBoundingBox();
this.m_worldCenter.copy(this.boundingBox.position);
this.m_localTangentSpace = localTangentSpace ?? false;
this.m_textStyleCache = new TileTextStyleCache(this);
this.m_offset = offset;
this.m_uniqueKey = TileKeyUtils.getKeyForTileKeyAndOffset(this.tileKey, this.offset);
if (dataSource.useGeometryLoader) {
this.m_tileGeometryLoader = new TileGeometryLoader(this, this.mapView.taskQueue);
this.attachGeometryLoadedCallback();
}
}
/**
* The visibility status of the {@link Tile}. It is actually
* visible or planned to become visible.
*/
get isVisible(): boolean {
// Tiles are not evaluated as invisible until the second frame they aren't requested.
// This happens in order to prevent that, during VisibleTileSet visibility evaluation,
// visible tiles that haven't yet been evaluated for the current frame are preemptively
// removed from [[DataSourceCache]].
// There is cases when a tile was already removed from the MapView, i.e. the PolaCaps
// Datasource might get remove on a change of projection, in this case
// this.dataSource.mapView will throw an error
try {
return this.frameNumLastRequested >= this.dataSource.mapView.frameNumber - 1;
} catch (error) {
logger.debug(error);
return false;
}
}
/**
* Sets the tile visibility status.
* @param visible - `True` to mark the tile as visible, `False` otherwise.
*/
set isVisible(visible: boolean) {
this.frameNumLastRequested = visible ? this.dataSource.mapView.frameNumber : -1;
if (!visible && this.m_tileGeometryLoader && !this.m_tileGeometryLoader.isSettled) {
this.m_tileGeometryLoader.cancel();
}
}
/**
* The {@link @xyzmaps/harp-geoutils#Projection} currently used by the {@link MapView}.
*/
get projection(): Projection {
return this.dataSource.projection;
}
/**
* The {@link MapView} this `Tile` belongs to.
*/
get mapView(): MapView {
return this.dataSource.mapView;
}
/**
* Whether the data of this tile is in local tangent space or not.
*
* @remarks
* If the data is in local tangent space (i.e. up vector is (0,0,1) for high zoomlevels) then
* {@link MapView} will rotate the objects before rendering using the rotation matrix of the
* oriented [[boundingBox]].
*/
get localTangentSpace(): boolean {
return this.m_localTangentSpace;
}
/*
* The size of this Tile in system memory.
*/
get memoryUsage(): number {
if (this.m_resourceInfo === undefined) {
this.computeResourceInfo();
}
return this.m_resourceInfo!.heapSize;
}
/**
* The center of this `Tile` in world coordinates.
*/
get center(): THREE.Vector3 {
return this.m_worldCenter;
}
/**
* Gets the key to uniquely represent this tile (based on
* the {@link tileKey} and {@link offset}).
*
* @remarks
* This key is only unique within the given {@link DataSource},
* to get a key which is unique across
* {@link DataSource}s see [[DataSourceCache.getKeyForTile]].
*/
get uniqueKey(): number {
return this.m_uniqueKey;
}
/**
* The optional offset, this is an integer which represents what multiple of 360 degrees to
* shift, only useful for flat projections, hence optional.
*/
get offset(): number {
return this.m_offset;
}
/**
* The optional offset, this is an integer which represents what multiple of 360 degrees to
* shift, only useful for flat projections, hence optional.
* @param offset - Which multiple of 360 degrees to apply to the {@link Tile}.
*/
set offset(offset: number) {
if (this.m_offset !== offset) {
this.m_uniqueKey = TileKeyUtils.getKeyForTileKeyAndOffset(this.tileKey, offset);
}
this.m_offset = offset;
}
/**
* Compute {@link TileResourceInfo} of this `Tile`.
*
* @remarks
* May be using a cached value. The method
* `invalidateResourceInfo` can be called beforehand to force a recalculation.
*
* @returns `TileResourceInfo` for this `Tile`.
*/
getResourceInfo(): TileResourceInfo {
if (this.m_resourceInfo === undefined) {
this.computeResourceInfo();
}
return this.m_resourceInfo!;
}
/**
* Force invalidation of the cached {@link TileResourceInfo}.
*
* @remarks
* Useful after the `Tile` has been
* modified.
*/
invalidateResourceInfo(): void {
this.m_resourceInfo = undefined;
}
/**
* Add ownership of a texture to this tile.
*
* @remarks
* The texture will be disposed if the `Tile` is disposed.
* @param texture - Texture to be owned by the `Tile`
*/
addOwnedTexture(texture: THREE.Texture): void {
this.m_ownedTextures.add(texture);
}
/**
* @internal
* @deprecated User text elements are deprecated.
*
* Gets the list of developer-defined {@link TextElement} in this `Tile`.
*
* @remarks
* This list is always rendered first.
*/
get userTextElements(): TextElementGroup {
let group = this.m_textElementGroups.groups.get(TextElement.HIGHEST_PRIORITY);
if (group === undefined) {
group = new TextElementGroup(TextElement.HIGHEST_PRIORITY);
this.m_textElementGroups.groups.set(group.priority, group);
}
return group;
}
/**
* Adds a developer-defined {@link TextElement} to this `Tile`.
*
* @remarks
* The {@link TextElement} is always
* visible, if it's in the map's currently visible area.
*
* @deprecated use [[addTextElement]].
*
* @param textElement - The Text element to add.
*/
addUserTextElement(textElement: TextElement) {
textElement.priority = TextElement.HIGHEST_PRIORITY;
this.addTextElement(textElement);
}
/**
* Removes a developer-defined {@link TextElement} from this `Tile`.
*
* @deprecated use `removeTextElement`.
*
* @param textElement - A developer-defined TextElement to remove.
* @returns `true` if the element has been removed successfully; `false` otherwise.
*/
removeUserTextElement(textElement: TextElement): boolean {
textElement.priority = TextElement.HIGHEST_PRIORITY;
return this.removeTextElement(textElement);
}
/**
* Adds a {@link TextElement} to this `Tile`, which is added to the visible set of
* {@link TextElement}s based on the capacity and visibility.
*
* @remarks
* The {@link TextElement}'s priority controls if or when it becomes visible.
*
* To ensure that a TextElement is visible, use a high value for its priority, such as
* `TextElement.HIGHEST_PRIORITY`. Since the number of visible TextElements is limited by the
* screen space, not all TextElements are visible at all times.
*
* @param textElement - The TextElement to add.
*/
addTextElement(textElement: TextElement) {
this.textElementGroups.add(textElement);
if (this.m_textElementsChanged === false) {
// HARP-8733: Clone all groups so that they are handled as new element groups
// by TextElementsRenderer and it doesn't try to reuse the same state stored
// for the old groups.
this.m_textElementGroups = this.textElementGroups.clone();
}
this.textElementsChanged = true;
}
/**
* Adds a `PathBlockingElement` to this `Tile`.
*
* @remarks
* This path has the highest priority and blocks
* all other labels. There maybe in future a use case to give it a priority, but as that isn't
* yet required, it is left to be implemented later if required.
* @param blockingElement - Element which should block all other labels.
*/
addBlockingElement(blockingElement: PathBlockingElement) {
this.m_pathBlockingElements.push(blockingElement);
}
/**
* Removes a {@link TextElement} from this `Tile`.
*
* @remarks
* For the element to be removed successfully, the
* priority of the {@link TextElement} has to be equal to its priority when it was added.
*
* @param textElement - The TextElement to remove.
* @returns `true` if the TextElement has been removed successfully; `false` otherwise.
*/
removeTextElement(textElement: TextElement): boolean {
const groups = this.textElementGroups;
if (!groups.remove(textElement)) {
return false;
}
if (this.m_textElementsChanged === false) {
// HARP-8733: Clone all groups so that they are handled as new element groups
// by TextElementsRenderer and it doesn't try to reuse the same state stored
// for the old groups.
this.m_textElementGroups = groups.clone();
}
this.textElementsChanged = true;
return true;
}
/**
* @internal
*
* Gets the current `GroupedPriorityList` which
* contains a list of all {@link TextElement}s to be
* selected and placed for rendering.
*/
get textElementGroups(): TextElementGroupPriorityList {
return this.m_textElementGroups;
}
/**
* Gets the current modification state for the list
* of {@link TextElement}s in the `Tile`.
*
* @remarks
* If the value is `true` the `TextElement` is placed for
* rendering during the next frame.
*/
get textElementsChanged(): boolean {
return this.m_textElementsChanged ?? false;
}
set textElementsChanged(changed: boolean) {
this.m_textElementsChanged = changed;
}
/**
* Returns true if the `Tile` has any text elements to render.
*/
hasTextElements(): boolean {
return this.m_textElementGroups.count() > 0;
}
/**
* Get the current blocking elements.
*/
get blockingElements(): PathBlockingElement[] {
return this.m_pathBlockingElements;
}
/**
* Called before {@link MapView} starts rendering this `Tile`.
*
* @remarks
* @param zoomLevel - The current zoom level.
* @returns Returns `true` if this `Tile` should be rendered. Influenced directly by the
* `skipRendering` property unless specifically overriden in deriving classes.
*/
willRender(_zoomLevel: number): boolean {
return !this.skipRendering && !this.delayRendering;
}
/**
* Called after {@link MapView} has rendered this `Tile`.
*/
didRender(): void {
// to be overridden by subclasses
}
/**
* Estimated visible area of tile used for sorting the priorities during loading.
*/
get visibleArea(): number {
return this.m_visibleArea;
}
set visibleArea(area: number) {
this.m_visibleArea = area;
if (this.tileLoader !== undefined) {
this.tileLoader.priority = area;
}
}
/**
* @internal
* Gets the tile's ground elevation range in meters.
*/
get elevationRange(): ElevationRange {
return this.m_elevationRange;
}
/**
* @internal
* Sets the tile's ground elevation range in meters.
*
* @param elevationRange - The elevation range.
*/
set elevationRange(elevationRange: ElevationRange) {
if (
elevationRange.minElevation === this.m_elevationRange.minElevation &&
elevationRange.maxElevation === this.m_elevationRange.maxElevation &&
elevationRange.calculationStatus === this.m_elevationRange.calculationStatus
) {
return;
}
this.m_elevationRange.minElevation = elevationRange.minElevation;
this.m_elevationRange.maxElevation = elevationRange.maxElevation;
this.m_elevationRange.calculationStatus = elevationRange.calculationStatus;
this.elevateGeoBox();
// Only update bounding box if tile has already been decoded and a maximum/minimum geometry
// height is provided by the data source.
if (this.m_maxGeometryHeight !== undefined || this.m_minGeometryHeight !== undefined) {
assert(this.decodedTile?.boundingBox === undefined);
this.updateBoundingBox();
}
}
/**
* Gets the decoded tile; it is removed after geometry handling.
*/
get decodedTile(): DecodedTile | undefined {
return this.m_decodedTile;
}
/**
* Applies the decoded tile to the tile.
*
* @remarks
* If the geometry is empty, then the tile's forceHasGeometry flag is set.
* Map is updated.
* @param decodedTile - The decoded tile to set.
*/
set decodedTile(decodedTile: DecodedTile | undefined) {
this.m_decodedTile = decodedTile;
this.invalidateResourceInfo();
if (decodedTile === undefined) {
return;
}
if (decodedTile.geometries.length === 0) {
this.forceHasGeometry(true);
}
// If the decoder provides a more accurate bounding box than the one we computed from
// the flat geo box we take it instead. Otherwise, if an elevation range was set, elevate
// bounding box to match the elevated geometry.
this.m_maxGeometryHeight = decodedTile.boundingBox
? undefined
: decodedTile.maxGeometryHeight ?? 0;
this.m_minGeometryHeight = decodedTile.boundingBox
? undefined
: decodedTile.minGeometryHeight ?? 0;
this.elevateGeoBox();
this.updateBoundingBox(decodedTile.boundingBox);
const stats = PerformanceStatistics.instance;
if (stats.enabled && decodedTile.decodeTime !== undefined) {
stats.currentFrame.addValue("decode.decodingTime", decodedTile.decodeTime);
stats.currentFrame.addValue("decode.decodedTiles", 1);
}
if (decodedTile.copyrightHolderIds !== undefined) {
this.copyrightInfo = decodedTile.copyrightHolderIds.map(id => ({ id }));
}
this.dataSource.requestUpdate();
}
/**
* Called when the default implementation of `dispose()` needs
* to free the geometry of a `Tile` object.
*
* @param object - The object that references the geometry.
* @returns `true` if the geometry can be disposed.
*/
shouldDisposeObjectGeometry(object: TileObject): boolean {
return true;
}
/**
* Called when the default implementation of `dispose()` needs
* to free a `Tile` object's material.
*
* @param object - The object referencing the geometry.
* @returns `true` if the material can be disposed.
*/
shouldDisposeObjectMaterial(object: TileObject): boolean {
return true;
}
/**
* Called when the default implementation of `dispose()` needs
* to free a Texture that is part of a `Tile` object's material.
*
* @param texture - The texture about to be disposed.
* @returns `true` if the texture can be disposed.
*/
shouldDisposeTexture(texture: THREE.Texture): boolean {
return this.m_ownedTextures.has(texture);
}
/**
* Returns `true` if this `Tile` has been disposed.
*/
get disposed(): boolean {
return this.m_disposed;
}
/**
* `True` if all geometry of the `Tile` has been loaded.
*/
get allGeometryLoaded(): boolean {
return this.m_tileGeometryLoader?.isFinished ?? this.hasGeometry;
}
/**
* MapView checks if this `Tile` is ready to be rendered while culling.
*
* By default, MapView checks if the [[objects]] list is not empty. However, you can override
* this check by manually setting this property.
*/
get hasGeometry(): boolean {
if (this.m_forceHasGeometry === undefined) {
return this.objects.length !== 0;
} else {
return this.m_forceHasGeometry;
}
}
/**
* Overrides the default value for [[hasGeometry]] if value is not `undefined`.
*
* @param value - A new value for the [[hasGeometry]] flag.
*/
forceHasGeometry(value: boolean | undefined) {
this.m_forceHasGeometry = value;
}
/**
* Reset the visibility counter. This will force the visibility check to be rerun on all objects
* in this `Tile`.
*/
resetVisibilityCounter(): void {
this.visibilityCounter = -1;
}
/**
* Gets the {@link ITileLoader} that manages this tile.
*/
get tileLoader(): ITileLoader | undefined {
return this.m_tileLoader;
}
/**
* Sets the {@link ITileLoader} to manage this tile.
*
* @param tileLoader - A {@link ITileLoader} instance to manage
* the loading process for this tile.
*/
set tileLoader(tileLoader: ITileLoader | undefined) {
this.m_tileLoader = tileLoader;
}
/**
* Loads this `Tile` geometry.
*
* @returns Promise which can be used to wait for the loading to be finished.
*/
async load(): Promise<void> {
const tileLoader = this.tileLoader;
if (tileLoader === undefined) {
return await Promise.resolve();
}
if (this.m_tileGeometryLoader) {
const wasSettled = this.m_tileGeometryLoader.isSettled;
this.m_tileGeometryLoader.reset();
if (wasSettled) {
this.attachGeometryLoadedCallback();
}
}
return await tileLoader
.loadAndDecode()
.then(tileLoaderState => {
assert(tileLoaderState === TileLoaderState.Ready);
const decodedTile = tileLoader.decodedTile;
this.decodedTile = decodedTile;
decodedTile?.dependencies?.forEach(mortonCode => {
this.dependencies.push(TileKey.fromMortonCode(mortonCode));
});
})
.catch(tileLoaderState => {
if (tileLoaderState === TileLoaderState.Failed) {
this.dispose();
} else if (tileLoaderState !== TileLoaderState.Canceled) {
logger.error("Unknown error" + tileLoaderState);
}
});
}
/**
* Text style cache for this tile.
* @hidden
*/
get textStyleCache(): TileTextStyleCache {
return this.m_textStyleCache;
}
/**
* Frees the rendering resources allocated by this `Tile`.
*
* @remarks
* The default implementation of this method frees the geometries and the materials for all the
* reachable objects.
* Textures are freed if they are owned by this `Tile` (i.e. if they where created by this
* `Tile`or if the ownership was explicitely set to this `Tile` by [[addOwnedTexture]]).
*/
clear() {
const disposeMaterial = (material: THREE.Material) => {
Object.getOwnPropertyNames(material).forEach((property: string) => {
const materialProperty = (material as any)[property];
if (materialProperty !== undefined && materialProperty instanceof THREE.Texture) {
const texture = materialProperty;
if (this.shouldDisposeTexture(texture)) {
texture.dispose();
}
}
});
material.dispose();
};
const disposeObject = (object: TileObject & DisposableObject) => {
if (this.shouldDisposeObjectGeometry(object)) {
if (object.geometry !== undefined) {
object.geometry.dispose();
}
if (object.geometries !== undefined) {
for (const geometry of object.geometries) {
geometry.dispose();
}
}
}
if (object.material !== undefined && this.shouldDisposeObjectMaterial(object)) {
if (object.material instanceof Array) {
object.material.forEach((material: THREE.Material | undefined) => {
if (material !== undefined) {
disposeMaterial(material);
}
});
} else {
disposeMaterial(object.material);
}
}
};
this.objects.forEach((rootObject: TileObject & DisposableObject) => {
rootObject.traverse((object: TileObject & DisposableObject) => {
disposeObject(object);
});
disposeObject(rootObject);
});
this.objects.length = 0;
if (this.preparedTextPaths) {
this.preparedTextPaths = [];
}
this.m_textStyleCache.clear();
this.clearTextElements();
this.invalidateResourceInfo();
}
/**
* Removes all {@link TextElement} from the tile.
*/
clearTextElements() {
if (!this.hasTextElements()) {
return;
}
this.textElementsChanged = true;
this.m_pathBlockingElements.splice(0);
this.textElementGroups.forEach((element: TextElement) => {
element.dispose();
});
this.textElementGroups.clear();
}
/**
* Adds a callback that will be called whenever the tile is disposed.
*
* @remarks
* Multiple callbacks may be added.
* @internal
* @param callback - The callback to be called when the tile is disposed.
*/
addDisposeCallback(callback: TileCallback) {
this.m_disposeCallback = chainCallbacks(this.m_disposeCallback, callback);
}
/**
* Disposes this `Tile`, freeing all geometries and materials for the reachable objects.
*/
dispose() {
if (this.m_disposed) {
return;
}
if (this.m_tileLoader) {
this.m_tileLoader.cancel();
this.m_tileLoader = undefined;
}
this.clear();
// Ensure that tile is removable from tile cache.