@math.gl/web-mercator 3.6.0 → 3.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,87 +0,0 @@
1
- import { lerp } from './math-utils';
2
- import { scaleToZoom, zoomToScale, lngLatToWorld, worldToLngLat } from './web-mercator-utils';
3
- import * as vec2 from 'gl-matrix/vec2';
4
- const EPSILON = 0.01;
5
- const VIEWPORT_TRANSITION_PROPS = ['longitude', 'latitude', 'zoom'];
6
- const DEFAULT_OPTS = {
7
- curve: 1.414,
8
- speed: 1.2
9
- // screenSpeed and maxDuration are used only if specified
10
- };
11
- /**
12
- * mapbox-gl-js flyTo : https://www.mapbox.com/mapbox-gl-js/api/#map#flyto.
13
- * It implements “Smooth and efficient zooming and panning.” algorithm by
14
- * "Jarke J. van Wijk and Wim A.A. Nuij"
15
- */
16
- export default function flyToViewport(startProps, endProps, t, options) {
17
- // Equations from above paper are referred where needed.
18
- const { startZoom, startCenterXY, uDelta, w0, u1, S, rho, rho2, r0 } = getFlyToTransitionParams(startProps, endProps, options);
19
- // If change in center is too small, do linear interpolaiton.
20
- if (u1 < EPSILON) {
21
- const viewport = {};
22
- for (const key of VIEWPORT_TRANSITION_PROPS) {
23
- const startValue = startProps[key];
24
- const endValue = endProps[key];
25
- viewport[key] = lerp(startValue, endValue, t);
26
- }
27
- // @ts-expect-error properties are populated dynamically
28
- return viewport;
29
- }
30
- const s = t * S;
31
- const w = Math.cosh(r0) / Math.cosh(r0 + rho * s);
32
- const u = (w0 * ((Math.cosh(r0) * Math.tanh(r0 + rho * s) - Math.sinh(r0)) / rho2)) / u1;
33
- const scaleIncrement = 1 / w; // Using w method for scaling.
34
- const newZoom = startZoom + scaleToZoom(scaleIncrement);
35
- const newCenterWorld = vec2.scale([], uDelta, u);
36
- vec2.add(newCenterWorld, newCenterWorld, startCenterXY);
37
- const newCenter = worldToLngLat(newCenterWorld);
38
- return {
39
- longitude: newCenter[0],
40
- latitude: newCenter[1],
41
- zoom: newZoom
42
- };
43
- }
44
- // returns transition duration in milliseconds
45
- export function getFlyToDuration(startProps, endProps, options) {
46
- const opts = { ...DEFAULT_OPTS, ...options };
47
- const { screenSpeed, speed, maxDuration } = opts;
48
- const { S, rho } = getFlyToTransitionParams(startProps, endProps, opts);
49
- const length = 1000 * S;
50
- let duration;
51
- if (Number.isFinite(screenSpeed)) {
52
- duration = length / (screenSpeed / rho);
53
- }
54
- else {
55
- duration = length / speed;
56
- }
57
- return Number.isFinite(maxDuration) && duration > maxDuration ? 0 : duration;
58
- }
59
- // Private Methods
60
- // Calculate all parameters that are static for given startProps and endProps
61
- function getFlyToTransitionParams(startProps, endProps, opts) {
62
- opts = Object.assign({}, DEFAULT_OPTS, opts);
63
- const rho = opts.curve;
64
- const startZoom = startProps.zoom;
65
- const startCenter = [startProps.longitude, startProps.latitude];
66
- const startScale = zoomToScale(startZoom);
67
- const endZoom = endProps.zoom;
68
- const endCenter = [endProps.longitude, endProps.latitude];
69
- const scale = zoomToScale(endZoom - startZoom);
70
- const startCenterXY = lngLatToWorld(startCenter);
71
- const endCenterXY = lngLatToWorld(endCenter);
72
- const uDelta = vec2.sub([], endCenterXY, startCenterXY);
73
- const w0 = Math.max(startProps.width, startProps.height);
74
- const w1 = w0 / scale;
75
- const u1 = vec2.length(uDelta) * startScale;
76
- // u0 is treated as '0' in Eq (9).
77
- // If u1 is too small, will generate invalid number
78
- const _u1 = Math.max(u1, EPSILON);
79
- // Implement Equation (9) from above algorithm.
80
- const rho2 = rho * rho;
81
- const b0 = (w1 * w1 - w0 * w0 + rho2 * rho2 * _u1 * _u1) / (2 * w0 * rho2 * _u1);
82
- const b1 = (w1 * w1 - w0 * w0 - rho2 * rho2 * _u1 * _u1) / (2 * w1 * rho2 * _u1);
83
- const r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0);
84
- const r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);
85
- const S = (r1 - r0) / rho;
86
- return { startZoom, startCenterXY, uDelta, w0, u1, S, rho, rho2, r0, r1 };
87
- }
@@ -1,51 +0,0 @@
1
- import { worldToLngLat } from './web-mercator-utils';
2
- import * as vec2 from 'gl-matrix/vec2';
3
- import { transformVector } from './math-utils';
4
- const DEGREES_TO_RADIANS = Math.PI / 180;
5
- /*
6
- * Returns the quad at the intersection of the frustum and the given z plane
7
- * @param {WebMercatorViewport} viewport
8
- * @param {Number} z - elevation in meters
9
- */
10
- export default function getBounds(viewport, z = 0) {
11
- // eslint-disable-next-line @typescript-eslint/unbound-method
12
- const { width, height, unproject } = viewport;
13
- const unprojectOps = { targetZ: z };
14
- const bottomLeft = unproject([0, height], unprojectOps);
15
- const bottomRight = unproject([width, height], unprojectOps);
16
- let topLeft;
17
- let topRight;
18
- const halfFov = viewport.fovy
19
- ? 0.5 * viewport.fovy * DEGREES_TO_RADIANS
20
- : Math.atan(0.5 / viewport.altitude);
21
- const angleToGround = (90 - viewport.pitch) * DEGREES_TO_RADIANS;
22
- // The top plane is parallel to the ground if halfFov == angleToGround
23
- if (halfFov > angleToGround - 0.01) {
24
- // intersect with the far plane
25
- topLeft = unprojectOnFarPlane(viewport, 0, z);
26
- topRight = unprojectOnFarPlane(viewport, width, z);
27
- }
28
- else {
29
- // intersect with the top plane
30
- topLeft = unproject([0, 0], unprojectOps);
31
- topRight = unproject([width, 0], unprojectOps);
32
- }
33
- return [bottomLeft, bottomRight, topRight, topLeft];
34
- }
35
- /*
36
- * Find a point on the far clipping plane of the viewport
37
- * @param {WebMercatorViewport} viewport
38
- * @param {Number} x - projected x in screen space
39
- * @param {Number} targetZ - the elevation of the point in meters
40
- */
41
- function unprojectOnFarPlane(viewport, x, targetZ) {
42
- const { pixelUnprojectionMatrix } = viewport;
43
- const coord0 = transformVector(pixelUnprojectionMatrix, [x, 0, 1, 1]);
44
- const coord1 = transformVector(pixelUnprojectionMatrix, [x, viewport.height, 1, 1]);
45
- const z = targetZ * viewport.distanceScales.unitsPerMeter[2];
46
- const t = (z - coord0[2]) / (coord1[2] - coord0[2]);
47
- const coord = vec2.lerp([], coord0, coord1, t);
48
- const result = worldToLngLat(coord);
49
- result.push(targetZ);
50
- return result;
51
- }
package/dist/index.js DELETED
@@ -1,8 +0,0 @@
1
- // Classic web-mercator-project
2
- export { default } from './web-mercator-viewport';
3
- export { default as WebMercatorViewport } from './web-mercator-viewport';
4
- export { default as getBounds } from './get-bounds';
5
- export { default as fitBounds } from './fit-bounds';
6
- export { default as normalizeViewportProps } from './normalize-viewport-props';
7
- export { default as flyToViewport, getFlyToDuration } from './fly-to-viewport';
8
- export { MAX_LATITUDE, lngLatToWorld, worldToLngLat, worldToPixels, pixelsToWorld, zoomToScale, scaleToZoom, altitudeToFovy, fovyToAltitude, getMeterZoom, getDistanceScales, addMetersToLngLat, getViewMatrix, getProjectionMatrix, getProjectionParameters } from './web-mercator-utils';
@@ -1,26 +0,0 @@
1
- import { transformMat4, scale } from 'gl-matrix/vec4';
2
- // Helper, avoids low-precision 32 bit matrices from gl-matrix mat4.create()
3
- export function createMat4() {
4
- return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
5
- }
6
- // Transforms a vec4 with a projection matrix
7
- export function transformVector(matrix, vector) {
8
- const result = transformMat4([], vector, matrix);
9
- scale(result, result, 1 / result[3]);
10
- return result;
11
- }
12
- export function mod(value, divisor) {
13
- const modulus = value % divisor;
14
- return modulus < 0 ? divisor + modulus : modulus;
15
- }
16
- export function lerp(start, end, step) {
17
- return step * end + (1 - step) * start;
18
- }
19
- export function clamp(x, min, max) {
20
- return x < min ? min : x > max ? max : x;
21
- }
22
- function ieLog2(x) {
23
- return Math.log(x) * Math.LOG2E;
24
- }
25
- // Handle missing log2 in IE 11
26
- export const log2 = Math.log2 || ieLog2;
@@ -1,41 +0,0 @@
1
- import { worldToLngLat } from './web-mercator-utils';
2
- import { mod, log2 } from './math-utils';
3
- // defined by mapbox-gl
4
- const TILE_SIZE = 512;
5
- /**
6
- * Apply mathematical constraints to viewport props
7
- * @param props
8
- */
9
- // eslint-disable-next-line complexity
10
- export default function normalizeViewportProps(props) {
11
- const { width, height, pitch = 0 } = props;
12
- let { longitude, latitude, zoom, bearing = 0 } = props;
13
- // Normalize degrees
14
- if (longitude < -180 || longitude > 180) {
15
- longitude = mod(longitude + 180, 360) - 180;
16
- }
17
- if (bearing < -180 || bearing > 180) {
18
- bearing = mod(bearing + 180, 360) - 180;
19
- }
20
- // Constrain zoom and shift center at low zoom levels
21
- const minZoom = log2(height / TILE_SIZE);
22
- if (zoom <= minZoom) {
23
- zoom = minZoom;
24
- latitude = 0;
25
- }
26
- else {
27
- // Eliminate white space above and below the map
28
- const halfHeightPixels = height / 2 / Math.pow(2, zoom);
29
- const minLatitude = worldToLngLat([0, halfHeightPixels])[1];
30
- if (latitude < minLatitude) {
31
- latitude = minLatitude;
32
- }
33
- else {
34
- const maxLatitude = worldToLngLat([0, TILE_SIZE - halfHeightPixels])[1];
35
- if (latitude > maxLatitude) {
36
- latitude = maxLatitude;
37
- }
38
- }
39
- }
40
- return { width, height, longitude, latitude, zoom, pitch, bearing };
41
- }
@@ -1,290 +0,0 @@
1
- // TODO - THE UTILITIES IN THIS FILE SHOULD BE IMPORTED FROM WEB-MERCATOR-VIEWPORT MODULE
2
- import { createMat4, transformVector, log2 } from './math-utils';
3
- import * as mat4 from 'gl-matrix/mat4';
4
- import * as vec2 from 'gl-matrix/vec2';
5
- import * as vec3 from 'gl-matrix/vec3';
6
- import assert from './assert';
7
- // CONSTANTS
8
- const PI = Math.PI;
9
- const PI_4 = PI / 4;
10
- const DEGREES_TO_RADIANS = PI / 180;
11
- const RADIANS_TO_DEGREES = 180 / PI;
12
- const TILE_SIZE = 512;
13
- // Average circumference (40075 km equatorial, 40007 km meridional)
14
- const EARTH_CIRCUMFERENCE = 40.03e6;
15
- // Latitude that makes a square world, 2 * atan(E ** PI) - PI / 2
16
- export const MAX_LATITUDE = 85.051129;
17
- // Mapbox default altitude
18
- export const DEFAULT_ALTITUDE = 1.5;
19
- /** Logarithimic zoom to linear scale **/
20
- export function zoomToScale(zoom) {
21
- return Math.pow(2, zoom);
22
- }
23
- /** Linear scale to logarithimic zoom **/
24
- export function scaleToZoom(scale) {
25
- return log2(scale);
26
- }
27
- /**
28
- * Project [lng,lat] on sphere onto [x,y] on 512*512 Mercator Zoom 0 tile.
29
- * Performs the nonlinear part of the web mercator projection.
30
- * Remaining projection is done with 4x4 matrices which also handles
31
- * perspective.
32
- *
33
- * @param lngLat - [lng, lat] coordinates
34
- * Specifies a point on the sphere to project onto the map.
35
- * @return [x,y] coordinates.
36
- */
37
- export function lngLatToWorld(lngLat) {
38
- const [lng, lat] = lngLat;
39
- assert(Number.isFinite(lng));
40
- assert(Number.isFinite(lat) && lat >= -90 && lat <= 90, 'invalid latitude');
41
- const lambda2 = lng * DEGREES_TO_RADIANS;
42
- const phi2 = lat * DEGREES_TO_RADIANS;
43
- const x = (TILE_SIZE * (lambda2 + PI)) / (2 * PI);
44
- const y = (TILE_SIZE * (PI + Math.log(Math.tan(PI_4 + phi2 * 0.5)))) / (2 * PI);
45
- return [x, y];
46
- }
47
- /**
48
- * Unproject world point [x,y] on map onto {lat, lon} on sphere
49
- *
50
- * @param xy - array with [x,y] members
51
- * representing point on projected map plane
52
- * @return - array with [x,y] of point on sphere.
53
- * Has toArray method if you need a GeoJSON Array.
54
- * Per cartographic tradition, lat and lon are specified as degrees.
55
- */
56
- export function worldToLngLat(xy) {
57
- const [x, y] = xy;
58
- const lambda2 = (x / TILE_SIZE) * (2 * PI) - PI;
59
- const phi2 = 2 * (Math.atan(Math.exp((y / TILE_SIZE) * (2 * PI) - PI)) - PI_4);
60
- return [lambda2 * RADIANS_TO_DEGREES, phi2 * RADIANS_TO_DEGREES];
61
- }
62
- /**
63
- * Returns the zoom level that gives a 1 meter pixel at a certain latitude
64
- * 1 = C*cos(y)/2^z/TILE_SIZE = C*cos(y)/2^(z+9)
65
- */
66
- export function getMeterZoom(options) {
67
- const { latitude } = options;
68
- assert(Number.isFinite(latitude));
69
- const latCosine = Math.cos(latitude * DEGREES_TO_RADIANS);
70
- return scaleToZoom(EARTH_CIRCUMFERENCE * latCosine) - 9;
71
- }
72
- /**
73
- * Calculate distance scales in meters around current lat/lon, both for
74
- * degrees and pixels.
75
- * In mercator projection mode, the distance scales vary significantly
76
- * with latitude.
77
- */
78
- export function getDistanceScales(options) {
79
- const { latitude, longitude, highPrecision = false } = options;
80
- assert(Number.isFinite(latitude) && Number.isFinite(longitude));
81
- const worldSize = TILE_SIZE;
82
- const latCosine = Math.cos(latitude * DEGREES_TO_RADIANS);
83
- /**
84
- * Number of pixels occupied by one degree longitude around current lat/lon:
85
- unitsPerDegreeX = d(lngLatToWorld([lng, lat])[0])/d(lng)
86
- = scale * TILE_SIZE * DEGREES_TO_RADIANS / (2 * PI)
87
- unitsPerDegreeY = d(lngLatToWorld([lng, lat])[1])/d(lat)
88
- = -scale * TILE_SIZE * DEGREES_TO_RADIANS / cos(lat * DEGREES_TO_RADIANS) / (2 * PI)
89
- */
90
- const unitsPerDegreeX = worldSize / 360;
91
- const unitsPerDegreeY = unitsPerDegreeX / latCosine;
92
- /**
93
- * Number of pixels occupied by one meter around current lat/lon:
94
- */
95
- const altUnitsPerMeter = worldSize / EARTH_CIRCUMFERENCE / latCosine;
96
- /**
97
- * LngLat: longitude -> east and latitude -> north (bottom left)
98
- * UTM meter offset: x -> east and y -> north (bottom left)
99
- * World space: x -> east and y -> south (top left)
100
- *
101
- * Y needs to be flipped when converting delta degree/meter to delta pixels
102
- */
103
- const result = {
104
- unitsPerMeter: [altUnitsPerMeter, altUnitsPerMeter, altUnitsPerMeter],
105
- metersPerUnit: [1 / altUnitsPerMeter, 1 / altUnitsPerMeter, 1 / altUnitsPerMeter],
106
- unitsPerDegree: [unitsPerDegreeX, unitsPerDegreeY, altUnitsPerMeter],
107
- degreesPerUnit: [1 / unitsPerDegreeX, 1 / unitsPerDegreeY, 1 / altUnitsPerMeter]
108
- };
109
- /**
110
- * Taylor series 2nd order for 1/latCosine
111
- f'(a) * (x - a)
112
- = d(1/cos(lat * DEGREES_TO_RADIANS))/d(lat) * dLat
113
- = DEGREES_TO_RADIANS * tan(lat * DEGREES_TO_RADIANS) / cos(lat * DEGREES_TO_RADIANS) * dLat
114
- */
115
- if (highPrecision) {
116
- const latCosine2 = (DEGREES_TO_RADIANS * Math.tan(latitude * DEGREES_TO_RADIANS)) / latCosine;
117
- const unitsPerDegreeY2 = (unitsPerDegreeX * latCosine2) / 2;
118
- const altUnitsPerDegree2 = (worldSize / EARTH_CIRCUMFERENCE) * latCosine2;
119
- const altUnitsPerMeter2 = (altUnitsPerDegree2 / unitsPerDegreeY) * altUnitsPerMeter;
120
- result.unitsPerDegree2 = [0, unitsPerDegreeY2, altUnitsPerDegree2];
121
- result.unitsPerMeter2 = [altUnitsPerMeter2, 0, altUnitsPerMeter2];
122
- }
123
- // Main results, used for converting meters to latlng deltas and scaling offsets
124
- return result;
125
- }
126
- /**
127
- * Offset a lng/lat position by meterOffset (northing, easting)
128
- */
129
- export function addMetersToLngLat(lngLatZ, xyz) {
130
- const [longitude, latitude, z0] = lngLatZ;
131
- const [x, y, z] = xyz;
132
- const { unitsPerMeter, unitsPerMeter2 } = getDistanceScales({
133
- longitude,
134
- latitude,
135
- highPrecision: true
136
- });
137
- const worldspace = lngLatToWorld(lngLatZ);
138
- worldspace[0] += x * (unitsPerMeter[0] + unitsPerMeter2[0] * y);
139
- worldspace[1] += y * (unitsPerMeter[1] + unitsPerMeter2[1] * y);
140
- const newLngLat = worldToLngLat(worldspace);
141
- const newZ = (z0 || 0) + (z || 0);
142
- return Number.isFinite(z0) || Number.isFinite(z) ? [newLngLat[0], newLngLat[1], newZ] : newLngLat;
143
- }
144
- /**
145
- *
146
- * view and projection matrix creation is intentionally kept compatible with
147
- * mapbox-gl's implementation to ensure that seamless interoperation
148
- * with mapbox and react-map-gl. See: https://github.com/mapbox/mapbox-gl-js
149
- */
150
- export function getViewMatrix(options) {
151
- const {
152
- // Viewport props
153
- height, pitch, bearing, altitude,
154
- // Pre-calculated parameters
155
- scale, center } = options;
156
- // VIEW MATRIX: PROJECTS MERCATOR WORLD COORDINATES
157
- // Note that mercator world coordinates typically need to be flipped
158
- //
159
- // Note: As usual, matrix operation orders should be read in reverse
160
- // since vectors will be multiplied from the right during transformation
161
- const vm = createMat4();
162
- // Move camera to altitude (along the pitch & bearing direction)
163
- mat4.translate(vm, vm, [0, 0, -altitude]);
164
- // Rotate by bearing, and then by pitch (which tilts the view)
165
- mat4.rotateX(vm, vm, -pitch * DEGREES_TO_RADIANS);
166
- mat4.rotateZ(vm, vm, bearing * DEGREES_TO_RADIANS);
167
- const relativeScale = scale / height;
168
- mat4.scale(vm, vm, [relativeScale, relativeScale, relativeScale]);
169
- if (center) {
170
- mat4.translate(vm, vm, vec3.negate([], center));
171
- }
172
- return vm;
173
- }
174
- /**
175
- * Calculates mapbox compatible projection matrix from parameters
176
- *
177
- * @param options.width Width of "viewport" or window
178
- * @param options.height Height of "viewport" or window
179
- * @param options.pitch Camera angle in degrees (0 is straight down)
180
- * @param options.fovy field of view in degrees
181
- * @param options.altitude if provided, field of view is calculated using `altitudeToFovy()`
182
- * @param options.nearZMultiplier control z buffer
183
- * @param options.farZMultiplier control z buffer
184
- * @returns project parameters object
185
- */
186
- export function getProjectionParameters(options) {
187
- const { width, height, altitude, pitch = 0, nearZMultiplier = 1, farZMultiplier = 1 } = options;
188
- let { fovy = altitudeToFovy(DEFAULT_ALTITUDE) } = options;
189
- // For back-compatibility allow field of view to be
190
- // derived from altitude
191
- if (altitude !== undefined) {
192
- fovy = altitudeToFovy(altitude);
193
- }
194
- const halfFov = 0.5 * fovy * DEGREES_TO_RADIANS;
195
- const focalDistance = fovyToAltitude(fovy);
196
- // Find the distance from the center point to the center top
197
- // in focal distance units using law of sines.
198
- const pitchRadians = pitch * DEGREES_TO_RADIANS;
199
- const topHalfSurfaceDistance = (Math.sin(halfFov) * focalDistance) /
200
- Math.sin(Math.min(Math.max(Math.PI / 2 - pitchRadians - halfFov, 0.01), Math.PI - 0.01));
201
- // Calculate z value of the farthest fragment that should be rendered.
202
- const farZ = Math.sin(pitchRadians) * topHalfSurfaceDistance + focalDistance;
203
- return {
204
- fov: 2 * halfFov,
205
- aspect: width / height,
206
- focalDistance,
207
- near: nearZMultiplier,
208
- far: farZ * farZMultiplier
209
- };
210
- }
211
- /**
212
- * CALCULATE PROJECTION MATRIX: PROJECTS FROM CAMERA (VIEW) SPACE TO CLIPSPACE
213
- *
214
- * To match mapbox's z buffer:
215
- * - \<= 0.28: nearZMultiplier: 0.1, farZmultiplier: 1
216
- * - \>= 0.29: nearZMultiplier: 1 / height, farZMultiplier: 1.01
217
- *
218
- * @param options Viewport options
219
- * @param options.width Width of "viewport" or window
220
- * @param options.height Height of "viewport" or window
221
- * @param options.pitch Camera angle in degrees (0 is straight down)
222
- * @param options.fovy field of view in degrees
223
- * @param options.altitude if provided, field of view is calculated using `altitudeToFovy()`
224
- * @param options.nearZMultiplier control z buffer
225
- * @param options.farZMultiplier control z buffer
226
- * @returns 4x4 projection matrix
227
- */
228
- export function getProjectionMatrix(options) {
229
- const { fov, aspect, near, far } = getProjectionParameters(options);
230
- const projectionMatrix = mat4.perspective([], fov, // fov in radians
231
- aspect, // aspect ratio
232
- near, // near plane
233
- far // far plane
234
- );
235
- return projectionMatrix;
236
- }
237
- /**
238
- *
239
- * Convert an altitude to field of view such that the
240
- * focal distance is equal to the altitude
241
- *
242
- * @param altitude - altitude of camera in screen units
243
- * @return fovy field of view in degrees
244
- */
245
- export function altitudeToFovy(altitude) {
246
- return 2 * Math.atan(0.5 / altitude) * RADIANS_TO_DEGREES;
247
- }
248
- /**
249
- *
250
- * Convert an field of view such that the
251
- * focal distance is equal to the altitude
252
- *
253
- * @param fovy - field of view in degrees
254
- * @return altitude altitude of camera in screen units
255
- */
256
- export function fovyToAltitude(fovy) {
257
- return 0.5 / Math.tan(0.5 * fovy * DEGREES_TO_RADIANS);
258
- }
259
- // Project flat coordinates to pixels on screen.
260
- export function worldToPixels(xyz, pixelProjectionMatrix) {
261
- const [x, y, z = 0] = xyz;
262
- assert(Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z));
263
- return transformVector(pixelProjectionMatrix, [x, y, z, 1]);
264
- }
265
- /**
266
- * Unproject pixels on screen to flat coordinates.
267
- *
268
- * @param xyz - pixel coordinate on screen.
269
- * @param pixelUnprojectionMatrix - unprojection matrix 4x4
270
- * @param targetZ - if pixel coordinate does not have a 3rd component (depth),
271
- * targetZ is used as the elevation plane to unproject onto
272
- * @return [x, y, Z] flat coordinates on 512*512 Mercator Zoom 0 tile.
273
- */
274
- export function pixelsToWorld(xyz, pixelUnprojectionMatrix, targetZ = 0) {
275
- const [x, y, z] = xyz;
276
- assert(Number.isFinite(x) && Number.isFinite(y), 'invalid pixel coordinate');
277
- if (Number.isFinite(z)) {
278
- // Has depth component
279
- const coord = transformVector(pixelUnprojectionMatrix, [x, y, z, 1]);
280
- return coord;
281
- }
282
- // since we don't know the correct projected z value for the point,
283
- // unproject two points to get a line and then find the point on that line with z=0
284
- const coord0 = transformVector(pixelUnprojectionMatrix, [x, y, 0, 1]);
285
- const coord1 = transformVector(pixelUnprojectionMatrix, [x, y, 1, 1]);
286
- const z0 = coord0[2];
287
- const z1 = coord1[2];
288
- const t = z0 === z1 ? 0 : ((targetZ || 0) - z0) / (z1 - z0);
289
- return vec2.lerp([], coord0, coord1, t);
290
- }