diff --git a/docs/whats-new.md b/docs/whats-new.md index a40c38c3..f1916ad5 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -31,6 +31,10 @@ - Add `isTypedArray()` and `isNumericArray()` utilities that both check values and return properly restricted types to help write strictly typed code (avoids the `DataView` issue with `ArrayBuffer.isView()`). +**`@math.gl/s2`** (NEW MODULE) + +- New module that contains a lightweight implementation of the S2 DGGS (Discrete Global Grid System). + ## v3.6 Target Release Date: Q4, 2021 diff --git a/modules/s2/README.md b/modules/s2/README.md new file mode 100644 index 00000000..a17d7ff6 --- /dev/null +++ b/modules/s2/README.md @@ -0,0 +1,7 @@ +# @math.gl/s2 + +[math.gl](https://math.gl/docs) is a suite of math modules for 3D and geospatial applications. + +This module contains math to work with the S2 DGGS (Discrete Global Grid System). + +For documentation please visit the [website](https://math.gl). diff --git a/modules/s2/docs/README.md b/modules/s2/docs/README.md new file mode 100644 index 00000000..03f3fda6 --- /dev/null +++ b/modules/s2/docs/README.md @@ -0,0 +1,21 @@ +# Overview + +`@math.gl/s2` is a small JavaScript library for working with the S2 DGGS (Discrete Global Grid System). + +## Installation + +```bash +npm install @math.gl/s2 +``` + +## Usage + +```js +import {} from '@math.gl/s2'; +``` + +## Attribution + +This module is a fork of a subset of the s2-geometry module under ISC License (ISC) +Copyright (c) 2012-2016, Jon Atkins +Copyright (c) 2016, AJ ONeal diff --git a/modules/s2/docs/api-reference/s2.md b/modules/s2/docs/api-reference/s2.md new file mode 100644 index 00000000..9fc8ee17 --- /dev/null +++ b/modules/s2/docs/api-reference/s2.md @@ -0,0 +1,5 @@ +# S2 + +See [s2geometry.io](https://s2geometry.io/) for more information. + +> TBA diff --git a/modules/s2/package.json b/modules/s2/package.json new file mode 100644 index 00000000..3536627f --- /dev/null +++ b/modules/s2/package.json @@ -0,0 +1,35 @@ +{ + "name": "@math.gl/s2", + "description": "A minimal S2 DGGS (Discrete Global Grid System) implementation", + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "version": "3.6.3", + "keywords": [ + "javascript", + "math", + "geospatial", + "sun", + "suncalc", + "solar" + ], + "repository": { + "type": "git", + "url": "https://github.com/uber-web/math.gl.git" + }, + "types": "dist/index.d.ts", + "main": "dist/es5/index.js", + "module": "dist/esm/index.js", + "files": [ + "dist", + "src" + ], + "dependencies": { + "@babel/runtime": "^7.12.0", + "long": "^5.2.1" + }, + "devDependencies": { + "s2-geometry": "^1.2.10" + } +} diff --git a/modules/s2/src/index.ts b/modules/s2/src/index.ts new file mode 100644 index 00000000..f795249e --- /dev/null +++ b/modules/s2/src/index.ts @@ -0,0 +1,13 @@ +// math.gl MIT license + +export {getIdFromToken, getGeoBounds, getS2QuadKey, getS2Polygon} from './s2-utils'; + +export { + getTokenFromId, + getS2ChildCellId, + getS2CellFromToken, + get2dRegionFromS2Cell +} from './s2-utils-ext'; + +export type {S2HeightInfo} from './s2-to-obb-points'; +export {getOrientedBoundingBoxCornerPoints} from './s2-to-obb-points'; diff --git a/modules/s2/src/s2-geometry.ts b/modules/s2/src/s2-geometry.ts new file mode 100644 index 00000000..12ef0c1f --- /dev/null +++ b/modules/s2/src/s2-geometry.ts @@ -0,0 +1,204 @@ +// math.gl, MIT license +/* +Adapted from s2-geometry under ISC License (ISC) +Copyright (c) 2012-2016, Jon Atkins +Copyright (c) 2016, AJ ONeal +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +*/ + +import Long from 'long'; + +// +// Functional Style +// +const FACE_BITS = 3; +const MAX_LEVEL = 30; +const POS_BITS = 2 * MAX_LEVEL + 1; // 61 (60 bits of data, 1 bit lsb marker) +const RADIAN_TO_DEGREE = 180 / Math.PI; + +export function IJToST( + ij: [number, number], + order: number, + offsets: [number, number] +): [number, number] { + const maxSize = 1 << order; + + return [(ij[0] + offsets[0]) / maxSize, (ij[1] + offsets[1]) / maxSize]; +} + +function singleSTtoUV(st: number): number { + if (st >= 0.5) { + return (1 / 3.0) * (4 * st * st - 1); + } + return (1 / 3.0) * (1 - 4 * (1 - st) * (1 - st)); +} + +export function STToUV(st: [number, number]): [number, number] { + return [singleSTtoUV(st[0]), singleSTtoUV(st[1])]; +} + +export function FaceUVToXYZ(face: number, [u, v]: [number, number]): [number, number, number] { + switch (face) { + case 0: + return [1, u, v]; + case 1: + return [-u, 1, v]; + case 2: + return [-u, -v, 1]; + case 3: + return [-1, -v, -u]; + case 4: + return [v, -1, -u]; + case 5: + return [v, u, -1]; + default: + throw new Error('Invalid face'); + } +} + +export function XYZToLngLat([x, y, z]: [number, number, number]): [number, number] { + const lat = Math.atan2(z, Math.sqrt(x * x + y * y)); + const lng = Math.atan2(y, x); + + return [lng * RADIAN_TO_DEGREE, lat * RADIAN_TO_DEGREE]; +} + +/* + Here is the version of toHilbertQuadkey taken from deck.gl + We replace it with the function that takes Long instead of string. + The original function does not support the case of level==0 + +export function toHilbertQuadkey(idS: string): string { + let bin = Long.fromString(idS, true, 10).toString(2); + + while (bin.length < FACE_BITS + POS_BITS) { + // eslint-disable-next-line prefer-template + bin = '0' + bin; + } + + // MUST come AFTER binstr has been left-padded with '0's + const lsbIndex = bin.lastIndexOf('1'); + // substr(start, len) + // substring(start, end) // includes start, does not include end + const faceB = bin.substring(0, 3); + // posB will always be a multiple of 2 (or it's invalid) + const posB = bin.substring(3, lsbIndex); + const levelN = posB.length / 2; + + const faceS = Long.fromString(faceB, true, 2).toString(10); + let posS = Long.fromString(posB, true, 2).toString(4); + + while (posS.length < levelN) { + // eslint-disable-next-line prefer-template + posS = '0' + posS; + } + + return `${faceS}/${posS}`; +} +*/ + +export function toHilbertQuadkey(id: Long): string { + let bin = id.toString(2); + + while (bin.length < FACE_BITS + POS_BITS) { + // eslint-disable-next-line prefer-template + bin = '0' + bin; + } + + // MUST come AFTER binstr has been left-padded with '0's + const lsbIndex = bin.lastIndexOf('1'); + // substr(start, len) + // substring(start, end) // includes start, does not include end + const faceB = bin.substring(0, 3); + // posB will always be a multiple of 2 (or it's invalid) + const posB = bin.substring(3, lsbIndex); + const levelN = posB.length / 2; + + const faceS = Long.fromString(faceB, true, 2).toString(10); + + /* + Here is a fix for the case when posB is an empty string that causes an exception in Long.fromString + + let posS = Long.fromString(posB, true, 2).toString(4); + */ + let posS = '0'; + if (levelN !== 0) { + // posB is not an empty string< because levelN!==0 + posS = Long.fromString(posB, true, 2).toString(4); + + while (posS.length < levelN) { + // eslint-disable-next-line prefer-template + posS = '0' + posS; + } + } + // Note, posS will be "0" for the level==0 + // TODO: Is it ok? + + return `${faceS}/${posS}`; +} + +function rotateAndFlipQuadrant(n: number, point: [number, number], rx: number, ry: number): void { + if (ry === 0) { + if (rx === 1) { + point[0] = n - 1 - point[0]; + point[1] = n - 1 - point[1]; + } + + const x = point[0]; + point[0] = point[1]; + point[1] = x; + } +} + +/* + Original function taken from deck.gl doesn't support the case of (face <= 5) + It's fixed here. +*/ +export function FromHilbertQuadKey(hilbertQuadkey: string): { + face: number; + ij: [number, number]; + level: number; +} { + const parts = hilbertQuadkey.split('/'); + const face = parseInt(parts[0], 10); + const position = parts[1]; + /* + Fix for the case of level==0 that corresponds to (face <= 5) + const maxLevel = position.length; + let level; + */ + const maxLevel = face > 5 ? position.length : 0; + let level = 0; + + const point = [0, 0] as [number, number]; + + for (let i = maxLevel - 1; i >= 0; i--) { + level = maxLevel - i; + const bit = position[i]; + let rx = 0; + let ry = 0; + if (bit === '1') { + ry = 1; + } else if (bit === '2') { + rx = 1; + ry = 1; + } else if (bit === '3') { + rx = 1; + } + + const val = Math.pow(2, level - 1); + rotateAndFlipQuadrant(val, point, rx, ry); + + point[0] += val * rx; + point[1] += val * ry; + } + + if (face % 2 === 1) { + const t = point[0]; + point[0] = point[1]; + point[1] = t; + } + + return {face, ij: point, level}; +} diff --git a/modules/s2/src/s2-to-obb-points.ts b/modules/s2/src/s2-to-obb-points.ts new file mode 100644 index 00000000..98af196d --- /dev/null +++ b/modules/s2/src/s2-to-obb-points.ts @@ -0,0 +1,72 @@ +import {getS2CellFromToken, get2dRegionFromS2Cell} from './s2-utils-ext'; +import {Vector3} from '@math.gl/core'; + +// import {OrientedBoundingBox, makeOrientedBoundingBoxFromPoints} from '@math.gl/culling'; +// import {Ellipsoid} from '@math.gl/geospatial'; + +export type S2HeightInfo = { + minimumHeight: number; + maximumHeight: number; +}; + +/** + * Converts S2HeightInfo to corner points of an oriented bounding box + * Can be used to constuct an OrientedBoundingBox instance + * + * @param s2bv - s2 bounding volume to convert + * @param [result] Optional object onto which to store the result. + * @returns The modified result parameter or a new `OrientedBoundingBox` instance if not provided. + */ +export function getOrientedBoundingBoxCornerPoints( + token: string, // This can be an S2 key or token + heighInfo?: S2HeightInfo +): Vector3[] { + const min: number = heighInfo?.minimumHeight || 0; + const max: number = heighInfo?.maximumHeight || 0; + + const s2cell = getS2CellFromToken(token); + const region = get2dRegionFromS2Cell(s2cell); + + // region is {lngWest, latSouth, lngEast, latNorth} in degrees + const W = region[0]; + const S = region[1]; + const E = region[2]; + const N = region[3]; + + const points: Vector3[] = []; + + points.push(new Vector3(W, N, min)); + points.push(new Vector3(E, N, min)); + points.push(new Vector3(E, S, min)); + points.push(new Vector3(W, S, min)); + + points.push(new Vector3(W, N, max)); + points.push(new Vector3(E, N, max)); + points.push(new Vector3(E, S, max)); + points.push(new Vector3(W, S, max)); + + return points; +} + +/* +function convertCartToXYZ(longitude, latitude, height, result?) { + const point = Ellipsoid.WGS84.cartographicToCartesian([longitude, latitude, height]); + return new Vector3(point[0], point[1], point[2]); +} + +// Add a point that doesn't allow the box dive under the Earth + // This point is actually a center of a face that could be a tangent to the Earth surface if max==0 + points.push(convertCartToXYZ((W + E) / 2.0, (S + N) / 2.0, max)); + + // points should be an array of Vector3 (XYZ) + // Passing result===null throws an exception from makeOrientedBoundingBoxFromPoints + const obb: OrientedBoundingBox = makeOrientedBoundingBoxFromPoints( + points, + result !== null ? result : undefined + ); + + const box: number[] = [...obb.center, ...obb.halfAxes]; + + return box; +} +*/ diff --git a/modules/s2/src/s2-utils-ext.ts b/modules/s2/src/s2-utils-ext.ts new file mode 100644 index 00000000..dffb831d --- /dev/null +++ b/modules/s2/src/s2-utils-ext.ts @@ -0,0 +1,78 @@ +import {FromHilbertQuadKey} from './s2-geometry'; +import {getS2QuadKey, getGeoBounds} from './s2-utils'; + +import Long from 'long'; + +function countTrailingZero(x: Long) { + const count = x.countTrailingZeros(); + return count; +} + +export function getTokenFromId(cellId: Long): string { + if (cellId.isZero()) return 'X'; + let numZeroDigits = countTrailingZero(cellId); + + const remainder = numZeroDigits % 4; + numZeroDigits = (numZeroDigits - remainder) / 4; + const trailingZeroHexChars = numZeroDigits; + numZeroDigits *= 4; + + const x = cellId.shiftRightUnsigned(numZeroDigits); + const hexString = x.toString(16).replace(/0+$/, ''); + const zeroString = Array(17 - trailingZeroHexChars - hexString.length).join('0'); + return zeroString + hexString; +} + +/** + * Return the lowest-numbered bit that is on for this cell id + * @private + */ +function lsb(cellId: Long): Long { + return cellId.and(cellId.not().add(1)); // eslint-disable-line +} + +export function getS2ChildCellId(cellId: Long, index: number): Long { + // Shift sentinel bit 2 positions to the right. + const newLsb = lsb(cellId).shiftRightUnsigned(2); + // Insert child index before the sentinel bit. + const childCellId: Long = cellId.add(Long.fromNumber(2 * index + 1 - 4).multiply(newLsb)); + return childCellId; +} + +export function getS2CellFromToken(token: string): { + face: number; + ij: [number, number]; + level: number; +} { + const key = getS2QuadKey(token); + const s2cell = FromHilbertQuadKey(key); + return s2cell; +} + +function S2CornersTo2dRegion(corners: Float64Array): number[] { + const longitudes: number[] = []; + const latitudes: number[] = []; + for (let i = 0; i < corners.length; i += 2) { + longitudes.push(corners[i]); + latitudes.push(corners[i + 1]); + } + longitudes.sort((a, b) => a - b); + latitudes.sort((a, b) => a - b); + // Return the region in degrees + return [ + longitudes[0], + latitudes[0], + longitudes[longitudes.length - 1], + latitudes[latitudes.length - 1] + ]; +} + +export function get2dRegionFromS2Cell(s2cell: { + face: number; + ij: [number, number]; + level: number; +}): number[] { + const corns = getGeoBounds(s2cell); + const region = S2CornersTo2dRegion(corns); + return region; +} diff --git a/modules/s2/src/s2-utils.ts b/modules/s2/src/s2-utils.ts new file mode 100644 index 00000000..fd1dd11f --- /dev/null +++ b/modules/s2/src/s2-utils.ts @@ -0,0 +1,157 @@ +// s2-geometry is a pure JavaScript port of Google/Niantic's S2 Geometry library +// which is perfect since it works in the browser. +import { + toHilbertQuadkey, + FromHilbertQuadKey, + IJToST, + STToUV, + FaceUVToXYZ, + XYZToLngLat +} from './s2-geometry'; +import Long from 'long'; + +/** + * Given an S2 token this function convert the token to 64 bit id + https://github.com/google/s2-geometry-library-java/blob/c04b68bf3197a9c34082327eeb3aec7ab7c85da1/src/com/google/common/geometry/S2CellId.java#L439 + * */ + +/* +Here is the version of getIdFromToken taken from deck.gl +We replace it with the function that returns Long instead of number + +function getIdFromToken(token: string): number { + // pad token with zeros to make the length 16 + const paddedToken = token.padEnd(16, '0'); + return Long.fromString(paddedToken, 16); +} +*/ +export function getIdFromToken(token: string): Long { + if (token === 'X') token = ''; + // pad token with zeros to make the length 16 + const paddedToken = token.padEnd(16, '0'); + + return Long.fromString(paddedToken, true, 16); +} + +const MAX_RESOLUTION = 100; + +/* Adapted from s2-geometry's S2Cell.getCornerLatLngs */ +/* eslint-disable max-statements */ + +/* + getGeoBounds is not exported in deck.gl. + We use it outside of this file. So, export it! +*/ +export function getGeoBounds({ + face, + ij, + level +}: { + face: number; + ij: [number, number]; + level: number; +}): Float64Array { + const offsets = [ + [0, 0], + [0, 1], + [1, 1], + [1, 0], + [0, 0] + ]; + + // The S2 cell edge is curved: http://s2geometry.io/ + // This is more prominent at lower levels + // resolution is the number of segments to generate per edge. + // We exponentially reduce resolution as level increases so it doesn't affect perf + // when there are a large number of cells + const resolution = Math.max(1, Math.ceil(MAX_RESOLUTION * Math.pow(2, -level))); + const result = new Float64Array(4 * resolution * 2 + 2); + let ptIndex = 0; + let prevLng = 0; + + for (let i = 0; i < 4; i++) { + const offset = offsets[i].slice(0) as [number, number]; + const nextOffset = offsets[i + 1]; + const stepI = (nextOffset[0] - offset[0]) / resolution; + const stepJ = (nextOffset[1] - offset[1]) / resolution; + + for (let j = 0; j < resolution; j++) { + offset[0] += stepI; + offset[1] += stepJ; + // Cell can be represented by coordinates IJ, ST, UV, XYZ + // http://s2geometry.io/devguide/s2cell_hierarchy#coordinate-systems + const st = IJToST(ij, level, offset); + const uv = STToUV(st); + const xyz = FaceUVToXYZ(face, uv); + const lngLat = XYZToLngLat(xyz); + + // Adjust longitude for Web Mercator projection + if (Math.abs(lngLat[1]) > 89.999) { + lngLat[0] = prevLng; + } + const deltaLng = lngLat[0] - prevLng; + lngLat[0] += deltaLng > 180 ? -360 : deltaLng < -180 ? 360 : 0; + + result[ptIndex++] = lngLat[0]; + result[ptIndex++] = lngLat[1]; + prevLng = lngLat[0]; + } + } + // close the loop + result[ptIndex++] = result[0]; + result[ptIndex++] = result[1]; + return result; +} +/* eslint-enable max-statements */ + +/* +Original function from deck.gl takes a token as a string or a number, which is wrong. +The token cannot be a number. It must be be a string. Otherwise leading zeros will be lost. + +export function getS2QuadKey(token: string | number): string { + if (typeof token === 'string') { + if (token.indexOf('/') > 0) { + // is Hilbert quad key + return token; + } + // is S2 token + token = getIdFromToken(token); + } + // is Long id + return toHilbertQuadkey(token.toString()); +} +*/ +export function getS2QuadKey(token: string): string { + if (token.indexOf('/') > 0) { + // is Hilbert quad key + return token; + } + // is S2 token + const id: Long = getIdFromToken(token); + return toHilbertQuadkey(id); +} + +/** + * Get a polygon with corner coordinates for an s2 cell + * @param {*} cell - This can be an S2 key or token + * @return {Float64Array} - a simple polygon in flat array format: [lng0, lat0, lng1, lat1, ...] + * - the polygon is closed, i.e. last coordinate is a copy of the first coordinate + */ +/* +Original function from deck.gl takes a token as a string or a number, which is wrong. +The token cannot be a number. It must be be a string. Otherwise leading zeros will be lost. + +export function getS2Polygon(token: string | number): Float64Array { + const key = getS2QuadKey(token); + const s2cell = FromHilbertQuadKey(key); + + return getGeoBounds(s2cell); +} +*/ + +export function getS2Polygon(token: string): Float64Array { + const key = getS2QuadKey(token); + const s2cell = FromHilbertQuadKey(key); + + return getGeoBounds(s2cell); +} diff --git a/modules/s2/test/data/sfcells-sf.json b/modules/s2/test/data/sfcells-sf.json new file mode 100644 index 00000000..5df5ab8f --- /dev/null +++ b/modules/s2/test/data/sfcells-sf.json @@ -0,0 +1,523 @@ +[{ + "token": "80858004", + "value": 0.5979242952642347 +}, { + "token": "8085800c", + "value": 0.5446256069712141 +}, { + "token": "80858014", + "value": 0.1187171597109975 +}, { + "token": "8085801c", + "value": 0.2859146314037557 +}, { + "token": "80858024", + "value": 0.19549012367504126 +}, { + "token": "80858034", + "value": 0.3373452974230604 +}, { + "token": "8085803c", + "value": 0.9218176408795662 +}, { + "token": "80858044", + "value": 0.23470692356446143 +}, { + "token": "8085804c", + "value": 0.1580509670379684 +}, { + "token": "80858054", + "value": 0.15992745628743954 +}, { + "token": "8085805c", + "value": 0.08396995862593659 +}, { + "token": "80858064", + "value": 0.8528624994099137 +}, { + "token": "8085806c", + "value": 0.644205644051216 +}, { + "token": "80858074", + "value": 0.7327824575390218 +}, { + "token": "8085807c", + "value": 0.03206116368501655 +}, { + "token": "80858084", + "value": 0.13521469550102694 +}, { + "token": "8085808c", + "value": 0.8535530864046055 +}, { + "token": "80858094", + "value": 0.3021071656292911 +}, { + "token": "8085809c", + "value": 0.3145135386133331 +}, { + "token": "808580a4", + "value": 0.22221972654594113 +}, { + "token": "808580ac", + "value": 0.2089824755550702 +}, { + "token": "808580b4", + "value": 0.21568217472680673 +}, { + "token": "808580bc", + "value": 0.9930882437101516 +}, { + "token": "808580c4", + "value": 0.6771468010341937 +}, { + "token": "808580cc", + "value": 0.06254546149649509 +}, { + "token": "808580d4", + "value": 0.0898475989412637 +}, { + "token": "808580dc", + "value": 0.49162678093756096 +}, { + "token": "808580e4", + "value": 0.051892796689529286 +}, { + "token": "808580ec", + "value": 0.7656423773539729 +}, { + "token": "808580f4", + "value": 0.4176961681646778 +}, { + "token": "808580fc", + "value": 0.4764575762690464 +}, { + "token": "80858104", + "value": 0.875560663474253 +}, { + "token": "8085811c", + "value": 0.3209959013941124 +}, { + "token": "80858124", + "value": 0.9676094014498655 +}, { + "token": "8085812c", + "value": 0.8003506574355166 +}, { + "token": "80858134", + "value": 0.034891461780171884 +}, { + "token": "80858644", + "value": 0.8488347081373842 +}, { + "token": "8085864c", + "value": 0.5411597765580489 +}, { + "token": "80858654", + "value": 0.3020505133285931 +}, { + "token": "8085865c", + "value": 0.44053851810796885 +}, { + "token": "80858664", + "value": 0.018102931578807713 +}, { + "token": "8085866c", + "value": 0.4708610883744251 +}, { + "token": "80858674", + "value": 0.8445041920035186 +}, { + "token": "8085867c", + "value": 0.7392562454515113 +}, { + "token": "8085868c", + "value": 0.39347130067527725 +}, { + "token": "80858694", + "value": 0.44498309263850944 +}, { + "token": "808586bc", + "value": 0.7950865956130442 +}, { + "token": "808586c4", + "value": 0.7385232599770808 +}, { + "token": "808586cc", + "value": 0.018430696365115518 +}, { + "token": "808586d4", + "value": 0.6976876914703944 +}, { + "token": "808586dc", + "value": 0.25548321522154827 +}, { + "token": "808586e4", + "value": 0.41907812568703373 +}, { + "token": "808586ec", + "value": 0.7290899222794696 +}, { + "token": "808586f4", + "value": 0.4876522132550285 +}, { + "token": "808586fc", + "value": 0.9791814942123487 +}, { + "token": "80858704", + "value": 0.1564051237695645 +}, { + "token": "8085870c", + "value": 0.744495038306515 +}, { + "token": "80858714", + "value": 0.5636255749919985 +}, { + "token": "8085871c", + "value": 0.7177669940621756 +}, { + "token": "80858724", + "value": 0.935541364441353 +}, { + "token": "8085872c", + "value": 0.23813259699989464 +}, { + "token": "80858734", + "value": 0.20646398267504473 +}, { + "token": "8085873c", + "value": 0.2302231506207013 +}, { + "token": "80858744", + "value": 0.8146528937322526 +}, { + "token": "8085874c", + "value": 0.16250640847801878 +}, { + "token": "80858754", + "value": 0.8559251431793231 +}, { + "token": "8085875c", + "value": 0.5518084918736605 +}, { + "token": "80858764", + "value": 0.3724154636273309 +}, { + "token": "8085876c", + "value": 0.012832647697721411 +}, { + "token": "80858774", + "value": 0.5610069108638975 +}, { + "token": "8085877c", + "value": 0.4776581643572013 +}, { + "token": "80858784", + "value": 0.12728544885717574 +}, { + "token": "8085878c", + "value": 0.47893591531516466 +}, { + "token": "80858794", + "value": 0.3063337875935812 +}, { + "token": "8085879c", + "value": 0.9073800330927748 +}, { + "token": "808587a4", + "value": 0.5379301824132303 +}, { + "token": "808587ac", + "value": 0.011113123736386621 +}, { + "token": "808587b4", + "value": 0.33081342331714514 +}, { + "token": "808587bc", + "value": 0.16191641631003306 +}, { + "token": "808f78ac", + "value": 0.5216683954302226 +}, { + "token": "808f78b4", + "value": 0.5285279357501274 +}, { + "token": "808f7c24", + "value": 0.24964281774378816 +}, { + "token": "808f7c2c", + "value": 0.5328015885099198 +}, { + "token": "808f7c34", + "value": 0.5819767316967777 +}, { + "token": "808f7c3c", + "value": 0.5896441351697632 +}, { + "token": "808f7c44", + "value": 0.5765363622666126 +}, { + "token": "808f7c4c", + "value": 0.8149459687907068 +}, { + "token": "808f7c54", + "value": 0.12107787886389243 +}, { + "token": "808f7cfc", + "value": 0.8526502486482175 +}, { + "token": "808f7d04", + "value": 0.28623779830815255 +}, { + "token": "808f7d0c", + "value": 0.10419603053055027 +}, { + "token": "808f7d14", + "value": 0.2520231652562299 +}, { + "token": "808f7d1c", + "value": 0.8877852826515231 +}, { + "token": "808f7d64", + "value": 0.2516990408971258 +}, { + "token": "808f7d6c", + "value": 0.7886336898433268 +}, { + "token": "808f7d74", + "value": 0.3308357482421824 +}, { + "token": "808f7d7c", + "value": 0.9954698798360961 +}, { + "token": "808f7d84", + "value": 0.28199844123382434 +}, { + "token": "808f7d8c", + "value": 0.32430099417470504 +}, { + "token": "808f7d94", + "value": 0.5984402085884064 +}, { + "token": "808f7d9c", + "value": 0.6793472057782628 +}, { + "token": "808f7da4", + "value": 0.033929426787699724 +}, { + "token": "808f7dac", + "value": 0.7678834799175067 +}, { + "token": "808f7db4", + "value": 0.9941391037002041 +}, { + "token": "808f7dbc", + "value": 0.36675213183092303 +}, { + "token": "808f7dc4", + "value": 0.40066088856840576 +}, { + "token": "808f7dcc", + "value": 0.7263378406177063 +}, { + "token": "808f7dd4", + "value": 0.04477271874976996 +}, { + "token": "808f7ddc", + "value": 0.7104685877059944 +}, { + "token": "808f7de4", + "value": 0.13419724684085477 +}, { + "token": "808f7dec", + "value": 0.7547222857615965 +}, { + "token": "808f7df4", + "value": 0.9280683006322386 +}, { + "token": "808f7dfc", + "value": 0.8220141360591591 +}, { + "token": "808f7e04", + "value": 0.9963272967038985 +}, { + "token": "808f7e0c", + "value": 0.1555577515936848 +}, { + "token": "808f7e14", + "value": 0.5631111145510213 +}, { + "token": "808f7e1c", + "value": 0.48498738652813933 +}, { + "token": "808f7e24", + "value": 0.6390846622343107 +}, { + "token": "808f7e2c", + "value": 0.7713411346164771 +}, { + "token": "808f7e34", + "value": 0.30300925574785986 +}, { + "token": "808f7e3c", + "value": 0.558699849050589 +}, { + "token": "808f7e44", + "value": 0.09988990383867447 +}, { + "token": "808f7e4c", + "value": 0.3069067328730657 +}, { + "token": "808f7e54", + "value": 0.43128853083719343 +}, { + "token": "808f7e5c", + "value": 0.5928264763933375 +}, { + "token": "808f7e64", + "value": 0.16117572767428334 +}, { + "token": "808f7e6c", + "value": 0.230861193468473 +}, { + "token": "808f7e74", + "value": 0.2536209599928523 +}, { + "token": "808f7e7c", + "value": 0.6134003809540043 +}, { + "token": "808f7e84", + "value": 0.7833849551129455 +}, { + "token": "808f7e8c", + "value": 0.45498849941513386 +}, { + "token": "808f7e94", + "value": 0.08962987759426433 +}, { + "token": "808f7e9c", + "value": 0.005011873959296365 +}, { + "token": "808f7ea4", + "value": 0.5784665723163016 +}, { + "token": "808f7ebc", + "value": 0.5191309233303725 +}, { + "token": "808f7ec4", + "value": 0.39905530113616816 +}, { + "token": "808f7ed4", + "value": 0.13825169595521447 +}, { + "token": "808f7edc", + "value": 0.8204175340623787 +}, { + "token": "808f7ee4", + "value": 0.622697450596031 +}, { + "token": "808f7eec", + "value": 0.9123428024448095 +}, { + "token": "808f7ef4", + "value": 0.7929627313491234 +}, { + "token": "808f7efc", + "value": 0.14057925336084875 +}, { + "token": "808f7f04", + "value": 0.03307304375084663 +}, { + "token": "808f7f0c", + "value": 0.5610326125073675 +}, { + "token": "808f7f14", + "value": 0.4322570558764176 +}, { + "token": "808f7f1c", + "value": 0.0503145116262389 +}, { + "token": "808f7f24", + "value": 0.16401887959047734 +}, { + "token": "808f7f2c", + "value": 0.4751520317382516 +}, { + "token": "808f7f34", + "value": 0.23500681721624983 +}, { + "token": "808f7f3c", + "value": 0.33015285910199244 +}, { + "token": "808f7f44", + "value": 0.45842014371901474 +}, { + "token": "808f7f4c", + "value": 0.06578565472002951 +}, { + "token": "808f7f54", + "value": 0.6186564073897249 +}, { + "token": "808f7f5c", + "value": 0.6773939262080393 +}, { + "token": "808f7f64", + "value": 0.11266112875578238 +}, { + "token": "808f7f6c", + "value": 0.24580063451598888 +}, { + "token": "808f7f74", + "value": 0.9769378264780044 +}, { + "token": "808f7f7c", + "value": 0.8704465762998475 +}, { + "token": "808f7f84", + "value": 0.3917742365841228 +}, { + "token": "808f7f8c", + "value": 0.9262572914676896 +}, { + "token": "808f7f94", + "value": 0.9053184108632224 +}, { + "token": "808f7f9c", + "value": 0.302183769904139 +}, { + "token": "808f7fa4", + "value": 0.29824837147682115 +}, { + "token": "808f7fac", + "value": 0.6758105057539954 +}, { + "token": "808f7fb4", + "value": 0.15327743161577612 +}, { + "token": "808f7fbc", + "value": 0.9308212467506611 +}, { + "token": "808f7fc4", + "value": 0.7937065369136609 +}, { + "token": "808f7fcc", + "value": 0.6043745575751156 +}, { + "token": "808f7fd4", + "value": 0.7455648234651862 +}, { + "token": "808f7fdc", + "value": 0.7621016332623176 +}, { + "token": "808f7fe4", + "value": 0.079259268233 +}, { + "token": "808f7fec", + "value": 0.42279838014027704 +}, { + "token": "808f7ff4", + "value": 0.9807399010025764 +}, { + "token": "808f7ffc", + "value": 0.3514178008689648 +}] \ No newline at end of file diff --git a/modules/s2/test/index.ts b/modules/s2/test/index.ts new file mode 100644 index 00000000..34ebfcb3 --- /dev/null +++ b/modules/s2/test/index.ts @@ -0,0 +1 @@ +import './s2-utils.spec'; diff --git a/modules/s2/test/s2-utils.spec.ts b/modules/s2/test/s2-utils.spec.ts new file mode 100644 index 00000000..1da84fcb --- /dev/null +++ b/modules/s2/test/s2-utils.spec.ts @@ -0,0 +1,72 @@ +// loaders.gl, MIT license +import test from 'tape-promise/tape'; + +import {getS2Center, getS2QuadKey, getS2Polygon} from '@math.gl/s2'; +// import {s2cells} from './data/sfcells-sf.json'; + +import {S2} from 's2-geometry'; +import Long from 'long'; + +test('Utils -> getS2Center', (t) => { + const s2Token = '8085873c'; + t.deepEqual(getS2Center(s2Token), [-122.4637079795235, 37.78228912269449]); + t.end(); +}); + +test('S2Layer#getS2QuadKey', (t) => { + const TEST_COORDINATES = [ + {lat: 0, lng: 0}, + {lat: -122.45, lng: 37.78}, + {lat: 85, lng: 180} + ]; + + const TEST_LEVELS = [1, 2, 4, 8, 16]; + + for (const point of TEST_COORDINATES) { + for (const level of TEST_LEVELS) { + const key = S2.latLngToKey(point.lat, point.lng, level); + const id = Long.fromString(S2.keyToId(key), true); + const token = id.toString(16).replace(/0+$/, ''); + + t.comment(`level ${level}, id: ${id.toString()}, token: ${token}`); + t.is(getS2QuadKey(key), key, 'Quad key to quad key'); + t.is(getS2QuadKey(id), key, 'Id to quad key'); + t.is(getS2QuadKey(token), key, 'Token to quad key'); + } + } + + t.end(); +}); + +test('S2Layer#getS2Polygon', (t) => { + const TEST_TOKENS = [ + '80858004', // face 4 + '1c', // face 0 + '2c', // face 1 + '5b', // face 2 + '6b', // face 3 + 'ab', // face 5 + '4/001003', + '54', // antimeridian + '5c', // antimeridian + new Long(0, -2138636288, false), + new Long(0, 1832910848, false) + ]; + + for (const token of TEST_TOKENS) { + const polygon = getS2Polygon(token); + t.ok(polygon instanceof Float64Array, 'polygon is flat array'); + t.is((polygon.length / 2 - 1) % 4, 0, 'polygon has 4 sides'); + t.deepEqual(polygon.slice(0, 2), polygon.slice(-2), 'polygon is closed'); + + let minLng = 180; + let maxLng = -180; + for (let i = 0; i < polygon.length; i += 2) { + minLng = Math.min(minLng, polygon[i]); + maxLng = Math.max(maxLng, polygon[i]); + } + t.ok(maxLng - minLng < 180, 'longitude is adjusted cross the antimeridian'); + } + + t.end(); +}); diff --git a/modules/s2/tsconfig.json b/modules/s2/tsconfig.json new file mode 100644 index 00000000..acd8f6b0 --- /dev/null +++ b/modules/s2/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.build.json", + "include": ["src/**/*"], + "exclude": ["node_modules"], + "compilerOptions": { + "composite": true, + "rootDir": "src", + "outDir": "dist" + }, + "references": [ + {"path": "../types"} + ] +} \ No newline at end of file diff --git a/test/modules.spec.ts b/test/modules.spec.ts index ce121bcb..d8a52fce 100644 --- a/test/modules.spec.ts +++ b/test/modules.spec.ts @@ -3,7 +3,8 @@ import '../modules/core/test'; import '../modules/culling/test'; import '../modules/geoid/test'; import '../modules/geospatial/test'; -// import '../modules/polygon/test'; -// import '../modules/proj4/test'; -// import '../modules/sun/test'; -// import '../modules/web-mercator/test'; +import '../modules/polygon/test'; +import '../modules/proj4/test'; +import '../modules/sun/test'; +import '../modules/web-mercator/test'; +// import '../modules/s2/test'; diff --git a/tsconfig.json b/tsconfig.json index c4151041..55aaca18 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -51,6 +51,8 @@ "@math.gl/polygon/test/*": ["modules/polygon/test/*"], "@math.gl/proj4/*": ["modules/proj4/src/*"], "@math.gl/proj4/test/*": ["modules/proj4/test/*"], + "@math.gl/s2/*": ["modules/s2/src/*"], + "@math.gl/s2/test/*": ["modules/s2/test/*"], "@math.gl/sun/*": ["modules/sun/src/*"], "@math.gl/sun/test/*": ["modules/sun/test/*"], "@math.gl/types/*": ["modules/types/src/*"], diff --git a/yarn.lock b/yarn.lock index 5852a956..ef1a76c3 100644 --- a/yarn.lock +++ b/yarn.lock @@ -8039,6 +8039,16 @@ loglevel@^1.6.8: resolved "https://registry.yarnpkg.com/loglevel/-/loglevel-1.7.1.tgz#005fde2f5e6e47068f935ff28573e125ef72f197" integrity sha512-Hesni4s5UkWkwCGJMQGAh71PaLUmKFM60dHvq0zi/vDhhrzuk+4GgNbTXJ12YYQJn6ZKBDNIjYcuQGKudvqrIw== +long@^3.2.0: + version "3.2.0" + resolved "https://registry.yarnpkg.com/long/-/long-3.2.0.tgz#d821b7138ca1cb581c172990ef14db200b5c474b" + integrity sha512-ZYvPPOMqUwPoDsbJaR10iQJYnMuZhRTvHYl62ErLIEX7RgFlziSBUUvrt3OVfc47QlHHpzPZYP17g3Fv7oeJkg== + +long@^5.2.1: + version "5.2.1" + resolved "https://registry.yarnpkg.com/long/-/long-5.2.1.tgz#e27595d0083d103d2fa2c20c7699f8e0c92b897f" + integrity sha512-GKSNGeNAtw8IryjjkhZxuKB3JzlcLTwjtiQCHKvqQet81I93kXslhDQruGI/QsddO83mcDToBVy7GqGS/zYf/A== + loose-envify@^1.0.0, loose-envify@^1.1.0, loose-envify@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.4.0.tgz#71ee51fa7be4caec1a63839f7e682d8132d30caf" @@ -10616,6 +10626,13 @@ rxjs@^6.4.0: dependencies: tslib "^1.9.0" +s2-geometry@^1.2.10: + version "1.2.10" + resolved "https://registry.yarnpkg.com/s2-geometry/-/s2-geometry-1.2.10.tgz#c6ff22f3eccafd0eea491b60b44c141b9887acab" + integrity sha512-5WejfQu1XZ25ZerW8uL6xP1sM2krcOYKhI6TbfybGRf+vTQLrm3E+4n0+1lWg+MYqFjPzoe51zKhn2sBRMCt5g== + dependencies: + long "^3.2.0" + safe-buffer@5.1.2, safe-buffer@~5.1.0, safe-buffer@~5.1.1: version "5.1.2" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d"