@duoquote/polytini 0.0.0-stage → 0.1.0
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.
- package/LICENSE +21 -0
- package/README.md +120 -3
- package/dist/deckgl.cjs +250 -0
- package/dist/flexible.cjs +229 -0
- package/dist/google.cjs +232 -0
- package/dist/leaflet-auto.cjs +209 -0
- package/dist/leaflet.cjs +231 -0
- package/dist/mapbox.cjs +185 -0
- package/dist/maplibre.cjs +185 -0
- package/dist/node.cjs +322 -0
- package/dist/presets.cjs +65 -0
- package/dist/turf.cjs +267 -0
- package/dist/types/cli.d.cts +2 -0
- package/dist/types/deckgl.d.cts +60 -0
- package/dist/types/flexible.d.cts +80 -0
- package/dist/types/google.d.cts +48 -0
- package/dist/types/google.jsr.d.cts +60 -0
- package/dist/types/index.d.cts +87 -0
- package/dist/types/leaflet-auto.d.cts +4 -0
- package/dist/types/leaflet-auto.jsr.d.cts +2 -0
- package/dist/types/leaflet.d.cts +39 -0
- package/dist/types/leaflet.jsr.d.cts +13 -0
- package/dist/types/mapbox.d.cts +50 -0
- package/dist/types/maplibre.d.cts +54 -0
- package/dist/types/openlayers.d.cts +23 -0
- package/dist/types/presets.d.cts +66 -0
- package/dist/types/turf.d.cts +33 -0
- package/dist/types/wasm.d.cts +33 -0
- package/dist/web.cjs +231 -0
- package/package.json +200 -6
- package/src/browser.js +15 -0
- package/src/bun.js +4 -0
- package/src/cli-lib.js +160 -0
- package/src/cli.js +7 -0
- package/src/core.js +268 -0
- package/src/deckgl.js +176 -0
- package/src/deno.js +12 -0
- package/src/error.js +15 -0
- package/src/fast.js +179 -0
- package/src/flexible.js +283 -0
- package/src/google.js +70 -0
- package/src/leaflet-auto.js +11 -0
- package/src/leaflet.js +44 -0
- package/src/mapbox.js +10 -0
- package/src/maplibre.js +57 -0
- package/src/node.js +17 -0
- package/src/openlayers.js +172 -0
- package/src/presets.js +242 -0
- package/src/text.js +111 -0
- package/src/turf.js +80 -0
- package/src/wasm-bytes.js +2 -0
- package/src/wasm.js +235 -0
- package/src/web.js +9 -0
- package/types/cli.d.ts +2 -0
- package/types/deckgl.d.ts +60 -0
- package/types/flexible.d.ts +80 -0
- package/types/google.d.ts +48 -0
- package/types/google.jsr.d.ts +60 -0
- package/types/index.d.ts +87 -0
- package/types/leaflet-auto.d.ts +4 -0
- package/types/leaflet-auto.jsr.d.ts +2 -0
- package/types/leaflet.d.ts +39 -0
- package/types/leaflet.jsr.d.ts +13 -0
- package/types/mapbox.d.ts +50 -0
- package/types/maplibre.d.ts +54 -0
- package/types/openlayers.d.ts +23 -0
- package/types/presets.d.ts +66 -0
- package/types/turf.d.ts +33 -0
- package/types/wasm.d.ts +33 -0
- package/wasm/polytini.wasm +0 -0
package/src/deckgl.js
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
// deck.gl: encoded polylines straight into deck.gl's binary data format, one
|
|
2
|
+
// typed array for all lines and no array per point.
|
|
3
|
+
//
|
|
4
|
+
// import { PathLayer } from '@deck.gl/layers';
|
|
5
|
+
// import { binaryPaths } from '@duoquote/polytini/deckgl';
|
|
6
|
+
// const data = binaryPaths(routes.map((r) => r.geometry), { precision: 6 });
|
|
7
|
+
// new PathLayer({ id: 'routes', data, _pathType: 'open', getWidth: 3 });
|
|
8
|
+
//
|
|
9
|
+
// The result has the shape deck.gl 9 documents for PathLayer, TripsLayer and
|
|
10
|
+
// SolidPolygonLayer:
|
|
11
|
+
// { length, startIndices, attributes: { getPath: { value, size } } }
|
|
12
|
+
// where startIndices has length + 1 entries, the last one the vertex count,
|
|
13
|
+
// and value holds [lng, lat] or [lng, lat, z] per vertex. Positions always
|
|
14
|
+
// come out as [lng, lat], whatever `order` the options or a preset say,
|
|
15
|
+
// because that is what deck.gl reads.
|
|
16
|
+
//
|
|
17
|
+
// Each string is decoded twice over its characters: a first pass over all
|
|
18
|
+
// strings counts the values (every value ends with exactly one character
|
|
19
|
+
// below code 95), so one buffer of the right size is allocated, and a second
|
|
20
|
+
// pass decodes into it. Strings the fast loop does not take (bad characters,
|
|
21
|
+
// a cut-off value, values of more than 30 bits) go through polytini's exact
|
|
22
|
+
// decoder, which throws a PolylineError in strict mode, the default.
|
|
23
|
+
//
|
|
24
|
+
// PolygonLayer, the composite layer, does not take binary data in deck.gl
|
|
25
|
+
// 9.4: it calls getPolygon on every row to build its outlines, and binary
|
|
26
|
+
// data has no rows (it fails with "Cannot read properties of undefined").
|
|
27
|
+
// For filled polygons with outlines, use a SolidPolygonLayer with
|
|
28
|
+
// binaryPolygons data plus a PathLayer with the same buffer as getPath:
|
|
29
|
+
// new PathLayer({ data: { ...polys, attributes: { getPath: polys.attributes.getPolygon } }, _pathType: 'open' })
|
|
30
|
+
//
|
|
31
|
+
// No deck.gl code is imported.
|
|
32
|
+
/* @ts-self-types="../types/deckgl.d.ts" */
|
|
33
|
+
import { decodeFlat } from './web.js';
|
|
34
|
+
import { opts, st, fail } from './core.js';
|
|
35
|
+
|
|
36
|
+
// Decodes a 2D string into out[2k], out[2k + 1] as [lng, lat] from vertex k.
|
|
37
|
+
// Returns the number of vertices, or -1 when the string needs the exact
|
|
38
|
+
// decoder. Writes past the end of a typed array are dropped, and anything
|
|
39
|
+
// written for a bad string is overwritten afterwards.
|
|
40
|
+
function fill2(str, out, k, f) {
|
|
41
|
+
const len = str.length, start = k;
|
|
42
|
+
let i = 0, lat = 0, lng = 0, bad = 0, c, v, s;
|
|
43
|
+
k *= 2;
|
|
44
|
+
while (i < len) {
|
|
45
|
+
c = str.charCodeAt(i++) - 63;
|
|
46
|
+
bad |= c;
|
|
47
|
+
v = c & 31;
|
|
48
|
+
for (s = 5; c >= 32; s += 5) {
|
|
49
|
+
c = str.charCodeAt(i++) - 63;
|
|
50
|
+
bad |= c;
|
|
51
|
+
v |= (c & 31) << s;
|
|
52
|
+
}
|
|
53
|
+
bad |= 30 - s;
|
|
54
|
+
lat += (v >>> 1) ^ -(v & 1);
|
|
55
|
+
c = str.charCodeAt(i++) - 63;
|
|
56
|
+
bad |= c;
|
|
57
|
+
v = c & 31;
|
|
58
|
+
for (s = 5; c >= 32; s += 5) {
|
|
59
|
+
c = str.charCodeAt(i++) - 63;
|
|
60
|
+
bad |= c;
|
|
61
|
+
v |= (c & 31) << s;
|
|
62
|
+
}
|
|
63
|
+
bad |= 30 - s;
|
|
64
|
+
lng += (v >>> 1) ^ -(v & 1);
|
|
65
|
+
out[k++] = lng / f;
|
|
66
|
+
out[k++] = lat / f;
|
|
67
|
+
}
|
|
68
|
+
return bad & ~63 || i != len ? -1 : k / 2 - start;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// The same for d values per point (3 or 4): [lng, lat] plus z when size is
|
|
72
|
+
// 3, and the last value into ts when ts is given.
|
|
73
|
+
function fillN(str, out, ts, k, d, size, f, zf) {
|
|
74
|
+
const len = str.length, start = k, sum = [0, 0, 0, 0];
|
|
75
|
+
let i = 0, bad = 0, a, c, v, s, j;
|
|
76
|
+
while (i < len) {
|
|
77
|
+
for (a = 0; a < d; a++) {
|
|
78
|
+
c = str.charCodeAt(i++) - 63;
|
|
79
|
+
bad |= c;
|
|
80
|
+
v = c & 31;
|
|
81
|
+
for (s = 5; c >= 32; s += 5) {
|
|
82
|
+
c = str.charCodeAt(i++) - 63;
|
|
83
|
+
bad |= c;
|
|
84
|
+
v |= (c & 31) << s;
|
|
85
|
+
}
|
|
86
|
+
bad |= 30 - s;
|
|
87
|
+
sum[a] += (v >>> 1) ^ -(v & 1);
|
|
88
|
+
}
|
|
89
|
+
j = k * size;
|
|
90
|
+
out[j] = sum[1] / f;
|
|
91
|
+
out[j + 1] = sum[0] / f;
|
|
92
|
+
if (size == 3) out[j + 2] = sum[2] / zf;
|
|
93
|
+
if (ts) ts[k] = sum[d - 1] / zf;
|
|
94
|
+
k++;
|
|
95
|
+
}
|
|
96
|
+
return bad & ~63 || i != len ? -1 : k - start;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// The exact decoder, for strings the fast loops gave up on. It returns at
|
|
100
|
+
// most as many points as the first pass counted, so they fit.
|
|
101
|
+
function slow(str, o, out, ts, k, d, size) {
|
|
102
|
+
const flat = decodeFlat(str, o), n = flat.length / d;
|
|
103
|
+
for (let p = 0; p < n; p++, k++) {
|
|
104
|
+
for (let a = 0; a < size; a++) out[k * size + a] = flat[p * d + a];
|
|
105
|
+
if (ts) ts[k] = flat[p * d + d - 1];
|
|
106
|
+
}
|
|
107
|
+
return n;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function build(encoded, o, polygons) {
|
|
111
|
+
const list = typeof encoded == 'string' ? [encoded] : encoded;
|
|
112
|
+
if (!Array.isArray(list)) fail('input', 'Expected a string or an array of strings');
|
|
113
|
+
const f = opts(o), { dims: d, zf } = st, time = !polygons && o != null && typeof o == 'object' && !!o.timestamps;
|
|
114
|
+
const size = time ? d - 1 : d;
|
|
115
|
+
if (size < 2 || size > 3) fail('option', time ? 'timestamps need dimensions 3 or 4' : 'Invalid dimensions for deck.gl: use 2 or 3, or 4 with timestamps');
|
|
116
|
+
const Type = o?.float32 ? Float32Array : Float64Array;
|
|
117
|
+
const n = list.length;
|
|
118
|
+
// Pass 1: an upper bound of the vertex count, exact for valid strings.
|
|
119
|
+
// Polygons get room for one more vertex per ring to close it.
|
|
120
|
+
let max = 0;
|
|
121
|
+
for (let i = 0; i < n; i++) {
|
|
122
|
+
const s = list[i];
|
|
123
|
+
if (typeof s != 'string') fail('input', 'Expected a string', i);
|
|
124
|
+
let values = 0;
|
|
125
|
+
for (let j = 0; j < s.length; j++) values += (s.charCodeAt(j) - 95) >>> 31;
|
|
126
|
+
max += ((values / d) | 0) + (polygons ? 1 : 0);
|
|
127
|
+
}
|
|
128
|
+
const out = new Type(max * size), ts = time ? new Float32Array(max) : null, starts = new Uint32Array(n + 1);
|
|
129
|
+
const exact = { ...(typeof o == 'number' ? { precision: o } : o), order: 'lnglat' };
|
|
130
|
+
// Pass 2: decode each string at the running vertex offset.
|
|
131
|
+
let k = 0;
|
|
132
|
+
for (let i = 0; i < n; i++) {
|
|
133
|
+
const s = list[i];
|
|
134
|
+
starts[i] = k;
|
|
135
|
+
let m = d == 2 ? fill2(s, out, k, f) : fillN(s, out, ts, k, d, size, f, zf);
|
|
136
|
+
if (m < 0) m = slow(s, exact, out, ts, k, d, size);
|
|
137
|
+
if (polygons && m > 0) {
|
|
138
|
+
// Close the ring if the last vertex is not the first.
|
|
139
|
+
const a = k * size, b = (k + m - 1) * size;
|
|
140
|
+
let open = false;
|
|
141
|
+
for (let c = 0; c < size; c++) open ||= out[a + c] !== out[b + c];
|
|
142
|
+
if (open) {
|
|
143
|
+
for (let c = 0; c < size; c++) out[b + size + c] = out[a + c];
|
|
144
|
+
m++;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
k += m;
|
|
148
|
+
}
|
|
149
|
+
starts[n] = k;
|
|
150
|
+
const value = k * size < out.length ? out.subarray(0, k * size) : out;
|
|
151
|
+
const attributes = polygons ? { getPolygon: { value, size } } : { getPath: { value, size } };
|
|
152
|
+
if (ts) attributes.getTimestamps = { value: k < ts.length ? ts.subarray(0, k) : ts, size: 1 };
|
|
153
|
+
return { length: n, startIndices: starts, attributes };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Binary data for PathLayer and TripsLayer: one path per string. Options:
|
|
158
|
+
* polytini options or a preset, plus `float32` (Float32Array instead of
|
|
159
|
+
* Float64Array) and, for TripsLayer, `timestamps`: the last value of each
|
|
160
|
+
* point (dimensions 3 or 4) goes to attributes.getTimestamps instead of the
|
|
161
|
+
* positions. Timestamps are always a Float32Array: TripsLayer's timestamp
|
|
162
|
+
* attribute is 32-bit, and deck.gl 9.4 drew nothing for a TripsLayer given
|
|
163
|
+
* Float64Array timestamps (checked in test/deckgl.test.js). Keep them small,
|
|
164
|
+
* for example seconds since the start of the trip.
|
|
165
|
+
*/
|
|
166
|
+
export const binaryPaths = (encoded, options) => build(encoded, options, false);
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Binary data for SolidPolygonLayer: one ring per string, closed (the first
|
|
170
|
+
* vertex is repeated at the end when it is not there already). The binary
|
|
171
|
+
* format has no holes. With _normalize: false deck.gl uses the rings as
|
|
172
|
+
* they are, so for extruded polygons they must also be in the layer's
|
|
173
|
+
* _windingOrder; leave _normalize on when the winding is unknown.
|
|
174
|
+
* Options: polytini options or a preset, plus float32.
|
|
175
|
+
*/
|
|
176
|
+
export const binaryPolygons = (encoded, options) => build(encoded, options, true);
|
package/src/deno.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// Deno entry: the core plus the TextEncoder/TextDecoder byte paths in
|
|
2
|
+
// text.js. Deno has no global Buffer, and node:buffer measured slower than
|
|
3
|
+
// the portable core there (see the README), so this doesn't use it.
|
|
4
|
+
/* @ts-self-types="../types/index.d.ts" */
|
|
5
|
+
import { decode, encode } from './text.js';
|
|
6
|
+
import { latLngs, toGeo, fromGeo } from './core.js';
|
|
7
|
+
|
|
8
|
+
export { PolylineError } from './core.js';
|
|
9
|
+
export { decode, decodeFlat, encode, encodeFlat } from './text.js';
|
|
10
|
+
export const decodeLatLng = /* @__PURE__ */ latLngs(decode);
|
|
11
|
+
export const toGeoJSON = /* @__PURE__ */ toGeo(decode);
|
|
12
|
+
export const fromGeoJSON = /* @__PURE__ */ fromGeo(encode);
|
package/src/error.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// The error type every entry point and subpath throws. Its own module, so
|
|
2
|
+
// subpaths that only need the error (like /flexible) don't pull in the
|
|
3
|
+
// Google-format code.
|
|
4
|
+
export class PolylineError extends Error {
|
|
5
|
+
constructor(code, message, index) {
|
|
6
|
+
super(index == null ? message : message + ' at ' + index);
|
|
7
|
+
this.name = 'PolylineError';
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.index = index;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export const fail = (code, message, index) => {
|
|
14
|
+
throw new PolylineError(code, message, index);
|
|
15
|
+
};
|
package/src/fast.js
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// Fast paths for runtimes with Node's Buffer: Node and Bun. Each choice here
|
|
2
|
+
// was measured with the benchmark fixtures (see "Platform notes" in the
|
|
3
|
+
// README):
|
|
4
|
+
//
|
|
5
|
+
// - Decode copies the string into a scratch buffer with `ucs2Write` and
|
|
6
|
+
// parses the Uint16Array. On V8, charCodeAt in a hot loop re-checks the
|
|
7
|
+
// string representation on every call, and the copy is close to a memcpy.
|
|
8
|
+
// `latin1Write` is a bit faster but keeps only the low byte, so U+0151
|
|
9
|
+
// would turn into a valid "Q". UTF-16 keeps strict mode exact.
|
|
10
|
+
// - The decoder counts the points first (two characters per step, through
|
|
11
|
+
// a Uint32Array view), so the output array is allocated at its exact size.
|
|
12
|
+
// Growing it with push, or trimming an oversized one, both measured slower.
|
|
13
|
+
// - Encode writes bytes into a scratch buffer and makes the string with one
|
|
14
|
+
// `latin1Slice` call. That was 2 to 4 times faster than building the string
|
|
15
|
+
// with += on both V8 and JavaScriptCore, and the result is a flat string.
|
|
16
|
+
// - The character loops branch on "is there another chunk". A branchless
|
|
17
|
+
// version was faster on the real-world lines, where 1 and 2 character
|
|
18
|
+
// values alternate at random, but slower on the GPS tracks, where they come
|
|
19
|
+
// in runs the branch predictor learns. Branchy won 5 of the 6 columns.
|
|
20
|
+
// - Strings under 64 characters skip the copy and use the core's loop.
|
|
21
|
+
import { opts, st, LIMIT, slowDecode, slowEncode, decodeLoop, flip } from './core.js';
|
|
22
|
+
|
|
23
|
+
// Scratch memory is reused between calls up to this size. Bigger inputs get
|
|
24
|
+
// a temporary buffer, so one huge line doesn't pin megabytes for good.
|
|
25
|
+
const KEEP = 1 << 20;
|
|
26
|
+
|
|
27
|
+
// `grow`: above this many points, build the result by appending instead of
|
|
28
|
+
// allocating it at its final size. See node.js for why.
|
|
29
|
+
export function fast(Buffer, grow = Infinity) {
|
|
30
|
+
const ucs2Write = Buffer.prototype.ucs2Write, latin1Slice = Buffer.prototype.latin1Slice;
|
|
31
|
+
// The kept scratch buffer and its views. allocUnsafeSlow gives each buffer
|
|
32
|
+
// its own ArrayBuffer at offset 0, so the wider views are aligned.
|
|
33
|
+
let kept, k16, k32, u16;
|
|
34
|
+
const views = (buf) => [buf, new Uint16Array(buf.buffer, 0, buf.length >> 1), new Uint32Array(buf.buffer, 0, buf.length >> 2)];
|
|
35
|
+
[kept, k16, k32] = views(Buffer.allocUnsafeSlow(1 << 14));
|
|
36
|
+
const scratch = (bytes) => (bytes <= kept.length ? kept : bytes <= KEEP ? ([kept, k16, k32] = views(Buffer.allocUnsafeSlow(bytes)))[0] : Buffer.allocUnsafeSlow(bytes));
|
|
37
|
+
|
|
38
|
+
// Copies str into scratch as UTF-16, points u16 at it, and returns the
|
|
39
|
+
// number of values.
|
|
40
|
+
function load(str, len) {
|
|
41
|
+
const buf = scratch((len + 4) * 2 + 8);
|
|
42
|
+
ucs2Write.call(buf, str, 0);
|
|
43
|
+
let u32 = k32;
|
|
44
|
+
if (buf == kept) u16 = k16;
|
|
45
|
+
else [, u16, u32] = views(buf);
|
|
46
|
+
// Padding: '?' is a complete zero value, so a truncated string stops
|
|
47
|
+
// inside the buffer and leaves the index past len.
|
|
48
|
+
u16[len] = u16[len + 1] = u16[len + 2] = 63;
|
|
49
|
+
// Every value ends with one character below code 95. Count the others,
|
|
50
|
+
// which have bit 5 set after adding 1, two characters per word.
|
|
51
|
+
let more = 0;
|
|
52
|
+
for (let k = 0, w = (len + 1) >> 1; k < w; k++) {
|
|
53
|
+
const y = ((u32[k] + 0x10001) >>> 5) & 0x10001;
|
|
54
|
+
more += (y & 0xffff) + (y >>> 16);
|
|
55
|
+
}
|
|
56
|
+
return len - more;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// decodeLoop over the UTF-16 copy, with an exactly sized output. Returns
|
|
60
|
+
// null for slowDecode. Tuples and flat output are separate loops here: one
|
|
61
|
+
// shared loop with a per-point branch measured about 20% slower on
|
|
62
|
+
// JavaScriptCore at 10,000 points.
|
|
63
|
+
function big(str, f) {
|
|
64
|
+
const len = str.length, want = load(str, len) >> 1, b = u16, out = want > grow ? [] : Array(want);
|
|
65
|
+
let i = 0, n = 0, lat = 0, lng = 0, bad = 0, c, v, s;
|
|
66
|
+
while (i < len) {
|
|
67
|
+
c = b[i++] - 63;
|
|
68
|
+
bad |= c;
|
|
69
|
+
v = c & 31;
|
|
70
|
+
for (s = 5; c >= 32; s += 5) {
|
|
71
|
+
c = b[i++] - 63;
|
|
72
|
+
bad |= c | (25 - s);
|
|
73
|
+
v |= (c & 31) << s;
|
|
74
|
+
}
|
|
75
|
+
lat += (v >>> 1) ^ -(v & 1);
|
|
76
|
+
c = b[i++] - 63;
|
|
77
|
+
bad |= c;
|
|
78
|
+
v = c & 31;
|
|
79
|
+
for (s = 5; c >= 32; s += 5) {
|
|
80
|
+
c = b[i++] - 63;
|
|
81
|
+
bad |= c | (25 - s);
|
|
82
|
+
v |= (c & 31) << s;
|
|
83
|
+
}
|
|
84
|
+
lng += (v >>> 1) ^ -(v & 1);
|
|
85
|
+
out[n++] = [lat / f, lng / f];
|
|
86
|
+
}
|
|
87
|
+
// The count is exact for valid input, and invalid input stops here.
|
|
88
|
+
return bad & ~63 || i != len ? null : out;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function bigFlat(str, f, sw) {
|
|
92
|
+
const len = str.length, out = new Float64Array(load(str, len) & ~1), b = u16, a = +sw;
|
|
93
|
+
let i = 0, n = 0, lat = 0, lng = 0, bad = 0, c, v, s;
|
|
94
|
+
while (i < len) {
|
|
95
|
+
c = b[i++] - 63;
|
|
96
|
+
bad |= c;
|
|
97
|
+
v = c & 31;
|
|
98
|
+
for (s = 5; c >= 32; s += 5) {
|
|
99
|
+
c = b[i++] - 63;
|
|
100
|
+
bad |= c | (25 - s);
|
|
101
|
+
v |= (c & 31) << s;
|
|
102
|
+
}
|
|
103
|
+
lat += (v >>> 1) ^ -(v & 1);
|
|
104
|
+
c = b[i++] - 63;
|
|
105
|
+
bad |= c;
|
|
106
|
+
v = c & 31;
|
|
107
|
+
for (s = 5; c >= 32; s += 5) {
|
|
108
|
+
c = b[i++] - 63;
|
|
109
|
+
bad |= c | (25 - s);
|
|
110
|
+
v |= (c & 31) << s;
|
|
111
|
+
}
|
|
112
|
+
lng += (v >>> 1) ^ -(v & 1);
|
|
113
|
+
out[n + a] = lat / f;
|
|
114
|
+
out[n + 1 - a] = lng / f;
|
|
115
|
+
n += 2;
|
|
116
|
+
}
|
|
117
|
+
return bad & ~63 || i != len ? null : out;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const decodeWith = (str, o, flat) => {
|
|
121
|
+
const f = opts(o);
|
|
122
|
+
if (st.dims != 2 || typeof str != 'string') return slowDecode(str, f, flat);
|
|
123
|
+
const out = str.length < 64 ? decodeLoop(str, f, st.swap, flat) : flat ? bigFlat(str, f, st.swap) : big(str, f);
|
|
124
|
+
return out ? (st.swap && !flat ? flip(out) : out) : slowDecode(str, f, flat);
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
// Writes bytes into scratch, 7 per value at most below LIMIT. Returns null
|
|
128
|
+
// for slowEncode.
|
|
129
|
+
function encodeLoop(src, f, a, flat) {
|
|
130
|
+
const n = flat ? src.length >> 1 : src.length, buf = scratch(n * 14 + 8);
|
|
131
|
+
let i = 0, k = 0, la = 0, lb = 0, x, y, p, q, z, pt;
|
|
132
|
+
try {
|
|
133
|
+
for (; i < n; i++) {
|
|
134
|
+
if (flat) {
|
|
135
|
+
x = src[i * 2 + a];
|
|
136
|
+
y = src[i * 2 + 1 - a];
|
|
137
|
+
} else {
|
|
138
|
+
pt = src[i];
|
|
139
|
+
x = pt[a];
|
|
140
|
+
y = pt[1 - a];
|
|
141
|
+
}
|
|
142
|
+
if (typeof x != 'number' || typeof y != 'number' || !((x *= f) < LIMIT && x > -LIMIT && (y *= f) < LIMIT && y > -LIMIT)) return null;
|
|
143
|
+
// Round half away from zero. floor(|x| + 0.5) is exact here except for
|
|
144
|
+
// |x| = 0.49999999999999994, where the addition rounds up to 1, so any
|
|
145
|
+
// |x| < 0.5 is set to 0 afterwards. Math.round would be exact on its own,
|
|
146
|
+
// but it measured 40% slower on JavaScriptCore.
|
|
147
|
+
p = x < 0 ? -((0.5 - x) | 0) : (x + 0.5) | 0;
|
|
148
|
+
q = y < 0 ? -((0.5 - y) | 0) : (y + 0.5) | 0;
|
|
149
|
+
if (x < 0.5 && x > -0.5) p = 0;
|
|
150
|
+
if (y < 0.5 && y > -0.5) q = 0;
|
|
151
|
+
z = p - la;
|
|
152
|
+
z = (z << 1) ^ (z >> 31);
|
|
153
|
+
for (; z >= 32; z >>>= 5) buf[k++] = (z & 31) + 95;
|
|
154
|
+
buf[k++] = z + 63;
|
|
155
|
+
z = q - lb;
|
|
156
|
+
z = (z << 1) ^ (z >> 31);
|
|
157
|
+
for (; z >= 32; z >>>= 5) buf[k++] = (z & 31) + 95;
|
|
158
|
+
buf[k++] = z + 63;
|
|
159
|
+
la = p;
|
|
160
|
+
lb = q;
|
|
161
|
+
}
|
|
162
|
+
} catch {
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
return latin1Slice.call(buf, 0, k);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const encodeWith = (src, o, flat) => {
|
|
169
|
+
const f = opts(o);
|
|
170
|
+
return (st.dims == 2 && f <= 1e6 && (flat ? src != null && !(src.length % 2) : Array.isArray(src)) ? encodeLoop(src, f, +st.swap, flat) : null) ?? slowEncode(src, f, flat);
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
return {
|
|
174
|
+
decode: (str, o) => decodeWith(str, o, 0),
|
|
175
|
+
decodeFlat: (str, o) => decodeWith(str, o, 1),
|
|
176
|
+
encode: (src, o) => encodeWith(src, o, 0),
|
|
177
|
+
encodeFlat: (src, o) => encodeWith(src, o, 1),
|
|
178
|
+
};
|
|
179
|
+
}
|
package/src/flexible.js
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
// HERE's Flexible Polyline format, version 1:
|
|
2
|
+
// https://github.com/heremaps/flexible-polyline
|
|
3
|
+
//
|
|
4
|
+
// A string is [version][header][data], each part made of varints written
|
|
5
|
+
// with a URL-safe 64 character alphabet: 5 data bits per character, and a
|
|
6
|
+
// sixth bit that says another character follows. The header holds the
|
|
7
|
+
// precision (bits 0 to 3), the third dimension type (bits 4 to 6) and its
|
|
8
|
+
// precision (bits 7 to 10). The data is zigzag encoded deltas, 2 or 3 values
|
|
9
|
+
// per point, the first point relative to 0.
|
|
10
|
+
//
|
|
11
|
+
// Like the Google-format core, decode and encode have a fast loop for the
|
|
12
|
+
// common case and an exact `slow*` function for the rest, which also reports
|
|
13
|
+
// every kind of bad input. Precision 15 needs up to 64 bits, more than a
|
|
14
|
+
// Number holds exactly, so the slow functions switch to BigInt where Number
|
|
15
|
+
// math would lose bits.
|
|
16
|
+
//
|
|
17
|
+
// Errors are PolylineError with one of these codes:
|
|
18
|
+
// 'input' decode got a non-string, or encode got no array of points
|
|
19
|
+
// 'option' precision or thirdDimPrecision not an integer from 0 to 15,
|
|
20
|
+
// or thirdDim not 0, 1, 2, 3, 6 or 7
|
|
21
|
+
// 'char' a character outside the alphabet (index = its position)
|
|
22
|
+
// 'truncated' the string ends inside the header, a value or a point
|
|
23
|
+
// 'version' the format version is not 1, or the header has bits set
|
|
24
|
+
// above bit 10, which version 1 doesn't define
|
|
25
|
+
// 'overflow' a value needs more than 64 bits, the limit of the other
|
|
26
|
+
// implementations
|
|
27
|
+
// 'coordinate' encode got a missing or non-finite value (index = point)
|
|
28
|
+
/* @ts-self-types="../types/flexible.d.ts" */
|
|
29
|
+
import { PolylineError, fail } from './error.js';
|
|
30
|
+
|
|
31
|
+
export { PolylineError };
|
|
32
|
+
|
|
33
|
+
// Third dimension types, as stored in the header. 4 and 5 are reserved:
|
|
34
|
+
// decode accepts them and encode refuses them, like the official code.
|
|
35
|
+
export const ABSENT = 0;
|
|
36
|
+
export const LEVEL = 1;
|
|
37
|
+
export const ALTITUDE = 2;
|
|
38
|
+
export const ELEVATION = 3;
|
|
39
|
+
export const RESERVED1 = 4;
|
|
40
|
+
export const RESERVED2 = 5;
|
|
41
|
+
export const CUSTOM1 = 6;
|
|
42
|
+
export const CUSTOM2 = 7;
|
|
43
|
+
const TYPES = [0, 1, 2, 3, 6, 7];
|
|
44
|
+
|
|
45
|
+
const E = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
|
|
46
|
+
|
|
47
|
+
// Character code to 6-bit value. 64 marks a character outside the alphabet,
|
|
48
|
+
// so OR-ing every value together and testing for > 63 finds them all.
|
|
49
|
+
const T = new Uint8Array(128).fill(64);
|
|
50
|
+
for (let i = 0; i < 64; i++) T[E.charCodeAt(i)] = i;
|
|
51
|
+
|
|
52
|
+
// The characters of every value below 1024, so one or two characters cost
|
|
53
|
+
// one concatenation instead of a loop.
|
|
54
|
+
const C = [];
|
|
55
|
+
for (let z = 0; z < 1024; z++) C[z] = z < 32 ? E[z] : E[(z & 31) | 32] + E[z >> 5];
|
|
56
|
+
|
|
57
|
+
// 10 ** p from parsed literals, so every factor is exact.
|
|
58
|
+
const P = [];
|
|
59
|
+
for (let p = 0; p < 16; p++) P[p] = +('1e' + p);
|
|
60
|
+
|
|
61
|
+
// The characters of an unsigned value below 2^53. Float math, because the
|
|
62
|
+
// bit operators would cut it to 32 bits.
|
|
63
|
+
const chars = (z) => {
|
|
64
|
+
let s = '';
|
|
65
|
+
for (; z > 31; z = Math.floor(z / 32)) s += E[(z % 32) | 32];
|
|
66
|
+
return s + E[z];
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const range = (p, name) => (typeof p == 'number' && p >= 0 && p <= 15 && p % 1 == 0 ? p : fail('option', name + ' must be an integer from 0 to 15'));
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Reads the version and the header. Returns the header bits plus 2048 times
|
|
73
|
+
* the index where the data starts, so decode allocates nothing for it.
|
|
74
|
+
*/
|
|
75
|
+
function head(str) {
|
|
76
|
+
if (typeof str != 'string') fail('input', 'Expected a string');
|
|
77
|
+
let i = 0, k = 0, v, m, c;
|
|
78
|
+
for (; k < 2; k++) {
|
|
79
|
+
// Both are varints. The version is always 'B' in practice, and the
|
|
80
|
+
// header takes 1 to 3 characters.
|
|
81
|
+
for (v = 0, m = 1, c = 32; c & 32; m *= 32, i++) {
|
|
82
|
+
if (i >= str.length) fail('truncated', 'Polyline ends inside the header', i);
|
|
83
|
+
c = T[str.charCodeAt(i)];
|
|
84
|
+
if (!(c < 64)) fail('char', 'Invalid character ' + JSON.stringify(str[i]), i);
|
|
85
|
+
v += (c & 31) * m;
|
|
86
|
+
}
|
|
87
|
+
if (!k && v != 1) fail('version', 'Unsupported format version ' + v, 0);
|
|
88
|
+
}
|
|
89
|
+
// Also false for NaN, from a long run of continuation characters.
|
|
90
|
+
return v < 2048 ? v + i * 2048 : fail('version', 'Invalid header', i);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Reads the header without decoding the points. */
|
|
94
|
+
export function header(str) {
|
|
95
|
+
const h = head(str) % 2048;
|
|
96
|
+
return { precision: h & 15, thirdDim: (h >> 4) & 7, thirdDimPrecision: h >> 7 };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Decodes to { precision, thirdDim, thirdDimPrecision, polyline }, the same
|
|
101
|
+
* object @here/flexpolyline returns. Points are [lat, lng], or [lat, lng, z]
|
|
102
|
+
* when the header has a third dimension.
|
|
103
|
+
*/
|
|
104
|
+
export function decode(str) {
|
|
105
|
+
const r = head(str), h = r % 2048, i = (r - h) / 2048, t = (h >> 4) & 7, f = P[h & 15], fz = P[h >> 7];
|
|
106
|
+
return { precision: h & 15, thirdDim: t, thirdDimPrecision: h >> 7, polyline: decodeLoop(str, i, f, fz, t) || slowDecode(str, i, f, fz, t ? 3 : 2) };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// The fast loop, or null when the input needs slowDecode: an invalid
|
|
110
|
+
// character, a truncated string, or a value of more than 10 characters.
|
|
111
|
+
// The value reader is written out three times: a shared helper or one
|
|
112
|
+
// generic loop over the axes measured 15 to 25% slower on V8.
|
|
113
|
+
function decodeLoop(str, i, f, fz, three) {
|
|
114
|
+
const len = str.length, out = [];
|
|
115
|
+
let n = 0, a = 0, b = 0, z = 0, bad = 0, w = 0, k, c, v, s;
|
|
116
|
+
// A code above 127 keeps its high bits in c, which marks it bad without
|
|
117
|
+
// changing the 6 value bits. Past the end, NaN reads as T[0], also bad,
|
|
118
|
+
// and ends the value. The first 6 characters (30 bits) use 32-bit math,
|
|
119
|
+
// later ones float math, exact up to 10 characters (50 bits). Float
|
|
120
|
+
// values then need float zigzag, as the bit operators cut to 32 bits.
|
|
121
|
+
// The sums stay exact below 2^53: w bounds what the large values add up
|
|
122
|
+
// to, and small ones would need a string of over 64 million characters.
|
|
123
|
+
while (i < len) {
|
|
124
|
+
k = str.charCodeAt(i++);
|
|
125
|
+
bad |= c = T[k & 127] | (k & -128);
|
|
126
|
+
for (v = c & 31, s = 5; c & 32; s += 5) {
|
|
127
|
+
k = str.charCodeAt(i++);
|
|
128
|
+
bad |= c = T[k & 127] | (k & -128);
|
|
129
|
+
if (s < 30) v |= (c & 31) << s;
|
|
130
|
+
else if (s < 50) w += v += (c & 31) * 2 ** s;
|
|
131
|
+
else bad = 64;
|
|
132
|
+
}
|
|
133
|
+
a += s > 30 ? (v % 2 ? -(v + 1) / 2 : v / 2) : (v >>> 1) ^ -(v & 1);
|
|
134
|
+
k = str.charCodeAt(i++);
|
|
135
|
+
bad |= c = T[k & 127] | (k & -128);
|
|
136
|
+
for (v = c & 31, s = 5; c & 32; s += 5) {
|
|
137
|
+
k = str.charCodeAt(i++);
|
|
138
|
+
bad |= c = T[k & 127] | (k & -128);
|
|
139
|
+
if (s < 30) v |= (c & 31) << s;
|
|
140
|
+
else if (s < 50) w += v += (c & 31) * 2 ** s;
|
|
141
|
+
else bad = 64;
|
|
142
|
+
}
|
|
143
|
+
b += s > 30 ? (v % 2 ? -(v + 1) / 2 : v / 2) : (v >>> 1) ^ -(v & 1);
|
|
144
|
+
if (three) {
|
|
145
|
+
k = str.charCodeAt(i++);
|
|
146
|
+
bad |= c = T[k & 127] | (k & -128);
|
|
147
|
+
for (v = c & 31, s = 5; c & 32; s += 5) {
|
|
148
|
+
k = str.charCodeAt(i++);
|
|
149
|
+
bad |= c = T[k & 127] | (k & -128);
|
|
150
|
+
if (s < 30) v |= (c & 31) << s;
|
|
151
|
+
else if (s < 50) w += v += (c & 31) * 2 ** s;
|
|
152
|
+
else bad = 64;
|
|
153
|
+
}
|
|
154
|
+
z += s > 30 ? (v % 2 ? -(v + 1) / 2 : v / 2) : (v >>> 1) ^ -(v & 1);
|
|
155
|
+
out[n++] = [a / f, b / f, z / fz];
|
|
156
|
+
} else out[n++] = [a / f, b / f];
|
|
157
|
+
}
|
|
158
|
+
return bad > 63 || i > len || w > 2 ** 52 ? null : out;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Exact decoder with BigInt sums, which also reports errors. */
|
|
162
|
+
function slowDecode(str, i, f, fz, d) {
|
|
163
|
+
const out = [], sum = [0n, 0n, 0n];
|
|
164
|
+
let pt = [], j = 0, v = 0n, s = 0n, k, c;
|
|
165
|
+
for (; i < str.length; i++) {
|
|
166
|
+
k = str.charCodeAt(i);
|
|
167
|
+
c = k < 128 ? T[k] : 64;
|
|
168
|
+
if (c > 63) fail('char', 'Invalid character ' + JSON.stringify(str[i]), i);
|
|
169
|
+
v |= BigInt(c & 31) << s;
|
|
170
|
+
if (c & 32) {
|
|
171
|
+
if ((s += 5n) > 60n) fail('overflow', 'Value too large', i);
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
if (v >> 64n) fail('overflow', 'Value too large', i);
|
|
175
|
+
sum[j] += v & 1n ? ~(v >> 1n) : v >> 1n;
|
|
176
|
+
pt[j] = Number(sum[j]) / (j < 2 ? f : fz);
|
|
177
|
+
if (++j == d) {
|
|
178
|
+
out.push(pt);
|
|
179
|
+
pt = [];
|
|
180
|
+
j = 0;
|
|
181
|
+
}
|
|
182
|
+
v = s = 0n;
|
|
183
|
+
}
|
|
184
|
+
if (s || j) fail('truncated', 'Polyline ends inside a ' + (s ? 'value' : 'point'), i);
|
|
185
|
+
return out;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Encodes points. Takes the @here/flexpolyline argument,
|
|
190
|
+
* { polyline, precision, thirdDim, thirdDimPrecision }, or the points with
|
|
191
|
+
* those fields in `options`, which win over the object's. Points are
|
|
192
|
+
* [lat, lng] or [lat, lng, z] arrays, or one flat array of numbers. Rounds
|
|
193
|
+
* half away from zero.
|
|
194
|
+
*/
|
|
195
|
+
export function encode(input, options) {
|
|
196
|
+
const obj = input != null && typeof input == 'object' && !(input.length >= 0), a = obj ? input : {}, o = options || {};
|
|
197
|
+
const pts = obj ? input.polyline : input;
|
|
198
|
+
const p = range(o.precision ?? a.precision ?? 5, 'precision');
|
|
199
|
+
const q = range(o.thirdDimPrecision ?? a.thirdDimPrecision ?? 0, 'thirdDimPrecision');
|
|
200
|
+
const t = o.thirdDim ?? a.thirdDim ?? 0;
|
|
201
|
+
if (!TYPES.includes(t)) fail('option', 'thirdDim must be 0, 1, 2, 3, 6 or 7');
|
|
202
|
+
if (pts == null || !(pts.length >= 0)) fail('input', 'Expected an array of points');
|
|
203
|
+
const s = 'B' + chars((q << 7) | (t << 4) | p), d = t ? 3 : 2, flat = typeof pts[0] == 'number';
|
|
204
|
+
if (flat && pts.length % d) fail('input', 'Flat array length is not a multiple of ' + d);
|
|
205
|
+
return (!flat && encodeLoop(pts, P[p], P[q], t, s)) || slowEncode(pts, P[p], P[q], d, flat, s);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// Scaled values below this keep deltas and zigzag values in 32-bit math.
|
|
209
|
+
// It covers coordinates up to precision 6.
|
|
210
|
+
const LIMIT = 2 ** 29;
|
|
211
|
+
|
|
212
|
+
// Rounded values below this keep deltas and zigzag values below 2^53.
|
|
213
|
+
const WIDE = 2 ** 51;
|
|
214
|
+
|
|
215
|
+
// The fast loop for arrays of points, or undefined when the input needs
|
|
216
|
+
// slowEncode: a value that is missing, not finite or too large.
|
|
217
|
+
function encodeLoop(pts, f, fz, three, s) {
|
|
218
|
+
const n = pts.length;
|
|
219
|
+
let i = 0, la = 0, lb = 0, lz = 0, x, y, w, p, q, r, z, pt;
|
|
220
|
+
try {
|
|
221
|
+
for (; i < n; i++) {
|
|
222
|
+
pt = pts[i];
|
|
223
|
+
x = pt[0] * f;
|
|
224
|
+
y = pt[1] * f;
|
|
225
|
+
w = three ? pt[2] * fz : 0;
|
|
226
|
+
// Also false for NaN, so missing values go the slow way.
|
|
227
|
+
if (!(x < LIMIT && x > -LIMIT && y < LIMIT && y > -LIMIT && w < LIMIT && w > -LIMIT)) return;
|
|
228
|
+
// Round half away from zero. Below LIMIT, adding 0.5 and truncating
|
|
229
|
+
// gives the exact result.
|
|
230
|
+
p = x < 0 ? -((0.5 - x) | 0) : (x + 0.5) | 0;
|
|
231
|
+
q = y < 0 ? -((0.5 - y) | 0) : (y + 0.5) | 0;
|
|
232
|
+
z = p - la;
|
|
233
|
+
z = (z << 1) ^ (z >> 31);
|
|
234
|
+
s += z < 1024 ? C[z] : chars(z);
|
|
235
|
+
z = q - lb;
|
|
236
|
+
z = (z << 1) ^ (z >> 31);
|
|
237
|
+
s += z < 1024 ? C[z] : chars(z);
|
|
238
|
+
la = p;
|
|
239
|
+
lb = q;
|
|
240
|
+
if (three) {
|
|
241
|
+
r = w < 0 ? -((0.5 - w) | 0) : (w + 0.5) | 0;
|
|
242
|
+
z = r - lz;
|
|
243
|
+
z = (z << 1) ^ (z >> 31);
|
|
244
|
+
s += z < 1024 ? C[z] : chars(z);
|
|
245
|
+
lz = r;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
} catch {
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
return s;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Exact encoder for any input. Rounded values are whole doubles, exact at
|
|
256
|
+
* any size, so they stay Numbers. Their deltas and zigzag values use float
|
|
257
|
+
* math below WIDE, where it is exact, and BigInt above.
|
|
258
|
+
*/
|
|
259
|
+
function slowEncode(pts, f, fz, d, flat, s) {
|
|
260
|
+
const n = flat ? pts.length / d : pts.length, last = [0, 0, 0];
|
|
261
|
+
for (let i = 0; i < n; i++) {
|
|
262
|
+
const pt = flat ? null : pts[i];
|
|
263
|
+
if (!flat && pt == null) fail('coordinate', 'Invalid point', i);
|
|
264
|
+
for (let a = 0; a < d; a++) {
|
|
265
|
+
const x = (flat ? pts[i * d + a] : pt[a]) * (a < 2 ? f : fz);
|
|
266
|
+
if (!(x - x == 0)) fail('coordinate', 'Invalid coordinate', i);
|
|
267
|
+
// Math.round of the magnitude is exact at any size. Adding 0.5 and
|
|
268
|
+
// flooring would round 2^52 + 1 up to 2^52 + 2.
|
|
269
|
+
const r = x < 0 ? -Math.round(-x) : Math.round(x), l = last[a];
|
|
270
|
+
let z = r - l;
|
|
271
|
+
last[a] = r;
|
|
272
|
+
if (r < WIDE && r > -WIDE && l < WIDE && l > -WIDE) s += chars(z < 0 ? -2 * z - 1 : 2 * z);
|
|
273
|
+
else {
|
|
274
|
+
z = BigInt(r) - BigInt(l);
|
|
275
|
+
z = z < 0n ? ~(z << 1n) : z << 1n;
|
|
276
|
+
if (z >> 64n) fail('overflow', 'Value too large', i);
|
|
277
|
+
for (; z > 31n; z >>= 5n) s += E[Number(z & 31n) | 32];
|
|
278
|
+
s += E[Number(z)];
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
return s;
|
|
283
|
+
}
|