@duoquote/geotini 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/CHANGELOG.md +88 -0
- package/LICENSE +21 -0
- package/README.md +331 -2
- package/package.json +126 -4
- package/src/deckgl.js +120 -0
- package/src/error.js +16 -0
- package/src/geoindex.js +373 -0
- package/src/geotini.js +3169 -0
- package/src/google.js +113 -0
- package/src/leaflet.js +82 -0
- package/src/mapbox.js +8 -0
- package/src/maplibre.js +74 -0
- package/src/mongodb.js +179 -0
- package/src/openlayers.js +69 -0
- package/src/redis.js +217 -0
- package/src/reference.js +1463 -0
- package/src/turf.js +79 -0
- package/types/deckgl.d.ts +53 -0
- package/types/google.d.ts +57 -0
- package/types/index.d.ts +453 -0
- package/types/leaflet.d.ts +56 -0
- package/types/mapbox.d.ts +29 -0
- package/types/maplibre.d.ts +53 -0
- package/types/mongodb.d.ts +108 -0
- package/types/openlayers.d.ts +39 -0
- package/types/redis.d.ts +117 -0
- package/types/reference.d.ts +133 -0
- package/types/turf.d.ts +59 -0
package/src/reference.js
ADDED
|
@@ -0,0 +1,1463 @@
|
|
|
1
|
+
// Geotini format, version 1: reference codec written directly from SPEC.md, one bit at a time.
|
|
2
|
+
//
|
|
3
|
+
// encode(geometry, options = 5, trace?) -> string GeoJSON geometry, [lng, lat(, z(, m))]
|
|
4
|
+
// decode(string) -> geometry
|
|
5
|
+
// encodeLine(points, options = 5) -> string [[lat, lng], ...] as LineString
|
|
6
|
+
// decodeLine(string) -> [[lat, lng], ...]
|
|
7
|
+
// inspect(string) -> { type, precision, ..., choices, geometry }
|
|
8
|
+
// canonical(string) -> the canonical string for the same geometry and options
|
|
9
|
+
//
|
|
10
|
+
// The binary form (SPEC.md section 23) holds the same bits, 8 to a byte:
|
|
11
|
+
//
|
|
12
|
+
// encodeValue, decodeValue, encodeLineValue, decodeLineValue, inspectValue
|
|
13
|
+
// and canonicalValue are the six above for a Uint8Array
|
|
14
|
+
// toValue(string) -> Uint8Array and fromValue(Uint8Array) -> string convert
|
|
15
|
+
//
|
|
16
|
+
// options: precision (0..15) or { precision, zPrecision, mPrecision, checksum, mode, choices }
|
|
17
|
+
// trace(label, bits): optional callback used by scripts/example.js to print worked examples.
|
|
18
|
+
//
|
|
19
|
+
// The encoder is the canonical encoder of SPEC.md section 16.4: it prices every
|
|
20
|
+
// mode and every Rice parameter in whole bits and keeps the cheapest, so the
|
|
21
|
+
// same geometry and options give the same string in every implementation.
|
|
22
|
+
/* @ts-self-types="../types/reference.d.ts" */
|
|
23
|
+
import { GeotiniError } from './error.js';
|
|
24
|
+
|
|
25
|
+
export const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
|
|
26
|
+
export const TYPES = ['Point', 'LineString', 'Polygon', 'MultiPoint', 'MultiLineString', 'MultiPolygon', 'GeometryCollection'];
|
|
27
|
+
export const KI = [0, 0, 0, 0, 0, 3, 6, 9, 13, 16, 19, 23, 26, 29, 33, 36];
|
|
28
|
+
export const COS2_17 = [4096, 4057, 3940, 3751, 3495, 3183, 2826, 2438, 2048, 1658, 1270, 913, 601, 345, 156, 39, 16];
|
|
29
|
+
|
|
30
|
+
const BLOCK = 16;
|
|
31
|
+
const MAX_DEPTH = 32;
|
|
32
|
+
const MAX_ZEROS = 23;
|
|
33
|
+
const MAX_COUNT = 134217719;
|
|
34
|
+
// A decoder's own limits (SPEC.md section 14), the same as the fast codec's.
|
|
35
|
+
// No string of more than MAX_LENGTH characters is taken. Below that the
|
|
36
|
+
// caller says how long a string may be and how much it may hold, with
|
|
37
|
+
// maxLength and maxPositions, and these are what holds when it doesn't.
|
|
38
|
+
const MAX_LENGTH = 2 ** 28;
|
|
39
|
+
// The same for a binary value, in bytes: as many bits as MAX_LENGTH characters.
|
|
40
|
+
const MAX_BYTES = 3 * 2 ** 26;
|
|
41
|
+
const DEFAULT_MAX_LENGTH = 2 ** 24, DEFAULT_MAX_POSITIONS = 2 ** 20;
|
|
42
|
+
const LIMIT = 2 ** 50;
|
|
43
|
+
const I32_MIN = -(2 ** 31), I32_MAX = 2 ** 31 - 1;
|
|
44
|
+
const POW = Array.from({ length: 16 }, (_, p) => 10 ** p);
|
|
45
|
+
const MODE_NAMES = ['delta', 'd2', 'slope-fold', 'ortho', 'ema', 'slope-lin'];
|
|
46
|
+
|
|
47
|
+
export { GeotiniError };
|
|
48
|
+
|
|
49
|
+
// What's being decoded, for the messages: a string, or a binary value.
|
|
50
|
+
let WHAT = 'string';
|
|
51
|
+
const invalid = (why, code) => {
|
|
52
|
+
throw new GeotiniError(code, `Invalid geotini ${WHAT}: ` + why);
|
|
53
|
+
};
|
|
54
|
+
// LIMIT_EXCEEDED isn't about the string, which may be valid, so the message
|
|
55
|
+
// names the option that decides.
|
|
56
|
+
const overLimit = (what) => {
|
|
57
|
+
throw new GeotiniError('LIMIT_EXCEEDED', `The ${WHAT} ` + what + ' allows');
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
// A Uint8Array, from this realm or another one (a vm context, an iframe),
|
|
61
|
+
// where instanceof is false: the internal name of a typed array, through
|
|
62
|
+
// this realm's getter, which a property can't fake.
|
|
63
|
+
const TA_NAME = /* @__PURE__ */ Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
|
|
64
|
+
const isBytes = (b) => b instanceof Uint8Array || TA_NAME.call(b) === 'Uint8Array';
|
|
65
|
+
|
|
66
|
+
// Pure-integer helpers
|
|
67
|
+
const i32 = (x) => x | 0;
|
|
68
|
+
const bitLength = (x) => {
|
|
69
|
+
let n = 0;
|
|
70
|
+
for (; x >= 1; x = Math.floor(x / 2)) n++;
|
|
71
|
+
return n;
|
|
72
|
+
};
|
|
73
|
+
const fitsI32 = (x) => x >= I32_MIN && x <= I32_MAX;
|
|
74
|
+
const zig32 = (v) => ((v << 1) ^ (v >> 31)) >>> 0;
|
|
75
|
+
const unzig32 = (z) => (z >>> 1) ^ -(z & 1);
|
|
76
|
+
const zigBig = (v) => (v < 0 ? -2 * v - 1 : 2 * v);
|
|
77
|
+
const unzigBig = (z) => (z % 2 ? -(z + 1) / 2 : z / 2);
|
|
78
|
+
// Every int32 has a fold: below -2^29 it's the fold of u + 2^32, which
|
|
79
|
+
// unfold7 wraps back to u.
|
|
80
|
+
const fold7 = (u) => {
|
|
81
|
+
if (u < -536870912) u += 4294967296;
|
|
82
|
+
return u < 0 ? (-u - 1) * 8 + 7 : u + Math.floor(u / 7);
|
|
83
|
+
};
|
|
84
|
+
const unfold7 = (z) => (z % 8 === 7 ? i32(~(z >>> 3)) : i32(z - (z >>> 3)));
|
|
85
|
+
const div32 = (a, b) => (b === 0 ? 0 : i32(Math.trunc(i32(a) / i32(b))));
|
|
86
|
+
|
|
87
|
+
// Pure-integer reciprocal table for |b| in 1..511
|
|
88
|
+
export const INV = Int32Array.from({ length: 512 }, (_, d) => (d ? Math.floor((16777216 + (d >> 1)) / d) : 0));
|
|
89
|
+
|
|
90
|
+
export function divSlope(a, b) {
|
|
91
|
+
a = i32(a);
|
|
92
|
+
b = i32(b);
|
|
93
|
+
if (b === 0) return 0;
|
|
94
|
+
const ad = Math.abs(b);
|
|
95
|
+
if (ad < 512) {
|
|
96
|
+
const q = Math.imul(a, INV[ad]) >> 12;
|
|
97
|
+
return b < 0 ? i32(-q) : q;
|
|
98
|
+
}
|
|
99
|
+
return div32(i32(a << 12), b);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// 4096 cos²(latitude) for a path that starts at the integer latitude lat0, or
|
|
103
|
+
// 4096 when lat0 isn't a latitude (beyond 90 degrees): the coordinates are
|
|
104
|
+
// then taken as planar. a / (d / 256) is floor(256 a / d) exactly: d / 256
|
|
105
|
+
// is exact in a double, and the quotient is never within an ulp of the next
|
|
106
|
+
// integer (256 a < 2^53 below precision 7, and d / 256 is an integer from 7).
|
|
107
|
+
export function cos2Int(lat0, prec) {
|
|
108
|
+
const a = Math.abs(lat0), d = 90 * POW[prec];
|
|
109
|
+
if (a > d) return 4096;
|
|
110
|
+
const u = Math.floor(a / (d / 256));
|
|
111
|
+
const idx = u >> 4;
|
|
112
|
+
if (idx >= 16) return 16;
|
|
113
|
+
const rem = u & 15;
|
|
114
|
+
return (COS2_17[idx] * (16 - rem) + COS2_17[idx + 1] * rem + 8) >> 4;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// Where the short codes of the first position start, in whole degrees of
|
|
118
|
+
// latitude and longitude, for precisions 0 to 7 (SPEC.md section 7).
|
|
119
|
+
const SHORT_FROM = [[-10, -10], [29, -5], [-65, -125], [-15, -10], [23, -10], [-65, -140], [-15, -30], [19, -10]];
|
|
120
|
+
|
|
121
|
+
// Truncated binary anchor parameters for precisions 0..7
|
|
122
|
+
export const ANCHOR = POW.slice(0, 8).map((f, p) => {
|
|
123
|
+
const NA = 180 * f + 1, NB = 360 * f + 1;
|
|
124
|
+
const bA = bitLength(NA) - 1, bB = bitLength(NB) - 1;
|
|
125
|
+
const TA = 2 ** (bA + 1) - NA, TB = 2 ** (bB + 1) - NB;
|
|
126
|
+
return { NA, NB, bA, bB, TA, TB, offA: -SHORT_FROM[p][0] * f, offB: -SHORT_FROM[p][1] * f, maxA: 90 * f, maxB: 180 * f };
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
// CRC-32C (Castagnoli) over the ASCII bytes of a string or over the bytes of
|
|
130
|
+
// a Uint8Array, or over the first `length` of them
|
|
131
|
+
export function crc32c(str, length = str.length) {
|
|
132
|
+
const text = typeof str === 'string';
|
|
133
|
+
let crc = 0xffffffff;
|
|
134
|
+
for (let i = 0; i < length; i++) {
|
|
135
|
+
crc ^= text ? str.charCodeAt(i) : str[i];
|
|
136
|
+
for (let b = 0; b < 8; b++) crc = crc & 1 ? (crc >>> 1) ^ 0x82f63b78 : crc >>> 1;
|
|
137
|
+
}
|
|
138
|
+
return (crc ^ 0xffffffff) >>> 0;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// ---------------------------------------------------------------- predictors (32-bit exact)
|
|
142
|
+
|
|
143
|
+
function slopeInit() {
|
|
144
|
+
return { sw: -1, s: 0, g: 0, pM: 0 };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function slopeStep1(st, da, db) {
|
|
148
|
+
st.sw = Math.abs(db) >= Math.abs(da) ? -1 : 0;
|
|
149
|
+
const dM = st.sw ? db : da, dm = st.sw ? da : db;
|
|
150
|
+
st.s = dM !== 0 ? divSlope(dm, dM) : 0;
|
|
151
|
+
st.pM = dM;
|
|
152
|
+
st.g = dM !== 0 ? (dM >> 31) : 0;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function slopeUpdate(st, dM, dm, err) {
|
|
156
|
+
st.pM = dM;
|
|
157
|
+
if (Math.abs(dm) > Math.abs(dM)) {
|
|
158
|
+
st.sw = ~st.sw;
|
|
159
|
+
st.s = divSlope(dM, dm);
|
|
160
|
+
st.pM = dm;
|
|
161
|
+
} else if (err !== 0 && dM !== 0) {
|
|
162
|
+
let ds = divSlope(err, dM);
|
|
163
|
+
if (Math.abs(dM) < 4) ds >>= 1;
|
|
164
|
+
st.s = i32(st.s + ds);
|
|
165
|
+
}
|
|
166
|
+
if (st.pM !== 0) st.g = st.pM >> 31;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function orthoInit(lat0, lng0, prec) {
|
|
170
|
+
const c2 = cos2Int(lat0, prec);
|
|
171
|
+
return { lat0, lng0, c2, c2s: c2 >> 4, swU: 0, sU: 0, swV: 0, sV: 0, maxL1: 0, nextV: 1, da1: 0, db1: 0 };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function orthoSetFrame(st, ua, ub) {
|
|
175
|
+
ua = i32(ua);
|
|
176
|
+
ub = i32(ub);
|
|
177
|
+
while (Math.abs(ua) >= 262144 || Math.abs(ub) >= 262144) {
|
|
178
|
+
ua >>= 1;
|
|
179
|
+
ub >>= 1;
|
|
180
|
+
}
|
|
181
|
+
const va = i32(-((Math.imul(st.c2, ub) + 2048) >> 12));
|
|
182
|
+
const vb = ua;
|
|
183
|
+
if (Math.abs(ub) >= Math.abs(ua)) { st.swU = 1; st.sU = divSlope(ua, ub); }
|
|
184
|
+
else { st.swU = 0; st.sU = divSlope(ub, ua); }
|
|
185
|
+
if (Math.abs(vb) >= Math.abs(va)) { st.swV = 1; st.sV = divSlope(va, vb); }
|
|
186
|
+
else { st.swV = 0; st.sV = divSlope(vb, va); }
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function orthoStep1(st, da, db) {
|
|
190
|
+
st.da1 = da;
|
|
191
|
+
st.db1 = db;
|
|
192
|
+
orthoSetFrame(st, da, db);
|
|
193
|
+
st.maxL1 = Math.abs(da) + Math.abs(db);
|
|
194
|
+
st.nextV = 1;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// curLat and curLng can be past 32 bits in a wide string: i32 wraps the
|
|
198
|
+
// exact difference.
|
|
199
|
+
function orthoClosingPred(st, curLat, curLng, m) {
|
|
200
|
+
if (m === 4) return [i32(-st.da1), i32(-st.db1)];
|
|
201
|
+
const sw = st.nextV ? st.swV : st.swU;
|
|
202
|
+
const s = st.nextV ? st.sV : st.sU;
|
|
203
|
+
const pA = sw ? (s >> 4) : 256;
|
|
204
|
+
const pB = sw ? 256 : (s >> 4);
|
|
205
|
+
const wB = (st.c2s * pB + 128) >> 8;
|
|
206
|
+
const denom = pA * pA + wB * pB;
|
|
207
|
+
if (denom <= 0) return [0, 0];
|
|
208
|
+
const remA = i32(st.lat0 - curLat);
|
|
209
|
+
const remB = i32(st.lng0 - curLng);
|
|
210
|
+
const num = remA * pA + remB * wB;
|
|
211
|
+
return [i32(Math.trunc((num * pA) / denom)), i32(Math.trunc((num * pB) / denom))];
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function orthoUpdate(st, da, db, err) {
|
|
215
|
+
const osw = st.nextV ? st.swU : st.swV;
|
|
216
|
+
const os = st.nextV ? st.sU : st.sV;
|
|
217
|
+
const oM = osw ? db : da, om = osw ? da : db;
|
|
218
|
+
const oerr = i32(om - ((Math.imul(oM, os) + 2048) >> 12));
|
|
219
|
+
const stayed = Math.abs(err) <= Math.abs(oerr);
|
|
220
|
+
const wasU = st.nextV ? !stayed : stayed;
|
|
221
|
+
st.nextV = wasU ? 1 : 0;
|
|
222
|
+
const l1 = Math.abs(da) + Math.abs(db);
|
|
223
|
+
if (Math.abs(da) < 262144 && Math.abs(db) < 262144 && l1 > st.maxL1) {
|
|
224
|
+
st.maxL1 = l1;
|
|
225
|
+
if (wasU) orthoSetFrame(st, da, db);
|
|
226
|
+
else orthoSetFrame(st, db, i32(-div32(i32(da << 12), st.c2)));
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// ---------------------------------------------------------------- decoding
|
|
231
|
+
|
|
232
|
+
// The 6 bits of each character, by character code, and -1 for a character
|
|
233
|
+
// outside the alphabet.
|
|
234
|
+
const VALUE = new Int8Array(128).fill(-1);
|
|
235
|
+
for (let i = 0; i < 64; i++) VALUE[ALPHABET.charCodeAt(i)] = i;
|
|
236
|
+
|
|
237
|
+
// The UTF-8 bytes of a string, what maxLength counts (SPEC.md section 14):
|
|
238
|
+
// its length when it's ASCII, and a unit is at most 3 bytes. A lone
|
|
239
|
+
// surrogate counts the 3 bytes of the U+FFFD TextEncoder writes for it.
|
|
240
|
+
const utf8Length = (s, max) => (s.length * 3 > max ? new TextEncoder().encode(s).length : s.length);
|
|
241
|
+
|
|
242
|
+
// Reads a string one bit at a time, the most significant bit of each
|
|
243
|
+
// character first. A bit is taken from its character when it's asked for, so
|
|
244
|
+
// reading takes no memory of its own, however long the string is. (It once
|
|
245
|
+
// unpacked the whole string into an array of bits before the header was
|
|
246
|
+
// read: 100 MB for a megabyte of characters, valid or not.)
|
|
247
|
+
//
|
|
248
|
+
// With `binary` the source is a Uint8Array, the binary form of SPEC.md
|
|
249
|
+
// section 23: the same bits, 8 to a byte. `unit` is how many bits one
|
|
250
|
+
// character or one byte gives. Nothing else about reading differs, and the
|
|
251
|
+
// three places that count characters or bytes are here: the length, the
|
|
252
|
+
// check, and the padding at the end.
|
|
253
|
+
class Reader {
|
|
254
|
+
constructor(src, maxLength, binary) {
|
|
255
|
+
// The length is judged before anything is read, whatever the string holds:
|
|
256
|
+
// its bytes, or the UTF-8 bytes of its characters.
|
|
257
|
+
if ((binary ? src.length : utf8Length(src, maxLength)) > maxLength) overLimit('is longer than maxLength');
|
|
258
|
+
if (src.length === 0) invalid(binary ? 'no bytes' : 'empty string', 'TRUNCATED');
|
|
259
|
+
// Every character is checked before any bit is read (SPEC.md section 2).
|
|
260
|
+
// A byte can have any value, so a binary value has nothing to check here.
|
|
261
|
+
if (!binary) {
|
|
262
|
+
for (let i = 0; i < src.length; i++) {
|
|
263
|
+
const c = src.charCodeAt(i);
|
|
264
|
+
if (c > 127 || VALUE[c] < 0) invalid('character outside base64url alphabet', 'BAD_CHARACTER');
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
this.src = src;
|
|
268
|
+
this.unit = binary ? 8 : 6;
|
|
269
|
+
this.pos = 0; // the next bit to read
|
|
270
|
+
this.end = src.length * this.unit; // one past the last bit: the end of the string, or the start of its check
|
|
271
|
+
}
|
|
272
|
+
get left() {
|
|
273
|
+
return this.end - this.pos;
|
|
274
|
+
}
|
|
275
|
+
bit() {
|
|
276
|
+
if (this.pos >= this.end) invalid('truncated', 'TRUNCATED');
|
|
277
|
+
const unit = this.unit, at = Math.floor(this.pos / unit);
|
|
278
|
+
const value = unit === 8 ? this.src[at] : VALUE[this.src.charCodeAt(at)];
|
|
279
|
+
return (value >> (unit - 1 - (this.pos++ % unit))) & 1;
|
|
280
|
+
}
|
|
281
|
+
// The check at the end of the string, against the CRC-32C of everything
|
|
282
|
+
// before it. kind is the header's field: 1 short, 2 full. A string keeps
|
|
283
|
+
// 12 bits of the CRC in 2 characters, or all 32 and 4 zero bits in 6
|
|
284
|
+
// (SPEC.md section 12). A binary value keeps 16 bits in 2 bytes, or all 32
|
|
285
|
+
// in 4 (section 23.2). From then on the string ends where the check starts.
|
|
286
|
+
verifyCheck(kind) {
|
|
287
|
+
const binary = this.unit === 8, tailLen = kind === 1 ? 2 : binary ? 4 : 6;
|
|
288
|
+
if (this.src.length < 3 + tailLen) invalid('truncated checksum', 'TRUNCATED');
|
|
289
|
+
const body = this.src.length - tailLen, crc = crc32c(this.src, body), resume = this.pos;
|
|
290
|
+
this.pos = body * this.unit;
|
|
291
|
+
let matches;
|
|
292
|
+
if (binary) matches = kind === 2 ? this.read(32) === crc : this.read(16) === crc >>> 16;
|
|
293
|
+
else matches = kind === 2 ? this.read(32) === crc && this.read(4) === 0 : this.read(12) === crc >>> 20;
|
|
294
|
+
if (!matches) invalid('checksum mismatch', 'CHECKSUM');
|
|
295
|
+
this.pos = resume;
|
|
296
|
+
this.end = body * this.unit;
|
|
297
|
+
}
|
|
298
|
+
read(n) {
|
|
299
|
+
let v = 0;
|
|
300
|
+
while (n-- > 0) v = v * 2 + this.bit();
|
|
301
|
+
return v;
|
|
302
|
+
}
|
|
303
|
+
unary(max) {
|
|
304
|
+
let c = 0;
|
|
305
|
+
while (this.bit() === 0) {
|
|
306
|
+
if (++c > max) invalid('value too large', 'OUT_OF_RANGE');
|
|
307
|
+
}
|
|
308
|
+
return c;
|
|
309
|
+
}
|
|
310
|
+
count() {
|
|
311
|
+
let zeros = 0;
|
|
312
|
+
while (this.bit() === 0) {
|
|
313
|
+
if (++zeros > MAX_ZEROS) invalid('count too large', 'COUNT_TOO_LARGE');
|
|
314
|
+
}
|
|
315
|
+
return (2 ** zeros + this.read(zeros) - 1) * 8 + this.read(3);
|
|
316
|
+
}
|
|
317
|
+
// A container count: every part takes at least `each` bits, so a count
|
|
318
|
+
// that needs more than are left is a string cut short.
|
|
319
|
+
bounded(each) {
|
|
320
|
+
const n = this.count();
|
|
321
|
+
if (n * each > this.left) invalid('count exceeds remaining input', 'TRUNCATED');
|
|
322
|
+
return n;
|
|
323
|
+
}
|
|
324
|
+
sized() {
|
|
325
|
+
const n = this.read(6);
|
|
326
|
+
if (n > 53) invalid('sized number length above 53', 'OUT_OF_RANGE');
|
|
327
|
+
const z = this.read(n);
|
|
328
|
+
if (n > 0 && z < 2 ** (n - 1)) invalid('sized number not canonical', 'NON_CANONICAL');
|
|
329
|
+
return z;
|
|
330
|
+
}
|
|
331
|
+
// The long form's codes max + 1 and max + 2 are the parameters -1 and -2.
|
|
332
|
+
param(prev, width, max, minTarget) {
|
|
333
|
+
let zeros = 0;
|
|
334
|
+
while (zeros < 8 && this.bit() === 0) zeros++;
|
|
335
|
+
let k;
|
|
336
|
+
if (zeros < 8) {
|
|
337
|
+
k = prev + unzigBig(zeros);
|
|
338
|
+
if (k < minTarget || k > max) invalid('Rice parameter out of range', 'OUT_OF_RANGE');
|
|
339
|
+
} else {
|
|
340
|
+
const t = this.read(width);
|
|
341
|
+
if (t > max + 2) invalid('Rice parameter out of range', 'OUT_OF_RANGE');
|
|
342
|
+
k = t > max ? max - t : t;
|
|
343
|
+
if (zigBig(k - prev) < 8) invalid('Rice parameter not in shortest form', 'NON_CANONICAL');
|
|
344
|
+
if (k < minTarget) invalid('Rice parameter out of range', 'OUT_OF_RANGE');
|
|
345
|
+
}
|
|
346
|
+
return k;
|
|
347
|
+
}
|
|
348
|
+
// Rice-T6 quotient given class c and k, enforcing z < 2^maxBits
|
|
349
|
+
quotient(c, k, maxBits) {
|
|
350
|
+
const maxQ = 2 ** (maxBits - k);
|
|
351
|
+
let q;
|
|
352
|
+
if (c < 6) {
|
|
353
|
+
q = c;
|
|
354
|
+
} else {
|
|
355
|
+
const n = c - 4;
|
|
356
|
+
if (n + k >= maxBits) invalid('value too large', 'OUT_OF_RANGE');
|
|
357
|
+
q = 2 ** n + this.read(n) + 2;
|
|
358
|
+
}
|
|
359
|
+
if (q >= maxQ) invalid('value too large', 'OUT_OF_RANGE');
|
|
360
|
+
return q;
|
|
361
|
+
}
|
|
362
|
+
pair(k1, k2, maxBits) {
|
|
363
|
+
const c1 = this.unary(maxBits + 3 - k1);
|
|
364
|
+
const c2 = this.unary(maxBits + 3 - k2);
|
|
365
|
+
const f1 = this.read(k1);
|
|
366
|
+
const f2 = this.read(k2);
|
|
367
|
+
const q1 = this.quotient(c1, k1, maxBits);
|
|
368
|
+
const q2 = this.quotient(c2, k2, maxBits);
|
|
369
|
+
return [q1 * 2 ** k1 + f1, q2 * 2 ** k2 + f2];
|
|
370
|
+
}
|
|
371
|
+
single(k, maxBits) {
|
|
372
|
+
const c = this.unary(maxBits + 3 - k);
|
|
373
|
+
const f = this.read(k);
|
|
374
|
+
const q = this.quotient(c, k, maxBits);
|
|
375
|
+
return q * 2 ** k + f;
|
|
376
|
+
}
|
|
377
|
+
mode() {
|
|
378
|
+
const b0 = this.bit(), b1 = this.bit();
|
|
379
|
+
if (b0 === 0) return b1; // 00 -> 0 (delta), 01 -> 1 (d2)
|
|
380
|
+
if (b1 === 0) return 2; // 10 -> 2 (slope-fold)
|
|
381
|
+
if (this.bit() === 0) return 3; // 110 -> 3 (ortho)
|
|
382
|
+
return 4 + this.bit(); // 1110 -> 4 (ema), 1111 -> 5 (slope-lin)
|
|
383
|
+
}
|
|
384
|
+
// Fewer bits than one character or one byte gives may be left, all zero.
|
|
385
|
+
finish() {
|
|
386
|
+
if (this.left > this.unit - 1) invalid('trailing data', 'TRAILING_DATA');
|
|
387
|
+
while (this.left > 0) if (this.bit() !== 0) invalid('non-zero padding', 'TRAILING_DATA');
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
function readTruncCoord(r, N, b, T, off, maxVal) {
|
|
392
|
+
const v = r.read(b);
|
|
393
|
+
let u;
|
|
394
|
+
if (v < T) {
|
|
395
|
+
u = v;
|
|
396
|
+
} else {
|
|
397
|
+
u = v * 2 + r.bit() - T;
|
|
398
|
+
if (u >= N) invalid('first position out of globe bounds', 'OUT_OF_RANGE');
|
|
399
|
+
}
|
|
400
|
+
let val = u - off;
|
|
401
|
+
if (val > maxVal) val -= N;
|
|
402
|
+
if (val < -maxVal) val += N;
|
|
403
|
+
return val;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// rec, when given, collects the header fields and the coding choices: the
|
|
407
|
+
// mode of each geometry (modes) and every Rice parameter (k), each in the
|
|
408
|
+
// order they're read, and the predictor bit of each extra coordinate (pred).
|
|
409
|
+
// With needCheck, a string that carries no check is refused like one whose
|
|
410
|
+
// check fails: damage to the first characters can turn a checked string into
|
|
411
|
+
// an unchecked one, and only the reader knows a check was meant to be there.
|
|
412
|
+
// With binary, str is a Uint8Array: the binary form (SPEC.md section 23).
|
|
413
|
+
function decodeCore(str, expectLine, rec, options, binary = false) {
|
|
414
|
+
if (binary ? !isBytes(str) : typeof str !== 'string') throw new TypeError(binary ? 'Expected a Uint8Array' : 'Expected a string');
|
|
415
|
+
WHAT = binary ? 'value' : 'string';
|
|
416
|
+
const { needCheck, maxLength, maxPositions } = decodeOptions(options, binary);
|
|
417
|
+
const r = new Reader(str, maxLength, binary);
|
|
418
|
+
// What the string has put in the result so far, against maxPositions: one
|
|
419
|
+
// for every geometry and every polygon where it begins, and for a path,
|
|
420
|
+
// when its count is read, one for itself and one for every position. So a
|
|
421
|
+
// string that holds too much is refused at the count, before the work.
|
|
422
|
+
let counted = 0;
|
|
423
|
+
const count = (n) => {
|
|
424
|
+
counted += n;
|
|
425
|
+
if (counted > maxPositions) overLimit('holds more than maxPositions');
|
|
426
|
+
};
|
|
427
|
+
|
|
428
|
+
// Header
|
|
429
|
+
let type, prec;
|
|
430
|
+
const o = { wide: 0, open: 0, z: 0, m: 0, check: 0 };
|
|
431
|
+
if (r.bit() === 0) {
|
|
432
|
+
// 0 t2(2) p6(1)
|
|
433
|
+
const t2 = r.read(2), p6 = r.bit();
|
|
434
|
+
type = [0, 1, 2, 5][t2];
|
|
435
|
+
prec = 5 + p6;
|
|
436
|
+
} else if (r.bit() === 0) {
|
|
437
|
+
// 10 s2(2) p6(1)
|
|
438
|
+
const s2 = r.read(2), p6 = r.bit();
|
|
439
|
+
if (s2 < 3) {
|
|
440
|
+
type = [3, 4, 6][s2];
|
|
441
|
+
prec = 5 + p6;
|
|
442
|
+
} else {
|
|
443
|
+
type = p6 ? 2 : 1;
|
|
444
|
+
prec = 7;
|
|
445
|
+
}
|
|
446
|
+
} else if (r.bit() === 0) {
|
|
447
|
+
// 110 s3(3)
|
|
448
|
+
const s3 = r.read(3);
|
|
449
|
+
if (s3 >= 5) invalid('a later version of the format', 'UNSUPPORTED_VERSION');
|
|
450
|
+
type = [0, 3, 4, 5, 6][s3];
|
|
451
|
+
prec = 7;
|
|
452
|
+
} else {
|
|
453
|
+
if (r.bit() === 1) invalid('a later version of the format', 'UNSUPPORTED_VERSION');
|
|
454
|
+
// 1110: the extended header. All 13 bits are read before any is judged,
|
|
455
|
+
// and the check, when there is one, is verified first: a damaged header
|
|
456
|
+
// is then a CHECKSUM refusal, whatever its other bits say.
|
|
457
|
+
type = r.read(3);
|
|
458
|
+
prec = r.read(4);
|
|
459
|
+
o.wide = r.bit();
|
|
460
|
+
o.open = r.bit();
|
|
461
|
+
o.z = r.bit();
|
|
462
|
+
o.m = r.bit();
|
|
463
|
+
o.check = r.read(2);
|
|
464
|
+
if (o.check === 3) invalid('a later version of the format', 'UNSUPPORTED_VERSION');
|
|
465
|
+
if (needCheck && !o.check) invalid(`a check was required and the ${WHAT} has none`, 'CHECKSUM');
|
|
466
|
+
if (o.check) r.verifyCheck(o.check);
|
|
467
|
+
if (type === 7) invalid('a later version of the format', 'UNSUPPORTED_VERSION');
|
|
468
|
+
if (o.m && !o.z) invalid('a fourth coordinate without a third is reserved for a later version', 'UNSUPPORTED_VERSION');
|
|
469
|
+
if (prec > 7 && !o.wide) invalid('precision above 7 requires wide option', 'BAD_HEADER');
|
|
470
|
+
const anyOpt = o.wide || o.open || o.z || o.m || o.check;
|
|
471
|
+
if (!anyOpt && prec >= 5 && prec <= 7) invalid('header not in shortest form', 'NON_CANONICAL');
|
|
472
|
+
if (o.open && (type === 0 || type === 1 || type === 3 || type === 4)) invalid('openRings on a type without rings', 'NON_CANONICAL');
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
if (needCheck && !o.check) invalid(`a check was required and the ${WHAT} has none`, 'CHECKSUM');
|
|
476
|
+
if (expectLine && type !== 1) invalid('expected a LineString', 'WRONG_TYPE');
|
|
477
|
+
|
|
478
|
+
const extraP = [], extraF = [], extraPred = [];
|
|
479
|
+
if (o.z) { extraP.push(r.read(4)); extraPred.push(r.bit()); }
|
|
480
|
+
if (o.m) { extraP.push(r.read(4)); extraPred.push(r.bit()); }
|
|
481
|
+
for (const p of extraP) extraF.push(POW[p]);
|
|
482
|
+
|
|
483
|
+
const f = POW[prec];
|
|
484
|
+
const kMax = o.wide ? 52 : 24;
|
|
485
|
+
const maxBits = o.wide ? 53 : 32;
|
|
486
|
+
const maxVal = 2 ** maxBits - 1;
|
|
487
|
+
// steps counts the block-coded points of the string so far. needWide and
|
|
488
|
+
// openRing say whether the wide and openRings options were needed.
|
|
489
|
+
const st = { started: false, lat: 0, lng: 0, k1: KI[prec], k2: 0, extra: extraF.map(() => 0), ke: extraF.map(() => 0), steps: 0, needWide: prec > 7, openRing: false };
|
|
490
|
+
const choice = (v, list) => { if (rec) rec.choices[list || 'k'].push(v); };
|
|
491
|
+
|
|
492
|
+
const makePoint = (geoOrder) => {
|
|
493
|
+
if (o.wide) {
|
|
494
|
+
if (Math.abs(st.lat) > LIMIT || Math.abs(st.lng) > LIMIT) invalid('coordinate exceeds 2^50', 'OUT_OF_RANGE');
|
|
495
|
+
if (!fitsI32(st.lat) || !fitsI32(st.lng)) st.needWide = true;
|
|
496
|
+
}
|
|
497
|
+
// Written at its final length. A position that grows by push keeps room
|
|
498
|
+
// for 17 more numbers: 216 bytes on V8, where this one takes 80.
|
|
499
|
+
const first = geoOrder ? st.lng / f : st.lat / f, second = geoOrder ? st.lat / f : st.lng / f;
|
|
500
|
+
if (extraF.length === 0) return [first, second];
|
|
501
|
+
if (extraF.length === 1) return [first, second, st.extra[0] / extraF[0]];
|
|
502
|
+
return [first, second, st.extra[0] / extraF[0], st.extra[1] / extraF[1]];
|
|
503
|
+
};
|
|
504
|
+
|
|
505
|
+
const extraStep = (d, v) => {
|
|
506
|
+
st.extra[d] += v;
|
|
507
|
+
if (Math.abs(st.extra[d]) > LIMIT) invalid('extra coordinate exceeds 2^50', 'OUT_OF_RANGE');
|
|
508
|
+
};
|
|
509
|
+
|
|
510
|
+
const position = (geoOrder) => {
|
|
511
|
+
if (!st.started) {
|
|
512
|
+
st.started = true;
|
|
513
|
+
if (o.wide) {
|
|
514
|
+
st.lat = unzigBig(r.sized());
|
|
515
|
+
st.lng = unzigBig(r.sized());
|
|
516
|
+
if (Math.abs(st.lat) > 90 * f || Math.abs(st.lng) > 180 * f) st.needWide = true;
|
|
517
|
+
} else {
|
|
518
|
+
const anc = ANCHOR[prec];
|
|
519
|
+
st.lat = readTruncCoord(r, anc.NA, anc.bA, anc.TA, anc.offA, anc.maxA);
|
|
520
|
+
st.lng = readTruncCoord(r, anc.NB, anc.bB, anc.TB, anc.offB, anc.maxB);
|
|
521
|
+
}
|
|
522
|
+
} else if (r.bit() === 1) {
|
|
523
|
+
const L = r.read(o.wide ? 6 : 5) + 1;
|
|
524
|
+
if (L > maxBits) invalid('jump length too large', 'OUT_OF_RANGE');
|
|
525
|
+
const a = r.read(L), b = r.read(L);
|
|
526
|
+
const top = 2 ** (L - 1);
|
|
527
|
+
if (a < top && b < top) invalid('jump not in shortest form', 'NON_CANONICAL');
|
|
528
|
+
if (o.wide) { st.lat += unzigBig(a); st.lng += unzigBig(b); }
|
|
529
|
+
else { st.lat = i32(st.lat + unzig32(a)); st.lng = i32(st.lng + unzig32(b)); }
|
|
530
|
+
}
|
|
531
|
+
for (let d = 0; d < extraF.length; d++) extraStep(d, unzigBig(r.sized()));
|
|
532
|
+
return makePoint(geoOrder);
|
|
533
|
+
};
|
|
534
|
+
|
|
535
|
+
const path = (mode, kind, geoOrder) => {
|
|
536
|
+
const hasBit = kind === 0 || (kind === 1 && o.open);
|
|
537
|
+
const closed = kind === 2 ? 0 : hasBit ? r.bit() : 1;
|
|
538
|
+
if (kind === 1 && !closed) st.openRing = true;
|
|
539
|
+
const m = r.count();
|
|
540
|
+
if (closed && m === 0) invalid('closed path with zero points', 'EMPTY_CLOSED_PATH');
|
|
541
|
+
const isSplit = mode === 2 || mode === 3 || mode === 5;
|
|
542
|
+
// The bounds rule: more points than the bits left can hold is a string cut short.
|
|
543
|
+
if (m > 0 && m - 1 > (isSplit ? r.left : 4 * r.left)) invalid('point count exceeds remaining bits', 'TRUNCATED');
|
|
544
|
+
// The path counts now: one for itself, and its positions, with the
|
|
545
|
+
// first one again at the end of a closed path.
|
|
546
|
+
count(m === 0 ? 1 : 1 + m + closed);
|
|
547
|
+
if (m === 0) return [];
|
|
548
|
+
const out = [position(geoOrder)];
|
|
549
|
+
const lat0 = st.lat, lng0 = st.lng, extra0 = st.extra.slice();
|
|
550
|
+
const n = m - 1;
|
|
551
|
+
let va = 0, vb = 0;
|
|
552
|
+
const slope = isSplit && mode !== 3 ? slopeInit() : null;
|
|
553
|
+
const ortho = mode === 3 ? orthoInit(st.lat, st.lng, prec) : null;
|
|
554
|
+
const ve = extraF.map(() => 0);
|
|
555
|
+
st.steps += n;
|
|
556
|
+
|
|
557
|
+
for (let i = 0; i < n; i += BLOCK) {
|
|
558
|
+
const cnt = Math.min(BLOCK, n - i);
|
|
559
|
+
if (!isSplit) {
|
|
560
|
+
const k = r.param(st.k1, o.wide ? 6 : 5, kMax, -2);
|
|
561
|
+
choice(k);
|
|
562
|
+
st.k1 = k < 0 ? 0 : k;
|
|
563
|
+
let mask = 0;
|
|
564
|
+
if (k === -1) {
|
|
565
|
+
mask = r.read(cnt);
|
|
566
|
+
if (mask === 0) invalid('empty sparse block', 'NON_CANONICAL');
|
|
567
|
+
}
|
|
568
|
+
for (let j = 0; j < cnt; j++) {
|
|
569
|
+
const idx = i + j;
|
|
570
|
+
let z1 = 0, z2 = 0;
|
|
571
|
+
if (k === -2) {
|
|
572
|
+
// (0, 0)
|
|
573
|
+
} else if (k === -1) {
|
|
574
|
+
if ((mask >>> (cnt - 1 - j)) & 1) {
|
|
575
|
+
[z1, z2] = r.pair(0, 0, maxBits);
|
|
576
|
+
if (z1 === 0) {
|
|
577
|
+
if (z2 >= maxVal) invalid('sparse value overflow', 'OUT_OF_RANGE');
|
|
578
|
+
z2 += 1;
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
} else {
|
|
582
|
+
[z1, z2] = r.pair(k, k, maxBits);
|
|
583
|
+
}
|
|
584
|
+
if (o.wide) {
|
|
585
|
+
const ra = unzigBig(z1), rb = unzigBig(z2);
|
|
586
|
+
const da = mode === 0 ? ra : va + ra;
|
|
587
|
+
const db = mode === 0 ? rb : vb + rb;
|
|
588
|
+
if (mode === 1) { va = da; vb = db; }
|
|
589
|
+
else if (mode === 4) { va = idx === 0 ? da : Math.floor((va + da) / 2); vb = idx === 0 ? db : Math.floor((vb + db) / 2); }
|
|
590
|
+
st.lat += da;
|
|
591
|
+
st.lng += db;
|
|
592
|
+
} else {
|
|
593
|
+
const ra = unzig32(z1), rb = unzig32(z2);
|
|
594
|
+
const da = mode === 0 ? ra : i32(va + ra);
|
|
595
|
+
const db = mode === 0 ? rb : i32(vb + rb);
|
|
596
|
+
if (mode === 1) { va = da; vb = db; }
|
|
597
|
+
else if (mode === 4) { va = idx === 0 ? da : (va + da) >> 1; vb = idx === 0 ? db : (vb + db) >> 1; }
|
|
598
|
+
st.lat = i32(st.lat + da);
|
|
599
|
+
st.lng = i32(st.lng + db);
|
|
600
|
+
}
|
|
601
|
+
out.push(makePoint(geoOrder));
|
|
602
|
+
}
|
|
603
|
+
} else {
|
|
604
|
+
// Split mode: 2 (slope-fold), 3 (ortho), 5 (slope-lin). The steps are
|
|
605
|
+
// 32-bit in ordinary and wide strings alike; a wide string only adds
|
|
606
|
+
// them to the position exactly.
|
|
607
|
+
const closingK2 = mode === 3 && closed === 1 && m >= 4;
|
|
608
|
+
let hasK1 = false, hasK2 = false;
|
|
609
|
+
for (let j = 0; j < cnt; j++) {
|
|
610
|
+
const idx = i + j;
|
|
611
|
+
if (idx === 0) hasK1 = true;
|
|
612
|
+
else if (closingK2 && idx === n - 1) hasK2 = true;
|
|
613
|
+
else { hasK1 = true; hasK2 = true; }
|
|
614
|
+
}
|
|
615
|
+
let k1 = st.k1, k2 = st.k2;
|
|
616
|
+
if (hasK1) { k1 = r.param(st.k1, 5, 24, 0); choice(k1); st.k1 = k1; }
|
|
617
|
+
if (hasK2) { k2 = r.param(st.k2, 5, 24, -1); choice(k2); st.k2 = k2 < 0 ? 0 : k2; }
|
|
618
|
+
for (let j = 0; j < cnt; j++) {
|
|
619
|
+
const idx = i + j;
|
|
620
|
+
let da, db;
|
|
621
|
+
if (idx === 0) {
|
|
622
|
+
const [z1, z2] = r.pair(k1, k1, 32);
|
|
623
|
+
da = unzig32(z1); db = unzig32(z2);
|
|
624
|
+
if (mode === 3) orthoStep1(ortho, da, db);
|
|
625
|
+
else slopeStep1(slope, da, db);
|
|
626
|
+
} else if (closingK2 && idx === n - 1) {
|
|
627
|
+
let ea = 0, eb = 0;
|
|
628
|
+
if (k2 >= 0) {
|
|
629
|
+
const [z1, z2] = r.pair(k2, k2, 32);
|
|
630
|
+
ea = unzig32(z1); eb = unzig32(z2);
|
|
631
|
+
}
|
|
632
|
+
const [pda, pdb] = orthoClosingPred(ortho, st.lat, st.lng, m);
|
|
633
|
+
da = i32(pda + ea); db = i32(pdb + eb);
|
|
634
|
+
} else {
|
|
635
|
+
let z1, z2 = 0;
|
|
636
|
+
if (k2 < 0) z1 = r.single(k1, 32);
|
|
637
|
+
else [z1, z2] = r.pair(k1, k2, 32);
|
|
638
|
+
if (mode === 3) {
|
|
639
|
+
const sw = ortho.nextV ? ortho.swV : ortho.swU;
|
|
640
|
+
const s = ortho.nextV ? ortho.sV : ortho.sU;
|
|
641
|
+
const dM = unzig32(z1), err = unzig32(z2);
|
|
642
|
+
const dm = i32(((Math.imul(dM, s) + 2048) >> 12) + err);
|
|
643
|
+
da = sw ? dm : dM; db = sw ? dM : dm;
|
|
644
|
+
orthoUpdate(ortho, da, db, err);
|
|
645
|
+
} else {
|
|
646
|
+
let dM;
|
|
647
|
+
if (mode === 5) dM = i32(slope.pM + unzig32(z1));
|
|
648
|
+
else {
|
|
649
|
+
const u = unfold7(z1);
|
|
650
|
+
dM = i32((u ^ slope.g) - slope.g);
|
|
651
|
+
}
|
|
652
|
+
const err = unzig32(z2);
|
|
653
|
+
const dm = i32(((Math.imul(dM, slope.s) + 2048) >> 12) + err);
|
|
654
|
+
da = slope.sw ? dm : dM; db = slope.sw ? dM : dm;
|
|
655
|
+
slopeUpdate(slope, dM, dm, err);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
st.lat = o.wide ? st.lat + da : i32(st.lat + da);
|
|
659
|
+
st.lng = o.wide ? st.lng + db : i32(st.lng + db);
|
|
660
|
+
out.push(makePoint(geoOrder));
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
// Extra coordinates for this block
|
|
664
|
+
for (let d = 0; d < extraF.length; d++) {
|
|
665
|
+
const ke = r.param(st.ke[d], 6, 52, -1);
|
|
666
|
+
choice(ke);
|
|
667
|
+
st.ke[d] = ke < 0 ? 0 : ke;
|
|
668
|
+
for (let j = 0; j < cnt; j++) {
|
|
669
|
+
const z = ke < 0 ? 0 : r.single(ke, 53);
|
|
670
|
+
const rv = unzigBig(z);
|
|
671
|
+
const dv = extraPred[d] ? ve[d] + rv : rv;
|
|
672
|
+
ve[d] = dv;
|
|
673
|
+
extraStep(d, dv);
|
|
674
|
+
out[out.length - cnt + j][2 + d] = st.extra[d] / extraF[d];
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
// A path that could have been written closed must be.
|
|
679
|
+
if (hasBit && !closed && m >= 2 && st.lat === lat0 && st.lng === lng0 && st.extra.every((v, d) => v === extra0[d])) invalid('open path whose last point repeats the first', 'NON_CANONICAL');
|
|
680
|
+
if (closed) out.push(out[0].slice());
|
|
681
|
+
return out;
|
|
682
|
+
};
|
|
683
|
+
|
|
684
|
+
const polygon = (mode) => {
|
|
685
|
+
count(1);
|
|
686
|
+
let n = 1;
|
|
687
|
+
if (r.bit() === 0) {
|
|
688
|
+
n = r.bounded(4);
|
|
689
|
+
if (n === 1) invalid('ring count 1 written as count', 'NON_CANONICAL');
|
|
690
|
+
}
|
|
691
|
+
const rings = [];
|
|
692
|
+
for (let i = 0; i < n; i++) rings.push(path(mode, 1, true));
|
|
693
|
+
return rings;
|
|
694
|
+
};
|
|
695
|
+
|
|
696
|
+
const body = (t, depth) => {
|
|
697
|
+
count(1);
|
|
698
|
+
if (t === 0) {
|
|
699
|
+
if (r.bit() === 0) return { type: 'Point', coordinates: [] };
|
|
700
|
+
count(1);
|
|
701
|
+
return { type: 'Point', coordinates: position(true) };
|
|
702
|
+
}
|
|
703
|
+
if (t === 6) {
|
|
704
|
+
if (depth >= MAX_DEPTH) invalid('collection nesting exceeds 32', 'TOO_DEEP');
|
|
705
|
+
const n = r.bounded(4);
|
|
706
|
+
const geometries = [];
|
|
707
|
+
for (let i = 0; i < n; i++) {
|
|
708
|
+
const mt = r.read(3);
|
|
709
|
+
if (mt === 7) invalid('a later version of the format', 'UNSUPPORTED_VERSION');
|
|
710
|
+
geometries.push(body(mt, depth + 1));
|
|
711
|
+
}
|
|
712
|
+
return { type: 'GeometryCollection', geometries };
|
|
713
|
+
}
|
|
714
|
+
const md = r.mode();
|
|
715
|
+
choice(md, 'modes');
|
|
716
|
+
const before = st.steps;
|
|
717
|
+
let coordinates;
|
|
718
|
+
if (t === 1) coordinates = path(md, 0, true);
|
|
719
|
+
else if (t === 2) coordinates = polygon(md);
|
|
720
|
+
else if (t === 3) coordinates = path(md, 2, true);
|
|
721
|
+
else {
|
|
722
|
+
const n = r.bounded(4);
|
|
723
|
+
coordinates = [];
|
|
724
|
+
for (let i = 0; i < n; i++) coordinates.push(t === 4 ? path(md, 0, true) : polygon(md));
|
|
725
|
+
}
|
|
726
|
+
// A mode that predicted nothing must be 0.
|
|
727
|
+
if (md !== 0 && st.steps === before) invalid('mode on a geometry with no block-coded point', 'NON_CANONICAL');
|
|
728
|
+
return { type: TYPES[t], coordinates };
|
|
729
|
+
};
|
|
730
|
+
|
|
731
|
+
if (rec) rec.choices = { pred: extraPred.slice(), modes: [], k: [] };
|
|
732
|
+
let res;
|
|
733
|
+
if (expectLine) {
|
|
734
|
+
count(1); // the line is a geometry like any other
|
|
735
|
+
const md = r.mode();
|
|
736
|
+
choice(md, 'modes');
|
|
737
|
+
res = path(md, 0, false);
|
|
738
|
+
if (md !== 0 && st.steps === 0) invalid('mode on a geometry with no block-coded point', 'NON_CANONICAL');
|
|
739
|
+
} else {
|
|
740
|
+
res = body(type, 0);
|
|
741
|
+
}
|
|
742
|
+
// Options that this string didn't need are another spelling of it.
|
|
743
|
+
if (o.wide && !st.needWide) invalid('wide without a coordinate that needs it', 'NON_CANONICAL');
|
|
744
|
+
if (o.open && !st.openRing) invalid('openRings without an open ring', 'NON_CANONICAL');
|
|
745
|
+
if (o.z && !st.started) invalid('Z or M without a position', 'NON_CANONICAL');
|
|
746
|
+
if (st.steps === 0 && extraPred.some((p) => p === 1)) invalid('extra predictor without a block-coded point', 'NON_CANONICAL');
|
|
747
|
+
// The header and the body end here. What's left is padding, then the check.
|
|
748
|
+
const bits = r.pos;
|
|
749
|
+
r.finish();
|
|
750
|
+
if (rec) {
|
|
751
|
+
Object.assign(rec, { type: TYPES[type], precision: prec, checksum: o.check === 2 ? true : o.check === 1 ? 'short' : false, wide: !!o.wide, openRings: !!o.open, bits });
|
|
752
|
+
if (o.z) rec.zPrecision = extraP[0];
|
|
753
|
+
if (o.m) rec.mPrecision = extraP[1];
|
|
754
|
+
}
|
|
755
|
+
return res;
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
// The options of decode, decodeLine, inspect and canonical: nothing, or an
|
|
759
|
+
// object.
|
|
760
|
+
// - checksum says that the string must carry a check: true, or 'short' so
|
|
761
|
+
// that one options object can go to encode and to decode. Either kind of
|
|
762
|
+
// check satisfies it.
|
|
763
|
+
// - maxLength is the most characters a string may have, or the most bytes a
|
|
764
|
+
// binary value may have, and maxPositions the most it may put in the
|
|
765
|
+
// result. Each is an integer from 0 up, or Infinity.
|
|
766
|
+
function decodeOptions(options, binary) {
|
|
767
|
+
const out = { needCheck: false, maxLength: DEFAULT_MAX_LENGTH, maxPositions: DEFAULT_MAX_POSITIONS };
|
|
768
|
+
if (options == null) return out;
|
|
769
|
+
if (typeof options !== 'object') throw new TypeError('options must be an object');
|
|
770
|
+
for (const key of ['maxLength', 'maxPositions']) {
|
|
771
|
+
const v = options[key];
|
|
772
|
+
if (v == null) continue;
|
|
773
|
+
if (typeof v !== 'number' || !(v >= 0) || (v !== Infinity && !Number.isInteger(v))) throw new RangeError('maxLength and maxPositions must be integers from 0 up, or Infinity');
|
|
774
|
+
out[key] = v;
|
|
775
|
+
}
|
|
776
|
+
out.maxLength = Math.min(out.maxLength, binary ? MAX_BYTES : MAX_LENGTH);
|
|
777
|
+
out.needCheck = checkKind(options.checksum) !== 0;
|
|
778
|
+
return out;
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
export function decode(str, options) { return decodeCore(str, false, null, options); }
|
|
782
|
+
export function decodeLine(str, options) { return decodeCore(str, true, null, options); }
|
|
783
|
+
|
|
784
|
+
// The header fields of a string, its coding choices (the mode of each
|
|
785
|
+
// geometry and every Rice parameter, in the order they're read, and the
|
|
786
|
+
// predictor bit of each extra coordinate) and its geometry.
|
|
787
|
+
export function inspect(str, options) {
|
|
788
|
+
const rec = {};
|
|
789
|
+
rec.geometry = decodeCore(str, false, rec, options);
|
|
790
|
+
return rec;
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
// ---------------------------------------------------------------- the binary form (SPEC.md section 23)
|
|
794
|
+
|
|
795
|
+
export function decodeValue(bytes, options) { return decodeCore(bytes, false, null, options, true); }
|
|
796
|
+
export function decodeLineValue(bytes, options) { return decodeCore(bytes, true, null, options, true); }
|
|
797
|
+
export function inspectValue(bytes, options) {
|
|
798
|
+
const rec = {};
|
|
799
|
+
rec.geometry = decodeCore(bytes, false, rec, options, true);
|
|
800
|
+
return rec;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
// The check of a binary value: the 16 most significant bits of the CRC-32C
|
|
804
|
+
// of the bytes before it in 2 bytes (kind 1), or all 32 in 4 (kind 2), most
|
|
805
|
+
// significant byte first. `payload` is how many bytes come before it.
|
|
806
|
+
function putCheck(bytes, payload, kind) {
|
|
807
|
+
const crc = crc32c(bytes, payload);
|
|
808
|
+
bytes[payload] = crc >>> 24;
|
|
809
|
+
bytes[payload + 1] = (crc >>> 16) & 255;
|
|
810
|
+
if (kind === 2) { bytes[payload + 2] = (crc >>> 8) & 255; bytes[payload + 3] = crc & 255; }
|
|
811
|
+
}
|
|
812
|
+
const checkBytes = (kind) => (kind === 2 ? 4 : kind === 1 ? 2 : 0);
|
|
813
|
+
const kindOf = (checksum) => (checksum === true ? 2 : checksum === 'short' ? 1 : 0);
|
|
814
|
+
|
|
815
|
+
// The binary value for a string (SPEC.md section 23.6). The string is
|
|
816
|
+
// decoded first, with decode's options, and what decode refuses this refuses
|
|
817
|
+
// with the same code: only a decoder knows where the geometry of a string
|
|
818
|
+
// ends, and the number of bytes depends on it. Then the header and body bits
|
|
819
|
+
// are written 8 to a byte, and the check is computed again, over the bytes.
|
|
820
|
+
export function toValue(str, options) {
|
|
821
|
+
const rec = {};
|
|
822
|
+
decodeCore(str, false, rec, options);
|
|
823
|
+
const kind = kindOf(rec.checksum), payload = Math.ceil(rec.bits / 8);
|
|
824
|
+
const out = new Uint8Array(payload + checkBytes(kind));
|
|
825
|
+
for (let i = 0; i < rec.bits; i++) {
|
|
826
|
+
if ((VALUE[str.charCodeAt(Math.floor(i / 6))] >> (5 - (i % 6))) & 1) out[i >> 3] |= 128 >> (i & 7);
|
|
827
|
+
}
|
|
828
|
+
if (kind) putCheck(out, payload, kind);
|
|
829
|
+
return out;
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
// The string for a binary value: the same the other way.
|
|
833
|
+
export function fromValue(bytes, options) {
|
|
834
|
+
const rec = {};
|
|
835
|
+
decodeCore(bytes, false, rec, options, true);
|
|
836
|
+
const kind = kindOf(rec.checksum);
|
|
837
|
+
let out = '';
|
|
838
|
+
for (let i = 0; i < rec.bits; i += 6) {
|
|
839
|
+
let v = 0;
|
|
840
|
+
for (let b = i; b < i + 6; b++) v = v * 2 + (b < rec.bits ? (bytes[b >> 3] >> (7 - (b & 7))) & 1 : 0);
|
|
841
|
+
out += ALPHABET[v];
|
|
842
|
+
}
|
|
843
|
+
return kind ? withCheck(out, kind) : out;
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
// The canonical binary value for what a binary value decodes to: the binary
|
|
847
|
+
// form of canonical()'s string, with the same options.
|
|
848
|
+
export function canonicalValue(bytes, options) {
|
|
849
|
+
if (!isBytes(bytes)) throw new TypeError('Expected a Uint8Array');
|
|
850
|
+
const to = options == null ? null : options.to;
|
|
851
|
+
if (to == null) {
|
|
852
|
+
const h = inspectValue(bytes, options);
|
|
853
|
+
return encodeValue(h.geometry, { precision: h.precision, zPrecision: h.zPrecision, mPrecision: h.mPrecision, checksum: h.checksum });
|
|
854
|
+
}
|
|
855
|
+
const target = typeof to === 'object' ? { precision: to.precision, zPrecision: to.zPrecision, mPrecision: to.mPrecision, checksum: to.checksum, favor: to.favor } : to;
|
|
856
|
+
decodeOptions(options, true);
|
|
857
|
+
encode({ type: 'Point', coordinates: [] }, target);
|
|
858
|
+
return encodeValue(decodeValue(bytes, options), target);
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
// The canonical string for what str decodes to.
|
|
862
|
+
//
|
|
863
|
+
// Without a target that's at str's own precisions and with its kind of
|
|
864
|
+
// check, and str is canonical when this returns str itself. Those settings
|
|
865
|
+
// are the sender's: the same geometry has another canonical string at each
|
|
866
|
+
// precision and with each kind of check.
|
|
867
|
+
//
|
|
868
|
+
// With options.to, a precision or the options of encode, nothing is taken
|
|
869
|
+
// from str but its geometry, and the result is encode(decode(str, options),
|
|
870
|
+
// to). That's the string to use as a key for strings from elsewhere: at a
|
|
871
|
+
// target the application fixes, one geometry has one string.
|
|
872
|
+
export function canonical(str, options) {
|
|
873
|
+
if (typeof str !== 'string') throw new TypeError('Expected a string');
|
|
874
|
+
const to = options == null ? null : options.to;
|
|
875
|
+
if (to == null) {
|
|
876
|
+
const h = inspect(str, options);
|
|
877
|
+
return encode(h.geometry, { precision: h.precision, zPrecision: h.zPrecision, mPrecision: h.mPrecision, checksum: h.checksum });
|
|
878
|
+
}
|
|
879
|
+
const target = typeof to === 'object' ? { precision: to.precision, zPrecision: to.zPrecision, mPrecision: to.mPrecision, checksum: to.checksum, favor: to.favor } : to;
|
|
880
|
+
// The target is judged first, by encoding nothing at it, so that a wrong
|
|
881
|
+
// one is the caller's RangeError whatever the string is.
|
|
882
|
+
decodeOptions(options);
|
|
883
|
+
encode({ type: 'Point', coordinates: [] }, target);
|
|
884
|
+
return encode(decode(str, options), target);
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
// ---------------------------------------------------------------- encoding
|
|
888
|
+
|
|
889
|
+
class Writer {
|
|
890
|
+
constructor(trace) {
|
|
891
|
+
this.bits = [];
|
|
892
|
+
this.trace = trace || null;
|
|
893
|
+
}
|
|
894
|
+
put(n, v, label) {
|
|
895
|
+
let s = '';
|
|
896
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
897
|
+
const b = Math.floor(v / 2 ** i) % 2;
|
|
898
|
+
this.bits.push(b);
|
|
899
|
+
if (this.trace) s += b;
|
|
900
|
+
}
|
|
901
|
+
if (this.trace) this.trace(label || '', s);
|
|
902
|
+
}
|
|
903
|
+
unary(c, label) {
|
|
904
|
+
let s = '';
|
|
905
|
+
for (let i = 0; i < c; i++) { this.bits.push(0); if (this.trace) s += '0'; }
|
|
906
|
+
this.bits.push(1);
|
|
907
|
+
if (this.trace) this.trace(label || '', s + '1');
|
|
908
|
+
}
|
|
909
|
+
count(n, label) {
|
|
910
|
+
if (n > MAX_COUNT) throw new RangeError('Count exceeds maximum');
|
|
911
|
+
const z = bitLength((n >>> 3) + 1) - 1;
|
|
912
|
+
this.put(2 * z + 4, n + 8, label);
|
|
913
|
+
}
|
|
914
|
+
sized(z, label) {
|
|
915
|
+
const n = z ? bitLength(z) : 0;
|
|
916
|
+
this.put(6, n, label ? label + ' length' : null);
|
|
917
|
+
if (n) this.put(n, z, label ? label + ' bits' : null);
|
|
918
|
+
}
|
|
919
|
+
// The long form writes -1 as max + 1 and -2 as max + 2.
|
|
920
|
+
param(k, prev, width, max, label) {
|
|
921
|
+
const dz = zigBig(k - prev);
|
|
922
|
+
if (dz < 8) {
|
|
923
|
+
this.unary(dz, label);
|
|
924
|
+
} else {
|
|
925
|
+
this.put(8, 0, label ? label + ' (far)' : null);
|
|
926
|
+
this.put(width, k < 0 ? max - k : k, label ? label + ' value' : null);
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
pair(z1, z2, k1, k2, label) {
|
|
930
|
+
const p1 = 2 ** k1, p2 = 2 ** k2;
|
|
931
|
+
const q1 = Math.floor(z1 / p1), q2 = Math.floor(z2 / p2);
|
|
932
|
+
const f1 = z1 - q1 * p1, f2 = z2 - q2 * p2;
|
|
933
|
+
let c1 = q1, n1 = 0, e1 = 0;
|
|
934
|
+
if (q1 >= 6) { const v = q1 - 2; n1 = bitLength(v) - 1; c1 = n1 + 4; e1 = v - 2 ** n1; }
|
|
935
|
+
let c2 = q2, n2 = 0, e2 = 0;
|
|
936
|
+
if (q2 >= 6) { const v = q2 - 2; n2 = bitLength(v) - 1; c2 = n2 + 4; e2 = v - 2 ** n2; }
|
|
937
|
+
this.unary(c1, label ? label + ': c1' : null);
|
|
938
|
+
this.unary(c2, label ? label + ': c2' : null);
|
|
939
|
+
if (k1) this.put(k1, f1, label ? label + ': f1' : null);
|
|
940
|
+
if (k2) this.put(k2, f2, label ? label + ': f2' : null);
|
|
941
|
+
if (n1) this.put(n1, e1, label ? label + ': e1' : null);
|
|
942
|
+
if (n2) this.put(n2, e2, label ? label + ': e2' : null);
|
|
943
|
+
}
|
|
944
|
+
single(z, k, label) {
|
|
945
|
+
const p = 2 ** k;
|
|
946
|
+
const q = Math.floor(z / p), f = z - q * p;
|
|
947
|
+
let c = q, n = 0, e = 0;
|
|
948
|
+
if (q >= 6) { const v = q - 2; n = bitLength(v) - 1; c = n + 4; e = v - 2 ** n; }
|
|
949
|
+
this.unary(c, label ? label + ': c' : null);
|
|
950
|
+
if (k) this.put(k, f, label ? label + ': f' : null);
|
|
951
|
+
if (n) this.put(n, e, label ? label + ': e' : null);
|
|
952
|
+
}
|
|
953
|
+
mode(m, label) {
|
|
954
|
+
const map = [[2, 0], [2, 1], [2, 2], [3, 6], [4, 14], [4, 15]];
|
|
955
|
+
this.put(map[m][0], map[m][1], label);
|
|
956
|
+
}
|
|
957
|
+
toString() {
|
|
958
|
+
let out = '';
|
|
959
|
+
for (let i = 0; i < this.bits.length; i += 6) {
|
|
960
|
+
let v = 0;
|
|
961
|
+
for (let b = 0; b < 6; b++) v = (v << 1) | (this.bits[i + b] || 0);
|
|
962
|
+
out += ALPHABET[v];
|
|
963
|
+
}
|
|
964
|
+
return out;
|
|
965
|
+
}
|
|
966
|
+
// The bits 8 to a byte, with room after them for a check of `extra` bytes.
|
|
967
|
+
toValue(extra) {
|
|
968
|
+
const out = new Uint8Array(Math.ceil(this.bits.length / 8) + extra);
|
|
969
|
+
for (let i = 0; i < this.bits.length; i++) if (this.bits[i]) out[i >> 3] |= 128 >> (i & 7);
|
|
970
|
+
return out;
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
// A string with its check: the 12 most significant bits of the CRC-32C of
|
|
975
|
+
// its characters in 2 characters (kind 1), or all 32 and 4 zero bits in 6.
|
|
976
|
+
function withCheck(out, kind) {
|
|
977
|
+
const c = crc32c(out);
|
|
978
|
+
out += ALPHABET[c >>> 26] + ALPHABET[(c >>> 20) & 63];
|
|
979
|
+
if (kind === 2) out += ALPHABET[(c >>> 14) & 63] + ALPHABET[(c >>> 8) & 63] + ALPHABET[(c >>> 2) & 63] + ALPHABET[(c << 4) & 63];
|
|
980
|
+
return out;
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
// The bits of a Rice-T6 value z with parameter k, and of a parameter k after prev.
|
|
984
|
+
const valCost = (z, k) => {
|
|
985
|
+
const q = Math.floor(z / 2 ** k);
|
|
986
|
+
if (q < 6) return q + 1 + k;
|
|
987
|
+
const n = bitLength(q - 2) - 1;
|
|
988
|
+
return 2 * n + 5 + k;
|
|
989
|
+
};
|
|
990
|
+
const paramCost = (k, prev, far) => {
|
|
991
|
+
const dz = zigBig(k - prev);
|
|
992
|
+
return dz < 8 ? dz + 1 : far;
|
|
993
|
+
};
|
|
994
|
+
const MODE_BITS = [2, 2, 2, 3, 4, 4];
|
|
995
|
+
|
|
996
|
+
// The canonical parameter of a block: the cheapest of every parameter the
|
|
997
|
+
// block can use, and the smallest of those on a tie. `kind` is 'paired'
|
|
998
|
+
// (vals holds every z1, then every z2), 'k1', or 'zeroable' for a k2 or an
|
|
999
|
+
// extra coordinate, which can be -1 when every value is 0.
|
|
1000
|
+
function bestK(vals, prev, kMax, far, kind) {
|
|
1001
|
+
const n = vals.length;
|
|
1002
|
+
const allZero = vals.every((v) => v === 0);
|
|
1003
|
+
let best = Infinity, bk = 0;
|
|
1004
|
+
if (kind === 'paired' && allZero) { best = paramCost(-2, prev, far); bk = -2; }
|
|
1005
|
+
if (kind === 'paired' && !allZero) {
|
|
1006
|
+
// Sparse: a mask bit per point, then the points that aren't (0, 0).
|
|
1007
|
+
const cnt = n >> 1;
|
|
1008
|
+
let c = paramCost(-1, prev, far) + cnt;
|
|
1009
|
+
for (let i = 0; i < cnt; i++) {
|
|
1010
|
+
const a = vals[i], b = vals[cnt + i];
|
|
1011
|
+
if (a === 0 && b === 0) continue;
|
|
1012
|
+
c += valCost(a, 0) + valCost(a === 0 ? b - 1 : b, 0);
|
|
1013
|
+
}
|
|
1014
|
+
best = c; bk = -1;
|
|
1015
|
+
}
|
|
1016
|
+
if (kind === 'zeroable' && allZero) { best = paramCost(-1, prev, far); bk = -1; }
|
|
1017
|
+
for (let k = 0; k <= kMax; k++) {
|
|
1018
|
+
let c = paramCost(k, prev, far);
|
|
1019
|
+
for (let i = 0; i < n && c < best; i++) c += valCost(vals[i], k);
|
|
1020
|
+
if (c < best) { best = c; bk = k; }
|
|
1021
|
+
}
|
|
1022
|
+
return [bk, best];
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
// The values a mode writes for the m - 1 steps of a path, or null when the
|
|
1026
|
+
// mode can't write them: a value of 2^53 or more in a wide string, or, for a
|
|
1027
|
+
// split mode in a wide string, a step outside 32 bits.
|
|
1028
|
+
function residuals(pts, m, closed, prec, mode, wide) {
|
|
1029
|
+
const z1 = [], z2 = [];
|
|
1030
|
+
if (mode === 0 || mode === 1 || mode === 4) {
|
|
1031
|
+
let va = 0, vb = 0;
|
|
1032
|
+
for (let i = 1; i < m; i++) {
|
|
1033
|
+
let da = pts[i][0] - pts[i - 1][0], db = pts[i][1] - pts[i - 1][1];
|
|
1034
|
+
if (!wide) { da = i32(da); db = i32(db); }
|
|
1035
|
+
const ra = mode === 0 ? da : (wide ? da - va : i32(da - va));
|
|
1036
|
+
const rb = mode === 0 ? db : (wide ? db - vb : i32(db - vb));
|
|
1037
|
+
if (mode === 1) { va = da; vb = db; }
|
|
1038
|
+
else if (mode === 4) {
|
|
1039
|
+
va = i === 1 ? da : (wide ? Math.floor((va + da) / 2) : (va + da) >> 1);
|
|
1040
|
+
vb = i === 1 ? db : (wide ? Math.floor((vb + db) / 2) : (vb + db) >> 1);
|
|
1041
|
+
}
|
|
1042
|
+
const za = wide ? zigBig(ra) : zig32(ra), zb = wide ? zigBig(rb) : zig32(rb);
|
|
1043
|
+
if (wide && (za >= 2 ** 53 || zb >= 2 ** 53)) return null;
|
|
1044
|
+
z1.push(za); z2.push(zb);
|
|
1045
|
+
}
|
|
1046
|
+
return { z1, z2, split: false };
|
|
1047
|
+
}
|
|
1048
|
+
const steps = [];
|
|
1049
|
+
for (let i = 1; i < m; i++) {
|
|
1050
|
+
const da = pts[i][0] - pts[i - 1][0], db = pts[i][1] - pts[i - 1][1];
|
|
1051
|
+
if (wide && !(fitsI32(da) && fitsI32(db))) return null;
|
|
1052
|
+
steps.push([i32(da), i32(db)]);
|
|
1053
|
+
}
|
|
1054
|
+
if (mode === 2 || mode === 5) {
|
|
1055
|
+
const st = slopeInit();
|
|
1056
|
+
for (let i = 1; i < m; i++) {
|
|
1057
|
+
const [da, db] = steps[i - 1];
|
|
1058
|
+
if (i === 1) {
|
|
1059
|
+
z1.push(zig32(da)); z2.push(zig32(db));
|
|
1060
|
+
slopeStep1(st, da, db);
|
|
1061
|
+
continue;
|
|
1062
|
+
}
|
|
1063
|
+
const dM = st.sw ? db : da, dm = st.sw ? da : db;
|
|
1064
|
+
const err = i32(dm - ((Math.imul(dM, st.s) + 2048) >> 12));
|
|
1065
|
+
if (mode === 5) z1.push(zig32(i32(dM - st.pM)));
|
|
1066
|
+
else z1.push(fold7(i32((dM ^ st.g) - st.g)));
|
|
1067
|
+
z2.push(zig32(err));
|
|
1068
|
+
slopeUpdate(st, dM, dm, err);
|
|
1069
|
+
}
|
|
1070
|
+
return { z1, z2, split: true, closingK2: false };
|
|
1071
|
+
}
|
|
1072
|
+
// mode === 3: ortho
|
|
1073
|
+
const st = orthoInit(pts[0][0], pts[0][1], prec);
|
|
1074
|
+
const closingK2 = closed === 1 && m >= 4;
|
|
1075
|
+
for (let i = 1; i < m; i++) {
|
|
1076
|
+
const [da, db] = steps[i - 1];
|
|
1077
|
+
if (i === 1) {
|
|
1078
|
+
z1.push(zig32(da)); z2.push(zig32(db));
|
|
1079
|
+
orthoStep1(st, da, db);
|
|
1080
|
+
continue;
|
|
1081
|
+
}
|
|
1082
|
+
if (closingK2 && i === m - 1) {
|
|
1083
|
+
const [pda, pdb] = orthoClosingPred(st, pts[i - 1][0], pts[i - 1][1], m);
|
|
1084
|
+
z1.push(zig32(i32(da - pda))); z2.push(zig32(i32(db - pdb)));
|
|
1085
|
+
continue;
|
|
1086
|
+
}
|
|
1087
|
+
const sw = st.nextV ? st.swV : st.swU, s = st.nextV ? st.sV : st.sU;
|
|
1088
|
+
const dM = sw ? db : da, dm = sw ? da : db;
|
|
1089
|
+
const err = i32(dm - ((Math.imul(dM, s) + 2048) >> 12));
|
|
1090
|
+
z1.push(zig32(dM)); z2.push(zig32(err));
|
|
1091
|
+
orthoUpdate(st, da, db, err);
|
|
1092
|
+
}
|
|
1093
|
+
return { z1, z2, split: true, closingK2 };
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
// The values of the block of cnt steps from step i that each parameter codes.
|
|
1097
|
+
function blockValues(res, n, i, cnt) {
|
|
1098
|
+
if (!res.split) return { both: [...res.z1.slice(i, i + cnt), ...res.z2.slice(i, i + cnt)] };
|
|
1099
|
+
const v1 = [], v2 = [];
|
|
1100
|
+
for (let j = 0; j < cnt; j++) {
|
|
1101
|
+
const idx = i + j;
|
|
1102
|
+
if (idx === 0) v1.push(res.z1[0], res.z2[0]);
|
|
1103
|
+
else if (res.closingK2 && idx === n - 1) v2.push(res.z1[idx], res.z2[idx]);
|
|
1104
|
+
else { v1.push(res.z1[idx]); v2.push(res.z2[idx]); }
|
|
1105
|
+
}
|
|
1106
|
+
return { v1, v2 };
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
// The checksum option: true is the full check, 'short' the short one, and
|
|
1110
|
+
// false or nothing is no check. Anything else is refused: a value like
|
|
1111
|
+
// 'none' must not turn a check on.
|
|
1112
|
+
const checkKind = (v) => {
|
|
1113
|
+
if (v == null || v === false) return 0;
|
|
1114
|
+
if (v === true) return 2;
|
|
1115
|
+
if (v === 'short') return 1;
|
|
1116
|
+
throw new RangeError("checksum must be true, false or 'short'");
|
|
1117
|
+
};
|
|
1118
|
+
|
|
1119
|
+
export function encode(geometry, options, trace) { return encodeCore(geometry, options, trace, false); }
|
|
1120
|
+
// The same geometry and options as a binary value: the same bits, 8 to a
|
|
1121
|
+
// byte, with the binary form's check (SPEC.md section 23).
|
|
1122
|
+
export function encodeValue(geometry, options, trace) { return encodeCore(geometry, options, trace, true); }
|
|
1123
|
+
|
|
1124
|
+
function encodeCore(geometry, options, trace, binary) {
|
|
1125
|
+
// An option that's left out (undefined or null) takes its default. One
|
|
1126
|
+
// that's given must be one of its values (SPEC.md section 16.2).
|
|
1127
|
+
let prec = 5, zp = null, mp = null, check = 0, forcedMode = null, replay = null, force = {};
|
|
1128
|
+
if (options != null && typeof options !== 'object') prec = options;
|
|
1129
|
+
else if (options != null) {
|
|
1130
|
+
if (options.precision != null) prec = options.precision;
|
|
1131
|
+
if (options.zPrecision != null) zp = options.zPrecision;
|
|
1132
|
+
if (options.mPrecision != null) mp = options.mPrecision;
|
|
1133
|
+
check = checkKind(options.checksum);
|
|
1134
|
+
if (options.favor != null && options.favor !== 'size') throw new RangeError("the reference encoder is the canonical one: favor can only be 'size'");
|
|
1135
|
+
if (options.mode != null) forcedMode = options.mode;
|
|
1136
|
+
if (options.choices != null) replay = { pred: options.choices.pred, modes: options.choices.modes, k: options.choices.k, mi: 0, at: 0 };
|
|
1137
|
+
if (options.force != null) force = options.force;
|
|
1138
|
+
}
|
|
1139
|
+
if (zp === null) zp = prec;
|
|
1140
|
+
if (mp === null) mp = prec;
|
|
1141
|
+
for (const p of [prec, zp, mp]) {
|
|
1142
|
+
if (!Number.isInteger(p) || p < 0 || p > 15) throw new RangeError('precision, zPrecision and mPrecision must be integers from 0 to 15');
|
|
1143
|
+
}
|
|
1144
|
+
if (forcedMode !== null && !(Number.isInteger(forcedMode) && forcedMode >= 0 && forcedMode <= 5)) throw new RangeError('mode must be an integer from 0 to 5');
|
|
1145
|
+
if (geometry != null && geometry.type === 'Feature') geometry = geometry.geometry;
|
|
1146
|
+
|
|
1147
|
+
const f = POW[prec], xf = [POW[zp], POW[mp]];
|
|
1148
|
+
let dims = 0, big = false, first = null, openRings = 0;
|
|
1149
|
+
|
|
1150
|
+
const quant = (x, scale) => {
|
|
1151
|
+
const v = x * scale;
|
|
1152
|
+
if (typeof x !== 'number' || !Number.isFinite(v)) throw new RangeError('Invalid coordinate');
|
|
1153
|
+
const r = v < 0 ? -Math.round(-v) : Math.round(v);
|
|
1154
|
+
if (!(r >= -LIMIT && r <= LIMIT)) throw new RangeError('Coordinate exceeds 2^50');
|
|
1155
|
+
return r + 0;
|
|
1156
|
+
};
|
|
1157
|
+
const prepPos = (c) => {
|
|
1158
|
+
if (c == null || !(c.length >= 2 && c.length <= 4)) throw new TypeError('Position must have 2 to 4 numbers');
|
|
1159
|
+
if (dims && dims !== c.length) throw new TypeError('Inconsistent position dimensions');
|
|
1160
|
+
dims = c.length;
|
|
1161
|
+
const q = [quant(c[1], f), quant(c[0], f)];
|
|
1162
|
+
for (let d = 2; d < dims; d++) q.push(quant(c[d], xf[d - 2]));
|
|
1163
|
+
if (!fitsI32(q[0]) || !fitsI32(q[1])) big = true;
|
|
1164
|
+
if (!first) first = q;
|
|
1165
|
+
return q;
|
|
1166
|
+
};
|
|
1167
|
+
const prepPath = (coords, kind) => {
|
|
1168
|
+
if (!Array.isArray(coords)) throw new TypeError('Expected array of positions');
|
|
1169
|
+
const pts = coords.map(prepPos), n = pts.length;
|
|
1170
|
+
const closed = kind !== 2 && n > 1 && !force.open && pts[0].every((v, i) => v === pts[n - 1][i]) ? 1 : 0;
|
|
1171
|
+
if (kind === 1 && !closed) openRings = 1;
|
|
1172
|
+
return { kind, pts, closed, m: n - closed };
|
|
1173
|
+
};
|
|
1174
|
+
const prep = (node, depth) => {
|
|
1175
|
+
const type = TYPES.indexOf(node == null ? node : node.type);
|
|
1176
|
+
if (type < 0) throw new TypeError('Expected a GeoJSON geometry');
|
|
1177
|
+
if (type === 6) {
|
|
1178
|
+
if (depth >= MAX_DEPTH) throw new RangeError('Collections nested too deep');
|
|
1179
|
+
if (!Array.isArray(node.geometries)) throw new TypeError('Expected geometries array');
|
|
1180
|
+
return { type, members: node.geometries.map((m) => prep(m, depth + 1)) };
|
|
1181
|
+
}
|
|
1182
|
+
const c = node.coordinates;
|
|
1183
|
+
if (!Array.isArray(c)) throw new TypeError('Expected coordinates array');
|
|
1184
|
+
if (type === 0) return { type, point: c.length ? prepPos(c) : null };
|
|
1185
|
+
if (type === 1 || type === 3) return { type, paths: [prepPath(c, type === 1 ? 0 : 2)] };
|
|
1186
|
+
if (type === 4) return { type, paths: c.map((l) => prepPath(l, 0)) };
|
|
1187
|
+
const prepRings = (p) => { if (!Array.isArray(p)) throw new TypeError('Expected rings array'); return p.map((r) => prepPath(r, 1)); };
|
|
1188
|
+
return type === 2 ? { type, polygons: [prepRings(c)] } : { type, polygons: c.map(prepRings) };
|
|
1189
|
+
};
|
|
1190
|
+
|
|
1191
|
+
const tree = prep(geometry, 0);
|
|
1192
|
+
if (force.openRings) openRings = 1;
|
|
1193
|
+
const nx = dims > 2 ? dims - 2 : 0;
|
|
1194
|
+
// Wide when the string can't be ordinary: the precision, an integer
|
|
1195
|
+
// outside 32 bits, or a first position that has no anchor code.
|
|
1196
|
+
const wide = prec > 7 || big || (first != null && (Math.abs(first[0]) > 90 * f || Math.abs(first[1]) > 180 * f)) || !!force.wide;
|
|
1197
|
+
const kMax = wide ? 52 : 24, width = wide ? 6 : 5, far = 8 + width;
|
|
1198
|
+
|
|
1199
|
+
// The predictor of each extra coordinate, over every path of the string:
|
|
1200
|
+
// second differences when their bit lengths add up to less.
|
|
1201
|
+
const allPaths = [];
|
|
1202
|
+
// One push for each path: a spread of every path at once overflowed the
|
|
1203
|
+
// stack from about 125,000 lines or rings.
|
|
1204
|
+
const collectPaths = (node) => {
|
|
1205
|
+
if (node.paths) for (const p of node.paths) allPaths.push(p);
|
|
1206
|
+
else if (node.polygons) for (const rings of node.polygons) for (const p of rings) allPaths.push(p);
|
|
1207
|
+
else if (node.members) for (const m of node.members) collectPaths(m);
|
|
1208
|
+
};
|
|
1209
|
+
collectPaths(tree);
|
|
1210
|
+
const extraPred = [];
|
|
1211
|
+
for (let d = 0; d < nx; d++) {
|
|
1212
|
+
let c0 = 0, c1 = 0, fits = true;
|
|
1213
|
+
for (const p of allPaths) {
|
|
1214
|
+
let pv = 0;
|
|
1215
|
+
for (let i = 1; i < p.m; i++) {
|
|
1216
|
+
const dv = p.pts[i][2 + d] - p.pts[i - 1][2 + d], z = zigBig(dv - pv);
|
|
1217
|
+
c0 += bitLength(zigBig(dv));
|
|
1218
|
+
c1 += bitLength(z);
|
|
1219
|
+
if (z >= 2 ** 53) fits = false;
|
|
1220
|
+
pv = dv;
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
extraPred.push(replay ? replay.pred[d] : fits && c1 < c0 ? 1 : 0);
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
const w = new Writer(trace);
|
|
1227
|
+
const optsBits = (wide ? 32 : 0) | (openRings ? 16 : 0) | (nx > 0 ? 8 : 0) | (nx > 1 ? 4 : 0) | check;
|
|
1228
|
+
if (!optsBits && (prec === 5 || prec === 6)) {
|
|
1229
|
+
const p6 = prec - 5;
|
|
1230
|
+
const t = tree.type;
|
|
1231
|
+
if (t === 0) w.put(4, 0 | p6, `header: Point, p${prec}`);
|
|
1232
|
+
else if (t === 1) w.put(4, 2 | p6, `header: LineString, p${prec}`);
|
|
1233
|
+
else if (t === 2) w.put(4, 4 | p6, `header: Polygon, p${prec}`);
|
|
1234
|
+
else if (t === 5) w.put(4, 6 | p6, `header: MultiPolygon, p${prec}`);
|
|
1235
|
+
else if (t === 3) w.put(5, 16 | p6, `header: MultiPoint, p${prec}`);
|
|
1236
|
+
else if (t === 4) w.put(5, 18 | p6, `header: MultiLineString, p${prec}`);
|
|
1237
|
+
else w.put(5, 20 | p6, `header: GeometryCollection, p${prec}`);
|
|
1238
|
+
} else if (!optsBits && prec === 7) {
|
|
1239
|
+
const t = tree.type;
|
|
1240
|
+
if (t === 1) w.put(5, 22, 'header: LineString, p7');
|
|
1241
|
+
else if (t === 2) w.put(5, 23, 'header: Polygon, p7');
|
|
1242
|
+
else {
|
|
1243
|
+
const m7 = { 0: 0, 3: 1, 4: 2, 5: 3, 6: 4 }[t];
|
|
1244
|
+
w.put(6, 48 | m7, `header: ${TYPES[t]}, p7`);
|
|
1245
|
+
}
|
|
1246
|
+
} else {
|
|
1247
|
+
w.put(4, 14, 'header: extended');
|
|
1248
|
+
w.put(3, tree.type, `type: ${TYPES[tree.type]}`);
|
|
1249
|
+
w.put(4, prec, `precision ${prec}`);
|
|
1250
|
+
w.put(6, optsBits, 'options');
|
|
1251
|
+
}
|
|
1252
|
+
if (nx > 0) { w.put(4, zp, `z precision ${zp}`); w.put(1, extraPred[0], `z pred ${extraPred[0]}`); }
|
|
1253
|
+
if (nx > 1) { w.put(4, mp, `m precision ${mp}`); w.put(1, extraPred[1], `m pred ${extraPred[1]}`); }
|
|
1254
|
+
|
|
1255
|
+
let started = false, lat = 0, lng = 0, k1 = KI[prec], k2 = 0;
|
|
1256
|
+
const xv = [0, 0], xk = [0, 0];
|
|
1257
|
+
|
|
1258
|
+
const putTrunc = (val, N, b, T, off, label) => {
|
|
1259
|
+
let u = val + off;
|
|
1260
|
+
if (u < 0) u += N;
|
|
1261
|
+
if (u >= N) u -= N;
|
|
1262
|
+
if (u < T) w.put(b, u, `${label} (short ${b}b)`);
|
|
1263
|
+
else w.put(b + 1, u + T, `${label} (long ${b + 1}b)`);
|
|
1264
|
+
};
|
|
1265
|
+
|
|
1266
|
+
const putPos = (q, label) => {
|
|
1267
|
+
if (!started) {
|
|
1268
|
+
started = true;
|
|
1269
|
+
if (wide) {
|
|
1270
|
+
w.sized(zigBig(q[0]), label + ' lat');
|
|
1271
|
+
w.sized(zigBig(q[1]), label + ' lng');
|
|
1272
|
+
} else {
|
|
1273
|
+
const anc = ANCHOR[prec];
|
|
1274
|
+
putTrunc(q[0], anc.NA, anc.bA, anc.TA, anc.offA, `${label} lat ${q[0]}`);
|
|
1275
|
+
putTrunc(q[1], anc.NB, anc.bB, anc.TB, anc.offB, `${label} lng ${q[1]}`);
|
|
1276
|
+
}
|
|
1277
|
+
} else {
|
|
1278
|
+
const a = wide ? zigBig(q[0] - lat) : zig32(i32(q[0] - lat));
|
|
1279
|
+
const b = wide ? zigBig(q[1] - lng) : zig32(i32(q[1] - lng));
|
|
1280
|
+
const L = Math.max(bitLength(a), bitLength(b));
|
|
1281
|
+
if (L === 0) w.put(1, 0, `${label}: same as last`);
|
|
1282
|
+
else {
|
|
1283
|
+
w.put(1, 1, `${label}: jump`);
|
|
1284
|
+
w.put(width, L - 1, `jump width ${L}`);
|
|
1285
|
+
w.put(L, a, `jump dlat zig=${a}`);
|
|
1286
|
+
w.put(L, b, `jump dlng zig=${b}`);
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
lat = q[0]; lng = q[1];
|
|
1290
|
+
for (let d = 0; d < nx; d++) {
|
|
1291
|
+
w.sized(zigBig(q[2 + d] - xv[d]), `${label} extra${d}`);
|
|
1292
|
+
xv[d] = q[2 + d];
|
|
1293
|
+
}
|
|
1294
|
+
};
|
|
1295
|
+
|
|
1296
|
+
// The parameters of one block, chosen after the carried ck1 and ck2, with
|
|
1297
|
+
// their bits. A parameter the block doesn't read is null.
|
|
1298
|
+
const chooseBlock = (res, n, i, cnt, ck1, ck2) => {
|
|
1299
|
+
const v = blockValues(res, n, i, cnt);
|
|
1300
|
+
if (!res.split) {
|
|
1301
|
+
const [k, c] = bestK(v.both, ck1, kMax, far, 'paired');
|
|
1302
|
+
return { rk1: k, rk2: k, bits: c };
|
|
1303
|
+
}
|
|
1304
|
+
let rk1 = null, rk2 = null, bits = 0;
|
|
1305
|
+
if (v.v1.length) { const [k, c] = bestK(v.v1, ck1, 24, 13, 'k1'); rk1 = k; bits += c; }
|
|
1306
|
+
if (v.v2.length) { const [k, c] = bestK(v.v2, ck2, 24, 13, 'zeroable'); rk2 = k; bits += c; }
|
|
1307
|
+
return { rk1, rk2, bits };
|
|
1308
|
+
};
|
|
1309
|
+
const carry = (rk, ck) => (rk === null ? ck : rk < 0 ? 0 : rk);
|
|
1310
|
+
|
|
1311
|
+
// What a mode costs for the paths of one geometry, from the parameters
|
|
1312
|
+
// carried so far, or null when it can't write them.
|
|
1313
|
+
const modeCost = (paths, mode) => {
|
|
1314
|
+
let c = MODE_BITS[mode], ck1 = k1, ck2 = k2;
|
|
1315
|
+
for (const p of paths) {
|
|
1316
|
+
if (p.m <= 1) continue;
|
|
1317
|
+
const res = residuals(p.pts, p.m, p.closed, prec, mode, wide);
|
|
1318
|
+
if (!res) return null;
|
|
1319
|
+
const n = p.m - 1;
|
|
1320
|
+
for (let i = 0; i < n; i += BLOCK) {
|
|
1321
|
+
const blk = chooseBlock(res, n, i, Math.min(BLOCK, n - i), ck1, ck2);
|
|
1322
|
+
c += blk.bits;
|
|
1323
|
+
ck1 = carry(blk.rk1, ck1);
|
|
1324
|
+
if (res.split) ck2 = carry(blk.rk2, ck2);
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
return c;
|
|
1328
|
+
};
|
|
1329
|
+
|
|
1330
|
+
// A geometry with no block-coded point has nothing to predict: mode 0.
|
|
1331
|
+
const chooseMode = (paths) => {
|
|
1332
|
+
if (replay) return replay.modes[replay.mi++];
|
|
1333
|
+
if (!paths.some((p) => p.m > 1)) return 0;
|
|
1334
|
+
if (forcedMode !== null) return forcedMode;
|
|
1335
|
+
let best = Infinity, bestM = 0;
|
|
1336
|
+
for (let m = 0; m <= 5; m++) {
|
|
1337
|
+
const c = modeCost(paths, m);
|
|
1338
|
+
if (c !== null && c < best) { best = c; bestM = m; }
|
|
1339
|
+
}
|
|
1340
|
+
return bestM;
|
|
1341
|
+
};
|
|
1342
|
+
|
|
1343
|
+
const putPath = (p, mode, label) => {
|
|
1344
|
+
if (p.kind === 0 || (p.kind === 1 && openRings)) w.put(1, p.closed, `${label} closed=${p.closed}`);
|
|
1345
|
+
w.count(p.m, `${label} count=${p.m}`);
|
|
1346
|
+
if (p.m === 0) return;
|
|
1347
|
+
putPos(p.pts[0], `${label} P0`);
|
|
1348
|
+
const ve = [0, 0];
|
|
1349
|
+
if (p.m > 1) {
|
|
1350
|
+
const res = residuals(p.pts, p.m, p.closed, prec, mode, wide), n = p.m - 1;
|
|
1351
|
+
if (!res) throw new RangeError(`mode ${mode} can't write this path`);
|
|
1352
|
+
for (let i = 0; i < n; i += BLOCK) {
|
|
1353
|
+
const cnt = Math.min(BLOCK, n - i);
|
|
1354
|
+
let { rk1, rk2 } = chooseBlock(res, n, i, cnt, k1, k2);
|
|
1355
|
+
if (replay) {
|
|
1356
|
+
if (!res.split) rk1 = rk2 = replay.k[replay.at++];
|
|
1357
|
+
else { if (rk1 !== null) rk1 = replay.k[replay.at++]; if (rk2 !== null) rk2 = replay.k[replay.at++]; }
|
|
1358
|
+
}
|
|
1359
|
+
if (!res.split) {
|
|
1360
|
+
w.param(rk1, k1, width, kMax, `k ${k1} -> ${rk1}`);
|
|
1361
|
+
k1 = rk1 < 0 ? 0 : rk1;
|
|
1362
|
+
if (rk1 === -1) {
|
|
1363
|
+
let mask = 0;
|
|
1364
|
+
for (let j = 0; j < cnt; j++) mask = mask * 2 + (res.z1[i + j] !== 0 || res.z2[i + j] !== 0 ? 1 : 0);
|
|
1365
|
+
w.put(cnt, mask, 'sparse mask');
|
|
1366
|
+
for (let j = 0; j < cnt; j++) {
|
|
1367
|
+
const idx = i + j, a = res.z1[idx], b = res.z2[idx];
|
|
1368
|
+
if (a === 0 && b === 0) continue;
|
|
1369
|
+
w.pair(a, a === 0 ? b - 1 : b, 0, 0, `pt ${idx + 1}`);
|
|
1370
|
+
}
|
|
1371
|
+
} else if (rk1 >= 0) {
|
|
1372
|
+
for (let j = 0; j < cnt; j++) {
|
|
1373
|
+
const idx = i + j;
|
|
1374
|
+
w.pair(res.z1[idx], res.z2[idx], rk1, rk1, `pt ${idx + 1}`);
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
} else {
|
|
1378
|
+
if (rk1 !== null) { w.param(rk1, k1, 5, 24, `k1 ${k1} -> ${rk1}`); k1 = rk1; }
|
|
1379
|
+
if (rk2 !== null) { w.param(rk2, k2, 5, 24, `k2 ${k2} -> ${rk2}`); k2 = rk2 < 0 ? 0 : rk2; }
|
|
1380
|
+
for (let j = 0; j < cnt; j++) {
|
|
1381
|
+
const idx = i + j;
|
|
1382
|
+
if (idx === 0) w.pair(res.z1[0], res.z2[0], rk1, rk1, 'pt 1');
|
|
1383
|
+
else if (res.closingK2 && idx === n - 1) {
|
|
1384
|
+
if (rk2 >= 0) w.pair(res.z1[idx], res.z2[idx], rk2, rk2, `pt ${idx + 1} (close)`);
|
|
1385
|
+
} else {
|
|
1386
|
+
if (rk2 < 0) w.single(res.z1[idx], rk1, `pt ${idx + 1} (z2=0)`);
|
|
1387
|
+
else w.pair(res.z1[idx], res.z2[idx], rk1, rk2, `pt ${idx + 1}`);
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
// Extra coords for this block
|
|
1392
|
+
for (let d = 0; d < nx; d++) {
|
|
1393
|
+
const ex = [];
|
|
1394
|
+
for (let j = 0; j < cnt; j++) {
|
|
1395
|
+
const idx = 1 + i + j;
|
|
1396
|
+
const dv = p.pts[idx][2 + d] - p.pts[idx - 1][2 + d];
|
|
1397
|
+
const rv = extraPred[d] ? dv - ve[d] : dv;
|
|
1398
|
+
ve[d] = dv;
|
|
1399
|
+
ex.push(zigBig(rv));
|
|
1400
|
+
xv[d] = p.pts[idx][2 + d];
|
|
1401
|
+
}
|
|
1402
|
+
let [ek] = bestK(ex, xk[d], 52, 14, 'zeroable');
|
|
1403
|
+
if (replay) ek = replay.k[replay.at++];
|
|
1404
|
+
w.param(ek, xk[d], 6, 52, `ke[${d}] ${xk[d]} -> ${ek}`);
|
|
1405
|
+
xk[d] = ek < 0 ? 0 : ek;
|
|
1406
|
+
if (ek >= 0) for (const v of ex) w.single(v, ek);
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
lat = p.pts[p.m - 1][0];
|
|
1411
|
+
lng = p.pts[p.m - 1][1];
|
|
1412
|
+
};
|
|
1413
|
+
|
|
1414
|
+
const putNode = (node) => {
|
|
1415
|
+
if (node.type === 0) {
|
|
1416
|
+
w.put(1, node.point ? 1 : 0, node.point ? 'point present' : 'empty point');
|
|
1417
|
+
if (node.point) putPos(node.point, 'Point');
|
|
1418
|
+
return;
|
|
1419
|
+
}
|
|
1420
|
+
if (node.type === 6) {
|
|
1421
|
+
w.count(node.members.length, `collection count=${node.members.length}`);
|
|
1422
|
+
for (const m of node.members) {
|
|
1423
|
+
w.put(3, m.type, `member type: ${TYPES[m.type]}`);
|
|
1424
|
+
putNode(m);
|
|
1425
|
+
}
|
|
1426
|
+
return;
|
|
1427
|
+
}
|
|
1428
|
+
const paths = node.paths || node.polygons.flat();
|
|
1429
|
+
const md = chooseMode(paths);
|
|
1430
|
+
w.mode(md, `mode ${md} (${MODE_NAMES[md]})`);
|
|
1431
|
+
if (node.paths) {
|
|
1432
|
+
if (node.type === 4) w.count(node.paths.length, `lines=${node.paths.length}`);
|
|
1433
|
+
node.paths.forEach((p, i) => putPath(p, md, `line ${i + 1}`));
|
|
1434
|
+
} else {
|
|
1435
|
+
if (node.type === 5) w.count(node.polygons.length, `polygons=${node.polygons.length}`);
|
|
1436
|
+
node.polygons.forEach((rings, pi) => {
|
|
1437
|
+
if (rings.length === 1) w.put(1, 1, `poly ${pi + 1}: single ring`);
|
|
1438
|
+
else { w.put(1, 0, `poly ${pi + 1}: multi ring`); w.count(rings.length, `rings=${rings.length}`); }
|
|
1439
|
+
rings.forEach((r, ri) => putPath(r, md, `p${pi + 1}r${ri + 1}`));
|
|
1440
|
+
});
|
|
1441
|
+
}
|
|
1442
|
+
};
|
|
1443
|
+
|
|
1444
|
+
putNode(tree);
|
|
1445
|
+
if (binary) {
|
|
1446
|
+
const out = w.toValue(checkBytes(check));
|
|
1447
|
+
if (check) putCheck(out, out.length - checkBytes(check), check);
|
|
1448
|
+
return out;
|
|
1449
|
+
}
|
|
1450
|
+
const out = w.toString();
|
|
1451
|
+
return check ? withCheck(out, check) : out;
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
const lineString = (points) => {
|
|
1455
|
+
if (!Array.isArray(points)) throw new TypeError('Expected array of [lat, lng] points');
|
|
1456
|
+
const coordinates = points.map((p) => {
|
|
1457
|
+
if (p == null || !(p.length >= 2)) throw new TypeError('Expected [lat, lng] point');
|
|
1458
|
+
return p.length === 2 ? [p[1], p[0]] : [p[1], p[0], ...p.slice(2)];
|
|
1459
|
+
});
|
|
1460
|
+
return { type: 'LineString', coordinates };
|
|
1461
|
+
};
|
|
1462
|
+
export function encodeLine(points, options) { return encode(lineString(points), options); }
|
|
1463
|
+
export function encodeLineValue(points, options) { return encodeValue(lineString(points), options); }
|