forked from heremaps/harp.gl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MapView.ts
3885 lines (3399 loc) · 135 KB
/
MapView.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 {
Env,
FontCatalogConfig,
MapEnv,
PostEffects,
TextStyleDefinition,
Theme,
Value
} from "@xyzmaps/harp-datasource-protocol";
import { ViewRanges } from "@xyzmaps/harp-datasource-protocol/lib/ViewRanges";
import {
EarthConstants,
GeoBox,
GeoBoxExtentLike,
GeoCoordinates,
GeoPolygon,
isGeoBoxExtentLike,
isGeoCoordinatesLike,
isVector3Like,
mercatorProjection,
OrientedBox3,
Projection,
ProjectionType,
TilingScheme,
Vector3Like
} from "@xyzmaps/harp-geoutils";
import { GeoCoordLike } from "@xyzmaps/harp-geoutils/lib/coordinates/GeoCoordLike";
import {
assert,
getOptionValue,
LoggerManager,
LogLevel,
PerformanceTimer,
TaskQueue,
UriResolver
} from "@xyzmaps/harp-utils";
import * as THREE from "three";
import { AnimatedExtrusionHandler } from "./AnimatedExtrusionHandler";
import { BackgroundDataSource } from "./BackgroundDataSource";
import { CameraMovementDetector } from "./CameraMovementDetector";
import { CameraUtils } from "./CameraUtils";
import { ClipPlanesEvaluator, createDefaultClipPlanesEvaluator } from "./ClipPlanesEvaluator";
import { IMapAntialiasSettings, IMapRenderingManager, MapRenderingManager } from "./composing";
import { ConcurrentDecoderFacade } from "./ConcurrentDecoderFacade";
import { ConcurrentTilerFacade } from "./ConcurrentTilerFacade";
import { CopyrightInfo } from "./copyrights/CopyrightInfo";
import { DataSource } from "./DataSource";
import { ElevationProvider } from "./ElevationProvider";
import { ElevationRangeSource } from "./ElevationRangeSource";
import { EventDispatcher } from "./EventDispatcher";
import {
DEFAULT_FOV_CALCULATION,
FovCalculation,
MAX_FOV_DEG,
MIN_FOV_DEG
} from "./FovCalculation";
import { FrustumIntersection } from "./FrustumIntersection";
import { overlayOnElevation } from "./geometry/overlayOnElevation";
import { TileGeometryManager } from "./geometry/TileGeometryManager";
import { MapViewImageCache } from "./image/MapViewImageCache";
import { IntersectParams } from "./IntersectParams";
import { MapAnchors } from "./MapAnchors";
import { MapViewEnvironment } from "./MapViewEnvironment";
import { MapViewFog } from "./MapViewFog";
import { MapViewTaskScheduler } from "./MapViewTaskScheduler";
import { MapViewThemeManager } from "./MapViewThemeManager";
import { PickHandler, PickResult } from "./PickHandler";
import { PoiManager } from "./poi/PoiManager";
import { PoiTableManager } from "./poi/PoiTableManager";
import { PolarTileDataSource } from "./PolarTileDataSource";
import { ScreenProjector } from "./ScreenProjector";
import { FrameStats, PerformanceStatistics } from "./Statistics";
import { MapViewState } from "./text/MapViewState";
import { TextElement } from "./text/TextElement";
import { TextElementsRenderer } from "./text/TextElementsRenderer";
import { TextElementsRendererOptions } from "./text/TextElementsRendererOptions";
import { Tile } from "./Tile";
import { TileObjectRenderer } from "./TileObjectsRenderer";
import { MapViewUtils } from "./Utils";
import { ResourceComputationType, VisibleTileSet, VisibleTileSetOptions } from "./VisibleTileSet";
declare const process: any;
// Cache value, because access to process.env.NODE_ENV is SLOW!
const isProduction = process.env.NODE_ENV === "production";
if (isProduction) {
// In production: silence logging below error.
LoggerManager.instance.setLogLevelForAll(LogLevel.Error);
} else {
// In dev: silence logging below log (silences "debug" and "trace" levels).
LoggerManager.instance.setLogLevelForAll(LogLevel.Log);
}
export enum TileTaskGroups {
FETCH_AND_DECODE = "fetch",
//DECODE = "decode",
CREATE = "create"
//UPLOAD = "upload"
}
export enum MapViewEventNames {
/** Called before this `MapView` starts to render a new frame. */
Update = "update",
/** Called when the WebGL canvas is resized. */
Resize = "resize",
/** Called when the frame is about to be rendered. */
Render = "render",
/** Called after a frame has been rendered. */
AfterRender = "didrender",
/** Called after the first frame has been rendered. */
FirstFrame = "first-render",
/**
* Called when the rendered frame was complete, i.e. all the necessary tiles and resources
* are loaded and rendered.
*/
FrameComplete = "frame-complete",
/** Called when the theme has been loaded with the internal {@link ThemeLoader}. */
ThemeLoaded = "theme-loaded",
/** Called when the animation mode has started. */
AnimationStarted = "animation-started",
/** Called when the animation mode has stopped. */
AnimationFinished = "animation-finished",
/** Called when a camera interaction has been detected. */
MovementStarted = "movement-started",
/** Called when a camera interaction has been stopped. */
MovementFinished = "movement-finished",
/** Called when a data source has been connected or failed to connect. */
DataSourceConnect = "datasource-connect",
/** Emitted when copyright info of rendered map has been changed. */
CopyrightChanged = "copyright-changed",
/** Called when the WebGL context is lost. */
ContextLost = "webglcontext-lost",
/** Called when the WebGL context is restored. */
ContextRestored = "webglcontext-restored",
/** Called when camera position has been changed. */
CameraPositionChanged = "camera-changed",
/** Called when dispose has been called, before any cleanup is done. */
Dispose = "dispose"
}
const logger = LoggerManager.instance.create("MapView");
const DEFAULT_CAM_NEAR_PLANE = 0.1;
const DEFAULT_CAM_FAR_PLANE = 4000000;
const DEFAULT_MIN_ZOOM_LEVEL = 1;
/**
* Default maximum zoom level.
*/
const DEFAULT_MAX_ZOOM_LEVEL = 20;
/**
* Default minimum camera height.
*/
const DEFAULT_MIN_CAMERA_HEIGHT = 20;
/**
* Style set used by {@link PolarTileDataSource} by default.
*/
const DEFAULT_POLAR_STYLE_SET_NAME = "polar";
/**
* The type of `RenderEvent`.
*/
export interface RenderEvent extends THREE.Event {
type: MapViewEventNames;
time?: number;
}
const cache = {
vector2: [new THREE.Vector2()],
vector3: [new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3()],
rayCaster: new THREE.Raycaster(),
groundPlane: new THREE.Plane(),
groundSphere: new THREE.Sphere(undefined, EarthConstants.EQUATORIAL_RADIUS),
matrix4: [new THREE.Matrix4(), new THREE.Matrix4()],
transform: [
{
position: new THREE.Vector3(),
xAxis: new THREE.Vector3(),
yAxis: new THREE.Vector3(),
zAxis: new THREE.Vector3()
}
],
color: new THREE.Color()
};
/**
* Hint for the WebGL implementation on which power mode to prefer.
*
* @see https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.12
*/
export enum MapViewPowerPreference {
/** Default value. */
Default = "default",
/** Lower power mode, used to conserve energy. */
LowPower = "low-power",
/** Maximum performance. */
HighPerformance = "high-performance"
}
/**
* User configuration for the {@link MapView}.
*/
export interface MapViewOptions extends TextElementsRendererOptions, Partial<LookAtParams> {
/**
* The canvas element used to render the scene.
*/
canvas: HTMLCanvasElement;
/**
* Optional WebGL Rendering Context.
* (https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext)
*/
context?: WebGLRenderingContext;
/**
* `true` if the canvas contains an alpha (transparency) buffer or not. Default is `false`.
*/
alpha?: boolean;
/**
* If `true`adds a Background Mesh for each tile
*
* @default `true`
*/
addBackgroundDatasource?: boolean;
/**
* Whether the native WebGL antialiasing should be enabled. It is better to disable it if the
* MapView's MSAA is enabled.
*
* @default `true` for `pixelRatio` < `2.0`, `false` otherwise.
*/
enableNativeWebglAntialias?: boolean;
/**
* Antialias settings for the map rendering. It is better to disable the native antialiasing if
* the custom antialiasing is enabled.
*/
customAntialiasSettings?: IMapAntialiasSettings;
/**
* `Projection` used by the `MapView`.
*
* The default value is [[mercatorProjection]].
*/
projection?: Projection;
/**
* The URL of the script that the decoder worker runs. The default URL is
* `./decoder.bundle.js`.
*
* Relative URIs are resolved to full URL using the document's base URL
* (see: https://www.w3.org/TR/WD-html40-970917/htmlweb.html#h-5.1.2).
*/
decoderUrl?: string;
/**
* The number of Web Workers used to decode data. The default is
* CLAMP(`navigator.hardwareConcurrency` - 1, 1, 2).
*/
decoderCount?: number;
/**
* The {@link @xyzmaps/harp-datasource-protocol#Theme} used by Mapview.
*
* This Theme can be one of the following:
* - `string` : the URI of the theme file used to style this map
* - `Theme` : the `Theme` object already loaded
* - `Promise<Theme>` : the future `Theme` object
* - `undefined` : the theme is not yet set up, but can be set later. Rendering waits until
* the theme is set.
*
* **Note:** Layers that use a theme do not render any content until that theme is available.
*
* Relative URIs are resolved to full URL using the document's base URL
* (see: https://www.w3.org/TR/WD-html40-970917/htmlweb.html#h-5.1.2).
*
* Custom URIs (of theme itself and of resources referenced by theme) may be resolved with help
* of [[uriResolver]].
*
* @see {@link ThemeLoader.load} for details how theme is loaded
*/
theme?: string | Theme | Promise<Theme>;
/**
* Resolve `URI` referenced in `MapView` assets using this resolver.
*
* Use, to support application/deployment specific `URI`s into actual `URLs` that can be loaded
* with `fetch`.
*
* Example:
* ```
* uriResolver: new PrefixMapUriResolver({
* "local://poiMasterList": "/assets/poiMasterList.json",
* // will match only 'local//:poiMasterList' and
* // resolve to `/assets/poiMasterList.json`
* "local://icons/": "/assets/icons/"
* // will match only 'local//:icons/ANYPATH' (and similar) and
* // resolve to `/assets/icons/ANYPATH`
* })
* ```
*
* @see {@link @xyzmaps/harp-utils#UriResolver}
* @See {@link @xyzmaps/harp-utils#PrefixMapUriResolver}
*/
uriResolver?: UriResolver;
/**
* The minimum zoom level; default is `1`.
*/
minZoomLevel?: number;
/**
* Determines the minimum camera height, in meters.
*/
minCameraHeight?: number;
/**
* The maximum zoom level. The default is `14`.
*/
maxZoomLevel?: number;
/**
* User-defined camera clipping planes distance evaluator.
* If not defined, {@link TiltViewClipPlanesEvaluator} will be used by {@link MapView}.
*
* @default {@link TiltViewClipPlanesEvaluator}
*/
clipPlanesEvaluator?: ClipPlanesEvaluator;
/**
* Set to true to extend the frustum culling. This improves the rejection of some tiles, which
* normal frustum culling cannot detect. You can disable this property to measure performance.
*
* @default true
*/
extendedFrustumCulling?: boolean;
/**
* The maximum number of tiles rendered from one data source at a time.
*
* @default See [[MapViewDefaults.maxVisibleDataSourceTiles]].
*/
maxVisibleDataSourceTiles?: number;
/**
* Size of a tile cache for one data source.
*
* @default See [[MapViewDefaults.tileCacheSize]].
*/
tileCacheSize?: number;
/**
* Specify if the cache should be counted in tiles or in megabytes.
*
* @see [[MapViewDefaults.resourceComputationType]].
*/
resourceComputationType?: ResourceComputationType;
/**
* Limits the number of reduced zoom levels (lower detail)
* to be searched for fallback tiles.
*
* When zooming in, newly elected tiles may have not
* yet loaded. {@link MapView} searches through
* the tile cache for tiles ready to be displayed in
* lower zoom levels. The tiles may be
* located shallower in the quadtree.
*
* To disable a cache search, set the value to `0`.
*
* @default [[MapViewDefaults.quadTreeSearchDistanceUp]]
*/
quadTreeSearchDistanceUp?: number;
/**
* Limits the number of higher zoom levels (more detailed)
* to be searched for fallback tiles.
*
* When zooming out, newly elected tiles may have not
* yet loaded. {@link MapView} searches through
* the tile cache for tiles ready to be displayed in
* higher zoom levels. These tiles may be
* located deeper in the quadtree.
*
* To disable a cache search, set the value to `0`.
*
* @default [[MapViewDefaults.quadTreeSearchDistanceDown]]
*/
quadTreeSearchDistanceDown?: number;
/**
* Set to `true` to measure performance statistics.
*/
enableStatistics?: boolean;
/**
* Preserve the buffers until they are cleared manually or overwritten.
*
* Set to `true` in order to copy {@link MapView} canvas contents
* to an image or another canvas.
*
* @default `false`.
* @see https://threejs.org/docs/#api/renderers/WebGLRenderer.preserveDrawingBuffer
*/
preserveDrawingBuffer?: boolean;
/**
* @deprecated Not needed anymore, roads can be picked by default.
*/
enableRoadPicking?: boolean;
/**
* Set to `true` to allow picking of technique information associated with objects.
*/
enablePickTechnique?: boolean;
/**
* Maximum timeout, in milliseconds, before a [[MOVEMENT_FINISHED_EVENT]] is sent after the
* latest frame with a camera movement. The default is 300ms.
*/
movementThrottleTimeout?: number;
/**
* How to calculate the Field of View, if not specified, then
* [[DEFAULT_FOV_CALCULATION]] is used.
*/
fovCalculation?: FovCalculation;
/*
* An array of ISO 639-1 language codes for data sources.
*/
languages?: string[];
/**
* Sets the data sources to use specific country point of view (political view).
*
* This option may result in rendering different country borders then commonly accepted for
* some regions and it mainly regards to so called __disputed borders__. Although not all
* data sources or themes may support it.
*
* @note Country code should be coded in lower-case ISO 3166-1 alpha-2 standard, if this option
* is `undefined` the majority point of view will be used.
*/
politicalView?: string;
/**
* Set fixed pixel ratio for rendering. Useful when rendering on high resolution displays with
* low performance GPUs that may be fill-rate limited.
* @default `window.devicePixelRatio`
*/
pixelRatio?: number;
/**
* Set fixed pixel ratio for rendering when the camera is moving or an animation is running.
* Useful when rendering on high resolution displays with low performance GPUs that may be
* fill-rate limited.
*
* If a value is specified, a low resolution render pass is used to render the scene into a
* low resolution render target, before it is copied to the screen.
*
* A value of `undefined` disables the low res render pass. Values between 0.5 and
* `window.devicePixelRatio` can be tried to give good results. The value should not be larger
* than `window.devicePixelRatio`.
*
* @note Since no anti-aliasing is applied during dynamic rendering with `dynamicPixelRatio`
* defined, visual artifacts may occur, especially with thin lines..
*
* @note The resolution of icons and text labels is not affected.
*
* @default `undefined`
*/
dynamicPixelRatio?: number;
/**
* Set maximum FPS (Frames Per Second). If VSync in enabled, the specified number may not be
* reached, but instead the next smaller number than `maxFps` that is equal to the refresh rate
* divided by an integer number.
*
* E.g.: If the monitors refresh rate is set to 60hz, and if `maxFps` is set to a value of `40`
* (60hz/1.5), the actual used FPS may be 30 (60hz/2). For displays that have a refresh rate of
* 60hz, good values for `maxFps` are 30, 20, 15, 12, 10, 6, 3 and 1. A value of `0` is ignored.
*/
maxFps?: number;
/**
* Enable map repeat for planar projections.
* If `true`, map will be repeated in longitudinal direction continuously.
* If `false`, map will end on lon -180 & 180 deg.
*
* @default `true`
*/
tileWrappingEnabled?: boolean;
/**
* Set tiling scheme for [[BackgroundDataSource]]
*/
backgroundTilingScheme?: TilingScheme;
/**
* Should be the {@link PolarTileDataSource} used on spherical projection.
* Default is `true`.
*/
enablePolarDataSource?: boolean;
/**
* The name of the [[StyleSet]] used by {@link PolarTileDataSource}
* to evaluate for the decoding.
* Default is `"polar"`.
*/
polarStyleSetName?: string;
/**
* Storage level offset of regular tiles from reference datasource to align
* {@link PolarTileDataSource} tiles to.
* Default is `-1`.
*/
polarGeometryLevelOffset?: number;
/**
* Hint for the WebGL implementation on which power mode to prefer.
*/
powerPreference?: MapViewPowerPreference;
/**
* Set to `true` to allow rendering scene synchronously.
*
* By calling `renderSync()` scene draws immediately, opposite to default case when
* `update` method requests redraw and waits for the next animation frame.
*
* You need to set up your own render loop controller.
* Event `MapViewEventNames.Update` fired when {@link MapView} requests for an redraw.
* E.g.: When tiles loaded asynchronously and ready for rendering.
*
* @note Internal `maxFps` will be overridden and may not work properly as `renderSync`
* intended to be called from external render loop.
*
* @default false.
*/
synchronousRendering?: boolean;
/**
* Set true to enable rendering mixed levels of detail (increases rendering performance).
* If not set will enable mixed levels of detail for spherical projection
* and disable for other projections.
*
* @default undefined
*/
enableMixedLod?: boolean;
/**
* If enableMixedLod is `true`, this value will be used to calculate the minimum Pixel Size of a
* tile regarding to the screen size. When the area of a tile is smaller then this calculated
* area on the screen, the subdivision of tiles is stopped and therefore higher level tiles will
* be rendered instead.
* @beta
*
* @default 256
*/
lodMinTilePixelSize?: number;
/**
* Enable shadows in the map. Shadows will only be casted on features that use the "standard"
* or "extruded-polygon" technique in the map theme.
* @default false
*/
enableShadows?: boolean;
/**
* Enable throttling for the TaskScheduler
* @default false
* @beta
*/
throttlingEnabled?: boolean;
/**
* If set, the view will constrained within the given bounds in geo coordinates.
*/
maxBounds?: GeoBox;
}
/**
* Default settings used by {@link MapView} collected in one place.
* @internal
*/
const MapViewDefaults = {
projection: mercatorProjection,
addBackgroundDatasource: true,
maxVisibleDataSourceTiles: 100,
extendedFrustumCulling: true,
tileCacheSize: 200,
resourceComputationType: ResourceComputationType.EstimationInMb,
quadTreeSearchDistanceUp: 3,
quadTreeSearchDistanceDown: 2,
pixelRatio:
typeof window !== "undefined" && window.devicePixelRatio !== undefined
? window.devicePixelRatio
: 1.0,
target: new GeoCoordinates(25, 0),
zoomLevel: 5,
tilt: 0,
heading: 0,
theme: {},
maxTilesPerFrame: 0
};
/**
* Parameters for {@link (MapView.lookAt:WITH_PARAMS)}.
*/
export interface LookAtParams {
/**
* Target/look at point of the MapView.
*
* @note If the given point is not on the ground (altitude != 0) {@link MapView} will do a
* raycasting internally to find a target on the ground.
*
* As a consequence {@link MapView.target} and {@link MapView.zoomLevel}
* will not match the values
* that were passed into the {@link (MapView.lookAt:WITH_PARAMS)} method.
* @default `new GeoCoordinates(25, 0)` in {@link MapView.constructor} context.
* @default {@link MapView.target} in {@link (MapView.lookAt:WITH_PARAMS)} context.
*/
target: GeoCoordLike;
/**
* Fit MapView to these boundaries.
*
* If specified, `zoomLevel` and `distance` parameters are ignored and `lookAt` calculates best
* `zoomLevel` to fit given bounds.
*
* * if `bounds` is {@link @xyzmaps/harp-geoutils#GeoBox}, then `lookAt`
* use {@link LookAtParams.target} or `bounds.target` and
* ensure whole box is visible
*
* * if `bounds` is {@link @xyzmaps/harp-geoutils#GeoPolygon}, then `lookAt`
* use `bounds.getCentroid()` and ensure whole polygon is visible
*
* * if `bounds` is {@link @xyzmaps/harp-geoutils#GeoBoxExtentLike},
* then `lookAt` will use {@link LookAtParams.target} or
* current {@link MapView.target} and ensure whole extents are visible
*
* * if `bounds` is [[GeoCoordLike]][], then `lookAt` will use {@link LookAtParams.target} or
* calculated `target` as center of world box covering given points and ensure all points are
* visible
*
* Note in sphere projection some points are not visible if you specify bounds that span more
* than 180 degrees in any direction.
*
* @see {@link (MapView.lookAt:WITH_PARAMS)} for details on how `bounds`
* interact with `target` parameter
*/
bounds: GeoBox | GeoBoxExtentLike | GeoCoordLike[] | GeoPolygon;
/**
* Camera distance to the target point in world units.
* @default zoomLevel defaults will be used if not set.
*/
distance: number;
/**
* Zoomlevel of the MapView.
* @note Takes precedence over distance.
* @default 5 in {@link MapView.constructor} context.
* @default {@link MapView.zoomLevel} in {@link (MapView.lookAt:WITH_PARAMS)} context.
*/
zoomLevel: number;
/**
* Tilt angle in degrees. 0 is top down view.
* @default 0 in {@link MapView.constructor} context.
* @default {@link MapView.tilt} in {@link (MapView.lookAt:WITH_PARAMS)} context.
* @note Maximum supported tilt is 89°
*/
tilt: number;
/**
* Heading angle in degrees and clockwise. 0 is north-up.
* @default 0 in {@link MapView.constructor} context.
* @default {@link MapView.heading} in {@link (MapView.lookAt:WITH_PARAMS)} context.
*/
heading: number;
}
/**
* The core class of the library to call in order to create a map visualization. It needs to be
* linked to datasources.
*/
export class MapView extends EventDispatcher {
/**
* Keep the events here to avoid a global reference to MapView (and thus prevent garbage collection).
*/
private readonly UPDATE_EVENT: RenderEvent = { type: MapViewEventNames.Update };
private readonly RENDER_EVENT: RenderEvent = { type: MapViewEventNames.Render };
private readonly DID_RENDER_EVENT: RenderEvent = { type: MapViewEventNames.AfterRender };
private readonly FIRST_FRAME_EVENT: RenderEvent = { type: MapViewEventNames.FirstFrame };
private readonly FRAME_COMPLETE_EVENT: RenderEvent = {
type: MapViewEventNames.FrameComplete
};
private readonly THEME_LOADED_EVENT: RenderEvent = {
type: MapViewEventNames.ThemeLoaded
};
private readonly ANIMATION_STARTED_EVENT: RenderEvent = {
type: MapViewEventNames.AnimationStarted
};
private readonly ANIMATION_FINISHED_EVENT: RenderEvent = {
type: MapViewEventNames.AnimationFinished
};
private readonly MOVEMENT_STARTED_EVENT: RenderEvent = {
type: MapViewEventNames.MovementStarted
};
private readonly MOVEMENT_FINISHED_EVENT: RenderEvent = {
type: MapViewEventNames.MovementFinished
};
private readonly CONTEXT_LOST_EVENT: RenderEvent = {
type: MapViewEventNames.ContextLost
};
private readonly CONTEXT_RESTORED_EVENT: RenderEvent = {
type: MapViewEventNames.ContextRestored
};
private readonly COPYRIGHT_CHANGED_EVENT: RenderEvent = {
type: MapViewEventNames.CopyrightChanged
};
private readonly DISPOSE_EVENT: RenderEvent = { type: MapViewEventNames.Dispose };
/**
* The instance of {@link MapRenderingManager} managing the rendering of the map. It is a public
* property to allow access and modification of some parameters of the rendering process at
* runtime.
*/
readonly mapRenderingManager: IMapRenderingManager;
private m_renderLabels: boolean = true;
private m_movementFinishedUpdateTimerId?: any;
private m_postEffects?: PostEffects;
private readonly m_screenProjector: ScreenProjector;
private m_visibleTiles: VisibleTileSet;
private readonly m_tileObjectRenderer: TileObjectRenderer;
private m_elevationSource?: DataSource;
private m_elevationRangeSource?: ElevationRangeSource;
private m_elevationProvider?: ElevationProvider;
private m_visibleTileSetLock: boolean = false;
private readonly m_tileGeometryManager: TileGeometryManager;
private m_tileWrappingEnabled: boolean = true;
private m_zoomLevel: number = DEFAULT_MIN_ZOOM_LEVEL;
private m_minZoomLevel: number = DEFAULT_MIN_ZOOM_LEVEL;
private m_maxZoomLevel: number = DEFAULT_MAX_ZOOM_LEVEL;
private readonly m_minCameraHeight: number = DEFAULT_MIN_CAMERA_HEIGHT;
private m_geoMaxBounds?: GeoBox;
private m_worldMaxBounds?: THREE.Box3 | OrientedBox3;
private readonly m_camera: THREE.PerspectiveCamera;
/**
* Relative to eye camera.
*
* This camera is internal camera used to improve precision
* when rendering geometries.
*/
private readonly m_rteCamera = new THREE.PerspectiveCamera();
private m_yaw = 0;
private m_pitch = 0;
private m_roll = 0;
private m_targetDistance = 0;
private m_targetGeoPos = GeoCoordinates.fromObject(MapViewDefaults.target!);
// Focus point world coords may be calculated after setting projection, use dummy value here.
private readonly m_targetWorldPos = new THREE.Vector3();
private readonly m_viewRanges: ViewRanges = {
near: DEFAULT_CAM_NEAR_PLANE,
far: DEFAULT_CAM_FAR_PLANE,
minimum: DEFAULT_CAM_NEAR_PLANE,
maximum: DEFAULT_CAM_FAR_PLANE
};
private m_pointOfView?: THREE.PerspectiveCamera;
private m_pixelToWorld?: number;
private m_pixelRatio?: number;
/** Default scene for map objects and map anchors */
private readonly m_scene: THREE.Scene = new THREE.Scene();
/** Separate scene for overlay map anchors */
private readonly m_overlayScene: THREE.Scene = new THREE.Scene();
/** Root node of [[m_scene]] that gets cleared every frame. */
private readonly m_sceneRoot = new THREE.Object3D();
/** Root node of [[m_overlayScene]] that gets cleared every frame. */
private readonly m_overlaySceneRoot = new THREE.Object3D();
private readonly m_mapAnchors: MapAnchors = new MapAnchors();
private m_animationCount: number = 0;
private m_animationFrameHandle: number | undefined;
private m_drawing: boolean = false;
private m_updatePending: boolean = false;
private readonly m_renderer: THREE.WebGLRenderer;
private m_frameNumber = 0;
private m_textElementsRenderer: TextElementsRenderer;
private m_forceCameraAspect: number | undefined = undefined;
// type any as it returns different types depending on the environment
private m_taskSchedulerTimeout: any = undefined;
//
// sources
//
private readonly m_tileDataSources: DataSource[] = [];
private readonly m_connectedDataSources = new Set<string>();
private readonly m_failedDataSources = new Set<string>();
private readonly m_polarDataSource?: PolarTileDataSource;
private readonly m_enablePolarDataSource: boolean = true;
// gestures
private readonly m_raycaster = new THREE.Raycaster();
private readonly m_plane = new THREE.Plane(new THREE.Vector3(0, 0, 1));
private readonly m_sphere = new THREE.Sphere(undefined, EarthConstants.EQUATORIAL_RADIUS);
private readonly m_options: MapViewOptions;
private readonly m_visibleTileSetOptions: VisibleTileSetOptions;
private readonly m_uriResolver?: UriResolver;
private m_previousFrameTimeStamp?: number;
private m_firstFrameRendered = false;
private m_firstFrameComplete = false;
private readonly handleRequestAnimationFrame: (frameStartTime: number) => void;
private readonly m_pickHandler: PickHandler;
private readonly m_userImageCache: MapViewImageCache = new MapViewImageCache();
private readonly m_env: MapEnv = new MapEnv({});
private readonly m_poiManager: PoiManager = new PoiManager(this);
private readonly m_poiTableManager: PoiTableManager = new PoiTableManager(this);
private readonly m_collisionDebugCanvas: HTMLCanvasElement | undefined;
// Detection of camera movement and scene change:
private readonly m_movementDetector: CameraMovementDetector;
private m_thisFrameTilesChanged: boolean | undefined;
private m_lastTileIds: string = "";
private m_languages: string[] | undefined;
private m_politicalView: string | undefined;
private m_copyrightInfo: CopyrightInfo[] = [];
private readonly m_animatedExtrusionHandler: AnimatedExtrusionHandler;
private m_enableMixedLod: boolean | undefined;
private readonly m_lodMinTilePixelSize: number | undefined;
private m_taskScheduler: MapViewTaskScheduler;
private readonly m_themeManager: MapViewThemeManager;
private readonly m_sceneEnvironment: MapViewEnvironment;
// `true` if dispose() has been called on `MapView`.
private m_disposed = false;
/**
* Constructs a new `MapView` with the given options or canvas element.
*
* @param options - The `MapView` options or the HTML canvas element used to display the map.
*/
constructor(options: MapViewOptions) {
super();
// make a copy to avoid unwanted changes to the original options.
this.m_options = { ...options };
this.m_uriResolver = this.m_options.uriResolver;
if (this.m_options.minZoomLevel !== undefined) {
this.m_minZoomLevel = this.m_options.minZoomLevel;
}
if (this.m_options.maxZoomLevel !== undefined) {
this.m_maxZoomLevel = this.m_options.maxZoomLevel;
}
if (this.m_options.minCameraHeight !== undefined) {
this.m_minCameraHeight = this.m_options.minCameraHeight;
}
if (this.m_options.maxBounds !== undefined) {
this.m_geoMaxBounds = this.m_options.maxBounds;
}
if (this.m_options.decoderUrl !== undefined) {
ConcurrentDecoderFacade.defaultScriptUrl = this.m_uriResolver
? this.m_uriResolver.resolveUri(this.m_options.decoderUrl)
: this.m_options.decoderUrl;
}
if (this.m_options.decoderCount !== undefined) {
ConcurrentDecoderFacade.defaultWorkerCount = this.m_options.decoderCount;
}
this.m_visibleTileSetOptions = {
...MapViewDefaults,
clipPlanesEvaluator:
options.clipPlanesEvaluator !== undefined
? options.clipPlanesEvaluator
: createDefaultClipPlanesEvaluator()
};
if (options.projection !== undefined) {
this.m_visibleTileSetOptions.projection = options.projection;
}
if (options.extendedFrustumCulling !== undefined) {
this.m_visibleTileSetOptions.extendedFrustumCulling = options.extendedFrustumCulling;
}
if (options.maxVisibleDataSourceTiles !== undefined) {
this.m_visibleTileSetOptions.maxVisibleDataSourceTiles =
options.maxVisibleDataSourceTiles;
}
if (options.tileCacheSize !== undefined) {
this.m_visibleTileSetOptions.tileCacheSize = options.tileCacheSize;
}
if (options.resourceComputationType !== undefined) {
this.m_visibleTileSetOptions.resourceComputationType = options.resourceComputationType;
}
if (options.quadTreeSearchDistanceUp !== undefined) {
this.m_visibleTileSetOptions.quadTreeSearchDistanceUp =
options.quadTreeSearchDistanceUp;
}
if (options.quadTreeSearchDistanceDown !== undefined) {
this.m_visibleTileSetOptions.quadTreeSearchDistanceDown =
options.quadTreeSearchDistanceDown;
}
if (options.enablePolarDataSource !== undefined) {
this.m_enablePolarDataSource = options.enablePolarDataSource;
}
this.m_pixelRatio = options.pixelRatio;
this.m_options.maxFps = this.m_options.maxFps ?? 0;
this.m_options.enableStatistics = this.m_options.enableStatistics === true;
this.m_languages = this.m_options.languages;
this.m_politicalView = this.m_options.politicalView;
this.handleRequestAnimationFrame = this.renderLoop.bind(this);
if (this.m_options.tileWrappingEnabled !== undefined) {
this.m_tileWrappingEnabled = this.m_options.tileWrappingEnabled;
}
// Initialization of the stats
this.setupStats(this.m_options.enableStatistics);
this.canvas.addEventListener("webglcontextlost", this.onWebGLContextLost);
this.canvas.addEventListener("webglcontextrestored", this.onWebGLContextRestored);
// Initialization of the renderer, enable backward compatibility with three.js <= 0.117
this.m_renderer = new ((THREE as any).WebGL1Renderer ?? THREE.WebGLRenderer)({
canvas: this.canvas,
context: this.m_options.context,
antialias: this.nativeWebglAntialiasEnabled,
alpha: this.m_options.alpha,
preserveDrawingBuffer: this.m_options.preserveDrawingBuffer === true,
powerPreference:
this.m_options.powerPreference === undefined
? MapViewPowerPreference.Default
: this.m_options.powerPreference
});
this.m_renderer.autoClear = false;