forked from maplibre/maplibre-gl-js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathglobe_transform.ts
1124 lines (985 loc) · 47.5 KB
/
globe_transform.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
import {mat2, mat4, vec3, vec4} from 'gl-matrix';
import {MAX_VALID_LATITUDE, TransformHelper, TransformUpdateResult} from '../transform_helper';
import {MercatorTransform} from './mercator_transform';
import {LngLat, earthRadius} from '../lng_lat';
import {angleToRotateBetweenVectors2D, clamp, differenceOfAnglesDegrees, distanceOfAnglesRadians, easeCubicInOut, lerp, pointPlaneSignedDistance, warnOnce} from '../../util/util';
import {UnwrappedTileID, OverscaledTileID, CanonicalTileID} from '../../source/tile_id';
import Point from '@mapbox/point-geometry';
import {browser} from '../../util/browser';
import {Terrain} from '../../render/terrain';
import {GlobeProjection, globeConstants} from './globe';
import {ProjectionData} from '../../render/program/projection_program';
import {MercatorCoordinate} from '../mercator_coordinate';
import {PointProjection} from '../../symbol/projection';
import {LngLatBounds} from '../lng_lat_bounds';
import {IReadonlyTransform, ITransform} from '../transform_interface';
import {PaddingOptions} from '../edge_insets';
import {tileCoordinatesToMercatorCoordinates} from './mercator_utils';
import {angularCoordinatesRadiansToVector, angularCoordinatesToSurfaceVector, getGlobeRadiusPixels, getZoomAdjustment, mercatorCoordinatesToAngularCoordinatesRadians, sphereSurfacePointToCoordinates} from './globe_utils';
/**
* Describes the intersection of ray and sphere.
* When null, no intersection occured.
* When both "t" values are the same, the ray just touched the sphere's surface.
* When both value are different, a full intersection occured.
*/
type RaySphereIntersection = {
/**
* The ray parameter for intersection that is "less" along the ray direction.
* Note that this value can be negative, meaning that this intersection occured before the ray's origin.
* The intersection point can be computed as `origin + direction * tMin`.
*/
tMin: number;
/**
* The ray parameter for intersection that is "more" along the ray direction.
* Note that this value can be negative, meaning that this intersection occured before the ray's origin.
* The intersection point can be computed as `origin + direction * tMax`.
*/
tMax: number;
} | null;
// These functions create **64** bit float vectors and matrices, unlike default gl-matrix functions.
function createVec4(): vec4 { return new Float64Array(4) as any; }
function createVec3(): vec3 { return new Float64Array(3) as any; }
function createMat4(): mat4 { return new Float64Array(16) as any; }
function createIdentityMat4(): mat4 {
const m = new Float64Array(16) as any;
mat4.identity(m);
return m;
}
export class GlobeTransform implements ITransform {
private _helper: TransformHelper;
//
// Implementation of transform getters and setters
//
get pixelsToClipSpaceMatrix(): mat4 {
return this._helper.pixelsToClipSpaceMatrix;
}
get clipSpaceToPixelsMatrix(): mat4 {
return this._helper.clipSpaceToPixelsMatrix;
}
get pixelsToGLUnits(): [number, number] {
return this._helper.pixelsToGLUnits;
}
get centerOffset(): Point {
return this._helper.centerOffset;
}
get size(): Point {
return this._helper.size;
}
get rotationMatrix(): mat2 {
return this._helper.rotationMatrix;
}
get centerPoint(): Point {
return this._helper.centerPoint;
}
get pixelsPerMeter(): number {
return this._helper.pixelsPerMeter;
}
setMinZoom(zoom: number): void {
this._helper.setMinZoom(zoom);
}
setMaxZoom(zoom: number): void {
this._helper.setMaxZoom(zoom);
}
setMinPitch(pitch: number): void {
this._helper.setMinPitch(pitch);
}
setMaxPitch(pitch: number): void {
this._helper.setMaxPitch(pitch);
}
setRenderWorldCopies(renderWorldCopies: boolean): void {
this._helper.setRenderWorldCopies(renderWorldCopies);
}
setBearing(bearing: number): void {
this._helper.setBearing(bearing);
}
setPitch(pitch: number): void {
this._helper.setPitch(pitch);
}
setFov(fov: number): void {
this._helper.setFov(fov);
}
setZoom(zoom: number): void {
this._helper.setZoom(zoom);
}
setCenter(center: LngLat): void {
this._helper.setCenter(center);
}
setElevation(elevation: number): void {
this._helper.setElevation(elevation);
}
setMinElevationForCurrentTile(elevation: number): void {
this._helper.setMinElevationForCurrentTile(elevation);
}
setPadding(padding: PaddingOptions): void {
this._helper.setPadding(padding);
}
interpolatePadding(start: PaddingOptions, target: PaddingOptions, t: number): void {
return this._helper.interpolatePadding(start, target, t);
}
isPaddingEqual(padding: PaddingOptions): boolean {
return this._helper.isPaddingEqual(padding);
}
coveringZoomLevel(options: { roundZoom?: boolean; tileSize: number }): number {
return this._helper.coveringZoomLevel(options);
}
resize(width: number, height: number): void {
this._helper.resize(width, height);
}
getMaxBounds(): LngLatBounds {
return this._helper.getMaxBounds();
}
setMaxBounds(bounds?: LngLatBounds): void {
this._helper.setMaxBounds(bounds);
}
getCameraQueryGeometry(queryGeometry: Point[]): Point[] {
return this._helper.getCameraQueryGeometry(this.getCameraPoint(), queryGeometry);
}
get tileSize(): number {
return this._helper.tileSize;
}
get tileZoom(): number {
return this._helper.tileZoom;
}
get scale(): number {
return this._helper.scale;
}
get worldSize(): number {
return this._helper.worldSize;
}
get width(): number {
return this._helper.width;
}
get height(): number {
return this._helper.height;
}
get angle(): number {
return this._helper.angle;
}
get lngRange(): [number, number] {
return this._helper.lngRange;
}
get latRange(): [number, number] {
return this._helper.latRange;
}
get minZoom(): number {
return this._helper.minZoom;
}
get maxZoom(): number {
return this._helper.maxZoom;
}
get zoom(): number {
return this._helper.zoom;
}
get center(): LngLat {
return this._helper.center;
}
get minPitch(): number {
return this._helper.minPitch;
}
get maxPitch(): number {
return this._helper.maxPitch;
}
get pitch(): number {
return this._helper.pitch;
}
get bearing(): number {
return this._helper.bearing;
}
get fov(): number {
return this._helper.fov;
}
get elevation(): number {
return this._helper.elevation;
}
get minElevationForCurrentTile(): number {
return this._helper.minElevationForCurrentTile;
}
get padding(): PaddingOptions {
return this._helper.padding;
}
get unmodified(): boolean {
return this._helper.unmodified;
}
get renderWorldCopies(): boolean {
return this._helper.renderWorldCopies;
}
//
// Implementation of globe transform
//
private _cachedClippingPlane: vec4 = createVec4();
// Transition handling
private _lastGlobeStateEnabled: boolean = true;
private _lastLargeZoomStateChange: number = -1000.0;
private _lastLargeZoomState: boolean = false;
private _skipNextAnimation: boolean = true;
private _projectionMatrix: mat4 = createIdentityMat4();
private _globeViewProjMatrix: mat4 = createIdentityMat4();
private _globeViewProjMatrixNoCorrection: mat4 = createIdentityMat4();
private _globeViewProjMatrixNoCorrectionInverted: mat4 = createIdentityMat4();
private _globeProjMatrixInverted: mat4 = createIdentityMat4();
private _cameraPosition: vec3 = createVec3();
private _lastGlobeChangeTime: number = -1000.0;
private _globeProjectionEnabled = true;
/**
* Note: projection instance should only be accessed in the {@link newFrameUpdate} function
* to ensure the transform's state isn't unintentionally changed.
*/
private _projectionInstance: GlobeProjection;
private _lastGlobeRenderingState: boolean = true;
private _globeLatitudeErrorCorrectionRadians: number = 0;
private get _globeRendering(): boolean {
return this._globeness > 0;
}
/**
* Globe projection can smoothly interpolate between globe view and mercator. This variable controls this interpolation.
* Value 0 is mercator, value 1 is globe, anything between is an interpolation between the two projections.
*/
private _globeness: number = 1.0;
private _mercatorTransform: MercatorTransform;
private _nearZ;
private _farZ;
public constructor(globeProjection: GlobeProjection, globeProjectionEnabled: boolean = true) {
this._helper = new TransformHelper({
calcMatrices: () => { this._calcMatrices(); },
getConstrained: (center, zoom) => { return this.getConstrained(center, zoom); }
});
this._globeProjectionEnabled = globeProjectionEnabled;
this._globeness = globeProjectionEnabled ? 1 : 0; // When transform is cloned for use in symbols, `_updateAnimation` function which usually sets this value never gets called.
this._projectionInstance = globeProjection;
this._mercatorTransform = new MercatorTransform();
}
clone(): ITransform {
const clone = new GlobeTransform(null, this._globeProjectionEnabled);
clone.apply(this);
this.newFrameUpdate();
return clone;
}
public apply(that: IReadonlyTransform): void {
this._helper.apply(that);
this._mercatorTransform.apply(this);
}
public get projectionMatrix(): mat4 { return this._globeRendering ? this._projectionMatrix : this._mercatorTransform.projectionMatrix; }
public get modelViewProjectionMatrix(): mat4 { return this._globeRendering ? this._globeViewProjMatrixNoCorrection : this._mercatorTransform.modelViewProjectionMatrix; }
public get inverseProjectionMatrix(): mat4 { return this._globeRendering ? this._globeProjMatrixInverted : this._mercatorTransform.inverseProjectionMatrix; }
public get useGlobeControls(): boolean { return this._globeRendering; }
public get cameraPosition(): vec3 {
// Return a copy - don't let outside code mutate our precomputed camera position.
const copy = createVec3(); // Ensure the resulting vector is float64s
copy[0] = this._cameraPosition[0];
copy[1] = this._cameraPosition[1];
copy[2] = this._cameraPosition[2];
return copy;
}
get cameraToCenterDistance(): number {
// Globe uses the same cameraToCenterDistance as mercator.
return this._mercatorTransform.cameraToCenterDistance;
}
public get nearZ(): number { return this._nearZ; }
public get farZ(): number { return this._farZ; }
/**
* Returns whether globe view is allowed.
* When allowed, globe fill function as normal, displaying a 3D planet,
* but transitioning to mercator at high zoom levels.
* Otherwise, mercator will be used at all zoom levels instead.
* Set with {@link setGlobeViewAllowed}.
*/
public getGlobeViewAllowed(): boolean {
return this._globeProjectionEnabled;
}
/**
* Sets whether globe view is allowed. When allowed, globe fill function as normal, displaying a 3D planet,
* but transitioning to mercator at high zoom levels.
* Otherwise, mercator will be used at all zoom levels instead.
* @param allow - Sets whether glove view is allowed.
* @param animateTransition - Controls whether the transition between globe view and mercator (if triggered by this call) should be animated. True by default.
*/
public setGlobeViewAllowed(allow: boolean, animateTransition: boolean = true) {
if (allow === this._globeProjectionEnabled) {
return;
}
if (!animateTransition) {
this._skipNextAnimation = true;
}
this._globeProjectionEnabled = allow;
this._lastGlobeChangeTime = browser.now();
}
/**
* Should be called at the beginning of every frame to synchronize the transform with the underlying projection.
*/
newFrameUpdate(): TransformUpdateResult {
if (this._projectionInstance) {
// Note: the _globeRendering field is only updated inside this function.
// This function should never be called on a cloned transform, thus ensuring that
// the state of a cloned transform is never changed after creation.
this._projectionInstance.useGlobeRendering = this._globeRendering;
this._projectionInstance.errorQueryLatitudeDegrees = this.center.lat;
this._globeLatitudeErrorCorrectionRadians = this._projectionInstance.latitudeErrorCorrectionRadians;
}
this._globeness = this._computeGlobenessAnimation();
this._calcMatrices();
let forcePlacementUpdate = false;
if (this._lastGlobeRenderingState !== this._globeRendering) {
forcePlacementUpdate = true;
}
this._lastGlobeRenderingState = this._globeRendering;
return {
forcePlacementUpdate
};
}
/**
* Compute new globeness, if needed.
*/
private _computeGlobenessAnimation(): number {
// Update globe transition animation
const globeState = this._globeProjectionEnabled;
const currentTime = browser.now();
if (globeState !== this._lastGlobeStateEnabled) {
this._lastGlobeChangeTime = currentTime;
this._lastGlobeStateEnabled = globeState;
}
const oldGlobeness = this._globeness;
// Transition parameter, where 0 is the start and 1 is end.
const globeTransition = Math.min(Math.max((currentTime - this._lastGlobeChangeTime) / 1000.0 / globeConstants.globeTransitionTimeSeconds, 0.0), 1.0);
let newGlobeness = globeState ? globeTransition : (1.0 - globeTransition);
if (this._skipNextAnimation) {
newGlobeness = globeState ? 1.0 : 0.0;
this._lastGlobeChangeTime = currentTime - globeConstants.globeTransitionTimeSeconds * 1000.0 * 2.0;
this._skipNextAnimation = false;
}
// Update globe zoom transition
const currentZoomState = this.zoom >= globeConstants.maxGlobeZoom;
if (currentZoomState !== this._lastLargeZoomState) {
this._lastLargeZoomState = currentZoomState;
this._lastLargeZoomStateChange = currentTime;
}
const zoomTransition = Math.min(Math.max((currentTime - this._lastLargeZoomStateChange) / 1000.0 / globeConstants.zoomTransitionTimeSeconds, 0.0), 1.0);
const zoomGlobenessBound = currentZoomState ? (1.0 - zoomTransition) : zoomTransition;
newGlobeness = Math.min(newGlobeness, zoomGlobenessBound);
newGlobeness = easeCubicInOut(newGlobeness); // Smooth animation
if (oldGlobeness !== newGlobeness) {
this.setCenter(new LngLat(
this._mercatorTransform.center.lng + differenceOfAnglesDegrees(this._mercatorTransform.center.lng, this.center.lng) * newGlobeness,
lerp(this._mercatorTransform.center.lat, this.center.lat, newGlobeness)
));
this.setZoom(lerp(this._mercatorTransform.zoom, this.zoom, newGlobeness));
}
return newGlobeness;
}
isRenderingDirty(): boolean {
const now = browser.now();
// Globe transition
return (now - this._lastGlobeChangeTime) / 1000.0 < (Math.max(globeConstants.globeTransitionTimeSeconds, globeConstants.zoomTransitionTimeSeconds) + 0.2);
}
getProjectionData(overscaledTileID: OverscaledTileID, aligned?: boolean, ignoreTerrainMatrix?: boolean): ProjectionData {
const data = this._mercatorTransform.getProjectionData(overscaledTileID, aligned, ignoreTerrainMatrix);
// Set 'u_projection_matrix' to actual globe transform
if (this._globeRendering) {
data['u_projection_matrix'] = this._globeViewProjMatrix;
}
data['u_projection_clipping_plane'] = this._cachedClippingPlane as [number, number, number, number];
data['u_projection_transition'] = this._globeness;
return data;
}
private _computeClippingPlane(globeRadiusPixels: number): vec4 {
// We want to compute a plane equation that, when applied to the unit sphere generated
// in the vertex shader, places all visible parts of the sphere into the positive half-space
// and all the non-visible parts in the negative half-space.
// We can then use that to accurately clip all non-visible geometry.
// cam....------------A
// .... |
// .... |
// ....B
// ggggggggg
// gggggg | .gggggg
// ggg | ...ggg ^
// gg | |
// g | y
// g | |
// g C #---x--->
//
// Notes:
// - note the coordinate axes
// - "g" marks the globe edge
// - the dotted line is the camera center "ray" - we are looking in this direction
// - "cam" is camera origin
// - "C" is globe center
// - "B" is the point on "top" of the globe - camera is looking at B - "B" is the intersection between the camera center ray and the globe
// - this._pitch is the angle at B between points cam,B,A
// - this.cameraToCenterDistance is the distance from camera to "B"
// - globe radius is (0.5 * this.worldSize)
// - "T" is any point where a tangent line from "cam" touches the globe surface
// - elevation is assumed to be zero - globe rendering must be separate from terrain rendering anyway
const pitch = this.pitch * Math.PI / 180.0;
// scale things so that the globe radius is 1
const distanceCameraToB = this.cameraToCenterDistance / globeRadiusPixels;
const radius = 1;
// Distance from camera to "A" - the point at the same elevation as camera, right above center point on globe
const distanceCameraToA = Math.sin(pitch) * distanceCameraToB;
// Distance from "A" to "C"
const distanceAtoC = (Math.cos(pitch) * distanceCameraToB + radius);
// Distance from camera to "C" - the globe center
const distanceCameraToC = Math.sqrt(distanceCameraToA * distanceCameraToA + distanceAtoC * distanceAtoC);
// cam - C - T angle cosine (at C)
const camCTcosine = radius / distanceCameraToC;
// Distance from globe center to the plane defined by all possible "T" points
const tangentPlaneDistanceToC = camCTcosine * radius;
let vectorCtoCamX = -distanceCameraToA;
let vectorCtoCamY = distanceAtoC;
// Normalize the vector
const vectorCtoCamLength = Math.sqrt(vectorCtoCamX * vectorCtoCamX + vectorCtoCamY * vectorCtoCamY);
vectorCtoCamX /= vectorCtoCamLength;
vectorCtoCamY /= vectorCtoCamLength;
// Note the swizzled components
const planeVector: vec3 = [0, vectorCtoCamX, vectorCtoCamY];
// Apply transforms - lat, lng and angle (NOT pitch - already accounted for, as it affects the tangent plane)
vec3.rotateZ(planeVector, planeVector, [0, 0, 0], this.angle);
vec3.rotateX(planeVector, planeVector, [0, 0, 0], -1 * this.center.lat * Math.PI / 180.0);
vec3.rotateY(planeVector, planeVector, [0, 0, 0], this.center.lng * Math.PI / 180.0);
// Scale the plane vector up
// we don't want the actually visible parts of the sphere to end up beyond distance 1 from the plane - otherwise they would be clipped by the near plane.
const scale = 0.25;
vec3.scale(planeVector, planeVector, scale);
return [...planeVector, -tangentPlaneDistanceToC * scale];
}
private _projectTileCoordinatesToSphere(inTileX: number, inTileY: number, tileID: UnwrappedTileID): vec3 {
const mercator = tileCoordinatesToMercatorCoordinates(inTileX, inTileY, tileID.canonical);
const angular = mercatorCoordinatesToAngularCoordinatesRadians(mercator[0], mercator[1]);
const sphere = angularCoordinatesRadiansToVector(angular[0], angular[1]);
return sphere;
}
public isOccluded(x: number, y: number, unwrappedTileID: UnwrappedTileID): boolean {
if (!this._globeRendering) {
return this._mercatorTransform.isOccluded(x, y, unwrappedTileID);
}
const spherePos = this._projectTileCoordinatesToSphere(x, y, unwrappedTileID);
return !this.isSurfacePointVisible(spherePos);
}
public transformLightDirection(dir: vec3): vec3 {
const sphereX = this._helper._center.lng * Math.PI / 180.0;
const sphereY = this._helper._center.lat * Math.PI / 180.0;
const len = Math.cos(sphereY);
const spherePos: vec3 = [
Math.sin(sphereX) * len,
Math.sin(sphereY),
Math.cos(sphereX) * len
];
const axisRight: vec3 = [spherePos[2], 0.0, -spherePos[0]]; // Equivalent to cross(vec3(0.0, 1.0, 0.0), vec)
const axisDown: vec3 = [0, 0, 0];
vec3.cross(axisDown, axisRight, spherePos);
vec3.normalize(axisRight, axisRight);
vec3.normalize(axisDown, axisDown);
const transformed: vec3 = [
axisRight[0] * dir[0] + axisDown[0] * dir[1] + spherePos[0] * dir[2],
axisRight[1] * dir[0] + axisDown[1] * dir[1] + spherePos[1] * dir[2],
axisRight[2] * dir[0] + axisDown[2] * dir[1] + spherePos[2] * dir[2]
];
const normalized: vec3 = [0, 0, 0];
vec3.normalize(normalized, transformed);
return normalized;
}
private getAnimatedLatitude() {
return lerp(this._mercatorTransform.center.lat, this._helper._center.lat, this._globeness);
}
public getPixelScale(): number {
return 1.0 / Math.cos(this.getAnimatedLatitude() * Math.PI / 180);
}
public getCircleRadiusCorrection(): number {
return Math.cos(this.getAnimatedLatitude() * Math.PI / 180);
}
public getPitchedTextCorrection(textAnchor: Point, tileID: UnwrappedTileID): number {
if (!this._globeRendering) {
return 1.0;
}
const mercator = tileCoordinatesToMercatorCoordinates(textAnchor.x, textAnchor.y, tileID.canonical);
const angular = mercatorCoordinatesToAngularCoordinatesRadians(mercator[0], mercator[1]);
return this.getCircleRadiusCorrection() / Math.cos(angular[1]);
}
public projectTileCoordinates(x: number, y: number, unwrappedTileID: UnwrappedTileID, getElevation: (x: number, y: number) => number): PointProjection {
if (!this._globeRendering) {
return this._mercatorTransform.projectTileCoordinates(x, y, unwrappedTileID, getElevation);
}
const spherePos = this._projectTileCoordinatesToSphere(x, y, unwrappedTileID);
const elevation = getElevation ? getElevation(x, y) : 0.0;
const vectorMultiplier = 1.0 + elevation / earthRadius;
const pos: vec4 = [spherePos[0] * vectorMultiplier, spherePos[1] * vectorMultiplier, spherePos[2] * vectorMultiplier, 1];
vec4.transformMat4(pos, pos, this._globeViewProjMatrixNoCorrection);
// Also check whether the point projects to the backfacing side of the sphere.
const plane = this._cachedClippingPlane;
// dot(position on sphere, occlusion plane equation)
const dotResult = plane[0] * spherePos[0] + plane[1] * spherePos[1] + plane[2] * spherePos[2] + plane[3];
const isOccluded = dotResult < 0.0;
return {
point: new Point(pos[0] / pos[3], pos[1] / pos[3]),
signedDistanceFromCamera: pos[3],
isOccluded
};
}
private _calcMatrices(): void {
if (!this._helper._width || !this._helper._height) {
return;
}
if (this._mercatorTransform) {
this._mercatorTransform.apply(this, true);
}
const globeRadiusPixels = getGlobeRadiusPixels(this.worldSize, this.center.lat);
// Construct a completely separate matrix for globe view
const globeMatrix = createMat4();
const globeMatrixUncorrected = createMat4();
this._nearZ = 0.5;
this._farZ = this.cameraToCenterDistance + globeRadiusPixels * 2.0; // just set the far plane far enough - we will calculate our own z in the vertex shader anyway
mat4.perspective(globeMatrix, this.fov * Math.PI / 180, this.width / this.height, this._nearZ, this._farZ);
// Apply center of perspective offset
const offset = this.centerOffset;
globeMatrix[8] = -offset.x * 2 / this._helper._width;
globeMatrix[9] = offset.y * 2 / this._helper._height;
this._projectionMatrix = mat4.clone(globeMatrix);
this._globeProjMatrixInverted = createMat4();
mat4.invert(this._globeProjMatrixInverted, globeMatrix);
mat4.translate(globeMatrix, globeMatrix, [0, 0, -this.cameraToCenterDistance]);
mat4.rotateX(globeMatrix, globeMatrix, -this.pitch * Math.PI / 180);
mat4.rotateZ(globeMatrix, globeMatrix, -this.angle);
mat4.translate(globeMatrix, globeMatrix, [0.0, 0, -globeRadiusPixels]);
// Rotate the sphere to center it on viewed coordinates
const scaleVec = createVec3();
scaleVec[0] = globeRadiusPixels;
scaleVec[1] = globeRadiusPixels;
scaleVec[2] = globeRadiusPixels;
// Keep a atan-correction-free matrix for transformations done on the CPU with accurate math
mat4.rotateX(globeMatrixUncorrected, globeMatrix, this.center.lat * Math.PI / 180.0);
mat4.rotateY(globeMatrixUncorrected, globeMatrixUncorrected, -this.center.lng * Math.PI / 180.0);
mat4.scale(globeMatrixUncorrected, globeMatrixUncorrected, scaleVec); // Scale the unit sphere to a sphere with diameter of 1
this._globeViewProjMatrixNoCorrection = globeMatrixUncorrected;
mat4.rotateX(globeMatrix, globeMatrix, this.center.lat * Math.PI / 180.0 - this._globeLatitudeErrorCorrectionRadians);
mat4.rotateY(globeMatrix, globeMatrix, -this.center.lng * Math.PI / 180.0);
mat4.scale(globeMatrix, globeMatrix, scaleVec); // Scale the unit sphere to a sphere with diameter of 1
this._globeViewProjMatrix = globeMatrix;
this._globeViewProjMatrixNoCorrectionInverted = createMat4();
mat4.invert(this._globeViewProjMatrixNoCorrectionInverted, globeMatrixUncorrected);
const zero = createVec3();
this._cameraPosition = createVec3();
this._cameraPosition[2] = this.cameraToCenterDistance / globeRadiusPixels;
vec3.rotateX(this._cameraPosition, this._cameraPosition, zero, this.pitch * Math.PI / 180);
vec3.rotateZ(this._cameraPosition, this._cameraPosition, zero, this.angle);
vec3.add(this._cameraPosition, this._cameraPosition, [0, 0, 1]);
vec3.rotateX(this._cameraPosition, this._cameraPosition, zero, -this.center.lat * Math.PI / 180.0);
vec3.rotateY(this._cameraPosition, this._cameraPosition, zero, this.center.lng * Math.PI / 180.0);
this._cachedClippingPlane = this._computeClippingPlane(globeRadiusPixels);
}
calculateFogMatrix(_unwrappedTileID: UnwrappedTileID): mat4 {
warnOnce('calculateFogMatrix is not supported on globe projection.');
const m = createMat4();
mat4.identity(m);
return m;
}
getVisibleUnwrappedCoordinates(tileID: CanonicalTileID): UnwrappedTileID[] {
// Globe: TODO: implement for globe #3887
return this._mercatorTransform.getVisibleUnwrappedCoordinates(tileID);
}
coveringTiles(options: {
tileSize: number; minzoom?: number;
maxzoom?: number; roundZoom?: boolean; reparseOverscaled?: boolean; renderWorldCopies?: boolean; terrain?: Terrain;
}): OverscaledTileID[] {
// Globe: TODO: implement for globe #3887
return this._mercatorTransform.coveringTiles(options);
}
recalculateZoom(terrain: Terrain): void {
this._mercatorTransform.recalculateZoom(terrain);
this.apply(this._mercatorTransform);
}
customLayerMatrix(): mat4 {
// Globe: TODO
return this._mercatorTransform.customLayerMatrix();
}
maxPitchScaleFactor(): number {
// Using mercator version of this should be good enough approximation for globe.
return this._mercatorTransform.maxPitchScaleFactor();
}
getCameraPoint(): Point {
return this._mercatorTransform.getCameraPoint();
}
lngLatToCameraDepth(lngLat: LngLat, elevation: number): number {
if (!this._globeRendering) {
return this._mercatorTransform.lngLatToCameraDepth(lngLat, elevation);
}
if (!this._globeViewProjMatrixNoCorrection) {
return 1.0; // _calcMatrices hasn't run yet
}
const vec = angularCoordinatesToSurfaceVector(lngLat);
vec3.scale(vec, vec, (1.0 + elevation / earthRadius));
const result = createVec4();
vec4.transformMat4(result, [vec[0], vec[1], vec[2], 1], this._globeViewProjMatrixNoCorrection);
return result[2] / result[3];
}
precacheTiles(coords: OverscaledTileID[]): void {
this._mercatorTransform.precacheTiles(coords);
}
getBounds(): LngLatBounds {
if (!this._globeRendering) {
return this._mercatorTransform.getBounds();
}
const xMid = this.width * 0.5;
const yMid = this.height * 0.5;
// LngLat extremes will probably tend to be in screen corners or in middle of screen edges.
// These test points should result in a pretty good approximation.
const testPoints = [
new Point(0, 0),
new Point(xMid, 0),
new Point(this.width, 0),
new Point(this.width, yMid),
new Point(this.width, this.height),
new Point(xMid, this.height),
new Point(0, this.height),
new Point(0, yMid),
];
const projectedPoints = [];
for (const p of testPoints) {
projectedPoints.push(this.unprojectScreenPoint(p));
}
// We can't construct a simple min/max aabb, since points might lie on either side of the antimeridian.
// We will instead compute the furthest points relative to map center.
// We also take advantage of the fact that `unprojectScreenPoint` will snap pixels
// outside the planet to the closest point on the planet's horizon.
let mostEast = 0, mostWest = 0, mostNorth = 0, mostSouth = 0; // We will store these values signed.
const center = this.center;
for (const p of projectedPoints) {
const dLng = differenceOfAnglesDegrees(center.lng, p.lng);
const dLat = differenceOfAnglesDegrees(center.lat, p.lat);
if (dLng < mostWest) {
mostWest = dLng;
}
if (dLng > mostEast) {
mostEast = dLng;
}
if (dLat < mostSouth) {
mostSouth = dLat;
}
if (dLat > mostNorth) {
mostNorth = dLat;
}
}
const boundsArray: [number, number, number, number] = [
center.lng + mostWest, // west
center.lat + mostSouth, // south
center.lng + mostEast, // east
center.lat + mostNorth // north
];
// Sometimes the poles might end up not being on the horizon,
// thus not being detected as the northernmost/southernmost points.
// We fix that here.
if (this.isSurfacePointOnScreen([0, 1, 0])) {
// North pole is visible
// This also means that the entire longitude range must be visible
boundsArray[3] = 90;
boundsArray[0] = -180;
boundsArray[2] = 180;
}
if (this.isSurfacePointOnScreen([0, -1, 0])) {
// South pole is visible
boundsArray[1] = -90;
boundsArray[0] = -180;
boundsArray[2] = 180;
}
return new LngLatBounds(boundsArray);
}
getConstrained(lngLat: LngLat, zoom: number): { center: LngLat; zoom: number } {
// Globe: TODO: respect _lngRange, _latRange
// It is possible to implement exact constrain for globe, but I don't think it is worth the effort.
const constrainedLat = clamp(lngLat.lat, -MAX_VALID_LATITUDE, MAX_VALID_LATITUDE);
const constrainedZoom = clamp(+zoom, this.minZoom + getZoomAdjustment(0, constrainedLat), this.maxZoom);
return {
center: new LngLat(
lngLat.lng,
constrainedLat
),
zoom: constrainedZoom
};
}
/**
* Note: automatically adjusts zoom to keep planet size consistent
* (same size before and after a {@link setLocationAtPoint} call).
*/
setLocationAtPoint(lnglat: LngLat, point: Point): void {
if (!this._globeRendering) {
this._mercatorTransform.setLocationAtPoint(lnglat, point);
this.apply(this._mercatorTransform);
return;
}
// This returns some fake coordinates for pixels that do not lie on the planet.
// Whatever uses this `setLocationAtPoint` function will need to account for that.
const pointLngLat = this.unprojectScreenPoint(point);
const vecToPixelCurrent = angularCoordinatesToSurfaceVector(pointLngLat);
const vecToTarget = angularCoordinatesToSurfaceVector(lnglat);
const zero = createVec3();
vec3.zero(zero);
const rotatedPixelVector = createVec3();
vec3.rotateY(rotatedPixelVector, vecToPixelCurrent, zero, -this.center.lng * Math.PI / 180.0);
vec3.rotateX(rotatedPixelVector, rotatedPixelVector, zero, this.center.lat * Math.PI / 180.0);
// We are looking for the lng,lat that will rotate `vecToTarget`
// so that it is equal to `rotatedPixelVector`.
// The second rotation around X axis cannot change the X component,
// so we first must find the longitude such that rotating `vecToTarget` with it
// will place it so its X component is equal to X component of `rotatedPixelVector`.
// There will exist zero, one or two longitudes that satisfy this.
// x |
// / |
// / | the line is the target X - rotatedPixelVector.x
// / | the x is vecToTarget projected to x,z plane
// . | the dot is origin
//
// We need to rotate vecToTarget so that it intersects the line.
// If vecToTarget is shorter than the distance to the line from origin, it is impossible.
// Otherwise, we compute the intersection of the line with a ring with radius equal to
// length of vecToTarget projected to XZ plane.
const vecToTargetXZLengthSquared = vecToTarget[0] * vecToTarget[0] + vecToTarget[2] * vecToTarget[2];
const targetXSquared = rotatedPixelVector[0] * rotatedPixelVector[0];
if (vecToTargetXZLengthSquared < targetXSquared) {
// Zero solutions - setLocationAtPoint is impossible.
return;
}
// The intersection's Z coordinates
const intersectionA = Math.sqrt(vecToTargetXZLengthSquared - targetXSquared);
const intersectionB = -intersectionA; // the second solution
const lngA = angleToRotateBetweenVectors2D(vecToTarget[0], vecToTarget[2], rotatedPixelVector[0], intersectionA);
const lngB = angleToRotateBetweenVectors2D(vecToTarget[0], vecToTarget[2], rotatedPixelVector[0], intersectionB);
const vecToTargetLngA = createVec3();
vec3.rotateY(vecToTargetLngA, vecToTarget, zero, -lngA);
const latA = angleToRotateBetweenVectors2D(vecToTargetLngA[1], vecToTargetLngA[2], rotatedPixelVector[1], rotatedPixelVector[2]);
const vecToTargetLngB = createVec3();
vec3.rotateY(vecToTargetLngB, vecToTarget, zero, -lngB);
const latB = angleToRotateBetweenVectors2D(vecToTargetLngB[1], vecToTargetLngB[2], rotatedPixelVector[1], rotatedPixelVector[2]);
// Is at least one of the needed latitudes valid?
const limit = Math.PI * 0.5;
const isValidA = latA >= -limit && latA <= limit;
const isValidB = latB >= -limit && latB <= limit;
let validLng: number;
let validLat: number;
if (isValidA && isValidB) {
// Pick the solution that is closer to current map center.
const centerLngRadians = this.center.lng * Math.PI / 180.0;
const centerLatRadians = this.center.lat * Math.PI / 180.0;
const lngDistA = distanceOfAnglesRadians(lngA, centerLngRadians);
const latDistA = distanceOfAnglesRadians(latA, centerLatRadians);
const lngDistB = distanceOfAnglesRadians(lngB, centerLngRadians);
const latDistB = distanceOfAnglesRadians(latB, centerLatRadians);
if ((lngDistA + latDistA) < (lngDistB + latDistB)) {
validLng = lngA;
validLat = latA;
} else {
validLng = lngB;
validLat = latB;
}
} else if (isValidA) {
validLng = lngA;
validLat = latA;
} else if (isValidB) {
validLng = lngB;
validLat = latB;
} else {
// No solution.
return;
}
const newLng = validLng / Math.PI * 180;
const newLat = validLat / Math.PI * 180;
const oldLat = this.center.lat;
this.setCenter(new LngLat(newLng, clamp(newLat, -90, 90)));
this.setZoom(this.zoom + getZoomAdjustment(oldLat, this.center.lat));
}
locationToScreenPoint(lnglat: LngLat, terrain?: Terrain): Point {
if (!this._globeRendering) {
return this._mercatorTransform.locationToScreenPoint(lnglat, terrain);
}
const pos = angularCoordinatesToSurfaceVector(lnglat);
if (terrain) {
const elevation = terrain.getElevationForLngLatZoom(lnglat, this._helper._tileZoom);
vec3.scale(pos, pos, 1.0 + elevation / earthRadius);
}
return this._projectSurfacePointToScreen(pos);
}
/**
* Projects a given vector on the surface of a unit sphere (or possible above the surface)
* and returns its coordinates on screen in pixels.
*/
private _projectSurfacePointToScreen(pos: vec3): Point {
const projected = createVec4();
vec4.transformMat4(projected, [...pos, 1] as vec4, this._globeViewProjMatrixNoCorrection);
projected[0] /= projected[3];
projected[1] /= projected[3];
return new Point(
(projected[0] * 0.5 + 0.5) * this.width,
(-projected[1] * 0.5 + 0.5) * this.height
);
}
screenPointToMercatorCoordinate(p: Point, terrain?: Terrain): MercatorCoordinate {
if (!this._globeRendering || terrain) {
// Mercator has terrain handling implemented properly and since terrain
// simply draws tile coordinates into a special framebuffer, this works well even for globe.
return this._mercatorTransform.screenPointToMercatorCoordinate(p, terrain);
}
return MercatorCoordinate.fromLngLat(this.unprojectScreenPoint(p));
}
screenPointToLocation(p: Point, terrain?: Terrain): LngLat {
if (!this._globeRendering || terrain) {
// Mercator has terrain handling implemented properly and since terrain
// simply draws tile coordinates into a special framebuffer, this works well even for globe.
return this._mercatorTransform.screenPointToLocation(p, terrain);
}
return this.unprojectScreenPoint(p);
}
isPointOnMapSurface(p: Point, terrain?: Terrain): boolean {
if (!this._globeRendering) {
return this._mercatorTransform.isPointOnMapSurface(p, terrain);
}
const rayOrigin = this._cameraPosition;
const rayDirection = this.getRayDirectionFromPixel(p);
const intersection = this.rayPlanetIntersection(rayOrigin, rayDirection);
return !!intersection;
}
/**
* Computes normalized direction of a ray from the camera to the given screen pixel.
*/
getRayDirectionFromPixel(p: Point): vec3 {
const pos = createVec4();
pos[0] = (p.x / this.width) * 2.0 - 1.0;
pos[1] = ((p.y / this.height) * 2.0 - 1.0) * -1.0;
pos[2] = 1;
pos[3] = 1;
vec4.transformMat4(pos, pos, this._globeViewProjMatrixNoCorrectionInverted);
pos[0] /= pos[3];
pos[1] /= pos[3];
pos[2] /= pos[3];
const ray = createVec3();
ray[0] = pos[0] - this._cameraPosition[0];
ray[1] = pos[1] - this._cameraPosition[1];
ray[2] = pos[2] - this._cameraPosition[2];
const rayNormalized: vec3 = createVec3();
vec3.normalize(rayNormalized, ray);
return rayNormalized;
}
/**
* For a given point on the unit sphere of the planet, returns whether it is visible from
* camera's position (not taking into account camera rotation at all).
*/
private isSurfacePointVisible(p: vec3): boolean {
if (!this._globeRendering) {
return true;
}
const plane = this._cachedClippingPlane;
// dot(position on sphere, occlusion plane equation)
const dotResult = plane[0] * p[0] + plane[1] * p[1] + plane[2] * p[2] + plane[3];
return dotResult >= 0.0;
}
/**
* Returns whether surface point is visible on screen.