@math.gl/geospatial 5.0.0-alpha.12 → 5.0.0-alpha.14

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.
@@ -6,12 +6,18 @@
6
6
 
7
7
  import {NumericArray} from '@math.gl/types';
8
8
  import {Vector3, assert, equals as equalsEpsilon} from '@math.gl/core';
9
+ import {
10
+ createLocalFrameBasis,
11
+ eastNorthUpBasisFromDirections,
12
+ localFrameToMatrix
13
+ } from '@math.gl/core/local-frame';
9
14
 
10
15
  import type {Ellipsoid} from '../ellipsoid';
11
16
 
12
17
  const EPSILON14 = 1e-14;
13
18
 
14
19
  const scratchOrigin = new Vector3();
20
+ const scratchBasis = createLocalFrameBasis();
15
21
 
16
22
  export type AxisDirection = 'up' | 'down' | 'north' | 'east' | 'south' | 'west';
17
23
 
@@ -105,6 +111,32 @@ export function localFrameToFixedFrame(
105
111
  // If x and y are zero, assume origin is at a pole, which is a special case.
106
112
  const atPole = equalsEpsilon(origin.x, 0.0, EPSILON14) && equalsEpsilon(origin.y, 0.0, EPSILON14);
107
113
 
114
+ // Only the qualified sphere/oblate basis is shared. Three-radius and center
115
+ // conventions keep the retained Cesium path, without changing its normal choice.
116
+ const radii = ellipsoid.radii;
117
+ if (
118
+ radii.x === radii.y &&
119
+ radii.x > 0 &&
120
+ radii.z > 0 &&
121
+ radii.z <= radii.x &&
122
+ (!atPole || origin.z !== 0)
123
+ ) {
124
+ const {east, up} = scratchAxisVectors;
125
+ if (atPole) {
126
+ east.set(0, 1, 0);
127
+ up.set(0, 0, Math.sign(origin.z));
128
+ } else {
129
+ east.set(-origin.y, origin.x, 0).normalize();
130
+ ellipsoid.geodeticSurfaceNormal(origin, up);
131
+ }
132
+ if (
133
+ !eastNorthUpBasisFromDirections(east, up, scratchBasis) ||
134
+ !localFrameToMatrix(scratchBasis, origin, firstAxis, secondAxis, thirdAxis, result)
135
+ )
136
+ throw new Error('Unsupported local frame');
137
+ return result;
138
+ }
139
+
108
140
  if (atPole) {
109
141
  // Look up axis value and adjust
110
142
  const sign = Math.sign(origin.z);
@@ -143,22 +175,35 @@ export function localFrameToFixedFrame(
143
175
  thirdAxisVector = scratchAxisVectors[thirdAxis];
144
176
  }
145
177
 
146
- // TODO - assuming the result is column-major
147
- result[0] = firstAxisVector.x;
148
- result[1] = firstAxisVector.y;
149
- result[2] = firstAxisVector.z;
178
+ // Snapshot the retained three-radius/center path too: application result setters
179
+ // can recursively invoke either path and overwrite all module scratch vectors.
180
+ const ax = firstAxisVector.x,
181
+ ay = firstAxisVector.y,
182
+ az = firstAxisVector.z;
183
+ const bx = secondAxisVector.x,
184
+ by = secondAxisVector.y,
185
+ bz = secondAxisVector.z;
186
+ const cx = thirdAxisVector.x,
187
+ cy = thirdAxisVector.y,
188
+ cz = thirdAxisVector.z;
189
+ const x = origin.x,
190
+ y = origin.y,
191
+ z = origin.z;
192
+ result[0] = ax;
193
+ result[1] = ay;
194
+ result[2] = az;
150
195
  result[3] = 0.0;
151
- result[4] = secondAxisVector.x;
152
- result[5] = secondAxisVector.y;
153
- result[6] = secondAxisVector.z;
196
+ result[4] = bx;
197
+ result[5] = by;
198
+ result[6] = bz;
154
199
  result[7] = 0.0;
155
- result[8] = thirdAxisVector.x;
156
- result[9] = thirdAxisVector.y;
157
- result[10] = thirdAxisVector.z;
200
+ result[8] = cx;
201
+ result[9] = cy;
202
+ result[10] = cz;
158
203
  result[11] = 0.0;
159
- result[12] = origin.x;
160
- result[13] = origin.y;
161
- result[14] = origin.z;
204
+ result[12] = x;
205
+ result[13] = y;
206
+ result[14] = z;
162
207
  result[15] = 1.0;
163
208
  return result;
164
209
  }
@@ -0,0 +1,135 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ // SPDX-FileComment: Original scaled-space analytic geometry. Consumer requirements: https://github.com/keplergl/kepler.gl/pull/3557 and https://github.com/keplergl/kepler.gl/pull/3593. No implementation code copied.
5
+
6
+ /** The limb is center + axis1*cos(t) + axis2*sin(t), in input Cartesian units. */
7
+ export type EllipsoidHorizon = {
8
+ center: number[];
9
+ axis1: number[];
10
+ axis2: number[];
11
+ };
12
+
13
+ /** Axis-aligned ellipsoid queries, independent of viewport and vector classes. */
14
+ export class EllipsoidOccluder {
15
+ readonly radii: readonly number[];
16
+ readonly center: readonly number[];
17
+
18
+ constructor(radii: Readonly<ArrayLike<number>>, center: Readonly<ArrayLike<number>> = [0, 0, 0]) {
19
+ validateVector(radii);
20
+ validateVector(center);
21
+ if (Array.from(radii).some(value => value <= 0)) throw new RangeError('Radii must be positive');
22
+ this.radii = Object.freeze(Array.from(radii));
23
+ this.center = Object.freeze(Array.from(center));
24
+ }
25
+
26
+ /** Nonnegative ray parameter interval, including tangency and inside-origin rays.
27
+ * Direction need not be normalized. Undefined is a true miss; never clamps a miss
28
+ * to the limb. Result is untouched on miss. Distances equal parameters only for
29
+ * unit directions. Zero direction is a miss.
30
+ */
31
+ intersectRay(
32
+ origin: Readonly<ArrayLike<number>>,
33
+ direction: Readonly<ArrayLike<number>>,
34
+ result: number[] = [0, 0]
35
+ ): number[] | undefined {
36
+ validateVector(origin);
37
+ validateVector(direction);
38
+ const [x, y, z] = this.scalePoint(origin);
39
+ const dx = direction[0] / this.radii[0];
40
+ const dy = direction[1] / this.radii[1];
41
+ const dz = direction[2] / this.radii[2];
42
+ // Normalize in scaled space: avoid a tiny quadratic coefficient for ECEF rays.
43
+ const length = Math.hypot(dx, dy, dz);
44
+ if (length === 0 || !Number.isFinite(length)) return undefined;
45
+ const ux = dx / length,
46
+ uy = dy / length,
47
+ uz = dz / length;
48
+ const along = -(x * ux + y * uy + z * uz);
49
+ const perpendicular = Math.hypot(y * uz - z * uy, z * ux - x * uz, x * uy - y * ux);
50
+ if (perpendicular > 1) return undefined;
51
+ const half = Math.sqrt((1 - perpendicular) * (1 + perpendicular));
52
+ let near = along - half;
53
+ let far = along + half;
54
+ // Recover the small root by the root product rather than subtracting large terms.
55
+ const radius = Math.hypot(x, y, z);
56
+ if (!Number.isFinite(radius)) throw new RangeError('Scaled origin magnitude must be finite');
57
+ if (half > 0 && along > 0 && far !== 0) near = ((radius - 1) / far) * (radius + 1);
58
+ if (half > 0 && along < 0 && near !== 0) far = ((radius - 1) / near) * (radius + 1);
59
+ if (far < 0) return undefined;
60
+ result[0] = Math.max(0, Math.min(near, far)) / length;
61
+ result[1] = Math.max(0, far) / length;
62
+ return result;
63
+ }
64
+
65
+ /** True if the finite camera-to-point segment enters the solid interior.
66
+ * Surface contact/tangency alone is not occlusion. Works for elevated points;
67
+ * unlike a facing-normal test it does not discard visible points beyond the
68
+ * surface horizon. tolerance is a nonnegative scaled-space squared-radius margin.
69
+ */
70
+ isPointOccluded(
71
+ camera: Readonly<ArrayLike<number>>,
72
+ point: Readonly<ArrayLike<number>>,
73
+ tolerance = 1e-12
74
+ ): boolean {
75
+ validateVector(camera);
76
+ validateVector(point);
77
+ if (!Number.isFinite(tolerance) || tolerance < 0 || tolerance >= 1)
78
+ throw new RangeError('Tolerance must be in [0, 1)');
79
+ const a = this.scalePoint(camera);
80
+ const b = this.scalePoint(point);
81
+ const dx = b[0] - a[0],
82
+ dy = b[1] - a[1],
83
+ dz = b[2] - a[2];
84
+ const length = Math.hypot(dx, dy, dz);
85
+ if (!Number.isFinite(length)) throw new RangeError('Segment magnitude must be finite');
86
+ if (length === 0) return Math.hypot(...a) ** 2 < 1 - tolerance;
87
+ const ux = dx / length,
88
+ uy = dy / length,
89
+ uz = dz / length;
90
+ const distance = Math.max(0, Math.min(length, -(a[0] * ux + a[1] * uy + a[2] * uz)));
91
+ return (
92
+ Math.hypot(a[0] + distance * ux, a[1] + distance * uy, a[2] + distance * uz) ** 2 <
93
+ 1 - tolerance
94
+ );
95
+ }
96
+
97
+ /** Exact apparent limb ellipse for an exterior camera; undefined on/inside surface. */
98
+ getHorizon(camera: Readonly<ArrayLike<number>>): EllipsoidHorizon | undefined {
99
+ validateVector(camera);
100
+ const scaled = this.scalePoint(camera);
101
+ const distance = Math.hypot(...scaled);
102
+ if (!Number.isFinite(distance)) throw new RangeError('Camera magnitude must be finite');
103
+ if (distance <= 1) return undefined;
104
+ const normal = scaled.map(value => value / distance);
105
+ // Choose a basis away from parallel to the normal, including polar views.
106
+ const reference = Math.abs(normal[2]) < 0.9 ? [0, 0, 1] : [0, 1, 0];
107
+ const u = cross(normal, reference);
108
+ const uLength = Math.hypot(...u);
109
+ const v = cross(
110
+ normal,
111
+ u.map(value => value / uLength)
112
+ );
113
+ const radius = Math.sqrt((1 - 1 / distance) * (1 + 1 / distance));
114
+ return {
115
+ center: normal.map((value, i) => this.center[i] + (this.radii[i] * value) / distance),
116
+ axis1: u.map((value, i) => (this.radii[i] * radius * value) / uLength),
117
+ axis2: v.map((value, i) => this.radii[i] * radius * value)
118
+ };
119
+ }
120
+
121
+ private scalePoint(point: Readonly<ArrayLike<number>>): number[] {
122
+ const result = this.radii.map((radius, i) => (point[i] - this.center[i]) / radius);
123
+ if (!result.every(Number.isFinite)) throw new RangeError('Scaled coordinates must be finite');
124
+ return result;
125
+ }
126
+ }
127
+
128
+ function validateVector(vector: Readonly<ArrayLike<number>>): void {
129
+ if (vector.length !== 3 || !Array.from(vector).every(Number.isFinite))
130
+ throw new RangeError('Expected three finite Cartesian components');
131
+ }
132
+
133
+ function cross(a: number[], b: number[]): number[] {
134
+ return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
135
+ }
package/src/ellipsoid.ts CHANGED
@@ -179,16 +179,13 @@ export class Ellipsoid {
179
179
  const y = 'x' in cartesian ? object.y : cartesian[1];
180
180
  const z = 'x' in cartesian ? object.z : cartesian[2];
181
181
  if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) return undefined;
182
- // Shared inverse is qualified for the unambiguous surface/exterior domain.
183
- // Interior/radial-fallback and non-spheroid behavior retain the Cesium kernel.
184
- const a = this.radii.x,
185
- b = this.radii.z;
186
- const normSquared = (x / a) ** 2 + (y / a) ** 2 + (z / b) ** 2;
182
+ // Sphere/oblate conversion chooses the unique nearest normal, including interiors.
183
+ // Preserve legacy geometry magnitude limits; prolate/triaxial keep their own kernel.
187
184
  if (
188
185
  this.spheroidGeometry &&
189
- Number.isFinite(normSquared) &&
190
- normSquared >= 1 - 16 * Number.EPSILON &&
191
- Number.isFinite(x * x + y * y + z * z)
186
+ Number.isFinite(x * x + y * y + z * z) &&
187
+ Number.isFinite(this.oneOverRadiiSquared.x) &&
188
+ Number.isFinite(this.oneOverRadiiSquared.z)
192
189
  ) {
193
190
  spheroidScratch.x = x;
194
191
  spheroidScratch.y = y;
@@ -0,0 +1,87 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ import {splitGlobeBounds, type GlobeBounds} from './globe-horizon-bounds';
5
+
6
+ /** Equal-angle longitude/latitude grid: one world tile at level zero, north-origin Y. */
7
+ export type GeographicTile = {x: number; y: number; level: number};
8
+ /** Inclusive integer tile ranges. Ranges are disjoint and ordered by minX. */
9
+ export type GeographicTileRange = {minX: number; maxX: number; minY: number; maxY: number};
10
+
11
+ /** Geographic degree bounds of an equal-angle tile, not Web Mercator XYZ. */
12
+ export function getGeographicTileBounds(tile: GeographicTile): GlobeBounds {
13
+ const size = gridSize(tile.level);
14
+ if (![tile.x, tile.y].every(v => Number.isInteger(v) && v >= 0 && v < size))
15
+ throw new RangeError('Tile coordinates must be integers inside the level grid');
16
+ return [
17
+ -180 + (360 * tile.x) / size,
18
+ 90 - (180 * (tile.y + 1)) / size,
19
+ -180 + (360 * (tile.x + 1)) / size,
20
+ 90 - (180 * tile.y) / size
21
+ ];
22
+ }
23
+
24
+ /** Address a point in degrees. Interior edges belong to the east/south tile. */
25
+ export function getGeographicTile(
26
+ longitude: number,
27
+ latitude: number,
28
+ level: number
29
+ ): GeographicTile {
30
+ const size = gridSize(level);
31
+ if (
32
+ !Number.isFinite(longitude) ||
33
+ longitude < -180 ||
34
+ longitude > 180 ||
35
+ !Number.isFinite(latitude) ||
36
+ latitude < -90 ||
37
+ latitude > 90
38
+ )
39
+ throw new RangeError('Expected longitude in [-180, 180] and latitude in [-90, 90]');
40
+ return {
41
+ x: Math.min(size - 1, Math.floor(((longitude + 180) / 360) * size)),
42
+ y: Math.min(size - 1, Math.floor(((90 - latitude) / 180) * size)),
43
+ level
44
+ };
45
+ }
46
+
47
+ /** Cover a degree rectangle without enumerating tiles, including wrapped longitude.
48
+ * Positive-area queries exclude edge-only neighbors; zero-width/height queries use
49
+ * point-address edge ownership. Both +/-180 spellings of the seam stay explicit.
50
+ */
51
+ export function getGeographicTileRanges(bounds: GlobeBounds, level: number): GeographicTileRange[] {
52
+ const size = gridSize(level);
53
+ const split = splitGlobeBounds(bounds);
54
+ const positiveWidth = split.filter(([west, , east]) => east > west);
55
+ const rectangles = positiveWidth.length ? positiveWidth : split;
56
+ const intervals = rectangles
57
+ .map(([west, south, east, north]) => {
58
+ const start = getGeographicTile(west, north, level);
59
+ return {
60
+ minX: start.x,
61
+ maxX:
62
+ west === east
63
+ ? start.x
64
+ : Math.max(start.x, Math.min(size - 1, Math.ceil(((east + 180) / 360) * size) - 1)),
65
+ minY: start.y,
66
+ maxY:
67
+ south === north
68
+ ? start.y
69
+ : Math.max(start.y, Math.min(size - 1, Math.ceil(((90 - south) / 180) * size) - 1))
70
+ };
71
+ })
72
+ .sort((a, b) => a.minX - b.minX);
73
+ const result: GeographicTileRange[] = [];
74
+ for (const range of intervals) {
75
+ const previous = result[result.length - 1];
76
+ if (previous && range.minX <= previous.maxX + 1)
77
+ previous.maxX = Math.max(previous.maxX, range.maxX);
78
+ else result.push(range);
79
+ }
80
+ return result;
81
+ }
82
+
83
+ function gridSize(level: number): number {
84
+ if (!Number.isInteger(level) || level < 0 || level > 30)
85
+ throw new RangeError('Level must be an integer from 0 through 30');
86
+ return 2 ** level;
87
+ }
@@ -0,0 +1,68 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ // SPDX-FileComment: Original spherical-cap extrema; requirements from https://github.com/keplergl/kepler.gl/pull/3557. No sampled viewport or upstream implementation copied.
5
+
6
+ /** Degrees [west, south, east, north]; west > east means a dateline crossing. */
7
+ export type GlobeBounds = readonly [number, number, number, number];
8
+
9
+ /** Conservative geographic extent of every visible surface point on a sphere.
10
+ * Cartesian X points to longitude 0, Y to longitude 90, Z north. Covers the
11
+ * entire horizon cap, not just the screen: safe overfetch, not viewport-tight.
12
+ * Returns undefined on/inside the sphere. Radius and camera use matching units.
13
+ */
14
+ export function getGlobeHorizonBounds(
15
+ camera: Readonly<ArrayLike<number>>,
16
+ radius: number
17
+ ): GlobeBounds | undefined {
18
+ if (
19
+ camera.length !== 3 ||
20
+ !Array.from(camera).every(Number.isFinite) ||
21
+ !Number.isFinite(radius) ||
22
+ radius <= 0
23
+ )
24
+ throw new RangeError('Expected a finite camera and positive sphere radius');
25
+ const distance = Math.hypot(camera[0], camera[1], camera[2]);
26
+ if (!Number.isFinite(distance)) throw new RangeError('Camera magnitude must be finite');
27
+ if (distance <= radius) return undefined;
28
+ const latitude = Math.atan2(camera[2], Math.hypot(camera[0], camera[1]));
29
+ const longitude = Math.atan2(camera[1], camera[0]);
30
+ const angle = Math.acos(radius / distance);
31
+ const degrees = 180 / Math.PI;
32
+ // Outward padding protects tangent and near-pole limits from floating rounding.
33
+ const padding = 1e-10;
34
+ const south = Math.max(-90, (latitude - angle) * degrees - padding);
35
+ const north = Math.min(90, (latitude + angle) * degrees + padding);
36
+ if (Math.abs(latitude) + angle >= Math.PI / 2 - 1e-12) return [-180, south, 180, north];
37
+ const extent = Math.asin(Math.min(1, Math.sin(angle) / Math.cos(latitude))) * degrees + padding;
38
+ return [wrap(longitude * degrees - extent), south, wrap(longitude * degrees + extent), north];
39
+ }
40
+
41
+ /** Split wrapped bounds into protocol-safe rectangles (e.g. EPSG:4326 WMS).
42
+ * No screen sampling, image caching or request policy is implied.
43
+ */
44
+ export function splitGlobeBounds(bounds: GlobeBounds): GlobeBounds[] {
45
+ const [west, south, east, north] = bounds;
46
+ if (
47
+ bounds.length !== 4 ||
48
+ !bounds.every(Number.isFinite) ||
49
+ west < -180 ||
50
+ west > 180 ||
51
+ east < -180 ||
52
+ east > 180 ||
53
+ south < -90 ||
54
+ north > 90 ||
55
+ south > north
56
+ )
57
+ throw new RangeError('Invalid degree bounds');
58
+ return west <= east
59
+ ? [[west, south, east, north]]
60
+ : [
61
+ [west, south, 180, north],
62
+ [-180, south, east, north]
63
+ ];
64
+ }
65
+
66
+ function wrap(longitude: number): number {
67
+ return ((((longitude + 180) % 360) + 360) % 360) - 180;
68
+ }
package/src/index.ts CHANGED
@@ -10,3 +10,15 @@ export type {GeodeticRegion, MakeOBBFromRegionOptions} from './make-obb-from-reg
10
10
  export {isWGS84} from './type-utils';
11
11
 
12
12
  export type {SpheroidParameters} from '@math.gl/types';
13
+
14
+ export {EllipsoidOccluder} from './ellipsoid-occluder';
15
+ export type {EllipsoidHorizon} from './ellipsoid-occluder';
16
+ export {getGlobeHorizonBounds, splitGlobeBounds} from './globe-horizon-bounds';
17
+ export type {GlobeBounds} from './globe-horizon-bounds';
18
+
19
+ export {
20
+ getGeographicTile,
21
+ getGeographicTileBounds,
22
+ getGeographicTileRanges
23
+ } from './geographic-tiles';
24
+ export type {GeographicTile, GeographicTileRange} from './geographic-tiles';