vendor: 1,208,619 bytes, lines 1-34299
1/** 2* MapLibre GL JS 3* @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v6.11.1/LICENSE.txt 4*/ 5//#region \0rolldown/runtime.js 6var __create = Object.create; 7var __defProp = Object.defineProperty; 8var __getOwnPropDesc = Object.getOwnPropertyDescriptor; 9var __getOwnPropNames = Object.getOwnPropertyNames; 10var __getProtoOf = Object.getPrototypeOf; 11var __hasOwnProp = Object.prototype.hasOwnProperty; 12var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports); 13var __copyProps = (to, from, except, desc) => { 14 if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { 15 key = keys[i]; 16 if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { 17 get: ((k) => from[k]).bind(null, key), 18 enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable 19 }); 20 } 21 return to; 22}; 23var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", { 24 value: mod, 25 enumerable: true 26}) : target, mod)); 27//#endregion 28//#region node_modules/@mapbox/point-geometry/index.js 29/** 30* A standalone point geometry with useful accessor, comparison, and 31* modification methods. 32* 33* @class 34* @param {number} x the x-coordinate. This could be longitude or screen pixels, or any other sort of unit. 35* @param {number} y the y-coordinate. This could be latitude or screen pixels, or any other sort of unit. 36* 37* @example 38* const point = new Point(-77, 38); 39*/ 40function Point(x, y) { 41 this.x = x; 42 this.y = y; 43} 44Point.prototype = { 45 /** 46 * Clone this point, returning a new point that can be modified 47 * without affecting the old one. 48 * @return {Point} the clone 49 */ 50 clone() { 51 return new Point(this.x, this.y); 52 }, 53 /** 54 * Add this point's x & y coordinates to another point, 55 * yielding a new point. 56 * @param {Point} p the other point 57 * @return {Point} output point 58 */ 59 add(p) { 60 return this.clone()._add(p); 61 }, 62 /** 63 * Subtract this point's x & y coordinates to from point, 64 * yielding a new point. 65 * @param {Point} p the other point 66 * @return {Point} output point 67 */ 68 sub(p) { 69 return this.clone()._sub(p); 70 }, 71 /** 72 * Multiply this point's x & y coordinates by point, 73 * yielding a new point. 74 * @param {Point} p the other point 75 * @return {Point} output point 76 */ 77 multByPoint(p) { 78 return this.clone()._multByPoint(p); 79 }, 80 /** 81 * Divide this point's x & y coordinates by point, 82 * yielding a new point. 83 * @param {Point} p the other point 84 * @return {Point} output point 85 */ 86 divByPoint(p) { 87 return this.clone()._divByPoint(p); 88 }, 89 /** 90 * Multiply this point's x & y coordinates by a factor, 91 * yielding a new point. 92 * @param {number} k factor 93 * @return {Point} output point 94 */ 95 mult(k) { 96 return this.clone()._mult(k); 97 }, 98 /** 99 * Divide this point's x & y coordinates by a factor, 100 * yielding a new point. 101 * @param {number} k factor 102 * @return {Point} output point 103 */ 104 div(k) { 105 return this.clone()._div(k); 106 }, 107 /** 108 * Rotate this point around the 0, 0 origin by an angle a, 109 * given in radians 110 * @param {number} a angle to rotate around, in radians 111 * @return {Point} output point 112 */ 113 rotate(a) { 114 return this.clone()._rotate(a); 115 }, 116 /** 117 * Rotate this point around p point by an angle a, 118 * given in radians 119 * @param {number} a angle to rotate around, in radians 120 * @param {Point} p Point to rotate around 121 * @return {Point} output point 122 */ 123 rotateAround(a, p) { 124 return this.clone()._rotateAround(a, p); 125 }, 126 /** 127 * Multiply this point by a 4x1 transformation matrix 128 * @param {[number, number, number, number]} m transformation matrix 129 * @return {Point} output point 130 */ 131 matMult(m) { 132 return this.clone()._matMult(m); 133 }, 134 /** 135 * Calculate this point but as a unit vector from 0, 0, meaning 136 * that the distance from the resulting point to the 0, 0 137 * coordinate will be equal to 1 and the angle from the resulting 138 * point to the 0, 0 coordinate will be the same as before. 139 * @return {Point} unit vector point 140 */ 141 unit() { 142 return this.clone()._unit(); 143 }, 144 /** 145 * Compute a perpendicular point, where the new y coordinate 146 * is the old x coordinate and the new x coordinate is the old y 147 * coordinate multiplied by -1 148 * @return {Point} perpendicular point 149 */ 150 perp() { 151 return this.clone()._perp(); 152 }, 153 /** 154 * Return a version of this point with the x & y coordinates 155 * rounded to integers. 156 * @return {Point} rounded point 157 */ 158 round() { 159 return this.clone()._round(); 160 }, 161 /** 162 * Return the magnitude of this point: this is the Euclidean 163 * distance from the 0, 0 coordinate to this point's x and y 164 * coordinates. 165 * @return {number} magnitude 166 */ 167 mag() { 168 return Math.sqrt(this.x * this.x + this.y * this.y); 169 }, 170 /** 171 * Judge whether this point is equal to another point, returning 172 * true or false. 173 * @param {Point} other the other point 174 * @return {boolean} whether the points are equal 175 */ 176 equals(other) { 177 return this.x === other.x && this.y === other.y; 178 }, 179 /** 180 * Calculate the distance from this point to another point 181 * @param {Point} p the other point 182 * @return {number} distance 183 */ 184 dist(p) { 185 return Math.sqrt(this.distSqr(p)); 186 }, 187 /** 188 * Calculate the distance from this point to another point, 189 * without the square root step. Useful if you're comparing 190 * relative distances. 191 * @param {Point} p the other point 192 * @return {number} distance 193 */ 194 distSqr(p) { 195 const dx = p.x - this.x, dy = p.y - this.y; 196 return dx * dx + dy * dy; 197 }, 198 /** 199 * Get the angle from the 0, 0 coordinate to this point, in radians 200 * coordinates. 201 * @return {number} angle 202 */ 203 angle() { 204 return Math.atan2(this.y, this.x); 205 }, 206 /** 207 * Get the angle from this point to another point, in radians 208 * @param {Point} b the other point 209 * @return {number} angle 210 */ 211 angleTo(b) { 212 return Math.atan2(this.y - b.y, this.x - b.x); 213 }, 214 /** 215 * Get the angle between this point and another point, in radians 216 * @param {Point} b the other point 217 * @return {number} angle 218 */ 219 angleWith(b) { 220 return this.angleWithSep(b.x, b.y); 221 }, 222 /** 223 * Find the angle of the two vectors, solving the formula for 224 * the cross product a x b = |a||b|sin(θ) for θ. 225 * @param {number} x the x-coordinate 226 * @param {number} y the y-coordinate 227 * @return {number} the angle in radians 228 */ 229 angleWithSep(x, y) { 230 return Math.atan2(this.x * y - this.y * x, this.x * x + this.y * y); 231 }, 232 /** @param {[number, number, number, number]} m */ 233 _matMult(m) { 234 const x = m[0] * this.x + m[1] * this.y, y = m[2] * this.x + m[3] * this.y; 235 this.x = x; 236 this.y = y; 237 return this; 238 }, 239 /** @param {Point} p */ 240 _add(p) { 241 this.x += p.x; 242 this.y += p.y; 243 return this; 244 }, 245 /** @param {Point} p */ 246 _sub(p) { 247 this.x -= p.x; 248 this.y -= p.y; 249 return this; 250 }, 251 /** @param {number} k */ 252 _mult(k) { 253 this.x *= k; 254 this.y *= k; 255 return this; 256 }, 257 /** @param {number} k */ 258 _div(k) { 259 this.x /= k; 260 this.y /= k; 261 return this; 262 }, 263 /** @param {Point} p */ 264 _multByPoint(p) { 265 this.x *= p.x; 266 this.y *= p.y; 267 return this; 268 }, 269 /** @param {Point} p */ 270 _divByPoint(p) { 271 this.x /= p.x; 272 this.y /= p.y; 273 return this; 274 }, 275 _unit() { 276 this._div(this.mag()); 277 return this; 278 }, 279 _perp() { 280 const y = this.y; 281 this.y = this.x; 282 this.x = -y; 283 return this; 284 }, 285 /** @param {number} angle */ 286 _rotate(angle) { 287 const cos = Math.cos(angle), sin = Math.sin(angle), x = cos * this.x - sin * this.y, y = sin * this.x + cos * this.y; 288 this.x = x; 289 this.y = y; 290 return this; 291 }, 292 /** 293 * @param {number} angle 294 * @param {Point} p 295 */ 296 _rotateAround(angle, p) { 297 const cos = Math.cos(angle), sin = Math.sin(angle), x = p.x + cos * (this.x - p.x) - sin * (this.y - p.y), y = p.y + sin * (this.x - p.x) + cos * (this.y - p.y); 298 this.x = x; 299 this.y = y; 300 return this; 301 }, 302 _round() { 303 this.x = Math.round(this.x); 304 this.y = Math.round(this.y); 305 return this; 306 }, 307 constructor: Point 308}; 309/** 310* Construct a point from an array if necessary, otherwise if the input 311* is already a Point, return it unchanged. 312* @param {Point | [number, number] | {x: number, y: number}} p input value 313* @return {Point} constructed point. 314* @example 315* // this 316* var point = Point.convert([0, 1]); 317* // is equivalent to 318* var point = new Point(0, 1); 319*/ 320Point.convert = function(p) { 321 if (p instanceof Point) return p; 322 if (Array.isArray(p)) return new Point(+p[0], +p[1]); 323 if (p.x !== void 0 && p.y !== void 0) return new Point(+p.x, +p.y); 324 throw new Error("Expected [x, y] or {x, y} point format"); 325}; 326//#endregion 327//#region node_modules/@mapbox/unitbezier/index.js 328function unitBezier$1(p1x, p1y, p2x, p2y) { 329 const cx = 3 * p1x; 330 const bx = 3 * (p2x - p1x) - cx; 331 const ax = 1 - cx - bx; 332 const cy = 3 * p1y; 333 const by = 3 * (p2y - p1y) - cy; 334 const ay = 1 - cy - by; 335 return function solve(x, epsilon = 1e-6) { 336 if (x <= 0) return 0; 337 if (x >= 1) return 1; 338 let t = x; 339 for (let i = 0; i < 8; i++) { 340 const x2 = ((ax * t + bx) * t + cx) * t - x; 341 if (Math.abs(x2) < epsilon) return ((ay * t + by) * t + cy) * t; 342 const d2 = (3 * ax * t + 2 * bx) * t + cx; 343 if (Math.abs(d2) < 1e-6) break; 344 t -= x2 / d2; 345 } 346 let t0 = 0; 347 let t1 = 1; 348 t = x; 349 for (let i = 0; i < 20; i++) { 350 const x2 = ((ax * t + bx) * t + cx) * t; 351 if (Math.abs(x2 - x) < epsilon) break; 352 if (x > x2) t0 = t; 353 else t1 = t; 354 t = (t0 + t1) * .5; 355 } 356 return ((ay * t + by) * t + cy) * t; 357 }; 358} 359//#endregion 360//#region src/util/offscreen_canvas_supported.ts 361let supportsOffscreenCanvas; 362/** 363* @returns true if the browser can rasterise into an `OffscreenCanvas`, false otherwise. 364* 365* The browser is probed once and the answer cached. The `getContext` result has to be coerced to a 366* boolean for that: it is null when there is no 2d context, and `??=` reads a cached null as 367* "not probed yet". 368*/ 369function offscreenCanvasSupported() { 370 supportsOffscreenCanvas ??= typeof OffscreenCanvas !== "undefined" && !!new OffscreenCanvas(1, 1).getContext("2d") && typeof createImageBitmap === "function"; 371 return supportsOffscreenCanvas; 372} 373//#endregion 374//#region src/util/offscreen_canvas_distorted.ts 375let offscreenCanvasDistorted; 376/** 377* Some browsers don't return the exact pixels from a canvas to prevent user fingerprinting (see #3185). 378* This function writes pixels to an OffscreenCanvas and reads them back using getImageData, returning false 379* if they don't match. 380* 381* @returns true if the browser supports OffscreenCanvas but it distorts getImageData results, false otherwise. 382*/ 383function isOffscreenCanvasDistorted() { 384 if (offscreenCanvasDistorted == null) { 385 offscreenCanvasDistorted = false; 386 if (offscreenCanvasSupported()) { 387 const size = 5; 388 const context = new OffscreenCanvas(size, size).getContext("2d", { willReadFrequently: true }); 389 if (context) { 390 for (let i = 0; i < 25; i++) { 391 const base = i * 4; 392 context.fillStyle = `rgb(${base},${base + 1},${base + 2})`; 393 context.fillRect(i % size, Math.floor(i / size), 1, 1); 394 } 395 const data = context.getImageData(0, 0, size, size).data; 396 for (let i = 0; i < 100; i++) if (i % 4 !== 3 && data[i] !== i) { 397 offscreenCanvasDistorted = true; 398 break; 399 } 400 } 401 } 402 } 403 return offscreenCanvasDistorted || false; 404} 405var ARRAY_TYPE = typeof Float32Array !== "undefined" ? Float32Array : Array; 406/** 407* 2x2 Matrix 408* @module mat2 409*/ 410/** 411* Creates a new identity mat2 412* 413* @returns {mat2} a new 2x2 matrix 414*/ 415function create$8() { 416 var out = new ARRAY_TYPE(4); 417 if (ARRAY_TYPE != Float32Array) { 418 out[1] = 0; 419 out[2] = 0; 420 } 421 out[0] = 1; 422 out[3] = 1; 423 return out; 424} 425/** 426* Inverts a mat2 427* 428* @param {mat2} out the receiving matrix 429* @param {ReadonlyMat2} a the source matrix 430* @returns {mat2 | null} out, or null if source matrix is not invertible 431*/ 432function invert$5(out, a) { 433 var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3]; 434 var det = a0 * a3 - a2 * a1; 435 if (!det) return null; 436 det = 1 / det; 437 out[0] = a3 * det; 438 out[1] = -a1 * det; 439 out[2] = -a2 * det; 440 out[3] = a0 * det; 441 return out; 442} 443/** 444* Calculates the determinant of a mat2 445* 446* @param {ReadonlyMat2} a the source matrix 447* @returns {Number} determinant of a 448*/ 449function determinant$3(a) { 450 return a[0] * a[3] - a[2] * a[1]; 451} 452/** 453* Rotates a mat2 by the given angle 454* 455* @param {mat2} out the receiving matrix 456* @param {ReadonlyMat2} a the matrix to rotate 457* @param {Number} rad the angle to rotate the matrix by 458* @returns {mat2} out 459*/ 460function rotate$4(out, a, rad) { 461 var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3]; 462 var s = Math.sin(rad); 463 var c = Math.cos(rad); 464 out[0] = a0 * c + a2 * s; 465 out[1] = a1 * c + a3 * s; 466 out[2] = a0 * -s + a2 * c; 467 out[3] = a1 * -s + a3 * c; 468 return out; 469} 470/** 471* 3x3 Matrix 472* @module mat3 473*/ 474/** 475* Creates a new identity mat3 476* 477* @returns {mat3} a new 3x3 matrix 478*/ 479function create$6() { 480 var out = new ARRAY_TYPE(9); 481 if (ARRAY_TYPE != Float32Array) { 482 out[1] = 0; 483 out[2] = 0; 484 out[3] = 0; 485 out[5] = 0; 486 out[6] = 0; 487 out[7] = 0; 488 } 489 out[0] = 1; 490 out[4] = 1; 491 out[8] = 1; 492 return out; 493} 494/** 495* Calculates the determinant of a mat3 496* 497* @param {ReadonlyMat3} a the source matrix 498* @returns {Number} determinant of a 499*/ 500function determinant$1(a) { 501 var a00 = a[0], a01 = a[1], a02 = a[2]; 502 var a10 = a[3], a11 = a[4], a12 = a[5]; 503 var a20 = a[6], a21 = a[7], a22 = a[8]; 504 return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20); 505} 506/** 507* Creates a matrix from a given angle 508* This is equivalent to (but much faster than): 509* 510* mat3.identity(dest); 511* mat3.rotate(dest, dest, rad); 512* 513* @param {mat3} out mat3 receiving operation result 514* @param {Number} rad the angle to rotate the matrix by 515* @returns {mat3} out 516*/ 517function fromRotation$2(out, rad) { 518 var s = Math.sin(rad), c = Math.cos(rad); 519 out[0] = c; 520 out[1] = s; 521 out[2] = 0; 522 out[3] = -s; 523 out[4] = c; 524 out[5] = 0; 525 out[6] = 0; 526 out[7] = 0; 527 out[8] = 1; 528 return out; 529} 530/** 531* Calculates a 3x3 matrix from the given quaternion 532* 533* @param {mat3} out mat3 receiving operation result 534* @param {ReadonlyQuat} q Quaternion to create matrix from 535* 536* @returns {mat3} out 537*/ 538function fromQuat$1(out, q) { 539 var x = q[0], y = q[1], z = q[2], w = q[3]; 540 var x2 = x + x; 541 var y2 = y + y; 542 var z2 = z + z; 543 var xx = x * x2; 544 var yx = y * x2; 545 var yy = y * y2; 546 var zx = z * x2; 547 var zy = z * y2; 548 var zz = z * z2; 549 var wx = w * x2; 550 var wy = w * y2; 551 var wz = w * z2; 552 out[0] = 1 - yy - zz; 553 out[3] = yx - wz; 554 out[6] = zx + wy; 555 out[1] = yx + wz; 556 out[4] = 1 - xx - zz; 557 out[7] = zy - wx; 558 out[2] = zx - wy; 559 out[5] = zy + wx; 560 out[8] = 1 - xx - yy; 561 return out; 562} 563/** 564* 4x4 Matrix<br>Format: column-major, when typed out it looks like row-major<br>The matrices are being post multiplied. 565* @module mat4 566*/ 567/** 568* Creates a new identity mat4 569* 570* @returns {mat4} a new 4x4 matrix 571*/ 572function create$5() { 573 var out = new ARRAY_TYPE(16); 574 if (ARRAY_TYPE != Float32Array) { 575 out[1] = 0; 576 out[2] = 0; 577 out[3] = 0; 578 out[4] = 0; 579 out[6] = 0; 580 out[7] = 0; 581 out[8] = 0; 582 out[9] = 0; 583 out[11] = 0; 584 out[12] = 0; 585 out[13] = 0; 586 out[14] = 0; 587 } 588 out[0] = 1; 589 out[5] = 1; 590 out[10] = 1; 591 out[15] = 1; 592 return out; 593} 594/** 595* Creates a new mat4 initialized with values from an existing matrix 596* 597* @param {ReadonlyMat4} a matrix to clone 598* @returns {mat4} a new 4x4 matrix 599*/ 600function clone$6(a) { 601 var out = new ARRAY_TYPE(16); 602 out[0] = a[0]; 603 out[1] = a[1]; 604 out[2] = a[2]; 605 out[3] = a[3]; 606 out[4] = a[4]; 607 out[5] = a[5]; 608 out[6] = a[6]; 609 out[7] = a[7]; 610 out[8] = a[8]; 611 out[9] = a[9]; 612 out[10] = a[10]; 613 out[11] = a[11]; 614 out[12] = a[12]; 615 out[13] = a[13]; 616 out[14] = a[14]; 617 out[15] = a[15]; 618 return out; 619} 620/** 621* Copy the values from one mat4 to another 622* 623* @param {mat4} out the receiving matrix 624* @param {ReadonlyMat4} a the source matrix 625* @returns {mat4} out 626*/ 627function copy$5(out, a) { 628 out[0] = a[0]; 629 out[1] = a[1]; 630 out[2] = a[2]; 631 out[3] = a[3]; 632 out[4] = a[4]; 633 out[5] = a[5]; 634 out[6] = a[6]; 635 out[7] = a[7]; 636 out[8] = a[8]; 637 out[9] = a[9]; 638 out[10] = a[10]; 639 out[11] = a[11]; 640 out[12] = a[12]; 641 out[13] = a[13]; 642 out[14] = a[14]; 643 out[15] = a[15]; 644 return out; 645} 646/** 647* Set a mat4 to the identity matrix 648* 649* @param {mat4} out the receiving matrix 650* @returns {mat4} out 651*/ 652function identity$2(out) { 653 out[0] = 1; 654 out[1] = 0; 655 out[2] = 0; 656 out[3] = 0; 657 out[4] = 0; 658 out[5] = 1; 659 out[6] = 0; 660 out[7] = 0; 661 out[8] = 0; 662 out[9] = 0; 663 out[10] = 1; 664 out[11] = 0; 665 out[12] = 0; 666 out[13] = 0; 667 out[14] = 0; 668 out[15] = 1; 669 return out; 670} 671/** 672* Inverts a mat4 673* 674* @param {mat4} out the receiving matrix 675* @param {ReadonlyMat4} a the source matrix 676* @returns {mat4 | null} out, or null if source matrix is not invertible 677*/ 678function invert$2(out, a) { 679 var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3]; 680 var a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7]; 681 var a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11]; 682 var a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]; 683 var b00 = a00 * a11 - a01 * a10; 684 var b01 = a00 * a12 - a02 * a10; 685 var b02 = a00 * a13 - a03 * a10; 686 var b03 = a01 * a12 - a02 * a11; 687 var b04 = a01 * a13 - a03 * a11; 688 var b05 = a02 * a13 - a03 * a12; 689 var b06 = a20 * a31 - a21 * a30; 690 var b07 = a20 * a32 - a22 * a30; 691 var b08 = a20 * a33 - a23 * a30; 692 var b09 = a21 * a32 - a22 * a31; 693 var b10 = a21 * a33 - a23 * a31; 694 var b11 = a22 * a33 - a23 * a32; 695 var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; 696 if (!det) return null; 697 det = 1 / det; 698 out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; 699 out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; 700 out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; 701 out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; 702 out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; 703 out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; 704 out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; 705 out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; 706 out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; 707 out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; 708 out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; 709 out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; 710 out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; 711 out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; 712 out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; 713 out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; 714 return out; 715} 716/** 717* Multiplies two mat4s 718* 719* @param {mat4} out the receiving matrix 720* @param {ReadonlyMat4} a the first operand 721* @param {ReadonlyMat4} b the second operand 722* @returns {mat4} out 723*/ 724function multiply$5(out, a, b) { 725 var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3]; 726 var a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7]; 727 var a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11]; 728 var a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]; 729 var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3]; 730 out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; 731 out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; 732 out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; 733 out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; 734 b0 = b[4]; 735 b1 = b[5]; 736 b2 = b[6]; 737 b3 = b[7]; 738 out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; 739 out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; 740 out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; 741 out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; 742 b0 = b[8]; 743 b1 = b[9]; 744 b2 = b[10]; 745 b3 = b[11]; 746 out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; 747 out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; 748 out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; 749 out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; 750 b0 = b[12]; 751 b1 = b[13]; 752 b2 = b[14]; 753 b3 = b[15]; 754 out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; 755 out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; 756 out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; 757 out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; 758 return out; 759} 760/** 761* Translate a mat4 by the given vector 762* 763* @param {mat4} out the receiving matrix 764* @param {ReadonlyMat4} a the matrix to translate 765* @param {ReadonlyVec3} v vector to translate by 766* @returns {mat4} out 767*/ 768function translate$2(out, a, v) { 769 var x = v[0], y = v[1], z = v[2]; 770 var a00, a01, a02, a03; 771 var a10, a11, a12, a13; 772 var a20, a21, a22, a23; 773 if (a === out) { 774 out[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; 775 out[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; 776 out[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; 777 out[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; 778 } else { 779 a00 = a[0]; 780 a01 = a[1]; 781 a02 = a[2]; 782 a03 = a[3]; 783 a10 = a[4]; 784 a11 = a[5]; 785 a12 = a[6]; 786 a13 = a[7]; 787 a20 = a[8]; 788 a21 = a[9]; 789 a22 = a[10]; 790 a23 = a[11]; 791 out[0] = a00; 792 out[1] = a01; 793 out[2] = a02; 794 out[3] = a03; 795 out[4] = a10; 796 out[5] = a11; 797 out[6] = a12; 798 out[7] = a13; 799 out[8] = a20; 800 out[9] = a21; 801 out[10] = a22; 802 out[11] = a23; 803 out[12] = a00 * x + a10 * y + a20 * z + a[12]; 804 out[13] = a01 * x + a11 * y + a21 * z + a[13]; 805 out[14] = a02 * x + a12 * y + a22 * z + a[14]; 806 out[15] = a03 * x + a13 * y + a23 * z + a[15]; 807 } 808 return out; 809} 810/** 811* Scales the mat4 by the dimensions in the given vec3 not using vectorization 812* 813* @param {mat4} out the receiving matrix 814* @param {ReadonlyMat4} a the matrix to scale 815* @param {ReadonlyVec3} v the vec3 to scale the matrix by 816* @returns {mat4} out 817**/ 818function scale$5(out, a, v) { 819 var x = v[0], y = v[1], z = v[2]; 820 out[0] = a[0] * x; 821 out[1] = a[1] * x; 822 out[2] = a[2] * x; 823 out[3] = a[3] * x; 824 out[4] = a[4] * y; 825 out[5] = a[5] * y; 826 out[6] = a[6] * y; 827 out[7] = a[7] * y; 828 out[8] = a[8] * z; 829 out[9] = a[9] * z; 830 out[10] = a[10] * z; 831 out[11] = a[11] * z; 832 out[12] = a[12]; 833 out[13] = a[13]; 834 out[14] = a[14]; 835 out[15] = a[15]; 836 return out; 837} 838/** 839* Rotates a matrix by the given angle around the X axis 840* 841* @param {mat4} out the receiving matrix 842* @param {ReadonlyMat4} a the matrix to rotate 843* @param {Number} rad the angle to rotate the matrix by 844* @returns {mat4} out 845*/ 846function rotateX$3(out, a, rad) { 847 var s = Math.sin(rad); 848 var c = Math.cos(rad); 849 var a10 = a[4]; 850 var a11 = a[5]; 851 var a12 = a[6]; 852 var a13 = a[7]; 853 var a20 = a[8]; 854 var a21 = a[9]; 855 var a22 = a[10]; 856 var a23 = a[11]; 857 if (a !== out) { 858 out[0] = a[0]; 859 out[1] = a[1]; 860 out[2] = a[2]; 861 out[3] = a[3]; 862 out[12] = a[12]; 863 out[13] = a[13]; 864 out[14] = a[14]; 865 out[15] = a[15]; 866 } 867 out[4] = a10 * c + a20 * s; 868 out[5] = a11 * c + a21 * s; 869 out[6] = a12 * c + a22 * s; 870 out[7] = a13 * c + a23 * s; 871 out[8] = a20 * c - a10 * s; 872 out[9] = a21 * c - a11 * s; 873 out[10] = a22 * c - a12 * s; 874 out[11] = a23 * c - a13 * s; 875 return out; 876} 877/** 878* Rotates a matrix by the given angle around the Y axis 879* 880* @param {mat4} out the receiving matrix 881* @param {ReadonlyMat4} a the matrix to rotate 882* @param {Number} rad the angle to rotate the matrix by 883* @returns {mat4} out 884*/ 885function rotateY$3(out, a, rad) { 886 var s = Math.sin(rad); 887 var c = Math.cos(rad); 888 var a00 = a[0]; 889 var a01 = a[1]; 890 var a02 = a[2]; 891 var a03 = a[3]; 892 var a20 = a[8]; 893 var a21 = a[9]; 894 var a22 = a[10]; 895 var a23 = a[11]; 896 if (a !== out) { 897 out[4] = a[4]; 898 out[5] = a[5]; 899 out[6] = a[6]; 900 out[7] = a[7]; 901 out[12] = a[12]; 902 out[13] = a[13]; 903 out[14] = a[14]; 904 out[15] = a[15]; 905 } 906 out[0] = a00 * c - a20 * s; 907 out[1] = a01 * c - a21 * s; 908 out[2] = a02 * c - a22 * s; 909 out[3] = a03 * c - a23 * s; 910 out[8] = a00 * s + a20 * c; 911 out[9] = a01 * s + a21 * c; 912 out[10] = a02 * s + a22 * c; 913 out[11] = a03 * s + a23 * c; 914 return out; 915} 916/** 917* Rotates a matrix by the given angle around the Z axis 918* 919* @param {mat4} out the receiving matrix 920* @param {ReadonlyMat4} a the matrix to rotate 921* @param {Number} rad the angle to rotate the matrix by 922* @returns {mat4} out 923*/ 924function rotateZ$3(out, a, rad) { 925 var s = Math.sin(rad); 926 var c = Math.cos(rad); 927 var a00 = a[0]; 928 var a01 = a[1]; 929 var a02 = a[2]; 930 var a03 = a[3]; 931 var a10 = a[4]; 932 var a11 = a[5]; 933 var a12 = a[6]; 934 var a13 = a[7]; 935 if (a !== out) { 936 out[8] = a[8]; 937 out[9] = a[9]; 938 out[10] = a[10]; 939 out[11] = a[11]; 940 out[12] = a[12]; 941 out[13] = a[13]; 942 out[14] = a[14]; 943 out[15] = a[15]; 944 } 945 out[0] = a00 * c + a10 * s; 946 out[1] = a01 * c + a11 * s; 947 out[2] = a02 * c + a12 * s; 948 out[3] = a03 * c + a13 * s; 949 out[4] = a10 * c - a00 * s; 950 out[5] = a11 * c - a01 * s; 951 out[6] = a12 * c - a02 * s; 952 out[7] = a13 * c - a03 * s; 953 return out; 954} 955/** 956* Creates a matrix from a vector scaling 957* This is equivalent to (but much faster than): 958* 959* mat4.identity(dest); 960* mat4.scale(dest, dest, vec); 961* 962* @param {mat4} out mat4 receiving operation result 963* @param {ReadonlyVec3} v Scaling vector 964* @returns {mat4} out 965*/ 966function fromScaling(out, v) { 967 out[0] = v[0]; 968 out[1] = 0; 969 out[2] = 0; 970 out[3] = 0; 971 out[4] = 0; 972 out[5] = v[1]; 973 out[6] = 0; 974 out[7] = 0; 975 out[8] = 0; 976 out[9] = 0; 977 out[10] = v[2]; 978 out[11] = 0; 979 out[12] = 0; 980 out[13] = 0; 981 out[14] = 0; 982 out[15] = 1; 983 return out; 984} 985/** 986* Generates a perspective projection matrix with the given bounds. 987* The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1], 988* which matches WebGL/OpenGL's clip volume. 989* Passing null/undefined/no value for far will generate infinite projection matrix. 990* 991* @param {mat4} out mat4 frustum matrix will be written into 992* @param {number} fovy Vertical field of view in radians 993* @param {number} aspect Aspect ratio. typically viewport width/height 994* @param {number} near Near bound of the frustum 995* @param {number} far Far bound of the frustum, can be null or Infinity 996* @returns {mat4} out 997*/ 998function perspectiveNO(out, fovy, aspect, near, far) { 999 var f = 1 / Math.tan(fovy / 2); 1000 out[0] = f / aspect; 1001 out[1] = 0; 1002 out[2] = 0; 1003 out[3] = 0; 1004 out[4] = 0; 1005 out[5] = f; 1006 out[6] = 0; 1007 out[7] = 0; 1008 out[8] = 0; 1009 out[9] = 0; 1010 out[11] = -1; 1011 out[12] = 0; 1012 out[13] = 0; 1013 out[15] = 0; 1014 if (far != null && far !== Infinity) { 1015 var nf = 1 / (near - far); 1016 out[10] = (far + near) * nf; 1017 out[14] = 2 * far * near * nf; 1018 } else { 1019 out[10] = -1; 1020 out[14] = -2 * near; 1021 } 1022 return out; 1023} 1024/** 1025* Alias for {@link mat4.perspectiveNO} 1026* @function 1027*/ 1028var perspective = perspectiveNO; 1029/** 1030* Generates a orthogonal projection matrix with the given bounds. 1031* The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1], 1032* which matches WebGL/OpenGL's clip volume. 1033* 1034* @param {mat4} out mat4 frustum matrix will be written into 1035* @param {number} left Left bound of the frustum 1036* @param {number} right Right bound of the frustum 1037* @param {number} bottom Bottom bound of the frustum 1038* @param {number} top Top bound of the frustum 1039* @param {number} near Near bound of the frustum 1040* @param {number} far Far bound of the frustum 1041* @returns {mat4} out 1042*/ 1043function orthoNO(out, left, right, bottom, top, near, far) { 1044 var lr = 1 / (left - right); 1045 var bt = 1 / (bottom - top); 1046 var nf = 1 / (near - far); 1047 out[0] = -2 * lr; 1048 out[1] = 0; 1049 out[2] = 0; 1050 out[3] = 0; 1051 out[4] = 0; 1052 out[5] = -2 * bt; 1053 out[6] = 0; 1054 out[7] = 0; 1055 out[8] = 0; 1056 out[9] = 0; 1057 out[10] = 2 * nf; 1058 out[11] = 0; 1059 out[12] = (left + right) * lr; 1060 out[13] = (top + bottom) * bt; 1061 out[14] = (far + near) * nf; 1062 out[15] = 1; 1063 return out; 1064} 1065/** 1066* Alias for {@link mat4.orthoNO} 1067* @function 1068*/ 1069var ortho = orthoNO; 1070/** 1071* Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) 1072* 1073* @param {ReadonlyMat4} a The first matrix. 1074* @param {ReadonlyMat4} b The second matrix. 1075* @returns {Boolean} True if the matrices are equal, false otherwise. 1076*/ 1077function exactEquals$5(a, b) { 1078 return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8] && a[9] === b[9] && a[10] === b[10] && a[11] === b[11] && a[12] === b[12] && a[13] === b[13] && a[14] === b[14] && a[15] === b[15]; 1079} 1080/** 1081* Returns whether or not the matrices have approximately the same elements in the same position. 1082* 1083* @param {ReadonlyMat4} a The first matrix. 1084* @param {ReadonlyMat4} b The second matrix. 1085* @returns {Boolean} True if the matrices are equal, false otherwise. 1086*/ 1087function equals$6(a, b) { 1088 var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3]; 1089 var a4 = a[4], a5 = a[5], a6 = a[6], a7 = a[7]; 1090 var a8 = a[8], a9 = a[9], a10 = a[10], a11 = a[11]; 1091 var a12 = a[12], a13 = a[13], a14 = a[14], a15 = a[15]; 1092 var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3]; 1093 var b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7]; 1094 var b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11]; 1095 var b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15]; 1096 return Math.abs(a0 - b0) <= 1e-6 * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= 1e-6 * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= 1e-6 * Math.max(1, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= 1e-6 * Math.max(1, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= 1e-6 * Math.max(1, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= 1e-6 * Math.max(1, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= 1e-6 * Math.max(1, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= 1e-6 * Math.max(1, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= 1e-6 * Math.max(1, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= 1e-6 * Math.max(1, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= 1e-6 * Math.max(1, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= 1e-6 * Math.max(1, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= 1e-6 * Math.max(1, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= 1e-6 * Math.max(1, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= 1e-6 * Math.max(1, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= 1e-6 * Math.max(1, Math.abs(a15), Math.abs(b15)); 1097} 1098/** 1099* 3 Dimensional Vector 1100* @module vec3 1101*/ 1102/** 1103* Creates a new, empty vec3 1104* 1105* @returns {vec3} a new 3D vector 1106*/ 1107function create$4() { 1108 var out = new ARRAY_TYPE(3); 1109 if (ARRAY_TYPE != Float32Array) { 1110 out[0] = 0; 1111 out[1] = 0; 1112 out[2] = 0; 1113 } 1114 return out; 1115} 1116/** 1117* Creates a new vec3 initialized with values from an existing vector 1118* 1119* @param {ReadonlyVec3} a vector to clone 1120* @returns {vec3} a new 3D vector 1121*/ 1122function clone$5(a) { 1123 var out = new ARRAY_TYPE(3); 1124 out[0] = a[0]; 1125 out[1] = a[1]; 1126 out[2] = a[2]; 1127 return out; 1128} 1129/** 1130* Calculates the length of a vec3 1131* 1132* @param {ReadonlyVec3} a vector to calculate length of 1133* @returns {Number} length of a 1134*/ 1135function length$4(a) { 1136 var x = a[0]; 1137 var y = a[1]; 1138 var z = a[2]; 1139 return Math.sqrt(x * x + y * y + z * z); 1140} 1141/** 1142* Creates a new vec3 initialized with the given values 1143* 1144* @param {Number} x X component 1145* @param {Number} y Y component 1146* @param {Number} z Z component 1147* @returns {vec3} a new 3D vector 1148*/ 1149function fromValues$4(x, y, z) { 1150 var out = new ARRAY_TYPE(3); 1151 out[0] = x; 1152 out[1] = y; 1153 out[2] = z; 1154 return out; 1155} 1156/** 1157* Adds two vec3's 1158* 1159* @param {vec3} out the receiving vector 1160* @param {ReadonlyVec3} a the first operand 1161* @param {ReadonlyVec3} b the second operand 1162* @returns {vec3} out 1163*/ 1164function add$4(out, a, b) { 1165 out[0] = a[0] + b[0]; 1166 out[1] = a[1] + b[1]; 1167 out[2] = a[2] + b[2]; 1168 return out; 1169} 1170/** 1171* Subtracts vector b from vector a 1172* 1173* @param {vec3} out the receiving vector 1174* @param {ReadonlyVec3} a the first operand 1175* @param {ReadonlyVec3} b the second operand 1176* @returns {vec3} out 1177*/ 1178function subtract$2(out, a, b) { 1179 out[0] = a[0] - b[0]; 1180 out[1] = a[1] - b[1]; 1181 out[2] = a[2] - b[2]; 1182 return out; 1183} 1184/** 1185* Scales a vec3 by a scalar number 1186* 1187* @param {vec3} out the receiving vector 1188* @param {ReadonlyVec3} a the vector to scale 1189* @param {Number} b amount to scale the vector by 1190* @returns {vec3} out 1191*/ 1192function scale$4(out, a, b) { 1193 out[0] = a[0] * b; 1194 out[1] = a[1] * b; 1195 out[2] = a[2] * b; 1196 return out; 1197} 1198/** 1199* Adds two vec3's after scaling the second operand by a scalar value 1200* 1201* @param {vec3} out the receiving vector 1202* @param {ReadonlyVec3} a the first operand 1203* @param {ReadonlyVec3} b the second operand 1204* @param {Number} scale the amount to scale b by before adding 1205* @returns {vec3} out 1206*/ 1207function scaleAndAdd$2(out, a, b, scale) { 1208 out[0] = a[0] + b[0] * scale; 1209 out[1] = a[1] + b[1] * scale; 1210 out[2] = a[2] + b[2] * scale; 1211 return out; 1212} 1213/** 1214* Calculates the euclidian distance between two vec3's 1215* 1216* @param {ReadonlyVec3} a the first operand 1217* @param {ReadonlyVec3} b the second operand 1218* @returns {Number} distance between a and b 1219*/ 1220function distance$2(a, b) { 1221 var x = b[0] - a[0]; 1222 var y = b[1] - a[1]; 1223 var z = b[2] - a[2]; 1224 return Math.sqrt(x * x + y * y + z * z); 1225} 1226/** 1227* Negates the components of a vec3 1228* 1229* @param {vec3} out the receiving vector 1230* @param {ReadonlyVec3} a vector to negate 1231* @returns {vec3} out 1232*/ 1233function negate$2(out, a) { 1234 out[0] = -a[0]; 1235 out[1] = -a[1]; 1236 out[2] = -a[2]; 1237 return out; 1238} 1239/** 1240* Normalize a vec3 1241* 1242* @param {vec3} out the receiving vector 1243* @param {ReadonlyVec3} a vector to normalize 1244* @returns {vec3} out 1245*/ 1246function normalize$4(out, a) { 1247 var x = a[0]; 1248 var y = a[1]; 1249 var z = a[2]; 1250 var len = x * x + y * y + z * z; 1251 if (len > 0) len = 1 / Math.sqrt(len); 1252 out[0] = a[0] * len; 1253 out[1] = a[1] * len; 1254 out[2] = a[2] * len; 1255 return out; 1256} 1257/** 1258* Calculates the dot product of two vec3's 1259* 1260* @param {ReadonlyVec3} a the first operand 1261* @param {ReadonlyVec3} b the second operand 1262* @returns {Number} dot product of a and b 1263*/ 1264function dot$5(a, b) { 1265 return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; 1266} 1267/** 1268* Computes the cross product of two vec3's 1269* 1270* @param {vec3} out the receiving vector 1271* @param {ReadonlyVec3} a the first operand 1272* @param {ReadonlyVec3} b the second operand 1273* @returns {vec3} out 1274*/ 1275function cross$2(out, a, b) { 1276 var ax = a[0], ay = a[1], az = a[2]; 1277 var bx = b[0], by = b[1], bz = b[2]; 1278 out[0] = ay * bz - az * by; 1279 out[1] = az * bx - ax * bz; 1280 out[2] = ax * by - ay * bx; 1281 return out; 1282} 1283/** 1284* Transforms the vec3 with a mat4. 1285* 4th vector component is implicitly '1' 1286* 1287* @param {vec3} out the receiving vector 1288* @param {ReadonlyVec3} a the vector to transform 1289* @param {ReadonlyMat4} m matrix to transform with 1290* @returns {vec3} out 1291*/ 1292function transformMat4$2(out, a, m) { 1293 var x = a[0], y = a[1], z = a[2]; 1294 var w = m[3] * x + m[7] * y + m[11] * z + m[15]; 1295 w = w || 1; 1296 out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w; 1297 out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w; 1298 out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w; 1299 return out; 1300} 1301/** 1302* Transforms the vec3 with a mat3. 1303* 1304* @param {vec3} out the receiving vector 1305* @param {ReadonlyVec3} a the vector to transform 1306* @param {ReadonlyMat3} m the 3x3 matrix to transform with 1307* @returns {vec3} out 1308*/ 1309function transformMat3$1(out, a, m) { 1310 var x = a[0], y = a[1], z = a[2]; 1311 out[0] = x * m[0] + y * m[3] + z * m[6]; 1312 out[1] = x * m[1] + y * m[4] + z * m[7]; 1313 out[2] = x * m[2] + y * m[5] + z * m[8]; 1314 return out; 1315} 1316/** 1317* Transforms the vec3 with a quat 1318* Can also be used for dual quaternions. (Multiply it with the real part) 1319* 1320* @param {vec3} out the receiving vector 1321* @param {ReadonlyVec3} a the vector to transform 1322* @param {ReadonlyQuat} q normalized quaternion to transform with 1323* @returns {vec3} out 1324*/ 1325function transformQuat$1(out, a, q) { 1326 var qx = q[0], qy = q[1], qz = q[2], qw = q[3]; 1327 var vx = a[0], vy = a[1], vz = a[2]; 1328 var tx = qy * vz - qz * vy; 1329 var ty = qz * vx - qx * vz; 1330 var tz = qx * vy - qy * vx; 1331 tx = tx + tx; 1332 ty = ty + ty; 1333 tz = tz + tz; 1334 out[0] = vx + qw * tx + qy * tz - qz * ty; 1335 out[1] = vy + qw * ty + qz * tx - qx * tz; 1336 out[2] = vz + qw * tz + qx * ty - qy * tx; 1337 return out; 1338} 1339/** 1340* Rotate a 3D vector around the x-axis 1341* @param {vec3} out The receiving vec3 1342* @param {ReadonlyVec3} a The vec3 point to rotate 1343* @param {ReadonlyVec3} b The origin of the rotation 1344* @param {Number} rad The angle of rotation in radians 1345* @returns {vec3} out 1346*/ 1347function rotateX$2(out, a, b, rad) { 1348 var p = [], r = []; 1349 p[0] = a[0] - b[0]; 1350 p[1] = a[1] - b[1]; 1351 p[2] = a[2] - b[2]; 1352 r[0] = p[0]; 1353 r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad); 1354 r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad); 1355 out[0] = r[0] + b[0]; 1356 out[1] = r[1] + b[1]; 1357 out[2] = r[2] + b[2]; 1358 return out; 1359} 1360/** 1361* Rotate a 3D vector around the y-axis 1362* @param {vec3} out The receiving vec3 1363* @param {ReadonlyVec3} a The vec3 point to rotate 1364* @param {ReadonlyVec3} b The origin of the rotation 1365* @param {Number} rad The angle of rotation in radians 1366* @returns {vec3} out 1367*/ 1368function rotateY$2(out, a, b, rad) { 1369 var p = [], r = []; 1370 p[0] = a[0] - b[0]; 1371 p[1] = a[1] - b[1]; 1372 p[2] = a[2] - b[2]; 1373 r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad); 1374 r[1] = p[1]; 1375 r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad); 1376 out[0] = r[0] + b[0]; 1377 out[1] = r[1] + b[1]; 1378 out[2] = r[2] + b[2]; 1379 return out; 1380} 1381/** 1382* Rotate a 3D vector around the z-axis 1383* @param {vec3} out The receiving vec3 1384* @param {ReadonlyVec3} a The vec3 point to rotate 1385* @param {ReadonlyVec3} b The origin of the rotation 1386* @param {Number} rad The angle of rotation in radians 1387* @returns {vec3} out 1388*/ 1389function rotateZ$2(out, a, b, rad) { 1390 var p = [], r = []; 1391 p[0] = a[0] - b[0]; 1392 p[1] = a[1] - b[1]; 1393 p[2] = a[2] - b[2]; 1394 r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad); 1395 r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad); 1396 r[2] = p[2]; 1397 out[0] = r[0] + b[0]; 1398 out[1] = r[1] + b[1]; 1399 out[2] = r[2] + b[2]; 1400 return out; 1401} 1402/** 1403* Set the components of a vec3 to zero 1404* 1405* @param {vec3} out the receiving vector 1406* @returns {vec3} out 1407*/ 1408function zero$2(out) { 1409 out[0] = 0; 1410 out[1] = 0; 1411 out[2] = 0; 1412 return out; 1413} 1414/** 1415* Alias for {@link vec3.subtract} 1416* @function 1417*/ 1418var sub$2 = subtract$2; 1419/** 1420* Alias for {@link vec3.length} 1421* @function 1422*/ 1423var len$4 = length$4; 1424(function() { 1425 var vec = create$4(); 1426 return function(a, stride, offset, count, fn, arg) { 1427 var i, l; 1428 if (!stride) stride = 3; 1429 if (!offset) offset = 0; 1430 if (count) l = Math.min(count * stride + offset, a.length); 1431 else l = a.length; 1432 for (i = offset; i < l; i += stride) { 1433 vec[0] = a[i]; 1434 vec[1] = a[i + 1]; 1435 vec[2] = a[i + 2]; 1436 fn(vec, vec, arg); 1437 a[i] = vec[0]; 1438 a[i + 1] = vec[1]; 1439 a[i + 2] = vec[2]; 1440 } 1441 return a; 1442 }; 1443})(); 1444/** 1445* 4 Dimensional Vector 1446* @module vec4 1447*/ 1448/** 1449* Creates a new, empty vec4 1450* 1451* @returns {vec4} a new 4D vector 1452*/ 1453function create$3() { 1454 var out = new ARRAY_TYPE(4); 1455 if (ARRAY_TYPE != Float32Array) { 1456 out[0] = 0; 1457 out[1] = 0; 1458 out[2] = 0; 1459 out[3] = 0; 1460 } 1461 return out; 1462} 1463/** 1464* Creates a new vec4 initialized with the given values 1465* 1466* @param {Number} x X component 1467* @param {Number} y Y component 1468* @param {Number} z Z component 1469* @param {Number} w W component 1470* @returns {vec4} a new 4D vector 1471*/ 1472function fromValues$3(x, y, z, w) { 1473 var out = new ARRAY_TYPE(4); 1474 out[0] = x; 1475 out[1] = y; 1476 out[2] = z; 1477 out[3] = w; 1478 return out; 1479} 1480/** 1481* Multiplies two vec4's 1482* 1483* @param {vec4} out the receiving vector 1484* @param {ReadonlyVec4} a the first operand 1485* @param {ReadonlyVec4} b the second operand 1486* @returns {vec4} out 1487*/ 1488function multiply$3(out, a, b) { 1489 out[0] = a[0] * b[0]; 1490 out[1] = a[1] * b[1]; 1491 out[2] = a[2] * b[2]; 1492 out[3] = a[3] * b[3]; 1493 return out; 1494} 1495/** 1496* Scales a vec4 by a scalar number 1497* 1498* @param {vec4} out the receiving vector 1499* @param {ReadonlyVec4} a the vector to scale 1500* @param {Number} b amount to scale the vector by 1501* @returns {vec4} out 1502*/ 1503function scale$3(out, a, b) { 1504 out[0] = a[0] * b; 1505 out[1] = a[1] * b; 1506 out[2] = a[2] * b; 1507 out[3] = a[3] * b; 1508 return out; 1509} 1510/** 1511* Normalize a vec4 1512* 1513* @param {vec4} out the receiving vector 1514* @param {ReadonlyVec4} a vector to normalize 1515* @returns {vec4} out 1516*/ 1517function normalize$3(out, a) { 1518 var x = a[0]; 1519 var y = a[1]; 1520 var z = a[2]; 1521 var w = a[3]; 1522 var len = x * x + y * y + z * z + w * w; 1523 if (len > 0) len = 1 / Math.sqrt(len); 1524 out[0] = x * len; 1525 out[1] = y * len; 1526 out[2] = z * len; 1527 out[3] = w * len; 1528 return out; 1529} 1530/** 1531* Transforms the vec4 with a mat4. 1532* 1533* @param {vec4} out the receiving vector 1534* @param {ReadonlyVec4} a the vector to transform 1535* @param {ReadonlyMat4} m matrix to transform with 1536* @returns {vec4} out 1537*/ 1538function transformMat4$1(out, a, m) { 1539 var x = a[0], y = a[1], z = a[2], w = a[3]; 1540 out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w; 1541 out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w; 1542 out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w; 1543 out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w; 1544 return out; 1545} 1546/** 1547* Alias for {@link vec4.multiply} 1548* @function 1549*/ 1550var mul$3 = multiply$3; 1551(function() { 1552 var vec = create$3(); 1553 return function(a, stride, offset, count, fn, arg) { 1554 var i, l; 1555 if (!stride) stride = 4; 1556 if (!offset) offset = 0; 1557 if (count) l = Math.min(count * stride + offset, a.length); 1558 else l = a.length; 1559 for (i = offset; i < l; i += stride) { 1560 vec[0] = a[i]; 1561 vec[1] = a[i + 1]; 1562 vec[2] = a[i + 2]; 1563 vec[3] = a[i + 3]; 1564 fn(vec, vec, arg); 1565 a[i] = vec[0]; 1566 a[i + 1] = vec[1]; 1567 a[i + 2] = vec[2]; 1568 a[i + 3] = vec[3]; 1569 } 1570 return a; 1571 }; 1572})(); 1573/** 1574* Quaternion in the format XYZW 1575* @module quat 1576*/ 1577/** 1578* Creates a new identity quat 1579* 1580* @returns {quat} a new quaternion 1581*/ 1582function create$2() { 1583 var out = new ARRAY_TYPE(4); 1584 if (ARRAY_TYPE != Float32Array) { 1585 out[0] = 0; 1586 out[1] = 0; 1587 out[2] = 0; 1588 } 1589 out[3] = 1; 1590 return out; 1591} 1592/** 1593* Sets a quat from the given angle and rotation axis, 1594* then returns it. 1595* 1596* @param {quat} out the receiving quaternion 1597* @param {ReadonlyVec3} axis the axis around which to rotate 1598* @param {Number} rad the angle in radians 1599* @returns {quat} out 1600**/ 1601function setAxisAngle(out, axis, rad) { 1602 rad = rad * .5; 1603 var s = Math.sin(rad); 1604 out[0] = s * axis[0]; 1605 out[1] = s * axis[1]; 1606 out[2] = s * axis[2]; 1607 out[3] = Math.cos(rad); 1608 return out; 1609} 1610/** 1611* Multiplies two quat's 1612* 1613* @param {quat} out the receiving quaternion 1614* @param {ReadonlyQuat} a the first operand 1615* @param {ReadonlyQuat} b the second operand 1616* @returns {quat} out 1617*/ 1618function multiply$2(out, a, b) { 1619 var ax = a[0], ay = a[1], az = a[2], aw = a[3]; 1620 var bx = b[0], by = b[1], bz = b[2], bw = b[3]; 1621 out[0] = ax * bw + aw * bx + ay * bz - az * by; 1622 out[1] = ay * bw + aw * by + az * bx - ax * bz; 1623 out[2] = az * bw + aw * bz + ax * by - ay * bx; 1624 out[3] = aw * bw - ax * bx - ay * by - az * bz; 1625 return out; 1626} 1627/** 1628* Performs a spherical linear interpolation between two quat 1629* 1630* @param {quat} out the receiving quaternion 1631* @param {ReadonlyQuat} a the first operand 1632* @param {ReadonlyQuat} b the second operand 1633* @param {Number} t interpolation amount, in the range [0-1], between the two inputs 1634* @returns {quat} out 1635*/ 1636function slerp(out, a, b, t) { 1637 var ax = a[0], ay = a[1], az = a[2], aw = a[3]; 1638 var bx = b[0], by = b[1], bz = b[2], bw = b[3]; 1639 var omega, cosom = ax * bx + ay * by + az * bz + aw * bw, sinom, scale0, scale1; 1640 if (cosom < 0) { 1641 cosom = -cosom; 1642 bx = -bx; 1643 by = -by; 1644 bz = -bz; 1645 bw = -bw; 1646 } 1647 if (1 - cosom > 1e-6) { 1648 omega = Math.acos(cosom); 1649 sinom = Math.sin(omega); 1650 scale0 = Math.sin((1 - t) * omega) / sinom; 1651 scale1 = Math.sin(t * omega) / sinom; 1652 } else { 1653 scale0 = 1 - t; 1654 scale1 = t; 1655 } 1656 out[0] = scale0 * ax + scale1 * bx; 1657 out[1] = scale0 * ay + scale1 * by; 1658 out[2] = scale0 * az + scale1 * bz; 1659 out[3] = scale0 * aw + scale1 * bw; 1660 return out; 1661} 1662/** 1663* Creates a quaternion from the given 3x3 rotation matrix. 1664* 1665* NOTE: The resultant quaternion is not normalized, so you should be sure 1666* to renormalize the quaternion yourself where necessary. 1667* 1668* @param {quat} out the receiving quaternion 1669* @param {ReadonlyMat3} m rotation matrix 1670* @returns {quat} out 1671* @function 1672*/ 1673function fromMat3(out, m) { 1674 var fTrace = m[0] + m[4] + m[8]; 1675 var fRoot; 1676 if (fTrace > 0) { 1677 fRoot = Math.sqrt(fTrace + 1); 1678 out[3] = .5 * fRoot; 1679 fRoot = .5 / fRoot; 1680 out[0] = (m[5] - m[7]) * fRoot; 1681 out[1] = (m[6] - m[2]) * fRoot; 1682 out[2] = (m[1] - m[3]) * fRoot; 1683 } else { 1684 var i = 0; 1685 if (m[4] > m[0]) i = 1; 1686 if (m[8] > m[i * 3 + i]) i = 2; 1687 var j = (i + 1) % 3; 1688 var k = (i + 2) % 3; 1689 fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1); 1690 out[i] = .5 * fRoot; 1691 fRoot = .5 / fRoot; 1692 out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot; 1693 out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot; 1694 out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot; 1695 } 1696 return out; 1697} 1698/** 1699* Creates a quaternion from the given euler angle x, y, z using the provided intrinsic order for the conversion. 1700* 1701* @param {quat} out the receiving quaternion 1702* @param {Number} x Angle to rotate around X axis in degrees. 1703* @param {Number} y Angle to rotate around Y axis in degrees. 1704* @param {Number} z Angle to rotate around Z axis in degrees. 1705* @param {'xyz'|'xzy'|'yxz'|'yzx'|'zxy'|'zyx'} order Intrinsic order for conversion, default is zyx. 1706* @returns {quat} out 1707* @function 1708*/ 1709function fromEuler(out, x, y, z) { 1710 var order = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : "zyx"; 1711 var halfToRad = Math.PI / 360; 1712 x *= halfToRad; 1713 z *= halfToRad; 1714 y *= halfToRad; 1715 var sx = Math.sin(x); 1716 var cx = Math.cos(x); 1717 var sy = Math.sin(y); 1718 var cy = Math.cos(y); 1719 var sz = Math.sin(z); 1720 var cz = Math.cos(z); 1721 switch (order) { 1722 case "xyz": 1723 out[0] = sx * cy * cz + cx * sy * sz; 1724 out[1] = cx * sy * cz - sx * cy * sz; 1725 out[2] = cx * cy * sz + sx * sy * cz; 1726 out[3] = cx * cy * cz - sx * sy * sz; 1727 break; 1728 case "xzy": 1729 out[0] = sx * cy * cz - cx * sy * sz; 1730 out[1] = cx * sy * cz - sx * cy * sz; 1731 out[2] = cx * cy * sz + sx * sy * cz; 1732 out[3] = cx * cy * cz + sx * sy * sz; 1733 break; 1734 case "yxz": 1735 out[0] = sx * cy * cz + cx * sy * sz; 1736 out[1] = cx * sy * cz - sx * cy * sz; 1737 out[2] = cx * cy * sz - sx * sy * cz; 1738 out[3] = cx * cy * cz + sx * sy * sz; 1739 break; 1740 case "yzx": 1741 out[0] = sx * cy * cz + cx * sy * sz; 1742 out[1] = cx * sy * cz + sx * cy * sz; 1743 out[2] = cx * cy * sz - sx * sy * cz; 1744 out[3] = cx * cy * cz - sx * sy * sz; 1745 break; 1746 case "zxy": 1747 out[0] = sx * cy * cz - cx * sy * sz; 1748 out[1] = cx * sy * cz + sx * cy * sz; 1749 out[2] = cx * cy * sz + sx * sy * cz; 1750 out[3] = cx * cy * cz - sx * sy * sz; 1751 break; 1752 case "zyx": 1753 out[0] = sx * cy * cz - cx * sy * sz; 1754 out[1] = cx * sy * cz + sx * cy * sz; 1755 out[2] = cx * cy * sz - sx * sy * cz; 1756 out[3] = cx * cy * cz + sx * sy * sz; 1757 break; 1758 default: throw new Error("Unknown angle order " + order); 1759 } 1760 return out; 1761} 1762/** 1763* Creates a new quat initialized with the given values 1764* 1765* @param {Number} x X component 1766* @param {Number} y Y component 1767* @param {Number} z Z component 1768* @param {Number} w W component 1769* @returns {quat} a new quaternion 1770* @function 1771*/ 1772var fromValues$2 = fromValues$3; 1773/** 1774* Normalize a quat 1775* 1776* @param {quat} out the receiving quaternion 1777* @param {ReadonlyQuat} a quaternion to normalize 1778* @returns {quat} out 1779* @function 1780*/ 1781var normalize$2 = normalize$3; 1782(function() { 1783 var tmpvec3 = create$4(); 1784 var xUnitVec3 = fromValues$4(1, 0, 0); 1785 var yUnitVec3 = fromValues$4(0, 1, 0); 1786 return function(out, a, b) { 1787 var dot = dot$5(a, b); 1788 if (dot < -.999999) { 1789 cross$2(tmpvec3, xUnitVec3, a); 1790 if (len$4(tmpvec3) < 1e-6) cross$2(tmpvec3, yUnitVec3, a); 1791 normalize$4(tmpvec3, tmpvec3); 1792 setAxisAngle(out, tmpvec3, Math.PI); 1793 return out; 1794 } else if (dot > .999999) { 1795 out[0] = 0; 1796 out[1] = 0; 1797 out[2] = 0; 1798 out[3] = 1; 1799 return out; 1800 } else { 1801 cross$2(tmpvec3, a, b); 1802 out[0] = tmpvec3[0]; 1803 out[1] = tmpvec3[1]; 1804 out[2] = tmpvec3[2]; 1805 out[3] = 1 + dot; 1806 return normalize$2(out, out); 1807 } 1808 }; 1809})(); 1810(function() { 1811 var temp1 = create$2(); 1812 var temp2 = create$2(); 1813 return function(out, a, b, c, d, t) { 1814 slerp(temp1, a, d, t); 1815 slerp(temp2, b, c, t); 1816 slerp(out, temp1, temp2, 2 * t * (1 - t)); 1817 return out; 1818 }; 1819})(); 1820(function() { 1821 var matr = create$6(); 1822 return function(out, view, right, up) { 1823 matr[0] = right[0]; 1824 matr[3] = right[1]; 1825 matr[6] = right[2]; 1826 matr[1] = up[0]; 1827 matr[4] = up[1]; 1828 matr[7] = up[2]; 1829 matr[2] = -view[0]; 1830 matr[5] = -view[1]; 1831 matr[8] = -view[2]; 1832 return normalize$2(out, fromMat3(out, matr)); 1833 }; 1834})(); 1835/** 1836* 2 Dimensional Vector 1837* @module vec2 1838*/ 1839/** 1840* Creates a new, empty vec2 1841* 1842* @returns {vec2} a new 2D vector 1843*/ 1844function create() { 1845 var out = new ARRAY_TYPE(2); 1846 if (ARRAY_TYPE != Float32Array) { 1847 out[0] = 0; 1848 out[1] = 0; 1849 } 1850 return out; 1851} 1852/** 1853* Creates a new vec2 initialized with the given values 1854* 1855* @param {Number} x X component 1856* @param {Number} y Y component 1857* @returns {vec2} a new 2D vector 1858*/ 1859function fromValues(x, y) { 1860 var out = new ARRAY_TYPE(2); 1861 out[0] = x; 1862 out[1] = y; 1863 return out; 1864} 1865/** 1866* Scales a vec2 by a scalar number 1867* 1868* @param {vec2} out the receiving vector 1869* @param {ReadonlyVec2} a the vector to scale 1870* @param {Number} b amount to scale the vector by 1871* @returns {vec2} out 1872*/ 1873function scale(out, a, b) { 1874 out[0] = a[0] * b; 1875 out[1] = a[1] * b; 1876 return out; 1877} 1878/** 1879* Calculates the length of a vec2 1880* 1881* @param {ReadonlyVec2} a vector to calculate length of 1882* @returns {Number} length of a 1883*/ 1884function length(a) { 1885 var x = a[0], y = a[1]; 1886 return Math.sqrt(x * x + y * y); 1887} 1888/** 1889* Calculates the squared length of a vec2 1890* 1891* @param {ReadonlyVec2} a vector to calculate squared length of 1892* @returns {Number} squared length of a 1893*/ 1894function squaredLength(a) { 1895 var x = a[0], y = a[1]; 1896 return x * x + y * y; 1897} 1898/** 1899* Calculates the dot product of two vec2's 1900* 1901* @param {ReadonlyVec2} a the first operand 1902* @param {ReadonlyVec2} b the second operand 1903* @returns {Number} dot product of a and b 1904*/ 1905function dot$1(a, b) { 1906 return a[0] * b[0] + a[1] * b[1]; 1907} 1908/** 1909* Set the components of a vec2 to zero 1910* 1911* @param {vec2} out the receiving vector 1912* @returns {vec2} out 1913*/ 1914function zero(out) { 1915 out[0] = 0; 1916 out[1] = 0; 1917 return out; 1918} 1919/** 1920* Alias for {@link vec2.squaredLength} 1921* @function 1922*/ 1923var sqrLen = squaredLength; 1924(function() { 1925 var vec = create(); 1926 return function(a, stride, offset, count, fn, arg) { 1927 var i, l; 1928 if (!stride) stride = 2; 1929 if (!offset) offset = 0; 1930 if (count) l = Math.min(count * stride + offset, a.length); 1931 else l = a.length; 1932 for (i = offset; i < l; i += stride) { 1933 vec[0] = a[i]; 1934 vec[1] = a[i + 1]; 1935 fn(vec, vec, arg); 1936 a[i] = vec[0]; 1937 a[i + 1] = vec[1]; 1938 } 1939 return a; 1940 }; 1941})(); 1942//#endregion 1943//#region src/data/extent.ts 1944/** 1945* The maximum value of a coordinate in the internal tile coordinate system. Coordinates of 1946* all source features normalized to this extent upon load. 1947* 1948* The value is a consequence of the following: 1949* 1950* * Vertex buffer store positions as signed 16 bit integers. 1951* * One bit is lost for signedness to support tile buffers. 1952* * One bit is lost because the line vertex buffer used to pack 1 bit of other data into the int. 1953* * One bit is lost to support features extending past the extent on the right edge of the tile. 1954* * This leaves us with 2^13 = 8192 1955*/ 1956const EXTENT$1 = 8192; 1957//#endregion 1958//#region src/source/pixels_to_tile_units.ts 1959/** 1960* Converts a pixel value at a the given zoom level to tile units. 1961* 1962* The shaders mostly calculate everything in tile units so style 1963* properties need to be converted from pixels to tile units using this. 1964* 1965* For example, a translation by 30 pixels at zoom 6.5 will be a 1966* translation by pixelsToTileUnits(30, 6.5) tile units. 1967* 1968* @returns value in tile units 1969*/ 1970function pixelsToTileUnits(tile, pixelValue, z) { 1971 return pixelValue * (EXTENT$1 / (tile.tileSize * Math.pow(2, z - tile.tileID.overscaledZ))); 1972} 1973//#endregion 1974//#region src/util/util.ts 1975const JSON_PREFIX = "__$json__:"; 1976/** 1977* Ensures that a value is an `Error` instance. 1978* If the value is already an `Error`, it is returned as-is. 1979* Otherwise, a new `Error` is created from its string representation. 1980*/ 1981function ensureError(e) { 1982 if (e instanceof Error) return e; 1983 return new Error(typeof e === "string" ? e : String(e)); 1984} 1985/** 1986* Returns a new 64 bit float vec4 of zeroes. 1987*/ 1988function createVec4f64() { 1989 return /* @__PURE__ */ new Float64Array(4); 1990} 1991/** 1992* Returns a new 64 bit float vec3 of zeroes. 1993*/ 1994function createVec3f64() { 1995 return /* @__PURE__ */ new Float64Array(3); 1996} 1997/** 1998* Returns a new 64 bit float mat4 of zeroes. 1999*/ 2000function createMat4f64() { 2001 return /* @__PURE__ */ new Float64Array(16); 2002} 2003/** 2004* Returns a new 64 bit float mat4 set to identity. 2005*/ 2006function createIdentityMat4f64() { 2007 const m = /* @__PURE__ */ new Float64Array(16); 2008 identity$2(m); 2009 return m; 2010} 2011/** 2012* Returns a new 32 bit float mat4 set to identity. 2013*/ 2014function createIdentityMat4f32() { 2015 const m = /* @__PURE__ */ new Float32Array(16); 2016 identity$2(m); 2017 return m; 2018} 2019/** 2020* Returns a translation in tile units that correctly incorporates the view angle and the *-translate and *-translate-anchor properties. 2021* @param inViewportPixelUnitsUnits - True when the units accepted by the matrix are in viewport pixels instead of tile units. 2022*/ 2023function translatePosition(transform, tile, translate, translateAnchor, inViewportPixelUnitsUnits = false) { 2024 if (!translate[0] && !translate[1]) return [0, 0]; 2025 const angle = inViewportPixelUnitsUnits ? translateAnchor === "map" ? -transform.bearingInRadians : 0 : translateAnchor === "viewport" ? transform.bearingInRadians : 0; 2026 if (angle) { 2027 const sinA = Math.sin(angle); 2028 const cosA = Math.cos(angle); 2029 translate = [translate[0] * cosA - translate[1] * sinA, translate[0] * sinA + translate[1] * cosA]; 2030 } 2031 return [inViewportPixelUnitsUnits ? translate[0] : pixelsToTileUnits(tile, translate[0], transform.zoom), inViewportPixelUnitsUnits ? translate[1] : pixelsToTileUnits(tile, translate[1], transform.zoom)]; 2032} 2033/** 2034* Returns the signed distance between a point and a plane. 2035* @param plane - The plane equation, in the form where the first three components are the normal and the fourth component is the plane's distance from origin along normal. 2036* @param point - The point whose distance from plane is returned. 2037* @returns Signed distance of the point from the plane. Positive distances are in the half space where the plane normal points to, negative otherwise. 2038*/ 2039function pointPlaneSignedDistance(plane, point) { 2040 return plane[0] * point[0] + plane[1] * point[1] + plane[2] * point[2] + plane[3]; 2041} 2042/** 2043* Finds an intersection points of three planes. Returns `null` if no such (single) point exists. 2044* The planes *must* be in Hessian normal form - their xyz components must form a unit vector. 2045*/ 2046function threePlaneIntersection(plane0, plane1, plane2) { 2047 const det = determinant$1([ 2048 plane0[0], 2049 plane0[1], 2050 plane0[2], 2051 plane1[0], 2052 plane1[1], 2053 plane1[2], 2054 plane2[0], 2055 plane2[1], 2056 plane2[2] 2057 ]); 2058 if (det === 0) return null; 2059 const cross12 = cross$2([], [ 2060 plane1[0], 2061 plane1[1], 2062 plane1[2] 2063 ], [ 2064 plane2[0], 2065 plane2[1], 2066 plane2[2] 2067 ]); 2068 const cross20 = cross$2([], [ 2069 plane2[0], 2070 plane2[1], 2071 plane2[2] 2072 ], [ 2073 plane0[0], 2074 plane0[1], 2075 plane0[2] 2076 ]); 2077 const cross01 = cross$2([], [ 2078 plane0[0], 2079 plane0[1], 2080 plane0[2] 2081 ], [ 2082 plane1[0], 2083 plane1[1], 2084 plane1[2] 2085 ]); 2086 const sum = scale$4([], cross12, -plane0[3]); 2087 add$4(sum, sum, scale$4([], cross20, -plane1[3])); 2088 add$4(sum, sum, scale$4([], cross01, -plane2[3])); 2089 scale$4(sum, sum, 1 / det); 2090 return sum; 2091} 2092/** 2093* Returns a parameter `t` such that the point obtained by 2094* `origin + direction * t` lies on the given plane. 2095* If the ray is parallel to the plane, returns null. 2096* Returns a negative value if the ray is pointing away from the plane. 2097* Direction does not need to be normalized. 2098*/ 2099function rayPlaneIntersection(origin, direction, plane) { 2100 const dotOriginPlane = origin[0] * plane[0] + origin[1] * plane[1] + origin[2] * plane[2]; 2101 const dotDirectionPlane = direction[0] * plane[0] + direction[1] * plane[1] + direction[2] * plane[2]; 2102 if (dotDirectionPlane === 0) return null; 2103 return (-dotOriginPlane - plane[3]) / dotDirectionPlane; 2104} 2105/** 2106* Returns the angle in radians between two 2D vectors. 2107* The angle is signed and describes how much the first vector would need to be be rotated clockwise 2108* (assuming X is right and Y is down) so that it points in the same direction as the second vector. 2109* @param vec1x - The X component of the first vector. 2110* @param vec1y - The Y component of the first vector. 2111* @param vec2x - The X component of the second vector. 2112* @param vec2y - The Y component of the second vector. 2113* @returns The signed angle between the two vectors, in range -PI..PI. 2114*/ 2115function angleToRotateBetweenVectors2D(vec1x, vec1y, vec2x, vec2y) { 2116 const length1 = Math.sqrt(vec1x * vec1x + vec1y * vec1y); 2117 const length2 = Math.sqrt(vec2x * vec2x + vec2y * vec2y); 2118 vec1x /= length1; 2119 vec1y /= length1; 2120 vec2x /= length2; 2121 vec2y /= length2; 2122 const dot = vec1x * vec2x + vec1y * vec2y; 2123 const angle = Math.acos(dot); 2124 if (-vec1y * vec2x + vec1x * vec2y > 0) return angle; 2125 else return -angle; 2126} 2127/** 2128* For two angles in degrees, returns how many degrees to add to the first angle in order to obtain the second angle. 2129* The returned difference value is always the shorted of the two - its absolute value is never greater than 180°. 2130*/ 2131function differenceOfAnglesDegrees(degreesA, degreesB) { 2132 const a = mod(degreesA, 360); 2133 const b = mod(degreesB, 360); 2134 const diff1 = b - a; 2135 const diff2 = b > a ? diff1 - 360 : diff1 + 360; 2136 if (Math.abs(diff1) < Math.abs(diff2)) return diff1; 2137 else return diff2; 2138} 2139/** 2140* When given two angles in radians, returns the angular distance between them - the shorter one of the two possible arcs. 2141*/ 2142function distanceOfAnglesRadians(radiansA, radiansB) { 2143 const a = mod(radiansA, Math.PI * 2); 2144 const b = mod(radiansB, Math.PI * 2); 2145 return Math.min(Math.abs(a - b), Math.abs(a - b + Math.PI * 2), Math.abs(a - b - Math.PI * 2)); 2146} 2147/** 2148* Modulo function, as opposed to javascript's `%`, which is a remainder. 2149* This functions will return positive values, even if the first operand is negative. 2150*/ 2151function mod(n, m) { 2152 return (n % m + m) % m; 2153} 2154/** 2155* Takes a value in *old range*, linearly maps that range to *new range*, and returns the value in that new range. 2156* Additionally, if the value is outside *old range*, it is clamped inside it. 2157* Also works if one of the ranges is flipped (its `min` being larger than `max`). 2158*/ 2159function remapSaturate(value, oldRangeMin, oldRangeMax, newRangeMin, newRangeMax) { 2160 return lerp(newRangeMin, newRangeMax, clamp$2((value - oldRangeMin) / (oldRangeMax - oldRangeMin), 0, 1)); 2161} 2162/** 2163* Linearly interpolate between two values, similar to `mix` function from GLSL. No clamping is done. 2164* @param a - The first value to interpolate. This value is returned when mix=0. 2165* @param b - The second value to interpolate. This value is returned when mix=1. 2166* @param mix - The interpolation factor. Range 0..1 interpolates between `a` and `b`, but values outside this range are also accepted. 2167*/ 2168function lerp(a, b, mix) { 2169 return a * (1 - mix) + b * mix; 2170} 2171/** 2172* For a given collection of 2D points, returns their axis-aligned bounding box, 2173* in the format [minX, minY, maxX, maxY]. 2174*/ 2175function getAABB(points) { 2176 let tlX = Infinity; 2177 let tlY = Infinity; 2178 let brX = -Infinity; 2179 let brY = -Infinity; 2180 for (const p of points) { 2181 tlX = Math.min(tlX, p.x); 2182 tlY = Math.min(tlY, p.y); 2183 brX = Math.max(brX, p.x); 2184 brY = Math.max(brY, p.y); 2185 } 2186 return [ 2187 tlX, 2188 tlY, 2189 brX, 2190 brY 2191 ]; 2192} 2193/** 2194* For a given set of tile ids, returns the edge tile ids for the bounding box. 2195*/ 2196function getEdgeTiles(tileIDs) { 2197 if (!tileIDs.length) return /* @__PURE__ */ new Set(); 2198 const targetZ = Math.max(...tileIDs.map((id) => id.canonical.z)); 2199 let minX = Infinity, maxX = -Infinity; 2200 let minY = Infinity, maxY = -Infinity; 2201 const projected = []; 2202 for (const id of tileIDs) { 2203 const { x, y, z } = id.canonical; 2204 const scale = Math.pow(2, targetZ - z); 2205 const px = x * scale; 2206 const py = y * scale; 2207 projected.push({ 2208 id, 2209 x: px, 2210 y: py 2211 }); 2212 if (px < minX) minX = px; 2213 if (px > maxX) maxX = px; 2214 if (py < minY) minY = py; 2215 if (py > maxY) maxY = py; 2216 } 2217 const edgeTiles = /* @__PURE__ */ new Set(); 2218 for (const p of projected) if (p.x === minX || p.x === maxX || p.y === minY || p.y === maxY) edgeTiles.add(p.id); 2219 return edgeTiles; 2220} 2221/** 2222* Given a value `t` that varies between 0 and 1, return 2223* an interpolation function that eases between 0 and 1 in a pleasing 2224* cubic in-out fashion. 2225*/ 2226function easeCubicInOut(t) { 2227 if (t <= 0) return 0; 2228 if (t >= 1) return 1; 2229 const t2 = t * t, t3 = t2 * t; 2230 return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75); 2231} 2232/** 2233* Given given (x, y), (x1, y1) control points for a bezier curve, 2234* return a function that interpolates along that curve. 2235* 2236* @param p1x - control point 1 x coordinate 2237* @param p1y - control point 1 y coordinate 2238* @param p2x - control point 2 x coordinate 2239* @param p2y - control point 2 y coordinate 2240*/ 2241function bezier(p1x, p1y, p2x, p2y) { 2242 return unitBezier$1(p1x, p1y, p2x, p2y); 2243} 2244/** 2245* A default bezier-curve powered easing function with 2246* control points (0.25, 0.1) and (0.25, 1) 2247*/ 2248const defaultEasing = bezier(.25, .1, .25, 1); 2249/** 2250* constrain n to the given range via min + max 2251* 2252* @param n - value 2253* @param min - the minimum value to be returned 2254* @param max - the maximum value to be returned 2255* @returns the clamped value 2256*/ 2257function clamp$2(n, min, max) { 2258 return Math.min(max, Math.max(min, n)); 2259} 2260/** 2261* constrain n to the given range, excluding the minimum, via modular arithmetic 2262* 2263* @param n - value 2264* @param min - the minimum value to be returned, exclusive 2265* @param max - the maximum value to be returned, inclusive 2266* @returns constrained number 2267*/ 2268function wrap$1(n, min, max) { 2269 const d = max - min; 2270 const w = ((n - min) % d + d) % d + min; 2271 return w === min ? max : w; 2272} 2273function extend(dest, ...sources) { 2274 for (const src of sources) for (const k in src) dest[k] = src[k]; 2275 return dest; 2276} 2277/** 2278* Given an object and a number of properties as strings, return version 2279* of that object with only those properties. 2280* 2281* @param src - the object 2282* @param properties - an array of property names chosen 2283* to appear on the resulting object. 2284* @returns object with limited properties. 2285* @example 2286* ```ts 2287* let foo = { name: 'Charlie', age: 10 }; 2288* let justName = pick(foo, ['name']); // justName = { name: 'Charlie' } 2289* ``` 2290*/ 2291function pick(src, properties) { 2292 const result = {}; 2293 for (const k of properties) if (k in src) result[k] = src[k]; 2294 return result; 2295} 2296let id = 1; 2297/** 2298* Return a unique numeric id, starting at 1 and incrementing with 2299* each call. 2300* 2301* @returns unique numeric id. 2302*/ 2303function uniqueId() { 2304 return id++; 2305} 2306/** 2307* Return whether a given value is a power of two 2308*/ 2309function isPowerOfTwo(value) { 2310 return Math.log(value) / Math.LN2 % 1 === 0; 2311} 2312/** 2313* Return the next power of two, or the input value if already a power of two 2314*/ 2315function nextPowerOfTwo(value) { 2316 if (value <= 1) return 1; 2317 return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2)); 2318} 2319/** 2320* Computes scaling from zoom level. 2321*/ 2322function zoomScale(zoom) { 2323 return Math.pow(2, zoom); 2324} 2325/** 2326* Computes zoom level from scaling. 2327*/ 2328function scaleZoom(scale) { 2329 return Math.log(scale) / Math.LN2; 2330} 2331/** 2332* Evaluates the snapped zoom level based on zoomSnap. If zoomSnap is 0 or less, the zoom level is returned unchanged. 2333* If delta is provided, it performs directional snapping (ceil for zoom-in, floor for zoom-out). 2334* @param zoom - The input zoom level 2335* @param zoomSnap - The grid interval to snap to, e.g. 1.0 for 1.0 zoom levels, 0.5 for 0.5 zoom levels, etc. 2336* @param delta - Optional scroll delta or direction. If positive, snaps up; if negative, snaps down. 2337* @returns The snapped zoom level 2338*/ 2339function evaluateZoomSnap(zoom, zoomSnap, delta) { 2340 if (zoomSnap <= 0) return zoom; 2341 const inv = 1 / zoomSnap; 2342 if (delta === void 0 || Math.abs(delta) < 1e-10) return Math.round(zoom * inv) / inv; 2343 return (delta > 0 ? Math.ceil(zoom * inv - 1e-9) : Math.floor(zoom * inv + 1e-10)) / inv; 2344} 2345/** 2346* Create an object by mapping all the values of an existing object while 2347* preserving their keys. 2348*/ 2349function mapObject(input, iterator, context) { 2350 const output = {}; 2351 for (const key in input) output[key] = iterator.call(context || this, input[key], key, input); 2352 return output; 2353} 2354/** 2355* Create an object by filtering out values of an existing object. 2356*/ 2357function filterObject(input, iterator, context) { 2358 const output = {}; 2359 for (const key in input) if (iterator.call(context || this, input[key], key, input)) output[key] = input[key]; 2360 return output; 2361} 2362/** 2363* Deeply compares two object literals. 2364* @param a - first object literal to be compared 2365* @param b - second object literal to be compared 2366* @returns true if the two object literals are deeply equal, false otherwise 2367*/ 2368function deepEqual$1(a, b) { 2369 if (Array.isArray(a)) { 2370 if (!Array.isArray(b) || a.length !== b.length) return false; 2371 for (let i = 0; i < a.length; i++) if (!deepEqual$1(a[i], b[i])) return false; 2372 return true; 2373 } 2374 if (typeof a === "object" && a !== null && b !== null) { 2375 if (!(typeof b === "object")) return false; 2376 if (Object.keys(a).length !== Object.keys(b).length) return false; 2377 for (const key in a) if (!deepEqual$1(a[key], b[key])) return false; 2378 return true; 2379 } 2380 return a === b; 2381} 2382/** 2383* Deeply clones two objects. 2384*/ 2385function clone(input) { 2386 if (Array.isArray(input)) return input.map(clone); 2387 else if (typeof input === "object" && input) return mapObject(input, clone); 2388 else return input; 2389} 2390/** 2391* Print a warning message to the console and ensure duplicate warning messages 2392* are not printed. 2393*/ 2394const warnOnceHistory = {}; 2395function warnOnce(message) { 2396 if (!warnOnceHistory[message]) { 2397 if (typeof console !== "undefined") console.warn(message); 2398 warnOnceHistory[message] = true; 2399 } 2400} 2401/** 2402* Indicates if the provided Points are in a counter clockwise (true) or clockwise (false) order 2403* 2404* @returns true for a counter clockwise set of points 2405*/ 2406function isCounterClockwise(a, b, c) { 2407 return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x); 2408} 2409/** 2410* For two lines a and b in 2d space, defined by any two points along the lines, 2411* find the intersection point, or return null if the lines are parallel 2412* 2413* @param a1 - First point on line a 2414* @param a2 - Second point on line a 2415* @param b1 - First point on line b 2416* @param b2 - Second point on line b 2417* 2418* @returns the intersection point of the two lines or null if they are parallel 2419*/ 2420function findLineIntersection(a1, a2, b1, b2) { 2421 const aDeltaY = a2.y - a1.y; 2422 const aDeltaX = a2.x - a1.x; 2423 const bDeltaY = b2.y - b1.y; 2424 const bDeltaX = b2.x - b1.x; 2425 const denominator = bDeltaY * aDeltaX - bDeltaX * aDeltaY; 2426 if (denominator === 0) return null; 2427 const originDeltaY = a1.y - b1.y; 2428 const originDeltaX = a1.x - b1.x; 2429 const aInterpolation = (bDeltaX * originDeltaY - bDeltaY * originDeltaX) / denominator; 2430 return new Point(a1.x + aInterpolation * aDeltaX, a1.y + aInterpolation * aDeltaY); 2431} 2432/** 2433* Converts spherical coordinates to cartesian coordinates. 2434* 2435* @param spherical - Spherical coordinates, in [radial, azimuthal, polar] 2436* @returns cartesian coordinates in [x, y, z] 2437*/ 2438function sphericalToCartesian([r, azimuthal, polar]) { 2439 azimuthal += 90; 2440 azimuthal *= Math.PI / 180; 2441 polar *= Math.PI / 180; 2442 return [ 2443 r * Math.cos(azimuthal) * Math.sin(polar), 2444 r * Math.sin(azimuthal) * Math.sin(polar), 2445 r * Math.cos(polar) 2446 ]; 2447} 2448/** 2449* Returns true if the when run in the web-worker context. 2450* 2451* @returns `true` if the when run in the web-worker context. 2452*/ 2453function isWorker(self) { 2454 return typeof WorkerGlobalScope !== "undefined" && typeof self !== "undefined" && self instanceof WorkerGlobalScope; 2455} 2456/** 2457* Parses data from 'Cache-Control' headers. 2458* 2459* @param cacheControl - Value of 'Cache-Control' header 2460* @returns object containing parsed header info. 2461*/ 2462function parseCacheControl(cacheControl) { 2463 const re = /(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g; 2464 const header = {}; 2465 cacheControl.replace(re, ($0, $1, $2, $3) => { 2466 const value = $2 || $3; 2467 header[$1] = value ? value.toLowerCase() : true; 2468 return ""; 2469 }); 2470 if (header["max-age"]) { 2471 const maxAge = parseInt(header["max-age"], 10); 2472 if (isNaN(maxAge)) delete header["max-age"]; 2473 else header["max-age"] = maxAge; 2474 } 2475 return header; 2476} 2477let _isSafari = null; 2478/** 2479* Returns true when run in WebKit derived browsers. 2480* This is used as a workaround for a memory leak in Safari caused by using Transferable objects to 2481* transfer data between WebWorkers and the main thread. 2482* https://github.com/mapbox/mapbox-gl-js/issues/8771 2483* 2484* This should be removed once the underlying Safari issue is fixed. 2485* 2486* @param scope - Since this function is used both on the main thread and WebWorker context, 2487* let the calling scope pass in the global scope object. 2488* @returns `true` when run in WebKit derived browsers. 2489*/ 2490function isSafari(scope) { 2491 if (_isSafari == null) { 2492 const userAgent = scope.navigator ? scope.navigator.userAgent : null; 2493 _isSafari = !!scope.safari || !!(userAgent && (/\b(iPad|iPhone|iPod)\b/.test(userAgent) || !!userAgent.match("Safari") && !userAgent.match("Chrome"))); 2494 } 2495 return _isSafari; 2496} 2497function isImageBitmap(image) { 2498 return typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap; 2499} 2500/** 2501* Converts an ArrayBuffer to an ImageBitmap. 2502* 2503* Used mostly for testing purposes only, because mocking libs don't know how to work with ArrayBuffers, but work 2504* perfectly fine with ImageBitmaps. Might also be used for environments (other than testing) not supporting 2505* ArrayBuffers. 2506* 2507* @param data - Data to convert 2508* @returns - A promise resolved when the conversion is finished 2509*/ 2510const arrayBufferToImageBitmap = async (data, options) => { 2511 const blob = new Blob([new Uint8Array(data)], { type: "image/png" }); 2512 try { 2513 return createImageBitmap(blob, options); 2514 } catch (e) { 2515 throw new Error(`Could not load image because of ${ensureError(e).message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`); 2516 } 2517}; 2518const transparentPngUrl = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII="; 2519/** 2520* Converts an ArrayBuffer to an HTMLImageElement. 2521* 2522* Used mostly for testing purposes only, because mocking libs don't know how to work with ArrayBuffers, but work 2523* perfectly fine with ImageBitmaps. Might also be used for environments (other than testing) not supporting 2524* ArrayBuffers. 2525* 2526* @param data - Data to convert 2527* @returns - A promise resolved when the conversion is finished 2528*/ 2529const arrayBufferToImage = (data) => { 2530 return new Promise((resolve, reject) => { 2531 const img = new Image(); 2532 img.onload = () => { 2533 resolve(img); 2534 URL.revokeObjectURL(img.src); 2535 img.onload = null; 2536 window.requestAnimationFrame(() => img.src = transparentPngUrl); 2537 }; 2538 img.onerror = () => reject(/* @__PURE__ */ new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.")); 2539 const blob = new Blob([new Uint8Array(data)], { type: "image/png" }); 2540 img.src = URL.createObjectURL(blob); 2541 }); 2542}; 2543/** 2544* Computes the webcodecs VideoFrame API options to select a rectangle out of 2545* an image and write it into the destination rectangle. 2546* 2547* Rect (x/y/width/height) select the overlapping rectangle from the source image 2548* and layout (offset/stride) write that overlapping rectangle to the correct place 2549* in the destination image. 2550* 2551* Offset is the byte offset in the dest image that the first pixel appears at 2552* and stride is the number of bytes to the start of the next row: 2553* âââââââââââââ 2554* â dest â 2555* â âââââ¼ââââââââ 2556* âoffsetââââââ sourceâ 2557* â âââââ â 2558* â âââââ¼ââââââââ 2559* âstride â ââââ 2560* ââââââââ â 2561* âââââââââââââ 2562* 2563* @param image - source image containing a width and height attribute 2564* @param x - top-left x coordinate to read from the image 2565* @param y - top-left y coordinate to read from the image 2566* @param width - width of the rectangle to read from the image 2567* @param height - height of the rectangle to read from the image 2568* @returns the layout and rect options to pass into VideoFrame API 2569*/ 2570function computeVideoFrameParameters(image, x, y, width, height) { 2571 const destRowOffset = Math.max(-x, 0) * 4; 2572 const offset = (Math.max(0, y) - y) * width * 4 + destRowOffset; 2573 const stride = width * 4; 2574 const sourceLeft = Math.max(0, x); 2575 const sourceTop = Math.max(0, y); 2576 const sourceRight = Math.min(image.width, x + width); 2577 const sourceBottom = Math.min(image.height, y + height); 2578 return { 2579 rect: { 2580 x: sourceLeft, 2581 y: sourceTop, 2582 width: sourceRight - sourceLeft, 2583 height: sourceBottom - sourceTop 2584 }, 2585 layout: [{ 2586 offset, 2587 stride 2588 }] 2589 }; 2590} 2591/** 2592* Reads pixels from an ImageBitmap/Image/canvas using webcodec VideoFrame API. 2593* 2594* @param data - image, imagebitmap, or canvas to parse 2595* @param x - top-left x coordinate to read from the image 2596* @param y - top-left y coordinate to read from the image 2597* @param width - width of the rectangle to read from the image 2598* @param height - height of the rectangle to read from the image 2599* @returns a promise containing the parsed RGBA pixel values of the image, or the error if an error occurred 2600*/ 2601async function readImageUsingVideoFrame(image, x, y, width, height) { 2602 if (typeof VideoFrame === "undefined") throw new Error("VideoFrame not supported"); 2603 const frame = new VideoFrame(image, { timestamp: 0 }); 2604 try { 2605 const format = frame?.format; 2606 if (!format || !(format.startsWith("BGR") || format.startsWith("RGB"))) throw new Error(`Unrecognized format ${format}`); 2607 const swapBR = format.startsWith("BGR"); 2608 const result = new Uint8ClampedArray(width * height * 4); 2609 await frame.copyTo(result, computeVideoFrameParameters(image, x, y, width, height)); 2610 if (swapBR) for (let i = 0; i < result.length; i += 4) { 2611 const tmp = result[i]; 2612 result[i] = result[i + 2]; 2613 result[i + 2] = tmp; 2614 } 2615 return result; 2616 } finally { 2617 frame.close(); 2618 } 2619} 2620let offscreenCanvas; 2621let offscreenCanvasContext; 2622/** 2623* Reads pixels from an ImageBitmap/Image/canvas using OffscreenCanvas 2624* 2625* @param data - image, imagebitmap, or canvas to parse 2626* @param x - top-left x coordinate to read from the image 2627* @param y - top-left y coordinate to read from the image 2628* @param width - width of the rectangle to read from the image 2629* @param height - height of the rectangle to read from the image 2630* @returns a promise containing the parsed RGBA pixel values of the image, or the error if an error occurred 2631*/ 2632function readImageDataUsingOffscreenCanvas(imgBitmap, x, y, width, height) { 2633 const origWidth = imgBitmap.width; 2634 const origHeight = imgBitmap.height; 2635 if (!offscreenCanvas || !offscreenCanvasContext) { 2636 offscreenCanvas = new OffscreenCanvas(origWidth, origHeight); 2637 offscreenCanvasContext = offscreenCanvas.getContext("2d", { willReadFrequently: true }); 2638 } 2639 offscreenCanvas.width = origWidth; 2640 offscreenCanvas.height = origHeight; 2641 offscreenCanvasContext.drawImage(imgBitmap, 0, 0, origWidth, origHeight); 2642 const imgData = offscreenCanvasContext.getImageData(x, y, width, height); 2643 offscreenCanvasContext.clearRect(0, 0, origWidth, origHeight); 2644 return imgData.data; 2645} 2646/** 2647* Reads RGBA pixels from an preferring OffscreenCanvas, but falling back to VideoFrame if supported and 2648* the browser is mangling OffscreenCanvas getImageData results. 2649* 2650* @param data - image, imagebitmap, or canvas to parse 2651* @param x - top-left x coordinate to read from the image 2652* @param y - top-left y coordinate to read from the image 2653* @param width - width of the rectangle to read from the image 2654* @param height - height of the rectangle to read from the image 2655* @returns a promise containing the parsed RGBA pixel values of the image 2656*/ 2657async function getImageData(image, x, y, width, height) { 2658 if (isOffscreenCanvasDistorted()) try { 2659 return await readImageUsingVideoFrame(image, x, y, width, height); 2660 } catch {} 2661 return readImageDataUsingOffscreenCanvas(image, x, y, width, height); 2662} 2663/** 2664* This method is used in order to register an event listener using a lambda function. 2665* The return value will allow unsubscribing from the event, without the need to store the method reference. 2666* @param target - The target 2667* @param message - The message 2668* @param listener - The listener 2669* @param options - The options 2670* @returns a subscription object that can be used to unsubscribe from the event 2671*/ 2672function subscribe(target, message, listener, options) { 2673 target.addEventListener(message, listener, options); 2674 return { unsubscribe: () => { 2675 target.removeEventListener(message, listener, options); 2676 } }; 2677} 2678/** 2679* This method converts degrees to radians. 2680* The return value is the radian value. 2681* @param degrees - The number of degrees 2682* @returns radians 2683*/ 2684function degreesToRadians(degrees) { 2685 return degrees * Math.PI / 180; 2686} 2687/** 2688* This method converts radians to degrees. 2689* The return value is the degrees value. 2690* @param degrees - The number of radians 2691* @returns degrees 2692*/ 2693function radiansToDegrees(degrees) { 2694 return degrees / Math.PI * 180; 2695} 2696function rollPitchBearingEqual(a, b) { 2697 return a.roll == b.roll && a.pitch == b.pitch && a.bearing == b.bearing; 2698} 2699/** 2700* This method converts a rotation quaternion to roll, pitch, and bearing angles in degrees. 2701* @param rotation - The rotation quaternion 2702* @returns roll, pitch, and bearing angles in degrees 2703*/ 2704function getRollPitchBearing(rotation) { 2705 const m = /* @__PURE__ */ new Float64Array(9); 2706 fromQuat$1(m, rotation); 2707 const xAngle = radiansToDegrees(-Math.asin(clamp$2(m[2], -1, 1))); 2708 let roll; 2709 let bearing; 2710 if (Math.hypot(m[5], m[8]) < .001) { 2711 roll = 0; 2712 bearing = -radiansToDegrees(Math.atan2(m[3], m[4])); 2713 } else { 2714 roll = radiansToDegrees(m[5] === 0 && m[8] === 0 ? 0 : Math.atan2(m[5], m[8])); 2715 bearing = radiansToDegrees(m[1] === 0 && m[0] === 0 ? 0 : Math.atan2(m[1], m[0])); 2716 } 2717 return { 2718 roll, 2719 pitch: xAngle + 90, 2720 bearing 2721 }; 2722} 2723function getAngleDelta(lastPoint, currentPoint, center) { 2724 const pointVect = fromValues(currentPoint.x - center.x, currentPoint.y - center.y); 2725 const lastPointVec = fromValues(lastPoint.x - center.x, lastPoint.y - center.y); 2726 const crossProduct = pointVect[0] * lastPointVec[1] - pointVect[1] * lastPointVec[0]; 2727 return radiansToDegrees(Math.atan2(crossProduct, dot$1(pointVect, lastPointVec))); 2728} 2729/** 2730* This method converts roll, pitch, and bearing angles in degrees to a rotation quaternion. 2731* @param roll - Roll angle in degrees 2732* @param pitch - Pitch angle in degrees 2733* @param bearing - Bearing angle in degrees 2734* @returns The rotation quaternion 2735*/ 2736function rollPitchBearingToQuat(roll, pitch, bearing) { 2737 const rotation = /* @__PURE__ */ new Float64Array(4); 2738 fromEuler(rotation, roll, pitch - 90, bearing); 2739 return rotation; 2740} 2741const MAX_VALID_LATITUDE = 85.051129; 2742const touchableEvents = { 2743 touchstart: true, 2744 touchmove: true, 2745 touchmoveWindow: true, 2746 touchend: true, 2747 touchcancel: true 2748}; 2749const pointableEvents = { 2750 dblclick: true, 2751 click: true, 2752 mouseover: true, 2753 mouseout: true, 2754 mousedown: true, 2755 mousemove: true, 2756 mousemoveWindow: true, 2757 mouseup: true, 2758 mouseupWindow: true, 2759 contextmenu: true, 2760 wheel: true 2761}; 2762function isTouchableEvent(event, eventType) { 2763 return touchableEvents[eventType] && "touches" in event; 2764} 2765/** 2766* Checks if an event is a pointable event (mouse or wheel event). 2767* Uses the event target's window context for cross-window support. 2768*/ 2769function isPointableEvent(event, eventType) { 2770 if (!pointableEvents[eventType]) return false; 2771 const domEvent = event; 2772 const targetWindow = (domEvent?.target)?.ownerDocument?.defaultView || window; 2773 return domEvent instanceof targetWindow.MouseEvent || domEvent instanceof targetWindow.WheelEvent; 2774} 2775function isTouchableOrPointableType(eventType) { 2776 return touchableEvents[eventType] || pointableEvents[eventType]; 2777} 2778//#endregion 2779//#region src/util/abort_error.ts 2780/** 2781* An error message to use when an operation is aborted 2782*/ 2783const ABORT_ERROR = "AbortError"; 2784var AbortError = class extends Error { 2785 constructor(messageOrError = ABORT_ERROR) { 2786 super(messageOrError instanceof Error ? messageOrError.message : messageOrError); 2787 this.name = ABORT_ERROR; 2788 if (messageOrError instanceof Error && messageOrError.stack) this.stack = messageOrError.stack; 2789 } 2790}; 2791/** 2792* Check if an error is an abort error 2793* @param error - An error object 2794* @returns - true if the error is an abort error 2795*/ 2796function isAbortError(error) { 2797 return error instanceof Error && error.name === "AbortError"; 2798} 2799/** 2800* Throws an AbortError if the provided abort signal has already been aborted. 2801* 2802* @param signal - The abort signal to check. 2803* @throws AbortError If the signal is aborted. 2804*/ 2805function throwIfAborted(signal) { 2806 if (signal.aborted) throw new AbortError(signal.reason); 2807} 2808//#endregion 2809//#region src/util/config.ts 2810const config = { 2811 MAX_PARALLEL_IMAGE_REQUESTS: 16, 2812 MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME: 8, 2813 MAX_TILE_CACHE_ZOOM_LEVELS: 5, 2814 REGISTERED_PROTOCOLS: {}, 2815 WORKER_URL: "" 2816}; 2817//#endregion 2818//#region src/source/protocol_crud.ts 2819function getProtocol(url) { 2820 return config.REGISTERED_PROTOCOLS[url.substring(0, url.indexOf("://"))]; 2821} 2822/** 2823* Adds a custom load resource function that will be called when using a URL that starts with a custom url schema. 2824* This will happen in the main thread, and workers might call it if they don't know how to handle the protocol. 2825* The example below will be triggered for custom:// urls defined in the sources list in the style definitions. 2826* The function passed will receive the request parameters and should return with the resulting resource. 2827* `requestParameters.type` says which kind of resource is expected. A tile is an `ArrayBuffer`, for example 2828* a non-compressed pbf vector tile. An image is either its encoded bytes or an `ImageBitmap`/`HTMLImageElement`, 2829* which is used without decoding. See {@link AddProtocolResponseData} for every accepted shape. 2830* 2831* @param customProtocol - the protocol to hook, for example 'custom' 2832* @param loadFn - the function to use when trying to fetch a tile specified by the customProtocol 2833* @example 2834* ```ts 2835* // This will fetch a file using the fetch API (this is obviously a non interesting example...) 2836* addProtocol('custom', async (params, abortController) => { 2837* const t = await fetch(`https://${params.url.split("://")[1]}`); 2838* if (t.status == 200) { 2839* const buffer = await t.arrayBuffer(); 2840* return {data: buffer} 2841* } else { 2842* throw new Error(`Tile fetch error: ${t.statusText}`); 2843* } 2844* }); 2845* // the following is an example of a way to return an error when trying to load a tile 2846* addProtocol('custom2', async (params, abortController) => { 2847* throw new Error('someErrorMessage'); 2848* }); 2849* // An image handler that draws or computes its tiles can return them decoded, as an ImageBitmap. 2850* addProtocol('drawn', async (params, abortController) => { 2851* const canvas = new OffscreenCanvas(256, 256); 2852* // ... draw the tile ... 2853* return {data: await createImageBitmap(canvas)}; 2854* }); 2855* ``` 2856* @see [Add a COG raster source](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-cog-raster-source/) 2857* @see [Add Contour Lines](https://maplibre.org/maplibre-gl-js/docs/examples/add-contour-lines/) 2858* @see [PMTiles source and protocol](https://maplibre.org/maplibre-gl-js/docs/examples/pmtiles-source-and-protocol/) 2859* @see [Use addProtocol to Transform Feature Properties](https://maplibre.org/maplibre-gl-js/docs/examples/use-addprotocol-to-transform-feature-properties/) 2860*/ 2861function addProtocol(customProtocol, loadFn) { 2862 config.REGISTERED_PROTOCOLS[customProtocol] = loadFn; 2863} 2864/** 2865* Removes a previously added protocol in the main thread. 2866* 2867* @param customProtocol - the custom protocol to remove registration for 2868* @example 2869* ```ts 2870* removeProtocol('custom'); 2871* ``` 2872*/ 2873function removeProtocol(customProtocol) { 2874 delete config.REGISTERED_PROTOCOLS[customProtocol]; 2875} 2876//#endregion 2877//#region src/util/ajax.ts 2878/** 2879* This is used to identify the global dispatcher id when sending a message from the worker without a target map id. 2880*/ 2881const GLOBAL_DISPATCHER_ID = "global-dispatcher"; 2882/** 2883* An error thrown when a HTTP request results in an error response. 2884*/ 2885var AJAXError = class extends Error { 2886 /** 2887 * @param status - The response's HTTP status code. 2888 * @param statusText - The response's HTTP status text. 2889 * @param url - The request's URL. 2890 * @param body - The response's body. 2891 */ 2892 constructor(status, statusText, url, body) { 2893 super(`AJAXError: ${statusText} (${status}): ${url}`); 2894 this.status = status; 2895 this.statusText = statusText; 2896 this.url = url; 2897 this.body = body; 2898 } 2899}; 2900/** 2901* Ensure that we're sending the correct referrer from blob URL worker bundles. 2902* For files loaded from the local file system, `location.origin` will be set 2903* to the string(!) "null" (Firefox), or "file://" (Chrome, Safari, Edge), 2904* and we will set an empty referrer. Otherwise, we're using the document's URL. 2905* If we're on a blob URL and parent window is cross-origin, parent.location throws 2906* SecurityError DOMException, this means we are probably not in blob URL worker bundle. 2907*/ 2908function getReferrer() { 2909 if (isWorker(self)) return self.worker?.referrer; 2910 if (window.location.protocol === "blob:") try { 2911 return window.parent.location.href; 2912 } catch {} 2913 return window.location.href; 2914} 2915/** 2916* Determines whether a URL is a file:// URL. This is obviously the case if it begins 2917* with file://. Relative URLs are also file:// URLs iff the original document was loaded 2918* via a file:// URL. 2919* @param url - The URL to check 2920* @returns `true` if the URL is a file:// URL, `false` otherwise 2921*/ 2922const isFileURL = (url) => url.startsWith("file:") || getReferrer()?.startsWith("file:") && !/^\w+:/.test(url); 2923async function makeFetchRequest(requestParameters, abortController) { 2924 const request = new Request(requestParameters.url, { 2925 method: requestParameters.method || "GET", 2926 body: requestParameters.body, 2927 credentials: requestParameters.credentials, 2928 headers: requestParameters.headers, 2929 cache: requestParameters.cache, 2930 referrer: getReferrer(), 2931 referrerPolicy: requestParameters.referrerPolicy, 2932 signal: abortController.signal 2933 }); 2934 if (requestParameters.type === "json" && !request.headers.has("Accept")) request.headers.set("Accept", "application/json"); 2935 let response; 2936 try { 2937 response = await fetch(request); 2938 } catch (e) { 2939 if (isAbortError(e)) throw e; 2940 throw new AJAXError(0, ensureError(e).message, requestParameters.url, new Blob()); 2941 } 2942 if (!response.ok) { 2943 const body = await response.blob(); 2944 throw new AJAXError(response.status, response.statusText, requestParameters.url, body); 2945 } 2946 let parsePromise; 2947 if (requestParameters.type === "arrayBuffer" || requestParameters.type === "image") parsePromise = response.arrayBuffer(); 2948 else if (requestParameters.type === "json") parsePromise = response.json(); 2949 else parsePromise = response.text(); 2950 const result = await parsePromise; 2951 throwIfAborted(abortController.signal); 2952 return { 2953 data: result, 2954 cacheControl: response.headers.get("Cache-Control"), 2955 expires: response.headers.get("Expires"), 2956 etag: response.headers.get("ETag") 2957 }; 2958} 2959function makeXMLHttpRequest(requestParameters, abortController) { 2960 return new Promise((resolve, reject) => { 2961 const xhr = new XMLHttpRequest(); 2962 xhr.open(requestParameters.method || "GET", requestParameters.url, true); 2963 if (requestParameters.type === "arrayBuffer" || requestParameters.type === "image") xhr.responseType = "arraybuffer"; 2964 for (const k in requestParameters.headers) xhr.setRequestHeader(k, requestParameters.headers[k]); 2965 if (requestParameters.type === "json") { 2966 xhr.responseType = "text"; 2967 if (!requestParameters.headers?.Accept) xhr.setRequestHeader("Accept", "application/json"); 2968 } 2969 xhr.withCredentials = requestParameters.credentials === "include"; 2970 xhr.onerror = () => { 2971 reject(new Error(xhr.statusText)); 2972 }; 2973 xhr.onload = () => { 2974 if (abortController.signal.aborted) return; 2975 if ((xhr.status >= 200 && xhr.status < 300 || xhr.status === 0) && xhr.response !== null) { 2976 let data = xhr.response; 2977 if (requestParameters.type === "json") try { 2978 data = JSON.parse(xhr.response); 2979 } catch (err) { 2980 reject(err); 2981 return; 2982 } 2983 resolve({ 2984 data, 2985 cacheControl: xhr.getResponseHeader("Cache-Control"), 2986 expires: xhr.getResponseHeader("Expires"), 2987 etag: xhr.getResponseHeader("ETag") 2988 }); 2989 } else { 2990 const body = new Blob([xhr.response], { type: xhr.getResponseHeader("Content-Type") }); 2991 reject(new AJAXError(xhr.status, xhr.statusText, requestParameters.url, body)); 2992 } 2993 }; 2994 abortController.signal.addEventListener("abort", () => { 2995 xhr.abort(); 2996 reject(new AbortError(abortController.signal.reason)); 2997 }); 2998 xhr.send(requestParameters.body); 2999 }); 3000} 3001/** 3002* We're trying to use the Fetch API if possible. However, requests for resources with the file:// URI scheme don't work with the Fetch API. 3003* In this case we unconditionally use XHR on the current thread since referrers don't matter. 3004* This method can also use the registered method if `addProtocol` was called. 3005* @param requestParameters - The request parameters 3006* @param abortController - The abort controller allowing to cancel the request 3007* @returns a promise resolving to the response, including cache control and expiry data 3008*/ 3009const makeRequest = async function(requestParameters, abortController) { 3010 if (requestParameters.url.includes("://") && !/^https?:|^file:/.test(requestParameters.url)) { 3011 const protocolLoadFn = getProtocol(requestParameters.url); 3012 if (protocolLoadFn) { 3013 const response = await protocolLoadFn(requestParameters, abortController); 3014 if (!response.data && requestParameters.type === "arrayBuffer") return extend(response, { data: /* @__PURE__ */ new ArrayBuffer(0) }); 3015 return response; 3016 } 3017 if (isWorker(self) && self.worker?.actor) return self.worker.actor.sendAsync({ 3018 type: "GR", 3019 data: requestParameters, 3020 targetMapId: GLOBAL_DISPATCHER_ID 3021 }, abortController); 3022 } 3023 if (!isFileURL(requestParameters.url)) { 3024 if (fetch && Request && AbortController && Object.hasOwn(Request.prototype, "signal")) return makeFetchRequest(requestParameters, abortController); 3025 if (isWorker(self) && self.worker?.actor) return self.worker.actor.sendAsync({ 3026 type: "GR", 3027 data: requestParameters, 3028 mustQueue: true, 3029 targetMapId: GLOBAL_DISPATCHER_ID 3030 }, abortController); 3031 } 3032 return makeXMLHttpRequest(requestParameters, abortController); 3033}; 3034const getJSON = (requestParameters, abortController) => { 3035 return makeRequest(extend(requestParameters, { type: "json" }), abortController); 3036}; 3037const getArrayBuffer = (requestParameters, abortController) => { 3038 return makeRequest(extend(requestParameters, { type: "arrayBuffer" }), abortController); 3039}; 3040/** 3041* Determines whether a URL is same origin as the current location. Supports relative URLs too. 3042* 3043* A relative URL "/foo" or "./foo" will throw exception in URL's ctor, 3044* try-catch is expansive so just use a heuristic check to avoid it 3045* 3046* - Relative URL and empty URL are always same origin. 3047* - data URL containing an image is always same origin. 3048* - blob URL is checked using `URL` constructor by its parent URL; opaque blob URL is never same origin. 3049* - Absolute URL is checked using `URL` constructor. 3050* 3051* Checks blob URL before relative URL because opaque blob URL does not contain `://` too. 3052* 3053* @param inComingUrl - The URL to check 3054* @returns `true` if the URL is same origin as current location, `false` otherwise 3055*/ 3056function sameOrigin(inComingUrl) { 3057 if (!inComingUrl) return true; 3058 if (inComingUrl.startsWith("data:image/")) return true; 3059 if (inComingUrl.startsWith("blob:")) { 3060 inComingUrl = inComingUrl.slice(5); 3061 if (inComingUrl.startsWith("null")) return false; 3062 } 3063 if (inComingUrl.indexOf("://") <= 0) return true; 3064 const urlObj = new URL(inComingUrl); 3065 const locationObj = window.location; 3066 return urlObj.protocol === locationObj.protocol && urlObj.host === locationObj.host; 3067} 3068const getVideo = (urls) => { 3069 const video = window.document.createElement("video"); 3070 video.muted = true; 3071 return new Promise((resolve) => { 3072 video.onloadstart = () => { 3073 resolve(video); 3074 }; 3075 for (const url of urls) { 3076 const s = window.document.createElement("source"); 3077 if (!sameOrigin(url)) video.crossOrigin = "Anonymous"; 3078 s.src = url; 3079 video.appendChild(s); 3080 } 3081 }); 3082}; 3083//#endregion 3084//#region src/util/evented.ts 3085function _addEventListener(type, listener, listenerList) { 3086 if (!listenerList[type]?.includes(listener)) { 3087 listenerList[type] ||= []; 3088 listenerList[type].push(listener); 3089 } 3090} 3091function _removeEventListener(type, listener, listenerList) { 3092 if (listenerList?.[type]) { 3093 const index = listenerList[type].indexOf(listener); 3094 if (index !== -1) listenerList[type].splice(index, 1); 3095 } 3096} 3097/** 3098* The event class 3099*/ 3100var Event = class { 3101 constructor(type, data = {}) { 3102 extend(this, data); 3103 this.type = type; 3104 } 3105}; 3106/** 3107* An error event 3108*/ 3109var ErrorEvent = class extends Event { 3110 constructor(error, data = {}) { 3111 super("error", extend({ error }, data)); 3112 } 3113}; 3114/** 3115* Methods mixed in to other classes for event capabilities. 3116* 3117* @group Event Related 3118*/ 3119var Evented = class { 3120 /** 3121 * Adds a listener to a specified event type. 3122 * 3123 * @param type - The event type to add a listen for. 3124 * @param listener - The function to be called when the event is fired. 3125 * The listener function is called with the data object passed to `fire`, 3126 * extended with `target` and `type` properties. 3127 */ 3128 on(type, listener) { 3129 this._listeners ||= {}; 3130 _addEventListener(type, listener, this._listeners); 3131 return { unsubscribe: () => { 3132 this.off(type, listener); 3133 } }; 3134 } 3135 /** 3136 * Removes a previously registered event listener. 3137 * 3138 * @param type - The event type to remove listeners for. 3139 * @param listener - The listener function to remove. 3140 */ 3141 off(type, listener) { 3142 _removeEventListener(type, listener, this._listeners); 3143 _removeEventListener(type, listener, this._oneTimeListeners); 3144 return this; 3145 } 3146 once(type, listener) { 3147 if (!listener) return new Promise((resolve) => this.once(type, resolve)); 3148 this._oneTimeListeners ||= {}; 3149 _addEventListener(type, listener, this._oneTimeListeners); 3150 return this; 3151 } 3152 fire(event, properties) { 3153 const firedEvent = typeof event === "string" ? new Event(event, properties || {}) : event; 3154 const type = firedEvent.type; 3155 if (this.listens(type)) { 3156 firedEvent.target = this; 3157 const listeners = this._listeners?.[type]?.slice() ?? []; 3158 for (const listener of listeners) listener.call(this, firedEvent); 3159 const oneTimeListeners = this._oneTimeListeners?.[type]?.slice() ?? []; 3160 for (const listener of oneTimeListeners) { 3161 _removeEventListener(type, listener, this._oneTimeListeners); 3162 listener.call(this, firedEvent); 3163 } 3164 const parent = this._eventedParent; 3165 if (parent) { 3166 extend(firedEvent, typeof this._eventedParentData === "function" ? this._eventedParentData() : this._eventedParentData); 3167 parent.fire(firedEvent); 3168 } 3169 } else if (firedEvent instanceof ErrorEvent) console.error(firedEvent.error); 3170 return this; 3171 } 3172 /** 3173 * Returns a true if this instance of Evented or any forwardeed instances of Evented have a listener for the specified type. 3174 * 3175 * @param type - The event type 3176 * @returns `true` if there is at least one registered listener for specified event type, `false` otherwise 3177 */ 3178 listens(type) { 3179 return Boolean(this._listeners?.[type]?.length || this._oneTimeListeners?.[type]?.length || this._eventedParent?.listens(type)); 3180 } 3181 /** 3182 * Bubble all events fired by this instance of Evented to this parent instance of Evented. 3183 */ 3184 setEventedParent(parent, data) { 3185 this._eventedParent = parent; 3186 this._eventedParentData = data; 3187 return this; 3188 } 3189}; 3190//#endregion 3191//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/reference/v8.mjs 3192var v8_default = { 3193 $version: 8, 3194 $root: { 3195 "version": { 3196 "required": true, 3197 "type": "enum", 3198 "values": [8] 3199 }, 3200 "name": { "type": "string" }, 3201 "metadata": { "type": "*" }, 3202 "center": { 3203 "type": "array", 3204 "value": "number", 3205 "length": 2 3206 }, 3207 "centerAltitude": { "type": "number" }, 3208 "zoom": { "type": "number" }, 3209 "bearing": { 3210 "type": "number", 3211 "default": 0, 3212 "period": 360, 3213 "units": "degrees" 3214 }, 3215 "pitch": { 3216 "type": "number", 3217 "default": 0, 3218 "units": "degrees" 3219 }, 3220 "roll": { 3221 "type": "number", 3222 "default": 0, 3223 "units": "degrees" 3224 }, 3225 "state": { 3226 "type": "state", 3227 "default": {} 3228 }, 3229 "light": { "type": "light" }, 3230 "sky": { "type": "sky" }, 3231 "projection": { "type": "projection" }, 3232 "terrain": { "type": "terrain" }, 3233 "sources": { 3234 "required": true, 3235 "type": "sources" 3236 }, 3237 "sprite": { "type": "sprite" }, 3238 "glyphs": { "type": "string" }, 3239 "font-faces": { "type": "fontFaces" }, 3240 "transition": { "type": "transition" }, 3241 "layers": { 3242 "required": true, 3243 "type": "array", 3244 "value": "layer" 3245 } 3246 }, 3247 sources: { "*": { "type": "source" } }, 3248 source: [ 3249 "source_vector", 3250 "source_raster", 3251 "source_raster_dem", 3252 "source_geojson", 3253 "source_video", 3254 "source_image" 3255 ], 3256 source_vector: { 3257 "type": { 3258 "required": true, 3259 "type": "enum", 3260 "values": { "vector": {} } 3261 }, 3262 "url": { "type": "string" }, 3263 "tiles": { 3264 "type": "array", 3265 "value": "string" 3266 }, 3267 "bounds": { 3268 "type": "array", 3269 "value": "number", 3270 "length": 4, 3271 "default": [ 3272 -180, 3273 -85.051129, 3274 180, 3275 85.051129 3276 ] 3277 }, 3278 "scheme": { 3279 "type": "enum", 3280 "values": { 3281 "xyz": {}, 3282 "tms": {} 3283 }, 3284 "default": "xyz" 3285 }, 3286 "minzoom": { 3287 "type": "number", 3288 "default": 0 3289 }, 3290 "maxzoom": { 3291 "type": "number", 3292 "default": 22 3293 }, 3294 "attribution": { "type": "string" }, 3295 "promoteId": { "type": "promoteId" }, 3296 "volatile": { 3297 "type": "boolean", 3298 "default": false 3299 }, 3300 "encoding": { 3301 "type": "enum", 3302 "values": { 3303 "mvt": {}, 3304 "mlt": {} 3305 }, 3306 "default": "mvt" 3307 }, 3308 "*": { "type": "*" } 3309 }, 3310 source_raster: { 3311 "type": { 3312 "required": true, 3313 "type": "enum", 3314 "values": { "raster": {} } 3315 }, 3316 "url": { "type": "string" }, 3317 "tiles": { 3318 "type": "array", 3319 "value": "string" 3320 }, 3321 "bounds": { 3322 "type": "array", 3323 "value": "number", 3324 "length": 4, 3325 "default": [ 3326 -180, 3327 -85.051129, 3328 180, 3329 85.051129 3330 ] 3331 }, 3332 "minzoom": { 3333 "type": "number", 3334 "default": 0 3335 }, 3336 "maxzoom": { 3337 "type": "number", 3338 "default": 22 3339 }, 3340 "tileSize": { 3341 "type": "number", 3342 "default": 512, 3343 "units": "pixels" 3344 }, 3345 "scheme": { 3346 "type": "enum", 3347 "values": { 3348 "xyz": {}, 3349 "tms": {} 3350 }, 3351 "default": "xyz" 3352 }, 3353 "attribution": { "type": "string" }, 3354 "volatile": { 3355 "type": "boolean", 3356 "default": false 3357 }, 3358 "*": { "type": "*" } 3359 }, 3360 source_raster_dem: { 3361 "type": { 3362 "required": true, 3363 "type": "enum", 3364 "values": { "raster-dem": {} } 3365 }, 3366 "url": { "type": "string" }, 3367 "tiles": { 3368 "type": "array", 3369 "value": "string" 3370 }, 3371 "bounds": { 3372 "type": "array", 3373 "value": "number", 3374 "length": 4, 3375 "default": [ 3376 -180, 3377 -85.051129, 3378 180, 3379 85.051129 3380 ] 3381 }, 3382 "minzoom": { 3383 "type": "number", 3384 "default": 0 3385 }, 3386 "maxzoom": { 3387 "type": "number", 3388 "default": 22 3389 }, 3390 "tileSize": { 3391 "type": "number", 3392 "default": 512, 3393 "units": "pixels" 3394 }, 3395 "attribution": { "type": "string" }, 3396 "encoding": { 3397 "type": "enum", 3398 "values": { 3399 "terrarium": {}, 3400 "mapbox": {}, 3401 "custom": {} 3402 }, 3403 "default": "mapbox" 3404 }, 3405 "redFactor": { 3406 "type": "number", 3407 "default": 1 3408 }, 3409 "blueFactor": { 3410 "type": "number", 3411 "default": 1 3412 }, 3413 "greenFactor": { 3414 "type": "number", 3415 "default": 1 3416 }, 3417 "baseShift": { 3418 "type": "number", 3419 "default": 0 3420 }, 3421 "volatile": { 3422 "type": "boolean", 3423 "default": false 3424 }, 3425 "*": { "type": "*" } 3426 }, 3427 source_geojson: { 3428 "type": { 3429 "required": true, 3430 "type": "enum", 3431 "values": { "geojson": {} } 3432 }, 3433 "data": { 3434 "required": true, 3435 "type": "*" 3436 }, 3437 "maxzoom": { 3438 "type": "number", 3439 "default": 18 3440 }, 3441 "attribution": { "type": "string" }, 3442 "buffer": { 3443 "type": "number", 3444 "default": 128, 3445 "maximum": 512, 3446 "minimum": 0 3447 }, 3448 "filter": { "type": "filter" }, 3449 "tolerance": { 3450 "type": "number", 3451 "default": .375 3452 }, 3453 "cluster": { 3454 "type": "boolean", 3455 "default": false 3456 }, 3457 "clusterRadius": { 3458 "type": "number", 3459 "default": 50, 3460 "minimum": 0 3461 }, 3462 "clusterMaxZoom": { "type": "number" }, 3463 "clusterMinPoints": { "type": "number" }, 3464 "clusterProperties": { "type": "*" }, 3465 "lineMetrics": { 3466 "type": "boolean", 3467 "default": false 3468 }, 3469 "generateId": { 3470 "type": "boolean", 3471 "default": false 3472 }, 3473 "promoteId": { "type": "promoteId" } 3474 }, 3475 source_video: { 3476 "type": { 3477 "required": true, 3478 "type": "enum", 3479 "values": { "video": {} } 3480 }, 3481 "urls": { 3482 "required": true, 3483 "type": "array", 3484 "value": "string" 3485 }, 3486 "coordinates": { 3487 "required": true, 3488 "type": "array", 3489 "length": 4, 3490 "value": { 3491 "type": "array", 3492 "length": 2, 3493 "value": "number" 3494 } 3495 } 3496 }, 3497 source_image: { 3498 "type": { 3499 "required": true, 3500 "type": "enum", 3501 "values": { "image": {} } 3502 }, 3503 "url": { "type": "string" }, 3504 "coordinates": { 3505 "required": true, 3506 "type": "array", 3507 "length": 4, 3508 "value": { 3509 "type": "array", 3510 "length": 2, 3511 "value": "number" 3512 } 3513 } 3514 }, 3515 layer: { 3516 "id": { 3517 "type": "string", 3518 "required": true 3519 }, 3520 "type": { 3521 "type": "enum", 3522 "values": { 3523 "fill": {}, 3524 "line": {}, 3525 "symbol": {}, 3526 "circle": {}, 3527 "heatmap": {}, 3528 "fill-extrusion": {}, 3529 "raster": {}, 3530 "hillshade": {}, 3531 "color-relief": {}, 3532 "background": {} 3533 }, 3534 "required": true 3535 }, 3536 "metadata": { "type": "*" }, 3537 "source": { "type": "string" }, 3538 "source-layer": { "type": "string" }, 3539 "minzoom": { 3540 "type": "number", 3541 "minimum": 0, 3542 "maximum": 24 3543 }, 3544 "maxzoom": { 3545 "type": "number", 3546 "minimum": 0, 3547 "maximum": 24 3548 }, 3549 "filter": { "type": "filter" }, 3550 "layout": { "type": "layout" }, 3551 "paint": { "type": "paint" } 3552 }, 3553 layout: [ 3554 "layout_fill", 3555 "layout_line", 3556 "layout_circle", 3557 "layout_heatmap", 3558 "layout_fill-extrusion", 3559 "layout_symbol", 3560 "layout_raster", 3561 "layout_hillshade", 3562 "layout_color-relief", 3563 "layout_background" 3564 ], 3565 layout_background: { "visibility": { 3566 "type": "enum", 3567 "values": { 3568 "visible": {}, 3569 "none": {} 3570 }, 3571 "default": "visible", 3572 "expression": { 3573 "interpolated": false, 3574 "parameters": ["global-state"] 3575 }, 3576 "property-type": "data-constant" 3577 } }, 3578 layout_fill: { 3579 "fill-sort-key": { 3580 "type": "number", 3581 "expression": { 3582 "interpolated": false, 3583 "parameters": ["zoom", "feature"] 3584 }, 3585 "property-type": "data-driven" 3586 }, 3587 "visibility": { 3588 "type": "enum", 3589 "values": { 3590 "visible": {}, 3591 "none": {} 3592 }, 3593 "default": "visible", 3594 "expression": { 3595 "interpolated": false, 3596 "parameters": ["global-state"] 3597 }, 3598 "property-type": "data-constant" 3599 } 3600 }, 3601 layout_circle: { 3602 "circle-sort-key": { 3603 "type": "number", 3604 "expression": { 3605 "interpolated": false, 3606 "parameters": ["zoom", "feature"] 3607 }, 3608 "property-type": "data-driven" 3609 }, 3610 "visibility": { 3611 "type": "enum", 3612 "values": { 3613 "visible": {}, 3614 "none": {} 3615 }, 3616 "default": "visible", 3617 "expression": { 3618 "interpolated": false, 3619 "parameters": ["global-state"] 3620 }, 3621 "property-type": "data-constant" 3622 } 3623 }, 3624 layout_heatmap: { "visibility": { 3625 "type": "enum", 3626 "values": { 3627 "visible": {}, 3628 "none": {} 3629 }, 3630 "default": "visible", 3631 "expression": { 3632 "interpolated": false, 3633 "parameters": ["global-state"] 3634 }, 3635 "property-type": "data-constant" 3636 } }, 3637 "layout_fill-extrusion": { 3638 "visibility": { 3639 "type": "enum", 3640 "values": { 3641 "visible": {}, 3642 "none": {} 3643 }, 3644 "default": "visible", 3645 "expression": { 3646 "interpolated": false, 3647 "parameters": ["global-state"] 3648 }, 3649 "property-type": "data-constant" 3650 }, 3651 "fill-extrusion-rounded-corner-distance": { 3652 "type": "number", 3653 "default": 0, 3654 "minimum": 0, 3655 "units": "meters", 3656 "property-type": "constant" 3657 } 3658 }, 3659 layout_line: { 3660 "line-cap": { 3661 "type": "enum", 3662 "values": { 3663 "butt": {}, 3664 "round": {}, 3665 "square": {} 3666 }, 3667 "default": "butt", 3668 "expression": { 3669 "interpolated": false, 3670 "parameters": ["zoom", "feature"] 3671 }, 3672 "property-type": "data-driven" 3673 }, 3674 "line-join": { 3675 "type": "enum", 3676 "values": { 3677 "bevel": {}, 3678 "round": {}, 3679 "miter": {} 3680 }, 3681 "default": "miter", 3682 "expression": { 3683 "interpolated": false, 3684 "parameters": ["zoom", "feature"] 3685 }, 3686 "property-type": "data-driven" 3687 }, 3688 "line-miter-limit": { 3689 "type": "number", 3690 "default": 2, 3691 "requires": [{ "line-join": "miter" }], 3692 "expression": { 3693 "interpolated": true, 3694 "parameters": ["zoom", "feature"] 3695 }, 3696 "property-type": "data-driven" 3697 }, 3698 "line-round-limit": { 3699 "type": "number", 3700 "default": 1.05, 3701 "requires": [{ "line-join": "round" }], 3702 "expression": { 3703 "interpolated": true, 3704 "parameters": ["zoom", "feature"] 3705 }, 3706 "property-type": "data-driven" 3707 }, 3708 "line-sort-key": { 3709 "type": "number", 3710 "expression": { 3711 "interpolated": false, 3712 "parameters": ["zoom", "feature"] 3713 }, 3714 "property-type": "data-driven" 3715 }, 3716 "visibility": { 3717 "type": "enum", 3718 "values": { 3719 "visible": {}, 3720 "none": {} 3721 }, 3722 "default": "visible", 3723 "expression": { 3724 "interpolated": false, 3725 "parameters": ["global-state"] 3726 }, 3727 "property-type": "data-constant" 3728 } 3729 }, 3730 layout_symbol: { 3731 "symbol-placement": { 3732 "type": "enum", 3733 "values": { 3734 "point": {}, 3735 "line": {}, 3736 "line-center": {} 3737 }, 3738 "default": "point", 3739 "expression": { 3740 "interpolated": false, 3741 "parameters": ["zoom"] 3742 }, 3743 "property-type": "data-constant" 3744 }, 3745 "symbol-spacing": { 3746 "type": "number", 3747 "default": 250, 3748 "minimum": 1, 3749 "units": "pixels", 3750 "requires": [{ "symbol-placement": "line" }], 3751 "expression": { 3752 "interpolated": true, 3753 "parameters": ["zoom"] 3754 }, 3755 "property-type": "data-constant" 3756 }, 3757 "symbol-avoid-edges": { 3758 "type": "boolean", 3759 "default": false, 3760 "expression": { 3761 "interpolated": false, 3762 "parameters": ["zoom"] 3763 }, 3764 "property-type": "data-constant" 3765 }, 3766 "symbol-sort-key": { 3767 "type": "number", 3768 "expression": { 3769 "interpolated": false, 3770 "parameters": ["zoom", "feature"] 3771 }, 3772 "property-type": "data-driven" 3773 }, 3774 "symbol-z-order": { 3775 "type": "enum", 3776 "values": { 3777 "auto": {}, 3778 "viewport-y": {}, 3779 "source": {} 3780 }, 3781 "default": "auto", 3782 "expression": { 3783 "interpolated": false, 3784 "parameters": ["zoom"] 3785 }, 3786 "property-type": "data-constant" 3787 }, 3788 "icon-allow-overlap": { 3789 "type": "boolean", 3790 "default": false, 3791 "requires": ["icon-image", { "!": "icon-overlap" }], 3792 "expression": { 3793 "interpolated": false, 3794 "parameters": ["zoom"] 3795 }, 3796 "property-type": "data-constant" 3797 }, 3798 "icon-overlap": { 3799 "type": "enum", 3800 "values": { 3801 "never": {}, 3802 "always": {}, 3803 "cooperative": {} 3804 }, 3805 "requires": ["icon-image"], 3806 "expression": { 3807 "interpolated": false, 3808 "parameters": ["zoom"] 3809 }, 3810 "property-type": "data-constant" 3811 }, 3812 "icon-ignore-placement": { 3813 "type": "boolean", 3814 "default": false, 3815 "requires": ["icon-image"], 3816 "expression": { 3817 "interpolated": false, 3818 "parameters": ["zoom"] 3819 }, 3820 "property-type": "data-constant" 3821 }, 3822 "icon-optional": { 3823 "type": "boolean", 3824 "default": false, 3825 "requires": ["icon-image", "text-field"], 3826 "expression": { 3827 "interpolated": false, 3828 "parameters": ["zoom"] 3829 }, 3830 "property-type": "data-constant" 3831 }, 3832 "icon-rotation-alignment": { 3833 "type": "enum", 3834 "values": { 3835 "map": {}, 3836 "viewport": {}, 3837 "auto": {} 3838 }, 3839 "default": "auto", 3840 "requires": ["icon-image"], 3841 "expression": { 3842 "interpolated": false, 3843 "parameters": ["zoom", "feature"] 3844 }, 3845 "property-type": "data-driven" 3846 }, 3847 "icon-size": { 3848 "type": "number", 3849 "default": 1, 3850 "minimum": 0, 3851 "units": "factor of the original icon size", 3852 "requires": ["icon-image"], 3853 "expression": { 3854 "interpolated": true, 3855 "parameters": ["zoom", "feature"] 3856 }, 3857 "property-type": "data-driven" 3858 }, 3859 "icon-text-fit": { 3860 "type": "enum", 3861 "values": { 3862 "none": {}, 3863 "width": {}, 3864 "height": {}, 3865 "both": {} 3866 }, 3867 "default": "none", 3868 "requires": ["icon-image", "text-field"], 3869 "expression": { 3870 "interpolated": false, 3871 "parameters": ["zoom"] 3872 }, 3873 "property-type": "data-constant" 3874 }, 3875 "icon-text-fit-padding": { 3876 "type": "array", 3877 "value": "number", 3878 "length": 4, 3879 "default": [ 3880 0, 3881 0, 3882 0, 3883 0 3884 ], 3885 "units": "pixels", 3886 "requires": [ 3887 "icon-image", 3888 "text-field", 3889 { "icon-text-fit": [ 3890 "both", 3891 "width", 3892 "height" 3893 ] } 3894 ], 3895 "expression": { 3896 "interpolated": true, 3897 "parameters": ["zoom"] 3898 }, 3899 "property-type": "data-constant" 3900 }, 3901 "icon-image": { 3902 "type": "resolvedImage", 3903 "tokens": true, 3904 "expression": { 3905 "interpolated": false, 3906 "parameters": ["zoom", "feature"] 3907 }, 3908 "property-type": "data-driven" 3909 }, 3910 "icon-rotate": { 3911 "type": "number", 3912 "default": 0, 3913 "period": 360, 3914 "units": "degrees", 3915 "requires": ["icon-image"], 3916 "expression": { 3917 "interpolated": true, 3918 "parameters": ["zoom", "feature"] 3919 }, 3920 "property-type": "data-driven" 3921 }, 3922 "icon-padding": { 3923 "type": "padding", 3924 "default": [2], 3925 "units": "pixels", 3926 "requires": ["icon-image"], 3927 "expression": { 3928 "interpolated": true, 3929 "parameters": ["zoom", "feature"] 3930 }, 3931 "property-type": "data-driven" 3932 }, 3933 "icon-keep-upright": { 3934 "type": "boolean", 3935 "default": false, 3936 "requires": [ 3937 "icon-image", 3938 { "icon-rotation-alignment": "map" }, 3939 { "symbol-placement": ["line", "line-center"] } 3940 ], 3941 "expression": { 3942 "interpolated": false, 3943 "parameters": ["zoom"] 3944 }, 3945 "property-type": "data-constant" 3946 }, 3947 "icon-offset": { 3948 "type": "array", 3949 "value": "number", 3950 "length": 2, 3951 "default": [0, 0], 3952 "requires": ["icon-image"], 3953 "expression": { 3954 "interpolated": true, 3955 "parameters": ["zoom", "feature"] 3956 }, 3957 "property-type": "data-driven" 3958 }, 3959 "icon-anchor": { 3960 "type": "enum", 3961 "values": { 3962 "center": {}, 3963 "left": {}, 3964 "right": {}, 3965 "top": {}, 3966 "bottom": {}, 3967 "top-left": {}, 3968 "top-right": {}, 3969 "bottom-left": {}, 3970 "bottom-right": {} 3971 }, 3972 "default": "center", 3973 "requires": ["icon-image"], 3974 "expression": { 3975 "interpolated": false, 3976 "parameters": ["zoom", "feature"] 3977 }, 3978 "property-type": "data-driven" 3979 }, 3980 "icon-pitch-alignment": { 3981 "type": "enum", 3982 "values": { 3983 "map": {}, 3984 "viewport": {}, 3985 "auto": {} 3986 }, 3987 "default": "auto", 3988 "requires": ["icon-image"], 3989 "expression": { 3990 "interpolated": false, 3991 "parameters": ["zoom"] 3992 }, 3993 "property-type": "data-constant" 3994 }, 3995 "text-pitch-alignment": { 3996 "type": "enum", 3997 "values": { 3998 "map": {}, 3999 "viewport": {}, 4000 "auto": {} 4001 }, 4002 "default": "auto", 4003 "requires": ["text-field"], 4004 "expression": { 4005 "interpolated": false, 4006 "parameters": ["zoom"] 4007 }, 4008 "property-type": "data-constant" 4009 }, 4010 "text-rotation-alignment": { 4011 "type": "enum", 4012 "values": { 4013 "map": {}, 4014 "viewport": {}, 4015 "viewport-glyph": {}, 4016 "auto": {} 4017 }, 4018 "default": "auto", 4019 "requires": ["text-field"], 4020 "expression": { 4021 "interpolated": false, 4022 "parameters": ["zoom"] 4023 }, 4024 "property-type": "data-constant" 4025 }, 4026 "text-field": { 4027 "type": "formatted", 4028 "default": "", 4029 "tokens": true, 4030 "expression": { 4031 "interpolated": false, 4032 "parameters": ["zoom", "feature"] 4033 }, 4034 "property-type": "data-driven" 4035 }, 4036 "text-font": { 4037 "type": "array", 4038 "value": "string", 4039 "default": ["Open Sans Regular", "Arial Unicode MS Regular"], 4040 "requires": ["text-field"], 4041 "expression": { 4042 "interpolated": false, 4043 "parameters": ["zoom", "feature"] 4044 }, 4045 "property-type": "data-driven" 4046 }, 4047 "text-size": { 4048 "type": "number", 4049 "default": 16, 4050 "minimum": 0, 4051 "units": "pixels", 4052 "requires": ["text-field"], 4053 "expression": { 4054 "interpolated": true, 4055 "parameters": ["zoom", "feature"] 4056 }, 4057 "property-type": "data-driven" 4058 }, 4059 "text-max-width": { 4060 "type": "number", 4061 "default": 10, 4062 "minimum": 0, 4063 "units": "ems", 4064 "requires": ["text-field"], 4065 "expression": { 4066 "interpolated": true, 4067 "parameters": ["zoom", "feature"] 4068 }, 4069 "property-type": "data-driven" 4070 }, 4071 "text-line-height": { 4072 "type": "number", 4073 "default": 1.2, 4074 "units": "ems", 4075 "requires": ["text-field"], 4076 "expression": { 4077 "interpolated": true, 4078 "parameters": ["zoom"] 4079 }, 4080 "property-type": "data-constant" 4081 }, 4082 "text-letter-spacing": { 4083 "type": "number", 4084 "default": 0, 4085 "units": "ems", 4086 "requires": ["text-field"], 4087 "expression": { 4088 "interpolated": true, 4089 "parameters": ["zoom", "feature"] 4090 }, 4091 "property-type": "data-driven" 4092 }, 4093 "text-justify": { 4094 "type": "enum", 4095 "values": { 4096 "auto": {}, 4097 "left": {}, 4098 "center": {}, 4099 "right": {} 4100 }, 4101 "default": "center", 4102 "requires": ["text-field"], 4103 "expression": { 4104 "interpolated": false, 4105 "parameters": ["zoom", "feature"] 4106 }, 4107 "property-type": "data-driven" 4108 }, 4109 "text-radial-offset": { 4110 "type": "number", 4111 "units": "ems", 4112 "default": 0, 4113 "requires": ["text-field"], 4114 "property-type": "data-driven", 4115 "expression": { 4116 "interpolated": true, 4117 "parameters": ["zoom", "feature"] 4118 } 4119 }, 4120 "text-variable-anchor": { 4121 "type": "array", 4122 "value": "enum", 4123 "values": { 4124 "center": {}, 4125 "left": {}, 4126 "right": {}, 4127 "top": {}, 4128 "bottom": {}, 4129 "top-left": {}, 4130 "top-right": {}, 4131 "bottom-left": {}, 4132 "bottom-right": {} 4133 }, 4134 "requires": ["text-field", { "symbol-placement": ["point"] }], 4135 "expression": { 4136 "interpolated": false, 4137 "parameters": ["zoom"] 4138 }, 4139 "property-type": "data-constant" 4140 }, 4141 "text-variable-anchor-offset": { 4142 "type": "variableAnchorOffsetCollection", 4143 "requires": ["text-field", { "symbol-placement": ["point"] }], 4144 "expression": { 4145 "interpolated": true, 4146 "parameters": ["zoom", "feature"] 4147 }, 4148 "property-type": "data-driven" 4149 }, 4150 "text-anchor": { 4151 "type": "enum", 4152 "values": { 4153 "center": {}, 4154 "left": {}, 4155 "right": {}, 4156 "top": {}, 4157 "bottom": {}, 4158 "top-left": {}, 4159 "top-right": {}, 4160 "bottom-left": {}, 4161 "bottom-right": {} 4162 }, 4163 "default": "center", 4164 "requires": ["text-field", { "!": "text-variable-anchor" }], 4165 "expression": { 4166 "interpolated": false, 4167 "parameters": ["zoom", "feature"] 4168 }, 4169 "property-type": "data-driven" 4170 }, 4171 "text-max-angle": { 4172 "type": "number", 4173 "default": 45, 4174 "units": "degrees", 4175 "requires": ["text-field", { "symbol-placement": ["line", "line-center"] }], 4176 "expression": { 4177 "interpolated": true, 4178 "parameters": ["zoom"] 4179 }, 4180 "property-type": "data-constant" 4181 }, 4182 "text-writing-mode": { 4183 "type": "array", 4184 "value": "enum", 4185 "values": { 4186 "horizontal": {}, 4187 "vertical": {} 4188 }, 4189 "requires": ["text-field", { "symbol-placement": ["point"] }], 4190 "expression": { 4191 "interpolated": false, 4192 "parameters": ["zoom"] 4193 }, 4194 "property-type": "data-constant" 4195 }, 4196 "text-rotate": { 4197 "type": "number", 4198 "default": 0, 4199 "period": 360, 4200 "units": "degrees", 4201 "requires": ["text-field"], 4202 "expression": { 4203 "interpolated": true, 4204 "parameters": ["zoom", "feature"] 4205 }, 4206 "property-type": "data-driven" 4207 }, 4208 "text-padding": { 4209 "type": "number", 4210 "default": 2, 4211 "minimum": 0, 4212 "units": "pixels", 4213 "requires": ["text-field"], 4214 "expression": { 4215 "interpolated": true, 4216 "parameters": ["zoom"] 4217 }, 4218 "property-type": "data-constant" 4219 }, 4220 "text-keep-upright": { 4221 "type": "boolean", 4222 "default": true, 4223 "requires": [ 4224 "text-field", 4225 { "text-rotation-alignment": "map" }, 4226 { "symbol-placement": ["line", "line-center"] } 4227 ], 4228 "expression": { 4229 "interpolated": false, 4230 "parameters": ["zoom"] 4231 }, 4232 "property-type": "data-constant" 4233 }, 4234 "text-transform": { 4235 "type": "enum", 4236 "values": { 4237 "none": {}, 4238 "uppercase": {}, 4239 "lowercase": {} 4240 }, 4241 "default": "none", 4242 "requires": ["text-field"], 4243 "expression": { 4244 "interpolated": false, 4245 "parameters": ["zoom", "feature"] 4246 }, 4247 "property-type": "data-driven" 4248 }, 4249 "text-offset": { 4250 "type": "array", 4251 "value": "number", 4252 "units": "ems", 4253 "length": 2, 4254 "default": [0, 0], 4255 "requires": ["text-field", { "!": "text-radial-offset" }], 4256 "expression": { 4257 "interpolated": true, 4258 "parameters": ["zoom", "feature"] 4259 }, 4260 "property-type": "data-driven" 4261 }, 4262 "text-allow-overlap": { 4263 "type": "boolean", 4264 "default": false, 4265 "requires": ["text-field", { "!": "text-overlap" }], 4266 "expression": { 4267 "interpolated": false, 4268 "parameters": ["zoom"] 4269 }, 4270 "property-type": "data-constant" 4271 }, 4272 "text-overlap": { 4273 "type": "enum", 4274 "values": { 4275 "never": {}, 4276 "always": {}, 4277 "cooperative": {} 4278 }, 4279 "requires": ["text-field"], 4280 "expression": { 4281 "interpolated": false, 4282 "parameters": ["zoom"] 4283 }, 4284 "property-type": "data-constant" 4285 }, 4286 "text-ignore-placement": { 4287 "type": "boolean", 4288 "default": false, 4289 "requires": ["text-field"], 4290 "expression": { 4291 "interpolated": false, 4292 "parameters": ["zoom"] 4293 }, 4294 "property-type": "data-constant" 4295 }, 4296 "text-optional": { 4297 "type": "boolean", 4298 "default": false, 4299 "requires": ["text-field", "icon-image"], 4300 "expression": { 4301 "interpolated": false, 4302 "parameters": ["zoom"] 4303 }, 4304 "property-type": "data-constant" 4305 }, 4306 "symbol-height-offset": { 4307 "type": "number", 4308 "default": 0, 4309 "units": "meters", 4310 "requires": [{ "symbol-placement": ["point"] }], 4311 "expression": { 4312 "interpolated": true, 4313 "parameters": ["zoom", "feature"] 4314 }, 4315 "property-type": "data-driven" 4316 }, 4317 "symbol-height-anchor": { 4318 "type": "enum", 4319 "values": { 4320 "ground": {}, 4321 "absolute": {} 4322 }, 4323 "default": "ground", 4324 "requires": ["symbol-height-offset"], 4325 "expression": { 4326 "interpolated": false, 4327 "parameters": ["zoom"] 4328 }, 4329 "property-type": "data-constant" 4330 }, 4331 "visibility": { 4332 "type": "enum", 4333 "values": { 4334 "visible": {}, 4335 "none": {} 4336 }, 4337 "default": "visible", 4338 "expression": { 4339 "interpolated": false, 4340 "parameters": ["global-state"] 4341 }, 4342 "property-type": "data-constant" 4343 } 4344 }, 4345 layout_raster: { "visibility": { 4346 "type": "enum", 4347 "values": { 4348 "visible": {}, 4349 "none": {} 4350 }, 4351 "default": "visible", 4352 "expression": { 4353 "interpolated": false, 4354 "parameters": ["global-state"] 4355 }, 4356 "property-type": "data-constant" 4357 } }, 4358 layout_hillshade: { "visibility": { 4359 "type": "enum", 4360 "values": { 4361 "visible": {}, 4362 "none": {} 4363 }, 4364 "default": "visible", 4365 "expression": { 4366 "interpolated": false, 4367 "parameters": ["global-state"] 4368 }, 4369 "property-type": "data-constant" 4370 } }, 4371 "layout_color-relief": { "visibility": { 4372 "type": "enum", 4373 "values": { 4374 "visible": {}, 4375 "none": {} 4376 }, 4377 "default": "visible", 4378 "expression": { 4379 "interpolated": false, 4380 "parameters": ["global-state"] 4381 }, 4382 "property-type": "data-constant" 4383 } }, 4384 filter: { 4385 "type": "boolean", 4386 "expression": { 4387 "interpolated": false, 4388 "parameters": ["zoom", "feature"] 4389 }, 4390 "property-type": "data-driven" 4391 }, 4392 filter_operator: { 4393 "type": "enum", 4394 "values": { 4395 "==": {}, 4396 "!=": {}, 4397 ">": {}, 4398 ">=": {}, 4399 "<": {}, 4400 "<=": {}, 4401 "in": {}, 4402 "!in": {}, 4403 "all": {}, 4404 "any": {}, 4405 "none": {}, 4406 "has": {}, 4407 "!has": {} 4408 } 4409 }, 4410 geometry_type: { 4411 "type": "enum", 4412 "values": { 4413 "Point": {}, 4414 "LineString": {}, 4415 "Polygon": {} 4416 } 4417 }, 4418 "function": { 4419 "expression": { "type": "expression" }, 4420 "stops": { 4421 "type": "array", 4422 "value": "function_stop" 4423 }, 4424 "base": { 4425 "type": "number", 4426 "default": 1, 4427 "minimum": 0 4428 }, 4429 "property": { 4430 "type": "string", 4431 "default": "$zoom" 4432 }, 4433 "type": { 4434 "type": "enum", 4435 "values": { 4436 "identity": {}, 4437 "exponential": {}, 4438 "interval": {}, 4439 "categorical": {} 4440 }, 4441 "default": "exponential" 4442 }, 4443 "colorSpace": { 4444 "type": "enum", 4445 "values": { 4446 "rgb": {}, 4447 "lab": {}, 4448 "hcl": {} 4449 }, 4450 "default": "rgb" 4451 }, 4452 "default": { 4453 "type": "*", 4454 "required": false 4455 } 4456 }, 4457 function_stop: { 4458 "type": "array", 4459 "minimum": 0, 4460 "maximum": 24, 4461 "value": ["number", "color"], 4462 "length": 2 4463 }, 4464 expression: { 4465 "type": "array", 4466 "value": "expression_name", 4467 "minimum": 1 4468 }, 4469 light: { 4470 "anchor": { 4471 "type": "enum", 4472 "default": "viewport", 4473 "values": { 4474 "map": {}, 4475 "viewport": {} 4476 }, 4477 "property-type": "data-constant", 4478 "transition": false, 4479 "expression": { 4480 "interpolated": false, 4481 "parameters": ["zoom"] 4482 } 4483 }, 4484 "position": { 4485 "type": "array", 4486 "default": [ 4487 1.15, 4488 210, 4489 30 4490 ], 4491 "length": 3, 4492 "value": "number", 4493 "property-type": "data-constant", 4494 "transition": true, 4495 "expression": { 4496 "interpolated": true, 4497 "parameters": ["zoom"] 4498 } 4499 }, 4500 "color": { 4501 "type": "color", 4502 "property-type": "data-constant", 4503 "default": "#ffffff", 4504 "expression": { 4505 "interpolated": true, 4506 "parameters": ["zoom"] 4507 }, 4508 "transition": true 4509 }, 4510 "intensity": { 4511 "type": "number", 4512 "property-type": "data-constant", 4513 "default": .5, 4514 "minimum": 0, 4515 "maximum": 1, 4516 "expression": { 4517 "interpolated": true, 4518 "parameters": ["zoom"] 4519 }, 4520 "transition": true 4521 } 4522 }, 4523 sky: { 4524 "sky-color": { 4525 "type": "color", 4526 "property-type": "data-constant", 4527 "default": "#88C6FC", 4528 "expression": { 4529 "interpolated": true, 4530 "parameters": ["zoom"] 4531 }, 4532 "transition": true 4533 }, 4534 "horizon-color": { 4535 "type": "color", 4536 "property-type": "data-constant", 4537 "default": "#ffffff", 4538 "expression": { 4539 "interpolated": true, 4540 "parameters": ["zoom"] 4541 }, 4542 "transition": true 4543 }, 4544 "fog-color": { 4545 "type": "color", 4546 "property-type": "data-constant", 4547 "default": "#ffffff", 4548 "expression": { 4549 "interpolated": true, 4550 "parameters": ["zoom"] 4551 }, 4552 "transition": true 4553 }, 4554 "fog-ground-blend": { 4555 "type": "number", 4556 "property-type": "data-constant", 4557 "default": .5, 4558 "minimum": 0, 4559 "maximum": 1, 4560 "expression": { 4561 "interpolated": true, 4562 "parameters": ["zoom"] 4563 }, 4564 "transition": true 4565 }, 4566 "horizon-fog-blend": { 4567 "type": "number", 4568 "property-type": "data-constant", 4569 "default": .8, 4570 "minimum": 0, 4571 "maximum": 1, 4572 "expression": { 4573 "interpolated": true, 4574 "parameters": ["zoom"] 4575 }, 4576 "transition": true 4577 }, 4578 "sky-horizon-blend": { 4579 "type": "number", 4580 "property-type": "data-constant", 4581 "default": .8, 4582 "minimum": 0, 4583 "maximum": 1, 4584 "expression": { 4585 "interpolated": true, 4586 "parameters": ["zoom"] 4587 }, 4588 "transition": true 4589 }, 4590 "atmosphere-blend": { 4591 "type": "number", 4592 "property-type": "data-constant", 4593 "default": .8, 4594 "minimum": 0, 4595 "maximum": 1, 4596 "expression": { 4597 "interpolated": true, 4598 "parameters": ["zoom"] 4599 }, 4600 "transition": true 4601 } 4602 }, 4603 terrain: { 4604 "source": { 4605 "type": "string", 4606 "required": true 4607 }, 4608 "exaggeration": { 4609 "type": "number", 4610 "minimum": 0, 4611 "default": 1 4612 } 4613 }, 4614 projection: { "type": { 4615 "type": "projectionDefinition", 4616 "default": "mercator", 4617 "property-type": "data-constant", 4618 "transition": false, 4619 "expression": { 4620 "interpolated": true, 4621 "parameters": ["zoom"] 4622 } 4623 } }, 4624 paint: [ 4625 "paint_fill", 4626 "paint_line", 4627 "paint_circle", 4628 "paint_heatmap", 4629 "paint_fill-extrusion", 4630 "paint_symbol", 4631 "paint_raster", 4632 "paint_hillshade", 4633 "paint_color-relief", 4634 "paint_background" 4635 ], 4636 paint_fill: { 4637 "fill-antialias": { 4638 "type": "boolean", 4639 "default": true, 4640 "expression": { 4641 "interpolated": false, 4642 "parameters": ["zoom"] 4643 }, 4644 "property-type": "data-constant" 4645 }, 4646 "fill-opacity": { 4647 "type": "number", 4648 "default": 1, 4649 "minimum": 0, 4650 "maximum": 1, 4651 "transition": true, 4652 "expression": { 4653 "interpolated": true, 4654 "parameters": [ 4655 "zoom", 4656 "feature", 4657 "feature-state" 4658 ] 4659 }, 4660 "property-type": "data-driven" 4661 }, 4662 "fill-layer-opacity": { 4663 "type": "number", 4664 "default": 1, 4665 "minimum": 0, 4666 "maximum": 1, 4667 "transition": true, 4668 "expression": { 4669 "interpolated": true, 4670 "parameters": ["zoom", "global-state"] 4671 }, 4672 "property-type": "data-constant" 4673 }, 4674 "fill-color": { 4675 "type": "color", 4676 "default": "#000000", 4677 "transition": true, 4678 "expression": { 4679 "interpolated": true, 4680 "parameters": [ 4681 "zoom", 4682 "feature", 4683 "feature-state" 4684 ] 4685 }, 4686 "property-type": "data-driven" 4687 }, 4688 "fill-outline-color": { 4689 "type": "color", 4690 "transition": true, 4691 "requires": [{ "!": "fill-pattern" }, { "fill-antialias": true }], 4692 "expression": { 4693 "interpolated": true, 4694 "parameters": [ 4695 "zoom", 4696 "feature", 4697 "feature-state" 4698 ] 4699 }, 4700 "property-type": "data-driven" 4701 }, 4702 "fill-translate": { 4703 "type": "array", 4704 "value": "number", 4705 "length": 2, 4706 "default": [0, 0], 4707 "transition": true, 4708 "units": "pixels", 4709 "expression": { 4710 "interpolated": true, 4711 "parameters": ["zoom"] 4712 }, 4713 "property-type": "data-constant" 4714 }, 4715 "fill-translate-anchor": { 4716 "type": "enum", 4717 "values": { 4718 "map": {}, 4719 "viewport": {} 4720 }, 4721 "default": "map", 4722 "requires": ["fill-translate"], 4723 "expression": { 4724 "interpolated": false, 4725 "parameters": ["zoom"] 4726 }, 4727 "property-type": "data-constant" 4728 }, 4729 "fill-pattern": { 4730 "type": "resolvedImage", 4731 "transition": true, 4732 "expression": { 4733 "interpolated": false, 4734 "parameters": ["zoom", "feature"] 4735 }, 4736 "property-type": "cross-faded-data-driven" 4737 } 4738 }, 4739 "paint_fill-extrusion": { 4740 "fill-extrusion-opacity": { 4741 "type": "number", 4742 "default": 1, 4743 "minimum": 0, 4744 "maximum": 1, 4745 "transition": true, 4746 "expression": { 4747 "interpolated": true, 4748 "parameters": ["zoom"] 4749 }, 4750 "property-type": "data-constant" 4751 }, 4752 "fill-extrusion-color": { 4753 "type": "color", 4754 "default": "#000000", 4755 "transition": true, 4756 "requires": [{ "!": "fill-extrusion-pattern" }], 4757 "expression": { 4758 "interpolated": true, 4759 "parameters": [ 4760 "zoom", 4761 "feature", 4762 "feature-state" 4763 ] 4764 }, 4765 "property-type": "data-driven" 4766 }, 4767 "fill-extrusion-translate": { 4768 "type": "array", 4769 "value": "number", 4770 "length": 2, 4771 "default": [0, 0], 4772 "transition": true, 4773 "units": "pixels", 4774 "expression": { 4775 "interpolated": true, 4776 "parameters": ["zoom"] 4777 }, 4778 "property-type": "data-constant" 4779 }, 4780 "fill-extrusion-translate-anchor": { 4781 "type": "enum", 4782 "values": { 4783 "map": {}, 4784 "viewport": {} 4785 }, 4786 "default": "map", 4787 "requires": ["fill-extrusion-translate"], 4788 "expression": { 4789 "interpolated": false, 4790 "parameters": ["zoom"] 4791 }, 4792 "property-type": "data-constant" 4793 }, 4794 "fill-extrusion-pattern": { 4795 "type": "resolvedImage", 4796 "transition": true, 4797 "expression": { 4798 "interpolated": false, 4799 "parameters": ["zoom", "feature"] 4800 }, 4801 "property-type": "cross-faded-data-driven" 4802 }, 4803 "fill-extrusion-height": { 4804 "type": "number", 4805 "default": 0, 4806 "units": "meters", 4807 "transition": true, 4808 "expression": { 4809 "interpolated": true, 4810 "parameters": [ 4811 "zoom", 4812 "feature", 4813 "feature-state" 4814 ] 4815 }, 4816 "property-type": "data-driven" 4817 }, 4818 "fill-extrusion-base": { 4819 "type": "number", 4820 "default": 0, 4821 "units": "meters", 4822 "transition": true, 4823 "requires": ["fill-extrusion-height"], 4824 "expression": { 4825 "interpolated": true, 4826 "parameters": [ 4827 "zoom", 4828 "feature", 4829 "feature-state" 4830 ] 4831 }, 4832 "property-type": "data-driven" 4833 }, 4834 "fill-extrusion-vertical-gradient": { 4835 "type": "boolean", 4836 "default": true, 4837 "transition": false, 4838 "expression": { 4839 "interpolated": false, 4840 "parameters": ["zoom"] 4841 }, 4842 "property-type": "data-constant" 4843 } 4844 }, 4845 paint_line: { 4846 "line-opacity": { 4847 "type": "number", 4848 "default": 1, 4849 "minimum": 0, 4850 "maximum": 1, 4851 "transition": true, 4852 "expression": { 4853 "interpolated": true, 4854 "parameters": [ 4855 "zoom", 4856 "feature", 4857 "feature-state" 4858 ] 4859 }, 4860 "property-type": "data-driven" 4861 }, 4862 "line-layer-opacity": { 4863 "type": "number", 4864 "default": 1, 4865 "minimum": 0, 4866 "maximum": 1, 4867 "transition": true, 4868 "expression": { 4869 "interpolated": true, 4870 "parameters": ["zoom", "global-state"] 4871 }, 4872 "property-type": "data-constant" 4873 }, 4874 "line-color": { 4875 "type": "color", 4876 "default": "#000000", 4877 "transition": true, 4878 "requires": [{ "!": "line-pattern" }], 4879 "expression": { 4880 "interpolated": true, 4881 "parameters": [ 4882 "zoom", 4883 "feature", 4884 "feature-state" 4885 ] 4886 }, 4887 "property-type": "data-driven" 4888 }, 4889 "line-translate": { 4890 "type": "array", 4891 "value": "number", 4892 "length": 2, 4893 "default": [0, 0], 4894 "transition": true, 4895 "units": "pixels", 4896 "expression": { 4897 "interpolated": true, 4898 "parameters": ["zoom"] 4899 }, 4900 "property-type": "data-constant" 4901 }, 4902 "line-translate-anchor": { 4903 "type": "enum", 4904 "values": { 4905 "map": {}, 4906 "viewport": {} 4907 }, 4908 "default": "map", 4909 "requires": ["line-translate"], 4910 "expression": { 4911 "interpolated": false, 4912 "parameters": ["zoom"] 4913 }, 4914 "property-type": "data-constant" 4915 }, 4916 "line-width": { 4917 "type": "number", 4918 "default": 1, 4919 "minimum": 0, 4920 "transition": true, 4921 "units": "pixels", 4922 "expression": { 4923 "interpolated": true, 4924 "parameters": [ 4925 "zoom", 4926 "feature", 4927 "feature-state" 4928 ] 4929 }, 4930 "property-type": "data-driven" 4931 }, 4932 "line-gap-width": { 4933 "type": "number", 4934 "default": 0, 4935 "minimum": 0, 4936 "transition": true, 4937 "units": "pixels", 4938 "expression": { 4939 "interpolated": true, 4940 "parameters": [ 4941 "zoom", 4942 "feature", 4943 "feature-state" 4944 ] 4945 }, 4946 "property-type": "data-driven" 4947 }, 4948 "line-offset": { 4949 "type": "number", 4950 "default": 0, 4951 "transition": true, 4952 "units": "pixels", 4953 "expression": { 4954 "interpolated": true, 4955 "parameters": [ 4956 "zoom", 4957 "feature", 4958 "feature-state" 4959 ] 4960 }, 4961 "property-type": "data-driven" 4962 }, 4963 "line-blur": { 4964 "type": "number", 4965 "default": 0, 4966 "minimum": 0, 4967 "transition": true, 4968 "units": "pixels", 4969 "expression": { 4970 "interpolated": true, 4971 "parameters": [ 4972 "zoom", 4973 "feature", 4974 "feature-state" 4975 ] 4976 }, 4977 "property-type": "data-driven" 4978 }, 4979 "line-dasharray": { 4980 "type": "array", 4981 "value": "number", 4982 "minimum": 0, 4983 "transition": true, 4984 "units": "line widths", 4985 "requires": [{ "!": "line-pattern" }], 4986 "expression": { 4987 "interpolated": false, 4988 "parameters": ["zoom", "feature"] 4989 }, 4990 "property-type": "cross-faded-data-driven" 4991 }, 4992 "line-pattern": { 4993 "type": "resolvedImage", 4994 "transition": true, 4995 "expression": { 4996 "interpolated": false, 4997 "parameters": ["zoom", "feature"] 4998 }, 4999 "property-type": "cross-faded-data-driven" 5000 }, 5001 "line-gradient": { 5002 "type": "color", 5003 "transition": false, 5004 "requires": [ 5005 { "!": "line-dasharray" }, 5006 { "!": "line-pattern" }, 5007 { 5008 "source": "geojson", 5009 "has": { "lineMetrics": true } 5010 } 5011 ], 5012 "expression": { 5013 "interpolated": true, 5014 "parameters": ["line-progress"] 5015 }, 5016 "property-type": "color-ramp" 5017 } 5018 }, 5019 paint_circle: { 5020 "circle-radius": { 5021 "type": "number", 5022 "default": 5, 5023 "minimum": 0, 5024 "transition": true, 5025 "units": "pixels", 5026 "expression": { 5027 "interpolated": true, 5028 "parameters": [ 5029 "zoom", 5030 "feature", 5031 "feature-state" 5032 ] 5033 }, 5034 "property-type": "data-driven" 5035 }, 5036 "circle-color": { 5037 "type": "color", 5038 "default": "#000000", 5039 "transition": true, 5040 "expression": { 5041 "interpolated": true, 5042 "parameters": [ 5043 "zoom", 5044 "feature", 5045 "feature-state" 5046 ] 5047 }, 5048 "property-type": "data-driven" 5049 }, 5050 "circle-blur": { 5051 "type": "number", 5052 "default": 0, 5053 "transition": true, 5054 "expression": { 5055 "interpolated": true, 5056 "parameters": [ 5057 "zoom", 5058 "feature", 5059 "feature-state" 5060 ] 5061 }, 5062 "property-type": "data-driven" 5063 }, 5064 "circle-opacity": { 5065 "type": "number", 5066 "default": 1, 5067 "minimum": 0, 5068 "maximum": 1, 5069 "transition": true, 5070 "expression": { 5071 "interpolated": true, 5072 "parameters": [ 5073 "zoom", 5074 "feature", 5075 "feature-state" 5076 ] 5077 }, 5078 "property-type": "data-driven" 5079 }, 5080 "circle-translate": { 5081 "type": "array", 5082 "value": "number", 5083 "length": 2, 5084 "default": [0, 0], 5085 "transition": true, 5086 "units": "pixels", 5087 "expression": { 5088 "interpolated": true, 5089 "parameters": ["zoom"] 5090 }, 5091 "property-type": "data-constant" 5092 }, 5093 "circle-translate-anchor": { 5094 "type": "enum", 5095 "values": { 5096 "map": {}, 5097 "viewport": {} 5098 }, 5099 "default": "map", 5100 "requires": ["circle-translate"], 5101 "expression": { 5102 "interpolated": false, 5103 "parameters": ["zoom"] 5104 }, 5105 "property-type": "data-constant" 5106 }, 5107 "circle-pitch-scale": { 5108 "type": "enum", 5109 "values": { 5110 "map": {}, 5111 "viewport": {} 5112 }, 5113 "default": "map", 5114 "expression": { 5115 "interpolated": false, 5116 "parameters": ["zoom"] 5117 }, 5118 "property-type": "data-constant" 5119 }, 5120 "circle-pitch-alignment": { 5121 "type": "enum", 5122 "values": { 5123 "map": {}, 5124 "viewport": {} 5125 }, 5126 "default": "viewport", 5127 "expression": { 5128 "interpolated": false, 5129 "parameters": ["zoom"] 5130 }, 5131 "property-type": "data-constant" 5132 }, 5133 "circle-stroke-width": { 5134 "type": "number", 5135 "default": 0, 5136 "minimum": 0, 5137 "transition": true, 5138 "units": "pixels", 5139 "expression": { 5140 "interpolated": true, 5141 "parameters": [ 5142 "zoom", 5143 "feature", 5144 "feature-state" 5145 ] 5146 }, 5147 "property-type": "data-driven" 5148 }, 5149 "circle-stroke-color": { 5150 "type": "color", 5151 "default": "#000000", 5152 "transition": true, 5153 "expression": { 5154 "interpolated": true, 5155 "parameters": [ 5156 "zoom", 5157 "feature", 5158 "feature-state" 5159 ] 5160 }, 5161 "property-type": "data-driven" 5162 }, 5163 "circle-stroke-opacity": { 5164 "type": "number", 5165 "default": 1, 5166 "minimum": 0, 5167 "maximum": 1, 5168 "transition": true, 5169 "expression": { 5170 "interpolated": true, 5171 "parameters": [ 5172 "zoom", 5173 "feature", 5174 "feature-state" 5175 ] 5176 }, 5177 "property-type": "data-driven" 5178 } 5179 }, 5180 paint_heatmap: { 5181 "heatmap-radius": { 5182 "type": "number", 5183 "default": 30, 5184 "minimum": 1, 5185 "transition": true, 5186 "units": "pixels", 5187 "expression": { 5188 "interpolated": true, 5189 "parameters": [ 5190 "zoom", 5191 "feature", 5192 "feature-state" 5193 ] 5194 }, 5195 "property-type": "data-driven" 5196 }, 5197 "heatmap-weight": { 5198 "type": "number", 5199 "default": 1, 5200 "minimum": 0, 5201 "transition": false, 5202 "expression": { 5203 "interpolated": true, 5204 "parameters": [ 5205 "zoom", 5206 "feature", 5207 "feature-state" 5208 ] 5209 }, 5210 "property-type": "data-driven" 5211 }, 5212 "heatmap-intensity": { 5213 "type": "number", 5214 "default": 1, 5215 "minimum": 0, 5216 "transition": true, 5217 "expression": { 5218 "interpolated": true, 5219 "parameters": ["zoom"] 5220 }, 5221 "property-type": "data-constant" 5222 }, 5223 "heatmap-color": { 5224 "type": "color", 5225 "default": [ 5226 "interpolate", 5227 ["linear"], 5228 ["heatmap-density"], 5229 0, 5230 "rgba(0, 0, 255, 0)", 5231 .1, 5232 "royalblue", 5233 .3, 5234 "cyan", 5235 .5, 5236 "lime", 5237 .7, 5238 "yellow", 5239 1, 5240 "red" 5241 ], 5242 "transition": false, 5243 "expression": { 5244 "interpolated": true, 5245 "parameters": ["heatmap-density"] 5246 }, 5247 "property-type": "color-ramp" 5248 }, 5249 "heatmap-opacity": { 5250 "type": "number", 5251 "default": 1, 5252 "minimum": 0, 5253 "maximum": 1, 5254 "transition": true, 5255 "expression": { 5256 "interpolated": true, 5257 "parameters": ["zoom"] 5258 }, 5259 "property-type": "data-constant" 5260 } 5261 }, 5262 paint_symbol: { 5263 "icon-opacity": { 5264 "type": "number", 5265 "default": 1, 5266 "minimum": 0, 5267 "maximum": 1, 5268 "transition": true, 5269 "requires": ["icon-image"], 5270 "expression": { 5271 "interpolated": true, 5272 "parameters": [ 5273 "zoom", 5274 "feature", 5275 "feature-state" 5276 ] 5277 }, 5278 "property-type": "data-driven" 5279 }, 5280 "icon-color": { 5281 "type": "color", 5282 "default": "#000000", 5283 "transition": true, 5284 "requires": ["icon-image"], 5285 "expression": { 5286 "interpolated": true, 5287 "parameters": [ 5288 "zoom", 5289 "feature", 5290 "feature-state" 5291 ] 5292 }, 5293 "property-type": "data-driven" 5294 }, 5295 "icon-halo-color": { 5296 "type": "color", 5297 "default": "rgba(0, 0, 0, 0)", 5298 "transition": true, 5299 "requires": ["icon-image"], 5300 "expression": { 5301 "interpolated": true, 5302 "parameters": [ 5303 "zoom", 5304 "feature", 5305 "feature-state" 5306 ] 5307 }, 5308 "property-type": "data-driven" 5309 }, 5310 "icon-halo-width": { 5311 "type": "number", 5312 "default": 0, 5313 "minimum": 0, 5314 "transition": true, 5315 "units": "pixels", 5316 "requires": ["icon-image"], 5317 "expression": { 5318 "interpolated": true, 5319 "parameters": [ 5320 "zoom", 5321 "feature", 5322 "feature-state" 5323 ] 5324 }, 5325 "property-type": "data-driven" 5326 }, 5327 "icon-halo-blur": { 5328 "type": "number", 5329 "default": 0, 5330 "minimum": 0, 5331 "transition": true, 5332 "units": "pixels", 5333 "requires": ["icon-image"], 5334 "expression": { 5335 "interpolated": true, 5336 "parameters": [ 5337 "zoom", 5338 "feature", 5339 "feature-state" 5340 ] 5341 }, 5342 "property-type": "data-driven" 5343 }, 5344 "icon-translate": { 5345 "type": "array", 5346 "value": "number", 5347 "length": 2, 5348 "default": [0, 0], 5349 "transition": true, 5350 "units": "pixels", 5351 "requires": ["icon-image"], 5352 "expression": { 5353 "interpolated": true, 5354 "parameters": ["zoom"] 5355 }, 5356 "property-type": "data-constant" 5357 }, 5358 "icon-translate-anchor": { 5359 "type": "enum", 5360 "values": { 5361 "map": {}, 5362 "viewport": {} 5363 }, 5364 "default": "map", 5365 "requires": ["icon-image", "icon-translate"], 5366 "expression": { 5367 "interpolated": false, 5368 "parameters": ["zoom"] 5369 }, 5370 "property-type": "data-constant" 5371 }, 5372 "text-opacity": { 5373 "type": "number", 5374 "default": 1, 5375 "minimum": 0, 5376 "maximum": 1, 5377 "transition": true, 5378 "requires": ["text-field"], 5379 "expression": { 5380 "interpolated": true, 5381 "parameters": [ 5382 "zoom", 5383 "feature", 5384 "feature-state" 5385 ] 5386 }, 5387 "property-type": "data-driven" 5388 }, 5389 "text-color": { 5390 "type": "color", 5391 "default": "#000000", 5392 "transition": true, 5393 "overridable": true, 5394 "requires": ["text-field"], 5395 "expression": { 5396 "interpolated": true, 5397 "parameters": [ 5398 "zoom", 5399 "feature", 5400 "feature-state" 5401 ] 5402 }, 5403 "property-type": "data-driven" 5404 }, 5405 "text-halo-color": { 5406 "type": "color", 5407 "default": "rgba(0, 0, 0, 0)", 5408 "transition": true, 5409 "requires": ["text-field"], 5410 "expression": { 5411 "interpolated": true, 5412 "parameters": [ 5413 "zoom", 5414 "feature", 5415 "feature-state" 5416 ] 5417 }, 5418 "property-type": "data-driven" 5419 }, 5420 "text-halo-width": { 5421 "type": "number", 5422 "default": 0, 5423 "minimum": 0, 5424 "transition": true, 5425 "units": "pixels", 5426 "requires": ["text-field"], 5427 "expression": { 5428 "interpolated": true, 5429 "parameters": [ 5430 "zoom", 5431 "feature", 5432 "feature-state" 5433 ] 5434 }, 5435 "property-type": "data-driven" 5436 }, 5437 "text-halo-blur": { 5438 "type": "number", 5439 "default": 0, 5440 "minimum": 0, 5441 "transition": true, 5442 "units": "pixels", 5443 "requires": ["text-field"], 5444 "expression": { 5445 "interpolated": true, 5446 "parameters": [ 5447 "zoom", 5448 "feature", 5449 "feature-state" 5450 ] 5451 }, 5452 "property-type": "data-driven" 5453 }, 5454 "text-translate": { 5455 "type": "array", 5456 "value": "number", 5457 "length": 2, 5458 "default": [0, 0], 5459 "transition": true, 5460 "units": "pixels", 5461 "requires": ["text-field"], 5462 "expression": { 5463 "interpolated": true, 5464 "parameters": ["zoom"] 5465 }, 5466 "property-type": "data-constant" 5467 }, 5468 "text-translate-anchor": { 5469 "type": "enum", 5470 "values": { 5471 "map": {}, 5472 "viewport": {} 5473 }, 5474 "default": "map", 5475 "requires": ["text-field", "text-translate"], 5476 "expression": { 5477 "interpolated": false, 5478 "parameters": ["zoom"] 5479 }, 5480 "property-type": "data-constant" 5481 } 5482 }, 5483 paint_raster: { 5484 "raster-opacity": { 5485 "type": "number", 5486 "default": 1, 5487 "minimum": 0, 5488 "maximum": 1, 5489 "transition": true, 5490 "expression": { 5491 "interpolated": true, 5492 "parameters": ["zoom"] 5493 }, 5494 "property-type": "data-constant" 5495 }, 5496 "raster-hue-rotate": { 5497 "type": "number", 5498 "default": 0, 5499 "period": 360, 5500 "transition": true, 5501 "units": "degrees", 5502 "expression": { 5503 "interpolated": true, 5504 "parameters": ["zoom"] 5505 }, 5506 "property-type": "data-constant" 5507 }, 5508 "raster-brightness-min": { 5509 "type": "number", 5510 "default": 0, 5511 "minimum": 0, 5512 "maximum": 1, 5513 "transition": true, 5514 "expression": { 5515 "interpolated": true, 5516 "parameters": ["zoom"] 5517 }, 5518 "property-type": "data-constant" 5519 }, 5520 "raster-brightness-max": { 5521 "type": "number", 5522 "default": 1, 5523 "minimum": 0, 5524 "maximum": 1, 5525 "transition": true, 5526 "expression": { 5527 "interpolated": true, 5528 "parameters": ["zoom"] 5529 }, 5530 "property-type": "data-constant" 5531 }, 5532 "raster-saturation": { 5533 "type": "number", 5534 "default": 0, 5535 "minimum": -1, 5536 "maximum": 1, 5537 "transition": true, 5538 "expression": { 5539 "interpolated": true, 5540 "parameters": ["zoom"] 5541 }, 5542 "property-type": "data-constant" 5543 }, 5544 "raster-contrast": { 5545 "type": "number", 5546 "default": 0, 5547 "minimum": -1, 5548 "maximum": 1, 5549 "transition": true, 5550 "expression": { 5551 "interpolated": true, 5552 "parameters": ["zoom"] 5553 }, 5554 "property-type": "data-constant" 5555 }, 5556 "resampling": { 5557 "type": "enum", 5558 "values": { 5559 "linear": {}, 5560 "nearest": {} 5561 }, 5562 "default": "linear", 5563 "expression": { 5564 "interpolated": false, 5565 "parameters": ["zoom"] 5566 }, 5567 "property-type": "data-constant" 5568 }, 5569 "raster-resampling": { 5570 "type": "enum", 5571 "values": { 5572 "linear": {}, 5573 "nearest": {} 5574 }, 5575 "default": "linear", 5576 "expression": { 5577 "interpolated": false, 5578 "parameters": ["zoom"] 5579 }, 5580 "property-type": "data-constant" 5581 }, 5582 "raster-fade-duration": { 5583 "type": "number", 5584 "default": 300, 5585 "minimum": 0, 5586 "transition": false, 5587 "units": "milliseconds", 5588 "expression": { 5589 "interpolated": true, 5590 "parameters": ["zoom"] 5591 }, 5592 "property-type": "data-constant" 5593 } 5594 }, 5595 paint_hillshade: { 5596 "hillshade-illumination-direction": { 5597 "type": "numberArray", 5598 "default": 335, 5599 "minimum": 0, 5600 "maximum": 359, 5601 "transition": false, 5602 "expression": { 5603 "interpolated": true, 5604 "parameters": ["zoom"] 5605 }, 5606 "property-type": "data-constant" 5607 }, 5608 "hillshade-illumination-altitude": { 5609 "type": "numberArray", 5610 "default": 45, 5611 "minimum": 0, 5612 "maximum": 90, 5613 "transition": false, 5614 "expression": { 5615 "interpolated": true, 5616 "parameters": ["zoom"] 5617 }, 5618 "property-type": "data-constant" 5619 }, 5620 "hillshade-illumination-anchor": { 5621 "type": "enum", 5622 "values": { 5623 "map": {}, 5624 "viewport": {} 5625 }, 5626 "default": "viewport", 5627 "expression": { 5628 "interpolated": false, 5629 "parameters": ["zoom"] 5630 }, 5631 "property-type": "data-constant" 5632 }, 5633 "hillshade-exaggeration": { 5634 "type": "number", 5635 "default": .5, 5636 "minimum": 0, 5637 "maximum": 1, 5638 "transition": true, 5639 "expression": { 5640 "interpolated": true, 5641 "parameters": ["zoom"] 5642 }, 5643 "property-type": "data-constant" 5644 }, 5645 "hillshade-shadow-color": { 5646 "type": "colorArray", 5647 "default": "#000000", 5648 "transition": true, 5649 "expression": { 5650 "interpolated": true, 5651 "parameters": ["zoom"] 5652 }, 5653 "property-type": "data-constant" 5654 }, 5655 "hillshade-highlight-color": { 5656 "type": "colorArray", 5657 "default": "#FFFFFF", 5658 "transition": true, 5659 "expression": { 5660 "interpolated": true, 5661 "parameters": ["zoom"] 5662 }, 5663 "property-type": "data-constant" 5664 }, 5665 "hillshade-accent-color": { 5666 "type": "color", 5667 "default": "#000000", 5668 "transition": true, 5669 "expression": { 5670 "interpolated": true, 5671 "parameters": ["zoom"] 5672 }, 5673 "property-type": "data-constant" 5674 }, 5675 "hillshade-method": { 5676 "type": "enum", 5677 "values": { 5678 "standard": {}, 5679 "basic": {}, 5680 "combined": {}, 5681 "igor": {}, 5682 "multidirectional": {} 5683 }, 5684 "default": "standard", 5685 "expression": { 5686 "interpolated": false, 5687 "parameters": ["zoom"] 5688 }, 5689 "property-type": "data-constant" 5690 }, 5691 "resampling": { 5692 "type": "enum", 5693 "values": { 5694 "linear": {}, 5695 "nearest": {} 5696 }, 5697 "default": "linear", 5698 "expression": { 5699 "interpolated": false, 5700 "parameters": ["zoom"] 5701 }, 5702 "property-type": "data-constant" 5703 } 5704 }, 5705 "paint_color-relief": { 5706 "color-relief-opacity": { 5707 "type": "number", 5708 "default": 1, 5709 "minimum": 0, 5710 "maximum": 1, 5711 "transition": true, 5712 "expression": { 5713 "interpolated": true, 5714 "parameters": ["zoom"] 5715 }, 5716 "property-type": "data-constant" 5717 }, 5718 "color-relief-color": { 5719 "type": "color", 5720 "transition": false, 5721 "expression": { 5722 "interpolated": true, 5723 "parameters": ["elevation"] 5724 }, 5725 "property-type": "color-ramp" 5726 }, 5727 "resampling": { 5728 "type": "enum", 5729 "values": { 5730 "linear": {}, 5731 "nearest": {} 5732 }, 5733 "default": "linear", 5734 "expression": { 5735 "interpolated": false, 5736 "parameters": ["zoom"] 5737 }, 5738 "property-type": "data-constant" 5739 } 5740 }, 5741 paint_background: { 5742 "background-color": { 5743 "type": "color", 5744 "default": "#000000", 5745 "transition": true, 5746 "requires": [{ "!": "background-pattern" }], 5747 "expression": { 5748 "interpolated": true, 5749 "parameters": ["zoom"] 5750 }, 5751 "property-type": "data-constant" 5752 }, 5753 "background-pattern": { 5754 "type": "resolvedImage", 5755 "transition": true, 5756 "expression": { 5757 "interpolated": false, 5758 "parameters": ["zoom"] 5759 }, 5760 "property-type": "cross-faded" 5761 }, 5762 "background-opacity": { 5763 "type": "number", 5764 "default": 1, 5765 "minimum": 0, 5766 "maximum": 1, 5767 "transition": true, 5768 "expression": { 5769 "interpolated": true, 5770 "parameters": ["zoom"] 5771 }, 5772 "property-type": "data-constant" 5773 } 5774 }, 5775 transition: { 5776 "duration": { 5777 "type": "number", 5778 "default": 300, 5779 "minimum": 0, 5780 "units": "milliseconds" 5781 }, 5782 "delay": { 5783 "type": "number", 5784 "default": 0, 5785 "minimum": 0, 5786 "units": "milliseconds" 5787 } 5788 }, 5789 "property-type": { 5790 "data-driven": { "type": "property-type" }, 5791 "cross-faded": { "type": "property-type" }, 5792 "cross-faded-data-driven": { "type": "property-type" }, 5793 "color-ramp": { "type": "property-type" }, 5794 "data-constant": { "type": "property-type" }, 5795 "constant": { "type": "property-type" } 5796 }, 5797 promoteId: { "*": { "type": "string" } }, 5798 interpolation: { 5799 "type": "array", 5800 "value": "interpolation_name", 5801 "minimum": 1 5802 }, 5803 interpolation_name: { 5804 "type": "enum", 5805 "values": { 5806 "linear": { "syntax": { 5807 "overloads": [{ 5808 "parameters": [], 5809 "output-type": "interpolation" 5810 }], 5811 "parameters": [] 5812 } }, 5813 "exponential": { "syntax": { 5814 "overloads": [{ 5815 "parameters": ["base"], 5816 "output-type": "interpolation" 5817 }], 5818 "parameters": [{ 5819 "name": "base", 5820 "type": "number literal" 5821 }] 5822 } }, 5823 "cubic-bezier": { "syntax": { 5824 "overloads": [{ 5825 "parameters": [ 5826 "x1", 5827 "y1", 5828 "x2", 5829 "y2" 5830 ], 5831 "output-type": "interpolation" 5832 }], 5833 "parameters": [ 5834 { 5835 "name": "x1", 5836 "type": "number literal" 5837 }, 5838 { 5839 "name": "y1", 5840 "type": "number literal" 5841 }, 5842 { 5843 "name": "x2", 5844 "type": "number literal" 5845 }, 5846 { 5847 "name": "y2", 5848 "type": "number literal" 5849 } 5850 ] 5851 } } 5852 } 5853 } 5854}; 5855//#endregion 5856//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/reference/latest.mjs 5857const latest = v8_default; 5858//#endregion 5859//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/util/ref_properties.mjs 5860const refProperties = [ 5861 "type", 5862 "source", 5863 "source-layer", 5864 "minzoom", 5865 "maxzoom", 5866 "filter", 5867 "layout" 5868]; 5869//#endregion 5870//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/deref.mjs 5871function deref(layer, parent) { 5872 const result = {}; 5873 for (const k in layer) if (k !== "ref") result[k] = layer[k]; 5874 refProperties.forEach((k) => { 5875 if (k in parent) result[k] = parent[k]; 5876 }); 5877 return result; 5878} 5879/** 5880* 5881* The input is not modified. The output may contain references to portions 5882* of the input. 5883* 5884* @param layers - array of layers, some of which may contain `ref` properties 5885* whose value is the `id` of another property 5886* @returns a new array where such layers have been augmented with the 'type', 'source', etc. properties 5887* from the parent layer, and the `ref` property has been removed. 5888*/ 5889function derefLayers(layers) { 5890 layers = layers.slice(); 5891 const map = Object.create(null); 5892 for (let i = 0; i < layers.length; i++) map[layers[i].id] = layers[i]; 5893 for (let i = 0; i < layers.length; i++) if ("ref" in layers[i]) layers[i] = deref(layers[i], map[layers[i].ref]); 5894 return layers; 5895} 5896//#endregion 5897//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/util/deep_equal.mjs 5898/** 5899* Deeply compares two object literals. 5900* 5901* @private 5902*/ 5903function deepEqual(a, b) { 5904 if (Array.isArray(a)) { 5905 if (!Array.isArray(b) || a.length !== b.length) return false; 5906 for (let i = 0; i < a.length; i++) if (!deepEqual(a[i], b[i])) return false; 5907 return true; 5908 } 5909 if (typeof a === "object" && a !== null && b !== null) { 5910 if (!(typeof b === "object")) return false; 5911 if (Object.keys(a).length !== Object.keys(b).length) return false; 5912 for (const key in a) if (!deepEqual(a[key], b[key])) return false; 5913 return true; 5914 } 5915 return a === b; 5916} 5917//#endregion 5918//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/diff.mjs 5919/** 5920* The main reason for this method is to allow type check when adding a command to the array. 5921* @param commands - The commands array to add to 5922* @param command - The command to add 5923*/ 5924function addCommand(commands, command) { 5925 commands.push(command); 5926} 5927function addSource(sourceId, after, commands) { 5928 addCommand(commands, { 5929 command: "addSource", 5930 args: [sourceId, after[sourceId]] 5931 }); 5932} 5933function removeSource(sourceId, commands, sourcesRemoved) { 5934 addCommand(commands, { 5935 command: "removeSource", 5936 args: [sourceId] 5937 }); 5938 sourcesRemoved[sourceId] = true; 5939} 5940function updateSource(sourceId, after, commands, sourcesRemoved) { 5941 removeSource(sourceId, commands, sourcesRemoved); 5942 addSource(sourceId, after, commands); 5943} 5944function canUpdateGeoJSON(before, after, sourceId) { 5945 let prop; 5946 for (prop in before[sourceId]) { 5947 if (!Object.prototype.hasOwnProperty.call(before[sourceId], prop)) continue; 5948 if (prop !== "data" && !deepEqual(before[sourceId][prop], after[sourceId][prop])) return false; 5949 } 5950 for (prop in after[sourceId]) { 5951 if (!Object.prototype.hasOwnProperty.call(after[sourceId], prop)) continue; 5952 if (prop !== "data" && !deepEqual(before[sourceId][prop], after[sourceId][prop])) return false; 5953 } 5954 return true; 5955} 5956function diffSources(before, after, commands, sourcesRemoved) { 5957 before = before || {}; 5958 after = after || {}; 5959 let sourceId; 5960 for (sourceId in before) { 5961 if (!Object.prototype.hasOwnProperty.call(before, sourceId)) continue; 5962 if (!Object.prototype.hasOwnProperty.call(after, sourceId)) removeSource(sourceId, commands, sourcesRemoved); 5963 } 5964 for (sourceId in after) { 5965 if (!Object.prototype.hasOwnProperty.call(after, sourceId)) continue; 5966 if (!Object.prototype.hasOwnProperty.call(before, sourceId)) addSource(sourceId, after, commands); 5967 else if (!deepEqual(before[sourceId], after[sourceId])) { 5968 if (before[sourceId].type === "geojson" && after[sourceId].type === "geojson" && canUpdateGeoJSON(before, after, sourceId)) addCommand(commands, { 5969 command: "setGeoJSONSourceData", 5970 args: [sourceId, after[sourceId].data] 5971 }); 5972 else updateSource(sourceId, after, commands, sourcesRemoved); 5973 } 5974 } 5975} 5976/** 5977* Adds a paint or layout property command for a single property of a layer. 5978* The property names are taken from a layer's paint/layout object, so they are known to be 5979* valid names for the given command, which a `for ... in` loop over that object can't express. 5980* @param after - The paint or layout object to take the property value from 5981* @param commands - The commands array to add to 5982* @param layerId - The id of the layer the property belongs to 5983* @param prop - The name of the property that changed 5984* @param command - The command to add 5985*/ 5986function addPropertyCommand(after, commands, layerId, prop, command) { 5987 if (command === "setPaintProperty") addCommand(commands, { 5988 command, 5989 args: [ 5990 layerId, 5991 prop, 5992 after[prop] 5993 ] 5994 }); 5995 else addCommand(commands, { 5996 command, 5997 args: [ 5998 layerId, 5999 prop, 6000 after[prop] 6001 ] 6002 }); 6003} 6004function diffLayerPropertyChanges(before, after, commands, layerId, command) { 6005 before = before || {}; 6006 after = after || {}; 6007 for (const prop in before) { 6008 if (!Object.prototype.hasOwnProperty.call(before, prop)) continue; 6009 if (!deepEqual(before[prop], after[prop])) addPropertyCommand(after, commands, layerId, prop, command); 6010 } 6011 for (const prop in after) { 6012 if (!Object.prototype.hasOwnProperty.call(after, prop) || Object.prototype.hasOwnProperty.call(before, prop)) continue; 6013 if (!deepEqual(before[prop], after[prop])) addPropertyCommand(after, commands, layerId, prop, command); 6014 } 6015} 6016function pluckId(layer) { 6017 return layer.id; 6018} 6019function indexById(group, layer) { 6020 group[layer.id] = layer; 6021 return group; 6022} 6023function diffLayers(before, after, commands) { 6024 before = before || []; 6025 after = after || []; 6026 const beforeOrder = before.map(pluckId); 6027 const afterOrder = after.map(pluckId); 6028 const beforeIndex = before.reduce(indexById, {}); 6029 const afterIndex = after.reduce(indexById, {}); 6030 const tracker = beforeOrder.slice(); 6031 const clean = Object.create(null); 6032 let layerId; 6033 let beforeLayer; 6034 let afterLayer; 6035 let insertBeforeLayerId; 6036 let prop; 6037 for (let i = 0, d = 0; i < beforeOrder.length; i++) { 6038 layerId = beforeOrder[i]; 6039 if (!Object.prototype.hasOwnProperty.call(afterIndex, layerId)) { 6040 addCommand(commands, { 6041 command: "removeLayer", 6042 args: [layerId] 6043 }); 6044 tracker.splice(tracker.indexOf(layerId, d), 1); 6045 } else d++; 6046 } 6047 for (let i = 0, d = 0; i < afterOrder.length; i++) { 6048 layerId = afterOrder[afterOrder.length - 1 - i]; 6049 if (tracker[tracker.length - 1 - i] === layerId) continue; 6050 if (Object.prototype.hasOwnProperty.call(beforeIndex, layerId)) { 6051 addCommand(commands, { 6052 command: "removeLayer", 6053 args: [layerId] 6054 }); 6055 tracker.splice(tracker.lastIndexOf(layerId, tracker.length - d), 1); 6056 } else d++; 6057 insertBeforeLayerId = tracker[tracker.length - i]; 6058 addCommand(commands, { 6059 command: "addLayer", 6060 args: [afterIndex[layerId], insertBeforeLayerId] 6061 }); 6062 tracker.splice(tracker.length - i, 0, layerId); 6063 clean[layerId] = true; 6064 } 6065 for (let i = 0; i < afterOrder.length; i++) { 6066 layerId = afterOrder[i]; 6067 beforeLayer = beforeIndex[layerId]; 6068 afterLayer = afterIndex[layerId]; 6069 if (clean[layerId] || deepEqual(beforeLayer, afterLayer)) continue; 6070 if (!deepEqual(beforeLayer.source, afterLayer.source) || !deepEqual(beforeLayer["source-layer"], afterLayer["source-layer"]) || !deepEqual(beforeLayer.type, afterLayer.type)) { 6071 addCommand(commands, { 6072 command: "removeLayer", 6073 args: [layerId] 6074 }); 6075 insertBeforeLayerId = tracker[tracker.lastIndexOf(layerId) + 1]; 6076 addCommand(commands, { 6077 command: "addLayer", 6078 args: [afterLayer, insertBeforeLayerId] 6079 }); 6080 continue; 6081 } 6082 diffLayerPropertyChanges(beforeLayer.layout, afterLayer.layout, commands, layerId, "setLayoutProperty"); 6083 diffLayerPropertyChanges(beforeLayer.paint, afterLayer.paint, commands, layerId, "setPaintProperty"); 6084 if (!deepEqual(beforeLayer.filter, afterLayer.filter)) addCommand(commands, { 6085 command: "setFilter", 6086 args: [layerId, afterLayer.filter] 6087 }); 6088 if (!deepEqual(beforeLayer.minzoom, afterLayer.minzoom) || !deepEqual(beforeLayer.maxzoom, afterLayer.maxzoom)) addCommand(commands, { 6089 command: "setLayerZoomRange", 6090 args: [ 6091 layerId, 6092 afterLayer.minzoom, 6093 afterLayer.maxzoom 6094 ] 6095 }); 6096 for (prop in beforeLayer) { 6097 if (!Object.prototype.hasOwnProperty.call(beforeLayer, prop)) continue; 6098 if (prop === "layout" || prop === "paint" || prop === "filter" || prop === "metadata" || prop === "minzoom" || prop === "maxzoom") continue; 6099 if (prop.indexOf("paint.") === 0) diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, "setPaintProperty"); 6100 else if (!deepEqual(beforeLayer[prop], afterLayer[prop])) addCommand(commands, { 6101 command: "setLayerProperty", 6102 args: [ 6103 layerId, 6104 prop, 6105 afterLayer[prop] 6106 ] 6107 }); 6108 } 6109 for (prop in afterLayer) { 6110 if (!Object.prototype.hasOwnProperty.call(afterLayer, prop) || Object.prototype.hasOwnProperty.call(beforeLayer, prop)) continue; 6111 if (prop === "layout" || prop === "paint" || prop === "filter" || prop === "metadata" || prop === "minzoom" || prop === "maxzoom") continue; 6112 if (prop.indexOf("paint.") === 0) diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, "setPaintProperty"); 6113 else if (!deepEqual(beforeLayer[prop], afterLayer[prop])) addCommand(commands, { 6114 command: "setLayerProperty", 6115 args: [ 6116 layerId, 6117 prop, 6118 afterLayer[prop] 6119 ] 6120 }); 6121 } 6122 } 6123} 6124/** 6125* Diff two stylesheet 6126* 6127* Creates semanticly aware diffs that can easily be applied at runtime. 6128* Operations produced by the diff closely resemble the maplibre-gl-js API. Any 6129* error creating the diff will fall back to the 'setStyle' operation. 6130* 6131* Example diff: 6132* [ 6133* { command: 'setConstant', args: ['@water', '#0000FF'] }, 6134* { command: 'setPaintProperty', args: ['background', 'background-color', 'black'] } 6135* ] 6136* 6137* @private 6138* @param {*} [before] stylesheet to compare from 6139* @param {*} after stylesheet to compare to 6140* @returns Array list of changes 6141*/ 6142function diff(before, after) { 6143 if (!before) return [{ 6144 command: "setStyle", 6145 args: [after] 6146 }]; 6147 let commands = []; 6148 try { 6149 if (!deepEqual(before.version, after.version)) return [{ 6150 command: "setStyle", 6151 args: [after] 6152 }]; 6153 if (!deepEqual(before.center, after.center)) commands.push({ 6154 command: "setCenter", 6155 args: [after.center] 6156 }); 6157 if (!deepEqual(before.state, after.state)) commands.push({ 6158 command: "setGlobalState", 6159 args: [after.state] 6160 }); 6161 if (!deepEqual(before.centerAltitude, after.centerAltitude)) commands.push({ 6162 command: "setCenterAltitude", 6163 args: [after.centerAltitude] 6164 }); 6165 if (!deepEqual(before.zoom, after.zoom)) commands.push({ 6166 command: "setZoom", 6167 args: [after.zoom] 6168 }); 6169 if (!deepEqual(before.bearing, after.bearing)) commands.push({ 6170 command: "setBearing", 6171 args: [after.bearing] 6172 }); 6173 if (!deepEqual(before.pitch, after.pitch)) commands.push({ 6174 command: "setPitch", 6175 args: [after.pitch] 6176 }); 6177 if (!deepEqual(before.roll, after.roll)) commands.push({ 6178 command: "setRoll", 6179 args: [after.roll] 6180 }); 6181 if (!deepEqual(before.sprite, after.sprite)) commands.push({ 6182 command: "setSprite", 6183 args: [after.sprite] 6184 }); 6185 if (!deepEqual(before.glyphs, after.glyphs)) commands.push({ 6186 command: "setGlyphs", 6187 args: [after.glyphs] 6188 }); 6189 if (!deepEqual(before["font-faces"], after["font-faces"])) commands.push({ 6190 command: "setFontFaces", 6191 args: [after["font-faces"]] 6192 }); 6193 if (!deepEqual(before.transition, after.transition)) commands.push({ 6194 command: "setTransition", 6195 args: [after.transition] 6196 }); 6197 if (!deepEqual(before.light, after.light)) commands.push({ 6198 command: "setLight", 6199 args: [after.light] 6200 }); 6201 const terrainChanged = !deepEqual(before.terrain, after.terrain); 6202 if (terrainChanged && !after.terrain) commands.push({ 6203 command: "setTerrain", 6204 args: [void 0] 6205 }); 6206 if (!deepEqual(before.sky, after.sky)) commands.push({ 6207 command: "setSky", 6208 args: [after.sky] 6209 }); 6210 if (!deepEqual(before.projection, after.projection)) commands.push({ 6211 command: "setProjection", 6212 args: [after.projection] 6213 }); 6214 const sourcesRemoved = {}; 6215 const removeOrAddSourceCommands = []; 6216 diffSources(before.sources, after.sources, removeOrAddSourceCommands, sourcesRemoved); 6217 const beforeLayers = []; 6218 if (before.layers) before.layers.forEach((layer) => { 6219 if ("source" in layer && sourcesRemoved[layer.source]) commands.push({ 6220 command: "removeLayer", 6221 args: [layer.id] 6222 }); 6223 else beforeLayers.push(layer); 6224 }); 6225 commands = commands.concat(removeOrAddSourceCommands); 6226 diffLayers(beforeLayers, after.layers, commands); 6227 if (terrainChanged && after.terrain) commands.push({ 6228 command: "setTerrain", 6229 args: [after.terrain] 6230 }); 6231 } catch (e) { 6232 console.warn("Unable to compute style diff:", e); 6233 commands = [{ 6234 command: "setStyle", 6235 args: [after] 6236 }]; 6237 } 6238 return commands; 6239} 6240//#endregion 6241//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/error/validation_error.mjs 6242var ValidationError = class { 6243 constructor(key, value, message, identifier, severity = "error") { 6244 this.message = (key ? `${key}: ` : "") + message; 6245 if (identifier) this.identifier = identifier; 6246 this.severity = severity; 6247 if (value !== null && value !== void 0 && value.__line__) this.line = value.__line__; 6248 } 6249}; 6250//#endregion 6251//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types.mjs 6252const NullType = { kind: "null" }; 6253const NumberType = { kind: "number" }; 6254const StringType = { kind: "string" }; 6255const BooleanType = { kind: "boolean" }; 6256const ColorType = { kind: "color" }; 6257const ProjectionDefinitionType = { kind: "projectionDefinition" }; 6258const ObjectType = { kind: "object" }; 6259const ValueType = { kind: "value" }; 6260const ErrorType = { kind: "error" }; 6261const CollatorType = { kind: "collator" }; 6262const FormattedType = { kind: "formatted" }; 6263const PaddingType = { kind: "padding" }; 6264const ColorArrayType = { kind: "colorArray" }; 6265const NumberArrayType = { kind: "numberArray" }; 6266const ResolvedImageType = { kind: "resolvedImage" }; 6267const VariableAnchorOffsetCollectionType = { kind: "variableAnchorOffsetCollection" }; 6268function array(itemType, N) { 6269 return { 6270 kind: "array", 6271 itemType, 6272 N 6273 }; 6274} 6275function typeToString(type) { 6276 if (type.kind === "array") { 6277 const itemType = typeToString(type.itemType); 6278 return typeof type.N === "number" ? `array<${itemType}, ${type.N}>` : type.itemType.kind === "value" ? "array" : `array<${itemType}>`; 6279 } else return type.kind; 6280} 6281const valueMemberTypes = [ 6282 NullType, 6283 NumberType, 6284 StringType, 6285 BooleanType, 6286 ColorType, 6287 ProjectionDefinitionType, 6288 FormattedType, 6289 ObjectType, 6290 array(ValueType), 6291 PaddingType, 6292 NumberArrayType, 6293 ColorArrayType, 6294 ResolvedImageType, 6295 VariableAnchorOffsetCollectionType 6296]; 6297/** 6298* Returns null if `t` is a subtype of `expected`; otherwise returns an 6299* error message. 6300* @private 6301*/ 6302function checkSubtype(expected, t) { 6303 if (t.kind === "error") return null; 6304 else if (expected.kind === "array") { 6305 if (t.kind === "array" && (t.N === 0 && t.itemType.kind === "value" || !checkSubtype(expected.itemType, t.itemType)) && (typeof expected.N !== "number" || expected.N === t.N)) return null; 6306 } else if (expected.kind === t.kind) return null; 6307 else if (expected.kind === "value") { 6308 for (const memberType of valueMemberTypes) if (!checkSubtype(memberType, t)) return null; 6309 } 6310 return `Expected ${typeToString(expected)} but found ${typeToString(t)} instead.`; 6311} 6312function isValidType(provided, allowedTypes) { 6313 return allowedTypes.some((t) => t.kind === provided.kind); 6314} 6315function isValidNativeType(provided, allowedTypes) { 6316 return allowedTypes.some((t) => { 6317 if (t === "null") return provided === null; 6318 else if (t === "array") return Array.isArray(provided); 6319 else if (t === "object") return provided && !Array.isArray(provided) && typeof provided === "object"; 6320 else return t === typeof provided; 6321 }); 6322} 6323/** 6324* Verify whether the specified type is of the same type as the specified sample. 6325* 6326* @param provided Type to verify 6327* @param sample Sample type to reference 6328* @returns `true` if both objects are of the same type, `false` otherwise 6329* @example basic types 6330* if (verifyType(outputType, ValueType)) { 6331* // type narrowed to: 6332* outputType.kind; // 'value' 6333* } 6334* @example array types 6335* if (verifyType(outputType, array(NumberType))) { 6336* // type narrowed to: 6337* outputType.kind; // 'array' 6338* outputType.itemType; // NumberTypeT 6339* outputType.itemType.kind; // 'number' 6340* } 6341*/ 6342function verifyType(provided, sample) { 6343 if (provided.kind === "array" && sample.kind === "array") return provided.itemType.kind === sample.itemType.kind && typeof provided.N === "number"; 6344 return provided.kind === sample.kind; 6345} 6346//#endregion 6347//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types/color_spaces.mjs 6348const Xn = .96422; 6349const Yn = 1; 6350const Zn = .82521; 6351const t0 = 4 / 29; 6352const t1 = 6 / 29; 6353const t2 = 3 * t1 * t1; 6354const t3 = t1 * t1 * t1; 6355const deg2rad = Math.PI / 180; 6356const rad2deg = 180 / Math.PI; 6357function constrainAngle(angle) { 6358 angle = angle % 360; 6359 if (angle < 0) angle += 360; 6360 return angle; 6361} 6362function rgbToLab([r, g, b, alpha]) { 6363 r = rgb2xyz(r); 6364 g = rgb2xyz(g); 6365 b = rgb2xyz(b); 6366 let x, z; 6367 const y = xyz2lab((.2225045 * r + .7168786 * g + .0606169 * b) / Yn); 6368 if (r === g && g === b) x = z = y; 6369 else { 6370 x = xyz2lab((.4360747 * r + .3850649 * g + .1430804 * b) / Xn); 6371 z = xyz2lab((.0139322 * r + .0971045 * g + .7141733 * b) / Zn); 6372 } 6373 const l = 116 * y - 16; 6374 return [ 6375 l < 0 ? 0 : l, 6376 500 * (x - y), 6377 200 * (y - z), 6378 alpha 6379 ]; 6380} 6381function rgb2xyz(x) { 6382 return x <= .04045 ? x / 12.92 : Math.pow((x + .055) / 1.055, 2.4); 6383} 6384function xyz2lab(t) { 6385 return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0; 6386} 6387function labToRgb([l, a, b, alpha]) { 6388 let y = (l + 16) / 116, x = isNaN(a) ? y : y + a / 500, z = isNaN(b) ? y : y - b / 200; 6389 y = Yn * lab2xyz(y); 6390 x = Xn * lab2xyz(x); 6391 z = Zn * lab2xyz(z); 6392 return [ 6393 xyz2rgb(3.1338561 * x - 1.6168667 * y - .4906146 * z), 6394 xyz2rgb(-.9787684 * x + 1.9161415 * y + .033454 * z), 6395 xyz2rgb(.0719453 * x - .2289914 * y + 1.4052427 * z), 6396 alpha 6397 ]; 6398} 6399function xyz2rgb(x) { 6400 x = x <= .00304 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - .055; 6401 return x < 0 ? 0 : x > 1 ? 1 : x; 6402} 6403function lab2xyz(t) { 6404 return t > t1 ? t * t * t : t2 * (t - t0); 6405} 6406function rgbToHcl(rgbColor) { 6407 const [l, a, b, alpha] = rgbToLab(rgbColor); 6408 const c = Math.sqrt(a * a + b * b); 6409 return [ 6410 Math.round(c * 1e4) ? constrainAngle(Math.atan2(b, a) * rad2deg) : NaN, 6411 c, 6412 l, 6413 alpha 6414 ]; 6415} 6416function hclToRgb([h, c, l, alpha]) { 6417 h = isNaN(h) ? 0 : h * deg2rad; 6418 return labToRgb([ 6419 l, 6420 Math.cos(h) * c, 6421 Math.sin(h) * c, 6422 alpha 6423 ]); 6424} 6425function hslToRgb([h, s, l, alpha]) { 6426 h = constrainAngle(h); 6427 s /= 100; 6428 l /= 100; 6429 function f(n) { 6430 const k = (n + h / 30) % 12; 6431 const a = s * Math.min(l, 1 - l); 6432 return l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1)); 6433 } 6434 return [ 6435 f(0), 6436 f(8), 6437 f(4), 6438 alpha 6439 ]; 6440} 6441//#endregion 6442//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/util/get_own.mjs 6443const hasOwnProperty = Object.hasOwn || function hasOwnProperty(object, key) { 6444 return Object.prototype.hasOwnProperty.call(object, key); 6445}; 6446function getOwn(object, key) { 6447 return hasOwnProperty(object, key) ? object[key] : void 0; 6448} 6449//#endregion 6450//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types/parse_css_color.mjs 6451/** 6452* CSS color parser compliant with CSS Color 4 Specification. 6453* Supports: named colors, `transparent` keyword, all rgb hex notations, 6454* rgb(), rgba(), hsl() and hsla() functions. 6455* Does not round the parsed values to integers from the range 0..255. 6456* 6457* Syntax: 6458* 6459* <alpha-value> = <number> | <percentage> 6460* <hue> = <number> | <angle> 6461* 6462* rgb() = rgb( <percentage>{3} [ / <alpha-value> ]? ) | rgb( <number>{3} [ / <alpha-value> ]? ) 6463* rgb() = rgb( <percentage>#{3} , <alpha-value>? ) | rgb( <number>#{3} , <alpha-value>? ) 6464* 6465* hsl() = hsl( <hue> <percentage> <percentage> [ / <alpha-value> ]? ) 6466* hsl() = hsl( <hue>, <percentage>, <percentage>, <alpha-value>? ) 6467* 6468* Caveats: 6469* - <angle> - <number> with optional `deg` suffix; `grad`, `rad`, `turn` are not supported 6470* - `none` keyword is not supported 6471* - comments inside rgb()/hsl() are not supported 6472* - legacy color syntax rgba() is supported with an identical grammar and behavior to rgb() 6473* - legacy color syntax hsla() is supported with an identical grammar and behavior to hsl() 6474* 6475* @param input CSS color string to parse. 6476* @returns Color in sRGB color space, with `red`, `green`, `blue` 6477* and `alpha` channels normalized to the range 0..1, 6478* or `undefined` if the input is not a valid color string. 6479*/ 6480function parseCssColor(input) { 6481 input = input.toLowerCase().trim(); 6482 if (input === "transparent") return [ 6483 0, 6484 0, 6485 0, 6486 0 6487 ]; 6488 const namedColorsMatch = getOwn(namedColors, input); 6489 if (namedColorsMatch) { 6490 const [r, g, b] = namedColorsMatch; 6491 return [ 6492 r / 255, 6493 g / 255, 6494 b / 255, 6495 1 6496 ]; 6497 } 6498 if (input.startsWith("#")) { 6499 if (/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(input)) { 6500 const step = input.length < 6 ? 1 : 2; 6501 let i = 1; 6502 return [ 6503 parseHex(input.slice(i, i += step)), 6504 parseHex(input.slice(i, i += step)), 6505 parseHex(input.slice(i, i += step)), 6506 parseHex(input.slice(i, i + step) || "ff") 6507 ]; 6508 } 6509 } 6510 if (input.startsWith("rgb")) { 6511 const rgbMatch = input.match(/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/); 6512 if (rgbMatch) { 6513 const [_, r, rp, f1, g, gp, f2, b, bp, f3, a, ap] = rgbMatch; 6514 const argFormat = [ 6515 f1 || " ", 6516 f2 || " ", 6517 f3 6518 ].join(""); 6519 if (argFormat === " " || argFormat === " /" || argFormat === ",," || argFormat === ",,,") { 6520 const valFormat = [ 6521 rp, 6522 gp, 6523 bp 6524 ].join(""); 6525 const maxValue = valFormat === "%%%" ? 100 : valFormat === "" ? 255 : 0; 6526 if (maxValue) { 6527 const rgba = [ 6528 clamp$1(+r / maxValue, 0, 1), 6529 clamp$1(+g / maxValue, 0, 1), 6530 clamp$1(+b / maxValue, 0, 1), 6531 a ? parseAlpha(+a, ap) : 1 6532 ]; 6533 if (validateNumbers(rgba)) return rgba; 6534 } 6535 } 6536 return; 6537 } 6538 } 6539 const hslMatch = input.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/); 6540 if (hslMatch) { 6541 const [_, h, f1, s, f2, l, f3, a, ap] = hslMatch; 6542 const argFormat = [ 6543 f1 || " ", 6544 f2 || " ", 6545 f3 6546 ].join(""); 6547 if (argFormat === " " || argFormat === " /" || argFormat === ",," || argFormat === ",,,") { 6548 const hsla = [ 6549 +h, 6550 clamp$1(+s, 0, 100), 6551 clamp$1(+l, 0, 100), 6552 a ? parseAlpha(+a, ap) : 1 6553 ]; 6554 if (validateNumbers(hsla)) return hslToRgb(hsla); 6555 } 6556 } 6557} 6558function parseHex(hex) { 6559 return parseInt(hex.padEnd(2, hex), 16) / 255; 6560} 6561function parseAlpha(a, asPercentage) { 6562 return clamp$1(asPercentage ? a / 100 : a, 0, 1); 6563} 6564function clamp$1(n, min, max) { 6565 return Math.min(Math.max(min, n), max); 6566} 6567/** 6568* The regular expression for numeric values is not super specific, and it may 6569* happen that it will accept a value that is not a valid number. In order to 6570* detect and eliminate such values this function exists. 6571* 6572* @param array Array of uncertain numbers. 6573* @returns `true` if the specified array contains only valid numbers, `false` otherwise. 6574*/ 6575function validateNumbers(array) { 6576 return !array.some(Number.isNaN); 6577} 6578/** 6579* To generate: 6580* - visit {@link https://www.w3.org/TR/css-color-4/#named-colors} 6581* - run in the console: 6582* @example 6583* copy(`{\n${[...document.querySelector('.named-color-table tbody').children].map((tr) => `${tr.cells[2].textContent.trim()}: [${tr.cells[4].textContent.trim().split(/\s+/).join(', ')}],`).join('\n')}\n}`); 6584*/ 6585const namedColors = { 6586 aliceblue: [ 6587 240, 6588 248, 6589 255 6590 ], 6591 antiquewhite: [ 6592 250, 6593 235, 6594 215 6595 ], 6596 aqua: [ 6597 0, 6598 255, 6599 255 6600 ], 6601 aquamarine: [ 6602 127, 6603 255, 6604 212 6605 ], 6606 azure: [ 6607 240, 6608 255, 6609 255 6610 ], 6611 beige: [ 6612 245, 6613 245, 6614 220 6615 ], 6616 bisque: [ 6617 255, 6618 228, 6619 196 6620 ], 6621 black: [ 6622 0, 6623 0, 6624 0 6625 ], 6626 blanchedalmond: [ 6627 255, 6628 235, 6629 205 6630 ], 6631 blue: [ 6632 0, 6633 0, 6634 255 6635 ], 6636 blueviolet: [ 6637 138, 6638 43, 6639 226 6640 ], 6641 brown: [ 6642 165, 6643 42, 6644 42 6645 ], 6646 burlywood: [ 6647 222, 6648 184, 6649 135 6650 ], 6651 cadetblue: [ 6652 95, 6653 158, 6654 160 6655 ], 6656 chartreuse: [ 6657 127, 6658 255, 6659 0 6660 ], 6661 chocolate: [ 6662 210, 6663 105, 6664 30 6665 ], 6666 coral: [ 6667 255, 6668 127, 6669 80 6670 ], 6671 cornflowerblue: [ 6672 100, 6673 149, 6674 237 6675 ], 6676 cornsilk: [ 6677 255, 6678 248, 6679 220 6680 ], 6681 crimson: [ 6682 220, 6683 20, 6684 60 6685 ], 6686 cyan: [ 6687 0, 6688 255, 6689 255 6690 ], 6691 darkblue: [ 6692 0, 6693 0, 6694 139 6695 ], 6696 darkcyan: [ 6697 0, 6698 139, 6699 139 6700 ], 6701 darkgoldenrod: [ 6702 184, 6703 134, 6704 11 6705 ], 6706 darkgray: [ 6707 169, 6708 169, 6709 169 6710 ], 6711 darkgreen: [ 6712 0, 6713 100, 6714 0 6715 ], 6716 darkgrey: [ 6717 169, 6718 169, 6719 169 6720 ], 6721 darkkhaki: [ 6722 189, 6723 183, 6724 107 6725 ], 6726 darkmagenta: [ 6727 139, 6728 0, 6729 139 6730 ], 6731 darkolivegreen: [ 6732 85, 6733 107, 6734 47 6735 ], 6736 darkorange: [ 6737 255, 6738 140, 6739 0 6740 ], 6741 darkorchid: [ 6742 153, 6743 50, 6744 204 6745 ], 6746 darkred: [ 6747 139, 6748 0, 6749 0 6750 ], 6751 darksalmon: [ 6752 233, 6753 150, 6754 122 6755 ], 6756 darkseagreen: [ 6757 143, 6758 188, 6759 143 6760 ], 6761 darkslateblue: [ 6762 72, 6763 61, 6764 139 6765 ], 6766 darkslategray: [ 6767 47, 6768 79, 6769 79 6770 ], 6771 darkslategrey: [ 6772 47, 6773 79, 6774 79 6775 ], 6776 darkturquoise: [ 6777 0, 6778 206, 6779 209 6780 ], 6781 darkviolet: [ 6782 148, 6783 0, 6784 211 6785 ], 6786 deeppink: [ 6787 255, 6788 20, 6789 147 6790 ], 6791 deepskyblue: [ 6792 0, 6793 191, 6794 255 6795 ], 6796 dimgray: [ 6797 105, 6798 105, 6799 105 6800 ], 6801 dimgrey: [ 6802 105, 6803 105, 6804 105 6805 ], 6806 dodgerblue: [ 6807 30, 6808 144, 6809 255 6810 ], 6811 firebrick: [ 6812 178, 6813 34, 6814 34 6815 ], 6816 floralwhite: [ 6817 255, 6818 250, 6819 240 6820 ], 6821 forestgreen: [ 6822 34, 6823 139, 6824 34 6825 ], 6826 fuchsia: [ 6827 255, 6828 0, 6829 255 6830 ], 6831 gainsboro: [ 6832 220, 6833 220, 6834 220 6835 ], 6836 ghostwhite: [ 6837 248, 6838 248, 6839 255 6840 ], 6841 gold: [ 6842 255, 6843 215, 6844 0 6845 ], 6846 goldenrod: [ 6847 218, 6848 165, 6849 32 6850 ], 6851 gray: [ 6852 128, 6853 128, 6854 128 6855 ], 6856 green: [ 6857 0, 6858 128, 6859 0 6860 ], 6861 greenyellow: [ 6862 173, 6863 255, 6864 47 6865 ], 6866 grey: [ 6867 128, 6868 128, 6869 128 6870 ], 6871 honeydew: [ 6872 240, 6873 255, 6874 240 6875 ], 6876 hotpink: [ 6877 255, 6878 105, 6879 180 6880 ], 6881 indianred: [ 6882 205, 6883 92, 6884 92 6885 ], 6886 indigo: [ 6887 75, 6888 0, 6889 130 6890 ], 6891 ivory: [ 6892 255, 6893 255, 6894 240 6895 ], 6896 khaki: [ 6897 240, 6898 230, 6899 140 6900 ], 6901 lavender: [ 6902 230, 6903 230, 6904 250 6905 ], 6906 lavenderblush: [ 6907 255, 6908 240, 6909 245 6910 ], 6911 lawngreen: [ 6912 124, 6913 252, 6914 0 6915 ], 6916 lemonchiffon: [ 6917 255, 6918 250, 6919 205 6920 ], 6921 lightblue: [ 6922 173, 6923 216, 6924 230 6925 ], 6926 lightcoral: [ 6927 240, 6928 128, 6929 128 6930 ], 6931 lightcyan: [ 6932 224, 6933 255, 6934 255 6935 ], 6936 lightgoldenrodyellow: [ 6937 250, 6938 250, 6939 210 6940 ], 6941 lightgray: [ 6942 211, 6943 211, 6944 211 6945 ], 6946 lightgreen: [ 6947 144, 6948 238, 6949 144 6950 ], 6951 lightgrey: [ 6952 211, 6953 211, 6954 211 6955 ], 6956 lightpink: [ 6957 255, 6958 182, 6959 193 6960 ], 6961 lightsalmon: [ 6962 255, 6963 160, 6964 122 6965 ], 6966 lightseagreen: [ 6967 32, 6968 178, 6969 170 6970 ], 6971 lightskyblue: [ 6972 135, 6973 206, 6974 250 6975 ], 6976 lightslategray: [ 6977 119, 6978 136, 6979 153 6980 ], 6981 lightslategrey: [ 6982 119, 6983 136, 6984 153 6985 ], 6986 lightsteelblue: [ 6987 176, 6988 196, 6989 222 6990 ], 6991 lightyellow: [ 6992 255, 6993 255, 6994 224 6995 ], 6996 lime: [ 6997 0, 6998 255, 6999 0 7000 ], 7001 limegreen: [ 7002 50, 7003 205, 7004 50 7005 ], 7006 linen: [ 7007 250, 7008 240, 7009 230 7010 ], 7011 magenta: [ 7012 255, 7013 0, 7014 255 7015 ], 7016 maroon: [ 7017 128, 7018 0, 7019 0 7020 ], 7021 mediumaquamarine: [ 7022 102, 7023 205, 7024 170 7025 ], 7026 mediumblue: [ 7027 0, 7028 0, 7029 205 7030 ], 7031 mediumorchid: [ 7032 186, 7033 85, 7034 211 7035 ], 7036 mediumpurple: [ 7037 147, 7038 112, 7039 219 7040 ], 7041 mediumseagreen: [ 7042 60, 7043 179, 7044 113 7045 ], 7046 mediumslateblue: [ 7047 123, 7048 104, 7049 238 7050 ], 7051 mediumspringgreen: [ 7052 0, 7053 250, 7054 154 7055 ], 7056 mediumturquoise: [ 7057 72, 7058 209, 7059 204 7060 ], 7061 mediumvioletred: [ 7062 199, 7063 21, 7064 133 7065 ], 7066 midnightblue: [ 7067 25, 7068 25, 7069 112 7070 ], 7071 mintcream: [ 7072 245, 7073 255, 7074 250 7075 ], 7076 mistyrose: [ 7077 255, 7078 228, 7079 225 7080 ], 7081 moccasin: [ 7082 255, 7083 228, 7084 181 7085 ], 7086 navajowhite: [ 7087 255, 7088 222, 7089 173 7090 ], 7091 navy: [ 7092 0, 7093 0, 7094 128 7095 ], 7096 oldlace: [ 7097 253, 7098 245, 7099 230 7100 ], 7101 olive: [ 7102 128, 7103 128, 7104 0 7105 ], 7106 olivedrab: [ 7107 107, 7108 142, 7109 35 7110 ], 7111 orange: [ 7112 255, 7113 165, 7114 0 7115 ], 7116 orangered: [ 7117 255, 7118 69, 7119 0 7120 ], 7121 orchid: [ 7122 218, 7123 112, 7124 214 7125 ], 7126 palegoldenrod: [ 7127 238, 7128 232, 7129 170 7130 ], 7131 palegreen: [ 7132 152, 7133 251, 7134 152 7135 ], 7136 paleturquoise: [ 7137 175, 7138 238, 7139 238 7140 ], 7141 palevioletred: [ 7142 219, 7143 112, 7144 147 7145 ], 7146 papayawhip: [ 7147 255, 7148 239, 7149 213 7150 ], 7151 peachpuff: [ 7152 255, 7153 218, 7154 185 7155 ], 7156 peru: [ 7157 205, 7158 133, 7159 63 7160 ], 7161 pink: [ 7162 255, 7163 192, 7164 203 7165 ], 7166 plum: [ 7167 221, 7168 160, 7169 221 7170 ], 7171 powderblue: [ 7172 176, 7173 224, 7174 230 7175 ], 7176 purple: [ 7177 128, 7178 0, 7179 128 7180 ], 7181 rebeccapurple: [ 7182 102, 7183 51, 7184 153 7185 ], 7186 red: [ 7187 255, 7188 0, 7189 0 7190 ], 7191 rosybrown: [ 7192 188, 7193 143, 7194 143 7195 ], 7196 royalblue: [ 7197 65, 7198 105, 7199 225 7200 ], 7201 saddlebrown: [ 7202 139, 7203 69, 7204 19 7205 ], 7206 salmon: [ 7207 250, 7208 128, 7209 114 7210 ], 7211 sandybrown: [ 7212 244, 7213 164, 7214 96 7215 ], 7216 seagreen: [ 7217 46, 7218 139, 7219 87 7220 ], 7221 seashell: [ 7222 255, 7223 245, 7224 238 7225 ], 7226 sienna: [ 7227 160, 7228 82, 7229 45 7230 ], 7231 silver: [ 7232 192, 7233 192, 7234 192 7235 ], 7236 skyblue: [ 7237 135, 7238 206, 7239 235 7240 ], 7241 slateblue: [ 7242 106, 7243 90, 7244 205 7245 ], 7246 slategray: [ 7247 112, 7248 128, 7249 144 7250 ], 7251 slategrey: [ 7252 112, 7253 128, 7254 144 7255 ], 7256 snow: [ 7257 255, 7258 250, 7259 250 7260 ], 7261 springgreen: [ 7262 0, 7263 255, 7264 127 7265 ], 7266 steelblue: [ 7267 70, 7268 130, 7269 180 7270 ], 7271 tan: [ 7272 210, 7273 180, 7274 140 7275 ], 7276 teal: [ 7277 0, 7278 128, 7279 128 7280 ], 7281 thistle: [ 7282 216, 7283 191, 7284 216 7285 ], 7286 tomato: [ 7287 255, 7288 99, 7289 71 7290 ], 7291 turquoise: [ 7292 64, 7293 224, 7294 208 7295 ], 7296 violet: [ 7297 238, 7298 130, 7299 238 7300 ], 7301 wheat: [ 7302 245, 7303 222, 7304 179 7305 ], 7306 white: [ 7307 255, 7308 255, 7309 255 7310 ], 7311 whitesmoke: [ 7312 245, 7313 245, 7314 245 7315 ], 7316 yellow: [ 7317 255, 7318 255, 7319 0 7320 ], 7321 yellowgreen: [ 7322 154, 7323 205, 7324 50 7325 ] 7326}; 7327//#endregion 7328//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/util/interpolate-primitives.mjs 7329function interpolateNumber(from, to, t) { 7330 return from + t * (to - from); 7331} 7332function interpolateArray(from, to, t) { 7333 return from.map((d, i) => { 7334 return interpolateNumber(d, to[i], t); 7335 }); 7336} 7337//#endregion 7338//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types/color.mjs 7339/** 7340* Checks whether the specified color space is one of the supported interpolation color spaces. 7341* 7342* @param colorSpace Color space key to verify. 7343* @returns `true` if the specified color space is one of the supported 7344* interpolation color spaces, `false` otherwise 7345*/ 7346function isSupportedInterpolationColorSpace(colorSpace) { 7347 return colorSpace === "rgb" || colorSpace === "hcl" || colorSpace === "lab"; 7348} 7349/** 7350* Color representation used by WebGL. 7351* Defined in sRGB color space and pre-blended with alpha. 7352* @private 7353*/ 7354var Color = class Color { 7355 /** 7356 * @param r Red component premultiplied by `alpha` 0..1 7357 * @param g Green component premultiplied by `alpha` 0..1 7358 * @param b Blue component premultiplied by `alpha` 0..1 7359 * @param [alpha=1] Alpha component 0..1 7360 * @param [premultiplied=true] Whether the `r`, `g` and `b` values have already 7361 * been multiplied by alpha. If `true` nothing happens if `false` then they will 7362 * be multiplied automatically. 7363 */ 7364 constructor(r, g, b, alpha = 1, premultiplied = true) { 7365 this.r = r; 7366 this.g = g; 7367 this.b = b; 7368 this.a = alpha; 7369 if (!premultiplied) { 7370 this.r *= alpha; 7371 this.g *= alpha; 7372 this.b *= alpha; 7373 if (!alpha) this.overwriteGetter("rgb", [ 7374 r, 7375 g, 7376 b, 7377 alpha 7378 ]); 7379 } 7380 } 7381 static { 7382 this.black = new Color(0, 0, 0, 1); 7383 } 7384 static { 7385 this.white = new Color(1, 1, 1, 1); 7386 } 7387 static { 7388 this.transparent = new Color(0, 0, 0, 0); 7389 } 7390 static { 7391 this.red = new Color(1, 0, 0, 1); 7392 } 7393 /** 7394 * Parses CSS color strings and converts colors to sRGB color space if needed. 7395 * Officially supported color formats: 7396 * - keyword, e.g. 'aquamarine' or 'steelblue' 7397 * - hex (with 3, 4, 6 or 8 digits), e.g. '#f0f' or '#e9bebea9' 7398 * - rgb and rgba, e.g. 'rgb(0,240,120)' or 'rgba(0%,94%,47%,0.1)' or 'rgb(0 240 120 / .3)' 7399 * - hsl and hsla, e.g. 'hsl(0,0%,83%)' or 'hsla(0,0%,83%,.5)' or 'hsl(0 0% 83% / 20%)' 7400 * 7401 * @param input CSS color string to parse. 7402 * @returns A `Color` instance, or `undefined` if the input is not a valid color string. 7403 */ 7404 static parse(input) { 7405 if (input instanceof Color) return input; 7406 if (typeof input !== "string") return; 7407 const rgba = parseCssColor(input); 7408 if (rgba) return new Color(...rgba, false); 7409 } 7410 /** 7411 * Used in color interpolation and by 'to-rgba' expression. 7412 * 7413 * @returns Gien color, with reversed alpha blending, in sRGB color space. 7414 */ 7415 get rgb() { 7416 const { r, g, b, a } = this; 7417 const f = a || Infinity; 7418 return this.overwriteGetter("rgb", [ 7419 r / f, 7420 g / f, 7421 b / f, 7422 a 7423 ]); 7424 } 7425 /** 7426 * Used in color interpolation. 7427 * 7428 * @returns Gien color, with reversed alpha blending, in HCL color space. 7429 */ 7430 get hcl() { 7431 return this.overwriteGetter("hcl", rgbToHcl(this.rgb)); 7432 } 7433 /** 7434 * Used in color interpolation. 7435 * 7436 * @returns Gien color, with reversed alpha blending, in LAB color space. 7437 */ 7438 get lab() { 7439 return this.overwriteGetter("lab", rgbToLab(this.rgb)); 7440 } 7441 /** 7442 * Lazy getter pattern. When getter is called for the first time lazy value 7443 * is calculated and then overwrites getter function in given object instance. 7444 * 7445 * @example: 7446 * const redColor = Color.parse('red'); 7447 * let x = redColor.hcl; // this will invoke `get hcl()`, which will calculate 7448 * // the value of red in HCL space and invoke this `overwriteGetter` function 7449 * // which in turn will set a field with a key 'hcl' in the `redColor` object. 7450 * // In other words it will override `get hcl()` from its `Color` prototype 7451 * // with its own property: hcl = [calculated red value in hcl]. 7452 * let y = redColor.hcl; // next call will no longer invoke getter but simply 7453 * // return the previously calculated value 7454 * x === y; // true - `x` is exactly the same object as `y` 7455 * 7456 * @param getterKey Getter key 7457 * @param lazyValue Lazily calculated value to be memoized by current instance 7458 * @private 7459 */ 7460 overwriteGetter(getterKey, lazyValue) { 7461 Object.defineProperty(this, getterKey, { value: lazyValue }); 7462 return lazyValue; 7463 } 7464 /** 7465 * Used by 'to-string' expression. 7466 * 7467 * @returns Serialized color in format `rgba(r,g,b,a)` 7468 * where r,g,b are numbers within 0..255 and alpha is number within 1..0 7469 * 7470 * @example 7471 * var purple = new Color.parse('purple'); 7472 * purple.toString; // = "rgba(128,0,128,1)" 7473 * var translucentGreen = new Color.parse('rgba(26, 207, 26, .73)'); 7474 * translucentGreen.toString(); // = "rgba(26,207,26,0.73)" 7475 */ 7476 toString() { 7477 const [r, g, b, a] = this.rgb; 7478 return `rgba(${[ 7479 r, 7480 g, 7481 b 7482 ].map((n) => Math.round(n * 255)).join(",")},${a})`; 7483 } 7484 static interpolate(from, to, t, spaceKey = "rgb") { 7485 switch (spaceKey) { 7486 case "rgb": { 7487 const [r, g, b, alpha] = interpolateArray(from.rgb, to.rgb, t); 7488 return new Color(r, g, b, alpha, false); 7489 } 7490 case "hcl": { 7491 const [hue0, chroma0, light0, alphaF] = from.hcl; 7492 const [hue1, chroma1, light1, alphaT] = to.hcl; 7493 let hue, chroma; 7494 if (!isNaN(hue0) && !isNaN(hue1)) { 7495 let dh = hue1 - hue0; 7496 if (hue1 > hue0 && dh > 180) dh -= 360; 7497 else if (hue1 < hue0 && hue0 - hue1 > 180) dh += 360; 7498 hue = hue0 + t * dh; 7499 } else if (!isNaN(hue0)) { 7500 hue = hue0; 7501 if (light1 === 1 || light1 === 0) chroma = chroma0; 7502 } else if (!isNaN(hue1)) { 7503 hue = hue1; 7504 if (light0 === 1 || light0 === 0) chroma = chroma1; 7505 } else hue = NaN; 7506 const [r, g, b, alpha] = hclToRgb([ 7507 hue, 7508 chroma ?? interpolateNumber(chroma0, chroma1, t), 7509 interpolateNumber(light0, light1, t), 7510 interpolateNumber(alphaF, alphaT, t) 7511 ]); 7512 return new Color(r, g, b, alpha, false); 7513 } 7514 case "lab": { 7515 const [r, g, b, alpha] = labToRgb(interpolateArray(from.lab, to.lab, t)); 7516 return new Color(r, g, b, alpha, false); 7517 } 7518 } 7519 } 7520}; 7521//#endregion 7522//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types/formatted.mjs 7523const VERTICAL_ALIGN_OPTIONS = [ 7524 "bottom", 7525 "center", 7526 "top" 7527]; 7528var FormattedSection = class { 7529 constructor(text, image, scale, fontStack, textColor, verticalAlign) { 7530 this.text = text; 7531 this.image = image; 7532 this.scale = scale; 7533 this.fontStack = fontStack; 7534 this.textColor = textColor; 7535 this.verticalAlign = verticalAlign; 7536 } 7537}; 7538var Formatted = class Formatted { 7539 constructor(sections) { 7540 this.sections = sections; 7541 } 7542 static fromString(unformatted) { 7543 return new Formatted([new FormattedSection(unformatted, null, null, null, null, null)]); 7544 } 7545 isEmpty() { 7546 if (this.sections.length === 0) return true; 7547 return !this.sections.some((section) => section.text.length !== 0 || section.image && section.image.name.length !== 0); 7548 } 7549 static factory(text) { 7550 if (text instanceof Formatted) return text; 7551 else return Formatted.fromString(text); 7552 } 7553 toString() { 7554 if (this.sections.length === 0) return ""; 7555 return this.sections.map((section) => section.text).join(""); 7556 } 7557}; 7558//#endregion 7559//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types/padding.mjs 7560/** 7561* A set of four numbers representing padding around a box. Create instances from 7562* bare arrays or numeric values using the static method `Padding.parse`. 7563* @private 7564*/ 7565var Padding = class Padding { 7566 constructor(values) { 7567 this.values = values.slice(); 7568 } 7569 /** 7570 * Numeric padding values 7571 * @param input A padding value 7572 * @returns A `Padding` instance, or `undefined` if the input is not a valid padding value. 7573 */ 7574 static parse(input) { 7575 if (input instanceof Padding) return input; 7576 if (typeof input === "number") return new Padding([ 7577 input, 7578 input, 7579 input, 7580 input 7581 ]); 7582 if (!Array.isArray(input)) return; 7583 if (input.length < 1 || input.length > 4) return; 7584 for (const val of input) if (typeof val !== "number") return; 7585 switch (input.length) { 7586 case 1: 7587 input = [ 7588 input[0], 7589 input[0], 7590 input[0], 7591 input[0] 7592 ]; 7593 break; 7594 case 2: 7595 input = [ 7596 input[0], 7597 input[1], 7598 input[0], 7599 input[1] 7600 ]; 7601 break; 7602 case 3: input = [ 7603 input[0], 7604 input[1], 7605 input[2], 7606 input[1] 7607 ]; 7608 } 7609 return new Padding(input); 7610 } 7611 toString() { 7612 return JSON.stringify(this.values); 7613 } 7614 static interpolate(from, to, t) { 7615 return new Padding(interpolateArray(from.values, to.values, t)); 7616 } 7617}; 7618//#endregion 7619//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types/number_array.mjs 7620/** 7621* An array of numbers. Create instances from 7622* bare arrays or numeric values using the static method `NumberArray.parse`. 7623* @private 7624*/ 7625var NumberArray = class NumberArray { 7626 constructor(values) { 7627 this.values = values.slice(); 7628 } 7629 /** 7630 * Numeric NumberArray values 7631 * @param input A NumberArray value 7632 * @returns A `NumberArray` instance, or `undefined` if the input is not a valid NumberArray value. 7633 */ 7634 static parse(input) { 7635 if (input instanceof NumberArray) return input; 7636 if (typeof input === "number") return new NumberArray([input]); 7637 if (!Array.isArray(input)) return; 7638 for (const val of input) if (typeof val !== "number") return; 7639 return new NumberArray(input); 7640 } 7641 toString() { 7642 return JSON.stringify(this.values); 7643 } 7644 static interpolate(from, to, t) { 7645 return new NumberArray(interpolateArray(from.values, to.values, t)); 7646 } 7647}; 7648//#endregion 7649//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types/color_array.mjs 7650/** 7651* An array of colors. Create instances from 7652* bare arrays or strings using the static method `ColorArray.parse`. 7653* @private 7654*/ 7655var ColorArray = class ColorArray { 7656 constructor(values) { 7657 this.values = values.slice(); 7658 } 7659 /** 7660 * ColorArray values 7661 * @param input A ColorArray value 7662 * @returns A `ColorArray` instance, or `undefined` if the input is not a valid ColorArray value. 7663 */ 7664 static parse(input) { 7665 if (input instanceof ColorArray) return input; 7666 if (typeof input === "string") { 7667 const parsed_val = Color.parse(input); 7668 if (!parsed_val) return; 7669 return new ColorArray([parsed_val]); 7670 } 7671 if (!Array.isArray(input)) return; 7672 const colors = []; 7673 for (const val of input) { 7674 if (typeof val !== "string") return; 7675 const parsed_val = Color.parse(val); 7676 if (!parsed_val) return; 7677 colors.push(parsed_val); 7678 } 7679 return new ColorArray(colors); 7680 } 7681 toString() { 7682 return JSON.stringify(this.values); 7683 } 7684 static interpolate(from, to, t, spaceKey = "rgb") { 7685 const colors = []; 7686 if (from.values.length != to.values.length) throw new Error(`colorArray: Arrays have mismatched length (${from.values.length} vs. ${to.values.length}), cannot interpolate.`); 7687 for (let i = 0; i < from.values.length; i++) colors.push(Color.interpolate(from.values[i], to.values[i], t, spaceKey)); 7688 return new ColorArray(colors); 7689 } 7690}; 7691//#endregion 7692//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/runtime_error.mjs 7693var RuntimeError = class extends Error { 7694 constructor(message, path) { 7695 super(message); 7696 this.name = "RuntimeError"; 7697 this.path = path; 7698 } 7699 toJSON() { 7700 return this.message; 7701 } 7702}; 7703//#endregion 7704//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types/variable_anchor_offset_collection.mjs 7705/** Set of valid anchor positions, as a set for validation */ 7706const anchors = /* @__PURE__ */ new Set([ 7707 "center", 7708 "left", 7709 "right", 7710 "top", 7711 "bottom", 7712 "top-left", 7713 "top-right", 7714 "bottom-left", 7715 "bottom-right" 7716]); 7717/** 7718* Utility class to assist managing values for text-variable-anchor-offset property. Create instances from 7719* bare arrays using the static method `VariableAnchorOffsetCollection.parse`. 7720* @private 7721*/ 7722var VariableAnchorOffsetCollection = class VariableAnchorOffsetCollection { 7723 constructor(values) { 7724 this.values = values.slice(); 7725 } 7726 static parse(input) { 7727 if (input instanceof VariableAnchorOffsetCollection) return input; 7728 if (!Array.isArray(input) || input.length < 1 || input.length % 2 !== 0) return; 7729 for (let i = 0; i < input.length; i += 2) { 7730 const anchorValue = input[i]; 7731 const offsetValue = input[i + 1]; 7732 if (typeof anchorValue !== "string" || !anchors.has(anchorValue)) return; 7733 if (!Array.isArray(offsetValue) || offsetValue.length !== 2 || typeof offsetValue[0] !== "number" || typeof offsetValue[1] !== "number") return; 7734 } 7735 return new VariableAnchorOffsetCollection(input); 7736 } 7737 toString() { 7738 return JSON.stringify(this.values); 7739 } 7740 static interpolate(from, to, t, key) { 7741 const fromValues = from.values; 7742 const toValues = to.values; 7743 if (fromValues.length !== toValues.length) throw new RuntimeError(`Cannot interpolate values of different length. from: ${from.toString()}, to: ${to.toString()}`, key); 7744 const output = []; 7745 for (let i = 0; i < fromValues.length; i += 2) { 7746 if (fromValues[i] !== toValues[i]) throw new RuntimeError(`Cannot interpolate values containing mismatched anchors. from[${i}]: ${fromValues[i]}, to[${i}]: ${toValues[i]}`, key); 7747 output.push(fromValues[i]); 7748 const [fx, fy] = fromValues[i + 1]; 7749 const [tx, ty] = toValues[i + 1]; 7750 output.push([interpolateNumber(fx, tx, t), interpolateNumber(fy, ty, t)]); 7751 } 7752 return new VariableAnchorOffsetCollection(output); 7753 } 7754}; 7755//#endregion 7756//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types/resolved_image.mjs 7757var ResolvedImage = class ResolvedImage { 7758 constructor(options) { 7759 this.name = options.name; 7760 this.available = options.available; 7761 } 7762 toString() { 7763 return this.name; 7764 } 7765 static fromString(name) { 7766 if (!name) return null; 7767 return new ResolvedImage({ 7768 name, 7769 available: false 7770 }); 7771 } 7772}; 7773//#endregion 7774//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types/projection_definition.mjs 7775var ProjectionDefinition = class ProjectionDefinition { 7776 constructor(from, to, transition) { 7777 this.from = from; 7778 this.to = to; 7779 this.transition = transition; 7780 } 7781 toString() { 7782 if (this.from === this.to && this.transition === 1) return this.from; 7783 return JSON.stringify([ 7784 this.from, 7785 this.to, 7786 this.transition 7787 ]); 7788 } 7789 static interpolate(from, to, t) { 7790 return new ProjectionDefinition(from, to, t); 7791 } 7792 static parse(input) { 7793 if (input instanceof ProjectionDefinition) return input; 7794 if (Array.isArray(input) && input.length === 3 && typeof input[0] === "string" && typeof input[1] === "string" && typeof input[2] === "number") return new ProjectionDefinition(input[0], input[1], input[2]); 7795 if (typeof input === "object" && typeof input.from === "string" && typeof input.to === "string" && typeof input.transition === "number") return new ProjectionDefinition(input.from, input.to, input.transition); 7796 if (typeof input === "string") return new ProjectionDefinition(input, input, 1); 7797 } 7798}; 7799//#endregion 7800//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/types/collator.mjs 7801var Collator = class { 7802 constructor(caseSensitive, diacriticSensitive, locale) { 7803 if (caseSensitive) this.sensitivity = diacriticSensitive ? "variant" : "case"; 7804 else this.sensitivity = diacriticSensitive ? "accent" : "base"; 7805 this.locale = locale; 7806 this.collator = new Intl.Collator(this.locale ? this.locale : [], { 7807 sensitivity: this.sensitivity, 7808 usage: "search" 7809 }); 7810 } 7811 compare(lhs, rhs) { 7812 return this.collator.compare(lhs, rhs); 7813 } 7814 resolvedLocale() { 7815 return new Intl.Collator(this.locale ? this.locale : []).resolvedOptions().locale; 7816 } 7817}; 7818//#endregion 7819//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/values.mjs 7820function validateRGBA(r, g, b, a) { 7821 if (!(typeof r === "number" && r >= 0 && r <= 255 && typeof g === "number" && g >= 0 && g <= 255 && typeof b === "number" && b >= 0 && b <= 255)) return `Invalid rgba value [${(typeof a === "number" ? [ 7822 r, 7823 g, 7824 b, 7825 a 7826 ] : [ 7827 r, 7828 g, 7829 b 7830 ]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`; 7831 if (!(typeof a === "undefined" || typeof a === "number" && a >= 0 && a <= 1)) return `Invalid rgba value [${[ 7832 r, 7833 g, 7834 b, 7835 a 7836 ].join(", ")}]: 'a' must be between 0 and 1.`; 7837 return null; 7838} 7839function isValue(mixed) { 7840 if (mixed === null || typeof mixed === "string" || typeof mixed === "boolean" || typeof mixed === "number" || mixed instanceof ProjectionDefinition || mixed instanceof Color || mixed instanceof Collator || mixed instanceof Formatted || mixed instanceof Padding || mixed instanceof NumberArray || mixed instanceof ColorArray || mixed instanceof VariableAnchorOffsetCollection || mixed instanceof ResolvedImage) return true; 7841 else if (Array.isArray(mixed)) { 7842 for (const item of mixed) if (!isValue(item)) return false; 7843 return true; 7844 } else if (typeof mixed === "object") { 7845 for (const key in mixed) if (!isValue(mixed[key])) return false; 7846 return true; 7847 } else return false; 7848} 7849function typeOf(value) { 7850 if (value === null) return NullType; 7851 else if (typeof value === "string") return StringType; 7852 else if (typeof value === "boolean") return BooleanType; 7853 else if (typeof value === "number") return NumberType; 7854 else if (value instanceof Color) return ColorType; 7855 else if (value instanceof ProjectionDefinition) return ProjectionDefinitionType; 7856 else if (value instanceof Collator) return CollatorType; 7857 else if (value instanceof Formatted) return FormattedType; 7858 else if (value instanceof Padding) return PaddingType; 7859 else if (value instanceof NumberArray) return NumberArrayType; 7860 else if (value instanceof ColorArray) return ColorArrayType; 7861 else if (value instanceof VariableAnchorOffsetCollection) return VariableAnchorOffsetCollectionType; 7862 else if (value instanceof ResolvedImage) return ResolvedImageType; 7863 else if (Array.isArray(value)) { 7864 const length = value.length; 7865 let itemType; 7866 for (const item of value) { 7867 const t = typeOf(item); 7868 if (!itemType) itemType = t; 7869 else if (itemType === t) continue; 7870 else { 7871 itemType = ValueType; 7872 break; 7873 } 7874 } 7875 return array(itemType || ValueType, length); 7876 } else return ObjectType; 7877} 7878function valueToString(value) { 7879 const type = typeof value; 7880 if (value === null) return ""; 7881 else if (type === "string" || type === "number" || type === "boolean") return String(value); 7882 else if (value instanceof Color || value instanceof ProjectionDefinition || value instanceof Formatted || value instanceof Padding || value instanceof NumberArray || value instanceof ColorArray || value instanceof VariableAnchorOffsetCollection || value instanceof ResolvedImage) return value.toString(); 7883 else return JSON.stringify(value); 7884} 7885//#endregion 7886//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/literal.mjs 7887var Literal = class Literal { 7888 constructor(type, value) { 7889 this.type = type; 7890 this.value = value; 7891 } 7892 static parse(args, context) { 7893 if (args.length !== 2) return context.error(`'literal' expression requires exactly one argument, but found ${args.length - 1} instead.`); 7894 if (!isValue(args[1])) return context.error(`invalid value of type "${typeof args[1]}"`); 7895 const value = args[1]; 7896 let type = typeOf(value); 7897 const expected = context.expectedType; 7898 if (type.kind === "array" && type.N === 0 && expected && expected.kind === "array" && (typeof expected.N !== "number" || expected.N === 0)) type = expected; 7899 return new Literal(type, value); 7900 } 7901 evaluate() { 7902 return this.value; 7903 } 7904 eachChild() {} 7905 outputDefined() { 7906 return true; 7907 } 7908}; 7909//#endregion 7910//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/evaluation_context.mjs 7911const geometryTypes = [ 7912 "Unknown", 7913 "Point", 7914 "LineString", 7915 "Polygon" 7916]; 7917var EvaluationContext = class { 7918 constructor() { 7919 this.globals = null; 7920 this.feature = null; 7921 this.featureState = null; 7922 this.formattedSection = null; 7923 this._parseColorCache = /* @__PURE__ */ new Map(); 7924 this.availableImages = null; 7925 this.canonical = null; 7926 } 7927 id() { 7928 return this.feature && "id" in this.feature ? this.feature.id : null; 7929 } 7930 geometryType() { 7931 return this.feature ? typeof this.feature.type === "number" ? geometryTypes[this.feature.type] : this.feature.type : null; 7932 } 7933 geometry() { 7934 return this.feature && "geometry" in this.feature ? this.feature.geometry : null; 7935 } 7936 canonicalID() { 7937 return this.canonical; 7938 } 7939 properties() { 7940 return this.feature && this.feature.properties || {}; 7941 } 7942 parseColor(input) { 7943 let cached = this._parseColorCache.get(input); 7944 if (!cached) { 7945 cached = Color.parse(input); 7946 this._parseColorCache.set(input, cached); 7947 } 7948 return cached; 7949 } 7950}; 7951//#endregion 7952//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/stops.mjs 7953/** 7954* Returns the index of the last stop <= input, or 0 if it doesn't exist. 7955* @private 7956*/ 7957function findStopLessThanOrEqualTo(stops, input, key) { 7958 const lastIndex = stops.length - 1; 7959 let lowerIndex = 0; 7960 let upperIndex = lastIndex; 7961 let currentIndex = 0; 7962 let currentValue, nextValue; 7963 while (lowerIndex <= upperIndex) { 7964 currentIndex = Math.floor((lowerIndex + upperIndex) / 2); 7965 currentValue = stops[currentIndex]; 7966 nextValue = stops[currentIndex + 1]; 7967 if (currentValue <= input) { 7968 if (currentIndex === lastIndex || input < nextValue) return currentIndex; 7969 lowerIndex = currentIndex + 1; 7970 } else if (currentValue > input) upperIndex = currentIndex - 1; 7971 else throw new RuntimeError("Input is not a number.", key); 7972 } 7973 return 0; 7974} 7975//#endregion 7976//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/step.mjs 7977var Step = class Step { 7978 constructor(type, input, stops, key) { 7979 this.type = type; 7980 this.input = input; 7981 this.key = key; 7982 this.labels = []; 7983 this.outputs = []; 7984 for (const [label, expression] of stops) { 7985 this.labels.push(label); 7986 this.outputs.push(expression); 7987 } 7988 } 7989 static parse(args, context) { 7990 if (args.length - 1 < 4) return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`); 7991 if ((args.length - 1) % 2 !== 0) return context.error("Expected an even number of arguments."); 7992 const input = context.parse(args[1], 1, NumberType); 7993 if (!input) return null; 7994 const stops = []; 7995 let outputType = null; 7996 if (context.expectedType && context.expectedType.kind !== "value") outputType = context.expectedType; 7997 for (let i = 1; i < args.length; i += 2) { 7998 const label = i === 1 ? -Infinity : args[i]; 7999 const value = args[i + 1]; 8000 const labelKey = i; 8001 const valueKey = i + 1; 8002 if (typeof label !== "number") return context.error("Input/output pairs for \"step\" expressions must be defined using literal numeric values (not computed expressions) for the input values.", labelKey); 8003 if (stops.length && stops[stops.length - 1][0] >= label) return context.error("Input/output pairs for \"step\" expressions must be arranged with input values in strictly ascending order.", labelKey); 8004 const parsed = context.parse(value, valueKey, outputType); 8005 if (!parsed) return null; 8006 outputType = outputType || parsed.type; 8007 stops.push([label, parsed]); 8008 } 8009 return new Step(outputType, input, stops, context.key); 8010 } 8011 evaluate(ctx) { 8012 const labels = this.labels; 8013 const outputs = this.outputs; 8014 if (labels.length === 1) return outputs[0].evaluate(ctx); 8015 const value = this.input.evaluate(ctx); 8016 if (value <= labels[0]) return outputs[0].evaluate(ctx); 8017 const stopCount = labels.length; 8018 if (value >= labels[stopCount - 1]) return outputs[stopCount - 1].evaluate(ctx); 8019 return outputs[findStopLessThanOrEqualTo(labels, value, this.key)].evaluate(ctx); 8020 } 8021 eachChild(fn) { 8022 fn(this.input); 8023 for (const expression of this.outputs) fn(expression); 8024 } 8025 outputDefined() { 8026 return this.outputs.every((out) => out.outputDefined()); 8027 } 8028}; 8029//#endregion 8030//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/node_modules/@mapbox/unitbezier/index.mjs 8031function unitBezier(p1x, p1y, p2x, p2y) { 8032 const cx = 3 * p1x; 8033 const bx = 3 * (p2x - p1x) - cx; 8034 const ax = 1 - cx - bx; 8035 const cy = 3 * p1y; 8036 const by = 3 * (p2y - p1y) - cy; 8037 const ay = 1 - cy - by; 8038 return function solve(x, epsilon = 1e-6) { 8039 if (x <= 0) return 0; 8040 if (x >= 1) return 1; 8041 let t = x; 8042 for (let i = 0; i < 8; i++) { 8043 const x2 = ((ax * t + bx) * t + cx) * t - x; 8044 if (Math.abs(x2) < epsilon) return ((ay * t + by) * t + cy) * t; 8045 const d2 = (3 * ax * t + 2 * bx) * t + cx; 8046 if (Math.abs(d2) < 1e-6) break; 8047 t -= x2 / d2; 8048 } 8049 let t0 = 0; 8050 let t1 = 1; 8051 t = x; 8052 for (let i = 0; i < 20; i++) { 8053 const x2 = ((ax * t + bx) * t + cx) * t; 8054 if (Math.abs(x2 - x) < epsilon) break; 8055 if (x > x2) t0 = t; 8056 else t1 = t; 8057 t = (t0 + t1) * .5; 8058 } 8059 return ((ay * t + by) * t + cy) * t; 8060 }; 8061} 8062//#endregion 8063//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/interpolate.mjs 8064var Interpolate = class Interpolate { 8065 constructor(type, operator, interpolation, input, stops, key) { 8066 this.type = type; 8067 this.operator = operator; 8068 this.interpolation = interpolation; 8069 this.input = input; 8070 this.key = key; 8071 this.labels = []; 8072 this.outputs = []; 8073 for (const [label, expression] of stops) { 8074 this.labels.push(label); 8075 this.outputs.push(expression); 8076 } 8077 } 8078 static interpolationFactor(interpolation, input, lower, upper) { 8079 let t = 0; 8080 if (interpolation.name === "exponential") t = exponentialInterpolation(input, interpolation.base, lower, upper); 8081 else if (interpolation.name === "linear") t = exponentialInterpolation(input, 1, lower, upper); 8082 else if (interpolation.name === "cubic-bezier") { 8083 const c = interpolation.controlPoints; 8084 t = unitBezier(c[0], c[1], c[2], c[3])(exponentialInterpolation(input, 1, lower, upper)); 8085 } 8086 return t; 8087 } 8088 static parse(args, context) { 8089 let [operator, interpolation, input, ...rest] = args; 8090 if (!Array.isArray(interpolation) || interpolation.length === 0) return context.error("Expected an interpolation type expression.", 1); 8091 if (interpolation[0] === "linear") interpolation = { name: "linear" }; 8092 else if (interpolation[0] === "exponential") { 8093 const base = interpolation[1]; 8094 if (typeof base !== "number") return context.error("Exponential interpolation requires a numeric base.", 1, 1); 8095 interpolation = { 8096 name: "exponential", 8097 base 8098 }; 8099 } else if (interpolation[0] === "cubic-bezier") { 8100 const controlPoints = interpolation.slice(1); 8101 if (controlPoints.length !== 4 || controlPoints.some((t) => typeof t !== "number" || t < 0 || t > 1)) return context.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.", 1); 8102 interpolation = { 8103 name: "cubic-bezier", 8104 controlPoints 8105 }; 8106 } else return context.error(`Unknown interpolation type ${String(interpolation[0])}`, 1, 0); 8107 if (args.length - 1 < 4) return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`); 8108 if ((args.length - 1) % 2 !== 0) return context.error("Expected an even number of arguments."); 8109 input = context.parse(input, 2, NumberType); 8110 if (!input) return null; 8111 const stops = []; 8112 let outputType = null; 8113 if ((operator === "interpolate-hcl" || operator === "interpolate-lab") && context.expectedType != ColorArrayType) outputType = ColorType; 8114 else if (context.expectedType && context.expectedType.kind !== "value") outputType = context.expectedType; 8115 for (let i = 0; i < rest.length; i += 2) { 8116 const label = rest[i]; 8117 const value = rest[i + 1]; 8118 const labelKey = i + 3; 8119 const valueKey = i + 4; 8120 if (typeof label !== "number") return context.error("Input/output pairs for \"interpolate\" expressions must be defined using literal numeric values (not computed expressions) for the input values.", labelKey); 8121 if (stops.length && stops[stops.length - 1][0] >= label) return context.error("Input/output pairs for \"interpolate\" expressions must be arranged with input values in strictly ascending order.", labelKey); 8122 const parsed = context.parse(value, valueKey, outputType); 8123 if (!parsed) return null; 8124 outputType = outputType || parsed.type; 8125 stops.push([label, parsed]); 8126 } 8127 if (!verifyType(outputType, NumberType) && !verifyType(outputType, ProjectionDefinitionType) && !verifyType(outputType, ColorType) && !verifyType(outputType, PaddingType) && !verifyType(outputType, NumberArrayType) && !verifyType(outputType, ColorArrayType) && !verifyType(outputType, VariableAnchorOffsetCollectionType) && !verifyType(outputType, array(NumberType))) return context.error(`Type ${typeToString(outputType)} is not interpolatable.`); 8128 return new Interpolate(outputType, operator, interpolation, input, stops, context.key); 8129 } 8130 evaluate(ctx) { 8131 const labels = this.labels; 8132 const outputs = this.outputs; 8133 if (labels.length === 1) return outputs[0].evaluate(ctx); 8134 const value = this.input.evaluate(ctx); 8135 if (value <= labels[0]) return outputs[0].evaluate(ctx); 8136 const stopCount = labels.length; 8137 if (value >= labels[stopCount - 1]) return outputs[stopCount - 1].evaluate(ctx); 8138 const index = findStopLessThanOrEqualTo(labels, value, this.key); 8139 const lower = labels[index]; 8140 const upper = labels[index + 1]; 8141 const t = Interpolate.interpolationFactor(this.interpolation, value, lower, upper); 8142 const outputLower = outputs[index].evaluate(ctx); 8143 const outputUpper = outputs[index + 1].evaluate(ctx); 8144 switch (this.operator) { 8145 case "interpolate": switch (this.type.kind) { 8146 case "number": return interpolateNumber(outputLower, outputUpper, t); 8147 case "color": return Color.interpolate(outputLower, outputUpper, t); 8148 case "padding": return Padding.interpolate(outputLower, outputUpper, t); 8149 case "colorArray": return ColorArray.interpolate(outputLower, outputUpper, t); 8150 case "numberArray": return NumberArray.interpolate(outputLower, outputUpper, t); 8151 case "variableAnchorOffsetCollection": return VariableAnchorOffsetCollection.interpolate(outputLower, outputUpper, t, this.key); 8152 case "array": return interpolateArray(outputLower, outputUpper, t); 8153 case "projectionDefinition": return ProjectionDefinition.interpolate(outputLower, outputUpper, t); 8154 } 8155 case "interpolate-hcl": switch (this.type.kind) { 8156 case "color": return Color.interpolate(outputLower, outputUpper, t, "hcl"); 8157 case "colorArray": return ColorArray.interpolate(outputLower, outputUpper, t, "hcl"); 8158 } 8159 case "interpolate-lab": switch (this.type.kind) { 8160 case "color": return Color.interpolate(outputLower, outputUpper, t, "lab"); 8161 case "colorArray": return ColorArray.interpolate(outputLower, outputUpper, t, "lab"); 8162 } 8163 } 8164 } 8165 eachChild(fn) { 8166 fn(this.input); 8167 for (const expression of this.outputs) fn(expression); 8168 } 8169 outputDefined() { 8170 return this.outputs.every((out) => out.outputDefined()); 8171 } 8172}; 8173/** 8174* Returns a ratio that can be used to interpolate between exponential function 8175* stops. 8176* How it works: Two consecutive stop values define a (scaled and shifted) exponential function `f(x) = a * base^x + b`, where `base` is the user-specified base, 8177* and `a` and `b` are constants affording sufficient degrees of freedom to fit 8178* the function to the given stops. 8179* 8180* Here's a bit of algebra that lets us compute `f(x)` directly from the stop 8181* values without explicitly solving for `a` and `b`: 8182* 8183* First stop value: `f(x0) = y0 = a * base^x0 + b` 8184* Second stop value: `f(x1) = y1 = a * base^x1 + b` 8185* => `y1 - y0 = a(base^x1 - base^x0)` 8186* => `a = (y1 - y0)/(base^x1 - base^x0)` 8187* 8188* Desired value: `f(x) = y = a * base^x + b` 8189* => `f(x) = y0 + a * (base^x - base^x0)` 8190* 8191* From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a 8192* little algebra: 8193* ``` 8194* a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0) 8195* = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0) 8196* ``` 8197* 8198* If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have 8199* `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as 8200* an interpolation factor between the two stops' output values. 8201* 8202* (Note: a slightly different form for `ratio`, 8203* `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer 8204* expensive `Math.pow()` operations.) 8205* 8206* @private 8207*/ 8208function exponentialInterpolation(input, base, lowerValue, upperValue) { 8209 const difference = upperValue - lowerValue; 8210 const progress = input - lowerValue; 8211 if (difference === 0) return 0; 8212 else if (base === 1) return progress / difference; 8213 else return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1); 8214} 8215const interpolateFactory = { 8216 color: Color.interpolate, 8217 number: interpolateNumber, 8218 padding: Padding.interpolate, 8219 numberArray: NumberArray.interpolate, 8220 colorArray: ColorArray.interpolate, 8221 variableAnchorOffsetCollection: VariableAnchorOffsetCollection.interpolate, 8222 array: interpolateArray 8223}; 8224//#endregion 8225//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/format.mjs 8226var FormatExpression = class FormatExpression { 8227 constructor(sections) { 8228 this.type = FormattedType; 8229 this.sections = sections; 8230 } 8231 static parse(args, context) { 8232 if (args.length < 2) return context.error("Expected at least one argument."); 8233 const firstArg = args[1]; 8234 if (!Array.isArray(firstArg) && typeof firstArg === "object") return context.error("First argument must be an image or text section."); 8235 const sections = []; 8236 let nextTokenMayBeObject = false; 8237 for (let i = 1; i <= args.length - 1; ++i) { 8238 const arg = args[i]; 8239 if (nextTokenMayBeObject && typeof arg === "object" && !Array.isArray(arg)) { 8240 nextTokenMayBeObject = false; 8241 let scale = null; 8242 if (arg["font-scale"]) { 8243 scale = context.parse(arg["font-scale"], 1, NumberType); 8244 if (!scale) return null; 8245 } 8246 let font = null; 8247 if (arg["text-font"]) { 8248 font = context.parse(arg["text-font"], 1, array(StringType)); 8249 if (!font) return null; 8250 } 8251 let textColor = null; 8252 if (arg["text-color"]) { 8253 textColor = context.parse(arg["text-color"], 1, ColorType); 8254 if (!textColor) return null; 8255 } 8256 let verticalAlign = null; 8257 if (arg["vertical-align"]) { 8258 if (typeof arg["vertical-align"] === "string" && !VERTICAL_ALIGN_OPTIONS.includes(arg["vertical-align"])) return context.error(`'vertical-align' must be one of: 'bottom', 'center', 'top' but found '${arg["vertical-align"]}' instead.`); 8259 verticalAlign = context.parse(arg["vertical-align"], 1, StringType); 8260 if (!verticalAlign) return null; 8261 } 8262 const lastExpression = sections[sections.length - 1]; 8263 lastExpression.scale = scale; 8264 lastExpression.font = font; 8265 lastExpression.textColor = textColor; 8266 lastExpression.verticalAlign = verticalAlign; 8267 } else { 8268 const content = context.parse(args[i], 1, ValueType); 8269 if (!content) return null; 8270 const kind = content.type.kind; 8271 if (kind !== "string" && kind !== "value" && kind !== "null" && kind !== "resolvedImage") return context.error("Formatted text type must be 'string', 'value', 'image' or 'null'."); 8272 nextTokenMayBeObject = true; 8273 sections.push({ 8274 content, 8275 scale: null, 8276 font: null, 8277 textColor: null, 8278 verticalAlign: null 8279 }); 8280 } 8281 } 8282 return new FormatExpression(sections); 8283 } 8284 evaluate(ctx) { 8285 const evaluateSection = (section) => { 8286 const evaluatedContent = section.content.evaluate(ctx); 8287 if (typeOf(evaluatedContent) === ResolvedImageType) return new FormattedSection("", evaluatedContent, null, null, null, section.verticalAlign ? section.verticalAlign.evaluate(ctx) : null); 8288 return new FormattedSection(valueToString(evaluatedContent), null, section.scale ? section.scale.evaluate(ctx) : null, section.font ? section.font.evaluate(ctx).join(",") : null, section.textColor ? section.textColor.evaluate(ctx) : null, section.verticalAlign ? section.verticalAlign.evaluate(ctx) : null); 8289 }; 8290 return new Formatted(this.sections.map(evaluateSection)); 8291 } 8292 eachChild(fn) { 8293 for (const section of this.sections) { 8294 fn(section.content); 8295 if (section.scale) fn(section.scale); 8296 if (section.font) fn(section.font); 8297 if (section.textColor) fn(section.textColor); 8298 if (section.verticalAlign) fn(section.verticalAlign); 8299 } 8300 } 8301 outputDefined() { 8302 return false; 8303 } 8304}; 8305//#endregion 8306//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/node_modules/quickselect/index.mjs 8307/** 8308* Rearranges items so that all items in the [left, k] are the smallest. 8309* The k-th element will have the (k - left + 1)-th smallest value in [left, right]. 8310* 8311* @template T 8312* @param {T[]} arr the array to partially sort (in place) 8313* @param {number} k middle index for partial sorting (as defined above) 8314* @param {number} [left=0] left index of the range to sort 8315* @param {number} [right=arr.length-1] right index 8316* @param {(a: T, b: T) => number} [compare = (a, b) => a - b] compare function 8317*/ 8318function quickselect(arr, k, left = 0, right = arr.length - 1, compare = defaultCompare) { 8319 while (right > left) { 8320 if (right - left > 600) { 8321 const n = right - left + 1; 8322 const m = k - left + 1; 8323 const z = Math.log(n); 8324 const s = .5 * Math.exp(2 * z / 3); 8325 const sd = .5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); 8326 quickselect(arr, k, Math.max(left, Math.floor(k - m * s / n + sd)), Math.min(right, Math.floor(k + (n - m) * s / n + sd)), compare); 8327 } 8328 const t = arr[k]; 8329 let i = left; 8330 /** @type {number} */ 8331 let j = right; 8332 swap$2(arr, left, k); 8333 if (compare(arr[right], t) > 0) swap$2(arr, left, right); 8334 while (i < j) { 8335 swap$2(arr, i, j); 8336 i++; 8337 j--; 8338 while (compare(arr[i], t) < 0) i++; 8339 while (compare(arr[j], t) > 0) j--; 8340 } 8341 if (compare(arr[left], t) === 0) swap$2(arr, left, j); 8342 else { 8343 j++; 8344 swap$2(arr, j, right); 8345 } 8346 if (j <= k) left = j + 1; 8347 if (k <= j) right = j - 1; 8348 } 8349} 8350/** 8351* @template T 8352* @param {T[]} arr 8353* @param {number} i 8354* @param {number} j 8355*/ 8356function swap$2(arr, i, j) { 8357 const tmp = arr[i]; 8358 arr[i] = arr[j]; 8359 arr[j] = tmp; 8360} 8361/** 8362* @template T 8363* @param {T} a 8364* @param {T} b 8365* @returns {number} 8366*/ 8367function defaultCompare(a, b) { 8368 return a < b ? -1 : a > b ? 1 : 0; 8369} 8370//#endregion 8371//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/util/classify_rings.mjs 8372/** 8373* Classifies an array of rings into polygons with outer rings and holes 8374* @param rings - the rings to classify 8375* @param maxRings - the maximum number of rings to include in a polygon, use 0 to include all rings 8376* @returns an array of polygons with internal rings as holes 8377*/ 8378function classifyRings$1(rings, maxRings) { 8379 if (rings.length <= 1) return [rings]; 8380 const polygons = []; 8381 let polygon; 8382 let ccw; 8383 for (const ring of rings) { 8384 const area = calculateSignedArea(ring); 8385 if (area === 0) continue; 8386 ring.area = Math.abs(area); 8387 if (ccw === void 0) ccw = area < 0; 8388 if (ccw === area < 0) { 8389 if (polygon) polygons.push(polygon); 8390 polygon = [ring]; 8391 } else polygon.push(ring); 8392 } 8393 if (polygon) polygons.push(polygon); 8394 if (maxRings > 1) for (let j = 0; j < polygons.length; j++) { 8395 if (polygons[j].length <= maxRings) continue; 8396 quickselect(polygons[j], maxRings, 1, polygons[j].length - 1, compareAreas); 8397 polygons[j] = polygons[j].slice(0, maxRings); 8398 } 8399 return polygons; 8400} 8401function compareAreas(a, b) { 8402 return b.area - a.area; 8403} 8404/** 8405* Returns the signed area for the polygon ring. Positive areas are exterior rings and 8406* have a clockwise winding. Negative areas are interior rings and have a counter clockwise 8407* ordering. 8408* 8409* @param ring - Exterior or interior ring 8410* @returns Signed area 8411*/ 8412function calculateSignedArea(ring) { 8413 let sum = 0; 8414 for (let i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) { 8415 p1 = ring[i]; 8416 p2 = ring[j]; 8417 sum += (p2.x - p1.x) * (p1.y + p2.y); 8418 } 8419 return sum; 8420} 8421//#endregion 8422//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/assertion.mjs 8423const types$1 = { 8424 string: StringType, 8425 number: NumberType, 8426 boolean: BooleanType, 8427 object: ObjectType 8428}; 8429var Assertion = class Assertion { 8430 constructor(type, args, key) { 8431 this.type = type; 8432 this.args = args; 8433 this.key = key; 8434 } 8435 static parse(args, context) { 8436 if (args.length < 2) return context.error("Expected at least one argument."); 8437 let i = 1; 8438 let type; 8439 const name = args[0]; 8440 if (name === "array") { 8441 let itemType; 8442 if (args.length > 2) { 8443 const type = args[1]; 8444 if (typeof type !== "string" || !(type in types$1) || type === "object") return context.error("The item type argument of \"array\" must be one of string, number, boolean", 1); 8445 itemType = types$1[type]; 8446 i++; 8447 } else itemType = ValueType; 8448 let N; 8449 if (args.length > 3) { 8450 if (args[2] !== null && (typeof args[2] !== "number" || args[2] < 0 || args[2] !== Math.floor(args[2]))) return context.error("The length argument to \"array\" must be a positive integer literal", 2); 8451 N = args[2]; 8452 i++; 8453 } 8454 type = array(itemType, N); 8455 } else { 8456 if (!types$1[name]) throw new Error(`Types doesn't contain name = ${name}`); 8457 type = types$1[name]; 8458 } 8459 const parsed = []; 8460 for (; i < args.length; i++) { 8461 const input = context.parse(args[i], i, ValueType); 8462 if (!input) return null; 8463 parsed.push(input); 8464 } 8465 return new Assertion(type, parsed, context.key); 8466 } 8467 evaluate(ctx) { 8468 for (let i = 0; i < this.args.length; i++) { 8469 const value = this.args[i].evaluate(ctx); 8470 if (!checkSubtype(this.type, typeOf(value))) return value; 8471 else if (i === this.args.length - 1) throw new RuntimeError(`Expected value to be of type ${typeToString(this.type)}, but found ${typeToString(typeOf(value))} instead.`, this.key); 8472 } 8473 throw new Error(); 8474 } 8475 eachChild(fn) { 8476 this.args.forEach(fn); 8477 } 8478 outputDefined() { 8479 return this.args.every((arg) => arg.outputDefined()); 8480 } 8481}; 8482//#endregion 8483//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/coercion.mjs 8484const types = { 8485 "to-boolean": BooleanType, 8486 "to-color": ColorType, 8487 "to-number": NumberType, 8488 "to-string": StringType 8489}; 8490/** 8491* Special form for error-coalescing coercion expressions "to-number", 8492* "to-color". Since these coercions can fail at runtime, they accept multiple 8493* arguments, only evaluating one at a time until one succeeds. 8494* 8495* @private 8496*/ 8497var Coercion = class Coercion { 8498 constructor(type, args, key) { 8499 this.type = type; 8500 this.args = args; 8501 this.key = key; 8502 } 8503 static parse(args, context) { 8504 if (args.length < 2) return context.error("Expected at least one argument."); 8505 const name = args[0]; 8506 if (!types[name]) throw new Error(`Can't parse ${name} as it is not part of the known types`); 8507 if ((name === "to-boolean" || name === "to-string") && args.length !== 2) return context.error("Expected one argument."); 8508 const type = types[name]; 8509 const parsed = []; 8510 for (let i = 1; i < args.length; i++) { 8511 const input = context.parse(args[i], i, ValueType); 8512 if (!input) return null; 8513 parsed.push(input); 8514 } 8515 return new Coercion(type, parsed, context.key); 8516 } 8517 evaluate(ctx) { 8518 switch (this.type.kind) { 8519 case "boolean": return Boolean(this.args[0].evaluate(ctx)); 8520 case "color": { 8521 let input; 8522 let error; 8523 for (const arg of this.args) { 8524 input = arg.evaluate(ctx); 8525 error = null; 8526 if (input instanceof Color) return input; 8527 else if (typeof input === "string") { 8528 const c = ctx.parseColor(input); 8529 if (c) return c; 8530 } else if (Array.isArray(input)) { 8531 if (input.length < 3 || input.length > 4) error = `Invalid rgba value ${JSON.stringify(input)}: expected an array containing either three or four numeric values.`; 8532 else error = validateRGBA(input[0], input[1], input[2], input[3]); 8533 if (!error) return new Color(input[0] / 255, input[1] / 255, input[2] / 255, input[3]); 8534 } 8535 } 8536 throw new RuntimeError(error || `Could not parse color from value '${typeof input === "string" ? input : JSON.stringify(input)}'`, this.key); 8537 } 8538 case "padding": { 8539 let input; 8540 for (const arg of this.args) { 8541 input = arg.evaluate(ctx); 8542 const pad = Padding.parse(input); 8543 if (pad) return pad; 8544 } 8545 throw new RuntimeError(`Could not parse padding from value '${typeof input === "string" ? input : JSON.stringify(input)}'`, this.key); 8546 } 8547 case "numberArray": { 8548 let input; 8549 for (const arg of this.args) { 8550 input = arg.evaluate(ctx); 8551 const val = NumberArray.parse(input); 8552 if (val) return val; 8553 } 8554 throw new RuntimeError(`Could not parse numberArray from value '${typeof input === "string" ? input : JSON.stringify(input)}'`, this.key); 8555 } 8556 case "colorArray": { 8557 let input; 8558 for (const arg of this.args) { 8559 input = arg.evaluate(ctx); 8560 const val = ColorArray.parse(input); 8561 if (val) return val; 8562 } 8563 throw new RuntimeError(`Could not parse colorArray from value '${typeof input === "string" ? input : JSON.stringify(input)}'`, this.key); 8564 } 8565 case "variableAnchorOffsetCollection": { 8566 let input; 8567 for (const arg of this.args) { 8568 input = arg.evaluate(ctx); 8569 const coll = VariableAnchorOffsetCollection.parse(input); 8570 if (coll) return coll; 8571 } 8572 throw new RuntimeError(`Could not parse variableAnchorOffsetCollection from value '${typeof input === "string" ? input : JSON.stringify(input)}'`, this.key); 8573 } 8574 case "number": { 8575 let value = null; 8576 for (const arg of this.args) { 8577 value = arg.evaluate(ctx); 8578 if (value === null) return 0; 8579 const num = Number(value); 8580 if (isNaN(num)) continue; 8581 return num; 8582 } 8583 throw new RuntimeError(`Could not convert ${JSON.stringify(value)} to number.`, this.key); 8584 } 8585 case "formatted": return Formatted.fromString(valueToString(this.args[0].evaluate(ctx))); 8586 case "resolvedImage": return ResolvedImage.fromString(valueToString(this.args[0].evaluate(ctx))); 8587 case "projectionDefinition": { 8588 const input = this.args[0].evaluate(ctx); 8589 if (ProjectionDefinition.parse(input)) return input; 8590 throw new RuntimeError(`Could not parse projectionDefinition from value '${typeof input === "string" ? input : JSON.stringify(input)}'`, this.key); 8591 } 8592 default: return valueToString(this.args[0].evaluate(ctx)); 8593 } 8594 } 8595 eachChild(fn) { 8596 this.args.forEach(fn); 8597 } 8598 outputDefined() { 8599 return this.args.every((arg) => arg.outputDefined()); 8600 } 8601}; 8602//#endregion 8603//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/let.mjs 8604var Let = class Let { 8605 constructor(bindings, result) { 8606 this.type = result.type; 8607 this.bindings = [].concat(bindings); 8608 this.result = result; 8609 } 8610 evaluate(ctx) { 8611 return this.result.evaluate(ctx); 8612 } 8613 eachChild(fn) { 8614 for (const binding of this.bindings) fn(binding[1]); 8615 fn(this.result); 8616 } 8617 static parse(args, context) { 8618 if (args.length < 4) return context.error(`Expected at least 3 arguments, but found ${args.length - 1} instead.`); 8619 const bindings = []; 8620 for (let i = 1; i < args.length - 1; i += 2) { 8621 const name = args[i]; 8622 if (typeof name !== "string") return context.error(`Expected string, but found ${typeof name} instead.`, i); 8623 if (/[^a-zA-Z0-9_]/.test(name)) return context.error("Variable names must contain only alphanumeric characters or '_'.", i); 8624 const value = context.parse(args[i + 1], i + 1); 8625 if (!value) return null; 8626 bindings.push([name, value]); 8627 } 8628 const result = context.parse(args[args.length - 1], args.length - 1, context.expectedType, bindings); 8629 if (!result) return null; 8630 return new Let(bindings, result); 8631 } 8632 outputDefined() { 8633 return this.result.outputDefined(); 8634 } 8635}; 8636//#endregion 8637//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/var.mjs 8638var Var = class Var { 8639 constructor(name, boundExpression) { 8640 this.type = boundExpression.type; 8641 this.name = name; 8642 this.boundExpression = boundExpression; 8643 } 8644 static parse(args, context) { 8645 if (args.length !== 2 || typeof args[1] !== "string") return context.error("'var' expression requires exactly one string literal argument."); 8646 const name = args[1]; 8647 if (!context.scope.has(name)) return context.error(`Unknown variable "${name}". Make sure "${name}" has been bound in an enclosing "let" expression before using it.`, 1); 8648 return new Var(name, context.scope.get(name)); 8649 } 8650 evaluate(ctx) { 8651 return this.boundExpression.evaluate(ctx); 8652 } 8653 eachChild() {} 8654 outputDefined() { 8655 return false; 8656 } 8657}; 8658//#endregion 8659//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/at.mjs 8660var At = class At { 8661 constructor(type, index, input, key) { 8662 this.type = type; 8663 this.index = index; 8664 this.input = input; 8665 this.key = key; 8666 } 8667 static parse(args, context) { 8668 if (args.length !== 3) return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`); 8669 const index = context.parse(args[1], 1, NumberType); 8670 const input = context.parse(args[2], 2, array(context.expectedType || ValueType)); 8671 if (!index || !input) return null; 8672 const t = input.type; 8673 return new At(t.itemType, index, input, context.key); 8674 } 8675 evaluate(ctx) { 8676 const index = this.index.evaluate(ctx); 8677 const array = this.input.evaluate(ctx); 8678 if (index < 0) throw new RuntimeError(`Array index out of bounds: ${index} < 0.`, this.key); 8679 if (index >= array.length) throw new RuntimeError(`Array index out of bounds: ${index} > ${array.length - 1}.`, this.key); 8680 if (index !== Math.floor(index)) throw new RuntimeError(`Array index must be an integer, but found ${index} instead.`, this.key); 8681 return array[index]; 8682 } 8683 eachChild(fn) { 8684 fn(this.index); 8685 fn(this.input); 8686 } 8687 outputDefined() { 8688 return false; 8689 } 8690}; 8691//#endregion 8692//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/in.mjs 8693var In = class In { 8694 constructor(needle, haystack, key) { 8695 this.needle = needle; 8696 this.haystack = haystack; 8697 this.key = key; 8698 this.type = BooleanType; 8699 } 8700 static parse(args, context) { 8701 if (args.length !== 3) return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`); 8702 const needle = context.parse(args[1], 1, ValueType); 8703 const haystack = context.parse(args[2], 2, ValueType); 8704 if (!needle || !haystack) return null; 8705 if (!isValidType(needle.type, [ 8706 BooleanType, 8707 StringType, 8708 NumberType, 8709 NullType, 8710 ValueType 8711 ])) return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${typeToString(needle.type)} instead`); 8712 return new In(needle, haystack, context.key); 8713 } 8714 evaluate(ctx) { 8715 const needle = this.needle.evaluate(ctx); 8716 const haystack = this.haystack.evaluate(ctx); 8717 if (!haystack) return false; 8718 if (!isValidNativeType(needle, [ 8719 "boolean", 8720 "string", 8721 "number", 8722 "null" 8723 ])) throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${typeToString(typeOf(needle))} instead.`, this.key); 8724 if (!isValidNativeType(haystack, ["string", "array"])) throw new RuntimeError(`Expected second argument to be of type array or string, but found ${typeToString(typeOf(haystack))} instead.`, this.key); 8725 return haystack.indexOf(needle) >= 0; 8726 } 8727 eachChild(fn) { 8728 fn(this.needle); 8729 fn(this.haystack); 8730 } 8731 outputDefined() { 8732 return true; 8733 } 8734}; 8735//#endregion 8736//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/index_of.mjs 8737var IndexOf = class IndexOf { 8738 constructor(needle, haystack, key, fromIndex) { 8739 this.needle = needle; 8740 this.haystack = haystack; 8741 this.key = key; 8742 this.fromIndex = fromIndex; 8743 this.type = NumberType; 8744 } 8745 static parse(args, context) { 8746 if (args.length <= 2 || args.length >= 5) return context.error(`Expected 2 or 3 arguments, but found ${args.length - 1} instead.`); 8747 const needle = context.parse(args[1], 1, ValueType); 8748 const haystack = context.parse(args[2], 2, ValueType); 8749 if (!needle || !haystack) return null; 8750 if (!isValidType(needle.type, [ 8751 BooleanType, 8752 StringType, 8753 NumberType, 8754 NullType, 8755 ValueType 8756 ])) return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${typeToString(needle.type)} instead`); 8757 if (args.length === 4) { 8758 const fromIndex = context.parse(args[3], 3, NumberType); 8759 if (!fromIndex) return null; 8760 return new IndexOf(needle, haystack, context.key, fromIndex); 8761 } else return new IndexOf(needle, haystack, context.key); 8762 } 8763 evaluate(ctx) { 8764 const needle = this.needle.evaluate(ctx); 8765 const haystack = this.haystack.evaluate(ctx); 8766 if (!isValidNativeType(needle, [ 8767 "boolean", 8768 "string", 8769 "number", 8770 "null" 8771 ])) throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${typeToString(typeOf(needle))} instead.`, this.key); 8772 let fromIndex; 8773 if (this.fromIndex) fromIndex = this.fromIndex.evaluate(ctx); 8774 if (isValidNativeType(haystack, ["string"])) { 8775 const rawIndex = haystack.indexOf(needle, fromIndex); 8776 if (rawIndex === -1) return -1; 8777 else return [...haystack.slice(0, rawIndex)].length; 8778 } else if (isValidNativeType(haystack, ["array"])) return haystack.indexOf(needle, fromIndex); 8779 else throw new RuntimeError(`Expected second argument to be of type array or string, but found ${typeToString(typeOf(haystack))} instead.`, this.key); 8780 } 8781 eachChild(fn) { 8782 fn(this.needle); 8783 fn(this.haystack); 8784 if (this.fromIndex) fn(this.fromIndex); 8785 } 8786 outputDefined() { 8787 return false; 8788 } 8789}; 8790//#endregion 8791//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/match.mjs 8792var Match = class Match { 8793 constructor(inputType, outputType, input, cases, outputs, otherwise) { 8794 this.inputType = inputType; 8795 this.type = outputType; 8796 this.input = input; 8797 this.cases = cases; 8798 this.outputs = outputs; 8799 this.otherwise = otherwise; 8800 } 8801 static parse(args, context) { 8802 if (args.length < 5) return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`); 8803 if (args.length % 2 !== 1) return context.error("Expected an even number of arguments."); 8804 let inputType; 8805 let outputType; 8806 if (context.expectedType && context.expectedType.kind !== "value") outputType = context.expectedType; 8807 const cases = {}; 8808 const outputs = []; 8809 for (let i = 2; i < args.length - 1; i += 2) { 8810 let labels = args[i]; 8811 const value = args[i + 1]; 8812 if (!Array.isArray(labels)) labels = [labels]; 8813 const labelContext = context.concat(i); 8814 if (labels.length === 0) return labelContext.error("Expected at least one branch label."); 8815 for (const label of labels) { 8816 if (typeof label !== "number" && typeof label !== "string") return labelContext.error("Branch labels must be numbers or strings."); 8817 else if (typeof label === "number" && Math.abs(label) > Number.MAX_SAFE_INTEGER) return labelContext.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`); 8818 else if (typeof label === "number" && Math.floor(label) !== label) return labelContext.error("Numeric branch labels must be integer values."); 8819 else if (!inputType) inputType = typeOf(label); 8820 else if (labelContext.checkSubtype(inputType, typeOf(label))) return null; 8821 if (typeof cases[String(label)] !== "undefined") return labelContext.error("Branch labels must be unique."); 8822 cases[String(label)] = outputs.length; 8823 } 8824 const result = context.parse(value, i, outputType); 8825 if (!result) return null; 8826 outputType = outputType || result.type; 8827 outputs.push(result); 8828 } 8829 const input = context.parse(args[1], 1, ValueType); 8830 if (!input) return null; 8831 const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType); 8832 if (!otherwise) return null; 8833 if (input.type.kind !== "value" && context.concat(1).checkSubtype(inputType, input.type)) return null; 8834 return new Match(inputType, outputType, input, cases, outputs, otherwise); 8835 } 8836 evaluate(ctx) { 8837 const input = this.input.evaluate(ctx); 8838 return (typeOf(input) === this.inputType && this.outputs[this.cases[input]] || this.otherwise).evaluate(ctx); 8839 } 8840 eachChild(fn) { 8841 fn(this.input); 8842 this.outputs.forEach(fn); 8843 fn(this.otherwise); 8844 } 8845 outputDefined() { 8846 return this.outputs.every((out) => out.outputDefined()) && this.otherwise.outputDefined(); 8847 } 8848}; 8849//#endregion 8850//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/case.mjs 8851var Case = class Case { 8852 constructor(type, branches, otherwise) { 8853 this.type = type; 8854 this.branches = branches; 8855 this.otherwise = otherwise; 8856 } 8857 static parse(args, context) { 8858 if (args.length < 4) return context.error(`Expected at least 3 arguments, but found only ${args.length - 1}.`); 8859 if (args.length % 2 !== 0) return context.error("Expected an odd number of arguments."); 8860 let outputType; 8861 if (context.expectedType && context.expectedType.kind !== "value") outputType = context.expectedType; 8862 const branches = []; 8863 for (let i = 1; i < args.length - 1; i += 2) { 8864 const test = context.parse(args[i], i, BooleanType); 8865 if (!test) return null; 8866 const result = context.parse(args[i + 1], i + 1, outputType); 8867 if (!result) return null; 8868 branches.push([test, result]); 8869 outputType = outputType || result.type; 8870 } 8871 const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType); 8872 if (!otherwise) return null; 8873 if (!outputType) throw new Error("Can't infer output type"); 8874 return new Case(outputType, branches, otherwise); 8875 } 8876 evaluate(ctx) { 8877 for (const [test, expression] of this.branches) if (test.evaluate(ctx)) return expression.evaluate(ctx); 8878 return this.otherwise.evaluate(ctx); 8879 } 8880 eachChild(fn) { 8881 for (const [test, expression] of this.branches) { 8882 fn(test); 8883 fn(expression); 8884 } 8885 fn(this.otherwise); 8886 } 8887 outputDefined() { 8888 return this.branches.every(([_, out]) => out.outputDefined()) && this.otherwise.outputDefined(); 8889 } 8890}; 8891//#endregion 8892//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/slice.mjs 8893var Slice = class Slice { 8894 constructor(type, input, beginIndex, key, endIndex) { 8895 this.type = type; 8896 this.input = input; 8897 this.beginIndex = beginIndex; 8898 this.key = key; 8899 this.endIndex = endIndex; 8900 } 8901 static parse(args, context) { 8902 if (args.length <= 2 || args.length >= 5) return context.error(`Expected 2 or 3 arguments, but found ${args.length - 1} instead.`); 8903 const input = context.parse(args[1], 1, ValueType); 8904 const beginIndex = context.parse(args[2], 2, NumberType); 8905 if (!input || !beginIndex) return null; 8906 if (!isValidType(input.type, [ 8907 array(ValueType), 8908 StringType, 8909 ValueType 8910 ])) return context.error(`Expected first argument to be of type array or string, but found ${typeToString(input.type)} instead`); 8911 if (args.length === 4) { 8912 const endIndex = context.parse(args[3], 3, NumberType); 8913 if (!endIndex) return null; 8914 return new Slice(input.type, input, beginIndex, context.key, endIndex); 8915 } else return new Slice(input.type, input, beginIndex, context.key); 8916 } 8917 evaluate(ctx) { 8918 const input = this.input.evaluate(ctx); 8919 const beginIndex = this.beginIndex.evaluate(ctx); 8920 let endIndex; 8921 if (this.endIndex) endIndex = this.endIndex.evaluate(ctx); 8922 if (isValidNativeType(input, ["string"])) return [...input].slice(beginIndex, endIndex).join(""); 8923 else if (isValidNativeType(input, ["array"])) return input.slice(beginIndex, endIndex); 8924 else throw new RuntimeError(`Expected first argument to be of type array or string, but found ${typeToString(typeOf(input))} instead.`, this.key); 8925 } 8926 eachChild(fn) { 8927 fn(this.input); 8928 fn(this.beginIndex); 8929 if (this.endIndex) fn(this.endIndex); 8930 } 8931 outputDefined() { 8932 return false; 8933 } 8934}; 8935//#endregion 8936//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/coalesce.mjs 8937var Coalesce = class Coalesce { 8938 constructor(type, args) { 8939 this.type = type; 8940 this.args = args; 8941 } 8942 static parse(args, context) { 8943 if (args.length < 2) return context.error("Expected at least one argument."); 8944 let outputType = null; 8945 const expectedType = context.expectedType; 8946 if (expectedType && expectedType.kind !== "value") outputType = expectedType; 8947 const parsedArgs = []; 8948 for (const arg of args.slice(1)) { 8949 const parsed = context.parse(arg, 1 + parsedArgs.length, outputType, void 0, { typeAnnotation: "omit" }); 8950 if (!parsed) return null; 8951 outputType = outputType || parsed.type; 8952 parsedArgs.push(parsed); 8953 } 8954 if (!outputType) throw new Error("No output type"); 8955 return expectedType && parsedArgs.some((arg) => checkSubtype(expectedType, arg.type)) ? new Coalesce(ValueType, parsedArgs) : new Coalesce(outputType, parsedArgs); 8956 } 8957 evaluate(ctx) { 8958 let result = null; 8959 let argCount = 0; 8960 let requestedImageName; 8961 for (const arg of this.args) { 8962 argCount++; 8963 result = arg.evaluate(ctx); 8964 if (result && result instanceof ResolvedImage && !result.available) { 8965 if (!requestedImageName) requestedImageName = result.name; 8966 result = null; 8967 if (argCount === this.args.length) result = requestedImageName; 8968 } 8969 if (result !== null) break; 8970 } 8971 return result; 8972 } 8973 eachChild(fn) { 8974 this.args.forEach(fn); 8975 } 8976 outputDefined() { 8977 return this.args.every((arg) => arg.outputDefined()); 8978 } 8979}; 8980//#endregion 8981//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/comparison.mjs 8982function isComparableType(op, type) { 8983 if (op === "==" || op === "!=") return type.kind === "boolean" || type.kind === "string" || type.kind === "number" || type.kind === "null" || type.kind === "value"; 8984 else return type.kind === "string" || type.kind === "number" || type.kind === "value"; 8985} 8986function eq(ctx, a, b) { 8987 return a === b; 8988} 8989function neq(ctx, a, b) { 8990 return a !== b; 8991} 8992function lt(ctx, a, b) { 8993 return a < b; 8994} 8995function gt(ctx, a, b) { 8996 return a > b; 8997} 8998function lteq(ctx, a, b) { 8999 return a <= b; 9000} 9001function gteq(ctx, a, b) { 9002 return a >= b; 9003} 9004function eqCollate(ctx, a, b, c) { 9005 return c.compare(a, b) === 0; 9006} 9007function neqCollate(ctx, a, b, c) { 9008 return !eqCollate(ctx, a, b, c); 9009} 9010function ltCollate(ctx, a, b, c) { 9011 return c.compare(a, b) < 0; 9012} 9013function gtCollate(ctx, a, b, c) { 9014 return c.compare(a, b) > 0; 9015} 9016function lteqCollate(ctx, a, b, c) { 9017 return c.compare(a, b) <= 0; 9018} 9019function gteqCollate(ctx, a, b, c) { 9020 return c.compare(a, b) >= 0; 9021} 9022/** 9023* Special form for comparison operators, implementing the signatures: 9024* - (T, T, ?Collator) => boolean 9025* - (T, value, ?Collator) => boolean 9026* - (value, T, ?Collator) => boolean 9027* 9028* For inequalities, T must be either value, string, or number. For ==/!=, it 9029* can also be boolean or null. 9030* 9031* Equality semantics are equivalent to Javascript's strict equality (===/!==) 9032* -- i.e., when the arguments' types don't match, == evaluates to false, != to 9033* true. 9034* 9035* When types don't match in an ordering comparison, a runtime error is thrown. 9036* 9037* @private 9038*/ 9039function makeComparison(op, compareBasic, compareWithCollator) { 9040 const isOrderComparison = op !== "==" && op !== "!="; 9041 return class Comparison { 9042 constructor(lhs, rhs, key, collator) { 9043 this.lhs = lhs; 9044 this.rhs = rhs; 9045 this.key = key; 9046 this.collator = collator; 9047 this.type = BooleanType; 9048 this.hasUntypedArgument = lhs.type.kind === "value" || rhs.type.kind === "value"; 9049 } 9050 static parse(args, context) { 9051 if (args.length !== 3 && args.length !== 4) return context.error("Expected two or three arguments."); 9052 const op = args[0]; 9053 let lhs = context.parse(args[1], 1, ValueType); 9054 if (!lhs) return null; 9055 if (!isComparableType(op, lhs.type)) return context.concat(1).error(`"${op}" comparisons are not supported for type '${typeToString(lhs.type)}'.`); 9056 let rhs = context.parse(args[2], 2, ValueType); 9057 if (!rhs) return null; 9058 if (!isComparableType(op, rhs.type)) return context.concat(2).error(`"${op}" comparisons are not supported for type '${typeToString(rhs.type)}'.`); 9059 if (lhs.type.kind !== rhs.type.kind && lhs.type.kind !== "value" && rhs.type.kind !== "value") return context.error(`Cannot compare types '${typeToString(lhs.type)}' and '${typeToString(rhs.type)}'.`); 9060 if (isOrderComparison) { 9061 if (lhs.type.kind === "value" && rhs.type.kind !== "value") lhs = new Assertion(rhs.type, [lhs], context.key); 9062 else if (lhs.type.kind !== "value" && rhs.type.kind === "value") rhs = new Assertion(lhs.type, [rhs], context.key); 9063 } 9064 let collator = null; 9065 if (args.length === 4) { 9066 if (lhs.type.kind !== "string" && rhs.type.kind !== "string" && lhs.type.kind !== "value" && rhs.type.kind !== "value") return context.error("Cannot use collator to compare non-string types."); 9067 collator = context.parse(args[3], 3, CollatorType); 9068 if (!collator) return null; 9069 } 9070 return new Comparison(lhs, rhs, context.key, collator); 9071 } 9072 evaluate(ctx) { 9073 const lhs = this.lhs.evaluate(ctx); 9074 const rhs = this.rhs.evaluate(ctx); 9075 if (isOrderComparison && this.hasUntypedArgument) { 9076 const lt = typeOf(lhs); 9077 const rt = typeOf(rhs); 9078 if (lt.kind !== rt.kind || !(lt.kind === "string" || lt.kind === "number")) throw new RuntimeError(`Expected arguments for "${op}" to be (string, string) or (number, number), but found (${lt.kind}, ${rt.kind}) instead.`, this.key); 9079 } 9080 if (this.collator && !isOrderComparison && this.hasUntypedArgument) { 9081 const lt = typeOf(lhs); 9082 const rt = typeOf(rhs); 9083 if (lt.kind !== "string" || rt.kind !== "string") return compareBasic(ctx, lhs, rhs); 9084 } 9085 return this.collator ? compareWithCollator(ctx, lhs, rhs, this.collator.evaluate(ctx)) : compareBasic(ctx, lhs, rhs); 9086 } 9087 eachChild(fn) { 9088 fn(this.lhs); 9089 fn(this.rhs); 9090 if (this.collator) fn(this.collator); 9091 } 9092 outputDefined() { 9093 return true; 9094 } 9095 }; 9096} 9097const Equals = makeComparison("==", eq, eqCollate); 9098const NotEquals = makeComparison("!=", neq, neqCollate); 9099const LessThan = makeComparison("<", lt, ltCollate); 9100const GreaterThan = makeComparison(">", gt, gtCollate); 9101const LessThanOrEqual = makeComparison("<=", lteq, lteqCollate); 9102const GreaterThanOrEqual = makeComparison(">=", gteq, gteqCollate); 9103//#endregion 9104//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/collator.mjs 9105var CollatorExpression = class CollatorExpression { 9106 constructor(caseSensitive, diacriticSensitive, locale) { 9107 this.type = CollatorType; 9108 this.locale = locale; 9109 this.caseSensitive = caseSensitive; 9110 this.diacriticSensitive = diacriticSensitive; 9111 } 9112 static parse(args, context) { 9113 if (args.length !== 2) return context.error("Expected one argument."); 9114 const options = args[1]; 9115 if (typeof options !== "object" || Array.isArray(options)) return context.error("Collator options argument must be an object."); 9116 const caseSensitive = context.parse(options["case-sensitive"] === void 0 ? false : options["case-sensitive"], 1, BooleanType); 9117 if (!caseSensitive) return null; 9118 const diacriticSensitive = context.parse(options["diacritic-sensitive"] === void 0 ? false : options["diacritic-sensitive"], 1, BooleanType); 9119 if (!diacriticSensitive) return null; 9120 let locale = null; 9121 if (options["locale"]) { 9122 locale = context.parse(options["locale"], 1, StringType); 9123 if (!locale) return null; 9124 } 9125 return new CollatorExpression(caseSensitive, diacriticSensitive, locale); 9126 } 9127 evaluate(ctx) { 9128 return new Collator(this.caseSensitive.evaluate(ctx), this.diacriticSensitive.evaluate(ctx), this.locale ? this.locale.evaluate(ctx) : null); 9129 } 9130 eachChild(fn) { 9131 fn(this.caseSensitive); 9132 fn(this.diacriticSensitive); 9133 if (this.locale) fn(this.locale); 9134 } 9135 outputDefined() { 9136 return false; 9137 } 9138}; 9139//#endregion 9140//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/number_format.mjs 9141var NumberFormat = class NumberFormat { 9142 constructor(number, locale, currency, unit, minFractionDigits, maxFractionDigits) { 9143 this.type = StringType; 9144 this.number = number; 9145 this.locale = locale; 9146 this.currency = currency; 9147 this.unit = unit; 9148 this.minFractionDigits = minFractionDigits; 9149 this.maxFractionDigits = maxFractionDigits; 9150 } 9151 static parse(args, context) { 9152 if (args.length !== 3) return context.error("Expected two arguments."); 9153 const number = context.parse(args[1], 1, NumberType); 9154 if (!number) return null; 9155 const options = args[2]; 9156 if (typeof options !== "object" || Array.isArray(options)) return context.error("NumberFormat options argument must be an object."); 9157 let locale = null; 9158 if (options["locale"]) { 9159 locale = context.parse(options["locale"], 1, StringType); 9160 if (!locale) return null; 9161 } 9162 let currency = null; 9163 if (options["currency"]) { 9164 currency = context.parse(options["currency"], 1, StringType); 9165 if (!currency) return null; 9166 } 9167 let unit = null; 9168 if (options["unit"]) { 9169 unit = context.parse(options["unit"], 1, StringType); 9170 if (!unit) return null; 9171 } 9172 if (currency && unit) return context.error("NumberFormat options `currency` and `unit` are mutually exclusive"); 9173 let minFractionDigits = null; 9174 if (options["min-fraction-digits"]) { 9175 minFractionDigits = context.parse(options["min-fraction-digits"], 1, NumberType); 9176 if (!minFractionDigits) return null; 9177 } 9178 let maxFractionDigits = null; 9179 if (options["max-fraction-digits"]) { 9180 maxFractionDigits = context.parse(options["max-fraction-digits"], 1, NumberType); 9181 if (!maxFractionDigits) return null; 9182 } 9183 return new NumberFormat(number, locale, currency, unit, minFractionDigits, maxFractionDigits); 9184 } 9185 evaluate(ctx) { 9186 return new Intl.NumberFormat(this.locale ? this.locale.evaluate(ctx) : [], { 9187 style: this.currency ? "currency" : this.unit ? "unit" : "decimal", 9188 currency: this.currency ? this.currency.evaluate(ctx) : void 0, 9189 unit: this.unit ? this.unit.evaluate(ctx) : void 0, 9190 minimumFractionDigits: this.minFractionDigits ? this.minFractionDigits.evaluate(ctx) : void 0, 9191 maximumFractionDigits: this.maxFractionDigits ? this.maxFractionDigits.evaluate(ctx) : void 0 9192 }).format(this.number.evaluate(ctx)); 9193 } 9194 eachChild(fn) { 9195 fn(this.number); 9196 if (this.locale) fn(this.locale); 9197 if (this.currency) fn(this.currency); 9198 if (this.unit) fn(this.unit); 9199 if (this.minFractionDigits) fn(this.minFractionDigits); 9200 if (this.maxFractionDigits) fn(this.maxFractionDigits); 9201 } 9202 outputDefined() { 9203 return false; 9204 } 9205}; 9206//#endregion 9207//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/image.mjs 9208var ImageExpression = class ImageExpression { 9209 constructor(input) { 9210 this.type = ResolvedImageType; 9211 this.input = input; 9212 } 9213 static parse(args, context) { 9214 if (args.length !== 2) return context.error("Expected two arguments."); 9215 const name = context.parse(args[1], 1, StringType); 9216 if (!name) return context.error("No image name provided."); 9217 return new ImageExpression(name); 9218 } 9219 evaluate(ctx) { 9220 const evaluatedImageName = this.input.evaluate(ctx); 9221 const value = ResolvedImage.fromString(evaluatedImageName); 9222 if (value && ctx.availableImages) value.available = ctx.availableImages.indexOf(evaluatedImageName) > -1; 9223 return value; 9224 } 9225 eachChild(fn) { 9226 fn(this.input); 9227 } 9228 outputDefined() { 9229 return false; 9230 } 9231}; 9232//#endregion 9233//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/length.mjs 9234var Length = class Length { 9235 constructor(input, key) { 9236 this.input = input; 9237 this.key = key; 9238 this.type = NumberType; 9239 } 9240 static parse(args, context) { 9241 if (args.length !== 2) return context.error(`Expected 1 argument, but found ${args.length - 1} instead.`); 9242 const input = context.parse(args[1], 1); 9243 if (!input) return null; 9244 if (input.type.kind !== "array" && input.type.kind !== "string" && input.type.kind !== "value") return context.error(`Expected argument of type string or array, but found ${typeToString(input.type)} instead.`); 9245 return new Length(input, context.key); 9246 } 9247 evaluate(ctx) { 9248 const input = this.input.evaluate(ctx); 9249 if (typeof input === "string") return [...input].length; 9250 else if (Array.isArray(input)) return input.length; 9251 else throw new RuntimeError(`Expected value to be of type string or array, but found ${typeToString(typeOf(input))} instead.`, this.key); 9252 } 9253 eachChild(fn) { 9254 fn(this.input); 9255 } 9256 outputDefined() { 9257 return false; 9258 } 9259}; 9260//#endregion 9261//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/util/geometry_util.mjs 9262const EXTENT = 8192; 9263function getTileCoordinates(p, canonical) { 9264 const x = mercatorXfromLng$1(p[0]); 9265 const y = mercatorYfromLat$1(p[1]); 9266 const tilesAtZoom = Math.pow(2, canonical.z); 9267 return [Math.round(x * tilesAtZoom * EXTENT), Math.round(y * tilesAtZoom * EXTENT)]; 9268} 9269function getLngLatFromTileCoord(coord, canonical) { 9270 const tilesAtZoom = Math.pow(2, canonical.z); 9271 const x = (coord[0] / EXTENT + canonical.x) / tilesAtZoom; 9272 const y = (coord[1] / EXTENT + canonical.y) / tilesAtZoom; 9273 return [lngFromMercatorXfromLng(x), latFromMercatorY$1(y)]; 9274} 9275function mercatorXfromLng$1(lng) { 9276 return (180 + lng) / 360; 9277} 9278function lngFromMercatorXfromLng(mercatorX) { 9279 return mercatorX * 360 - 180; 9280} 9281function mercatorYfromLat$1(lat) { 9282 return (180 - 180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360))) / 360; 9283} 9284function latFromMercatorY$1(mercatorY) { 9285 return 360 / Math.PI * Math.atan(Math.exp((180 - mercatorY * 360) * Math.PI / 180)) - 90; 9286} 9287function updateBBox(bbox, coord) { 9288 bbox[0] = Math.min(bbox[0], coord[0]); 9289 bbox[1] = Math.min(bbox[1], coord[1]); 9290 bbox[2] = Math.max(bbox[2], coord[0]); 9291 bbox[3] = Math.max(bbox[3], coord[1]); 9292} 9293function boxWithinBox(bbox1, bbox2) { 9294 if (bbox1[0] <= bbox2[0]) return false; 9295 if (bbox1[2] >= bbox2[2]) return false; 9296 if (bbox1[1] <= bbox2[1]) return false; 9297 if (bbox1[3] >= bbox2[3]) return false; 9298 return true; 9299} 9300function rayIntersect(p, p1, p2) { 9301 return p1[1] > p[1] !== p2[1] > p[1] && p[0] < (p2[0] - p1[0]) * (p[1] - p1[1]) / (p2[1] - p1[1]) + p1[0]; 9302} 9303function pointOnBoundary(p, p1, p2) { 9304 const x1 = p[0] - p1[0]; 9305 const y1 = p[1] - p1[1]; 9306 const x2 = p[0] - p2[0]; 9307 const y2 = p[1] - p2[1]; 9308 return x1 * y2 - x2 * y1 === 0 && x1 * x2 <= 0 && y1 * y2 <= 0; 9309} 9310function segmentIntersectSegment(a, b, c, d) { 9311 const vectorP = [b[0] - a[0], b[1] - a[1]]; 9312 if (perp([d[0] - c[0], d[1] - c[1]], vectorP) === 0) return false; 9313 if (twoSided(a, b, c, d) && twoSided(c, d, a, b)) return true; 9314 return false; 9315} 9316function lineIntersectPolygon(p1, p2, polygon) { 9317 for (const ring of polygon) for (let j = 0; j < ring.length - 1; ++j) if (segmentIntersectSegment(p1, p2, ring[j], ring[j + 1])) return true; 9318 return false; 9319} 9320function pointWithinPolygon(point, rings, trueIfOnBoundary = false) { 9321 let inside = false; 9322 for (const ring of rings) for (let j = 0; j < ring.length - 1; j++) { 9323 if (pointOnBoundary(point, ring[j], ring[j + 1])) return trueIfOnBoundary; 9324 if (rayIntersect(point, ring[j], ring[j + 1])) inside = !inside; 9325 } 9326 return inside; 9327} 9328function pointWithinPolygons(point, polygons) { 9329 for (const polygon of polygons) if (pointWithinPolygon(point, polygon)) return true; 9330 return false; 9331} 9332function lineStringWithinPolygon(line, polygon) { 9333 for (const point of line) if (!pointWithinPolygon(point, polygon)) return false; 9334 for (let i = 0; i < line.length - 1; ++i) if (lineIntersectPolygon(line[i], line[i + 1], polygon)) return false; 9335 return true; 9336} 9337function lineStringWithinPolygons(line, polygons) { 9338 for (const polygon of polygons) if (lineStringWithinPolygon(line, polygon)) return true; 9339 return false; 9340} 9341function perp(v1, v2) { 9342 return v1[0] * v2[1] - v1[1] * v2[0]; 9343} 9344function twoSided(p1, p2, q1, q2) { 9345 const x1 = p1[0] - q1[0]; 9346 const y1 = p1[1] - q1[1]; 9347 const x2 = p2[0] - q1[0]; 9348 const y2 = p2[1] - q1[1]; 9349 const x3 = q2[0] - q1[0]; 9350 const y3 = q2[1] - q1[1]; 9351 const det1 = x1 * y3 - x3 * y1; 9352 const det2 = x2 * y3 - x3 * y2; 9353 if (det1 > 0 && det2 < 0 || det1 < 0 && det2 > 0) return true; 9354 return false; 9355} 9356//#endregion 9357//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/within.mjs 9358function getTilePolygon(coordinates, bbox, canonical) { 9359 const polygon = []; 9360 for (let i = 0; i < coordinates.length; i++) { 9361 const ring = []; 9362 for (let j = 0; j < coordinates[i].length; j++) { 9363 const coord = getTileCoordinates(coordinates[i][j], canonical); 9364 updateBBox(bbox, coord); 9365 ring.push(coord); 9366 } 9367 polygon.push(ring); 9368 } 9369 return polygon; 9370} 9371function getTilePolygons(coordinates, bbox, canonical) { 9372 const polygons = []; 9373 for (let i = 0; i < coordinates.length; i++) { 9374 const polygon = getTilePolygon(coordinates[i], bbox, canonical); 9375 polygons.push(polygon); 9376 } 9377 return polygons; 9378} 9379function updatePoint(p, bbox, polyBBox, worldSize) { 9380 if (p[0] < polyBBox[0] || p[0] > polyBBox[2]) { 9381 const halfWorldSize = worldSize * .5; 9382 let shift = p[0] - polyBBox[0] > halfWorldSize ? -worldSize : polyBBox[0] - p[0] > halfWorldSize ? worldSize : 0; 9383 if (shift === 0) shift = p[0] - polyBBox[2] > halfWorldSize ? -worldSize : polyBBox[2] - p[0] > halfWorldSize ? worldSize : 0; 9384 p[0] += shift; 9385 } 9386 updateBBox(bbox, p); 9387} 9388function resetBBox(bbox) { 9389 bbox[0] = bbox[1] = Infinity; 9390 bbox[2] = bbox[3] = -Infinity; 9391} 9392function getTilePoints(geometry, pointBBox, polyBBox, canonical) { 9393 const worldSize = Math.pow(2, canonical.z) * EXTENT; 9394 const shifts = [canonical.x * EXTENT, canonical.y * EXTENT]; 9395 const tilePoints = []; 9396 for (const points of geometry) for (const point of points) { 9397 const p = [point.x + shifts[0], point.y + shifts[1]]; 9398 updatePoint(p, pointBBox, polyBBox, worldSize); 9399 tilePoints.push(p); 9400 } 9401 return tilePoints; 9402} 9403function getTileLines(geometry, lineBBox, polyBBox, canonical) { 9404 const worldSize = Math.pow(2, canonical.z) * EXTENT; 9405 const shifts = [canonical.x * EXTENT, canonical.y * EXTENT]; 9406 const tileLines = []; 9407 for (const line of geometry) { 9408 const tileLine = []; 9409 for (const point of line) { 9410 const p = [point.x + shifts[0], point.y + shifts[1]]; 9411 updateBBox(lineBBox, p); 9412 tileLine.push(p); 9413 } 9414 tileLines.push(tileLine); 9415 } 9416 if (lineBBox[2] - lineBBox[0] <= worldSize / 2) { 9417 resetBBox(lineBBox); 9418 for (const line of tileLines) for (const p of line) updatePoint(p, lineBBox, polyBBox, worldSize); 9419 } 9420 return tileLines; 9421} 9422function pointsWithinPolygons(ctx, polygonGeometry) { 9423 const pointBBox = [ 9424 Infinity, 9425 Infinity, 9426 -Infinity, 9427 -Infinity 9428 ]; 9429 const polyBBox = [ 9430 Infinity, 9431 Infinity, 9432 -Infinity, 9433 -Infinity 9434 ]; 9435 const canonical = ctx.canonicalID(); 9436 if (polygonGeometry.type === "Polygon") { 9437 const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical); 9438 const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical); 9439 if (!boxWithinBox(pointBBox, polyBBox)) return false; 9440 for (const point of tilePoints) if (!pointWithinPolygon(point, tilePolygon)) return false; 9441 } 9442 if (polygonGeometry.type === "MultiPolygon") { 9443 const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical); 9444 const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical); 9445 if (!boxWithinBox(pointBBox, polyBBox)) return false; 9446 for (const point of tilePoints) if (!pointWithinPolygons(point, tilePolygons)) return false; 9447 } 9448 return true; 9449} 9450function linesWithinPolygons(ctx, polygonGeometry) { 9451 const lineBBox = [ 9452 Infinity, 9453 Infinity, 9454 -Infinity, 9455 -Infinity 9456 ]; 9457 const polyBBox = [ 9458 Infinity, 9459 Infinity, 9460 -Infinity, 9461 -Infinity 9462 ]; 9463 const canonical = ctx.canonicalID(); 9464 if (polygonGeometry.type === "Polygon") { 9465 const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical); 9466 const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical); 9467 if (!boxWithinBox(lineBBox, polyBBox)) return false; 9468 for (const line of tileLines) if (!lineStringWithinPolygon(line, tilePolygon)) return false; 9469 } 9470 if (polygonGeometry.type === "MultiPolygon") { 9471 const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical); 9472 const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical); 9473 if (!boxWithinBox(lineBBox, polyBBox)) return false; 9474 for (const line of tileLines) if (!lineStringWithinPolygons(line, tilePolygons)) return false; 9475 } 9476 return true; 9477} 9478var Within = class Within { 9479 constructor(geojson, geometries) { 9480 this.type = BooleanType; 9481 this.geojson = geojson; 9482 this.geometries = geometries; 9483 } 9484 static parse(args, context) { 9485 if (args.length !== 2) return context.error(`'within' expression requires exactly one argument, but found ${args.length - 1} instead.`); 9486 if (isValue(args[1])) { 9487 const geojson = args[1]; 9488 if (geojson.type === "FeatureCollection") { 9489 const polygonsCoords = []; 9490 for (const polygon of geojson.features) { 9491 const { type, coordinates } = polygon.geometry; 9492 if (type === "Polygon") polygonsCoords.push(coordinates); 9493 if (type === "MultiPolygon") polygonsCoords.push(...coordinates); 9494 } 9495 if (polygonsCoords.length) return new Within(geojson, { 9496 type: "MultiPolygon", 9497 coordinates: polygonsCoords 9498 }); 9499 } else if (geojson.type === "Feature") { 9500 const type = geojson.geometry.type; 9501 if (type === "Polygon" || type === "MultiPolygon") return new Within(geojson, geojson.geometry); 9502 } else if (geojson.type === "Polygon" || geojson.type === "MultiPolygon") return new Within(geojson, geojson); 9503 } 9504 return context.error("'within' expression requires valid geojson object that contains polygon geometry type."); 9505 } 9506 evaluate(ctx) { 9507 if (ctx.geometry() != null && ctx.canonicalID() != null) { 9508 if (ctx.geometryType() === "Point") return pointsWithinPolygons(ctx, this.geometries); 9509 else if (ctx.geometryType() === "LineString") return linesWithinPolygons(ctx, this.geometries); 9510 } 9511 return false; 9512 } 9513 eachChild() {} 9514 outputDefined() { 9515 return true; 9516 } 9517}; 9518//#endregion 9519//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/node_modules/tinyqueue/index.mjs 9520var TinyQueue$1 = class { 9521 constructor(data = [], compare = (a, b) => a < b ? -1 : a > b ? 1 : 0) { 9522 this.data = data; 9523 this.length = this.data.length; 9524 this.compare = compare; 9525 if (this.length > 0) for (let i = (this.length >> 1) - 1; i >= 0; i--) this._down(i); 9526 } 9527 push(item) { 9528 this.data.push(item); 9529 this._up(this.length++); 9530 } 9531 pop() { 9532 if (this.length === 0) return void 0; 9533 const top = this.data[0]; 9534 const bottom = this.data.pop(); 9535 if (--this.length > 0) { 9536 this.data[0] = bottom; 9537 this._down(0); 9538 } 9539 return top; 9540 } 9541 peek() { 9542 return this.data[0]; 9543 } 9544 _up(pos) { 9545 const { data, compare } = this; 9546 const item = data[pos]; 9547 while (pos > 0) { 9548 const parent = pos - 1 >> 1; 9549 const current = data[parent]; 9550 if (compare(item, current) >= 0) break; 9551 data[pos] = current; 9552 pos = parent; 9553 } 9554 data[pos] = item; 9555 } 9556 _down(pos) { 9557 const { data, compare } = this; 9558 const halfLength = this.length >> 1; 9559 const item = data[pos]; 9560 while (pos < halfLength) { 9561 let bestChild = (pos << 1) + 1; 9562 const right = bestChild + 1; 9563 if (right < this.length && compare(data[right], data[bestChild]) < 0) bestChild = right; 9564 if (compare(data[bestChild], item) >= 0) break; 9565 data[pos] = data[bestChild]; 9566 pos = bestChild; 9567 } 9568 data[pos] = item; 9569 } 9570}; 9571//#endregion 9572//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/util/cheap_ruler.mjs 9573const RE = 6378.137; 9574const E2 = .0066943799901413165; 9575const RAD = Math.PI / 180; 9576var CheapRuler = class { 9577 constructor(lat) { 9578 const m = RAD * RE * 1e3; 9579 const coslat = Math.cos(lat * RAD); 9580 const w2 = 1 / (1 - E2 * (1 - coslat * coslat)); 9581 const w = Math.sqrt(w2); 9582 this.kx = m * w * coslat; 9583 this.ky = m * w * w2 * .9933056200098587; 9584 } 9585 /** 9586 * Given two points of the form [longitude, latitude], returns the distance. 9587 * 9588 * @param a - point [longitude, latitude] 9589 * @param b - point [longitude, latitude] 9590 * @returns distance 9591 * @example 9592 * const distance = ruler.distance([30.5, 50.5], [30.51, 50.49]); 9593 * //=distance 9594 */ 9595 distance(a, b) { 9596 const dx = this.wrap(a[0] - b[0]) * this.kx; 9597 const dy = (a[1] - b[1]) * this.ky; 9598 return Math.sqrt(dx * dx + dy * dy); 9599 } 9600 /** 9601 * Returns an object of the form {point, index, t}, where point is closest point on the line 9602 * from the given point, index is the start index of the segment with the closest point, 9603 * and t is a parameter from 0 to 1 that indicates where the closest point is on that segment. 9604 * 9605 * @param line - an array of points that form the line 9606 * @param p - point [longitude, latitude] 9607 * @returns the nearest point, its index in the array and the proportion along the line 9608 * @example 9609 * const point = ruler.pointOnLine(line, [-67.04, 50.5]).point; 9610 * //=point 9611 */ 9612 pointOnLine(line, p) { 9613 let minDist = Infinity; 9614 let minX, minY, minI, minT; 9615 for (let i = 0; i < line.length - 1; i++) { 9616 let x = line[i][0]; 9617 let y = line[i][1]; 9618 let dx = this.wrap(line[i + 1][0] - x) * this.kx; 9619 let dy = (line[i + 1][1] - y) * this.ky; 9620 let t = 0; 9621 if (dx !== 0 || dy !== 0) { 9622 t = (this.wrap(p[0] - x) * this.kx * dx + (p[1] - y) * this.ky * dy) / (dx * dx + dy * dy); 9623 if (t > 1) { 9624 x = line[i + 1][0]; 9625 y = line[i + 1][1]; 9626 } else if (t > 0) { 9627 x += dx / this.kx * t; 9628 y += dy / this.ky * t; 9629 } 9630 } 9631 dx = this.wrap(p[0] - x) * this.kx; 9632 dy = (p[1] - y) * this.ky; 9633 const sqDist = dx * dx + dy * dy; 9634 if (sqDist < minDist) { 9635 minDist = sqDist; 9636 minX = x; 9637 minY = y; 9638 minI = i; 9639 minT = t; 9640 } 9641 } 9642 return { 9643 point: [minX, minY], 9644 index: minI, 9645 t: Math.max(0, Math.min(1, minT)) 9646 }; 9647 } 9648 wrap(deg) { 9649 while (deg < -180) deg += 360; 9650 while (deg > 180) deg -= 360; 9651 return deg; 9652 } 9653}; 9654//#endregion 9655//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/distance.mjs 9656const MinPointsSize = 100; 9657const MinLinePointsSize = 50; 9658function compareDistPair(a, b) { 9659 return b[0] - a[0]; 9660} 9661function getRangeSize(range) { 9662 return range[1] - range[0] + 1; 9663} 9664function isRangeSafe(range, threshold) { 9665 return range[1] >= range[0] && range[1] < threshold; 9666} 9667function splitRange(range, isLine) { 9668 if (range[0] > range[1]) return [null, null]; 9669 const size = getRangeSize(range); 9670 if (isLine) { 9671 if (size === 2) return [range, null]; 9672 const size1 = Math.floor(size / 2); 9673 return [[range[0], range[0] + size1], [range[0] + size1, range[1]]]; 9674 } 9675 if (size === 1) return [range, null]; 9676 const size1 = Math.floor(size / 2) - 1; 9677 return [[range[0], range[0] + size1], [range[0] + size1 + 1, range[1]]]; 9678} 9679function getBBox(coords, range) { 9680 if (!isRangeSafe(range, coords.length)) return [ 9681 Infinity, 9682 Infinity, 9683 -Infinity, 9684 -Infinity 9685 ]; 9686 const bbox = [ 9687 Infinity, 9688 Infinity, 9689 -Infinity, 9690 -Infinity 9691 ]; 9692 for (let i = range[0]; i <= range[1]; ++i) updateBBox(bbox, coords[i]); 9693 return bbox; 9694} 9695function getPolygonBBox(polygon) { 9696 const bbox = [ 9697 Infinity, 9698 Infinity, 9699 -Infinity, 9700 -Infinity 9701 ]; 9702 for (const ring of polygon) for (const coord of ring) updateBBox(bbox, coord); 9703 return bbox; 9704} 9705function isValidBBox(bbox) { 9706 return bbox[0] !== -Infinity && bbox[1] !== -Infinity && bbox[2] !== Infinity && bbox[3] !== Infinity; 9707} 9708function bboxToBBoxDistance(bbox1, bbox2, ruler) { 9709 if (!isValidBBox(bbox1) || !isValidBBox(bbox2)) return NaN; 9710 let dx = 0; 9711 let dy = 0; 9712 if (bbox1[2] < bbox2[0]) dx = bbox2[0] - bbox1[2]; 9713 if (bbox1[0] > bbox2[2]) dx = bbox1[0] - bbox2[2]; 9714 if (bbox1[1] > bbox2[3]) dy = bbox1[1] - bbox2[3]; 9715 if (bbox1[3] < bbox2[1]) dy = bbox2[1] - bbox1[3]; 9716 return ruler.distance([0, 0], [dx, dy]); 9717} 9718function pointToLineDistance(point, line, ruler) { 9719 const nearestPoint = ruler.pointOnLine(line, point); 9720 return ruler.distance(point, nearestPoint.point); 9721} 9722function segmentToSegmentDistance(p1, p2, q1, q2, ruler) { 9723 const dist1 = Math.min(pointToLineDistance(p1, [q1, q2], ruler), pointToLineDistance(p2, [q1, q2], ruler)); 9724 const dist2 = Math.min(pointToLineDistance(q1, [p1, p2], ruler), pointToLineDistance(q2, [p1, p2], ruler)); 9725 return Math.min(dist1, dist2); 9726} 9727function lineToLineDistance(line1, range1, line2, range2, ruler) { 9728 if (!(isRangeSafe(range1, line1.length) && isRangeSafe(range2, line2.length))) return Infinity; 9729 let dist = Infinity; 9730 for (let i = range1[0]; i < range1[1]; ++i) { 9731 const p1 = line1[i]; 9732 const p2 = line1[i + 1]; 9733 for (let j = range2[0]; j < range2[1]; ++j) { 9734 const q1 = line2[j]; 9735 const q2 = line2[j + 1]; 9736 if (segmentIntersectSegment(p1, p2, q1, q2)) return 0; 9737 dist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler)); 9738 } 9739 } 9740 return dist; 9741} 9742function pointsToPointsDistance(points1, range1, points2, range2, ruler) { 9743 if (!(isRangeSafe(range1, points1.length) && isRangeSafe(range2, points2.length))) return NaN; 9744 let dist = Infinity; 9745 for (let i = range1[0]; i <= range1[1]; ++i) for (let j = range2[0]; j <= range2[1]; ++j) { 9746 dist = Math.min(dist, ruler.distance(points1[i], points2[j])); 9747 if (dist === 0) return dist; 9748 } 9749 return dist; 9750} 9751function pointToPolygonDistance(point, polygon, ruler) { 9752 if (pointWithinPolygon(point, polygon, true)) return 0; 9753 let dist = Infinity; 9754 for (const ring of polygon) { 9755 const front = ring[0]; 9756 const back = ring[ring.length - 1]; 9757 if (front !== back) { 9758 dist = Math.min(dist, pointToLineDistance(point, [back, front], ruler)); 9759 if (dist === 0) return dist; 9760 } 9761 const nearestPoint = ruler.pointOnLine(ring, point); 9762 dist = Math.min(dist, ruler.distance(point, nearestPoint.point)); 9763 if (dist === 0) return dist; 9764 } 9765 return dist; 9766} 9767function lineToPolygonDistance(line, range, polygon, ruler) { 9768 if (!isRangeSafe(range, line.length)) return NaN; 9769 for (let i = range[0]; i <= range[1]; ++i) if (pointWithinPolygon(line[i], polygon, true)) return 0; 9770 let dist = Infinity; 9771 for (let i = range[0]; i < range[1]; ++i) { 9772 const p1 = line[i]; 9773 const p2 = line[i + 1]; 9774 for (const ring of polygon) for (let j = 0, len = ring.length, k = len - 1; j < len; k = j++) { 9775 const q1 = ring[k]; 9776 const q2 = ring[j]; 9777 if (segmentIntersectSegment(p1, p2, q1, q2)) return 0; 9778 dist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler)); 9779 } 9780 } 9781 return dist; 9782} 9783function polygonIntersect(poly1, poly2) { 9784 for (const ring of poly1) for (const point of ring) if (pointWithinPolygon(point, poly2, true)) return true; 9785 return false; 9786} 9787function polygonToPolygonDistance(polygon1, polygon2, ruler, currentMiniDist = Infinity) { 9788 const bbox1 = getPolygonBBox(polygon1); 9789 const bbox2 = getPolygonBBox(polygon2); 9790 if (currentMiniDist !== Infinity && bboxToBBoxDistance(bbox1, bbox2, ruler) >= currentMiniDist) return currentMiniDist; 9791 if (boxWithinBox(bbox1, bbox2)) { 9792 if (polygonIntersect(polygon1, polygon2)) return 0; 9793 } else if (polygonIntersect(polygon2, polygon1)) return 0; 9794 let dist = Infinity; 9795 for (const ring1 of polygon1) for (let i = 0, len1 = ring1.length, l = len1 - 1; i < len1; l = i++) { 9796 const p1 = ring1[l]; 9797 const p2 = ring1[i]; 9798 for (const ring2 of polygon2) for (let j = 0, len2 = ring2.length, k = len2 - 1; j < len2; k = j++) { 9799 const q1 = ring2[k]; 9800 const q2 = ring2[j]; 9801 if (segmentIntersectSegment(p1, p2, q1, q2)) return 0; 9802 dist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler)); 9803 } 9804 } 9805 return dist; 9806} 9807function updateQueue(distQueue, miniDist, ruler, points, polyBBox, rangeA) { 9808 if (!rangeA) return; 9809 const tempDist = bboxToBBoxDistance(getBBox(points, rangeA), polyBBox, ruler); 9810 if (tempDist < miniDist) distQueue.push([ 9811 tempDist, 9812 rangeA, 9813 [0, 0] 9814 ]); 9815} 9816function updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, range1, range2) { 9817 if (!range1 || !range2) return; 9818 const tempDist = bboxToBBoxDistance(getBBox(pointSet1, range1), getBBox(pointSet2, range2), ruler); 9819 if (tempDist < miniDist) distQueue.push([ 9820 tempDist, 9821 range1, 9822 range2 9823 ]); 9824} 9825function pointsToPolygonDistance(points, isLine, polygon, ruler, currentMiniDist = Infinity) { 9826 let miniDist = Math.min(ruler.distance(points[0], polygon[0][0]), currentMiniDist); 9827 if (miniDist === 0) return miniDist; 9828 const distQueue = new TinyQueue$1([[ 9829 0, 9830 [0, points.length - 1], 9831 [0, 0] 9832 ]], compareDistPair); 9833 const polyBBox = getPolygonBBox(polygon); 9834 while (distQueue.length > 0) { 9835 const distPair = distQueue.pop(); 9836 if (distPair[0] >= miniDist) continue; 9837 const range = distPair[1]; 9838 const threshold = isLine ? MinLinePointsSize : MinPointsSize; 9839 if (getRangeSize(range) <= threshold) { 9840 if (!isRangeSafe(range, points.length)) return NaN; 9841 if (isLine) { 9842 const tempDist = lineToPolygonDistance(points, range, polygon, ruler); 9843 if (isNaN(tempDist) || tempDist === 0) return tempDist; 9844 miniDist = Math.min(miniDist, tempDist); 9845 } else for (let i = range[0]; i <= range[1]; ++i) { 9846 const tempDist = pointToPolygonDistance(points[i], polygon, ruler); 9847 miniDist = Math.min(miniDist, tempDist); 9848 if (miniDist === 0) return 0; 9849 } 9850 } else { 9851 const newRangesA = splitRange(range, isLine); 9852 updateQueue(distQueue, miniDist, ruler, points, polyBBox, newRangesA[0]); 9853 updateQueue(distQueue, miniDist, ruler, points, polyBBox, newRangesA[1]); 9854 } 9855 } 9856 return miniDist; 9857} 9858function pointSetToPointSetDistance(pointSet1, isLine1, pointSet2, isLine2, ruler, currentMiniDist = Infinity) { 9859 let miniDist = Math.min(currentMiniDist, ruler.distance(pointSet1[0], pointSet2[0])); 9860 if (miniDist === 0) return miniDist; 9861 const distQueue = new TinyQueue$1([[ 9862 0, 9863 [0, pointSet1.length - 1], 9864 [0, pointSet2.length - 1] 9865 ]], compareDistPair); 9866 while (distQueue.length > 0) { 9867 const distPair = distQueue.pop(); 9868 if (distPair[0] >= miniDist) continue; 9869 const rangeA = distPair[1]; 9870 const rangeB = distPair[2]; 9871 const threshold1 = isLine1 ? MinLinePointsSize : MinPointsSize; 9872 const threshold2 = isLine2 ? MinLinePointsSize : MinPointsSize; 9873 if (getRangeSize(rangeA) <= threshold1 && getRangeSize(rangeB) <= threshold2) { 9874 if (!isRangeSafe(rangeA, pointSet1.length) && isRangeSafe(rangeB, pointSet2.length)) return NaN; 9875 let tempDist; 9876 if (isLine1 && isLine2) { 9877 tempDist = lineToLineDistance(pointSet1, rangeA, pointSet2, rangeB, ruler); 9878 miniDist = Math.min(miniDist, tempDist); 9879 } else if (isLine1 && !isLine2) { 9880 const sublibe = pointSet1.slice(rangeA[0], rangeA[1] + 1); 9881 for (let i = rangeB[0]; i <= rangeB[1]; ++i) { 9882 tempDist = pointToLineDistance(pointSet2[i], sublibe, ruler); 9883 miniDist = Math.min(miniDist, tempDist); 9884 if (miniDist === 0) return miniDist; 9885 } 9886 } else if (!isLine1 && isLine2) { 9887 const sublibe = pointSet2.slice(rangeB[0], rangeB[1] + 1); 9888 for (let i = rangeA[0]; i <= rangeA[1]; ++i) { 9889 tempDist = pointToLineDistance(pointSet1[i], sublibe, ruler); 9890 miniDist = Math.min(miniDist, tempDist); 9891 if (miniDist === 0) return miniDist; 9892 } 9893 } else { 9894 tempDist = pointsToPointsDistance(pointSet1, rangeA, pointSet2, rangeB, ruler); 9895 miniDist = Math.min(miniDist, tempDist); 9896 } 9897 } else { 9898 const newRangesA = splitRange(rangeA, isLine1); 9899 const newRangesB = splitRange(rangeB, isLine2); 9900 updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[0], newRangesB[0]); 9901 updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[0], newRangesB[1]); 9902 updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[1], newRangesB[0]); 9903 updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[1], newRangesB[1]); 9904 } 9905 } 9906 return miniDist; 9907} 9908function pointToGeometryDistance(ctx, geometries) { 9909 const tilePoints = ctx.geometry(); 9910 const pointPosition = tilePoints.flat().map((p) => getLngLatFromTileCoord([p.x, p.y], ctx.canonical)); 9911 if (tilePoints.length === 0) return NaN; 9912 const ruler = new CheapRuler(pointPosition[0][1]); 9913 let dist = Infinity; 9914 for (const geometry of geometries) { 9915 switch (geometry.type) { 9916 case "Point": 9917 dist = Math.min(dist, pointSetToPointSetDistance(pointPosition, false, [geometry.coordinates], false, ruler, dist)); 9918 break; 9919 case "LineString": 9920 dist = Math.min(dist, pointSetToPointSetDistance(pointPosition, false, geometry.coordinates, true, ruler, dist)); 9921 break; 9922 case "Polygon": dist = Math.min(dist, pointsToPolygonDistance(pointPosition, false, geometry.coordinates, ruler, dist)); 9923 } 9924 if (dist === 0) return dist; 9925 } 9926 return dist; 9927} 9928function lineStringToGeometryDistance(ctx, geometries) { 9929 const tileLine = ctx.geometry(); 9930 const linePositions = tileLine.flat().map((p) => getLngLatFromTileCoord([p.x, p.y], ctx.canonical)); 9931 if (tileLine.length === 0) return NaN; 9932 const ruler = new CheapRuler(linePositions[0][1]); 9933 let dist = Infinity; 9934 for (const geometry of geometries) { 9935 switch (geometry.type) { 9936 case "Point": 9937 dist = Math.min(dist, pointSetToPointSetDistance(linePositions, true, [geometry.coordinates], false, ruler, dist)); 9938 break; 9939 case "LineString": 9940 dist = Math.min(dist, pointSetToPointSetDistance(linePositions, true, geometry.coordinates, true, ruler, dist)); 9941 break; 9942 case "Polygon": dist = Math.min(dist, pointsToPolygonDistance(linePositions, true, geometry.coordinates, ruler, dist)); 9943 } 9944 if (dist === 0) return dist; 9945 } 9946 return dist; 9947} 9948function polygonToGeometryDistance(ctx, geometries) { 9949 const tilePolygon = ctx.geometry(); 9950 if (tilePolygon.length === 0 || tilePolygon[0].length === 0) return NaN; 9951 const polygons = classifyRings$1(tilePolygon, 0).map((polygon) => { 9952 return polygon.map((ring) => { 9953 return ring.map((p) => getLngLatFromTileCoord([p.x, p.y], ctx.canonical)); 9954 }); 9955 }); 9956 const ruler = new CheapRuler(polygons[0][0][0][1]); 9957 let dist = Infinity; 9958 for (const geometry of geometries) for (const polygon of polygons) { 9959 switch (geometry.type) { 9960 case "Point": 9961 dist = Math.min(dist, pointsToPolygonDistance([geometry.coordinates], false, polygon, ruler, dist)); 9962 break; 9963 case "LineString": 9964 dist = Math.min(dist, pointsToPolygonDistance(geometry.coordinates, true, polygon, ruler, dist)); 9965 break; 9966 case "Polygon": dist = Math.min(dist, polygonToPolygonDistance(polygon, geometry.coordinates, ruler, dist)); 9967 } 9968 if (dist === 0) return dist; 9969 } 9970 return dist; 9971} 9972function toSimpleGeometry(geometry) { 9973 if (geometry.type === "MultiPolygon") return geometry.coordinates.map((polygon) => { 9974 return { 9975 type: "Polygon", 9976 coordinates: polygon 9977 }; 9978 }); 9979 if (geometry.type === "MultiLineString") return geometry.coordinates.map((lineString) => { 9980 return { 9981 type: "LineString", 9982 coordinates: lineString 9983 }; 9984 }); 9985 if (geometry.type === "MultiPoint") return geometry.coordinates.map((point) => { 9986 return { 9987 type: "Point", 9988 coordinates: point 9989 }; 9990 }); 9991 return [geometry]; 9992} 9993var Distance = class Distance { 9994 constructor(geojson, geometries) { 9995 this.type = NumberType; 9996 this.geojson = geojson; 9997 this.geometries = geometries; 9998 } 9999 static parse(args, context) { 10000 if (args.length !== 2) return context.error(`'distance' expression requires exactly one argument, but found ${args.length - 1} instead.`); 10001 if (isValue(args[1])) { 10002 const geojson = args[1]; 10003 if (geojson.type === "FeatureCollection") return new Distance(geojson, geojson.features.map((feature) => toSimpleGeometry(feature.geometry)).flat()); 10004 else if (geojson.type === "Feature") return new Distance(geojson, toSimpleGeometry(geojson.geometry)); 10005 else if ("type" in geojson && "coordinates" in geojson) return new Distance(geojson, toSimpleGeometry(geojson)); 10006 } 10007 return context.error("'distance' expression requires valid geojson object that contains polygon geometry type."); 10008 } 10009 evaluate(ctx) { 10010 if (ctx.geometry() != null && ctx.canonicalID() != null) { 10011 if (ctx.geometryType() === "Point") return pointToGeometryDistance(ctx, this.geometries); 10012 else if (ctx.geometryType() === "LineString") return lineStringToGeometryDistance(ctx, this.geometries); 10013 else if (ctx.geometryType() === "Polygon") return polygonToGeometryDistance(ctx, this.geometries); 10014 } 10015 return NaN; 10016 } 10017 eachChild() {} 10018 outputDefined() { 10019 return true; 10020 } 10021}; 10022//#endregion 10023//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/semiliteral.mjs 10024var Semiliteral = class Semiliteral { 10025 constructor(arr) { 10026 let elementType = null; 10027 for (const expr of arr) if (!elementType) elementType = expr.type; 10028 else if (elementType === expr.type) continue; 10029 else { 10030 elementType = ValueType; 10031 break; 10032 } 10033 this.type = array(elementType ?? ValueType, arr.length); 10034 this.arr = arr; 10035 } 10036 static parse(args, context) { 10037 if (args.length !== 2) return context.error(`'semiliteral' expression requires exactly one argument, but found ${args.length - 1} instead.`); 10038 if (!isValue(args[1])) return context.error(`invalid value of type "${typeof args[1]}"`); 10039 const value = args[1]; 10040 const type = typeOf(value); 10041 if (type.kind === "array") { 10042 const arr = value; 10043 const arrayContext = context.concat(1); 10044 const parsed = []; 10045 for (let i = 0; i < arr.length; i++) { 10046 const item = arrayContext.parse(arr[i], i, ValueType); 10047 if (!item) return null; 10048 parsed.push(item); 10049 } 10050 return new Semiliteral(parsed); 10051 } else return new Literal(type, value); 10052 } 10053 evaluate(ctx) { 10054 return this.arr.map((arg) => arg.evaluate(ctx)); 10055 } 10056 eachChild(fn) { 10057 this.arr.forEach(fn); 10058 } 10059 outputDefined() { 10060 return this.arr.every((arg) => arg.outputDefined()); 10061 } 10062}; 10063//#endregion 10064//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/global_state.mjs 10065var GlobalState = class GlobalState { 10066 constructor(key) { 10067 this.key = key; 10068 this.type = ValueType; 10069 } 10070 static parse(args, context) { 10071 if (args.length !== 2) return context.error(`Expected 1 argument, but found ${args.length - 1} instead.`); 10072 const key = args[1]; 10073 if (key === void 0 || key === null) return context.error("Global state property must be defined."); 10074 if (typeof key !== "string") return context.error(`Global state property must be string, but found ${typeof args[1]} instead.`); 10075 return new GlobalState(key); 10076 } 10077 evaluate(ctx) { 10078 const globalState = ctx.globals?.globalState; 10079 if (!globalState || Object.keys(globalState).length === 0) return null; 10080 return getOwn(globalState, this.key) ?? null; 10081 } 10082 eachChild() {} 10083 outputDefined() { 10084 return false; 10085 } 10086}; 10087//#endregion 10088//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/definitions/index.mjs 10089const expressions$1 = { 10090 "==": Equals, 10091 "!=": NotEquals, 10092 ">": GreaterThan, 10093 "<": LessThan, 10094 ">=": GreaterThanOrEqual, 10095 "<=": LessThanOrEqual, 10096 array: Assertion, 10097 at: At, 10098 boolean: Assertion, 10099 case: Case, 10100 coalesce: Coalesce, 10101 collator: CollatorExpression, 10102 format: FormatExpression, 10103 image: ImageExpression, 10104 in: In, 10105 "index-of": IndexOf, 10106 interpolate: Interpolate, 10107 "interpolate-hcl": Interpolate, 10108 "interpolate-lab": Interpolate, 10109 length: Length, 10110 let: Let, 10111 literal: Literal, 10112 match: Match, 10113 number: Assertion, 10114 "number-format": NumberFormat, 10115 object: Assertion, 10116 semiliteral: Semiliteral, 10117 slice: Slice, 10118 step: Step, 10119 string: Assertion, 10120 "to-boolean": Coercion, 10121 "to-color": Coercion, 10122 "to-number": Coercion, 10123 "to-string": Coercion, 10124 var: Var, 10125 within: Within, 10126 distance: Distance, 10127 "global-state": GlobalState 10128}; 10129//#endregion 10130//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/parsing_error.mjs 10131var ExpressionParsingError = class extends Error { 10132 constructor(key, message) { 10133 super(message); 10134 this.message = message; 10135 this.key = key; 10136 } 10137}; 10138//#endregion 10139//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/scope.mjs 10140/** 10141* Tracks `let` bindings during expression parsing. 10142* @private 10143*/ 10144var Scope = class Scope { 10145 constructor(parent, bindings = []) { 10146 this.parent = parent; 10147 this.bindings = {}; 10148 for (const [name, expression] of bindings) this.bindings[name] = expression; 10149 } 10150 concat(bindings) { 10151 return new Scope(this, bindings); 10152 } 10153 get(name) { 10154 if (this.bindings[name]) return this.bindings[name]; 10155 if (this.parent) return this.parent.get(name); 10156 throw new Error(`${name} not found in scope.`); 10157 } 10158 has(name) { 10159 if (this.bindings[name]) return true; 10160 return this.parent ? this.parent.has(name) : false; 10161 } 10162}; 10163//#endregion 10164//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/parsing_context.mjs 10165/** 10166* State associated parsing at a given point in an expression tree. 10167* @private 10168*/ 10169var ParsingContext = class ParsingContext { 10170 constructor(registry, isConstantFunc, path = [], expectedType, scope = new Scope(), errors = []) { 10171 this.registry = registry; 10172 this.path = path; 10173 this.key = path.map((part) => `[${part}]`).join(""); 10174 this.scope = scope; 10175 this.errors = errors; 10176 this.expectedType = expectedType; 10177 this._isConstant = isConstantFunc; 10178 } 10179 /** 10180 * @param expr the JSON expression to parse 10181 * @param index the optional argument index if this expression is an argument of a parent expression that's being parsed 10182 * @param options 10183 * @param options.omitTypeAnnotations set true to omit inferred type annotations. Caller beware: with this option set, the parsed expression's type will NOT satisfy `expectedType` if it would normally be wrapped in an inferred annotation. 10184 * @private 10185 */ 10186 parse(expr, index, expectedType, bindings, options = {}) { 10187 if (index != null) return this.concat(index, expectedType, bindings)._parse(expr, options); 10188 return this._parse(expr, options); 10189 } 10190 _parse(expr, options) { 10191 if (expr === null || typeof expr === "string" || typeof expr === "boolean" || typeof expr === "number") expr = ["literal", expr]; 10192 const key = this.key; 10193 function annotate(parsed, type, typeAnnotation) { 10194 if (typeAnnotation === "assert") return new Assertion(type, [parsed], key); 10195 else if (typeAnnotation === "coerce") return new Coercion(type, [parsed], key); 10196 else return parsed; 10197 } 10198 if (Array.isArray(expr)) { 10199 if (expr.length === 0) return this.error("Expected an array with at least one element. If you wanted a literal array, use [\"literal\", []]."); 10200 const op = expr[0]; 10201 if (typeof op !== "string") { 10202 this.error(`Expression name must be a string, but found ${typeof op} instead. If you wanted a literal array, use ["literal", [...]].`, 0); 10203 return null; 10204 } 10205 const Expr = this.registry[op]; 10206 if (Expr) { 10207 let parsed = Expr.parse(expr, this); 10208 if (!parsed) return null; 10209 if (this.expectedType) { 10210 const expected = this.expectedType; 10211 const actual = parsed.type; 10212 if ((expected.kind === "string" || expected.kind === "number" || expected.kind === "boolean" || expected.kind === "object" || expected.kind === "array") && actual.kind === "value") parsed = annotate(parsed, expected, options.typeAnnotation || "assert"); 10213 else if ("projectionDefinition" === expected.kind && [ 10214 "string", 10215 "array", 10216 "value" 10217 ].includes(actual.kind) || [ 10218 "color", 10219 "formatted", 10220 "resolvedImage" 10221 ].includes(expected.kind) && ["value", "string"].includes(actual.kind) || ["padding", "numberArray"].includes(expected.kind) && [ 10222 "value", 10223 "number", 10224 "array" 10225 ].includes(actual.kind) || "colorArray" === expected.kind && [ 10226 "value", 10227 "string", 10228 "array" 10229 ].includes(actual.kind) || "variableAnchorOffsetCollection" === expected.kind && ["value", "array"].includes(actual.kind)) parsed = annotate(parsed, expected, options.typeAnnotation || "coerce"); 10230 else if (this.checkSubtype(expected, actual)) return null; 10231 } 10232 if (!(parsed instanceof Literal) && parsed.type.kind !== "resolvedImage" && this._isConstant(parsed)) { 10233 const ec = new EvaluationContext(); 10234 try { 10235 parsed = new Literal(parsed.type, parsed.evaluate(ec)); 10236 } catch (e) { 10237 this.error(e.message); 10238 return null; 10239 } 10240 } 10241 return parsed; 10242 } 10243 return this.error(`Unknown expression "${op}". If you wanted a literal array, use ["literal", [...]].`, 0); 10244 } else if (typeof expr === "undefined") return this.error("'undefined' value invalid. Use null instead."); 10245 else if (typeof expr === "object") return this.error("Bare objects invalid. Use [\"literal\", {...}] instead."); 10246 else return this.error(`Expected an array, but found ${typeof expr} instead.`); 10247 } 10248 /** 10249 * Returns a copy of this context suitable for parsing the subexpression at 10250 * index `index`, optionally appending to 'let' binding map. 10251 * 10252 * Note that `errors` property, intended for collecting errors while 10253 * parsing, is copied by reference rather than cloned. 10254 * @private 10255 */ 10256 concat(index, expectedType, bindings) { 10257 const path = typeof index === "number" ? this.path.concat(index) : this.path; 10258 const scope = bindings ? this.scope.concat(bindings) : this.scope; 10259 return new ParsingContext(this.registry, this._isConstant, path, expectedType || null, scope, this.errors); 10260 } 10261 /** 10262 * Push a parsing (or type checking) error into the `this.errors` 10263 * @param error The message 10264 * @param keys Optionally specify the source of the error at a child 10265 * of the current expression at `this.key`. 10266 * @private 10267 */ 10268 error(error, ...keys) { 10269 const key = `${this.key}${keys.map((k) => `[${k}]`).join("")}`; 10270 this.errors.push(new ExpressionParsingError(key, error)); 10271 } 10272 /** 10273 * Returns null if `t` is a subtype of `expected`; otherwise returns an 10274 * error message and also pushes it to `this.errors`. 10275 * @param expected The expected type 10276 * @param t The actual type 10277 * @returns null if `t` is a subtype of `expected`; otherwise returns an error message 10278 */ 10279 checkSubtype(expected, t) { 10280 const error = checkSubtype(expected, t); 10281 if (error) this.error(error); 10282 return error; 10283 } 10284}; 10285//#endregion 10286//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/compound_expression.mjs 10287var CompoundExpression = class CompoundExpression { 10288 constructor(name, type, evaluate, args, key) { 10289 this.name = name; 10290 this.type = type; 10291 this._evaluate = evaluate; 10292 this.args = args; 10293 this.key = key; 10294 } 10295 evaluate(ctx) { 10296 return this._evaluate(ctx, this.args, this.key); 10297 } 10298 eachChild(fn) { 10299 this.args.forEach(fn); 10300 } 10301 outputDefined() { 10302 return false; 10303 } 10304 static parse(args, context) { 10305 const op = args[0]; 10306 const definition = CompoundExpression.definitions[op]; 10307 if (!definition) return context.error(`Unknown expression "${op}". If you wanted a literal array, use ["literal", [...]].`, 0); 10308 const type = Array.isArray(definition) ? definition[0] : definition.type; 10309 const availableOverloads = Array.isArray(definition) ? [[definition[1], definition[2]]] : definition.overloads; 10310 const overloads = availableOverloads.filter(([signature]) => !Array.isArray(signature) || signature.length === args.length - 1); 10311 let signatureContext = null; 10312 for (const [params, evaluate] of overloads) { 10313 signatureContext = new ParsingContext(context.registry, isExpressionConstant, context.path, null, context.scope); 10314 const parsedArgs = []; 10315 let argParseFailed = false; 10316 for (let i = 1; i < args.length; i++) { 10317 const arg = args[i]; 10318 const expectedType = Array.isArray(params) ? params[i - 1] : params.type; 10319 const parsed = signatureContext.parse(arg, 1 + parsedArgs.length, expectedType); 10320 if (!parsed) { 10321 argParseFailed = true; 10322 break; 10323 } 10324 parsedArgs.push(parsed); 10325 } 10326 if (argParseFailed) continue; 10327 if (Array.isArray(params)) { 10328 if (params.length !== parsedArgs.length) { 10329 signatureContext.error(`Expected ${params.length} arguments, but found ${parsedArgs.length} instead.`); 10330 continue; 10331 } 10332 } 10333 for (let i = 0; i < parsedArgs.length; i++) { 10334 const expected = Array.isArray(params) ? params[i] : params.type; 10335 const arg = parsedArgs[i]; 10336 signatureContext.concat(i + 1).checkSubtype(expected, arg.type); 10337 } 10338 if (signatureContext.errors.length === 0) return new CompoundExpression(op, type, evaluate, parsedArgs, context.key); 10339 } 10340 if (overloads.length === 1) context.errors.push(...signatureContext.errors); 10341 else { 10342 const signatures = (overloads.length ? overloads : availableOverloads).map(([params]) => stringifySignature(params)).join(" | "); 10343 const actualTypes = []; 10344 for (let i = 1; i < args.length; i++) { 10345 const parsed = context.parse(args[i], 1 + actualTypes.length); 10346 if (!parsed) return null; 10347 actualTypes.push(typeToString(parsed.type)); 10348 } 10349 context.error(`Expected arguments of type ${signatures}, but found (${actualTypes.join(", ")}) instead.`); 10350 } 10351 return null; 10352 } 10353 static register(registry, definitions) { 10354 CompoundExpression.definitions = definitions; 10355 for (const name in definitions) registry[name] = CompoundExpression; 10356 } 10357}; 10358function rgba(ctx, [r, g, b, a], key) { 10359 r = r.evaluate(ctx); 10360 g = g.evaluate(ctx); 10361 b = b.evaluate(ctx); 10362 const alpha = a ? a.evaluate(ctx) : 1; 10363 const error = validateRGBA(r, g, b, alpha); 10364 if (error) throw new RuntimeError(error, key); 10365 return new Color(r / 255, g / 255, b / 255, alpha, false); 10366} 10367function has(key, obj) { 10368 return key in obj && obj[key] !== void 0; 10369} 10370function get(key, obj) { 10371 const v = obj[key]; 10372 return typeof v === "undefined" ? null : v; 10373} 10374function binarySearch(v, a, i, j) { 10375 while (i <= j) { 10376 const m = i + j >> 1; 10377 if (a[m] === v) return true; 10378 if (a[m] > v) j = m - 1; 10379 else i = m + 1; 10380 } 10381 return false; 10382} 10383function varargs(type) { 10384 return { type }; 10385} 10386CompoundExpression.register(expressions$1, { 10387 error: [ 10388 ErrorType, 10389 [StringType], 10390 (ctx, [v], key) => { 10391 throw new RuntimeError(v.evaluate(ctx), key); 10392 } 10393 ], 10394 typeof: [ 10395 StringType, 10396 [ValueType], 10397 (ctx, [v]) => typeToString(typeOf(v.evaluate(ctx))) 10398 ], 10399 "to-rgba": [ 10400 array(NumberType, 4), 10401 [ColorType], 10402 (ctx, [v]) => { 10403 const [r, g, b, a] = v.evaluate(ctx).rgb; 10404 return [ 10405 r * 255, 10406 g * 255, 10407 b * 255, 10408 a 10409 ]; 10410 } 10411 ], 10412 rgb: [ 10413 ColorType, 10414 [ 10415 NumberType, 10416 NumberType, 10417 NumberType 10418 ], 10419 rgba 10420 ], 10421 rgba: [ 10422 ColorType, 10423 [ 10424 NumberType, 10425 NumberType, 10426 NumberType, 10427 NumberType 10428 ], 10429 rgba 10430 ], 10431 has: { 10432 type: BooleanType, 10433 overloads: [[[StringType], (ctx, [key]) => has(key.evaluate(ctx), ctx.properties())], [[StringType, ObjectType], (ctx, [key, obj]) => has(key.evaluate(ctx), obj.evaluate(ctx))]] 10434 }, 10435 get: { 10436 type: ValueType, 10437 overloads: [[[StringType], (ctx, [key]) => get(key.evaluate(ctx), ctx.properties())], [[StringType, ObjectType], (ctx, [key, obj]) => get(key.evaluate(ctx), obj.evaluate(ctx))]] 10438 }, 10439 "feature-state": [ 10440 ValueType, 10441 [StringType], 10442 (ctx, [key]) => get(key.evaluate(ctx), ctx.featureState || {}) 10443 ], 10444 properties: [ 10445 ObjectType, 10446 [], 10447 (ctx) => ctx.properties() 10448 ], 10449 "geometry-type": [ 10450 StringType, 10451 [], 10452 (ctx) => ctx.geometryType() 10453 ], 10454 id: [ 10455 ValueType, 10456 [], 10457 (ctx) => ctx.id() 10458 ], 10459 zoom: [ 10460 NumberType, 10461 [], 10462 (ctx) => ctx.globals.zoom 10463 ], 10464 "heatmap-density": [ 10465 NumberType, 10466 [], 10467 (ctx) => ctx.globals.heatmapDensity || 0 10468 ], 10469 elevation: [ 10470 NumberType, 10471 [], 10472 (ctx) => ctx.globals.elevation || 0 10473 ], 10474 "line-progress": [ 10475 NumberType, 10476 [], 10477 (ctx) => ctx.globals.lineProgress || 0 10478 ], 10479 accumulated: [ 10480 ValueType, 10481 [], 10482 (ctx) => ctx.globals.accumulated === void 0 ? null : ctx.globals.accumulated 10483 ], 10484 "+": [ 10485 NumberType, 10486 varargs(NumberType), 10487 (ctx, args) => { 10488 let result = 0; 10489 for (const arg of args) result += arg.evaluate(ctx); 10490 return result; 10491 } 10492 ], 10493 "*": [ 10494 NumberType, 10495 varargs(NumberType), 10496 (ctx, args) => { 10497 let result = 1; 10498 for (const arg of args) result *= arg.evaluate(ctx); 10499 return result; 10500 } 10501 ], 10502 "-": { 10503 type: NumberType, 10504 overloads: [[[NumberType, NumberType], (ctx, [a, b]) => a.evaluate(ctx) - b.evaluate(ctx)], [[NumberType], (ctx, [a]) => -a.evaluate(ctx)]] 10505 }, 10506 "/": [ 10507 NumberType, 10508 [NumberType, NumberType], 10509 (ctx, [a, b]) => a.evaluate(ctx) / b.evaluate(ctx) 10510 ], 10511 "%": [ 10512 NumberType, 10513 [NumberType, NumberType], 10514 (ctx, [a, b]) => a.evaluate(ctx) % b.evaluate(ctx) 10515 ], 10516 ln2: [ 10517 NumberType, 10518 [], 10519 () => Math.LN2 10520 ], 10521 pi: [ 10522 NumberType, 10523 [], 10524 () => Math.PI 10525 ], 10526 e: [ 10527 NumberType, 10528 [], 10529 () => Math.E 10530 ], 10531 "^": [ 10532 NumberType, 10533 [NumberType, NumberType], 10534 (ctx, [b, e]) => Math.pow(b.evaluate(ctx), e.evaluate(ctx)) 10535 ], 10536 sqrt: [ 10537 NumberType, 10538 [NumberType], 10539 (ctx, [x]) => Math.sqrt(x.evaluate(ctx)) 10540 ], 10541 log10: [ 10542 NumberType, 10543 [NumberType], 10544 (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN10 10545 ], 10546 ln: [ 10547 NumberType, 10548 [NumberType], 10549 (ctx, [n]) => Math.log(n.evaluate(ctx)) 10550 ], 10551 log2: [ 10552 NumberType, 10553 [NumberType], 10554 (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN2 10555 ], 10556 sin: [ 10557 NumberType, 10558 [NumberType], 10559 (ctx, [n]) => Math.sin(n.evaluate(ctx)) 10560 ], 10561 cos: [ 10562 NumberType, 10563 [NumberType], 10564 (ctx, [n]) => Math.cos(n.evaluate(ctx)) 10565 ], 10566 tan: [ 10567 NumberType, 10568 [NumberType], 10569 (ctx, [n]) => Math.tan(n.evaluate(ctx)) 10570 ], 10571 asin: [ 10572 NumberType, 10573 [NumberType], 10574 (ctx, [n]) => Math.asin(n.evaluate(ctx)) 10575 ], 10576 acos: [ 10577 NumberType, 10578 [NumberType], 10579 (ctx, [n]) => Math.acos(n.evaluate(ctx)) 10580 ], 10581 atan: [ 10582 NumberType, 10583 [NumberType], 10584 (ctx, [n]) => Math.atan(n.evaluate(ctx)) 10585 ], 10586 min: [ 10587 NumberType, 10588 varargs(NumberType), 10589 (ctx, args) => Math.min(...args.map((arg) => arg.evaluate(ctx))) 10590 ], 10591 max: [ 10592 NumberType, 10593 varargs(NumberType), 10594 (ctx, args) => Math.max(...args.map((arg) => arg.evaluate(ctx))) 10595 ], 10596 abs: [ 10597 NumberType, 10598 [NumberType], 10599 (ctx, [n]) => Math.abs(n.evaluate(ctx)) 10600 ], 10601 round: [ 10602 NumberType, 10603 [NumberType], 10604 (ctx, [n]) => { 10605 const v = n.evaluate(ctx); 10606 return v < 0 ? -Math.round(-v) : Math.round(v); 10607 } 10608 ], 10609 floor: [ 10610 NumberType, 10611 [NumberType], 10612 (ctx, [n]) => Math.floor(n.evaluate(ctx)) 10613 ], 10614 ceil: [ 10615 NumberType, 10616 [NumberType], 10617 (ctx, [n]) => Math.ceil(n.evaluate(ctx)) 10618 ], 10619 "filter-==": [ 10620 BooleanType, 10621 [StringType, ValueType], 10622 (ctx, [k, v]) => ctx.properties()[k.value] === v.value 10623 ], 10624 "filter-id-==": [ 10625 BooleanType, 10626 [ValueType], 10627 (ctx, [v]) => ctx.id() === v.value 10628 ], 10629 "filter-type-==": [ 10630 BooleanType, 10631 [StringType], 10632 (ctx, [v]) => ctx.geometryType() === v.value 10633 ], 10634 "filter-<": [ 10635 BooleanType, 10636 [StringType, ValueType], 10637 (ctx, [k, v]) => { 10638 const a = ctx.properties()[k.value]; 10639 const b = v.value; 10640 return typeof a === typeof b && a < b; 10641 } 10642 ], 10643 "filter-id-<": [ 10644 BooleanType, 10645 [ValueType], 10646 (ctx, [v]) => { 10647 const a = ctx.id(); 10648 const b = v.value; 10649 return typeof a === typeof b && a < b; 10650 } 10651 ], 10652 "filter->": [ 10653 BooleanType, 10654 [StringType, ValueType], 10655 (ctx, [k, v]) => { 10656 const a = ctx.properties()[k.value]; 10657 const b = v.value; 10658 return typeof a === typeof b && a > b; 10659 } 10660 ], 10661 "filter-id->": [ 10662 BooleanType, 10663 [ValueType], 10664 (ctx, [v]) => { 10665 const a = ctx.id(); 10666 const b = v.value; 10667 return typeof a === typeof b && a > b; 10668 } 10669 ], 10670 "filter-<=": [ 10671 BooleanType, 10672 [StringType, ValueType], 10673 (ctx, [k, v]) => { 10674 const a = ctx.properties()[k.value]; 10675 const b = v.value; 10676 return typeof a === typeof b && a <= b; 10677 } 10678 ], 10679 "filter-id-<=": [ 10680 BooleanType, 10681 [ValueType], 10682 (ctx, [v]) => { 10683 const a = ctx.id(); 10684 const b = v.value; 10685 return typeof a === typeof b && a <= b; 10686 } 10687 ], 10688 "filter->=": [ 10689 BooleanType, 10690 [StringType, ValueType], 10691 (ctx, [k, v]) => { 10692 const a = ctx.properties()[k.value]; 10693 const b = v.value; 10694 return typeof a === typeof b && a >= b; 10695 } 10696 ], 10697 "filter-id->=": [ 10698 BooleanType, 10699 [ValueType], 10700 (ctx, [v]) => { 10701 const a = ctx.id(); 10702 const b = v.value; 10703 return typeof a === typeof b && a >= b; 10704 } 10705 ], 10706 "filter-has": [ 10707 BooleanType, 10708 [ValueType], 10709 (ctx, [k]) => { 10710 const key = k.value; 10711 const props = ctx.properties(); 10712 return key in props && props[key] !== void 0; 10713 } 10714 ], 10715 "filter-has-id": [ 10716 BooleanType, 10717 [], 10718 (ctx) => ctx.id() !== null && ctx.id() !== void 0 10719 ], 10720 "filter-type-in": [ 10721 BooleanType, 10722 [array(StringType)], 10723 (ctx, [v]) => v.value.indexOf(ctx.geometryType()) >= 0 10724 ], 10725 "filter-id-in": [ 10726 BooleanType, 10727 [array(ValueType)], 10728 (ctx, [v]) => v.value.indexOf(ctx.id()) >= 0 10729 ], 10730 "filter-in-small": [ 10731 BooleanType, 10732 [StringType, array(ValueType)], 10733 (ctx, [k, v]) => v.value.indexOf(ctx.properties()[k.value]) >= 0 10734 ], 10735 "filter-in-large": [ 10736 BooleanType, 10737 [StringType, array(ValueType)], 10738 (ctx, [k, v]) => binarySearch(ctx.properties()[k.value], v.value, 0, v.value.length - 1) 10739 ], 10740 all: { 10741 type: BooleanType, 10742 overloads: [[[BooleanType, BooleanType], (ctx, [a, b]) => a.evaluate(ctx) && b.evaluate(ctx)], [varargs(BooleanType), (ctx, args) => { 10743 for (const arg of args) if (!arg.evaluate(ctx)) return false; 10744 return true; 10745 }]] 10746 }, 10747 any: { 10748 type: BooleanType, 10749 overloads: [[[BooleanType, BooleanType], (ctx, [a, b]) => a.evaluate(ctx) || b.evaluate(ctx)], [varargs(BooleanType), (ctx, args) => { 10750 for (const arg of args) if (arg.evaluate(ctx)) return true; 10751 return false; 10752 }]] 10753 }, 10754 "!": [ 10755 BooleanType, 10756 [BooleanType], 10757 (ctx, [b]) => !b.evaluate(ctx) 10758 ], 10759 "is-supported-script": [ 10760 BooleanType, 10761 [StringType], 10762 (ctx, [s]) => { 10763 const isSupportedScript = ctx.globals && ctx.globals.isSupportedScript; 10764 if (isSupportedScript) return isSupportedScript(s.evaluate(ctx)); 10765 return true; 10766 } 10767 ], 10768 upcase: [ 10769 StringType, 10770 [StringType], 10771 (ctx, [s]) => s.evaluate(ctx).toUpperCase() 10772 ], 10773 downcase: [ 10774 StringType, 10775 [StringType], 10776 (ctx, [s]) => s.evaluate(ctx).toLowerCase() 10777 ], 10778 concat: [ 10779 StringType, 10780 varargs(ValueType), 10781 (ctx, args) => args.map((arg) => valueToString(arg.evaluate(ctx))).join("") 10782 ], 10783 split: [ 10784 array(StringType), 10785 [StringType, StringType], 10786 (ctx, [s, delim]) => s.evaluate(ctx).split(delim.evaluate(ctx)) 10787 ], 10788 join: [ 10789 StringType, 10790 [array(StringType), StringType], 10791 (ctx, [arr, delim]) => arr.evaluate(ctx).join(delim.evaluate(ctx)) 10792 ], 10793 "resolved-locale": [ 10794 StringType, 10795 [CollatorType], 10796 (ctx, [collator]) => collator.evaluate(ctx).resolvedLocale() 10797 ] 10798}); 10799function stringifySignature(signature) { 10800 if (Array.isArray(signature)) return `(${signature.map(typeToString).join(", ")})`; 10801 else return `(${typeToString(signature.type)}...)`; 10802} 10803function isExpressionConstant(expression) { 10804 if (expression instanceof Var) return isExpressionConstant(expression.boundExpression); 10805 else if (expression instanceof CompoundExpression && expression.name === "error") return false; 10806 else if (expression instanceof CollatorExpression) return false; 10807 else if (expression instanceof Within) return false; 10808 else if (expression instanceof Distance) return false; 10809 else if (expression instanceof GlobalState) return false; 10810 const isTypeAnnotation = expression instanceof Coercion || expression instanceof Assertion; 10811 let childrenConstant = true; 10812 expression.eachChild((child) => { 10813 if (isTypeAnnotation) childrenConstant = childrenConstant && isExpressionConstant(child); 10814 else childrenConstant = childrenConstant && child instanceof Literal; 10815 }); 10816 if (!childrenConstant) return false; 10817 return isFeatureConstant(expression) && isGlobalPropertyConstant(expression, [ 10818 "zoom", 10819 "heatmap-density", 10820 "elevation", 10821 "line-progress", 10822 "accumulated", 10823 "is-supported-script" 10824 ]); 10825} 10826function isFeatureConstant(e) { 10827 if (e instanceof CompoundExpression) { 10828 if (e.name === "get" && e.args.length === 1) return false; 10829 else if (e.name === "feature-state") return false; 10830 else if (e.name === "has" && e.args.length === 1) return false; 10831 else if (e.name === "properties" || e.name === "geometry-type" || e.name === "id") return false; 10832 else if (/^filter-/.test(e.name)) return false; 10833 } 10834 if (e instanceof Within) return false; 10835 if (e instanceof Distance) return false; 10836 let result = true; 10837 e.eachChild((arg) => { 10838 if (result && !isFeatureConstant(arg)) result = false; 10839 }); 10840 return result; 10841} 10842function isStateConstant(e) { 10843 if (e instanceof CompoundExpression) { 10844 if (e.name === "feature-state") return false; 10845 } 10846 let result = true; 10847 e.eachChild((arg) => { 10848 if (result && !isStateConstant(arg)) result = false; 10849 }); 10850 return result; 10851} 10852function isGlobalPropertyConstant(e, properties) { 10853 if (e instanceof CompoundExpression && properties.indexOf(e.name) >= 0) return false; 10854 let result = true; 10855 e.eachChild((arg) => { 10856 if (result && !isGlobalPropertyConstant(arg, properties)) result = false; 10857 }); 10858 return result; 10859} 10860//#endregion 10861//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/util/properties.mjs 10862function supportsPropertyExpression(spec) { 10863 return spec["property-type"] === "data-driven" || spec["property-type"] === "cross-faded-data-driven"; 10864} 10865function supportsZoomExpression(spec) { 10866 return !!spec.expression && spec.expression.parameters.indexOf("zoom") > -1; 10867} 10868function supportsInterpolation(spec) { 10869 return !!spec.expression && spec.expression.interpolated; 10870} 10871/** 10872* Matches a `<property>-transition` key and captures the property it belongs to. 10873*/ 10874const transitionPropertyRegExp = /^(.*)-transition$/; 10875//#endregion 10876//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/util/extend.mjs 10877function extendBy(output, ...inputs) { 10878 for (const input of inputs) for (const k in input) output[k] = input[k]; 10879 return output; 10880} 10881//#endregion 10882//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/util/get_type.mjs 10883function getType(val) { 10884 if (val instanceof Number) return "number"; 10885 else if (val instanceof String) return "string"; 10886 else if (val instanceof Boolean) return "boolean"; 10887 else if (Array.isArray(val)) return "array"; 10888 else if (val === null) return "null"; 10889 else return typeof val; 10890} 10891//#endregion 10892//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/function/index.mjs 10893function isFunction$1(value) { 10894 return typeof value === "object" && value !== null && !Array.isArray(value) && typeOf(value) === ObjectType; 10895} 10896function identityFunction(x) { 10897 return x; 10898} 10899function getParseFunction(propertySpec) { 10900 switch (propertySpec.type) { 10901 case "color": return Color.parse; 10902 case "padding": return Padding.parse; 10903 case "numberArray": return NumberArray.parse; 10904 case "colorArray": return ColorArray.parse; 10905 default: return null; 10906 } 10907} 10908function getInnerFunction(type) { 10909 switch (type) { 10910 case "exponential": return evaluateExponentialFunction; 10911 case "interval": return evaluateIntervalFunction; 10912 case "categorical": return evaluateCategoricalFunction; 10913 case "identity": return evaluateIdentityFunction; 10914 default: throw new Error(`Unknown function type "${type}"`); 10915 } 10916} 10917function createFunction(parameters, propertySpec) { 10918 const zoomAndFeatureDependent = parameters.stops && typeof parameters.stops[0][0] === "object"; 10919 const featureDependent = zoomAndFeatureDependent || parameters.property !== void 0; 10920 const zoomDependent = zoomAndFeatureDependent || !featureDependent; 10921 const type = parameters.type || (supportsInterpolation(propertySpec) ? "exponential" : "interval"); 10922 const parseFn = getParseFunction(propertySpec); 10923 if (parseFn) { 10924 parameters = extendBy({}, parameters); 10925 if (parameters.stops) parameters.stops = parameters.stops.map((stop) => { 10926 return [stop[0], parseFn(stop[1])]; 10927 }); 10928 if (parameters.default) parameters.default = parseFn(parameters.default); 10929 else parameters.default = parseFn(propertySpec.default); 10930 } 10931 if (parameters.colorSpace && !isSupportedInterpolationColorSpace(parameters.colorSpace)) throw new Error(`Unknown color space: "${parameters.colorSpace}"`); 10932 const innerFun = getInnerFunction(type); 10933 let hashedStops; 10934 let categoricalKeyType; 10935 if (type === "categorical") { 10936 hashedStops = Object.create(null); 10937 for (const stop of parameters.stops) hashedStops[stop[0]] = stop[1]; 10938 categoricalKeyType = typeof parameters.stops[0][0]; 10939 } 10940 if (zoomAndFeatureDependent) { 10941 const featureFunctions = {}; 10942 const zoomStops = []; 10943 for (let s = 0; s < parameters.stops.length; s++) { 10944 const stop = parameters.stops[s]; 10945 const zoom = stop[0].zoom; 10946 if (featureFunctions[zoom] === void 0) { 10947 featureFunctions[zoom] = { 10948 zoom, 10949 type: parameters.type, 10950 property: parameters.property, 10951 default: parameters.default, 10952 stops: [] 10953 }; 10954 zoomStops.push(zoom); 10955 } 10956 featureFunctions[zoom].stops.push([stop[0].value, stop[1]]); 10957 } 10958 const featureFunctionStops = []; 10959 for (const z of zoomStops) featureFunctionStops.push([featureFunctions[z].zoom, createFunction(featureFunctions[z], propertySpec)]); 10960 const interpolationType = { name: "linear" }; 10961 return { 10962 kind: "composite", 10963 interpolationType, 10964 interpolationFactor: Interpolate.interpolationFactor.bind(void 0, interpolationType), 10965 zoomStops: featureFunctionStops.map((s) => s[0]), 10966 evaluate({ zoom }, properties) { 10967 return evaluateExponentialFunction({ 10968 stops: featureFunctionStops, 10969 base: parameters.base 10970 }, propertySpec, zoom).evaluate(zoom, properties); 10971 } 10972 }; 10973 } else if (zoomDependent) { 10974 const interpolationType = type === "exponential" ? { 10975 name: "exponential", 10976 base: parameters.base !== void 0 ? parameters.base : 1 10977 } : null; 10978 return { 10979 kind: "camera", 10980 interpolationType, 10981 interpolationFactor: Interpolate.interpolationFactor.bind(void 0, interpolationType), 10982 zoomStops: parameters.stops.map((s) => s[0]), 10983 evaluate: ({ zoom }) => innerFun(parameters, propertySpec, zoom, hashedStops, categoricalKeyType) 10984 }; 10985 } else return { 10986 kind: "source", 10987 evaluate(_, feature) { 10988 const value = feature && feature.properties ? feature.properties[parameters.property] : void 0; 10989 if (value === void 0) return coalesce$1(parameters.default, propertySpec.default); 10990 return innerFun(parameters, propertySpec, value, hashedStops, categoricalKeyType); 10991 } 10992 }; 10993} 10994function coalesce$1(a, b, c) { 10995 if (a !== void 0) return a; 10996 if (b !== void 0) return b; 10997 if (c !== void 0) return c; 10998} 10999function evaluateCategoricalFunction(parameters, propertySpec, input, hashedStops, keyType) { 11000 return coalesce$1(typeof input === keyType ? hashedStops[input] : void 0, parameters.default, propertySpec.default); 11001} 11002function evaluateIntervalFunction(parameters, propertySpec, input) { 11003 if (getType(input) !== "number") return coalesce$1(parameters.default, propertySpec.default); 11004 const n = parameters.stops.length; 11005 if (n === 1) return parameters.stops[0][1]; 11006 if (input <= parameters.stops[0][0]) return parameters.stops[0][1]; 11007 if (input >= parameters.stops[n - 1][0]) return parameters.stops[n - 1][1]; 11008 const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input, ""); 11009 return parameters.stops[index][1]; 11010} 11011function evaluateExponentialFunction(parameters, propertySpec, input) { 11012 const base = parameters.base !== void 0 ? parameters.base : 1; 11013 if (getType(input) !== "number") return coalesce$1(parameters.default, propertySpec.default); 11014 const n = parameters.stops.length; 11015 if (n === 1) return parameters.stops[0][1]; 11016 if (input <= parameters.stops[0][0]) return parameters.stops[0][1]; 11017 if (input >= parameters.stops[n - 1][0]) return parameters.stops[n - 1][1]; 11018 const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input, ""); 11019 const t = interpolationFactor(input, base, parameters.stops[index][0], parameters.stops[index + 1][0]); 11020 const outputLower = parameters.stops[index][1]; 11021 const outputUpper = parameters.stops[index + 1][1]; 11022 const interp = interpolateFactory[propertySpec.type] || identityFunction; 11023 if (typeof outputLower.evaluate === "function") return { evaluate(...args) { 11024 const evaluatedLower = outputLower.evaluate.apply(void 0, args); 11025 const evaluatedUpper = outputUpper.evaluate.apply(void 0, args); 11026 if (evaluatedLower === void 0 || evaluatedUpper === void 0) return; 11027 return interp(evaluatedLower, evaluatedUpper, t, parameters.colorSpace); 11028 } }; 11029 return interp(outputLower, outputUpper, t, parameters.colorSpace); 11030} 11031function evaluateIdentityFunction(parameters, propertySpec, input) { 11032 switch (propertySpec.type) { 11033 case "color": 11034 input = Color.parse(input); 11035 break; 11036 case "formatted": 11037 input = Formatted.fromString(input.toString()); 11038 break; 11039 case "resolvedImage": 11040 input = ResolvedImage.fromString(input.toString()); 11041 break; 11042 case "padding": 11043 input = Padding.parse(input); 11044 break; 11045 case "colorArray": 11046 input = ColorArray.parse(input); 11047 break; 11048 case "numberArray": 11049 input = NumberArray.parse(input); 11050 break; 11051 default: if (getType(input) !== propertySpec.type && (propertySpec.type !== "enum" || !propertySpec.values[input])) input = void 0; 11052 } 11053 return coalesce$1(input, parameters.default, propertySpec.default); 11054} 11055/** 11056* Returns a ratio that can be used to interpolate between exponential function 11057* stops. 11058* 11059* How it works: 11060* Two consecutive stop values define a (scaled and shifted) exponential 11061* function `f(x) = a * base^x + b`, where `base` is the user-specified base, 11062* and `a` and `b` are constants affording sufficient degrees of freedom to fit 11063* the function to the given stops. 11064* 11065* Here's a bit of algebra that lets us compute `f(x)` directly from the stop 11066* values without explicitly solving for `a` and `b`: 11067* 11068* First stop value: `f(x0) = y0 = a * base^x0 + b` 11069* Second stop value: `f(x1) = y1 = a * base^x1 + b` 11070* => `y1 - y0 = a(base^x1 - base^x0)` 11071* => `a = (y1 - y0)/(base^x1 - base^x0)` 11072* 11073* Desired value: `f(x) = y = a * base^x + b` 11074* => `f(x) = y0 + a * (base^x - base^x0)` 11075* 11076* From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a 11077* little algebra: 11078* ``` 11079* a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0) 11080* = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0) 11081* ``` 11082* 11083* If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have 11084* `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as 11085* an interpolation factor between the two stops' output values. 11086* 11087* (Note: a slightly different form for `ratio`, 11088* `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer 11089* expensive `Math.pow()` operations.) 11090* 11091* @private 11092*/ 11093function interpolationFactor(input, base, lowerValue, upperValue) { 11094 const difference = upperValue - lowerValue; 11095 const progress = input - lowerValue; 11096 if (difference === 0) return 0; 11097 else if (base === 1) return progress / difference; 11098 else return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1); 11099} 11100//#endregion 11101//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/util/result.mjs 11102function success(value) { 11103 return { 11104 result: "success", 11105 value 11106 }; 11107} 11108function error(value) { 11109 return { 11110 result: "error", 11111 value 11112 }; 11113} 11114//#endregion 11115//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/index.mjs 11116var StyleExpression = class { 11117 constructor(expression, rootKey, propertySpec, globalState) { 11118 this.expression = expression; 11119 this._warningHistory = {}; 11120 this._evaluator = new EvaluationContext(); 11121 this._defaultValue = propertySpec ? getDefaultValue(propertySpec) : null; 11122 this._enumValues = propertySpec && propertySpec.type === "enum" ? propertySpec.values : null; 11123 this._globalState = globalState; 11124 this._rootKey = rootKey; 11125 } 11126 evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) { 11127 if (this._globalState) globals = addGlobalState(globals, this._globalState); 11128 this._evaluator.globals = globals; 11129 this._evaluator.feature = feature; 11130 this._evaluator.featureState = featureState; 11131 this._evaluator.canonical = canonical; 11132 this._evaluator.availableImages = availableImages || null; 11133 this._evaluator.formattedSection = formattedSection; 11134 return this.expression.evaluate(this._evaluator); 11135 } 11136 evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) { 11137 if (this._globalState) globals = addGlobalState(globals, this._globalState); 11138 this._evaluator.globals = globals; 11139 this._evaluator.feature = feature || null; 11140 this._evaluator.featureState = featureState || null; 11141 this._evaluator.canonical = canonical; 11142 this._evaluator.availableImages = availableImages || null; 11143 this._evaluator.formattedSection = formattedSection || null; 11144 try { 11145 const val = this.expression.evaluate(this._evaluator); 11146 if (val === null || val === void 0 || typeof val === "number" && val !== val) return this._defaultValue; 11147 if (this._enumValues && !(val in this._enumValues)) throw new RuntimeError(`Expected value to be one of ${Object.keys(this._enumValues).map((v) => JSON.stringify(v)).join(", ")}, but found ${JSON.stringify(val)} instead.`, ""); 11148 return val; 11149 } catch (e) { 11150 const path = e instanceof RuntimeError ? e.path : ""; 11151 const dedupKey = `${path}|${e.message}`; 11152 if (!this._warningHistory[dedupKey]) { 11153 this._warningHistory[dedupKey] = true; 11154 if (typeof console !== "undefined") console.warn(formatRuntimeWarning(this._rootKey, path, e.message, this._defaultValue)); 11155 } 11156 return this._defaultValue; 11157 } 11158 } 11159}; 11160/** 11161* Builds the warning logged when an expression or legacy function fails at 11162* evaluation: a `rootKey + index path` location prefix, plus the fallback 11163* value being used. 11164* @param rootKey Caller-supplied location of the expression in the style JSON 11165* @param path Index path of the throwing sub-expression ('' for the root) 11166* @param message The error message from the failed evaluation 11167* @param defaultValue The value being fallen back to 11168* @returns The formatted warning string 11169*/ 11170function formatRuntimeWarning(rootKey, path, message, defaultValue) { 11171 return `${rootKey}${path}: ${message}${defaultValue == null ? "" : ` Falling back to ${String(defaultValue)}.`}`; 11172} 11173/** 11174* Rejects a missing or empty root key. The location prefix is what makes 11175* runtime warnings actionable, so callers must always supply one; failing 11176* here surfaces the programmer error at style load instead of producing 11177* unattributable warnings at render time. 11178* @param rootKey The root key to check 11179*/ 11180function assertRootKey(rootKey) { 11181 if (!rootKey) throw new Error("rootKey must identify the location of the expression in the style JSON, e.g. \"layers[3].paint.line-width\"."); 11182} 11183function isExpression(expression) { 11184 return Array.isArray(expression) && expression.length > 0 && typeof expression[0] === "string" && expression[0] in expressions$1; 11185} 11186/** 11187* Parse and typecheck the given style spec JSON expression. If 11188* options.defaultValue is provided, then the resulting StyleExpression's 11189* `evaluate()` method will handle errors by logging a warning (once per 11190* message) and returning the default value. Otherwise, it will throw 11191* evaluation errors. 11192* 11193* @private 11194*/ 11195function createExpression(expression, rootKey, propertySpec, globalState) { 11196 assertRootKey(rootKey); 11197 const parser = new ParsingContext(expressions$1, isExpressionConstant, [], propertySpec ? getExpectedType(propertySpec) : void 0); 11198 const parsed = parser.parse(expression, void 0, void 0, void 0, propertySpec && propertySpec.type === "string" ? { typeAnnotation: "coerce" } : void 0); 11199 if (!parsed) return error(parser.errors); 11200 return success(new StyleExpression(parsed, rootKey, propertySpec, globalState)); 11201} 11202var ZoomConstantExpression = class { 11203 constructor(kind, expression, globalState) { 11204 this.kind = kind; 11205 this._styleExpression = expression; 11206 this.isStateDependent = kind !== "constant" && !isStateConstant(expression.expression); 11207 this.globalStateRefs = findGlobalStateRefs(expression.expression); 11208 this._globalState = globalState; 11209 } 11210 evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) { 11211 if (this._globalState) globals = addGlobalState(globals, this._globalState); 11212 return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection); 11213 } 11214 evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) { 11215 if (this._globalState) globals = addGlobalState(globals, this._globalState); 11216 return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection); 11217 } 11218}; 11219var ZoomDependentExpression = class { 11220 constructor(kind, expression, zoomStops, interpolationType, globalState) { 11221 this.kind = kind; 11222 this.zoomStops = zoomStops; 11223 this._styleExpression = expression; 11224 this.isStateDependent = kind !== "camera" && !isStateConstant(expression.expression); 11225 this.globalStateRefs = findGlobalStateRefs(expression.expression); 11226 this.interpolationType = interpolationType; 11227 this._globalState = globalState; 11228 } 11229 evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) { 11230 if (this._globalState) globals = addGlobalState(globals, this._globalState); 11231 return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection); 11232 } 11233 evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) { 11234 if (this._globalState) globals = addGlobalState(globals, this._globalState); 11235 return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection); 11236 } 11237 interpolationFactor(input, lower, upper) { 11238 if (this.interpolationType) return Interpolate.interpolationFactor(this.interpolationType, input, lower, upper); 11239 else return 0; 11240 } 11241}; 11242function isZoomExpression(expression) { 11243 return expression._styleExpression !== void 0; 11244} 11245function createPropertyExpression(expressionInput, rootKey, propertySpec, globalState) { 11246 const expression = createExpression(expressionInput, rootKey, propertySpec, globalState); 11247 if (expression.result === "error") return expression; 11248 const parsed = expression.value.expression; 11249 const isFeatureConstantResult = isFeatureConstant(parsed); 11250 if (!isFeatureConstantResult && !supportsPropertyExpression(propertySpec)) return error([new ExpressionParsingError("", "data expressions not supported")]); 11251 const isZoomConstant = isGlobalPropertyConstant(parsed, ["zoom"]); 11252 if (!isZoomConstant && !supportsZoomExpression(propertySpec)) return error([new ExpressionParsingError("", "zoom expressions not supported")]); 11253 const zoomCurve = findZoomCurve(parsed); 11254 if (!zoomCurve && !isZoomConstant) return error([new ExpressionParsingError("", "\"zoom\" expression may only be used as input to a top-level \"step\" or \"interpolate\" expression.")]); 11255 else if (zoomCurve instanceof ExpressionParsingError) return error([zoomCurve]); 11256 else if (zoomCurve instanceof Interpolate && !supportsInterpolation(propertySpec)) return error([new ExpressionParsingError("", "\"interpolate\" expressions cannot be used with this property")]); 11257 if (!zoomCurve) return success(isFeatureConstantResult ? new ZoomConstantExpression("constant", expression.value, globalState) : new ZoomConstantExpression("source", expression.value, globalState)); 11258 const interpolationType = zoomCurve instanceof Interpolate ? zoomCurve.interpolation : void 0; 11259 return success(isFeatureConstantResult ? new ZoomDependentExpression("camera", expression.value, zoomCurve.labels, interpolationType, globalState) : new ZoomDependentExpression("composite", expression.value, zoomCurve.labels, interpolationType, globalState)); 11260} 11261var StylePropertyFunction = class StylePropertyFunction { 11262 constructor(parameters, rootKey, specification) { 11263 this.isStateDependent = false; 11264 this.globalStateRefs = /* @__PURE__ */ new Set(); 11265 this._globalState = null; 11266 assertRootKey(rootKey); 11267 this._parameters = parameters; 11268 this._specification = specification; 11269 this._rootKey = rootKey; 11270 this._defaultValue = getDefaultValue(specification); 11271 this._warningHistory = {}; 11272 const fn = createFunction(this._parameters, this._specification); 11273 this.kind = fn.kind; 11274 this.interpolationFactor = fn.interpolationFactor; 11275 this.zoomStops = fn.zoomStops; 11276 this.interpolationType = fn.interpolationType; 11277 this._innerEvaluate = fn.evaluate; 11278 } 11279 /** 11280 * Evaluates the legacy function, handling a runtime throw (e.g. interpolating 11281 * mismatched value types) by warning with the property location and falling 11282 * back to the spec default, mirroring {@link StyleExpression.evaluate}. 11283 * @param globals Global evaluation properties (e.g. zoom) 11284 * @param feature The feature being evaluated, if any 11285 * @returns The function result, or the spec default if evaluation throws 11286 */ 11287 evaluate(globals, feature) { 11288 try { 11289 return this._innerEvaluate(globals, feature); 11290 } catch (e) { 11291 const message = e instanceof Error ? e.message : String(e); 11292 const dedupKey = `|${message}`; 11293 if (!this._warningHistory[dedupKey]) { 11294 this._warningHistory[dedupKey] = true; 11295 if (typeof console !== "undefined") console.warn(formatRuntimeWarning(this._rootKey, "", message, this._defaultValue)); 11296 } 11297 return this._defaultValue; 11298 } 11299 } 11300 static deserialize(serialized) { 11301 return new StylePropertyFunction(serialized._parameters, serialized._rootKey, serialized._specification); 11302 } 11303 static serialize(input) { 11304 return { 11305 _parameters: input._parameters, 11306 _specification: input._specification, 11307 _rootKey: input._rootKey 11308 }; 11309 } 11310}; 11311function normalizePropertyExpression(value, rootKey, specification, globalState) { 11312 if (isFunction$1(value)) return new StylePropertyFunction(value, rootKey, specification); 11313 else if (isExpression(value)) { 11314 const expression = createPropertyExpression(value, rootKey, specification, globalState); 11315 if (expression.result === "error") throw new Error(expression.value.map((err) => `${err.key}: ${err.message}`).join(", ")); 11316 return expression.value; 11317 } else { 11318 let constant = value; 11319 if (specification.type === "color" && typeof value === "string") constant = Color.parse(value); 11320 else if (specification.type === "padding" && (typeof value === "number" || Array.isArray(value))) constant = Padding.parse(value); 11321 else if (specification.type === "numberArray" && (typeof value === "number" || Array.isArray(value))) constant = NumberArray.parse(value); 11322 else if (specification.type === "colorArray" && (typeof value === "string" || Array.isArray(value))) constant = ColorArray.parse(value); 11323 else if (specification.type === "variableAnchorOffsetCollection" && Array.isArray(value)) constant = VariableAnchorOffsetCollection.parse(value); 11324 else if (specification.type === "projectionDefinition" && typeof value === "string") constant = ProjectionDefinition.parse(value); 11325 return { 11326 globalStateRefs: /* @__PURE__ */ new Set(), 11327 _globalState: null, 11328 kind: "constant", 11329 evaluate: () => constant 11330 }; 11331 } 11332} 11333function findZoomCurve(expression) { 11334 let result = null; 11335 if (expression instanceof Let) result = findZoomCurve(expression.result); 11336 else if (expression instanceof Coalesce) for (const arg of expression.args) { 11337 result = findZoomCurve(arg); 11338 if (result) break; 11339 } 11340 else if ((expression instanceof Step || expression instanceof Interpolate) && expression.input instanceof CompoundExpression && expression.input.name === "zoom") result = expression; 11341 if (result instanceof ExpressionParsingError) return result; 11342 expression.eachChild((child) => { 11343 const childResult = findZoomCurve(child); 11344 if (childResult instanceof ExpressionParsingError) result = childResult; 11345 else if (!result && childResult) result = new ExpressionParsingError("", "\"zoom\" expression may only be used as input to a top-level \"step\" or \"interpolate\" expression."); 11346 else if (result && childResult && result !== childResult) result = new ExpressionParsingError("", "Only one zoom-based \"step\" or \"interpolate\" subexpression may be used in an expression."); 11347 }); 11348 return result; 11349} 11350function findGlobalStateRefs(expression, results = /* @__PURE__ */ new Set()) { 11351 if (expression instanceof GlobalState) results.add(expression.key); 11352 expression.eachChild((childExpression) => { 11353 findGlobalStateRefs(childExpression, results); 11354 }); 11355 return results; 11356} 11357function getExpectedType(spec) { 11358 const types = { 11359 color: ColorType, 11360 string: StringType, 11361 number: NumberType, 11362 enum: StringType, 11363 boolean: BooleanType, 11364 formatted: FormattedType, 11365 padding: PaddingType, 11366 numberArray: NumberArrayType, 11367 colorArray: ColorArrayType, 11368 projectionDefinition: ProjectionDefinitionType, 11369 resolvedImage: ResolvedImageType, 11370 variableAnchorOffsetCollection: VariableAnchorOffsetCollectionType 11371 }; 11372 if (spec.type === "array") return array(types[spec.value] || ValueType, spec.length); 11373 return types[spec.type]; 11374} 11375function getDefaultValue(spec) { 11376 if (spec.type === "color" && isFunction$1(spec.default)) return new Color(0, 0, 0, 0); 11377 switch (spec.type) { 11378 case "color": return Color.parse(spec.default) || null; 11379 case "padding": return Padding.parse(spec.default) || null; 11380 case "numberArray": return NumberArray.parse(spec.default) || null; 11381 case "colorArray": return ColorArray.parse(spec.default) || null; 11382 case "variableAnchorOffsetCollection": return VariableAnchorOffsetCollection.parse(spec.default) || null; 11383 case "projectionDefinition": return ProjectionDefinition.parse(spec.default) || null; 11384 default: return spec.default === void 0 ? null : spec.default; 11385 } 11386} 11387function addGlobalState(globals, globalState) { 11388 const { zoom, heatmapDensity, elevation, lineProgress, isSupportedScript, accumulated } = globals ?? {}; 11389 return { 11390 zoom, 11391 heatmapDensity, 11392 elevation, 11393 lineProgress, 11394 isSupportedScript, 11395 accumulated, 11396 globalState 11397 }; 11398} 11399//#endregion 11400//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/feature_filter/index.mjs 11401function classifyChildren(children) { 11402 let sawLegacy = false; 11403 for (const child of children) { 11404 const classification = classifyFilter(child); 11405 if (classification === "expression") return "expression"; 11406 if (classification === "legacy") sawLegacy = true; 11407 } 11408 return sawLegacy ? "legacy" : "neutral"; 11409} 11410function classifyFilter(filter) { 11411 if (typeof filter === "boolean") return "neutral"; 11412 if (!Array.isArray(filter) || filter.length === 0) return "legacy"; 11413 switch (filter[0]) { 11414 case "has": 11415 if (filter.length < 2 || filter[1] === "$id" || filter[1] === "$type") return "legacy"; 11416 return filter.length === 2 ? "neutral" : "expression"; 11417 case "in": return filter.length >= 3 && (typeof filter[1] !== "string" || Array.isArray(filter[2])) ? "expression" : "legacy"; 11418 case "!in": 11419 case "!has": return "legacy"; 11420 case "==": 11421 case "!=": 11422 case ">": 11423 case ">=": 11424 case "<": 11425 case "<=": return filter.length !== 3 || Array.isArray(filter[1]) || Array.isArray(filter[2]) ? "expression" : "legacy"; 11426 case "none": return "legacy"; 11427 case "any": 11428 case "all": return classifyChildren(filter.slice(1)); 11429 default: return "expression"; 11430 } 11431} 11432function isExpressionFilter(filter) { 11433 return classifyFilter(filter) !== "legacy"; 11434} 11435function getFilterPropertyExpression(property) { 11436 if (property === "$type") return ["geometry-type"]; 11437 if (property === "$id") return ["id"]; 11438 return ["get", property]; 11439} 11440function getLegacyFilterExpressionSuggestion(filter) { 11441 switch (filter[0]) { 11442 case "==": 11443 case "!=": 11444 case "<": 11445 case "<=": 11446 case ">": 11447 case ">=": 11448 if (filter.length !== 3 || typeof filter[1] !== "string") return null; 11449 return [ 11450 filter[0], 11451 getFilterPropertyExpression(filter[1]), 11452 filter[2] 11453 ]; 11454 case "in": 11455 case "!in": { 11456 if (filter.length < 2 || typeof filter[1] !== "string") return null; 11457 const expression = [ 11458 "in", 11459 getFilterPropertyExpression(filter[1]), 11460 ["literal", filter.slice(2)] 11461 ]; 11462 return filter[0] === "!in" ? ["!", expression] : expression; 11463 } 11464 case "has": 11465 case "!has": { 11466 if (filter.length !== 2 || typeof filter[1] !== "string") return null; 11467 if (filter[1] === "$type" || filter[1] === "$id") return null; 11468 const expression = ["has", filter[1]]; 11469 return filter[0] === "!has" ? ["!", expression] : expression; 11470 } 11471 default: return null; 11472 } 11473} 11474function getMixedFilterMessage(filter) { 11475 if ((filter[0] === "<" || filter[0] === "<=" || filter[0] === ">" || filter[0] === ">=") && filter[1] === "$type") return `"$type" cannot be use with operator "${filter[0]}"`; 11476 const suggestion = getLegacyFilterExpressionSuggestion(filter); 11477 if (suggestion) return `Mixing deprecated filter syntax with expression syntax is not supported. Replace ${JSON.stringify(filter)} with ${JSON.stringify(suggestion)}.`; 11478 return `Mixing deprecated filter syntax with expression syntax is not supported. Convert ${JSON.stringify(filter)} to expression syntax.`; 11479} 11480function checkChild(index, path, filter) { 11481 const child = filter[index]; 11482 if (!Array.isArray(child)) return null; 11483 if (!isExpressionFilter(child)) return { 11484 path: path.concat(index), 11485 legacyFilter: child 11486 }; 11487 return findMixedLegacyFilter(child, path.concat(index)); 11488} 11489function findMixedLegacyFilter(filter, path = []) { 11490 if (!Array.isArray(filter) || filter.length < 1) return null; 11491 switch (filter[0]) { 11492 case "all": 11493 case "any": 11494 case "none": 11495 for (let i = 1; i < filter.length; i++) { 11496 const diagnostic = checkChild(i, path, filter); 11497 if (diagnostic) return diagnostic; 11498 } 11499 break; 11500 case "!": { 11501 const diagnostic = checkChild(1, path, filter); 11502 if (diagnostic) return diagnostic; 11503 break; 11504 } 11505 case "case": for (let i = 1; i < filter.length - 1; i += 2) { 11506 const diagnostic = checkChild(i, path, filter); 11507 if (diagnostic) return diagnostic; 11508 } 11509 } 11510 return null; 11511} 11512function warnAboutMixedLegacyFilter(filter, rootKey) { 11513 const diagnostic = findMixedLegacyFilter(filter); 11514 if (!diagnostic || typeof console === "undefined") return; 11515 const path = diagnostic.path.map((index) => `[${index}]`).join(""); 11516 console.warn(`${rootKey}${path}: ${getMixedFilterMessage(diagnostic.legacyFilter)}`); 11517} 11518const filterSpec = { 11519 type: "boolean", 11520 default: false, 11521 transition: false, 11522 "property-type": "data-driven", 11523 expression: { 11524 interpolated: false, 11525 parameters: ["zoom", "feature"] 11526 } 11527}; 11528/** 11529* Given a filter expressed as nested arrays, return a new function 11530* that evaluates whether a given feature (with a .properties or .tags property) 11531* passes its test. 11532* 11533* @private 11534* @param filter MapLibre filter 11535* @param rootKey Location of the filter in the style JSON (e.g. `layers[3].filter`), 11536* used to prefix runtime warnings 11537* @param [globalState] Global state object to be used for evaluating 'global-state' expressions 11538* @returns filter-evaluating function 11539*/ 11540function featureFilter(filter, rootKey, globalState) { 11541 if (filter === null || filter === void 0) return { 11542 filter: () => true, 11543 needGeometry: false, 11544 getGlobalStateRefs: () => /* @__PURE__ */ new Set() 11545 }; 11546 if (!isExpressionFilter(filter)) filter = convertFilter$1(filter); 11547 else warnAboutMixedLegacyFilter(filter, rootKey); 11548 const compiled = createExpression(filter, rootKey, filterSpec, globalState); 11549 if (compiled.result === "error") throw new Error(compiled.value.map((err) => `${err.key}: ${err.message}`).join(", ")); 11550 else return { 11551 filter: (globalProperties, feature, canonical) => compiled.value.evaluate(globalProperties, feature, {}, canonical), 11552 needGeometry: geometryNeeded(filter), 11553 getGlobalStateRefs: () => findGlobalStateRefs(compiled.value.expression) 11554 }; 11555} 11556function compare(a, b) { 11557 return a < b ? -1 : a > b ? 1 : 0; 11558} 11559function geometryNeeded(filter) { 11560 if (!Array.isArray(filter)) return false; 11561 if (filter[0] === "within" || filter[0] === "distance") return true; 11562 for (let index = 1; index < filter.length; index++) if (geometryNeeded(filter[index])) return true; 11563 return false; 11564} 11565function convertFilter$1(filter) { 11566 if (!filter) return true; 11567 const op = filter[0]; 11568 if (filter.length <= 1) return op !== "any"; 11569 return op === "==" ? convertComparisonOp$1(filter[1], filter[2], "==") : op === "!=" ? convertNegation(convertComparisonOp$1(filter[1], filter[2], "==")) : op === "<" || op === ">" || op === "<=" || op === ">=" ? convertComparisonOp$1(filter[1], filter[2], op) : op === "any" ? convertDisjunctionOp(filter.slice(1)) : op === "all" ? ["all"].concat(filter.slice(1).map(convertFilter$1)) : op === "none" ? ["all"].concat(filter.slice(1).map(convertFilter$1).map(convertNegation)) : op === "in" ? convertInOp$1(filter[1], filter.slice(2)) : op === "!in" ? convertNegation(convertInOp$1(filter[1], filter.slice(2))) : op === "has" ? convertHasOp$1(filter[1]) : op === "!has" ? convertNegation(convertHasOp$1(filter[1])) : true; 11570} 11571function convertComparisonOp$1(property, value, op) { 11572 switch (property) { 11573 case "$type": return [`filter-type-${op}`, value]; 11574 case "$id": return [`filter-id-${op}`, value]; 11575 default: return [ 11576 `filter-${op}`, 11577 property, 11578 value 11579 ]; 11580 } 11581} 11582function convertDisjunctionOp(filters) { 11583 return ["any"].concat(filters.map(convertFilter$1)); 11584} 11585function convertInOp$1(property, values) { 11586 if (values.length === 0) return false; 11587 switch (property) { 11588 case "$type": return ["filter-type-in", ["literal", values]]; 11589 case "$id": return ["filter-id-in", ["literal", values]]; 11590 default: if (values.length > 200 && !values.some((v) => typeof v !== typeof values[0])) return [ 11591 "filter-in-large", 11592 property, 11593 ["literal", values.sort(compare)] 11594 ]; 11595 else return [ 11596 "filter-in-small", 11597 property, 11598 ["literal", values] 11599 ]; 11600 } 11601} 11602function convertHasOp$1(property) { 11603 switch (property) { 11604 case "$type": return true; 11605 case "$id": return ["filter-has-id"]; 11606 default: return ["filter-has", property]; 11607 } 11608} 11609function convertNegation(filter) { 11610 return ["!", filter]; 11611} 11612//#endregion 11613//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/group_by_layout.mjs 11614function stringify$1(obj) { 11615 const type = typeof obj; 11616 if (type === "number" || type === "boolean" || type === "string" || obj === void 0 || obj === null) return JSON.stringify(obj); 11617 if (Array.isArray(obj)) { 11618 let str = "["; 11619 for (const val of obj) str += `${stringify$1(val)},`; 11620 return `${str}]`; 11621 } 11622 const keys = Object.keys(obj).sort(); 11623 let str = "{"; 11624 for (let i = 0; i < keys.length; i++) str += `${JSON.stringify(keys[i])}:${stringify$1(obj[keys[i]])},`; 11625 return `${str}}`; 11626} 11627function getKey$1(layer) { 11628 let key = ""; 11629 for (const k of refProperties) key += `/${stringify$1(layer[k])}`; 11630 return key; 11631} 11632/** 11633* Groups layers by their layout-affecting properties. 11634* These are the properties that were formerly used by explicit `ref` mechanism 11635* for layers: 'type', 'source', 'source-layer', 'minzoom', 'maxzoom', 11636* 'filter', and 'layout'. 11637* 11638* The input is not modified. The output layers are references to the 11639* input layers. 11640* 11641* @param layers - an array of {@link LayerSpecification}. 11642* @param cachedKeys - an object to keep already calculated keys. 11643* @returns an array of arrays of {@link LayerSpecification} objects, where each inner array 11644* contains layers that share the same layout-affecting properties. 11645*/ 11646function groupByLayout(layers, cachedKeys) { 11647 const groups = {}; 11648 for (let i = 0; i < layers.length; i++) { 11649 const k = cachedKeys && cachedKeys[layers[i].id] || getKey$1(layers[i]); 11650 if (cachedKeys) cachedKeys[layers[i].id] = k; 11651 let group = groups[k]; 11652 if (!group) group = groups[k] = []; 11653 group.push(layers[i]); 11654 } 11655 const result = []; 11656 for (const k in groups) result.push(groups[k]); 11657 return result; 11658} 11659//#endregion 11660//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/empty.mjs 11661function emptyStyle() { 11662 const style = {}; 11663 const version = latest["$version"]; 11664 for (const styleKey in latest["$root"]) { 11665 const specification = latest["$root"][styleKey]; 11666 if (specification.required) { 11667 let value = null; 11668 if (styleKey === "version") value = version; 11669 else if (specification.type === "array") value = []; 11670 else value = {}; 11671 if (value != null) style[styleKey] = value; 11672 } 11673 } 11674 return style; 11675} 11676//#endregion 11677//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_constants.mjs 11678function validateConstants(options) { 11679 const key = options.key; 11680 const constants = options.value; 11681 if (constants) return [new ValidationError(key, constants, "constants have been deprecated as of v8")]; 11682 else return []; 11683} 11684//#endregion 11685//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/util/unbundle_jsonlint.mjs 11686function unbundle(value) { 11687 if (value instanceof Number || value instanceof String || value instanceof Boolean) return value.valueOf(); 11688 else return value; 11689} 11690function deepUnbundle(value) { 11691 if (Array.isArray(value)) return value.map(deepUnbundle); 11692 else if (value instanceof Object && !(value instanceof Number || value instanceof String || value instanceof Boolean)) { 11693 const unbundledValue = {}; 11694 for (const key in value) unbundledValue[key] = deepUnbundle(value[key]); 11695 return unbundledValue; 11696 } 11697 return unbundle(value); 11698} 11699//#endregion 11700//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_object.mjs 11701function validateObject(options) { 11702 const key = options.key; 11703 const object = options.value; 11704 const elementSpecs = options.valueSpec || {}; 11705 const elementValidators = options.objectElementValidators || {}; 11706 const style = options.style; 11707 const styleSpec = options.styleSpec; 11708 const validateSpec = options.validateSpec; 11709 let errors = []; 11710 const type = getType(object); 11711 if (type !== "object") return [new ValidationError(key, object, `object expected, ${type} found`)]; 11712 for (const objectKey in object) { 11713 const elementSpecKey = objectKey.split(".")[0]; 11714 const elementSpec = getOwn(elementSpecs, elementSpecKey) || elementSpecs["*"]; 11715 let validateElement; 11716 if (getOwn(elementValidators, elementSpecKey)) validateElement = elementValidators[elementSpecKey]; 11717 else if (getOwn(elementSpecs, elementSpecKey)) { 11718 if (object[objectKey] === void 0) continue; 11719 validateElement = validateSpec; 11720 } else if (elementValidators["*"]) validateElement = elementValidators["*"]; 11721 else if (elementSpecs["*"]) validateElement = validateSpec; 11722 else { 11723 errors.push(new ValidationError(key, object[objectKey], `unknown property "${objectKey}"`)); 11724 continue; 11725 } 11726 errors = errors.concat(validateElement({ 11727 key: (key ? `${key}.` : key) + objectKey, 11728 value: object[objectKey], 11729 valueSpec: elementSpec, 11730 style, 11731 styleSpec, 11732 object, 11733 objectKey, 11734 validateSpec 11735 }, object)); 11736 } 11737 for (const elementSpecKey in elementSpecs) { 11738 if (elementValidators[elementSpecKey]) continue; 11739 if (elementSpecs[elementSpecKey].required && elementSpecs[elementSpecKey]["default"] === void 0 && object[elementSpecKey] === void 0) errors.push(new ValidationError(key, object, `missing required property "${elementSpecKey}"`)); 11740 } 11741 return errors; 11742} 11743//#endregion 11744//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_array.mjs 11745function validateArray(options) { 11746 const array = options.value; 11747 const arraySpec = options.valueSpec; 11748 const validateSpec = options.validateSpec; 11749 const style = options.style; 11750 const styleSpec = options.styleSpec; 11751 const key = options.key; 11752 const validateArrayElement = options.arrayElementValidator || validateSpec; 11753 if (getType(array) !== "array") return [new ValidationError(key, array, `array expected, ${getType(array)} found`)]; 11754 if (arraySpec.length && array.length !== arraySpec.length) return [new ValidationError(key, array, `array length ${arraySpec.length} expected, length ${array.length} found`)]; 11755 let arrayElementSpec = { 11756 type: arraySpec.value, 11757 values: arraySpec.values 11758 }; 11759 if (styleSpec.$version < 7) arrayElementSpec["function"] = arraySpec.function; 11760 if (getType(arraySpec.value) === "object") arrayElementSpec = arraySpec.value; 11761 let errors = []; 11762 for (let i = 0; i < array.length; i++) errors = errors.concat(validateArrayElement({ 11763 array, 11764 arrayIndex: i, 11765 value: array[i], 11766 valueSpec: arrayElementSpec, 11767 validateSpec: options.validateSpec, 11768 style, 11769 styleSpec, 11770 key: `${key}[${i}]` 11771 })); 11772 return errors; 11773} 11774//#endregion 11775//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_number.mjs 11776function validateNumber(options) { 11777 const key = options.key; 11778 const value = options.value; 11779 const valueSpec = options.valueSpec; 11780 let type = getType(value); 11781 if (type === "number" && value !== value) type = "NaN"; 11782 if (type !== "number") return [new ValidationError(key, value, `number expected, ${type} found`)]; 11783 if ("minimum" in valueSpec && value < valueSpec.minimum) return [new ValidationError(key, value, `${value} is less than the minimum value ${valueSpec.minimum}`)]; 11784 if ("maximum" in valueSpec && value > valueSpec.maximum) return [new ValidationError(key, value, `${value} is greater than the maximum value ${valueSpec.maximum}`)]; 11785 return []; 11786} 11787//#endregion 11788//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_function.mjs 11789function validateFunction(options) { 11790 const functionValueSpec = options.valueSpec; 11791 const functionType = unbundle(options.value.type); 11792 let stopKeyType; 11793 let stopDomainValues = {}; 11794 let previousStopDomainValue; 11795 let previousStopDomainZoom; 11796 const isZoomFunction = functionType !== "categorical" && options.value.property === void 0; 11797 const isPropertyFunction = !isZoomFunction; 11798 const isZoomAndPropertyFunction = getType(options.value.stops) === "array" && getType(options.value.stops[0]) === "array" && getType(options.value.stops[0][0]) === "object"; 11799 const errors = validateObject({ 11800 key: options.key, 11801 value: options.value, 11802 valueSpec: options.styleSpec.function, 11803 validateSpec: options.validateSpec, 11804 style: options.style, 11805 styleSpec: options.styleSpec, 11806 objectElementValidators: { 11807 stops: validateFunctionStops, 11808 default: validateFunctionDefault 11809 } 11810 }); 11811 if (functionType === "identity" && isZoomFunction) errors.push(new ValidationError(options.key, options.value, "missing required property \"property\"")); 11812 if (functionType !== "identity" && !options.value.stops) errors.push(new ValidationError(options.key, options.value, "missing required property \"stops\"")); 11813 if (functionType === "exponential" && options.valueSpec.expression && !supportsInterpolation(options.valueSpec)) errors.push(new ValidationError(options.key, options.value, "exponential functions not supported")); 11814 if (options.styleSpec.$version >= 8) { 11815 if (isPropertyFunction && !supportsPropertyExpression(options.valueSpec)) errors.push(new ValidationError(options.key, options.value, "property functions not supported")); 11816 else if (isZoomFunction && !supportsZoomExpression(options.valueSpec)) errors.push(new ValidationError(options.key, options.value, "zoom functions not supported")); 11817 } 11818 if ((functionType === "categorical" || isZoomAndPropertyFunction) && options.value.property === void 0) errors.push(new ValidationError(options.key, options.value, "\"property\" property is required")); 11819 return errors; 11820 function validateFunctionStops(options) { 11821 if (functionType === "identity") return [new ValidationError(options.key, options.value, "identity function may not have a \"stops\" property")]; 11822 let errors = []; 11823 const value = options.value; 11824 errors = errors.concat(validateArray({ 11825 key: options.key, 11826 value, 11827 valueSpec: options.valueSpec, 11828 validateSpec: options.validateSpec, 11829 style: options.style, 11830 styleSpec: options.styleSpec, 11831 arrayElementValidator: validateFunctionStop 11832 })); 11833 if (getType(value) === "array" && value.length === 0) errors.push(new ValidationError(options.key, value, "array must have at least one stop")); 11834 return errors; 11835 } 11836 function validateFunctionStop(options) { 11837 let errors = []; 11838 const value = options.value; 11839 const key = options.key; 11840 if (getType(value) !== "array") return [new ValidationError(key, value, `array expected, ${getType(value)} found`)]; 11841 if (value.length !== 2) return [new ValidationError(key, value, `array length 2 expected, length ${value.length} found`)]; 11842 if (isZoomAndPropertyFunction) { 11843 if (getType(value[0]) !== "object") return [new ValidationError(key, value, `object expected, ${getType(value[0])} found`)]; 11844 if (value[0].zoom === void 0) return [new ValidationError(key, value, "object stop key must have zoom")]; 11845 if (value[0].value === void 0) return [new ValidationError(key, value, "object stop key must have value")]; 11846 if (previousStopDomainZoom && previousStopDomainZoom > unbundle(value[0].zoom)) return [new ValidationError(key, value[0].zoom, "stop zoom values must appear in ascending order")]; 11847 if (unbundle(value[0].zoom) !== previousStopDomainZoom) { 11848 previousStopDomainZoom = unbundle(value[0].zoom); 11849 previousStopDomainValue = void 0; 11850 stopDomainValues = {}; 11851 } 11852 errors = errors.concat(validateObject({ 11853 key: `${key}[0]`, 11854 value: value[0], 11855 valueSpec: { zoom: {} }, 11856 validateSpec: options.validateSpec, 11857 style: options.style, 11858 styleSpec: options.styleSpec, 11859 objectElementValidators: { 11860 zoom: validateNumber, 11861 value: validateStopDomainValue 11862 } 11863 })); 11864 } else errors = errors.concat(validateStopDomainValue({ 11865 key: `${key}[0]`, 11866 value: value[0], 11867 valueSpec: {}, 11868 validateSpec: options.validateSpec, 11869 style: options.style, 11870 styleSpec: options.styleSpec 11871 }, value)); 11872 if (isExpression(deepUnbundle(value[1]))) return errors.concat([new ValidationError(`${key}[1]`, value[1], "expressions are not allowed in function stops.")]); 11873 return errors.concat(options.validateSpec({ 11874 key: `${key}[1]`, 11875 value: value[1], 11876 valueSpec: functionValueSpec, 11877 validateSpec: options.validateSpec, 11878 style: options.style, 11879 styleSpec: options.styleSpec 11880 })); 11881 } 11882 function validateStopDomainValue(options, stop) { 11883 const type = getType(options.value); 11884 const value = unbundle(options.value); 11885 const reportValue = options.value !== null ? options.value : stop; 11886 if (!stopKeyType) stopKeyType = type; 11887 else if (type !== stopKeyType) return [new ValidationError(options.key, reportValue, `${type} stop domain type must match previous stop domain type ${stopKeyType}`)]; 11888 if (type !== "number" && type !== "string" && type !== "boolean") return [new ValidationError(options.key, reportValue, "stop domain value must be a number, string, or boolean")]; 11889 if (type !== "number" && functionType !== "categorical") { 11890 let message = `number expected, ${type} found`; 11891 if (supportsPropertyExpression(functionValueSpec) && functionType === void 0) message += "\nIf you intended to use a categorical function, specify `\"type\": \"categorical\"`."; 11892 return [new ValidationError(options.key, reportValue, message)]; 11893 } 11894 if (functionType === "categorical" && type === "number" && (!isFinite(value) || Math.floor(value) !== value)) return [new ValidationError(options.key, reportValue, `integer expected, found ${value}`)]; 11895 if (functionType !== "categorical" && type === "number" && previousStopDomainValue !== void 0 && value < previousStopDomainValue) return [new ValidationError(options.key, reportValue, "stop domain values must appear in ascending order")]; 11896 else previousStopDomainValue = value; 11897 if (functionType === "categorical" && value in stopDomainValues) return [new ValidationError(options.key, reportValue, "stop domain values must be unique")]; 11898 else stopDomainValues[value] = true; 11899 return []; 11900 } 11901 function validateFunctionDefault(options) { 11902 return options.validateSpec({ 11903 key: options.key, 11904 value: options.value, 11905 valueSpec: functionValueSpec, 11906 validateSpec: options.validateSpec, 11907 style: options.style, 11908 styleSpec: options.styleSpec 11909 }); 11910 } 11911} 11912//#endregion 11913//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_expression.mjs 11914function validateExpression(options) { 11915 const expression = (options.expressionContext === "property" ? createPropertyExpression : createExpression)(deepUnbundle(options.value), options.key, options.valueSpec); 11916 if (expression.result === "error") return expression.value.map((error) => { 11917 return new ValidationError(`${options.key}${error.key}`, options.value, error.message); 11918 }); 11919 const expressionObj = expression.value.expression || expression.value._styleExpression.expression; 11920 if (options.expressionContext === "property" && options.propertyKey === "text-font" && !expressionObj.outputDefined()) return [new ValidationError(options.key, options.value, `Invalid data expression for "${options.propertyKey}". Output values must be contained as literals within the expression.`)]; 11921 if (options.expressionContext === "property" && options.propertyType === "layout" && !isStateConstant(expressionObj)) return [new ValidationError(options.key, options.value, "\"feature-state\" data expressions are not supported with layout properties.")]; 11922 if (options.expressionContext === "filter" && !isStateConstant(expressionObj)) return [new ValidationError(options.key, options.value, "\"feature-state\" data expressions are not supported with filters.")]; 11923 if (options.expressionContext && options.expressionContext.indexOf("cluster") === 0) { 11924 if (!isGlobalPropertyConstant(expressionObj, ["zoom", "feature-state"])) return [new ValidationError(options.key, options.value, "\"zoom\" and \"feature-state\" expressions are not supported with cluster properties.")]; 11925 if (options.expressionContext === "cluster-initial" && !isFeatureConstant(expressionObj)) return [new ValidationError(options.key, options.value, "Feature data expressions are not supported with initial expression part of cluster properties.")]; 11926 } 11927 return []; 11928} 11929//#endregion 11930//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_boolean.mjs 11931function validateBoolean(options) { 11932 const value = options.value; 11933 const key = options.key; 11934 const type = getType(value); 11935 if (type !== "boolean") return [new ValidationError(key, value, `boolean expected, ${type} found`)]; 11936 return []; 11937} 11938//#endregion 11939//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_color.mjs 11940function validateColor(options) { 11941 const key = options.key; 11942 const value = options.value; 11943 const type = getType(value); 11944 if (type !== "string") return [new ValidationError(key, value, `color expected, ${type} found`)]; 11945 if (!Color.parse(String(value))) return [new ValidationError(key, value, `color expected, "${value}" found`)]; 11946 return []; 11947} 11948//#endregion 11949//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_enum.mjs 11950function validateEnum(options) { 11951 const key = options.key; 11952 const value = options.value; 11953 const valueSpec = options.valueSpec; 11954 const errors = []; 11955 if (Array.isArray(valueSpec.values)) { 11956 if (valueSpec.values.indexOf(unbundle(value)) === -1) errors.push(new ValidationError(key, value, `expected one of [${valueSpec.values.join(", ")}], ${JSON.stringify(value)} found`)); 11957 } else if (Object.keys(valueSpec.values).indexOf(unbundle(value)) === -1) errors.push(new ValidationError(key, value, `expected one of [${Object.keys(valueSpec.values).join(", ")}], ${JSON.stringify(value)} found`)); 11958 return errors; 11959} 11960//#endregion 11961//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_filter.mjs 11962function getValueAtPath(value, path) { 11963 let current = value; 11964 for (const index of path) current = current[index]; 11965 return current; 11966} 11967/** 11968* Reports a filter that mixes deprecated syntax into an expression tree as a *warning*. 11969* @param options The validation options, used for the key and the un-unbundled value 11970* @param value The unbundled filter to inspect 11971* @returns A single warning, or an empty array when nothing is mixed 11972*/ 11973function validateNoMixedLegacyFilter(options, value) { 11974 const diagnostic = findMixedLegacyFilter(value); 11975 if (!diagnostic) return []; 11976 return [new ValidationError(`${options.key}${diagnostic.path.map((index) => `[${index}]`).join("")}`, getValueAtPath(options.value, diagnostic.path), getMixedFilterMessage(diagnostic.legacyFilter), null, "warning")]; 11977} 11978function validateFilter(options) { 11979 const value = deepUnbundle(options.value); 11980 if (!isExpressionFilter(value)) return validateNonExpressionFilter(options); 11981 return [...validateNoMixedLegacyFilter(options, value), ...validateExpression(extendBy({}, options, { 11982 expressionContext: "filter", 11983 valueSpec: { value: "boolean" } 11984 }))]; 11985} 11986function validateNonExpressionFilter(options) { 11987 const value = options.value; 11988 const key = options.key; 11989 if (getType(value) !== "array") return [new ValidationError(key, value, `array expected, ${getType(value)} found`)]; 11990 const styleSpec = options.styleSpec; 11991 let type; 11992 let errors = []; 11993 if (value.length < 1) return [new ValidationError(key, value, "filter array must have at least 1 element")]; 11994 errors = errors.concat(validateEnum({ 11995 key: `${key}[0]`, 11996 value: value[0], 11997 valueSpec: styleSpec.filter_operator, 11998 style: options.style, 11999 styleSpec: options.styleSpec 12000 })); 12001 switch (unbundle(value[0])) { 12002 case "<": 12003 case "<=": 12004 case ">": 12005 case ">=": if (value.length >= 2 && unbundle(value[1]) === "$type") errors.push(new ValidationError(key, value, `"$type" cannot be use with operator "${value[0]}"`)); 12006 case "==": 12007 case "!=": if (value.length !== 3) errors.push(new ValidationError(key, value, `filter array for operator "${value[0]}" must have 3 elements`)); 12008 case "in": 12009 case "!in": 12010 if (value.length >= 2) { 12011 type = getType(value[1]); 12012 if (type !== "string") errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`)); 12013 } 12014 for (let i = 2; i < value.length; i++) { 12015 type = getType(value[i]); 12016 if (unbundle(value[1]) === "$type") errors = errors.concat(validateEnum({ 12017 key: `${key}[${i}]`, 12018 value: value[i], 12019 valueSpec: styleSpec.geometry_type, 12020 style: options.style, 12021 styleSpec: options.styleSpec 12022 })); 12023 else if (type !== "string" && type !== "number" && type !== "boolean") errors.push(new ValidationError(`${key}[${i}]`, value[i], `string, number, or boolean expected, ${type} found`)); 12024 } 12025 break; 12026 case "any": 12027 case "all": 12028 case "none": 12029 for (let i = 1; i < value.length; i++) errors = errors.concat(validateNonExpressionFilter({ 12030 key: `${key}[${i}]`, 12031 value: value[i], 12032 style: options.style, 12033 styleSpec: options.styleSpec 12034 })); 12035 break; 12036 case "has": 12037 case "!has": 12038 type = getType(value[1]); 12039 if (value.length !== 2) errors.push(new ValidationError(key, value, `filter array for "${value[0]}" operator must have 2 elements`)); 12040 else if (type !== "string") errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`)); 12041 } 12042 return errors; 12043} 12044//#endregion 12045//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_property.mjs 12046function validateProperty(options, propertyType) { 12047 const key = options.key; 12048 const validateSpec = options.validateSpec; 12049 const style = options.style; 12050 const styleSpec = options.styleSpec; 12051 const value = options.value; 12052 const propertyKey = options.objectKey; 12053 const layerSpec = styleSpec[`${propertyType}_${options.layerType}`]; 12054 if (!layerSpec) return []; 12055 const transitionMatch = propertyKey.match(transitionPropertyRegExp); 12056 if (propertyType === "paint" && transitionMatch && layerSpec[transitionMatch[1]] && layerSpec[transitionMatch[1]].transition) return validateSpec({ 12057 key, 12058 value, 12059 valueSpec: styleSpec.transition, 12060 style, 12061 styleSpec 12062 }); 12063 const valueSpec = options.valueSpec || layerSpec[propertyKey]; 12064 if (!valueSpec) return [new ValidationError(key, value, `unknown property "${propertyKey}"`)]; 12065 let tokenMatch; 12066 if (getType(value) === "string" && supportsPropertyExpression(valueSpec) && !valueSpec.tokens && (tokenMatch = /^{([^}]+)}$/.exec(value))) return [new ValidationError(key, value, `"${propertyKey}" does not support interpolation syntax\nUse an identity property function instead: \`{ "type": "identity", "property": ${JSON.stringify(tokenMatch[1])} }\`.`)]; 12067 const errors = []; 12068 if (options.layerType === "symbol") { 12069 if (propertyKey === "text-font" && isFunction$1(deepUnbundle(value)) && unbundle(value.type) === "identity") errors.push(new ValidationError(key, value, "\"text-font\" does not support identity functions")); 12070 } 12071 return errors.concat(validateSpec({ 12072 key: options.key, 12073 value, 12074 valueSpec, 12075 style, 12076 styleSpec, 12077 expressionContext: "property", 12078 propertyType, 12079 propertyKey 12080 })); 12081} 12082//#endregion 12083//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_paint_property.mjs 12084function validatePaintProperty(options) { 12085 return validateProperty(options, "paint"); 12086} 12087//#endregion 12088//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_layout_property.mjs 12089function validateLayoutProperty(options) { 12090 return validateProperty(options, "layout"); 12091} 12092//#endregion 12093//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_layer.mjs 12094function validateLayer(options) { 12095 let errors = []; 12096 const layer = options.value; 12097 const key = options.key; 12098 const style = options.style; 12099 const styleSpec = options.styleSpec; 12100 if (getType(layer) !== "object") return [new ValidationError(key, layer, `object expected, ${getType(layer)} found`)]; 12101 if (!layer.type && !layer.ref) errors.push(new ValidationError(key, layer, "either \"type\" or \"ref\" is required")); 12102 let type = unbundle(layer.type); 12103 const ref = unbundle(layer.ref); 12104 if (layer.id) { 12105 const layerId = unbundle(layer.id); 12106 for (let i = 0; i < options.arrayIndex; i++) { 12107 const otherLayer = style.layers[i]; 12108 if (unbundle(otherLayer.id) === layerId) errors.push(new ValidationError(key, layer.id, `duplicate layer id "${layer.id}", previously used at line ${otherLayer.id.__line__}`)); 12109 } 12110 } 12111 if ("ref" in layer) { 12112 [ 12113 "type", 12114 "source", 12115 "source-layer", 12116 "filter", 12117 "layout" 12118 ].forEach((p) => { 12119 if (p in layer) errors.push(new ValidationError(key, layer[p], `"${p}" is prohibited for ref layers`)); 12120 }); 12121 let parent; 12122 style.layers.forEach((layer) => { 12123 if (unbundle(layer.id) === ref) parent = layer; 12124 }); 12125 if (!parent) errors.push(new ValidationError(key, layer.ref, `ref layer "${ref}" not found`)); 12126 else if (parent.ref) errors.push(new ValidationError(key, layer.ref, "ref cannot reference another ref layer")); 12127 else type = unbundle(parent.type); 12128 } else if (type !== "background") { 12129 if (!layer.source) errors.push(new ValidationError(key, layer, "missing required property \"source\"")); 12130 else { 12131 const source = style.sources && style.sources[layer.source]; 12132 const sourceType = source && unbundle(source.type); 12133 if (!source) errors.push(new ValidationError(key, layer.source, `source "${layer.source}" not found`)); 12134 else if (sourceType === "vector" && type === "raster") errors.push(new ValidationError(key, layer.source, `layer "${layer.id}" requires a raster source`)); 12135 else if (sourceType !== "raster-dem" && type === "hillshade") errors.push(new ValidationError(key, layer.source, `layer "${layer.id}" requires a raster-dem source`)); 12136 else if (sourceType !== "raster-dem" && type === "color-relief") errors.push(new ValidationError(key, layer.source, `layer "${layer.id}" requires a raster-dem source`)); 12137 else if (sourceType === "raster" && type !== "raster") errors.push(new ValidationError(key, layer.source, `layer "${layer.id}" requires a vector source`)); 12138 else if (sourceType === "vector" && !layer["source-layer"]) errors.push(new ValidationError(key, layer, `layer "${layer.id}" must specify a "source-layer"`)); 12139 else if (sourceType === "raster-dem" && type !== "hillshade" && type !== "color-relief") errors.push(new ValidationError(key, layer.source, "raster-dem source can only be used with layer type 'hillshade' or 'color-relief'.")); 12140 else if (type === "line" && layer.paint && layer.paint["line-gradient"] && (sourceType !== "geojson" || !source.lineMetrics)) errors.push(new ValidationError(key, layer, `layer "${layer.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)); 12141 } 12142 } 12143 if (type === "raster" && layer.paint?.resampling && layer.paint?.["raster-resampling"]) errors.push(new ValidationError(key, layer.paint, `layer "${layer.id}" redundantly specifies "resampling" and "raster-resampling" paint properties, but only one is allowed. It is advised to use "resampling".`)); 12144 errors = errors.concat(validateObject({ 12145 key, 12146 value: layer, 12147 valueSpec: styleSpec.layer, 12148 style: options.style, 12149 styleSpec: options.styleSpec, 12150 validateSpec: options.validateSpec, 12151 objectElementValidators: { 12152 "*"() { 12153 return []; 12154 }, 12155 type() { 12156 return options.validateSpec({ 12157 key: `${key}.type`, 12158 value: layer.type, 12159 valueSpec: styleSpec.layer.type, 12160 style: options.style, 12161 styleSpec: options.styleSpec, 12162 validateSpec: options.validateSpec, 12163 object: layer, 12164 objectKey: "type" 12165 }); 12166 }, 12167 filter: validateFilter, 12168 layout(options) { 12169 return validateObject({ 12170 layer, 12171 key: options.key, 12172 value: options.value, 12173 style: options.style, 12174 styleSpec: options.styleSpec, 12175 validateSpec: options.validateSpec, 12176 objectElementValidators: { "*"(options) { 12177 return validateLayoutProperty(extendBy({ layerType: type }, options)); 12178 } } 12179 }); 12180 }, 12181 paint(options) { 12182 return validateObject({ 12183 layer, 12184 key: options.key, 12185 value: options.value, 12186 style: options.style, 12187 styleSpec: options.styleSpec, 12188 validateSpec: options.validateSpec, 12189 objectElementValidators: { "*"(options) { 12190 return validatePaintProperty(extendBy({ layerType: type }, options)); 12191 } } 12192 }); 12193 } 12194 } 12195 })); 12196 return errors; 12197} 12198//#endregion 12199//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_string.mjs 12200function validateString(options) { 12201 const value = options.value; 12202 const key = options.key; 12203 const type = getType(value); 12204 if (type !== "string") return [new ValidationError(key, value, `string expected, ${type} found`)]; 12205 return []; 12206} 12207//#endregion 12208//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_raster_dem_source.mjs 12209function validateRasterDEMSource(options) { 12210 const sourceName = options.sourceName ?? ""; 12211 const rasterDEM = options.value; 12212 const styleSpec = options.styleSpec; 12213 const rasterDEMSpec = styleSpec.source_raster_dem; 12214 const style = options.style; 12215 let errors = []; 12216 const rootType = getType(rasterDEM); 12217 if (rasterDEM === void 0) return errors; 12218 else if (rootType !== "object") { 12219 errors.push(new ValidationError("source_raster_dem", rasterDEM, `object expected, ${rootType} found`)); 12220 return errors; 12221 } 12222 const isCustomEncoding = unbundle(rasterDEM.encoding) === "custom"; 12223 const customEncodingKeys = [ 12224 "redFactor", 12225 "greenFactor", 12226 "blueFactor", 12227 "baseShift" 12228 ]; 12229 const encodingName = options.value.encoding ? `"${options.value.encoding}"` : "Default"; 12230 for (const key in rasterDEM) if (!isCustomEncoding && customEncodingKeys.includes(key)) errors.push(new ValidationError(key, rasterDEM[key], `In "${sourceName}": "${key}" is only valid when "encoding" is set to "custom". ${encodingName} encoding found`)); 12231 else if (rasterDEMSpec[key]) errors = errors.concat(options.validateSpec({ 12232 key, 12233 value: rasterDEM[key], 12234 valueSpec: rasterDEMSpec[key], 12235 validateSpec: options.validateSpec, 12236 style, 12237 styleSpec 12238 })); 12239 else errors.push(new ValidationError(key, rasterDEM[key], `unknown property "${key}"`)); 12240 return errors; 12241} 12242//#endregion 12243//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_source.mjs 12244const objectElementValidators = { promoteId: validatePromoteId }; 12245function validateSource(options) { 12246 const value = options.value; 12247 const key = options.key; 12248 const styleSpec = options.styleSpec; 12249 const style = options.style; 12250 const validateSpec = options.validateSpec; 12251 if (!value.type) return [new ValidationError(key, value, "\"type\" is required")]; 12252 const type = unbundle(value.type); 12253 let errors; 12254 switch (type) { 12255 case "vector": 12256 case "raster": 12257 errors = validateObject({ 12258 key, 12259 value, 12260 valueSpec: styleSpec[`source_${type.replace("-", "_")}`], 12261 style: options.style, 12262 styleSpec, 12263 objectElementValidators, 12264 validateSpec 12265 }); 12266 return errors; 12267 case "raster-dem": 12268 errors = validateRasterDEMSource({ 12269 sourceName: key, 12270 value, 12271 style: options.style, 12272 styleSpec, 12273 validateSpec 12274 }); 12275 return errors; 12276 case "geojson": 12277 errors = validateObject({ 12278 key, 12279 value, 12280 valueSpec: styleSpec.source_geojson, 12281 style, 12282 styleSpec, 12283 validateSpec, 12284 objectElementValidators 12285 }); 12286 if (value.cluster) for (const prop in value.clusterProperties) { 12287 const [operator, mapExpr] = value.clusterProperties[prop]; 12288 const reduceExpr = typeof operator === "string" ? [ 12289 operator, 12290 ["accumulated"], 12291 ["get", prop] 12292 ] : operator; 12293 errors.push(...validateExpression({ 12294 key: `${key}.${prop}.map`, 12295 value: mapExpr, 12296 validateSpec, 12297 expressionContext: "cluster-map" 12298 })); 12299 errors.push(...validateExpression({ 12300 key: `${key}.${prop}.reduce`, 12301 value: reduceExpr, 12302 validateSpec, 12303 expressionContext: "cluster-reduce" 12304 })); 12305 } 12306 return errors; 12307 case "video": return validateObject({ 12308 key, 12309 value, 12310 valueSpec: styleSpec.source_video, 12311 style, 12312 validateSpec, 12313 styleSpec 12314 }); 12315 case "image": return validateObject({ 12316 key, 12317 value, 12318 valueSpec: styleSpec.source_image, 12319 style, 12320 validateSpec, 12321 styleSpec 12322 }); 12323 case "canvas": return [new ValidationError(key, null, "Please use runtime APIs to add canvas sources, rather than including them in stylesheets.", "source.canvas")]; 12324 default: return validateEnum({ 12325 key: `${key}.type`, 12326 value: value.type, 12327 valueSpec: { values: [ 12328 "vector", 12329 "raster", 12330 "raster-dem", 12331 "geojson", 12332 "video", 12333 "image" 12334 ] }, 12335 style, 12336 validateSpec, 12337 styleSpec 12338 }); 12339 } 12340} 12341function validatePromoteId({ key, value }) { 12342 if (getType(value) === "string") return validateString({ 12343 key, 12344 value 12345 }); 12346 else { 12347 const errors = []; 12348 for (const prop in value) errors.push(...validateString({ 12349 key: `${key}.${prop}`, 12350 value: value[prop] 12351 })); 12352 return errors; 12353 } 12354} 12355//#endregion 12356//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_light.mjs 12357function validateLight(options) { 12358 const light = options.value; 12359 const styleSpec = options.styleSpec; 12360 const lightSpec = styleSpec.light; 12361 const style = options.style; 12362 let errors = []; 12363 const rootType = getType(light); 12364 if (light === void 0) return errors; 12365 else if (rootType !== "object") { 12366 errors = errors.concat([new ValidationError("light", light, `object expected, ${rootType} found`)]); 12367 return errors; 12368 } 12369 for (const key in light) { 12370 const transitionMatch = key.match(transitionPropertyRegExp); 12371 if (transitionMatch && lightSpec[transitionMatch[1]] && lightSpec[transitionMatch[1]].transition) errors = errors.concat(options.validateSpec({ 12372 key, 12373 value: light[key], 12374 valueSpec: styleSpec.transition, 12375 validateSpec: options.validateSpec, 12376 style, 12377 styleSpec 12378 })); 12379 else if (lightSpec[key]) errors = errors.concat(options.validateSpec({ 12380 key, 12381 value: light[key], 12382 valueSpec: lightSpec[key], 12383 validateSpec: options.validateSpec, 12384 style, 12385 styleSpec 12386 })); 12387 else errors = errors.concat([new ValidationError(key, light[key], `unknown property "${key}"`)]); 12388 } 12389 return errors; 12390} 12391//#endregion 12392//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_sky.mjs 12393function validateSky(options) { 12394 const sky = options.value; 12395 const styleSpec = options.styleSpec; 12396 const skySpec = styleSpec.sky; 12397 const style = options.style; 12398 const rootType = getType(sky); 12399 if (sky === void 0) return []; 12400 else if (rootType !== "object") return [new ValidationError("sky", sky, `object expected, ${rootType} found`)]; 12401 let errors = []; 12402 for (const key in sky) { 12403 const transitionMatch = key.match(transitionPropertyRegExp); 12404 if (transitionMatch && skySpec[transitionMatch[1]] && skySpec[transitionMatch[1]].transition) errors = errors.concat(options.validateSpec({ 12405 key, 12406 value: sky[key], 12407 valueSpec: styleSpec.transition, 12408 style, 12409 styleSpec 12410 })); 12411 else if (skySpec[key]) errors = errors.concat(options.validateSpec({ 12412 key, 12413 value: sky[key], 12414 valueSpec: skySpec[key], 12415 style, 12416 styleSpec 12417 })); 12418 else errors = errors.concat([new ValidationError(key, sky[key], `unknown property "${key}"`)]); 12419 } 12420 return errors; 12421} 12422//#endregion 12423//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_terrain.mjs 12424function validateTerrain(options) { 12425 const terrain = options.value; 12426 const styleSpec = options.styleSpec; 12427 const terrainSpec = styleSpec.terrain; 12428 const style = options.style; 12429 let errors = []; 12430 const rootType = getType(terrain); 12431 if (terrain === void 0) return errors; 12432 else if (rootType !== "object") { 12433 errors = errors.concat([new ValidationError("terrain", terrain, `object expected, ${rootType} found`)]); 12434 return errors; 12435 } 12436 for (const key in terrain) if (terrainSpec[key]) errors = errors.concat(options.validateSpec({ 12437 key, 12438 value: terrain[key], 12439 valueSpec: terrainSpec[key], 12440 validateSpec: options.validateSpec, 12441 style, 12442 styleSpec 12443 })); 12444 else errors = errors.concat([new ValidationError(key, terrain[key], `unknown property "${key}"`)]); 12445 return errors; 12446} 12447//#endregion 12448//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_formatted.mjs 12449function validateFormatted(options) { 12450 if (validateString(options).length === 0) return []; 12451 return validateExpression(options); 12452} 12453//#endregion 12454//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_image.mjs 12455function validateImage(options) { 12456 if (validateString(options).length === 0) return []; 12457 return validateExpression(options); 12458} 12459//#endregion 12460//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_padding.mjs 12461function validatePadding(options) { 12462 const key = options.key; 12463 const value = options.value; 12464 if (getType(value) === "array") { 12465 if (value.length < 1 || value.length > 4) return [new ValidationError(key, value, `padding requires 1 to 4 values; ${value.length} values found`)]; 12466 const arrayElementSpec = { type: "number" }; 12467 let errors = []; 12468 for (let i = 0; i < value.length; i++) errors = errors.concat(options.validateSpec({ 12469 key: `${key}[${i}]`, 12470 value: value[i], 12471 validateSpec: options.validateSpec, 12472 valueSpec: arrayElementSpec 12473 })); 12474 return errors; 12475 } else return validateNumber({ 12476 key, 12477 value, 12478 valueSpec: {} 12479 }); 12480} 12481//#endregion 12482//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_number_array.mjs 12483function validateNumberArray(options) { 12484 const key = options.key; 12485 const value = options.value; 12486 if (getType(value) === "array") { 12487 const arrayElementSpec = { type: "number" }; 12488 if (value.length < 1) return [new ValidationError(key, value, "array length at least 1 expected, length 0 found")]; 12489 let errors = []; 12490 for (let i = 0; i < value.length; i++) errors = errors.concat(options.validateSpec({ 12491 key: `${key}[${i}]`, 12492 value: value[i], 12493 validateSpec: options.validateSpec, 12494 valueSpec: arrayElementSpec 12495 })); 12496 return errors; 12497 } else return validateNumber({ 12498 key, 12499 value, 12500 valueSpec: {} 12501 }); 12502} 12503//#endregion 12504//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_color_array.mjs 12505function validateColorArray(options) { 12506 const key = options.key; 12507 const value = options.value; 12508 if (getType(value) === "array") { 12509 if (value.length < 1) return [new ValidationError(key, value, "array length at least 1 expected, length 0 found")]; 12510 let errors = []; 12511 for (let i = 0; i < value.length; i++) errors = errors.concat(validateColor({ 12512 key: `${key}[${i}]`, 12513 value: value[i], 12514 valueSpec: {} 12515 })); 12516 return errors; 12517 } else return validateColor({ 12518 key, 12519 value, 12520 valueSpec: {} 12521 }); 12522} 12523//#endregion 12524//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_variable_anchor_offset_collection.mjs 12525function validateVariableAnchorOffsetCollection(options) { 12526 const key = options.key; 12527 const value = options.value; 12528 const type = getType(value); 12529 const styleSpec = options.styleSpec; 12530 if (type !== "array" || value.length < 1 || value.length % 2 !== 0) return [new ValidationError(key, value, "variableAnchorOffsetCollection requires a non-empty array of even length")]; 12531 let errors = []; 12532 for (let i = 0; i < value.length; i += 2) { 12533 errors = errors.concat(validateEnum({ 12534 key: `${key}[${i}]`, 12535 value: value[i], 12536 valueSpec: styleSpec["layout_symbol"]["text-anchor"] 12537 })); 12538 errors = errors.concat(validateArray({ 12539 key: `${key}[${i + 1}]`, 12540 value: value[i + 1], 12541 valueSpec: { 12542 length: 2, 12543 value: "number" 12544 }, 12545 validateSpec: options.validateSpec, 12546 style: options.style, 12547 styleSpec 12548 })); 12549 } 12550 return errors; 12551} 12552//#endregion 12553//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_sprite.mjs 12554function validateSprite(options) { 12555 let errors = []; 12556 const sprite = options.value; 12557 const key = options.key; 12558 if (!Array.isArray(sprite)) return validateString({ 12559 key, 12560 value: sprite 12561 }); 12562 else { 12563 const allSpriteIds = []; 12564 const allSpriteURLs = []; 12565 for (const i in sprite) { 12566 if (sprite[i].id && allSpriteIds.includes(sprite[i].id)) errors.push(new ValidationError(key, sprite, `all the sprites' ids must be unique, but ${sprite[i].id} is duplicated`)); 12567 allSpriteIds.push(sprite[i].id); 12568 if (sprite[i].url && allSpriteURLs.includes(sprite[i].url)) errors.push(new ValidationError(key, sprite, `all the sprites' URLs must be unique, but ${sprite[i].url} is duplicated`)); 12569 allSpriteURLs.push(sprite[i].url); 12570 errors = errors.concat(validateObject({ 12571 key: `${key}[${i}]`, 12572 value: sprite[i], 12573 valueSpec: { 12574 id: { 12575 type: "string", 12576 required: true 12577 }, 12578 url: { 12579 type: "string", 12580 required: true 12581 } 12582 }, 12583 validateSpec: options.validateSpec 12584 })); 12585 } 12586 return errors; 12587 } 12588} 12589//#endregion 12590//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_projection.mjs 12591function validateProjection(options) { 12592 const projection = options.value; 12593 const styleSpec = options.styleSpec; 12594 const projectionSpec = styleSpec.projection; 12595 const style = options.style; 12596 const rootType = getType(projection); 12597 if (projection === void 0) return []; 12598 else if (rootType !== "object") return [new ValidationError("projection", projection, `object expected, ${rootType} found`)]; 12599 let errors = []; 12600 for (const key in projection) if (projectionSpec[key]) errors = errors.concat(options.validateSpec({ 12601 key, 12602 value: projection[key], 12603 valueSpec: projectionSpec[key], 12604 style, 12605 styleSpec 12606 })); 12607 else errors = errors.concat([new ValidationError(key, projection[key], `unknown property "${key}"`)]); 12608 return errors; 12609} 12610//#endregion 12611//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_projectiondefinition.mjs 12612function validateProjectionDefinition(options) { 12613 const key = options.key; 12614 let value = options.value; 12615 value = value instanceof String ? value.valueOf() : value; 12616 const type = getType(value); 12617 if (type === "array" && !isProjectionDefinitionValue(value) && !isPropertyValueSpecification(value)) return [new ValidationError(key, value, `projection expected, invalid array ${JSON.stringify(value)} found`)]; 12618 else if (!["array", "string"].includes(type)) return [new ValidationError(key, value, `projection expected, invalid type "${type}" found`)]; 12619 return []; 12620} 12621function isPropertyValueSpecification(value) { 12622 if ([ 12623 "interpolate", 12624 "step", 12625 "literal" 12626 ].includes(value[0])) return true; 12627 return false; 12628} 12629function isProjectionDefinitionValue(value) { 12630 return Array.isArray(value) && value.length === 3 && typeof value[0] === "string" && typeof value[1] === "string" && typeof value[2] === "number"; 12631} 12632//#endregion 12633//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/util/is_object_literal.mjs 12634function isObjectLiteral(anything) { 12635 return Boolean(anything) && anything.constructor === Object; 12636} 12637//#endregion 12638//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_state.mjs 12639function validateState(options) { 12640 if (!isObjectLiteral(options.value)) return [new ValidationError(options.key, options.value, `object expected, ${getType(options.value)} found`)]; 12641 return []; 12642} 12643//#endregion 12644//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_font_faces.mjs 12645const MAX_CODE_POINT = 1114111; 12646/** 12647* A single unicode range, as described by the [CSS descriptor with the same name](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/unicode-range): 12648* a single code point (`U+26`), a range of code points (`U+0-7F`) or a wildcard range (`U+4??`). 12649* At most six hexadecimal digits are allowed on either side. 12650*/ 12651const UNICODE_RANGE_REGEX = /^u\+(?:([0-9a-f]{1,6})(?:-([0-9a-f]{1,6}))?|([0-9a-f]{0,5}\?{1,6}))$/i; 12652function validateUnicodeRange(key, value) { 12653 if (getType(value) !== "string") return []; 12654 const range = `${value}`; 12655 const invalid = () => [new ValidationError(key, value, `invalid unicode range, expected a value such as "U+26", "U+0-10FFFF" or "U+4??"`)]; 12656 const match = range.match(UNICODE_RANGE_REGEX); 12657 if (!match) return invalid(); 12658 const [, start, end, wildcard] = match; 12659 if (wildcard !== void 0) return wildcard.length > 6 ? invalid() : []; 12660 const startCodePoint = parseInt(start, 16); 12661 const endCodePoint = end === void 0 ? startCodePoint : parseInt(end, 16); 12662 if (startCodePoint > MAX_CODE_POINT || endCodePoint > MAX_CODE_POINT) return [new ValidationError(key, value, `unicode range is out of bounds, the maximum code point is U+10FFFF`)]; 12663 if (startCodePoint > endCodePoint) return [new ValidationError(key, value, `unicode range start must not be greater than its end, but ${range} is`)]; 12664 return []; 12665} 12666function validateFontFaces(options) { 12667 const key = options.key ?? "font-faces"; 12668 const value = options.value; 12669 const validateSpec = options.validateSpec; 12670 const styleSpec = options.styleSpec ?? v8_default; 12671 const style = options.style; 12672 if (!isObjectLiteral(value)) return [new ValidationError(key, value, `object expected, ${getType(value)} found`)]; 12673 const errors = []; 12674 for (const fontName in value) { 12675 const fontValue = value[fontName]; 12676 const fontValueType = getType(fontValue); 12677 if (fontValueType === "string") errors.push(...validateString({ 12678 key: `${key}.${fontName}`, 12679 value: fontValue 12680 })); 12681 else if (fontValueType === "array") { 12682 const fontFaceSpec = { 12683 url: { 12684 type: "string", 12685 required: true 12686 }, 12687 "unicode-range": { 12688 type: "array", 12689 value: "string" 12690 } 12691 }; 12692 for (const [i, fontFace] of fontValue.entries()) { 12693 const fontFaceKey = `${key}.${fontName}[${i}]`; 12694 errors.push(...validateObject({ 12695 key: fontFaceKey, 12696 value: fontFace, 12697 valueSpec: fontFaceSpec, 12698 styleSpec, 12699 style, 12700 validateSpec 12701 })); 12702 const unicodeRanges = isObjectLiteral(fontFace) ? fontFace["unicode-range"] : void 0; 12703 if (getType(unicodeRanges) !== "array") continue; 12704 for (const [j, unicodeRange] of unicodeRanges.entries()) errors.push(...validateUnicodeRange(`${fontFaceKey}.unicode-range[${j}]`, unicodeRange)); 12705 } 12706 } else errors.push(new ValidationError(`${key}.${fontName}`, fontValue, `string or array expected, ${fontValueType} found`)); 12707 } 12708 return errors; 12709} 12710//#endregion 12711//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate.mjs 12712const VALIDATORS = { 12713 "*"() { 12714 return []; 12715 }, 12716 array: validateArray, 12717 boolean: validateBoolean, 12718 number: validateNumber, 12719 color: validateColor, 12720 constants: validateConstants, 12721 enum: validateEnum, 12722 filter: validateFilter, 12723 function: validateFunction, 12724 layer: validateLayer, 12725 object: validateObject, 12726 source: validateSource, 12727 light: validateLight, 12728 sky: validateSky, 12729 terrain: validateTerrain, 12730 projection: validateProjection, 12731 projectionDefinition: validateProjectionDefinition, 12732 string: validateString, 12733 formatted: validateFormatted, 12734 resolvedImage: validateImage, 12735 padding: validatePadding, 12736 numberArray: validateNumberArray, 12737 colorArray: validateColorArray, 12738 variableAnchorOffsetCollection: validateVariableAnchorOffsetCollection, 12739 sprite: validateSprite, 12740 state: validateState, 12741 fontFaces: validateFontFaces 12742}; 12743/** 12744* Main recursive validation function used internally. 12745* You should use `validateStyleMin` in the browser or `validateStyle` in node env. 12746* @param options - the options object 12747* @param options.key - string representing location of validation in style tree. Used only 12748* for more informative error reporting. 12749* @param options.value - current value from style being evaluated. May be anything from a 12750* high level object that needs to be descended into deeper or a simple 12751* scalar value. 12752* @param options.valueSpec - current spec being evaluated. Tracks value. 12753* @param options.styleSpec - current full spec being evaluated. 12754* @param options.validateSpec - the validate function itself 12755* @param options.style - the style object 12756* @param options.objectElementValidators - optional object of functions that will be called 12757* @returns an array of errors, or an empty array if no errors are found. 12758*/ 12759function validate(options) { 12760 const value = options.value; 12761 const valueSpec = options.valueSpec; 12762 const styleSpec = options.styleSpec; 12763 options.validateSpec = validate; 12764 if (valueSpec.expression && isFunction$1(unbundle(value))) return validateFunction(options); 12765 else if (valueSpec.expression && isExpression(deepUnbundle(value))) return validateExpression(options); 12766 else if (valueSpec.type && VALIDATORS[valueSpec.type]) return VALIDATORS[valueSpec.type](options); 12767 else return validateObject(extendBy({}, options, { valueSpec: valueSpec.type ? styleSpec[valueSpec.type] : valueSpec })); 12768} 12769//#endregion 12770//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate/validate_glyphs_url.mjs 12771function validateGlyphsUrl(options) { 12772 const value = options.value; 12773 const key = options.key; 12774 const errors = validateString(options); 12775 if (errors.length) return errors; 12776 if (value.indexOf("{fontstack}") === -1) errors.push(new ValidationError(key, value, "\"glyphs\" url must include a \"{fontstack}\" token")); 12777 if (value.indexOf("{range}") === -1) errors.push(new ValidationError(key, value, "\"glyphs\" url must include a \"{range}\" token")); 12778 return errors; 12779} 12780//#endregion 12781//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/validate_style.min.mjs 12782/** 12783* Validate a MapLibre style against the style specification. 12784* Use this when running in the browser. 12785* 12786* @param style - The style to be validated. 12787* @param styleSpec - The style specification to validate against. 12788* If omitted, the latest style spec is used. 12789* @returns an array of errors, or an empty array if no errors are found. 12790* @example 12791* const validate = require('@maplibre/maplibre-gl-style-spec/').validateStyleMin; 12792* const errors = validate(style); 12793*/ 12794function validateStyleMin(style, styleSpec = latest) { 12795 let errors = []; 12796 errors = errors.concat(validate({ 12797 key: "", 12798 value: style, 12799 valueSpec: styleSpec.$root, 12800 styleSpec, 12801 style, 12802 validateSpec: validate, 12803 objectElementValidators: { 12804 glyphs: validateGlyphsUrl, 12805 "*"() { 12806 return []; 12807 } 12808 } 12809 })); 12810 if (style["constants"]) errors = errors.concat(validateConstants({ 12811 key: "constants", 12812 value: style["constants"], 12813 style, 12814 styleSpec, 12815 validateSpec: validate 12816 })); 12817 return sortErrors(errors); 12818} 12819validateStyleMin.source = wrapCleanErrors(injectValidateSpec(validateSource)); 12820validateStyleMin.sprite = wrapCleanErrors(injectValidateSpec(validateSprite)); 12821validateStyleMin.glyphs = wrapCleanErrors(injectValidateSpec(validateGlyphsUrl)); 12822validateStyleMin.fontFaces = wrapCleanErrors(injectValidateSpec(validateFontFaces)); 12823validateStyleMin.light = wrapCleanErrors(injectValidateSpec(validateLight)); 12824validateStyleMin.sky = wrapCleanErrors(injectValidateSpec(validateSky)); 12825validateStyleMin.terrain = wrapCleanErrors(injectValidateSpec(validateTerrain)); 12826validateStyleMin.state = wrapCleanErrors(injectValidateSpec(validateState)); 12827validateStyleMin.layer = wrapCleanErrors(injectValidateSpec(validateLayer)); 12828validateStyleMin.filter = wrapCleanErrors(injectValidateSpec(validateFilter)); 12829validateStyleMin.paintProperty = wrapCleanErrors(injectValidateSpec(validatePaintProperty)); 12830validateStyleMin.layoutProperty = wrapCleanErrors(injectValidateSpec(validateLayoutProperty)); 12831function injectValidateSpec(validator) { 12832 return function(options) { 12833 return validator(Object.assign({}, options, { validateSpec: validate })); 12834 }; 12835} 12836function sortErrors(errors) { 12837 return [].concat(errors).sort((a, b) => { 12838 return a.line - b.line; 12839 }); 12840} 12841function wrapCleanErrors(inner) { 12842 return function(...args) { 12843 return sortErrors(inner.apply(this, args)); 12844 }; 12845} 12846//#endregion 12847//#region node_modules/@maplibre/maplibre-gl-style-spec/dist/expression/visibility.mjs 12848const visibilitySpec = { 12849 type: "enum", 12850 "property-type": "data-constant", 12851 expression: { 12852 interpolated: false, 12853 parameters: ["global-state"] 12854 }, 12855 values: { 12856 visible: {}, 12857 none: {} 12858 }, 12859 transition: false, 12860 default: "visible" 12861}; 12862var VisibilityExpressionClass = class { 12863 constructor(visibility, rootKey, globalState) { 12864 this._rootKey = rootKey; 12865 this._globalState = globalState; 12866 this.setValue(visibility); 12867 } 12868 evaluate() { 12869 return this._literalValue ?? this._compiledValue.evaluate({}); 12870 } 12871 setValue(visibility) { 12872 if (visibility === null || visibility === void 0 || visibility === "visible" || visibility === "none") { 12873 this._literalValue = visibility === "none" ? "none" : "visible"; 12874 this._compiledValue = void 0; 12875 this._globalStateRefs = /* @__PURE__ */ new Set(); 12876 return; 12877 } 12878 const compiled = createExpression(visibility, this._rootKey, visibilitySpec, this._globalState); 12879 if (compiled.result === "error") { 12880 this._literalValue = "visible"; 12881 this._compiledValue = void 0; 12882 throw new Error(compiled.value.map((err) => `${err.key}: ${err.message}`).join(", ")); 12883 } 12884 this._literalValue = void 0; 12885 this._compiledValue = compiled.value; 12886 this._globalStateRefs = findGlobalStateRefs(compiled.value.expression); 12887 } 12888 getGlobalStateRefs() { 12889 return this._globalStateRefs; 12890 } 12891}; 12892/** 12893* Creates a visibility expression from a visibility specification. 12894* @param visibility - the visibility specification, literal or expression 12895* @param rootKey - location of the visibility value in the style JSON 12896* (e.g. `layers[3].layout.visibility`), used to prefix runtime warnings 12897* @param globalState - the global state object 12898* @returns visibility expression object 12899*/ 12900function createVisibility(visibility, rootKey, globalState) { 12901 return new VisibilityExpressionClass(visibility, rootKey, globalState); 12902} 12903//#endregion 12904//#region src/style/validate_style.ts 12905const validateStyle = validateStyleMin; 12906/** 12907* The source types the spec has a schema for, and therefore the only ones it can judge. Taken from 12908* the spec itself so the two cannot drift apart. 12909*/ 12910const SPEC_SOURCE_TYPES = new Set(Object.keys(latest).filter((key) => key.startsWith("source_")).map((key) => key.slice(7).replaceAll("_", "-"))); 12911/** 12912* The sources whose type the spec has no schema for, so it rejects them outright even though we 12913* render them: `canvas`, and anything registered with {@link addSourceType}. They are the renderer's 12914* business rather than the spec's, so the spec's complaints about them are dropped -- otherwise 12915* `map.setStyle(map.getStyle())` would fail on a source the user added correctly. 12916* 12917* Each such source produces a single error keyed by `sources.<id>`, which is what is matched here. 12918* @param style - the style about to be validated 12919* @returns the `sources.<id>` key prefixes whose errors should be ignored 12920*/ 12921function unjudgeableSourceKeys(style) { 12922 return Object.entries(style.sources ?? {}).filter(([, source]) => !SPEC_SOURCE_TYPES.has(source.type)).map(([id]) => `sources.${id}`); 12923} 12924/** 12925* Validates a whole style and emits what it finds, ignoring the sources the spec cannot judge. 12926* 12927* @param emitter - the object to fire {@link ErrorEvent}s on 12928* @param style - the style to validate 12929* @returns whether validation failed, i.e. whether the caller should give up on the style 12930*/ 12931function validateStyleAndEmit(emitter, style) { 12932 const ignored = unjudgeableSourceKeys(style); 12933 return emitValidationErrors(emitter, validateStyle(style).filter(({ message }) => !ignored.some((key) => message.startsWith(`${key}:`) || message.startsWith(`${key}.`)))); 12934} 12935/** 12936* Emits everything a validator found, and reports whether any of it was severe enough to abort. 12937* 12938* Warnings are logged rather than emitted as errors: the style still renders, just not necessarily 12939* as its author intended (e.g. a filter mixing deprecated syntax into an expression tree). Treating 12940* them as errors would abort the whole style load and leave a blank map. 12941* See https://github.com/maplibre/maplibre-style-spec/issues/1751 12942* 12943* @param emitter - the object to fire {@link ErrorEvent}s on 12944* @param errors - what validation turned up, if anything 12945* @returns whether validation failed, i.e. whether the caller should give up on the value 12946*/ 12947function emitValidationErrors(emitter, errors) { 12948 let hasErrors = false; 12949 for (const error of errors) { 12950 if (error.severity === "warning") { 12951 warnOnce(error.message); 12952 continue; 12953 } 12954 emitter.fire(new ErrorEvent(new Error(error.message))); 12955 hasErrors = true; 12956 } 12957 return hasErrors; 12958} 12959/** 12960* Runs a validator over a value and emits whatever it finds. 12961* 12962* @param emitter - the object to fire {@link ErrorEvent}s on 12963* @param validator - the validator to run, e.g. {@link validateFilter} 12964* @param params - what to validate: the `value`, plus whatever context the validator needs, such as 12965* the `key` locating it in the style, or the surrounding `style` that {@link validateStyle.layer} looks at 12966* @param options - setter options; validation is skipped entirely when `validate` is `false` 12967* @returns whether validation failed, i.e. whether the caller should give up on the value 12968*/ 12969function validateAndEmit(emitter, validator, params, options) { 12970 if (options?.validate === false) return false; 12971 return emitValidationErrors(emitter, validator({ 12972 styleSpec: latest, 12973 ...params 12974 })); 12975} 12976//#endregion 12977//#region src/util/transferable_grid_index.ts 12978const NUM_PARAMS = 3; 12979var TransferableGridIndex = class TransferableGridIndex { 12980 constructor(extent, n, padding) { 12981 const cells = this.cells = []; 12982 if (extent instanceof ArrayBuffer) { 12983 this.arrayBuffer = extent; 12984 const array = new Int32Array(this.arrayBuffer); 12985 extent = array[0]; 12986 n = array[1]; 12987 padding = array[2]; 12988 this.d = n + 2 * padding; 12989 for (let k = 0; k < this.d * this.d; k++) { 12990 const start = array[NUM_PARAMS + k]; 12991 const end = array[NUM_PARAMS + k + 1]; 12992 cells.push(start === end ? null : array.subarray(start, end)); 12993 } 12994 const keysOffset = array[NUM_PARAMS + cells.length]; 12995 const bboxesOffset = array[NUM_PARAMS + cells.length + 1]; 12996 this.keys = array.subarray(keysOffset, bboxesOffset); 12997 this.bboxes = array.subarray(bboxesOffset); 12998 this.insert = this._insertReadonly; 12999 } else { 13000 this.d = n + 2 * padding; 13001 for (let i = 0; i < this.d * this.d; i++) cells.push([]); 13002 this.keys = []; 13003 this.bboxes = []; 13004 } 13005 this.n = n; 13006 this.extent = extent; 13007 this.padding = padding; 13008 this.scale = n / extent; 13009 this.uid = 0; 13010 const p = padding / n * extent; 13011 this.min = -p; 13012 this.max = extent + p; 13013 } 13014 insert(key, x1, y1, x2, y2) { 13015 this._forEachCell(x1, y1, x2, y2, this._insertCell, this.uid++, void 0, void 0); 13016 this.keys.push(key); 13017 this.bboxes.push(x1); 13018 this.bboxes.push(y1); 13019 this.bboxes.push(x2); 13020 this.bboxes.push(y2); 13021 } 13022 _insertReadonly() { 13023 throw new Error("Cannot insert into a GridIndex created from an ArrayBuffer."); 13024 } 13025 _insertCell(x1, y1, x2, y2, cellIndex, uid) { 13026 this.cells[cellIndex].push(uid); 13027 } 13028 query(x1, y1, x2, y2, intersectionTest) { 13029 const min = this.min; 13030 const max = this.max; 13031 if (x1 <= min && y1 <= min && max <= x2 && max <= y2 && !intersectionTest) return [...this.keys]; 13032 else { 13033 const result = []; 13034 this._forEachCell(x1, y1, x2, y2, this._queryCell, result, {}, intersectionTest); 13035 return result; 13036 } 13037 } 13038 _queryCell(x1, y1, x2, y2, cellIndex, result, seenUids, intersectionTest) { 13039 const cell = this.cells[cellIndex]; 13040 if (cell !== null) { 13041 const keys = this.keys; 13042 const bboxes = this.bboxes; 13043 for (const uid of cell) if (seenUids[uid] === void 0) { 13044 const offset = uid * 4; 13045 if (intersectionTest ? intersectionTest(bboxes[offset + 0], bboxes[offset + 1], bboxes[offset + 2], bboxes[offset + 3]) : x1 <= bboxes[offset + 2] && y1 <= bboxes[offset + 3] && x2 >= bboxes[offset + 0] && y2 >= bboxes[offset + 1]) { 13046 seenUids[uid] = true; 13047 result.push(keys[uid]); 13048 } else seenUids[uid] = false; 13049 } 13050 } 13051 } 13052 _forEachCell(x1, y1, x2, y2, fn, arg1, arg2, intersectionTest) { 13053 const cx1 = this._convertToCellCoord(x1); 13054 const cy1 = this._convertToCellCoord(y1); 13055 const cx2 = this._convertToCellCoord(x2); 13056 const cy2 = this._convertToCellCoord(y2); 13057 for (let x = cx1; x <= cx2; x++) for (let y = cy1; y <= cy2; y++) { 13058 const cellIndex = this.d * y + x; 13059 if (intersectionTest && !intersectionTest(this._convertFromCellCoord(x), this._convertFromCellCoord(y), this._convertFromCellCoord(x + 1), this._convertFromCellCoord(y + 1))) continue; 13060 if (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2, intersectionTest)) return; 13061 } 13062 } 13063 _convertFromCellCoord(x) { 13064 return (x - this.padding) / this.scale; 13065 } 13066 _convertToCellCoord(x) { 13067 return Math.max(0, Math.min(this.d - 1, Math.floor(x * this.scale) + this.padding)); 13068 } 13069 toArrayBuffer() { 13070 if (this.arrayBuffer) return this.arrayBuffer; 13071 const cells = this.cells; 13072 const metadataLength = NUM_PARAMS + this.cells.length + 1 + 1; 13073 let totalCellLength = 0; 13074 for (const cell of this.cells) totalCellLength += cell.length; 13075 const array = new Int32Array(metadataLength + totalCellLength + this.keys.length + this.bboxes.length); 13076 array[0] = this.extent; 13077 array[1] = this.n; 13078 array[2] = this.padding; 13079 let offset = metadataLength; 13080 for (let k = 0; k < cells.length; k++) { 13081 const cell = cells[k]; 13082 array[NUM_PARAMS + k] = offset; 13083 array.set(cell, offset); 13084 offset += cell.length; 13085 } 13086 array[NUM_PARAMS + cells.length] = offset; 13087 array.set(this.keys, offset); 13088 offset += this.keys.length; 13089 array[NUM_PARAMS + cells.length + 1] = offset; 13090 array.set(this.bboxes, offset); 13091 offset += this.bboxes.length; 13092 return array.buffer; 13093 } 13094 static serialize(grid, transferables) { 13095 const buffer = grid.toArrayBuffer(); 13096 if (transferables) transferables.push(buffer); 13097 return { buffer }; 13098 } 13099 static deserialize(serialized) { 13100 return new TransferableGridIndex(serialized.buffer); 13101 } 13102}; 13103//#endregion 13104//#region src/util/web_worker_transfer.ts 13105const registry = {}; 13106/** 13107* Register the given class as serializable. 13108* 13109* @param options - the registration options 13110*/ 13111function register(name, klass, options = {}) { 13112 if (registry[name]) throw new Error(`${name} is already registered.`); 13113 Object.defineProperty(klass, "_classRegistryKey", { 13114 value: name, 13115 writeable: false 13116 }); 13117 registry[name] = { 13118 klass, 13119 omit: options.omit || [], 13120 shallow: options.shallow || [] 13121 }; 13122} 13123register("Object", Object); 13124register("Set", Set); 13125register("TransferableGridIndex", TransferableGridIndex); 13126register("Color", Color); 13127register("Error", Error); 13128register("AJAXError", AJAXError); 13129register("ResolvedImage", ResolvedImage); 13130register("StylePropertyFunction", StylePropertyFunction); 13131register("StyleExpression", StyleExpression, { omit: ["_evaluator"] }); 13132register("ZoomDependentExpression", ZoomDependentExpression); 13133register("ZoomConstantExpression", ZoomConstantExpression); 13134register("CompoundExpression", CompoundExpression, { omit: ["_evaluate"] }); 13135for (const name in expressions$1) { 13136 if (expressions$1[name]._classRegistryKey) continue; 13137 register(`Expression_${name}`, expressions$1[name]); 13138} 13139function isArrayBuffer(value) { 13140 return value && typeof ArrayBuffer !== "undefined" && (value instanceof ArrayBuffer || value.constructor?.name === "ArrayBuffer"); 13141} 13142function getClassRegistryKey(input) { 13143 const klass = input.constructor; 13144 return input.$name || klass._classRegistryKey; 13145} 13146function isRegistered(input) { 13147 if (input === null || typeof input !== "object") return false; 13148 const classRegistryKey = getClassRegistryKey(input); 13149 return classRegistryKey && classRegistryKey !== "Object"; 13150} 13151function isSerializeHandledByBuiltin(input) { 13152 return !isRegistered(input) && (input === null || input === void 0 || typeof input === "boolean" || typeof input === "number" || typeof input === "string" || input instanceof Boolean || input instanceof Number || input instanceof String || input instanceof Date || input instanceof RegExp || input instanceof Blob || input instanceof Error || isArrayBuffer(input) || isImageBitmap(input) || ArrayBuffer.isView(input) || input instanceof ImageData); 13153} 13154/** 13155* Serialize the given object for transfer to or from a web worker. 13156* 13157* For non-builtin types, recursively serialize each property (possibly 13158* omitting certain properties - see register()), and package the result along 13159* with the constructor's `name` so that the appropriate constructor can be 13160* looked up in `deserialize()`. 13161* 13162* If a `transferables` array is provided, add any transferable objects (i.e., 13163* any ArrayBuffers or ArrayBuffer views) to the list. (If a copy is needed, 13164* this should happen in the client code, before using serialize().) 13165*/ 13166function serialize(input, transferables) { 13167 if (isSerializeHandledByBuiltin(input)) { 13168 if (isArrayBuffer(input) || isImageBitmap(input)) { 13169 if (transferables) transferables.push(input); 13170 } 13171 if (ArrayBuffer.isView(input)) { 13172 if (transferables) transferables.push(input.buffer); 13173 } 13174 if (input instanceof ImageData) { 13175 if (transferables) transferables.push(input.data.buffer); 13176 } 13177 return input; 13178 } 13179 if (Array.isArray(input)) { 13180 const serialized = []; 13181 for (const item of input) serialized.push(serialize(item, transferables)); 13182 return serialized; 13183 } 13184 if (typeof input !== "object") throw new Error(`can't serialize object of type ${typeof input}`); 13185 const classRegistryKey = getClassRegistryKey(input); 13186 if (!classRegistryKey) throw new Error(`can't serialize object of unregistered class ${input.constructor.name}`); 13187 if (!registry[classRegistryKey]) throw new Error(`${classRegistryKey} is not registered.`); 13188 const { klass } = registry[classRegistryKey]; 13189 const properties = klass.serialize ? klass.serialize(input, transferables) : {}; 13190 if (!klass.serialize) { 13191 for (const key in input) { 13192 if (!input.hasOwnProperty(key)) continue; 13193 if (registry[classRegistryKey].omit.includes(key)) continue; 13194 const property = input[key]; 13195 if (property === void 0) continue; 13196 properties[key] = registry[classRegistryKey].shallow.includes(key) ? property : serialize(property, transferables); 13197 } 13198 if (input instanceof Error) properties.message = input.message; 13199 } else if (properties === transferables?.[transferables.length - 1]) throw new Error("statically serialized object won't survive transfer of $name property"); 13200 if (properties.$name) throw new Error("$name property is reserved for worker serialization logic."); 13201 if (classRegistryKey !== "Object") properties.$name = classRegistryKey; 13202 return properties; 13203} 13204function deserialize(input) { 13205 if (isSerializeHandledByBuiltin(input)) return input; 13206 if (Array.isArray(input)) return input.map(deserialize); 13207 if (typeof input !== "object") throw new Error(`can't deserialize object of type ${typeof input}`); 13208 const classRegistryKey = getClassRegistryKey(input) || "Object"; 13209 if (!registry[classRegistryKey]) throw new Error(`can't deserialize unregistered class ${classRegistryKey}`); 13210 const { klass } = registry[classRegistryKey]; 13211 if (!klass) throw new Error(`can't deserialize unregistered class ${classRegistryKey}`); 13212 if (klass.deserialize) return klass.deserialize(input); 13213 const result = Object.create(klass.prototype); 13214 for (const key of Object.keys(input)) { 13215 if (key === "$name") continue; 13216 const value = input[key]; 13217 result[key] = registry[classRegistryKey].shallow.includes(key) ? value : deserialize(value); 13218 } 13219 return result; 13220} 13221//#endregion 13222//#region src/style/zoom_history.ts 13223var ZoomHistory = class { 13224 constructor() { 13225 this.first = true; 13226 } 13227 update(z, now) { 13228 const floorZ = Math.floor(z); 13229 if (this.first) { 13230 this.first = false; 13231 this.lastIntegerZoom = floorZ; 13232 this.lastIntegerZoomTime = 0; 13233 this.lastZoom = z; 13234 this.lastFloorZoom = floorZ; 13235 return true; 13236 } 13237 if (this.lastFloorZoom > floorZ) { 13238 this.lastIntegerZoom = floorZ + 1; 13239 this.lastIntegerZoomTime = now; 13240 } else if (this.lastFloorZoom < floorZ) { 13241 this.lastIntegerZoom = floorZ; 13242 this.lastIntegerZoomTime = now; 13243 } 13244 if (z !== this.lastZoom) { 13245 this.lastZoom = z; 13246 this.lastFloorZoom = floorZ; 13247 return true; 13248 } 13249 return false; 13250 } 13251}; 13252//#endregion 13253//#region src/style/evaluation_parameters.ts 13254/** 13255* @internal 13256* A parameter that can be evaluated to a value. 13257* It's main purpose is a parameter to expression `evaluate` methods. 13258*/ 13259var EvaluationParameters = class { 13260 constructor(zoom, options) { 13261 this.zoom = zoom; 13262 if (options) { 13263 this.now = options.now || 0; 13264 this.fadeDuration = options.fadeDuration || 0; 13265 this.zoomHistory = options.zoomHistory || new ZoomHistory(); 13266 this.transition = options.transition || {}; 13267 } else { 13268 this.now = 0; 13269 this.fadeDuration = 0; 13270 this.zoomHistory = new ZoomHistory(); 13271 this.transition = {}; 13272 } 13273 } 13274 crossFadingFactor() { 13275 if (this.fadeDuration === 0) return 1; 13276 else return Math.min((this.now - this.zoomHistory.lastIntegerZoomTime) / this.fadeDuration, 1); 13277 } 13278 getCrossfadeParameters() { 13279 const z = this.zoom; 13280 const fraction = z - Math.floor(z); 13281 const t = this.crossFadingFactor(); 13282 return z > this.zoomHistory.lastIntegerZoom ? { 13283 fromScale: 2, 13284 toScale: 1, 13285 t: fraction + (1 - fraction) * t 13286 } : { 13287 fromScale: .5, 13288 toScale: 1, 13289 t: 1 - (1 - t) * fraction 13290 }; 13291 } 13292}; 13293//#endregion 13294//#region src/style/properties.ts 13295const TRANSITION_SUFFIX = "-transition"; 13296/** 13297* @internal 13298* `PropertyValue` represents the value part of a property key-value unit. It's used to represent both 13299* paint and layout property values, and regardless of whether or not their property supports data-driven 13300* expressions. 13301* 13302* `PropertyValue` stores the raw input value as seen in a style or a runtime styling API call, i.e. one of the 13303* following: 13304* 13305* * A constant value of the type appropriate for the property 13306* * A function which produces a value of that type (but functions are quasi-deprecated in favor of expressions) 13307* * An expression which produces a value of that type 13308* * "undefined"/"not present", in which case the property is assumed to take on its default value. 13309* 13310* In addition to storing the original input value, `PropertyValue` also stores a normalized representation, 13311* effectively treating functions as if they are expressions, and constant or default values as if they are 13312* (constant) expressions. 13313*/ 13314var PropertyValue = class { 13315 constructor(property, value, rootKey, globalState) { 13316 this.property = property; 13317 this.value = value; 13318 this.expression = normalizePropertyExpression(value === void 0 ? property.specification.default : value, rootKey, property.specification, globalState); 13319 } 13320 isDataDriven() { 13321 return this.expression.kind === "source" || this.expression.kind === "composite"; 13322 } 13323 getGlobalStateRefs() { 13324 return this.expression.globalStateRefs || /* @__PURE__ */ new Set(); 13325 } 13326 /** Whether the expression reads one of the global state keys in `refs`. */ 13327 readsGlobalState(refs) { 13328 const globalStateRefs = this.getGlobalStateRefs(); 13329 return refs.some((ref) => globalStateRefs.has(ref)); 13330 } 13331 possiblyEvaluate(parameters, canonical, availableImages) { 13332 return this.property.possiblyEvaluate(this, parameters, canonical, availableImages); 13333 } 13334}; 13335/** 13336* @internal 13337* Paint properties are _transitionable_: they can change in a fluid manner, interpolating or cross-fading between 13338* old and new value. The duration of the transition, and the delay before it begins, is configurable. 13339* 13340* `TransitionablePropertyValue` is a compositional class that stores both the property value and that transition 13341* configuration. 13342* 13343* A `TransitionablePropertyValue` can calculate the next step in the evaluation chain for paint property values: 13344* `TransitioningPropertyValue`. 13345*/ 13346var TransitionablePropertyValue = class { 13347 constructor(property, rootKey, globalState) { 13348 this.property = property; 13349 this.value = new PropertyValue(property, void 0, rootKey, globalState); 13350 } 13351 /** The same `PropertyValue` means `setValue` was never called, so there is nothing to transition to. */ 13352 transitioned(parameters, prior) { 13353 if (prior.value === this.value) return prior; 13354 return new TransitioningPropertyValue(this.property, this.value, prior, extend({}, parameters.transition, this.transition), parameters.now); 13355 } 13356 untransitioned() { 13357 return new TransitioningPropertyValue(this.property, this.value, null, {}, 0); 13358 } 13359}; 13360/** 13361* @internal 13362* `Transitionable` stores a map of all (property name, `TransitionablePropertyValue`) pairs for paint properties of a 13363* given layer type. It can calculate the `TransitioningPropertyValue`s for all of them at once, producing a 13364* `Transitioning` instance for the same set of properties. 13365*/ 13366var Transitionable = class { 13367 constructor(properties, rootKey, globalState) { 13368 this._properties = properties; 13369 this._values = Object.create(properties.defaultTransitionablePropertyValues); 13370 this._globalState = globalState; 13371 this._rootKey = rootKey; 13372 } 13373 /** rootKey of a property, e.g. `layers[3].paint.line-color`. */ 13374 _propertyRootKey(name) { 13375 return `${this._rootKey}.${String(name)}`; 13376 } 13377 hasProperty(name) { 13378 return name in this._properties.defaultTransitionablePropertyValues; 13379 } 13380 getValue(name) { 13381 return clone(this._values[name].value.value); 13382 } 13383 setValue(name, value) { 13384 if (!Object.hasOwn(this._values, name)) this._values[name] = new TransitionablePropertyValue(this._values[name].property, this._propertyRootKey(name), this._globalState); 13385 this._values[name].value = new PropertyValue(this._values[name].property, value === null ? void 0 : clone(value), this._propertyRootKey(name), this._globalState); 13386 } 13387 /** Applies a whole spec, skipping the values we already hold so they do not transition. */ 13388 setValues(values) { 13389 for (const name in values) { 13390 const value = values[name]; 13391 if (name.endsWith("-transition")) this.setTransition(name.slice(0, -11), value); 13392 else if (!deepEqual$1(this._values[name].value.value, value)) this.setValue(name, value); 13393 } 13394 } 13395 getTransition(name) { 13396 return clone(this._values[name].transition); 13397 } 13398 setTransition(name, value) { 13399 if (!Object.hasOwn(this._values, name)) this._values[name] = new TransitionablePropertyValue(this._values[name].property, this._propertyRootKey(name), this._globalState); 13400 this._values[name].transition = clone(value) || void 0; 13401 } 13402 /** Keeps the transitions running in `transitioning` on `priorGlobalState` where they read one of `refs` live. */ 13403 retainPriorGlobalState(refs, priorGlobalState, transitioning) { 13404 for (const name of Object.keys(transitioning._values)) for (let step = transitioning._values[name]; step; step = step.prior) { 13405 const { value } = step; 13406 if (!value.property.specification.transition || value.isDataDriven() || value.expression._globalState !== this._globalState || !value.readsGlobalState(refs)) continue; 13407 step.value = new PropertyValue(value.property, value.value, this._propertyRootKey(name), priorGlobalState); 13408 } 13409 } 13410 /** Reads every value that reads one of `refs` again and transitions it from what `transitioning` shows. */ 13411 applyGlobalStateChange(refs, priorGlobalState, transitioning, parameters) { 13412 this.retainPriorGlobalState(refs, priorGlobalState, transitioning); 13413 let changed = false; 13414 for (const name of Object.keys(this._values)) { 13415 const { value } = this._values[name]; 13416 if (!value.readsGlobalState(refs)) continue; 13417 this.setValue(name, value.value); 13418 changed = true; 13419 } 13420 return changed ? this.transitioned(parameters, transitioning) : transitioning; 13421 } 13422 serialize() { 13423 const result = {}; 13424 for (const property of Object.keys(this._values)) { 13425 const value = this.getValue(property); 13426 if (value !== void 0) result[property] = value; 13427 const transition = this.getTransition(property); 13428 if (transition !== void 0) result[`${property}${TRANSITION_SUFFIX}`] = transition; 13429 } 13430 return result; 13431 } 13432 transitioned(parameters, prior) { 13433 const result = new Transitioning(this._properties); 13434 for (const property of Object.keys(this._values)) result._values[property] = this._values[property].transitioned(parameters, prior._values[property]); 13435 return result; 13436 } 13437 untransitioned() { 13438 const result = new Transitioning(this._properties); 13439 for (const property of Object.keys(this._values)) result._values[property] = this._values[property].untransitioned(); 13440 return result; 13441 } 13442}; 13443/** 13444* @internal 13445* `TransitioningPropertyValue` implements the first of two intermediate steps in the evaluation chain of a paint 13446* property value. In this step, transitions between old and new values are handled: as long as the transition is in 13447* progress, `TransitioningPropertyValue` maintains a reference to the prior value, and interpolates between it and 13448* the new value based on the current time and the configured transition duration and delay. The product is the next 13449* step in the evaluation chain: the "possibly evaluated" result type `R`. See below for more on this concept. 13450*/ 13451var TransitioningPropertyValue = class { 13452 constructor(property, value, prior, transition, now) { 13453 this.property = property; 13454 this.value = value; 13455 this.begin = now + transition.delay || 0; 13456 this.end = this.begin + transition.duration || 0; 13457 if (property.specification.transition && (transition.delay || transition.duration)) this.prior = prior; 13458 } 13459 possiblyEvaluate(parameters, canonical, availableImages) { 13460 const now = parameters.now || 0; 13461 const finalValue = this.value.possiblyEvaluate(parameters, canonical, availableImages); 13462 const prior = this.prior; 13463 if (!prior) return finalValue; 13464 else if (now > this.end) { 13465 this.prior = null; 13466 return finalValue; 13467 } else if (this.value.isDataDriven()) { 13468 this.prior = null; 13469 return finalValue; 13470 } else if (now < this.begin) return prior.possiblyEvaluate(parameters, canonical, availableImages); 13471 else { 13472 const t = (now - this.begin) / (this.end - this.begin); 13473 return this.property.interpolate(prior.possiblyEvaluate(parameters, canonical, availableImages), finalValue, easeCubicInOut(t)); 13474 } 13475 } 13476}; 13477/** 13478* @internal 13479* `Transitioning` stores a map of all (property name, `TransitioningPropertyValue`) pairs for paint properties of a 13480* given layer type. It can calculate the possibly-evaluated values for all of them at once, producing a 13481* `PossiblyEvaluated` instance for the same set of properties. 13482*/ 13483var Transitioning = class { 13484 constructor(properties) { 13485 this._properties = properties; 13486 this._values = Object.create(properties.defaultTransitioningPropertyValues); 13487 } 13488 possiblyEvaluate(parameters, canonical, availableImages) { 13489 const result = new PossiblyEvaluated(this._properties); 13490 for (const property of Object.keys(this._values)) result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages); 13491 return result; 13492 } 13493 hasTransition() { 13494 for (const property of Object.keys(this._values)) if (this._values[property].prior) return true; 13495 return false; 13496 } 13497}; 13498/** 13499* Because layout properties are not transitionable, they have a simpler representation and evaluation chain than 13500* paint properties: `PropertyValue`s are possibly evaluated, producing possibly evaluated values, which are then 13501* fully evaluated. 13502* 13503* `Layout` stores a map of all (property name, `PropertyValue`) pairs for layout properties of a 13504* given layer type. It can calculate the possibly-evaluated values for all of them at once, producing a 13505* `PossiblyEvaluated` instance for the same set of properties. 13506*/ 13507var Layout = class { 13508 constructor(properties, rootKey, globalState) { 13509 this._properties = properties; 13510 this._values = Object.create(properties.defaultPropertyValues); 13511 this._globalState = globalState; 13512 this._rootKey = rootKey; 13513 } 13514 /** rootKey of a property, e.g. `layers[3].layout.line-cap`. */ 13515 _propertyRootKey(name) { 13516 return `${this._rootKey}.${String(name)}`; 13517 } 13518 hasValue(name) { 13519 return this._values[name].value !== void 0; 13520 } 13521 hasProperty(name) { 13522 return name in this._properties.defaultPropertyValues; 13523 } 13524 getValue(name) { 13525 return clone(this._values[name].value); 13526 } 13527 setValue(name, value) { 13528 this._values[name] = new PropertyValue(this._values[name].property, value === null ? void 0 : clone(value), this._propertyRootKey(name), this._globalState); 13529 } 13530 serialize() { 13531 const result = {}; 13532 for (const property of Object.keys(this._values)) { 13533 const value = this.getValue(property); 13534 if (value !== void 0) result[property] = value; 13535 } 13536 return result; 13537 } 13538 possiblyEvaluate(parameters, canonical, availableImages) { 13539 const result = new PossiblyEvaluated(this._properties); 13540 for (const property of Object.keys(this._values)) result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages); 13541 return result; 13542 } 13543}; 13544/** 13545* @internal 13546* `PossiblyEvaluatedPropertyValue` is used for data-driven paint and layout property values. It holds a 13547* `PossiblyEvaluatedValue` and the `GlobalProperties` that were used to generate it. You're not allowed to supply 13548* a different set of `GlobalProperties` when performing the final evaluation because they would be ignored in the 13549* case where the input value was a constant or camera function. 13550*/ 13551var PossiblyEvaluatedPropertyValue = class { 13552 constructor(property, value, parameters) { 13553 this.property = property; 13554 this.value = value; 13555 this.parameters = parameters; 13556 } 13557 isConstant() { 13558 return this.value.kind === "constant"; 13559 } 13560 constantOr(value) { 13561 if (this.value.kind === "constant") return this.value.value; 13562 else return value; 13563 } 13564 evaluate(feature, featureState, canonical, availableImages) { 13565 return this.property.evaluate(this.value, this.parameters, feature, featureState, canonical, availableImages); 13566 } 13567}; 13568/** 13569* @internal 13570* `PossiblyEvaluated` stores a map of all (property name, `R`) pairs for paint or layout properties of a 13571* given layer type. 13572*/ 13573var PossiblyEvaluated = class { 13574 constructor(properties) { 13575 this._properties = properties; 13576 this._values = Object.create(properties.defaultPossiblyEvaluatedValues); 13577 } 13578 get(name) { 13579 return this._values[name]; 13580 } 13581}; 13582/** 13583* Returns the length of the array value, or undefined if the value is not an array or a style spec array wrapper. 13584*/ 13585function getArrayValueLength(value) { 13586 if (Array.isArray(value)) return value.length; 13587 const values = value?.values; 13588 return Array.isArray(values) ? values.length : void 0; 13589} 13590/** 13591* Returns true if the two values are arrays of different length, either bare arrays or style spec array wrappers. 13592*/ 13593function isNonInterpolableArrayChange(a, b) { 13594 const lengthA = getArrayValueLength(a); 13595 const lengthB = getArrayValueLength(b); 13596 return lengthA !== void 0 && lengthB !== void 0 && lengthA !== lengthB; 13597} 13598/** 13599* @internal 13600* An implementation of `Property` for properties that do not permit data-driven (source or composite) expressions. 13601* This restriction allows us to declare statically that the result of possibly evaluating this kind of property 13602* is in fact always the scalar type `T`, and can be used without further evaluating the value on a per-feature basis. 13603*/ 13604var DataConstantProperty = class { 13605 constructor(specification, name) { 13606 this.specification = specification; 13607 this.name = name; 13608 } 13609 possiblyEvaluate(value, parameters) { 13610 if (value.isDataDriven()) throw new Error("Value should not be data driven"); 13611 return value.expression.evaluate(parameters); 13612 } 13613 interpolate(a, b, t) { 13614 if (isNonInterpolableArrayChange(a, b)) { 13615 warnOnce(`Property "${this.name}" is trying to interpolate arrays of different lengths. Rendering may 'jump'.`); 13616 return b; 13617 } 13618 const interpolationType = this.specification.type; 13619 const interpolationFn = interpolateFactory[interpolationType]; 13620 if (interpolationFn) return interpolationFn(a, b, t); 13621 else return a; 13622 } 13623}; 13624/** 13625* @internal 13626* An implementation of `Property` for properties that permit data-driven (source or composite) expressions. 13627* The result of possibly evaluating this kind of property is `PossiblyEvaluatedPropertyValue<T>`; obtaining 13628* a scalar value `T` requires further evaluation on a per-feature basis. 13629*/ 13630var DataDrivenProperty = class { 13631 constructor(specification, name, overrides) { 13632 this.specification = specification; 13633 this.name = name; 13634 this.overrides = overrides; 13635 } 13636 possiblyEvaluate(value, parameters, canonical, availableImages) { 13637 if (value.expression.kind === "constant" || value.expression.kind === "camera") return new PossiblyEvaluatedPropertyValue(this, { 13638 kind: "constant", 13639 value: value.expression.evaluate(parameters, null, {}, canonical, availableImages) 13640 }, parameters); 13641 else return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters); 13642 } 13643 interpolate(a, b, t) { 13644 if (a.value.kind !== "constant" || b.value.kind !== "constant") return a; 13645 if (a.value.value === void 0 || b.value.value === void 0) return new PossiblyEvaluatedPropertyValue(this, { 13646 kind: "constant", 13647 value: void 0 13648 }, a.parameters); 13649 if (isNonInterpolableArrayChange(a.value.value, b.value.value)) { 13650 warnOnce(`Property "${this.name}" is trying to interpolate arrays of different lengths. Rendering may 'jump'.`); 13651 return b; 13652 } 13653 const interpolationType = this.specification.type; 13654 const interpolationFn = interpolateFactory[interpolationType]; 13655 if (interpolationFn) { 13656 const interpolatedValue = interpolationFn(a.value.value, b.value.value, t); 13657 return new PossiblyEvaluatedPropertyValue(this, { 13658 kind: "constant", 13659 value: interpolatedValue 13660 }, a.parameters); 13661 } else return a; 13662 } 13663 evaluate(value, parameters, feature, featureState, canonical, availableImages) { 13664 if (value.kind === "constant") return value.value; 13665 else return value.evaluate(parameters, feature, featureState, canonical, availableImages); 13666 } 13667}; 13668/** 13669* @internal 13670* An implementation of `Property` for data driven `line-pattern` which are transitioned by cross-fading 13671* rather than interpolation. 13672*/ 13673var CrossFadedDataDrivenProperty = class extends DataDrivenProperty { 13674 possiblyEvaluate(value, parameters, canonical, availableImages) { 13675 if (value.value === void 0) return new PossiblyEvaluatedPropertyValue(this, { 13676 kind: "constant", 13677 value: void 0 13678 }, parameters); 13679 else if (value.expression.kind === "constant") { 13680 const evaluatedValue = value.expression.evaluate(parameters, null, {}, canonical, availableImages); 13681 const constantValue = value.property.specification.type === "resolvedImage" && typeof evaluatedValue !== "string" ? evaluatedValue.name : evaluatedValue; 13682 const constant = this._calculate(constantValue, constantValue, constantValue, parameters); 13683 return new PossiblyEvaluatedPropertyValue(this, { 13684 kind: "constant", 13685 value: constant 13686 }, parameters); 13687 } else if (value.expression.kind === "camera") { 13688 const cameraVal = this._calculate(value.expression.evaluate({ zoom: parameters.zoom - 1 }), value.expression.evaluate({ zoom: parameters.zoom }), value.expression.evaluate({ zoom: parameters.zoom + 1 }), parameters); 13689 return new PossiblyEvaluatedPropertyValue(this, { 13690 kind: "constant", 13691 value: cameraVal 13692 }, parameters); 13693 } else return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters); 13694 } 13695 evaluate(value, globals, feature, featureState, canonical, availableImages) { 13696 if (value.kind === "source") { 13697 const constant = value.evaluate(globals, feature, featureState, canonical, availableImages); 13698 return this._calculate(constant, constant, constant, globals); 13699 } else if (value.kind === "composite") return this._calculate(value.evaluate({ zoom: Math.floor(globals.zoom) - 1 }, feature, featureState), value.evaluate({ zoom: Math.floor(globals.zoom) }, feature, featureState), value.evaluate({ zoom: Math.floor(globals.zoom) + 1 }, feature, featureState), globals); 13700 else return value.value; 13701 } 13702 _calculate(min, mid, max, parameters) { 13703 return parameters.zoom > parameters.zoomHistory.lastIntegerZoom ? { 13704 from: min, 13705 to: mid 13706 } : { 13707 from: max, 13708 to: mid 13709 }; 13710 } 13711 interpolate(a) { 13712 return a; 13713 } 13714}; 13715/** 13716* @internal 13717* An implementation of `Property` for `*-pattern` and `line-dasharray`, which are transitioned by cross-fading 13718* rather than interpolation. 13719*/ 13720var CrossFadedProperty = class { 13721 constructor(specification, name) { 13722 this.specification = specification; 13723 this.name = name; 13724 } 13725 possiblyEvaluate(value, parameters, canonical, availableImages) { 13726 if (value.value === void 0) return; 13727 else if (value.expression.kind === "constant") { 13728 const constant = value.expression.evaluate(parameters, null, {}, canonical, availableImages); 13729 return this._calculate(constant, constant, constant, parameters); 13730 } else return this._calculate(value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom - 1), parameters)), value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom), parameters)), value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom + 1), parameters)), parameters); 13731 } 13732 _calculate(min, mid, max, parameters) { 13733 return parameters.zoom > parameters.zoomHistory.lastIntegerZoom ? { 13734 from: min, 13735 to: mid 13736 } : { 13737 from: max, 13738 to: mid 13739 }; 13740 } 13741 interpolate(a) { 13742 return a; 13743 } 13744}; 13745/** 13746* @internal 13747* An implementation of `Property` for `heatmap-color` and `line-gradient`. Interpolation is a no-op, and 13748* evaluation returns a boolean value in order to indicate its presence, but the real 13749* evaluation happens in StyleLayer classes. 13750*/ 13751var ColorRampProperty = class { 13752 constructor(specification, name) { 13753 this.specification = specification; 13754 this.name = name; 13755 } 13756 possiblyEvaluate(value, parameters, canonical, availableImages) { 13757 return !!value.expression.evaluate(parameters, null, {}, canonical, availableImages); 13758 } 13759 interpolate() { 13760 return false; 13761 } 13762}; 13763/** 13764* @internal 13765* `Properties` holds objects containing default values for the layout or paint property set of a given 13766* layer type. These objects are immutable, and they are used as the prototypes for the `_values` members of 13767* `Transitionable`, `Transitioning`, `Layout`, and `PossiblyEvaluated`. This allows these classes to avoid 13768* doing work in the common case where a property has no explicit value set and should be considered to take 13769* on the default value: using `for (const property of Object.keys(this._values))`, they can iterate over 13770* only the _own_ properties of `_values`, skipping repeated calculation of transitions and possible/final 13771* evaluations for defaults, the result of which will always be the same. 13772*/ 13773var Properties = class { 13774 constructor(properties) { 13775 this.properties = properties; 13776 this.defaultPropertyValues = {}; 13777 this.defaultTransitionablePropertyValues = {}; 13778 this.defaultTransitioningPropertyValues = {}; 13779 this.defaultPossiblyEvaluatedValues = {}; 13780 this.overridableProperties = []; 13781 for (const property in properties) { 13782 const prop = properties[property]; 13783 if (prop.specification.overridable) this.overridableProperties.push(property); 13784 const defaultPropertyValue = this.defaultPropertyValues[property] = new PropertyValue(prop, void 0, prop.name, void 0); 13785 const defaultTransitionablePropertyValue = this.defaultTransitionablePropertyValues[property] = new TransitionablePropertyValue(prop, prop.name, void 0); 13786 this.defaultTransitioningPropertyValues[property] = defaultTransitionablePropertyValue.untransitioned(); 13787 this.defaultPossiblyEvaluatedValues[property] = defaultPropertyValue.possiblyEvaluate({}); 13788 } 13789 } 13790}; 13791register("DataDrivenProperty", DataDrivenProperty); 13792register("DataConstantProperty", DataConstantProperty); 13793register("CrossFadedDataDrivenProperty", CrossFadedDataDrivenProperty); 13794register("CrossFadedProperty", CrossFadedProperty); 13795register("ColorRampProperty", ColorRampProperty); 13796//#endregion 13797//#region src/style/style_layer.ts 13798const ERROR_PAINT_NOT_LAYOUT = " is a PAINT property not a LAYOUT property. Use get/setPaintProperty instead?"; 13799const ERROR_LAYOUT_NOT_PAINT = " is a LAYOUT property not a PAINT property. Use get/setLayoutProperty instead?"; 13800/** 13801* A base class for style layers 13802*/ 13803var StyleLayer = class extends Evented { 13804 constructor(layer, properties, globalState) { 13805 super(); 13806 this.id = layer.id; 13807 this.type = layer.type; 13808 this._globalState = globalState; 13809 this._featureFilter = { 13810 filter: () => true, 13811 needGeometry: false, 13812 getGlobalStateRefs: () => /* @__PURE__ */ new Set() 13813 }; 13814 this._visibilityExpression = createVisibility(this.visibility, `layers[${this.id}].layout.visibility`, globalState); 13815 if (layer.type === "custom") return; 13816 this.metadata = layer.metadata; 13817 this.minzoom = layer.minzoom; 13818 this.maxzoom = layer.maxzoom; 13819 if (layer.type !== "background") { 13820 this.source = layer.source; 13821 this.sourceLayer = layer["source-layer"]; 13822 this.filter = layer.filter; 13823 this._featureFilter = featureFilter(layer.filter, `layers[${this.id}].filter`, globalState); 13824 } 13825 if (properties.layout) this._unevaluatedLayout = new Layout(properties.layout, `layers[${this.id}].layout`, globalState); 13826 if (properties.paint) { 13827 this._transitionablePaint = new Transitionable(properties.paint, `layers[${this.id}].paint`, globalState); 13828 for (const property in layer.paint) this.setPaintProperty(property, layer.paint[property], { validate: false }); 13829 for (const property in layer.layout) this.setLayoutProperty(property, layer.layout[property], { validate: false }); 13830 this._transitioningPaint = this._transitionablePaint.untransitioned(); 13831 this.paint = new PossiblyEvaluated(properties.paint); 13832 } 13833 } 13834 setFilter(filter) { 13835 this.filter = filter; 13836 this._featureFilter = featureFilter(filter, `layers[${this.id}].filter`, this._globalState); 13837 } 13838 getCrossfadeParameters() { 13839 return this._crossfadeParameters; 13840 } 13841 getLayoutProperty(name) { 13842 if (name === "visibility") return this.visibility; 13843 if (this._transitionablePaint?.hasProperty(name)) throw new Error(name + ERROR_PAINT_NOT_LAYOUT); 13844 if (!this._unevaluatedLayout) throw new Error(`Cannot get layout property "${name}" on layer type "${this.type}" which has no layout properties.`); 13845 return this._unevaluatedLayout.getValue(name); 13846 } 13847 /** 13848 * Get list of global state references that are used within layout or filter properties. 13849 * This is used to determine if layer source need to be reloaded when global state property changes. 13850 * 13851 */ 13852 getLayoutAffectingGlobalStateRefs() { 13853 const globalStateRefs = /* @__PURE__ */ new Set(); 13854 for (const globalStateRef of this._visibilityExpression.getGlobalStateRefs()) globalStateRefs.add(globalStateRef); 13855 if (this._unevaluatedLayout) for (const propertyName in this._unevaluatedLayout._values) { 13856 const value = this._unevaluatedLayout._values[propertyName]; 13857 for (const globalStateRef of value.getGlobalStateRefs()) globalStateRefs.add(globalStateRef); 13858 } 13859 for (const globalStateRef of this._featureFilter.getGlobalStateRefs()) globalStateRefs.add(globalStateRef); 13860 return globalStateRefs; 13861 } 13862 /** 13863 * Get list of global state references that are used within paint properties. 13864 * This is used to determine if layer needs to be repainted when global state property changes. 13865 * 13866 */ 13867 getPaintAffectingGlobalStateRefs() { 13868 const globalStateRefs = new globalThis.Map(); 13869 if (this._transitionablePaint) for (const propertyName in this._transitionablePaint._values) { 13870 const value = this._transitionablePaint._values[propertyName].value; 13871 for (const globalStateRef of value.getGlobalStateRefs()) { 13872 const properties = globalStateRefs.get(globalStateRef) ?? []; 13873 properties.push({ 13874 name: propertyName, 13875 value: value.value 13876 }); 13877 globalStateRefs.set(globalStateRef, properties); 13878 } 13879 } 13880 return globalStateRefs; 13881 } 13882 /** 13883 * Get list of global state references that are used within visibility expression. 13884 * This is used to determine if layer visibility needs to be updated when global state property changes. 13885 */ 13886 getVisibilityAffectingGlobalStateRefs() { 13887 return this._visibilityExpression.getGlobalStateRefs(); 13888 } 13889 setLayoutProperty(name, value, options = {}) { 13890 if (name === "visibility") { 13891 this.visibility = value; 13892 this._visibilityExpression.setValue(value); 13893 this.recalculateVisibility(); 13894 return; 13895 } 13896 if (this._transitionablePaint?.hasProperty(name)) { 13897 this.fire(new ErrorEvent(/* @__PURE__ */ new Error(name + ERROR_PAINT_NOT_LAYOUT))); 13898 return; 13899 } 13900 if (value !== null && value !== void 0 && this._validate(validateStyle.layoutProperty, `layers.${this.id}.layout.${name}`, name, value, options)) return; 13901 this._unevaluatedLayout.setValue(name, value); 13902 } 13903 getPaintProperty(name) { 13904 if (name.endsWith("-transition")) { 13905 const baseName = name.slice(0, -11); 13906 if (baseName === "visibility" || this._unevaluatedLayout?.hasProperty(baseName)) throw new Error(name + ERROR_LAYOUT_NOT_PAINT); 13907 return this._transitionablePaint.getTransition(baseName); 13908 } else { 13909 if (name === "visibility" || this._unevaluatedLayout?.hasProperty(name)) throw new Error(name + ERROR_LAYOUT_NOT_PAINT); 13910 return this._transitionablePaint.getValue(name); 13911 } 13912 } 13913 setPaintProperty(name, value, options = {}) { 13914 if (name === "visibility" || this._unevaluatedLayout?.hasProperty(name)) { 13915 this.fire(new ErrorEvent(/* @__PURE__ */ new Error(name + ERROR_LAYOUT_NOT_PAINT))); 13916 return false; 13917 } 13918 if (value !== null && value !== void 0 && this._validate(validateStyle.paintProperty, `layers.${this.id}.paint.${name}`, name, value, options)) return false; 13919 if (name.endsWith("-transition")) { 13920 this._transitionablePaint.setTransition(name.slice(0, -11), value || void 0); 13921 return false; 13922 } else { 13923 const transitionable = this._transitionablePaint._values[name]; 13924 const isCrossFadedProperty = transitionable.property.specification["property-type"] === "cross-faded-data-driven"; 13925 const wasDataDriven = transitionable.value.isDataDriven(); 13926 const oldValue = transitionable.value; 13927 this._transitionablePaint.setValue(name, value); 13928 this._handleSpecialPaintPropertyUpdate(name); 13929 const newValue = this._transitionablePaint._values[name].value; 13930 return newValue.isDataDriven() || wasDataDriven || isCrossFadedProperty || this._handleOverridablePaintPropertyUpdate(name, oldValue, newValue); 13931 } 13932 } 13933 _handleSpecialPaintPropertyUpdate(_) {} 13934 _handleOverridablePaintPropertyUpdate(name, oldValue, newValue) { 13935 return false; 13936 } 13937 isHidden(zoom = this.minzoom, roundMinZoom = false) { 13938 if (this.minzoom && zoom < (roundMinZoom ? Math.floor(this.minzoom) : this.minzoom)) return true; 13939 if (this.maxzoom && zoom >= this.maxzoom) return true; 13940 return this._evaluatedVisibility === "none"; 13941 } 13942 updateTransitions(parameters) { 13943 this._transitioningPaint = this._transitionablePaint.transitioned(parameters, this._transitioningPaint); 13944 } 13945 /** The re-read itself goes through `setPaintProperty`, which also rebuilds colour ramps and relayouts. */ 13946 retainPriorGlobalState(refs, priorGlobalState) { 13947 this._transitionablePaint?.retainPriorGlobalState(refs, priorGlobalState, this._transitioningPaint); 13948 } 13949 hasTransition() { 13950 return this._transitioningPaint.hasTransition(); 13951 } 13952 recalculateVisibility() { 13953 this._evaluatedVisibility = this._visibilityExpression.evaluate(); 13954 } 13955 recalculate(parameters, availableImages) { 13956 if (parameters.getCrossfadeParameters) this._crossfadeParameters = parameters.getCrossfadeParameters(); 13957 if (this._unevaluatedLayout) this.layout = this._unevaluatedLayout.possiblyEvaluate(parameters, void 0, availableImages); 13958 this.paint = this._transitioningPaint.possiblyEvaluate(parameters, void 0, availableImages); 13959 } 13960 serialize() { 13961 const output = { 13962 "id": this.id, 13963 "type": this.type, 13964 "source": this.source, 13965 "source-layer": this.sourceLayer, 13966 "metadata": this.metadata, 13967 "minzoom": this.minzoom, 13968 "maxzoom": this.maxzoom, 13969 "filter": this.filter, 13970 "layout": this._unevaluatedLayout?.serialize(), 13971 "paint": this._transitionablePaint?.serialize() 13972 }; 13973 if (this.visibility) { 13974 output.layout ||= {}; 13975 output.layout.visibility = this.visibility; 13976 } 13977 return filterObject(output, (value, key) => { 13978 return value !== void 0 && !(key === "layout" && !Object.keys(value).length) && !(key === "paint" && !Object.keys(value).length); 13979 }); 13980 } 13981 _validate(validate, key, name, value, options = {}) { 13982 return validateAndEmit(this, validate, { 13983 key, 13984 layerType: this.type, 13985 objectKey: name, 13986 value 13987 }, options); 13988 } 13989 is3D() { 13990 return false; 13991 } 13992 isTileClipped() { 13993 return false; 13994 } 13995 hasOffscreenPass() { 13996 return false; 13997 } 13998 resize() {} 13999 isStateDependent() { 14000 for (const property in this.paint._values) { 14001 const value = this.paint.get(property); 14002 if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) continue; 14003 if ((value.value.kind === "source" || value.value.kind === "composite") && value.value.isStateDependent) return true; 14004 } 14005 return false; 14006 } 14007}; 14008//#endregion 14009//#region src/style/style_layer/raster_style_layer_properties.g.ts 14010let paint$9; 14011const getPaint$9 = () => paint$9 = paint$9 || new Properties({ 14012 "raster-opacity": new DataConstantProperty(latest["paint_raster"]["raster-opacity"], "raster-opacity"), 14013 "raster-hue-rotate": new DataConstantProperty(latest["paint_raster"]["raster-hue-rotate"], "raster-hue-rotate"), 14014 "raster-brightness-min": new DataConstantProperty(latest["paint_raster"]["raster-brightness-min"], "raster-brightness-min"), 14015 "raster-brightness-max": new DataConstantProperty(latest["paint_raster"]["raster-brightness-max"], "raster-brightness-max"), 14016 "raster-saturation": new DataConstantProperty(latest["paint_raster"]["raster-saturation"], "raster-saturation"), 14017 "raster-contrast": new DataConstantProperty(latest["paint_raster"]["raster-contrast"], "raster-contrast"), 14018 "resampling": new DataConstantProperty(latest["paint_raster"]["resampling"], "resampling"), 14019 "raster-resampling": new DataConstantProperty(latest["paint_raster"]["raster-resampling"], "raster-resampling"), 14020 "raster-fade-duration": new DataConstantProperty(latest["paint_raster"]["raster-fade-duration"], "raster-fade-duration") 14021}); 14022var raster_style_layer_properties_g_default = { get paint() { 14023 return getPaint$9(); 14024} }; 14025//#endregion 14026//#region src/style/style_layer/raster_style_layer.ts 14027const isRasterStyleLayer = (layer) => layer.type === "raster"; 14028var RasterStyleLayer = class extends StyleLayer { 14029 constructor(layer, globalState) { 14030 super(layer, raster_style_layer_properties_g_default, globalState); 14031 } 14032}; 14033//#endregion 14034//#region src/util/struct_array.ts 14035/** 14036* @internal 14037* A view type size 14038*/ 14039const viewTypes = { 14040 "Int8": Int8Array, 14041 "Uint8": Uint8Array, 14042 "Int16": Int16Array, 14043 "Uint16": Uint16Array, 14044 "Int32": Int32Array, 14045 "Uint32": Uint32Array, 14046 "Float32": Float32Array 14047}; 14048/** @internal */ 14049var Struct = class { 14050 /** 14051 * @param structArray - The StructArray the struct is stored in 14052 * @param index - The index of the struct in the StructArray. 14053 */ 14054 constructor(structArray, index) { 14055 this._structArray = structArray; 14056 this._pos1 = index * this.size; 14057 this._pos2 = this._pos1 / 2; 14058 this._pos4 = this._pos1 / 4; 14059 this._pos8 = this._pos1 / 8; 14060 } 14061}; 14062const DEFAULT_CAPACITY = 128; 14063const RESIZE_MULTIPLIER = 5; 14064/** 14065* @internal 14066* `StructArray` provides an abstraction over `ArrayBuffer` and `TypedArray` 14067* making it behave like an array of typed structs. 14068* 14069* Conceptually, a StructArray is comprised of elements, i.e., instances of its 14070* associated struct type. Each particular struct type, together with an 14071* alignment size, determines the memory layout of a StructArray whose elements 14072* are of that type. Thus, for each such layout that we need, we have 14073* a corresponding StructArrayLayout class, inheriting from StructArray and 14074* implementing `emplaceBack()` and `_refreshViews()`. 14075* 14076* In some cases, where we need to access particular elements of a StructArray, 14077* we implement a more specific subclass that inherits from one of the 14078* StructArrayLayouts and adds a `get(i): T` accessor that returns a structured 14079* object whose properties are proxies into the underlying memory space for the 14080* i-th element. This affords the convenience of working with (seemingly) plain 14081* Javascript objects without the overhead of serializing/deserializing them 14082* into ArrayBuffers for efficient web worker transfer. 14083*/ 14084var StructArray = class { 14085 constructor() { 14086 this.isTransferred = false; 14087 this.capacity = -1; 14088 this.resize(0); 14089 } 14090 /** 14091 * Serialize a StructArray instance. Serializes both the raw data and the 14092 * metadata needed to reconstruct the StructArray base class during 14093 * deserialization. 14094 */ 14095 static serialize(array, transferables) { 14096 array._trim(); 14097 if (transferables) { 14098 array.isTransferred = true; 14099 transferables.push(array.arrayBuffer); 14100 } 14101 return { 14102 length: array.length, 14103 arrayBuffer: array.arrayBuffer 14104 }; 14105 } 14106 static deserialize(input) { 14107 const structArray = Object.create(this.prototype); 14108 structArray.arrayBuffer = input.arrayBuffer; 14109 structArray.length = input.length; 14110 structArray.capacity = input.arrayBuffer.byteLength / structArray.bytesPerElement; 14111 structArray._refreshViews(); 14112 return structArray; 14113 } 14114 /** 14115 * Resize the array to discard unused capacity. 14116 */ 14117 _trim() { 14118 if (this.length !== this.capacity) { 14119 this.capacity = this.length; 14120 this.arrayBuffer = this.arrayBuffer.slice(0, this.length * this.bytesPerElement); 14121 this._refreshViews(); 14122 } 14123 } 14124 /** 14125 * Resets the length of the array to 0 without de-allocating capacity. 14126 */ 14127 clear() { 14128 this.length = 0; 14129 } 14130 /** 14131 * Resize the array. 14132 * If `n` is greater than the current length then additional elements with undefined values are added. 14133 * If `n` is less than the current length then the array will be reduced to the first `n` elements. 14134 * @param n - The new size of the array. 14135 */ 14136 resize(n) { 14137 this.reserve(n); 14138 this.length = n; 14139 } 14140 /** 14141 * Indicate a planned increase in size, so that any necessary allocation may 14142 * be done once, ahead of time. 14143 * @param n - The expected size of the array. 14144 */ 14145 reserve(n) { 14146 if (n > this.capacity) { 14147 this.capacity = Math.max(n, Math.floor(this.capacity * RESIZE_MULTIPLIER), DEFAULT_CAPACITY); 14148 this.arrayBuffer = new ArrayBuffer(this.capacity * this.bytesPerElement); 14149 const oldUint8Array = this.uint8; 14150 this._refreshViews(); 14151 if (oldUint8Array) this.uint8.set(oldUint8Array); 14152 } 14153 } 14154 /** 14155 * Create TypedArray views for the current ArrayBuffer. 14156 */ 14157 _refreshViews() { 14158 throw new Error("_refreshViews() must be implemented by each concrete StructArray layout"); 14159 } 14160 /** 14161 * Replace the buffer with an empty one so typed views release the original ArrayBuffer for GC. 14162 */ 14163 freeBufferAfterUpload() { 14164 this.arrayBuffer = /* @__PURE__ */ new ArrayBuffer(0); 14165 this._refreshViews(); 14166 } 14167}; 14168/** 14169* Given a list of member fields, create a full StructArrayLayout, in 14170* particular calculating the correct byte offset for each field. This data 14171* is used at build time to generate StructArrayLayout_*.emplaceBack() and 14172* other accessors, and at runtime for binding vertex buffer attributes. 14173*/ 14174function createLayout(members, alignment = 1) { 14175 let offset = 0; 14176 let maxSize = 0; 14177 return { 14178 members: members.map((member) => { 14179 const typeSize = sizeOf(member.type); 14180 const memberOffset = offset = align$1(offset, Math.max(alignment, typeSize)); 14181 const components = member.components || 1; 14182 maxSize = Math.max(maxSize, typeSize); 14183 offset += typeSize * components; 14184 return { 14185 name: member.name, 14186 type: member.type, 14187 components, 14188 offset: memberOffset 14189 }; 14190 }), 14191 size: align$1(offset, Math.max(maxSize, alignment)), 14192 alignment 14193 }; 14194} 14195function sizeOf(type) { 14196 return viewTypes[type].BYTES_PER_ELEMENT; 14197} 14198function align$1(offset, size) { 14199 return Math.ceil(offset / size) * size; 14200} 14201//#endregion 14202//#region src/data/array_types.g.ts 14203/** 14204* @internal 14205* Implementation of the StructArray layout: 14206* [0] - Int16[2] 14207* 14208*/ 14209var StructArrayLayout2i4 = class extends StructArray { 14210 _refreshViews() { 14211 this.uint8 = new Uint8Array(this.arrayBuffer); 14212 this.int16 = new Int16Array(this.arrayBuffer); 14213 } 14214 emplaceBack(v0, v1) { 14215 const i = this.length; 14216 this.resize(i + 1); 14217 return this.emplace(i, v0, v1); 14218 } 14219 emplace(i, v0, v1) { 14220 const o2 = i * 2; 14221 this.int16[o2 + 0] = v0; 14222 this.int16[o2 + 1] = v1; 14223 return i; 14224 } 14225}; 14226StructArrayLayout2i4.prototype.bytesPerElement = 4; 14227register("StructArrayLayout2i4", StructArrayLayout2i4); 14228/** 14229* @internal 14230* Implementation of the StructArray layout: 14231* [0] - Int16[3] 14232* 14233*/ 14234var StructArrayLayout3i6 = class extends StructArray { 14235 _refreshViews() { 14236 this.uint8 = new Uint8Array(this.arrayBuffer); 14237 this.int16 = new Int16Array(this.arrayBuffer); 14238 } 14239 emplaceBack(v0, v1, v2) { 14240 const i = this.length; 14241 this.resize(i + 1); 14242 return this.emplace(i, v0, v1, v2); 14243 } 14244 emplace(i, v0, v1, v2) { 14245 const o2 = i * 3; 14246 this.int16[o2 + 0] = v0; 14247 this.int16[o2 + 1] = v1; 14248 this.int16[o2 + 2] = v2; 14249 return i; 14250 } 14251}; 14252StructArrayLayout3i6.prototype.bytesPerElement = 6; 14253register("StructArrayLayout3i6", StructArrayLayout3i6); 14254/** 14255* @internal 14256* Implementation of the StructArray layout: 14257* [0] - Int16[4] 14258* 14259*/ 14260var StructArrayLayout4i8 = class extends StructArray { 14261 _refreshViews() { 14262 this.uint8 = new Uint8Array(this.arrayBuffer); 14263 this.int16 = new Int16Array(this.arrayBuffer); 14264 } 14265 emplaceBack(v0, v1, v2, v3) { 14266 const i = this.length; 14267 this.resize(i + 1); 14268 return this.emplace(i, v0, v1, v2, v3); 14269 } 14270 emplace(i, v0, v1, v2, v3) { 14271 const o2 = i * 4; 14272 this.int16[o2 + 0] = v0; 14273 this.int16[o2 + 1] = v1; 14274 this.int16[o2 + 2] = v2; 14275 this.int16[o2 + 3] = v3; 14276 return i; 14277 } 14278}; 14279StructArrayLayout4i8.prototype.bytesPerElement = 8; 14280register("StructArrayLayout4i8", StructArrayLayout4i8); 14281/** 14282* @internal 14283* Implementation of the StructArray layout: 14284* [0] - Int16[2] 14285* [4] - Int16[4] 14286* 14287*/ 14288var StructArrayLayout2i4i12 = class extends StructArray { 14289 _refreshViews() { 14290 this.uint8 = new Uint8Array(this.arrayBuffer); 14291 this.int16 = new Int16Array(this.arrayBuffer); 14292 } 14293 emplaceBack(v0, v1, v2, v3, v4, v5) { 14294 const i = this.length; 14295 this.resize(i + 1); 14296 return this.emplace(i, v0, v1, v2, v3, v4, v5); 14297 } 14298 emplace(i, v0, v1, v2, v3, v4, v5) { 14299 const o2 = i * 6; 14300 this.int16[o2 + 0] = v0; 14301 this.int16[o2 + 1] = v1; 14302 this.int16[o2 + 2] = v2; 14303 this.int16[o2 + 3] = v3; 14304 this.int16[o2 + 4] = v4; 14305 this.int16[o2 + 5] = v5; 14306 return i; 14307 } 14308}; 14309StructArrayLayout2i4i12.prototype.bytesPerElement = 12; 14310register("StructArrayLayout2i4i12", StructArrayLayout2i4i12); 14311/** 14312* @internal 14313* Implementation of the StructArray layout: 14314* [0] - Int16[2] 14315* [4] - Uint8[4] 14316* 14317*/ 14318var StructArrayLayout2i4ub8 = class extends StructArray { 14319 _refreshViews() { 14320 this.uint8 = new Uint8Array(this.arrayBuffer); 14321 this.int16 = new Int16Array(this.arrayBuffer); 14322 } 14323 emplaceBack(v0, v1, v2, v3, v4, v5) { 14324 const i = this.length; 14325 this.resize(i + 1); 14326 return this.emplace(i, v0, v1, v2, v3, v4, v5); 14327 } 14328 emplace(i, v0, v1, v2, v3, v4, v5) { 14329 const o2 = i * 4; 14330 const o1 = i * 8; 14331 this.int16[o2 + 0] = v0; 14332 this.int16[o2 + 1] = v1; 14333 this.uint8[o1 + 4] = v2; 14334 this.uint8[o1 + 5] = v3; 14335 this.uint8[o1 + 6] = v4; 14336 this.uint8[o1 + 7] = v5; 14337 return i; 14338 } 14339}; 14340StructArrayLayout2i4ub8.prototype.bytesPerElement = 8; 14341register("StructArrayLayout2i4ub8", StructArrayLayout2i4ub8); 14342/** 14343* @internal 14344* Implementation of the StructArray layout: 14345* [0] - Float32[2] 14346* 14347*/ 14348var StructArrayLayout2f8 = class extends StructArray { 14349 _refreshViews() { 14350 this.uint8 = new Uint8Array(this.arrayBuffer); 14351 this.float32 = new Float32Array(this.arrayBuffer); 14352 } 14353 emplaceBack(v0, v1) { 14354 const i = this.length; 14355 this.resize(i + 1); 14356 return this.emplace(i, v0, v1); 14357 } 14358 emplace(i, v0, v1) { 14359 const o4 = i * 2; 14360 this.float32[o4 + 0] = v0; 14361 this.float32[o4 + 1] = v1; 14362 return i; 14363 } 14364}; 14365StructArrayLayout2f8.prototype.bytesPerElement = 8; 14366register("StructArrayLayout2f8", StructArrayLayout2f8); 14367/** 14368* @internal 14369* Implementation of the StructArray layout: 14370* [0] - Uint16[10] 14371* 14372*/ 14373var StructArrayLayout10ui20 = class extends StructArray { 14374 _refreshViews() { 14375 this.uint8 = new Uint8Array(this.arrayBuffer); 14376 this.uint16 = new Uint16Array(this.arrayBuffer); 14377 } 14378 emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) { 14379 const i = this.length; 14380 this.resize(i + 1); 14381 return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9); 14382 } 14383 emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) { 14384 const o2 = i * 10; 14385 this.uint16[o2 + 0] = v0; 14386 this.uint16[o2 + 1] = v1; 14387 this.uint16[o2 + 2] = v2; 14388 this.uint16[o2 + 3] = v3; 14389 this.uint16[o2 + 4] = v4; 14390 this.uint16[o2 + 5] = v5; 14391 this.uint16[o2 + 6] = v6; 14392 this.uint16[o2 + 7] = v7; 14393 this.uint16[o2 + 8] = v8; 14394 this.uint16[o2 + 9] = v9; 14395 return i; 14396 } 14397}; 14398StructArrayLayout10ui20.prototype.bytesPerElement = 20; 14399register("StructArrayLayout10ui20", StructArrayLayout10ui20); 14400/** 14401* @internal 14402* Implementation of the StructArray layout: 14403* [0] - Uint16[8] 14404* 14405*/ 14406var StructArrayLayout8ui16 = class extends StructArray { 14407 _refreshViews() { 14408 this.uint8 = new Uint8Array(this.arrayBuffer); 14409 this.uint16 = new Uint16Array(this.arrayBuffer); 14410 } 14411 emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7) { 14412 const i = this.length; 14413 this.resize(i + 1); 14414 return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7); 14415 } 14416 emplace(i, v0, v1, v2, v3, v4, v5, v6, v7) { 14417 const o2 = i * 8; 14418 this.uint16[o2 + 0] = v0; 14419 this.uint16[o2 + 1] = v1; 14420 this.uint16[o2 + 2] = v2; 14421 this.uint16[o2 + 3] = v3; 14422 this.uint16[o2 + 4] = v4; 14423 this.uint16[o2 + 5] = v5; 14424 this.uint16[o2 + 6] = v6; 14425 this.uint16[o2 + 7] = v7; 14426 return i; 14427 } 14428}; 14429StructArrayLayout8ui16.prototype.bytesPerElement = 16; 14430register("StructArrayLayout8ui16", StructArrayLayout8ui16); 14431/** 14432* @internal 14433* Implementation of the StructArray layout: 14434* [0] - Int16[4] 14435* [8] - Uint16[4] 14436* [16] - Int16[4] 14437* [24] - Float32[1] 14438* 14439*/ 14440var StructArrayLayout4i4ui4i1f28 = class extends StructArray { 14441 _refreshViews() { 14442 this.uint8 = new Uint8Array(this.arrayBuffer); 14443 this.int16 = new Int16Array(this.arrayBuffer); 14444 this.uint16 = new Uint16Array(this.arrayBuffer); 14445 this.float32 = new Float32Array(this.arrayBuffer); 14446 } 14447 emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) { 14448 const i = this.length; 14449 this.resize(i + 1); 14450 return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12); 14451 } 14452 emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) { 14453 const o2 = i * 14; 14454 const o4 = i * 7; 14455 this.int16[o2 + 0] = v0; 14456 this.int16[o2 + 1] = v1; 14457 this.int16[o2 + 2] = v2; 14458 this.int16[o2 + 3] = v3; 14459 this.uint16[o2 + 4] = v4; 14460 this.uint16[o2 + 5] = v5; 14461 this.uint16[o2 + 6] = v6; 14462 this.uint16[o2 + 7] = v7; 14463 this.int16[o2 + 8] = v8; 14464 this.int16[o2 + 9] = v9; 14465 this.int16[o2 + 10] = v10; 14466 this.int16[o2 + 11] = v11; 14467 this.float32[o4 + 6] = v12; 14468 return i; 14469 } 14470}; 14471StructArrayLayout4i4ui4i1f28.prototype.bytesPerElement = 28; 14472register("StructArrayLayout4i4ui4i1f28", StructArrayLayout4i4ui4i1f28); 14473/** 14474* @internal 14475* Implementation of the StructArray layout: 14476* [0] - Float32[3] 14477* 14478*/ 14479var StructArrayLayout3f12 = class extends StructArray { 14480 _refreshViews() { 14481 this.uint8 = new Uint8Array(this.arrayBuffer); 14482 this.float32 = new Float32Array(this.arrayBuffer); 14483 } 14484 emplaceBack(v0, v1, v2) { 14485 const i = this.length; 14486 this.resize(i + 1); 14487 return this.emplace(i, v0, v1, v2); 14488 } 14489 emplace(i, v0, v1, v2) { 14490 const o4 = i * 3; 14491 this.float32[o4 + 0] = v0; 14492 this.float32[o4 + 1] = v1; 14493 this.float32[o4 + 2] = v2; 14494 return i; 14495 } 14496}; 14497StructArrayLayout3f12.prototype.bytesPerElement = 12; 14498register("StructArrayLayout3f12", StructArrayLayout3f12); 14499/** 14500* @internal 14501* Implementation of the StructArray layout: 14502* [0] - Uint32[1] 14503* 14504*/ 14505var StructArrayLayout1ul4 = class extends StructArray { 14506 _refreshViews() { 14507 this.uint8 = new Uint8Array(this.arrayBuffer); 14508 this.uint32 = new Uint32Array(this.arrayBuffer); 14509 } 14510 emplaceBack(v0) { 14511 const i = this.length; 14512 this.resize(i + 1); 14513 return this.emplace(i, v0); 14514 } 14515 emplace(i, v0) { 14516 const o4 = i * 1; 14517 this.uint32[o4 + 0] = v0; 14518 return i; 14519 } 14520}; 14521StructArrayLayout1ul4.prototype.bytesPerElement = 4; 14522register("StructArrayLayout1ul4", StructArrayLayout1ul4); 14523/** 14524* @internal 14525* Implementation of the StructArray layout: 14526* [0] - Int16[6] 14527* [12] - Uint32[1] 14528* [16] - Uint16[2] 14529* 14530*/ 14531var StructArrayLayout6i1ul2ui20 = class extends StructArray { 14532 _refreshViews() { 14533 this.uint8 = new Uint8Array(this.arrayBuffer); 14534 this.int16 = new Int16Array(this.arrayBuffer); 14535 this.uint32 = new Uint32Array(this.arrayBuffer); 14536 this.uint16 = new Uint16Array(this.arrayBuffer); 14537 } 14538 emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8) { 14539 const i = this.length; 14540 this.resize(i + 1); 14541 return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8); 14542 } 14543 emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8) { 14544 const o2 = i * 10; 14545 const o4 = i * 5; 14546 this.int16[o2 + 0] = v0; 14547 this.int16[o2 + 1] = v1; 14548 this.int16[o2 + 2] = v2; 14549 this.int16[o2 + 3] = v3; 14550 this.int16[o2 + 4] = v4; 14551 this.int16[o2 + 5] = v5; 14552 this.uint32[o4 + 3] = v6; 14553 this.uint16[o2 + 8] = v7; 14554 this.uint16[o2 + 9] = v8; 14555 return i; 14556 } 14557}; 14558StructArrayLayout6i1ul2ui20.prototype.bytesPerElement = 20; 14559register("StructArrayLayout6i1ul2ui20", StructArrayLayout6i1ul2ui20); 14560/** 14561* @internal 14562* Implementation of the StructArray layout: 14563* [0] - Int16[2] 14564* [4] - Int16[2] 14565* [8] - Int16[2] 14566* 14567*/ 14568var StructArrayLayout2i2i2i12 = class extends StructArray { 14569 _refreshViews() { 14570 this.uint8 = new Uint8Array(this.arrayBuffer); 14571 this.int16 = new Int16Array(this.arrayBuffer); 14572 } 14573 emplaceBack(v0, v1, v2, v3, v4, v5) { 14574 const i = this.length; 14575 this.resize(i + 1); 14576 return this.emplace(i, v0, v1, v2, v3, v4, v5); 14577 } 14578 emplace(i, v0, v1, v2, v3, v4, v5) { 14579 const o2 = i * 6; 14580 this.int16[o2 + 0] = v0; 14581 this.int16[o2 + 1] = v1; 14582 this.int16[o2 + 2] = v2; 14583 this.int16[o2 + 3] = v3; 14584 this.int16[o2 + 4] = v4; 14585 this.int16[o2 + 5] = v5; 14586 return i; 14587 } 14588}; 14589StructArrayLayout2i2i2i12.prototype.bytesPerElement = 12; 14590register("StructArrayLayout2i2i2i12", StructArrayLayout2i2i2i12); 14591/** 14592* @internal 14593* Implementation of the StructArray layout: 14594* [0] - Float32[2] 14595* [8] - Float32[1] 14596* [12] - Int16[2] 14597* 14598*/ 14599var StructArrayLayout2f1f2i16 = class extends StructArray { 14600 _refreshViews() { 14601 this.uint8 = new Uint8Array(this.arrayBuffer); 14602 this.float32 = new Float32Array(this.arrayBuffer); 14603 this.int16 = new Int16Array(this.arrayBuffer); 14604 } 14605 emplaceBack(v0, v1, v2, v3, v4) { 14606 const i = this.length; 14607 this.resize(i + 1); 14608 return this.emplace(i, v0, v1, v2, v3, v4); 14609 } 14610 emplace(i, v0, v1, v2, v3, v4) { 14611 const o4 = i * 4; 14612 const o2 = i * 8; 14613 this.float32[o4 + 0] = v0; 14614 this.float32[o4 + 1] = v1; 14615 this.float32[o4 + 2] = v2; 14616 this.int16[o2 + 6] = v3; 14617 this.int16[o2 + 7] = v4; 14618 return i; 14619 } 14620}; 14621StructArrayLayout2f1f2i16.prototype.bytesPerElement = 16; 14622register("StructArrayLayout2f1f2i16", StructArrayLayout2f1f2i16); 14623/** 14624* @internal 14625* Implementation of the StructArray layout: 14626* [0] - Uint8[2] 14627* [4] - Float32[2] 14628* [12] - Int16[2] 14629* 14630*/ 14631var StructArrayLayout2ub2f2i16 = class extends StructArray { 14632 _refreshViews() { 14633 this.uint8 = new Uint8Array(this.arrayBuffer); 14634 this.float32 = new Float32Array(this.arrayBuffer); 14635 this.int16 = new Int16Array(this.arrayBuffer); 14636 } 14637 emplaceBack(v0, v1, v2, v3, v4, v5) { 14638 const i = this.length; 14639 this.resize(i + 1); 14640 return this.emplace(i, v0, v1, v2, v3, v4, v5); 14641 } 14642 emplace(i, v0, v1, v2, v3, v4, v5) { 14643 const o1 = i * 16; 14644 const o4 = i * 4; 14645 const o2 = i * 8; 14646 this.uint8[o1 + 0] = v0; 14647 this.uint8[o1 + 1] = v1; 14648 this.float32[o4 + 1] = v2; 14649 this.float32[o4 + 2] = v3; 14650 this.int16[o2 + 6] = v4; 14651 this.int16[o2 + 7] = v5; 14652 return i; 14653 } 14654}; 14655StructArrayLayout2ub2f2i16.prototype.bytesPerElement = 16; 14656register("StructArrayLayout2ub2f2i16", StructArrayLayout2ub2f2i16); 14657/** 14658* @internal 14659* Implementation of the StructArray layout: 14660* [0] - Uint16[3] 14661* 14662*/ 14663var StructArrayLayout3ui6 = class extends StructArray { 14664 _refreshViews() { 14665 this.uint8 = new Uint8Array(this.arrayBuffer); 14666 this.uint16 = new Uint16Array(this.arrayBuffer); 14667 } 14668 emplaceBack(v0, v1, v2) { 14669 const i = this.length; 14670 this.resize(i + 1); 14671 return this.emplace(i, v0, v1, v2); 14672 } 14673 emplace(i, v0, v1, v2) { 14674 const o2 = i * 3; 14675 this.uint16[o2 + 0] = v0; 14676 this.uint16[o2 + 1] = v1; 14677 this.uint16[o2 + 2] = v2; 14678 return i; 14679 } 14680}; 14681StructArrayLayout3ui6.prototype.bytesPerElement = 6; 14682register("StructArrayLayout3ui6", StructArrayLayout3ui6); 14683/** 14684* @internal 14685* Implementation of the StructArray layout: 14686* [0] - Int16[2] 14687* [4] - Uint16[2] 14688* [8] - Uint32[3] 14689* [20] - Uint16[3] 14690* [28] - Float32[2] 14691* [36] - Uint8[3] 14692* [40] - Uint32[1] 14693* [44] - Int16[1] 14694* [48] - Float32[1] 14695* 14696*/ 14697var StructArrayLayout2i2ui3ul3ui2f3ub1ul1i1f52 = class extends StructArray { 14698 _refreshViews() { 14699 this.uint8 = new Uint8Array(this.arrayBuffer); 14700 this.int16 = new Int16Array(this.arrayBuffer); 14701 this.uint16 = new Uint16Array(this.arrayBuffer); 14702 this.uint32 = new Uint32Array(this.arrayBuffer); 14703 this.float32 = new Float32Array(this.arrayBuffer); 14704 } 14705 emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) { 14706 const i = this.length; 14707 this.resize(i + 1); 14708 return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17); 14709 } 14710 emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) { 14711 const o2 = i * 26; 14712 const o4 = i * 13; 14713 const o1 = i * 52; 14714 this.int16[o2 + 0] = v0; 14715 this.int16[o2 + 1] = v1; 14716 this.uint16[o2 + 2] = v2; 14717 this.uint16[o2 + 3] = v3; 14718 this.uint32[o4 + 2] = v4; 14719 this.uint32[o4 + 3] = v5; 14720 this.uint32[o4 + 4] = v6; 14721 this.uint16[o2 + 10] = v7; 14722 this.uint16[o2 + 11] = v8; 14723 this.uint16[o2 + 12] = v9; 14724 this.float32[o4 + 7] = v10; 14725 this.float32[o4 + 8] = v11; 14726 this.uint8[o1 + 36] = v12; 14727 this.uint8[o1 + 37] = v13; 14728 this.uint8[o1 + 38] = v14; 14729 this.uint32[o4 + 10] = v15; 14730 this.int16[o2 + 22] = v16; 14731 this.float32[o4 + 12] = v17; 14732 return i; 14733 } 14734}; 14735StructArrayLayout2i2ui3ul3ui2f3ub1ul1i1f52.prototype.bytesPerElement = 52; 14736register("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i1f52", StructArrayLayout2i2ui3ul3ui2f3ub1ul1i1f52); 14737/** 14738* @internal 14739* Implementation of the StructArray layout: 14740* [0] - Int16[8] 14741* [16] - Uint16[15] 14742* [48] - Uint32[1] 14743* [52] - Float32[2] 14744* [60] - Uint16[2] 14745* [64] - Float32[1] 14746* 14747*/ 14748var StructArrayLayout8i15ui1ul2f2ui1f68 = class extends StructArray { 14749 _refreshViews() { 14750 this.uint8 = new Uint8Array(this.arrayBuffer); 14751 this.int16 = new Int16Array(this.arrayBuffer); 14752 this.uint16 = new Uint16Array(this.arrayBuffer); 14753 this.uint32 = new Uint32Array(this.arrayBuffer); 14754 this.float32 = new Float32Array(this.arrayBuffer); 14755 } 14756 emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) { 14757 const i = this.length; 14758 this.resize(i + 1); 14759 return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28); 14760 } 14761 emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) { 14762 const o2 = i * 34; 14763 const o4 = i * 17; 14764 this.int16[o2 + 0] = v0; 14765 this.int16[o2 + 1] = v1; 14766 this.int16[o2 + 2] = v2; 14767 this.int16[o2 + 3] = v3; 14768 this.int16[o2 + 4] = v4; 14769 this.int16[o2 + 5] = v5; 14770 this.int16[o2 + 6] = v6; 14771 this.int16[o2 + 7] = v7; 14772 this.uint16[o2 + 8] = v8; 14773 this.uint16[o2 + 9] = v9; 14774 this.uint16[o2 + 10] = v10; 14775 this.uint16[o2 + 11] = v11; 14776 this.uint16[o2 + 12] = v12; 14777 this.uint16[o2 + 13] = v13; 14778 this.uint16[o2 + 14] = v14; 14779 this.uint16[o2 + 15] = v15; 14780 this.uint16[o2 + 16] = v16; 14781 this.uint16[o2 + 17] = v17; 14782 this.uint16[o2 + 18] = v18; 14783 this.uint16[o2 + 19] = v19; 14784 this.uint16[o2 + 20] = v20; 14785 this.uint16[o2 + 21] = v21; 14786 this.uint16[o2 + 22] = v22; 14787 this.uint32[o4 + 12] = v23; 14788 this.float32[o4 + 13] = v24; 14789 this.float32[o4 + 14] = v25; 14790 this.uint16[o2 + 30] = v26; 14791 this.uint16[o2 + 31] = v27; 14792 this.float32[o4 + 16] = v28; 14793 return i; 14794 } 14795}; 14796StructArrayLayout8i15ui1ul2f2ui1f68.prototype.bytesPerElement = 68; 14797register("StructArrayLayout8i15ui1ul2f2ui1f68", StructArrayLayout8i15ui1ul2f2ui1f68); 14798/** 14799* @internal 14800* Implementation of the StructArray layout: 14801* [0] - Float32[1] 14802* 14803*/ 14804var StructArrayLayout1f4 = class extends StructArray { 14805 _refreshViews() { 14806 this.uint8 = new Uint8Array(this.arrayBuffer); 14807 this.float32 = new Float32Array(this.arrayBuffer); 14808 } 14809 emplaceBack(v0) { 14810 const i = this.length; 14811 this.resize(i + 1); 14812 return this.emplace(i, v0); 14813 } 14814 emplace(i, v0) { 14815 const o4 = i * 1; 14816 this.float32[o4 + 0] = v0; 14817 return i; 14818 } 14819}; 14820StructArrayLayout1f4.prototype.bytesPerElement = 4; 14821register("StructArrayLayout1f4", StructArrayLayout1f4); 14822/** 14823* @internal 14824* Implementation of the StructArray layout: 14825* [0] - Uint16[1] 14826* [4] - Float32[2] 14827* 14828*/ 14829var StructArrayLayout1ui2f12 = class extends StructArray { 14830 _refreshViews() { 14831 this.uint8 = new Uint8Array(this.arrayBuffer); 14832 this.uint16 = new Uint16Array(this.arrayBuffer); 14833 this.float32 = new Float32Array(this.arrayBuffer); 14834 } 14835 emplaceBack(v0, v1, v2) { 14836 const i = this.length; 14837 this.resize(i + 1); 14838 return this.emplace(i, v0, v1, v2); 14839 } 14840 emplace(i, v0, v1, v2) { 14841 const o2 = i * 6; 14842 const o4 = i * 3; 14843 this.uint16[o2 + 0] = v0; 14844 this.float32[o4 + 1] = v1; 14845 this.float32[o4 + 2] = v2; 14846 return i; 14847 } 14848}; 14849StructArrayLayout1ui2f12.prototype.bytesPerElement = 12; 14850register("StructArrayLayout1ui2f12", StructArrayLayout1ui2f12); 14851/** 14852* @internal 14853* Implementation of the StructArray layout: 14854* [0] - Uint32[1] 14855* [4] - Uint16[2] 14856* 14857*/ 14858var StructArrayLayout1ul2ui8 = class extends StructArray { 14859 _refreshViews() { 14860 this.uint8 = new Uint8Array(this.arrayBuffer); 14861 this.uint32 = new Uint32Array(this.arrayBuffer); 14862 this.uint16 = new Uint16Array(this.arrayBuffer); 14863 } 14864 emplaceBack(v0, v1, v2) { 14865 const i = this.length; 14866 this.resize(i + 1); 14867 return this.emplace(i, v0, v1, v2); 14868 } 14869 emplace(i, v0, v1, v2) { 14870 const o4 = i * 2; 14871 const o2 = i * 4; 14872 this.uint32[o4 + 0] = v0; 14873 this.uint16[o2 + 2] = v1; 14874 this.uint16[o2 + 3] = v2; 14875 return i; 14876 } 14877}; 14878StructArrayLayout1ul2ui8.prototype.bytesPerElement = 8; 14879register("StructArrayLayout1ul2ui8", StructArrayLayout1ul2ui8); 14880/** 14881* @internal 14882* Implementation of the StructArray layout: 14883* [0] - Uint16[2] 14884* 14885*/ 14886var StructArrayLayout2ui4 = class extends StructArray { 14887 _refreshViews() { 14888 this.uint8 = new Uint8Array(this.arrayBuffer); 14889 this.uint16 = new Uint16Array(this.arrayBuffer); 14890 } 14891 emplaceBack(v0, v1) { 14892 const i = this.length; 14893 this.resize(i + 1); 14894 return this.emplace(i, v0, v1); 14895 } 14896 emplace(i, v0, v1) { 14897 const o2 = i * 2; 14898 this.uint16[o2 + 0] = v0; 14899 this.uint16[o2 + 1] = v1; 14900 return i; 14901 } 14902}; 14903StructArrayLayout2ui4.prototype.bytesPerElement = 4; 14904register("StructArrayLayout2ui4", StructArrayLayout2ui4); 14905/** 14906* @internal 14907* Implementation of the StructArray layout: 14908* [0] - Uint16[1] 14909* 14910*/ 14911var StructArrayLayout1ui2 = class extends StructArray { 14912 _refreshViews() { 14913 this.uint8 = new Uint8Array(this.arrayBuffer); 14914 this.uint16 = new Uint16Array(this.arrayBuffer); 14915 } 14916 emplaceBack(v0) { 14917 const i = this.length; 14918 this.resize(i + 1); 14919 return this.emplace(i, v0); 14920 } 14921 emplace(i, v0) { 14922 const o2 = i * 1; 14923 this.uint16[o2 + 0] = v0; 14924 return i; 14925 } 14926}; 14927StructArrayLayout1ui2.prototype.bytesPerElement = 2; 14928register("StructArrayLayout1ui2", StructArrayLayout1ui2); 14929/** 14930* @internal 14931* Implementation of the StructArray layout: 14932* [0] - Float32[4] 14933* 14934*/ 14935var StructArrayLayout4f16 = class extends StructArray { 14936 _refreshViews() { 14937 this.uint8 = new Uint8Array(this.arrayBuffer); 14938 this.float32 = new Float32Array(this.arrayBuffer); 14939 } 14940 emplaceBack(v0, v1, v2, v3) { 14941 const i = this.length; 14942 this.resize(i + 1); 14943 return this.emplace(i, v0, v1, v2, v3); 14944 } 14945 emplace(i, v0, v1, v2, v3) { 14946 const o4 = i * 4; 14947 this.float32[o4 + 0] = v0; 14948 this.float32[o4 + 1] = v1; 14949 this.float32[o4 + 2] = v2; 14950 this.float32[o4 + 3] = v3; 14951 return i; 14952 } 14953}; 14954StructArrayLayout4f16.prototype.bytesPerElement = 16; 14955register("StructArrayLayout4f16", StructArrayLayout4f16); 14956/** @internal */ 14957var CollisionBoxStruct = class extends Struct { 14958 get anchorPointX() { 14959 return this._structArray.int16[this._pos2 + 0]; 14960 } 14961 get anchorPointY() { 14962 return this._structArray.int16[this._pos2 + 1]; 14963 } 14964 get x1() { 14965 return this._structArray.int16[this._pos2 + 2]; 14966 } 14967 get y1() { 14968 return this._structArray.int16[this._pos2 + 3]; 14969 } 14970 get x2() { 14971 return this._structArray.int16[this._pos2 + 4]; 14972 } 14973 get y2() { 14974 return this._structArray.int16[this._pos2 + 5]; 14975 } 14976 get featureIndex() { 14977 return this._structArray.uint32[this._pos4 + 3]; 14978 } 14979 get sourceLayerIndex() { 14980 return this._structArray.uint16[this._pos2 + 8]; 14981 } 14982 get bucketIndex() { 14983 return this._structArray.uint16[this._pos2 + 9]; 14984 } 14985 get anchorPoint() { 14986 return new Point(this.anchorPointX, this.anchorPointY); 14987 } 14988}; 14989CollisionBoxStruct.prototype.size = 20; 14990/** @internal */ 14991var CollisionBoxArray = class extends StructArrayLayout6i1ul2ui20 { 14992 /** 14993 * Return the CollisionBoxStruct at the given location in the array. 14994 * @param index - The index of the element. 14995 */ 14996 get(index) { 14997 return new CollisionBoxStruct(this, index); 14998 } 14999}; 15000register("CollisionBoxArray", CollisionBoxArray); 15001/** @internal */ 15002var PlacedSymbolStruct = class extends Struct { 15003 get anchorX() { 15004 return this._structArray.int16[this._pos2 + 0]; 15005 } 15006 get anchorY() { 15007 return this._structArray.int16[this._pos2 + 1]; 15008 } 15009 get glyphStartIndex() { 15010 return this._structArray.uint16[this._pos2 + 2]; 15011 } 15012 get numGlyphs() { 15013 return this._structArray.uint16[this._pos2 + 3]; 15014 } 15015 get vertexStartIndex() { 15016 return this._structArray.uint32[this._pos4 + 2]; 15017 } 15018 get lineStartIndex() { 15019 return this._structArray.uint32[this._pos4 + 3]; 15020 } 15021 get lineLength() { 15022 return this._structArray.uint32[this._pos4 + 4]; 15023 } 15024 get segment() { 15025 return this._structArray.uint16[this._pos2 + 10]; 15026 } 15027 get lowerSize() { 15028 return this._structArray.uint16[this._pos2 + 11]; 15029 } 15030 get upperSize() { 15031 return this._structArray.uint16[this._pos2 + 12]; 15032 } 15033 get lineOffsetX() { 15034 return this._structArray.float32[this._pos4 + 7]; 15035 } 15036 get lineOffsetY() { 15037 return this._structArray.float32[this._pos4 + 8]; 15038 } 15039 get writingMode() { 15040 return this._structArray.uint8[this._pos1 + 36]; 15041 } 15042 get placedOrientation() { 15043 return this._structArray.uint8[this._pos1 + 37]; 15044 } 15045 set placedOrientation(x) { 15046 this._structArray.uint8[this._pos1 + 37] = x; 15047 } 15048 get hidden() { 15049 return this._structArray.uint8[this._pos1 + 38]; 15050 } 15051 set hidden(x) { 15052 this._structArray.uint8[this._pos1 + 38] = x; 15053 } 15054 get crossTileID() { 15055 return this._structArray.uint32[this._pos4 + 10]; 15056 } 15057 set crossTileID(x) { 15058 this._structArray.uint32[this._pos4 + 10] = x; 15059 } 15060 get associatedIconIndex() { 15061 return this._structArray.int16[this._pos2 + 22]; 15062 } 15063 get heightOffset() { 15064 return this._structArray.float32[this._pos4 + 12]; 15065 } 15066}; 15067PlacedSymbolStruct.prototype.size = 52; 15068/** @internal */ 15069var PlacedSymbolArray = class extends StructArrayLayout2i2ui3ul3ui2f3ub1ul1i1f52 { 15070 /** 15071 * Return the PlacedSymbolStruct at the given location in the array. 15072 * @param index - The index of the element. 15073 */ 15074 get(index) { 15075 return new PlacedSymbolStruct(this, index); 15076 } 15077}; 15078register("PlacedSymbolArray", PlacedSymbolArray); 15079/** @internal */ 15080var SymbolInstanceStruct = class extends Struct { 15081 get anchorX() { 15082 return this._structArray.int16[this._pos2 + 0]; 15083 } 15084 get anchorY() { 15085 return this._structArray.int16[this._pos2 + 1]; 15086 } 15087 get rightJustifiedTextSymbolIndex() { 15088 return this._structArray.int16[this._pos2 + 2]; 15089 } 15090 get centerJustifiedTextSymbolIndex() { 15091 return this._structArray.int16[this._pos2 + 3]; 15092 } 15093 get leftJustifiedTextSymbolIndex() { 15094 return this._structArray.int16[this._pos2 + 4]; 15095 } 15096 get verticalPlacedTextSymbolIndex() { 15097 return this._structArray.int16[this._pos2 + 5]; 15098 } 15099 get placedIconSymbolIndex() { 15100 return this._structArray.int16[this._pos2 + 6]; 15101 } 15102 get verticalPlacedIconSymbolIndex() { 15103 return this._structArray.int16[this._pos2 + 7]; 15104 } 15105 get key() { 15106 return this._structArray.uint16[this._pos2 + 8]; 15107 } 15108 get textBoxStartIndex() { 15109 return this._structArray.uint16[this._pos2 + 9]; 15110 } 15111 get textBoxEndIndex() { 15112 return this._structArray.uint16[this._pos2 + 10]; 15113 } 15114 get verticalTextBoxStartIndex() { 15115 return this._structArray.uint16[this._pos2 + 11]; 15116 } 15117 get verticalTextBoxEndIndex() { 15118 return this._structArray.uint16[this._pos2 + 12]; 15119 } 15120 get iconBoxStartIndex() { 15121 return this._structArray.uint16[this._pos2 + 13]; 15122 } 15123 get iconBoxEndIndex() { 15124 return this._structArray.uint16[this._pos2 + 14]; 15125 } 15126 get verticalIconBoxStartIndex() { 15127 return this._structArray.uint16[this._pos2 + 15]; 15128 } 15129 get verticalIconBoxEndIndex() { 15130 return this._structArray.uint16[this._pos2 + 16]; 15131 } 15132 get featureIndex() { 15133 return this._structArray.uint16[this._pos2 + 17]; 15134 } 15135 get numHorizontalGlyphVertices() { 15136 return this._structArray.uint16[this._pos2 + 18]; 15137 } 15138 get numVerticalGlyphVertices() { 15139 return this._structArray.uint16[this._pos2 + 19]; 15140 } 15141 get numIconVertices() { 15142 return this._structArray.uint16[this._pos2 + 20]; 15143 } 15144 get numVerticalIconVertices() { 15145 return this._structArray.uint16[this._pos2 + 21]; 15146 } 15147 get useRuntimeCollisionCircles() { 15148 return this._structArray.uint16[this._pos2 + 22]; 15149 } 15150 get crossTileID() { 15151 return this._structArray.uint32[this._pos4 + 12]; 15152 } 15153 set crossTileID(x) { 15154 this._structArray.uint32[this._pos4 + 12] = x; 15155 } 15156 get textBoxScale() { 15157 return this._structArray.float32[this._pos4 + 13]; 15158 } 15159 get collisionCircleDiameter() { 15160 return this._structArray.float32[this._pos4 + 14]; 15161 } 15162 get textAnchorOffsetStartIndex() { 15163 return this._structArray.uint16[this._pos2 + 30]; 15164 } 15165 get textAnchorOffsetEndIndex() { 15166 return this._structArray.uint16[this._pos2 + 31]; 15167 } 15168 get heightOffset() { 15169 return this._structArray.float32[this._pos4 + 16]; 15170 } 15171}; 15172SymbolInstanceStruct.prototype.size = 68; 15173/** @internal */ 15174var SymbolInstanceArray = class extends StructArrayLayout8i15ui1ul2f2ui1f68 { 15175 /** 15176 * Return the SymbolInstanceStruct at the given location in the array. 15177 * @param index - The index of the element. 15178 */ 15179 get(index) { 15180 return new SymbolInstanceStruct(this, index); 15181 } 15182}; 15183register("SymbolInstanceArray", SymbolInstanceArray); 15184/** @internal */ 15185var GlyphOffsetArray = class extends StructArrayLayout1f4 { 15186 getoffsetX(index) { 15187 return this.float32[index * 1 + 0]; 15188 } 15189}; 15190register("GlyphOffsetArray", GlyphOffsetArray); 15191/** @internal */ 15192var SymbolLineVertexArray = class extends StructArrayLayout3i6 { 15193 getx(index) { 15194 return this.int16[index * 3 + 0]; 15195 } 15196 gety(index) { 15197 return this.int16[index * 3 + 1]; 15198 } 15199 gettileUnitDistanceFromAnchor(index) { 15200 return this.int16[index * 3 + 2]; 15201 } 15202}; 15203register("SymbolLineVertexArray", SymbolLineVertexArray); 15204/** @internal */ 15205var TextAnchorOffsetStruct = class extends Struct { 15206 get textAnchor() { 15207 return this._structArray.uint16[this._pos2 + 0]; 15208 } 15209 get textOffset0() { 15210 return this._structArray.float32[this._pos4 + 1]; 15211 } 15212 get textOffset1() { 15213 return this._structArray.float32[this._pos4 + 2]; 15214 } 15215}; 15216TextAnchorOffsetStruct.prototype.size = 12; 15217/** @internal */ 15218var TextAnchorOffsetArray = class extends StructArrayLayout1ui2f12 { 15219 /** 15220 * Return the TextAnchorOffsetStruct at the given location in the array. 15221 * @param index - The index of the element. 15222 */ 15223 get(index) { 15224 return new TextAnchorOffsetStruct(this, index); 15225 } 15226}; 15227register("TextAnchorOffsetArray", TextAnchorOffsetArray); 15228/** @internal */ 15229var FeatureIndexStruct = class extends Struct { 15230 get featureIndex() { 15231 return this._structArray.uint32[this._pos4 + 0]; 15232 } 15233 get sourceLayerIndex() { 15234 return this._structArray.uint16[this._pos2 + 2]; 15235 } 15236 get bucketIndex() { 15237 return this._structArray.uint16[this._pos2 + 3]; 15238 } 15239}; 15240FeatureIndexStruct.prototype.size = 8; 15241/** @internal */ 15242var FeatureIndexArray = class extends StructArrayLayout1ul2ui8 { 15243 /** 15244 * Return the FeatureIndexStruct at the given location in the array. 15245 * @param index - The index of the element. 15246 */ 15247 get(index) { 15248 return new FeatureIndexStruct(this, index); 15249 } 15250}; 15251register("FeatureIndexArray", FeatureIndexArray); 15252var PosArray = class extends StructArrayLayout2i4 {}; 15253var Pos3dArray = class extends StructArrayLayout3i6 {}; 15254var RasterBoundsArray = class extends StructArrayLayout4i8 {}; 15255var CircleLayoutArray = class extends StructArrayLayout2i4 {}; 15256var FillLayoutArray = class extends StructArrayLayout2i4 {}; 15257var FillExtrusionLayoutArray = class extends StructArrayLayout2i4i12 {}; 15258var LineLayoutArray = class extends StructArrayLayout2i4ub8 {}; 15259var LineExtLayoutArray = class extends StructArrayLayout2f8 {}; 15260var PatternLayoutArray = class extends StructArrayLayout10ui20 {}; 15261var DashLayoutArray = class extends StructArrayLayout8ui16 {}; 15262var SymbolLayoutArray = class extends StructArrayLayout4i4ui4i1f28 {}; 15263var SymbolDynamicLayoutArray = class extends StructArrayLayout3f12 {}; 15264var SymbolOpacityArray = class extends StructArrayLayout1ul4 {}; 15265var CollisionBoxLayoutArray = class extends StructArrayLayout2i2i2i12 {}; 15266var CollisionCircleLayoutArray = class extends StructArrayLayout2f1f2i16 {}; 15267var CollisionVertexArray = class extends StructArrayLayout2ub2f2i16 {}; 15268var QuadTriangleArray = class extends StructArrayLayout3ui6 {}; 15269var TriangleIndexArray = class extends StructArrayLayout3ui6 {}; 15270var LineIndexArray = class extends StructArrayLayout2ui4 {}; 15271var LineStripIndexArray = class extends StructArrayLayout1ui2 {}; 15272//#endregion 15273//#region src/data/bucket/circle_attributes.ts 15274const layout$7 = createLayout([{ 15275 name: "a_pos", 15276 components: 2, 15277 type: "Int16" 15278}], 4); 15279const members$4 = layout$7.members; 15280layout$7.size; 15281layout$7.alignment; 15282//#endregion 15283//#region src/data/segment.ts 15284/** 15285* @internal 15286* Used for calculations on vector segments 15287*/ 15288var SegmentVector = class SegmentVector { 15289 constructor(segments = []) { 15290 this._forceNewSegmentOnNextPrepare = false; 15291 this.segments = segments; 15292 } 15293 /** 15294 * Returns the last segment if `numVertices` fits into it. 15295 * If there are no segments yet or `numVertices` doesn't fit into the last one, creates a new empty segment and returns it. 15296 */ 15297 prepareSegment(numVertices, layoutVertexArray, indexArray, sortKey) { 15298 const lastSegment = this.segments[this.segments.length - 1]; 15299 if (numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) warnOnce(`Max vertices per segment is ${SegmentVector.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${numVertices}. Consider using the \`fillLargeMeshArrays\` function if you require meshes with more than ${SegmentVector.MAX_VERTEX_ARRAY_LENGTH} vertices.`); 15300 if (this._forceNewSegmentOnNextPrepare || !lastSegment || lastSegment.vertexLength + numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH || lastSegment.sortKey !== sortKey) return this.createNewSegment(layoutVertexArray, indexArray, sortKey); 15301 else return lastSegment; 15302 } 15303 /** 15304 * Creates a new empty segment and returns it. 15305 */ 15306 createNewSegment(layoutVertexArray, indexArray, sortKey) { 15307 const segment = { 15308 vertexOffset: layoutVertexArray.length, 15309 primitiveOffset: indexArray.length, 15310 vertexLength: 0, 15311 primitiveLength: 0, 15312 vaos: {} 15313 }; 15314 if (sortKey !== void 0) segment.sortKey = sortKey; 15315 this._forceNewSegmentOnNextPrepare = false; 15316 this.segments.push(segment); 15317 return segment; 15318 } 15319 /** 15320 * Returns the last segment, or creates a new segments if there are no segments yet. 15321 */ 15322 getOrCreateLatestSegment(layoutVertexArray, indexArray, sortKey) { 15323 return this.prepareSegment(0, layoutVertexArray, indexArray, sortKey); 15324 } 15325 /** 15326 * Causes the next call to {@link prepareSegment} to always return a new segment, 15327 * not reusing the current segment even if the new geometry would fit it. 15328 */ 15329 forceNewSegmentOnNextPrepare() { 15330 this._forceNewSegmentOnNextPrepare = true; 15331 } 15332 get() { 15333 return this.segments; 15334 } 15335 destroy() { 15336 for (const segment of this.segments) for (const k in segment.vaos) segment.vaos[k].destroy(); 15337 } 15338 static simpleSegment(vertexOffset, primitiveOffset, vertexLength, primitiveLength) { 15339 return new SegmentVector([{ 15340 vertexOffset, 15341 primitiveOffset, 15342 vertexLength, 15343 primitiveLength, 15344 vaos: {}, 15345 sortKey: 0 15346 }]); 15347 } 15348}; 15349/** 15350* The maximum size of a vertex array. This limit is imposed by WebGL's 16 bit 15351* addressing of vertex buffers. 15352*/ 15353SegmentVector.MAX_VERTEX_ARRAY_LENGTH = Math.pow(2, 16) - 1; 15354register("SegmentVector", SegmentVector); 15355//#endregion 15356//#region src/shaders/encode_attribute.ts 15357/** 15358* Packs two numbers, interpreted as 8-bit unsigned integers, into a single 15359* float. Unpack them in the shader using the `unpack_float()` function, 15360* defined in _prelude.vertex.glsl 15361*/ 15362function packUint8ToFloat(a, b) { 15363 a = clamp$2(Math.floor(a), 0, 255); 15364 b = clamp$2(Math.floor(b), 0, 255); 15365 return 256 * a + b; 15366} 15367//#endregion 15368//#region src/data/bucket/pattern_attributes.ts 15369const patternAttributes = createLayout([ 15370 { 15371 name: "a_pattern_from", 15372 components: 4, 15373 type: "Uint16" 15374 }, 15375 { 15376 name: "a_pattern_to", 15377 components: 4, 15378 type: "Uint16" 15379 }, 15380 { 15381 name: "a_pixel_ratio_from", 15382 components: 1, 15383 type: "Uint16" 15384 }, 15385 { 15386 name: "a_pixel_ratio_to", 15387 components: 1, 15388 type: "Uint16" 15389 } 15390]); 15391//#endregion 15392//#region src/data/bucket/dash_attributes.ts 15393const dashAttributes = createLayout([{ 15394 name: "a_dasharray_from", 15395 components: 4, 15396 type: "Uint16" 15397}, { 15398 name: "a_dasharray_to", 15399 components: 4, 15400 type: "Uint16" 15401}]); 15402//#endregion 15403//#region node_modules/murmurhash-js/murmurhash3_gc.js 15404var require_murmurhash3_gc = /* @__PURE__ */ __commonJSMin(((exports, module) => { 15405 /** 15406 * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011) 15407 * 15408 * @author <a href="mailto:[email protected]">Gary Court</a> 15409 * @see http://github.com/garycourt/murmurhash-js 15410 * @author <a href="mailto:[email protected]">Austin Appleby</a> 15411 * @see http://sites.google.com/site/murmurhash/ 15412 * 15413 * @param {string} key ASCII only 15414 * @param {number} seed Positive integer only 15415 * @return {number} 32-bit positive integer hash 15416 */ 15417 function murmurhash3_32_gc(key, seed) { 15418 var remainder = key.length & 3, bytes = key.length - remainder, h1 = seed, h1b, c1 = 3432918353, c2 = 461845907, k1, i = 0; 15419 while (i < bytes) { 15420 k1 = key.charCodeAt(i) & 255 | (key.charCodeAt(++i) & 255) << 8 | (key.charCodeAt(++i) & 255) << 16 | (key.charCodeAt(++i) & 255) << 24; 15421 ++i; 15422 k1 = (k1 & 65535) * c1 + (((k1 >>> 16) * c1 & 65535) << 16) & 4294967295; 15423 k1 = k1 << 15 | k1 >>> 17; 15424 k1 = (k1 & 65535) * c2 + (((k1 >>> 16) * c2 & 65535) << 16) & 4294967295; 15425 h1 ^= k1; 15426 h1 = h1 << 13 | h1 >>> 19; 15427 h1b = (h1 & 65535) * 5 + (((h1 >>> 16) * 5 & 65535) << 16) & 4294967295; 15428 h1 = (h1b & 65535) + 27492 + (((h1b >>> 16) + 58964 & 65535) << 16); 15429 } 15430 k1 = 0; 15431 switch (remainder) { 15432 case 3: k1 ^= (key.charCodeAt(i + 2) & 255) << 16; 15433 case 2: k1 ^= (key.charCodeAt(i + 1) & 255) << 8; 15434 case 1: 15435 k1 ^= key.charCodeAt(i) & 255; 15436 k1 = (k1 & 65535) * c1 + (((k1 >>> 16) * c1 & 65535) << 16) & 4294967295; 15437 k1 = k1 << 15 | k1 >>> 17; 15438 k1 = (k1 & 65535) * c2 + (((k1 >>> 16) * c2 & 65535) << 16) & 4294967295; 15439 h1 ^= k1; 15440 } 15441 h1 ^= key.length; 15442 h1 ^= h1 >>> 16; 15443 h1 = (h1 & 65535) * 2246822507 + (((h1 >>> 16) * 2246822507 & 65535) << 16) & 4294967295; 15444 h1 ^= h1 >>> 13; 15445 h1 = (h1 & 65535) * 3266489909 + (((h1 >>> 16) * 3266489909 & 65535) << 16) & 4294967295; 15446 h1 ^= h1 >>> 16; 15447 return h1 >>> 0; 15448 } 15449 if (typeof module !== "undefined") module.exports = murmurhash3_32_gc; 15450})); 15451//#endregion 15452//#region node_modules/murmurhash-js/murmurhash2_gc.js 15453var require_murmurhash2_gc = /* @__PURE__ */ __commonJSMin(((exports, module) => { 15454 /** 15455 * JS Implementation of MurmurHash2 15456 * 15457 * @author <a href="mailto:[email protected]">Gary Court</a> 15458 * @see http://github.com/garycourt/murmurhash-js 15459 * @author <a href="mailto:[email protected]">Austin Appleby</a> 15460 * @see http://sites.google.com/site/murmurhash/ 15461 * 15462 * @param {string} str ASCII only 15463 * @param {number} seed Positive integer only 15464 * @return {number} 32-bit positive integer hash 15465 */ 15466 function murmurhash2_32_gc(str, seed) { 15467 var l = str.length, h = seed ^ l, i = 0, k; 15468 while (l >= 4) { 15469 k = str.charCodeAt(i) & 255 | (str.charCodeAt(++i) & 255) << 8 | (str.charCodeAt(++i) & 255) << 16 | (str.charCodeAt(++i) & 255) << 24; 15470 k = (k & 65535) * 1540483477 + (((k >>> 16) * 1540483477 & 65535) << 16); 15471 k ^= k >>> 24; 15472 k = (k & 65535) * 1540483477 + (((k >>> 16) * 1540483477 & 65535) << 16); 15473 h = (h & 65535) * 1540483477 + (((h >>> 16) * 1540483477 & 65535) << 16) ^ k; 15474 l -= 4; 15475 ++i; 15476 } 15477 switch (l) { 15478 case 3: h ^= (str.charCodeAt(i + 2) & 255) << 16; 15479 case 2: h ^= (str.charCodeAt(i + 1) & 255) << 8; 15480 case 1: 15481 h ^= str.charCodeAt(i) & 255; 15482 h = (h & 65535) * 1540483477 + (((h >>> 16) * 1540483477 & 65535) << 16); 15483 } 15484 h ^= h >>> 13; 15485 h = (h & 65535) * 1540483477 + (((h >>> 16) * 1540483477 & 65535) << 16); 15486 h ^= h >>> 15; 15487 return h >>> 0; 15488 } 15489 module.exports = murmurhash2_32_gc; 15490})); 15491//#endregion 15492//#region src/data/feature_position_map.ts 15493var import_murmurhash_js = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => { 15494 var murmur3 = require_murmurhash3_gc(); 15495 var murmur2 = require_murmurhash2_gc(); 15496 module.exports = murmur3; 15497 module.exports.murmur3 = murmur3; 15498 module.exports.murmur2 = murmur2; 15499})))(), 1); 15500var FeaturePositionMap = class FeaturePositionMap { 15501 constructor() { 15502 this.ids = []; 15503 this.positions = []; 15504 this.indexed = false; 15505 } 15506 add(id, index, start, end) { 15507 this.ids.push(getNumericId(id)); 15508 this.positions.push(index, start, end); 15509 } 15510 getPositions(id) { 15511 if (!this.indexed) throw new Error("Trying to get index, but feature positions are not indexed"); 15512 const intId = getNumericId(id); 15513 let i = 0; 15514 let j = this.ids.length - 1; 15515 while (i < j) { 15516 const m = i + j >> 1; 15517 if (this.ids[m] >= intId) j = m; 15518 else i = m + 1; 15519 } 15520 const positions = []; 15521 while (this.ids[i] === intId) { 15522 const index = this.positions[3 * i]; 15523 const start = this.positions[3 * i + 1]; 15524 const end = this.positions[3 * i + 2]; 15525 positions.push({ 15526 index, 15527 start, 15528 end 15529 }); 15530 i++; 15531 } 15532 return positions; 15533 } 15534 static serialize(map, transferables) { 15535 const ids = new Float64Array(map.ids); 15536 const positions = new Uint32Array(map.positions); 15537 sort$1(ids, positions, 0, ids.length - 1); 15538 if (transferables) transferables.push(ids.buffer, positions.buffer); 15539 return { 15540 ids, 15541 positions 15542 }; 15543 } 15544 static deserialize(obj) { 15545 const map = new FeaturePositionMap(); 15546 map.ids = obj.ids; 15547 map.positions = obj.positions; 15548 map.indexed = true; 15549 return map; 15550 } 15551}; 15552function getNumericId(value) { 15553 const numValue = +value; 15554 if (!isNaN(numValue) && numValue <= Number.MAX_SAFE_INTEGER) return numValue; 15555 return (0, import_murmurhash_js.default)(String(value)); 15556} 15557function sort$1(ids, positions, left, right) { 15558 while (left < right) { 15559 const pivot = ids[left + right >> 1]; 15560 let i = left - 1; 15561 let j = right + 1; 15562 while (true) { 15563 do 15564 i++; 15565 while (ids[i] < pivot); 15566 do 15567 j--; 15568 while (ids[j] > pivot); 15569 if (i >= j) break; 15570 swap$1(ids, i, j); 15571 swap$1(positions, 3 * i, 3 * j); 15572 swap$1(positions, 3 * i + 1, 3 * j + 1); 15573 swap$1(positions, 3 * i + 2, 3 * j + 2); 15574 } 15575 if (j - left < right - j) { 15576 sort$1(ids, positions, left, j); 15577 left = j + 1; 15578 } else { 15579 sort$1(ids, positions, j + 1, right); 15580 right = j; 15581 } 15582 } 15583} 15584function swap$1(arr, i, j) { 15585 const tmp = arr[i]; 15586 arr[i] = arr[j]; 15587 arr[j] = tmp; 15588} 15589register("FeaturePositionMap", FeaturePositionMap); 15590//#endregion 15591//#region src/webgl/uniform_binding.ts 15592/** 15593* @internal 15594* A base uniform abstract class 15595*/ 15596var Uniform = class { 15597 constructor(context, location) { 15598 this.gl = context.gl; 15599 this.location = location; 15600 } 15601}; 15602var Uniform1i = class extends Uniform { 15603 constructor(context, location) { 15604 super(context, location); 15605 this.current = 0; 15606 } 15607 set(v) { 15608 if (this.current !== v) { 15609 this.current = v; 15610 this.gl.uniform1i(this.location, v); 15611 } 15612 } 15613}; 15614var Uniform1f = class extends Uniform { 15615 constructor(context, location) { 15616 super(context, location); 15617 this.current = 0; 15618 } 15619 set(v) { 15620 if (this.current !== v) { 15621 this.current = v; 15622 this.gl.uniform1f(this.location, v); 15623 } 15624 } 15625}; 15626var Uniform2f = class extends Uniform { 15627 constructor(context, location) { 15628 super(context, location); 15629 this.current = [0, 0]; 15630 } 15631 set(v) { 15632 if (v[0] !== this.current[0] || v[1] !== this.current[1]) { 15633 this.current = v; 15634 this.gl.uniform2f(this.location, v[0], v[1]); 15635 } 15636 } 15637}; 15638var Uniform3f = class extends Uniform { 15639 constructor(context, location) { 15640 super(context, location); 15641 this.current = [ 15642 0, 15643 0, 15644 0 15645 ]; 15646 } 15647 set(v) { 15648 if (v[0] !== this.current[0] || v[1] !== this.current[1] || v[2] !== this.current[2]) { 15649 this.current = v; 15650 this.gl.uniform3f(this.location, v[0], v[1], v[2]); 15651 } 15652 } 15653}; 15654var Uniform4f = class extends Uniform { 15655 constructor(context, location) { 15656 super(context, location); 15657 this.current = [ 15658 0, 15659 0, 15660 0, 15661 0 15662 ]; 15663 } 15664 set(v) { 15665 if (v[0] !== this.current[0] || v[1] !== this.current[1] || v[2] !== this.current[2] || v[3] !== this.current[3]) { 15666 this.current = v; 15667 this.gl.uniform4f(this.location, v[0], v[1], v[2], v[3]); 15668 } 15669 } 15670}; 15671var UniformColor = class extends Uniform { 15672 constructor(context, location) { 15673 super(context, location); 15674 this.current = Color.transparent; 15675 } 15676 set(v) { 15677 if (v.r !== this.current.r || v.g !== this.current.g || v.b !== this.current.b || v.a !== this.current.a) { 15678 this.current = v; 15679 this.gl.uniform4f(this.location, v.r, v.g, v.b, v.a); 15680 } 15681 } 15682}; 15683var UniformColorArray = class extends Uniform { 15684 constructor(context, location) { 15685 super(context, location); 15686 this.current = new Array(); 15687 } 15688 set(v) { 15689 if (v != this.current) { 15690 this.current = v; 15691 const values = new Float32Array(v.length * 4); 15692 for (let i = 0; i < v.length; i++) { 15693 values[4 * i] = v[i].r; 15694 values[4 * i + 1] = v[i].g; 15695 values[4 * i + 2] = v[i].b; 15696 values[4 * i + 3] = v[i].a; 15697 } 15698 this.gl.uniform4fv(this.location, values); 15699 } 15700 } 15701}; 15702var UniformFloatArray = class extends Uniform { 15703 constructor(context, location) { 15704 super(context, location); 15705 this.current = new Array(); 15706 } 15707 set(v) { 15708 if (v != this.current) { 15709 this.current = v; 15710 const values = new Float32Array(v); 15711 this.gl.uniform1fv(this.location, values); 15712 } 15713 } 15714}; 15715const emptyMat4 = /* @__PURE__ */ new Float32Array(16); 15716var UniformMatrix4f = class extends Uniform { 15717 constructor(context, location) { 15718 super(context, location); 15719 this.current = emptyMat4; 15720 } 15721 set(v) { 15722 if (v[12] !== this.current[12] || v[0] !== this.current[0]) { 15723 this.current = v; 15724 this.gl.uniformMatrix4fv(this.location, false, v); 15725 return; 15726 } 15727 for (let i = 1; i < 16; i++) if (v[i] !== this.current[i]) { 15728 this.current = v; 15729 this.gl.uniformMatrix4fv(this.location, false, v); 15730 break; 15731 } 15732 } 15733}; 15734//#endregion 15735//#region src/data/program_configuration.ts 15736function packColor(color) { 15737 return [packUint8ToFloat(255 * color.r, 255 * color.g), packUint8ToFloat(255 * color.b, 255 * color.a)]; 15738} 15739var ConstantBinder = class { 15740 constructor(value, names, type) { 15741 this.value = value; 15742 this.uniformNames = names.map((name) => `u_${name}`); 15743 this.type = type; 15744 } 15745 setUniform(uniform, globals, currentValue) { 15746 uniform.set(currentValue.constantOr(this.value)); 15747 } 15748 getBinding(context, location, _) { 15749 return this.type === "color" ? new UniformColor(context, location) : new Uniform1f(context, location); 15750 } 15751}; 15752var CrossFadedConstantBinder = class { 15753 constructor(value, names) { 15754 this.uniformNames = names.map((name) => `u_${name}`); 15755 this.patternFrom = null; 15756 this.patternTo = null; 15757 this.pixelRatioFrom = 1; 15758 this.pixelRatioTo = 1; 15759 } 15760 setConstantPatternPositions(posTo, posFrom) { 15761 this.pixelRatioFrom = posFrom.pixelRatio; 15762 this.pixelRatioTo = posTo.pixelRatio; 15763 this.patternFrom = posFrom.tlbr; 15764 this.patternTo = posTo.tlbr; 15765 } 15766 setConstantDashPositions(dashTo, dashFrom) { 15767 this.dashTo = [ 15768 0, 15769 dashTo.y, 15770 dashTo.height, 15771 dashTo.width 15772 ]; 15773 this.dashFrom = [ 15774 0, 15775 dashFrom.y, 15776 dashFrom.height, 15777 dashFrom.width 15778 ]; 15779 } 15780 setUniform(uniform, globals, currentValue, uniformName) { 15781 let value = null; 15782 if (uniformName === "u_pattern_to") value = this.patternTo; 15783 else if (uniformName === "u_pattern_from") value = this.patternFrom; 15784 else if (uniformName === "u_dasharray_to") value = this.dashTo; 15785 else if (uniformName === "u_dasharray_from") value = this.dashFrom; 15786 else if (uniformName === "u_pixel_ratio_to") value = this.pixelRatioTo; 15787 else if (uniformName === "u_pixel_ratio_from") value = this.pixelRatioFrom; 15788 if (value !== null) uniform.set(value); 15789 } 15790 getBinding(context, location, name) { 15791 return name.startsWith("u_pattern") || name.startsWith("u_dasharray_") ? new Uniform4f(context, location) : new Uniform1f(context, location); 15792 } 15793}; 15794var SourceExpressionBinder = class { 15795 constructor(expression, names, type, PaintVertexArray) { 15796 this.expression = expression; 15797 this.type = type; 15798 this.maxValue = 0; 15799 this.paintVertexAttributes = names.map((name) => ({ 15800 name: `a_${name}`, 15801 type: "Float32", 15802 components: type === "color" ? 2 : 1, 15803 offset: 0 15804 })); 15805 this.paintVertexArray = new PaintVertexArray(); 15806 } 15807 populatePaintArray(newLength, feature, options) { 15808 const start = this.paintVertexArray.length; 15809 const value = this.expression.evaluate(new EvaluationParameters(0, options), feature, {}, options.canonical, [], options.formattedSection); 15810 this.paintVertexArray.resize(newLength); 15811 this._setPaintValue(start, newLength, value); 15812 } 15813 updatePaintArray(start, end, feature, featureState, options) { 15814 const value = this.expression.evaluate(new EvaluationParameters(0, options), feature, featureState); 15815 this._setPaintValue(start, end, value); 15816 } 15817 _setPaintValue(start, end, value) { 15818 if (this.type === "color") { 15819 const color = packColor(value); 15820 for (let i = start; i < end; i++) this.paintVertexArray.emplace(i, color[0], color[1]); 15821 } else { 15822 for (let i = start; i < end; i++) this.paintVertexArray.emplace(i, value); 15823 this.maxValue = Math.max(this.maxValue, Math.abs(value)); 15824 } 15825 } 15826 upload(context) { 15827 if (this.paintVertexArray?.arrayBuffer.byteLength) { 15828 if (this.paintVertexBuffer?.buffer) this.paintVertexBuffer.updateData(this.paintVertexArray); 15829 else this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent); 15830 } 15831 } 15832 destroy() { 15833 if (this.paintVertexBuffer) this.paintVertexBuffer.destroy(); 15834 } 15835}; 15836var CompositeExpressionBinder = class { 15837 constructor(expression, names, type, useIntegerZoom, zoom, PaintVertexArray) { 15838 this.expression = expression; 15839 this.uniformNames = names.map((name) => `u_${name}_t`); 15840 this.type = type; 15841 this.useIntegerZoom = useIntegerZoom; 15842 this.zoom = zoom; 15843 this.maxValue = 0; 15844 this.paintVertexAttributes = names.map((name) => ({ 15845 name: `a_${name}`, 15846 type: "Float32", 15847 components: type === "color" ? 4 : 2, 15848 offset: 0 15849 })); 15850 this.paintVertexArray = new PaintVertexArray(); 15851 } 15852 populatePaintArray(newLength, feature, options) { 15853 const min = this.expression.evaluate(new EvaluationParameters(this.zoom, options), feature, {}, options.canonical, [], options.formattedSection); 15854 const max = this.expression.evaluate(new EvaluationParameters(this.zoom + 1, options), feature, {}, options.canonical, [], options.formattedSection); 15855 const start = this.paintVertexArray.length; 15856 this.paintVertexArray.resize(newLength); 15857 this._setPaintValue(start, newLength, min, max); 15858 } 15859 updatePaintArray(start, end, feature, featureState, options) { 15860 const min = this.expression.evaluate(new EvaluationParameters(this.zoom, options), feature, featureState); 15861 const max = this.expression.evaluate(new EvaluationParameters(this.zoom + 1, options), feature, featureState); 15862 this._setPaintValue(start, end, min, max); 15863 } 15864 _setPaintValue(start, end, min, max) { 15865 if (this.type === "color") { 15866 const minColor = packColor(min); 15867 const maxColor = packColor(max); 15868 for (let i = start; i < end; i++) this.paintVertexArray.emplace(i, minColor[0], minColor[1], maxColor[0], maxColor[1]); 15869 } else { 15870 for (let i = start; i < end; i++) this.paintVertexArray.emplace(i, min, max); 15871 this.maxValue = Math.max(this.maxValue, Math.abs(min), Math.abs(max)); 15872 } 15873 } 15874 upload(context) { 15875 if (this.paintVertexArray?.arrayBuffer.byteLength) { 15876 if (this.paintVertexBuffer?.buffer) this.paintVertexBuffer.updateData(this.paintVertexArray); 15877 else this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent); 15878 } 15879 } 15880 destroy() { 15881 if (this.paintVertexBuffer) this.paintVertexBuffer.destroy(); 15882 } 15883 setUniform(uniform, globals) { 15884 const currentZoom = this.useIntegerZoom ? Math.floor(globals.zoom) : globals.zoom; 15885 const factor = clamp$2(this.expression.interpolationFactor(currentZoom, this.zoom, this.zoom + 1), 0, 1); 15886 uniform.set(factor); 15887 } 15888 getBinding(context, location, _) { 15889 return new Uniform1f(context, location); 15890 } 15891}; 15892var CrossFadedBinder = class { 15893 constructor(expression, type, useIntegerZoom, zoom, PaintVertexArray, layerId) { 15894 this.expression = expression; 15895 this.type = type; 15896 this.useIntegerZoom = useIntegerZoom; 15897 this.zoom = zoom; 15898 this.layerId = layerId; 15899 this.zoomInPaintVertexArray = new PaintVertexArray(); 15900 this.zoomOutPaintVertexArray = new PaintVertexArray(); 15901 } 15902 populatePaintArray(length, feature, options) { 15903 const start = this.zoomInPaintVertexArray.length; 15904 this.zoomInPaintVertexArray.resize(length); 15905 this.zoomOutPaintVertexArray.resize(length); 15906 this._setPaintValues(start, length, this.getPositionIds(feature), options); 15907 } 15908 updatePaintArray(start, end, feature, featureState, options) { 15909 this._setPaintValues(start, end, this.getPositionIds(feature), options); 15910 } 15911 _setPaintValues(start, end, positionIds, options) { 15912 const positions = this.getPositions(options); 15913 if (!positions || !positionIds) return; 15914 const min = positions[positionIds.min]; 15915 const mid = positions[positionIds.mid]; 15916 const max = positions[positionIds.max]; 15917 if (!min || !mid || !max) return; 15918 for (let i = start; i < end; i++) { 15919 this.emplace(this.zoomInPaintVertexArray, i, min, mid); 15920 this.emplace(this.zoomOutPaintVertexArray, i, max, mid); 15921 } 15922 } 15923 upload(context) { 15924 if (this.zoomInPaintVertexArray?.arrayBuffer.byteLength && this.zoomOutPaintVertexArray?.arrayBuffer.byteLength) { 15925 const attributes = this.getVertexAttributes(); 15926 this.zoomInPaintVertexBuffer = context.createVertexBuffer(this.zoomInPaintVertexArray, attributes, this.expression.isStateDependent); 15927 this.zoomOutPaintVertexBuffer = context.createVertexBuffer(this.zoomOutPaintVertexArray, attributes, this.expression.isStateDependent); 15928 } 15929 } 15930 destroy() { 15931 if (this.zoomOutPaintVertexBuffer) this.zoomOutPaintVertexBuffer.destroy(); 15932 if (this.zoomInPaintVertexBuffer) this.zoomInPaintVertexBuffer.destroy(); 15933 } 15934}; 15935var CrossFadedPatternBinder = class extends CrossFadedBinder { 15936 getPositions(options) { 15937 return options.imagePositions; 15938 } 15939 getPositionIds(feature) { 15940 return feature.patterns?.[this.layerId]; 15941 } 15942 getVertexAttributes() { 15943 return patternAttributes.members; 15944 } 15945 emplace(array, index, fromPos, toPos) { 15946 array.emplace(index, fromPos.tlbr[0], fromPos.tlbr[1], fromPos.tlbr[2], fromPos.tlbr[3], toPos.tlbr[0], toPos.tlbr[1], toPos.tlbr[2], toPos.tlbr[3], fromPos.pixelRatio, toPos.pixelRatio); 15947 } 15948}; 15949var CrossFadedDasharrayBinder = class extends CrossFadedBinder { 15950 getPositions(options) { 15951 return options.dashPositions; 15952 } 15953 getPositionIds(feature) { 15954 return feature.dashes?.[this.layerId]; 15955 } 15956 getVertexAttributes() { 15957 return dashAttributes.members; 15958 } 15959 emplace(array, index, fromPos, toPos) { 15960 array.emplace(index, 0, fromPos.y, fromPos.height, fromPos.width, 0, toPos.y, toPos.height, toPos.width); 15961 } 15962}; 15963/** 15964* @internal 15965* ProgramConfiguration contains the logic for binding style layer properties and tile 15966* layer feature data into GL program uniforms and vertex attributes. 15967* 15968* Non-data-driven property values are bound to shader uniforms. Data-driven property 15969* values are bound to vertex attributes. In order to support a uniform GLSL syntax over 15970* both, the [shaders](../shaders/README.md) define a `#pragma` abstraction, which 15971* ProgramConfiguration is responsible for implementing. At runtime, 15972* it examines the attributes of a particular layer, combines this with fixed knowledge 15973* about how layers of the particular type are implemented, and determines which uniforms 15974* and vertex attributes will be required. It can then substitute the appropriate text 15975* into the shader source code, create and link a program, and bind the uniforms and 15976* vertex attributes in preparation for drawing. 15977* 15978* When a vector tile is parsed, this same configuration information is used to 15979* populate the attribute buffers needed for data-driven styling using the zoom 15980* level and feature property data. 15981*/ 15982var ProgramConfiguration = class { 15983 constructor(layer, zoom, filterProperties) { 15984 this.binders = {}; 15985 this._buffers = []; 15986 const keys = []; 15987 for (const property in layer.paint._values) { 15988 if (!filterProperties(property)) continue; 15989 const value = layer.paint.get(property); 15990 if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) continue; 15991 const names = paintAttributeNames(property, layer.type); 15992 const expression = value.value; 15993 const type = value.property.specification.type; 15994 const useIntegerZoom = value.property.useIntegerZoom; 15995 const propType = value.property.specification["property-type"]; 15996 const isCrossFaded = propType === "cross-faded" || propType === "cross-faded-data-driven"; 15997 if (expression.kind === "constant") { 15998 this.binders[property] = isCrossFaded ? new CrossFadedConstantBinder(expression.value, names) : new ConstantBinder(expression.value, names, type); 15999 keys.push(`/u_${property}`); 16000 } else if (expression.kind === "source" || isCrossFaded) { 16001 const StructArrayLayout = layoutType(property, type, "source"); 16002 this.binders[property] = isCrossFaded ? property === "line-dasharray" ? new CrossFadedDasharrayBinder(expression, type, useIntegerZoom, zoom, StructArrayLayout, layer.id) : new CrossFadedPatternBinder(expression, type, useIntegerZoom, zoom, StructArrayLayout, layer.id) : new SourceExpressionBinder(expression, names, type, StructArrayLayout); 16003 keys.push(`/a_${property}`); 16004 } else { 16005 const StructArrayLayout = layoutType(property, type, "composite"); 16006 this.binders[property] = new CompositeExpressionBinder(expression, names, type, useIntegerZoom, zoom, StructArrayLayout); 16007 keys.push(`/z_${property}`); 16008 } 16009 } 16010 this.cacheKey = keys.sort().join(""); 16011 } 16012 getMaxValue(property) { 16013 const binder = this.binders[property]; 16014 return binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder ? binder.maxValue : 0; 16015 } 16016 populatePaintArrays(newLength, feature, options) { 16017 for (const property in this.binders) { 16018 const binder = this.binders[property]; 16019 if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedBinder) binder.populatePaintArray(newLength, feature, options); 16020 } 16021 } 16022 setConstantPatternPositions(posTo, posFrom) { 16023 for (const property in this.binders) { 16024 const binder = this.binders[property]; 16025 if (binder instanceof CrossFadedConstantBinder) binder.setConstantPatternPositions(posTo, posFrom); 16026 } 16027 } 16028 setConstantDashPositions(dashTo, dashFrom) { 16029 for (const property in this.binders) { 16030 const binder = this.binders[property]; 16031 if (binder instanceof CrossFadedConstantBinder) binder.setConstantDashPositions(dashTo, dashFrom); 16032 } 16033 } 16034 updatePaintArrays(featureStates, featureMap, vtLayer, layer, options) { 16035 let dirty = false; 16036 for (const fs of featureStates) { 16037 const positions = featureMap.getPositions(fs.id); 16038 for (const pos of positions) { 16039 const feature = vtLayer.feature(pos.index); 16040 for (const property in this.binders) { 16041 const binder = this.binders[property]; 16042 if ((binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedBinder) && binder.expression.isStateDependent === true) { 16043 binder.expression = layer.paint.get(property).value; 16044 binder.updatePaintArray(pos.start, pos.end, feature, fs.state, options); 16045 dirty = true; 16046 } 16047 } 16048 } 16049 } 16050 return dirty; 16051 } 16052 defines() { 16053 const result = []; 16054 for (const property in this.binders) { 16055 const binder = this.binders[property]; 16056 if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder) result.push(...binder.uniformNames.map((name) => `#define HAS_UNIFORM_${name}`)); 16057 } 16058 return result; 16059 } 16060 getBinderAttributes() { 16061 const result = []; 16062 for (const property in this.binders) { 16063 const binder = this.binders[property]; 16064 if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder) for (const attribute of binder.paintVertexAttributes) result.push(attribute.name); 16065 else if (binder instanceof CrossFadedBinder) { 16066 const attributes = binder.getVertexAttributes(); 16067 for (const attribute of attributes) result.push(attribute.name); 16068 } 16069 } 16070 return result; 16071 } 16072 getBinderUniforms() { 16073 const uniforms = []; 16074 for (const property in this.binders) { 16075 const binder = this.binders[property]; 16076 if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder || binder instanceof CompositeExpressionBinder) for (const uniformName of binder.uniformNames) uniforms.push(uniformName); 16077 } 16078 return uniforms; 16079 } 16080 getPaintVertexBuffers() { 16081 return this._buffers; 16082 } 16083 getUniforms(context, locations) { 16084 const uniforms = []; 16085 for (const property in this.binders) { 16086 const binder = this.binders[property]; 16087 if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder || binder instanceof CompositeExpressionBinder) { 16088 for (const name of binder.uniformNames) if (locations[name]) { 16089 const binding = binder.getBinding(context, locations[name], name); 16090 uniforms.push({ 16091 name, 16092 property, 16093 binding 16094 }); 16095 } 16096 } 16097 } 16098 return uniforms; 16099 } 16100 setUniforms(context, binderUniforms, properties, globals) { 16101 for (const { name, property, binding } of binderUniforms) this.binders[property].setUniform(binding, globals, properties.get(property), name); 16102 } 16103 updatePaintBuffers(crossfade) { 16104 this._buffers = []; 16105 for (const property in this.binders) { 16106 const binder = this.binders[property]; 16107 if (crossfade && binder instanceof CrossFadedBinder) { 16108 const patternVertexBuffer = crossfade.fromScale === 2 ? binder.zoomInPaintVertexBuffer : binder.zoomOutPaintVertexBuffer; 16109 if (patternVertexBuffer) this._buffers.push(patternVertexBuffer); 16110 } else if ((binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder) && binder.paintVertexBuffer) this._buffers.push(binder.paintVertexBuffer); 16111 } 16112 } 16113 upload(context) { 16114 for (const property in this.binders) { 16115 const binder = this.binders[property]; 16116 if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedBinder) binder.upload(context); 16117 } 16118 this.updatePaintBuffers(); 16119 } 16120 destroy() { 16121 for (const property in this.binders) { 16122 const binder = this.binders[property]; 16123 if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedBinder) binder.destroy(); 16124 } 16125 } 16126}; 16127var ProgramConfigurationSet = class { 16128 constructor(layers, zoom, filterProperties = () => true) { 16129 this.programConfigurations = {}; 16130 for (const layer of layers) this.programConfigurations[layer.id] = new ProgramConfiguration(layer, zoom, filterProperties); 16131 this.needsUpload = false; 16132 this._featureMap = new FeaturePositionMap(); 16133 this._bufferOffset = 0; 16134 } 16135 populatePaintArrays(length, feature, index, options) { 16136 for (const key in this.programConfigurations) this.programConfigurations[key].populatePaintArrays(length, feature, options); 16137 if (feature.id !== void 0) this._featureMap.add(feature.id, index, this._bufferOffset, length); 16138 this._bufferOffset = length; 16139 this.needsUpload = true; 16140 } 16141 updatePaintArrays(featureStates, vtLayer, layers, options) { 16142 for (const layer of layers) this.needsUpload = this.programConfigurations[layer.id].updatePaintArrays(featureStates, this._featureMap, vtLayer, layer, options) || this.needsUpload; 16143 } 16144 get(layerId) { 16145 return this.programConfigurations[layerId]; 16146 } 16147 upload(context) { 16148 if (!this.needsUpload) return; 16149 for (const layerId in this.programConfigurations) this.programConfigurations[layerId].upload(context); 16150 this.needsUpload = false; 16151 } 16152 destroy() { 16153 for (const layerId in this.programConfigurations) this.programConfigurations[layerId].destroy(); 16154 } 16155}; 16156function paintAttributeNames(property, type) { 16157 return { 16158 "text-opacity": ["opacity"], 16159 "icon-opacity": ["opacity"], 16160 "text-color": ["fill_color"], 16161 "icon-color": ["fill_color"], 16162 "text-halo-color": ["halo_color"], 16163 "icon-halo-color": ["halo_color"], 16164 "text-halo-blur": ["halo_blur"], 16165 "icon-halo-blur": ["halo_blur"], 16166 "text-halo-width": ["halo_width"], 16167 "icon-halo-width": ["halo_width"], 16168 "line-gap-width": ["gapwidth"], 16169 "line-dasharray": ["dasharray_to", "dasharray_from"], 16170 "line-pattern": [ 16171 "pattern_to", 16172 "pattern_from", 16173 "pixel_ratio_to", 16174 "pixel_ratio_from" 16175 ], 16176 "fill-pattern": [ 16177 "pattern_to", 16178 "pattern_from", 16179 "pixel_ratio_to", 16180 "pixel_ratio_from" 16181 ], 16182 "fill-extrusion-pattern": [ 16183 "pattern_to", 16184 "pattern_from", 16185 "pixel_ratio_to", 16186 "pixel_ratio_from" 16187 ] 16188 }[property] || [property.replace(`${type}-`, "").replace(/-/g, "_")]; 16189} 16190function getLayoutException(property) { 16191 return { 16192 "line-pattern": { 16193 "source": PatternLayoutArray, 16194 "composite": PatternLayoutArray 16195 }, 16196 "fill-pattern": { 16197 "source": PatternLayoutArray, 16198 "composite": PatternLayoutArray 16199 }, 16200 "fill-extrusion-pattern": { 16201 "source": PatternLayoutArray, 16202 "composite": PatternLayoutArray 16203 }, 16204 "line-dasharray": { 16205 "source": DashLayoutArray, 16206 "composite": DashLayoutArray 16207 } 16208 }[property]; 16209} 16210function layoutType(property, type, binderType) { 16211 const defaultLayouts = { 16212 "color": { 16213 "source": StructArrayLayout2f8, 16214 "composite": StructArrayLayout4f16 16215 }, 16216 "number": { 16217 "source": StructArrayLayout1f4, 16218 "composite": StructArrayLayout2f8 16219 } 16220 }; 16221 return getLayoutException(property)?.[binderType] || defaultLayouts[type][binderType]; 16222} 16223register("ConstantBinder", ConstantBinder); 16224register("CrossFadedConstantBinder", CrossFadedConstantBinder); 16225register("SourceExpressionBinder", SourceExpressionBinder); 16226register("CrossFadedPatternBinder", CrossFadedPatternBinder); 16227register("CrossFadedDasharrayBinder", CrossFadedDasharrayBinder); 16228register("CompositeExpressionBinder", CompositeExpressionBinder); 16229register("ProgramConfiguration", ProgramConfiguration, { omit: ["_buffers"] }); 16230register("ProgramConfigurationSet", ProgramConfigurationSet); 16231const MAX = Math.pow(2, 14) - 1; 16232const MIN = -MAX - 1; 16233/** 16234* Loads a geometry from a VectorTileFeatureLike and scales it to the common extent 16235* used internally. 16236* @param feature - the vector tile feature to load 16237*/ 16238function loadGeometry(feature) { 16239 const scale = EXTENT$1 / feature.extent; 16240 const geometry = feature.loadGeometry(); 16241 for (const ring of geometry) for (const point of ring) { 16242 const x = Math.round(point.x * scale); 16243 const y = Math.round(point.y * scale); 16244 point.x = clamp$2(x, MIN, MAX); 16245 point.y = clamp$2(y, MIN, MAX); 16246 if (x < point.x || x > point.x + 1 || y < point.y || y > point.y + 1) warnOnce("Geometry exceeds allowed extent, reduce your vector tile buffer size"); 16247 } 16248 return geometry; 16249} 16250//#endregion 16251//#region src/data/evaluation_feature.ts 16252/** 16253* Construct a new feature based on a VectorTileFeatureLike for expression evaluation, the geometry of which 16254* will be loaded based on necessity. 16255* @param feature - the feature to evaluate 16256* @param needGeometry - if set to true this will load the geometry 16257*/ 16258function toEvaluationFeature(feature, needGeometry) { 16259 return { 16260 type: feature.type, 16261 id: feature.id, 16262 properties: feature.properties, 16263 geometry: needGeometry ? loadGeometry(feature) : [] 16264 }; 16265} 16266//#endregion 16267//#region src/data/bucket/circle_bucket.ts 16268const VERTEX_MIN_VALUE = -32768; 16269function addCircleVertex(layoutVertexArray, x, y, extrudeX, extrudeY) { 16270 layoutVertexArray.emplaceBack(VERTEX_MIN_VALUE + x * 8 + extrudeX, VERTEX_MIN_VALUE + y * 8 + extrudeY); 16271} 16272/** 16273* @internal 16274* Circles are represented by two triangles. 16275* 16276* Each corner has a pos that is the center of the circle and an extrusion 16277* vector that is where it points. 16278*/ 16279var CircleBucket = class { 16280 constructor(options) { 16281 this.zoom = options.zoom; 16282 this.overscaling = options.overscaling; 16283 this.layers = options.layers; 16284 this.layerIds = this.layers.map((layer) => layer.id); 16285 this.index = options.index; 16286 this.hasDependencies = false; 16287 this.layoutVertexArray = new CircleLayoutArray(); 16288 this.indexArray = new TriangleIndexArray(); 16289 this.segments = new SegmentVector(); 16290 this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom); 16291 this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); 16292 } 16293 populate(features, options, canonical) { 16294 const styleLayer = this.layers[0]; 16295 const bucketFeatures = []; 16296 let circleSortKey = null; 16297 let sortFeaturesByKey = false; 16298 let subdivide = styleLayer.type === "heatmap"; 16299 if (styleLayer.type === "circle") { 16300 const circleStyle = styleLayer; 16301 circleSortKey = circleStyle.layout.get("circle-sort-key"); 16302 sortFeaturesByKey = !circleSortKey.isConstant(); 16303 subdivide ||= circleStyle.paint.get("circle-pitch-alignment") === "map"; 16304 } 16305 const granularity = subdivide ? options.subdivisionGranularity.circle : 1; 16306 const globalProperties = new EvaluationParameters(this.zoom); 16307 const needGeometry = this.layers[0]._featureFilter.needGeometry; 16308 for (const { feature, id, index, sourceLayerIndex } of features) { 16309 const evaluationFeature = toEvaluationFeature(feature, needGeometry); 16310 if (!this.layers[0]._featureFilter.filter(globalProperties, evaluationFeature, canonical)) continue; 16311 const sortKey = sortFeaturesByKey ? circleSortKey.evaluate(evaluationFeature, {}, canonical) : void 0; 16312 const bucketFeature = { 16313 id, 16314 properties: feature.properties, 16315 type: feature.type, 16316 sourceLayerIndex, 16317 index, 16318 geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature), 16319 patterns: {}, 16320 sortKey 16321 }; 16322 bucketFeatures.push(bucketFeature); 16323 } 16324 if (sortFeaturesByKey) bucketFeatures.sort((a, b) => a.sortKey - b.sortKey); 16325 for (const bucketFeature of bucketFeatures) { 16326 const { geometry, index, sourceLayerIndex } = bucketFeature; 16327 const feature = features[index].feature; 16328 this.addFeature(bucketFeature, geometry, index, canonical, granularity); 16329 options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index); 16330 } 16331 } 16332 update(states, vtLayer, imagePositions) { 16333 if (!this.stateDependentLayers.length) return; 16334 this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, { imagePositions }); 16335 } 16336 addFeatures(_parameters) {} 16337 isEmpty() { 16338 return this.layoutVertexArray.length === 0; 16339 } 16340 uploadPending() { 16341 return !this.uploaded || this.programConfigurations.needsUpload; 16342 } 16343 upload(context) { 16344 if (!this.uploaded) { 16345 this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$4); 16346 this.indexBuffer = context.createIndexBuffer(this.indexArray); 16347 } 16348 this.programConfigurations.upload(context); 16349 this.uploaded = true; 16350 } 16351 destroy() { 16352 if (!this.layoutVertexBuffer) return; 16353 this.layoutVertexBuffer.destroy(); 16354 this.indexBuffer.destroy(); 16355 this.programConfigurations.destroy(); 16356 this.segments.destroy(); 16357 } 16358 addFeature(feature, geometry, index, canonical, granularity = 1) { 16359 let extrudes; 16360 switch (granularity) { 16361 case 1: 16362 extrudes = [0, 7]; 16363 break; 16364 case 3: 16365 extrudes = [ 16366 0, 16367 2, 16368 5, 16369 7 16370 ]; 16371 break; 16372 case 5: 16373 extrudes = [ 16374 0, 16375 1, 16376 3, 16377 4, 16378 6, 16379 7 16380 ]; 16381 break; 16382 case 7: 16383 extrudes = [ 16384 0, 16385 1, 16386 2, 16387 3, 16388 4, 16389 5, 16390 6, 16391 7 16392 ]; 16393 break; 16394 default: throw new Error(`Invalid circle bucket granularity: ${granularity}; valid values are 1, 3, 5, 7.`); 16395 } 16396 const verticesPerAxis = extrudes.length; 16397 for (const ring of geometry) for (const point of ring) { 16398 const vx = point.x; 16399 const vy = point.y; 16400 if (vx < 0 || vx >= 8192 || vy < 0 || vy >= 8192) continue; 16401 const segment = this.segments.prepareSegment(verticesPerAxis * verticesPerAxis, this.layoutVertexArray, this.indexArray, feature.sortKey); 16402 const index = segment.vertexLength; 16403 for (let y = 0; y < verticesPerAxis; y++) for (let x = 0; x < verticesPerAxis; x++) addCircleVertex(this.layoutVertexArray, vx, vy, extrudes[x], extrudes[y]); 16404 for (let y = 0; y < verticesPerAxis - 1; y++) for (let x = 0; x < verticesPerAxis - 1; x++) { 16405 const lowerIndex = index + y * verticesPerAxis + x; 16406 const upperIndex = index + (y + 1) * verticesPerAxis + x; 16407 this.indexArray.emplaceBack(lowerIndex, upperIndex + 1, lowerIndex + 1); 16408 this.indexArray.emplaceBack(lowerIndex, upperIndex, upperIndex + 1); 16409 } 16410 segment.vertexLength += verticesPerAxis * verticesPerAxis; 16411 segment.primitiveLength += (verticesPerAxis - 1) * (verticesPerAxis - 1) * 2; 16412 } 16413 this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, { 16414 imagePositions: {}, 16415 canonical 16416 }); 16417 } 16418}; 16419register("CircleBucket", CircleBucket, { omit: ["layers"] }); 16420//#endregion 16421//#region src/util/intersection_tests.ts 16422function polygonIntersectsPolygon(polygonA, polygonB) { 16423 for (const point of polygonA) if (polygonContainsPoint(polygonB, point)) return true; 16424 for (const point of polygonB) if (polygonContainsPoint(polygonA, point)) return true; 16425 return lineIntersectsLine(polygonA, polygonB); 16426} 16427function polygonIntersectsBufferedPoint(polygon, point, radius) { 16428 if (polygonContainsPoint(polygon, point)) return true; 16429 return pointIntersectsBufferedLine(point, polygon, radius); 16430} 16431function polygonIntersectsMultiPolygon(polygon, multiPolygon) { 16432 if (polygon.length === 1) return multiPolygonContainsPoint(multiPolygon, polygon[0]); 16433 for (const ring of multiPolygon) for (const point of ring) if (polygonContainsPoint(polygon, point)) return true; 16434 for (const point of polygon) if (multiPolygonContainsPoint(multiPolygon, point)) return true; 16435 for (const ring of multiPolygon) if (lineIntersectsLine(polygon, ring)) return true; 16436 return false; 16437} 16438function polygonIntersectsBufferedMultiLine(polygon, multiLine, radius) { 16439 for (const line of multiLine) { 16440 if (polygon.length >= 3) { 16441 for (const point of line) if (polygonContainsPoint(polygon, point)) return true; 16442 } 16443 if (lineIntersectsBufferedLine(polygon, line, radius)) return true; 16444 } 16445 return false; 16446} 16447function lineIntersectsBufferedLine(lineA, lineB, radius) { 16448 if (lineA.length > 1) { 16449 if (lineIntersectsLine(lineA, lineB)) return true; 16450 for (const point of lineB) if (pointIntersectsBufferedLine(point, lineA, radius)) return true; 16451 } 16452 for (const point of lineA) if (pointIntersectsBufferedLine(point, lineB, radius)) return true; 16453 return false; 16454} 16455function lineIntersectsLine(lineA, lineB) { 16456 if (lineA.length === 0 || lineB.length === 0) return false; 16457 for (let i = 0; i < lineA.length - 1; i++) { 16458 const a0 = lineA[i]; 16459 const a1 = lineA[i + 1]; 16460 for (let j = 0; j < lineB.length - 1; j++) { 16461 const b0 = lineB[j]; 16462 const b1 = lineB[j + 1]; 16463 if (lineSegmentIntersectsLineSegment(a0, a1, b0, b1)) return true; 16464 } 16465 } 16466 return false; 16467} 16468function lineSegmentIntersectsLineSegment(a0, a1, b0, b1) { 16469 return isCounterClockwise(a0, b0, b1) !== isCounterClockwise(a1, b0, b1) && isCounterClockwise(a0, a1, b0) !== isCounterClockwise(a0, a1, b1); 16470} 16471function pointIntersectsBufferedLine(p, line, radius) { 16472 const radiusSquared = radius * radius; 16473 if (line.length === 1) return p.distSqr(line[0]) < radiusSquared; 16474 for (let i = 1; i < line.length; i++) { 16475 const v = line[i - 1], w = line[i]; 16476 if (distToSegmentSquared(p, v, w) < radiusSquared) return true; 16477 } 16478 return false; 16479} 16480function distToSegmentSquared(p, v, w) { 16481 const l2 = v.distSqr(w); 16482 if (l2 === 0) return p.distSqr(v); 16483 const t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2; 16484 if (t < 0) return p.distSqr(v); 16485 if (t > 1) return p.distSqr(w); 16486 return p.distSqr(w.sub(v)._mult(t)._add(v)); 16487} 16488function multiPolygonContainsPoint(rings, p) { 16489 let c = false, ring, p1, p2; 16490 for (const currentRing of rings) { 16491 ring = currentRing; 16492 for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { 16493 p1 = ring[i]; 16494 p2 = ring[j]; 16495 if (p1.y > p.y !== p2.y > p.y && p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x) c = !c; 16496 } 16497 } 16498 return c; 16499} 16500function polygonContainsPoint(ring, p) { 16501 let c = false; 16502 for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { 16503 const p1 = ring[i]; 16504 const p2 = ring[j]; 16505 if (p1.y > p.y !== p2.y > p.y && p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x) c = !c; 16506 } 16507 return c; 16508} 16509function polygonIntersectsBox(ring, boxX1, boxY1, boxX2, boxY2) { 16510 for (const p of ring) if (boxX1 <= p.x && boxY1 <= p.y && boxX2 >= p.x && boxY2 >= p.y) return true; 16511 const corners = [ 16512 new Point(boxX1, boxY1), 16513 new Point(boxX1, boxY2), 16514 new Point(boxX2, boxY2), 16515 new Point(boxX2, boxY1) 16516 ]; 16517 if (ring.length > 2) { 16518 for (const corner of corners) if (polygonContainsPoint(ring, corner)) return true; 16519 } 16520 for (let i = 0; i < ring.length - 1; i++) { 16521 const p1 = ring[i]; 16522 const p2 = ring[i + 1]; 16523 if (edgeIntersectsBox(p1, p2, corners)) return true; 16524 } 16525 return false; 16526} 16527function edgeIntersectsBox(e1, e2, corners) { 16528 const tl = corners[0]; 16529 const br = corners[2]; 16530 if (e1.x < tl.x && e2.x < tl.x || e1.x > br.x && e2.x > br.x || e1.y < tl.y && e2.y < tl.y || e1.y > br.y && e2.y > br.y) return false; 16531 const dir = isCounterClockwise(e1, e2, corners[0]); 16532 return dir !== isCounterClockwise(e1, e2, corners[1]) || dir !== isCounterClockwise(e1, e2, corners[2]) || dir !== isCounterClockwise(e1, e2, corners[3]); 16533} 16534//#endregion 16535//#region src/style/query_utils.ts 16536function getMaximumPaintValue(property, layer, bucket) { 16537 const value = layer.paint.get(property).value; 16538 if (value.kind === "constant") return value.value; 16539 else return bucket.programConfigurations.get(layer.id).getMaxValue(property); 16540} 16541function translateDistance(translate) { 16542 return Math.sqrt(translate[0] * translate[0] + translate[1] * translate[1]); 16543} 16544/** 16545* @internal 16546* Translates a geometry by a certain pixels in tile coordinates 16547* @param queryGeometry - The geometry to translate in tile coordinates 16548* @param translate - The translation in pixels 16549* @param translateAnchor - The anchor of the translation 16550* @param bearing - The bearing of the map 16551* @param pixelsToTileUnits - The scale factor from pixels to tile units 16552* @returns the translated geometry in tile coordinates 16553*/ 16554function translate(queryGeometry, translate, translateAnchor, bearing, pixelsToTileUnits) { 16555 if (!translate[0] && !translate[1]) return queryGeometry; 16556 const pt = Point.convert(translate)._mult(pixelsToTileUnits); 16557 if (translateAnchor === "viewport") pt._rotate(-bearing); 16558 const translated = []; 16559 for (const point of queryGeometry) translated.push(point.sub(pt)); 16560 return translated; 16561} 16562/** 16563* Filter out consecutive duplicate points from a line 16564*/ 16565function _stripDuplicates(ring) { 16566 const filteredRing = []; 16567 for (let index = 0; index < ring.length; index++) { 16568 const point = ring[index]; 16569 const prevPoint = filteredRing.at(-1); 16570 if (index === 0 || prevPoint && !point.equals(prevPoint)) filteredRing.push(point); 16571 } 16572 return filteredRing; 16573} 16574function offsetLine(rings, offset) { 16575 const newRings = []; 16576 for (const rawRing of rings) { 16577 const ring = _stripDuplicates(rawRing); 16578 const newRing = []; 16579 for (let index = 0; index < ring.length; index++) { 16580 const point = ring[index]; 16581 const prevPoint = ring[index - 1]; 16582 const nextPoint = ring[index + 1]; 16583 const unitNormalAB = index === 0 ? new Point(0, 0) : point.sub(prevPoint)._unit()._perp(); 16584 const unitNormalBC = index === ring.length - 1 ? new Point(0, 0) : nextPoint.sub(point)._unit()._perp(); 16585 const bisectorDir = unitNormalAB._add(unitNormalBC)._unit(); 16586 const cosHalfAngle = bisectorDir.x * unitNormalBC.x + bisectorDir.y * unitNormalBC.y; 16587 if (cosHalfAngle !== 0) bisectorDir._mult(1 / cosHalfAngle); 16588 newRing.push(bisectorDir._mult(offset)._add(point)); 16589 } 16590 newRings.push(newRing); 16591 } 16592 return newRings; 16593} 16594function intersectionTestMapMap({ queryGeometry, size }, point) { 16595 return polygonIntersectsBufferedPoint(queryGeometry, point, size); 16596} 16597function intersectionTestMapViewport({ queryGeometry, size, transform, unwrappedTileID, getElevation }, point) { 16598 return polygonIntersectsBufferedPoint(queryGeometry, point, size * (transform.projectTileCoordinates(point.x, point.y, unwrappedTileID, getElevation?.(point.x, point.y)).signedDistanceFromCamera / transform.cameraToCenterDistance)); 16599} 16600function intersectionTestViewportMap({ queryGeometry, size, transform, unwrappedTileID, getElevation }, point) { 16601 const w = transform.projectTileCoordinates(point.x, point.y, unwrappedTileID, getElevation?.(point.x, point.y)).signedDistanceFromCamera; 16602 const adjustedSize = size * (transform.cameraToCenterDistance / w); 16603 return polygonIntersectsBufferedPoint(queryGeometry, projectPoint(point, transform, unwrappedTileID, getElevation), adjustedSize); 16604} 16605function intersectionTestViewportViewport({ queryGeometry, size, transform, unwrappedTileID, getElevation }, point) { 16606 return polygonIntersectsBufferedPoint(queryGeometry, projectPoint(point, transform, unwrappedTileID, getElevation), size); 16607} 16608function circleIntersection({ queryGeometry, size, transform, unwrappedTileID, getElevation, pitchAlignment = "map", pitchScale = "map" }, geometry) { 16609 const intersectionTest = pitchAlignment === "map" ? pitchScale === "map" ? intersectionTestMapMap : intersectionTestMapViewport : pitchScale === "map" ? intersectionTestViewportMap : intersectionTestViewportViewport; 16610 const param = { 16611 queryGeometry, 16612 size, 16613 transform, 16614 unwrappedTileID, 16615 getElevation 16616 }; 16617 for (const ring of geometry) for (const point of ring) if (intersectionTest(param, point)) return true; 16618 return false; 16619} 16620function projectPoint(tilePoint, transform, unwrappedTileID, getElevation) { 16621 const clipPoint = transform.projectTileCoordinates(tilePoint.x, tilePoint.y, unwrappedTileID, getElevation?.(tilePoint.x, tilePoint.y)).point; 16622 return new Point((clipPoint.x * .5 + .5) * transform.width, (-clipPoint.y * .5 + .5) * transform.height); 16623} 16624function projectQueryGeometry$1(queryGeometry, transform, unwrappedTileID, getElevation) { 16625 return queryGeometry.map((p) => { 16626 return projectPoint(p, transform, unwrappedTileID, getElevation); 16627 }); 16628} 16629//#endregion 16630//#region src/style/style_layer/circle_style_layer_properties.g.ts 16631let layout$6; 16632const getLayout$4 = () => layout$6 = layout$6 || new Properties({ "circle-sort-key": new DataDrivenProperty(latest["layout_circle"]["circle-sort-key"], "circle-sort-key") }); 16633let paint$8; 16634const getPaint$8 = () => paint$8 = paint$8 || new Properties({ 16635 "circle-radius": new DataDrivenProperty(latest["paint_circle"]["circle-radius"], "circle-radius"), 16636 "circle-color": new DataDrivenProperty(latest["paint_circle"]["circle-color"], "circle-color"), 16637 "circle-blur": new DataDrivenProperty(latest["paint_circle"]["circle-blur"], "circle-blur"), 16638 "circle-opacity": new DataDrivenProperty(latest["paint_circle"]["circle-opacity"], "circle-opacity"), 16639 "circle-translate": new DataConstantProperty(latest["paint_circle"]["circle-translate"], "circle-translate"), 16640 "circle-translate-anchor": new DataConstantProperty(latest["paint_circle"]["circle-translate-anchor"], "circle-translate-anchor"), 16641 "circle-pitch-scale": new DataConstantProperty(latest["paint_circle"]["circle-pitch-scale"], "circle-pitch-scale"), 16642 "circle-pitch-alignment": new DataConstantProperty(latest["paint_circle"]["circle-pitch-alignment"], "circle-pitch-alignment"), 16643 "circle-stroke-width": new DataDrivenProperty(latest["paint_circle"]["circle-stroke-width"], "circle-stroke-width"), 16644 "circle-stroke-color": new DataDrivenProperty(latest["paint_circle"]["circle-stroke-color"], "circle-stroke-color"), 16645 "circle-stroke-opacity": new DataDrivenProperty(latest["paint_circle"]["circle-stroke-opacity"], "circle-stroke-opacity") 16646}); 16647var circle_style_layer_properties_g_default = { 16648 get paint() { 16649 return getPaint$8(); 16650 }, 16651 get layout() { 16652 return getLayout$4(); 16653 } 16654}; 16655//#endregion 16656//#region src/style/style_layer/circle_style_layer.ts 16657const isCircleStyleLayer = (layer) => layer.type === "circle"; 16658/** 16659* A style layer that defines a circle 16660*/ 16661var CircleStyleLayer = class extends StyleLayer { 16662 constructor(layer, globalState) { 16663 super(layer, circle_style_layer_properties_g_default, globalState); 16664 } 16665 createBucket(parameters) { 16666 return new CircleBucket(parameters); 16667 } 16668 queryRadius(bucket) { 16669 const circleBucket = bucket; 16670 return getMaximumPaintValue("circle-radius", this, circleBucket) + getMaximumPaintValue("circle-stroke-width", this, circleBucket) + translateDistance(this.paint.get("circle-translate")); 16671 } 16672 queryIntersectsFeature({ queryGeometry, feature, featureState, geometry, transform, pixelsToTileUnits, unwrappedTileID, getElevation }) { 16673 const translatedPolygon = translate(queryGeometry, this.paint.get("circle-translate"), this.paint.get("circle-translate-anchor"), -transform.bearingInRadians, pixelsToTileUnits); 16674 const size = this.paint.get("circle-radius").evaluate(feature, featureState) + this.paint.get("circle-stroke-width").evaluate(feature, featureState); 16675 const pitchScale = this.paint.get("circle-pitch-scale"); 16676 const pitchAlignment = this.paint.get("circle-pitch-alignment"); 16677 let transformedPolygon; 16678 let transformedSize; 16679 if (pitchAlignment === "map") { 16680 transformedPolygon = translatedPolygon; 16681 transformedSize = size * pixelsToTileUnits; 16682 } else { 16683 transformedPolygon = projectQueryGeometry$1(translatedPolygon, transform, unwrappedTileID, getElevation); 16684 transformedSize = size; 16685 } 16686 return circleIntersection({ 16687 queryGeometry: transformedPolygon, 16688 size: transformedSize, 16689 transform, 16690 unwrappedTileID, 16691 getElevation, 16692 pitchAlignment, 16693 pitchScale 16694 }, geometry); 16695 } 16696}; 16697//#endregion 16698//#region src/data/bucket/heatmap_bucket.ts 16699var HeatmapBucket = class extends CircleBucket {}; 16700register("HeatmapBucket", HeatmapBucket, { omit: ["layers"] }); 16701//#endregion 16702//#region src/style/style_layer/heatmap_style_layer_properties.g.ts 16703let paint$7; 16704const getPaint$7 = () => paint$7 = paint$7 || new Properties({ 16705 "heatmap-radius": new DataDrivenProperty(latest["paint_heatmap"]["heatmap-radius"], "heatmap-radius"), 16706 "heatmap-weight": new DataDrivenProperty(latest["paint_heatmap"]["heatmap-weight"], "heatmap-weight"), 16707 "heatmap-intensity": new DataConstantProperty(latest["paint_heatmap"]["heatmap-intensity"], "heatmap-intensity"), 16708 "heatmap-color": new ColorRampProperty(latest["paint_heatmap"]["heatmap-color"], "heatmap-color"), 16709 "heatmap-opacity": new DataConstantProperty(latest["paint_heatmap"]["heatmap-opacity"], "heatmap-opacity") 16710}); 16711var heatmap_style_layer_properties_g_default = { get paint() { 16712 return getPaint$7(); 16713} }; 16714//#endregion 16715//#region src/util/image.ts 16716function createImage(image, { width, height }, channels, data) { 16717 if (!data) data = new Uint8Array(width * height * channels); 16718 else if (data instanceof Uint8ClampedArray) data = new Uint8Array(data.buffer); 16719 else if (data.length !== width * height * channels) throw new RangeError(`mismatched image size. expected: ${data.length} but got: ${width * height * channels}`); 16720 image.width = width; 16721 image.height = height; 16722 image.data = data; 16723 return image; 16724} 16725function resizeImage(image, { width, height }, channels) { 16726 if (width === image.width && height === image.height) return; 16727 const newImage = createImage({}, { 16728 width, 16729 height 16730 }, channels); 16731 copyImage(image, newImage, { 16732 x: 0, 16733 y: 0 16734 }, { 16735 x: 0, 16736 y: 0 16737 }, { 16738 width: Math.min(image.width, width), 16739 height: Math.min(image.height, height) 16740 }, channels); 16741 image.width = width; 16742 image.height = height; 16743 image.data = newImage.data; 16744} 16745function copyImage(srcImg, dstImg, srcPt, dstPt, size, channels) { 16746 if (size.width === 0 || size.height === 0) return dstImg; 16747 if (size.width > srcImg.width || size.height > srcImg.height || srcPt.x > srcImg.width - size.width || srcPt.y > srcImg.height - size.height) throw new RangeError("out of range source coordinates for image copy"); 16748 if (size.width > dstImg.width || size.height > dstImg.height || dstPt.x > dstImg.width - size.width || dstPt.y > dstImg.height - size.height) throw new RangeError("out of range destination coordinates for image copy"); 16749 const srcData = srcImg.data; 16750 const dstData = dstImg.data; 16751 if (srcData === dstData) throw new Error("srcData equals dstData, so image is already copied"); 16752 for (let y = 0; y < size.height; y++) { 16753 const srcOffset = ((srcPt.y + y) * srcImg.width + srcPt.x) * channels; 16754 const dstOffset = ((dstPt.y + y) * dstImg.width + dstPt.x) * channels; 16755 for (let i = 0; i < size.width * channels; i++) dstData[dstOffset + i] = srcData[srcOffset + i]; 16756 } 16757 return dstImg; 16758} 16759/** 16760* An image with alpha color value 16761*/ 16762var AlphaImage = class AlphaImage { 16763 constructor(size, data) { 16764 createImage(this, size, 1, data); 16765 } 16766 resize(size) { 16767 resizeImage(this, size, 1); 16768 } 16769 clone() { 16770 return new AlphaImage({ 16771 width: this.width, 16772 height: this.height 16773 }, new Uint8Array(this.data)); 16774 } 16775 static copy(srcImg, dstImg, srcPt, dstPt, size) { 16776 copyImage(srcImg, dstImg, srcPt, dstPt, size, 1); 16777 } 16778}; 16779/** 16780* An object to store image data not premultiplied, because ImageData is not premultiplied. 16781* Premultiplication is applied in JS before uploading to a texture. 16782*/ 16783var RGBAImage = class RGBAImage { 16784 constructor(size, data) { 16785 createImage(this, size, 4, data); 16786 } 16787 resize(size) { 16788 resizeImage(this, size, 4); 16789 } 16790 replace(data, copy) { 16791 if (copy) this.data.set(data); 16792 else if (data instanceof Uint8ClampedArray) this.data = new Uint8Array(data.buffer); 16793 else this.data = data; 16794 } 16795 clone() { 16796 return new RGBAImage({ 16797 width: this.width, 16798 height: this.height 16799 }, new Uint8Array(this.data)); 16800 } 16801 static copy(srcImg, dstImg, srcPt, dstPt, size) { 16802 copyImage(srcImg, dstImg, srcPt, dstPt, size, 4); 16803 } 16804 setPixel(row, col, value) { 16805 const rLocation = (row * this.width + col) * 4; 16806 this.data[rLocation + 0] = Math.round(value.r * 255 / value.a); 16807 this.data[rLocation + 1] = Math.round(value.g * 255 / value.a); 16808 this.data[rLocation + 2] = Math.round(value.b * 255 / value.a); 16809 this.data[rLocation + 3] = Math.round(value.a * 255); 16810 } 16811}; 16812/** Returns a copy of RGBA data with premultiplied alpha. */ 16813function premultiplyAlpha(data) { 16814 const out = new Uint8Array(data.length); 16815 for (let i = 0; i < data.length; i += 4) { 16816 const a = data[i + 3]; 16817 out[i + 0] = Math.round(data[i + 0] * a / 255); 16818 out[i + 1] = Math.round(data[i + 1] * a / 255); 16819 out[i + 2] = Math.round(data[i + 2] * a / 255); 16820 out[i + 3] = a; 16821 } 16822 return out; 16823} 16824register("AlphaImage", AlphaImage); 16825register("RGBAImage", RGBAImage); 16826//#endregion 16827//#region src/util/color_ramp.ts 16828/** 16829* Given an expression that should evaluate to a color ramp, 16830* return a RGBA image representing that ramp expression. 16831*/ 16832function renderColorRamp(params) { 16833 const evaluationGlobals = {}; 16834 const width = params.resolution || 256; 16835 const height = params.clips ? params.clips.length : 1; 16836 const image = params.image || new RGBAImage({ 16837 width, 16838 height 16839 }); 16840 if (!isPowerOfTwo(width)) throw new Error(`width is not a power of 2 - ${width}`); 16841 const renderPixel = (stride, index, progress) => { 16842 evaluationGlobals[params.evaluationKey] = progress; 16843 const pxColor = params.expression.evaluate(evaluationGlobals); 16844 image.setPixel(stride / 4 / width, index / 4, pxColor); 16845 }; 16846 if (!params.clips) for (let i = 0, j = 0; i < width; i++, j += 4) { 16847 const progress = i / (width - 1); 16848 renderPixel(0, j, progress); 16849 } 16850 else for (let clip = 0, stride = 0; clip < height; ++clip, stride += width * 4) for (let i = 0, j = 0; i < width; i++, j += 4) { 16851 const progress = i / (width - 1); 16852 const { start, end } = params.clips[clip]; 16853 const evaluationProgress = start * (1 - progress) + end * progress; 16854 renderPixel(stride, j, evaluationProgress); 16855 } 16856 return image; 16857} 16858//#endregion 16859//#region src/style/style_layer/heatmap_style_layer.ts 16860const HEATMAP_FULL_RENDER_FBO_KEY = "big-fb"; 16861const isHeatmapStyleLayer = (layer) => layer.type === "heatmap"; 16862/** 16863* A style layer that defines a heatmap 16864*/ 16865var HeatmapStyleLayer = class extends StyleLayer { 16866 createBucket(options) { 16867 return new HeatmapBucket(options); 16868 } 16869 constructor(layer, globalState) { 16870 super(layer, heatmap_style_layer_properties_g_default, globalState); 16871 this.heatmapFbos = /* @__PURE__ */ new Map(); 16872 this._updateColorRamp(); 16873 } 16874 _handleSpecialPaintPropertyUpdate(name) { 16875 if (name === "heatmap-color") this._updateColorRamp(); 16876 } 16877 _updateColorRamp() { 16878 const expression = this._transitionablePaint._values["heatmap-color"].value.expression; 16879 this.colorRamp = renderColorRamp({ 16880 expression, 16881 evaluationKey: "heatmapDensity", 16882 image: this.colorRamp 16883 }); 16884 this.colorRampTexture = null; 16885 } 16886 resize() { 16887 if (this.heatmapFbos.has("big-fb")) this.heatmapFbos.delete(HEATMAP_FULL_RENDER_FBO_KEY); 16888 } 16889 queryRadius(bucket) { 16890 return getMaximumPaintValue("heatmap-radius", this, bucket); 16891 } 16892 queryIntersectsFeature({ queryGeometry, feature, featureState, geometry, transform, pixelsToTileUnits, unwrappedTileID, getElevation }) { 16893 return circleIntersection({ 16894 queryGeometry, 16895 size: this.paint.get("heatmap-radius").evaluate(feature, featureState) * pixelsToTileUnits, 16896 transform, 16897 unwrappedTileID, 16898 getElevation 16899 }, geometry); 16900 } 16901 hasOffscreenPass() { 16902 return this.paint.get("heatmap-opacity") !== 0 && !this.isHidden(); 16903 } 16904}; 16905//#endregion 16906//#region src/style/style_layer/hillshade_style_layer_properties.g.ts 16907let paint$6; 16908const getPaint$6 = () => paint$6 = paint$6 || new Properties({ 16909 "hillshade-illumination-direction": new DataConstantProperty(latest["paint_hillshade"]["hillshade-illumination-direction"], "hillshade-illumination-direction"), 16910 "hillshade-illumination-altitude": new DataConstantProperty(latest["paint_hillshade"]["hillshade-illumination-altitude"], "hillshade-illumination-altitude"), 16911 "hillshade-illumination-anchor": new DataConstantProperty(latest["paint_hillshade"]["hillshade-illumination-anchor"], "hillshade-illumination-anchor"), 16912 "hillshade-exaggeration": new DataConstantProperty(latest["paint_hillshade"]["hillshade-exaggeration"], "hillshade-exaggeration"), 16913 "hillshade-shadow-color": new DataConstantProperty(latest["paint_hillshade"]["hillshade-shadow-color"], "hillshade-shadow-color"), 16914 "hillshade-highlight-color": new DataConstantProperty(latest["paint_hillshade"]["hillshade-highlight-color"], "hillshade-highlight-color"), 16915 "hillshade-accent-color": new DataConstantProperty(latest["paint_hillshade"]["hillshade-accent-color"], "hillshade-accent-color"), 16916 "hillshade-method": new DataConstantProperty(latest["paint_hillshade"]["hillshade-method"], "hillshade-method"), 16917 "resampling": new DataConstantProperty(latest["paint_hillshade"]["resampling"], "resampling") 16918}); 16919var hillshade_style_layer_properties_g_default = { get paint() { 16920 return getPaint$6(); 16921} }; 16922//#endregion 16923//#region src/style/style_layer/hillshade_style_layer.ts 16924const isHillshadeStyleLayer = (layer) => layer.type === "hillshade"; 16925var HillshadeStyleLayer = class extends StyleLayer { 16926 constructor(layer, globalState) { 16927 super(layer, hillshade_style_layer_properties_g_default, globalState); 16928 this.recalculate({ 16929 zoom: 0, 16930 zoomHistory: {} 16931 }, void 0); 16932 } 16933 getIlluminationProperties() { 16934 let direction = this.paint.get("hillshade-illumination-direction").values; 16935 let altitude = this.paint.get("hillshade-illumination-altitude").values; 16936 let highlightColor = this.paint.get("hillshade-highlight-color").values; 16937 let shadowColor = this.paint.get("hillshade-shadow-color").values; 16938 const numIlluminationSources = Math.max(direction.length, altitude.length, highlightColor.length, shadowColor.length); 16939 direction = direction.concat(Array(numIlluminationSources - direction.length).fill(direction.at(-1))); 16940 altitude = altitude.concat(Array(numIlluminationSources - altitude.length).fill(altitude.at(-1))); 16941 highlightColor = highlightColor.concat(Array(numIlluminationSources - highlightColor.length).fill(highlightColor.at(-1))); 16942 shadowColor = shadowColor.concat(Array(numIlluminationSources - shadowColor.length).fill(shadowColor.at(-1))); 16943 const altitudeRadians = altitude.map(degreesToRadians); 16944 return { 16945 directionRadians: direction.map(degreesToRadians), 16946 altitudeRadians, 16947 shadowColor, 16948 highlightColor 16949 }; 16950 } 16951 hasOffscreenPass() { 16952 return this.paint.get("hillshade-exaggeration") !== 0 && !this.isHidden(); 16953 } 16954}; 16955//#endregion 16956//#region src/style/style_layer/color_relief_style_layer_properties.g.ts 16957let paint$5; 16958const getPaint$5 = () => paint$5 = paint$5 || new Properties({ 16959 "color-relief-opacity": new DataConstantProperty(latest["paint_color-relief"]["color-relief-opacity"], "color-relief-opacity"), 16960 "color-relief-color": new ColorRampProperty(latest["paint_color-relief"]["color-relief-color"], "color-relief-color"), 16961 "resampling": new DataConstantProperty(latest["paint_color-relief"]["resampling"], "resampling") 16962}); 16963var color_relief_style_layer_properties_g_default = { get paint() { 16964 return getPaint$5(); 16965} }; 16966//#endregion 16967//#region src/webgl/texture.ts 16968function hasDataProperty(image) { 16969 return "data" in image; 16970} 16971/** 16972* @internal 16973* A `Texture` GL related object 16974*/ 16975var Texture = class { 16976 constructor(context, image, format, options) { 16977 this.context = context; 16978 this.format = format; 16979 this.texture = context.gl.createTexture(); 16980 this._ownedHandle = this.texture; 16981 this.update(image, options); 16982 } 16983 update(image, options, position) { 16984 const { width, height } = image; 16985 const resize = (this.size?.[0] !== width || this.size[1] !== height) && !position; 16986 const { context } = this; 16987 const { gl } = context; 16988 this.useMipmap = Boolean(options?.useMipmap); 16989 if (resize && this.size && this.format === gl.RGBA) { 16990 gl.deleteTexture(this.texture); 16991 this.texture = gl.createTexture(); 16992 this._ownedHandle = this.texture; 16993 this.magFilter = void 0; 16994 this.minFilter = void 0; 16995 this.wrap = void 0; 16996 } 16997 gl.bindTexture(gl.TEXTURE_2D, this.texture); 16998 context.pixelStoreUnpackFlipY.set(false); 16999 context.pixelStoreUnpack.set(1); 17000 const wantPremultiply = this.format === gl.RGBA && options?.premultiply !== false; 17001 if (resize) { 17002 this.size = [width, height]; 17003 if (this.format === gl.RGBA && width > 0 && height > 0) { 17004 const mipLevels = this.useMipmap ? Math.floor(Math.log2(Math.max(width, height))) + 1 : 1; 17005 gl.texStorage2D(gl.TEXTURE_2D, mipLevels, gl.RGBA8, width, height); 17006 if (hasDataProperty(image)) { 17007 context.pixelStoreUnpackPremultiplyAlpha.set(false); 17008 let { data } = image; 17009 if (wantPremultiply && data) data = premultiplyAlpha(data); 17010 if (data) gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, data); 17011 } else { 17012 context.pixelStoreUnpackPremultiplyAlpha.set(wantPremultiply); 17013 gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, image); 17014 } 17015 } else if (hasDataProperty(image)) { 17016 context.pixelStoreUnpackPremultiplyAlpha.set(false); 17017 this._uploadRawData(image, wantPremultiply, width, height, gl); 17018 } else { 17019 context.pixelStoreUnpackPremultiplyAlpha.set(wantPremultiply); 17020 this._uploadDomImage(image, gl); 17021 } 17022 } else { 17023 const { x, y } = position || { 17024 x: 0, 17025 y: 0 17026 }; 17027 if (hasDataProperty(image)) { 17028 context.pixelStoreUnpackPremultiplyAlpha.set(false); 17029 this._updateRawData(image, wantPremultiply, x, y, width, height, gl); 17030 } else { 17031 context.pixelStoreUnpackPremultiplyAlpha.set(wantPremultiply); 17032 this._updateDomImage(image, x, y, gl); 17033 } 17034 } 17035 if (this.useMipmap && !(hasDataProperty(image) && image.data === null)) gl.generateMipmap(gl.TEXTURE_2D); 17036 context.pixelStoreUnpackFlipY.setDefault(); 17037 context.pixelStoreUnpack.setDefault(); 17038 context.pixelStoreUnpackPremultiplyAlpha.setDefault(); 17039 } 17040 _uploadDomImage(image, gl) { 17041 gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, gl.UNSIGNED_BYTE, image); 17042 } 17043 _uploadRawData(image, wantPremultiply, width, height, gl) { 17044 let { data } = image; 17045 if (wantPremultiply && data) data = premultiplyAlpha(data); 17046 gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, gl.UNSIGNED_BYTE, data); 17047 } 17048 _updateDomImage(image, x, y, gl) { 17049 gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, gl.RGBA, gl.UNSIGNED_BYTE, image); 17050 } 17051 _updateRawData(image, wantPremultiply, x, y, width, height, gl) { 17052 let { data } = image; 17053 if (wantPremultiply && data) data = premultiplyAlpha(data); 17054 gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, data); 17055 } 17056 bind(magFilter, wrap, minFilter) { 17057 const { context } = this; 17058 const { gl } = context; 17059 if (this.texture !== this._ownedHandle) this.texture = this._ownedHandle; 17060 gl.bindTexture(gl.TEXTURE_2D, this.texture); 17061 if ((minFilter === gl.LINEAR_MIPMAP_NEAREST || minFilter === gl.LINEAR_MIPMAP_LINEAR) && !this.useMipmap) minFilter = gl.LINEAR; 17062 const effectiveMinFilter = minFilter || magFilter; 17063 if (magFilter !== this.magFilter) { 17064 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter); 17065 this.magFilter = magFilter; 17066 } 17067 if (effectiveMinFilter !== this.minFilter) { 17068 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, effectiveMinFilter); 17069 this.minFilter = effectiveMinFilter; 17070 } 17071 if (wrap !== this.wrap) { 17072 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap); 17073 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap); 17074 this.wrap = wrap; 17075 } 17076 } 17077 /** 17078 * Builds the mip chain after the texture was drawn into as a framebuffer attachment. 17079 * An allocation without pixels (`data: null`) gets no chain from `update`, so a render target is built once, here, after the draw. 17080 */ 17081 generateMipmap() { 17082 if (!this.useMipmap) return; 17083 const { gl } = this.context; 17084 gl.bindTexture(gl.TEXTURE_2D, this.texture); 17085 gl.generateMipmap(gl.TEXTURE_2D); 17086 } 17087 destroy() { 17088 const { gl } = this.context; 17089 gl.deleteTexture(this.texture); 17090 this.texture = null; 17091 this._ownedHandle = null; 17092 } 17093}; 17094//#endregion 17095//#region src/data/dem_data.ts 17096/** 17097* DEMData is a data structure for decoding, backfilling, and storing elevation data for processing in the hillshade shaders 17098* data can be populated either from a png raw image tile or from serialized data sent back from a worker. When data is initially 17099* loaded from a image tile, we decode the pixel values using the appropriate decoding formula, but we store the 17100* elevation data as an Int32 value. we add 65536 (2^16) to eliminate negative values and enable the use of 17101* integer overflow when creating the texture used in the hillshadePrepare step. 17102* 17103* DEMData also handles the backfilling of data from a tile's neighboring tiles. This is necessary because we use a pixel's 8 17104* surrounding pixel values to compute the slope at that pixel, and we cannot accurately calculate the slope at pixels on a 17105* tile's edge without backfilling from neighboring tiles. 17106*/ 17107var DEMData = class DEMData { 17108 static { 17109 this.byteViewCache = /* @__PURE__ */ new WeakMap(); 17110 } 17111 /** 17112 * Constructs a `DEMData` object 17113 * @param uid - the tile's unique id 17114 * @param data - RGBAImage data has uniform 2px padding on all sides: square tile edge size defines stride 17115 // and dim is calculated as stride - 4. 17116 * @param encoding - the encoding type of the data 17117 * @param redFactor - the red channel factor used to unpack the data, used for `custom` encoding only 17118 * @param greenFactor - the green channel factor used to unpack the data, used for `custom` encoding only 17119 * @param blueFactor - the blue channel factor used to unpack the data, used for `custom` encoding only 17120 * @param baseShift - the base shift used to unpack the data, used for `custom` encoding only 17121 */ 17122 constructor(uid, data, encoding, redFactor = 1, greenFactor = 1, blueFactor = 1, baseShift = 0) { 17123 this.uid = uid; 17124 if (data.height !== data.width) throw new RangeError("DEM tiles must be square"); 17125 if (encoding && ![ 17126 "mapbox", 17127 "terrarium", 17128 "custom" 17129 ].includes(encoding)) { 17130 warnOnce(`"${encoding}" is not a valid encoding type. Valid types include "mapbox", "terrarium" and "custom".`); 17131 return; 17132 } 17133 this.stride = data.height; 17134 const dim = this.dim = data.height - 4; 17135 this.data = new Uint32Array(data.data.buffer); 17136 DEMData.byteViewCache.set(this, new Uint8Array(this.data.buffer)); 17137 switch (encoding) { 17138 case "terrarium": 17139 this.redFactor = 256; 17140 this.greenFactor = 1; 17141 this.blueFactor = 1 / 256; 17142 this.baseShift = 32768; 17143 break; 17144 case "custom": 17145 this.redFactor = redFactor; 17146 this.greenFactor = greenFactor; 17147 this.blueFactor = blueFactor; 17148 this.baseShift = baseShift; 17149 break; 17150 default: 17151 this.redFactor = 6553.6; 17152 this.greenFactor = 25.6; 17153 this.blueFactor = .1; 17154 this.baseShift = 1e4; 17155 } 17156 for (let y = -2; y < dim + 2; y++) { 17157 const offset = this._idx(0, Math.max(0, Math.min(dim - 1, y))); 17158 if (y < 0 || y >= dim) this.data.copyWithin(this._idx(0, y), offset, offset + dim); 17159 this.data.fill(this.data[offset], this._idx(-2, y), this._idx(0, y)); 17160 this.data.fill(this.data[offset + dim - 1], this._idx(dim, y), this._idx(dim + 1, y) + 1); 17161 } 17162 const pixels = this._getByteView(); 17163 this.min = Number.MAX_SAFE_INTEGER; 17164 this.max = Number.MIN_SAFE_INTEGER; 17165 for (let x = 0; x < dim; x++) for (let y = 0; y < dim; y++) { 17166 const index = this._idx(x, y) * 4; 17167 const ele = this._unpackAtIndex(pixels, index); 17168 if (ele > this.max) this.max = ele; 17169 if (ele < this.min) this.min = ele; 17170 } 17171 } 17172 get(x, y) { 17173 const pixels = this._getByteView(); 17174 const index = this._idx(x, y) * 4; 17175 return this._unpackAtIndex(pixels, index); 17176 } 17177 sampleBilinear(x, y) { 17178 const cx = Math.floor(x); 17179 const cy = Math.floor(y); 17180 if (cx < -1 || cx >= this.dim || cy < -1 || cy >= this.dim) throw new RangeError(`Out of range source coordinates for DEM data. x: ${x}, y: ${y}, dim: ${this.dim}`); 17181 const pixels = this._getByteView(); 17182 const index = ((cy + 2) * this.stride + cx + 2) * 4; 17183 const strideByteWidth = this.stride * 4; 17184 const tx = x - cx; 17185 const ty = y - cy; 17186 const z00 = this._unpackAtIndex(pixels, index); 17187 const z10 = this._unpackAtIndex(pixels, index + 4); 17188 const z01 = this._unpackAtIndex(pixels, index + strideByteWidth); 17189 const z11 = this._unpackAtIndex(pixels, index + strideByteWidth + 4); 17190 return z00 * (1 - tx) * (1 - ty) + z10 * tx * (1 - ty) + z01 * (1 - tx) * ty + z11 * tx * ty; 17191 } 17192 getUnpackVector() { 17193 return [ 17194 this.redFactor, 17195 this.greenFactor, 17196 this.blueFactor, 17197 this.baseShift 17198 ]; 17199 } 17200 _idx(x, y) { 17201 if (x < -2 || x >= this.dim + 2 || y < -2 || y >= this.dim + 2) throw new RangeError(`Out of range source coordinates for DEM data. x: ${x}, y: ${y}, dim: ${this.dim}`); 17202 return (y + 2) * this.stride + (x + 2); 17203 } 17204 unpack(r, g, b) { 17205 return r * this.redFactor + g * this.greenFactor + b * this.blueFactor - this.baseShift; 17206 } 17207 pack(v) { 17208 return packDEMData(v, this.getUnpackVector()); 17209 } 17210 getPixels() { 17211 return new RGBAImage({ 17212 width: this.stride, 17213 height: this.stride 17214 }, this._getByteView()); 17215 } 17216 backfillBorder(borderTile, dx, dy) { 17217 if (this.dim !== borderTile.dim) throw new Error("dem dimension mismatch"); 17218 let xMin = dx * this.dim, xMax = dx * this.dim + this.dim, yMin = dy * this.dim, yMax = dy * this.dim + this.dim; 17219 switch (dx) { 17220 case -1: 17221 xMin = xMax - 2; 17222 break; 17223 case 1: xMax = xMin + 2; 17224 } 17225 switch (dy) { 17226 case -1: 17227 yMin = yMax - 2; 17228 break; 17229 case 1: yMax = yMin + 2; 17230 } 17231 const ox = -dx * this.dim; 17232 const oy = -dy * this.dim; 17233 for (let y = yMin; y < yMax; y++) for (let x = xMin; x < xMax; x++) this.data[this._idx(x, y)] = borderTile.data[this._idx(x + ox, y + oy)]; 17234 } 17235 _getByteView() { 17236 let byteView = DEMData.byteViewCache.get(this); 17237 if (byteView?.buffer !== this.data.buffer) { 17238 byteView = new Uint8Array(this.data.buffer); 17239 DEMData.byteViewCache.set(this, byteView); 17240 } 17241 return byteView; 17242 } 17243 _unpackAtIndex(pixels, index) { 17244 return this.unpack(pixels[index], pixels[index + 1], pixels[index + 2]); 17245 } 17246}; 17247function packDEMData(v, unpackVector) { 17248 const redFactor = unpackVector[0]; 17249 const greenFactor = unpackVector[1]; 17250 const blueFactor = unpackVector[2]; 17251 const baseShift = unpackVector[3]; 17252 const minScale = Math.min(redFactor, greenFactor, blueFactor); 17253 const vScaled = Math.round((v + baseShift) / minScale); 17254 return { 17255 r: Math.floor(vScaled * minScale / redFactor) % 256, 17256 g: Math.floor(vScaled * minScale / greenFactor) % 256, 17257 b: Math.floor(vScaled * minScale / blueFactor) % 256 17258 }; 17259} 17260register("DEMData", DEMData); 17261//#endregion 17262//#region src/style/style_layer/color_relief_style_layer.ts 17263const isColorReliefStyleLayer = (layer) => layer.type === "color-relief"; 17264var ColorReliefStyleLayer = class extends StyleLayer { 17265 constructor(layer, globalState) { 17266 super(layer, color_relief_style_layer_properties_g_default, globalState); 17267 } 17268 /** 17269 * Create the color ramp, enforcing a maximum length for the vectors. This modifies the internal color ramp, 17270 * so that the remapping is only performed once. 17271 * 17272 * @param maxLength - the maximum number of stops in the color ramp 17273 * 17274 * @return a `ColorRamp` object with no more than `maxLength` stops. 17275 * 17276 */ 17277 _createColorRamp(maxLength) { 17278 const colorRamp = { 17279 elevationStops: [], 17280 colorStops: [] 17281 }; 17282 const expression = this._transitionablePaint._values["color-relief-color"].value.expression; 17283 if (expression instanceof ZoomConstantExpression && expression._styleExpression.expression instanceof Interpolate) { 17284 this.colorRampExpression = expression; 17285 const interpolater = expression._styleExpression.expression; 17286 colorRamp.elevationStops = interpolater.labels; 17287 colorRamp.colorStops = []; 17288 for (const label of colorRamp.elevationStops) colorRamp.colorStops.push(interpolater.evaluate({ globals: { elevation: label } })); 17289 } 17290 if (colorRamp.elevationStops.length < 1) { 17291 colorRamp.elevationStops = [0]; 17292 colorRamp.colorStops = [Color.transparent]; 17293 } 17294 if (colorRamp.elevationStops.length < 2) { 17295 colorRamp.elevationStops.push(colorRamp.elevationStops[0] + 1); 17296 colorRamp.colorStops.push(colorRamp.colorStops[0]); 17297 } 17298 if (colorRamp.elevationStops.length <= maxLength) return colorRamp; 17299 const remappedColorRamp = { 17300 elevationStops: [], 17301 colorStops: [] 17302 }; 17303 const remapStepSize = (colorRamp.elevationStops.length - 1) / (maxLength - 1); 17304 for (let i = 0; i < colorRamp.elevationStops.length - .5; i += remapStepSize) { 17305 remappedColorRamp.elevationStops.push(colorRamp.elevationStops[Math.round(i)]); 17306 remappedColorRamp.colorStops.push(colorRamp.colorStops[Math.round(i)]); 17307 } 17308 warnOnce(`Too many colors in specification of ${this.id} color-relief layer, may not render properly. Max possible colors: ${maxLength}, provided: ${colorRamp.elevationStops.length}`); 17309 return remappedColorRamp; 17310 } 17311 _colorRampChanged() { 17312 return this.colorRampExpression != this._transitionablePaint._values["color-relief-color"].value.expression; 17313 } 17314 getColorRampTextures(context, maxLength, unpackVector) { 17315 if (this.colorRampTextures && !this._colorRampChanged()) return this.colorRampTextures; 17316 const colorRamp = this._createColorRamp(maxLength); 17317 const colorImage = new RGBAImage({ 17318 width: colorRamp.colorStops.length, 17319 height: 1 17320 }); 17321 const elevationImage = new RGBAImage({ 17322 width: colorRamp.colorStops.length, 17323 height: 1 17324 }); 17325 for (let i = 0; i < colorRamp.elevationStops.length; i++) { 17326 const elevationPacked = packDEMData(colorRamp.elevationStops[i], unpackVector); 17327 elevationImage.setPixel(0, i, new Color(elevationPacked.r / 255, elevationPacked.g / 255, elevationPacked.b / 255, 1)); 17328 colorImage.setPixel(0, i, colorRamp.colorStops[i]); 17329 } 17330 this.colorRampTextures = { 17331 elevationTexture: new Texture(context, elevationImage, context.gl.RGBA), 17332 colorTexture: new Texture(context, colorImage, context.gl.RGBA) 17333 }; 17334 return this.colorRampTextures; 17335 } 17336 hasOffscreenPass() { 17337 return !this.isHidden() && !!this.colorRampTextures; 17338 } 17339}; 17340//#endregion 17341//#region src/data/bucket/fill_attributes.ts 17342const layout$5 = createLayout([{ 17343 name: "a_pos", 17344 components: 2, 17345 type: "Int16" 17346}], 4); 17347const members$3 = layout$5.members; 17348layout$5.size; 17349layout$5.alignment; 17350//#endregion 17351//#region src/data/bucket/pattern_bucket_features.ts 17352function hasPattern(type, layers, options) { 17353 const patterns = options.patternDependencies; 17354 let hasPattern = false; 17355 for (const layer of layers) { 17356 const patternProperty = layer.paint.get(`${type}-pattern`); 17357 if (!patternProperty.isConstant()) hasPattern = true; 17358 const constantPattern = patternProperty.constantOr(null); 17359 if (constantPattern) { 17360 hasPattern = true; 17361 patterns[constantPattern.to] = true; 17362 patterns[constantPattern.from] = true; 17363 } 17364 } 17365 return hasPattern; 17366} 17367function addPatternDependencies(type, layers, patternFeature, parameters, options) { 17368 const { zoom } = parameters; 17369 const patterns = options.patternDependencies; 17370 for (const layer of layers) { 17371 const patternPropertyValue = layer.paint.get(`${type}-pattern`).value; 17372 if (patternPropertyValue.kind !== "constant") { 17373 let min = patternPropertyValue.evaluate({ zoom: zoom - 1 }, patternFeature, {}, options.availableImages); 17374 let mid = patternPropertyValue.evaluate({ zoom }, patternFeature, {}, options.availableImages); 17375 let max = patternPropertyValue.evaluate({ zoom: zoom + 1 }, patternFeature, {}, options.availableImages); 17376 min = min?.name ? min.name : min; 17377 mid = mid?.name ? mid.name : mid; 17378 max = max?.name ? max.name : max; 17379 patterns[min] = true; 17380 patterns[mid] = true; 17381 patterns[max] = true; 17382 patternFeature.patterns[layer.id] = { 17383 min, 17384 mid, 17385 max 17386 }; 17387 } 17388 } 17389 return patternFeature; 17390} 17391//#endregion 17392//#region node_modules/earcut/src/earcut.js 17393/** 17394* A vertex in a circular doubly linked list representing a polygon ring. 17395* `prev`/`next` are always linked (set immediately after {@link createNode}), so they're typed 17396* non-null; `prevZ`/`nextZ` are the z-order list links and are null at the ends. 17397* 17398* @typedef {object} Node 17399* @property {number} i vertex index in the coordinates array 17400* @property {number} x vertex x coordinate 17401* @property {number} y vertex y coordinate 17402* @property {Node} prev previous vertex node in the polygon ring 17403* @property {Node} next next vertex node in the polygon ring 17404* @property {number} z z-order curve value; doubles as the owning block index during eliminateHoles 17405* @property {Node | null} prevZ previous node in z-order 17406* @property {Node | null} nextZ next node in z-order 17407*/ 17408/** @type {Set<Node>} */ 17409const steiners = /* @__PURE__ */ new Set(); 17410let filteredOut = false; 17411/** 17412* Triangulate a polygon given as a flat array of vertex coordinates. 17413* 17414* @param {ArrayLike<number>} data flat array of vertex coordinates 17415* @param {ArrayLike<number> | null} [holeIndices] indices (in vertices, not coordinates) where each hole ring starts 17416* @param {number} [dim=2] number of coordinates per vertex in `data` 17417* @returns {number[]} triangles as triplets of vertex indices into `data` 17418* @example earcut([10,0, 0,50, 60,60, 70,10]); // [1,0,3, 3,2,1] 17419*/ 17420function earcut(data, holeIndices, dim = 2) { 17421 const hasHoles = holeIndices && holeIndices.length; 17422 const outerLen = hasHoles ? holeIndices[0] * dim : data.length; 17423 if (steiners.size) steiners.clear(); 17424 let outerNode = linkedList(data, 0, outerLen, dim, true); 17425 /** @type {number[]} */ 17426 const triangles = []; 17427 if (!outerNode || outerNode.next === outerNode.prev) return triangles; 17428 let minX = 0, minY = 0, invSize = 0; 17429 if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); 17430 if (data.length > 80 * dim) { 17431 minX = data[0]; 17432 minY = data[1]; 17433 let maxX = minX; 17434 let maxY = minY; 17435 for (let i = dim; i < outerLen; i += dim) { 17436 const x = data[i]; 17437 const y = data[i + 1]; 17438 if (x < minX) minX = x; 17439 if (y < minY) minY = y; 17440 if (x > maxX) maxX = x; 17441 if (y > maxY) maxY = y; 17442 } 17443 invSize = Math.max(maxX - minX, maxY - minY); 17444 invSize = invSize !== 0 ? 32767 / invSize : 0; 17445 } 17446 earcutLinked(outerNode, triangles, minX, minY, invSize); 17447 return triangles; 17448} 17449/** @param {ArrayLike<number>} data @param {number} start @param {number} end @param {number} dim @param {boolean} clockwise @returns {Node | null} */ 17450function linkedList(data, start, end, dim, clockwise) { 17451 /** @type {Node | null} */ 17452 let last = null; 17453 if (clockwise === signedArea$1(data, start, end, dim) > 0) for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last); 17454 else for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last); 17455 if (last && equals(last, last.next)) { 17456 removeNode(last); 17457 last = last.next; 17458 } 17459 return last; 17460} 17461/** @param {Node} start @param {Node} [end] @returns {Node} */ 17462function filterPoints(start, end = start) { 17463 const full = end === start; 17464 let p = start, again; 17465 do { 17466 again = false; 17467 if (p !== p.next && (steiners.size === 0 || !steiners.has(p)) && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { 17468 if (full || p === end) end = p.prev; 17469 filteredOut = true; 17470 removeNode(p); 17471 p = p.prev; 17472 again = true; 17473 } else if (full || p !== end) { 17474 p = p.next; 17475 again = !full; 17476 } 17477 } while (again || p !== end); 17478 return end; 17479} 17480/** @param {Node} ear @param {number[]} triangles @param {number} minX @param {number} minY @param {number} invSize */ 17481function earcutLinked(ear, triangles, minX, minY, invSize) { 17482 if (invSize) indexCurve(ear, minX, minY, invSize); 17483 let stop = ear, cured = false; 17484 while (ear.prev !== ear.next) { 17485 const prev = ear.prev; 17486 /** @type {Node} */ 17487 const next = ear.next; 17488 if (area(prev, ear, next) < 0 && (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear))) { 17489 triangles.push(prev.i, ear.i, next.i); 17490 removeNode(ear); 17491 ear = next; 17492 stop = next; 17493 continue; 17494 } 17495 ear = next; 17496 if (ear === stop) { 17497 filteredOut = false; 17498 ear = filterPoints(ear); 17499 if (filteredOut) { 17500 stop = ear; 17501 continue; 17502 } 17503 if (!cured) { 17504 ear = cureLocalIntersections(ear, triangles); 17505 stop = ear; 17506 cured = true; 17507 continue; 17508 } 17509 splitEarcut(ear, triangles, minX, minY, invSize); 17510 break; 17511 } 17512 } 17513} 17514/** @param {Node} ear @returns {boolean} */ 17515function isEar(ear) { 17516 const a = ear.prev, b = ear, c = ear.next, ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y, x0 = Math.min(ax, bx, cx), y0 = Math.min(ay, by, cy), x1 = Math.max(ax, bx, cx), y1 = Math.max(ay, by, cy); 17517 let p = c.next; 17518 while (p !== a) { 17519 if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && !(ax === p.x && ay === p.y) && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; 17520 p = p.next; 17521 } 17522 return true; 17523} 17524/** @param {Node} ear @param {number} minX @param {number} minY @param {number} invSize @returns {boolean} */ 17525function isEarHashed(ear, minX, minY, invSize) { 17526 const a = ear.prev, b = ear, c = ear.next, ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y, x0 = Math.min(ax, bx, cx), y0 = Math.min(ay, by, cy), x1 = Math.max(ax, bx, cx), y1 = Math.max(ay, by, cy), minZ = zOrder(x0, y0, minX, minY, invSize), maxZ = zOrder(x1, y1, minX, minY, invSize); 17527 let p = ear.prevZ; 17528 while (p && p.z >= minZ) { 17529 if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== c && !(ax === p.x && ay === p.y) && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; 17530 p = p.prevZ; 17531 } 17532 let n = ear.nextZ; 17533 while (n && n.z <= maxZ) { 17534 if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== c && !(ax === n.x && ay === n.y) && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; 17535 n = n.nextZ; 17536 } 17537 return true; 17538} 17539/** @param {Node} start @param {number[]} triangles @returns {Node} */ 17540function cureLocalIntersections(start, triangles) { 17541 let p = start; 17542 let cured = false; 17543 do { 17544 const a = p.prev, b = p.next.next; 17545 if (intersects(a, p, p.next, b, false) && locallyInside(a, b) && locallyInside(b, a)) { 17546 triangles.push(a.i, p.i, b.i); 17547 removeNode(p); 17548 removeNode(p.next); 17549 p = start = b; 17550 cured = true; 17551 } 17552 p = p.next; 17553 } while (p !== start); 17554 return cured ? filterPoints(p) : p; 17555} 17556/** @param {Node} start @param {number[]} triangles @param {number} minX @param {number} minY @param {number} invSize */ 17557function splitEarcut(start, triangles, minX, minY, invSize) { 17558 let a = start; 17559 do { 17560 let b = a.next.next; 17561 while (b !== a.prev) { 17562 if (a.i !== b.i && isValidDiagonal(a, b)) { 17563 let c = splitPolygon(a, b); 17564 a = filterPoints(a, a.next); 17565 c = filterPoints(c, c.next); 17566 earcutLinked(a, triangles, minX, minY, invSize); 17567 earcutLinked(c, triangles, minX, minY, invSize); 17568 return; 17569 } 17570 b = b.next; 17571 } 17572 a = a.next; 17573 } while (a !== start); 17574} 17575let indexActive = false; 17576/** @param {ArrayLike<number>} data @param {ArrayLike<number>} holeIndices @param {Node} outerNode @param {number} dim @returns {Node} */ 17577function eliminateHoles(data, holeIndices, outerNode, dim) { 17578 const queue = []; 17579 for (let i = 0, len = holeIndices.length; i < len; i++) { 17580 const list = linkedList(data, holeIndices[i] * dim, i < len - 1 ? holeIndices[i + 1] * dim : data.length, dim, false); 17581 if (list === list.next) steiners.add(list); 17582 queue.push(getLeftmost(list)); 17583 } 17584 queue.sort(compareXYSlope); 17585 buildBlockIndex(data.length / dim, holeIndices.length); 17586 indexSegment(outerNode, outerNode); 17587 indexActive = true; 17588 for (let i = 0; i < queue.length; i++) outerNode = eliminateHole(queue[i], outerNode); 17589 indexActive = false; 17590 return filterPoints(outerNode); 17591} 17592/** @param {Node} a @param {Node} b @returns {number} */ 17593function compareXYSlope(a, b) { 17594 return a.x - b.x || a.y - b.y || (a.next.y - a.y) / (a.next.x - a.x) - (b.next.y - b.y) / (b.next.x - b.x); 17595} 17596/** @param {Node} hole @param {Node} outerNode @returns {Node} */ 17597function eliminateHole(hole, outerNode) { 17598 const bridge = findHoleBridge(hole, outerNode); 17599 if (!bridge) return outerNode; 17600 const bridgeReverse = splitPolygon(bridge, hole); 17601 const bridge2 = bridgeReverse.next; 17602 indexSegment(bridge, bridge2.next); 17603 filterPoints(bridgeReverse, bridgeReverse.next); 17604 return filterPoints(bridge, bridge.next); 17605} 17606const K = 16; 17607let blockBBox = /* @__PURE__ */ new Float64Array(0); 17608let numBlocks = 0; 17609/** @type {Node[]} */ 17610const blockHead = []; 17611/** @type {Node[]} */ 17612const blockStop = []; 17613/** @param {number} maxNodes @param {number} numHoles */ 17614function buildBlockIndex(maxNodes, numHoles) { 17615 const maxBlocks = Math.ceil((maxNodes + 2 * numHoles) / K) + numHoles + 2; 17616 if (blockBBox.length < maxBlocks * 4) blockBBox = new Float64Array(maxBlocks * 4); 17617 numBlocks = 0; 17618} 17619/** @param {Node} head @param {Node} stop */ 17620function indexSegment(head, stop) { 17621 let p = head; 17622 do { 17623 const b = numBlocks++; 17624 blockHead[b] = p; 17625 let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; 17626 let k = 0; 17627 do { 17628 const c = p.next; 17629 p.z = b; 17630 if (p.x < minX) minX = p.x; 17631 if (p.x > maxX) maxX = p.x; 17632 if (p.y < minY) minY = p.y; 17633 if (p.y > maxY) maxY = p.y; 17634 if (c.x < minX) minX = c.x; 17635 if (c.x > maxX) maxX = c.x; 17636 if (c.y < minY) minY = c.y; 17637 if (c.y > maxY) maxY = c.y; 17638 p = c; 17639 } while (++k < K && p !== stop); 17640 blockStop[b] = p; 17641 const g = b * 4; 17642 blockBBox[g] = minX; 17643 blockBBox[g + 1] = minY; 17644 blockBBox[g + 2] = maxX; 17645 blockBBox[g + 3] = maxY; 17646 } while (p !== stop); 17647} 17648/** @param {Node} head @param {Node} tail */ 17649function growBlock(head, tail) { 17650 const g = head.z * 4; 17651 if (tail.x < blockBBox[g]) blockBBox[g] = tail.x; 17652 if (tail.y < blockBBox[g + 1]) blockBBox[g + 1] = tail.y; 17653 if (tail.x > blockBBox[g + 2]) blockBBox[g + 2] = tail.x; 17654 if (tail.y > blockBBox[g + 3]) blockBBox[g + 3] = tail.y; 17655} 17656/** @param {number} b @returns {Node} */ 17657function liveBlockStop(b) { 17658 let stop = blockStop[b]; 17659 while (stop.prev.next !== stop) stop = stop.next; 17660 blockStop[b] = stop; 17661 return stop; 17662} 17663/** @param {number} b @returns {Node} */ 17664function liveBlockHead(b) { 17665 let head = blockHead[b]; 17666 while (head.prev.next !== head) head = head.next; 17667 blockHead[b] = head; 17668 return head; 17669} 17670/** @param {Node} hole @param {Node} outerNode @returns {Node | null} */ 17671function findHoleBridge(hole, outerNode) { 17672 let p = outerNode; 17673 const hx = hole.x; 17674 const hy = hole.y; 17675 let qx = -Infinity; 17676 /** @type {Node | undefined} */ 17677 let m; 17678 if (equals(hole, p)) return p; 17679 for (let b = 0, g = 0; b < numBlocks; b++, g += 4) { 17680 if (hy < blockBBox[g + 1] || hy > blockBBox[g + 3] || blockBBox[g] > hx || blockBBox[g + 2] <= qx) continue; 17681 const stop = liveBlockStop(b); 17682 p = liveBlockHead(b); 17683 do { 17684 if (p.prev.next === p) { 17685 if (equals(hole, p.next)) return p.next; 17686 else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { 17687 const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); 17688 if (x <= hx && x > qx) { 17689 qx = x; 17690 m = p.x < p.next.x ? p : p.next; 17691 if (x === hx) return m; 17692 } 17693 } 17694 } 17695 p = p.next; 17696 } while (p !== stop); 17697 } 17698 if (!m) return null; 17699 const mx = m.x; 17700 const my = m.y; 17701 const tminY = Math.min(hy, my); 17702 const tmaxY = Math.max(hy, my); 17703 let tanMin = Infinity; 17704 for (let b = 0, g = 0; b < numBlocks; b++, g += 4) { 17705 if (blockBBox[g + 2] < mx || blockBBox[g] > hx || blockBBox[g + 3] < tminY || blockBBox[g + 1] > tmaxY) continue; 17706 const stop = liveBlockStop(b); 17707 p = liveBlockHead(b); 17708 do { 17709 if (p.prev.next === p && hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { 17710 const tan = Math.abs(hy - p.y) / (hx - p.x); 17711 if ((locallyInside(p, hole) || p.y === hy && p.next.y === hy && p.next.x > hx) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) { 17712 m = p; 17713 tanMin = tan; 17714 } 17715 } 17716 p = p.next; 17717 } while (p !== stop); 17718 } 17719 return m; 17720} 17721/** @param {Node} m @param {Node} p @returns {boolean} */ 17722function sectorContainsSector(m, p) { 17723 return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; 17724} 17725/** @type {Node[]} */ 17726const sortArr = []; 17727/** @type {Node[]} */ 17728let sortBuf = []; 17729let zArr = /* @__PURE__ */ new Uint32Array(0); 17730let zBuf = /* @__PURE__ */ new Uint32Array(0); 17731const counts = /* @__PURE__ */ new Uint32Array(256); 17732/** @param {Node} start @param {number} minX @param {number} minY @param {number} invSize */ 17733function indexCurve(start, minX, minY, invSize) { 17734 let p = start; 17735 let n = 0; 17736 do { 17737 p.z = zOrder(p.x, p.y, minX, minY, invSize); 17738 sortArr[n++] = p; 17739 p = p.next; 17740 } while (p !== start); 17741 sortNodes(n); 17742 /** @type {Node | null} */ 17743 let prev = null; 17744 for (let i = 0; i < n; i++) { 17745 const node = sortArr[i]; 17746 node.prevZ = prev; 17747 if (prev) prev.nextZ = node; 17748 prev = node; 17749 } 17750 /** @type {Node} */ prev.nextZ = null; 17751} 17752/** @param {number} n */ 17753function sortNodes(n) { 17754 if (n <= 32) { 17755 for (let i = 1; i < n; i++) { 17756 const node = sortArr[i], z = node.z; 17757 let j = i - 1; 17758 while (j >= 0 && sortArr[j].z > z) { 17759 sortArr[j + 1] = sortArr[j]; 17760 j--; 17761 } 17762 sortArr[j + 1] = node; 17763 } 17764 return; 17765 } 17766 if (zArr.length < n) { 17767 zArr = new Uint32Array(n); 17768 zBuf = new Uint32Array(n); 17769 sortBuf = new Array(n); 17770 } 17771 for (let i = 0; i < n; i++) zArr[i] = sortArr[i].z; 17772 radixPass(n, sortArr, zArr, sortBuf, zBuf, 0); 17773 radixPass(n, sortBuf, zBuf, sortArr, zArr, 8); 17774 radixPass(n, sortArr, zArr, sortBuf, zBuf, 16); 17775 radixPass(n, sortBuf, zBuf, sortArr, zArr, 24); 17776} 17777/** @param {number} n @param {Node[]} src @param {Uint32Array} srcZ @param {Node[]} dst @param {Uint32Array} dstZ @param {number} shift */ 17778function radixPass(n, src, srcZ, dst, dstZ, shift) { 17779 counts.fill(0); 17780 for (let i = 0; i < n; i++) counts[srcZ[i] >>> shift & 255]++; 17781 let sum = 0; 17782 for (let b = 0; b < 256; b++) { 17783 const c = counts[b]; 17784 counts[b] = sum; 17785 sum += c; 17786 } 17787 for (let i = 0; i < n; i++) { 17788 const z = srcZ[i]; 17789 const pos = counts[z >>> shift & 255]++; 17790 dst[pos] = src[i]; 17791 dstZ[pos] = z; 17792 } 17793} 17794/** @param {number} x @param {number} y @param {number} minX @param {number} minY @param {number} invSize @returns {number} */ 17795function zOrder(x, y, minX, minY, invSize) { 17796 x = (x - minX) * invSize | 0; 17797 y = (y - minY) * invSize | 0; 17798 x = (x | x << 8) & 16711935; 17799 x = (x | x << 4) & 252645135; 17800 x = (x | x << 2) & 858993459; 17801 x = (x | x << 1) & 1431655765; 17802 y = (y | y << 8) & 16711935; 17803 y = (y | y << 4) & 252645135; 17804 y = (y | y << 2) & 858993459; 17805 y = (y | y << 1) & 1431655765; 17806 return x | y << 1; 17807} 17808/** @param {Node} start @returns {Node} */ 17809function getLeftmost(start) { 17810 let p = start, leftmost = start; 17811 do { 17812 if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p; 17813 p = p.next; 17814 } while (p !== start); 17815 return leftmost; 17816} 17817/** @param {number} ax @param {number} ay @param {number} bx @param {number} by @param {number} cx @param {number} cy @param {number} px @param {number} py @returns {boolean} */ 17818function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { 17819 return (cx - px) * (ay - py) >= (ax - px) * (cy - py) && (ax - px) * (by - py) >= (bx - px) * (ay - py) && (bx - px) * (cy - py) >= (cx - px) * (by - py); 17820} 17821/** @param {Node} a @param {Node} b @returns {boolean} true when the diagonal is valid */ 17822function isValidDiagonal(a, b) { 17823 const zeroLength = equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0; 17824 return a.next.i !== b.i && (zeroLength || locallyInside(a, b) && locallyInside(b, a) && (area(a.prev, a, b.prev) !== 0 || area(a, b.prev, b) !== 0)) && !intersectsPolygon(a, b) && (zeroLength || middleInside(a, b)); 17825} 17826/** @param {Node} p @param {Node} q @param {Node} r @returns {number} */ 17827function area(p, q, r) { 17828 return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); 17829} 17830/** @param {Node} p1 @param {Node} p2 @returns {boolean} */ 17831function equals(p1, p2) { 17832 return p1.x === p2.x && p1.y === p2.y; 17833} 17834/** @param {Node} p1 @param {Node} q1 @param {Node} p2 @param {Node} q2 @param {boolean} [includeBoundary] @returns {boolean} */ 17835function intersects(p1, q1, p2, q2, includeBoundary = true) { 17836 const o1 = area(p1, q1, p2); 17837 const o2 = area(p1, q1, q2); 17838 const o3 = area(p2, q2, p1); 17839 const o4 = area(p2, q2, q1); 17840 if ((o1 > 0 && o2 < 0 || o1 < 0 && o2 > 0) && (o3 > 0 && o4 < 0 || o3 < 0 && o4 > 0)) return true; 17841 if (!includeBoundary) return false; 17842 if (o1 === 0 && onSegment(p1, p2, q1)) return true; 17843 if (o2 === 0 && onSegment(p1, q2, q1)) return true; 17844 if (o3 === 0 && onSegment(p2, p1, q2)) return true; 17845 if (o4 === 0 && onSegment(p2, q1, q2)) return true; 17846 return false; 17847} 17848/** @param {Node} p @param {Node} q @param {Node} r @returns {boolean} */ 17849function onSegment(p, q, r) { 17850 return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y); 17851} 17852/** @param {Node} a @param {Node} b @returns {boolean} */ 17853function intersectsPolygon(a, b) { 17854 const minX = Math.min(a.x, b.x); 17855 const maxX = Math.max(a.x, b.x); 17856 const minY = Math.min(a.y, b.y); 17857 const maxY = Math.max(a.y, b.y); 17858 let p = a; 17859 do { 17860 const n = p.next; 17861 if (p.x > maxX && n.x > maxX || p.x < minX && n.x < minX || p.y > maxY && n.y > maxY || p.y < minY && n.y < minY) { 17862 p = n; 17863 continue; 17864 } 17865 if (p.i !== a.i && n.i !== a.i && p.i !== b.i && n.i !== b.i && intersects(p, n, a, b)) return true; 17866 p = n; 17867 } while (p !== a); 17868 return false; 17869} 17870/** @param {Node} a @param {Node} b @returns {boolean} */ 17871function locallyInside(a, b) { 17872 return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; 17873} 17874/** @param {Node} a @param {Node} b @returns {boolean} */ 17875function middleInside(a, b) { 17876 let p = a; 17877 let inside = false; 17878 const px = (a.x + b.x) / 2; 17879 const py = (a.y + b.y) / 2; 17880 do { 17881 const n = p.next; 17882 if (p.y > py !== n.y > py && px < (n.x - p.x) * (py - p.y) / (n.y - p.y) + p.x) inside = !inside; 17883 p = n; 17884 } while (p !== a); 17885 return inside; 17886} 17887/** @param {Node} a @param {Node} b @returns {Node} */ 17888function splitPolygon(a, b) { 17889 const a2 = createNode(a.i, a.x, a.y), b2 = createNode(b.i, b.x, b.y), an = a.next, bp = b.prev; 17890 a.next = b; 17891 b.prev = a; 17892 a2.next = an; 17893 an.prev = a2; 17894 b2.next = a2; 17895 a2.prev = b2; 17896 bp.next = b2; 17897 b2.prev = bp; 17898 return b2; 17899} 17900/** @param {number} i @param {number} x @param {number} y @param {Node | null} last @returns {Node} */ 17901function insertNode(i, x, y, last) { 17902 const p = createNode(i, x, y); 17903 if (!last) { 17904 p.prev = p; 17905 p.next = p; 17906 } else { 17907 p.next = last.next; 17908 p.prev = last; 17909 last.next.prev = p; 17910 last.next = p; 17911 } 17912 return p; 17913} 17914/** @param {Node} p */ 17915function removeNode(p) { 17916 p.next.prev = p.prev; 17917 p.prev.next = p.next; 17918 if (p.prevZ) p.prevZ.nextZ = p.nextZ; 17919 if (p.nextZ) p.nextZ.prevZ = p.prevZ; 17920 if (indexActive) growBlock(p.prev, p.next); 17921} 17922/** @param {number} i @param {number} x @param {number} y @returns {Node} */ 17923function createNode(i, x, y) { 17924 return { 17925 i, 17926 x, 17927 y, 17928 prev: null, 17929 next: null, 17930 z: 0, 17931 prevZ: null, 17932 nextZ: null 17933 }; 17934} 17935/** @param {ArrayLike<number>} data @param {number} start @param {number} end @param {number} dim @returns {number} */ 17936function signedArea$1(data, start, end, dim) { 17937 let sum = 0; 17938 for (let i = start, j = end - dim; i < end; i += dim) { 17939 sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); 17940 j = i; 17941 } 17942 return sum; 17943} 17944//#endregion 17945//#region src/render/subdivision_granularity_settings.ts 17946/** 17947* Controls how much subdivision happens for a given type of geometry at different zoom levels. 17948*/ 17949var SubdivisionGranularityExpression = class { 17950 constructor(baseZoomGranularity, minGranularity) { 17951 if (minGranularity > baseZoomGranularity) throw new Error("Min granularity must not be greater than base granularity."); 17952 this._baseZoomGranularity = baseZoomGranularity; 17953 this._minGranularity = minGranularity; 17954 } 17955 getGranularityForZoomLevel(zoomLevel) { 17956 const divisor = 1 << zoomLevel; 17957 return Math.max(Math.floor(this._baseZoomGranularity / divisor), this._minGranularity, 1); 17958 } 17959}; 17960/** 17961* An object describing how much subdivision should be applied to different types of geometry at different zoom levels. 17962*/ 17963var SubdivisionGranularitySetting = class SubdivisionGranularitySetting { 17964 constructor(options) { 17965 this.fill = options.fill; 17966 this.line = options.line; 17967 this.tile = options.tile; 17968 this.stencil = options.stencil; 17969 this.circle = options.circle; 17970 } 17971 static { 17972 this.noSubdivision = new SubdivisionGranularitySetting({ 17973 fill: new SubdivisionGranularityExpression(0, 0), 17974 line: new SubdivisionGranularityExpression(0, 0), 17975 tile: new SubdivisionGranularityExpression(0, 0), 17976 stencil: new SubdivisionGranularityExpression(0, 0), 17977 circle: 1 17978 }); 17979 } 17980}; 17981//#endregion 17982//#region src/render/subdivision.ts 17983register("SubdivisionGranularityExpression", SubdivisionGranularityExpression); 17984register("SubdivisionGranularitySetting", SubdivisionGranularitySetting); 17985const NORTH_POLE_Y = -32768; 17986const SOUTH_POLE_Y = 32767; 17987var Subdivider = class { 17988 constructor(granularity, canonical) { 17989 this._vertexBuffer = []; 17990 this._vertexDictionary = /* @__PURE__ */ new Map(); 17991 this._used = false; 17992 this._granularity = granularity; 17993 this._granularityCellSize = EXTENT$1 / granularity; 17994 this._canonical = canonical; 17995 } 17996 _getKey(x, y) { 17997 x = x + 32768; 17998 y = y + 32768; 17999 return x << 16 | y << 0; 18000 } 18001 /** 18002 * Returns an index into the internal vertex buffer for a vertex at the given coordinates. 18003 * If the internal vertex buffer contains no such vertex, then it is added. 18004 */ 18005 _vertexToIndex(x, y) { 18006 if (x < -32768 || y < -32768 || x > 32767 || y > 32767) throw new Error("Vertex coordinates are out of signed 16 bit integer range."); 18007 const xInt = Math.round(x) | 0; 18008 const yInt = Math.round(y) | 0; 18009 const key = this._getKey(xInt, yInt); 18010 const existing = this._vertexDictionary.get(key); 18011 if (existing !== void 0) return existing; 18012 const index = this._vertexBuffer.length / 2; 18013 this._vertexDictionary.set(key, index); 18014 this._vertexBuffer.push(xInt, yInt); 18015 return index; 18016 } 18017 /** 18018 * Subdivides a polygon by iterating over rows of granularity subdivision cells and splitting each row along vertical subdivision axes. 18019 * @param inputIndices - Indices into the flattened input vertices of the triangulated polygon (the output of `earcut`). 18020 * @param inputRemap - Index into the internal vertex buffer for each flattened input vertex. 18021 * @returns Indices into the internal vertex buffer for triangles that are a subdivision of the input geometry. 18022 */ 18023 _subdivideTrianglesScanline(inputIndices, inputRemap) { 18024 if (this._granularity < 2) return fixWindingOrder(this._vertexBuffer, remapIndices(inputIndices, inputRemap)); 18025 const finalIndices = []; 18026 const numIndices = inputIndices.length; 18027 for (let primitiveIndex = 0; primitiveIndex < numIndices; primitiveIndex += 3) { 18028 const triangleIndices = [ 18029 inputRemap[inputIndices[primitiveIndex + 0]], 18030 inputRemap[inputIndices[primitiveIndex + 1]], 18031 inputRemap[inputIndices[primitiveIndex + 2]] 18032 ]; 18033 const triangleVertices = [ 18034 this._vertexBuffer[triangleIndices[0] * 2 + 0], 18035 this._vertexBuffer[triangleIndices[0] * 2 + 1], 18036 this._vertexBuffer[triangleIndices[1] * 2 + 0], 18037 this._vertexBuffer[triangleIndices[1] * 2 + 1], 18038 this._vertexBuffer[triangleIndices[2] * 2 + 0], 18039 this._vertexBuffer[triangleIndices[2] * 2 + 1] 18040 ]; 18041 let minX = Infinity; 18042 let minY = Infinity; 18043 let maxX = -Infinity; 18044 let maxY = -Infinity; 18045 for (let i = 0; i < 3; i++) { 18046 const vx = triangleVertices[i * 2]; 18047 const vy = triangleVertices[i * 2 + 1]; 18048 minX = Math.min(minX, vx); 18049 maxX = Math.max(maxX, vx); 18050 minY = Math.min(minY, vy); 18051 maxY = Math.max(maxY, vy); 18052 } 18053 if (minX === maxX || minY === maxY) continue; 18054 const cellXmin = Math.floor(minX / this._granularityCellSize); 18055 const cellXmax = Math.ceil(maxX / this._granularityCellSize); 18056 const cellYmin = Math.floor(minY / this._granularityCellSize); 18057 const cellYmax = Math.ceil(maxY / this._granularityCellSize); 18058 if (cellXmin === cellXmax && cellYmin === cellYmax) { 18059 finalIndices.push(...triangleIndices); 18060 continue; 18061 } 18062 for (let cellRow = cellYmin; cellRow < cellYmax; cellRow++) { 18063 const ring = this._scanlineGenerateVertexRingForCellRow(cellRow, triangleVertices, triangleIndices); 18064 scanlineTriangulateVertexRing(this._vertexBuffer, ring, finalIndices); 18065 } 18066 } 18067 return finalIndices; 18068 } 18069 /** 18070 * Takes a triangle and a cell row index, returns a subdivided vertex ring of the intersection of the triangle and the cell row. 18071 * @param cellRow - Index of the cell row. A cell row of index `i` convert range from `i * granularityCellSize` to `(i + 1) * granularityCellSize`. 18072 * @param triangleVertices - An array of 6 elements, contains flattened positions of the triangle's vertices: `[v0x, v0y, v1x, v1y, v2x, v2y]`. 18073 * @param triangleIndices - An array of 3 elements, contains the original indices of the triangle's vertices: `[index0, index1, index2]`. 18074 * @returns The resulting ring of vertex indices and the index (to the returned ring array) of the leftmost vertex in the ring. 18075 */ 18076 _scanlineGenerateVertexRingForCellRow(cellRow, triangleVertices, triangleIndices) { 18077 const cellRowYTop = cellRow * this._granularityCellSize; 18078 const cellRowYBottom = cellRowYTop + this._granularityCellSize; 18079 const ring = []; 18080 for (let edgeIndex = 0; edgeIndex < 3; edgeIndex++) { 18081 const aX = triangleVertices[edgeIndex * 2]; 18082 const aY = triangleVertices[edgeIndex * 2 + 1]; 18083 const bX = triangleVertices[(edgeIndex + 1) * 2 % 6]; 18084 const bY = triangleVertices[((edgeIndex + 1) * 2 + 1) % 6]; 18085 const cX = triangleVertices[(edgeIndex + 2) * 2 % 6]; 18086 const cY = triangleVertices[((edgeIndex + 2) * 2 + 1) % 6]; 18087 const dirX = bX - aX; 18088 const dirY = bY - aY; 18089 const isParallelY = dirX === 0; 18090 const isParallelX = dirY === 0; 18091 const tTop = (cellRowYTop - aY) / dirY; 18092 const tBottom = (cellRowYBottom - aY) / dirY; 18093 const tEnter = Math.min(tTop, tBottom); 18094 const tExit = Math.max(tTop, tBottom); 18095 if (!isParallelX && (tEnter >= 1 || tExit <= 0) || isParallelX && (aY < cellRowYTop || aY > cellRowYBottom)) { 18096 if (bY >= cellRowYTop && bY <= cellRowYBottom) ring.push(triangleIndices[(edgeIndex + 1) % 3]); 18097 continue; 18098 } 18099 if (!isParallelX && tEnter > 0) { 18100 const x = aX + dirX * tEnter; 18101 const y = aY + dirY * tEnter; 18102 ring.push(this._vertexToIndex(x, y)); 18103 } 18104 const enterX = aX + dirX * Math.max(tEnter, 0); 18105 const exitX = aX + dirX * Math.min(tExit, 1); 18106 if (!isParallelY) this._generateIntraEdgeVertices(ring, aX, aY, bX, bY, enterX, exitX); 18107 if (!isParallelX && tExit < 1) { 18108 const x = aX + dirX * tExit; 18109 const y = aY + dirY * tExit; 18110 ring.push(this._vertexToIndex(x, y)); 18111 } 18112 if (isParallelX || bY >= cellRowYTop && bY <= cellRowYBottom) ring.push(triangleIndices[(edgeIndex + 1) % 3]); 18113 if (!isParallelX && (bY <= cellRowYTop || bY >= cellRowYBottom)) this._generateInterEdgeVertices(ring, aX, aY, bX, bY, cX, cY, exitX, cellRowYTop, cellRowYBottom); 18114 } 18115 return ring; 18116 } 18117 /** 18118 * Generates ring vertices along an edge A-\>B, but only in the part that intersects a given cell row. 18119 * Does not handle adding edge endpoint vertices or edge cell row enter/exit vertices. 18120 * @param ring - Ordered array of vertex indices for the constructed ring. New indices are placed here. 18121 * @param enterX - The X coordinate of the point where edge A-\>B enters the current cell row. 18122 * @param exitX - The X coordinate of the point where edge A-\>B exits the current cell row. 18123 */ 18124 _generateIntraEdgeVertices(ring, aX, aY, bX, bY, enterX, exitX) { 18125 const dirX = bX - aX; 18126 const dirY = bY - aY; 18127 const isParallelX = dirY === 0; 18128 const leftX = isParallelX ? Math.min(aX, bX) : Math.min(enterX, exitX); 18129 const rightX = isParallelX ? Math.max(aX, bX) : Math.max(enterX, exitX); 18130 const edgeSubdivisionLeftCellX = Math.floor(leftX / this._granularityCellSize) + 1; 18131 const edgeSubdivisionRightCellX = Math.ceil(rightX / this._granularityCellSize) - 1; 18132 if (isParallelX ? aX < bX : enterX < exitX) for (let cellX = edgeSubdivisionLeftCellX; cellX <= edgeSubdivisionRightCellX; cellX++) { 18133 const x = cellX * this._granularityCellSize; 18134 const y = aY + dirY * (x - aX) / dirX; 18135 ring.push(this._vertexToIndex(x, y)); 18136 } 18137 else for (let cellX = edgeSubdivisionRightCellX; cellX >= edgeSubdivisionLeftCellX; cellX--) { 18138 const x = cellX * this._granularityCellSize; 18139 const y = aY + dirY * (x - aX) / dirX; 18140 ring.push(this._vertexToIndex(x, y)); 18141 } 18142 } 18143 /** 18144 * Generates ring vertices along cell border. 18145 * Call when processing an edge A-\>B that exits the current row (B lies outside the current row). 18146 * Generates vertices along the cell edge between the exit point from cell row 18147 * of edge A-\>B and entry of edge B-\>C, or entry of C-\>A if both A and C lie outside the cell row. 18148 * Does not handle adding edge endpoint vertices or edge cell row enter/exit vertices. 18149 * @param ring - Ordered array of vertex indices for the constructed ring. New indices are placed here. 18150 * @param exitX - The X coordinate of the point where edge A-\>B exits the current cell row. 18151 * @param cellRowYTop - The current cell row top Y coordinate. 18152 * @param cellRowYBottom - The current cell row bottom Y coordinate. 18153 */ 18154 _generateInterEdgeVertices(ring, aX, aY, bX, bY, cX, cY, exitX, cellRowYTop, cellRowYBottom) { 18155 const dirY = bY - aY; 18156 const dir2X = cX - bX; 18157 const dir2Y = cY - bY; 18158 const t2Top = (cellRowYTop - bY) / dir2Y; 18159 const t2Bottom = (cellRowYBottom - bY) / dir2Y; 18160 const t2Enter = Math.min(t2Top, t2Bottom); 18161 const t2Exit = Math.max(t2Top, t2Bottom); 18162 const enter2X = bX + dir2X * t2Enter; 18163 let boundarySubdivisionLeftCellX = Math.floor(Math.min(enter2X, exitX) / this._granularityCellSize) + 1; 18164 let boundarySubdivisionRightCellX = Math.ceil(Math.max(enter2X, exitX) / this._granularityCellSize) - 1; 18165 let isBoundaryLeftToRight = exitX < enter2X; 18166 const isParallelX2 = dir2Y === 0; 18167 if (isParallelX2 && (cY === cellRowYTop || cY === cellRowYBottom)) return; 18168 if (isParallelX2 || t2Enter >= 1 || t2Exit <= 0) { 18169 const dir3X = aX - cX; 18170 const dir3Y = aY - cY; 18171 const t3Top = (cellRowYTop - cY) / dir3Y; 18172 const t3Bottom = (cellRowYBottom - cY) / dir3Y; 18173 const enter3X = cX + dir3X * Math.min(t3Top, t3Bottom); 18174 boundarySubdivisionLeftCellX = Math.floor(Math.min(enter3X, exitX) / this._granularityCellSize) + 1; 18175 boundarySubdivisionRightCellX = Math.ceil(Math.max(enter3X, exitX) / this._granularityCellSize) - 1; 18176 isBoundaryLeftToRight = exitX < enter3X; 18177 } 18178 const boundaryY = dirY > 0 ? cellRowYBottom : cellRowYTop; 18179 if (isBoundaryLeftToRight) for (let cellX = boundarySubdivisionLeftCellX; cellX <= boundarySubdivisionRightCellX; cellX++) { 18180 const x = cellX * this._granularityCellSize; 18181 ring.push(this._vertexToIndex(x, boundaryY)); 18182 } 18183 else for (let cellX = boundarySubdivisionRightCellX; cellX >= boundarySubdivisionLeftCellX; cellX--) { 18184 const x = cellX * this._granularityCellSize; 18185 ring.push(this._vertexToIndex(x, boundaryY)); 18186 } 18187 } 18188 /** 18189 * Generates an outline for a given polygon, returns a list of arrays of line indices. 18190 */ 18191 _generateOutline(polygon, inputRemap) { 18192 const subdividedLines = []; 18193 let ringStart = 0; 18194 for (const ring of polygon) { 18195 const pathIndices = this._granularity < 2 ? this._ringPathIndices(ring, ringStart, inputRemap) : this._pointArrayToIndices(subdivideVertexLine(ring, this._granularity, true)); 18196 ringStart += ring.length; 18197 const lineIndices = []; 18198 for (let i = 1; i < pathIndices.length; i++) { 18199 lineIndices.push(pathIndices[i - 1]); 18200 lineIndices.push(pathIndices[i]); 18201 } 18202 subdividedLines.push(lineIndices); 18203 } 18204 return subdividedLines; 18205 } 18206 /** 18207 * The outline path `subdivideVertexLine(ring, granularity, true)` returns when the granularity is too low to 18208 * subdivide, as vertex buffer indices rather than points, read from `inputRemap` instead of looked up per point. 18209 */ 18210 _ringPathIndices(ring, start, inputRemap) { 18211 const indices = inputRemap.slice(start, start + ring.length); 18212 if (indices.length >= 2 && ringIsOpen(ring)) indices.push(indices[0]); 18213 return indices; 18214 } 18215 /** 18216 * Adds pole geometry if needed. 18217 * @param subdividedTriangles - Array of generated triangle indices, new pole geometry is appended here. 18218 */ 18219 _handlePoles(subdividedTriangles) { 18220 let north = false; 18221 let south = false; 18222 if (this._canonical) { 18223 if (this._canonical.y === 0) north = true; 18224 if (this._canonical.y === (1 << this._canonical.z) - 1) south = true; 18225 } 18226 if (north || south) this._fillPoles(subdividedTriangles, north, south); 18227 } 18228 /** 18229 * Checks the internal vertex buffer for all vertices that might lie on the special pole coordinates and shifts them by one unit. 18230 * Use for removing unintended pole vertices that might have been created during subdivision. After calling this function, actual pole vertices can be safely generated. 18231 */ 18232 _ensureNoPoleVertices() { 18233 const flattened = this._vertexBuffer; 18234 for (let i = 0; i < flattened.length; i += 2) { 18235 const vy = flattened[i + 1]; 18236 if (vy === -32768) flattened[i + 1] = -32767; 18237 if (vy === 32767) flattened[i + 1] = 32766; 18238 } 18239 } 18240 /** 18241 * Generates a quad from an edge to a pole with the correct winding order. 18242 * Helper function used inside {@link _fillPoles}. 18243 * @param indices - Index array into which the geometry is generated. 18244 * @param i0 - Index of the first edge vertex. 18245 * @param i1 - Index of the second edge vertex. 18246 * @param v0x - X coordinate of the first edge vertex. 18247 * @param v1x - X coordinate of the second edge vertex. 18248 * @param poleY - The Y coordinate of the desired pole (NORTH_POLE_Y or SOUTH_POLE_Y). 18249 */ 18250 _generatePoleQuad(indices, i0, i1, v0x, v1x, poleY) { 18251 if (v0x > v1x !== (poleY === NORTH_POLE_Y)) { 18252 indices.push(i0); 18253 indices.push(i1); 18254 indices.push(this._vertexToIndex(v0x, poleY)); 18255 indices.push(i1); 18256 indices.push(this._vertexToIndex(v1x, poleY)); 18257 indices.push(this._vertexToIndex(v0x, poleY)); 18258 } else { 18259 indices.push(i1); 18260 indices.push(i0); 18261 indices.push(this._vertexToIndex(v0x, poleY)); 18262 indices.push(this._vertexToIndex(v1x, poleY)); 18263 indices.push(i1); 18264 indices.push(this._vertexToIndex(v0x, poleY)); 18265 } 18266 } 18267 /** 18268 * Detects edges that border the north or south tile edge 18269 * and adds triangles that extend those edges to the poles. 18270 * Only run this function on tiles that border the poles. 18271 * Assumes that supplied geometry is clipped to the inclusive range of 0..EXTENT. 18272 * Mutates the supplies vertex and index arrays. 18273 * @param indices - Triangle indices. This array is appended with new primitives. 18274 * @param north - Whether to generate geometry for the north pole. 18275 * @param south - Whether to generate geometry for the south pole. 18276 */ 18277 _fillPoles(indices, north, south) { 18278 const flattened = this._vertexBuffer; 18279 const northEdge = 0; 18280 const southEdge = EXTENT$1; 18281 const numIndices = indices.length; 18282 for (let primitiveIndex = 2; primitiveIndex < numIndices; primitiveIndex += 3) { 18283 const i0 = indices[primitiveIndex - 2]; 18284 const i1 = indices[primitiveIndex - 1]; 18285 const i2 = indices[primitiveIndex]; 18286 const v0x = flattened[i0 * 2]; 18287 const v0y = flattened[i0 * 2 + 1]; 18288 const v1x = flattened[i1 * 2]; 18289 const v1y = flattened[i1 * 2 + 1]; 18290 const v2x = flattened[i2 * 2]; 18291 const v2y = flattened[i2 * 2 + 1]; 18292 if (north) { 18293 if (v0y === northEdge && v1y === northEdge) this._generatePoleQuad(indices, i0, i1, v0x, v1x, NORTH_POLE_Y); 18294 if (v1y === northEdge && v2y === northEdge) this._generatePoleQuad(indices, i1, i2, v1x, v2x, NORTH_POLE_Y); 18295 if (v2y === northEdge && v0y === northEdge) this._generatePoleQuad(indices, i2, i0, v2x, v0x, NORTH_POLE_Y); 18296 } 18297 if (south) { 18298 if (v0y === southEdge && v1y === southEdge) this._generatePoleQuad(indices, i0, i1, v0x, v1x, SOUTH_POLE_Y); 18299 if (v1y === southEdge && v2y === southEdge) this._generatePoleQuad(indices, i1, i2, v1x, v2x, SOUTH_POLE_Y); 18300 if (v2y === southEdge && v0y === southEdge) this._generatePoleQuad(indices, i2, i0, v2x, v0x, SOUTH_POLE_Y); 18301 } 18302 } 18303 } 18304 /** 18305 * Adds all vertices in the supplied flattened vertex buffer into the internal vertex buffer. 18306 * @returns The index into the internal vertex buffer for each input vertex, in the order `flatten` produced them. 18307 */ 18308 _initializeVertices(flattened) { 18309 const inputRemap = []; 18310 for (let i = 0; i < flattened.length; i += 2) inputRemap.push(this._vertexToIndex(flattened[i], flattened[i + 1])); 18311 return inputRemap; 18312 } 18313 /** 18314 * Subdivides an input mesh. Imagine a regular square grid with the target granularity overlaid over the mesh - this is the subdivision's result. 18315 * Assumes a mesh of tile features - vertex coordinates are integers, visible range where subdivision happens is 0..8192. 18316 * @param polygon - The input polygon, specified as a list of vertex rings. 18317 * @param generateOutlineLines - When true, also generates line indices for outline of the supplied polygon. 18318 * @returns Vertex and index buffers with subdivision applied. 18319 */ 18320 subdividePolygonInternal(polygon, generateOutlineLines) { 18321 if (this._used) throw new Error("Subdivision: multiple use not allowed."); 18322 this._used = true; 18323 const { flattened, holeIndices } = flatten(polygon); 18324 const inputRemap = this._initializeVertices(flattened); 18325 let subdividedTriangles; 18326 try { 18327 const earcutResult = earcut(flattened, holeIndices); 18328 subdividedTriangles = this._subdivideTrianglesScanline(earcutResult, inputRemap); 18329 } catch (e) { 18330 console.error(e); 18331 } 18332 let subdividedLines = []; 18333 if (generateOutlineLines) subdividedLines = this._generateOutline(polygon, inputRemap); 18334 this._ensureNoPoleVertices(); 18335 this._handlePoles(subdividedTriangles); 18336 if (this._granularity >= 2 && this._canonical?.z === 0) { 18337 subdividedTriangles = this._removeTrianglesOutsideTileX(subdividedTriangles); 18338 subdividedLines = subdividedLines.map((lines) => this._removeLinesOutsideTileX(lines)); 18339 } 18340 return { 18341 verticesFlattened: this._vertexBuffer, 18342 indicesTriangles: subdividedTriangles, 18343 indicesLineList: subdividedLines 18344 }; 18345 } 18346 _vertexOutsideTileX(index) { 18347 const x = this._vertexBuffer[index * 2]; 18348 return x < 0 || x > 8192; 18349 } 18350 /** 18351 * Drops all triangles that reach beyond the tile's X extent. 18352 * 18353 * On globe the z0 tile's buffer wraps around the planet onto the tile itself, drawing buffered geometry twice. 18354 * Only globe uses subdivision (`granularity >= 2`), so mercator is never affected. 18355 * @param indices - Triangle indices into `this._vertexBuffer`. 18356 * @returns The indices with every triangle that has a vertex outside the tile's X extent removed. 18357 */ 18358 _removeTrianglesOutsideTileX(indices) { 18359 const filtered = []; 18360 for (let i = 0; i < indices.length; i += 3) { 18361 if (this._vertexOutsideTileX(indices[i]) || this._vertexOutsideTileX(indices[i + 1]) || this._vertexOutsideTileX(indices[i + 2])) continue; 18362 filtered.push(indices[i], indices[i + 1], indices[i + 2]); 18363 } 18364 return filtered; 18365 } 18366 /** 18367 * Drops all outline line segments that reach beyond the tile's X extent, 18368 * for the same reason as {@link Subdivider._removeTrianglesOutsideTileX}. 18369 * @param indices - Line segment indices into `this._vertexBuffer`. 18370 * @returns The indices with every segment that has a vertex outside the tile's X extent removed. 18371 */ 18372 _removeLinesOutsideTileX(indices) { 18373 const filtered = []; 18374 for (let i = 0; i < indices.length; i += 2) { 18375 if (this._vertexOutsideTileX(indices[i]) || this._vertexOutsideTileX(indices[i + 1])) continue; 18376 filtered.push(indices[i], indices[i + 1]); 18377 } 18378 return filtered; 18379 } 18380 /** 18381 * Converts an array of points into an array of indices into the internal vertex buffer (`_finalVertices`). 18382 */ 18383 _pointArrayToIndices(array) { 18384 const indices = []; 18385 for (const p of array) indices.push(this._vertexToIndex(p.x, p.y)); 18386 return indices; 18387 } 18388}; 18389/** 18390* Subdivides a polygon to a given granularity. Intended for preprocessing geometry for the 'fill' and 'fill-extrusion' layer types. 18391* All returned triangles have the counter-clockwise winding order. 18392* @param polygon - An array of point rings that specify the polygon. The first ring is the polygon exterior, all subsequent rings form holes inside the first ring. 18393* @param canonical - The canonical tile ID of the tile this polygon belongs to. Needed for generating special geometry for tiles that border the poles. 18394* @param granularity - The subdivision granularity. If we assume tile EXTENT=8192, then a granularity of 2 will result in geometry being "cut" on each axis 18395* divisible by 4096 (including outside the tile range, so -8192, -4096, or 12288...), granularity of 8 on axes divisible by 1024 and so on. 18396* Granularity of 1 or lower results in *no* subdivision. 18397* @param generateOutlineLines - When true, also generates index arrays for subdivided lines that form the outline of the supplied polygon. True by default. 18398* @returns An object that contains the generated vertex array, triangle index array and, if specified, line index arrays. 18399*/ 18400function subdividePolygon(polygon, canonical, granularity, generateOutlineLines = true) { 18401 return new Subdivider(granularity, canonical).subdividePolygonInternal(polygon, generateOutlineLines); 18402} 18403/** 18404* Subdivides a line represented by an array of points. Mainly intended for preprocessing geometry for the 'line' layer type. 18405* Assumes a line segment between each two consecutive points in the array. 18406* Does not assume a line segment from last point to first point, unless `isRing` is set to `true`. 18407* For example, an array of 4 points describes exactly 3 line segments. 18408* @param linePoints - An array of points describing the line segments. 18409* @param granularity - Subdivision granularity. 18410* @param isRing - When true, an additional line segment is assumed to exist between the input array's last and first point. 18411* @returns A new array of points of the subdivided line segments. The array may contain some of the original Point objects. If `isRing` is set to `true`, then this also includes the (subdivided) segment from the last point of the input array to the first point. 18412* 18413* @example 18414* ```ts 18415* const result = subdivideVertexLine([ 18416* new Point(0, 0), 18417* new Point(8, 0), 18418* new Point(0, 8), 18419* ], EXTENT / 4, false); 18420* // Results in an array of points with these (x, y) coordinates: 18421* // 0, 0 18422* // 4, 0 18423* // 8, 0 18424* // 4, 4 18425* // 0, 8 18426* ``` 18427* 18428* @example 18429* ```ts 18430* const result = subdivideVertexLine([ 18431* new Point(0, 0), 18432* new Point(8, 0), 18433* new Point(0, 8), 18434* ], EXTENT / 4, true); 18435* // Results in an array of points with these (x, y) coordinates: 18436* // 0, 0 18437* // 4, 0 18438* // 8, 0 18439* // 4, 4 18440* // 0, 8 18441* // 0, 4 18442* // 0, 0 18443* ``` 18444*/ 18445function subdivideVertexLine(linePoints, granularity, isRing = false) { 18446 if (!linePoints || linePoints.length < 1) return []; 18447 if (linePoints.length < 2) return []; 18448 const addLastToFirstSegment = isRing && ringIsOpen(linePoints); 18449 if (granularity < 2) { 18450 if (addLastToFirstSegment) return [...linePoints, linePoints[0]]; 18451 else return [...linePoints]; 18452 } 18453 const cellSize = Math.floor(EXTENT$1 / granularity); 18454 const finalLineVertices = []; 18455 finalLineVertices.push(new Point(linePoints[0].x, linePoints[0].y)); 18456 const totalPoints = linePoints.length; 18457 const lastIndex = addLastToFirstSegment ? totalPoints : totalPoints - 1; 18458 for (let pointIndex = 0; pointIndex < lastIndex; pointIndex++) { 18459 const linePoint0 = linePoints[pointIndex]; 18460 const linePoint1 = pointIndex < totalPoints - 1 ? linePoints[pointIndex + 1] : linePoints[0]; 18461 const lineVertex0x = linePoint0.x; 18462 const lineVertex0y = linePoint0.y; 18463 const lineVertex1x = linePoint1.x; 18464 const lineVertex1y = linePoint1.y; 18465 const dirXnonZero = lineVertex0x !== lineVertex1x; 18466 const dirYnonZero = lineVertex0y !== lineVertex1y; 18467 if (!dirXnonZero && !dirYnonZero) continue; 18468 const dirX = lineVertex1x - lineVertex0x; 18469 const dirY = lineVertex1y - lineVertex0y; 18470 const absDirX = Math.abs(dirX); 18471 const absDirY = Math.abs(dirY); 18472 let lastPointX = lineVertex0x; 18473 let lastPointY = lineVertex0y; 18474 while (true) { 18475 const nextBoundaryX = dirX > 0 ? (Math.floor(lastPointX / cellSize) + 1) * cellSize : (Math.ceil(lastPointX / cellSize) - 1) * cellSize; 18476 const nextBoundaryY = dirY > 0 ? (Math.floor(lastPointY / cellSize) + 1) * cellSize : (Math.ceil(lastPointY / cellSize) - 1) * cellSize; 18477 const axisDistanceToBoundaryX = Math.abs(lastPointX - nextBoundaryX); 18478 const axisDistanceToBoundaryY = Math.abs(lastPointY - nextBoundaryY); 18479 const axisDistanceToEndX = Math.abs(lastPointX - lineVertex1x); 18480 const axisDistanceToEndY = Math.abs(lastPointY - lineVertex1y); 18481 const realDistanceToBoundaryX = dirXnonZero ? axisDistanceToBoundaryX / absDirX : Number.POSITIVE_INFINITY; 18482 const realDistanceToBoundaryY = dirYnonZero ? axisDistanceToBoundaryY / absDirY : Number.POSITIVE_INFINITY; 18483 if ((axisDistanceToEndX <= axisDistanceToBoundaryX || !dirXnonZero) && (axisDistanceToEndY <= axisDistanceToBoundaryY || !dirYnonZero)) break; 18484 if (realDistanceToBoundaryX < realDistanceToBoundaryY && dirXnonZero || !dirYnonZero) { 18485 lastPointX = nextBoundaryX; 18486 lastPointY = lastPointY + dirY * realDistanceToBoundaryX; 18487 const next = new Point(lastPointX, Math.round(lastPointY)); 18488 if (finalLineVertices[finalLineVertices.length - 1].x !== next.x || finalLineVertices[finalLineVertices.length - 1].y !== next.y) finalLineVertices.push(next); 18489 } else { 18490 lastPointX = lastPointX + dirX * realDistanceToBoundaryY; 18491 lastPointY = nextBoundaryY; 18492 const next = new Point(Math.round(lastPointX), lastPointY); 18493 if (finalLineVertices[finalLineVertices.length - 1].x !== next.x || finalLineVertices[finalLineVertices.length - 1].y !== next.y) finalLineVertices.push(next); 18494 } 18495 } 18496 const last = new Point(lineVertex1x, lineVertex1y); 18497 if (finalLineVertices[finalLineVertices.length - 1].x !== last.x || finalLineVertices[finalLineVertices.length - 1].y !== last.y) finalLineVertices.push(last); 18498 } 18499 return finalLineVertices; 18500} 18501/** 18502* Whether a ring's last vertex differs from its first, so that drawing it needs a closing segment. 18503*/ 18504function ringIsOpen(ring) { 18505 return !ring[0].equals(ring[ring.length - 1]); 18506} 18507/** 18508* Takes a polygon as an array of point rings, returns a flattened array of the X,Y coordinates of these points. 18509* Also creates an array of hole indices. Both returned arrays are required for `earcut`. 18510*/ 18511function flatten(polygon) { 18512 const holeIndices = []; 18513 const flattened = []; 18514 for (const ring of polygon) { 18515 if (ring.length === 0) continue; 18516 if (ring !== polygon[0]) holeIndices.push(flattened.length / 2); 18517 for (const vertex of ring) { 18518 flattened.push(vertex.x); 18519 flattened.push(vertex.y); 18520 } 18521 } 18522 return { 18523 flattened, 18524 holeIndices 18525 }; 18526} 18527/** 18528* Returns a copy of `indices` where every index is replaced by `remap[index]`. 18529* @param indices - Indices into the array `remap` was built for. 18530* @param remap - The replacement for each index. 18531*/ 18532function remapIndices(indices, remap) { 18533 const remapped = new Array(indices.length); 18534 for (let i = 0; i < indices.length; i++) remapped[i] = remap[indices[i]]; 18535 return remapped; 18536} 18537/** 18538* Returns a new array of indices where all triangles have the counter-clockwise winding order. 18539* @param flattened - Flattened vertex buffer. 18540* @param indices - Triangle indices. 18541*/ 18542function fixWindingOrder(flattened, indices) { 18543 const corrected = []; 18544 for (let i = 0; i < indices.length; i += 3) { 18545 const i0 = indices[i]; 18546 const i1 = indices[i + 1]; 18547 const i2 = indices[i + 2]; 18548 const v0x = flattened[i0 * 2]; 18549 const v0y = flattened[i0 * 2 + 1]; 18550 const v1x = flattened[i1 * 2]; 18551 const v1y = flattened[i1 * 2 + 1]; 18552 const v2x = flattened[i2 * 2]; 18553 const v2y = flattened[i2 * 2 + 1]; 18554 const e0x = v1x - v0x; 18555 const e0y = v1y - v0y; 18556 const e1x = v2x - v0x; 18557 if (e0x * (v2y - v0y) - e0y * e1x > 0) { 18558 corrected.push(i0); 18559 corrected.push(i2); 18560 corrected.push(i1); 18561 } else { 18562 corrected.push(i0); 18563 corrected.push(i1); 18564 corrected.push(i2); 18565 } 18566 } 18567 return corrected; 18568} 18569/** 18570* Triangulates a ring of vertex indices. Appends to the supplied array of final triangle indices. 18571* @param vertexBuffer - Flattened vertex coordinate array. 18572* @param ring - Ordered ring of vertex indices to triangulate. 18573* @param leftmostIndex - The index of the leftmost vertex in the supplied ring. 18574* @param finalIndices - Array of final triangle indices, into where the resulting triangles are appended. 18575*/ 18576function scanlineTriangulateVertexRing(vertexBuffer, ring, finalIndices) { 18577 if (ring.length === 0) throw new Error("Subdivision vertex ring is empty."); 18578 let leftmostIndex = 0; 18579 let leftmostX = vertexBuffer[ring[0] * 2]; 18580 for (let i = 1; i < ring.length; i++) { 18581 const x = vertexBuffer[ring[i] * 2]; 18582 if (x < leftmostX) { 18583 leftmostX = x; 18584 leftmostIndex = i; 18585 } 18586 } 18587 const ringVertexLength = ring.length; 18588 let lastEdgeA = leftmostIndex; 18589 let lastEdgeB = (lastEdgeA + 1) % ringVertexLength; 18590 while (true) { 18591 const candidateIndexA = lastEdgeA - 1 >= 0 ? lastEdgeA - 1 : ringVertexLength - 1; 18592 const candidateIndexB = (lastEdgeB + 1) % ringVertexLength; 18593 const candidateAx = vertexBuffer[ring[candidateIndexA] * 2]; 18594 const candidateAy = vertexBuffer[ring[candidateIndexA] * 2 + 1]; 18595 const candidateBx = vertexBuffer[ring[candidateIndexB] * 2]; 18596 const candidateBy = vertexBuffer[ring[candidateIndexB] * 2 + 1]; 18597 const lastEdgeAx = vertexBuffer[ring[lastEdgeA] * 2]; 18598 const lastEdgeAy = vertexBuffer[ring[lastEdgeA] * 2 + 1]; 18599 const lastEdgeBx = vertexBuffer[ring[lastEdgeB] * 2]; 18600 const lastEdgeBy = vertexBuffer[ring[lastEdgeB] * 2 + 1]; 18601 let pickA = false; 18602 if (candidateAx < candidateBx) pickA = true; 18603 else if (candidateAx > candidateBx) pickA = false; 18604 else { 18605 const nx = lastEdgeBy - lastEdgeAy; 18606 const ny = -(lastEdgeBx - lastEdgeAx); 18607 const sign = lastEdgeAy < lastEdgeBy ? 1 : -1; 18608 if (((candidateAx - lastEdgeAx) * nx + (candidateAy - lastEdgeAy) * ny) * sign > ((candidateBx - lastEdgeAx) * nx + (candidateBy - lastEdgeAy) * ny) * sign) pickA = true; 18609 } 18610 if (pickA) { 18611 const c = ring[candidateIndexA]; 18612 const a = ring[lastEdgeA]; 18613 const b = ring[lastEdgeB]; 18614 if (c !== a && c !== b && a !== b) finalIndices.push(b, a, c); 18615 lastEdgeA--; 18616 if (lastEdgeA < 0) lastEdgeA = ringVertexLength - 1; 18617 } else { 18618 const c = ring[candidateIndexB]; 18619 const a = ring[lastEdgeA]; 18620 const b = ring[lastEdgeB]; 18621 if (c !== a && c !== b && a !== b) finalIndices.push(b, a, c); 18622 lastEdgeB++; 18623 if (lastEdgeB >= ringVertexLength) lastEdgeB = 0; 18624 } 18625 if (candidateIndexA === candidateIndexB) break; 18626 } 18627} 18628//#endregion 18629//#region src/render/fill_large_mesh_arrays.ts 18630/** 18631* This function will take any "mesh" and fill in into vertex buffers, breaking it up into multiple drawcalls as needed 18632* if too many (\>65535) vertices are used. 18633* This function is mainly intended for use with subdivided geometry, since sometimes subdivision might generate 18634* more vertices than what fits into 16 bit indices. 18635* 18636* Accepts a triangle mesh, optionally with a line list (for fill outlines) as well. The triangle and line segments are expected to share a single vertex buffer. 18637* 18638* Mutates the provided `segmentsTriangles` and `segmentsLines` SegmentVectors, 18639* `vertexArray`, `triangleIndexArray` and optionally `lineIndexArray`. 18640* Does not mutate the input `flattened` vertices, `triangleIndices` and `lineList`. 18641* @param addVertex - A function for adding a new vertex into `vertexArray`. We might sometimes want to add more values per vertex than just X and Y coordinates, which can be handled in this function. 18642* @param segmentsTriangles - The segment array for triangle draw calls. New segments will be placed here. 18643* @param vertexArray - The vertex array into which new vertices are placed by the provided `addVertex` function. 18644* @param triangleIndexArray - Index array for drawing triangles. New triangle indices are placed here. 18645* @param flattened - The input flattened array or vertex coordinates. 18646* @param triangleIndices - Triangle indices into `flattened`. 18647* @param segmentsLines - Segment array for line draw calls. New segments will be placed here. Only needed if the mesh also contains lines. 18648* @param lineIndexArray - Index array for drawing lines. New triangle indices are placed here. Only needed if the mesh also contains lines. 18649* @param lineList - Line indices into `flattened`. Only needed if the mesh also contains lines. 18650*/ 18651function fillLargeMeshArrays(addVertex, segmentsTriangles, vertexArray, triangleIndexArray, flattened, triangleIndices, segmentsLines, lineIndexArray, lineList) { 18652 const numVertices = flattened.length / 2; 18653 const hasLines = segmentsLines && lineIndexArray && lineList; 18654 if (numVertices < SegmentVector.MAX_VERTEX_ARRAY_LENGTH) { 18655 const triangleSegment = segmentsTriangles.prepareSegment(numVertices, vertexArray, triangleIndexArray); 18656 const triangleIndex = triangleSegment.vertexLength; 18657 for (let i = 0; i < triangleIndices.length; i += 3) triangleIndexArray.emplaceBack(triangleIndex + triangleIndices[i], triangleIndex + triangleIndices[i + 1], triangleIndex + triangleIndices[i + 2]); 18658 triangleSegment.vertexLength += numVertices; 18659 triangleSegment.primitiveLength += triangleIndices.length / 3; 18660 let lineIndicesStart; 18661 let lineSegment; 18662 if (hasLines) { 18663 lineSegment = segmentsLines.prepareSegment(numVertices, vertexArray, lineIndexArray); 18664 lineIndicesStart = lineSegment.vertexLength; 18665 lineSegment.vertexLength += numVertices; 18666 } 18667 for (let i = 0; i < flattened.length; i += 2) addVertex(flattened[i], flattened[i + 1]); 18668 if (hasLines) for (const lineIndices of lineList) { 18669 for (let i = 1; i < lineIndices.length; i += 2) lineIndexArray.emplaceBack(lineIndicesStart + lineIndices[i - 1], lineIndicesStart + lineIndices[i]); 18670 lineSegment.primitiveLength += lineIndices.length / 2; 18671 } 18672 } else { 18673 fillSegmentsTriangles(segmentsTriangles, vertexArray, triangleIndexArray, flattened, triangleIndices, addVertex); 18674 if (hasLines) fillSegmentsLines(segmentsLines, vertexArray, lineIndexArray, flattened, lineList, addVertex); 18675 segmentsTriangles.forceNewSegmentOnNextPrepare(); 18676 segmentsLines?.forceNewSegmentOnNextPrepare(); 18677 } 18678} 18679/** 18680* Determines the new index of a vertex given by its old index. 18681* @param actualVertexIndices - Array that maps the old index of a given vertex to a new index in the final vertex buffer. 18682* @param flattened - Old vertex buffer. 18683* @param addVertex - Function for creating a new vertex in the final vertex buffer. 18684* @param totalVerticesCreated - Reference to an int holding how many vertices were added to the final vertex buffer. 18685* @param oldIndex - The old index of the desired vertex. 18686* @param needsCopy - Whether to duplicate the desired vertex in the final vertex buffer. 18687* @param segment - The current segment. 18688* @returns Index of the vertex in the final vertex array. 18689*/ 18690function copyOrReuseVertex(actualVertexIndices, flattened, addVertex, totalVerticesCreated, oldIndex, needsCopy, segment) { 18691 if (needsCopy) { 18692 const newIndex = totalVerticesCreated.count; 18693 addVertex(flattened[oldIndex * 2], flattened[oldIndex * 2 + 1]); 18694 actualVertexIndices[oldIndex] = totalVerticesCreated.count; 18695 totalVerticesCreated.count++; 18696 segment.vertexLength++; 18697 return newIndex; 18698 } else return actualVertexIndices[oldIndex]; 18699} 18700function fillSegmentsTriangles(segmentsTriangles, vertexArray, triangleIndexArray, flattened, triangleIndices, addVertex) { 18701 const actualVertexIndices = []; 18702 for (let i = 0; i < flattened.length / 2; i++) actualVertexIndices.push(-1); 18703 const totalVerticesCreated = { count: 0 }; 18704 let currentSegmentCutoff = 0; 18705 let segment = segmentsTriangles.getOrCreateLatestSegment(vertexArray, triangleIndexArray); 18706 let baseVertex = segment.vertexLength; 18707 for (let primitiveEndIndex = 2; primitiveEndIndex < triangleIndices.length; primitiveEndIndex += 3) { 18708 const i0 = triangleIndices[primitiveEndIndex - 2]; 18709 const i1 = triangleIndices[primitiveEndIndex - 1]; 18710 const i2 = triangleIndices[primitiveEndIndex]; 18711 let i0needsVertexCopy = actualVertexIndices[i0] < currentSegmentCutoff; 18712 let i1needsVertexCopy = actualVertexIndices[i1] < currentSegmentCutoff; 18713 let i2needsVertexCopy = actualVertexIndices[i2] < currentSegmentCutoff; 18714 const vertexCopyCount = (i0needsVertexCopy ? 1 : 0) + (i1needsVertexCopy ? 1 : 0) + (i2needsVertexCopy ? 1 : 0); 18715 if (segment.vertexLength + vertexCopyCount > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) { 18716 segment = segmentsTriangles.createNewSegment(vertexArray, triangleIndexArray); 18717 currentSegmentCutoff = totalVerticesCreated.count; 18718 i0needsVertexCopy = true; 18719 i1needsVertexCopy = true; 18720 i2needsVertexCopy = true; 18721 baseVertex = 0; 18722 } 18723 const actualIndex0 = copyOrReuseVertex(actualVertexIndices, flattened, addVertex, totalVerticesCreated, i0, i0needsVertexCopy, segment); 18724 const actualIndex1 = copyOrReuseVertex(actualVertexIndices, flattened, addVertex, totalVerticesCreated, i1, i1needsVertexCopy, segment); 18725 const actualIndex2 = copyOrReuseVertex(actualVertexIndices, flattened, addVertex, totalVerticesCreated, i2, i2needsVertexCopy, segment); 18726 triangleIndexArray.emplaceBack(baseVertex + actualIndex0 - currentSegmentCutoff, baseVertex + actualIndex1 - currentSegmentCutoff, baseVertex + actualIndex2 - currentSegmentCutoff); 18727 segment.primitiveLength++; 18728 } 18729} 18730function fillSegmentsLines(segmentsLines, vertexArray, lineIndexArray, flattened, lineList, addVertex) { 18731 const actualVertexIndices = []; 18732 for (let i = 0; i < flattened.length / 2; i++) actualVertexIndices.push(-1); 18733 const totalVerticesCreated = { count: 0 }; 18734 let currentSegmentCutoff = 0; 18735 let segment = segmentsLines.getOrCreateLatestSegment(vertexArray, lineIndexArray); 18736 let baseVertex = segment.vertexLength; 18737 for (const currentLine of lineList) for (let lineVertex = 1; lineVertex < currentLine.length; lineVertex += 2) { 18738 const i0 = currentLine[lineVertex - 1]; 18739 const i1 = currentLine[lineVertex]; 18740 let i0needsVertexCopy = actualVertexIndices[i0] < currentSegmentCutoff; 18741 let i1needsVertexCopy = actualVertexIndices[i1] < currentSegmentCutoff; 18742 const vertexCopyCount = (i0needsVertexCopy ? 1 : 0) + (i1needsVertexCopy ? 1 : 0); 18743 if (segment.vertexLength + vertexCopyCount > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) { 18744 segment = segmentsLines.createNewSegment(vertexArray, lineIndexArray); 18745 currentSegmentCutoff = totalVerticesCreated.count; 18746 i0needsVertexCopy = true; 18747 i1needsVertexCopy = true; 18748 baseVertex = 0; 18749 } 18750 const actualIndex0 = copyOrReuseVertex(actualVertexIndices, flattened, addVertex, totalVerticesCreated, i0, i0needsVertexCopy, segment); 18751 const actualIndex1 = copyOrReuseVertex(actualVertexIndices, flattened, addVertex, totalVerticesCreated, i1, i1needsVertexCopy, segment); 18752 lineIndexArray.emplaceBack(baseVertex + actualIndex0 - currentSegmentCutoff, baseVertex + actualIndex1 - currentSegmentCutoff); 18753 segment.primitiveLength++; 18754 } 18755} 18756//#endregion 18757//#region src/data/bucket/fill_bucket.ts 18758const EARCUT_MAX_RINGS$1 = 500; 18759var FillBucket = class { 18760 constructor(options) { 18761 this.zoom = options.zoom; 18762 this.overscaling = options.overscaling; 18763 this.layers = options.layers; 18764 this.layerIds = this.layers.map((layer) => layer.id); 18765 this.index = options.index; 18766 this.hasDependencies = false; 18767 this.sdfPatterns = {}; 18768 this.patternFeatures = []; 18769 this.layoutVertexArray = new FillLayoutArray(); 18770 this.indexArray = new TriangleIndexArray(); 18771 this.indexArray2 = new LineIndexArray(); 18772 this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom); 18773 this.segments = new SegmentVector(); 18774 this.segments2 = new SegmentVector(); 18775 this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); 18776 } 18777 populate(features, options, canonical) { 18778 this.hasDependencies = hasPattern("fill", this.layers, options); 18779 const fillSortKey = this.layers[0].layout.get("fill-sort-key"); 18780 const sortFeaturesByKey = !fillSortKey.isConstant(); 18781 const bucketFeatures = []; 18782 const globalProperties = new EvaluationParameters(this.zoom); 18783 const needGeometry = this.layers[0]._featureFilter.needGeometry; 18784 for (const { feature, id, index, sourceLayerIndex } of features) { 18785 const evaluationFeature = toEvaluationFeature(feature, needGeometry); 18786 if (!this.layers[0]._featureFilter.filter(globalProperties, evaluationFeature, canonical)) continue; 18787 const sortKey = sortFeaturesByKey ? fillSortKey.evaluate(evaluationFeature, {}, canonical, options.availableImages) : void 0; 18788 const bucketFeature = { 18789 id, 18790 properties: feature.properties, 18791 type: feature.type, 18792 sourceLayerIndex, 18793 index, 18794 geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature), 18795 patterns: {}, 18796 sortKey 18797 }; 18798 bucketFeatures.push(bucketFeature); 18799 } 18800 if (sortFeaturesByKey) bucketFeatures.sort((a, b) => a.sortKey - b.sortKey); 18801 for (const bucketFeature of bucketFeatures) { 18802 const { geometry, index, sourceLayerIndex } = bucketFeature; 18803 if (this.hasDependencies) { 18804 const patternFeature = addPatternDependencies("fill", this.layers, bucketFeature, { zoom: this.zoom }, options); 18805 this.patternFeatures.push(patternFeature); 18806 } else this.addFeature(bucketFeature, geometry, index, canonical, {}, options.subdivisionGranularity); 18807 const feature = features[index].feature; 18808 options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index); 18809 } 18810 } 18811 update(states, vtLayer, imagePositions) { 18812 if (!this.stateDependentLayers.length) return; 18813 this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, { imagePositions }); 18814 } 18815 addFeatures({ options, canonical, patternPositions, patternMap }) { 18816 this.detectSdfPatterns(patternMap); 18817 for (const feature of this.patternFeatures) this.addFeature(feature, feature.geometry, feature.index, canonical, patternPositions, options.subdivisionGranularity); 18818 } 18819 detectSdfPatterns(imageMap) { 18820 for (const feature of this.patternFeatures) for (const layerId in feature.patterns) { 18821 const pattern = feature.patterns[layerId]; 18822 this.recordSdfPattern(layerId, imageMap[pattern.min]); 18823 this.recordSdfPattern(layerId, imageMap[pattern.mid]); 18824 this.recordSdfPattern(layerId, imageMap[pattern.max]); 18825 } 18826 for (const layer of this.layers) { 18827 const pattern = layer.paint.get("fill-pattern").constantOr(null); 18828 if (pattern) { 18829 this.recordSdfPattern(layer.id, imageMap[pattern.from.toString()]); 18830 this.recordSdfPattern(layer.id, imageMap[pattern.to.toString()]); 18831 } 18832 } 18833 } 18834 recordSdfPattern(layerId, image) { 18835 if (!image) return; 18836 const isSdf = image.sdf === true; 18837 const existing = this.sdfPatterns[layerId]; 18838 if (existing === void 0) this.sdfPatterns[layerId] = isSdf; 18839 else if (existing !== isSdf) warnOnce(`Style sheet warning: Cannot mix SDF and non-SDF fill patterns in layer "${layerId}"`); 18840 } 18841 isEmpty() { 18842 return this.layoutVertexArray.length === 0; 18843 } 18844 uploadPending() { 18845 return !this.uploaded || this.programConfigurations.needsUpload; 18846 } 18847 upload(context) { 18848 if (!this.uploaded) { 18849 this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$3); 18850 this.indexBuffer = context.createIndexBuffer(this.indexArray); 18851 this.indexBuffer2 = context.createIndexBuffer(this.indexArray2); 18852 } 18853 this.programConfigurations.upload(context); 18854 this.uploaded = true; 18855 } 18856 destroy() { 18857 if (!this.layoutVertexBuffer) return; 18858 this.layoutVertexBuffer.destroy(); 18859 this.indexBuffer.destroy(); 18860 this.indexBuffer2.destroy(); 18861 this.programConfigurations.destroy(); 18862 this.segments.destroy(); 18863 this.segments2.destroy(); 18864 } 18865 addFeature(feature, geometry, index, canonical, imagePositions, subdivisionGranularity) { 18866 for (const polygon of classifyRings$1(geometry, EARCUT_MAX_RINGS$1)) { 18867 const subdivided = subdividePolygon(polygon, canonical, subdivisionGranularity.fill.getGranularityForZoomLevel(canonical.z)); 18868 const vertexArray = this.layoutVertexArray; 18869 fillLargeMeshArrays((x, y) => { 18870 vertexArray.emplaceBack(x, y); 18871 }, this.segments, this.layoutVertexArray, this.indexArray, subdivided.verticesFlattened, subdivided.indicesTriangles, this.segments2, this.indexArray2, subdivided.indicesLineList); 18872 } 18873 this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, { 18874 imagePositions, 18875 canonical 18876 }); 18877 } 18878}; 18879register("FillBucket", FillBucket, { omit: ["layers", "patternFeatures"] }); 18880//#endregion 18881//#region src/style/style_layer/fill_style_layer_properties.g.ts 18882let layout$4; 18883const getLayout$3 = () => layout$4 = layout$4 || new Properties({ "fill-sort-key": new DataDrivenProperty(latest["layout_fill"]["fill-sort-key"], "fill-sort-key") }); 18884let paint$4; 18885const getPaint$4 = () => paint$4 = paint$4 || new Properties({ 18886 "fill-antialias": new DataConstantProperty(latest["paint_fill"]["fill-antialias"], "fill-antialias"), 18887 "fill-opacity": new DataDrivenProperty(latest["paint_fill"]["fill-opacity"], "fill-opacity"), 18888 "fill-layer-opacity": new DataConstantProperty(latest["paint_fill"]["fill-layer-opacity"], "fill-layer-opacity"), 18889 "fill-color": new DataDrivenProperty(latest["paint_fill"]["fill-color"], "fill-color"), 18890 "fill-outline-color": new DataDrivenProperty(latest["paint_fill"]["fill-outline-color"], "fill-outline-color"), 18891 "fill-translate": new DataConstantProperty(latest["paint_fill"]["fill-translate"], "fill-translate"), 18892 "fill-translate-anchor": new DataConstantProperty(latest["paint_fill"]["fill-translate-anchor"], "fill-translate-anchor"), 18893 "fill-pattern": new CrossFadedDataDrivenProperty(latest["paint_fill"]["fill-pattern"], "fill-pattern") 18894}); 18895var fill_style_layer_properties_g_default = { 18896 get paint() { 18897 return getPaint$4(); 18898 }, 18899 get layout() { 18900 return getLayout$3(); 18901 } 18902}; 18903//#endregion 18904//#region src/style/style_layer/fill_style_layer.ts 18905const isFillStyleLayer = (layer) => layer.type === "fill"; 18906var FillStyleLayer = class extends StyleLayer { 18907 constructor(layer, globalState) { 18908 super(layer, fill_style_layer_properties_g_default, globalState); 18909 } 18910 recalculate(parameters, availableImages) { 18911 super.recalculate(parameters, availableImages); 18912 const outlineColor = this.paint._values["fill-outline-color"]; 18913 if (outlineColor.value.kind === "constant" && outlineColor.value.value === void 0) this.paint._values["fill-outline-color"] = this.paint._values["fill-color"]; 18914 } 18915 createBucket(parameters) { 18916 return new FillBucket(parameters); 18917 } 18918 queryRadius() { 18919 return translateDistance(this.paint.get("fill-translate")); 18920 } 18921 queryIntersectsFeature({ queryGeometry, geometry, transform, pixelsToTileUnits }) { 18922 return polygonIntersectsMultiPolygon(translate(queryGeometry, this.paint.get("fill-translate"), this.paint.get("fill-translate-anchor"), -transform.bearingInRadians, pixelsToTileUnits), geometry); 18923 } 18924 isTileClipped() { 18925 return true; 18926 } 18927}; 18928//#endregion 18929//#region src/data/bucket/fill_extrusion_attributes.ts 18930const layout$3 = createLayout([{ 18931 name: "a_pos", 18932 components: 2, 18933 type: "Int16" 18934}, { 18935 name: "a_normal_ed", 18936 components: 4, 18937 type: "Int16" 18938}], 4); 18939const centroidAttributes = createLayout([{ 18940 name: "a_centroid", 18941 components: 2, 18942 type: "Int16" 18943}], 4); 18944const members$2 = layout$3.members; 18945layout$3.size; 18946layout$3.alignment; 18947//#endregion 18948//#region src/geo/bounds.ts 18949/** A 2-d bounding box covering an X and Y range. */ 18950var Bounds = class Bounds { 18951 constructor() { 18952 this.minX = Infinity; 18953 this.maxX = -Infinity; 18954 this.minY = Infinity; 18955 this.maxY = -Infinity; 18956 } 18957 /** 18958 * Expands this bounding box to include point. 18959 * 18960 * @param point - The point to include in this bounding box 18961 * @returns This mutated bounding box 18962 */ 18963 extend(point) { 18964 this.minX = Math.min(this.minX, point.x); 18965 this.minY = Math.min(this.minY, point.y); 18966 this.maxX = Math.max(this.maxX, point.x); 18967 this.maxY = Math.max(this.maxY, point.y); 18968 return this; 18969 } 18970 /** 18971 * Expands this bounding box by a fixed amount in each direction. 18972 * 18973 * @param amount - The amount to expand the box by, or contract if negative 18974 * @returns This mutated bounding box 18975 */ 18976 expandBy(amount) { 18977 this.minX -= amount; 18978 this.minY -= amount; 18979 this.maxX += amount; 18980 this.maxY += amount; 18981 if (this.minX > this.maxX || this.minY > this.maxY) { 18982 this.minX = Infinity; 18983 this.maxX = -Infinity; 18984 this.minY = Infinity; 18985 this.maxY = -Infinity; 18986 } 18987 return this; 18988 } 18989 /** 18990 * Shrinks this bounding box by a fixed amount in each direction. 18991 * 18992 * @param amount - The amount to shrink the box by 18993 * @returns This mutated bounding box 18994 */ 18995 shrinkBy(amount) { 18996 return this.expandBy(-amount); 18997 } 18998 /** 18999 * Returns a new bounding box that contains all of the corners of this bounding 19000 * box with a transform applied. Does not modify this bounding box. 19001 * 19002 * @param fn - The function to apply to each corner 19003 * @returns A new bounding box containing all of the mapped points. 19004 */ 19005 map(fn) { 19006 const result = new Bounds(); 19007 result.extend(fn(new Point(this.minX, this.minY))); 19008 result.extend(fn(new Point(this.maxX, this.minY))); 19009 result.extend(fn(new Point(this.minX, this.maxY))); 19010 result.extend(fn(new Point(this.maxX, this.maxY))); 19011 return result; 19012 } 19013 /** 19014 * Creates a new bounding box that includes all points provided. 19015 * 19016 * @param points - The points to include inside the bounding box 19017 * @returns The new bounding box 19018 */ 19019 static fromPoints(points) { 19020 const result = new Bounds(); 19021 for (const p of points) result.extend(p); 19022 return result; 19023 } 19024 contains(point) { 19025 return point.x >= this.minX && point.x <= this.maxX && point.y >= this.minY && point.y <= this.maxY; 19026 } 19027 empty() { 19028 return this.minX > this.maxX; 19029 } 19030 width() { 19031 return this.maxX - this.minX; 19032 } 19033 height() { 19034 return this.maxY - this.minY; 19035 } 19036 covers(other) { 19037 return !this.empty() && !other.empty() && other.minX >= this.minX && other.maxX <= this.maxX && other.minY >= this.minY && other.maxY <= this.maxY; 19038 } 19039 intersects(other) { 19040 return !this.empty() && !other.empty() && other.minX <= this.maxX && other.maxX >= this.minX && other.minY <= this.maxY && other.maxY >= this.minY; 19041 } 19042}; 19043//#endregion 19044//#region src/data/extent_bounds.ts 19045/** 19046* The bounding box covering the entire extent of a tile. 19047*/ 19048const EXTENT_BOUNDS = Bounds.fromPoints([new Point(0, 0), new Point(EXTENT$1, EXTENT$1)]); 19049/** 19050* Whether an edge runs along one of the lines the tile was cut out of the world at. Clipping happens 19051* on the buffer rectangle, outside the tile, so an axis parallel edge out there belongs to the cut 19052* rather than to the feature. Such an edge is shared with the neighbouring tile, which cuts the same 19053* feature somewhere else, so geometry derived from it has to stay identical in both tiles. 19054* @param p1 - First vertex of the edge 19055* @param p2 - Second vertex of the edge 19056* @returns True when the edge lies on a clip line. 19057*/ 19058function isBoundaryEdge(p1, p2) { 19059 return p1.x === p2.x && (p1.x < 0 || p1.x > 8192) || p1.y === p2.y && (p1.y < 0 || p1.y > 8192); 19060} 19061/** 19062* Whether a ring lies completely off one side of the tile, and so cannot contribute a visible pixel. 19063* @param ring - Ring to test 19064* @returns True when every vertex is beyond the same edge of the tile. 19065*/ 19066function isEntirelyOutside(ring) { 19067 return ring.every((p) => p.x < 0) || ring.every((p) => p.x > 8192) || ring.every((p) => p.y < 0) || ring.every((p) => p.y > 8192); 19068} 19069//#endregion 19070//#region node_modules/@mapbox/vector-tile/index.js 19071/** @import {PbfReader} from 'pbf' */ 19072/** @import {Feature} from 'geojson' */ 19073var VectorTileFeature = class { 19074 /** 19075 * @param {PbfReader} pbf 19076 * @param {number} end 19077 * @param {number} extent 19078 * @param {string[]} keys 19079 * @param {(number | string | boolean)[]} values 19080 */ 19081 constructor(pbf, end, extent, keys, values) { 19082 /** @type {Record<string, number | string | boolean>} */ 19083 this.properties = Object.create(null); 19084 this.extent = extent; 19085 /** @type {0 | 1 | 2 | 3} */ 19086 this.type = 0; 19087 /** @type {number | undefined} */ 19088 this.id = void 0; 19089 /** @private */ 19090 this._pbf = pbf; 19091 /** @private */ 19092 this._geometry = -1; 19093 /** @private */ 19094 this._keys = keys; 19095 /** @private */ 19096 this._values = values; 19097 while (pbf.pos < end) { 19098 const tag = pbf.readVarint(); 19099 if (tag === 8) this.id = pbf.readVarint(); 19100 else if (tag === 18) { 19101 const tagsEnd = pbf.readVarint() + pbf.pos; 19102 while (pbf.pos < tagsEnd) { 19103 const key = keys[pbf.readVarint()]; 19104 const value = values[pbf.readVarint()]; 19105 this.properties[key] = value; 19106 } 19107 } else if (tag === 24) this.type = pbf.readVarint(); 19108 else if (tag === 34) { 19109 this._geometry = pbf.pos; 19110 pbf.skip(tag); 19111 } else pbf.skip(tag); 19112 } 19113 } 19114 loadGeometry() { 19115 if (this._geometry < 0) throw new Error("feature has no geometry"); 19116 const pbf = this._pbf; 19117 pbf.pos = this._geometry; 19118 const end = pbf.readVarint() + pbf.pos; 19119 /** @type Point[][] */ 19120 const lines = []; 19121 /** @type Point[] | undefined */ 19122 let line; 19123 let cmd = 1; 19124 let length = 0; 19125 let x = 0; 19126 let y = 0; 19127 while (pbf.pos < end) { 19128 if (length <= 0) { 19129 const cmdLen = pbf.readVarint(); 19130 cmd = cmdLen & 7; 19131 length = cmdLen >> 3; 19132 if (length === 0) continue; 19133 } 19134 length--; 19135 if (cmd === 1) { 19136 x += pbf.readSVarint(); 19137 y += pbf.readSVarint(); 19138 if (line) lines.push(line); 19139 line = [new Point(x, y)]; 19140 } else if (cmd === 2) { 19141 x += pbf.readSVarint(); 19142 y += pbf.readSVarint(); 19143 if (line) line.push(new Point(x, y)); 19144 } else if (cmd === 7) { 19145 if (line) line.push(line[0].clone()); 19146 } else throw new Error(`unknown command ${cmd}`); 19147 } 19148 if (line) lines.push(line); 19149 return lines; 19150 } 19151 bbox() { 19152 if (this._geometry < 0) throw new Error("feature has no geometry"); 19153 const pbf = this._pbf; 19154 pbf.pos = this._geometry; 19155 const end = pbf.readVarint() + pbf.pos; 19156 let cmd = 1, length = 0, x = 0, y = 0, x1 = Infinity, x2 = -Infinity, y1 = Infinity, y2 = -Infinity; 19157 while (pbf.pos < end) { 19158 if (length <= 0) { 19159 const cmdLen = pbf.readVarint(); 19160 cmd = cmdLen & 7; 19161 length = cmdLen >> 3; 19162 if (length === 0) continue; 19163 } 19164 length--; 19165 if (cmd === 1 || cmd === 2) { 19166 x += pbf.readSVarint(); 19167 y += pbf.readSVarint(); 19168 if (x < x1) x1 = x; 19169 if (x > x2) x2 = x; 19170 if (y < y1) y1 = y; 19171 if (y > y2) y2 = y; 19172 } else if (cmd !== 7) throw new Error(`unknown command ${cmd}`); 19173 } 19174 return [ 19175 x1, 19176 y1, 19177 x2, 19178 y2 19179 ]; 19180 } 19181 /** 19182 * @param {number} x 19183 * @param {number} y 19184 * @param {number} z 19185 * @return {Feature} 19186 */ 19187 toGeoJSON(x, y, z) { 19188 const size = this.extent * Math.pow(2, z), x0 = this.extent * x, y0 = this.extent * y, vtCoords = this.loadGeometry(); 19189 /** @param {Point} p */ 19190 function projectPoint(p) { 19191 return [(p.x + x0) * 360 / size - 180, 360 / Math.PI * Math.atan(Math.exp((1 - (p.y + y0) * 2 / size) * Math.PI)) - 90]; 19192 } 19193 /** @param {Point[]} line */ 19194 function projectLine(line) { 19195 return line.map(projectPoint); 19196 } 19197 /** @type {Feature["geometry"]} */ 19198 let geometry; 19199 if (this.type === 1) { 19200 const points = []; 19201 for (const line of vtCoords) points.push(line[0]); 19202 const coordinates = projectLine(points); 19203 geometry = points.length === 1 ? { 19204 type: "Point", 19205 coordinates: coordinates[0] 19206 } : { 19207 type: "MultiPoint", 19208 coordinates 19209 }; 19210 } else if (this.type === 2) { 19211 const coordinates = vtCoords.map(projectLine); 19212 geometry = coordinates.length === 1 ? { 19213 type: "LineString", 19214 coordinates: coordinates[0] 19215 } : { 19216 type: "MultiLineString", 19217 coordinates 19218 }; 19219 } else if (this.type === 3) { 19220 const polygons = classifyRings(vtCoords); 19221 const coordinates = []; 19222 for (const polygon of polygons) coordinates.push(polygon.map(projectLine)); 19223 geometry = coordinates.length === 1 ? { 19224 type: "Polygon", 19225 coordinates: coordinates[0] 19226 } : { 19227 type: "MultiPolygon", 19228 coordinates 19229 }; 19230 } else throw new Error("unknown feature type"); 19231 /** @type {Feature} */ 19232 const result = { 19233 type: "Feature", 19234 geometry, 19235 properties: this.properties 19236 }; 19237 if (this.id != null) result.id = this.id; 19238 return result; 19239 } 19240}; 19241/** @type {['Unknown', 'Point', 'LineString', 'Polygon']} */ 19242VectorTileFeature.types = [ 19243 "Unknown", 19244 "Point", 19245 "LineString", 19246 "Polygon" 19247]; 19248/** classifies an array of rings into polygons with outer rings and holes 19249* @param {Point[][]} rings 19250*/ 19251function classifyRings(rings) { 19252 const len = rings.length; 19253 if (len <= 1) return [rings]; 19254 const polygons = []; 19255 let polygon, ccw; 19256 for (let i = 0; i < len; i++) { 19257 const area = signedArea(rings[i]); 19258 if (area === 0) continue; 19259 if (ccw === void 0) ccw = area < 0; 19260 if (ccw === area < 0) { 19261 if (polygon) polygons.push(polygon); 19262 polygon = [rings[i]]; 19263 } else if (polygon) polygon.push(rings[i]); 19264 } 19265 if (polygon) polygons.push(polygon); 19266 return polygons; 19267} 19268/** @param {Point[]} ring */ 19269function signedArea(ring) { 19270 let sum = 0; 19271 for (let i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) { 19272 p1 = ring[i]; 19273 p2 = ring[j]; 19274 sum += (p2.x - p1.x) * (p1.y + p2.y); 19275 } 19276 return sum; 19277} 19278var VectorTileLayer = class { 19279 /** 19280 * @param {PbfReader} pbf 19281 * @param {number} [end] 19282 */ 19283 constructor(pbf, end) { 19284 this.version = 1; 19285 this.name = ""; 19286 this.extent = 4096; 19287 this.length = 0; 19288 /** @private */ 19289 this._pbf = pbf; 19290 /** @private 19291 * @type {string[]} */ 19292 this._keys = []; 19293 /** @private 19294 * @type {(number | string | boolean)[]} */ 19295 this._values = []; 19296 /** @private 19297 * @type {number[]} */ 19298 this._features = []; 19299 if (end === void 0) end = pbf.length; 19300 while (pbf.pos < end) { 19301 const tag = pbf.readVarint(); 19302 if (tag === 10) this.name = pbf.readString(); 19303 else if (tag === 18) { 19304 this._features.push(pbf.pos); 19305 pbf.skip(tag); 19306 } else if (tag === 26) this._keys.push(pbf.readString()); 19307 else if (tag === 34) this._values.push(readValueMessage(pbf)); 19308 else if (tag === 40) this.extent = pbf.readVarint(); 19309 else if (tag === 120) this.version = pbf.readVarint(); 19310 else pbf.skip(tag); 19311 } 19312 this.length = this._features.length; 19313 } 19314 /** return feature `i` from this layer as a `VectorTileFeature` 19315 * @param {number} i 19316 */ 19317 feature(i) { 19318 if (i < 0 || i >= this._features.length) throw new Error("feature index out of bounds"); 19319 this._pbf.pos = this._features[i]; 19320 const end = this._pbf.readVarint() + this._pbf.pos; 19321 return new VectorTileFeature(this._pbf, end, this.extent, this._keys, this._values); 19322 } 19323}; 19324/** 19325* @param {PbfReader} pbf 19326*/ 19327function readValueMessage(pbf) { 19328 let value = null; 19329 const end = pbf.readVarint() + pbf.pos; 19330 while (pbf.pos < end) { 19331 const tag = pbf.readVarint(); 19332 value = tag === 10 ? pbf.readString() : tag === 21 ? pbf.readFloat() : tag === 25 ? pbf.readDouble() : tag === 32 ? pbf.readVarint(true) : tag === 40 ? pbf.readVarint() : tag === 48 ? pbf.readSVarint() : tag === 56 ? pbf.readBoolean() : (pbf.skip(tag), null); 19333 } 19334 if (value == null) throw new Error("unknown feature value"); 19335 return value; 19336} 19337var VectorTile = class { 19338 /** 19339 * @param {PbfReader} pbf 19340 * @param {number} [end] 19341 */ 19342 constructor(pbf, end = pbf.length) { 19343 /** @type {Record<string, VectorTileLayer>} */ 19344 const layers = Object.create(null); 19345 while (pbf.pos < end) { 19346 const tag = pbf.readVarint(); 19347 if (tag === 26) { 19348 const layer = new VectorTileLayer(pbf, pbf.readVarint() + pbf.pos); 19349 if (layer.length) layers[layer.name] = layer; 19350 } else pbf.skip(tag); 19351 } 19352 this.layers = layers; 19353 } 19354}; 19355//#endregion 19356//#region src/geo/lng_lat.ts 19357const earthRadius = 6371008.8; 19358/** 19359* A `LngLat` object represents a given longitude and latitude coordinate, measured in degrees. 19360* These coordinates are based on the [WGS84 (EPSG:4326) standard](https://en.wikipedia.org/wiki/World_Geodetic_System#WGS84). 19361* 19362* MapLibre GL JS uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match the 19363* [GeoJSON specification](https://tools.ietf.org/html/rfc7946). 19364* 19365* Note that any MapLibre GL JS method that accepts a `LngLat` object as an argument or option 19366* can also accept an `Array` of two numbers and will perform an implicit conversion. 19367* This flexible type is documented as {@link LngLatLike}. 19368* 19369* @group Geography and Geometry 19370* 19371* @example 19372* ```ts 19373* let ll = new LngLat(-123.9749, 40.7736); 19374* ll.lng; // = -123.9749 19375* ``` 19376* @see [Get coordinates of the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/get-coordinates-of-the-mouse-pointer/) 19377*/ 19378var LngLat = class LngLat { 19379 /** 19380 * @param lng - Longitude, measured in degrees. 19381 * @param lat - Latitude, measured in degrees. 19382 */ 19383 constructor(lng, lat) { 19384 if (isNaN(lng) || isNaN(lat)) throw new Error(`Invalid LngLat object: (${lng}, ${lat})`); 19385 this.lng = +lng; 19386 this.lat = +lat; 19387 if (this.lat > 90 || this.lat < -90) throw new Error("Invalid LngLat latitude value: must be between -90 and 90"); 19388 } 19389 /** 19390 * Returns a new `LngLat` object whose longitude is wrapped to the range (-180, 180). 19391 * 19392 * @returns The wrapped `LngLat` object. 19393 * @example 19394 * ```ts 19395 * let ll = new LngLat(286.0251, 40.7736); 19396 * let wrapped = ll.wrap(); 19397 * wrapped.lng; // = -73.9749 19398 * ``` 19399 */ 19400 wrap() { 19401 return new LngLat(wrap$1(this.lng, -180, 180), this.lat); 19402 } 19403 /** 19404 * Returns the coordinates represented as an array of two numbers. 19405 * 19406 * @returns The coordinates represented as an array of longitude and latitude. 19407 * @example 19408 * ```ts 19409 * let ll = new LngLat(-73.9749, 40.7736); 19410 * ll.toArray(); // = [-73.9749, 40.7736] 19411 * ``` 19412 */ 19413 toArray() { 19414 return [this.lng, this.lat]; 19415 } 19416 /** 19417 * Returns the coordinates represent as a string. 19418 * 19419 * @returns The coordinates represented as a string of the format `'LngLat(lng, lat)'`. 19420 * @example 19421 * ```ts 19422 * let ll = new LngLat(-73.9749, 40.7736); 19423 * ll.toString(); // = "LngLat(-73.9749, 40.7736)" 19424 * ``` 19425 */ 19426 toString() { 19427 return `LngLat(${this.lng}, ${this.lat})`; 19428 } 19429 /** 19430 * Returns the approximate distance between a pair of coordinates in meters 19431 * Uses the Haversine Formula (from R.W. Sinnott, "Virtues of the Haversine", Sky and Telescope, vol. 68, no. 2, 1984, p. 159) 19432 * 19433 * @param lngLat - coordinates to compute the distance to 19434 * @returns Distance in meters between the two coordinates. 19435 * @example 19436 * ```ts 19437 * let new_york = new LngLat(-74.0060, 40.7128); 19438 * let los_angeles = new LngLat(-118.2437, 34.0522); 19439 * new_york.distanceTo(los_angeles); // = 3935751.690893987, "true distance" using a non-spherical approximation is ~3966km 19440 * ``` 19441 */ 19442 distanceTo(lngLat) { 19443 const rad = Math.PI / 180; 19444 const lat1 = this.lat * rad; 19445 const lat2 = lngLat.lat * rad; 19446 const a = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos((lngLat.lng - this.lng) * rad); 19447 return earthRadius * Math.acos(Math.min(a, 1)); 19448 } 19449 /** 19450 * Converts an array of two numbers or an object with `lng` and `lat` or `lon` and `lat` properties 19451 * to a `LngLat` object. 19452 * 19453 * If a `LngLat` object is passed in, the function returns it unchanged. 19454 * 19455 * @param input - An array of two numbers or object to convert, or a `LngLat` object to return. 19456 * @returns A new `LngLat` object, if a conversion occurred, or the original `LngLat` object. 19457 * @example 19458 * ```ts 19459 * let arr = [-73.9749, 40.7736]; 19460 * let ll = LngLat.convert(arr); 19461 * ll; // = LngLat {lng: -73.9749, lat: 40.7736} 19462 * ``` 19463 */ 19464 static convert(input) { 19465 if (input instanceof LngLat) return input; 19466 if (Array.isArray(input) && (input.length === 2 || input.length === 3)) return new LngLat(Number(input[0]), Number(input[1])); 19467 if (!Array.isArray(input) && typeof input === "object" && input !== null) return new LngLat(Number("lng" in input ? input.lng : input.lon), Number(input.lat)); 19468 throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: <lng>, lat: <lat>}, an object {lon: <lng>, lat: <lat>}, or an array of [<lng>, <lat>]"); 19469 } 19470}; 19471//#endregion 19472//#region src/geo/mercator_coordinate.ts 19473const earthCircumference = 2 * Math.PI * earthRadius; 19474function circumferenceAtLatitude(latitude) { 19475 return earthCircumference * Math.cos(latitude * Math.PI / 180); 19476} 19477function mercatorXfromLng(lng) { 19478 return (180 + lng) / 360; 19479} 19480function mercatorYfromLat(lat) { 19481 return (180 - 180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360))) / 360; 19482} 19483function mercatorZfromAltitude(altitude, lat) { 19484 return altitude / circumferenceAtLatitude(lat); 19485} 19486function lngFromMercatorX(x) { 19487 return x * 360 - 180; 19488} 19489function latFromMercatorY(y) { 19490 const y2 = 180 - y * 360; 19491 return 360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90; 19492} 19493function altitudeFromMercatorZ(z, y) { 19494 return z * circumferenceAtLatitude(latFromMercatorY(y)); 19495} 19496/** 19497* Determine the Mercator scale factor for a given latitude, see 19498* https://en.wikipedia.org/wiki/Mercator_projection#Scale_factor 19499* 19500* At the equator the scale factor will be 1, which increases at higher latitudes. 19501* 19502* @param lat - Latitude 19503* @returns scale factor 19504*/ 19505function mercatorScale(lat) { 19506 return 1 / Math.cos(lat * Math.PI / 180); 19507} 19508/** 19509* A `MercatorCoordinate` object represents a projected three dimensional position. 19510* 19511* `MercatorCoordinate` uses the web mercator projection ([EPSG:3857](https://epsg.io/3857)) with slightly different units: 19512* 19513* - the size of 1 unit is the width of the projected world instead of the "mercator meter" 19514* - the origin of the coordinate space is at the north-west corner instead of the middle 19515* 19516* For example, `MercatorCoordinate(0, 0, 0)` is the north-west corner of the mercator world and 19517* `MercatorCoordinate(1, 1, 0)` is the south-east corner. If you are familiar with 19518* [vector tiles](https://github.com/mapbox/vector-tile-spec) it may be helpful to think 19519* of the coordinate space as the `0/0/0` tile with an extent of `1`. 19520* 19521* The `z` dimension of `MercatorCoordinate` is conformal. A cube in the mercator coordinate space would be rendered as a cube. 19522* 19523* @group Geography and Geometry 19524* 19525* @example 19526* ```ts 19527* let nullIsland = new MercatorCoordinate(0.5, 0.5, 0); 19528* ``` 19529* @see [Add a custom style layer](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-custom-style-layer/) 19530* @see [Add a 3D model using three.js](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-3d-model-using-threejs/) 19531* @see [Add a simple custom layer on a globe](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-simple-custom-layer-on-a-globe/) 19532*/ 19533var MercatorCoordinate = class MercatorCoordinate { 19534 /** 19535 * @param x - The x component of the position. 19536 * @param y - The y component of the position. 19537 * @param z - The z component of the position. 19538 */ 19539 constructor(x, y, z = 0) { 19540 this.x = +x; 19541 this.y = +y; 19542 this.z = +z; 19543 } 19544 /** 19545 * Project a `LngLat` to a `MercatorCoordinate`. 19546 * 19547 * @param lngLatLike - The location to project. 19548 * @param altitude - The altitude in meters of the position. 19549 * @returns The projected mercator coordinate. 19550 * @example 19551 * ```ts 19552 * let coord = MercatorCoordinate.fromLngLat({ lng: 0, lat: 0}, 0); 19553 * coord; // MercatorCoordinate(0.5, 0.5, 0) 19554 * ``` 19555 */ 19556 static fromLngLat(lngLatLike, altitude = 0) { 19557 const lngLat = LngLat.convert(lngLatLike); 19558 return new MercatorCoordinate(mercatorXfromLng(lngLat.lng), mercatorYfromLat(lngLat.lat), mercatorZfromAltitude(altitude, lngLat.lat)); 19559 } 19560 /** 19561 * Returns the `LngLat` for the coordinate. 19562 * 19563 * @returns The `LngLat` object. 19564 * @example 19565 * ```ts 19566 * let coord = new MercatorCoordinate(0.5, 0.5, 0); 19567 * let lngLat = coord.toLngLat(); // LngLat(0, 0) 19568 * ``` 19569 */ 19570 toLngLat() { 19571 return new LngLat(lngFromMercatorX(this.x), latFromMercatorY(this.y)); 19572 } 19573 /** 19574 * Returns the altitude in meters of the coordinate. 19575 * 19576 * @returns The altitude in meters. 19577 * @example 19578 * ```ts 19579 * let coord = new MercatorCoordinate(0, 0, 0.02); 19580 * coord.toAltitude(); // 6914.281956295339 19581 * ``` 19582 */ 19583 toAltitude() { 19584 return altitudeFromMercatorZ(this.z, this.y); 19585 } 19586 /** 19587 * Returns the distance of 1 meter in `MercatorCoordinate` units at this latitude. 19588 * 19589 * For coordinates in real world units using meters, this naturally provides the scale 19590 * to transform into `MercatorCoordinate`s. 19591 * 19592 * @returns Distance of 1 meter in `MercatorCoordinate` units. 19593 */ 19594 meterInMercatorCoordinateUnits() { 19595 return 1 / earthCircumference * mercatorScale(latFromMercatorY(this.y)); 19596 } 19597}; 19598//#endregion 19599//#region src/geo/projection/mercator_utils.ts 19600const maxMercatorHorizonAngle = 89.25; 19601/** 19602* Returns mercator coordinates in range 0..1 for given coordinates inside a specified tile. 19603* @param inTileX - X coordinate in tile units - range [0..EXTENT]. 19604* @param inTileY - Y coordinate in tile units - range [0..EXTENT]. 19605* @param canonicalTileID - Tile canonical ID - mercator X, Y and zoom. 19606* @returns Mercator coordinates of the specified point in range [0..1]. 19607*/ 19608function tileCoordinatesToMercatorCoordinates(inTileX, inTileY, canonicalTileID) { 19609 const scale = 1 / (1 << canonicalTileID.z); 19610 return new MercatorCoordinate(inTileX / EXTENT$1 * scale + canonicalTileID.x * scale, inTileY / EXTENT$1 * scale + canonicalTileID.y * scale); 19611} 19612/** 19613* Returns LngLat for given in-tile coordinates and tile ID. 19614* @param inTileX - X coordinate in tile units - range [0..EXTENT]. 19615* @param inTileY - Y coordinate in tile units - range [0..EXTENT]. 19616* @param canonicalTileID - Tile canonical ID - mercator X, Y and zoom. 19617*/ 19618function tileCoordinatesToLocation(inTileX, inTileY, canonicalTileID) { 19619 return tileCoordinatesToMercatorCoordinates(inTileX, inTileY, canonicalTileID).toLngLat(); 19620} 19621/** 19622* Convert from LngLat to world coordinates (Mercator coordinates scaled by world size). 19623* @param worldSize - Mercator world size computed from zoom level and tile size. 19624* @param lnglat - The location to convert. 19625* @returns Point 19626*/ 19627function projectToWorldCoordinates(worldSize, lnglat) { 19628 const lat = clamp$2(lnglat.lat, -85.051129, MAX_VALID_LATITUDE); 19629 return new Point(mercatorXfromLng(lnglat.lng) * worldSize, mercatorYfromLat(lat) * worldSize); 19630} 19631/** 19632* Convert from world coordinates (mercator coordinates scaled by world size) to LngLat. 19633* @param worldSize - Mercator world size computed from zoom level and tile size. 19634* @param point - World coordinate. 19635* @returns LngLat 19636*/ 19637function unprojectFromWorldCoordinates(worldSize, point) { 19638 return new MercatorCoordinate(point.x / worldSize, point.y / worldSize).toLngLat(); 19639} 19640/** 19641* Calculate pixel height of the visible horizon in relation to map-center (e.g. height/2), 19642* multiplied by a static factor to simulate the earth-radius. 19643* The calculated value is the horizontal line from the camera-height to sea-level. 19644* @returns Horizon above center in pixels. 19645*/ 19646function getMercatorHorizon(transform) { 19647 return transform.cameraToCenterDistance * Math.min(Math.tan(degreesToRadians(90 - transform.pitch)) * .85, Math.tan(degreesToRadians(maxMercatorHorizonAngle - transform.pitch))); 19648} 19649function calculateTileMatrix(unwrappedTileID, worldSize) { 19650 const canonical = unwrappedTileID.canonical; 19651 const scale = worldSize / zoomScale(canonical.z); 19652 const unwrappedX = canonical.x + Math.pow(2, canonical.z) * unwrappedTileID.wrap; 19653 const worldMatrix = /* @__PURE__ */ new Float64Array(16); 19654 identity$2(worldMatrix); 19655 translate$2(worldMatrix, worldMatrix, [ 19656 unwrappedX * scale, 19657 canonical.y * scale, 19658 0 19659 ]); 19660 scale$5(worldMatrix, worldMatrix, [ 19661 scale / EXTENT$1, 19662 scale / EXTENT$1, 19663 1 19664 ]); 19665 return worldMatrix; 19666} 19667function cameraMercatorCoordinateFromCenterAndRotation(center, elevation, pitch, bearing, distance) { 19668 const centerMercator = MercatorCoordinate.fromLngLat(center, elevation); 19669 const dMercator = distance * mercatorZfromAltitude(1, center.lat); 19670 const { x, y, z } = cameraDirectionFromPitchBearing(pitch, bearing); 19671 const dxMercator = dMercator * -x; 19672 const dyMercator = dMercator * -y; 19673 const dzMercator = dMercator * z; 19674 return new MercatorCoordinate(centerMercator.x + dxMercator, centerMercator.y + dyMercator, centerMercator.z + dzMercator); 19675} 19676/** 19677* Returns the position of the camera in mercator coordinates, with its altitude in `z`. 19678* Computed from the center, pitch, bearing and camera distance, so it holds for any projection. 19679*/ 19680function cameraMercatorCoordinate(transform) { 19681 const pixelPerMeter = mercatorZfromAltitude(1, transform.center.lat) * transform.worldSize; 19682 return cameraMercatorCoordinateFromCenterAndRotation(transform.center, transform.elevation, transform.pitch, transform.bearing, transform.cameraToCenterDistance / pixelPerMeter); 19683} 19684function cameraDirectionFromPitchBearing(pitch, bearing) { 19685 const pitchRadians = degreesToRadians(pitch); 19686 const bearingRadians = degreesToRadians(bearing); 19687 const z = Math.cos(-pitchRadians); 19688 const h = Math.sin(pitchRadians); 19689 return { 19690 x: h * Math.sin(bearingRadians), 19691 y: -h * Math.cos(bearingRadians), 19692 z 19693 }; 19694} 19695//#endregion 19696//#region src/data/bucket/round_polygon_corners.ts 19697/** 19698* Rounds polygon corners by calculating arc points at each corner vertex. 19699* A distance of zero or less disables rounding. 19700* @param polygon - Collection of polygon rings (outer ring and hole rings) 19701* @param distanceInTileUnits - Corner rounding distance in tile units, as returned by {@link getTileUnitsForMeters} 19702*/ 19703function roundPolygonCornersIfNeeded(polygon, distanceInTileUnits) { 19704 if (distanceInTileUnits <= 0 || !polygon || polygon.length === 0) return polygon; 19705 return polygon.map((ring) => roundRing(ring, distanceInTileUnits)); 19706} 19707/** 19708* Converts a distance in meters to tile units at the center of the given tile. The result only 19709* depends on the tile, so it is computed once per tile rather than once per feature. 19710* @param distanceInMeters - Distance in meters 19711* @param canonical - Canonical tile ID used for meter to tile unit conversion 19712*/ 19713function getTileUnitsForMeters(distanceInMeters, canonical) { 19714 const centerLocation = tileCoordinatesToLocation(EXTENT$1 / 2, EXTENT$1 / 2, canonical); 19715 const meterInMercator = MercatorCoordinate.fromLngLat(centerLocation).meterInMercatorCoordinateUnits(); 19716 const tileUnitsPerMercator = (1 << canonical.z) * EXTENT$1; 19717 return distanceInMeters * meterInMercator * tileUnitsPerMercator; 19718} 19719/** 19720* Rounds the corners of a single ring. 19721* 19722* Corners that tile clipping created are left sharp: they belong to the cut rather than to the 19723* feature, and the neighbouring tile cuts the same feature elsewhere, so rounding them would leave 19724* the two halves out of step. Every vertex ends up on the integer tile grid, because triangulation, 19725* subdivision and the vertex buffers snap and deduplicate vertices there - arcs finer than a tile 19726* unit would otherwise be merged only after they were triangulated, turning the mesh into spikes. 19727* 19728* A ring that collapses into fewer than three distinct vertices is returned unchanged. 19729* @param ring - Ring to round, closed or open 19730* @param distanceInTileUnits - Corner rounding distance, already converted to tile units 19731*/ 19732function roundRing(ring, distanceInTileUnits) { 19733 if (!ring || ring.length < 3) return ring; 19734 const isClosed = ring[0].x === ring[ring.length - 1].x && ring[0].y === ring[ring.length - 1].y; 19735 const vertexCount = isClosed ? ring.length - 1 : ring.length; 19736 if (vertexCount < 3) return ring; 19737 const newRing = []; 19738 let previousIsBoundary = isBoundaryEdge(ring[vertexCount - 1], ring[0]); 19739 for (let i = 0; i < vertexCount; i++) { 19740 const previous = ring[(i - 1 + vertexCount) % vertexCount]; 19741 const current = ring[i]; 19742 const next = ring[(i + 1) % vertexCount]; 19743 const nextIsBoundary = isBoundaryEdge(current, next); 19744 if (previousIsBoundary || nextIsBoundary) newRing.push(current.clone()); 19745 else appendRoundCorner(newRing, previous, current, next, distanceInTileUnits); 19746 previousIsBoundary = nextIsBoundary; 19747 } 19748 const snapped = snapToIntegerGrid(newRing); 19749 if (snapped.length < 3) return ring; 19750 if (isClosed) snapped.push(snapped[0].clone()); 19751 return snapped; 19752} 19753/** 19754* Rounds every vertex to the integer tile grid, dropping vertices that collapse onto their neighbour. 19755* The ring is treated as closed, so the wrap-around duplicate is dropped as well. 19756* @param ring - Ring to snap 19757*/ 19758function snapToIntegerGrid(ring) { 19759 const snapped = []; 19760 for (const p of ring) { 19761 const point = p.round(); 19762 const previous = snapped[snapped.length - 1]; 19763 if (previous?.x === point.x && previous?.y === point.y) continue; 19764 snapped.push(point); 19765 } 19766 while (snapped.length > 1 && snapped[0].x === snapped[snapped.length - 1].x && snapped[0].y === snapped[snapped.length - 1].y) snapped.pop(); 19767 return snapped; 19768} 19769/** 19770* Appends the arc that replaces one corner, or the corner itself when it is too shallow or too sharp 19771* to round. 19772* @param newRing - Ring being built, the arc points are appended to it 19773* @param prev - Vertex before the corner 19774* @param current - The corner 19775* @param next - Vertex after the corner 19776* @param distanceInTileUnits - Corner rounding distance, already converted to tile units 19777*/ 19778function appendRoundCorner(newRing, prev, current, next, distanceInTileUnits) { 19779 const ua = prev.sub(current); 19780 const ub = next.sub(current); 19781 const lenA = ua.mag(); 19782 const lenB = ub.mag(); 19783 if (lenA < 1e-6 || lenB < 1e-6) { 19784 newRing.push(current.clone()); 19785 return; 19786 } 19787 ua._div(lenA); 19788 ub._div(lenB); 19789 const dot = ua.x * ub.x + ua.y * ub.y; 19790 if (Math.abs(dot) > Math.cos(5 * Math.PI / 180)) { 19791 newRing.push(current.clone()); 19792 return; 19793 } 19794 const maxEdgeLenPercent = .2; 19795 const r = Math.min(distanceInTileUnits, lenA * maxEdgeLenPercent, lenB * maxEdgeLenPercent); 19796 const tangentA = current.add(ua.mult(r)); 19797 const tangentB = current.add(ub.mult(r)); 19798 const cosHalfTheta = Math.sqrt((1 + dot) / 2); 19799 const center = current.add(ua.add(ub)._unit()._mult(r / cosHalfTheta)); 19800 const sweepAngle = tangentA.sub(center).angleWith(tangentB.sub(center)); 19801 const numSegments = Math.max(2, Math.ceil(Math.abs(sweepAngle) / (Math.PI / 6) - 1e-6)); 19802 for (let s = 0; s <= numSegments; s++) newRing.push(tangentA.rotateAround(sweepAngle * (s / numSegments), center)); 19803} 19804//#endregion 19805//#region src/data/bucket/fill_extrusion_bucket.ts 19806const EARCUT_MAX_RINGS = 500; 19807const FACTOR = Math.pow(2, 13); 19808function addVertex$1(vertexArray, x, y, nx, ny, nz, t, e) { 19809 vertexArray.emplaceBack(x, y, Math.floor(nx * FACTOR) * 2 + t, ny * FACTOR * 2, nz * FACTOR * 2, Math.round(e)); 19810} 19811var FillExtrusionBucket = class { 19812 constructor(options) { 19813 this.zoom = options.zoom; 19814 this.overscaling = options.overscaling; 19815 this.layers = options.layers; 19816 this.layerIds = this.layers.map((layer) => layer.id); 19817 this.index = options.index; 19818 this.hasDependencies = false; 19819 this.layoutVertexArray = new FillExtrusionLayoutArray(); 19820 this.centroidVertexArray = new PosArray(); 19821 this.indexArray = new TriangleIndexArray(); 19822 this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom); 19823 this.segments = new SegmentVector(); 19824 this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); 19825 } 19826 populate(features, options, canonical) { 19827 this.features = []; 19828 this.hasDependencies = hasPattern("fill-extrusion", this.layers, options); 19829 const globalProperties = new EvaluationParameters(this.zoom); 19830 const layer = this.layers[0]; 19831 const roundedCornerDistanceInMeters = layer.layout.get("fill-extrusion-rounded-corner-distance"); 19832 const roundedCornerDistance = roundedCornerDistanceInMeters > 0 ? getTileUnitsForMeters(roundedCornerDistanceInMeters, canonical) : 0; 19833 const needGeometry = layer._featureFilter.needGeometry; 19834 for (const { feature, id, index, sourceLayerIndex } of features) { 19835 const evaluationFeature = toEvaluationFeature(feature, needGeometry); 19836 if (!layer._featureFilter.filter(globalProperties, evaluationFeature, canonical)) continue; 19837 const bucketFeature = { 19838 id, 19839 sourceLayerIndex, 19840 index, 19841 geometry: roundPolygonCornersIfNeeded(needGeometry ? evaluationFeature.geometry : loadGeometry(feature), roundedCornerDistance), 19842 properties: feature.properties, 19843 type: feature.type, 19844 patterns: {} 19845 }; 19846 if (this.hasDependencies) this.features.push(addPatternDependencies("fill-extrusion", this.layers, bucketFeature, { zoom: this.zoom }, options)); 19847 else this.addFeature(bucketFeature, bucketFeature.geometry, index, canonical, {}, options.subdivisionGranularity); 19848 options.featureIndex.insert(feature, bucketFeature.geometry, index, sourceLayerIndex, this.index, true); 19849 } 19850 } 19851 addFeatures({ options, canonical, patternPositions }) { 19852 for (const feature of this.features) { 19853 const { geometry } = feature; 19854 this.addFeature(feature, geometry, feature.index, canonical, patternPositions, options.subdivisionGranularity); 19855 } 19856 } 19857 update(states, vtLayer, imagePositions) { 19858 if (!this.stateDependentLayers.length) return; 19859 this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, { imagePositions }); 19860 } 19861 isEmpty() { 19862 return this.layoutVertexArray.length === 0 && this.centroidVertexArray.length === 0; 19863 } 19864 uploadPending() { 19865 return !this.uploaded || this.programConfigurations.needsUpload; 19866 } 19867 upload(context) { 19868 if (!this.uploaded) { 19869 this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$2); 19870 this.centroidVertexBuffer = context.createVertexBuffer(this.centroidVertexArray, centroidAttributes.members, true); 19871 this.indexBuffer = context.createIndexBuffer(this.indexArray); 19872 } 19873 this.programConfigurations.upload(context); 19874 this.uploaded = true; 19875 } 19876 destroy() { 19877 if (!this.layoutVertexBuffer) return; 19878 this.layoutVertexBuffer.destroy(); 19879 this.indexBuffer.destroy(); 19880 this.programConfigurations.destroy(); 19881 this.segments.destroy(); 19882 this.centroidVertexBuffer.destroy(); 19883 } 19884 addFeature(feature, geometry, index, canonical, imagePositions, subdivisionGranularity) { 19885 for (const polygon of classifyRings$1(geometry, EARCUT_MAX_RINGS)) { 19886 const centroid = { 19887 x: 0, 19888 y: 0, 19889 sampleCount: 0 19890 }; 19891 const oldVertexCount = this.layoutVertexArray.length; 19892 this.processPolygon(centroid, canonical, feature, polygon, subdivisionGranularity); 19893 const addedVertices = this.layoutVertexArray.length - oldVertexCount; 19894 const centroidX = Math.floor(centroid.x / centroid.sampleCount); 19895 const centroidY = Math.floor(centroid.y / centroid.sampleCount); 19896 for (let i = 0; i < addedVertices; i++) this.centroidVertexArray.emplaceBack(centroidX, centroidY); 19897 } 19898 this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, { 19899 imagePositions, 19900 canonical 19901 }); 19902 } 19903 processPolygon(centroid, canonical, feature, polygon, subdivisionGranularity) { 19904 if (polygon.length < 1) return; 19905 if (isEntirelyOutside(polygon[0])) return; 19906 for (const ring of polygon) { 19907 if (ring.length === 0) continue; 19908 accumulatePointsToCentroid(centroid, ring); 19909 } 19910 const segmentReference = { segment: this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray) }; 19911 const granularity = subdivisionGranularity.fill.getGranularityForZoomLevel(canonical.z); 19912 const isPolygon = VectorTileFeature.types[feature.type] === "Polygon"; 19913 for (const ring of polygon) { 19914 if (ring.length === 0) continue; 19915 if (isEntirelyOutside(ring)) continue; 19916 const subdividedRing = subdivideVertexLine(ring, granularity, isPolygon); 19917 this._generateSideFaces(subdividedRing, segmentReference); 19918 } 19919 if (!isPolygon) return; 19920 const subdividedPolygon = subdividePolygon(polygon, canonical, granularity, false); 19921 const vertexArray = this.layoutVertexArray; 19922 fillLargeMeshArrays((x, y) => { 19923 addVertex$1(vertexArray, x, y, 0, 0, 1, 1, 0); 19924 }, this.segments, this.layoutVertexArray, this.indexArray, subdividedPolygon.verticesFlattened, subdividedPolygon.indicesTriangles); 19925 } 19926 /** 19927 * Generates side faces for the supplied geometry. Assumes `geometry` to be a line string, like the output of {@link subdivideVertexLine}. 19928 * For rings, it is assumed that the first and last vertex of `geometry` are equal. 19929 */ 19930 _generateSideFaces(geometry, segmentReference) { 19931 let edgeDistance = 0; 19932 for (let p = 1; p < geometry.length; p++) { 19933 const p1 = geometry[p]; 19934 const p2 = geometry[p - 1]; 19935 if (isBoundaryEdge(p1, p2)) continue; 19936 if (segmentReference.segment.vertexLength + 4 > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) segmentReference.segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray); 19937 const perp = p1.sub(p2)._perp()._unit(); 19938 const dist = p2.dist(p1); 19939 if (edgeDistance + dist > 32768) edgeDistance = 0; 19940 addVertex$1(this.layoutVertexArray, p1.x, p1.y, perp.x, perp.y, 0, 0, edgeDistance); 19941 addVertex$1(this.layoutVertexArray, p1.x, p1.y, perp.x, perp.y, 0, 1, edgeDistance); 19942 edgeDistance += dist; 19943 addVertex$1(this.layoutVertexArray, p2.x, p2.y, perp.x, perp.y, 0, 0, edgeDistance); 19944 addVertex$1(this.layoutVertexArray, p2.x, p2.y, perp.x, perp.y, 0, 1, edgeDistance); 19945 const bottomRight = segmentReference.segment.vertexLength; 19946 this.indexArray.emplaceBack(bottomRight, bottomRight + 2, bottomRight + 1); 19947 this.indexArray.emplaceBack(bottomRight + 1, bottomRight + 2, bottomRight + 3); 19948 segmentReference.segment.vertexLength += 4; 19949 segmentReference.segment.primitiveLength += 2; 19950 } 19951 } 19952}; 19953/** 19954* Accumulates geometry to centroid. Geometry can be either a polygon ring, a line string or a closed line string. 19955* In case of a polygon ring or line ring, the last vertex is ignored if it is the same as the first vertex. 19956*/ 19957function accumulatePointsToCentroid(centroid, geometry) { 19958 for (let i = 0; i < geometry.length; i++) { 19959 const p = geometry[i]; 19960 if (i === geometry.length - 1 && geometry[0].x === p.x && geometry[0].y === p.y) continue; 19961 centroid.x += p.x; 19962 centroid.y += p.y; 19963 centroid.sampleCount++; 19964 } 19965} 19966register("FillExtrusionBucket", FillExtrusionBucket, { omit: ["layers", "features"] }); 19967//#endregion 19968//#region src/style/style_layer/fill_extrusion_style_layer_properties.g.ts 19969let layout$2; 19970const getLayout$2 = () => layout$2 = layout$2 || new Properties({ "fill-extrusion-rounded-corner-distance": new DataConstantProperty(latest["layout_fill-extrusion"]["fill-extrusion-rounded-corner-distance"], "fill-extrusion-rounded-corner-distance") }); 19971let paint$3; 19972const getPaint$3 = () => paint$3 = paint$3 || new Properties({ 19973 "fill-extrusion-opacity": new DataConstantProperty(latest["paint_fill-extrusion"]["fill-extrusion-opacity"], "fill-extrusion-opacity"), 19974 "fill-extrusion-color": new DataDrivenProperty(latest["paint_fill-extrusion"]["fill-extrusion-color"], "fill-extrusion-color"), 19975 "fill-extrusion-translate": new DataConstantProperty(latest["paint_fill-extrusion"]["fill-extrusion-translate"], "fill-extrusion-translate"), 19976 "fill-extrusion-translate-anchor": new DataConstantProperty(latest["paint_fill-extrusion"]["fill-extrusion-translate-anchor"], "fill-extrusion-translate-anchor"), 19977 "fill-extrusion-pattern": new CrossFadedDataDrivenProperty(latest["paint_fill-extrusion"]["fill-extrusion-pattern"], "fill-extrusion-pattern"), 19978 "fill-extrusion-height": new DataDrivenProperty(latest["paint_fill-extrusion"]["fill-extrusion-height"], "fill-extrusion-height"), 19979 "fill-extrusion-base": new DataDrivenProperty(latest["paint_fill-extrusion"]["fill-extrusion-base"], "fill-extrusion-base"), 19980 "fill-extrusion-vertical-gradient": new DataConstantProperty(latest["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"], "fill-extrusion-vertical-gradient") 19981}); 19982var fill_extrusion_style_layer_properties_g_default = { 19983 get paint() { 19984 return getPaint$3(); 19985 }, 19986 get layout() { 19987 return getLayout$2(); 19988 } 19989}; 19990const isFillExtrusionStyleLayer = (layer) => layer.type === "fill-extrusion"; 19991var FillExtrusionStyleLayer = class extends StyleLayer { 19992 constructor(layer, globalState) { 19993 super(layer, fill_extrusion_style_layer_properties_g_default, globalState); 19994 } 19995 createBucket(parameters) { 19996 return new FillExtrusionBucket(parameters); 19997 } 19998 queryRadius() { 19999 return translateDistance(this.paint.get("fill-extrusion-translate")); 20000 } 20001 is3D() { 20002 return true; 20003 } 20004 queryIntersectsFeature({ queryGeometry, feature, featureState, geometry, transform, pixelsToTileUnits, pixelPosMatrix }) { 20005 const translatedPolygon = translate(queryGeometry, this.paint.get("fill-extrusion-translate"), this.paint.get("fill-extrusion-translate-anchor"), -transform.bearingInRadians, pixelsToTileUnits); 20006 const height = this.paint.get("fill-extrusion-height").evaluate(feature, featureState); 20007 const base = this.paint.get("fill-extrusion-base").evaluate(feature, featureState); 20008 const projectedQueryGeometry = projectQueryGeometry(translatedPolygon, pixelPosMatrix, 0); 20009 const projected = projectExtrusion(geometry, base, height, pixelPosMatrix); 20010 const projectedBase = projected[0]; 20011 const projectedTop = projected[1]; 20012 return checkIntersection(projectedBase, projectedTop, projectedQueryGeometry); 20013 } 20014}; 20015function dot(a, b) { 20016 return a.x * b.x + a.y * b.y; 20017} 20018function getIntersectionDistance(projectedQueryGeometry, projectedFace) { 20019 if (projectedQueryGeometry.length === 1) { 20020 let i = 0; 20021 const a = projectedFace[i++]; 20022 let b; 20023 while (!b || a.equals(b)) { 20024 b = projectedFace[i++]; 20025 if (!b) return Infinity; 20026 } 20027 for (; i < projectedFace.length; i++) { 20028 const c = projectedFace[i]; 20029 const p = projectedQueryGeometry[0]; 20030 const ab = b.sub(a); 20031 const ac = c.sub(a); 20032 const ap = p.sub(a); 20033 const dotABAB = dot(ab, ab); 20034 const dotABAC = dot(ab, ac); 20035 const dotACAC = dot(ac, ac); 20036 const dotAPAB = dot(ap, ab); 20037 const dotAPAC = dot(ap, ac); 20038 const denom = dotABAB * dotACAC - dotABAC * dotABAC; 20039 const v = (dotACAC * dotAPAB - dotABAC * dotAPAC) / denom; 20040 const w = (dotABAB * dotAPAC - dotABAC * dotAPAB) / denom; 20041 const u = 1 - v - w; 20042 const distance = a.z * u + b.z * v + c.z * w; 20043 if (isFinite(distance)) return distance; 20044 } 20045 return Infinity; 20046 } else { 20047 let closestDistance = Infinity; 20048 for (const p of projectedFace) closestDistance = Math.min(closestDistance, p.z); 20049 return closestDistance; 20050 } 20051} 20052function checkIntersection(projectedBase, projectedTop, projectedQueryGeometry) { 20053 let closestDistance = Infinity; 20054 if (polygonIntersectsMultiPolygon(projectedQueryGeometry, projectedTop)) closestDistance = getIntersectionDistance(projectedQueryGeometry, projectedTop[0]); 20055 for (let r = 0; r < projectedTop.length; r++) { 20056 const ringTop = projectedTop[r]; 20057 const ringBase = projectedBase[r]; 20058 for (let p = 0; p < ringTop.length - 1; p++) { 20059 const topA = ringTop[p]; 20060 const topB = ringTop[p + 1]; 20061 const baseA = ringBase[p]; 20062 const face = [ 20063 topA, 20064 topB, 20065 ringBase[p + 1], 20066 baseA, 20067 topA 20068 ]; 20069 if (polygonIntersectsPolygon(projectedQueryGeometry, face)) closestDistance = Math.min(closestDistance, getIntersectionDistance(projectedQueryGeometry, face)); 20070 } 20071 } 20072 return closestDistance === Infinity ? false : closestDistance; 20073} 20074function projectExtrusion(geometry, zBase, zTop, m) { 20075 const projectedBase = []; 20076 const projectedTop = []; 20077 const baseXZ = m[8] * zBase; 20078 const baseYZ = m[9] * zBase; 20079 const baseZZ = m[10] * zBase; 20080 const baseWZ = m[11] * zBase; 20081 const topXZ = m[8] * zTop; 20082 const topYZ = m[9] * zTop; 20083 const topZZ = m[10] * zTop; 20084 const topWZ = m[11] * zTop; 20085 for (const r of geometry) { 20086 const ringBase = []; 20087 const ringTop = []; 20088 for (const p of r) { 20089 const x = p.x; 20090 const y = p.y; 20091 const sX = m[0] * x + m[4] * y + m[12]; 20092 const sY = m[1] * x + m[5] * y + m[13]; 20093 const sZ = m[2] * x + m[6] * y + m[14]; 20094 const sW = m[3] * x + m[7] * y + m[15]; 20095 const baseX = sX + baseXZ; 20096 const baseY = sY + baseYZ; 20097 const baseZ = sZ + baseZZ; 20098 const baseW = sW + baseWZ; 20099 const topX = sX + topXZ; 20100 const topY = sY + topYZ; 20101 const topZ = sZ + topZZ; 20102 const topW = sW + topWZ; 20103 const b = new Point(baseX / baseW, baseY / baseW); 20104 b.z = baseZ / baseW; 20105 ringBase.push(b); 20106 const t = new Point(topX / topW, topY / topW); 20107 t.z = topZ / topW; 20108 ringTop.push(t); 20109 } 20110 projectedBase.push(ringBase); 20111 projectedTop.push(ringTop); 20112 } 20113 return [projectedBase, projectedTop]; 20114} 20115function projectQueryGeometry(queryGeometry, pixelPosMatrix, z) { 20116 const projectedQueryGeometry = []; 20117 for (const p of queryGeometry) { 20118 const v = [ 20119 p.x, 20120 p.y, 20121 z, 20122 1 20123 ]; 20124 transformMat4$1(v, v, pixelPosMatrix); 20125 projectedQueryGeometry.push(new Point(v[0] / v[3], v[1] / v[3])); 20126 } 20127 return projectedQueryGeometry; 20128} 20129//#endregion 20130//#region node_modules/@maplibre/geojson-vt/dist/geojson-vt.mjs 20131/** 20132* calculate simplification data using optimized Douglas-Peucker algorithm 20133* @param coords - flat array of coordinates 20134* @param first - index of the first coordinate in the segment 20135* @param last - index of the last coordinate in the segment 20136* @param sqTolerance - square tolerance value 20137*/ 20138function simplify(coords, first, last, sqTolerance) { 20139 let maxSqDist = sqTolerance; 20140 const mid = first + (last - first >> 1); 20141 let minPosToMid = last - first; 20142 let index; 20143 const ax = coords[first]; 20144 const ay = coords[first + 1]; 20145 const bx = coords[last]; 20146 const by = coords[last + 1]; 20147 for (let i = first + 3; i < last; i += 3) { 20148 const d = getSqSegDist(coords[i], coords[i + 1], ax, ay, bx, by); 20149 if (d > maxSqDist) { 20150 index = i; 20151 maxSqDist = d; 20152 continue; 20153 } 20154 if (d === maxSqDist) { 20155 const posToMid = Math.abs(i - mid); 20156 if (posToMid < minPosToMid) { 20157 index = i; 20158 minPosToMid = posToMid; 20159 } 20160 } 20161 } 20162 if (maxSqDist > sqTolerance) { 20163 if (index - first > 3) simplify(coords, first, index, sqTolerance); 20164 coords[index + 2] = maxSqDist; 20165 if (last - index > 3) simplify(coords, index, last, sqTolerance); 20166 } 20167} 20168/** 20169* Claculates the square distance from a point to a segment 20170* @param px - x coordinate of the point 20171* @param py - y coordinate of the point 20172* @param x - x coordinate of the first segment endpoint 20173* @param y - y coordinate of the first segment endpoint 20174* @param bx - x coordinate of the second segment endpoint 20175* @param by - y coordinate of the second segment endpoint 20176* @returns square distance from a point to a segment 20177*/ 20178function getSqSegDist(px, py, x, y, bx, by) { 20179 let dx = bx - x; 20180 let dy = by - y; 20181 if (dx !== 0 || dy !== 0) { 20182 const t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy); 20183 if (t > 1) { 20184 x = bx; 20185 y = by; 20186 } else if (t > 0) { 20187 x += dx * t; 20188 y += dy * t; 20189 } 20190 } 20191 dx = px - x; 20192 dy = py - y; 20193 return dx * dx + dy * dy; 20194} 20195/** 20196* 20197* @param id - the feature's ID 20198* @param type - the feature's type 20199* @param geom - the feature's geometry 20200* @param tags - the feature's properties 20201* @returns the created feature 20202*/ 20203function createFeature(id, type, geom, tags) { 20204 const data = { 20205 type, 20206 geom 20207 }; 20208 const feature = { 20209 id: id == null ? null : id, 20210 type: data.type, 20211 geometry: data.geom, 20212 tags, 20213 minX: Infinity, 20214 minY: Infinity, 20215 maxX: -Infinity, 20216 maxY: -Infinity 20217 }; 20218 switch (data.type) { 20219 case "Point": 20220 case "MultiPoint": 20221 calcLineBBox(feature, data.geom); 20222 break; 20223 case "LineString": 20224 calcLineBBox(feature, data.geom.points); 20225 break; 20226 case "Polygon": 20227 calcLineBBox(feature, data.geom[0].points); 20228 break; 20229 case "MultiLineString": 20230 for (const line of data.geom) calcLineBBox(feature, line.points); 20231 break; 20232 case "MultiPolygon": for (const polygon of data.geom) calcLineBBox(feature, polygon[0].points); 20233 } 20234 return feature; 20235} 20236function optimizeLineMemory(line) { 20237 const lineImmutable = line; 20238 if (line.points.length > 64) lineImmutable.points = new Float64Array(line.points); 20239} 20240function calcLineBBox(feature, geom) { 20241 for (let i = 0; i < geom.length; i += 3) { 20242 feature.minX = Math.min(feature.minX, geom[i]); 20243 feature.minY = Math.min(feature.minY, geom[i + 1]); 20244 feature.maxX = Math.max(feature.maxX, geom[i]); 20245 feature.maxY = Math.max(feature.maxY, geom[i + 1]); 20246 } 20247} 20248const MAX_GEOMETRY_COLLECTION_DEPTH = 1024; 20249/** 20250* converts GeoJSON to internal source features (an intermediate projected JSON vector format with simplification data) 20251* @param data 20252* @param options 20253* @returns 20254*/ 20255function convertToInternal(data, options) { 20256 const features = []; 20257 switch (data.type) { 20258 case "FeatureCollection": 20259 for (let i = 0; i < data.features.length; i++) featureToInternal(features, data.features[i], options, i); 20260 break; 20261 case "Feature": 20262 featureToInternal(features, data, options); 20263 break; 20264 default: featureToInternal(features, { 20265 type: "Feature", 20266 geometry: data, 20267 properties: void 0 20268 }, options); 20269 } 20270 return features; 20271} 20272function featureToInternal(features, geojson, options, index, depth = 0) { 20273 if (!geojson.geometry) return; 20274 if (depth > MAX_GEOMETRY_COLLECTION_DEPTH) throw new Error("GeometryCollection nesting exceeds supported depth: 1024"); 20275 if (geojson.geometry.type === "GeometryCollection") { 20276 convertGeometryCollection(features, geojson, geojson.geometry, options, index, depth + 1); 20277 return; 20278 } 20279 if (!geojson.geometry.coordinates?.length) return; 20280 const id = getFeatureId(geojson, options, index); 20281 const tolerance = Math.pow(options.tolerance / ((1 << options.maxZoom) * options.extent), 2); 20282 switch (geojson.geometry.type) { 20283 case "Point": 20284 convertPointFeature(features, id, geojson.geometry, geojson.properties); 20285 return; 20286 case "MultiPoint": 20287 convertMultiPointFeature(features, id, geojson.geometry, geojson.properties); 20288 return; 20289 case "LineString": 20290 convertLineStringFeature(features, id, geojson.geometry, tolerance, geojson.properties); 20291 return; 20292 case "MultiLineString": 20293 convertMultiLineStringFeature(features, id, geojson.geometry, tolerance, options, geojson.properties); 20294 return; 20295 case "Polygon": 20296 convertPolygonFeature(features, id, geojson.geometry, tolerance, geojson.properties); 20297 return; 20298 case "MultiPolygon": 20299 convertMultiPolygonFeature(features, id, geojson.geometry, tolerance, geojson.properties); 20300 return; 20301 default: throw new Error("Input data is not a valid GeoJSON object."); 20302 } 20303} 20304function getFeatureId(geojson, options, index) { 20305 if (options.promoteId) return geojson.properties?.[options.promoteId]; 20306 if (options.generateId) return index || 0; 20307 return geojson.id; 20308} 20309function convertGeometryCollection(features, geojson, geometry, options, index, depth = 0) { 20310 for (const geom of geometry.geometries) featureToInternal(features, { 20311 id: geojson.id, 20312 type: "Feature", 20313 geometry: geom, 20314 properties: geojson.properties 20315 }, options, index, depth); 20316} 20317function convertPointFeature(features, id, geom, properties) { 20318 const out = []; 20319 out.push(projectX(geom.coordinates[0]), projectY(geom.coordinates[1]), 0); 20320 features.push(createFeature(id, "Point", out, properties)); 20321} 20322function convertMultiPointFeature(features, id, geom, properties) { 20323 const out = []; 20324 for (const coords of geom.coordinates) out.push(projectX(coords[0]), projectY(coords[1]), 0); 20325 features.push(createFeature(id, "MultiPoint", out, properties)); 20326} 20327function convertLineStringFeature(features, id, geom, tolerance, properties) { 20328 const out = { points: [] }; 20329 convertLine(geom.coordinates, out, tolerance, false); 20330 features.push(createFeature(id, "LineString", out, properties)); 20331} 20332function convertMultiLineStringFeature(features, id, geom, tolerance, options, properties) { 20333 if (options.lineMetrics) for (const line of geom.coordinates) { 20334 const out = { points: [] }; 20335 convertLine(line, out, tolerance, false); 20336 features.push(createFeature(id, "LineString", out, properties)); 20337 } 20338 else { 20339 const out = []; 20340 convertLines(geom.coordinates, out, tolerance, false); 20341 features.push(createFeature(id, "MultiLineString", out, properties)); 20342 } 20343} 20344function convertPolygonFeature(features, id, geom, tolerance, properties) { 20345 const out = []; 20346 convertLines(geom.coordinates, out, tolerance, true); 20347 features.push(createFeature(id, "Polygon", out, properties)); 20348} 20349function convertMultiPolygonFeature(features, id, geom, tolerance, properties) { 20350 const out = []; 20351 for (const polygon of geom.coordinates) { 20352 const polygonOut = []; 20353 convertLines(polygon, polygonOut, tolerance, true); 20354 out.push(polygonOut); 20355 } 20356 features.push(createFeature(id, "MultiPolygon", out, properties)); 20357} 20358function convertLine(ring, out, tolerance, isPolygon) { 20359 let x0, y0; 20360 let size = 0; 20361 for (let j = 0; j < ring.length; j++) { 20362 const x = projectX(ring[j][0]); 20363 const y = projectY(ring[j][1]); 20364 out.points.push(x, y, 0); 20365 if (j > 0) if (isPolygon) size += (x0 * y - x * y0) / 2; 20366 else size += Math.sqrt(Math.pow(x - x0, 2) + Math.pow(y - y0, 2)); 20367 x0 = x; 20368 y0 = y; 20369 } 20370 const last = out.points.length - 3; 20371 out.points[2] = 1; 20372 if (tolerance > 0) simplify(out.points, 0, last, tolerance); 20373 out.points[last + 2] = 1; 20374 optimizeLineMemory(out); 20375 out.size = Math.abs(size); 20376 out.start = 0; 20377 out.end = out.size; 20378} 20379function convertLines(rings, out, tolerance, isPolygon) { 20380 for (let i = 0; i < rings.length; i++) { 20381 const geom = { points: [] }; 20382 convertLine(rings[i], geom, tolerance, isPolygon); 20383 out.push(geom); 20384 } 20385} 20386/** 20387* Convert longitude to spherical mercator in [0..1] range 20388*/ 20389function projectX(x) { 20390 return x / 360 + .5; 20391} 20392/** 20393* Convert latitude to spherical mercator in [0..1] range 20394*/ 20395function projectY(y) { 20396 const sin = Math.sin(y * Math.PI / 180); 20397 const y2 = .5 - .25 * Math.log((1 + sin) / (1 - sin)) / Math.PI; 20398 return y2 < 0 ? 0 : y2 > 1 ? 1 : y2; 20399} 20400/** 20401* Converts internal source features back to GeoJSON format. 20402*/ 20403function convertToGeoJSON(source) { 20404 return { 20405 type: "FeatureCollection", 20406 features: source.map((feature) => featureToGeoJSON(feature)) 20407 }; 20408} 20409/** 20410* Converts a single internal feature to GeoJSON format. 20411*/ 20412function featureToGeoJSON(feature) { 20413 const geojsonFeature = { 20414 type: "Feature", 20415 geometry: geometryToGeoJSON(feature), 20416 properties: feature.tags 20417 }; 20418 if (feature.id != null) geojsonFeature.id = feature.id; 20419 return geojsonFeature; 20420} 20421/** 20422* Converts a single internal feature geometry to GeoJSON format. 20423*/ 20424function geometryToGeoJSON(feature) { 20425 const { type, geometry } = feature; 20426 switch (type) { 20427 case "Point": return { 20428 type, 20429 coordinates: unprojectPoint(geometry[0], geometry[1]) 20430 }; 20431 case "MultiPoint": return { 20432 type, 20433 coordinates: unprojectPoints(geometry) 20434 }; 20435 case "LineString": return { 20436 type, 20437 coordinates: unprojectPoints(geometry.points) 20438 }; 20439 case "MultiLineString": 20440 case "Polygon": return { 20441 type, 20442 coordinates: geometry.map((ring) => unprojectPoints(ring.points)) 20443 }; 20444 case "MultiPolygon": return { 20445 type, 20446 coordinates: geometry.map((polygon) => polygon.map((ring) => unprojectPoints(ring.points))) 20447 }; 20448 } 20449} 20450function unprojectPoints(coords) { 20451 const result = []; 20452 for (let i = 0; i < coords.length; i += 3) result.push(unprojectPoint(coords[i], coords[i + 1])); 20453 return result; 20454} 20455function unprojectPoint(x, y) { 20456 return [unprojectX(x), unprojectY(y)]; 20457} 20458/** 20459* Convert spherical mercator in [0..1] range to longitude 20460*/ 20461function unprojectX(x) { 20462 return (x - .5) * 360; 20463} 20464/** 20465* Convert spherical mercator in [0..1] range to latitude 20466*/ 20467function unprojectY(y) { 20468 const y2 = (180 - y * 360) * Math.PI / 180; 20469 return 360 * Math.atan(Math.exp(y2)) / Math.PI - 90; 20470} 20471/** 20472* clip features between two vertical or horizontal axis-parallel lines: 20473* | | 20474* ___|___ | / 20475* / | \____|____/ 20476* | | 20477* 20478* @param features - the features to clip 20479* @param scale - the scale to divide start and end inputs 20480* @param start - the start of the clip range 20481* @param end - the end of the clip range 20482* @param axis - which axis to clip against 20483* @param minAll - the minimum for all features in the relevant axis 20484* @param maxAll - the maximum for all features in the relevant axis 20485*/ 20486function clip(features, scale, start, end, axis, minAll, maxAll, options) { 20487 start /= scale; 20488 end /= scale; 20489 if (minAll >= start && maxAll < end) return features; 20490 if (maxAll < start || minAll >= end) return null; 20491 const clipped = []; 20492 for (const feature of features) { 20493 const min = axis === 0 ? feature.minX : feature.minY; 20494 const max = axis === 0 ? feature.maxX : feature.maxY; 20495 if (min >= start && max < end) { 20496 clipped.push(feature); 20497 continue; 20498 } 20499 if (max < start || min >= end) continue; 20500 switch (feature.type) { 20501 case "Point": 20502 case "MultiPoint": 20503 clipPointFeature(feature, clipped, start, end, axis); 20504 continue; 20505 case "LineString": 20506 clipLineStringFeature(feature, clipped, start, end, axis, options); 20507 continue; 20508 case "MultiLineString": 20509 clipMultiLineStringFeature(feature, clipped, start, end, axis); 20510 continue; 20511 case "Polygon": 20512 clipPolygonFeature(feature, clipped, start, end, axis); 20513 continue; 20514 case "MultiPolygon": 20515 clipMultiPolygonFeature(feature, clipped, start, end, axis); 20516 continue; 20517 } 20518 } 20519 if (!clipped.length) return null; 20520 return clipped; 20521} 20522function clipPointFeature(feature, clipped, start, end, axis) { 20523 const geom = []; 20524 clipPoints$1(feature.geometry, geom, start, end, axis); 20525 if (!geom.length) return; 20526 const type = geom.length === 3 ? "Point" : "MultiPoint"; 20527 clipped.push(createFeature(feature.id, type, geom, feature.tags)); 20528} 20529function clipLineStringFeature(feature, clipped, start, end, axis, options) { 20530 const geom = []; 20531 clipLine$1(feature.geometry, geom, start, end, axis, false, options.lineMetrics); 20532 if (!geom.length) return; 20533 if (options.lineMetrics) { 20534 for (const line of geom) clipped.push(createFeature(feature.id, "LineString", line, feature.tags)); 20535 return; 20536 } 20537 if (geom.length > 1) { 20538 clipped.push(createFeature(feature.id, "MultiLineString", geom, feature.tags)); 20539 return; 20540 } 20541 clipped.push(createFeature(feature.id, "LineString", geom[0], feature.tags)); 20542} 20543function clipMultiLineStringFeature(feature, clipped, start, end, axis) { 20544 const geom = []; 20545 clipLines$1(feature.geometry, geom, start, end, axis, false); 20546 if (!geom.length) return; 20547 if (geom.length === 1) { 20548 clipped.push(createFeature(feature.id, "LineString", geom[0], feature.tags)); 20549 return; 20550 } 20551 clipped.push(createFeature(feature.id, "MultiLineString", geom, feature.tags)); 20552} 20553function clipPolygonFeature(feature, clipped, start, end, axis) { 20554 const geom = []; 20555 clipLines$1(feature.geometry, geom, start, end, axis, true); 20556 if (!geom.length) return; 20557 clipped.push(createFeature(feature.id, "Polygon", geom, feature.tags)); 20558} 20559function clipMultiPolygonFeature(feature, clipped, start, end, axis) { 20560 const geom = []; 20561 for (const polygon of feature.geometry) { 20562 const newPolygon = []; 20563 clipLines$1(polygon, newPolygon, start, end, axis, true); 20564 if (!newPolygon.length) continue; 20565 geom.push(newPolygon); 20566 } 20567 if (!geom.length) return; 20568 clipped.push(createFeature(feature.id, "MultiPolygon", geom, feature.tags)); 20569} 20570function clipPoints$1(geom, newGeom, start, end, axis) { 20571 for (let i = 0; i < geom.length; i += 3) { 20572 const a = geom[i + axis]; 20573 if (a >= start && a <= end) addPoint(newGeom, geom[i], geom[i + 1], geom[i + 2]); 20574 } 20575} 20576function clipLine$1(geom, newGeom, start, end, axis, isPolygon, trackMetrics) { 20577 let slice = newSlice(geom); 20578 const intersect = axis === 0 ? intersectX : intersectY; 20579 let len = geom.start; 20580 let segLen, t; 20581 for (let i = 0; i < geom.points.length - 3; i += 3) { 20582 const ax = geom.points[i]; 20583 const ay = geom.points[i + 1]; 20584 const az = geom.points[i + 2]; 20585 const bx = geom.points[i + 3]; 20586 const by = geom.points[i + 4]; 20587 const a = axis === 0 ? ax : ay; 20588 const b = axis === 0 ? bx : by; 20589 let exited = false; 20590 if (trackMetrics) segLen = Math.sqrt(Math.pow(ax - bx, 2) + Math.pow(ay - by, 2)); 20591 if (a < start) { 20592 if (b > start) { 20593 t = intersect(slice, ax, ay, bx, by, start); 20594 if (trackMetrics) slice.start = len + segLen * t; 20595 } 20596 } else if (a > end) { 20597 if (b < end) { 20598 t = intersect(slice, ax, ay, bx, by, end); 20599 if (trackMetrics) slice.start = len + segLen * t; 20600 } 20601 } else addPoint(slice.points, ax, ay, az); 20602 if (b < start && a >= start) { 20603 t = intersect(slice, ax, ay, bx, by, start); 20604 exited = true; 20605 } 20606 if (b > end && a <= end) { 20607 t = intersect(slice, ax, ay, bx, by, end); 20608 exited = true; 20609 } 20610 if (!isPolygon && exited) { 20611 if (trackMetrics) slice.end = len + segLen * t; 20612 newGeom.push(slice); 20613 slice = newSlice(geom); 20614 } 20615 if (trackMetrics) len += segLen; 20616 } 20617 let last = geom.points.length - 3; 20618 const ax = geom.points[last]; 20619 const ay = geom.points[last + 1]; 20620 const az = geom.points[last + 2]; 20621 const a = axis === 0 ? ax : ay; 20622 if (a >= start && a <= end) addPoint(slice.points, ax, ay, az); 20623 last = slice.points.length - 3; 20624 if (isPolygon && last >= 3 && (slice.points[last] !== slice.points[0] || slice.points[last + 1] !== slice.points[1])) addPoint(slice.points, slice.points[0], slice.points[1], slice.points[2]); 20625 if (slice.points.length) { 20626 optimizeLineMemory(slice); 20627 newGeom.push(slice); 20628 } 20629} 20630function newSlice(line) { 20631 return { 20632 points: [], 20633 size: line.size, 20634 start: line.start, 20635 end: line.end 20636 }; 20637} 20638function clipLines$1(geom, newGeom, start, end, axis, isPolygon) { 20639 for (const line of geom) clipLine$1(line, newGeom, start, end, axis, isPolygon, false); 20640} 20641function addPoint(out, x, y, z) { 20642 out.push(x, y, z); 20643} 20644function intersectX(out, ax, ay, bx, by, x) { 20645 const t = (x - ax) / (bx - ax); 20646 addPoint(out.points, x, ay + (by - ay) * t, 1); 20647 return t; 20648} 20649function intersectY(out, ax, ay, bx, by, y) { 20650 const t = (y - ay) / (by - ay); 20651 addPoint(out.points, ax + (bx - ax) * t, y, 1); 20652 return t; 20653} 20654function wrap(features, options) { 20655 const buffer = options.buffer / options.extent; 20656 let merged = features; 20657 const left = clip(features, 1, -1 - buffer, buffer, 0, -1, 2, options); 20658 const right = clip(features, 1, 1 - buffer, 2 + buffer, 0, -1, 2, options); 20659 if (!left && !right) return merged; 20660 merged = clip(features, 1, -buffer, 1 + buffer, 0, -1, 2, options) || []; 20661 if (left) merged = shiftFeatureCoords(left, 1).concat(merged); 20662 if (right) merged = merged.concat(shiftFeatureCoords(right, -1)); 20663 return merged; 20664} 20665function shiftFeatureCoords(features, offset) { 20666 const newFeatures = []; 20667 for (const feature of features) switch (feature.type) { 20668 case "Point": 20669 case "MultiPoint": { 20670 const newGeometry = shiftPointCoords(feature.geometry, offset); 20671 newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags)); 20672 continue; 20673 } 20674 case "LineString": { 20675 const newGeometry = shiftLineCoords(feature.geometry, offset); 20676 newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags)); 20677 continue; 20678 } 20679 case "MultiLineString": 20680 case "Polygon": { 20681 const newGeometry = []; 20682 for (const line of feature.geometry) newGeometry.push(shiftLineCoords(line, offset)); 20683 newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags)); 20684 continue; 20685 } 20686 case "MultiPolygon": { 20687 const newGeometry = []; 20688 for (const polygon of feature.geometry) { 20689 const newPolygon = []; 20690 for (const line of polygon) newPolygon.push(shiftLineCoords(line, offset)); 20691 newGeometry.push(newPolygon); 20692 } 20693 newFeatures.push(createFeature(feature.id, feature.type, newGeometry, feature.tags)); 20694 continue; 20695 } 20696 } 20697 return newFeatures; 20698} 20699function shiftPointCoords(coords, offset) { 20700 const newCoords = []; 20701 for (let i = 0; i < coords.length; i += 3) newCoords.push(coords[i] + offset, coords[i + 1], coords[i + 2]); 20702 return newCoords; 20703} 20704function shiftLineCoords(line, offset) { 20705 const newLine = { 20706 points: [], 20707 size: line.size 20708 }; 20709 if (line.start !== void 0) { 20710 newLine.start = line.start; 20711 newLine.end = line.end; 20712 } 20713 for (let i = 0; i < line.points.length; i += 3) newLine.points.push(line.points[i] + offset, line.points[i + 1], line.points[i + 2]); 20714 optimizeLineMemory(newLine); 20715 return newLine; 20716} 20717/** 20718* Applies a GeoJSON Source Diff to an existing set of simplified features 20719* @param source 20720* @param dataDiff 20721* @param options 20722* @returns 20723*/ 20724function applySourceDiff(source, dataDiff, options) { 20725 const diff = diffToHashed(dataDiff, options); 20726 let affected = []; 20727 if (diff.removeAll) { 20728 affected = source; 20729 source = []; 20730 } 20731 if (diff.remove.size || diff.add.size) { 20732 const removeFeatures = []; 20733 for (const feature of source) if (diff.remove.has(feature.id) || diff.add.has(feature.id)) removeFeatures.push(feature); 20734 if (removeFeatures.length) { 20735 affected = affected.concat(removeFeatures); 20736 const removeIds = new Set(removeFeatures.map((f) => f.id)); 20737 source = source.filter((f) => !removeIds.has(f.id)); 20738 } 20739 if (diff.add.size) { 20740 let addFeatures = convertToInternal({ 20741 type: "FeatureCollection", 20742 features: Array.from(diff.add.values()) 20743 }, options); 20744 addFeatures = wrap(addFeatures, options); 20745 affected = affected.concat(addFeatures); 20746 source = source.concat(addFeatures); 20747 } 20748 } 20749 if (diff.update.size) { 20750 const oldFeaturesMap = /* @__PURE__ */ new Map(); 20751 let keepFeatures = []; 20752 for (const feature of source) if (diff.update.has(feature.id)) oldFeaturesMap.set(feature.id, [...oldFeaturesMap.get(feature.id) || [], feature]); 20753 else keepFeatures.push(feature); 20754 for (const [id, update] of diff.update) { 20755 const oldFeatures = oldFeaturesMap.get(id); 20756 if (!oldFeatures || oldFeatures.length === 0) continue; 20757 const updatedFeatures = getUpdatedFeatures(oldFeatures, update, options); 20758 affected = affected.concat(oldFeatures, updatedFeatures); 20759 keepFeatures = keepFeatures.concat(updatedFeatures); 20760 } 20761 source = keepFeatures; 20762 } 20763 return { 20764 affected, 20765 source 20766 }; 20767} 20768/** 20769* Gets updated simplified feature(s) based on a diff update object. 20770* @param vtFeatures - the original features 20771* @param update - the update object to apply 20772* @param options - the options to use for the wrap method 20773* @returns Updated features. If geometry is updated, returns new feature(s) converted from geojson and wrapped. If only properties are updated, returns feature(s) with tags updated. 20774*/ 20775function getUpdatedFeatures(vtFeatures, update, options) { 20776 const changeGeometry = !!update.newGeometry; 20777 const changeProps = update.removeAllProperties || update.removeProperties?.length > 0 || update.addOrUpdateProperties?.length > 0; 20778 if (changeGeometry) { 20779 const vtFeature = vtFeatures[0]; 20780 let features = convertToInternal({ 20781 type: "FeatureCollection", 20782 features: [{ 20783 type: "Feature", 20784 id: vtFeature.id, 20785 geometry: update.newGeometry, 20786 properties: changeProps ? applyPropertyUpdates(vtFeature.tags, update) : vtFeature.tags 20787 }] 20788 }, options); 20789 features = wrap(features, options); 20790 return features; 20791 } 20792 if (changeProps) { 20793 const updated = []; 20794 for (const vtFeature of vtFeatures) { 20795 const feature = { ...vtFeature }; 20796 feature.tags = applyPropertyUpdates(feature.tags, update); 20797 updated.push(feature); 20798 } 20799 return updated; 20800 } 20801 return vtFeatures; 20802} 20803/** 20804* helper to apply property updates from a diff update object to a properties object 20805*/ 20806function applyPropertyUpdates(tags, update) { 20807 if (update.removeAllProperties) return {}; 20808 const properties = { ...tags || {} }; 20809 if (update.removeProperties) for (const key of update.removeProperties) delete properties[key]; 20810 if (update.addOrUpdateProperties) for (const { key, value } of update.addOrUpdateProperties) properties[key] = value; 20811 return properties; 20812} 20813/** 20814* Convert a GeoJSON Source Diff to an idempotent hashed representation using Sets and Maps 20815*/ 20816function diffToHashed(diff, options) { 20817 if (!diff) return { 20818 remove: /* @__PURE__ */ new Set(), 20819 add: /* @__PURE__ */ new Map(), 20820 update: /* @__PURE__ */ new Map() 20821 }; 20822 return { 20823 removeAll: diff.removeAll, 20824 remove: new Set(diff.remove || []), 20825 add: new Map(diff.add?.map((feature) => [options.promoteId ? feature.properties[options.promoteId] : feature.id, feature])), 20826 update: new Map(diff.update?.map((update) => [update.id, update])) 20827 }; 20828} 20829const ARRAY_TYPES = [ 20830 Int8Array, 20831 Uint8Array, 20832 Uint8ClampedArray, 20833 Int16Array, 20834 Uint16Array, 20835 Int32Array, 20836 Uint32Array, 20837 Float32Array, 20838 Float64Array 20839]; 20840/** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor} TypedArrayConstructor */ 20841/** @typedef {Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array} TypedArray */ 20842const VERSION = 1; 20843const HEADER_SIZE = 8; 20844const STACK = /* @__PURE__ */ new Uint32Array(96); 20845var KDBush = class KDBush { 20846 /** 20847 * Creates an index from raw `ArrayBuffer` data. 20848 * @param {ArrayBufferLike} data 20849 */ 20850 static from(data) { 20851 if (!data || data.byteLength === void 0 || data.buffer) throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer."); 20852 const [magic, versionAndType] = new Uint8Array(data, 0, 2); 20853 if (magic !== 219) throw new Error("Data does not appear to be in a KDBush format."); 20854 const version = versionAndType >> 4; 20855 if (version !== VERSION) throw new Error(`Got v${version} data when expected v${VERSION}.`); 20856 const ArrayType = ARRAY_TYPES[versionAndType & 15]; 20857 if (!ArrayType) throw new Error("Unrecognized array type."); 20858 const [nodeSize] = new Uint16Array(data, 2, 1); 20859 const [numItems] = new Uint32Array(data, 4, 1); 20860 return new KDBush(numItems, nodeSize, ArrayType, void 0, data); 20861 } 20862 /** 20863 * Creates an index that will hold a given number of items. 20864 * @param {number} numItems 20865 * @param {number} [nodeSize=64] Size of the KD-tree node (64 by default). 20866 * @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default). 20867 * @param {ArrayBufferConstructor | SharedArrayBufferConstructor} [ArrayBufferType=ArrayBuffer] The array buffer type used for storage (`ArrayBuffer` by default). 20868 * @param {ArrayBufferLike} [data] (For internal use only) 20869 */ 20870 constructor(numItems, nodeSize = 64, ArrayType = Float64Array, ArrayBufferType = ArrayBuffer, data) { 20871 if (isNaN(numItems) || numItems < 0) throw new Error(`Unexpected numItems value: ${numItems}.`); 20872 this.numItems = +numItems; 20873 this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535); 20874 this.ArrayType = ArrayType; 20875 this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array; 20876 const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType); 20877 const coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT; 20878 const idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT; 20879 const padCoords = (8 - idsByteSize % 8) % 8; 20880 if (arrayTypeIndex < 0) throw new Error(`Unexpected typed array class: ${ArrayType}.`); 20881 if (data) { 20882 this.data = data; 20883 this.ids = new this.IndexArrayType(data, HEADER_SIZE, numItems); 20884 this.coords = new ArrayType(data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2); 20885 this._pos = numItems * 2; 20886 this._finished = true; 20887 } else { 20888 const data = this.data = new ArrayBufferType(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords); 20889 this.ids = new this.IndexArrayType(data, HEADER_SIZE, numItems); 20890 this.coords = new ArrayType(data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2); 20891 this._pos = 0; 20892 this._finished = false; 20893 new Uint8Array(data, 0, 2).set([219, 16 + arrayTypeIndex]); 20894 new Uint16Array(data, 2, 1)[0] = nodeSize; 20895 new Uint32Array(data, 4, 1)[0] = numItems; 20896 } 20897 } 20898 /** 20899 * Add a point to the index. 20900 * @param {number} x 20901 * @param {number} y 20902 * @returns {number} An incremental index associated with the added item (starting from `0`). 20903 */ 20904 add(x, y) { 20905 const index = this._pos >> 1; 20906 this.ids[index] = index; 20907 this.coords[this._pos++] = x; 20908 this.coords[this._pos++] = y; 20909 return index; 20910 } 20911 /** 20912 * Perform indexing of the added points. 20913 */ 20914 finish() { 20915 const numAdded = this._pos >> 1; 20916 if (numAdded !== this.numItems) throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`); 20917 sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0); 20918 this._finished = true; 20919 return this; 20920 } 20921 /** 20922 * Search the index for items within a given bounding box. 20923 * @param {number} minX 20924 * @param {number} minY 20925 * @param {number} maxX 20926 * @param {number} maxY 20927 * @returns {number[]} An array of indices correponding to the found items. 20928 */ 20929 range(minX, minY, maxX, maxY) { 20930 if (!this._finished) throw new Error("Data not yet indexed - call index.finish()."); 20931 const { ids, coords, nodeSize } = this; 20932 STACK[0] = 0; 20933 STACK[1] = ids.length - 1; 20934 STACK[2] = 0; 20935 let sp = 3; 20936 const result = []; 20937 while (sp > 0) { 20938 const axis = STACK[--sp]; 20939 const right = STACK[--sp]; 20940 const left = STACK[--sp]; 20941 if (right - left <= nodeSize) { 20942 for (let i = left; i <= right; i++) { 20943 const x = coords[2 * i]; 20944 const y = coords[2 * i + 1]; 20945 if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]); 20946 } 20947 continue; 20948 } 20949 const m = left + right >> 1; 20950 const x = coords[2 * m]; 20951 const y = coords[2 * m + 1]; 20952 if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]); 20953 if (axis === 0 ? minX <= x : minY <= y) { 20954 STACK[sp++] = left; 20955 STACK[sp++] = m - 1; 20956 STACK[sp++] = 1 - axis; 20957 } 20958 if (axis === 0 ? maxX >= x : maxY >= y) { 20959 STACK[sp++] = m + 1; 20960 STACK[sp++] = right; 20961 STACK[sp++] = 1 - axis; 20962 } 20963 } 20964 return result; 20965 } 20966 /** 20967 * Search the index for items within a given radius. 20968 * @param {number} qx 20969 * @param {number} qy 20970 * @param {number} r Query radius. 20971 * @returns {number[]} An array of indices correponding to the found items. 20972 */ 20973 within(qx, qy, r) { 20974 const result = []; 20975 this.withinInto(qx, qy, r, result); 20976 return result; 20977 } 20978 /** 20979 * Search the index for items within a given radius, writing matching ids into `out` 20980 * via indexed assignment (`out[i] = id`). Accepts any indexed-writable container â 20981 * a typed array sized to the expected upper bound (allocation-free, fast) or a plain 20982 * `Array` (which will grow as needed). Returns the number of matches written. 20983 * @param {number} qx 20984 * @param {number} qy 20985 * @param {number} r Query radius. 20986 * @param {number[] | TypedArray} out Container to write matching ids into. 20987 * @returns {number} The number of matches written to `out`. 20988 */ 20989 withinInto(qx, qy, r, out) { 20990 if (!this._finished) throw new Error("Data not yet indexed - call index.finish()."); 20991 const { ids, coords, nodeSize } = this; 20992 STACK[0] = 0; 20993 STACK[1] = ids.length - 1; 20994 STACK[2] = 0; 20995 let sp = 3; 20996 let count = 0; 20997 const r2 = r * r; 20998 while (sp > 0) { 20999 const axis = STACK[--sp]; 21000 const right = STACK[--sp]; 21001 const left = STACK[--sp]; 21002 if (right - left <= nodeSize) { 21003 for (let i = left; i <= right; i++) if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) out[count++] = ids[i]; 21004 continue; 21005 } 21006 const m = left + right >> 1; 21007 const x = coords[2 * m]; 21008 const y = coords[2 * m + 1]; 21009 if (sqDist(x, y, qx, qy) <= r2) out[count++] = ids[m]; 21010 if (axis === 0 ? qx - r <= x : qy - r <= y) { 21011 STACK[sp++] = left; 21012 STACK[sp++] = m - 1; 21013 STACK[sp++] = 1 - axis; 21014 } 21015 if (axis === 0 ? qx + r >= x : qy + r >= y) { 21016 STACK[sp++] = m + 1; 21017 STACK[sp++] = right; 21018 STACK[sp++] = 1 - axis; 21019 } 21020 } 21021 return count; 21022 } 21023}; 21024/** 21025* @param {Uint16Array | Uint32Array} ids 21026* @param {TypedArray} coords 21027* @param {number} nodeSize 21028* @param {number} left 21029* @param {number} right 21030* @param {number} axis 21031*/ 21032function sort(ids, coords, nodeSize, left, right, axis) { 21033 if (right - left <= nodeSize) return; 21034 const m = left + right >> 1; 21035 select(ids, coords, m, left, right, axis); 21036 sort(ids, coords, nodeSize, left, m - 1, 1 - axis); 21037 sort(ids, coords, nodeSize, m + 1, right, 1 - axis); 21038} 21039/** 21040* Custom Floyd-Rivest selection algorithm: sort ids and coords so that 21041* [left..k-1] items are smaller than k-th item (on either x or y axis) 21042* @param {Uint16Array | Uint32Array} ids 21043* @param {TypedArray} coords 21044* @param {number} k 21045* @param {number} left 21046* @param {number} right 21047* @param {number} axis 21048*/ 21049function select(ids, coords, k, left, right, axis) { 21050 while (right > left) { 21051 if (right - left > 600) { 21052 const n = right - left + 1; 21053 const m = k - left + 1; 21054 const z = Math.log(n); 21055 const s = .5 * Math.exp(2 * z / 3); 21056 const sd = .5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); 21057 select(ids, coords, k, Math.max(left, Math.floor(k - m * s / n + sd)), Math.min(right, Math.floor(k + (n - m) * s / n + sd)), axis); 21058 } 21059 const t = coords[2 * k + axis]; 21060 let i = left; 21061 let j = right; 21062 swapItem(ids, coords, left, k); 21063 if (coords[2 * right + axis] > t) swapItem(ids, coords, left, right); 21064 while (i < j) { 21065 swapItem(ids, coords, i, j); 21066 i++; 21067 j--; 21068 while (coords[2 * i + axis] < t) i++; 21069 while (coords[2 * j + axis] > t) j--; 21070 } 21071 if (coords[2 * left + axis] === t) swapItem(ids, coords, left, j); 21072 else { 21073 j++; 21074 swapItem(ids, coords, j, right); 21075 } 21076 if (j <= k) left = j + 1; 21077 if (k <= j) right = j - 1; 21078 } 21079} 21080/** 21081* @param {Uint16Array | Uint32Array} ids 21082* @param {TypedArray} coords 21083* @param {number} i 21084* @param {number} j 21085*/ 21086function swapItem(ids, coords, i, j) { 21087 swap(ids, i, j); 21088 swap(coords, 2 * i, 2 * j); 21089 swap(coords, 2 * i + 1, 2 * j + 1); 21090} 21091/** 21092* @param {TypedArray} arr 21093* @param {number} i 21094* @param {number} j 21095*/ 21096function swap(arr, i, j) { 21097 const tmp = arr[i]; 21098 arr[i] = arr[j]; 21099 arr[j] = tmp; 21100} 21101/** 21102* @param {number} ax 21103* @param {number} ay 21104* @param {number} bx 21105* @param {number} by 21106*/ 21107function sqDist(ax, ay, bx, by) { 21108 const dx = ax - bx; 21109 const dy = ay - by; 21110 return dx * dx + dy * dy; 21111} 21112const defaultClusterOptions = { 21113 minZoom: 0, 21114 maxZoom: 16, 21115 minPoints: 2, 21116 radius: 40, 21117 extent: 512, 21118 nodeSize: 64, 21119 log: false, 21120 generateId: false, 21121 reduce: null, 21122 map: (props) => props 21123}; 21124const OFFSET_ZOOM = 2; 21125const OFFSET_ID = 3; 21126const OFFSET_PARENT = 4; 21127const OFFSET_NUM = 5; 21128const OFFSET_PROP = 6; 21129/** 21130* This class allow clustering of geojson points. 21131*/ 21132var ClusterTileIndex = class { 21133 constructor(options) { 21134 this.options = Object.assign(Object.create(defaultClusterOptions), options); 21135 this.trees = new Array(this.options.maxZoom + 1); 21136 this.stride = this.options.reduce ? 7 : 6; 21137 this.clusterProps = []; 21138 this.points = []; 21139 } 21140 /** 21141 * Loads GeoJSON point features and builds the internal clustering index. 21142 * @param points - GeoJSON point features to cluster. 21143 */ 21144 load(points) { 21145 const features = []; 21146 for (const point of points) { 21147 if (!point.geometry) continue; 21148 const [lng, lat] = point.geometry.coordinates; 21149 const [x, y] = [projectX(lng), projectY(lat)]; 21150 const feature = { 21151 id: point.id, 21152 type: "Point", 21153 geometry: [x, y], 21154 tags: point.properties 21155 }; 21156 features.push(feature); 21157 } 21158 this.createIndex(features); 21159 } 21160 /** 21161 * @internal 21162 * Loads internal GeoJSONVT point features from a data source and builds the clustering index. 21163 * @param features - {@link GeoJSONVTInternalFeature} data source features to filter and cluster. 21164 */ 21165 initialize(features) { 21166 const points = []; 21167 for (const feature of features) { 21168 if (feature.type !== "Point") continue; 21169 points.push(feature); 21170 } 21171 this.createIndex(points); 21172 } 21173 /** 21174 * @internal 21175 * Updates the cluster data by rebuilding. 21176 * @param features 21177 */ 21178 updateIndex(features, _affected, options) { 21179 this.options = Object.assign(Object.create(defaultClusterOptions), options.clusterOptions); 21180 this.initialize(features); 21181 } 21182 createIndex(points) { 21183 const { log, minZoom, maxZoom } = this.options; 21184 if (log) console.time("total time"); 21185 const timerId = `prepare ${points.length} points`; 21186 if (log) console.time(timerId); 21187 this.points = points; 21188 const data = []; 21189 for (let i = 0; i < points.length; i++) { 21190 const p = points[i]; 21191 if (!p?.geometry) continue; 21192 let [x, y] = p.geometry; 21193 x = Math.fround(x); 21194 y = Math.fround(y); 21195 data.push(x, y, Infinity, i, -1, 1); 21196 if (this.options.reduce) data.push(0); 21197 } 21198 let tree = this.trees[maxZoom + 1] = this.createTree(data); 21199 if (log) console.timeEnd(timerId); 21200 for (let z = maxZoom; z >= minZoom; z--) { 21201 const now = Date.now(); 21202 tree = this.trees[z] = this.createTree(this.cluster(tree, z)); 21203 if (log) console.log("z%d: %d clusters in %dms", z, tree.numItems, Date.now() - now); 21204 } 21205 if (log) console.timeEnd("total time"); 21206 } 21207 /** 21208 * Returns clusters and/or points within a bounding box at a given zoom level. 21209 * @param bbox - Bounding box in `[westLng, southLat, eastLng, northLat]` order. 21210 * @param zoom - Zoom level to query. 21211 */ 21212 getClusters(bbox, zoom) { 21213 return this.getClustersInternal(bbox, zoom).map((f) => featureToGeoJSON(f)); 21214 } 21215 getClustersInternal(bbox, zoom) { 21216 let minLng = ((bbox[0] + 180) % 360 + 360) % 360 - 180; 21217 const minLat = Math.max(-90, Math.min(90, bbox[1])); 21218 let maxLng = bbox[2] === 180 ? 180 : ((bbox[2] + 180) % 360 + 360) % 360 - 180; 21219 const maxLat = Math.max(-90, Math.min(90, bbox[3])); 21220 if (bbox[2] - bbox[0] >= 360) { 21221 minLng = -180; 21222 maxLng = 180; 21223 } else if (minLng > maxLng) { 21224 const easternHem = this.getClustersInternal([ 21225 minLng, 21226 minLat, 21227 180, 21228 maxLat 21229 ], zoom); 21230 const westernHem = this.getClustersInternal([ 21231 -180, 21232 minLat, 21233 maxLng, 21234 maxLat 21235 ], zoom); 21236 return easternHem.concat(westernHem); 21237 } 21238 const tree = this.trees[this.limitZoom(zoom)]; 21239 const ids = tree.range(projectX(minLng), projectY(maxLat), projectX(maxLng), projectY(minLat)); 21240 const data = tree.flatData; 21241 const clusters = []; 21242 for (const id of ids) { 21243 const k = this.stride * id; 21244 clusters.push(data[k + OFFSET_NUM] > 1 ? getClusterFeature(data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]); 21245 } 21246 return clusters; 21247 } 21248 /** 21249 * Returns the immediate children (clusters or points) of a cluster as GeoJSON. 21250 * @param clusterId - The target cluster id. 21251 */ 21252 getChildren(clusterId) { 21253 const originId = this.getOriginId(clusterId); 21254 const originZoom = this.getOriginZoom(clusterId); 21255 const clusterError = /* @__PURE__ */ new Error("No cluster with the specified id: " + clusterId); 21256 const tree = this.trees[originZoom]; 21257 if (!tree) throw clusterError; 21258 const data = tree.flatData; 21259 if (originId * this.stride >= data.length) throw clusterError; 21260 const r = this.options.radius / (this.options.extent * Math.pow(2, originZoom - 1)); 21261 const x = data[originId * this.stride]; 21262 const y = data[originId * this.stride + 1]; 21263 const ids = tree.within(x, y, r); 21264 const children = []; 21265 for (const id of ids) { 21266 const k = id * this.stride; 21267 if (data[k + OFFSET_PARENT] === clusterId) children.push(data[k + OFFSET_NUM] > 1 ? getClusterGeoJSON(data, k, this.clusterProps) : featureToGeoJSON(this.points[data[k + OFFSET_ID]])); 21268 } 21269 if (children.length === 0) throw clusterError; 21270 return children; 21271 } 21272 /** 21273 * Returns leaf point features under a cluster, paginated by `limit` and `offset`. 21274 * @param clusterId - The target cluster id. 21275 * @param limit - Maximum number of points to return (defaults to `10`). 21276 * @param offset - Number of points to skip before collecting results (defaults to `0`). 21277 */ 21278 getLeaves(clusterId, limit, offset) { 21279 limit = limit || 10; 21280 offset = offset || 0; 21281 const leaves = []; 21282 this.appendLeaves(leaves, clusterId, limit, offset, 0); 21283 return leaves; 21284 } 21285 /** 21286 * Generates a vector-tile-like representation of a single tile. 21287 * @param z - Tile zoom. 21288 * @param x - Tile x coordinate. 21289 * @param y - Tile y coordinate. 21290 */ 21291 getTile(z, x, y) { 21292 const tree = this.trees[this.limitZoom(z)]; 21293 if (!tree) return null; 21294 const z2 = Math.pow(2, z); 21295 const { extent, radius } = this.options; 21296 const p = radius / extent; 21297 const top = (y - p) / z2; 21298 const bottom = (y + 1 + p) / z2; 21299 const tile = { 21300 transformed: true, 21301 features: [], 21302 source: null, 21303 x, 21304 y, 21305 z 21306 }; 21307 this.addTileFeatures(tree.range((x - p) / z2, top, (x + 1 + p) / z2, bottom), tree.flatData, x, y, z2, tile); 21308 if (x === 0) this.addTileFeatures(tree.range(1 - p / z2, top, 1, bottom), tree.flatData, z2, y, z2, tile); 21309 if (x === z2 - 1) this.addTileFeatures(tree.range(0, top, p / z2, bottom), tree.flatData, -1, y, z2, tile); 21310 return tile; 21311 } 21312 /** 21313 * Returns the zoom level at which a cluster expands into multiple children. 21314 * @param clusterId - The target cluster id. 21315 */ 21316 getClusterExpansionZoom(clusterId) { 21317 return this.getOriginZoom(clusterId); 21318 } 21319 appendLeaves(result, clusterId, limit, offset, skipped) { 21320 const children = this.getChildren(clusterId); 21321 for (const child of children) { 21322 const props = child.properties; 21323 if (props?.cluster) if (skipped + props.point_count <= offset) skipped += props.point_count; 21324 else skipped = this.appendLeaves(result, props.cluster_id, limit, offset, skipped); 21325 else if (skipped < offset) skipped++; 21326 else result.push(child); 21327 if (result.length === limit) break; 21328 } 21329 return skipped; 21330 } 21331 createTree(data) { 21332 const tree = new KDBush(data.length / this.stride | 0, this.options.nodeSize, Float32Array); 21333 for (let i = 0; i < data.length; i += this.stride) tree.add(data[i], data[i + 1]); 21334 tree.finish(); 21335 tree.flatData = data; 21336 tree.data = null; 21337 return tree; 21338 } 21339 addTileFeatures(ids, data, x, y, z2, tile) { 21340 for (const i of ids) { 21341 const k = i * this.stride; 21342 const isCluster = data[k + OFFSET_NUM] > 1; 21343 let tags; 21344 let px; 21345 let py; 21346 if (isCluster) { 21347 tags = getClusterProperties(data, k, this.clusterProps); 21348 px = data[k]; 21349 py = data[k + 1]; 21350 } else { 21351 const p = this.points[data[k + OFFSET_ID]]; 21352 tags = p.tags; 21353 [px, py] = p.geometry; 21354 } 21355 const f = { 21356 type: 1, 21357 geometry: [[Math.round(this.options.extent * (px * z2 - x)), Math.round(this.options.extent * (py * z2 - y))]], 21358 tags 21359 }; 21360 let id; 21361 if (isCluster || this.options.generateId) id = data[k + OFFSET_ID]; 21362 else id = this.points[data[k + OFFSET_ID]].id; 21363 if (id !== void 0) f.id = id; 21364 tile.features.push(f); 21365 } 21366 } 21367 limitZoom(z) { 21368 return Math.max(this.options.minZoom, Math.min(Math.floor(+z), this.options.maxZoom + 1)); 21369 } 21370 cluster(tree, zoom) { 21371 const { radius, extent, reduce, minPoints } = this.options; 21372 const r = radius / (extent * Math.pow(2, zoom)); 21373 const data = tree.flatData; 21374 const nextData = []; 21375 const stride = this.stride; 21376 for (let i = 0; i < data.length; i += stride) { 21377 if (data[i + OFFSET_ZOOM] <= zoom) continue; 21378 data[i + OFFSET_ZOOM] = zoom; 21379 const x = data[i]; 21380 const y = data[i + 1]; 21381 const neighborIds = tree.within(data[i], data[i + 1], r); 21382 const numPointsOrigin = data[i + OFFSET_NUM]; 21383 let numPoints = numPointsOrigin; 21384 for (const neighborId of neighborIds) { 21385 const k = neighborId * stride; 21386 if (data[k + OFFSET_ZOOM] > zoom) numPoints += data[k + OFFSET_NUM]; 21387 } 21388 if (numPoints > numPointsOrigin && numPoints >= minPoints) { 21389 let wx = x * numPointsOrigin; 21390 let wy = y * numPointsOrigin; 21391 let clusterProperties; 21392 let clusterPropIndex = -1; 21393 const id = ((i / stride | 0) << 5) + (zoom + 1) + this.points.length; 21394 for (const neighborId of neighborIds) { 21395 const k = neighborId * stride; 21396 if (data[k + OFFSET_ZOOM] <= zoom) continue; 21397 data[k + OFFSET_ZOOM] = zoom; 21398 const numPoints2 = data[k + OFFSET_NUM]; 21399 wx += data[k] * numPoints2; 21400 wy += data[k + 1] * numPoints2; 21401 data[k + OFFSET_PARENT] = id; 21402 if (reduce) { 21403 if (!clusterProperties) { 21404 clusterProperties = this.map(data, i, true); 21405 clusterPropIndex = this.clusterProps.length; 21406 this.clusterProps.push(clusterProperties); 21407 } 21408 reduce(clusterProperties, this.map(data, k)); 21409 } 21410 } 21411 data[i + OFFSET_PARENT] = id; 21412 nextData.push(wx / numPoints, wy / numPoints, Infinity, id, -1, numPoints); 21413 if (reduce) nextData.push(clusterPropIndex); 21414 } else { 21415 for (let j = 0; j < stride; j++) nextData.push(data[i + j]); 21416 if (numPoints > 1) for (const neighborId of neighborIds) { 21417 const k = neighborId * stride; 21418 if (data[k + OFFSET_ZOOM] <= zoom) continue; 21419 data[k + OFFSET_ZOOM] = zoom; 21420 for (let j = 0; j < stride; j++) nextData.push(data[k + j]); 21421 } 21422 } 21423 } 21424 return nextData; 21425 } 21426 getOriginId(clusterId) { 21427 return clusterId - this.points.length >> 5; 21428 } 21429 getOriginZoom(clusterId) { 21430 return (clusterId - this.points.length) % 32; 21431 } 21432 map(data, i, clone) { 21433 if (data[i + OFFSET_NUM] > 1) { 21434 const props = this.clusterProps[data[i + OFFSET_PROP]]; 21435 return clone ? Object.assign({}, props) : props; 21436 } 21437 const original = this.points[data[i + OFFSET_ID]].tags; 21438 const result = this.options.map(original); 21439 return clone && result === original ? Object.assign({}, result) : result; 21440 } 21441}; 21442function getClusterFeature(data, i, clusterProps) { 21443 return { 21444 id: data[i + OFFSET_ID], 21445 type: "Point", 21446 tags: getClusterProperties(data, i, clusterProps), 21447 geometry: [data[i], data[i + 1]] 21448 }; 21449} 21450function getClusterGeoJSON(data, i, clusterProps) { 21451 return { 21452 type: "Feature", 21453 id: data[i + OFFSET_ID], 21454 properties: getClusterProperties(data, i, clusterProps), 21455 geometry: { 21456 type: "Point", 21457 coordinates: [unprojectX(data[i]), unprojectY(data[i + 1])] 21458 } 21459 }; 21460} 21461function getClusterProperties(data, i, clusterProps) { 21462 const count = data[i + OFFSET_NUM]; 21463 const abbrev = count >= 1e4 ? `${Math.round(count / 1e3)}k` : count >= 1e3 ? `${Math.round(count / 100) / 10}k` : count; 21464 const propIndex = data[i + OFFSET_PROP]; 21465 const properties = propIndex === -1 ? {} : Object.assign({}, clusterProps[propIndex]); 21466 return Object.assign(properties, { 21467 cluster: true, 21468 cluster_id: data[i + OFFSET_ID], 21469 point_count: count, 21470 point_count_abbreviated: abbrev 21471 }); 21472} 21473const GEOJSONVT_CLIP_START = "geojsonvt_clip_start"; 21474const GEOJSONVT_CLIP_END = "geojsonvt_clip_end"; 21475/** 21476* Creates a tile object from the given features 21477* @param features - the features to include in the tile 21478* @param z 21479* @param tx 21480* @param ty 21481* @param options - the options object 21482* @returns the created tile 21483*/ 21484function createTile(features, z, tx, ty, options) { 21485 const tolerance = z === options.maxZoom ? 0 : options.tolerance / ((1 << z) * options.extent); 21486 const tile = { 21487 transformed: false, 21488 features: [], 21489 source: null, 21490 x: tx, 21491 y: ty, 21492 z, 21493 minX: 2, 21494 minY: 1, 21495 maxX: -1, 21496 maxY: 0, 21497 numPoints: 0, 21498 numSimplified: 0, 21499 numFeatures: features.length 21500 }; 21501 for (const feature of features) addFeature$1(tile, feature, tolerance, options); 21502 return tile; 21503} 21504function addFeature$1(tile, feature, tolerance, options) { 21505 tile.minX = Math.min(tile.minX, feature.minX); 21506 tile.minY = Math.min(tile.minY, feature.minY); 21507 tile.maxX = Math.max(tile.maxX, feature.maxX); 21508 tile.maxY = Math.max(tile.maxY, feature.maxY); 21509 switch (feature.type) { 21510 case "Point": 21511 case "MultiPoint": 21512 addPointsTileFeature(tile, feature); 21513 return; 21514 case "LineString": 21515 addLineTileFeautre(tile, feature, tolerance, options); 21516 return; 21517 case "MultiLineString": 21518 case "Polygon": 21519 addLinesTileFeature(tile, feature, tolerance); 21520 return; 21521 case "MultiPolygon": 21522 addMultiPolygonTileFeature(tile, feature, tolerance); 21523 return; 21524 } 21525} 21526function addPointsTileFeature(tile, feature) { 21527 const geometry = []; 21528 for (let i = 0; i < feature.geometry.length; i += 3) { 21529 geometry.push(feature.geometry[i], feature.geometry[i + 1]); 21530 tile.numPoints++; 21531 tile.numSimplified++; 21532 } 21533 if (!geometry.length) return; 21534 const tileFeature = { 21535 type: 1, 21536 tags: feature.tags || null, 21537 geometry 21538 }; 21539 if (feature.id !== null) tileFeature.id = feature.id; 21540 tile.features.push(tileFeature); 21541} 21542function addLineTileFeautre(tile, feature, tolerance, options) { 21543 const geometry = []; 21544 addLine(geometry, feature.geometry, tile, tolerance, false, false); 21545 if (!geometry.length) return; 21546 let tags = feature.tags || null; 21547 if (options.lineMetrics) { 21548 tags = {}; 21549 for (const key in feature.tags) tags[key] = feature.tags[key]; 21550 tags[GEOJSONVT_CLIP_START] = feature.geometry.start / feature.geometry.size; 21551 tags[GEOJSONVT_CLIP_END] = feature.geometry.end / feature.geometry.size; 21552 } 21553 const tileFeature = { 21554 type: 2, 21555 tags, 21556 geometry 21557 }; 21558 if (feature.id !== null) tileFeature.id = feature.id; 21559 tile.features.push(tileFeature); 21560} 21561function addLinesTileFeature(tile, feature, tolerance) { 21562 const geometry = []; 21563 for (let i = 0; i < feature.geometry.length; i++) addLine(geometry, feature.geometry[i], tile, tolerance, feature.type === "Polygon", i === 0); 21564 if (!geometry.length) return; 21565 const tileFeature = { 21566 type: feature.type === "Polygon" ? 3 : 2, 21567 tags: feature.tags || null, 21568 geometry 21569 }; 21570 if (feature.id !== null) tileFeature.id = feature.id; 21571 tile.features.push(tileFeature); 21572} 21573function addMultiPolygonTileFeature(tile, feature, tolerance) { 21574 const geometry = []; 21575 for (let k = 0; k < feature.geometry.length; k++) { 21576 const polygon = feature.geometry[k]; 21577 for (let i = 0; i < polygon.length; i++) addLine(geometry, polygon[i], tile, tolerance, true, i === 0); 21578 } 21579 if (!geometry.length) return; 21580 const tileFeature = { 21581 type: 3, 21582 tags: feature.tags || null, 21583 geometry 21584 }; 21585 if (feature.id !== null) tileFeature.id = feature.id; 21586 tile.features.push(tileFeature); 21587} 21588function addLine(result, geom, tile, tolerance, isPolygon, isOuter) { 21589 const sqTolerance = tolerance * tolerance; 21590 if (tolerance > 0 && geom.size < (isPolygon ? sqTolerance : tolerance)) { 21591 tile.numPoints += geom.points.length / 3; 21592 return; 21593 } 21594 const ring = []; 21595 for (let i = 0; i < geom.points.length; i += 3) { 21596 if (tolerance === 0 || geom.points[i + 2] > sqTolerance) { 21597 tile.numSimplified++; 21598 ring.push(geom.points[i], geom.points[i + 1]); 21599 } 21600 tile.numPoints++; 21601 } 21602 if (isPolygon) rewind(ring, isOuter); 21603 result.push(ring); 21604} 21605function rewind(ring, clockwise) { 21606 let area = 0; 21607 for (let i = 0, len = ring.length, j = len - 2; i < len; j = i, i += 2) area += (ring[i] - ring[j]) * (ring[i + 1] + ring[j + 1]); 21608 if (area > 0 !== clockwise) return; 21609 for (let i = 0, len = ring.length; i < len / 2; i += 2) { 21610 const x = ring[i]; 21611 const y = ring[i + 1]; 21612 ring[i] = ring[len - 2 - i]; 21613 ring[i + 1] = ring[len - 1 - i]; 21614 ring[len - 2 - i] = x; 21615 ring[len - 1 - i] = y; 21616 } 21617} 21618/** 21619* Transforms the coordinates of each feature in the given tile from 21620* mercator-projected space into (extent x extent) tile space. 21621* @param tile - the tile to transform, this gets modified in place 21622* @param extent - the tile extent (usually 4096) 21623* @returns the transformed tile 21624*/ 21625function transformTile(tile, extent) { 21626 if (tile.transformed) return tile; 21627 const z2 = 1 << tile.z; 21628 const tx = tile.x; 21629 const ty = tile.y; 21630 for (const feature of tile.features) if (feature.type === 1) transformPointFeature(feature, extent, z2, tx, ty); 21631 else transformNonPointFeature(feature, extent, z2, tx, ty); 21632 tile.transformed = true; 21633 return tile; 21634} 21635/** 21636* Transforms a single point feature from mercator-projected space into (extent x extent) tile space. 21637*/ 21638function transformPointFeature(feature, extent, z2, tx, ty) { 21639 const transformed = feature; 21640 const geometry = feature.geometry; 21641 const point = []; 21642 for (let i = 0; i < geometry.length; i += 2) point.push(transformPoint(geometry[i], geometry[i + 1], extent, z2, tx, ty)); 21643 transformed.geometry = point; 21644 return transformed; 21645} 21646/** 21647* Transforms a single non-point feature from mercator-projected space into (extent x extent) tile space. 21648*/ 21649function transformNonPointFeature(feature, extent, z2, tx, ty) { 21650 const transformed = feature; 21651 const geometry = feature.geometry; 21652 const nonPoint = []; 21653 for (const geom of geometry) { 21654 const ring = []; 21655 for (let i = 0; i < geom.length; i += 2) ring.push(transformPoint(geom[i], geom[i + 1], extent, z2, tx, ty)); 21656 nonPoint.push(ring); 21657 } 21658 transformed.geometry = nonPoint; 21659 return transformed; 21660} 21661function transformPoint(x, y, extent, z2, tx, ty) { 21662 return [Math.round(extent * (x * z2 - tx)), Math.round(extent * (y * z2 - ty))]; 21663} 21664var TileIndex = class { 21665 constructor(options) { 21666 this.options = options; 21667 this.total = 0; 21668 this.stats = {}; 21669 this.tiles = {}; 21670 this.tileCoords = []; 21671 this.stats = {}; 21672 this.total = 0; 21673 } 21674 initialize(features) { 21675 this.splitTile(features, 0, 0, 0); 21676 if (this.options.debug) { 21677 if (features.length) console.log("features: %d, points: %d", this.tiles[0].numFeatures, this.tiles[0].numPoints); 21678 console.timeEnd("generate tiles"); 21679 console.log("tiles generated:", this.total, JSON.stringify(this.stats)); 21680 } 21681 } 21682 /** {@inheritdoc} */ 21683 updateIndex(source, affected, options) { 21684 if (options.debug > 1) { 21685 console.log("invalidating tiles"); 21686 console.time("invalidating"); 21687 } 21688 this.invalidateTiles(affected); 21689 if (options.debug > 1) console.timeEnd("invalidating"); 21690 const [z, x, y] = [ 21691 0, 21692 0, 21693 0 21694 ]; 21695 const rootTile = createTile(source, z, x, y, options); 21696 rootTile.source = source; 21697 const id = toID(z, x, y); 21698 this.tiles[id] = rootTile; 21699 this.tileCoords.push({ 21700 z, 21701 x, 21702 y, 21703 id 21704 }); 21705 if (options.debug) { 21706 const key = `z${z}`; 21707 this.stats[key] = (this.stats[key] || 0) + 1; 21708 this.total++; 21709 } 21710 } 21711 /** {@inheritdoc} */ 21712 getClusterExpansionZoom(_clusterId) { 21713 return null; 21714 } 21715 /** {@inheritdoc} */ 21716 getChildren(_clusterId) { 21717 return null; 21718 } 21719 /** {@inheritdoc} */ 21720 getLeaves(_clusterId, _limit, _offset) { 21721 return null; 21722 } 21723 /** {@inheritdoc} */ 21724 getTile(z, x, y) { 21725 const { extent, debug } = this.options; 21726 const z2 = 1 << z; 21727 x = x + z2 & z2 - 1; 21728 const id = toID(z, x, y); 21729 if (this.tiles[id]) return transformTile(this.tiles[id], extent); 21730 if (debug > 1) console.log("drilling down to z%d-%d-%d", z, x, y); 21731 let z0 = z; 21732 let x0 = x; 21733 let y0 = y; 21734 let parent; 21735 while (!parent && z0 > 0) { 21736 z0--; 21737 x0 = x0 >> 1; 21738 y0 = y0 >> 1; 21739 parent = this.tiles[toID(z0, x0, y0)]; 21740 } 21741 if (!parent?.source) return null; 21742 if (debug > 1) { 21743 console.log("found parent tile z%d-%d-%d", z0, x0, y0); 21744 console.time("drilling down"); 21745 } 21746 this.splitTile(parent.source, z0, x0, y0, z, x, y); 21747 if (debug > 1) console.timeEnd("drilling down"); 21748 if (!this.tiles[id]) return null; 21749 return transformTile(this.tiles[id], extent); 21750 } 21751 /** 21752 * splits features from a parent tile to sub-tiles. 21753 * z, x, and y are the coordinates of the parent tile 21754 * cz, cx, and cy are the coordinates of the target tile 21755 * 21756 * If no target tile is specified, splitting stops when we reach the maximum 21757 * zoom or the number of points is low as specified in the options. 21758 * @internal 21759 * @param features - features to split 21760 * @param z - tile zoom level 21761 * @param x - tile x coordinate 21762 * @param y - tile y coordinate 21763 * @param cz - target tile zoom level 21764 * @param cx - target tile x coordinate 21765 * @param cy - target tile y coordinate 21766 */ 21767 splitTile(features, z, x, y, cz, cx, cy) { 21768 const stack = [ 21769 features, 21770 z, 21771 x, 21772 y 21773 ]; 21774 const options = this.options; 21775 const debug = options.debug; 21776 while (stack.length) { 21777 y = stack.pop(); 21778 x = stack.pop(); 21779 z = stack.pop(); 21780 features = stack.pop(); 21781 const z2 = 1 << z; 21782 const id = toID(z, x, y); 21783 let tile = this.tiles[id]; 21784 if (!tile) { 21785 if (debug > 1) console.time("creation"); 21786 tile = this.tiles[id] = createTile(features, z, x, y, options); 21787 this.tileCoords.push({ 21788 z, 21789 x, 21790 y, 21791 id 21792 }); 21793 if (debug) { 21794 if (debug > 1) { 21795 console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)", z, x, y, tile.numFeatures, tile.numPoints, tile.numSimplified); 21796 console.timeEnd("creation"); 21797 } 21798 const key = `z${z}`; 21799 this.stats[key] = (this.stats[key] || 0) + 1; 21800 this.total++; 21801 } 21802 } 21803 tile.source = features; 21804 if (cz == null) { 21805 if (z === options.indexMaxZoom || tile.numPoints <= options.indexMaxPoints) continue; 21806 } else if (z === options.maxZoom || z === cz) continue; 21807 else if (cz != null) { 21808 const zoomSteps = cz - z; 21809 if (x !== cx >> zoomSteps || y !== cy >> zoomSteps) continue; 21810 } 21811 tile.source = null; 21812 if (!features.length) continue; 21813 if (debug > 1) console.time("clipping"); 21814 const k1 = .5 * options.buffer / options.extent; 21815 const k2 = .5 - k1; 21816 const k3 = .5 + k1; 21817 const k4 = 1 + k1; 21818 let tl = null; 21819 let bl = null; 21820 let tr = null; 21821 let br = null; 21822 const left = clip(features, z2, x - k1, x + k3, 0, tile.minX, tile.maxX, options); 21823 const right = clip(features, z2, x + k2, x + k4, 0, tile.minX, tile.maxX, options); 21824 if (left) { 21825 tl = clip(left, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options); 21826 bl = clip(left, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options); 21827 } 21828 if (right) { 21829 tr = clip(right, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options); 21830 br = clip(right, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options); 21831 } 21832 if (debug > 1) console.timeEnd("clipping"); 21833 stack.push(tl || [], z + 1, x * 2, y * 2); 21834 stack.push(bl || [], z + 1, x * 2, y * 2 + 1); 21835 stack.push(tr || [], z + 1, x * 2 + 1, y * 2); 21836 stack.push(br || [], z + 1, x * 2 + 1, y * 2 + 1); 21837 } 21838 } 21839 /** 21840 * Invalidates (removes) tiles affected by the provided features 21841 * @internal 21842 * @param features 21843 */ 21844 invalidateTiles(features) { 21845 if (!features.length) return; 21846 const options = this.options; 21847 const { debug } = options; 21848 let minX = Infinity; 21849 let maxX = -Infinity; 21850 let minY = Infinity; 21851 let maxY = -Infinity; 21852 for (const feature of features) { 21853 minX = Math.min(minX, feature.minX); 21854 maxX = Math.max(maxX, feature.maxX); 21855 minY = Math.min(minY, feature.minY); 21856 maxY = Math.max(maxY, feature.maxY); 21857 } 21858 const k1 = options.buffer / options.extent; 21859 const removedLookup = /* @__PURE__ */ new Set(); 21860 for (const id in this.tiles) { 21861 const tile = this.tiles[id]; 21862 const z2 = 1 << tile.z; 21863 const tileMinX = (tile.x - k1) / z2; 21864 const tileMaxX = (tile.x + 1 + k1) / z2; 21865 const tileMinY = (tile.y - k1) / z2; 21866 const tileMaxY = (tile.y + 1 + k1) / z2; 21867 if (maxX < tileMinX || minX >= tileMaxX || maxY < tileMinY || minY >= tileMaxY) continue; 21868 let intersects = false; 21869 for (const feature of features) if (feature.maxX >= tileMinX && feature.minX < tileMaxX && feature.maxY >= tileMinY && feature.minY < tileMaxY) { 21870 intersects = true; 21871 break; 21872 } 21873 if (!intersects) continue; 21874 if (debug) { 21875 if (debug > 1) console.log("invalidate tile z%d-%d-%d (features: %d, points: %d, simplified: %d)", tile.z, tile.x, tile.y, tile.numFeatures, tile.numPoints, tile.numSimplified); 21876 const key = `z${tile.z}`; 21877 this.stats[key] = (this.stats[key] || 0) - 1; 21878 this.total--; 21879 } 21880 delete this.tiles[id]; 21881 removedLookup.add(id); 21882 } 21883 if (removedLookup.size) this.tileCoords = this.tileCoords.filter((c) => !removedLookup.has(c.id)); 21884 } 21885}; 21886function toID(z, x, y) { 21887 return ((1 << z) * y + x) * 32 + z; 21888} 21889const defaultOptions = { 21890 maxZoom: 14, 21891 indexMaxZoom: 5, 21892 indexMaxPoints: 1e5, 21893 tolerance: 3, 21894 extent: 4096, 21895 buffer: 64, 21896 lineMetrics: false, 21897 promoteId: null, 21898 generateId: false, 21899 updateable: false, 21900 cluster: false, 21901 clusterOptions: defaultClusterOptions, 21902 debug: 0 21903}; 21904/** 21905* Main class for creating and managing a vector tile index from GeoJSON data. 21906*/ 21907var GeoJSONVT = class { 21908 constructor(data, options) { 21909 options = this.options = Object.assign({}, defaultOptions, options); 21910 const debug = options.debug; 21911 if (debug) console.time("preprocess data"); 21912 if (options.maxZoom < 0 || options.maxZoom > 24) throw new Error("maxZoom should be in the 0-24 range"); 21913 if (options.promoteId && options.generateId) throw new Error("promoteId and generateId cannot be used together."); 21914 let features = convertToInternal(data, options); 21915 if (debug) { 21916 console.timeEnd("preprocess data"); 21917 console.log("index: maxZoom: %d, maxPoints: %d", options.indexMaxZoom, options.indexMaxPoints); 21918 console.time("generate tiles"); 21919 } 21920 features = wrap(features, options); 21921 if (options.updateable) this.source = features; 21922 this.initializeIndex(features, options); 21923 } 21924 initializeIndex(features, options) { 21925 this.tileIndex = options.cluster ? new ClusterTileIndex(options.clusterOptions) : new TileIndex(options); 21926 if (!features.length) return; 21927 this.tileIndex.initialize(features); 21928 } 21929 /** 21930 * Given z, x, and y tile coordinates, returns the corresponding tile with geometries in tile coordinates, much like MVT data is stored. 21931 * @param z - tile zoom level 21932 * @param x - tile x coordinate 21933 * @param y - tile y coordinate 21934 * @returns the transformed tile or null if not found 21935 */ 21936 getTile(z, x, y) { 21937 z = +z; 21938 x = +x; 21939 y = +y; 21940 if (z < 0 || z > 24) return null; 21941 return this.tileIndex.getTile(z, x, y); 21942 } 21943 /** 21944 * Updates the source data feature set using a {@link GeoJSONVTSourceDiff} 21945 * @param diff - the source diff object 21946 */ 21947 updateData(diff, filter) { 21948 const options = this.options; 21949 if (!options.updateable) throw new Error("to update tile geojson `updateable` option must be set to true"); 21950 let { affected, source } = applySourceDiff(this.source, diff, options); 21951 if (filter) ({affected, source} = this.filterUpdate(source, affected, filter)); 21952 if (!affected.length) return; 21953 this.source = source; 21954 this.tileIndex.updateIndex(source, affected, options); 21955 } 21956 /** 21957 * Filter an update using a predicate function. Returns the affected and updated source features. 21958 */ 21959 filterUpdate(source, affected, predicate) { 21960 const removeIds = /* @__PURE__ */ new Set(); 21961 for (const feature of source) { 21962 if (feature.id == void 0) continue; 21963 if (predicate(featureToGeoJSON(feature))) continue; 21964 affected.push(feature); 21965 removeIds.add(feature.id); 21966 } 21967 source = source.filter((feature) => !removeIds.has(feature.id)); 21968 return { 21969 affected, 21970 source 21971 }; 21972 } 21973 /** 21974 * Returns source data as GeoJSON - only available when `updateable` option is set to true. 21975 */ 21976 getData() { 21977 if (!this.options.updateable) throw new Error("to retrieve data the `updateable` option must be set to true"); 21978 return convertToGeoJSON(this.source); 21979 } 21980 /** 21981 * Update supercluster options and regenerate the index. 21982 * @param cluster - whether to enable clustering 21983 * @param clusterOptions - {@link SuperclusterOptions} 21984 */ 21985 updateClusterOptions(cluster, clusterOptions) { 21986 const wasCluster = this.options.cluster; 21987 this.options.cluster = cluster; 21988 this.options.clusterOptions = clusterOptions; 21989 if (wasCluster == cluster) { 21990 this.tileIndex.updateIndex(this.source, [], this.options); 21991 return; 21992 } 21993 this.initializeIndex(this.source, this.options); 21994 } 21995 /** 21996 * Returns the zoom level at which a cluster expands into multiple children. 21997 * @param clusterId - The target cluster id. 21998 * @returns the expansion zoom or null in case of non-clustered source 21999 */ 22000 getClusterExpansionZoom(clusterId) { 22001 return this.tileIndex.getClusterExpansionZoom(clusterId); 22002 } 22003 /** 22004 * Returns the immediate children (clusters or points) of a cluster as GeoJSON. 22005 * @param clusterId - The target cluster id. 22006 * @returns the immediate children or null in case of non-clustered source 22007 */ 22008 getClusterChildren(clusterId) { 22009 return this.tileIndex.getChildren(clusterId); 22010 } 22011 /** 22012 * Returns leaf point features under a cluster, paginated by `limit` and `offset`. 22013 * @param clusterId - The target cluster id. 22014 * @param limit - Maximum number of points to return (defaults to `10`). 22015 * @param offset - Number of points to skip before collecting results (defaults to `0`). 22016 * @returns leaf point features under a cluster or null in case of non-clustered source 22017 */ 22018 getClusterLeaves(clusterId, limit, offset) { 22019 return this.tileIndex.getLeaves(clusterId, limit, offset); 22020 } 22021}; 22022//#endregion 22023//#region src/data/bucket/line_attributes.ts 22024const lineLayoutAttributes = createLayout([{ 22025 name: "a_pos_normal", 22026 components: 2, 22027 type: "Int16" 22028}, { 22029 name: "a_data", 22030 components: 4, 22031 type: "Uint8" 22032}], 4); 22033const members$1 = lineLayoutAttributes.members; 22034lineLayoutAttributes.size; 22035lineLayoutAttributes.alignment; 22036//#endregion 22037//#region src/data/bucket/line_attributes_ext.ts 22038const lineLayoutAttributesExt = createLayout([{ 22039 name: "a_uv_x", 22040 components: 1, 22041 type: "Float32" 22042}, { 22043 name: "a_split_index", 22044 components: 1, 22045 type: "Float32" 22046}]); 22047const members = lineLayoutAttributesExt.members; 22048lineLayoutAttributesExt.size; 22049lineLayoutAttributesExt.alignment; 22050//#endregion 22051//#region src/data/bucket/line_bucket.ts 22052const EXTRUDE_SCALE = 63; 22053const COS_HALF_SHARP_CORNER = Math.cos(75 / 2 * (Math.PI / 180)); 22054const SHARP_CORNER_OFFSET = 15; 22055const DEG_PER_TRIANGLE = 20; 22056const LINE_DISTANCE_SCALE = 1 / 2; 22057const MAX_LINE_DISTANCE = Math.pow(2, 14) / LINE_DISTANCE_SCALE; 22058/** 22059* @internal 22060* Line bucket class 22061*/ 22062var LineBucket = class { 22063 constructor(options) { 22064 this.zoom = options.zoom; 22065 this.overscaling = options.overscaling; 22066 this.layers = options.layers; 22067 this.layerIds = this.layers.map((layer) => layer.id); 22068 this.index = options.index; 22069 this.hasDependencies = false; 22070 this.patternFeatures = []; 22071 this.lineClipsArray = []; 22072 this.gradients = {}; 22073 for (const layer of this.layers) this.gradients[layer.id] = {}; 22074 this.layoutVertexArray = new LineLayoutArray(); 22075 this.layoutVertexArray2 = new LineExtLayoutArray(); 22076 this.indexArray = new TriangleIndexArray(); 22077 this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom); 22078 this.segments = new SegmentVector(); 22079 this.maxLineLength = 0; 22080 this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); 22081 } 22082 populate(features, options, canonical) { 22083 this.hasDependencies = hasPattern("line", this.layers, options) || this.hasLineDasharray(this.layers); 22084 const lineSortKey = this.layers[0].layout.get("line-sort-key"); 22085 const sortFeaturesByKey = !lineSortKey.isConstant(); 22086 const bucketFeatures = []; 22087 const globalProperties = new EvaluationParameters(this.zoom); 22088 const needGeometry = this.layers[0]._featureFilter.needGeometry; 22089 for (const { feature, id, index, sourceLayerIndex } of features) { 22090 const evaluationFeature = toEvaluationFeature(feature, needGeometry); 22091 if (!this.layers[0]._featureFilter.filter(globalProperties, evaluationFeature, canonical)) continue; 22092 const sortKey = sortFeaturesByKey ? lineSortKey.evaluate(evaluationFeature, {}, canonical) : void 0; 22093 const bucketFeature = { 22094 id, 22095 properties: feature.properties, 22096 type: feature.type, 22097 sourceLayerIndex, 22098 index, 22099 geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature), 22100 patterns: {}, 22101 dashes: {}, 22102 sortKey 22103 }; 22104 bucketFeatures.push(bucketFeature); 22105 } 22106 if (sortFeaturesByKey) bucketFeatures.sort((a, b) => { 22107 return a.sortKey - b.sortKey; 22108 }); 22109 for (const bucketFeature of bucketFeatures) { 22110 const { geometry, index, sourceLayerIndex } = bucketFeature; 22111 if (this.hasDependencies) { 22112 if (hasPattern("line", this.layers, options)) addPatternDependencies("line", this.layers, bucketFeature, { zoom: this.zoom }, options); 22113 else if (this.hasLineDasharray(this.layers)) this.addLineDashDependencies(this.layers, bucketFeature, this.zoom, options); 22114 this.patternFeatures.push(bucketFeature); 22115 } else this.addFeature(bucketFeature, geometry, index, canonical, {}, {}, options.subdivisionGranularity); 22116 const feature = features[index].feature; 22117 options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index); 22118 } 22119 } 22120 update(states, vtLayer, imagePositions, dashPositions) { 22121 if (!this.stateDependentLayers.length) return; 22122 this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, { 22123 imagePositions, 22124 dashPositions 22125 }); 22126 } 22127 addFeatures({ options, canonical, patternPositions, dashPositions }) { 22128 for (const feature of this.patternFeatures) this.addFeature(feature, feature.geometry, feature.index, canonical, patternPositions, dashPositions, options.subdivisionGranularity); 22129 } 22130 isEmpty() { 22131 return this.layoutVertexArray.length === 0; 22132 } 22133 uploadPending() { 22134 return !this.uploaded || this.programConfigurations.needsUpload; 22135 } 22136 upload(context) { 22137 if (!this.uploaded) { 22138 if (this.layoutVertexArray2.length !== 0) this.layoutVertexBuffer2 = context.createVertexBuffer(this.layoutVertexArray2, members); 22139 this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$1); 22140 this.indexBuffer = context.createIndexBuffer(this.indexArray); 22141 } 22142 this.programConfigurations.upload(context); 22143 this.uploaded = true; 22144 } 22145 destroy() { 22146 if (!this.layoutVertexBuffer) return; 22147 this.layoutVertexBuffer.destroy(); 22148 this.indexBuffer.destroy(); 22149 this.programConfigurations.destroy(); 22150 this.segments.destroy(); 22151 } 22152 lineFeatureClips(feature) { 22153 if (!!feature.properties && Object.hasOwn(feature.properties, "geojsonvt_clip_start") && Object.hasOwn(feature.properties, "geojsonvt_clip_end")) return { 22154 start: +feature.properties[GEOJSONVT_CLIP_START], 22155 end: +feature.properties[GEOJSONVT_CLIP_END] 22156 }; 22157 } 22158 addFeature(feature, geometry, index, canonical, imagePositions, dashPositions, subdivisionGranularity) { 22159 const layout = this.layers[0].layout; 22160 const join = layout.get("line-join").evaluate(feature, {}); 22161 const cap = layout.get("line-cap").evaluate(feature, {}); 22162 const miterLimit = layout.get("line-miter-limit").evaluate(feature, {}); 22163 const roundLimit = layout.get("line-round-limit").evaluate(feature, {}); 22164 this.lineClips = this.lineFeatureClips(feature); 22165 for (const line of geometry) this.addLine(line, feature, join, cap, miterLimit, roundLimit, canonical, subdivisionGranularity); 22166 this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, { 22167 imagePositions, 22168 dashPositions, 22169 canonical 22170 }); 22171 } 22172 addLine(vertices, feature, join, cap, miterLimit, roundLimit, canonical, subdivisionGranularity) { 22173 this.distance = 0; 22174 this.scaledDistance = 0; 22175 this.totalDistance = 0; 22176 const granularity = canonical ? subdivisionGranularity.line.getGranularityForZoomLevel(canonical.z) : 1; 22177 vertices = subdivideVertexLine(vertices, granularity); 22178 if (this.lineClips) { 22179 this.lineClipsArray.push(this.lineClips); 22180 for (let i = 0; i < vertices.length - 1; i++) this.totalDistance += vertices[i].dist(vertices[i + 1]); 22181 this.updateScaledDistance(); 22182 this.maxLineLength = Math.max(this.maxLineLength, this.totalDistance); 22183 } 22184 const isPolygon = VectorTileFeature.types[feature.type] === "Polygon"; 22185 let len = vertices.length; 22186 while (len >= 2 && vertices[len - 1].equals(vertices[len - 2])) len--; 22187 let first = 0; 22188 while (first < len - 1 && vertices[first].equals(vertices[first + 1])) first++; 22189 if (len - first < (isPolygon ? 3 : 2)) return; 22190 if (join === "bevel") miterLimit = 1.05; 22191 const sharpCornerOffset = this.overscaling <= 16 ? SHARP_CORNER_OFFSET * EXTENT$1 / (512 * this.overscaling) : 0; 22192 const segment = this.segments.prepareSegment(len * 10, this.layoutVertexArray, this.indexArray); 22193 let currentVertex; 22194 let prevVertex; 22195 let nextVertex; 22196 let prevNormal; 22197 let nextNormal; 22198 this.e1 = this.e2 = -1; 22199 if (isPolygon) { 22200 currentVertex = vertices[len - 2]; 22201 nextNormal = vertices[first].sub(currentVertex)._unit()._perp(); 22202 } 22203 for (let i = first; i < len; i++) { 22204 nextVertex = i === len - 1 ? isPolygon ? vertices[first + 1] : void 0 : vertices[i + 1]; 22205 if (nextVertex && vertices[i].equals(nextVertex)) continue; 22206 if (nextNormal) prevNormal = nextNormal; 22207 if (currentVertex) prevVertex = currentVertex; 22208 currentVertex = vertices[i]; 22209 nextNormal = nextVertex ? nextVertex.sub(currentVertex)._unit()._perp() : prevNormal; 22210 prevNormal ||= nextNormal; 22211 let joinNormal = prevNormal.add(nextNormal); 22212 if (joinNormal.x !== 0 || joinNormal.y !== 0) joinNormal._unit(); 22213 const cosAngle = prevNormal.x * nextNormal.x + prevNormal.y * nextNormal.y; 22214 const cosHalfAngle = joinNormal.x * nextNormal.x + joinNormal.y * nextNormal.y; 22215 const miterLength = cosHalfAngle !== 0 ? 1 / cosHalfAngle : Infinity; 22216 const approxAngle = 2 * Math.sqrt(2 - 2 * cosHalfAngle); 22217 const isSharpCorner = cosHalfAngle < COS_HALF_SHARP_CORNER && prevVertex && nextVertex; 22218 const lineTurnsLeft = prevNormal.x * nextNormal.y - prevNormal.y * nextNormal.x > 0; 22219 if (isSharpCorner && i > first) { 22220 const prevSegmentLength = currentVertex.dist(prevVertex); 22221 if (prevSegmentLength > 2 * sharpCornerOffset) { 22222 const newPrevVertex = currentVertex.sub(currentVertex.sub(prevVertex)._mult(sharpCornerOffset / prevSegmentLength)._round()); 22223 this.updateDistance(prevVertex, newPrevVertex); 22224 this.addCurrentVertex(newPrevVertex, prevNormal, 0, 0, segment); 22225 prevVertex = newPrevVertex; 22226 } 22227 } 22228 const middleVertex = prevVertex && nextVertex; 22229 let currentJoin = middleVertex ? join : isPolygon ? "butt" : cap; 22230 if (middleVertex && currentJoin === "round") { 22231 if (miterLength < roundLimit) currentJoin = "miter"; 22232 else if (miterLength <= 2) currentJoin = "fakeround"; 22233 } 22234 if (currentJoin === "miter" && miterLength > miterLimit) currentJoin = "bevel"; 22235 if (currentJoin === "bevel") { 22236 if (miterLength > 2) currentJoin = "flipbevel"; 22237 if (miterLength < miterLimit) currentJoin = "miter"; 22238 } 22239 if (prevVertex) this.updateDistance(prevVertex, currentVertex); 22240 if (currentJoin === "miter") { 22241 joinNormal._mult(miterLength); 22242 this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment); 22243 } else if (currentJoin === "flipbevel") { 22244 if (miterLength > 100) joinNormal = nextNormal.mult(-1); 22245 else { 22246 const bevelLength = miterLength * prevNormal.add(nextNormal).mag() / prevNormal.sub(nextNormal).mag(); 22247 joinNormal._perp()._mult(bevelLength * (lineTurnsLeft ? -1 : 1)); 22248 } 22249 this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment); 22250 this.addCurrentVertex(currentVertex, joinNormal.mult(-1), 0, 0, segment); 22251 } else if (currentJoin === "bevel" || currentJoin === "fakeround") { 22252 const offset = -Math.sqrt(miterLength * miterLength - 1); 22253 const offsetA = lineTurnsLeft ? offset : 0; 22254 const offsetB = lineTurnsLeft ? 0 : offset; 22255 if (prevVertex) this.addCurrentVertex(currentVertex, prevNormal, offsetA, offsetB, segment); 22256 if (currentJoin === "fakeround") { 22257 const n = Math.round(approxAngle * 180 / Math.PI / DEG_PER_TRIANGLE); 22258 for (let m = 1; m < n; m++) { 22259 let t = m / n; 22260 if (t !== .5) { 22261 const t2 = t - .5; 22262 const A = 1.0904 + cosAngle * (-3.2452 + cosAngle * (3.55645 - cosAngle * 1.43519)); 22263 const B = .848013 + cosAngle * (-1.06021 + cosAngle * .215638); 22264 t = t + t * t2 * (t - 1) * (A * t2 * t2 + B); 22265 } 22266 const extrude = nextNormal.sub(prevNormal)._mult(t)._add(prevNormal)._unit()._mult(lineTurnsLeft ? -1 : 1); 22267 this.addHalfVertex(currentVertex, extrude.x, extrude.y, false, lineTurnsLeft, 0, segment); 22268 } 22269 } 22270 if (nextVertex) this.addCurrentVertex(currentVertex, nextNormal, -offsetA, -offsetB, segment); 22271 } else if (currentJoin === "butt") this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment); 22272 else if (currentJoin === "square") { 22273 const offset = prevVertex ? 1 : -1; 22274 this.addCurrentVertex(currentVertex, joinNormal, offset, offset, segment); 22275 } else if (currentJoin === "round") { 22276 if (prevVertex) { 22277 this.addCurrentVertex(currentVertex, prevNormal, 0, 0, segment); 22278 this.addCurrentVertex(currentVertex, prevNormal, 1, 1, segment, true); 22279 } 22280 if (nextVertex) { 22281 this.addCurrentVertex(currentVertex, nextNormal, -1, -1, segment, true); 22282 this.addCurrentVertex(currentVertex, nextNormal, 0, 0, segment); 22283 } 22284 } 22285 if (isSharpCorner && i < len - 1) { 22286 const nextSegmentLength = currentVertex.dist(nextVertex); 22287 if (nextSegmentLength > 2 * sharpCornerOffset) { 22288 const newCurrentVertex = currentVertex.add(nextVertex.sub(currentVertex)._mult(sharpCornerOffset / nextSegmentLength)._round()); 22289 this.updateDistance(currentVertex, newCurrentVertex); 22290 this.addCurrentVertex(newCurrentVertex, nextNormal, 0, 0, segment); 22291 currentVertex = newCurrentVertex; 22292 } 22293 } 22294 } 22295 } 22296 /** 22297 * Add two vertices to the buffers. 22298 * 22299 * @param p - the line vertex to add buffer vertices for 22300 * @param normal - vertex normal 22301 * @param endLeft - extrude to shift the left vertex along the line 22302 * @param endRight - extrude to shift the left vertex along the line 22303 * @param segment - the segment object to add the vertex to 22304 * @param round - whether this is a round cap 22305 */ 22306 addCurrentVertex(p, normal, endLeft, endRight, segment, round = false) { 22307 const leftX = normal.x + normal.y * endLeft; 22308 const leftY = normal.y - normal.x * endLeft; 22309 const rightX = -normal.x + normal.y * endRight; 22310 const rightY = -normal.y - normal.x * endRight; 22311 this.addHalfVertex(p, leftX, leftY, round, false, endLeft, segment); 22312 this.addHalfVertex(p, rightX, rightY, round, true, -endRight, segment); 22313 if (this.distance > MAX_LINE_DISTANCE / 2 && this.totalDistance === 0) { 22314 this.distance = 0; 22315 this.updateScaledDistance(); 22316 this.addCurrentVertex(p, normal, endLeft, endRight, segment, round); 22317 } 22318 } 22319 addHalfVertex({ x, y }, extrudeX, extrudeY, round, up, dir, segment) { 22320 const linesofarScaled = (this.lineClips ? this.scaledDistance * (MAX_LINE_DISTANCE - 1) : this.scaledDistance) * LINE_DISTANCE_SCALE; 22321 this.layoutVertexArray.emplaceBack((x << 1) + (round ? 1 : 0), (y << 1) + (up ? 1 : 0), Math.round(EXTRUDE_SCALE * extrudeX) + 128, Math.round(EXTRUDE_SCALE * extrudeY) + 128, (dir === 0 ? 0 : dir < 0 ? -1 : 1) + 1 | (linesofarScaled & 63) << 2, linesofarScaled >> 6); 22322 if (this.lineClips) { 22323 const uvX = (this.scaledDistance - this.lineClips.start) / (this.lineClips.end - this.lineClips.start); 22324 this.layoutVertexArray2.emplaceBack(uvX, this.lineClipsArray.length); 22325 } 22326 const e = segment.vertexLength++; 22327 if (this.e1 >= 0 && this.e2 >= 0) { 22328 this.indexArray.emplaceBack(this.e1, e, this.e2); 22329 segment.primitiveLength++; 22330 } 22331 if (up) this.e2 = e; 22332 else this.e1 = e; 22333 } 22334 updateScaledDistance() { 22335 this.scaledDistance = this.lineClips ? this.lineClips.start + (this.lineClips.end - this.lineClips.start) * this.distance / this.totalDistance : this.distance; 22336 } 22337 updateDistance(prev, next) { 22338 this.distance += prev.dist(next); 22339 this.updateScaledDistance(); 22340 } 22341 hasLineDasharray(layers) { 22342 for (const layer of layers) { 22343 const dasharrayProperty = layer.paint.get("line-dasharray"); 22344 if (dasharrayProperty && !dasharrayProperty.isConstant()) return true; 22345 } 22346 return false; 22347 } 22348 addLineDashDependencies(layers, bucketFeature, zoom, options) { 22349 for (const layer of layers) { 22350 const dasharrayProperty = layer.paint.get("line-dasharray"); 22351 if (!dasharrayProperty || dasharrayProperty.value.kind === "constant") continue; 22352 const round = layer.layout.get("line-cap").evaluate(bucketFeature, {}) === "round"; 22353 const min = { 22354 dasharray: dasharrayProperty.value.evaluate({ zoom: zoom - 1 }, bucketFeature, {}), 22355 round 22356 }; 22357 const mid = { 22358 dasharray: dasharrayProperty.value.evaluate({ zoom }, bucketFeature, {}), 22359 round 22360 }; 22361 const max = { 22362 dasharray: dasharrayProperty.value.evaluate({ zoom: zoom + 1 }, bucketFeature, {}), 22363 round 22364 }; 22365 const minKey = `${min.dasharray.join(",")},${min.round}`; 22366 const midKey = `${mid.dasharray.join(",")},${mid.round}`; 22367 const maxKey = `${max.dasharray.join(",")},${max.round}`; 22368 options.dashDependencies[minKey] = min; 22369 options.dashDependencies[midKey] = mid; 22370 options.dashDependencies[maxKey] = max; 22371 bucketFeature.dashes[layer.id] = { 22372 min: minKey, 22373 mid: midKey, 22374 max: maxKey 22375 }; 22376 } 22377 } 22378}; 22379register("LineBucket", LineBucket, { omit: ["layers", "patternFeatures"] }); 22380//#endregion 22381//#region src/style/style_layer/line_style_layer_properties.g.ts 22382let layout$1; 22383const getLayout$1 = () => layout$1 = layout$1 || new Properties({ 22384 "line-cap": new DataDrivenProperty(latest["layout_line"]["line-cap"], "line-cap"), 22385 "line-join": new DataDrivenProperty(latest["layout_line"]["line-join"], "line-join"), 22386 "line-miter-limit": new DataDrivenProperty(latest["layout_line"]["line-miter-limit"], "line-miter-limit"), 22387 "line-round-limit": new DataDrivenProperty(latest["layout_line"]["line-round-limit"], "line-round-limit"), 22388 "line-sort-key": new DataDrivenProperty(latest["layout_line"]["line-sort-key"], "line-sort-key") 22389}); 22390let paint$2; 22391const getPaint$2 = () => paint$2 = paint$2 || new Properties({ 22392 "line-opacity": new DataDrivenProperty(latest["paint_line"]["line-opacity"], "line-opacity"), 22393 "line-layer-opacity": new DataConstantProperty(latest["paint_line"]["line-layer-opacity"], "line-layer-opacity"), 22394 "line-color": new DataDrivenProperty(latest["paint_line"]["line-color"], "line-color"), 22395 "line-translate": new DataConstantProperty(latest["paint_line"]["line-translate"], "line-translate"), 22396 "line-translate-anchor": new DataConstantProperty(latest["paint_line"]["line-translate-anchor"], "line-translate-anchor"), 22397 "line-width": new DataDrivenProperty(latest["paint_line"]["line-width"], "line-width"), 22398 "line-gap-width": new DataDrivenProperty(latest["paint_line"]["line-gap-width"], "line-gap-width"), 22399 "line-offset": new DataDrivenProperty(latest["paint_line"]["line-offset"], "line-offset"), 22400 "line-blur": new DataDrivenProperty(latest["paint_line"]["line-blur"], "line-blur"), 22401 "line-dasharray": new CrossFadedDataDrivenProperty(latest["paint_line"]["line-dasharray"], "line-dasharray"), 22402 "line-pattern": new CrossFadedDataDrivenProperty(latest["paint_line"]["line-pattern"], "line-pattern"), 22403 "line-gradient": new ColorRampProperty(latest["paint_line"]["line-gradient"], "line-gradient") 22404}); 22405var line_style_layer_properties_g_default = { 22406 get paint() { 22407 return getPaint$2(); 22408 }, 22409 get layout() { 22410 return getLayout$1(); 22411 } 22412}; 22413//#endregion 22414//#region src/style/style_layer/line_style_layer.ts 22415var LineFloorwidthProperty = class extends DataDrivenProperty { 22416 possiblyEvaluate(value, parameters) { 22417 parameters = new EvaluationParameters(Math.floor(parameters.zoom), { 22418 now: parameters.now, 22419 fadeDuration: parameters.fadeDuration, 22420 zoomHistory: parameters.zoomHistory, 22421 transition: parameters.transition 22422 }); 22423 return super.possiblyEvaluate(value, parameters); 22424 } 22425 evaluate(value, globals, feature, featureState) { 22426 globals = extend({}, globals, { zoom: Math.floor(globals.zoom) }); 22427 return super.evaluate(value, globals, feature, featureState); 22428 } 22429}; 22430let lineFloorwidthProperty; 22431const isLineStyleLayer = (layer) => layer.type === "line"; 22432var LineStyleLayer = class extends StyleLayer { 22433 constructor(layer, globalState) { 22434 super(layer, line_style_layer_properties_g_default, globalState); 22435 this.gradientVersion = 0; 22436 if (!lineFloorwidthProperty) { 22437 lineFloorwidthProperty = new LineFloorwidthProperty(line_style_layer_properties_g_default.paint.properties["line-width"].specification, "line-floorwidth"); 22438 lineFloorwidthProperty.useIntegerZoom = true; 22439 } 22440 } 22441 _handleSpecialPaintPropertyUpdate(name) { 22442 if (name === "line-gradient") { 22443 const expression = this.gradientExpression(); 22444 if (isZoomExpression(expression)) this.stepInterpolant = expression._styleExpression.expression instanceof Step; 22445 else this.stepInterpolant = false; 22446 this.gradientVersion = (this.gradientVersion + 1) % Number.MAX_SAFE_INTEGER; 22447 } 22448 } 22449 gradientExpression() { 22450 return this._transitionablePaint._values["line-gradient"].value.expression; 22451 } 22452 recalculate(parameters, availableImages) { 22453 super.recalculate(parameters, availableImages); 22454 this.paint._values["line-floorwidth"] = lineFloorwidthProperty.possiblyEvaluate(this._transitioningPaint._values["line-width"].value, parameters); 22455 } 22456 createBucket(parameters) { 22457 return new LineBucket(parameters); 22458 } 22459 queryRadius(bucket) { 22460 const lineBucket = bucket; 22461 const width = getLineWidth(getMaximumPaintValue("line-width", this, lineBucket), getMaximumPaintValue("line-gap-width", this, lineBucket)); 22462 const offset = getMaximumPaintValue("line-offset", this, lineBucket); 22463 return width / 2 + Math.abs(offset) + translateDistance(this.paint.get("line-translate")); 22464 } 22465 queryIntersectsFeature({ queryGeometry, feature, featureState, geometry, transform, pixelsToTileUnits }) { 22466 const translatedPolygon = translate(queryGeometry, this.paint.get("line-translate"), this.paint.get("line-translate-anchor"), -transform.bearingInRadians, pixelsToTileUnits); 22467 const halfWidth = pixelsToTileUnits / 2 * getLineWidth(this.paint.get("line-width").evaluate(feature, featureState), this.paint.get("line-gap-width").evaluate(feature, featureState)); 22468 const lineOffset = this.paint.get("line-offset").evaluate(feature, featureState); 22469 if (lineOffset) geometry = offsetLine(geometry, lineOffset * pixelsToTileUnits); 22470 return polygonIntersectsBufferedMultiLine(translatedPolygon, geometry, halfWidth); 22471 } 22472 isTileClipped() { 22473 return true; 22474 } 22475}; 22476function getLineWidth(lineWidth, lineGapWidth) { 22477 if (lineGapWidth > 0) return lineGapWidth + 2 * lineWidth; 22478 else return lineWidth; 22479} 22480//#endregion 22481//#region src/data/bucket/symbol_attributes.ts 22482const symbolLayoutAttributes = createLayout([ 22483 { 22484 name: "a_pos_offset", 22485 components: 4, 22486 type: "Int16" 22487 }, 22488 { 22489 name: "a_data", 22490 components: 4, 22491 type: "Uint16" 22492 }, 22493 { 22494 name: "a_pixeloffset", 22495 components: 4, 22496 type: "Int16" 22497 }, 22498 { 22499 name: "a_height_offset", 22500 components: 1, 22501 type: "Float32" 22502 } 22503], 4); 22504const dynamicLayoutAttributes = createLayout([{ 22505 name: "a_projected_pos", 22506 components: 3, 22507 type: "Float32" 22508}], 4); 22509createLayout([{ 22510 name: "a_fade_opacity", 22511 components: 1, 22512 type: "Uint32" 22513}], 4); 22514const collisionVertexAttributes = createLayout([ 22515 { 22516 name: "a_placed", 22517 components: 2, 22518 type: "Uint8" 22519 }, 22520 { 22521 name: "a_shift", 22522 components: 2, 22523 type: "Float32" 22524 }, 22525 { 22526 name: "a_box_real", 22527 components: 2, 22528 type: "Int16" 22529 } 22530]); 22531createLayout([ 22532 { 22533 type: "Int16", 22534 name: "anchorPointX" 22535 }, 22536 { 22537 type: "Int16", 22538 name: "anchorPointY" 22539 }, 22540 { 22541 type: "Int16", 22542 name: "x1" 22543 }, 22544 { 22545 type: "Int16", 22546 name: "y1" 22547 }, 22548 { 22549 type: "Int16", 22550 name: "x2" 22551 }, 22552 { 22553 type: "Int16", 22554 name: "y2" 22555 }, 22556 { 22557 type: "Uint32", 22558 name: "featureIndex" 22559 }, 22560 { 22561 type: "Uint16", 22562 name: "sourceLayerIndex" 22563 }, 22564 { 22565 type: "Uint16", 22566 name: "bucketIndex" 22567 } 22568]); 22569const collisionBoxLayout = createLayout([ 22570 { 22571 name: "a_pos", 22572 components: 2, 22573 type: "Int16" 22574 }, 22575 { 22576 name: "a_anchor_pos", 22577 components: 2, 22578 type: "Int16" 22579 }, 22580 { 22581 name: "a_extrude", 22582 components: 2, 22583 type: "Int16" 22584 } 22585], 4); 22586const collisionCircleLayout = createLayout([ 22587 { 22588 name: "a_pos", 22589 components: 2, 22590 type: "Float32" 22591 }, 22592 { 22593 name: "a_radius", 22594 components: 1, 22595 type: "Float32" 22596 }, 22597 { 22598 name: "a_flags", 22599 components: 2, 22600 type: "Int16" 22601 } 22602], 4); 22603createLayout([{ 22604 name: "triangle", 22605 components: 3, 22606 type: "Uint16" 22607}]); 22608createLayout([ 22609 { 22610 type: "Int16", 22611 name: "anchorX" 22612 }, 22613 { 22614 type: "Int16", 22615 name: "anchorY" 22616 }, 22617 { 22618 type: "Uint16", 22619 name: "glyphStartIndex" 22620 }, 22621 { 22622 type: "Uint16", 22623 name: "numGlyphs" 22624 }, 22625 { 22626 type: "Uint32", 22627 name: "vertexStartIndex" 22628 }, 22629 { 22630 type: "Uint32", 22631 name: "lineStartIndex" 22632 }, 22633 { 22634 type: "Uint32", 22635 name: "lineLength" 22636 }, 22637 { 22638 type: "Uint16", 22639 name: "segment" 22640 }, 22641 { 22642 type: "Uint16", 22643 name: "lowerSize" 22644 }, 22645 { 22646 type: "Uint16", 22647 name: "upperSize" 22648 }, 22649 { 22650 type: "Float32", 22651 name: "lineOffsetX" 22652 }, 22653 { 22654 type: "Float32", 22655 name: "lineOffsetY" 22656 }, 22657 { 22658 type: "Uint8", 22659 name: "writingMode" 22660 }, 22661 { 22662 type: "Uint8", 22663 name: "placedOrientation" 22664 }, 22665 { 22666 type: "Uint8", 22667 name: "hidden" 22668 }, 22669 { 22670 type: "Uint32", 22671 name: "crossTileID" 22672 }, 22673 { 22674 type: "Int16", 22675 name: "associatedIconIndex" 22676 }, 22677 { 22678 type: "Float32", 22679 name: "heightOffset" 22680 } 22681]); 22682createLayout([ 22683 { 22684 type: "Int16", 22685 name: "anchorX" 22686 }, 22687 { 22688 type: "Int16", 22689 name: "anchorY" 22690 }, 22691 { 22692 type: "Int16", 22693 name: "rightJustifiedTextSymbolIndex" 22694 }, 22695 { 22696 type: "Int16", 22697 name: "centerJustifiedTextSymbolIndex" 22698 }, 22699 { 22700 type: "Int16", 22701 name: "leftJustifiedTextSymbolIndex" 22702 }, 22703 { 22704 type: "Int16", 22705 name: "verticalPlacedTextSymbolIndex" 22706 }, 22707 { 22708 type: "Int16", 22709 name: "placedIconSymbolIndex" 22710 }, 22711 { 22712 type: "Int16", 22713 name: "verticalPlacedIconSymbolIndex" 22714 }, 22715 { 22716 type: "Uint16", 22717 name: "key" 22718 }, 22719 { 22720 type: "Uint16", 22721 name: "textBoxStartIndex" 22722 }, 22723 { 22724 type: "Uint16", 22725 name: "textBoxEndIndex" 22726 }, 22727 { 22728 type: "Uint16", 22729 name: "verticalTextBoxStartIndex" 22730 }, 22731 { 22732 type: "Uint16", 22733 name: "verticalTextBoxEndIndex" 22734 }, 22735 { 22736 type: "Uint16", 22737 name: "iconBoxStartIndex" 22738 }, 22739 { 22740 type: "Uint16", 22741 name: "iconBoxEndIndex" 22742 }, 22743 { 22744 type: "Uint16", 22745 name: "verticalIconBoxStartIndex" 22746 }, 22747 { 22748 type: "Uint16", 22749 name: "verticalIconBoxEndIndex" 22750 }, 22751 { 22752 type: "Uint16", 22753 name: "featureIndex" 22754 }, 22755 { 22756 type: "Uint16", 22757 name: "numHorizontalGlyphVertices" 22758 }, 22759 { 22760 type: "Uint16", 22761 name: "numVerticalGlyphVertices" 22762 }, 22763 { 22764 type: "Uint16", 22765 name: "numIconVertices" 22766 }, 22767 { 22768 type: "Uint16", 22769 name: "numVerticalIconVertices" 22770 }, 22771 { 22772 type: "Uint16", 22773 name: "useRuntimeCollisionCircles" 22774 }, 22775 { 22776 type: "Uint32", 22777 name: "crossTileID" 22778 }, 22779 { 22780 type: "Float32", 22781 name: "textBoxScale" 22782 }, 22783 { 22784 type: "Float32", 22785 name: "collisionCircleDiameter" 22786 }, 22787 { 22788 type: "Uint16", 22789 name: "textAnchorOffsetStartIndex" 22790 }, 22791 { 22792 type: "Uint16", 22793 name: "textAnchorOffsetEndIndex" 22794 }, 22795 { 22796 type: "Float32", 22797 name: "heightOffset" 22798 } 22799]); 22800createLayout([{ 22801 type: "Float32", 22802 name: "offsetX" 22803}]); 22804createLayout([ 22805 { 22806 type: "Int16", 22807 name: "x" 22808 }, 22809 { 22810 type: "Int16", 22811 name: "y" 22812 }, 22813 { 22814 type: "Int16", 22815 name: "tileUnitDistanceFromAnchor" 22816 } 22817]); 22818createLayout([{ 22819 type: "Uint16", 22820 name: "textAnchor" 22821}, { 22822 type: "Float32", 22823 components: 2, 22824 name: "textOffset" 22825}]); 22826//#endregion 22827//#region src/source/rtl_text_plugin_worker.ts 22828var RTLWorkerPlugin = class { 22829 constructor() { 22830 this.TIMEOUT = 5e3; 22831 this.applyArabicShaping = null; 22832 this.processBidirectionalText = null; 22833 this.processStyledBidirectionalText = null; 22834 this.pluginStatus = "unavailable"; 22835 this.pluginURL = null; 22836 this.loadScriptResolve = () => {}; 22837 } 22838 setState(state) { 22839 this.pluginStatus = state.pluginStatus; 22840 this.pluginURL = state.pluginURL; 22841 } 22842 getState() { 22843 return { 22844 pluginStatus: this.pluginStatus, 22845 pluginURL: this.pluginURL 22846 }; 22847 } 22848 setMethods(rtlTextPlugin) { 22849 if (rtlWorkerPlugin.isParsed()) throw new Error("RTL text plugin already registered."); 22850 this.applyArabicShaping = rtlTextPlugin.applyArabicShaping; 22851 this.processBidirectionalText = rtlTextPlugin.processBidirectionalText; 22852 this.processStyledBidirectionalText = rtlTextPlugin.processStyledBidirectionalText; 22853 this.loadScriptResolve(); 22854 } 22855 isParsed() { 22856 return this.applyArabicShaping != null && this.processBidirectionalText != null && this.processStyledBidirectionalText != null; 22857 } 22858 getRTLTextPluginStatus() { 22859 return this.pluginStatus; 22860 } 22861 async syncState(incomingState, loadScript) { 22862 if (this.isParsed()) return this.getState(); 22863 if (incomingState.pluginStatus !== "loading") { 22864 this.setState(incomingState); 22865 return incomingState; 22866 } 22867 const urlToLoad = incomingState.pluginURL; 22868 const loadScriptPromise = new Promise((resolve) => { 22869 this.loadScriptResolve = resolve; 22870 }); 22871 const dontWaitForeverTimeoutPromise = new Promise((resolve) => setTimeout(() => resolve(), this.TIMEOUT)); 22872 await loadScript(urlToLoad); 22873 await Promise.race([loadScriptPromise, dontWaitForeverTimeoutPromise]); 22874 if (this.isParsed()) { 22875 const loadedState = { 22876 pluginStatus: "loaded", 22877 pluginURL: urlToLoad 22878 }; 22879 this.setState(loadedState); 22880 return loadedState; 22881 } 22882 this.setState({ 22883 pluginStatus: "error", 22884 pluginURL: "" 22885 }); 22886 throw new Error(`RTL Text Plugin failed to import scripts from ${urlToLoad}`); 22887 } 22888}; 22889const rtlWorkerPlugin = new RTLWorkerPlugin(); 22890//#endregion 22891//#region src/util/unicode_properties.g.ts 22892/** 22893* Returns whether the given codepoint belongs to a script that is written cursively, whose letters 22894* therefore cannot be spaced apart. 22895*/ 22896function codePointIsInCursiveScript(codePoint) { 22897 return /[\u0600-\u0604\u0606-\u060B\u060D-\u061A\u061C-\u061E\u0620-\u063F\u0641-\u064A\u0656-\u066F\u0671-\u06DC\u06DE-\u070D\u070F-\u074A\u074D-\u077F\u07C0-\u07FA\u07FD-\u07FF\u0840-\u085B\u085E\u0860-\u086A\u0870-\u0891\u0897-\u08E1\u08E3-\u08FF\u1800\u1801\u1804\u1806-\u1819\u1820-\u1878\u1880-\u18AA\uA840-\uA877\uFB50-\uFD3D\uFD40-\uFDCF\uFDF0-\uFDFF\uFE70-\uFE74\uFE76-\uFEFC]|\uD802[\uDEC0-\uDEE6\uDEEB-\uDEF6\uDF80-\uDF91\uDF99-\uDF9C\uDFA9-\uDFAF]|\uD803[\uDD00-\uDD27\uDD30-\uDD39\uDE60-\uDE7E\uDEC2-\uDEC7\uDED0-\uDED8\uDEFA-\uDEFF\uDF30-\uDF59\uDF70-\uDF89\uDFB0-\uDFCB]|\uD805[\uDE60-\uDE6C]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9C-\uDC9F]|\uD83A[\uDD00-\uDD4B\uDD50-\uDD59\uDD5E\uDD5F]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB\uDEF0\uDEF1]/gim.test(String.fromCodePoint(codePoint)); 22898} 22899/** 22900* Returns whether the given codepoint belongs to a script that is written horizontally from right 22901* to left. 22902*/ 22903function codePointIsInRTLScript(codePoint) { 22904 return /[\u0591-\u05C7\u05D0-\u05EA\u05EF-\u05F4\u0600-\u0604\u0606-\u060B\u060D-\u061A\u061C-\u061E\u0620-\u063F\u0641-\u064A\u0656-\u066F\u0671-\u06DC\u06DE-\u070D\u070F-\u074A\u074D-\u07B1\u07C0-\u07FA\u07FD-\u082D\u0830-\u083E\u0840-\u085B\u085E\u0860-\u086A\u0870-\u0891\u0897-\u08E1\u08E3-\u08FF\uFB1D-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFD3D\uFD40-\uFDCF\uFDF0-\uFDFF\uFE70-\uFE74\uFE76-\uFEFC]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC57-\uDC9E\uDCA7-\uDCAF\uDCE0-\uDCF2\uDCF4\uDCF5\uDCFB-\uDD1B\uDD1F-\uDD39\uDD3F-\uDD59\uDD80-\uDDB7\uDDBC-\uDDCF\uDDD2-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE38-\uDE3A\uDE3F-\uDE48\uDE50-\uDE58\uDE60-\uDE9F\uDEC0-\uDEE6\uDEEB-\uDEF6\uDF00-\uDF35\uDF39-\uDF55\uDF58-\uDF72\uDF78-\uDF91\uDF99-\uDF9C\uDFA9-\uDFAF]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDCFA-\uDD27\uDD30-\uDD39\uDD40-\uDD65\uDD69-\uDD85\uDD8E\uDD8F\uDE60-\uDE7E\uDE80-\uDEA9\uDEAB-\uDEAD\uDEB0\uDEB1\uDEC2-\uDEC7\uDED0-\uDED8\uDEFA-\uDF27\uDF30-\uDF59\uDF70-\uDF89\uDFB0-\uDFCB\uDFE0-\uDFF6]|\uD83A[\uDC00-\uDCC4\uDCC7-\uDCD6\uDD00-\uDD4B\uDD50-\uDD59\uDD5E\uDD5F]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB\uDEF0\uDEF1]/gim.test(String.fromCodePoint(codePoint)); 22905} 22906/** 22907* Returns whether the fallback fonts specified by the 22908* `localIdeographFontFamily` map option apply to the given codepoint. 22909*/ 22910function codePointUsesLocalIdeographFontFamily(codePoint) { 22911 return /[\u02EA\u02EB\u1100-\u11FF\u2E80-\u2FDF\u3000-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u4DBF\u4E00-\uA48C\uA490-\uA4C6\uA960-\uA97C\uAC00-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFE10-\uFE1F\uFE30-\uFE4F\uFF00-\uFFEF]|\uD81B[\uDFE0-\uDFFF]|[\uD81C-\uD822\uD840-\uD868\uD86A-\uD86D\uD86F-\uD872\uD874-\uD879\uD880-\uD883\uD885-\uD88C][\uDC00-\uDFFF]|\uD823[\uDC00-\uDCD5\uDCFF-\uDD1E\uDD80-\uDDF2]|\uD82B[\uDFF0-\uDFFF]|\uD82C[\uDC00-\uDEFB]|\uD83C[\uDE00-\uDEFF]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEAD\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0\uDFF0-\uDFFF]|\uD87B[\uDC00-\uDE5D]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A\uDF50-\uDFFF]|\uD88D[\uDC00-\uDC79]/gim.test(String.fromCodePoint(codePoint)); 22912} 22913/** 22914* Returns whether the given codepoint participates in ideographic line 22915* breaking. 22916*/ 22917function codePointAllowsIdeographicBreaking(codePoint) { 22918 return /[\u02EA\u02EB\u2E80-\u2FDF\u2FF0-\u303F\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FD-\u30FF\u3105-\u312F\u31A0-\u4DBF\u4E00-\uA48C\uA490-\uA4C6\uF900-\uFA6D\uFA70-\uFAD9\uFE10-\uFE1F\uFE30-\uFE4F\uFF00-\uFFEF]|\uD81B[\uDFE0-\uDFFF]|[\uD81C-\uD822\uD840-\uD868\uD86A-\uD86D\uD86F-\uD872\uD874-\uD879\uD880-\uD883\uD885-\uD88C][\uDC00-\uDFFF]|\uD823[\uDC00-\uDCD5\uDCFF-\uDD1E\uDD80-\uDDF2]|\uD82B[\uDFF0-\uDFFF]|\uD82C[\uDC00-\uDEFB]|\uD83C[\uDE00-\uDEFF]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEAD\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0\uDFF0-\uDFFF]|\uD87B[\uDC00-\uDE5D]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A\uDF50-\uDFFF]|\uD88D[\uDC00-\uDC79]/gim.test(String.fromCodePoint(codePoint)); 22919} 22920/** 22921* Returns true if the given Unicode codepoint identifies a character with 22922* upright orientation. 22923* 22924* A character has upright orientation if it is drawn upright (unrotated) 22925* whether the line is oriented horizontally or vertically, even if both 22926* adjacent characters can be rotated. For example, a Chinese character is 22927* always drawn upright. An uprightly oriented character causes an adjacent 22928* âneutralâ character to be drawn upright as well. 22929*/ 22930function codePointHasUprightVerticalOrientation(codePoint) { 22931 return /[\u02EA\u02EB\u1100-\u11FF\u1401-\u167F\u18B0-\u18FF\u2065\u20DD-\u20E0\u20E2-\u20E4\u2B97\u2BF0-\u2BFF\u2E50\u2E51\u2E80-\u3007\u3012\u3013\u3020-\u302F\u3031-\u30FB\u30FD-\uA4CF\uA960-\uA97F\uAC00-\uD7FF\uF900-\uFAFF\uFE10-\uFE1F\uFE30-\uFE48\uFE50-\uFE57\uFE5F-\uFE62\uFE67-\uFE6F\uFF00-\uFF07\uFF0A-\uFF0C\uFF0E-\uFF19\uFF1F-\uFF3A\uFF3C\uFF3E\uFF40-\uFF5A\uFFE0-\uFFE2\uFFE4-\uFFE7\uFFF0-\uFFF8]|\uD802[\uDD80-\uDD9F]|\uD805[\uDD80-\uDDFF]|\uD806[\uDE00-\uDEBF]|[\uD80C-\uD810\uD81C-\uD822\uD83C\uD83D\uD840-\uD87E\uD880-\uD8BE][\uDC00-\uDFFF]|\uD811[\uDC00-\uDE7F]|\uD81B[\uDFE0-\uDFFF]|\uD823[\uDC00-\uDDFF]|\uD82B[\uDFF0-\uDFFF]|\uD82C[\uDC00-\uDEFF]|\uD833[\uDEC0-\uDFCF]|\uD834[\uDC00-\uDDFF\uDEE0-\uDF7F]|\uD836[\uDC00-\uDEAF]|\uD83E[\uDD00-\uDEFF]|[\uD87F\uD8BF][\uDC00-\uDFFD]/gim.test(String.fromCodePoint(codePoint)); 22932} 22933/** 22934* Returns true if the given Unicode codepoint identifies a character with 22935* neutral orientation. 22936* 22937* A character has neutral orientation if it may be drawn rotated or unrotated 22938* when the line is oriented vertically, depending on the orientation of the 22939* adjacent characters. For example, along a vertically oriented line, the 22940* vulgar fraction ½ is drawn upright among Chinese characters but rotated among 22941* Latin letters. A neutrally oriented character does not influence whether an 22942* adjacent character is drawn upright or rotated. 22943*/ 22944function codePointHasNeutralVerticalOrientation(codePoint) { 22945 return /[\xA7\xA9\xAE\xB1\xBC-\xBE\xD7\xF7\u2016\u2020\u2021\u2030\u2031\u203B\u203C\u2042\u2047-\u2049\u2051\u2100-\u218F\u221E\u2234\u2235\u2300-\u2307\u230C-\u231F\u2324-\u2328\u232B\u237D-\u239A\u23BE-\u23CD\u23CF\u23D1-\u23DB\u23E2-\u2422\u2424-\u24FF\u25A0-\u2619\u2620-\u2767\u2776-\u2793\u2B12-\u2B2F\u2B50-\u2B59\u2BB8-\u2BEB\u3000-\u303F\u30A0-\u30FF\uE000-\uF8FF\uFE30-\uFE6F\uFF00-\uFFEF\uFFFC\uFFFD]|[\uDB80-\uDBFF][\uDC00-\uDFFF]/gim.test(String.fromCodePoint(codePoint)); 22946} 22947/** 22948* Returns whether the text could hold a grapheme cluster of more than one codepoint, and so is worth 22949* segmenting. A negative answer means every codepoint of it stands alone. 22950*/ 22951function textCanContainGraphemeClusters(text) { 22952 return /[\r\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0600-\u0605\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DD\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u070F\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0890\u0891\u0897-\u089F\u08CA-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D62\u0D63\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E33-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB3-\u0EBC\u0EC8-\u0ECE\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1037\u1039-\u103E\u1056-\u1059\u105E-\u1060\u1071-\u1074\u1082\u1084-\u1086\u108D\u109D\u1100-\u11FF\u135D-\u135F\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60\u1A62\u1A65-\u1A7C\u1A7F\u1AB0-\u1ADD\u1AE0-\u1AEB\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA960-\uA97C\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFF9E\uFF9F]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD803[\uDD24-\uDD27\uDD69-\uDD6D\uDEAB\uDEAC\uDEFA-\uDEFF\uDF46-\uDF50\uDF82-\uDF85]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC70\uDC73\uDC74\uDC7F-\uDC82\uDCB0-\uDCBA\uDCBD\uDCC2\uDCCD\uDD00-\uDD02\uDD27-\uDD34\uDD45\uDD46\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDDC2\uDDC3\uDDC9-\uDDCC\uDDCE\uDDCF\uDE2C-\uDE37\uDE3E\uDE41\uDEDF-\uDEEA\uDF00-\uDF03\uDF3B\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74\uDFB8-\uDFC0\uDFC2\uDFC5\uDFC7-\uDFCA\uDFCC-\uDFD2\uDFE1\uDFE2]|\uD805[\uDC35-\uDC46\uDC5E\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDDDC\uDDDD\uDE30-\uDE40\uDEAB-\uDEB7\uDF1D-\uDF1F\uDF22-\uDF2B]|\uD806[\uDC2C-\uDC3A\uDD30-\uDD35\uDD37\uDD38\uDD3B-\uDD43\uDDD1-\uDDD7\uDDDA-\uDDE0\uDDE4\uDE01-\uDE0A\uDE33-\uDE39\uDE3B-\uDE3E\uDE47\uDE51-\uDE5B\uDE84-\uDE99\uDF60-\uDF67]|\uD807[\uDC2F-\uDC36\uDC38-\uDC3F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD31-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD8A-\uDD8E\uDD90\uDD91\uDD93-\uDD97\uDEF3-\uDEF6\uDF00-\uDF03\uDF34-\uDF3A\uDF3E-\uDF42\uDF5A]|\uD80D[\uDC40\uDC47-\uDC55]|\uD818[\uDD1E-\uDD2F]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDD63\uDD67-\uDD6A\uDF4F\uDF51-\uDF87\uDF8F-\uDF92\uDFE4\uDFF0\uDFF1]|\uD82F[\uDC9D\uDC9E]|\uD833[\uDF00-\uDF2D\uDF30-\uDF46]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A\uDC8F\uDD30-\uDD36\uDEAE\uDEEC-\uDEEF]|\uD839[\uDCEC-\uDCEF\uDDEE\uDDEF\uDEE3\uDEE6\uDEEE\uDEEF\uDEF5]|\uD83A[\uDCD0-\uDCD6\uDD44-\uDD4A]|\uD83C[\uDDE6-\uDDFF\uDFFB-\uDFFF]|\uDB40[\uDC20-\uDC7F\uDD00-\uDDEF]/.test(text); 22953} 22954/** 22955* Returns whether the given codepoint belongs to a script that does not put spaces between words, 22956* and so can only be wrapped by asking the word segmenter where its words are. 22957*/ 22958function codePointIsWrittenWithoutSpaces(codePoint) { 22959 return /[\u0E01-\u0E3A\u0E40-\u0E4E\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECE\u0EDC-\u0EDF\u0F00-\u0F47\u0F49-\u0F6C\u0F71-\u0F97\u0F99-\u0FBC\u0FBE-\u0FCC\u0FCE-\u0FD4\u0FD9\u0FDA\u1000-\u103F\u1050-\u108F\u109A-\u109F\u1780-\u17D3\u17D7\u17DC\u17DD\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19DE\u19DF\u1A20-\u1A5E\u1A60-\u1A7C\u1AA0-\u1AAD\u1B00-\u1B4C\u1B4E-\u1B7F\uA980-\uA9CD\uA9D0-\uA9D9\uA9DE-\uA9EF\uA9FA-\uA9FE\uAA60-\uAAC2\uAADB-\uAADF]|\uD805[\uDF00-\uDF1A\uDF1D-\uDF2B\uDF3A\uDF3B\uDF3F-\uDF46]/gim.test(String.fromCodePoint(codePoint)); 22960} 22961/** 22962* Returns whether two grapheme clusters found by `Intl.Segmenter` are really one unit of writing, 22963* and so have to be measured and drawn as a whole. 22964* 22965* The segmenter follows the tailored rules CLDR uses for stepping a cursor through text, which put a 22966* boundary after an invisible stacker and before a spacing mark. Laying text out wants the untailored 22967* rules of UAX #29 instead: `á`, `á¬` and `á¸` are one Burmese syllable, not three. 22968*/ 22969function canCombineGraphemes(former, latter) { 22970 return /(?:[\u1039\u17D2\u1A60\u1BAB\u200D\uAAF6]|\uD802\uDE3F|\uD804[\uDD33\uDFD0]|\uD806[\uDD3E\uDE47\uDE99]|\uD807[\uDD45\uDD97\uDF42])$/.test(former) || /^\p{gc=Mc}/u.test(latter); 22971} 22972/** 22973* The joining type of each Arabic character, as `start,length` code point ranges delta-encoded in 22974* base 36, one entry per type. Anything absent from all of them is non-joining. 22975*/ 22976const ENCODED_JOINING_TYPES = { 22977 C: "18g,1;g2,3;4nb,1", 22978 D: "17k,1;5,1;1,1;1,5;4,d;1,7;1,2;z,2;8,g;i,12;1,2;9,1;1,1;1,2;14,3;2,1;28,9;3,f;2,4;1,1;2,3;2,6;7a,1;2,5;1,1;g,a;5,2;2,6;1,f", 22979 R: "17m,4;1,1;1,1;5,4;l,1;14,3;1,3;g,i;12,1;2,9;1,1;1,1;2,2;1,1;o,2;2x,3;f,2;4,1;1,2;3,2;6u,j;b,1;r,3;1,1;2,2;6,1", 22980 T: "174,b;1,1;1a,l;g,1;2t,7;2,6;2,2;1,4;bt,9;16,o;1,t;1clb,1" 22981}; 22982/** 22983* Each Arabic letter's Presentation Forms code points, as `[isolated, final, initial, medial]`. 22984* A shape the letter is not written in is 0. 22985*/ 22986const PRESENTATION_FORMS = { 22987 1569: [ 22988 65152, 22989 0, 22990 0, 22991 0 22992 ], 22993 1570: [ 22994 65153, 22995 65154, 22996 0, 22997 0 22998 ], 22999 1571: [ 23000 65155, 23001 65156, 23002 0, 23003 0 23004 ], 23005 1572: [ 23006 65157, 23007 65158, 23008 0, 23009 0 23010 ], 23011 1573: [ 23012 65159, 23013 65160, 23014 0, 23015 0 23016 ], 23017 1574: [ 23018 65161, 23019 65162, 23020 65163, 23021 65164 23022 ], 23023 1575: [ 23024 65165, 23025 65166, 23026 0, 23027 0 23028 ], 23029 1576: [ 23030 65167, 23031 65168, 23032 65169, 23033 65170 23034 ], 23035 1577: [ 23036 65171, 23037 65172, 23038 0, 23039 0 23040 ], 23041 1578: [ 23042 65173, 23043 65174, 23044 65175, 23045 65176 23046 ], 23047 1579: [ 23048 65177, 23049 65178, 23050 65179, 23051 65180 23052 ], 23053 1580: [ 23054 65181, 23055 65182, 23056 65183, 23057 65184 23058 ], 23059 1581: [ 23060 65185, 23061 65186, 23062 65187, 23063 65188 23064 ], 23065 1582: [ 23066 65189, 23067 65190, 23068 65191, 23069 65192 23070 ], 23071 1583: [ 23072 65193, 23073 65194, 23074 0, 23075 0 23076 ], 23077 1584: [ 23078 65195, 23079 65196, 23080 0, 23081 0 23082 ], 23083 1585: [ 23084 65197, 23085 65198, 23086 0, 23087 0 23088 ], 23089 1586: [ 23090 65199, 23091 65200, 23092 0, 23093 0 23094 ], 23095 1587: [ 23096 65201, 23097 65202, 23098 65203, 23099 65204 23100 ], 23101 1588: [ 23102 65205, 23103 65206, 23104 65207, 23105 65208 23106 ], 23107 1589: [ 23108 65209, 23109 65210, 23110 65211, 23111 65212 23112 ], 23113 1590: [ 23114 65213, 23115 65214, 23116 65215, 23117 65216 23118 ], 23119 1591: [ 23120 65217, 23121 65218, 23122 65219, 23123 65220 23124 ], 23125 1592: [ 23126 65221, 23127 65222, 23128 65223, 23129 65224 23130 ], 23131 1593: [ 23132 65225, 23133 65226, 23134 65227, 23135 65228 23136 ], 23137 1594: [ 23138 65229, 23139 65230, 23140 65231, 23141 65232 23142 ], 23143 1601: [ 23144 65233, 23145 65234, 23146 65235, 23147 65236 23148 ], 23149 1602: [ 23150 65237, 23151 65238, 23152 65239, 23153 65240 23154 ], 23155 1603: [ 23156 65241, 23157 65242, 23158 65243, 23159 65244 23160 ], 23161 1604: [ 23162 65245, 23163 65246, 23164 65247, 23165 65248 23166 ], 23167 1605: [ 23168 65249, 23169 65250, 23170 65251, 23171 65252 23172 ], 23173 1606: [ 23174 65253, 23175 65254, 23176 65255, 23177 65256 23178 ], 23179 1607: [ 23180 65257, 23181 65258, 23182 65259, 23183 65260 23184 ], 23185 1608: [ 23186 65261, 23187 65262, 23188 0, 23189 0 23190 ], 23191 1609: [ 23192 65263, 23193 65264, 23194 64488, 23195 64489 23196 ], 23197 1610: [ 23198 65265, 23199 65266, 23200 65267, 23201 65268 23202 ], 23203 1611: [ 23204 65136, 23205 0, 23206 0, 23207 65137 23208 ], 23209 1612: [ 23210 65138, 23211 0, 23212 0, 23213 0 23214 ], 23215 1613: [ 23216 65140, 23217 0, 23218 0, 23219 0 23220 ], 23221 1614: [ 23222 65142, 23223 0, 23224 0, 23225 65143 23226 ], 23227 1615: [ 23228 65144, 23229 0, 23230 0, 23231 65145 23232 ], 23233 1616: [ 23234 65146, 23235 0, 23236 0, 23237 65147 23238 ], 23239 1617: [ 23240 65148, 23241 0, 23242 0, 23243 65149 23244 ], 23245 1618: [ 23246 65150, 23247 0, 23248 0, 23249 65151 23250 ], 23251 1649: [ 23252 64336, 23253 64337, 23254 0, 23255 0 23256 ], 23257 1655: [ 23258 64477, 23259 0, 23260 0, 23261 0 23262 ], 23263 1657: [ 23264 64358, 23265 64359, 23266 64360, 23267 64361 23268 ], 23269 1658: [ 23270 64350, 23271 64351, 23272 64352, 23273 64353 23274 ], 23275 1659: [ 23276 64338, 23277 64339, 23278 64340, 23279 64341 23280 ], 23281 1662: [ 23282 64342, 23283 64343, 23284 64344, 23285 64345 23286 ], 23287 1663: [ 23288 64354, 23289 64355, 23290 64356, 23291 64357 23292 ], 23293 1664: [ 23294 64346, 23295 64347, 23296 64348, 23297 64349 23298 ], 23299 1667: [ 23300 64374, 23301 64375, 23302 64376, 23303 64377 23304 ], 23305 1668: [ 23306 64370, 23307 64371, 23308 64372, 23309 64373 23310 ], 23311 1670: [ 23312 64378, 23313 64379, 23314 64380, 23315 64381 23316 ], 23317 1671: [ 23318 64382, 23319 64383, 23320 64384, 23321 64385 23322 ], 23323 1672: [ 23324 64392, 23325 64393, 23326 0, 23327 0 23328 ], 23329 1676: [ 23330 64388, 23331 64389, 23332 0, 23333 0 23334 ], 23335 1677: [ 23336 64386, 23337 64387, 23338 0, 23339 0 23340 ], 23341 1678: [ 23342 64390, 23343 64391, 23344 0, 23345 0 23346 ], 23347 1681: [ 23348 64396, 23349 64397, 23350 0, 23351 0 23352 ], 23353 1688: [ 23354 64394, 23355 64395, 23356 0, 23357 0 23358 ], 23359 1700: [ 23360 64362, 23361 64363, 23362 64364, 23363 64365 23364 ], 23365 1702: [ 23366 64366, 23367 64367, 23368 64368, 23369 64369 23370 ], 23371 1705: [ 23372 64398, 23373 64399, 23374 64400, 23375 64401 23376 ], 23377 1709: [ 23378 64467, 23379 64468, 23380 64469, 23381 64470 23382 ], 23383 1711: [ 23384 64402, 23385 64403, 23386 64404, 23387 64405 23388 ], 23389 1713: [ 23390 64410, 23391 64411, 23392 64412, 23393 64413 23394 ], 23395 1715: [ 23396 64406, 23397 64407, 23398 64408, 23399 64409 23400 ], 23401 1722: [ 23402 64414, 23403 64415, 23404 0, 23405 0 23406 ], 23407 1723: [ 23408 64416, 23409 64417, 23410 64418, 23411 64419 23412 ], 23413 1726: [ 23414 64426, 23415 64427, 23416 64428, 23417 64429 23418 ], 23419 1728: [ 23420 64420, 23421 64421, 23422 0, 23423 0 23424 ], 23425 1729: [ 23426 64422, 23427 64423, 23428 64424, 23429 64425 23430 ], 23431 1733: [ 23432 64480, 23433 64481, 23434 0, 23435 0 23436 ], 23437 1734: [ 23438 64473, 23439 64474, 23440 0, 23441 0 23442 ], 23443 1735: [ 23444 64471, 23445 64472, 23446 0, 23447 0 23448 ], 23449 1736: [ 23450 64475, 23451 64476, 23452 0, 23453 0 23454 ], 23455 1737: [ 23456 64482, 23457 64483, 23458 0, 23459 0 23460 ], 23461 1739: [ 23462 64478, 23463 64479, 23464 0, 23465 0 23466 ], 23467 1740: [ 23468 64508, 23469 64509, 23470 64510, 23471 64511 23472 ], 23473 1744: [ 23474 64484, 23475 64485, 23476 64486, 23477 64487 23478 ], 23479 1746: [ 23480 64430, 23481 64431, 23482 0, 23483 0 23484 ], 23485 1747: [ 23486 64432, 23487 64433, 23488 0, 23489 0 23490 ] 23491}; 23492/** The lam-alef ligatures, keyed by the pair of letters they replace, as `[isolated, final]`. */ 23493const LIGATURES = { 23494 "ÙØ¢": [65269, 65270], 23495 "ÙØ£": [65271, 65272], 23496 "ÙØ¥": [65273, 65274], 23497 "ÙØ§": [65275, 65276] 23498}; 23499//#endregion 23500//#region src/symbol/arabic_shaping.ts 23501/** Lam, which is the only letter that has to be written as a ligature with the letter after it. */ 23502const LAM = 1604; 23503/** 23504* The blocks the Arabic script is written from, which is what makes shaping worth doing at all. 23505* 23506* Arabic proper, then its supplement and two extensions, then the two blocks of shapes this file 23507* rewrites letters into, so that text already shaped is recognised as needing to be looked at again. 23508*/ 23509const ARABIC = /[\u0600-\u06ff\u0750-\u077f\u0870-\u089f\u08a0-\u08ff\ufb50-\ufdff\ufe70-\ufeff]/; 23510/** 23511* Unpacks the `start,length` ranges of one joining type into the code points they stand for. 23512* 23513* The ranges are delta-encoded against the end of the range before them, so each is read relative to 23514* where the last one stopped. 23515*/ 23516function decodeRanges(encoded, type, into) { 23517 let previousEnd = 0; 23518 for (const range of encoded.split(";")) { 23519 const [delta, length] = range.split(",").map((value) => parseInt(value, 36)); 23520 const start = previousEnd + delta; 23521 for (let codePoint = start; codePoint < start + length; codePoint++) into.set(codePoint, type); 23522 previousEnd = start + length; 23523 } 23524} 23525const joiningTypes = /* @__PURE__ */ new Map(); 23526for (const [type, encoded] of Object.entries(ENCODED_JOINING_TYPES)) decodeRanges(encoded, type, joiningTypes); 23527/** Anything the Unicode database does not give a joining type stands on its own. */ 23528function joiningType(codePoint) { 23529 return joiningTypes.get(codePoint) ?? "U"; 23530} 23531/** Whether the character before this one reaches forward to touch it. */ 23532function joinsForward(type) { 23533 return type === "D" || type === "L" || type === "C"; 23534} 23535/** Whether the character after this one reaches back to touch it. */ 23536function joinsBackward(type) { 23537 return type === "D" || type === "R" || type === "C"; 23538} 23539/** 23540* The shape a letter takes given what it can reach on either side. 23541* 23542* A dual-joining letter takes all four shapes, while one that joins on a single side only ever 23543* stands alone or closes a word. A letter that never joins is left as it was written: it has one 23544* shape, so naming it by a presentation form would say nothing the code point does not already say. 23545*/ 23546function formFor(type, joinedBefore, joinedAfter) { 23547 if (type === "D") { 23548 if (joinedBefore && joinedAfter) return 3; 23549 if (joinedBefore) return 1; 23550 if (joinedAfter) return 2; 23551 return 0; 23552 } 23553 if (type === "R") return joinedBefore ? 1 : 0; 23554 if (type === "L") return joinedAfter ? 2 : 0; 23555 return null; 23556} 23557/** Splits text into characters, noting the joining type of each. */ 23558function toCharacters(text) { 23559 return [...text].map((character) => { 23560 const codePoint = character.codePointAt(0); 23561 return { 23562 codePoint, 23563 type: joiningType(codePoint), 23564 form: null 23565 }; 23566 }); 23567} 23568/** 23569* Works out the shape of every letter in the text. 23570* 23571* Transparent characters are looked straight through, so a letter joins to its neighbour across any 23572* vowel points written between them. 23573*/ 23574function assignLetterForms(characters) { 23575 const visible = characters.filter((character) => character.type !== "T"); 23576 for (let i = 0; i < visible.length; i++) { 23577 const character = visible[i]; 23578 const joinedBefore = i > 0 && joinsForward(visible[i - 1].type); 23579 const joinedAfter = i + 1 < visible.length && joinsBackward(visible[i + 1].type); 23580 character.form = formFor(character.type, joinedBefore, joinedAfter); 23581 } 23582} 23583/** 23584* Gives each vowel point the shape it takes over the letter it is written on. 23585* 23586* A mark sits higher and narrower over a letter that carries on into the next one than it does over 23587* one that ends a word, so it takes its shape from whether its letter joins forwards. 23588*/ 23589function assignMarkForms(characters) { 23590 let letterJoinsForward = false; 23591 for (const character of characters) if (character.type === "T") character.form = letterJoinsForward ? 3 : 0; 23592 else letterJoinsForward = character.form === 2 || character.form === 3; 23593} 23594/** 23595* Replaces each lam followed by an alef with the single character the pair is written as. 23596* 23597* The ligature closes a word when the lam it was made from reached back to the letter before it, and 23598* otherwise stands alone. Vowel points written between the two letters are kept, and follow the 23599* ligature they belong to. 23600*/ 23601function applyLigatures(characters) { 23602 const result = []; 23603 for (let i = 0; i < characters.length; i++) { 23604 const lam = characters[i]; 23605 if (lam.codePoint !== LAM) { 23606 result.push(lam); 23607 continue; 23608 } 23609 let next = i + 1; 23610 while (next < characters.length && characters[next].type === "T") next++; 23611 const alef = characters[next]; 23612 const ligature = alef && LIGATURES[String.fromCodePoint(LAM, alef.codePoint)]; 23613 if (!ligature) { 23614 result.push(lam); 23615 continue; 23616 } 23617 const joinedBefore = lam.form === 3 || lam.form === 1; 23618 result.push({ 23619 codePoint: ligature[joinedBefore ? 1 : 0], 23620 type: "R", 23621 form: 0 23622 }); 23623 result.push(...characters.slice(i + 1, next)); 23624 i = next; 23625 } 23626 return result; 23627} 23628/** 23629* The presentation form of this character, or the character itself where there is none to use. 23630* 23631* Not every shape exists to be asked for: a dammatan is only ever encoded as it looks on its own, 23632* so a dammatan written over a joined letter falls back to that one shape rather than to the 23633* unshaped mark, which is what the letters around it have already been shaped to expect. 23634*/ 23635function toPresentationForm(character) { 23636 if (character.form === null) return character.codePoint; 23637 const forms = PRESENTATION_FORMS[character.codePoint]; 23638 if (!forms) return character.codePoint; 23639 return forms[character.form] || forms[0] || character.codePoint; 23640} 23641/** 23642* Rewrites Arabic letters as the shape they take in the word they sit in. 23643* 23644* Arabic is cursive: a letter is written differently depending on whether the letters beside it 23645* reach out to touch it. MapLibre draws one glyph at a time and asks for each by code point, so the 23646* shape has to be chosen here and named by the Presentation Forms-B code point that stands for it. 23647* 23648* Text with no Arabic in it is returned unchanged. 23649*/ 23650function applyArabicShaping(text) { 23651 if (!ARABIC.test(text)) return text; 23652 const characters = toCharacters(text); 23653 assignLetterForms(characters); 23654 assignMarkForms(characters); 23655 return applyLigatures(characters).map((character) => String.fromCodePoint(toPresentationForm(character))).join(""); 23656} 23657//#endregion 23658//#region src/symbol/transform_text.ts 23659function transformTextInternal(text, layer, feature) { 23660 const transform = layer.layout.get("text-transform").evaluate(feature, {}); 23661 if (transform === "uppercase") text = text.toLocaleUpperCase(); 23662 else if (transform === "lowercase") text = text.toLocaleLowerCase(); 23663 return (rtlWorkerPlugin.applyArabicShaping ?? applyArabicShaping)(text); 23664} 23665function transformText(text, layer, feature) { 23666 for (const section of text.sections) section.text = transformTextInternal(section.text, layer, feature); 23667 return text; 23668} 23669//#endregion 23670//#region src/symbol/merge_lines.ts 23671function getKey(text, line, onRight) { 23672 const points = onRight ? line.last.points : line.first.points; 23673 const point = onRight ? points[points.length - 1] : points[0]; 23674 return `${text}:${point.x}:${point.y}`; 23675} 23676function joinChunks(line) { 23677 const first = line.first.points; 23678 let length = first.length; 23679 for (let chunk = line.first.next; chunk; chunk = chunk.next) length += chunk.points.length - 1; 23680 const points = new Array(length); 23681 for (let i = 0; i < first.length; i++) points[i] = first[i]; 23682 let at = first.length; 23683 for (let chunk = line.first.next; chunk; chunk = chunk.next) { 23684 const from = chunk.points; 23685 for (let i = 1; i < from.length; i++) points[at++] = from[i]; 23686 } 23687 return points; 23688} 23689function mergeFromRight(merged, rightIndex, leftKey, rightKey, line) { 23690 const i = rightIndex[leftKey]; 23691 delete rightIndex[leftKey]; 23692 rightIndex[rightKey] = i; 23693 const target = merged[i]; 23694 target.last.next = line.first; 23695 target.last = line.last; 23696 return i; 23697} 23698function mergeFromLeft(merged, leftIndex, leftKey, rightKey, line) { 23699 const i = leftIndex[rightKey]; 23700 delete leftIndex[rightKey]; 23701 leftIndex[leftKey] = i; 23702 const target = merged[i]; 23703 line.last.next = target.first; 23704 target.first = line.first; 23705 return i; 23706} 23707function mergeLines(features) { 23708 const leftIndex = {}; 23709 const rightIndex = {}; 23710 const merged = []; 23711 for (const feature of features) { 23712 const text = feature.text ? feature.text.toString() : null; 23713 const chunk = { 23714 points: feature.geometry[0], 23715 next: null 23716 }; 23717 const line = { 23718 feature, 23719 first: chunk, 23720 last: chunk 23721 }; 23722 if (!text) { 23723 merged.push(line); 23724 continue; 23725 } 23726 const leftKey = getKey(text, line), rightKey = getKey(text, line, true); 23727 if (leftKey in rightIndex && rightKey in leftIndex && rightIndex[leftKey] !== leftIndex[rightKey]) { 23728 const j = mergeFromLeft(merged, leftIndex, leftKey, rightKey, line); 23729 const i = mergeFromRight(merged, rightIndex, leftKey, rightKey, merged[j]); 23730 delete leftIndex[leftKey]; 23731 delete rightIndex[rightKey]; 23732 rightIndex[getKey(text, merged[i], true)] = i; 23733 merged[j].feature.geometry = null; 23734 } else if (leftKey in rightIndex) mergeFromRight(merged, rightIndex, leftKey, rightKey, line); 23735 else if (rightKey in leftIndex) mergeFromLeft(merged, leftIndex, leftKey, rightKey, line); 23736 else { 23737 const i = merged.push(line) - 1; 23738 leftIndex[leftKey] = i; 23739 rightIndex[rightKey] = i; 23740 } 23741 } 23742 const result = []; 23743 for (const line of merged) { 23744 const feature = line.feature; 23745 if (!feature.geometry) continue; 23746 if (line.first.next) feature.geometry[0] = joinChunks(line); 23747 result.push(feature); 23748 } 23749 return result; 23750} 23751//#endregion 23752//#region src/util/graphemes.ts 23753const hasSegmenter = typeof Intl !== "undefined" && "Segmenter" in Intl; 23754/** 23755* Decides where the grapheme clusters are, corrected by {@link canCombineGraphemes} where CLDR's 23756* cursor rules split a unit of writing. Built on first use: constructing the first `Intl.Segmenter` 23757* initializes ICU, which costs several milliseconds that the main thread, which never shapes text, 23758* should not pay at import. 23759*/ 23760let graphemeSegmenter; 23761/** 23762* Decides where the words are, drawing on the browser's own dictionaries. Built on first use. 23763*/ 23764let wordSegmenter; 23765/** 23766* Splits text into grapheme clusters, or into codepoints where the environment cannot do better. 23767* 23768* A codepoint is not a unit of writing: `שְ×` is a letter with two vowel points under it, which comes 23769* apart when drawn a codepoint at a time and holds together when drawn as one cluster. 23770* 23771* Text holding none of the characters a cluster can be built from skips the segmenter, which costs 23772* far more than the test that rules it out. 23773*/ 23774function toGraphemes(text) { 23775 if (!hasSegmenter || !textCanContainGraphemeClusters(text)) return [...text]; 23776 graphemeSegmenter ??= new Intl.Segmenter(void 0, { granularity: "grapheme" }); 23777 const graphemes = []; 23778 for (const { segment } of graphemeSegmenter.segment(text)) { 23779 const last = graphemes.length - 1; 23780 if (last >= 0 && canCombineGraphemes(graphemes[last], segment)) graphemes[last] += segment; 23781 else graphemes.push(segment); 23782 } 23783 return graphemes; 23784} 23785/** 23786* The offsets, in UTF-16 code units, at which a word begins. 23787* 23788* Only scripts that do not space their words ask for these, having no punctuation to break a line 23789* at. Without a segmenter, falls back to the boundaries a regular expression can find. 23790*/ 23791function wordBoundaries(text) { 23792 const boundaries = /* @__PURE__ */ new Set(); 23793 if (hasSegmenter) { 23794 wordSegmenter ??= new Intl.Segmenter(void 0, { granularity: "word" }); 23795 for (const { index } of wordSegmenter.segment(text)) boundaries.add(index); 23796 return boundaries; 23797 } 23798 let index = 0; 23799 for (const part of text.split(/\b|(?=\p{Ideo})/u)) { 23800 boundaries.add(index); 23801 index += part.length; 23802 } 23803 return boundaries; 23804} 23805/** 23806* Whether a grapheme is more than one codepoint, and so has to be drawn as a whole. 23807* 23808* Written without allocating: this runs over every grapheme of every label. 23809*/ 23810function isCluster(grapheme) { 23811 const first = grapheme.codePointAt(0); 23812 return grapheme.length > (first > 65535 ? 2 : 1); 23813} 23814//#endregion 23815//#region src/util/script_detection.ts 23816function charIsWhitespace(char) { 23817 return /\s/u.test(String.fromCodePoint(char)); 23818} 23819function allowsVerticalWritingMode(chars) { 23820 for (const char of chars) if (codePointHasUprightVerticalOrientation(char.codePointAt(0))) return true; 23821 return false; 23822} 23823function allowsLetterSpacing(chars) { 23824 for (const char of chars) if (!charAllowsLetterSpacing(char.codePointAt(0))) return false; 23825 return true; 23826} 23827/** 23828* Whether the letters around this character can be spaced apart from it. 23829* 23830* A cursive script joins its letters up, so spacing them apart takes the word apart. 23831*/ 23832function charAllowsLetterSpacing(char) { 23833 return !codePointIsInCursiveScript(char); 23834} 23835/** 23836* Returns true if the given Unicode codepoint identifies a character with 23837* rotated orientation. 23838* 23839* A character has rotated orientation if it is drawn rotated when the line is 23840* oriented vertically, even if both adjacent characters are upright. For 23841* example, a Latin letter is drawn rotated along a vertical line. A rotated 23842* character causes an adjacent âneutralâ character to be drawn rotated as well. 23843*/ 23844function charHasRotatedVerticalOrientation(char) { 23845 return !(codePointHasUprightVerticalOrientation(char) || codePointHasNeutralVerticalOrientation(char)); 23846} 23847function charInComplexShapingScript(char) { 23848 return /\p{sc=Arab}/u.test(String.fromCodePoint(char)); 23849} 23850/** Whether this character belongs to a script that is written horizontally from right to left. */ 23851function charInRTLScript(char) { 23852 return codePointIsInRTLScript(char); 23853} 23854function stringContainsRTLText(chars) { 23855 for (const char of chars) if (charInRTLScript(char.codePointAt(0))) return true; 23856 return false; 23857} 23858//#endregion 23859//#region src/util/verticalize_punctuation.ts 23860const verticalizedCharacterMap = { 23861 "!": "ï¸", 23862 "#": "ï¼", 23863 "$": "ï¼", 23864 "%": "ï¼ ", 23865 "&": "ï¼", 23866 "(": "︵", 23867 ")": "︶", 23868 "*": "ï¼", 23869 "+": "ï¼", 23870 ",": "ï¸", 23871 "-": "︲", 23872 ".": "ã»", 23873 "/": "ï¼", 23874 ":": "ï¸", 23875 ";": "ï¸", 23876 "<": "︿", 23877 "=": "ï¼", 23878 ">": "ï¹", 23879 "?": "ï¸", 23880 "@": "ï¼ ", 23881 "[": "ï¹", 23882 "\\": "ï¼¼", 23883 "]": "ï¹", 23884 "^": "ï¼¾", 23885 "_": "︳", 23886 "`": "ï½", 23887 "{": "︷", 23888 "|": "â", 23889 "}": "︸", 23890 "~": "ï½", 23891 "¢": "ï¿ ", 23892 "£": "ï¿¡", 23893 "Â¥": "ï¿¥", 23894 "¦": "¦", 23895 "¬": "ï¿¢", 23896 "¯": "ï¿£", 23897 "â": "︲", 23898 "â": "︱", 23899 "â": "ï¹", 23900 "â": "ï¹", 23901 "â": "ï¹", 23902 "â": "ï¹", 23903 "â¦": "ï¸", 23904 "â¯": "ï¸", 23905 "â§": "ã»", 23906 "â©": "₩", 23907 "ã": "ï¸", 23908 "ã": "ï¸", 23909 "ã": "︿", 23910 "ã": "ï¹", 23911 "ã": "︽", 23912 "ã": "︾", 23913 "ã": "ï¹", 23914 "ã": "ï¹", 23915 "ã": "ï¹", 23916 "ã": "ï¹", 23917 "ã": "︻", 23918 "ã": "︼", 23919 "ã": "︹", 23920 "ã": "︺", 23921 "ã": "ï¸", 23922 "ã": "ï¸", 23923 "ï¼": "ï¸", 23924 "ï¼": "︵", 23925 "ï¼": "︶", 23926 "ï¼": "ï¸", 23927 "ï¼": "︲", 23928 "ï¼": "ã»", 23929 "ï¼": "ï¸", 23930 "ï¼": "ï¸", 23931 "ï¼": "︿", 23932 "ï¼": "ï¹", 23933 "ï¼": "ï¸", 23934 "ï¼»": "ï¹", 23935 "ï¼½": "ï¹", 23936 "_": "︳", 23937 "ï½": "︷", 23938 "ï½": "â", 23939 "ï½": "︸", 23940 "ï½": "︵", 23941 "ï½ ": "︶", 23942 "。": "ï¸", 23943 "ï½¢": "ï¹", 23944 "ï½£": "ï¹" 23945}; 23946function verticalizePunctuation(input) { 23947 let output = ""; 23948 let prevChar = { 23949 premature: true, 23950 value: void 0 23951 }; 23952 const chars = input[Symbol.iterator](); 23953 let char = chars.next(); 23954 const nextChars = input[Symbol.iterator](); 23955 nextChars.next(); 23956 let nextChar = nextChars.next(); 23957 while (!char.done) { 23958 if ((nextChar.done || !charHasRotatedVerticalOrientation(nextChar.value.codePointAt(0)) || verticalizedCharacterMap[nextChar.value]) && (prevChar.premature || !charHasRotatedVerticalOrientation(prevChar.value.codePointAt(0)) || verticalizedCharacterMap[prevChar.value]) && verticalizedCharacterMap[char.value]) output += verticalizedCharacterMap[char.value]; 23959 else output += char.value; 23960 prevChar = { 23961 value: char.value, 23962 premature: false 23963 }; 23964 char = chars.next(); 23965 nextChar = nextChars.next(); 23966 } 23967 return output; 23968} 23969//#endregion 23970//#region src/symbol/tagged_string.ts 23971const PUAbegin = 57344; 23972const PUAend = 63743; 23973/** 23974* Characters a line may end on. 23975*/ 23976const breakable = { 23977 [10]: true, 23978 [13]: true, 23979 [32]: true, 23980 [38]: true, 23981 [41]: true, 23982 [43]: true, 23983 [45]: true, 23984 [47]: true, 23985 [173]: true, 23986 [183]: true, 23987 [8203]: true, 23988 [8208]: true, 23989 [8211]: true, 23990 [8231]: true 23991}; 23992/** 23993* Characters a line may begin with, whatever precedes them. 23994*/ 23995const breakableBefore = { [40]: true }; 23996/** 23997* Returns how far a grapheme cluster advances the pen, including any letter spacing after it. 23998* 23999* Where a font file covers the cluster it advances as the one shape it is drawn as. Where none does 24000* it is drawn a codepoint at a time, and has to be measured the same way. See `shapeLines`. 24001*/ 24002function getGlyphAdvance(grapheme, section, glyphMap, imagePositions, spacing, layoutTextSize) { 24003 if ("fontStack" in section) { 24004 const positions = glyphMap[section.fontStack]; 24005 const glyph = positions?.[grapheme]; 24006 if (glyph) return glyph.metrics.advance * section.scale + spacing; 24007 let advance = 0; 24008 for (const char of grapheme) { 24009 const fallback = positions?.[char]; 24010 if (fallback) advance += fallback.metrics.advance * section.scale + spacing; 24011 } 24012 return advance; 24013 } else { 24014 const imagePosition = imagePositions[section.imageName]; 24015 if (!imagePosition) return 0; 24016 return imagePosition.displaySize[0] * section.scale * 24 / layoutTextSize + spacing; 24017 } 24018} 24019function calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) { 24020 const raggedness = Math.pow(lineWidth - targetWidth, 2); 24021 if (isLastBreak) { 24022 if (lineWidth < targetWidth) return raggedness / 2; 24023 else return raggedness * 2; 24024 } 24025 return raggedness + Math.abs(penalty) * penalty; 24026} 24027/** 24028* Whether a grapheme cluster is entirely whitespace, and so can be trimmed off the end of a line. 24029*/ 24030function isWhitespaceGrapheme(grapheme) { 24031 return /^\s+$/u.test(grapheme); 24032} 24033/** 24034* Scores a candidate break, lower being better: a newline is one the text asked for, an opening 24035* bracket left at the end of a line is merely allowed. 24036* 24037* `codePoint` and `nextCodePoint` are the first codepoints of the clusters either side, which is 24038* what decides how a cluster breaks -- a CRLF is one cluster, so a newline is seen as its CR. 24039* 24040* @param penalizableIdeographicBreak - whether this falls between ideographs in text that also 24041* carries zero-width space hints, which are the better places to break 24042*/ 24043function calculatePenalty(codePoint, nextCodePoint, penalizableIdeographicBreak) { 24044 let penalty = 0; 24045 if (codePoint === 10 || codePoint === 13) penalty -= 1e4; 24046 if (penalizableIdeographicBreak) penalty += 150; 24047 if (codePoint === 40 || codePoint === 65288) penalty += 50; 24048 if (nextCodePoint === 41 || nextCodePoint === 65289) penalty += 50; 24049 return penalty; 24050} 24051function evaluateBreak(breakIndex, breakX, targetWidth, potentialBreaks, penalty, isLastBreak) { 24052 let bestPriorBreak = null; 24053 let bestBreakBadness = calculateBadness(breakX, targetWidth, penalty, isLastBreak); 24054 for (const potentialBreak of potentialBreaks) { 24055 const breakBadness = calculateBadness(breakX - potentialBreak.x, targetWidth, penalty, isLastBreak) + potentialBreak.badness; 24056 if (breakBadness <= bestBreakBadness) { 24057 bestPriorBreak = potentialBreak; 24058 bestBreakBadness = breakBadness; 24059 } 24060 } 24061 return { 24062 index: breakIndex, 24063 x: breakX, 24064 priorBreak: bestPriorBreak, 24065 badness: bestBreakBadness 24066 }; 24067} 24068function leastBadBreaks(lastLineBreak) { 24069 if (!lastLineBreak) return []; 24070 return leastBadBreaks(lastLineBreak.priorBreak).concat(lastLineBreak.index); 24071} 24072var TaggedString = class TaggedString { 24073 constructor(text = "", sections = [], sectionIndex = []) { 24074 this.text = text; 24075 this.sections = sections; 24076 this.sectionIndex = sectionIndex; 24077 this.imageSectionID = null; 24078 this._graphemes = null; 24079 } 24080 /** 24081 * The units this text is laid out in: grapheme clusters, so that a letter and the marks that 24082 * belong to it stay together. 24083 */ 24084 graphemes() { 24085 this._graphemes ??= toGraphemes(this.text); 24086 return this._graphemes; 24087 } 24088 static fromFeature(text, defaultFontStack) { 24089 const result = new TaggedString(); 24090 for (const section of text.sections) if (!section.image) result.addTextSection(section, defaultFontStack); 24091 else result.addImageSection(section); 24092 return result; 24093 } 24094 length() { 24095 return this.graphemes().length; 24096 } 24097 getSection(index) { 24098 return this.sections[this.sectionIndex[index]]; 24099 } 24100 getSectionIndex(index) { 24101 return this.sectionIndex[index]; 24102 } 24103 verticalizePunctuation() { 24104 this.text = verticalizePunctuation(this.text); 24105 this._graphemes = null; 24106 } 24107 /** 24108 * Returns whether the text contains zero-width spaces. 24109 * 24110 * Some tilesets such as Streets insert ZWSPs as hints for line 24111 * breaking in CJK text. 24112 */ 24113 hasZeroWidthSpaces() { 24114 return this.text.includes("â"); 24115 } 24116 /** 24117 * Drops the whitespace at each end of the line. 24118 * 24119 * Counted in clusters, which is what `sectionIndex` is indexed by: a CRLF is one cluster of two 24120 * code units, so counting code units would leave the sections short of the text. 24121 */ 24122 trim() { 24123 const graphemes = this.graphemes(); 24124 let start = 0; 24125 while (start < graphemes.length && isWhitespaceGrapheme(graphemes[start])) start++; 24126 let end = graphemes.length; 24127 while (end > start && isWhitespaceGrapheme(graphemes[end - 1])) end--; 24128 this.text = graphemes.slice(start, end).join(""); 24129 this.sectionIndex = this.sectionIndex.slice(start, end); 24130 this._graphemes = null; 24131 } 24132 substring(start, end) { 24133 const text = this.graphemes().slice(start, end).join(""); 24134 const sectionIndex = this.sectionIndex.slice(start, end); 24135 return new TaggedString(text, this.sections, sectionIndex); 24136 } 24137 /** 24138 * Converts a grapheme cluster index to a UTF-16 code unit (JavaScript character index). 24139 */ 24140 toCodeUnitIndex(graphemeIndex) { 24141 return this.graphemes().slice(0, graphemeIndex).join("").length; 24142 } 24143 toString() { 24144 return this.text; 24145 } 24146 getMaxScale() { 24147 return this.sectionIndex.reduce((max, index) => Math.max(max, this.sections[index].scale), 0); 24148 } 24149 getMaxImageSize(imagePositions) { 24150 let maxImageWidth = 0; 24151 let maxImageHeight = 0; 24152 for (let i = 0; i < this.length(); i++) { 24153 const section = this.getSection(i); 24154 if ("imageName" in section) { 24155 const imagePosition = imagePositions[section.imageName]; 24156 if (!imagePosition) continue; 24157 const size = imagePosition.displaySize; 24158 maxImageWidth = Math.max(maxImageWidth, size[0]); 24159 maxImageHeight = Math.max(maxImageHeight, size[1]); 24160 } 24161 } 24162 return { 24163 maxImageWidth, 24164 maxImageHeight 24165 }; 24166 } 24167 /** 24168 * Appends one section's text, recording which section each cluster it adds belongs to. 24169 * 24170 * A cluster belongs to the section its first character came from, so a section that only joins 24171 * the cluster before it -- an accent given its own formatting -- adds none of its own. Only the 24172 * last cluster and the new text are segmented, not the label from the start. 24173 */ 24174 _appendSection(text, sectionIndex) { 24175 const graphemes = this.graphemes(); 24176 const tail = graphemes.length > 0 ? graphemes[graphemes.length - 1] : ""; 24177 const joined = toGraphemes(tail + text); 24178 this.text += text; 24179 this._graphemes = graphemes.slice(0, tail ? -1 : void 0).concat(joined); 24180 const added = joined.length - (tail ? 1 : 0); 24181 for (let i = 0; i < added; i++) this.sectionIndex.push(sectionIndex); 24182 } 24183 addTextSection(section, defaultFontStack) { 24184 this.sections.push({ 24185 scale: section.scale || 1, 24186 verticalAlign: section.verticalAlign || "bottom", 24187 fontStack: section.fontStack || defaultFontStack 24188 }); 24189 this._appendSection(section.text, this.sections.length - 1); 24190 } 24191 addImageSection(section) { 24192 const imageName = section.image ? section.image.name : ""; 24193 if (imageName.length === 0) { 24194 warnOnce("Can't add FormattedSection with an empty image."); 24195 return; 24196 } 24197 const nextImageSectionCharCode = this.getNextImageSectionCharCode(); 24198 if (!nextImageSectionCharCode) { 24199 warnOnce(`Reached maximum number of images 6401`); 24200 return; 24201 } 24202 this.sections.push({ 24203 scale: 1, 24204 verticalAlign: section.verticalAlign || "bottom", 24205 imageName 24206 }); 24207 this._appendSection(String.fromCharCode(nextImageSectionCharCode), this.sections.length - 1); 24208 } 24209 getNextImageSectionCharCode() { 24210 if (!this.imageSectionID) { 24211 this.imageSectionID = PUAbegin; 24212 return this.imageSectionID; 24213 } 24214 if (this.imageSectionID >= PUAend) return null; 24215 return ++this.imageSectionID; 24216 } 24217 /** 24218 * Returns the cluster indices to break at for lines of roughly `maxWidth`, weighing each 24219 * candidate by how ragged it leaves the line. 24220 * 24221 * Breaks fall between clusters, never inside one, at a character or image a line may end on -- 24222 * plus, in scripts that do not space their words and so offer no such character, wherever the 24223 * word segmenter finds a word. It is not consulted elsewhere, isolating a comma as a word of its 24224 * own, nor until such a script turns up, costing more than the rest of this put together. 24225 */ 24226 determineLineBreaks(spacing, maxWidth, glyphMap, imagePositions, layoutTextSize) { 24227 const potentialLineBreaks = []; 24228 const targetWidth = this.determineAverageLineWidth(spacing, maxWidth, glyphMap, imagePositions, layoutTextSize); 24229 const hasZeroWidthSpaces = this.hasZeroWidthSpaces(); 24230 const graphemes = this.graphemes(); 24231 let wordStarts = null; 24232 let currentX = 0; 24233 let codeUnit = 0; 24234 for (let i = 0; i < graphemes.length; i++) { 24235 const grapheme = graphemes[i]; 24236 if (i > 0) { 24237 const previousCodePoint = graphemes[i - 1].codePointAt(0); 24238 const codePoint = grapheme.codePointAt(0); 24239 const ideographicBreak = codePointAllowsIdeographicBreaking(previousCodePoint); 24240 const withinAWordlessScript = codePointIsWrittenWithoutSpaces(previousCodePoint) && codePointIsWrittenWithoutSpaces(codePoint); 24241 if (breakable[previousCodePoint] || ideographicBreak || "imageName" in this.getSection(i - 1) || graphemes[i + 1] !== void 0 && breakableBefore[codePoint] || withinAWordlessScript && (wordStarts ??= wordBoundaries(this.text)).has(codeUnit)) potentialLineBreaks.push(evaluateBreak(i, currentX, targetWidth, potentialLineBreaks, calculatePenalty(previousCodePoint, codePoint, ideographicBreak && hasZeroWidthSpaces), false)); 24242 } 24243 if (!charIsWhitespace(grapheme.codePointAt(0))) currentX += getGlyphAdvance(grapheme, this.getSection(i), glyphMap, imagePositions, spacing, layoutTextSize); 24244 codeUnit += grapheme.length; 24245 } 24246 return leastBadBreaks(evaluateBreak(this.length(), currentX, targetWidth, potentialLineBreaks, 0, true)); 24247 } 24248 determineAverageLineWidth(spacing, maxWidth, glyphMap, imagePositions, layoutTextSize) { 24249 let totalWidth = 0; 24250 let index = 0; 24251 for (const grapheme of this.graphemes()) { 24252 const section = this.getSection(index); 24253 totalWidth += getGlyphAdvance(grapheme, section, glyphMap, imagePositions, spacing, layoutTextSize); 24254 index++; 24255 } 24256 const lineCount = Math.max(1, Math.ceil(totalWidth / maxWidth)); 24257 return totalWidth / lineCount; 24258 } 24259}; 24260//#endregion 24261//#region node_modules/bidi-js/dist/bidi.mjs 24262function bidiFactory() { 24263 return (function(exports) { 24264 var DATA = { 24265 "R": "13k,1a,2,3,3,2+1j,ch+16,a+1,5+2,2+n,5,a,4,6+16,4+3,h+1b,4mo,179q,2+9,2+11,2i9+7y,2+68,4,3+4,5+13,4+3,2+4k,3+29,8+cf,1t+7z,w+17,3+3m,1t+3z,16o1+5r,8+30,8+mc,29+1r,29+4v,75+73", 24266 "EN": "1c+9,3d+1,6,187+9,513,4+5,7+9,sf+j,175h+9,qw+q,161f+1d,4xt+a,25i+9", 24267 "ES": "17,2,6dp+1,f+1,av,16vr,mx+1,4o,2", 24268 "ET": "z+2,3h+3,b+1,ym,3e+1,2o,p4+1,8,6u,7c,g6,1wc,1n9+4,30+1b,2n,6d,qhx+1,h0m,a+1,49+2,63+1,4+1,6bb+3,12jj", 24269 "AN": "16o+5,2j+9,2+1,35,ed,1ff2+9,87+u", 24270 "CS": "18,2+1,b,2u,12k,55v,l,17v0,2,3,53,2+1,b", 24271 "B": "a,3,f+2,2v,690", 24272 "S": "9,2,k", 24273 "WS": "c,k,4f4,1vk+a,u,1j,335", 24274 "ON": "x+1,4+4,h+5,r+5,r+3,z,5+3,2+1,2+1,5,2+2,3+4,o,w,ci+1,8+d,3+d,6+8,2+g,39+1,9,6+1,2,33,b8,3+1,3c+1,7+1,5r,b,7h+3,sa+5,2,3i+6,jg+3,ur+9,2v,ij+1,9g+9,7+a,8m,4+1,49+x,14u,2+2,c+2,e+2,e+2,e+1,i+n,e+e,2+p,u+2,e+2,36+1,2+3,2+1,b,2+2,6+5,2,2,2,h+1,5+4,6+3,3+f,16+2,5+3l,3+81,1y+p,2+40,q+a,m+13,2r+ch,2+9e,75+hf,3+v,2+2w,6e+5,f+6,75+2a,1a+p,2+2g,d+5x,r+b,6+3,4+o,g,6+1,6+2,2k+1,4,2j,5h+z,1m+1,1e+f,t+2,1f+e,d+3,4o+3,2s+1,w,535+1r,h3l+1i,93+2,2s,b+1,3l+x,2v,4g+3,21+3,kz+1,g5v+1,5a,j+9,n+v,2,3,2+8,2+1,3+2,2,3,46+1,4+4,h+5,r+5,r+a,3h+2,4+6,b+4,78,1r+24,4+c,4,1hb,ey+6,103+j,16j+c,1ux+7,5+g,fsh,jdq+1t,4,57+2e,p1,1m,1m,1m,1m,4kt+1,7j+17,5+2r,d+e,3+e,2+e,2+10,m+4,w,1n+5,1q,4z+5,4b+rb,9+c,4+c,4+37,d+2g,8+b,l+b,5+1j,9+9,7+13,9+t,3+1,27+3c,2+29,2+3q,d+d,3+4,4+2,6+6,a+o,8+6,a+2,e+6,16+42,2+1i", 24275 "BN": "0+8,6+d,2s+5,2+p,e,4m9,1kt+2,2b+5,5+5,17q9+v,7k,6p+8,6+1,119d+3,440+7,96s+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+75,6p+2rz,1ben+1,1ekf+1,1ekf+1", 24276 "NSM": "lc+33,7o+6,7c+18,2,2+1,2+1,2,21+a,1d+k,h,2u+6,3+5,3+1,2+3,10,v+q,2k+a,1n+8,a,p+3,2+8,2+2,2+4,18+2,3c+e,2+v,1k,2,5+7,5,4+6,b+1,u,1n,5+3,9,l+1,r,3+1,1m,5+1,5+1,3+2,4,v+1,4,c+1,1m,5+4,2+1,5,l+1,n+5,2,1n,3,2+3,9,8+1,c+1,v,1q,d,1f,4,1m+2,6+2,2+3,8+1,c+1,u,1n,g+1,l+1,t+1,1m+1,5+3,9,l+1,u,21,8+2,2,2j,3+6,d+7,2r,3+8,c+5,23+1,s,2,2,1k+d,2+4,2+1,6+a,2+z,a,2v+3,2+5,2+1,3+1,q+1,5+2,h+3,e,3+1,7,g,jk+2,qb+2,u+2,u+1,v+1,1t+1,2+6,9,3+a,a,1a+2,3c+1,z,3b+2,5+1,a,7+2,64+1,3,1n,2+6,2,2,3+7,7+9,3,1d+g,1s+3,1d,2+4,2,6,15+8,d+1,x+3,3+1,2+2,1l,2+1,4,2+2,1n+7,3+1,49+2,2+c,2+6,5,7,4+1,5j+1l,2+4,k1+w,2db+2,3y,2p+v,ff+3,30+1,n9x+3,2+9,x+1,29+1,7l,4,5,q+1,6,48+1,r+h,e,13+7,q+a,1b+2,1d,3+3,3+1,14,1w+5,3+1,3+1,d,9,1c,1g,2+2,3+1,6+1,2,17+1,9,6n,3,5,fn5,ki+f,h+f,r2,6b,46+4,1af+2,2+1,6+3,15+2,5,4m+1,fy+3,as+1,4a+a,4x,1j+e,1l+2,1e+3,3+1,1y+2,11+4,2+7,1r,d+1,1h+8,b+3,3,2o+2,3,2+1,7,4h,4+7,m+1,1m+1,4,12+6,4+4,5g+7,3+2,2,o,2d+5,2,5+1,2+1,6n+3,7+1,2+1,s+1,2e+7,3,2+1,2z,2,3+5,2,2u+2,3+3,2+4,78+8,2+1,75+1,2,5,41+3,3+1,5,x+5,3+1,15+5,3+3,9,a+5,3+2,1b+c,2+1,bb+6,2+5,2d+l,3+6,2+1,2+1,3f+5,4,2+1,2+6,2,21+1,4,2,9o+1,f0c+4,1o+6,t5,1s+3,2a,f5l+1,43t+2,i+7,3+6,v+3,45+2,1j0+1i,5+1d,9,f,n+4,2+e,11t+6,2+g,3+6,2+1,2+4,7a+6,c6+3,15t+6,32+6,gzhy+6n", 24277 "AL": "16w,3,2,e+1b,z+2,2+2s,g+1,8+1,b+m,2+t,s+2i,c+e,4h+f,1d+1e,1bwe+dp,3+3z,x+c,2+1,35+3y,2rm+z,5+7,b+5,dt+l,c+u,17nl+27,1t+27,4x+6n,3+d", 24278 "LRO": "6ct", 24279 "RLO": "6cu", 24280 "LRE": "6cq", 24281 "RLE": "6cr", 24282 "PDF": "6cs", 24283 "LRI": "6ee", 24284 "RLI": "6ef", 24285 "FSI": "6eg", 24286 "PDI": "6eh" 24287 }; 24288 var TYPES = {}; 24289 var TYPES_TO_NAMES = {}; 24290 TYPES.L = 1; 24291 TYPES_TO_NAMES[1] = "L"; 24292 Object.keys(DATA).forEach(function(type, i) { 24293 TYPES[type] = 1 << i + 1; 24294 TYPES_TO_NAMES[TYPES[type]] = type; 24295 }); 24296 Object.freeze(TYPES); 24297 var ISOLATE_INIT_TYPES = TYPES.LRI | TYPES.RLI | TYPES.FSI; 24298 var STRONG_TYPES = TYPES.L | TYPES.R | TYPES.AL; 24299 var NEUTRAL_ISOLATE_TYPES = TYPES.B | TYPES.S | TYPES.WS | TYPES.ON | TYPES.FSI | TYPES.LRI | TYPES.RLI | TYPES.PDI; 24300 var BN_LIKE_TYPES = TYPES.BN | TYPES.RLE | TYPES.LRE | TYPES.RLO | TYPES.LRO | TYPES.PDF; 24301 var TRAILING_TYPES = TYPES.S | TYPES.WS | TYPES.B | ISOLATE_INIT_TYPES | TYPES.PDI | BN_LIKE_TYPES; 24302 var map = null; 24303 function parseData() { 24304 if (!map) { 24305 map = /* @__PURE__ */ new Map(); 24306 var start = 0; 24307 for (var type in DATA) if (DATA.hasOwnProperty(type)) { 24308 var segments = DATA[type]; 24309 var temp = ""; 24310 var end = void 0; 24311 var state = false; 24312 var lastCode = 0; 24313 for (var i = 0; i <= segments.length + 1; i += 1) { 24314 var char = segments[i]; 24315 if (char !== "," && i !== segments.length) { 24316 if (char === "+") { 24317 state = true; 24318 lastCode = start = lastCode + parseInt(temp, 36); 24319 temp = ""; 24320 } else temp += char; 24321 } else { 24322 if (!state) { 24323 lastCode = start = lastCode + parseInt(temp, 36); 24324 end = start; 24325 } else end = start + parseInt(temp, 36); 24326 state = false; 24327 temp = ""; 24328 lastCode = end; 24329 for (var j = start; j < end + 1; j += 1) map.set(j, TYPES[type]); 24330 } 24331 } 24332 } 24333 } 24334 } 24335 /** 24336 * @param {string} char 24337 * @return {number} 24338 */ 24339 function getBidiCharType(char) { 24340 parseData(); 24341 return map.get(char.codePointAt(0)) || TYPES.L; 24342 } 24343 /** 24344 * Get Bidi Character Type Name 24345 * @param {string} char 24346 * @returns { "L" | "R" | "EN" | "ES" | "ET" | "AN" | "CS" | "B" | "S" | "WS" | "ON" | "BN" | "NSM" | "AL" | "LRO" | "RLO" | "LRE" | "RLE" | "PDF" | "LRI" | "RLI" | "FSI" | "PDI" } 24347 */ 24348 function getBidiCharTypeName(char) { 24349 return TYPES_TO_NAMES[getBidiCharType(char)]; 24350 } 24351 var data$1 = { 24352 "pairs": "14>1,1e>2,u>2,2wt>1,1>1,1ge>1,1wp>1,1j>1,f>1,hm>1,1>1,u>1,u6>1,1>1,+5,28>1,w>1,1>1,+3,b8>1,1>1,+3,1>3,-1>-1,3>1,1>1,+2,1s>1,1>1,x>1,th>1,1>1,+2,db>1,1>1,+3,3>1,1>1,+2,14qm>1,1>1,+1,4q>1,1e>2,u>2,2>1,+1", 24353 "canonical": "6f1>-6dx,6dy>-6dx,6ec>-6ed,6ee>-6ed,6ww>2jj,-2ji>2jj,14r4>-1e7l,1e7m>-1e7l,1e7m>-1e5c,1e5d>-1e5b,1e5c>-14qx,14qy>-14qx,14vn>-1ecg,1ech>-1ecg,1edu>-1ecg,1eci>-1ecg,1eda>-1ecg,1eci>-1ecg,1eci>-168q,168r>-168q,168s>-14ye,14yf>-14ye" 24354 }; 24355 /** 24356 * Parses an string that holds encoded codepoint mappings, e.g. for bracket pairs or 24357 * mirroring characters, as encoded by scripts/generateBidiData.js. Returns an object 24358 * holding the `map`, and optionally a `reverseMap` if `includeReverse:true`. 24359 * @param {string} encodedString 24360 * @param {boolean} includeReverse - true if you want reverseMap in the output 24361 * @return {{map: Map<number, number>, reverseMap?: Map<number, number>}} 24362 */ 24363 function parseCharacterMap(encodedString, includeReverse) { 24364 var radix = 36; 24365 var lastCode = 0; 24366 var map = /* @__PURE__ */ new Map(); 24367 var reverseMap = includeReverse && /* @__PURE__ */ new Map(); 24368 var prevPair; 24369 encodedString.split(",").forEach(function visit(entry) { 24370 if (entry.indexOf("+") !== -1) for (var i = +entry; i--;) visit(prevPair); 24371 else { 24372 prevPair = entry; 24373 var ref = entry.split(">"); 24374 var a = ref[0]; 24375 var b = ref[1]; 24376 a = String.fromCodePoint(lastCode += parseInt(a, radix)); 24377 b = String.fromCodePoint(lastCode += parseInt(b, radix)); 24378 map.set(a, b); 24379 includeReverse && reverseMap.set(b, a); 24380 } 24381 }); 24382 return { 24383 map, 24384 reverseMap 24385 }; 24386 } 24387 var openToClose, closeToOpen, canonical; 24388 function parse$1() { 24389 if (!openToClose) { 24390 var ref = parseCharacterMap(data$1.pairs, true); 24391 var map = ref.map; 24392 var reverseMap = ref.reverseMap; 24393 openToClose = map; 24394 closeToOpen = reverseMap; 24395 canonical = parseCharacterMap(data$1.canonical, false).map; 24396 } 24397 } 24398 /** 24399 * Get the opening bracket character corresponding to a given closing bracket character. 24400 * @param {string} char 24401 * @returns {string | null} 24402 */ 24403 function openingToClosingBracket(char) { 24404 parse$1(); 24405 return openToClose.get(char) || null; 24406 } 24407 /** 24408 * Get the closing bracket character corresponding to a given opening bracket character. 24409 * @param {string} char 24410 * @returns {string | null} 24411 */ 24412 function closingToOpeningBracket(char) { 24413 parse$1(); 24414 return closeToOpen.get(char) || null; 24415 } 24416 /** 24417 * Retrieves the canonical form of a bracket character. 24418 * @param {string} char 24419 * @returns {string | null} 24420 */ 24421 function getCanonicalBracket(char) { 24422 parse$1(); 24423 return canonical.get(char) || null; 24424 } 24425 var TYPE_L = TYPES.L; 24426 var TYPE_R = TYPES.R; 24427 var TYPE_EN = TYPES.EN; 24428 var TYPE_ES = TYPES.ES; 24429 var TYPE_ET = TYPES.ET; 24430 var TYPE_AN = TYPES.AN; 24431 var TYPE_CS = TYPES.CS; 24432 var TYPE_B = TYPES.B; 24433 var TYPE_S = TYPES.S; 24434 var TYPE_ON = TYPES.ON; 24435 var TYPE_BN = TYPES.BN; 24436 var TYPE_NSM = TYPES.NSM; 24437 var TYPE_AL = TYPES.AL; 24438 var TYPE_LRO = TYPES.LRO; 24439 var TYPE_RLO = TYPES.RLO; 24440 var TYPE_LRE = TYPES.LRE; 24441 var TYPE_RLE = TYPES.RLE; 24442 var TYPE_PDF = TYPES.PDF; 24443 var TYPE_LRI = TYPES.LRI; 24444 var TYPE_RLI = TYPES.RLI; 24445 var TYPE_FSI = TYPES.FSI; 24446 var TYPE_PDI = TYPES.PDI; 24447 /** 24448 * @typedef {object} GetEmbeddingLevelsResult 24449 * @property {{start: number, end: number, level: number}[]} paragraphs 24450 * @property {Uint8Array} levels 24451 */ 24452 /** 24453 * This function applies the Bidirectional Algorithm to a string, returning the resolved embedding levels 24454 * in a single Uint8Array plus a list of objects holding each paragraph's start and end indices and resolved 24455 * base embedding level. 24456 * 24457 * @param {string} string - The input string 24458 * @param {"ltr"|"rtl"|"auto"} [baseDirection] - Use "ltr" or "rtl" to force a base paragraph direction, 24459 * otherwise a direction will be chosen automatically from each paragraph's contents. 24460 * @return {GetEmbeddingLevelsResult} 24461 */ 24462 function getEmbeddingLevels(string, baseDirection) { 24463 var MAX_DEPTH = 125; 24464 var charTypes = new Uint32Array(string.length); 24465 for (var i = 0; i < string.length; i++) charTypes[i] = getBidiCharType(string[i]); 24466 var charTypeCounts = /* @__PURE__ */ new Map(); 24467 function changeCharType(i, type) { 24468 var oldType = charTypes[i]; 24469 charTypes[i] = type; 24470 charTypeCounts.set(oldType, charTypeCounts.get(oldType) - 1); 24471 if (oldType & NEUTRAL_ISOLATE_TYPES) charTypeCounts.set(NEUTRAL_ISOLATE_TYPES, charTypeCounts.get(NEUTRAL_ISOLATE_TYPES) - 1); 24472 charTypeCounts.set(type, (charTypeCounts.get(type) || 0) + 1); 24473 if (type & NEUTRAL_ISOLATE_TYPES) charTypeCounts.set(NEUTRAL_ISOLATE_TYPES, (charTypeCounts.get(NEUTRAL_ISOLATE_TYPES) || 0) + 1); 24474 } 24475 var embedLevels = new Uint8Array(string.length); 24476 var isolationPairs = /* @__PURE__ */ new Map(); 24477 var paragraphs = []; 24478 var paragraph = null; 24479 for (var i$1 = 0; i$1 < string.length; i$1++) { 24480 if (!paragraph) paragraphs.push(paragraph = { 24481 start: i$1, 24482 end: string.length - 1, 24483 level: baseDirection === "rtl" ? 1 : baseDirection === "ltr" ? 0 : determineAutoEmbedLevel(i$1, false) 24484 }); 24485 if (charTypes[i$1] & TYPE_B) { 24486 paragraph.end = i$1; 24487 paragraph = null; 24488 } 24489 } 24490 var FORMATTING_TYPES = TYPE_RLE | TYPE_LRE | TYPE_RLO | TYPE_LRO | ISOLATE_INIT_TYPES | TYPE_PDI | TYPE_PDF | TYPE_B; 24491 var nextEven = function(n) { 24492 return n + (n & 1 ? 1 : 2); 24493 }; 24494 var nextOdd = function(n) { 24495 return n + (n & 1 ? 2 : 1); 24496 }; 24497 for (var paraIdx = 0; paraIdx < paragraphs.length; paraIdx++) { 24498 paragraph = paragraphs[paraIdx]; 24499 var statusStack = [{ 24500 _level: paragraph.level, 24501 _override: 0, 24502 _isolate: 0 24503 }]; 24504 var stackTop = void 0; 24505 var overflowIsolateCount = 0; 24506 var overflowEmbeddingCount = 0; 24507 var validIsolateCount = 0; 24508 charTypeCounts.clear(); 24509 for (var i$2 = paragraph.start; i$2 <= paragraph.end; i$2++) { 24510 var charType = charTypes[i$2]; 24511 stackTop = statusStack[statusStack.length - 1]; 24512 charTypeCounts.set(charType, (charTypeCounts.get(charType) || 0) + 1); 24513 if (charType & NEUTRAL_ISOLATE_TYPES) charTypeCounts.set(NEUTRAL_ISOLATE_TYPES, (charTypeCounts.get(NEUTRAL_ISOLATE_TYPES) || 0) + 1); 24514 if (charType & FORMATTING_TYPES) { 24515 if (charType & (TYPE_RLE | TYPE_LRE)) { 24516 embedLevels[i$2] = stackTop._level; 24517 var level = (charType === TYPE_RLE ? nextOdd : nextEven)(stackTop._level); 24518 if (level <= MAX_DEPTH && !overflowIsolateCount && !overflowEmbeddingCount) statusStack.push({ 24519 _level: level, 24520 _override: 0, 24521 _isolate: 0 24522 }); 24523 else if (!overflowIsolateCount) overflowEmbeddingCount++; 24524 } else if (charType & (TYPE_RLO | TYPE_LRO)) { 24525 embedLevels[i$2] = stackTop._level; 24526 var level$1 = (charType === TYPE_RLO ? nextOdd : nextEven)(stackTop._level); 24527 if (level$1 <= MAX_DEPTH && !overflowIsolateCount && !overflowEmbeddingCount) statusStack.push({ 24528 _level: level$1, 24529 _override: charType & TYPE_RLO ? TYPE_R : TYPE_L, 24530 _isolate: 0 24531 }); 24532 else if (!overflowIsolateCount) overflowEmbeddingCount++; 24533 } else if (charType & ISOLATE_INIT_TYPES) { 24534 if (charType & TYPE_FSI) charType = determineAutoEmbedLevel(i$2 + 1, true) === 1 ? TYPE_RLI : TYPE_LRI; 24535 embedLevels[i$2] = stackTop._level; 24536 if (stackTop._override) changeCharType(i$2, stackTop._override); 24537 var level$2 = (charType === TYPE_RLI ? nextOdd : nextEven)(stackTop._level); 24538 if (level$2 <= MAX_DEPTH && overflowIsolateCount === 0 && overflowEmbeddingCount === 0) { 24539 validIsolateCount++; 24540 statusStack.push({ 24541 _level: level$2, 24542 _override: 0, 24543 _isolate: 1, 24544 _isolInitIndex: i$2 24545 }); 24546 } else overflowIsolateCount++; 24547 } else if (charType & TYPE_PDI) { 24548 if (overflowIsolateCount > 0) overflowIsolateCount--; 24549 else if (validIsolateCount > 0) { 24550 overflowEmbeddingCount = 0; 24551 while (!statusStack[statusStack.length - 1]._isolate) statusStack.pop(); 24552 var isolInitIndex = statusStack[statusStack.length - 1]._isolInitIndex; 24553 if (isolInitIndex != null) { 24554 isolationPairs.set(isolInitIndex, i$2); 24555 isolationPairs.set(i$2, isolInitIndex); 24556 } 24557 statusStack.pop(); 24558 validIsolateCount--; 24559 } 24560 stackTop = statusStack[statusStack.length - 1]; 24561 embedLevels[i$2] = stackTop._level; 24562 if (stackTop._override) changeCharType(i$2, stackTop._override); 24563 } else if (charType & TYPE_PDF) { 24564 if (overflowIsolateCount === 0) { 24565 if (overflowEmbeddingCount > 0) overflowEmbeddingCount--; 24566 else if (!stackTop._isolate && statusStack.length > 1) { 24567 statusStack.pop(); 24568 stackTop = statusStack[statusStack.length - 1]; 24569 } 24570 } 24571 embedLevels[i$2] = stackTop._level; 24572 } else if (charType & TYPE_B) embedLevels[i$2] = paragraph.level; 24573 } else { 24574 embedLevels[i$2] = stackTop._level; 24575 if (stackTop._override && charType !== TYPE_BN) changeCharType(i$2, stackTop._override); 24576 } 24577 } 24578 var levelRuns = []; 24579 var currentRun = null; 24580 for (var i$3 = paragraph.start; i$3 <= paragraph.end; i$3++) { 24581 var charType$1 = charTypes[i$3]; 24582 if (!(charType$1 & BN_LIKE_TYPES)) { 24583 var lvl = embedLevels[i$3]; 24584 var isIsolInit = charType$1 & ISOLATE_INIT_TYPES; 24585 var isPDI = charType$1 === TYPE_PDI; 24586 if (currentRun && lvl === currentRun._level) { 24587 currentRun._end = i$3; 24588 currentRun._endsWithIsolInit = isIsolInit; 24589 } else levelRuns.push(currentRun = { 24590 _start: i$3, 24591 _end: i$3, 24592 _level: lvl, 24593 _startsWithPDI: isPDI, 24594 _endsWithIsolInit: isIsolInit 24595 }); 24596 } 24597 } 24598 var isolatingRunSeqs = []; 24599 for (var runIdx = 0; runIdx < levelRuns.length; runIdx++) { 24600 var run = levelRuns[runIdx]; 24601 if (!run._startsWithPDI || run._startsWithPDI && !isolationPairs.has(run._start)) { 24602 var seqRuns = [currentRun = run]; 24603 for (var pdiIndex = void 0; currentRun && currentRun._endsWithIsolInit && (pdiIndex = isolationPairs.get(currentRun._end)) != null;) for (var i$4 = runIdx + 1; i$4 < levelRuns.length; i$4++) if (levelRuns[i$4]._start === pdiIndex) { 24604 seqRuns.push(currentRun = levelRuns[i$4]); 24605 break; 24606 } 24607 var seqIndices = []; 24608 for (var i$5 = 0; i$5 < seqRuns.length; i$5++) { 24609 var run$1 = seqRuns[i$5]; 24610 for (var j = run$1._start; j <= run$1._end; j++) seqIndices.push(j); 24611 } 24612 var firstLevel = embedLevels[seqIndices[0]]; 24613 var prevLevel = paragraph.level; 24614 for (var i$6 = seqIndices[0] - 1; i$6 >= 0; i$6--) if (!(charTypes[i$6] & BN_LIKE_TYPES)) { 24615 prevLevel = embedLevels[i$6]; 24616 break; 24617 } 24618 var lastIndex = seqIndices[seqIndices.length - 1]; 24619 var lastLevel = embedLevels[lastIndex]; 24620 var nextLevel = paragraph.level; 24621 if (!(charTypes[lastIndex] & ISOLATE_INIT_TYPES)) { 24622 for (var i$7 = lastIndex + 1; i$7 <= paragraph.end; i$7++) if (!(charTypes[i$7] & BN_LIKE_TYPES)) { 24623 nextLevel = embedLevels[i$7]; 24624 break; 24625 } 24626 } 24627 isolatingRunSeqs.push({ 24628 _seqIndices: seqIndices, 24629 _sosType: Math.max(prevLevel, firstLevel) % 2 ? TYPE_R : TYPE_L, 24630 _eosType: Math.max(nextLevel, lastLevel) % 2 ? TYPE_R : TYPE_L 24631 }); 24632 } 24633 } 24634 for (var seqIdx = 0; seqIdx < isolatingRunSeqs.length; seqIdx++) { 24635 var ref = isolatingRunSeqs[seqIdx]; 24636 var seqIndices$1 = ref._seqIndices; 24637 var sosType = ref._sosType; 24638 var eosType = ref._eosType; 24639 /** 24640 * All the level runs in an isolating run sequence have the same embedding level. 24641 * 24642 * DO NOT change any `embedLevels[i]` within the current scope. 24643 */ 24644 var embedDirection = embedLevels[seqIndices$1[0]] & 1 ? TYPE_R : TYPE_L; 24645 if (charTypeCounts.get(TYPE_NSM)) for (var si = 0; si < seqIndices$1.length; si++) { 24646 var i$8 = seqIndices$1[si]; 24647 if (charTypes[i$8] & TYPE_NSM) { 24648 var prevType = sosType; 24649 for (var sj = si - 1; sj >= 0; sj--) if (!(charTypes[seqIndices$1[sj]] & BN_LIKE_TYPES)) { 24650 prevType = charTypes[seqIndices$1[sj]]; 24651 break; 24652 } 24653 changeCharType(i$8, prevType & (ISOLATE_INIT_TYPES | TYPE_PDI) ? TYPE_ON : prevType); 24654 } 24655 } 24656 if (charTypeCounts.get(TYPE_EN)) for (var si$1 = 0; si$1 < seqIndices$1.length; si$1++) { 24657 var i$9 = seqIndices$1[si$1]; 24658 if (charTypes[i$9] & TYPE_EN) for (var sj$1 = si$1 - 1; sj$1 >= -1; sj$1--) { 24659 var prevCharType = sj$1 === -1 ? sosType : charTypes[seqIndices$1[sj$1]]; 24660 if (prevCharType & STRONG_TYPES) { 24661 if (prevCharType === TYPE_AL) changeCharType(i$9, TYPE_AN); 24662 break; 24663 } 24664 } 24665 } 24666 if (charTypeCounts.get(TYPE_AL)) for (var si$2 = 0; si$2 < seqIndices$1.length; si$2++) { 24667 var i$10 = seqIndices$1[si$2]; 24668 if (charTypes[i$10] & TYPE_AL) changeCharType(i$10, TYPE_R); 24669 } 24670 if (charTypeCounts.get(TYPE_ES) || charTypeCounts.get(TYPE_CS)) for (var si$3 = 1; si$3 < seqIndices$1.length - 1; si$3++) { 24671 var i$11 = seqIndices$1[si$3]; 24672 if (charTypes[i$11] & (TYPE_ES | TYPE_CS)) { 24673 var prevType$1 = 0, nextType = 0; 24674 for (var sj$2 = si$3 - 1; sj$2 >= 0; sj$2--) { 24675 prevType$1 = charTypes[seqIndices$1[sj$2]]; 24676 if (!(prevType$1 & BN_LIKE_TYPES)) break; 24677 } 24678 for (var sj$3 = si$3 + 1; sj$3 < seqIndices$1.length; sj$3++) { 24679 nextType = charTypes[seqIndices$1[sj$3]]; 24680 if (!(nextType & BN_LIKE_TYPES)) break; 24681 } 24682 if (prevType$1 === nextType && (charTypes[i$11] === TYPE_ES ? prevType$1 === TYPE_EN : prevType$1 & (TYPE_EN | TYPE_AN))) changeCharType(i$11, prevType$1); 24683 } 24684 } 24685 if (charTypeCounts.get(TYPE_EN)) { 24686 for (var si$4 = 0; si$4 < seqIndices$1.length; si$4++) if (charTypes[seqIndices$1[si$4]] & TYPE_EN) { 24687 for (var sj$4 = si$4 - 1; sj$4 >= 0 && charTypes[seqIndices$1[sj$4]] & (TYPE_ET | BN_LIKE_TYPES); sj$4--) changeCharType(seqIndices$1[sj$4], TYPE_EN); 24688 for (si$4++; si$4 < seqIndices$1.length && charTypes[seqIndices$1[si$4]] & (TYPE_ET | BN_LIKE_TYPES | TYPE_EN); si$4++) if (charTypes[seqIndices$1[si$4]] !== TYPE_EN) changeCharType(seqIndices$1[si$4], TYPE_EN); 24689 } 24690 } 24691 if (charTypeCounts.get(TYPE_ET) || charTypeCounts.get(TYPE_ES) || charTypeCounts.get(TYPE_CS)) for (var si$5 = 0; si$5 < seqIndices$1.length; si$5++) { 24692 var i$13 = seqIndices$1[si$5]; 24693 if (charTypes[i$13] & (TYPE_ET | TYPE_ES | TYPE_CS)) { 24694 changeCharType(i$13, TYPE_ON); 24695 for (var sj$5 = si$5 - 1; sj$5 >= 0 && charTypes[seqIndices$1[sj$5]] & BN_LIKE_TYPES; sj$5--) changeCharType(seqIndices$1[sj$5], TYPE_ON); 24696 for (var sj$6 = si$5 + 1; sj$6 < seqIndices$1.length && charTypes[seqIndices$1[sj$6]] & BN_LIKE_TYPES; sj$6++) changeCharType(seqIndices$1[sj$6], TYPE_ON); 24697 } 24698 } 24699 if (charTypeCounts.get(TYPE_EN)) for (var si$6 = 0, prevStrongType = sosType; si$6 < seqIndices$1.length; si$6++) { 24700 var i$14 = seqIndices$1[si$6]; 24701 var type = charTypes[i$14]; 24702 if (type & TYPE_EN) { 24703 if (prevStrongType === TYPE_L) changeCharType(i$14, TYPE_L); 24704 } else if (type & STRONG_TYPES) prevStrongType = type; 24705 } 24706 if (charTypeCounts.get(NEUTRAL_ISOLATE_TYPES)) { 24707 var R_TYPES_FOR_N_STEPS = TYPE_R | TYPE_EN | TYPE_AN; 24708 var STRONG_TYPES_FOR_N_STEPS = R_TYPES_FOR_N_STEPS | TYPE_L; 24709 var bracketPairs = []; 24710 var openerStack = []; 24711 for (var si$7 = 0; si$7 < seqIndices$1.length; si$7++) if (charTypes[seqIndices$1[si$7]] & NEUTRAL_ISOLATE_TYPES) { 24712 var char = string[seqIndices$1[si$7]]; 24713 var oppositeBracket = void 0; 24714 if (openingToClosingBracket(char) !== null) { 24715 if (openerStack.length < 63) openerStack.push({ 24716 char, 24717 seqIndex: si$7 24718 }); 24719 else break; 24720 } else if ((oppositeBracket = closingToOpeningBracket(char)) !== null) for (var stackIdx = openerStack.length - 1; stackIdx >= 0; stackIdx--) { 24721 var stackChar = openerStack[stackIdx].char; 24722 if (stackChar === oppositeBracket || stackChar === closingToOpeningBracket(getCanonicalBracket(char)) || openingToClosingBracket(getCanonicalBracket(stackChar)) === char) { 24723 bracketPairs.push([openerStack[stackIdx].seqIndex, si$7]); 24724 openerStack.length = stackIdx; 24725 break; 24726 } 24727 } 24728 } 24729 bracketPairs.sort(function(a, b) { 24730 return a[0] - b[0]; 24731 }); 24732 for (var pairIdx = 0; pairIdx < bracketPairs.length; pairIdx++) { 24733 var ref$1 = bracketPairs[pairIdx]; 24734 var openSeqIdx = ref$1[0]; 24735 var closeSeqIdx = ref$1[1]; 24736 var foundStrongType = false; 24737 var useStrongType = 0; 24738 for (var si$8 = openSeqIdx + 1; si$8 < closeSeqIdx; si$8++) { 24739 var i$15 = seqIndices$1[si$8]; 24740 if (charTypes[i$15] & STRONG_TYPES_FOR_N_STEPS) { 24741 foundStrongType = true; 24742 var lr = charTypes[i$15] & R_TYPES_FOR_N_STEPS ? TYPE_R : TYPE_L; 24743 if (lr === embedDirection) { 24744 useStrongType = lr; 24745 break; 24746 } 24747 } 24748 } 24749 if (foundStrongType && !useStrongType) { 24750 useStrongType = sosType; 24751 for (var si$9 = openSeqIdx - 1; si$9 >= 0; si$9--) { 24752 var i$16 = seqIndices$1[si$9]; 24753 if (charTypes[i$16] & STRONG_TYPES_FOR_N_STEPS) { 24754 var lr$1 = charTypes[i$16] & R_TYPES_FOR_N_STEPS ? TYPE_R : TYPE_L; 24755 if (lr$1 !== embedDirection) useStrongType = lr$1; 24756 else useStrongType = embedDirection; 24757 break; 24758 } 24759 } 24760 } 24761 if (useStrongType) { 24762 charTypes[seqIndices$1[openSeqIdx]] = charTypes[seqIndices$1[closeSeqIdx]] = useStrongType; 24763 if (useStrongType !== embedDirection) { 24764 for (var si$10 = openSeqIdx + 1; si$10 < seqIndices$1.length; si$10++) if (!(charTypes[seqIndices$1[si$10]] & BN_LIKE_TYPES)) { 24765 if (getBidiCharType(string[seqIndices$1[si$10]]) & TYPE_NSM) charTypes[seqIndices$1[si$10]] = useStrongType; 24766 break; 24767 } 24768 } 24769 if (useStrongType !== embedDirection) { 24770 for (var si$11 = closeSeqIdx + 1; si$11 < seqIndices$1.length; si$11++) if (!(charTypes[seqIndices$1[si$11]] & BN_LIKE_TYPES)) { 24771 if (getBidiCharType(string[seqIndices$1[si$11]]) & TYPE_NSM) charTypes[seqIndices$1[si$11]] = useStrongType; 24772 break; 24773 } 24774 } 24775 } 24776 } 24777 for (var si$12 = 0; si$12 < seqIndices$1.length; si$12++) if (charTypes[seqIndices$1[si$12]] & NEUTRAL_ISOLATE_TYPES) { 24778 var niRunStart = si$12, niRunEnd = si$12; 24779 var prevType$2 = sosType; 24780 for (var si2 = si$12 - 1; si2 >= 0; si2--) if (charTypes[seqIndices$1[si2]] & BN_LIKE_TYPES) niRunStart = si2; 24781 else { 24782 prevType$2 = charTypes[seqIndices$1[si2]] & R_TYPES_FOR_N_STEPS ? TYPE_R : TYPE_L; 24783 break; 24784 } 24785 var nextType$1 = eosType; 24786 for (var si2$1 = si$12 + 1; si2$1 < seqIndices$1.length; si2$1++) if (charTypes[seqIndices$1[si2$1]] & (NEUTRAL_ISOLATE_TYPES | BN_LIKE_TYPES)) niRunEnd = si2$1; 24787 else { 24788 nextType$1 = charTypes[seqIndices$1[si2$1]] & R_TYPES_FOR_N_STEPS ? TYPE_R : TYPE_L; 24789 break; 24790 } 24791 for (var sj$7 = niRunStart; sj$7 <= niRunEnd; sj$7++) charTypes[seqIndices$1[sj$7]] = prevType$2 === nextType$1 ? prevType$2 : embedDirection; 24792 si$12 = niRunEnd; 24793 } 24794 } 24795 } 24796 for (var i$17 = paragraph.start; i$17 <= paragraph.end; i$17++) { 24797 var level$3 = embedLevels[i$17]; 24798 var type$1 = charTypes[i$17]; 24799 if (level$3 & 1) { 24800 if (type$1 & (TYPE_L | TYPE_EN | TYPE_AN)) embedLevels[i$17]++; 24801 } else if (type$1 & TYPE_R) embedLevels[i$17]++; 24802 else if (type$1 & (TYPE_AN | TYPE_EN)) embedLevels[i$17] += 2; 24803 if (type$1 & BN_LIKE_TYPES) embedLevels[i$17] = i$17 === 0 ? paragraph.level : embedLevels[i$17 - 1]; 24804 if (i$17 === paragraph.end || getBidiCharType(string[i$17]) & (TYPE_S | TYPE_B)) for (var j$1 = i$17; j$1 >= 0 && getBidiCharType(string[j$1]) & TRAILING_TYPES; j$1--) embedLevels[j$1] = paragraph.level; 24805 } 24806 } 24807 return { 24808 levels: embedLevels, 24809 paragraphs 24810 }; 24811 function determineAutoEmbedLevel(start, isFSI) { 24812 for (var i = start; i < string.length; i++) { 24813 var charType = charTypes[i]; 24814 if (charType & (TYPE_R | TYPE_AL)) return 1; 24815 if (charType & (TYPE_B | TYPE_L) || isFSI && charType === TYPE_PDI) return 0; 24816 if (charType & ISOLATE_INIT_TYPES) { 24817 var pdi = indexOfMatchingPDI(i); 24818 i = pdi === -1 ? string.length : pdi; 24819 } 24820 } 24821 return 0; 24822 } 24823 function indexOfMatchingPDI(isolateStart) { 24824 var isolationLevel = 1; 24825 for (var i = isolateStart + 1; i < string.length; i++) { 24826 var charType = charTypes[i]; 24827 if (charType & TYPE_B) break; 24828 if (charType & TYPE_PDI) { 24829 if (--isolationLevel === 0) return i; 24830 } else if (charType & ISOLATE_INIT_TYPES) isolationLevel++; 24831 } 24832 return -1; 24833 } 24834 } 24835 var data = "14>1,j>2,t>2,u>2,1a>g,2v3>1,1>1,1ge>1,1wd>1,b>1,1j>1,f>1,ai>3,-2>3,+1,8>1k0,-1jq>1y7,-1y6>1hf,-1he>1h6,-1h5>1ha,-1h8>1qi,-1pu>1,6>3u,-3s>7,6>1,1>1,f>1,1>1,+2,3>1,1>1,+13,4>1,1>1,6>1eo,-1ee>1,3>1mg,-1me>1mk,-1mj>1mi,-1mg>1mi,-1md>1,1>1,+2,1>10k,-103>1,1>1,4>1,5>1,1>1,+10,3>1,1>8,-7>8,+1,-6>7,+1,a>1,1>1,u>1,u6>1,1>1,+5,26>1,1>1,2>1,2>2,8>1,7>1,4>1,1>1,+5,b8>1,1>1,+3,1>3,-2>1,2>1,1>1,+2,c>1,3>1,1>1,+2,h>1,3>1,a>1,1>1,2>1,3>1,1>1,d>1,f>1,3>1,1a>1,1>1,6>1,7>1,13>1,k>1,1>1,+19,4>1,1>1,+2,2>1,1>1,+18,m>1,a>1,1>1,lk>1,1>1,4>1,2>1,f>1,3>1,1>1,+3,db>1,1>1,+3,3>1,1>1,+2,14qm>1,1>1,+1,6>1,4j>1,j>2,t>2,u>2,2>1,+1"; 24836 var mirrorMap; 24837 function parse() { 24838 if (!mirrorMap) { 24839 var ref = parseCharacterMap(data, true); 24840 var map = ref.map; 24841 ref.reverseMap.forEach(function(value, key) { 24842 map.set(key, value); 24843 }); 24844 mirrorMap = map; 24845 } 24846 } 24847 /** 24848 * Get the mirrored character for a given character, if one exists. 24849 * @param {string} char 24850 * @return {string|null} 24851 */ 24852 function getMirroredCharacter(char) { 24853 parse(); 24854 return mirrorMap.get(char) || null; 24855 } 24856 /** 24857 * Given a string and its resolved embedding levels, build a map of indices to replacement chars 24858 * for any characters in right-to-left segments that have defined mirrored characters. 24859 * @param {string} string 24860 * @param {Uint8Array} embeddingLevels 24861 * @param {number?} [start] 24862 * @param {number?} [end] 24863 * @return {Map<number, string>} 24864 */ 24865 function getMirroredCharactersMap(string, embeddingLevels, start, end) { 24866 var strLen = string.length; 24867 start = Math.max(0, start == null ? 0 : +start); 24868 end = Math.min(strLen - 1, end == null ? strLen - 1 : +end); 24869 var map = /* @__PURE__ */ new Map(); 24870 for (var i = start; i <= end; i++) if (embeddingLevels[i] & 1) { 24871 var mirror = getMirroredCharacter(string[i]); 24872 if (mirror !== null) map.set(i, mirror); 24873 } 24874 return map; 24875 } 24876 /** 24877 * Given a start and end denoting a single line within a string, and a set of precalculated 24878 * bidi embedding levels, produce a list of segments whose ordering should be flipped, in sequence. 24879 * @param {string} string - the full input string 24880 * @param {GetEmbeddingLevelsResult} embeddingLevelsResult - the result object from getEmbeddingLevels 24881 * @param {number} [start] - first character in a subset of the full string 24882 * @param {number} [end] - last character in a subset of the full string 24883 * @return {number[][]} - the list of start/end segments that should be flipped, in order. 24884 */ 24885 function getReorderSegments(string, embeddingLevelsResult, start, end) { 24886 var strLen = string.length; 24887 start = Math.max(0, start == null ? 0 : +start); 24888 end = Math.min(strLen - 1, end == null ? strLen - 1 : +end); 24889 var segments = []; 24890 embeddingLevelsResult.paragraphs.forEach(function(paragraph) { 24891 var lineStart = Math.max(start, paragraph.start); 24892 var lineEnd = Math.min(end, paragraph.end); 24893 if (lineStart < lineEnd) { 24894 var lineLevels = embeddingLevelsResult.levels.slice(lineStart, lineEnd + 1); 24895 for (var i = lineEnd; i >= lineStart && getBidiCharType(string[i]) & TRAILING_TYPES; i--) lineLevels[i] = paragraph.level; 24896 var maxLevel = paragraph.level; 24897 var minOddLevel = Infinity; 24898 for (var i$1 = 0; i$1 < lineLevels.length; i$1++) { 24899 var level = lineLevels[i$1]; 24900 if (level > maxLevel) maxLevel = level; 24901 if (level < minOddLevel) minOddLevel = level | 1; 24902 } 24903 for (var lvl = maxLevel; lvl >= minOddLevel; lvl--) for (var i$2 = 0; i$2 < lineLevels.length; i$2++) if (lineLevels[i$2] >= lvl) { 24904 var segStart = i$2; 24905 while (i$2 + 1 < lineLevels.length && lineLevels[i$2 + 1] >= lvl) i$2++; 24906 if (i$2 > segStart) segments.push([segStart + lineStart, i$2 + lineStart]); 24907 } 24908 } 24909 }); 24910 return segments; 24911 } 24912 /** 24913 * @param {string} string 24914 * @param {GetEmbeddingLevelsResult} embedLevelsResult 24915 * @param {number} [start] 24916 * @param {number} [end] 24917 * @return {string} the new string with bidi segments reordered 24918 */ 24919 function getReorderedString(string, embedLevelsResult, start, end) { 24920 var indices = getReorderedIndices(string, embedLevelsResult, start, end); 24921 var chars = [].concat(string); 24922 indices.forEach(function(charIndex, i) { 24923 chars[i] = (embedLevelsResult.levels[charIndex] & 1 ? getMirroredCharacter(string[charIndex]) : null) || string[charIndex]; 24924 }); 24925 return chars.join(""); 24926 } 24927 /** 24928 * @param {string} string 24929 * @param {GetEmbeddingLevelsResult} embedLevelsResult 24930 * @param {number} [start] 24931 * @param {number} [end] 24932 * @return {number[]} an array with character indices in their new bidi order 24933 */ 24934 function getReorderedIndices(string, embedLevelsResult, start, end) { 24935 var segments = getReorderSegments(string, embedLevelsResult, start, end); 24936 var indices = []; 24937 for (var i = 0; i < string.length; i++) indices[i] = i; 24938 segments.forEach(function(ref) { 24939 var start = ref[0]; 24940 var end = ref[1]; 24941 var slice = indices.slice(start, end + 1); 24942 for (var i = slice.length; i--;) indices[end - i] = slice[i]; 24943 }); 24944 return indices; 24945 } 24946 exports.closingToOpeningBracket = closingToOpeningBracket; 24947 exports.getBidiCharType = getBidiCharType; 24948 exports.getBidiCharTypeName = getBidiCharTypeName; 24949 exports.getCanonicalBracket = getCanonicalBracket; 24950 exports.getEmbeddingLevels = getEmbeddingLevels; 24951 exports.getMirroredCharacter = getMirroredCharacter; 24952 exports.getMirroredCharactersMap = getMirroredCharactersMap; 24953 exports.getReorderSegments = getReorderSegments; 24954 exports.getReorderedIndices = getReorderedIndices; 24955 exports.getReorderedString = getReorderedString; 24956 exports.openingToClosingBracket = openingToClosingBracket; 24957 Object.defineProperty(exports, "__esModule", { value: true }); 24958 return exports; 24959 })({}); 24960} 24961//#endregion 24962//#region src/symbol/bidi.ts 24963const bidi = bidiFactory(); 24964/** 24965* The characters that steer the bidirectional algorithm without being written. 24966* 24967* They have done their work by the time the text has been reordered, and no font draws them, so 24968* they are dropped rather than passed on to be looked up in a glyph atlas. 24969*/ 24970const BIDI_CONTROLS = /[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/; 24971/** 24972* The character types rule L1 resets to the paragraph's own direction. 24973* 24974* Trailing spaces belong to the paragraph rather than to the run they follow, so a line of Hebrew 24975* ending in a space does not put that space on the wrong end of the line. 24976*/ 24977const NEUTRAL_AT_END_OF_LINE = /* @__PURE__ */ new Set([ 24978 "WS", 24979 "FSI", 24980 "LRI", 24981 "RLI", 24982 "PDI" 24983]); 24984/** The character types rule L1 resets wherever they appear, along with the whitespace before them. */ 24985const ALWAYS_RESET = /* @__PURE__ */ new Set(["S", "B"]); 24986/** 24987* Splits a line into grapheme clusters, tagging each with the embedding level of its first character. 24988* 24989* Reordering whole clusters is what rule L3 asks for by another route: a letter and the marks 24990* written on it move as one, so reversing a right-to-left run cannot leave the marks stranded before 24991* their letter, and layout gets back the same units of writing it asked for glyphs for. 24992*/ 24993function toClusters(text, levels, start, end) { 24994 const clusters = []; 24995 let index = start; 24996 for (const cluster of toGraphemes(text.slice(start, end))) { 24997 clusters.push({ 24998 index, 24999 text: cluster, 25000 level: levels[index] 25001 }); 25002 index += cluster.length; 25003 } 25004 return clusters; 25005} 25006/** 25007* Applies rule L1, which hands whitespace at the end of a line back to the paragraph's direction. 25008* 25009* Without it a line of right-to-left text that ends in a space would be drawn with that space on 25010* its left, where the reader does not expect it. 25011*/ 25012function resetTrailingNeutrals(clusters, paragraphLevel) { 25013 let trailing = true; 25014 for (let i = clusters.length - 1; i >= 0; i--) { 25015 const type = bidi.getBidiCharTypeName(clusters[i].text[0]); 25016 if (ALWAYS_RESET.has(type)) { 25017 clusters[i].level = paragraphLevel; 25018 trailing = true; 25019 } else if (trailing && NEUTRAL_AT_END_OF_LINE.has(type)) clusters[i].level = paragraphLevel; 25020 else trailing = false; 25021 } 25022} 25023/** 25024* Applies rule L2, which turns embedding levels into the order the text is read on screen. 25025* 25026* Each level from the deepest down to the shallowest odd one reverses every run of characters at 25027* that level or deeper, so nesting a quotation in one direction inside a sentence in the other comes 25028* out right however far the nesting goes. 25029*/ 25030function reorder(clusters, paragraphLevel) { 25031 let highest = paragraphLevel; 25032 let lowestOdd = Infinity; 25033 for (const { level } of clusters) { 25034 if (level > highest) highest = level; 25035 if ((level | 1) < lowestOdd) lowestOdd = level | 1; 25036 } 25037 const ordered = clusters.slice(); 25038 for (let level = highest; level >= lowestOdd; level--) for (let start = 0; start < ordered.length; start++) { 25039 if (ordered[start].level < level) continue; 25040 let end = start; 25041 while (end + 1 < ordered.length && ordered[end + 1].level >= level) end++; 25042 for (let i = start, j = end; i < j; i++, j--) [ordered[i], ordered[j]] = [ordered[j], ordered[i]]; 25043 start = end; 25044 } 25045 return ordered; 25046} 25047/** 25048* Swaps a bracket for its mirror image where it is read right to left. 25049* 25050* An opening parenthesis in Hebrew text is drawn as the shape that opens in that direction, which is 25051* the one Unicode calls a closing parenthesis. 25052*/ 25053function mirror(cluster) { 25054 if (cluster.level % 2 === 0) return cluster.text; 25055 return bidi.getMirroredCharacter(cluster.text) ?? cluster.text; 25056} 25057/** The paragraph a line falls in, which is what its direction is taken from. */ 25058function paragraphLevelAt(paragraphs, start) { 25059 return paragraphs.find((paragraph) => start >= paragraph.start && start <= paragraph.end)?.level ?? 0; 25060} 25061/** 25062* Puts one line into visual order. 25063* 25064* Reordering happens a grapheme cluster at a time, so a letter and the marks written on it stay 25065* together however the line is rearranged. 25066*/ 25067function reorderLine(text, levels, paragraphLevel, start, end) { 25068 const clusters = toClusters(text, levels, start, end); 25069 resetTrailingNeutrals(clusters, paragraphLevel); 25070 let reorderedText = ""; 25071 const sourceIndices = []; 25072 for (const cluster of reorder(clusters, paragraphLevel)) { 25073 if (BIDI_CONTROLS.test(cluster.text)) continue; 25074 const mirrored = mirror(cluster); 25075 reorderedText += mirrored; 25076 sourceIndices.push(...Array(mirrored.length).fill(cluster.index)); 25077 } 25078 return { 25079 text: reorderedText, 25080 sourceIndices 25081 }; 25082} 25083/** 25084* The `[start, end)` code unit range of each line, given every offset the label is to be broken at. 25085* 25086* The offsets are put in order and duplicates dropped, because a line asked to break where a 25087* paragraph already ends should be one line rather than an empty one and a full one. 25088*/ 25089function lineRanges(text, breakPoints) { 25090 const inside = breakPoints.filter((point) => point > 0 && point < text.length); 25091 const bounds = [.../* @__PURE__ */ new Set([ 25092 0, 25093 ...inside, 25094 text.length 25095 ])].sort((a, b) => a - b); 25096 const ranges = []; 25097 for (let i = 0; i + 1 < bounds.length; i++) ranges.push([bounds[i], bounds[i + 1]]); 25098 return ranges; 25099} 25100/** 25101* Reorders every line of a label, keeping where each code unit came from. 25102* 25103* A label is broken where it was asked to be broken and wherever a paragraph ends. The separators 25104* that end a paragraph are the ones the bidirectional algorithm reads its direction afresh after, 25105* so a line may not run across one however wide it is. 25106*/ 25107function processLines(text, lineBreakPoints) { 25108 const { levels, paragraphs } = bidi.getEmbeddingLevels(text); 25109 return lineRanges(text, lineBreakPoints.concat(paragraphs.map((paragraph) => paragraph.start))).map(([start, end]) => reorderLine(text, levels, paragraphLevelAt(paragraphs, start), start, end)); 25110} 25111/** 25112* Puts text into the order it is read on screen, and breaks it into lines. 25113* 25114* @param text - a whole label in logical order 25115* @param lineBreakPoints - the code unit offsets the label is to be broken at 25116* @returns one string per line, each in visual order 25117*/ 25118function processBidirectionalText(text, lineBreakPoints) { 25119 return processLines(text, lineBreakPoints).map((line) => line.text); 25120} 25121/** 25122* The same as {@link processBidirectionalText}, carrying each code unit's formatting section with it 25123* so that a label built out of several `format` sections keeps its styling once reordered. 25124* 25125* @param text - a whole label in logical order 25126* @param styleIndices - the section each code unit of `text` belongs to 25127* @param lineBreakPoints - the code unit offsets the label is to be broken at 25128* @returns one `[line, styleIndices]` pair per line, each in visual order 25129*/ 25130function processStyledBidirectionalText(text, styleIndices, lineBreakPoints) { 25131 return processLines(text, lineBreakPoints).map((line) => [line.text, line.sourceIndices.map((index) => styleIndices[index] ?? 0)]); 25132} 25133//#endregion 25134//#region node_modules/pbf/index.js 25135const SHIFT_LEFT_32 = 4294967296; 25136const SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32; 25137const TEXT_DECODER_MIN_LENGTH$1 = 12; 25138const utf8TextDecoder$1 = typeof TextDecoder === "undefined" ? null : new TextDecoder("utf-8"); 25139const PBF_VARINT = 0; 25140const PBF_FIXED64 = 1; 25141const PBF_BYTES = 2; 25142const PBF_FIXED32 = 5; 25143var PbfReader = class { 25144 /** 25145 * @param {Uint8Array | ArrayBuffer} buf 25146 */ 25147 constructor(buf) { 25148 this.buf = ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf); 25149 this.dataView = new DataView(this.buf.buffer, this.buf.byteOffset, this.buf.byteLength); 25150 this.pos = 0; 25151 this.type = 0; 25152 this._valueStart = -1; 25153 this.length = this.buf.length; 25154 } 25155 /** 25156 * @template T 25157 * @param {(tag: number, result: T, pbf: PbfReader) => void} readField 25158 * @param {T} result 25159 * @param {number} [end] 25160 */ 25161 readFields(readField, result, end = this.length) { 25162 let field; 25163 while (field = this.nextField(end)) readField(field, result, this); 25164 return result; 25165 } 25166 /** 25167 * @template T 25168 * @param {(tag: number, result: T, pbf: PbfReader) => void} readField 25169 * @param {T} result 25170 */ 25171 readMessage(readField, result) { 25172 return this.readFields(readField, result, this.readVarint() + this.pos); 25173 } 25174 readFixed32() { 25175 const val = this.dataView.getUint32(this.pos, true); 25176 this.pos += 4; 25177 return val; 25178 } 25179 readSFixed32() { 25180 const val = this.dataView.getInt32(this.pos, true); 25181 this.pos += 4; 25182 return val; 25183 } 25184 readFixed64() { 25185 const val = this.dataView.getUint32(this.pos, true) + this.dataView.getUint32(this.pos + 4, true) * SHIFT_LEFT_32; 25186 this.pos += 8; 25187 return val; 25188 } 25189 readSFixed64() { 25190 const val = this.dataView.getUint32(this.pos, true) + this.dataView.getInt32(this.pos + 4, true) * SHIFT_LEFT_32; 25191 this.pos += 8; 25192 return val; 25193 } 25194 readFloat() { 25195 const val = this.dataView.getFloat32(this.pos, true); 25196 this.pos += 4; 25197 return val; 25198 } 25199 readDouble() { 25200 const val = this.dataView.getFloat64(this.pos, true); 25201 this.pos += 8; 25202 return val; 25203 } 25204 /** 25205 * @param {boolean} [isSigned] 25206 */ 25207 readVarint(isSigned) { 25208 const buf = this.buf; 25209 const b0 = buf[this.pos++]; 25210 if (b0 < 128) return b0; 25211 let val = b0 & 127, b; 25212 b = buf[this.pos++]; 25213 val |= (b & 127) << 7; 25214 if (b < 128) return val; 25215 b = buf[this.pos++]; 25216 val |= (b & 127) << 14; 25217 if (b < 128) return val; 25218 b = buf[this.pos++]; 25219 val |= (b & 127) << 21; 25220 if (b < 128) return val; 25221 b = buf[this.pos]; 25222 val |= (b & 15) << 28; 25223 return readVarintRemainder(val, isSigned, this); 25224 } 25225 readSVarint() { 25226 const num = this.readVarint(); 25227 return num % 2 === 1 ? (num + 1) / -2 : num / 2; 25228 } 25229 readBoolean() { 25230 return Boolean(this.readVarint()); 25231 } 25232 readString() { 25233 const end = this.readVarint() + this.pos; 25234 const pos = this.pos; 25235 this.pos = end; 25236 if (end - pos >= TEXT_DECODER_MIN_LENGTH$1 && utf8TextDecoder$1) return utf8TextDecoder$1.decode(this.buf.subarray(pos, end)); 25237 return readUtf8$1(this.buf, pos, end); 25238 } 25239 readBytes() { 25240 const end = this.readVarint() + this.pos, buffer = this.buf.subarray(this.pos, end); 25241 this.pos = end; 25242 return buffer; 25243 } 25244 /** 25245 * @param {number[]} [arr] 25246 * @param {boolean} [isSigned] 25247 */ 25248 readPackedVarint(arr = [], isSigned) { 25249 const end = this.readPackedEnd(); 25250 while (this.pos < end) arr.push(this.readVarint(isSigned)); 25251 return arr; 25252 } 25253 /** @param {number[]} [arr] */ 25254 readPackedSVarint(arr = []) { 25255 const end = this.readPackedEnd(); 25256 while (this.pos < end) arr.push(this.readSVarint()); 25257 return arr; 25258 } 25259 /** @param {boolean[]} [arr] */ 25260 readPackedBoolean(arr = []) { 25261 const end = this.readPackedEnd(); 25262 while (this.pos < end) arr.push(this.readBoolean()); 25263 return arr; 25264 } 25265 /** @param {number[]} [arr] */ 25266 readPackedFloat(arr = []) { 25267 const end = this.readPackedEnd(); 25268 while (this.pos < end) arr.push(this.readFloat()); 25269 return arr; 25270 } 25271 /** @param {number[]} [arr] */ 25272 readPackedDouble(arr = []) { 25273 const end = this.readPackedEnd(); 25274 while (this.pos < end) arr.push(this.readDouble()); 25275 return arr; 25276 } 25277 /** @param {number[]} [arr] */ 25278 readPackedFixed32(arr = []) { 25279 const end = this.readPackedEnd(); 25280 while (this.pos < end) arr.push(this.readFixed32()); 25281 return arr; 25282 } 25283 /** @param {number[]} [arr] */ 25284 readPackedSFixed32(arr = []) { 25285 const end = this.readPackedEnd(); 25286 while (this.pos < end) arr.push(this.readSFixed32()); 25287 return arr; 25288 } 25289 /** @param {number[]} [arr] */ 25290 readPackedFixed64(arr = []) { 25291 const end = this.readPackedEnd(); 25292 while (this.pos < end) arr.push(this.readFixed64()); 25293 return arr; 25294 } 25295 /** @param {number[]} [arr] */ 25296 readPackedSFixed64(arr = []) { 25297 const end = this.readPackedEnd(); 25298 while (this.pos < end) arr.push(this.readSFixed64()); 25299 return arr; 25300 } 25301 readPackedEnd() { 25302 return this.type === PBF_BYTES ? this.readVarint() + this.pos : this.pos + 1; 25303 } 25304 /** 25305 * Advance to the next field. Returns the field number, or 0 at end-of-message. 25306 * @param {number} [end] 25307 */ 25308 nextField(end = this.length) { 25309 if (this.pos === this._valueStart) this.skip(this.type); 25310 if (this.pos >= end) return 0; 25311 const tag = this.readVarint(); 25312 this.type = tag & 7; 25313 this._valueStart = this.pos; 25314 return tag >>> 3; 25315 } 25316 /** @param {number} val */ 25317 skip(val) { 25318 const type = val & 7; 25319 if (type === PBF_VARINT) while (this.buf[this.pos++] > 127); 25320 else if (type === PBF_BYTES) this.pos = this.readVarint() + this.pos; 25321 else if (type === PBF_FIXED32) this.pos += 4; 25322 else if (type === PBF_FIXED64) this.pos += 8; 25323 else throw new Error(`Unimplemented type: ${type}`); 25324 } 25325}; 25326var PbfWriter = class { 25327 /** 25328 * @param {Uint8Array | ArrayBuffer} [buf] 25329 */ 25330 constructor(buf = /* @__PURE__ */ new Uint8Array(16)) { 25331 this.buf = ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf); 25332 this.dataView = new DataView(this.buf.buffer, this.buf.byteOffset, this.buf.byteLength); 25333 this.pos = 0; 25334 this.length = this.buf.length; 25335 } 25336 /** 25337 * @param {number} tag 25338 * @param {number} type 25339 */ 25340 writeTag(tag, type) { 25341 this.writeVarint(tag << 3 | type); 25342 } 25343 /** @param {number} min */ 25344 realloc(min) { 25345 let length = this.length || 16; 25346 while (length < this.pos + min) length *= 2; 25347 if (length !== this.length) { 25348 const buf = new Uint8Array(length); 25349 buf.set(this.buf); 25350 this.buf = buf; 25351 this.dataView = new DataView(buf.buffer); 25352 this.length = length; 25353 } 25354 } 25355 finish() { 25356 this.length = this.pos; 25357 this.pos = 0; 25358 return this.buf.subarray(0, this.length); 25359 } 25360 /** @param {number} val */ 25361 writeFixed32(val) { 25362 this.realloc(4); 25363 this.dataView.setInt32(this.pos, val, true); 25364 this.pos += 4; 25365 } 25366 /** @param {number} val */ 25367 writeSFixed32(val) { 25368 this.realloc(4); 25369 this.dataView.setInt32(this.pos, val, true); 25370 this.pos += 4; 25371 } 25372 /** @param {number} val */ 25373 writeFixed64(val) { 25374 this.realloc(8); 25375 this.dataView.setInt32(this.pos, val & -1, true); 25376 this.dataView.setInt32(this.pos + 4, Math.floor(val * SHIFT_RIGHT_32), true); 25377 this.pos += 8; 25378 } 25379 /** @param {number} val */ 25380 writeSFixed64(val) { 25381 this.realloc(8); 25382 this.dataView.setInt32(this.pos, val & -1, true); 25383 this.dataView.setInt32(this.pos + 4, Math.floor(val * SHIFT_RIGHT_32), true); 25384 this.pos += 8; 25385 } 25386 /** @param {number} val */ 25387 writeVarint(val) { 25388 val = +val || 0; 25389 if (val >= 0 && val < 128) { 25390 if (this.pos >= this.length) this.realloc(1); 25391 this.buf[this.pos++] = val; 25392 return; 25393 } 25394 if (val > 268435455 || val < 0) { 25395 writeBigVarint(val, this); 25396 return; 25397 } 25398 this.realloc(4); 25399 this.buf[this.pos++] = val & 127 | (val > 127 ? 128 : 0); 25400 if (val <= 127) return; 25401 this.buf[this.pos++] = (val >>>= 7) & 127 | (val > 127 ? 128 : 0); 25402 if (val <= 127) return; 25403 this.buf[this.pos++] = (val >>>= 7) & 127 | (val > 127 ? 128 : 0); 25404 if (val <= 127) return; 25405 this.buf[this.pos++] = val >>> 7 & 127; 25406 } 25407 /** @param {number} val */ 25408 writeSVarint(val) { 25409 this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2); 25410 } 25411 /** @param {boolean} val */ 25412 writeBoolean(val) { 25413 this.writeVarint(+val); 25414 } 25415 /** @param {string} str */ 25416 writeString(str) { 25417 str = String(str); 25418 this.realloc(str.length * 4); 25419 this.pos++; 25420 const startPos = this.pos; 25421 this.pos = writeUtf8(this.buf, str, this.pos); 25422 const len = this.pos - startPos; 25423 if (len >= 128) makeRoomForExtraLength(startPos, len, this); 25424 this.pos = startPos - 1; 25425 this.writeVarint(len); 25426 this.pos += len; 25427 } 25428 /** @param {number} val */ 25429 writeFloat(val) { 25430 this.realloc(4); 25431 this.dataView.setFloat32(this.pos, val, true); 25432 this.pos += 4; 25433 } 25434 /** @param {number} val */ 25435 writeDouble(val) { 25436 this.realloc(8); 25437 this.dataView.setFloat64(this.pos, val, true); 25438 this.pos += 8; 25439 } 25440 /** @param {Uint8Array} buffer */ 25441 writeBytes(buffer) { 25442 const len = buffer.length; 25443 this.writeVarint(len); 25444 this.realloc(len); 25445 this.buf.set(buffer, this.pos); 25446 this.pos += len; 25447 } 25448 /** 25449 * @template T 25450 * @param {(obj: T, pbf: PbfWriter) => void} fn 25451 * @param {T} obj 25452 */ 25453 writeRawMessage(fn, obj) { 25454 this.pos++; 25455 const startPos = this.pos; 25456 fn(obj, this); 25457 const len = this.pos - startPos; 25458 if (len >= 128) makeRoomForExtraLength(startPos, len, this); 25459 this.pos = startPos - 1; 25460 this.writeVarint(len); 25461 this.pos += len; 25462 } 25463 /** 25464 * @template T 25465 * @param {number} tag 25466 * @param {(obj: T, pbf: PbfWriter) => void} fn 25467 * @param {T} obj 25468 */ 25469 writeMessage(tag, fn, obj) { 25470 this.writeTag(tag, PBF_BYTES); 25471 this.writeRawMessage(fn, obj); 25472 } 25473 /** 25474 * @param {number} tag 25475 * @param {number[]} arr 25476 */ 25477 writePackedVarint(tag, arr) { 25478 if (arr.length) this.writeMessage(tag, writePackedVarint, arr); 25479 } 25480 /** 25481 * @param {number} tag 25482 * @param {number[]} arr 25483 */ 25484 writePackedSVarint(tag, arr) { 25485 if (arr.length) this.writeMessage(tag, writePackedSVarint, arr); 25486 } 25487 /** 25488 * @param {number} tag 25489 * @param {boolean[]} arr 25490 */ 25491 writePackedBoolean(tag, arr) { 25492 if (arr.length) this.writeMessage(tag, writePackedBoolean, arr); 25493 } 25494 /** 25495 * @param {number} tag 25496 * @param {number[]} arr 25497 */ 25498 writePackedFloat(tag, arr) { 25499 if (arr.length) this.writeMessage(tag, writePackedFloat, arr); 25500 } 25501 /** 25502 * @param {number} tag 25503 * @param {number[]} arr 25504 */ 25505 writePackedDouble(tag, arr) { 25506 if (arr.length) this.writeMessage(tag, writePackedDouble, arr); 25507 } 25508 /** 25509 * @param {number} tag 25510 * @param {number[]} arr 25511 */ 25512 writePackedFixed32(tag, arr) { 25513 if (arr.length) this.writeMessage(tag, writePackedFixed32, arr); 25514 } 25515 /** 25516 * @param {number} tag 25517 * @param {number[]} arr 25518 */ 25519 writePackedSFixed32(tag, arr) { 25520 if (arr.length) this.writeMessage(tag, writePackedSFixed32, arr); 25521 } 25522 /** 25523 * @param {number} tag 25524 * @param {number[]} arr 25525 */ 25526 writePackedFixed64(tag, arr) { 25527 if (arr.length) this.writeMessage(tag, writePackedFixed64, arr); 25528 } 25529 /** 25530 * @param {number} tag 25531 * @param {number[]} arr 25532 */ 25533 writePackedSFixed64(tag, arr) { 25534 if (arr.length) this.writeMessage(tag, writePackedSFixed64, arr); 25535 } 25536 /** 25537 * @param {number} tag 25538 * @param {Uint8Array} buffer 25539 */ 25540 writeBytesField(tag, buffer) { 25541 this.writeTag(tag, PBF_BYTES); 25542 this.writeBytes(buffer); 25543 } 25544 /** 25545 * @param {number} tag 25546 * @param {number} val 25547 */ 25548 writeFixed32Field(tag, val) { 25549 this.writeTag(tag, PBF_FIXED32); 25550 this.writeFixed32(val); 25551 } 25552 /** 25553 * @param {number} tag 25554 * @param {number} val 25555 */ 25556 writeSFixed32Field(tag, val) { 25557 this.writeTag(tag, PBF_FIXED32); 25558 this.writeSFixed32(val); 25559 } 25560 /** 25561 * @param {number} tag 25562 * @param {number} val 25563 */ 25564 writeFixed64Field(tag, val) { 25565 this.writeTag(tag, PBF_FIXED64); 25566 this.writeFixed64(val); 25567 } 25568 /** 25569 * @param {number} tag 25570 * @param {number} val 25571 */ 25572 writeSFixed64Field(tag, val) { 25573 this.writeTag(tag, PBF_FIXED64); 25574 this.writeSFixed64(val); 25575 } 25576 /** 25577 * @param {number} tag 25578 * @param {number} val 25579 */ 25580 writeVarintField(tag, val) { 25581 this.writeTag(tag, PBF_VARINT); 25582 this.writeVarint(val); 25583 } 25584 /** 25585 * @param {number} tag 25586 * @param {number} val 25587 */ 25588 writeSVarintField(tag, val) { 25589 this.writeTag(tag, PBF_VARINT); 25590 this.writeSVarint(val); 25591 } 25592 /** 25593 * @param {number} tag 25594 * @param {string} str 25595 */ 25596 writeStringField(tag, str) { 25597 this.writeTag(tag, PBF_BYTES); 25598 this.writeString(str); 25599 } 25600 /** 25601 * @param {number} tag 25602 * @param {number} val 25603 */ 25604 writeFloatField(tag, val) { 25605 this.writeTag(tag, PBF_FIXED32); 25606 this.writeFloat(val); 25607 } 25608 /** 25609 * @param {number} tag 25610 * @param {number} val 25611 */ 25612 writeDoubleField(tag, val) { 25613 this.writeTag(tag, PBF_FIXED64); 25614 this.writeDouble(val); 25615 } 25616 /** 25617 * @param {number} tag 25618 * @param {boolean} val 25619 */ 25620 writeBooleanField(tag, val) { 25621 this.writeVarintField(tag, +val); 25622 } 25623}; 25624/** 25625* @param {number} l 25626* @param {boolean | undefined} s 25627* @param {PbfReader} p 25628*/ 25629function readVarintRemainder(l, s, p) { 25630 const buf = p.buf; 25631 let h, b; 25632 b = buf[p.pos++]; 25633 h = (b & 112) >> 4; 25634 if (b < 128) return toNum(l, h, s); 25635 b = buf[p.pos++]; 25636 h |= (b & 127) << 3; 25637 if (b < 128) return toNum(l, h, s); 25638 b = buf[p.pos++]; 25639 h |= (b & 127) << 10; 25640 if (b < 128) return toNum(l, h, s); 25641 b = buf[p.pos++]; 25642 h |= (b & 127) << 17; 25643 if (b < 128) return toNum(l, h, s); 25644 b = buf[p.pos++]; 25645 h |= (b & 127) << 24; 25646 if (b < 128) return toNum(l, h, s); 25647 b = buf[p.pos++]; 25648 h |= (b & 1) << 31; 25649 if (b < 128) return toNum(l, h, s); 25650 throw new Error("Expected varint not more than 10 bytes"); 25651} 25652/** 25653* @param {number} low 25654* @param {number} high 25655* @param {boolean} [isSigned] 25656*/ 25657function toNum(low, high, isSigned) { 25658 return isSigned ? high * 4294967296 + (low >>> 0) : (high >>> 0) * 4294967296 + (low >>> 0); 25659} 25660/** 25661* @param {number} val 25662* @param {PbfWriter} pbf 25663*/ 25664function writeBigVarint(val, pbf) { 25665 let low, high; 25666 if (val >= 0) { 25667 low = val % 4294967296 | 0; 25668 high = val / 4294967296 | 0; 25669 } else { 25670 low = ~(-val % 4294967296); 25671 high = ~(-val / 4294967296); 25672 if (low ^ 4294967295) low = low + 1 | 0; 25673 else { 25674 low = 0; 25675 high = high + 1 | 0; 25676 } 25677 } 25678 if (val >= 0x10000000000000000 || val < -0x10000000000000000) throw new Error("Given varint doesn't fit into 10 bytes"); 25679 pbf.realloc(10); 25680 writeBigVarintLow(low, high, pbf); 25681 writeBigVarintHigh(high, pbf); 25682} 25683/** 25684* @param {number} high 25685* @param {number} low 25686* @param {PbfWriter} pbf 25687*/ 25688function writeBigVarintLow(low, high, pbf) { 25689 pbf.buf[pbf.pos++] = low & 127 | 128; 25690 low >>>= 7; 25691 pbf.buf[pbf.pos++] = low & 127 | 128; 25692 low >>>= 7; 25693 pbf.buf[pbf.pos++] = low & 127 | 128; 25694 low >>>= 7; 25695 pbf.buf[pbf.pos++] = low & 127 | 128; 25696 low >>>= 7; 25697 pbf.buf[pbf.pos] = low & 127; 25698} 25699/** 25700* @param {number} high 25701* @param {PbfWriter} pbf 25702*/ 25703function writeBigVarintHigh(high, pbf) { 25704 const lsb = (high & 7) << 4; 25705 pbf.buf[pbf.pos++] |= lsb | ((high >>>= 3) ? 128 : 0); 25706 if (!high) return; 25707 pbf.buf[pbf.pos++] = high & 127 | ((high >>>= 7) ? 128 : 0); 25708 if (!high) return; 25709 pbf.buf[pbf.pos++] = high & 127 | ((high >>>= 7) ? 128 : 0); 25710 if (!high) return; 25711 pbf.buf[pbf.pos++] = high & 127 | ((high >>>= 7) ? 128 : 0); 25712 if (!high) return; 25713 pbf.buf[pbf.pos++] = high & 127 | ((high >>>= 7) ? 128 : 0); 25714 if (!high) return; 25715 pbf.buf[pbf.pos++] = high & 127; 25716} 25717/** 25718* @param {number} startPos 25719* @param {number} len 25720* @param {PbfWriter} pbf 25721*/ 25722function makeRoomForExtraLength(startPos, len, pbf) { 25723 const extraLen = len <= 16383 ? 1 : len <= 2097151 ? 2 : len <= 268435455 ? 3 : Math.floor(Math.log(len) / (Math.LN2 * 7)); 25724 pbf.realloc(extraLen); 25725 pbf.buf.copyWithin(startPos + extraLen, startPos, pbf.pos); 25726} 25727/** 25728* Packed varints often dominate encode time, so write the bytes inline 25729* through a local buffer pointer rather than calling writeVarint per element, 25730* falling back to writeVarint only for negatives or near the buffer's end. 25731* @param {number[]} arr 25732* @param {PbfWriter} pbf 25733*/ 25734function writePackedVarint(arr, pbf) { 25735 const n = arr.length; 25736 let buf = pbf.buf, pos = pbf.pos, limit = pbf.length; 25737 for (let i = 0; i < n; i++) { 25738 let val = arr[i]; 25739 if (val < 0 || pos + 10 > limit) { 25740 pbf.pos = pos; 25741 pbf.writeVarint(val); 25742 buf = pbf.buf; 25743 pos = pbf.pos; 25744 limit = pbf.length; 25745 continue; 25746 } 25747 while (val > 127) { 25748 buf[pos++] = val % 128 | 128; 25749 val = Math.floor(val / 128); 25750 } 25751 buf[pos++] = val; 25752 } 25753 pbf.pos = pos; 25754} 25755/** 25756* @param {number[]} arr 25757* @param {PbfWriter} pbf 25758*/ 25759function writePackedSVarint(arr, pbf) { 25760 for (let i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]); 25761} 25762/** 25763* @param {number[]} arr 25764* @param {PbfWriter} pbf 25765*/ 25766function writePackedFloat(arr, pbf) { 25767 for (let i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]); 25768} 25769/** 25770* @param {number[]} arr 25771* @param {PbfWriter} pbf 25772*/ 25773function writePackedDouble(arr, pbf) { 25774 for (let i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]); 25775} 25776/** 25777* @param {boolean[]} arr 25778* @param {PbfWriter} pbf 25779*/ 25780function writePackedBoolean(arr, pbf) { 25781 for (let i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]); 25782} 25783/** 25784* @param {number[]} arr 25785* @param {PbfWriter} pbf 25786*/ 25787function writePackedFixed32(arr, pbf) { 25788 for (let i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]); 25789} 25790/** 25791* @param {number[]} arr 25792* @param {PbfWriter} pbf 25793*/ 25794function writePackedSFixed32(arr, pbf) { 25795 for (let i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]); 25796} 25797/** 25798* @param {number[]} arr 25799* @param {PbfWriter} pbf 25800*/ 25801function writePackedFixed64(arr, pbf) { 25802 for (let i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]); 25803} 25804/** 25805* @param {number[]} arr 25806* @param {PbfWriter} pbf 25807*/ 25808function writePackedSFixed64(arr, pbf) { 25809 for (let i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]); 25810} 25811/** 25812* @param {Uint8Array} buf 25813* @param {number} pos 25814* @param {number} end 25815*/ 25816function readUtf8$1(buf, pos, end) { 25817 let str = ""; 25818 let i = pos; 25819 while (i < end) { 25820 const b0 = buf[i]; 25821 let c = null; 25822 let bytesPerSequence = b0 > 239 ? 4 : b0 > 223 ? 3 : b0 > 191 ? 2 : 1; 25823 if (i + bytesPerSequence > end) break; 25824 let b1, b2, b3; 25825 if (bytesPerSequence === 1) { 25826 if (b0 < 128) c = b0; 25827 } else if (bytesPerSequence === 2) { 25828 b1 = buf[i + 1]; 25829 if ((b1 & 192) === 128) { 25830 c = (b0 & 31) << 6 | b1 & 63; 25831 if (c <= 127) c = null; 25832 } 25833 } else if (bytesPerSequence === 3) { 25834 b1 = buf[i + 1]; 25835 b2 = buf[i + 2]; 25836 if ((b1 & 192) === 128 && (b2 & 192) === 128) { 25837 c = (b0 & 15) << 12 | (b1 & 63) << 6 | b2 & 63; 25838 if (c <= 2047 || c >= 55296 && c <= 57343) c = null; 25839 } 25840 } else if (bytesPerSequence === 4) { 25841 b1 = buf[i + 1]; 25842 b2 = buf[i + 2]; 25843 b3 = buf[i + 3]; 25844 if ((b1 & 192) === 128 && (b2 & 192) === 128 && (b3 & 192) === 128) { 25845 c = (b0 & 15) << 18 | (b1 & 63) << 12 | (b2 & 63) << 6 | b3 & 63; 25846 if (c <= 65535 || c >= 1114112) c = null; 25847 } 25848 } 25849 if (c === null) { 25850 c = 65533; 25851 bytesPerSequence = 1; 25852 } else if (c > 65535) { 25853 c -= 65536; 25854 str += String.fromCharCode(c >>> 10 & 1023 | 55296); 25855 c = 56320 | c & 1023; 25856 } 25857 str += String.fromCharCode(c); 25858 i += bytesPerSequence; 25859 } 25860 return str; 25861} 25862/** 25863* @param {Uint8Array} buf 25864* @param {string} str 25865* @param {number} pos 25866*/ 25867function writeUtf8(buf, str, pos) { 25868 for (let i = 0, c, lead; i < str.length; i++) { 25869 c = str.charCodeAt(i); 25870 if (c > 55295 && c < 57344) { 25871 if (lead) { 25872 if (c < 56320) { 25873 buf[pos++] = 239; 25874 buf[pos++] = 191; 25875 buf[pos++] = 189; 25876 lead = c; 25877 continue; 25878 } else { 25879 c = lead - 55296 << 10 | c - 56320 | 65536; 25880 lead = null; 25881 } 25882 } else { 25883 if (c > 56319 || i + 1 === str.length) { 25884 buf[pos++] = 239; 25885 buf[pos++] = 191; 25886 buf[pos++] = 189; 25887 } else lead = c; 25888 continue; 25889 } 25890 } else if (lead) { 25891 buf[pos++] = 239; 25892 buf[pos++] = 191; 25893 buf[pos++] = 189; 25894 lead = null; 25895 } 25896 if (c < 128) buf[pos++] = c; 25897 else { 25898 if (c < 2048) buf[pos++] = c >> 6 | 192; 25899 else { 25900 if (c < 65536) buf[pos++] = c >> 12 | 224; 25901 else { 25902 buf[pos++] = c >> 18 | 240; 25903 buf[pos++] = c >> 12 & 63 | 128; 25904 } 25905 buf[pos++] = c >> 6 & 63 | 128; 25906 } 25907 buf[pos++] = c & 63 | 128; 25908 } 25909 } 25910 return pos; 25911} 25912function readFontstacks(tag, glyphs, pbf) { 25913 if (tag === 1) pbf.readMessage(readFontstack, glyphs); 25914} 25915function readFontstack(tag, glyphs, pbf) { 25916 if (tag === 3) { 25917 const { id, bitmap, width, height, left, top, advance } = pbf.readMessage(readGlyph, {}); 25918 glyphs.push({ 25919 id, 25920 bitmap: new AlphaImage({ 25921 width: width + 6, 25922 height: height + 6 25923 }, bitmap), 25924 metrics: { 25925 width, 25926 height, 25927 left, 25928 top, 25929 advance 25930 } 25931 }); 25932 } 25933} 25934function readGlyph(tag, glyph, pbf) { 25935 if (tag === 1) glyph.id = pbf.readVarint(); 25936 else if (tag === 2) glyph.bitmap = pbf.readBytes(); 25937 else if (tag === 3) glyph.width = pbf.readVarint(); 25938 else if (tag === 4) glyph.height = pbf.readVarint(); 25939 else if (tag === 5) glyph.left = pbf.readSVarint(); 25940 else if (tag === 6) glyph.top = pbf.readSVarint(); 25941 else if (tag === 7) glyph.advance = pbf.readVarint(); 25942} 25943function parseGlyphPbf(data) { 25944 return new PbfReader(data).readFields(readFontstacks, []); 25945} 25946function isStyleImageWebGLData(data) { 25947 return typeof data?.renderWithWebGL === "function"; 25948} 25949function renderStyleImage(image) { 25950 const { userImage } = image; 25951 if (!userImage?.render) return false; 25952 if (!userImage.render()) return false; 25953 if (!isStyleImageWebGLData(userImage.data)) image.data.replace(new Uint8Array(userImage.data.buffer)); 25954 return true; 25955} 25956//#endregion 25957//#region node_modules/potpack/index.js 25958/** 25959* @typedef {Object} PotpackBox 25960* @property {number} w Box width. 25961* @property {number} h Box height. 25962* @property {number} [x] X coordinate in the resulting container. 25963* @property {number} [y] Y coordinate in the resulting container. 25964*/ 25965/** 25966* @typedef {Object} PotpackStats 25967* @property {number} w Width of the resulting container. 25968* @property {number} h Height of the resulting container. 25969* @property {number} fill The space utilization value (0 to 1). Higher is better. 25970*/ 25971/** 25972* Packs 2D rectangles into a near-square container. 25973* 25974* Mutates the {@link boxes} array: it's sorted (by height/width), 25975* and box objects are augmented with `x`, `y` coordinates. 25976* 25977* @param {PotpackBox[]} boxes 25978* @return {PotpackStats} 25979*/ 25980function potpack(boxes) { 25981 let area = 0; 25982 let maxWidth = 0; 25983 for (const box of boxes) { 25984 area += box.w * box.h; 25985 maxWidth = Math.max(maxWidth, box.w); 25986 } 25987 boxes.sort((a, b) => b.h - a.h); 25988 const spaces = [{ 25989 x: 0, 25990 y: 0, 25991 w: Math.max(Math.ceil(Math.sqrt(area / .95)), maxWidth), 25992 h: Infinity 25993 }]; 25994 let width = 0; 25995 let height = 0; 25996 for (const box of boxes) for (let i = spaces.length - 1; i >= 0; i--) { 25997 const space = spaces[i]; 25998 if (box.w > space.w || box.h > space.h) continue; 25999 box.x = space.x; 26000 box.y = space.y; 26001 height = Math.max(height, box.y + box.h); 26002 width = Math.max(width, box.x + box.w); 26003 if (box.w === space.w && box.h === space.h) { 26004 const last = spaces.pop(); 26005 if (last && i < spaces.length) spaces[i] = last; 26006 } else if (box.h === space.h) { 26007 space.x += box.w; 26008 space.w -= box.w; 26009 } else if (box.w === space.w) { 26010 space.y += box.h; 26011 space.h -= box.h; 26012 } else { 26013 spaces.push({ 26014 x: space.x + box.w, 26015 y: space.y, 26016 w: space.w - box.w, 26017 h: box.h 26018 }); 26019 space.y += box.h; 26020 space.h -= box.h; 26021 } 26022 break; 26023 } 26024 return { 26025 w: width, 26026 h: height, 26027 fill: area / (width * height) || 0 26028 }; 26029} 26030var ImagePosition = class { 26031 constructor(paddedRect, { pixelRatio, version, isWebGLImage = false, stretchX, stretchY, content, textFitWidth, textFitHeight }) { 26032 this.paddedRect = paddedRect; 26033 this.pixelRatio = pixelRatio; 26034 this.stretchX = stretchX; 26035 this.stretchY = stretchY; 26036 this.content = content; 26037 this.version = version; 26038 this.needsFirstWebGLRender = isWebGLImage; 26039 this.textFitWidth = textFitWidth; 26040 this.textFitHeight = textFitHeight; 26041 } 26042 get tl() { 26043 return [this.paddedRect.x + 1, this.paddedRect.y + 1]; 26044 } 26045 get br() { 26046 return [this.paddedRect.x + this.paddedRect.w - 1, this.paddedRect.y + this.paddedRect.h - 1]; 26047 } 26048 get tlbr() { 26049 return this.tl.concat(this.br); 26050 } 26051 get displaySize() { 26052 return [(this.paddedRect.w - 2) / this.pixelRatio, (this.paddedRect.h - 2) / this.pixelRatio]; 26053 } 26054}; 26055/** 26056* A single tile's packed copy of the icons and patterns its features reference, built in the 26057* worker so that the symbol layout can bake the positions within it straight into the vertex 26058* buffers. Each tile owns one, along with the texture it is uploaded to - as opposed to 26059* {@link ImageManager}, which owns the images of the whole style. 26060* @internal 26061*/ 26062var ImageAtlas = class { 26063 constructor(icons, patterns) { 26064 const iconPositions = {}, patternPositions = {}; 26065 this.haveRenderCallbacks = []; 26066 this.patchedUpdateVersion = -1; 26067 const bins = []; 26068 this.addImages(icons, iconPositions, bins); 26069 this.addImages(patterns, patternPositions, bins); 26070 const { w, h } = potpack(bins); 26071 const image = new RGBAImage({ 26072 width: w || 1, 26073 height: h || 1 26074 }); 26075 for (const id in icons) { 26076 const src = icons[id]; 26077 if (src.isWebGLImage) continue; 26078 const bin = iconPositions[id].paddedRect; 26079 RGBAImage.copy(src.data, image, { 26080 x: 0, 26081 y: 0 26082 }, { 26083 x: bin.x + 1, 26084 y: bin.y + 1 26085 }, src.data); 26086 } 26087 for (const id in patterns) { 26088 const src = patterns[id]; 26089 const bin = patternPositions[id].paddedRect; 26090 const x = bin.x + 1, y = bin.y + 1, w = src.data.width, h = src.data.height; 26091 RGBAImage.copy(src.data, image, { 26092 x: 0, 26093 y: 0 26094 }, { 26095 x, 26096 y 26097 }, src.data); 26098 RGBAImage.copy(src.data, image, { 26099 x: 0, 26100 y: h - 1 26101 }, { 26102 x, 26103 y: y - 1 26104 }, { 26105 width: w, 26106 height: 1 26107 }); 26108 RGBAImage.copy(src.data, image, { 26109 x: 0, 26110 y: 0 26111 }, { 26112 x, 26113 y: y + h 26114 }, { 26115 width: w, 26116 height: 1 26117 }); 26118 RGBAImage.copy(src.data, image, { 26119 x: w - 1, 26120 y: 0 26121 }, { 26122 x: x - 1, 26123 y 26124 }, { 26125 width: 1, 26126 height: h 26127 }); 26128 RGBAImage.copy(src.data, image, { 26129 x: 0, 26130 y: 0 26131 }, { 26132 x: x + w, 26133 y 26134 }, { 26135 width: 1, 26136 height: h 26137 }); 26138 } 26139 this.image = image; 26140 this.iconPositions = iconPositions; 26141 this.patternPositions = patternPositions; 26142 } 26143 addImages(images, positions, bins) { 26144 for (const id in images) { 26145 const src = images[id]; 26146 const bin = { 26147 x: 0, 26148 y: 0, 26149 w: src.data.width + 2, 26150 h: src.data.height + 2 26151 }; 26152 bins.push(bin); 26153 positions[id] = new ImagePosition(bin, src); 26154 if (src.hasRenderCallback) this.haveRenderCallbacks.push(id); 26155 } 26156 } 26157 /** 26158 * Brings this atlas' texture back in sync with the images it was built from, re-uploading the 26159 * ones that were replaced in the meantime. 26160 * 26161 * This runs for every in-view tile on every frame, so the common case of nothing having 26162 * changed has to cost nothing: a single comparison against {@link ImageManager.updateVersion} 26163 * ends the call. When something did change, only the images this atlas actually holds are 26164 * looked at - a handful per tile - and {@link ImageAtlas.patchUpdatedImage} then skips the 26165 * ones whose version still matches, leaving just the genuinely stale ones to upload. 26166 * 26167 * The render callbacks are dispatched first because they may update images themselves, and 26168 * those updates have to be part of the version this call catches up with - otherwise an 26169 * animated image would always be uploaded a frame late. 26170 */ 26171 patchUpdatedImages(imageManager, texture) { 26172 imageManager.dispatchRenderCallbacks(this.haveRenderCallbacks); 26173 if (this.patchedUpdateVersion === imageManager.updateVersion) return; 26174 this.patchedUpdateVersion = imageManager.updateVersion; 26175 for (const name in this.iconPositions) this.patchUpdatedImage(this.iconPositions[name], imageManager.getImage(name), texture); 26176 for (const name in this.patternPositions) this.patchUpdatedImage(this.patternPositions[name], imageManager.getImage(name), texture); 26177 } 26178 patchUpdatedImage(position, image, texture) { 26179 if (!position || !image) return; 26180 if (!position.needsFirstWebGLRender && position.version === image.version) return; 26181 position.needsFirstWebGLRender = false; 26182 position.version = image.version; 26183 const [x, y] = position.tl; 26184 const data = image.userImage?.data; 26185 if (!isStyleImageWebGLData(data)) { 26186 texture.update(image.data, void 0, { 26187 x, 26188 y 26189 }); 26190 return; 26191 } 26192 const { width, height } = image.data; 26193 texture.context.setCustomLayerDefaults(); 26194 data.renderWithWebGL({ 26195 gl: texture.context.gl, 26196 texture: texture.texture, 26197 x, 26198 y, 26199 width, 26200 height 26201 }); 26202 texture.context.setDirty(); 26203 } 26204}; 26205register("ImagePosition", ImagePosition); 26206register("ImageAtlas", ImageAtlas); 26207//#endregion 26208//#region src/symbol/shaping.ts 26209var WritingMode = /* @__PURE__ */ function(WritingMode) { 26210 WritingMode[WritingMode["none"] = 0] = "none"; 26211 WritingMode[WritingMode["horizontal"] = 1] = "horizontal"; 26212 WritingMode[WritingMode["vertical"] = 2] = "vertical"; 26213 WritingMode[WritingMode["horizontalOnly"] = 3] = "horizontalOnly"; 26214 return WritingMode; 26215}(WritingMode || {}); 26216function isEmpty(positionedLines) { 26217 for (const line of positionedLines) if (line.positionedGlyphs.length !== 0) return false; 26218 return true; 26219} 26220function breakLines(input, lineBreakPoints) { 26221 const lines = []; 26222 let start = 0; 26223 for (const lineBreak of lineBreakPoints) { 26224 lines.push(input.substring(start, lineBreak)); 26225 start = lineBreak; 26226 } 26227 if (start < input.length()) lines.push(input.substring(start, input.length())); 26228 return lines; 26229} 26230/** A character that is written on another one rather than beside it. */ 26231const COMBINING_MARK = /^\p{gc=M}$/u; 26232/** 26233* Puts the marks written on a letter back after the letter, and returns the new order as indices 26234* into `chars`. 26235* 26236* This is rule L3 of the Unicode Bidirectional Algorithm. Reversing a right-to-left run leaves each 26237* mark before its letter, and next to the letter before that -- so undoing it is what lets a letter 26238* and its marks be one grapheme cluster again. 26239* 26240* Only marks followed by a right-to-left letter move; in a left-to-right run they already follow 26241* their base. They come back in writing order, `m2 m1 base` to `base m1 m2`, since any other order 26242* is a different cluster from the one the tile asked for a glyph for. 26243*/ 26244function combiningMarksAfterTheirBase(chars) { 26245 const order = []; 26246 let i = 0; 26247 while (i < chars.length) { 26248 if (!COMBINING_MARK.test(chars[i])) { 26249 order.push(i); 26250 i++; 26251 continue; 26252 } 26253 let end = i; 26254 while (end < chars.length && COMBINING_MARK.test(chars[end])) end++; 26255 const base = chars[end]; 26256 if (base !== void 0 && charInRTLScript(base.codePointAt(0))) { 26257 order.push(end); 26258 for (let mark = end - 1; mark >= i; mark--) order.push(mark); 26259 i = end + 1; 26260 } else { 26261 for (let mark = i; mark < end; mark++) order.push(mark); 26262 i = end; 26263 } 26264 } 26265 return order; 26266} 26267/** 26268* Spreads each cluster's style section across the code units it takes, which is what a text plugin 26269* counts in. 26270*/ 26271function sectionForEachCodeUnit(input) { 26272 const sectionIndex = []; 26273 let i = 0; 26274 for (const grapheme of input.graphemes()) { 26275 sectionIndex.push(...Array(grapheme.length).fill(input.sectionIndex[i])); 26276 i++; 26277 } 26278 return sectionIndex; 26279} 26280/** 26281* Puts a label that reads in both directions into the order it is drawn, and breaks it into lines. 26282* 26283* The bidirectional algorithm works in code units rather than in the graphemes the rest of layout 26284* counts in, so the line breaks are converted on the way in and the sections on the way out. A 26285* plugin registered through the deprecated {@link setRTLTextPlugin} is used in place of the built-in 26286* implementation, so that a map relying on one keeps the behaviour it had. 26287*/ 26288function bidiLines(logicalInput, lineBreaks) { 26289 const codeUnitBreaks = lineBreaks.map((index) => logicalInput.toCodeUnitIndex(index)); 26290 const plugin = rtlWorkerPlugin.isParsed() ? rtlWorkerPlugin : null; 26291 if (logicalInput.sections.length === 1) { 26292 if (plugin) return plugin.processBidirectionalText(logicalInput.toString(), codeUnitBreaks).map((line) => taggedLineFromPlugin(line, logicalInput.sections, [...line].map(() => 0))); 26293 return processBidirectionalText(logicalInput.toString(), codeUnitBreaks).map((line) => taggedLine([...line], logicalInput.sections, [...line].map(() => 0))); 26294 } 26295 const sectionForCodeUnit = sectionForEachCodeUnit(logicalInput); 26296 if (plugin) return plugin.processStyledBidirectionalText(logicalInput.text, sectionForCodeUnit, codeUnitBreaks).map(([line, sections]) => taggedLineFromPlugin(line, logicalInput.sections, sections)); 26297 return processStyledBidirectionalText(logicalInput.text, sectionForCodeUnit, codeUnitBreaks).map(([line, sections]) => { 26298 const chars = [...line]; 26299 return taggedLine(chars, logicalInput.sections, codeUnitOfEachCharacter(chars).map((at) => sections[at] ?? 0)); 26300 }); 26301} 26302/** 26303* Builds a line out of what a text plugin returned: the text in reading order, and the section of 26304* each code unit. A cluster belongs to the section its first character does. 26305*/ 26306/** 26307* Builds a line of a label from text that is already in the order it is drawn. 26308* 26309* The sections arrive one per code unit, as the bidirectional algorithm counts, and are handed on 26310* one per grapheme cluster, as the rest of layout counts. 26311*/ 26312function taggedLine(chars, sections, sectionOfChar) { 26313 const tagged = new TaggedString(chars.join(""), sections, []); 26314 let at = 0; 26315 for (const grapheme of tagged.graphemes()) { 26316 tagged.sectionIndex.push(sectionOfChar[at] ?? 0); 26317 at += [...grapheme].length; 26318 } 26319 return tagged; 26320} 26321/** The code unit each character of a line starts at. */ 26322function codeUnitOfEachCharacter(chars) { 26323 const offsets = []; 26324 let codeUnit = 0; 26325 for (const char of chars) { 26326 offsets.push(codeUnit); 26327 codeUnit += char.length; 26328 } 26329 return offsets; 26330} 26331/** 26332* Builds a line from what a plugin registered through the deprecated `setRTLTextPlugin` returned. 26333* 26334* A plugin reorders one code point at a time, as ICU does, which leaves the marks of a right-to-left 26335* run before the letter they are written on, so rule L3 has to be applied here. The built-in 26336* implementation reorders whole grapheme clusters and needs none of this. 26337*/ 26338function taggedLineFromPlugin(line, sections, sectionForCodeUnit) { 26339 const chars = [...line]; 26340 const codeUnitOf = codeUnitOfEachCharacter(chars); 26341 const order = combiningMarksAfterTheirBase(chars); 26342 return taggedLine(order.map((index) => chars[index]), sections, order.map((index) => sectionForCodeUnit[codeUnitOf[index]] ?? 0)); 26343} 26344function shapeText(text, glyphMap, glyphPositions, imagePositions, defaultFontStack, maxWidth, lineHeight, textAnchor, textJustify, spacing, translate, writingMode, allowVerticalPlacement, layoutTextSize, layoutTextSizeThisZoom) { 26345 const logicalInput = TaggedString.fromFeature(text, defaultFontStack); 26346 if (writingMode === 2) logicalInput.verticalizePunctuation(); 26347 const lineBreaks = logicalInput.determineLineBreaks(spacing, maxWidth, glyphMap, imagePositions, layoutTextSize); 26348 const lines = stringContainsRTLText(logicalInput.text) ? bidiLines(logicalInput, lineBreaks) : breakLines(logicalInput, lineBreaks); 26349 const positionedLines = []; 26350 const shaping = { 26351 positionedLines, 26352 text: logicalInput.toString(), 26353 top: translate[1], 26354 bottom: translate[1], 26355 left: translate[0], 26356 right: translate[0], 26357 writingMode, 26358 iconsInText: false, 26359 verticalizable: false 26360 }; 26361 shapeLines(shaping, glyphMap, glyphPositions, imagePositions, lines, lineHeight, textAnchor, textJustify, writingMode, spacing, allowVerticalPlacement, layoutTextSizeThisZoom); 26362 if (isEmpty(positionedLines)) return false; 26363 return shaping; 26364} 26365function getAnchorAlignment(anchor) { 26366 let horizontalAlign = .5, verticalAlign = .5; 26367 switch (anchor) { 26368 case "right": 26369 case "top-right": 26370 case "bottom-right": 26371 horizontalAlign = 1; 26372 break; 26373 case "left": 26374 case "top-left": 26375 case "bottom-left": horizontalAlign = 0; 26376 } 26377 switch (anchor) { 26378 case "bottom": 26379 case "bottom-right": 26380 case "bottom-left": 26381 verticalAlign = 1; 26382 break; 26383 case "top": 26384 case "top-right": 26385 case "top-left": verticalAlign = 0; 26386 } 26387 return { 26388 horizontalAlign, 26389 verticalAlign 26390 }; 26391} 26392function calculateLineContentSize(imagePositions, line, layoutTextSizeFactor) { 26393 const maxGlyphSize = line.getMaxScale() * 24; 26394 const { maxImageWidth, maxImageHeight } = line.getMaxImageSize(imagePositions); 26395 const horizontalLineContentHeight = Math.max(maxGlyphSize, maxImageHeight * layoutTextSizeFactor); 26396 return { 26397 verticalLineContentWidth: Math.max(maxGlyphSize, maxImageWidth * layoutTextSizeFactor), 26398 horizontalLineContentHeight 26399 }; 26400} 26401function getVerticalAlignFactor(verticalAlign) { 26402 switch (verticalAlign) { 26403 case "top": return 0; 26404 case "center": return .5; 26405 default: return 1; 26406 } 26407} 26408function getRectAndMetrics(glyphPosition, glyphMap, section, key) { 26409 if (glyphPosition?.rect) return glyphPosition; 26410 const glyph = glyphMap[section.fontStack]?.[key]; 26411 if (!glyph) return null; 26412 return { 26413 rect: null, 26414 metrics: glyph.metrics 26415 }; 26416} 26417function isLineVertical(writingMode, allowVerticalPlacement, codePoint) { 26418 return !(writingMode === 1 || !allowVerticalPlacement && !codePointHasUprightVerticalOrientation(codePoint) || allowVerticalPlacement && (charIsWhitespace(codePoint) || charInComplexShapingScript(codePoint))); 26419} 26420/** Returns whether the codepoint is a decimal digit of any script (`\p{Nd}`). */ 26421function charIsDecimalDigit(codePoint) { 26422 return /\p{Nd}/u.test(String.fromCodePoint(codePoint)); 26423} 26424/** Returns whether the codepoint is an uppercase letter of any script (`\p{Lu}`). */ 26425function charIsUppercaseLetter(codePoint) { 26426 return /\p{Lu}/u.test(String.fromCodePoint(codePoint)); 26427} 26428/** Returns whether the codepoint is a punctuation or symbol character (`\p{P}` or `\p{S}`). */ 26429function charIsSymbolOrPunctuation(codePoint) { 26430 return /[\p{P}\p{S}]/u.test(String.fromCodePoint(codePoint)); 26431} 26432/** 26433* Uppercase runs longer than this are words (e.g. âISHIKAWAâ in a dual name), 26434* which read better lying along the line; shorter runs are codes (âJRâ, âA1â). 26435*/ 26436const MAX_UPRIGHT_LETTER_RUN = 3; 26437/** 26438* Returns whether a run qualifies for upright treatment: numbers of any length, 26439* optionally combined with symbols (â21â, â1-2â), and codes of up to 26440* {@link MAX_UPRIGHT_LETTER_RUN} uppercase letters and digits (âJRâ, âA1â). 26441*/ 26442function runIsUpright(run) { 26443 const isNumber = run.some(charIsDecimalDigit) && run.every((codePoint) => charIsDecimalDigit(codePoint) || charIsSymbolOrPunctuation(codePoint)); 26444 const isShortUppercaseCode = run.length <= MAX_UPRIGHT_LETTER_RUN && run.every((codePoint) => charIsUppercaseLetter(codePoint) || charIsDecimalDigit(codePoint)); 26445 return isNumber || isShortUppercaseCode; 26446} 26447/** 26448* Returns whether a letter or digit in a qualifying run is drawn upright. 26449* Punctuation and symbols are handled separately by 26450* {@link verticalizeSurroundedPunctuation}; complex-shaping scripts keep 26451* following the line. 26452*/ 26453function charIsUprightInRun(codePoint) { 26454 return (charIsDecimalDigit(codePoint) || charIsUppercaseLetter(codePoint)) && !charInComplexShapingScript(codePoint); 26455} 26456/** 26457* Replaces punctuation surrounded by upright characters with its vertical 26458* presentation form (â-â in â1-2â becomes â︲â) and marks it upright. 26459* `verticalizePunctuation` cannot do this earlier: it doesn't know which 26460* characters {@link determineLineVerticals} draws upright. 26461* 26462* Returns whether anything in `chars` was replaced. 26463*/ 26464function verticalizeSurroundedPunctuation(chars, verticals) { 26465 let replaced = false; 26466 for (let i = 0; i < chars.length; i++) { 26467 if (verticals[i]) continue; 26468 const verticalizedChar = verticalizedCharacterMap[chars[i]]; 26469 if (!verticalizedChar) continue; 26470 if ((i === 0 || verticals[i - 1]) && (i === chars.length - 1 || verticals[i + 1])) { 26471 chars[i] = verticalizedChar; 26472 verticals[i] = true; 26473 replaced = true; 26474 } 26475 } 26476 return replaced; 26477} 26478/** 26479* Returns, for each grapheme cluster of a vertically laid out line label, whether 26480* its glyph is drawn upright rather than lying along the line, and updates 26481* `line` with vertical presentation forms of punctuation. 26482* 26483* A run passed to {@link runIsUpright} is a maximal sequence of non-upright 26484* characters that are neither whitespace nor inline images. 26485* 26486* Counted in clusters, to line up with `getSection` and the layout loop. A cluster's orientation is 26487* that of the character it starts with. 26488*/ 26489function determineLineVerticals(line) { 26490 const chars = line.graphemes().slice(); 26491 const codePoints = chars.map((char) => char.codePointAt(0)); 26492 const verticals = codePoints.map(codePointHasUprightVerticalOrientation); 26493 const isRunCharacter = (i) => !verticals[i] && !charIsWhitespace(codePoints[i]) && !("imageName" in line.getSection(i)); 26494 for (let start = 0; start < codePoints.length; start++) { 26495 if (!isRunCharacter(start)) continue; 26496 let end = start; 26497 while (end + 1 < codePoints.length && isRunCharacter(end + 1)) end++; 26498 if (runIsUpright(codePoints.slice(start, end + 1))) for (let i = start; i <= end; i++) verticals[i] = charIsUprightInRun(codePoints[i]); 26499 start = end; 26500 } 26501 if (verticalizeSurroundedPunctuation(chars, verticals)) { 26502 line.text = chars.join(""); 26503 line._graphemes = null; 26504 } 26505 return verticals; 26506} 26507/** 26508* Places every glyph of every line, filling in `shaping`. 26509* 26510* A cluster is drawn as one shape where a font file covers it, and a codepoint at a time where none 26511* does -- which is what a style declaring no `font-faces` keeps doing. 26512*/ 26513function shapeLines(shaping, glyphMap, glyphPositions, imagePositions, lines, lineHeight, textAnchor, textJustify, writingMode, spacing, allowVerticalPlacement, layoutTextSizeThisZoom) { 26514 let x = 0; 26515 let y = 0; 26516 let maxLineLength = 0; 26517 let maxLineHeight = 0; 26518 const justify = textJustify === "right" ? 1 : textJustify === "left" ? 0 : .5; 26519 const layoutTextSizeFactor = 24 / layoutTextSizeThisZoom; 26520 let lineIndex = 0; 26521 for (const line of lines) { 26522 line.trim(); 26523 const lineMaxScale = line.getMaxScale(); 26524 const positionedLine = { 26525 positionedGlyphs: [], 26526 lineOffset: 0 26527 }; 26528 shaping.positionedLines[lineIndex] = positionedLine; 26529 const positionedGlyphs = positionedLine.positionedGlyphs; 26530 let imageOffset = 0; 26531 if (!line.length()) { 26532 y += lineHeight; 26533 ++lineIndex; 26534 continue; 26535 } 26536 const lineShapingSize = calculateLineContentSize(imagePositions, line, layoutTextSizeFactor); 26537 const lineVerticals = writingMode === 2 && !allowVerticalPlacement ? determineLineVerticals(line) : null; 26538 const graphemes = line.graphemes(); 26539 for (let i = 0; i < graphemes.length; i++) { 26540 const section = line.getSection(i); 26541 const grapheme = graphemes[i]; 26542 const codePoint = grapheme.codePointAt(0); 26543 const vertical = lineVerticals ? lineVerticals[i] : isLineVertical(writingMode, allowVerticalPlacement, codePoint); 26544 const keys = "fontStack" in section && isCluster(grapheme) && !glyphMap[section.fontStack]?.[grapheme] ? [...grapheme] : [grapheme]; 26545 for (const key of keys) { 26546 const positionedGlyph = { 26547 glyph: key.codePointAt(0), 26548 grapheme: key, 26549 imageName: null, 26550 x, 26551 y: y + -17, 26552 vertical, 26553 scale: 1, 26554 fontStack: "", 26555 sectionIndex: line.getSectionIndex(i), 26556 metrics: null, 26557 rect: null 26558 }; 26559 let sectionAttributes; 26560 if ("fontStack" in section) { 26561 sectionAttributes = shapeTextSection(section, key, vertical, lineShapingSize, glyphMap, glyphPositions); 26562 if (!sectionAttributes) continue; 26563 positionedGlyph.fontStack = section.fontStack; 26564 } else { 26565 shaping.iconsInText = true; 26566 section.scale *= layoutTextSizeFactor; 26567 sectionAttributes = shapeImageSection(section, vertical, lineMaxScale, lineShapingSize, imagePositions); 26568 if (!sectionAttributes) continue; 26569 imageOffset = Math.max(imageOffset, sectionAttributes.imageOffset); 26570 positionedGlyph.imageName = section.imageName; 26571 } 26572 const { rect, metrics, baselineOffset } = sectionAttributes; 26573 positionedGlyph.y += baselineOffset; 26574 positionedGlyph.scale = section.scale; 26575 positionedGlyph.metrics = metrics; 26576 positionedGlyph.rect = rect; 26577 positionedGlyphs.push(positionedGlyph); 26578 if (!vertical) x += metrics.advance * section.scale + spacing; 26579 else { 26580 shaping.verticalizable = true; 26581 const verticalAdvance = "imageName" in section ? metrics.advance : 24; 26582 x += verticalAdvance * section.scale + spacing; 26583 } 26584 } 26585 } 26586 if (positionedGlyphs.length !== 0) { 26587 const lineLength = x - spacing; 26588 maxLineLength = Math.max(lineLength, maxLineLength); 26589 justifyLine(positionedGlyphs, 0, positionedGlyphs.length - 1, justify); 26590 } 26591 x = 0; 26592 const maxLineOffset = (lineMaxScale - 1) * 24; 26593 positionedLine.lineOffset = Math.max(imageOffset, maxLineOffset); 26594 const currentLineHeight = lineHeight * lineMaxScale + imageOffset; 26595 y += currentLineHeight; 26596 maxLineHeight = Math.max(currentLineHeight, maxLineHeight); 26597 ++lineIndex; 26598 } 26599 const { horizontalAlign, verticalAlign } = getAnchorAlignment(textAnchor); 26600 align(shaping.positionedLines, justify, horizontalAlign, verticalAlign, maxLineLength, maxLineHeight, lineHeight, y, lines.length); 26601 shaping.top += -verticalAlign * y; 26602 shaping.bottom = shaping.top + y; 26603 shaping.left += -horizontalAlign * maxLineLength; 26604 shaping.right = shaping.left + maxLineLength; 26605} 26606function shapeTextSection(section, key, vertical, lineShapingSize, glyphMap, glyphPositions) { 26607 const glyphPosition = glyphPositions[section.fontStack]?.[key]; 26608 const rectAndMetrics = getRectAndMetrics(glyphPosition, glyphMap, section, key); 26609 if (rectAndMetrics === null) return null; 26610 let baselineOffset; 26611 if (vertical) baselineOffset = lineShapingSize.verticalLineContentWidth - section.scale * 24; 26612 else { 26613 const verticalAlignFactor = getVerticalAlignFactor(section.verticalAlign); 26614 baselineOffset = (lineShapingSize.horizontalLineContentHeight - section.scale * 24) * verticalAlignFactor; 26615 } 26616 return { 26617 rect: rectAndMetrics.rect, 26618 metrics: rectAndMetrics.metrics, 26619 baselineOffset 26620 }; 26621} 26622function shapeImageSection(section, vertical, lineMaxScale, lineShapingSize, imagePositions) { 26623 const imagePosition = imagePositions[section.imageName]; 26624 if (!imagePosition) return null; 26625 const rect = imagePosition.paddedRect; 26626 const size = imagePosition.displaySize; 26627 const metrics = { 26628 width: size[0], 26629 height: size[1], 26630 left: 1, 26631 top: -3, 26632 advance: vertical ? size[1] : size[0] 26633 }; 26634 let baselineOffset; 26635 if (vertical) baselineOffset = lineShapingSize.verticalLineContentWidth - size[1] * section.scale; 26636 else { 26637 const verticalAlignFactor = getVerticalAlignFactor(section.verticalAlign); 26638 baselineOffset = (lineShapingSize.horizontalLineContentHeight - size[1] * section.scale) * verticalAlignFactor; 26639 } 26640 const imageOffset = (vertical ? size[0] : size[1]) * section.scale - 24 * lineMaxScale; 26641 return { 26642 rect, 26643 metrics, 26644 baselineOffset, 26645 imageOffset 26646 }; 26647} 26648function justifyLine(positionedGlyphs, start, end, justify) { 26649 if (justify === 0) return; 26650 const lastPositionedGlyph = positionedGlyphs[end]; 26651 const lastAdvance = lastPositionedGlyph.metrics.advance * lastPositionedGlyph.scale; 26652 const lineIndent = (positionedGlyphs[end].x + lastAdvance) * justify; 26653 for (let j = start; j <= end; j++) positionedGlyphs[j].x -= lineIndent; 26654} 26655/** 26656* Aligns the lines based on horizontal and vertical alignment. 26657*/ 26658function align(positionedLines, justify, horizontalAlign, verticalAlign, maxLineLength, maxLineHeight, lineHeight, blockHeight, lineCount) { 26659 const shiftX = (justify - horizontalAlign) * maxLineLength; 26660 let shiftY = 0; 26661 if (maxLineHeight !== lineHeight) shiftY = -blockHeight * verticalAlign - -17; 26662 else shiftY = -verticalAlign * lineCount * lineHeight + .5 * lineHeight; 26663 for (const line of positionedLines) for (const positionedGlyph of line.positionedGlyphs) { 26664 positionedGlyph.x += shiftX; 26665 positionedGlyph.y += shiftY; 26666 } 26667} 26668function shapeIcon(image, iconOffset, iconAnchor) { 26669 const { horizontalAlign, verticalAlign } = getAnchorAlignment(iconAnchor); 26670 const dx = iconOffset[0]; 26671 const dy = iconOffset[1]; 26672 const x1 = dx - image.displaySize[0] * horizontalAlign; 26673 const x2 = x1 + image.displaySize[0]; 26674 const y1 = dy - image.displaySize[1] * verticalAlign; 26675 return { 26676 image, 26677 top: y1, 26678 bottom: y1 + image.displaySize[1], 26679 left: x1, 26680 right: x2 26681 }; 26682} 26683/** 26684* Called after a PositionedIcon has already been run through fitIconToText, 26685* but needs further adjustment to apply textFitWidth and textFitHeight. 26686* @param shapedIcon - The icon that will be adjusted. 26687* @returns Extents of the shapedIcon with text fit adjustments if necessary. 26688*/ 26689function applyTextFit(shapedIcon) { 26690 let iconLeft = shapedIcon.left; 26691 let iconTop = shapedIcon.top; 26692 let iconWidth = shapedIcon.right - iconLeft; 26693 let iconHeight = shapedIcon.bottom - iconTop; 26694 const contentWidth = shapedIcon.image.content[2] - shapedIcon.image.content[0]; 26695 const contentHeight = shapedIcon.image.content[3] - shapedIcon.image.content[1]; 26696 const textFitWidth = shapedIcon.image.textFitWidth ?? "stretchOrShrink"; 26697 const textFitHeight = shapedIcon.image.textFitHeight ?? "stretchOrShrink"; 26698 const contentAspectRatio = contentWidth / contentHeight; 26699 if (textFitHeight === "proportional") { 26700 if (textFitWidth === "stretchOnly" && iconWidth / iconHeight < contentAspectRatio || textFitWidth === "proportional") { 26701 const newIconWidth = Math.ceil(iconHeight * contentAspectRatio); 26702 iconLeft *= newIconWidth / iconWidth; 26703 iconWidth = newIconWidth; 26704 } 26705 } else if (textFitWidth === "proportional") { 26706 if (textFitHeight === "stretchOnly" && contentAspectRatio !== 0 && iconWidth / iconHeight > contentAspectRatio) { 26707 const newIconHeight = Math.ceil(iconWidth / contentAspectRatio); 26708 iconTop *= newIconHeight / iconHeight; 26709 iconHeight = newIconHeight; 26710 } 26711 } 26712 return { 26713 x1: iconLeft, 26714 y1: iconTop, 26715 x2: iconLeft + iconWidth, 26716 y2: iconTop + iconHeight 26717 }; 26718} 26719function fitIconToText(shapedIcon, shapedText, textFit, padding, iconOffset, fontScale) { 26720 const image = shapedIcon.image; 26721 let collisionPadding; 26722 if (image.content) { 26723 const content = image.content; 26724 const pixelRatio = image.pixelRatio || 1; 26725 collisionPadding = [ 26726 content[0] / pixelRatio, 26727 content[1] / pixelRatio, 26728 image.displaySize[0] - content[2] / pixelRatio, 26729 image.displaySize[1] - content[3] / pixelRatio 26730 ]; 26731 } 26732 const textLeft = shapedText.left * fontScale; 26733 const textRight = shapedText.right * fontScale; 26734 let top, right, bottom, left; 26735 if (textFit === "width" || textFit === "both") { 26736 left = iconOffset[0] + textLeft - padding[3]; 26737 right = iconOffset[0] + textRight + padding[1]; 26738 } else { 26739 left = iconOffset[0] + (textLeft + textRight - image.displaySize[0]) / 2; 26740 right = left + image.displaySize[0]; 26741 } 26742 const textTop = shapedText.top * fontScale; 26743 const textBottom = shapedText.bottom * fontScale; 26744 if (textFit === "height" || textFit === "both") { 26745 top = iconOffset[1] + textTop - padding[0]; 26746 bottom = iconOffset[1] + textBottom + padding[2]; 26747 } else { 26748 top = iconOffset[1] + (textTop + textBottom - image.displaySize[1]) / 2; 26749 bottom = top + image.displaySize[1]; 26750 } 26751 return { 26752 image, 26753 top, 26754 right, 26755 bottom, 26756 left, 26757 collisionPadding 26758 }; 26759} 26760const MAX_PACKED_SIZE = 32640; 26761/** 26762* The maximum number of glyphs per symbol bucket. UInt16 `glyphOffsetArrayStart` 26763* is the first index that can overflow at 65,535; see 26764* https://github.com/mapbox/mapbox-gl-js/issues/2907 for the motivation. 26765* Line and text-box starts could in theory overflow too, but there are far 26766* fewer boxes and lines than glyphs. 26767*/ 26768const MAX_GLYPHS = 65535; 26769/** 26770* Gets the bucket-level size data the painter needs to set symbol size uniforms. 26771*/ 26772function getSizeData(tileZoom, value) { 26773 const { expression } = value; 26774 if (expression.kind === "constant") return { 26775 kind: "constant", 26776 layoutSize: expression.evaluate(new EvaluationParameters(tileZoom + 1)) 26777 }; 26778 else if (expression.kind === "source") return { kind: "source" }; 26779 else if (expression.kind === "composite") { 26780 const { minZoom, maxZoom } = getCoveringZoomStops(expression.zoomStops, tileZoom); 26781 return { 26782 kind: "composite", 26783 minZoom, 26784 maxZoom, 26785 interpolationType: expression.interpolationType 26786 }; 26787 } else { 26788 const sizes = evaluateSizesAtZoomStops(expression); 26789 const layoutSize = expression.evaluate(new EvaluationParameters(tileZoom + 1)); 26790 return { 26791 kind: "camera", 26792 zoomStops: expression.zoomStops, 26793 sizes, 26794 layoutSize, 26795 interpolationType: expression.interpolationType 26796 }; 26797 } 26798} 26799/** 26800* Finds the pair of zoom stops covering `[tileZoom, tileZoom + 1]`. A composite size 26801* bakes each feature's size at these two zooms into the vertex data. 26802*/ 26803function getCoveringZoomStops(zoomStops, tileZoom) { 26804 let lower = 0; 26805 while (lower < zoomStops.length && zoomStops[lower] <= tileZoom) lower++; 26806 lower = Math.max(0, lower - 1); 26807 let upper = lower; 26808 while (upper < zoomStops.length && zoomStops[upper] < tileZoom + 1) upper++; 26809 upper = Math.min(zoomStops.length - 1, upper); 26810 return { 26811 minZoom: zoomStops[lower], 26812 maxZoom: zoomStops[upper] 26813 }; 26814} 26815/** 26816* Evaluates a camera size expression at each of its zoom stops. A step's first stop is 26817* `-Infinity`, so its base value is sampled just below the second stop instead. 26818*/ 26819function evaluateSizesAtZoomStops(expression) { 26820 return expression.zoomStops.map((zoomStop) => expression.evaluate(new EvaluationParameters(zoomStop === -Infinity ? expression.zoomStops[1] - 1 : zoomStop))); 26821} 26822function evaluateSizeForFeature(sizeData, { uSize, uSizeT }, { lowerSize, upperSize }) { 26823 if (sizeData.kind === "source") return lowerSize / 128; 26824 else if (sizeData.kind === "composite") return interpolateFactory.number(lowerSize / 128, upperSize / 128, uSizeT); 26825 return uSize; 26826} 26827/** 26828* Computes a bucket's size uniforms at the zoom being drawn, which on a retained tile 26829* differs from the zoom the bucket was built for. 26830*/ 26831function evaluateSizeForZoom(sizeData, zoom) { 26832 let uSizeT = 0; 26833 let uSize = 0; 26834 if (sizeData.kind === "constant") uSize = sizeData.layoutSize; 26835 else if (sizeData.kind === "camera") uSize = evaluateCameraSize(sizeData, zoom); 26836 else if (sizeData.kind === "composite") uSizeT = evaluateCompositeInterpolationFactor(sizeData, zoom); 26837 return { 26838 uSizeT, 26839 uSize 26840 }; 26841} 26842/** 26843* Evaluates a camera size at the drawn zoom, interpolating between the stops around it. 26844* Capped at `layoutSize`, the size the tile's collision boxes were built for: drawing 26845* larger than that would let labels overlap. 26846*/ 26847function evaluateCameraSize({ zoomStops, sizes, layoutSize, interpolationType }, zoom) { 26848 let lower = zoomStops.length - 1; 26849 while (lower > 0 && zoomStops[lower] > zoom) lower--; 26850 const upper = Math.min(lower + 1, zoomStops.length - 1); 26851 const t = !interpolationType ? 0 : clamp$2(Interpolate.interpolationFactor(interpolationType, zoom, zoomStops[lower], zoomStops[upper]), 0, 1); 26852 return Math.min(interpolateFactory.number(sizes[lower], sizes[upper], t), layoutSize); 26853} 26854/** 26855* Computes how far the drawn zoom sits between a composite size's two stops, clamped 26856* into `[0, 1]`: each feature only stores its size at those two stops, so all the 26857* renderer can do is blend between them. 26858*/ 26859function evaluateCompositeInterpolationFactor({ interpolationType, minZoom, maxZoom }, zoom) { 26860 return !interpolationType ? 0 : clamp$2(Interpolate.interpolationFactor(interpolationType, zoom, minZoom, maxZoom), 0, 1); 26861} 26862//#endregion 26863//#region src/symbol/anchor.ts 26864var Anchor = class Anchor extends Point { 26865 constructor(x, y, angle, segment) { 26866 super(x, y); 26867 this.angle = angle; 26868 if (segment !== void 0) this.segment = segment; 26869 } 26870 clone() { 26871 return new Anchor(this.x, this.y, this.angle, this.segment); 26872 } 26873}; 26874register("Anchor", Anchor); 26875//#endregion 26876//#region src/symbol/check_max_angle.ts 26877/** 26878* Labels placed around really sharp angles aren't readable. Check if any 26879* part of the potential label has a combined angle that is too big. 26880* 26881* @param line - The line to check 26882* @param anchor - The point on the line around which the label is anchored. 26883* @param labelLength - The length of the label in geometry units. 26884* @param windowSize - The check fails if the combined angles within a part of the line that is `windowSize` long is too big. 26885* @param maxAngle - The maximum combined angle that any window along the label is allowed to have. 26886* 26887* @returns whether the label should be placed 26888*/ 26889function checkMaxAngle(line, anchor, labelLength, windowSize, maxAngle) { 26890 if (anchor.segment === void 0 || labelLength === 0) return true; 26891 let p = anchor; 26892 let index = anchor.segment + 1; 26893 let anchorDistance = 0; 26894 while (anchorDistance > -labelLength / 2) { 26895 index--; 26896 if (index < 0) return false; 26897 anchorDistance -= line[index].dist(p); 26898 p = line[index]; 26899 } 26900 anchorDistance += line[index].dist(line[index + 1]); 26901 index++; 26902 const recentCorners = []; 26903 let recentAngleDelta = 0; 26904 while (anchorDistance < labelLength / 2) { 26905 const prev = line[index - 1]; 26906 const current = line[index]; 26907 const next = line[index + 1]; 26908 if (!next) return false; 26909 let angleDelta = prev.angleTo(current) - current.angleTo(next); 26910 angleDelta = Math.abs((angleDelta + 3 * Math.PI) % (Math.PI * 2) - Math.PI); 26911 recentCorners.push({ 26912 distance: anchorDistance, 26913 angleDelta 26914 }); 26915 recentAngleDelta += angleDelta; 26916 while (anchorDistance - recentCorners[0].distance > windowSize) recentAngleDelta -= recentCorners.shift().angleDelta; 26917 if (recentAngleDelta > maxAngle) return false; 26918 index++; 26919 anchorDistance += current.dist(next); 26920 } 26921 return true; 26922} 26923//#endregion 26924//#region src/symbol/get_anchors.ts 26925function getLineLength(line) { 26926 let lineLength = 0; 26927 for (let k = 0; k < line.length - 1; k++) lineLength += line[k].dist(line[k + 1]); 26928 return lineLength; 26929} 26930function getAngleWindowSize(shapedText, glyphSize, boxScale) { 26931 return shapedText ? 3 / 5 * glyphSize * boxScale : 0; 26932} 26933function getShapedLabelLength(shapedText, shapedIcon) { 26934 return Math.max(shapedText ? shapedText.right - shapedText.left : 0, shapedIcon ? shapedIcon.right - shapedIcon.left : 0); 26935} 26936function getCenterAnchor(line, maxAngle, shapedText, shapedIcon, glyphSize, boxScale) { 26937 const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale); 26938 const labelLength = getShapedLabelLength(shapedText, shapedIcon) * boxScale; 26939 let prevDistance = 0; 26940 const centerDistance = getLineLength(line) / 2; 26941 for (let i = 0; i < line.length - 1; i++) { 26942 const a = line[i], b = line[i + 1]; 26943 const segmentDistance = a.dist(b); 26944 if (prevDistance + segmentDistance > centerDistance) { 26945 const t = (centerDistance - prevDistance) / segmentDistance; 26946 const anchor = new Anchor(interpolateFactory.number(a.x, b.x, t), interpolateFactory.number(a.y, b.y, t), b.angleTo(a), i); 26947 anchor._round(); 26948 if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) return anchor; 26949 else return; 26950 } 26951 prevDistance += segmentDistance; 26952 } 26953} 26954function getAnchors(line, spacing, maxAngle, shapedText, shapedIcon, glyphSize, boxScale, overscaling, tileExtent) { 26955 const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale); 26956 const shapedLabelLength = getShapedLabelLength(shapedText, shapedIcon); 26957 const labelLength = shapedLabelLength * boxScale; 26958 const isLineContinued = line[0].x === 0 || line[0].x === tileExtent || line[0].y === 0 || line[0].y === tileExtent; 26959 if (spacing - labelLength < spacing / 4) spacing = labelLength + spacing / 4; 26960 const fixedExtraOffset = glyphSize * 2; 26961 return resample(line, !isLineContinued ? (shapedLabelLength / 2 + fixedExtraOffset) * boxScale * overscaling % spacing : spacing / 2 * overscaling % spacing, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, false, tileExtent); 26962} 26963function resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, placeAtMiddle, tileExtent) { 26964 const halfLabelLength = labelLength / 2; 26965 const lineLength = getLineLength(line); 26966 let distance = 0; 26967 let markedDistance = offset - spacing; 26968 let anchors = []; 26969 for (let i = 0; i < line.length - 1; i++) { 26970 const a = line[i], b = line[i + 1]; 26971 const segmentDist = a.dist(b), angle = b.angleTo(a); 26972 while (markedDistance + spacing < distance + segmentDist) { 26973 markedDistance += spacing; 26974 const t = (markedDistance - distance) / segmentDist, x = interpolateFactory.number(a.x, b.x, t), y = interpolateFactory.number(a.y, b.y, t); 26975 if (x >= 0 && x < tileExtent && y >= 0 && y < tileExtent && markedDistance - halfLabelLength >= 0 && markedDistance + halfLabelLength <= lineLength) { 26976 const anchor = new Anchor(x, y, angle, i); 26977 anchor._round(); 26978 if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) anchors.push(anchor); 26979 } 26980 } 26981 distance += segmentDist; 26982 } 26983 if (!placeAtMiddle && !anchors.length && !isLineContinued) anchors = resample(line, distance / 2, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, true, tileExtent); 26984 return anchors; 26985} 26986//#endregion 26987//#region src/symbol/clip_line.ts 26988/** 26989* Returns the part of a multiline that intersects with the provided rectangular box. 26990* 26991* @param lines - the lines to check 26992* @param x1 - the left edge of the box 26993* @param y1 - the top edge of the box 26994* @param x2 - the right edge of the box 26995* @param y2 - the bottom edge of the box 26996* @returns lines 26997*/ 26998function clipLine(lines, x1, y1, x2, y2) { 26999 const clippedLines = []; 27000 for (const line of lines) { 27001 let clippedLine; 27002 for (let i = 0; i < line.length - 1; i++) { 27003 let p0 = line[i]; 27004 let p1 = line[i + 1]; 27005 if (p0.x < x1 && p1.x < x1) continue; 27006 else if (p0.x < x1) p0 = new Point(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round(); 27007 else if (p1.x < x1) p1 = new Point(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round(); 27008 if (p0.y < y1 && p1.y < y1) continue; 27009 else if (p0.y < y1) p0 = new Point(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round(); 27010 else if (p1.y < y1) p1 = new Point(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round(); 27011 if (p0.x >= x2 && p1.x >= x2) continue; 27012 else if (p0.x >= x2) p0 = new Point(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round(); 27013 else if (p1.x >= x2) p1 = new Point(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round(); 27014 if (p0.y >= y2 && p1.y >= y2) continue; 27015 else if (p0.y >= y2) p0 = new Point(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round(); 27016 else if (p1.y >= y2) p1 = new Point(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round(); 27017 if (!clippedLine || !p0.equals(clippedLine[clippedLine.length - 1])) { 27018 clippedLine = [p0]; 27019 clippedLines.push(clippedLine); 27020 } 27021 clippedLine.push(p1); 27022 } 27023 } 27024 return clippedLines; 27025} 27026/** 27027* Clips the geometry to the given bounds. 27028* @param geometry - the geometry to clip 27029* @param type - the geometry type (1=POINT, 2=LINESTRING, 3=POLYGON) 27030* @param x1 - the left edge of the clipping box 27031* @param y1 - the top edge of the clipping box 27032* @param x2 - the right edge of the clipping box 27033* @param y2 - the bottom edge of the clipping box 27034* @returns the clipped geometry 27035*/ 27036function clipGeometry(geometry, type, x1, y1, x2, y2) { 27037 let clippedGeometry = clipGeometryOnAxis(geometry, type, x1, x2, 0); 27038 clippedGeometry = clipGeometryOnAxis(clippedGeometry, type, y1, y2, 1); 27039 return clippedGeometry; 27040} 27041/** 27042* Clip features between two vertical or horizontal axis-parallel lines: 27043* ``` 27044* | | 27045* ___|___ | / 27046* / | \____|____/ 27047* | | 27048*``` 27049* @param geometry - the geometry to clip 27050* @param type - the geometry type (1=POINT, 2=LINESTRING, 3=POLYGON) 27051* @param start - the start line coordinate (x or y) to clip against 27052* @param end - the end line coordinate (x or y) to clip against 27053* @param axis - the axis to clip on (X or Y) 27054* @returns the clipped geometry 27055*/ 27056function clipGeometryOnAxis(geometry, type, start, end, axis) { 27057 switch (type) { 27058 case 1: return clipPoints(geometry, start, end, axis); 27059 case 2: return clipLines(geometry, start, end, axis, false); 27060 case 3: return clipLines(geometry, start, end, axis, true); 27061 } 27062 return []; 27063} 27064function clipPoints(geometry, start, end, axis) { 27065 const newGeometry = []; 27066 for (const ring of geometry) for (const point of ring) { 27067 const a = axis === 0 ? point.x : point.y; 27068 if (a >= start && a <= end) newGeometry.push([point]); 27069 } 27070 return newGeometry; 27071} 27072/** 27073* Clips a line to the given start and end coordinates. 27074* @param line - the line to clip 27075* @param start - the start line coordinate (x or y) to clip against 27076* @param end - the end line coordinate (x or y) to clip against 27077* @param axis - the axis to clip on (X or Y) 27078* @param isPolygon - whether the line is part of a polygon 27079* @returns the clipped line(s) 27080*/ 27081function clipLineInternal(line, start, end, axis, isPolygon) { 27082 const intersectionPoint = axis === 0 ? intersectionPointX : intersectionPointY; 27083 let slice = []; 27084 const newLine = []; 27085 for (let i = 0; i < line.length - 1; i++) { 27086 const p1 = line[i]; 27087 const p2 = line[i + 1]; 27088 const pos1 = axis === 0 ? p1.x : p1.y; 27089 const pos2 = axis === 0 ? p2.x : p2.y; 27090 let exited = false; 27091 if (pos1 < start) { 27092 if (pos2 > start) slice.push(intersectionPoint(p1, p2, start)); 27093 } else if (pos1 > end) { 27094 if (pos2 < end) slice.push(intersectionPoint(p1, p2, end)); 27095 } else slice.push(p1); 27096 if (pos2 < start && pos1 >= start) { 27097 slice.push(intersectionPoint(p1, p2, start)); 27098 exited = true; 27099 } 27100 if (pos2 > end && pos1 <= end) { 27101 slice.push(intersectionPoint(p1, p2, end)); 27102 exited = true; 27103 } 27104 if (!isPolygon && exited) { 27105 newLine.push(slice); 27106 slice = []; 27107 } 27108 } 27109 const last = line.length - 1; 27110 const lastPos = axis === 0 ? line[last].x : line[last].y; 27111 if (lastPos >= start && lastPos <= end) slice.push(line[last]); 27112 if (isPolygon && slice.length > 0 && !slice[0].equals(slice[slice.length - 1])) slice.push(new Point(slice[0].x, slice[0].y)); 27113 if (slice.length > 0) newLine.push(slice); 27114 return newLine; 27115} 27116function clipLines(geometry, start, end, axis, isPolygon) { 27117 const newGeometry = []; 27118 for (const line of geometry) { 27119 const clippedLines = clipLineInternal(line, start, end, axis, isPolygon); 27120 if (clippedLines.length > 0) newGeometry.push(...clippedLines); 27121 } 27122 return newGeometry; 27123} 27124function intersectionPointX(p1, p2, x) { 27125 const t = (x - p1.x) / (p2.x - p1.x); 27126 return new Point(x, p1.y + (p2.y - p1.y) * t); 27127} 27128function intersectionPointY(p1, p2, y) { 27129 const t = (y - p1.y) / (p2.y - p1.y); 27130 return new Point(p1.x + (p2.x - p1.x) * t, y); 27131} 27132//#endregion 27133//#region src/symbol/quads.ts 27134const border = 1; 27135/** 27136* Create the quads used for rendering an icon. 27137*/ 27138function getIconQuads(shapedIcon, iconRotate, isSDFIcon, hasIconTextFit) { 27139 const quads = []; 27140 const image = shapedIcon.image; 27141 const pixelRatio = image.pixelRatio; 27142 const imageWidth = image.paddedRect.w - 2; 27143 const imageHeight = image.paddedRect.h - 2; 27144 let icon = { 27145 x1: shapedIcon.left, 27146 y1: shapedIcon.top, 27147 x2: shapedIcon.right, 27148 y2: shapedIcon.bottom 27149 }; 27150 const stretchX = image.stretchX || [[0, imageWidth]]; 27151 const stretchY = image.stretchY || [[0, imageHeight]]; 27152 const reduceRanges = (sum, range) => sum + range[1] - range[0]; 27153 const stretchWidth = stretchX.reduce(reduceRanges, 0); 27154 const stretchHeight = stretchY.reduce(reduceRanges, 0); 27155 const fixedWidth = imageWidth - stretchWidth; 27156 const fixedHeight = imageHeight - stretchHeight; 27157 let stretchOffsetX = 0; 27158 let stretchContentWidth = stretchWidth; 27159 let stretchOffsetY = 0; 27160 let stretchContentHeight = stretchHeight; 27161 let fixedOffsetX = 0; 27162 let fixedContentWidth = fixedWidth; 27163 let fixedOffsetY = 0; 27164 let fixedContentHeight = fixedHeight; 27165 if (image.content && hasIconTextFit) { 27166 const content = image.content; 27167 const contentWidth = content[2] - content[0]; 27168 const contentHeight = content[3] - content[1]; 27169 if (image.textFitWidth || image.textFitHeight) icon = applyTextFit(shapedIcon); 27170 stretchOffsetX = sumWithinRange(stretchX, 0, content[0]); 27171 stretchOffsetY = sumWithinRange(stretchY, 0, content[1]); 27172 stretchContentWidth = sumWithinRange(stretchX, content[0], content[2]); 27173 stretchContentHeight = sumWithinRange(stretchY, content[1], content[3]); 27174 fixedOffsetX = content[0] - stretchOffsetX; 27175 fixedOffsetY = content[1] - stretchOffsetY; 27176 fixedContentWidth = contentWidth - stretchContentWidth; 27177 fixedContentHeight = contentHeight - stretchContentHeight; 27178 } 27179 const iconLeft = icon.x1; 27180 const iconTop = icon.y1; 27181 const iconWidth = icon.x2 - iconLeft; 27182 const iconHeight = icon.y2 - iconTop; 27183 const makeBox = (left, top, right, bottom) => { 27184 const leftEm = getEmOffset(left.stretch - stretchOffsetX, stretchContentWidth, iconWidth, iconLeft); 27185 const leftPx = getPxOffset(left.fixed - fixedOffsetX, fixedContentWidth, left.stretch, stretchWidth); 27186 const topEm = getEmOffset(top.stretch - stretchOffsetY, stretchContentHeight, iconHeight, iconTop); 27187 const topPx = getPxOffset(top.fixed - fixedOffsetY, fixedContentHeight, top.stretch, stretchHeight); 27188 const rightEm = getEmOffset(right.stretch - stretchOffsetX, stretchContentWidth, iconWidth, iconLeft); 27189 const rightPx = getPxOffset(right.fixed - fixedOffsetX, fixedContentWidth, right.stretch, stretchWidth); 27190 const bottomEm = getEmOffset(bottom.stretch - stretchOffsetY, stretchContentHeight, iconHeight, iconTop); 27191 const bottomPx = getPxOffset(bottom.fixed - fixedOffsetY, fixedContentHeight, bottom.stretch, stretchHeight); 27192 const tl = new Point(leftEm, topEm); 27193 const tr = new Point(rightEm, topEm); 27194 const br = new Point(rightEm, bottomEm); 27195 const bl = new Point(leftEm, bottomEm); 27196 const pixelOffsetTL = new Point(leftPx / pixelRatio, topPx / pixelRatio); 27197 const pixelOffsetBR = new Point(rightPx / pixelRatio, bottomPx / pixelRatio); 27198 const angle = iconRotate * Math.PI / 180; 27199 if (angle) { 27200 const sin = Math.sin(angle), cos = Math.cos(angle), matrix = [ 27201 cos, 27202 -sin, 27203 sin, 27204 cos 27205 ]; 27206 tl._matMult(matrix); 27207 tr._matMult(matrix); 27208 bl._matMult(matrix); 27209 br._matMult(matrix); 27210 } 27211 const x1 = left.stretch + left.fixed; 27212 const x2 = right.stretch + right.fixed; 27213 const y1 = top.stretch + top.fixed; 27214 const y2 = bottom.stretch + bottom.fixed; 27215 return { 27216 tl, 27217 tr, 27218 bl, 27219 br, 27220 tex: { 27221 x: image.paddedRect.x + border + x1, 27222 y: image.paddedRect.y + border + y1, 27223 w: x2 - x1, 27224 h: y2 - y1 27225 }, 27226 writingMode: void 0, 27227 glyphOffset: [0, 0], 27228 sectionIndex: 0, 27229 pixelOffsetTL, 27230 pixelOffsetBR, 27231 minFontScaleX: fixedContentWidth / pixelRatio / iconWidth, 27232 minFontScaleY: fixedContentHeight / pixelRatio / iconHeight, 27233 isSDF: isSDFIcon 27234 }; 27235 }; 27236 if (!hasIconTextFit || !image.stretchX && !image.stretchY) quads.push(makeBox({ 27237 fixed: 0, 27238 stretch: -1 27239 }, { 27240 fixed: 0, 27241 stretch: -1 27242 }, { 27243 fixed: 0, 27244 stretch: imageWidth + 1 27245 }, { 27246 fixed: 0, 27247 stretch: imageHeight + 1 27248 })); 27249 else { 27250 const xCuts = stretchZonesToCuts(stretchX, fixedWidth, stretchWidth); 27251 const yCuts = stretchZonesToCuts(stretchY, fixedHeight, stretchHeight); 27252 for (let xi = 0; xi < xCuts.length - 1; xi++) { 27253 const x1 = xCuts[xi]; 27254 const x2 = xCuts[xi + 1]; 27255 for (let yi = 0; yi < yCuts.length - 1; yi++) { 27256 const y1 = yCuts[yi]; 27257 const y2 = yCuts[yi + 1]; 27258 quads.push(makeBox(x1, y1, x2, y2)); 27259 } 27260 } 27261 } 27262 return quads; 27263} 27264function sumWithinRange(ranges, min, max) { 27265 let sum = 0; 27266 for (const range of ranges) sum += Math.max(min, Math.min(max, range[1])) - Math.max(min, Math.min(max, range[0])); 27267 return sum; 27268} 27269function stretchZonesToCuts(stretchZones, fixedSize, stretchSize) { 27270 const cuts = [{ 27271 fixed: -1, 27272 stretch: 0 27273 }]; 27274 for (const [c1, c2] of stretchZones) { 27275 const last = cuts[cuts.length - 1]; 27276 cuts.push({ 27277 fixed: c1 - last.stretch, 27278 stretch: last.stretch 27279 }); 27280 cuts.push({ 27281 fixed: c1 - last.stretch, 27282 stretch: last.stretch + (c2 - c1) 27283 }); 27284 } 27285 cuts.push({ 27286 fixed: fixedSize + border, 27287 stretch: stretchSize 27288 }); 27289 return cuts; 27290} 27291function getEmOffset(stretchOffset, stretchSize, iconSize, iconOffset) { 27292 return stretchOffset / stretchSize * iconSize + iconOffset; 27293} 27294function getPxOffset(fixedOffset, fixedSize, stretchOffset, stretchSize) { 27295 return fixedOffset - fixedSize * stretchOffset / stretchSize; 27296} 27297/** 27298* Create the quads used for rendering a text label. 27299*/ 27300function getGlyphQuads(anchor, shaping, textOffset, layer, alongLine, feature, imageMap, allowVerticalPlacement) { 27301 const textRotate = layer.layout.get("text-rotate").evaluate(feature, {}) * Math.PI / 180; 27302 const quads = []; 27303 for (const line of shaping.positionedLines) for (const positionedGlyph of line.positionedGlyphs) { 27304 if (!positionedGlyph.rect) continue; 27305 const textureRect = positionedGlyph.rect || {}; 27306 let rectBuffer = 4; 27307 let isSDF = true; 27308 let pixelRatio = 1; 27309 let lineOffset = 0; 27310 const rotateVerticalGlyph = (alongLine || allowVerticalPlacement) && positionedGlyph.vertical; 27311 const halfAdvance = positionedGlyph.metrics.advance * positionedGlyph.scale / 2; 27312 if (allowVerticalPlacement && shaping.verticalizable) { 27313 const scaledGlyphOffset = (positionedGlyph.scale - 1) * 24; 27314 const imageOffset = (24 - positionedGlyph.metrics.width * positionedGlyph.scale) / 2; 27315 lineOffset = line.lineOffset / 2 - (positionedGlyph.imageName ? -imageOffset : scaledGlyphOffset); 27316 } 27317 if (positionedGlyph.imageName) { 27318 const image = imageMap[positionedGlyph.imageName]; 27319 isSDF = image.sdf; 27320 pixelRatio = image.pixelRatio; 27321 rectBuffer = 1 / pixelRatio; 27322 } 27323 const glyphOffset = alongLine ? [positionedGlyph.x + halfAdvance, positionedGlyph.y] : [0, 0]; 27324 let builtInOffset = alongLine ? [0, 0] : [positionedGlyph.x + halfAdvance + textOffset[0], positionedGlyph.y + textOffset[1] - lineOffset]; 27325 let verticalizedLabelOffset = [0, 0]; 27326 if (rotateVerticalGlyph) { 27327 verticalizedLabelOffset = builtInOffset; 27328 builtInOffset = [0, 0]; 27329 } 27330 const textureScale = positionedGlyph.metrics.isDoubleResolution ? 2 : 1; 27331 const x1 = (positionedGlyph.metrics.left - rectBuffer) * positionedGlyph.scale - halfAdvance + builtInOffset[0]; 27332 const y1 = (-positionedGlyph.metrics.top - rectBuffer) * positionedGlyph.scale + builtInOffset[1]; 27333 const x2 = x1 + textureRect.w / textureScale * positionedGlyph.scale / pixelRatio; 27334 const y2 = y1 + textureRect.h / textureScale * positionedGlyph.scale / pixelRatio; 27335 const tl = new Point(x1, y1); 27336 const tr = new Point(x2, y1); 27337 const bl = new Point(x1, y2); 27338 const br = new Point(x2, y2); 27339 if (rotateVerticalGlyph) { 27340 const center = new Point(-halfAdvance, halfAdvance - -17); 27341 const verticalRotation = -Math.PI / 2; 27342 const xHalfWidthOffsetCorrection = 12 - halfAdvance; 27343 const yImageOffsetCorrection = positionedGlyph.imageName ? xHalfWidthOffsetCorrection : 0; 27344 const halfWidthOffsetCorrection = new Point(22 - xHalfWidthOffsetCorrection, -yImageOffsetCorrection); 27345 const verticalOffsetCorrection = new Point(...verticalizedLabelOffset); 27346 tl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); 27347 tr._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); 27348 bl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); 27349 br._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); 27350 } 27351 if (textRotate) { 27352 const sin = Math.sin(textRotate), cos = Math.cos(textRotate), matrix = [ 27353 cos, 27354 -sin, 27355 sin, 27356 cos 27357 ]; 27358 tl._matMult(matrix); 27359 tr._matMult(matrix); 27360 bl._matMult(matrix); 27361 br._matMult(matrix); 27362 } 27363 const pixelOffsetTL = new Point(0, 0); 27364 const pixelOffsetBR = new Point(0, 0); 27365 quads.push({ 27366 tl, 27367 tr, 27368 bl, 27369 br, 27370 tex: textureRect, 27371 writingMode: shaping.writingMode, 27372 glyphOffset, 27373 sectionIndex: positionedGlyph.sectionIndex, 27374 isSDF, 27375 pixelOffsetTL, 27376 pixelOffsetBR, 27377 minFontScaleX: 0, 27378 minFontScaleY: 0 27379 }); 27380 } 27381 return quads; 27382} 27383//#endregion 27384//#region src/symbol/collision_feature.ts 27385/** 27386* A CollisionFeature represents the area of the tile covered by a single label. 27387* It is used with CollisionIndex to check if the label overlaps with any 27388* previous labels. A CollisionFeature is mostly just a set of CollisionBox 27389* objects. 27390*/ 27391var CollisionFeature = class { 27392 /** 27393 * Create a CollisionFeature, adding its collision box data to the given collisionBoxArray in the process. 27394 * For line aligned labels a collision circle diameter is computed instead. 27395 * 27396 * @param anchor - The point along the line around which the label is anchored. 27397 * @param shaped - The text or icon shaping results. 27398 * @param boxScale - A magic number used to convert from glyph metrics units to geometry units. 27399 * @param padding - The amount of padding to add around the label edges. 27400 * @param alignLine - Whether the label is aligned with the line or the viewport. 27401 */ 27402 constructor(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shaped, boxScale, padding, alignLine, rotate) { 27403 this.boxStartIndex = collisionBoxArray.length; 27404 if (alignLine) { 27405 let top = shaped.top; 27406 let bottom = shaped.bottom; 27407 const collisionPadding = shaped.collisionPadding; 27408 if (collisionPadding) { 27409 top -= collisionPadding[1]; 27410 bottom += collisionPadding[3]; 27411 } 27412 let height = bottom - top; 27413 if (height > 0) { 27414 height = Math.max(10, height); 27415 this.circleDiameter = height; 27416 } 27417 } else { 27418 const icon = shaped.image?.content && (shaped.image.textFitWidth || shaped.image.textFitHeight) ? applyTextFit(shaped) : { 27419 x1: shaped.left, 27420 y1: shaped.top, 27421 x2: shaped.right, 27422 y2: shaped.bottom 27423 }; 27424 icon.y1 = icon.y1 * boxScale - padding[0]; 27425 icon.y2 = icon.y2 * boxScale + padding[2]; 27426 icon.x1 = icon.x1 * boxScale - padding[3]; 27427 icon.x2 = icon.x2 * boxScale + padding[1]; 27428 const collisionPadding = shaped.collisionPadding; 27429 if (collisionPadding) { 27430 icon.x1 -= collisionPadding[0] * boxScale; 27431 icon.y1 -= collisionPadding[1] * boxScale; 27432 icon.x2 += collisionPadding[2] * boxScale; 27433 icon.y2 += collisionPadding[3] * boxScale; 27434 } 27435 if (rotate) { 27436 const tl = new Point(icon.x1, icon.y1); 27437 const tr = new Point(icon.x2, icon.y1); 27438 const bl = new Point(icon.x1, icon.y2); 27439 const br = new Point(icon.x2, icon.y2); 27440 const rotateRadians = rotate * Math.PI / 180; 27441 tl._rotate(rotateRadians); 27442 tr._rotate(rotateRadians); 27443 bl._rotate(rotateRadians); 27444 br._rotate(rotateRadians); 27445 icon.x1 = Math.min(tl.x, tr.x, bl.x, br.x); 27446 icon.x2 = Math.max(tl.x, tr.x, bl.x, br.x); 27447 icon.y1 = Math.min(tl.y, tr.y, bl.y, br.y); 27448 icon.y2 = Math.max(tl.y, tr.y, bl.y, br.y); 27449 } 27450 collisionBoxArray.emplaceBack(anchor.x, anchor.y, icon.x1, icon.y1, icon.x2, icon.y2, featureIndex, sourceLayerIndex, bucketIndex); 27451 } 27452 this.boxEndIndex = collisionBoxArray.length; 27453 } 27454}; 27455//#endregion 27456//#region node_modules/tinyqueue/index.js 27457var TinyQueue = class { 27458 constructor(data = [], compare = (a, b) => a < b ? -1 : a > b ? 1 : 0) { 27459 this.data = data; 27460 this.length = this.data.length; 27461 this.compare = compare; 27462 if (this.length > 0) for (let i = (this.length >> 1) - 1; i >= 0; i--) this._down(i); 27463 } 27464 push(item) { 27465 this.data.push(item); 27466 this._up(this.length++); 27467 } 27468 pop() { 27469 if (this.length === 0) return void 0; 27470 const top = this.data[0]; 27471 const bottom = this.data.pop(); 27472 if (--this.length > 0) { 27473 this.data[0] = bottom; 27474 this._down(0); 27475 } 27476 return top; 27477 } 27478 peek() { 27479 return this.data[0]; 27480 } 27481 _up(pos) { 27482 const { data, compare } = this; 27483 const item = data[pos]; 27484 while (pos > 0) { 27485 const parent = pos - 1 >> 1; 27486 const current = data[parent]; 27487 if (compare(item, current) >= 0) break; 27488 data[pos] = current; 27489 pos = parent; 27490 } 27491 data[pos] = item; 27492 } 27493 _down(pos) { 27494 const { data, compare } = this; 27495 const halfLength = this.length >> 1; 27496 const item = data[pos]; 27497 while (pos < halfLength) { 27498 let bestChild = (pos << 1) + 1; 27499 const right = bestChild + 1; 27500 if (right < this.length && compare(data[right], data[bestChild]) < 0) bestChild = right; 27501 if (compare(data[bestChild], item) >= 0) break; 27502 data[pos] = data[bestChild]; 27503 pos = bestChild; 27504 } 27505 data[pos] = item; 27506 } 27507}; 27508//#endregion 27509//#region src/util/find_pole_of_inaccessibility.ts 27510/** 27511* Finds an approximation of a polygon's Pole Of Inaccessibility https://en.wikipedia.org/wiki/Pole_of_inaccessibility 27512* This is a copy of https://github.com/mapbox/polylabel adapted to use Points 27513* 27514* @param polygonRings - first item in array is the outer ring followed optionally by the list of holes, should be an element of the result of util/classify_rings 27515* @param precision - Specified in input coordinate units. If 0 returns after first run, if `> 0` repeatedly narrows the search space until the radius of the area searched for the best pole is less than precision 27516* @returns Pole of Inaccessibility. 27517*/ 27518function findPoleOfInaccessibility(polygonRings, precision = 1) { 27519 const bounds = Bounds.fromPoints(polygonRings[0]); 27520 const cellSize = Math.min(bounds.width(), bounds.height()); 27521 let h = cellSize / 2; 27522 const cellQueue = new TinyQueue([], compareMax); 27523 const { minX, minY, maxX, maxY } = bounds; 27524 if (cellSize === 0) return new Point(minX, minY); 27525 for (let x = minX; x < maxX; x += cellSize) for (let y = minY; y < maxY; y += cellSize) cellQueue.push(new Cell(x + h, y + h, h, polygonRings)); 27526 const centroidCell = getCentroidCell(polygonRings); 27527 let bestCell = centroidCell; 27528 while (cellQueue.length) { 27529 const cell = cellQueue.pop(); 27530 if (cell.d > bestCell.d || !bestCell.d) bestCell = cell; 27531 if (cell.max - bestCell.d <= precision) continue; 27532 h = cell.h / 2; 27533 cellQueue.push(new Cell(cell.p.x - h, cell.p.y - h, h, polygonRings)); 27534 cellQueue.push(new Cell(cell.p.x + h, cell.p.y - h, h, polygonRings)); 27535 cellQueue.push(new Cell(cell.p.x - h, cell.p.y + h, h, polygonRings)); 27536 cellQueue.push(new Cell(cell.p.x + h, cell.p.y + h, h, polygonRings)); 27537 } 27538 if (centroidCell.d > 0 && bestCell.d - centroidCell.d <= precision) return centroidCell.p; 27539 return bestCell.p; 27540} 27541function compareMax(a, b) { 27542 return b.max - a.max; 27543} 27544var Cell = class { 27545 constructor(x, y, h, polygon) { 27546 this.p = new Point(x, y); 27547 this.h = h; 27548 this.d = pointToPolygonDist(this.p, polygon); 27549 this.max = this.d + this.h * Math.SQRT2; 27550 } 27551}; 27552function pointToPolygonDist(p, polygon) { 27553 let inside = false; 27554 let minDistSq = Infinity; 27555 for (const ring of polygon) for (let i = 0, len = ring.length, j = len - 1; i < len; j = i++) { 27556 const a = ring[i]; 27557 const b = ring[j]; 27558 if (a.y > p.y !== b.y > p.y && p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x) inside = !inside; 27559 minDistSq = Math.min(minDistSq, distToSegmentSquared(p, a, b)); 27560 } 27561 return (inside ? 1 : -1) * Math.sqrt(minDistSq); 27562} 27563function getCentroidCell(polygon) { 27564 let area = 0; 27565 let x = 0; 27566 let y = 0; 27567 const points = polygon[0]; 27568 for (let i = 0, len = points.length, j = len - 1; i < len; j = i++) { 27569 const a = points[i]; 27570 const b = points[j]; 27571 const f = a.x * b.y - b.x * a.y; 27572 x += (a.x + b.x) * f; 27573 y += (a.y + b.y) * f; 27574 area += f * 3; 27575 } 27576 return new Cell(x / area, y / area, 0, polygon); 27577} 27578//#endregion 27579//#region src/style/style_layer/variable_text_anchor.ts 27580let TextAnchorEnum = /* @__PURE__ */ function(TextAnchorEnum) { 27581 TextAnchorEnum[TextAnchorEnum["center"] = 1] = "center"; 27582 TextAnchorEnum[TextAnchorEnum["left"] = 2] = "left"; 27583 TextAnchorEnum[TextAnchorEnum["right"] = 3] = "right"; 27584 TextAnchorEnum[TextAnchorEnum["top"] = 4] = "top"; 27585 TextAnchorEnum[TextAnchorEnum["bottom"] = 5] = "bottom"; 27586 TextAnchorEnum[TextAnchorEnum["top-left"] = 6] = "top-left"; 27587 TextAnchorEnum[TextAnchorEnum["top-right"] = 7] = "top-right"; 27588 TextAnchorEnum[TextAnchorEnum["bottom-left"] = 8] = "bottom-left"; 27589 TextAnchorEnum[TextAnchorEnum["bottom-right"] = 9] = "bottom-right"; 27590 return TextAnchorEnum; 27591}({}); 27592const baselineOffset = 7; 27593const INVALID_TEXT_OFFSET = Number.POSITIVE_INFINITY; 27594function evaluateVariableOffset(anchor, offset) { 27595 function fromRadialOffset(anchor, radialOffset) { 27596 let x = 0, y = 0; 27597 if (radialOffset < 0) radialOffset = 0; 27598 const hypotenuse = radialOffset / Math.SQRT2; 27599 switch (anchor) { 27600 case "top-right": 27601 case "top-left": 27602 y = hypotenuse - baselineOffset; 27603 break; 27604 case "bottom-right": 27605 case "bottom-left": 27606 y = -hypotenuse + baselineOffset; 27607 break; 27608 case "bottom": 27609 y = -radialOffset + baselineOffset; 27610 break; 27611 case "top": y = radialOffset - baselineOffset; 27612 } 27613 switch (anchor) { 27614 case "top-right": 27615 case "bottom-right": 27616 x = -hypotenuse; 27617 break; 27618 case "top-left": 27619 case "bottom-left": 27620 x = hypotenuse; 27621 break; 27622 case "left": 27623 x = radialOffset; 27624 break; 27625 case "right": x = -radialOffset; 27626 } 27627 return [x, y]; 27628 } 27629 function fromTextOffset(anchor, offsetX, offsetY) { 27630 let x = 0, y = 0; 27631 offsetX = Math.abs(offsetX); 27632 offsetY = Math.abs(offsetY); 27633 switch (anchor) { 27634 case "top-right": 27635 case "top-left": 27636 case "top": 27637 y = offsetY - baselineOffset; 27638 break; 27639 case "bottom-right": 27640 case "bottom-left": 27641 case "bottom": y = -offsetY + baselineOffset; 27642 } 27643 switch (anchor) { 27644 case "top-right": 27645 case "bottom-right": 27646 case "right": 27647 x = -offsetX; 27648 break; 27649 case "top-left": 27650 case "bottom-left": 27651 case "left": x = offsetX; 27652 } 27653 return [x, y]; 27654 } 27655 return offset[1] !== INVALID_TEXT_OFFSET ? fromTextOffset(anchor, offset[0], offset[1]) : fromRadialOffset(anchor, offset[0]); 27656} 27657function getTextVariableAnchorOffset(layer, feature, canonical) { 27658 const layout = layer.layout; 27659 const variableAnchorOffset = layout.get("text-variable-anchor-offset")?.evaluate(feature, {}, canonical); 27660 if (variableAnchorOffset) { 27661 const sourceValues = variableAnchorOffset.values; 27662 const destValues = []; 27663 for (let i = 0; i < sourceValues.length; i += 2) { 27664 const anchor = destValues[i] = sourceValues[i]; 27665 const offset = sourceValues[i + 1].map((t) => t * 24); 27666 if (anchor.startsWith("top")) offset[1] -= baselineOffset; 27667 else if (anchor.startsWith("bottom")) offset[1] += baselineOffset; 27668 destValues[i + 1] = offset; 27669 } 27670 return new VariableAnchorOffsetCollection(destValues); 27671 } 27672 const variableAnchor = layout.get("text-variable-anchor"); 27673 if (variableAnchor) { 27674 let textOffset; 27675 if (layer._unevaluatedLayout.getValue("text-radial-offset") !== void 0) textOffset = [layout.get("text-radial-offset").evaluate(feature, {}, canonical) * 24, INVALID_TEXT_OFFSET]; 27676 else textOffset = layout.get("text-offset").evaluate(feature, {}, canonical).map((t) => t * 24); 27677 const anchorOffsets = []; 27678 for (const anchor of variableAnchor) anchorOffsets.push(anchor, evaluateVariableOffset(anchor, textOffset)); 27679 return new VariableAnchorOffsetCollection(anchorOffsets); 27680 } 27681 return null; 27682} 27683//#endregion 27684//#region src/symbol/symbol_layout.ts 27685function performSymbolLayout(args) { 27686 args.bucket.createArrays(); 27687 const tileSize = 512 * args.bucket.overscaling; 27688 args.bucket.tilePixelRatio = EXTENT$1 / tileSize; 27689 args.bucket.compareText = {}; 27690 args.bucket.iconsNeedLinear = false; 27691 const layer = args.bucket.layers[0]; 27692 const layout = layer.layout; 27693 const unevaluatedLayoutValues = layer._unevaluatedLayout._values; 27694 const sizes = { 27695 layoutIconSize: unevaluatedLayoutValues["icon-size"].possiblyEvaluate(new EvaluationParameters(args.bucket.zoom + 1), args.canonical), 27696 layoutTextSize: unevaluatedLayoutValues["text-size"].possiblyEvaluate(new EvaluationParameters(args.bucket.zoom + 1), args.canonical), 27697 textMaxSize: unevaluatedLayoutValues["text-size"].possiblyEvaluate(new EvaluationParameters(18)) 27698 }; 27699 if (args.bucket.textSizeData.kind === "composite") { 27700 const { minZoom, maxZoom } = args.bucket.textSizeData; 27701 sizes.compositeTextSizes = [unevaluatedLayoutValues["text-size"].possiblyEvaluate(new EvaluationParameters(minZoom), args.canonical), unevaluatedLayoutValues["text-size"].possiblyEvaluate(new EvaluationParameters(maxZoom), args.canonical)]; 27702 } 27703 if (args.bucket.iconSizeData.kind === "composite") { 27704 const { minZoom, maxZoom } = args.bucket.iconSizeData; 27705 sizes.compositeIconSizes = [unevaluatedLayoutValues["icon-size"].possiblyEvaluate(new EvaluationParameters(minZoom), args.canonical), unevaluatedLayoutValues["icon-size"].possiblyEvaluate(new EvaluationParameters(maxZoom), args.canonical)]; 27706 } 27707 const lineHeight = layout.get("text-line-height") * 24; 27708 const textAlongLine = layout.get("text-rotation-alignment") !== "viewport" && layout.get("symbol-placement") !== "point"; 27709 const keepUpright = layout.get("text-keep-upright"); 27710 const textSize = layout.get("text-size"); 27711 for (const feature of args.bucket.features) { 27712 const fontstack = layout.get("text-font").evaluate(feature, {}, args.canonical).join(","); 27713 const layoutTextSizeThisZoom = textSize.evaluate(feature, {}, args.canonical); 27714 const layoutTextSize = sizes.layoutTextSize.evaluate(feature, {}, args.canonical); 27715 const layoutIconSize = sizes.layoutIconSize.evaluate(feature, {}, args.canonical); 27716 const shapedTextOrientations = { 27717 horizontal: {}, 27718 vertical: void 0 27719 }; 27720 const text = feature.text; 27721 let textOffset = [0, 0]; 27722 if (text) { 27723 const unformattedText = text.toString(); 27724 const spacing = layout.get("text-letter-spacing").evaluate(feature, {}, args.canonical) * 24; 27725 const spacingIfAllowed = allowsLetterSpacing(unformattedText) ? spacing : 0; 27726 const textAnchor = layout.get("text-anchor").evaluate(feature, {}, args.canonical); 27727 const variableAnchorOffset = getTextVariableAnchorOffset(layer, feature, args.canonical); 27728 if (!variableAnchorOffset) { 27729 const radialOffset = layout.get("text-radial-offset").evaluate(feature, {}, args.canonical); 27730 if (radialOffset) textOffset = evaluateVariableOffset(textAnchor, [radialOffset * 24, INVALID_TEXT_OFFSET]); 27731 else textOffset = layout.get("text-offset").evaluate(feature, {}, args.canonical).map((t) => t * 24); 27732 } 27733 let textJustify = textAlongLine ? "center" : layout.get("text-justify").evaluate(feature, {}, args.canonical); 27734 const maxWidth = layout.get("symbol-placement") === "point" ? layout.get("text-max-width").evaluate(feature, {}, args.canonical) * 24 : Infinity; 27735 const addVerticalShapingForPointLabelIfNeeded = () => { 27736 if (args.bucket.allowVerticalPlacement && allowsVerticalWritingMode(unformattedText)) shapedTextOrientations.vertical = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, textAnchor, "left", spacingIfAllowed, textOffset, 2, true, layoutTextSize, layoutTextSizeThisZoom); 27737 }; 27738 if (!textAlongLine && variableAnchorOffset) { 27739 const justifications = /* @__PURE__ */ new Set(); 27740 if (textJustify === "auto") for (let i = 0; i < variableAnchorOffset.values.length; i += 2) justifications.add(getAnchorJustification(variableAnchorOffset.values[i])); 27741 else justifications.add(textJustify); 27742 let singleLine = false; 27743 for (const justification of justifications) { 27744 if (shapedTextOrientations.horizontal[justification]) continue; 27745 if (singleLine) shapedTextOrientations.horizontal[justification] = shapedTextOrientations.horizontal[0]; 27746 else { 27747 const shaping = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, "center", justification, spacingIfAllowed, textOffset, 1, false, layoutTextSize, layoutTextSizeThisZoom); 27748 if (shaping) { 27749 shapedTextOrientations.horizontal[justification] = shaping; 27750 singleLine = shaping.positionedLines.length === 1; 27751 } 27752 } 27753 } 27754 addVerticalShapingForPointLabelIfNeeded(); 27755 } else { 27756 if (textJustify === "auto") textJustify = getAnchorJustification(textAnchor); 27757 const shaping = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify, spacingIfAllowed, textOffset, 1, false, layoutTextSize, layoutTextSizeThisZoom); 27758 if (shaping) shapedTextOrientations.horizontal[textJustify] = shaping; 27759 addVerticalShapingForPointLabelIfNeeded(); 27760 if (allowsVerticalWritingMode(unformattedText) && textAlongLine && keepUpright) shapedTextOrientations.vertical = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify, spacingIfAllowed, textOffset, 2, false, layoutTextSize, layoutTextSizeThisZoom); 27761 } 27762 } 27763 let shapedIcon; 27764 let isSDFIcon = false; 27765 if (feature.icon?.name) { 27766 const image = args.imageMap[feature.icon.name]; 27767 if (image) { 27768 shapedIcon = shapeIcon(args.imagePositions[feature.icon.name], layout.get("icon-offset").evaluate(feature, {}, args.canonical), layout.get("icon-anchor").evaluate(feature, {}, args.canonical)); 27769 isSDFIcon = !!image.sdf; 27770 if (args.bucket.sdfIcons === void 0) args.bucket.sdfIcons = isSDFIcon; 27771 else if (args.bucket.sdfIcons !== isSDFIcon) warnOnce("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"); 27772 if (image.pixelRatio !== args.bucket.pixelRatio) args.bucket.iconsNeedLinear = true; 27773 else if (layout.get("icon-rotate").constantOr(1) !== 0) args.bucket.iconsNeedLinear = true; 27774 } 27775 } 27776 const shapedText = getDefaultHorizontalShaping(shapedTextOrientations.horizontal) || shapedTextOrientations.vertical; 27777 args.bucket.iconsInText ||= shapedText ? shapedText.iconsInText : false; 27778 if (shapedText || shapedIcon) addFeature(args.bucket, feature, shapedTextOrientations, shapedIcon, args.imageMap, sizes, layoutTextSize, layoutIconSize, textOffset, isSDFIcon, args.canonical, args.subdivisionGranularity, args.hasPromoteId); 27779 } 27780 if (args.showCollisionBoxes) args.bucket.generateCollisionDebugBuffers(); 27781} 27782function getAnchorJustification(anchor) { 27783 switch (anchor) { 27784 case "right": 27785 case "top-right": 27786 case "bottom-right": return "right"; 27787 case "left": 27788 case "top-left": 27789 case "bottom-left": return "left"; 27790 } 27791 return "center"; 27792} 27793/** 27794* Given a feature and its shaped text and icon data, add a 'symbol 27795* instance' for each _possible_ placement of the symbol feature. 27796* (At render it selects which of these instances to 27797* show or hide based on collisions with symbols in other layers.) 27798*/ 27799function addFeature(bucket, feature, shapedTextOrientations, shapedIcon, imageMap, sizes, layoutTextSize, layoutIconSize, textOffset, isSDFIcon, canonical, subdivisionGranularity, hasPromoteId) { 27800 let textMaxSize = sizes.textMaxSize.evaluate(feature, {}); 27801 if (textMaxSize === void 0) textMaxSize = layoutTextSize; 27802 const layout = bucket.layers[0].layout; 27803 const iconOffset = layout.get("icon-offset").evaluate(feature, {}, canonical); 27804 const defaultHorizontalShaping = getDefaultHorizontalShaping(shapedTextOrientations.horizontal); 27805 const glyphSize = 24, fontScale = layoutTextSize / glyphSize, textBoxScale = bucket.tilePixelRatio * fontScale, textMaxBoxScale = bucket.tilePixelRatio * textMaxSize / glyphSize, iconBoxScale = bucket.tilePixelRatio * layoutIconSize, symbolMinDistance = bucket.tilePixelRatio * layout.get("symbol-spacing"), textPadding = layout.get("text-padding") * bucket.tilePixelRatio, iconPadding = getIconPadding(layout, feature, canonical, bucket.tilePixelRatio), textMaxAngle = layout.get("text-max-angle") / 180 * Math.PI, textAlongLine = layout.get("text-rotation-alignment") !== "viewport" && layout.get("symbol-placement") !== "point", iconAlongLine = layout.get("icon-rotation-alignment").constantOr("viewport") === "map" && layout.get("symbol-placement") !== "point", symbolPlacement = layout.get("symbol-placement"), textRepeatDistance = symbolMinDistance / 2; 27806 const iconTextFit = layout.get("icon-text-fit"); 27807 let verticallyShapedIcon; 27808 if (shapedIcon && iconTextFit !== "none") { 27809 if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) verticallyShapedIcon = fitIconToText(shapedIcon, shapedTextOrientations.vertical, iconTextFit, layout.get("icon-text-fit-padding"), iconOffset, fontScale); 27810 if (defaultHorizontalShaping) shapedIcon = fitIconToText(shapedIcon, defaultHorizontalShaping, iconTextFit, layout.get("icon-text-fit-padding"), iconOffset, fontScale); 27811 } 27812 const granularity = canonical ? subdivisionGranularity.line.getGranularityForZoomLevel(canonical.z) : 1; 27813 const addSymbolAtAnchor = (line, anchor) => { 27814 if (anchor.x < 0 || anchor.x >= 8192 || anchor.y < 0 || anchor.y >= 8192) return; 27815 addSymbol(bucket, anchor, line, shapedTextOrientations, shapedIcon, imageMap, verticallyShapedIcon, bucket.layers[0], bucket.collisionBoxArray, feature.index, feature.sourceLayerIndex, bucket.index, textBoxScale, [ 27816 textPadding, 27817 textPadding, 27818 textPadding, 27819 textPadding 27820 ], textAlongLine, textOffset, iconBoxScale, iconPadding, iconAlongLine, iconOffset, feature, sizes, isSDFIcon, canonical, layoutTextSize, hasPromoteId); 27821 }; 27822 if (symbolPlacement === "line") for (const line of clipLine(feature.geometry, 0, 0, EXTENT$1, EXTENT$1)) { 27823 const subdividedLine = subdivideVertexLine(line, granularity); 27824 const anchors = getAnchors(subdividedLine, symbolMinDistance, textMaxAngle, shapedTextOrientations.vertical || defaultHorizontalShaping, shapedIcon, glyphSize, textMaxBoxScale, bucket.overscaling, EXTENT$1); 27825 for (const anchor of anchors) { 27826 const shapedText = defaultHorizontalShaping; 27827 if (!shapedText || !anchorIsTooClose(bucket, shapedText.text, textRepeatDistance, anchor)) addSymbolAtAnchor(subdividedLine, anchor); 27828 } 27829 } 27830 else if (symbolPlacement === "line-center") { 27831 for (const line of feature.geometry) if (line.length > 1) { 27832 const subdividedLine = subdivideVertexLine(line, granularity); 27833 const anchor = getCenterAnchor(subdividedLine, textMaxAngle, shapedTextOrientations.vertical || defaultHorizontalShaping, shapedIcon, glyphSize, textMaxBoxScale); 27834 if (anchor) addSymbolAtAnchor(subdividedLine, anchor); 27835 } 27836 } else if (feature.type === "Polygon") for (const polygon of classifyRings$1(feature.geometry, 0)) { 27837 const poi = findPoleOfInaccessibility(polygon, 16); 27838 addSymbolAtAnchor(subdivideVertexLine(polygon[0], granularity, true), new Anchor(poi.x, poi.y, 0)); 27839 } 27840 else if (feature.type === "LineString") for (const line of feature.geometry) { 27841 const subdividedLine = subdivideVertexLine(line, granularity); 27842 addSymbolAtAnchor(subdividedLine, new Anchor(subdividedLine[0].x, subdividedLine[0].y, 0)); 27843 } 27844 else if (feature.type === "Point") for (const points of feature.geometry) for (const point of points) addSymbolAtAnchor([point], new Anchor(point.x, point.y, 0)); 27845} 27846function addTextVariableAnchorOffsets(textAnchorOffsets, variableAnchorOffset) { 27847 const startIndex = textAnchorOffsets.length; 27848 const values = variableAnchorOffset?.values; 27849 if (values?.length > 0) for (let i = 0; i < values.length; i += 2) { 27850 const anchor = TextAnchorEnum[values[i]]; 27851 const offset = values[i + 1]; 27852 textAnchorOffsets.emplaceBack(anchor, offset[0], offset[1]); 27853 } 27854 return [startIndex, textAnchorOffsets.length]; 27855} 27856function addTextVertices(bucket, anchor, shapedText, imageMap, layer, textAlongLine, feature, textOffset, elevation, lineArray, writingMode, placementTypes, placedTextSymbolIndices, placedIconIndex, sizes, canonical) { 27857 const glyphQuads = getGlyphQuads(anchor, shapedText, textOffset, layer, textAlongLine, feature, imageMap, bucket.allowVerticalPlacement); 27858 const sizeData = bucket.textSizeData; 27859 let textSizeData = null; 27860 if (sizeData.kind === "source") { 27861 textSizeData = [128 * layer.layout.get("text-size").evaluate(feature, {})]; 27862 if (textSizeData[0] > 32640) warnOnce(`${bucket.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`); 27863 } else if (sizeData.kind === "composite") { 27864 textSizeData = [128 * sizes.compositeTextSizes[0].evaluate(feature, {}, canonical), 128 * sizes.compositeTextSizes[1].evaluate(feature, {}, canonical)]; 27865 if (textSizeData[0] > 32640 || textSizeData[1] > 32640) warnOnce(`${bucket.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`); 27866 } 27867 bucket.addSymbols(bucket.text, glyphQuads, textSizeData, textOffset, textAlongLine, feature, writingMode, anchor, lineArray.lineStartIndex, lineArray.lineLength, placedIconIndex, canonical, elevation); 27868 for (const placementType of placementTypes) placedTextSymbolIndices[placementType] = bucket.text.placedSymbolArray.length - 1; 27869 return glyphQuads.length * 4; 27870} 27871function getDefaultHorizontalShaping(horizontalShaping) { 27872 for (const justification in horizontalShaping) return horizontalShaping[justification]; 27873 return null; 27874} 27875/** 27876* Add a single label & icon placement. 27877*/ 27878function addSymbol(bucket, anchor, line, shapedTextOrientations, shapedIcon, imageMap, verticallyShapedIcon, layer, collisionBoxArray, featureIndex, sourceLayerIndex, bucketIndex, textBoxScale, textPadding, textAlongLine, textOffset, iconBoxScale, iconPadding, iconAlongLine, iconOffset, feature, sizes, isSDFIcon, canonical, layoutTextSize, hasPromoteId) { 27879 const lineArray = bucket.addToLineVertexArray(anchor, line); 27880 const elevation = layer.layout.get("symbol-height-offset").evaluate(feature, {}, canonical); 27881 if (elevation > bucket.maxHeightOffset) bucket.maxHeightOffset = elevation; 27882 let textCollisionFeature, iconCollisionFeature, verticalTextCollisionFeature, verticalIconCollisionFeature; 27883 let numIconVertices = 0; 27884 let numVerticalIconVertices = 0; 27885 let numHorizontalGlyphVertices = 0; 27886 let numVerticalGlyphVertices = 0; 27887 let placedIconSymbolIndex = -1; 27888 let verticalPlacedIconSymbolIndex = -1; 27889 const placedTextSymbolIndices = {}; 27890 let key = (0, import_murmurhash_js.default)(""); 27891 if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) { 27892 const verticalTextRotation = layer.layout.get("text-rotate").evaluate(feature, {}, canonical) + 90; 27893 const verticalShaping = shapedTextOrientations.vertical; 27894 verticalTextCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticalShaping, textBoxScale, textPadding, textAlongLine, verticalTextRotation); 27895 if (verticallyShapedIcon) verticalIconCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticallyShapedIcon, iconBoxScale, iconPadding, textAlongLine, verticalTextRotation); 27896 } 27897 if (shapedIcon) { 27898 const iconRotate = layer.layout.get("icon-rotate").evaluate(feature, {}); 27899 const hasIconTextFit = layer.layout.get("icon-text-fit") !== "none"; 27900 const iconQuads = getIconQuads(shapedIcon, iconRotate, isSDFIcon, hasIconTextFit); 27901 const verticalIconQuads = verticallyShapedIcon ? getIconQuads(verticallyShapedIcon, iconRotate, isSDFIcon, hasIconTextFit) : void 0; 27902 iconCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shapedIcon, iconBoxScale, iconPadding, false, iconRotate); 27903 numIconVertices = iconQuads.length * 4; 27904 const sizeData = bucket.iconSizeData; 27905 let iconSizeData = null; 27906 if (sizeData.kind === "source") { 27907 iconSizeData = [128 * layer.layout.get("icon-size").evaluate(feature, {})]; 27908 if (iconSizeData[0] > 32640) warnOnce(`${bucket.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`); 27909 } else if (sizeData.kind === "composite") { 27910 iconSizeData = [128 * sizes.compositeIconSizes[0].evaluate(feature, {}, canonical), 128 * sizes.compositeIconSizes[1].evaluate(feature, {}, canonical)]; 27911 if (iconSizeData[0] > 32640 || iconSizeData[1] > 32640) warnOnce(`${bucket.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`); 27912 } 27913 bucket.addSymbols(bucket.icon, iconQuads, iconSizeData, iconOffset, iconAlongLine, feature, 0, anchor, lineArray.lineStartIndex, lineArray.lineLength, -1, canonical, elevation); 27914 placedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1; 27915 if (verticalIconQuads) { 27916 numVerticalIconVertices = verticalIconQuads.length * 4; 27917 bucket.addSymbols(bucket.icon, verticalIconQuads, iconSizeData, iconOffset, iconAlongLine, feature, 2, anchor, lineArray.lineStartIndex, lineArray.lineLength, -1, canonical, elevation); 27918 verticalPlacedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1; 27919 } 27920 } 27921 const justifications = Object.keys(shapedTextOrientations.horizontal); 27922 for (const justification of justifications) { 27923 const shaping = shapedTextOrientations.horizontal[justification]; 27924 if (!textCollisionFeature) { 27925 key = (0, import_murmurhash_js.default)(shaping.text); 27926 textCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shaping, textBoxScale, textPadding, textAlongLine, layer.layout.get("text-rotate").evaluate(feature, {}, canonical)); 27927 } 27928 const singleLine = shaping.positionedLines.length === 1; 27929 numHorizontalGlyphVertices += addTextVertices(bucket, anchor, shaping, imageMap, layer, textAlongLine, feature, textOffset, elevation, lineArray, shapedTextOrientations.vertical ? 1 : 3, singleLine ? justifications : [justification], placedTextSymbolIndices, placedIconSymbolIndex, sizes, canonical); 27930 if (singleLine) break; 27931 } 27932 if (shapedTextOrientations.vertical) numVerticalGlyphVertices += addTextVertices(bucket, anchor, shapedTextOrientations.vertical, imageMap, layer, textAlongLine, feature, textOffset, elevation, lineArray, 2, ["vertical"], placedTextSymbolIndices, verticalPlacedIconSymbolIndex, sizes, canonical); 27933 const textBoxStartIndex = textCollisionFeature ? textCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; 27934 const textBoxEndIndex = textCollisionFeature ? textCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; 27935 const verticalTextBoxStartIndex = verticalTextCollisionFeature ? verticalTextCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; 27936 const verticalTextBoxEndIndex = verticalTextCollisionFeature ? verticalTextCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; 27937 const iconBoxStartIndex = iconCollisionFeature ? iconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; 27938 const iconBoxEndIndex = iconCollisionFeature ? iconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; 27939 const verticalIconBoxStartIndex = verticalIconCollisionFeature ? verticalIconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; 27940 const verticalIconBoxEndIndex = verticalIconCollisionFeature ? verticalIconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; 27941 let collisionCircleDiameter = -1; 27942 const getCollisionCircleHeight = (feature, prevHeight) => { 27943 if (feature?.circleDiameter) return Math.max(feature.circleDiameter, prevHeight); 27944 return prevHeight; 27945 }; 27946 collisionCircleDiameter = getCollisionCircleHeight(textCollisionFeature, collisionCircleDiameter); 27947 collisionCircleDiameter = getCollisionCircleHeight(verticalTextCollisionFeature, collisionCircleDiameter); 27948 collisionCircleDiameter = getCollisionCircleHeight(iconCollisionFeature, collisionCircleDiameter); 27949 collisionCircleDiameter = getCollisionCircleHeight(verticalIconCollisionFeature, collisionCircleDiameter); 27950 const useRuntimeCollisionCircles = collisionCircleDiameter > -1 ? 1 : 0; 27951 if (useRuntimeCollisionCircles) collisionCircleDiameter *= layoutTextSize / 24; 27952 if (bucket.glyphOffsetArray.length >= bucket.maxGlyphs) warnOnce("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"); 27953 if (feature.sortKey !== void 0) bucket.addToSortKeyRanges(bucket.symbolInstances.length, feature.sortKey); 27954 const variableAnchorOffset = getTextVariableAnchorOffset(layer, feature, canonical); 27955 const [textAnchorOffsetStartIndex, textAnchorOffsetEndIndex] = addTextVariableAnchorOffsets(bucket.textAnchorOffsets, variableAnchorOffset); 27956 if (hasPromoteId) key = keyWithFeatureId(key, feature); 27957 bucket.symbolInstances.emplaceBack(anchor.x, anchor.y, placedTextSymbolIndices.right >= 0 ? placedTextSymbolIndices.right : -1, placedTextSymbolIndices.center >= 0 ? placedTextSymbolIndices.center : -1, placedTextSymbolIndices.left >= 0 ? placedTextSymbolIndices.left : -1, placedTextSymbolIndices.vertical || -1, placedIconSymbolIndex, verticalPlacedIconSymbolIndex, key, textBoxStartIndex, textBoxEndIndex, verticalTextBoxStartIndex, verticalTextBoxEndIndex, iconBoxStartIndex, iconBoxEndIndex, verticalIconBoxStartIndex, verticalIconBoxEndIndex, featureIndex, numHorizontalGlyphVertices, numVerticalGlyphVertices, numIconVertices, numVerticalIconVertices, useRuntimeCollisionCircles, 0, textBoxScale, collisionCircleDiameter, textAnchorOffsetStartIndex, textAnchorOffsetEndIndex, elevation); 27958} 27959function anchorIsTooClose(bucket, text, repeatDistance, anchor) { 27960 const compareText = bucket.compareText; 27961 if (!(text in compareText)) compareText[text] = []; 27962 else { 27963 const otherAnchors = compareText[text]; 27964 for (let k = otherAnchors.length - 1; k >= 0; k--) if (anchor.dist(otherAnchors[k]) < repeatDistance) return true; 27965 } 27966 compareText[text].push(anchor); 27967 return false; 27968} 27969/** 27970* Hashes a promoted feature id into a symbol's cross-tile key, so that labels of different features never compete for 27971* a match in the `CrossTileSymbolIndex` even when their text and anchors coincide. Clusters keep the text-only 27972* key: supercluster gives a cluster an id that encodes the zoom it formed at, so the same cluster has a different id in 27973* every zoom level's tile. 27974*/ 27975function keyWithFeatureId(key, feature) { 27976 if (feature.id == null || feature.properties?.cluster) return key; 27977 return (0, import_murmurhash_js.default)(String(feature.id), key); 27978} 27979//#endregion 27980//#region src/style/style_layer/overlap_mode.ts 27981function getOverlapMode(layout, overlapProp, allowOverlapProp) { 27982 let result = "never"; 27983 const overlap = layout.get(overlapProp); 27984 if (overlap) result = overlap; 27985 else if (layout.get(allowOverlapProp)) result = "always"; 27986 return result; 27987} 27988//#endregion 27989//#region src/data/bucket/symbol_bucket.ts 27990const shaderOpacityAttributes = [{ 27991 name: "a_fade_opacity", 27992 components: 1, 27993 type: "Uint8", 27994 offset: 0 27995}]; 27996function addVertex(array, anchorX, anchorY, ox, oy, tx, ty, sizeVertex, isSDF, pixelOffsetX, pixelOffsetY, minFontScaleX, minFontScaleY, elevation) { 27997 const aSizeX = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[0])) : 0; 27998 const aSizeY = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[1])) : 0; 27999 array.emplaceBack(anchorX, anchorY, Math.round(ox * 32), Math.round(oy * 32), tx, ty, (aSizeX << 1) + (isSDF ? 1 : 0), aSizeY, pixelOffsetX * 16, pixelOffsetY * 16, minFontScaleX * 256, minFontScaleY * 256, elevation); 28000} 28001function addDynamicAttributes(dynamicLayoutVertexArray, p, angle) { 28002 dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); 28003 dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); 28004 dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); 28005 dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); 28006} 28007function containsRTLText(formattedText) { 28008 for (const section of formattedText.sections) if (stringContainsRTLText(section.text)) return true; 28009 return false; 28010} 28011var SymbolBuffers = class { 28012 constructor(programConfigurations) { 28013 this.layoutVertexArray = new SymbolLayoutArray(); 28014 this.indexArray = new TriangleIndexArray(); 28015 this.programConfigurations = programConfigurations; 28016 this.segments = new SegmentVector(); 28017 this.dynamicLayoutVertexArray = new SymbolDynamicLayoutArray(); 28018 this.opacityVertexArray = new SymbolOpacityArray(); 28019 this.hasVisibleVertices = false; 28020 this.placedSymbolArray = new PlacedSymbolArray(); 28021 } 28022 isEmpty() { 28023 return this.layoutVertexArray.length === 0 && this.indexArray.length === 0 && this.dynamicLayoutVertexArray.length === 0 && this.opacityVertexArray.length === 0; 28024 } 28025 upload(context, dynamicIndexBuffer, upload, update) { 28026 if (this.isEmpty()) return; 28027 if (upload) { 28028 this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, symbolLayoutAttributes.members); 28029 this.indexBuffer = context.createIndexBuffer(this.indexArray, dynamicIndexBuffer); 28030 this.dynamicLayoutVertexBuffer = context.createVertexBuffer(this.dynamicLayoutVertexArray, dynamicLayoutAttributes.members, true); 28031 this.opacityVertexBuffer = context.createVertexBuffer(this.opacityVertexArray, shaderOpacityAttributes, true); 28032 this.opacityVertexBuffer.itemSize = 1; 28033 } 28034 if (upload || update) this.programConfigurations.upload(context); 28035 } 28036 destroy() { 28037 if (!this.layoutVertexBuffer) return; 28038 this.layoutVertexBuffer.destroy(); 28039 this.indexBuffer.destroy(); 28040 this.programConfigurations.destroy(); 28041 this.segments.destroy(); 28042 this.dynamicLayoutVertexBuffer.destroy(); 28043 this.opacityVertexBuffer.destroy(); 28044 } 28045}; 28046register("SymbolBuffers", SymbolBuffers); 28047var CollisionBuffers = class { 28048 constructor(LayoutArray, layoutAttributes, IndexArray) { 28049 this.layoutVertexArray = new LayoutArray(); 28050 this.layoutAttributes = layoutAttributes; 28051 this.indexArray = new IndexArray(); 28052 this.segments = new SegmentVector(); 28053 this.collisionVertexArray = new CollisionVertexArray(); 28054 } 28055 upload(context) { 28056 this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, this.layoutAttributes); 28057 this.indexBuffer = context.createIndexBuffer(this.indexArray); 28058 this.collisionVertexBuffer = context.createVertexBuffer(this.collisionVertexArray, collisionVertexAttributes.members, true); 28059 } 28060 destroy() { 28061 if (!this.layoutVertexBuffer) return; 28062 this.layoutVertexBuffer.destroy(); 28063 this.indexBuffer.destroy(); 28064 this.segments.destroy(); 28065 this.collisionVertexBuffer.destroy(); 28066 } 28067}; 28068register("CollisionBuffers", CollisionBuffers); 28069/** 28070* @internal 28071* Unlike other buckets, which simply implement `addFeature` with type-specific 28072* logic for (essentially) triangulating feature geometries, SymbolBucket 28073* requires specialized behavior: 28074* 28075* 1. WorkerTile.parse(), the logical owner of the bucket creation process, 28076* calls SymbolBucket.populate(), which resolves text and icon tokens on 28077* each feature, adds each glyphs and symbols needed to the passed-in 28078* collections options.glyphDependencies and options.iconDependencies, and 28079* stores the feature data for use in subsequent step (this.features). 28080* 28081* 2. WorkerTile asynchronously requests from the main thread all of the glyphs 28082* and icons needed (by this bucket and any others). 28083* 28084* 3. WorkerTile calls SymbolBucket.addFeatures(), which delegates text shaping 28085* and layout to performSymbolLayout(). This step populates: 28086* `this.symbolInstances`: metadata on generated symbols 28087* `this.collisionBoxArray`: collision data for use by foreground 28088* `this.text`: SymbolBuffers for text symbols 28089* `this.icons`: SymbolBuffers for icons 28090* `this.iconCollisionBox`: Debug SymbolBuffers for icon collision boxes 28091* `this.textCollisionBox`: Debug SymbolBuffers for text collision boxes 28092* The results are sent to the foreground for rendering 28093* 28094* 4. placement.ts is run on the foreground, 28095* and uses the CollisionIndex along with current camera settings to determine 28096* which symbols can actually show on the map. Collided symbols are hidden 28097* using a dynamic "OpacityVertexArray". 28098*/ 28099var SymbolBucket = class { 28100 constructor(options) { 28101 this.collisionBoxArray = options.collisionBoxArray; 28102 this.zoom = options.zoom; 28103 this.overscaling = options.overscaling; 28104 this.layers = options.layers; 28105 this.layerIds = this.layers.map((layer) => layer.id); 28106 this.index = options.index; 28107 this.pixelRatio = options.pixelRatio; 28108 this.sourceLayerIndex = options.sourceLayerIndex; 28109 this.hasDependencies = true; 28110 this.hasRTLText = false; 28111 this.maxHeightOffset = 0; 28112 this.sortKeyRanges = []; 28113 this.collisionCircleArray = []; 28114 this.maxGlyphs = MAX_GLYPHS; 28115 const unevaluatedLayoutValues = this.layers[0]._unevaluatedLayout._values; 28116 this.textSizeData = getSizeData(this.zoom, unevaluatedLayoutValues["text-size"]); 28117 this.iconSizeData = getSizeData(this.zoom, unevaluatedLayoutValues["icon-size"]); 28118 const layout = this.layers[0].layout; 28119 const sortKey = layout.get("symbol-sort-key"); 28120 const zOrder = layout.get("symbol-z-order"); 28121 this.canOverlap = getOverlapMode(layout, "text-overlap", "text-allow-overlap") !== "never" || getOverlapMode(layout, "icon-overlap", "icon-allow-overlap") !== "never" || layout.get("text-ignore-placement") || layout.get("icon-ignore-placement"); 28122 this.sortFeaturesByKey = zOrder !== "viewport-y" && !sortKey.isConstant(); 28123 const zOrderByViewportY = zOrder === "viewport-y" || zOrder === "auto" && !this.sortFeaturesByKey; 28124 this.sortFeaturesByY = zOrderByViewportY && this.canOverlap; 28125 if (layout.get("symbol-placement") === "point") this.writingModes = layout.get("text-writing-mode").map((wm) => WritingMode[wm]); 28126 this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); 28127 this.sourceID = options.sourceID; 28128 } 28129 createArrays() { 28130 this.text = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, (property) => property.startsWith("text"))); 28131 this.icon = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, (property) => property.startsWith("icon"))); 28132 this.glyphOffsetArray = new GlyphOffsetArray(); 28133 this.lineVertexArray = new SymbolLineVertexArray(); 28134 this.symbolInstances = new SymbolInstanceArray(); 28135 this.textAnchorOffsets = new TextAnchorOffsetArray(); 28136 } 28137 /** 28138 * Collects the glyphs a label needs into `stacks`, so that the tile can ask for them. 28139 * 28140 * A cluster of several codepoints is asked for as a whole, so that it can be drawn as the one 28141 * shape it is written as. Its codepoints are asked for as well, to give layout something to draw 28142 * a codepoint at a time where the cluster itself yields no glyph. See `shapeLines`. 28143 * 28144 * A cluster can span two sections, a letter in one and the accent written on it in the next, so 28145 * the label is taken as a whole and each cluster attributed to the section its first character 28146 * came from -- the same way layout attributes it. Collecting each section's text on its own 28147 * would ask for glyphs no cluster is ever looked up by. 28148 */ 28149 calculateGlyphDependencies(text, stacks, fontStack, textAlongLine, doesAllowVerticalWritingMode) { 28150 const needsVerticalForms = (textAlongLine || this.allowVerticalPlacement) && doesAllowVerticalWritingMode; 28151 const tagged = TaggedString.fromFeature(text, fontStack); 28152 const graphemes = tagged.graphemes(); 28153 for (let i = 0; i < graphemes.length; i++) { 28154 const section = tagged.getSection(i); 28155 if ("imageName" in section) continue; 28156 const stack = stacks[section.fontStack] ||= {}; 28157 const grapheme = graphemes[i]; 28158 if (isCluster(grapheme)) stack[grapheme] = true; 28159 for (const char of grapheme) { 28160 stack[char] = true; 28161 if (!needsVerticalForms) continue; 28162 const verticalChar = verticalizedCharacterMap[char]; 28163 if (verticalChar) stack[verticalChar] = true; 28164 } 28165 } 28166 } 28167 populate(features, options, canonical) { 28168 const layer = this.layers[0]; 28169 const layout = layer.layout; 28170 const textFont = layout.get("text-font"); 28171 const textField = layout.get("text-field"); 28172 const iconImage = layout.get("icon-image"); 28173 const hasText = (textField.value.kind !== "constant" || textField.value.value instanceof Formatted && !textField.value.value.isEmpty() || textField.value.value.toString().length > 0) && (textFont.value.kind !== "constant" || textFont.value.value.length > 0); 28174 const hasIcon = iconImage.value.kind !== "constant" || !!iconImage.value.value || Object.keys(iconImage.parameters).length > 0; 28175 const symbolSortKey = layout.get("symbol-sort-key"); 28176 this.features = []; 28177 if (!hasText && !hasIcon) return; 28178 const icons = options.iconDependencies; 28179 const stacks = options.glyphDependencies; 28180 const availableImages = options.availableImages; 28181 const globalProperties = new EvaluationParameters(this.zoom); 28182 for (const { feature, id, index, sourceLayerIndex } of features) { 28183 const needGeometry = layer._featureFilter.needGeometry; 28184 const evaluationFeature = toEvaluationFeature(feature, needGeometry); 28185 if (!layer._featureFilter.filter(globalProperties, evaluationFeature, canonical)) continue; 28186 if (!needGeometry) evaluationFeature.geometry = loadGeometry(feature); 28187 let text; 28188 if (hasText) { 28189 const resolvedTokens = layer.getValueAndResolveTokens("text-field", evaluationFeature, canonical, availableImages); 28190 const formattedText = Formatted.factory(resolvedTokens); 28191 this.hasRTLText ||= containsRTLText(formattedText); 28192 text = transformText(formattedText, layer, evaluationFeature); 28193 } 28194 let icon; 28195 if (hasIcon) { 28196 const resolvedTokens = layer.getValueAndResolveTokens("icon-image", evaluationFeature, canonical, availableImages); 28197 if (resolvedTokens instanceof ResolvedImage) icon = resolvedTokens; 28198 else icon = ResolvedImage.fromString(resolvedTokens); 28199 } 28200 if (!text && !icon) continue; 28201 const sortKey = this.sortFeaturesByKey ? symbolSortKey.evaluate(evaluationFeature, {}, canonical) : void 0; 28202 const symbolFeature = { 28203 id, 28204 text, 28205 icon, 28206 index, 28207 sourceLayerIndex, 28208 geometry: evaluationFeature.geometry, 28209 properties: feature.properties, 28210 type: VectorTileFeature.types[feature.type], 28211 sortKey 28212 }; 28213 this.features.push(symbolFeature); 28214 if (icon) icons[icon.name] = true; 28215 if (text) { 28216 const fontStack = textFont.evaluate(evaluationFeature, {}, canonical).join(","); 28217 const textAlongLine = layout.get("text-rotation-alignment") !== "viewport" && layout.get("symbol-placement") !== "point"; 28218 this.allowVerticalPlacement = this.writingModes?.includes(2); 28219 const doesAllowVerticalWritingMode = allowsVerticalWritingMode(text.toString()); 28220 this.calculateGlyphDependencies(text, stacks, fontStack, textAlongLine, doesAllowVerticalWritingMode); 28221 for (const section of text.sections) if (section.image) icons[section.image.name] = true; 28222 } 28223 } 28224 if (layout.get("symbol-placement") === "line") this.features = mergeLines(this.features); 28225 if (this.sortFeaturesByKey) this.features.sort((a, b) => { 28226 return a.sortKey - b.sortKey; 28227 }); 28228 } 28229 update(states, vtLayer, imagePositions) { 28230 if (!this.stateDependentLayers.length) return; 28231 this.text.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, { imagePositions }); 28232 this.icon.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, { imagePositions }); 28233 } 28234 addFeatures({ options, canonical, glyphMap, glyphPositions, iconMap, iconPositions, showCollisionBoxes }) { 28235 performSymbolLayout({ 28236 bucket: this, 28237 glyphMap, 28238 glyphPositions, 28239 imageMap: iconMap, 28240 imagePositions: iconPositions, 28241 showCollisionBoxes, 28242 canonical, 28243 subdivisionGranularity: options.subdivisionGranularity, 28244 hasPromoteId: options.featureIndex.promoteId != null 28245 }); 28246 } 28247 isEmpty() { 28248 return this.symbolInstances.length === 0; 28249 } 28250 uploadPending() { 28251 return !this.uploaded || this.text.programConfigurations.needsUpload || this.icon.programConfigurations.needsUpload; 28252 } 28253 upload(context) { 28254 if (!this.uploaded && this.hasDebugData()) { 28255 this.textCollisionBox.upload(context); 28256 this.iconCollisionBox.upload(context); 28257 } 28258 this.text.upload(context, this.sortFeaturesByY, !this.uploaded, this.text.programConfigurations.needsUpload); 28259 this.icon.upload(context, this.sortFeaturesByY, !this.uploaded, this.icon.programConfigurations.needsUpload); 28260 this.uploaded = true; 28261 } 28262 destroyDebugData() { 28263 this.textCollisionBox.destroy(); 28264 this.iconCollisionBox.destroy(); 28265 } 28266 destroy() { 28267 this.text.destroy(); 28268 this.icon.destroy(); 28269 if (this.hasDebugData()) this.destroyDebugData(); 28270 } 28271 addToLineVertexArray(anchor, line) { 28272 const lineStartIndex = this.lineVertexArray.length; 28273 if (anchor.segment !== void 0) { 28274 let sumForwardLength = anchor.dist(line[anchor.segment + 1]); 28275 let sumBackwardLength = anchor.dist(line[anchor.segment]); 28276 const vertices = {}; 28277 for (let i = anchor.segment + 1; i < line.length; i++) { 28278 vertices[i] = { 28279 x: line[i].x, 28280 y: line[i].y, 28281 tileUnitDistanceFromAnchor: sumForwardLength 28282 }; 28283 if (i < line.length - 1) sumForwardLength += line[i + 1].dist(line[i]); 28284 } 28285 for (let i = anchor.segment || 0; i >= 0; i--) { 28286 vertices[i] = { 28287 x: line[i].x, 28288 y: line[i].y, 28289 tileUnitDistanceFromAnchor: sumBackwardLength 28290 }; 28291 if (i > 0) sumBackwardLength += line[i - 1].dist(line[i]); 28292 } 28293 for (let i = 0; i < line.length; i++) { 28294 const vertex = vertices[i]; 28295 this.lineVertexArray.emplaceBack(vertex.x, vertex.y, vertex.tileUnitDistanceFromAnchor); 28296 } 28297 } 28298 return { 28299 lineStartIndex, 28300 lineLength: this.lineVertexArray.length - lineStartIndex 28301 }; 28302 } 28303 addSymbols(arrays, quads, sizeVertex, lineOffset, alongLine, feature, writingMode, labelAnchor, lineStartIndex, lineLength, associatedIconIndex, canonical, elevation) { 28304 const indexArray = arrays.indexArray; 28305 const layoutVertexArray = arrays.layoutVertexArray; 28306 const segment = arrays.segments.prepareSegment(4 * quads.length, layoutVertexArray, indexArray, this.canOverlap ? feature.sortKey : void 0); 28307 const glyphOffsetArrayStart = this.glyphOffsetArray.length; 28308 const vertexStartIndex = segment.vertexLength; 28309 const angle = this.allowVerticalPlacement && writingMode === 2 ? Math.PI / 2 : 0; 28310 const sections = feature.text && feature.text.sections; 28311 for (let i = 0; i < quads.length; i++) { 28312 const { tl, tr, bl, br, tex, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY, glyphOffset, isSDF, sectionIndex } = quads[i]; 28313 const index = segment.vertexLength; 28314 const y = glyphOffset[1]; 28315 addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, tl.x, y + tl.y, tex.x, tex.y, sizeVertex, isSDF, pixelOffsetTL.x, pixelOffsetTL.y, minFontScaleX, minFontScaleY, elevation); 28316 addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, tr.x, y + tr.y, tex.x + tex.w, tex.y, sizeVertex, isSDF, pixelOffsetBR.x, pixelOffsetTL.y, minFontScaleX, minFontScaleY, elevation); 28317 addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, bl.x, y + bl.y, tex.x, tex.y + tex.h, sizeVertex, isSDF, pixelOffsetTL.x, pixelOffsetBR.y, minFontScaleX, minFontScaleY, elevation); 28318 addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, br.x, y + br.y, tex.x + tex.w, tex.y + tex.h, sizeVertex, isSDF, pixelOffsetBR.x, pixelOffsetBR.y, minFontScaleX, minFontScaleY, elevation); 28319 addDynamicAttributes(arrays.dynamicLayoutVertexArray, labelAnchor, angle); 28320 indexArray.emplaceBack(index, index + 2, index + 1); 28321 indexArray.emplaceBack(index + 1, index + 2, index + 3); 28322 segment.vertexLength += 4; 28323 segment.primitiveLength += 2; 28324 this.glyphOffsetArray.emplaceBack(glyphOffset[0]); 28325 if (i === quads.length - 1 || sectionIndex !== quads[i + 1].sectionIndex) arrays.programConfigurations.populatePaintArrays(layoutVertexArray.length, feature, feature.index, { 28326 imagePositions: {}, 28327 canonical, 28328 formattedSection: sections?.[sectionIndex] 28329 }); 28330 } 28331 arrays.placedSymbolArray.emplaceBack(labelAnchor.x, labelAnchor.y, glyphOffsetArrayStart, this.glyphOffsetArray.length - glyphOffsetArrayStart, vertexStartIndex, lineStartIndex, lineLength, labelAnchor.segment, sizeVertex ? sizeVertex[0] : 0, sizeVertex ? sizeVertex[1] : 0, lineOffset[0], lineOffset[1], writingMode, 0, false, 0, associatedIconIndex, elevation); 28332 } 28333 _addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, point, anchorX, anchorY, extrude) { 28334 collisionVertexArray.emplaceBack(0, 0); 28335 return layoutVertexArray.emplaceBack(point.x, point.y, anchorX, anchorY, Math.round(extrude.x), Math.round(extrude.y)); 28336 } 28337 addCollisionDebugVertices(x1, y1, x2, y2, arrays, boxAnchorPoint, symbolInstance) { 28338 const segment = arrays.segments.prepareSegment(4, arrays.layoutVertexArray, arrays.indexArray); 28339 const index = segment.vertexLength; 28340 const layoutVertexArray = arrays.layoutVertexArray; 28341 const collisionVertexArray = arrays.collisionVertexArray; 28342 const anchorX = symbolInstance.anchorX; 28343 const anchorY = symbolInstance.anchorY; 28344 this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x1, y1)); 28345 this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x2, y1)); 28346 this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x2, y2)); 28347 this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x1, y2)); 28348 segment.vertexLength += 4; 28349 const indexArray = arrays.indexArray; 28350 indexArray.emplaceBack(index, index + 1); 28351 indexArray.emplaceBack(index + 1, index + 2); 28352 indexArray.emplaceBack(index + 2, index + 3); 28353 indexArray.emplaceBack(index + 3, index); 28354 segment.primitiveLength += 4; 28355 } 28356 addDebugCollisionBoxes(startIndex, endIndex, symbolInstance, isText) { 28357 for (let b = startIndex; b < endIndex; b++) { 28358 const box = this.collisionBoxArray.get(b); 28359 const x1 = box.x1; 28360 const y1 = box.y1; 28361 const x2 = box.x2; 28362 const y2 = box.y2; 28363 this.addCollisionDebugVertices(x1, y1, x2, y2, isText ? this.textCollisionBox : this.iconCollisionBox, box.anchorPoint, symbolInstance); 28364 } 28365 } 28366 generateCollisionDebugBuffers() { 28367 if (this.hasDebugData()) this.destroyDebugData(); 28368 this.textCollisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray); 28369 this.iconCollisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray); 28370 for (let i = 0; i < this.symbolInstances.length; i++) { 28371 const symbolInstance = this.symbolInstances.get(i); 28372 this.addDebugCollisionBoxes(symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance, true); 28373 this.addDebugCollisionBoxes(symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance, true); 28374 this.addDebugCollisionBoxes(symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance, false); 28375 this.addDebugCollisionBoxes(symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex, symbolInstance, false); 28376 } 28377 } 28378 _deserializeCollisionBoxesForSymbol(collisionBoxArray, textStartIndex, textEndIndex, verticalTextStartIndex, verticalTextEndIndex, iconStartIndex, iconEndIndex, verticalIconStartIndex, verticalIconEndIndex) { 28379 const collisionArrays = {}; 28380 for (let k = textStartIndex; k < textEndIndex; k++) { 28381 const box = collisionBoxArray.get(k); 28382 collisionArrays.textBox = { 28383 x1: box.x1, 28384 y1: box.y1, 28385 x2: box.x2, 28386 y2: box.y2, 28387 anchorPointX: box.anchorPointX, 28388 anchorPointY: box.anchorPointY 28389 }; 28390 collisionArrays.textFeatureIndex = box.featureIndex; 28391 break; 28392 } 28393 for (let k = verticalTextStartIndex; k < verticalTextEndIndex; k++) { 28394 const box = collisionBoxArray.get(k); 28395 collisionArrays.verticalTextBox = { 28396 x1: box.x1, 28397 y1: box.y1, 28398 x2: box.x2, 28399 y2: box.y2, 28400 anchorPointX: box.anchorPointX, 28401 anchorPointY: box.anchorPointY 28402 }; 28403 collisionArrays.verticalTextFeatureIndex = box.featureIndex; 28404 break; 28405 } 28406 for (let k = iconStartIndex; k < iconEndIndex; k++) { 28407 const box = collisionBoxArray.get(k); 28408 collisionArrays.iconBox = { 28409 x1: box.x1, 28410 y1: box.y1, 28411 x2: box.x2, 28412 y2: box.y2, 28413 anchorPointX: box.anchorPointX, 28414 anchorPointY: box.anchorPointY 28415 }; 28416 collisionArrays.iconFeatureIndex = box.featureIndex; 28417 break; 28418 } 28419 for (let k = verticalIconStartIndex; k < verticalIconEndIndex; k++) { 28420 const box = collisionBoxArray.get(k); 28421 collisionArrays.verticalIconBox = { 28422 x1: box.x1, 28423 y1: box.y1, 28424 x2: box.x2, 28425 y2: box.y2, 28426 anchorPointX: box.anchorPointX, 28427 anchorPointY: box.anchorPointY 28428 }; 28429 collisionArrays.verticalIconFeatureIndex = box.featureIndex; 28430 break; 28431 } 28432 return collisionArrays; 28433 } 28434 deserializeCollisionBoxes(collisionBoxArray) { 28435 this.collisionArrays = []; 28436 for (let i = 0; i < this.symbolInstances.length; i++) { 28437 const symbolInstance = this.symbolInstances.get(i); 28438 this.collisionArrays.push(this._deserializeCollisionBoxesForSymbol(collisionBoxArray, symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex)); 28439 } 28440 } 28441 hasTextData() { 28442 return this.text.segments.get().length > 0; 28443 } 28444 hasIconData() { 28445 return this.icon.segments.get().length > 0; 28446 } 28447 hasDebugData() { 28448 return this.textCollisionBox && this.iconCollisionBox; 28449 } 28450 hasTextCollisionBoxData() { 28451 return this.hasDebugData() && this.textCollisionBox.segments.get().length > 0; 28452 } 28453 hasIconCollisionBoxData() { 28454 return this.hasDebugData() && this.iconCollisionBox.segments.get().length > 0; 28455 } 28456 addIndicesForPlacedSymbol(iconOrText, placedSymbolIndex) { 28457 const placedSymbol = iconOrText.placedSymbolArray.get(placedSymbolIndex); 28458 const endIndex = placedSymbol.vertexStartIndex + placedSymbol.numGlyphs * 4; 28459 for (let vertexIndex = placedSymbol.vertexStartIndex; vertexIndex < endIndex; vertexIndex += 4) { 28460 iconOrText.indexArray.emplaceBack(vertexIndex, vertexIndex + 2, vertexIndex + 1); 28461 iconOrText.indexArray.emplaceBack(vertexIndex + 1, vertexIndex + 2, vertexIndex + 3); 28462 } 28463 } 28464 getSortedSymbolIndexes(angle) { 28465 if (this.sortedAngle === angle && this.symbolInstanceIndexes !== void 0) return this.symbolInstanceIndexes; 28466 const sin = Math.sin(angle); 28467 const cos = Math.cos(angle); 28468 const rotatedYs = []; 28469 const featureIndexes = []; 28470 const result = []; 28471 for (let i = 0; i < this.symbolInstances.length; ++i) { 28472 result.push(i); 28473 const symbolInstance = this.symbolInstances.get(i); 28474 rotatedYs.push(Math.round(sin * symbolInstance.anchorX + cos * symbolInstance.anchorY) | 0); 28475 featureIndexes.push(symbolInstance.featureIndex); 28476 } 28477 result.sort((aIndex, bIndex) => { 28478 return rotatedYs[aIndex] - rotatedYs[bIndex] || featureIndexes[bIndex] - featureIndexes[aIndex]; 28479 }); 28480 return result; 28481 } 28482 addToSortKeyRanges(symbolInstanceIndex, sortKey) { 28483 const last = this.sortKeyRanges[this.sortKeyRanges.length - 1]; 28484 if (last?.sortKey === sortKey) last.symbolInstanceEnd = symbolInstanceIndex + 1; 28485 else this.sortKeyRanges.push({ 28486 sortKey, 28487 symbolInstanceStart: symbolInstanceIndex, 28488 symbolInstanceEnd: symbolInstanceIndex + 1 28489 }); 28490 } 28491 sortFeatures(angle) { 28492 if (!this.sortFeaturesByY) return; 28493 if (this.sortedAngle === angle) return; 28494 if (this.text.segments.get().length > 1 || this.icon.segments.get().length > 1) return; 28495 this.symbolInstanceIndexes = this.getSortedSymbolIndexes(angle); 28496 this.sortedAngle = angle; 28497 this.text.indexArray.clear(); 28498 this.icon.indexArray.clear(); 28499 this.featureSortOrder = []; 28500 for (const i of this.symbolInstanceIndexes) { 28501 const symbolInstance = this.symbolInstances.get(i); 28502 this.featureSortOrder.push(symbolInstance.featureIndex); 28503 const textIndices = [ 28504 symbolInstance.rightJustifiedTextSymbolIndex, 28505 symbolInstance.centerJustifiedTextSymbolIndex, 28506 symbolInstance.leftJustifiedTextSymbolIndex 28507 ]; 28508 for (let i = 0; i < textIndices.length; i++) { 28509 const index = textIndices[i]; 28510 if (index >= 0 && textIndices.indexOf(index) === i) this.addIndicesForPlacedSymbol(this.text, index); 28511 } 28512 if (symbolInstance.verticalPlacedTextSymbolIndex >= 0) this.addIndicesForPlacedSymbol(this.text, symbolInstance.verticalPlacedTextSymbolIndex); 28513 if (symbolInstance.placedIconSymbolIndex >= 0) this.addIndicesForPlacedSymbol(this.icon, symbolInstance.placedIconSymbolIndex); 28514 if (symbolInstance.verticalPlacedIconSymbolIndex >= 0) this.addIndicesForPlacedSymbol(this.icon, symbolInstance.verticalPlacedIconSymbolIndex); 28515 } 28516 if (this.text.indexBuffer) this.text.indexBuffer.updateData(this.text.indexArray); 28517 if (this.icon.indexBuffer) this.icon.indexBuffer.updateData(this.icon.indexArray); 28518 } 28519}; 28520register("SymbolBucket", SymbolBucket, { omit: [ 28521 "layers", 28522 "collisionBoxArray", 28523 "features", 28524 "compareText" 28525] }); 28526//#endregion 28527//#region src/util/resolve_tokens.ts 28528/** 28529* Replace tokens in a string template with values in an object 28530* 28531* @param properties - a key/value relationship between tokens and replacements 28532* @param text - the template string 28533* @returns the template with tokens replaced 28534*/ 28535function resolveTokens(properties, text) { 28536 return text.replace(/{([^{}]+)}/g, (match, key) => { 28537 return properties && key in properties ? String(properties[key]) : ""; 28538 }); 28539} 28540//#endregion 28541//#region src/style/style_layer/symbol_style_layer_properties.g.ts 28542let layout; 28543const getLayout = () => layout = layout || new Properties({ 28544 "symbol-placement": new DataConstantProperty(latest["layout_symbol"]["symbol-placement"], "symbol-placement"), 28545 "symbol-spacing": new DataConstantProperty(latest["layout_symbol"]["symbol-spacing"], "symbol-spacing"), 28546 "symbol-avoid-edges": new DataConstantProperty(latest["layout_symbol"]["symbol-avoid-edges"], "symbol-avoid-edges"), 28547 "symbol-sort-key": new DataDrivenProperty(latest["layout_symbol"]["symbol-sort-key"], "symbol-sort-key"), 28548 "symbol-z-order": new DataConstantProperty(latest["layout_symbol"]["symbol-z-order"], "symbol-z-order"), 28549 "icon-allow-overlap": new DataConstantProperty(latest["layout_symbol"]["icon-allow-overlap"], "icon-allow-overlap"), 28550 "icon-overlap": new DataConstantProperty(latest["layout_symbol"]["icon-overlap"], "icon-overlap"), 28551 "icon-ignore-placement": new DataConstantProperty(latest["layout_symbol"]["icon-ignore-placement"], "icon-ignore-placement"), 28552 "icon-optional": new DataConstantProperty(latest["layout_symbol"]["icon-optional"], "icon-optional"), 28553 "icon-rotation-alignment": new DataDrivenProperty(latest["layout_symbol"]["icon-rotation-alignment"], "icon-rotation-alignment"), 28554 "icon-size": new DataDrivenProperty(latest["layout_symbol"]["icon-size"], "icon-size"), 28555 "icon-text-fit": new DataConstantProperty(latest["layout_symbol"]["icon-text-fit"], "icon-text-fit"), 28556 "icon-text-fit-padding": new DataConstantProperty(latest["layout_symbol"]["icon-text-fit-padding"], "icon-text-fit-padding"), 28557 "icon-image": new DataDrivenProperty(latest["layout_symbol"]["icon-image"], "icon-image"), 28558 "icon-rotate": new DataDrivenProperty(latest["layout_symbol"]["icon-rotate"], "icon-rotate"), 28559 "icon-padding": new DataDrivenProperty(latest["layout_symbol"]["icon-padding"], "icon-padding"), 28560 "icon-keep-upright": new DataConstantProperty(latest["layout_symbol"]["icon-keep-upright"], "icon-keep-upright"), 28561 "icon-offset": new DataDrivenProperty(latest["layout_symbol"]["icon-offset"], "icon-offset"), 28562 "icon-anchor": new DataDrivenProperty(latest["layout_symbol"]["icon-anchor"], "icon-anchor"), 28563 "icon-pitch-alignment": new DataConstantProperty(latest["layout_symbol"]["icon-pitch-alignment"], "icon-pitch-alignment"), 28564 "text-pitch-alignment": new DataConstantProperty(latest["layout_symbol"]["text-pitch-alignment"], "text-pitch-alignment"), 28565 "text-rotation-alignment": new DataConstantProperty(latest["layout_symbol"]["text-rotation-alignment"], "text-rotation-alignment"), 28566 "text-field": new DataDrivenProperty(latest["layout_symbol"]["text-field"], "text-field"), 28567 "text-font": new DataDrivenProperty(latest["layout_symbol"]["text-font"], "text-font"), 28568 "text-size": new DataDrivenProperty(latest["layout_symbol"]["text-size"], "text-size"), 28569 "text-max-width": new DataDrivenProperty(latest["layout_symbol"]["text-max-width"], "text-max-width"), 28570 "text-line-height": new DataConstantProperty(latest["layout_symbol"]["text-line-height"], "text-line-height"), 28571 "text-letter-spacing": new DataDrivenProperty(latest["layout_symbol"]["text-letter-spacing"], "text-letter-spacing"), 28572 "text-justify": new DataDrivenProperty(latest["layout_symbol"]["text-justify"], "text-justify"), 28573 "text-radial-offset": new DataDrivenProperty(latest["layout_symbol"]["text-radial-offset"], "text-radial-offset"), 28574 "text-variable-anchor": new DataConstantProperty(latest["layout_symbol"]["text-variable-anchor"], "text-variable-anchor"), 28575 "text-variable-anchor-offset": new DataDrivenProperty(latest["layout_symbol"]["text-variable-anchor-offset"], "text-variable-anchor-offset"), 28576 "text-anchor": new DataDrivenProperty(latest["layout_symbol"]["text-anchor"], "text-anchor"), 28577 "text-max-angle": new DataConstantProperty(latest["layout_symbol"]["text-max-angle"], "text-max-angle"), 28578 "text-writing-mode": new DataConstantProperty(latest["layout_symbol"]["text-writing-mode"], "text-writing-mode"), 28579 "text-rotate": new DataDrivenProperty(latest["layout_symbol"]["text-rotate"], "text-rotate"), 28580 "text-padding": new DataConstantProperty(latest["layout_symbol"]["text-padding"], "text-padding"), 28581 "text-keep-upright": new DataConstantProperty(latest["layout_symbol"]["text-keep-upright"], "text-keep-upright"), 28582 "text-transform": new DataDrivenProperty(latest["layout_symbol"]["text-transform"], "text-transform"), 28583 "text-offset": new DataDrivenProperty(latest["layout_symbol"]["text-offset"], "text-offset"), 28584 "text-allow-overlap": new DataConstantProperty(latest["layout_symbol"]["text-allow-overlap"], "text-allow-overlap"), 28585 "text-overlap": new DataConstantProperty(latest["layout_symbol"]["text-overlap"], "text-overlap"), 28586 "text-ignore-placement": new DataConstantProperty(latest["layout_symbol"]["text-ignore-placement"], "text-ignore-placement"), 28587 "text-optional": new DataConstantProperty(latest["layout_symbol"]["text-optional"], "text-optional"), 28588 "symbol-height-offset": new DataDrivenProperty(latest["layout_symbol"]["symbol-height-offset"], "symbol-height-offset"), 28589 "symbol-height-anchor": new DataConstantProperty(latest["layout_symbol"]["symbol-height-anchor"], "symbol-height-anchor") 28590}); 28591let paint$1; 28592const getPaint$1 = () => paint$1 = paint$1 || new Properties({ 28593 "icon-opacity": new DataDrivenProperty(latest["paint_symbol"]["icon-opacity"], "icon-opacity"), 28594 "icon-color": new DataDrivenProperty(latest["paint_symbol"]["icon-color"], "icon-color"), 28595 "icon-halo-color": new DataDrivenProperty(latest["paint_symbol"]["icon-halo-color"], "icon-halo-color"), 28596 "icon-halo-width": new DataDrivenProperty(latest["paint_symbol"]["icon-halo-width"], "icon-halo-width"), 28597 "icon-halo-blur": new DataDrivenProperty(latest["paint_symbol"]["icon-halo-blur"], "icon-halo-blur"), 28598 "icon-translate": new DataConstantProperty(latest["paint_symbol"]["icon-translate"], "icon-translate"), 28599 "icon-translate-anchor": new DataConstantProperty(latest["paint_symbol"]["icon-translate-anchor"], "icon-translate-anchor"), 28600 "text-opacity": new DataDrivenProperty(latest["paint_symbol"]["text-opacity"], "text-opacity"), 28601 "text-color": new DataDrivenProperty(latest["paint_symbol"]["text-color"], "text-color", { 28602 runtimeType: ColorType, 28603 getOverride: (o) => o.textColor, 28604 hasOverride: (o) => !!o.textColor 28605 }), 28606 "text-halo-color": new DataDrivenProperty(latest["paint_symbol"]["text-halo-color"], "text-halo-color"), 28607 "text-halo-width": new DataDrivenProperty(latest["paint_symbol"]["text-halo-width"], "text-halo-width"), 28608 "text-halo-blur": new DataDrivenProperty(latest["paint_symbol"]["text-halo-blur"], "text-halo-blur"), 28609 "text-translate": new DataConstantProperty(latest["paint_symbol"]["text-translate"], "text-translate"), 28610 "text-translate-anchor": new DataConstantProperty(latest["paint_symbol"]["text-translate-anchor"], "text-translate-anchor") 28611}); 28612var symbol_style_layer_properties_g_default = { 28613 get paint() { 28614 return getPaint$1(); 28615 }, 28616 get layout() { 28617 return getLayout(); 28618 } 28619}; 28620//#endregion 28621//#region src/style/format_section_override.ts 28622var FormatSectionOverride = class { 28623 constructor(defaultValue) { 28624 if (defaultValue.property.overrides === void 0) throw new Error("overrides must be provided to instantiate FormatSectionOverride class"); 28625 this.type = defaultValue.property.overrides ? defaultValue.property.overrides.runtimeType : NullType; 28626 this.defaultValue = defaultValue; 28627 } 28628 evaluate(ctx) { 28629 if (ctx.formattedSection) { 28630 const overrides = this.defaultValue.property.overrides; 28631 if (overrides?.hasOverride(ctx.formattedSection)) return overrides.getOverride(ctx.formattedSection); 28632 } 28633 if (ctx.feature && ctx.featureState) return this.defaultValue.evaluate(ctx.feature, ctx.featureState); 28634 return this.defaultValue.property.specification.default; 28635 } 28636 eachChild(fn) { 28637 if (!this.defaultValue.isConstant()) { 28638 const expr = this.defaultValue.value; 28639 fn(expr._styleExpression.expression); 28640 } 28641 } 28642 outputDefined() { 28643 return false; 28644 } 28645 serialize() { 28646 return null; 28647 } 28648}; 28649register("FormatSectionOverride", FormatSectionOverride, { omit: ["defaultValue"] }); 28650//#endregion 28651//#region src/style/style_layer/symbol_style_layer.ts 28652const isSymbolStyleLayer = (layer) => layer.type === "symbol"; 28653var SymbolStyleLayer = class SymbolStyleLayer extends StyleLayer { 28654 constructor(layer, globalState) { 28655 super(layer, symbol_style_layer_properties_g_default, globalState); 28656 } 28657 recalculate(parameters, availableImages) { 28658 super.recalculate(parameters, availableImages); 28659 const iconRotationAlignment = this.layout.get("icon-rotation-alignment"); 28660 if (iconRotationAlignment.value.kind !== "constant" || iconRotationAlignment.value.value === "auto") this.layout._values["icon-rotation-alignment"] = new PossiblyEvaluatedPropertyValue(iconRotationAlignment.property, { 28661 kind: "constant", 28662 value: this.layout.get("symbol-placement") !== "point" ? "map" : "viewport" 28663 }, iconRotationAlignment.parameters); 28664 if (this.layout.get("text-rotation-alignment") === "auto") { 28665 if (this.layout.get("symbol-placement") !== "point") this.layout._values["text-rotation-alignment"] = "map"; 28666 else this.layout._values["text-rotation-alignment"] = "viewport"; 28667 } 28668 if (this.layout.get("text-pitch-alignment") === "auto") this.layout._values["text-pitch-alignment"] = this.layout.get("text-rotation-alignment") === "map" ? "map" : "viewport"; 28669 if (this.layout.get("icon-pitch-alignment") === "auto") this.layout._values["icon-pitch-alignment"] = this.layout.get("icon-rotation-alignment").constantOr("viewport"); 28670 if (this.layout.get("symbol-placement") === "point") { 28671 const writingModes = this.layout.get("text-writing-mode"); 28672 if (writingModes) { 28673 const deduped = []; 28674 for (const m of writingModes) if (!deduped.includes(m)) deduped.push(m); 28675 this.layout._values["text-writing-mode"] = deduped; 28676 } else this.layout._values["text-writing-mode"] = ["horizontal"]; 28677 } 28678 this._setPaintOverrides(); 28679 } 28680 getValueAndResolveTokens(name, feature, canonical, availableImages) { 28681 const value = this.layout.get(name).evaluate(feature, {}, canonical, availableImages); 28682 const unevaluated = this._unevaluatedLayout._values[name]; 28683 if (!unevaluated.isDataDriven() && !isExpression(unevaluated.value) && value) return resolveTokens(feature.properties, value); 28684 return value; 28685 } 28686 createBucket(parameters) { 28687 return new SymbolBucket(parameters); 28688 } 28689 queryRadius() { 28690 return 0; 28691 } 28692 queryIntersectsFeature() { 28693 throw new Error("Should take a different path in FeatureIndex"); 28694 } 28695 _setPaintOverrides() { 28696 for (const overridable of symbol_style_layer_properties_g_default.paint.overridableProperties) { 28697 if (!SymbolStyleLayer.hasPaintOverride(this.layout, overridable)) continue; 28698 const overridden = this.paint.get(overridable); 28699 const styleExpression = new StyleExpression(new FormatSectionOverride(overridden), `layers[${this.id}].paint.${overridden.property.name}`, overridden.property.specification); 28700 let expression = null; 28701 if (overridden.value.kind === "constant" || overridden.value.kind === "source") expression = new ZoomConstantExpression("source", styleExpression); 28702 else expression = new ZoomDependentExpression("composite", styleExpression, overridden.value.zoomStops); 28703 this.paint._values[overridable] = new PossiblyEvaluatedPropertyValue(overridden.property, expression, overridden.parameters); 28704 } 28705 } 28706 _handleOverridablePaintPropertyUpdate(name, oldValue, newValue) { 28707 if (!this.layout || oldValue.isDataDriven() || newValue.isDataDriven()) return false; 28708 return SymbolStyleLayer.hasPaintOverride(this.layout, name); 28709 } 28710 static hasPaintOverride(layout, propertyName) { 28711 const textField = layout.get("text-field"); 28712 const property = symbol_style_layer_properties_g_default.paint.properties[propertyName]; 28713 let hasOverrides = false; 28714 const checkSections = (sections) => { 28715 for (const section of sections) if (property.overrides?.hasOverride(section)) { 28716 hasOverrides = true; 28717 return; 28718 } 28719 }; 28720 if (textField.value.kind === "constant" && textField.value.value instanceof Formatted) checkSections(textField.value.value.sections); 28721 else if (textField.value.kind === "source" || textField.value.kind === "composite") { 28722 const checkExpression = (expression) => { 28723 if (hasOverrides) return; 28724 if (expression instanceof Literal && typeOf(expression.value) === FormattedType) { 28725 const formatted = expression.value; 28726 checkSections(formatted.sections); 28727 } else if (expression instanceof FormatExpression) checkSections(expression.sections); 28728 else expression.eachChild(checkExpression); 28729 }; 28730 const expr = textField.value; 28731 if (expr._styleExpression) checkExpression(expr._styleExpression.expression); 28732 } 28733 return hasOverrides; 28734 } 28735}; 28736function getIconPadding(layout, feature, canonical, pixelRatio = 1) { 28737 const values = layout.get("icon-padding").evaluate(feature, {}, canonical)?.values; 28738 return [ 28739 values[0] * pixelRatio, 28740 values[1] * pixelRatio, 28741 values[2] * pixelRatio, 28742 values[3] * pixelRatio 28743 ]; 28744} 28745//#endregion 28746//#region src/style/style_layer/background_style_layer_properties.g.ts 28747let paint; 28748const getPaint = () => paint = paint || new Properties({ 28749 "background-color": new DataConstantProperty(latest["paint_background"]["background-color"], "background-color"), 28750 "background-pattern": new CrossFadedProperty(latest["paint_background"]["background-pattern"], "background-pattern"), 28751 "background-opacity": new DataConstantProperty(latest["paint_background"]["background-opacity"], "background-opacity") 28752}); 28753var background_style_layer_properties_g_default = { get paint() { 28754 return getPaint(); 28755} }; 28756//#endregion 28757//#region src/style/style_layer/background_style_layer.ts 28758const isBackgroundStyleLayer = (layer) => layer.type === "background"; 28759var BackgroundStyleLayer = class extends StyleLayer { 28760 constructor(layer, globalState) { 28761 super(layer, background_style_layer_properties_g_default, globalState); 28762 } 28763}; 28764//#endregion 28765//#region src/style/style_layer/custom_style_layer.ts 28766function validateCustomStyleLayer(layerObject) { 28767 const errors = []; 28768 const id = layerObject.id; 28769 if (id === void 0) errors.push(new ValidationError(`layers.${id}`, null, "missing required property \"id\"")); 28770 if (layerObject.render === void 0) errors.push(new ValidationError(`layers.${id}`, null, "missing required method \"render\"")); 28771 if (layerObject.renderingMode && layerObject.renderingMode !== "2d" && layerObject.renderingMode !== "3d") errors.push(new ValidationError(`layers.${id}`, null, "property \"renderingMode\" must be either \"2d\" or \"3d\"")); 28772 return errors; 28773} 28774const isCustomStyleLayer = (layer) => layer.type === "custom"; 28775var CustomStyleLayer = class extends StyleLayer { 28776 constructor(implementation, globalState) { 28777 super(implementation, {}, globalState); 28778 this.onAdd = (map) => { 28779 if (this.implementation.onAdd) this.implementation.onAdd(map, map.painter.context.gl); 28780 }; 28781 this.onRemove = (map) => { 28782 if (this.implementation.onRemove) this.implementation.onRemove(map, map.painter.context.gl); 28783 }; 28784 this.implementation = implementation; 28785 } 28786 is3D() { 28787 return this.implementation.renderingMode === "3d"; 28788 } 28789 hasOffscreenPass() { 28790 return this.implementation.prerender !== void 0; 28791 } 28792 recalculate() {} 28793 updateTransitions() {} 28794 hasTransition() { 28795 return false; 28796 } 28797 serialize() { 28798 throw new Error("Custom layers cannot be serialized"); 28799 } 28800}; 28801//#endregion 28802//#region src/style/create_style_layer.ts 28803function createStyleLayer(layer, globalState) { 28804 if (layer.type === "custom") return new CustomStyleLayer(layer, globalState); 28805 switch (layer.type) { 28806 case "background": return new BackgroundStyleLayer(layer, globalState); 28807 case "circle": return new CircleStyleLayer(layer, globalState); 28808 case "color-relief": return new ColorReliefStyleLayer(layer, globalState); 28809 case "fill": return new FillStyleLayer(layer, globalState); 28810 case "fill-extrusion": return new FillExtrusionStyleLayer(layer, globalState); 28811 case "heatmap": return new HeatmapStyleLayer(layer, globalState); 28812 case "hillshade": return new HillshadeStyleLayer(layer, globalState); 28813 case "line": return new LineStyleLayer(layer, globalState); 28814 case "raster": return new RasterStyleLayer(layer, globalState); 28815 case "symbol": return new SymbolStyleLayer(layer, globalState); 28816 } 28817} 28818//#endregion 28819//#region src/util/throttled_invoker.ts 28820/** 28821* Invokes the wrapped function in a non-blocking way when trigger() is called. 28822* Invocation requests are ignored until the function was actually invoked. 28823*/ 28824var ThrottledInvoker = class { 28825 constructor(methodToThrottle) { 28826 this._methodToThrottle = methodToThrottle; 28827 this._triggered = false; 28828 this._channel = new MessageChannel(); 28829 this._channel.port2.onmessage = () => { 28830 this._triggered = false; 28831 this._methodToThrottle(); 28832 }; 28833 } 28834 trigger() { 28835 if (this._triggered) return; 28836 this._triggered = true; 28837 this._channel?.port1.postMessage(true); 28838 } 28839 remove() { 28840 delete this._channel; 28841 this._methodToThrottle = () => {}; 28842 } 28843}; 28844//#endregion 28845//#region src/util/actor.ts 28846const addEventDefaultOptions = { once: true }; 28847/** 28848* An implementation of the [Actor design pattern](https://en.wikipedia.org/wiki/Actor_model) 28849* that maintains the relationship between asynchronous tasks and the objects 28850* that spin them off - in this case, tasks like parsing parts of styles, 28851* owned by the styles 28852*/ 28853var Actor = class { 28854 /** 28855 * @param target - The target 28856 * @param mapId - A unique identifier for the Map instance using this Actor. 28857 */ 28858 constructor(target, mapId) { 28859 this.target = target; 28860 this.mapId = mapId; 28861 this.resolveRejects = {}; 28862 this.tasks = {}; 28863 this.taskQueue = []; 28864 this.abortControllers = {}; 28865 this.messageHandlers = {}; 28866 this.invoker = new ThrottledInvoker(() => this.process()); 28867 this.subscription = subscribe(this.target, "message", (message) => this.receive(message), false); 28868 this.globalScope = isWorker(self) ? target : window; 28869 } 28870 registerMessageHandler(type, handler) { 28871 this.messageHandlers[type] = handler; 28872 } 28873 unregisterMessageHandler(type) { 28874 delete this.messageHandlers[type]; 28875 } 28876 /** 28877 * Sends a message from a main-thread map to a Worker or from a Worker back to 28878 * a main-thread map instance. 28879 * @param message - the message to send 28880 * @param abortController - an optional AbortController to abort the request 28881 * @returns a promise that will be resolved with the response data 28882 */ 28883 sendAsync(message, abortController) { 28884 return new Promise((resolve, reject) => { 28885 const id = Math.round(Math.random() * 0xde0b6b3a7640000).toString(36).substring(0, 10); 28886 const subscription = abortController ? subscribe(abortController.signal, "abort", () => { 28887 subscription?.unsubscribe(); 28888 delete this.resolveRejects[id]; 28889 const cancelMessage = { 28890 id, 28891 type: "<cancel>", 28892 origin: location.origin, 28893 targetMapId: message.targetMapId, 28894 sourceMapId: this.mapId 28895 }; 28896 this.target.postMessage(cancelMessage); 28897 reject(new AbortError(abortController.signal.reason)); 28898 }, addEventDefaultOptions) : null; 28899 this.resolveRejects[id] = { 28900 resolve: (value) => { 28901 subscription?.unsubscribe(); 28902 resolve(value); 28903 }, 28904 reject: (reason) => { 28905 subscription?.unsubscribe(); 28906 reject(reason); 28907 } 28908 }; 28909 const buffers = []; 28910 const messageToPost = { 28911 ...message, 28912 id, 28913 sourceMapId: this.mapId, 28914 origin: location.origin, 28915 data: serialize(message.data, buffers) 28916 }; 28917 this.target.postMessage(messageToPost, { transfer: buffers }); 28918 }); 28919 } 28920 receive(message) { 28921 const data = message.data; 28922 const id = data.id; 28923 const SPECIAL_ORIGINS = [ 28924 "file://", 28925 "resource://android", 28926 "null" 28927 ]; 28928 const origins = [data.origin, location.origin]; 28929 const isSameOrigin = data.origin === location.origin; 28930 const hasSpecialOrigin = origins.some((origin) => SPECIAL_ORIGINS.includes(origin)); 28931 if (!isSameOrigin && !hasSpecialOrigin) return; 28932 if (data.targetMapId && this.mapId !== data.targetMapId) return; 28933 if (data.type === "<cancel>") { 28934 delete this.tasks[id]; 28935 const abortController = this.abortControllers[id]; 28936 delete this.abortControllers[id]; 28937 if (abortController) abortController.abort(); 28938 return; 28939 } 28940 if (isWorker(self) || data.mustQueue) { 28941 this.tasks[id] = data; 28942 this.taskQueue.push(id); 28943 this.invoker.trigger(); 28944 return; 28945 } 28946 this.processTask(id, data); 28947 } 28948 process() { 28949 if (this.taskQueue.length === 0) return; 28950 const id = this.taskQueue.shift(); 28951 const task = this.tasks[id]; 28952 delete this.tasks[id]; 28953 if (this.taskQueue.length > 0) this.invoker.trigger(); 28954 if (!task) return; 28955 this.processTask(id, task); 28956 } 28957 async processTask(id, task) { 28958 if (task.type === "<response>") { 28959 const resolveReject = this.resolveRejects[id]; 28960 delete this.resolveRejects[id]; 28961 if (!resolveReject) return; 28962 if (task.error) resolveReject.reject(ensureError(deserialize(task.error))); 28963 else resolveReject.resolve(deserialize(task.data)); 28964 return; 28965 } 28966 if (!this.messageHandlers[task.type]) { 28967 this.completeTask(id, null, null); 28968 return; 28969 } 28970 const params = deserialize(task.data); 28971 const abortController = new AbortController(); 28972 this.abortControllers[id] = abortController; 28973 try { 28974 const data = await this.messageHandlers[task.type](task.sourceMapId, params, abortController); 28975 this.completeTask(id, null, data); 28976 } catch (err) { 28977 this.completeTask(id, ensureError(err)); 28978 } 28979 } 28980 completeTask(id, err, data) { 28981 const buffers = []; 28982 delete this.abortControllers[id]; 28983 const responseMessage = { 28984 id, 28985 type: "<response>", 28986 sourceMapId: this.mapId, 28987 origin: location.origin, 28988 error: err ? serialize(err) : null, 28989 data: serialize(data, buffers) 28990 }; 28991 this.target.postMessage(responseMessage, { transfer: buffers }); 28992 } 28993 remove() { 28994 this.invoker.remove(); 28995 this.subscription.unsubscribe(); 28996 } 28997}; 28998//#endregion 28999//#region src/util/world_bounds.ts 29000/** 29001* Returns true if a given tile zoom (Z), X, and Y are in the bounds of the world. 29002* Zoom bounds are the minimum zoom (inclusive) through the maximum zoom (inclusive). 29003* X and Y bounds are 0 (inclusive) to their respective zoom-dependent maxima (exclusive). 29004* 29005* @param zoom - the tile zoom (Z) 29006* @param x - the tile X 29007* @param y - the tile Y 29008* @returns `true` if a given tile zoom, X, and Y are in the bounds of the world. 29009*/ 29010function isInBoundsForTileZoomXY(zoom, x, y) { 29011 return !(zoom < 0 || zoom > 25 || y < 0 || y >= Math.pow(2, zoom) || x < 0 || x >= Math.pow(2, zoom)); 29012} 29013/** 29014* Returns true if a given zoom and `LngLat` are in the bounds of the world. 29015* Does not wrap `LngLat` when checking if in bounds. 29016* Zoom bounds are the minimum zoom (inclusive) through the maximum zoom (inclusive). 29017* `LngLat` bounds are the mercator world's north-west corner (inclusive) to its south-east corner (exclusive). 29018* 29019* @param zoom - the tile zoom (Z) 29020* @param LngLat - the `LngLat` object containing the longitude and latitude 29021* @returns `true` if a given zoom and `LngLat` are in the bounds of the world. 29022*/ 29023function isInBoundsForZoomLngLat(zoom, lnglat) { 29024 const { x, y } = MercatorCoordinate.fromLngLat(lnglat); 29025 return !(zoom < 0 || zoom > 25 || y < 0 || y >= 1 || x < 0 || x >= 1); 29026} 29027//#endregion 29028//#region src/tile/tile_id.ts 29029/** 29030* A canonical way to define a tile ID 29031*/ 29032var CanonicalTileID = class { 29033 constructor(z, x, y) { 29034 if (!isInBoundsForTileZoomXY(z, x, y)) throw new Error(`x=${x}, y=${y}, z=${z} outside of bounds. 0<=x<${Math.pow(2, z)}, 0<=y<${Math.pow(2, z)} 0<=z<=25 `); 29035 this.z = z; 29036 this.x = x; 29037 this.y = y; 29038 this.key = calculateTileKey(0, z, z, x, y); 29039 } 29040 equals(id) { 29041 return this.z === id.z && this.x === id.x && this.y === id.y; 29042 } 29043 /** 29044 * given a list of urls, choose a url template and return a tile URL 29045 */ 29046 url(urls, pixelRatio, scheme) { 29047 const bbox = getTileBBox(this.x, this.y, this.z); 29048 const quadkey = getQuadkey(this.z, this.x, this.y); 29049 return urls[(this.x + this.y) % urls.length].replace(/{prefix}/g, (this.x % 16).toString(16) + (this.y % 16).toString(16)).replace(/{z}/g, String(this.z)).replace(/{x}/g, String(this.x)).replace(/{y}/g, String(scheme === "tms" ? Math.pow(2, this.z) - this.y - 1 : this.y)).replace(/{ratio}/g, pixelRatio > 1 ? "@2x" : "").replace(/{quadkey}/g, quadkey).replace(/{bbox-epsg-3857}/g, bbox); 29050 } 29051 isChildOf(parent) { 29052 const dz = this.z - parent.z; 29053 return dz > 0 && parent.x === this.x >> dz && parent.y === this.y >> dz; 29054 } 29055 getTilePoint(coord) { 29056 const tilesAtZoom = Math.pow(2, this.z); 29057 return new Point((coord.x * tilesAtZoom - this.x) * EXTENT$1, (coord.y * tilesAtZoom - this.y) * EXTENT$1); 29058 } 29059 toString() { 29060 return `${this.z}/${this.x}/${this.y}`; 29061 } 29062}; 29063/** 29064* @internal 29065* An unwrapped tile identifier 29066*/ 29067var UnwrappedTileID = class { 29068 constructor(wrap, canonical) { 29069 this.wrap = wrap; 29070 this.canonical = canonical; 29071 this.key = calculateTileKey(wrap, canonical.z, canonical.z, canonical.x, canonical.y); 29072 } 29073}; 29074/** 29075* An overscaled tile identifier 29076*/ 29077var OverscaledTileID = class OverscaledTileID { 29078 constructor(overscaledZ, wrap, z, x, y) { 29079 this.terrainRttPosMatrix32f = null; 29080 if (overscaledZ < z) throw new Error(`overscaledZ should be >= z; overscaledZ = ${overscaledZ}; z = ${z}`); 29081 this.overscaledZ = overscaledZ; 29082 this.wrap = wrap; 29083 this.canonical = new CanonicalTileID(z, +x, +y); 29084 this.key = calculateTileKey(wrap, overscaledZ, z, x, y); 29085 } 29086 clone() { 29087 return new OverscaledTileID(this.overscaledZ, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y); 29088 } 29089 equals(id) { 29090 return this.overscaledZ === id.overscaledZ && this.wrap === id.wrap && this.canonical.equals(id.canonical); 29091 } 29092 /** 29093 * Returns a new `OverscaledTileID` representing the tile at the target zoom level. 29094 * When targetZ is greater than the current canonical z, the canonical coordinates are unchanged. 29095 * When targetZ is less than the current canonical z, the canonical coordinates are updated. 29096 * @param targetZ - the zoom level to scale to. Must be less than or equal to this.overscaledZ 29097 * @returns a new OverscaledTileID representing the tile at the target zoom level 29098 * @throws if targetZ is greater than this.overscaledZ 29099 */ 29100 scaledTo(targetZ) { 29101 if (targetZ > this.overscaledZ) throw new Error(`targetZ > this.overscaledZ; targetZ = ${targetZ}; overscaledZ = ${this.overscaledZ}`); 29102 const zDifference = this.canonical.z - targetZ; 29103 if (targetZ > this.canonical.z) return new OverscaledTileID(targetZ, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y); 29104 else return new OverscaledTileID(targetZ, this.wrap, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference); 29105 } 29106 isOverscaled() { 29107 return this.overscaledZ > this.canonical.z; 29108 } 29109 calculateScaledKey(targetZ, withWrap) { 29110 if (targetZ > this.overscaledZ) throw new Error(`targetZ > this.overscaledZ; targetZ = ${targetZ}; overscaledZ = ${this.overscaledZ}`); 29111 const zDifference = this.canonical.z - targetZ; 29112 if (targetZ > this.canonical.z) return calculateTileKey(this.wrap * +withWrap, targetZ, this.canonical.z, this.canonical.x, this.canonical.y); 29113 else return calculateTileKey(this.wrap * +withWrap, targetZ, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference); 29114 } 29115 isChildOf(parent) { 29116 if (parent.wrap !== this.wrap) return false; 29117 if (this.overscaledZ - parent.overscaledZ <= 0) return false; 29118 if (parent.overscaledZ === 0) return this.overscaledZ > 0; 29119 const dz = this.canonical.z - parent.canonical.z; 29120 if (dz < 0) return false; 29121 return parent.canonical.x === this.canonical.x >> dz && parent.canonical.y === this.canonical.y >> dz; 29122 } 29123 children(sourceMaxZoom) { 29124 if (this.overscaledZ >= sourceMaxZoom) return [new OverscaledTileID(this.overscaledZ + 1, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y)]; 29125 const z = this.canonical.z + 1; 29126 const x = this.canonical.x * 2; 29127 const y = this.canonical.y * 2; 29128 return [ 29129 new OverscaledTileID(z, this.wrap, z, x, y), 29130 new OverscaledTileID(z, this.wrap, z, x + 1, y), 29131 new OverscaledTileID(z, this.wrap, z, x, y + 1), 29132 new OverscaledTileID(z, this.wrap, z, x + 1, y + 1) 29133 ]; 29134 } 29135 isLessThan(rhs) { 29136 if (this.wrap < rhs.wrap) return true; 29137 if (this.wrap > rhs.wrap) return false; 29138 if (this.overscaledZ < rhs.overscaledZ) return true; 29139 if (this.overscaledZ > rhs.overscaledZ) return false; 29140 if (this.canonical.x < rhs.canonical.x) return true; 29141 if (this.canonical.x > rhs.canonical.x) return false; 29142 return this.canonical.y < rhs.canonical.y; 29143 } 29144 wrapped() { 29145 return new OverscaledTileID(this.overscaledZ, 0, this.canonical.z, this.canonical.x, this.canonical.y); 29146 } 29147 unwrapTo(wrap) { 29148 return new OverscaledTileID(this.overscaledZ, wrap, this.canonical.z, this.canonical.x, this.canonical.y); 29149 } 29150 overscaleFactor() { 29151 return Math.pow(2, this.overscaledZ - this.canonical.z); 29152 } 29153 toUnwrapped() { 29154 return new UnwrappedTileID(this.wrap, this.canonical); 29155 } 29156 toString() { 29157 return `${this.overscaledZ}/${this.canonical.x}/${this.canonical.y}`; 29158 } 29159 getTilePoint(coord) { 29160 return this.canonical.getTilePoint(new MercatorCoordinate(coord.x - this.wrap, coord.y)); 29161 } 29162 /** 29163 * Maps tile-local coordinates that may fall outside the `[0, extent)` range 29164 * to the correct neighbor tile and the corresponding in-tile position. 29165 * 29166 * Coordinates can exceed tile bounds when geometry (e.g. symbol labels along 29167 * lines) extends across tile edges. This method resolves such coordinates to 29168 * the appropriate adjacent tile, wrapping horizontally across world boundaries 29169 * and returning `null` when the target falls beyond the polar tile-grid limits. 29170 * 29171 * When the coordinates are already in bounds, the original tile ID is returned. 29172 * 29173 * @param x - x coordinate relative to this tile, may be outside `[0, extent)` 29174 * @param y - y coordinate relative to this tile, may be outside `[0, extent)` 29175 * @param extent - tile coordinate extent, default {@link EXTENT} 29176 * @returns the resolved tile ID and in-tile coordinates, or `null` if the 29177 * target is beyond the tile grid (e.g. past the poles) 29178 */ 29179 normalizeCoordinates(x, y, extent = EXTENT$1) { 29180 if (x >= 0 && x < extent && y >= 0 && y < extent) return { 29181 tileID: this, 29182 x, 29183 y 29184 }; 29185 const tileOffsetX = Math.floor(x / extent); 29186 const tileOffsetY = Math.floor(y / extent); 29187 const newX = x - tileOffsetX * extent; 29188 const newY = y - tileOffsetY * extent; 29189 const z = this.canonical.z; 29190 const dim = 1 << z; 29191 const newCanonicalY = this.canonical.y + tileOffsetY; 29192 if (newCanonicalY < 0 || newCanonicalY >= dim) return null; 29193 let newCanonicalX = this.canonical.x + tileOffsetX; 29194 let newWrap = this.wrap; 29195 if (newCanonicalX < 0) { 29196 newWrap -= Math.ceil(-newCanonicalX / dim); 29197 newCanonicalX = (newCanonicalX % dim + dim) % dim; 29198 } else if (newCanonicalX >= dim) { 29199 newWrap += Math.floor(newCanonicalX / dim); 29200 newCanonicalX = newCanonicalX % dim; 29201 } 29202 return { 29203 tileID: new OverscaledTileID(this.overscaledZ, newWrap, z, newCanonicalX, newCanonicalY), 29204 x: newX, 29205 y: newY 29206 }; 29207 } 29208}; 29209function calculateTileKey(wrap, overscaledZ, z, x, y) { 29210 wrap *= 2; 29211 if (wrap < 0) wrap = wrap * -1 - 1; 29212 const dim = 1 << z; 29213 return (dim * dim * wrap + dim * y + x).toString(36) + z.toString(36) + overscaledZ.toString(36); 29214} 29215const EPSG3857_HALF_CIRCUMFERENCE = Math.PI * 6378137; 29216/** 29217* Builds the `{bbox-epsg-3857}` token used in WMS tile URLs: the tile's bounding 29218* box in EPSG:3857 meters as a `minX,minY,maxX,maxY` string. 29219* 29220* Inlined from the archived \@mapbox/whoots-js (ISC, Copyright (c) 2017 Mapbox). 29221*/ 29222function getTileBBox(x, y, z) { 29223 y = Math.pow(2, z) - y - 1; 29224 const min = getEpsg3857Coords(x * 256, y * 256, z); 29225 const max = getEpsg3857Coords((x + 1) * 256, (y + 1) * 256, z); 29226 return `${min[0]},${min[1]},${max[0]},${max[1]}`; 29227} 29228/** Projects tile pixel coordinates to EPSG:3857 meters. */ 29229function getEpsg3857Coords(x, y, z) { 29230 const resolution = 2 * EPSG3857_HALF_CIRCUMFERENCE / 256 / Math.pow(2, z); 29231 return [x * resolution - EPSG3857_HALF_CIRCUMFERENCE, y * resolution - EPSG3857_HALF_CIRCUMFERENCE]; 29232} 29233function getQuadkey(z, x, y) { 29234 let quadkey = ""; 29235 for (let i = z; i > 0; i--) { 29236 const mask = 1 << i - 1; 29237 quadkey += (x & mask ? 1 : 0) + (y & mask ? 2 : 0); 29238 } 29239 return quadkey; 29240} 29241function compareTileId(a, b) { 29242 const aWrap = Math.abs(a.wrap * 2) - +(a.wrap < 0); 29243 const bWrap = Math.abs(b.wrap * 2) - +(b.wrap < 0); 29244 return a.overscaledZ - b.overscaledZ || bWrap - aWrap || b.canonical.y - a.canonical.y || b.canonical.x - a.canonical.x; 29245} 29246register("CanonicalTileID", CanonicalTileID); 29247register("OverscaledTileID", OverscaledTileID, { omit: ["terrainRttPosMatrix32f"] }); 29248//#endregion 29249//#region node_modules/@maplibre/vt-pbf/dist/index.es.js 29250var FeatureWrapper = class { 29251 constructor(feature, extent) { 29252 this.feature = feature; 29253 this.type = feature.type; 29254 this.properties = feature.tags ? feature.tags : {}; 29255 this.extent = extent; 29256 if ("id" in feature) { 29257 if (typeof feature.id === "string") this.id = parseInt(feature.id, 10); 29258 else if (typeof feature.id === "number" && !isNaN(feature.id)) this.id = feature.id; 29259 } 29260 } 29261 loadGeometry() { 29262 const geometry = []; 29263 const rawGeo = this.feature.type === 1 ? [this.feature.geometry] : this.feature.geometry; 29264 for (const ring of rawGeo) { 29265 const newRing = []; 29266 for (const point of ring) newRing.push(new Point(point[0], point[1])); 29267 geometry.push(newRing); 29268 } 29269 return geometry; 29270 } 29271}; 29272const GEOJSON_TILE_LAYER_NAME = "_geojsonTileLayer"; 29273var GeoJSONWrapper = class { 29274 constructor(features, options) { 29275 this.layers = { [GEOJSON_TILE_LAYER_NAME]: this }; 29276 this.name = GEOJSON_TILE_LAYER_NAME; 29277 this.version = options ? options.version : 1; 29278 this.extent = options ? options.extent : 4096; 29279 this.length = features.length; 29280 this.features = features; 29281 } 29282 feature(i) { 29283 return new FeatureWrapper(this.features[i], this.extent); 29284 } 29285}; 29286/** 29287* Serialize a vector-tile-js-created tile to pbf 29288* 29289* @param tile - the tile to serialize 29290* @param jsonPrefix - a string prefix to prepend to JSON-stringified non-primitive property values, used to distinguish them from regular string values when parsing the tile later. Default is "". 29291* @return uncompressed, pbf-serialized tile data 29292*/ 29293function fromVectorTileJs(tile, jsonPrefix = "") { 29294 const out = new PbfWriter(); 29295 writeTile(tile, out, jsonPrefix); 29296 return out.finish(); 29297} 29298function writeTile(tile, pbf, jsonPrefix = "") { 29299 for (const key in tile.layers) pbf.writeMessage(3, (layer, pbf) => writeLayer(layer, pbf, jsonPrefix), tile.layers[key]); 29300} 29301function writeLayer(layer, pbf, jsonPrefix = "") { 29302 pbf.writeVarintField(15, layer.version || 1); 29303 pbf.writeStringField(1, layer.name || ""); 29304 pbf.writeVarintField(5, layer.extent || 4096); 29305 const context = { 29306 jsonPrefix, 29307 keys: [], 29308 values: [], 29309 keycache: {}, 29310 valuecache: {} 29311 }; 29312 for (let i = 0; i < layer.length; i++) { 29313 context.feature = layer.feature(i); 29314 pbf.writeMessage(2, writeFeature, context); 29315 } 29316 const keys = context.keys; 29317 for (const key of keys) pbf.writeStringField(3, key); 29318 const values = context.values; 29319 for (const value of values) pbf.writeMessage(4, writeValue, value); 29320} 29321function writeFeature(context, pbf) { 29322 if (!context.feature) return; 29323 const feature = context.feature; 29324 if (feature.id !== void 0) pbf.writeVarintField(1, feature.id); 29325 pbf.writeMessage(2, writeProperties, context); 29326 pbf.writeVarintField(3, feature.type); 29327 pbf.writeMessage(4, writeGeometry, feature); 29328} 29329function writeProperties(context, pbf) { 29330 for (const key in context.feature?.properties) { 29331 let value = context.feature.properties[key]; 29332 let keyIndex = context.keycache[key]; 29333 if (value == null) continue; 29334 if (typeof keyIndex === "undefined") { 29335 context.keys.push(key); 29336 keyIndex = context.keys.length - 1; 29337 context.keycache[key] = keyIndex; 29338 } 29339 pbf.writeVarint(keyIndex); 29340 if (typeof value !== "string" && typeof value !== "boolean" && typeof value !== "number") value = context.jsonPrefix + JSON.stringify(value); 29341 const valueKey = typeof value + ":" + value; 29342 let valueIndex = context.valuecache[valueKey]; 29343 if (typeof valueIndex === "undefined") { 29344 context.values.push(value); 29345 valueIndex = context.values.length - 1; 29346 context.valuecache[valueKey] = valueIndex; 29347 } 29348 pbf.writeVarint(valueIndex); 29349 } 29350} 29351function command(cmd, length) { 29352 return (length << 3) + (cmd & 7); 29353} 29354function zigzag(num) { 29355 return num << 1 ^ num >> 31; 29356} 29357function writeGeometry(feature, pbf) { 29358 const geometry = feature.loadGeometry(); 29359 const type = feature.type; 29360 let x = 0; 29361 let y = 0; 29362 for (const ring of geometry) { 29363 let count = 1; 29364 if (type === 1) count = ring.length; 29365 pbf.writeVarint(command(1, count)); 29366 const lineCount = type === 3 ? ring.length - 1 : ring.length; 29367 for (let i = 0; i < lineCount; i++) { 29368 if (i === 1 && type !== 1) pbf.writeVarint(command(2, lineCount - 1)); 29369 const dx = ring[i].x - x; 29370 const dy = ring[i].y - y; 29371 pbf.writeVarint(zigzag(dx)); 29372 pbf.writeVarint(zigzag(dy)); 29373 x += dx; 29374 y += dy; 29375 } 29376 if (feature.type === 3) pbf.writeVarint(command(7, 1)); 29377 } 29378} 29379function writeValue(value, pbf) { 29380 const type = typeof value; 29381 if (type === "string") pbf.writeStringField(1, value); 29382 else if (type === "boolean") pbf.writeBooleanField(7, value); 29383 else if (type === "number") if (value % 1 !== 0) pbf.writeDoubleField(3, value); 29384 else if (value < 0) pbf.writeSVarintField(6, value); 29385 else pbf.writeVarintField(5, value); 29386} 29387//#endregion 29388//#region src/util/dictionary_coder.ts 29389var DictionaryCoder = class { 29390 constructor(strings) { 29391 this._stringToNumber = {}; 29392 this._numberToString = []; 29393 for (let i = 0; i < strings.length; i++) { 29394 const string = strings[i]; 29395 this._stringToNumber[string] = i; 29396 this._numberToString[i] = string; 29397 } 29398 } 29399 encode(string) { 29400 return this._stringToNumber[string]; 29401 } 29402 decode(n) { 29403 if (n >= this._numberToString.length) throw new Error(`Out of bounds. Index requested n=${n} can't be >= this._numberToString.length ${this._numberToString.length}`); 29404 return this._numberToString[n]; 29405 } 29406}; 29407//#endregion 29408//#region src/util/vectortile_to_geojson.ts 29409/** 29410* A geojson feature 29411*/ 29412var GeoJSONFeature = class { 29413 constructor(vectorTileFeature, z, x, y, id) { 29414 this.type = "Feature"; 29415 this._vectorTileFeature = vectorTileFeature; 29416 this._x = x; 29417 this._y = y; 29418 this._z = z; 29419 for (const key in vectorTileFeature.properties) { 29420 if (typeof vectorTileFeature.properties[key] !== "string" || !vectorTileFeature.properties[key].startsWith("__$json__:")) continue; 29421 vectorTileFeature.properties[key] = JSON.parse(vectorTileFeature.properties[key].slice(10)); 29422 } 29423 this.properties = vectorTileFeature.properties; 29424 this.id = id; 29425 } 29426 projectPoint(p, x0, y0, size) { 29427 return [(p.x + x0) * 360 / size - 180, 360 / Math.PI * Math.atan(Math.exp((1 - (p.y + y0) * 2 / size) * Math.PI)) - 90]; 29428 } 29429 projectLine(line, x0, y0, size) { 29430 return line.map((p) => this.projectPoint(p, x0, y0, size)); 29431 } 29432 get geometry() { 29433 if (this._geometry) return this._geometry; 29434 const feature = this._vectorTileFeature; 29435 const size = feature.extent * Math.pow(2, this._z); 29436 const x0 = feature.extent * this._x; 29437 const y0 = feature.extent * this._y; 29438 const vtCoords = feature.loadGeometry(); 29439 switch (feature.type) { 29440 case 1: { 29441 const points = []; 29442 for (const line of vtCoords) points.push(line[0]); 29443 const coordinates = this.projectLine(points, x0, y0, size); 29444 this._geometry = points.length === 1 ? { 29445 type: "Point", 29446 coordinates: coordinates[0] 29447 } : { 29448 type: "MultiPoint", 29449 coordinates 29450 }; 29451 break; 29452 } 29453 case 2: { 29454 const coordinates = vtCoords.map((coord) => this.projectLine(coord, x0, y0, size)); 29455 this._geometry = coordinates.length === 1 ? { 29456 type: "LineString", 29457 coordinates: coordinates[0] 29458 } : { 29459 type: "MultiLineString", 29460 coordinates 29461 }; 29462 break; 29463 } 29464 case 3: { 29465 const polygons = classifyRings(vtCoords); 29466 const coordinates = []; 29467 for (const polygon of polygons) coordinates.push(polygon.map((coord) => this.projectLine(coord, x0, y0, size))); 29468 this._geometry = coordinates.length === 1 ? { 29469 type: "Polygon", 29470 coordinates: coordinates[0] 29471 } : { 29472 type: "MultiPolygon", 29473 coordinates 29474 }; 29475 break; 29476 } 29477 default: throw new Error(`unknown feature type: ${feature.type}`); 29478 } 29479 return this._geometry; 29480 } 29481 set geometry(g) { 29482 this._geometry = g; 29483 } 29484 toJSON() { 29485 const json = { geometry: this.geometry }; 29486 for (const i in this) { 29487 if (i === "_geometry" || i === "_vectorTileFeature" || i === "_x" || i === "_y" || i === "_z") continue; 29488 json[i] = this[i]; 29489 } 29490 return json; 29491 } 29492}; 29493//#endregion 29494//#region node_modules/@maplibre/mlt/dist/vector/vector.js 29495var Vector = class { 29496 constructor(_name, dataBuffer, sizeOrNullabilityBuffer) { 29497 this._name = _name; 29498 this.dataBuffer = dataBuffer; 29499 if (typeof sizeOrNullabilityBuffer === "number") this._size = sizeOrNullabilityBuffer; 29500 else { 29501 this.nullabilityBuffer = sizeOrNullabilityBuffer; 29502 this._size = sizeOrNullabilityBuffer.size(); 29503 } 29504 } 29505 getValue(index) { 29506 return this.nullabilityBuffer && !this.nullabilityBuffer.get(index) ? null : this.getValueFromBuffer(index); 29507 } 29508 has(index) { 29509 return this.nullabilityBuffer?.get(index) || !this.nullabilityBuffer; 29510 } 29511 get name() { 29512 return this._name; 29513 } 29514 get size() { 29515 return this._size; 29516 } 29517}; 29518//#endregion 29519//#region node_modules/@maplibre/mlt/dist/vector/fixedSizeVector.js 29520var FixedSizeVector = class extends Vector {}; 29521//#endregion 29522//#region node_modules/@maplibre/mlt/dist/vector/flat/int32FlatVector.js 29523var Int32FlatVector = class extends FixedSizeVector { 29524 getValueFromBuffer(index) { 29525 return this.dataBuffer[index]; 29526 } 29527}; 29528//#endregion 29529//#region node_modules/@maplibre/mlt/dist/vector/flat/doubleFlatVector.js 29530var DoubleFlatVector = class extends FixedSizeVector { 29531 getValueFromBuffer(index) { 29532 return this.dataBuffer[index]; 29533 } 29534}; 29535//#endregion 29536//#region node_modules/@maplibre/mlt/dist/vector/sequence/sequenceVector.js 29537var SequenceVector = class extends Vector { 29538 constructor(name, baseValueBuffer, delta, size) { 29539 super(name, baseValueBuffer, size); 29540 this.delta = delta; 29541 } 29542}; 29543//#endregion 29544//#region node_modules/@maplibre/mlt/dist/vector/sequence/int32SequenceVector.js 29545var Int32SequenceVector = class extends SequenceVector { 29546 constructor(name, baseValue, delta, size, isSigned) { 29547 super(name, isSigned ? Int32Array.of(baseValue) : Uint32Array.of(baseValue), delta, size); 29548 } 29549 getValueFromBuffer(index) { 29550 return this.dataBuffer[0] + index * this.delta; 29551 } 29552}; 29553//#endregion 29554//#region node_modules/@maplibre/mlt/dist/vector/constant/int32ConstVector.js 29555var Int32ConstVector = class extends Vector { 29556 constructor(name, value, sizeOrNullabilityBuffer, isSigned) { 29557 super(name, isSigned ? Int32Array.of(value) : Uint32Array.of(value), sizeOrNullabilityBuffer); 29558 } 29559 getValueFromBuffer(_index) { 29560 return this.dataBuffer[0]; 29561 } 29562}; 29563//#endregion 29564//#region node_modules/@maplibre/mlt/dist/vector/featureTable.js 29565var FeatureTable = class { 29566 constructor(_name, _geometryVector, _idVector, _propertyVectors, _extent = 4096) { 29567 this._name = _name; 29568 this._geometryVector = _geometryVector; 29569 this._idVector = _idVector; 29570 this._propertyVectors = _propertyVectors; 29571 this._extent = _extent; 29572 if (_name.length === 0) throw new Error("Missing layer name"); 29573 } 29574 get name() { 29575 return this._name; 29576 } 29577 get idVector() { 29578 return this._idVector; 29579 } 29580 get geometryVector() { 29581 return this._geometryVector; 29582 } 29583 get propertyVectors() { 29584 return this._propertyVectors ?? []; 29585 } 29586 getPropertyVector(name) { 29587 if (!this.propertyVectorsMap) this.propertyVectorsMap = new Map(this.propertyVectors.map((vector) => [vector.name, vector])); 29588 return this.propertyVectorsMap.get(name); 29589 } 29590 get numFeatures() { 29591 return this.geometryVector.numGeometries; 29592 } 29593 get extent() { 29594 return this._extent; 29595 } 29596 /** 29597 * Returns all features as an array 29598 */ 29599 getFeatures() { 29600 const features = []; 29601 const geometries = this.geometryVector.getGeometries(); 29602 for (let i = 0; i < this.numFeatures; i++) { 29603 let id; 29604 if (this.idVector) { 29605 const idValue = this.idVector.getValue(i); 29606 if (idValue !== null) id = this.containsMaxSafeIntegerValues(this.idVector) ? Number(idValue) : idValue; 29607 } 29608 const geometry = { 29609 coordinates: geometries[i], 29610 type: this.geometryVector.geometryType(i) 29611 }; 29612 const properties = {}; 29613 for (const propertyColumn of this.propertyVectors) { 29614 if (!propertyColumn) continue; 29615 const columnName = propertyColumn.name; 29616 const propertyValue = propertyColumn.getValue(i); 29617 if (propertyValue !== null) properties[columnName] = propertyValue; 29618 } 29619 features.push({ 29620 id, 29621 geometry, 29622 properties 29623 }); 29624 } 29625 return features; 29626 } 29627 containsMaxSafeIntegerValues(idVector) { 29628 return idVector instanceof Int32FlatVector || idVector instanceof Int32ConstVector || idVector instanceof Int32SequenceVector || idVector instanceof DoubleFlatVector; 29629 } 29630}; 29631//#endregion 29632//#region node_modules/@maplibre/mlt/dist/metadata/tileset/tilesetMetadata.js 29633const ColumnScope = { 29634 FEATURE: 0, 29635 VERTEX: 1 29636}; 29637const ScalarType = { 29638 BOOLEAN: 0, 29639 INT_8: 1, 29640 UINT_8: 2, 29641 INT_32: 3, 29642 UINT_32: 4, 29643 INT_64: 5, 29644 UINT_64: 6, 29645 FLOAT: 7, 29646 DOUBLE: 8, 29647 STRING: 9 29648}; 29649const ComplexType = { 29650 GEOMETRY: 0, 29651 STRUCT: 1, 29652 MAP: 2 29653}; 29654const LogicalScalarType = { ID: 0 }; 29655//#endregion 29656//#region node_modules/@maplibre/mlt/dist/decoding/intWrapper.js 29657var IntWrapper = class { 29658 constructor(value) { 29659 this.value = value; 29660 } 29661 get() { 29662 return this.value; 29663 } 29664 set(v) { 29665 this.value = v; 29666 } 29667 increment() { 29668 return this.value++; 29669 } 29670 add(v) { 29671 this.value += v; 29672 } 29673}; 29674//#endregion 29675//#region node_modules/@maplibre/mlt/dist/metadata/tile/logicalLevelTechnique.js 29676var LogicalLevelTechnique; 29677(function(LogicalLevelTechnique) { 29678 LogicalLevelTechnique["NONE"] = "NONE"; 29679 LogicalLevelTechnique["DELTA"] = "DELTA"; 29680 LogicalLevelTechnique["COMPONENTWISE_DELTA"] = "COMPONENTWISE_DELTA"; 29681 LogicalLevelTechnique["RLE"] = "RLE"; 29682 LogicalLevelTechnique["MORTON"] = "MORTON"; 29683})(LogicalLevelTechnique || (LogicalLevelTechnique = {})); 29684//#endregion 29685//#region node_modules/@maplibre/mlt/dist/metadata/tile/physicalLevelTechnique.js 29686var PhysicalLevelTechnique; 29687(function(PhysicalLevelTechnique) { 29688 PhysicalLevelTechnique["NONE"] = "NONE"; 29689 /** 29690 * Preferred option, tends to produce the best compression ratio and decoding performance. 29691 * But currently only limited to 32 bit integer. 29692 */ 29693 PhysicalLevelTechnique["FAST_PFOR"] = "FAST_PFOR"; 29694 /** 29695 * Can produce better results in combination with a heavyweight compression scheme like Gzip. 29696 * Simple compression scheme where the decoder are easier to implement compared to FastPfor. 29697 */ 29698 PhysicalLevelTechnique["VARINT"] = "VARINT"; 29699})(PhysicalLevelTechnique || (PhysicalLevelTechnique = {})); 29700//#endregion 29701//#region node_modules/@maplibre/mlt/dist/decoding/fastPforShared.js 29702/** 29703* Bit masks for each bitwidth 0-32. 29704* DO NOT MUTATE - this is a shared constant. 29705*/ 29706const masks = /* @__PURE__ */ new Uint32Array(33); 29707masks[0] = 0; 29708for (let bitWidth = 1; bitWidth <= 32; bitWidth++) masks[bitWidth] = bitWidth === 32 ? 4294967295 : 4294967295 >>> 32 - bitWidth; 29709const MASKS = masks; 29710const DEFAULT_PAGE_SIZE = 65536; 29711function greatestMultiple(value, factor) { 29712 return value - value % factor; 29713} 29714function roundUpToMultipleOf32(value) { 29715 return greatestMultiple(value + 31, 32); 29716} 29717function normalizePageSize(pageSize) { 29718 if (!Number.isFinite(pageSize) || pageSize <= 0) return DEFAULT_PAGE_SIZE; 29719 const aligned = greatestMultiple(Math.floor(pageSize), 256); 29720 return aligned === 0 ? 256 : aligned; 29721} 29722function bswap32(value) { 29723 const x = value >>> 0; 29724 return ((x & 255) << 24 | (x & 65280) << 8 | x >>> 8 & 65280 | x >>> 24 & 255) >>> 0; 29725} 29726function fastUnpack32_2(inValues, inPos, out, outPos) { 29727 let op = outPos; 29728 const in0 = inValues[inPos] >>> 0; 29729 const in1 = inValues[inPos + 1] >>> 0; 29730 out[op++] = in0 >>> 0 & 3; 29731 out[op++] = in0 >>> 2 & 3; 29732 out[op++] = in0 >>> 4 & 3; 29733 out[op++] = in0 >>> 6 & 3; 29734 out[op++] = in0 >>> 8 & 3; 29735 out[op++] = in0 >>> 10 & 3; 29736 out[op++] = in0 >>> 12 & 3; 29737 out[op++] = in0 >>> 14 & 3; 29738 out[op++] = in0 >>> 16 & 3; 29739 out[op++] = in0 >>> 18 & 3; 29740 out[op++] = in0 >>> 20 & 3; 29741 out[op++] = in0 >>> 22 & 3; 29742 out[op++] = in0 >>> 24 & 3; 29743 out[op++] = in0 >>> 26 & 3; 29744 out[op++] = in0 >>> 28 & 3; 29745 out[op++] = in0 >>> 30 & 3; 29746 out[op++] = in1 >>> 0 & 3; 29747 out[op++] = in1 >>> 2 & 3; 29748 out[op++] = in1 >>> 4 & 3; 29749 out[op++] = in1 >>> 6 & 3; 29750 out[op++] = in1 >>> 8 & 3; 29751 out[op++] = in1 >>> 10 & 3; 29752 out[op++] = in1 >>> 12 & 3; 29753 out[op++] = in1 >>> 14 & 3; 29754 out[op++] = in1 >>> 16 & 3; 29755 out[op++] = in1 >>> 18 & 3; 29756 out[op++] = in1 >>> 20 & 3; 29757 out[op++] = in1 >>> 22 & 3; 29758 out[op++] = in1 >>> 24 & 3; 29759 out[op++] = in1 >>> 26 & 3; 29760 out[op++] = in1 >>> 28 & 3; 29761 out[op] = in1 >>> 30 & 3; 29762} 29763function fastUnpack32_3(inValues, inPos, out, outPos) { 29764 let op = outPos; 29765 const in0 = inValues[inPos] >>> 0; 29766 const in1 = inValues[inPos + 1] >>> 0; 29767 const in2 = inValues[inPos + 2] >>> 0; 29768 out[op++] = in0 >>> 0 & 7; 29769 out[op++] = in0 >>> 3 & 7; 29770 out[op++] = in0 >>> 6 & 7; 29771 out[op++] = in0 >>> 9 & 7; 29772 out[op++] = in0 >>> 12 & 7; 29773 out[op++] = in0 >>> 15 & 7; 29774 out[op++] = in0 >>> 18 & 7; 29775 out[op++] = in0 >>> 21 & 7; 29776 out[op++] = in0 >>> 24 & 7; 29777 out[op++] = in0 >>> 27 & 7; 29778 out[op++] = (in0 >>> 30 | (in1 & 1) << 2) & 7; 29779 out[op++] = in1 >>> 1 & 7; 29780 out[op++] = in1 >>> 4 & 7; 29781 out[op++] = in1 >>> 7 & 7; 29782 out[op++] = in1 >>> 10 & 7; 29783 out[op++] = in1 >>> 13 & 7; 29784 out[op++] = in1 >>> 16 & 7; 29785 out[op++] = in1 >>> 19 & 7; 29786 out[op++] = in1 >>> 22 & 7; 29787 out[op++] = in1 >>> 25 & 7; 29788 out[op++] = in1 >>> 28 & 7; 29789 out[op++] = (in1 >>> 31 | (in2 & 3) << 1) & 7; 29790 out[op++] = in2 >>> 2 & 7; 29791 out[op++] = in2 >>> 5 & 7; 29792 out[op++] = in2 >>> 8 & 7; 29793 out[op++] = in2 >>> 11 & 7; 29794 out[op++] = in2 >>> 14 & 7; 29795 out[op++] = in2 >>> 17 & 7; 29796 out[op++] = in2 >>> 20 & 7; 29797 out[op++] = in2 >>> 23 & 7; 29798 out[op++] = in2 >>> 26 & 7; 29799 out[op] = in2 >>> 29 & 7; 29800} 29801function fastUnpack32_4(inValues, inPos, out, outPos) { 29802 let op = outPos; 29803 const in0 = inValues[inPos] >>> 0; 29804 const in1 = inValues[inPos + 1] >>> 0; 29805 const in2 = inValues[inPos + 2] >>> 0; 29806 const in3 = inValues[inPos + 3] >>> 0; 29807 out[op++] = in0 >>> 0 & 15; 29808 out[op++] = in0 >>> 4 & 15; 29809 out[op++] = in0 >>> 8 & 15; 29810 out[op++] = in0 >>> 12 & 15; 29811 out[op++] = in0 >>> 16 & 15; 29812 out[op++] = in0 >>> 20 & 15; 29813 out[op++] = in0 >>> 24 & 15; 29814 out[op++] = in0 >>> 28 & 15; 29815 out[op++] = in1 >>> 0 & 15; 29816 out[op++] = in1 >>> 4 & 15; 29817 out[op++] = in1 >>> 8 & 15; 29818 out[op++] = in1 >>> 12 & 15; 29819 out[op++] = in1 >>> 16 & 15; 29820 out[op++] = in1 >>> 20 & 15; 29821 out[op++] = in1 >>> 24 & 15; 29822 out[op++] = in1 >>> 28 & 15; 29823 out[op++] = in2 >>> 0 & 15; 29824 out[op++] = in2 >>> 4 & 15; 29825 out[op++] = in2 >>> 8 & 15; 29826 out[op++] = in2 >>> 12 & 15; 29827 out[op++] = in2 >>> 16 & 15; 29828 out[op++] = in2 >>> 20 & 15; 29829 out[op++] = in2 >>> 24 & 15; 29830 out[op++] = in2 >>> 28 & 15; 29831 out[op++] = in3 >>> 0 & 15; 29832 out[op++] = in3 >>> 4 & 15; 29833 out[op++] = in3 >>> 8 & 15; 29834 out[op++] = in3 >>> 12 & 15; 29835 out[op++] = in3 >>> 16 & 15; 29836 out[op++] = in3 >>> 20 & 15; 29837 out[op++] = in3 >>> 24 & 15; 29838 out[op] = in3 >>> 28 & 15; 29839} 29840function fastUnpack32_5(inValues, inPos, out, outPos) { 29841 let op = outPos; 29842 const in0 = inValues[inPos] >>> 0; 29843 const in1 = inValues[inPos + 1] >>> 0; 29844 const in2 = inValues[inPos + 2] >>> 0; 29845 const in3 = inValues[inPos + 3] >>> 0; 29846 const in4 = inValues[inPos + 4] >>> 0; 29847 out[op++] = in0 >>> 0 & 31; 29848 out[op++] = in0 >>> 5 & 31; 29849 out[op++] = in0 >>> 10 & 31; 29850 out[op++] = in0 >>> 15 & 31; 29851 out[op++] = in0 >>> 20 & 31; 29852 out[op++] = in0 >>> 25 & 31; 29853 out[op++] = (in0 >>> 30 | (in1 & 7) << 2) & 31; 29854 out[op++] = in1 >>> 3 & 31; 29855 out[op++] = in1 >>> 8 & 31; 29856 out[op++] = in1 >>> 13 & 31; 29857 out[op++] = in1 >>> 18 & 31; 29858 out[op++] = in1 >>> 23 & 31; 29859 out[op++] = (in1 >>> 28 | (in2 & 1) << 4) & 31; 29860 out[op++] = in2 >>> 1 & 31; 29861 out[op++] = in2 >>> 6 & 31; 29862 out[op++] = in2 >>> 11 & 31; 29863 out[op++] = in2 >>> 16 & 31; 29864 out[op++] = in2 >>> 21 & 31; 29865 out[op++] = in2 >>> 26 & 31; 29866 out[op++] = (in2 >>> 31 | (in3 & 15) << 1) & 31; 29867 out[op++] = in3 >>> 4 & 31; 29868 out[op++] = in3 >>> 9 & 31; 29869 out[op++] = in3 >>> 14 & 31; 29870 out[op++] = in3 >>> 19 & 31; 29871 out[op++] = in3 >>> 24 & 31; 29872 out[op++] = (in3 >>> 29 | (in4 & 3) << 3) & 31; 29873 out[op++] = in4 >>> 2 & 31; 29874 out[op++] = in4 >>> 7 & 31; 29875 out[op++] = in4 >>> 12 & 31; 29876 out[op++] = in4 >>> 17 & 31; 29877 out[op++] = in4 >>> 22 & 31; 29878 out[op] = in4 >>> 27 & 31; 29879} 29880function fastUnpack32_6(inValues, inPos, out, outPos) { 29881 let op = outPos; 29882 const in0 = inValues[inPos] >>> 0; 29883 const in1 = inValues[inPos + 1] >>> 0; 29884 const in2 = inValues[inPos + 2] >>> 0; 29885 const in3 = inValues[inPos + 3] >>> 0; 29886 const in4 = inValues[inPos + 4] >>> 0; 29887 const in5 = inValues[inPos + 5] >>> 0; 29888 out[op++] = in0 >>> 0 & 63; 29889 out[op++] = in0 >>> 6 & 63; 29890 out[op++] = in0 >>> 12 & 63; 29891 out[op++] = in0 >>> 18 & 63; 29892 out[op++] = in0 >>> 24 & 63; 29893 out[op++] = (in0 >>> 30 | (in1 & 15) << 2) & 63; 29894 out[op++] = in1 >>> 4 & 63; 29895 out[op++] = in1 >>> 10 & 63; 29896 out[op++] = in1 >>> 16 & 63; 29897 out[op++] = in1 >>> 22 & 63; 29898 out[op++] = (in1 >>> 28 | (in2 & 3) << 4) & 63; 29899 out[op++] = in2 >>> 2 & 63; 29900 out[op++] = in2 >>> 8 & 63; 29901 out[op++] = in2 >>> 14 & 63; 29902 out[op++] = in2 >>> 20 & 63; 29903 out[op++] = in2 >>> 26 & 63; 29904 out[op++] = in3 >>> 0 & 63; 29905 out[op++] = in3 >>> 6 & 63; 29906 out[op++] = in3 >>> 12 & 63; 29907 out[op++] = in3 >>> 18 & 63; 29908 out[op++] = in3 >>> 24 & 63; 29909 out[op++] = (in3 >>> 30 | (in4 & 15) << 2) & 63; 29910 out[op++] = in4 >>> 4 & 63; 29911 out[op++] = in4 >>> 10 & 63; 29912 out[op++] = in4 >>> 16 & 63; 29913 out[op++] = in4 >>> 22 & 63; 29914 out[op++] = (in4 >>> 28 | (in5 & 3) << 4) & 63; 29915 out[op++] = in5 >>> 2 & 63; 29916 out[op++] = in5 >>> 8 & 63; 29917 out[op++] = in5 >>> 14 & 63; 29918 out[op++] = in5 >>> 20 & 63; 29919 out[op] = in5 >>> 26 & 63; 29920} 29921function fastUnpack32_7(inValues, inPos, out, outPos) { 29922 let op = outPos; 29923 const in0 = inValues[inPos] >>> 0; 29924 const in1 = inValues[inPos + 1] >>> 0; 29925 const in2 = inValues[inPos + 2] >>> 0; 29926 const in3 = inValues[inPos + 3] >>> 0; 29927 const in4 = inValues[inPos + 4] >>> 0; 29928 const in5 = inValues[inPos + 5] >>> 0; 29929 const in6 = inValues[inPos + 6] >>> 0; 29930 out[op++] = in0 >>> 0 & 127; 29931 out[op++] = in0 >>> 7 & 127; 29932 out[op++] = in0 >>> 14 & 127; 29933 out[op++] = in0 >>> 21 & 127; 29934 out[op++] = (in0 >>> 28 | (in1 & 7) << 4) & 127; 29935 out[op++] = in1 >>> 3 & 127; 29936 out[op++] = in1 >>> 10 & 127; 29937 out[op++] = in1 >>> 17 & 127; 29938 out[op++] = in1 >>> 24 & 127; 29939 out[op++] = (in1 >>> 31 | (in2 & 63) << 1) & 127; 29940 out[op++] = in2 >>> 6 & 127; 29941 out[op++] = in2 >>> 13 & 127; 29942 out[op++] = in2 >>> 20 & 127; 29943 out[op++] = (in2 >>> 27 | (in3 & 3) << 5) & 127; 29944 out[op++] = in3 >>> 2 & 127; 29945 out[op++] = in3 >>> 9 & 127; 29946 out[op++] = in3 >>> 16 & 127; 29947 out[op++] = in3 >>> 23 & 127; 29948 out[op++] = (in3 >>> 30 | (in4 & 31) << 2) & 127; 29949 out[op++] = in4 >>> 5 & 127; 29950 out[op++] = in4 >>> 12 & 127; 29951 out[op++] = in4 >>> 19 & 127; 29952 out[op++] = (in4 >>> 26 | (in5 & 1) << 6) & 127; 29953 out[op++] = in5 >>> 1 & 127; 29954 out[op++] = in5 >>> 8 & 127; 29955 out[op++] = in5 >>> 15 & 127; 29956 out[op++] = in5 >>> 22 & 127; 29957 out[op++] = (in5 >>> 29 | (in6 & 15) << 3) & 127; 29958 out[op++] = in6 >>> 4 & 127; 29959 out[op++] = in6 >>> 11 & 127; 29960 out[op++] = in6 >>> 18 & 127; 29961 out[op] = in6 >>> 25 & 127; 29962} 29963function fastUnpack32_8(inValues, inPos, out, outPos) { 29964 let op = outPos; 29965 const in0 = inValues[inPos] >>> 0; 29966 const in1 = inValues[inPos + 1] >>> 0; 29967 const in2 = inValues[inPos + 2] >>> 0; 29968 const in3 = inValues[inPos + 3] >>> 0; 29969 const in4 = inValues[inPos + 4] >>> 0; 29970 const in5 = inValues[inPos + 5] >>> 0; 29971 const in6 = inValues[inPos + 6] >>> 0; 29972 const in7 = inValues[inPos + 7] >>> 0; 29973 out[op++] = in0 >>> 0 & 255; 29974 out[op++] = in0 >>> 8 & 255; 29975 out[op++] = in0 >>> 16 & 255; 29976 out[op++] = in0 >>> 24 & 255; 29977 out[op++] = in1 >>> 0 & 255; 29978 out[op++] = in1 >>> 8 & 255; 29979 out[op++] = in1 >>> 16 & 255; 29980 out[op++] = in1 >>> 24 & 255; 29981 out[op++] = in2 >>> 0 & 255; 29982 out[op++] = in2 >>> 8 & 255; 29983 out[op++] = in2 >>> 16 & 255; 29984 out[op++] = in2 >>> 24 & 255; 29985 out[op++] = in3 >>> 0 & 255; 29986 out[op++] = in3 >>> 8 & 255; 29987 out[op++] = in3 >>> 16 & 255; 29988 out[op++] = in3 >>> 24 & 255; 29989 out[op++] = in4 >>> 0 & 255; 29990 out[op++] = in4 >>> 8 & 255; 29991 out[op++] = in4 >>> 16 & 255; 29992 out[op++] = in4 >>> 24 & 255; 29993 out[op++] = in5 >>> 0 & 255; 29994 out[op++] = in5 >>> 8 & 255; 29995 out[op++] = in5 >>> 16 & 255; 29996 out[op++] = in5 >>> 24 & 255; 29997 out[op++] = in6 >>> 0 & 255; 29998 out[op++] = in6 >>> 8 & 255; 29999 out[op++] = in6 >>> 16 & 255; 30000 out[op++] = in6 >>> 24 & 255; 30001 out[op++] = in7 >>> 0 & 255; 30002 out[op++] = in7 >>> 8 & 255; 30003 out[op++] = in7 >>> 16 & 255; 30004 out[op] = in7 >>> 24 & 255; 30005} 30006function fastUnpack32_9(inValues, inPos, out, outPos) { 30007 let op = outPos; 30008 const in0 = inValues[inPos] >>> 0; 30009 const in1 = inValues[inPos + 1] >>> 0; 30010 const in2 = inValues[inPos + 2] >>> 0; 30011 const in3 = inValues[inPos + 3] >>> 0; 30012 const in4 = inValues[inPos + 4] >>> 0; 30013 const in5 = inValues[inPos + 5] >>> 0; 30014 const in6 = inValues[inPos + 6] >>> 0; 30015 const in7 = inValues[inPos + 7] >>> 0; 30016 const in8 = inValues[inPos + 8] >>> 0; 30017 out[op++] = in0 >>> 0 & 511; 30018 out[op++] = in0 >>> 9 & 511; 30019 out[op++] = in0 >>> 18 & 511; 30020 out[op++] = (in0 >>> 27 | (in1 & 15) << 5) & 511; 30021 out[op++] = in1 >>> 4 & 511; 30022 out[op++] = in1 >>> 13 & 511; 30023 out[op++] = in1 >>> 22 & 511; 30024 out[op++] = (in1 >>> 31 | (in2 & 255) << 1) & 511; 30025 out[op++] = in2 >>> 8 & 511; 30026 out[op++] = in2 >>> 17 & 511; 30027 out[op++] = (in2 >>> 26 | (in3 & 7) << 6) & 511; 30028 out[op++] = in3 >>> 3 & 511; 30029 out[op++] = in3 >>> 12 & 511; 30030 out[op++] = in3 >>> 21 & 511; 30031 out[op++] = (in3 >>> 30 | (in4 & 127) << 2) & 511; 30032 out[op++] = in4 >>> 7 & 511; 30033 out[op++] = in4 >>> 16 & 511; 30034 out[op++] = (in4 >>> 25 | (in5 & 3) << 7) & 511; 30035 out[op++] = in5 >>> 2 & 511; 30036 out[op++] = in5 >>> 11 & 511; 30037 out[op++] = in5 >>> 20 & 511; 30038 out[op++] = (in5 >>> 29 | (in6 & 63) << 3) & 511; 30039 out[op++] = in6 >>> 6 & 511; 30040 out[op++] = in6 >>> 15 & 511; 30041 out[op++] = (in6 >>> 24 | (in7 & 1) << 8) & 511; 30042 out[op++] = in7 >>> 1 & 511; 30043 out[op++] = in7 >>> 10 & 511; 30044 out[op++] = in7 >>> 19 & 511; 30045 out[op++] = (in7 >>> 28 | (in8 & 31) << 4) & 511; 30046 out[op++] = in8 >>> 5 & 511; 30047 out[op++] = in8 >>> 14 & 511; 30048 out[op] = in8 >>> 23 & 511; 30049} 30050function fastUnpack32_10(inValues, inPos, out, outPos) { 30051 let op = outPos; 30052 const in0 = inValues[inPos] >>> 0; 30053 const in1 = inValues[inPos + 1] >>> 0; 30054 const in2 = inValues[inPos + 2] >>> 0; 30055 const in3 = inValues[inPos + 3] >>> 0; 30056 const in4 = inValues[inPos + 4] >>> 0; 30057 const in5 = inValues[inPos + 5] >>> 0; 30058 const in6 = inValues[inPos + 6] >>> 0; 30059 const in7 = inValues[inPos + 7] >>> 0; 30060 const in8 = inValues[inPos + 8] >>> 0; 30061 const in9 = inValues[inPos + 9] >>> 0; 30062 out[op++] = in0 >>> 0 & 1023; 30063 out[op++] = in0 >>> 10 & 1023; 30064 out[op++] = in0 >>> 20 & 1023; 30065 out[op++] = (in0 >>> 30 | (in1 & 255) << 2) & 1023; 30066 out[op++] = in1 >>> 8 & 1023; 30067 out[op++] = in1 >>> 18 & 1023; 30068 out[op++] = (in1 >>> 28 | (in2 & 63) << 4) & 1023; 30069 out[op++] = in2 >>> 6 & 1023; 30070 out[op++] = in2 >>> 16 & 1023; 30071 out[op++] = (in2 >>> 26 | (in3 & 15) << 6) & 1023; 30072 out[op++] = in3 >>> 4 & 1023; 30073 out[op++] = in3 >>> 14 & 1023; 30074 out[op++] = (in3 >>> 24 | (in4 & 3) << 8) & 1023; 30075 out[op++] = in4 >>> 2 & 1023; 30076 out[op++] = in4 >>> 12 & 1023; 30077 out[op++] = in4 >>> 22 & 1023; 30078 out[op++] = in5 >>> 0 & 1023; 30079 out[op++] = in5 >>> 10 & 1023; 30080 out[op++] = in5 >>> 20 & 1023; 30081 out[op++] = (in5 >>> 30 | (in6 & 255) << 2) & 1023; 30082 out[op++] = in6 >>> 8 & 1023; 30083 out[op++] = in6 >>> 18 & 1023; 30084 out[op++] = (in6 >>> 28 | (in7 & 63) << 4) & 1023; 30085 out[op++] = in7 >>> 6 & 1023; 30086 out[op++] = in7 >>> 16 & 1023; 30087 out[op++] = (in7 >>> 26 | (in8 & 15) << 6) & 1023; 30088 out[op++] = in8 >>> 4 & 1023; 30089 out[op++] = in8 >>> 14 & 1023; 30090 out[op++] = (in8 >>> 24 | (in9 & 3) << 8) & 1023; 30091 out[op++] = in9 >>> 2 & 1023; 30092 out[op++] = in9 >>> 12 & 1023; 30093 out[op] = in9 >>> 22 & 1023; 30094} 30095function fastUnpack32_11(inValues, inPos, out, outPos) { 30096 let op = outPos; 30097 const in0 = inValues[inPos] >>> 0; 30098 const in1 = inValues[inPos + 1] >>> 0; 30099 const in2 = inValues[inPos + 2] >>> 0; 30100 const in3 = inValues[inPos + 3] >>> 0; 30101 const in4 = inValues[inPos + 4] >>> 0; 30102 const in5 = inValues[inPos + 5] >>> 0; 30103 const in6 = inValues[inPos + 6] >>> 0; 30104 const in7 = inValues[inPos + 7] >>> 0; 30105 const in8 = inValues[inPos + 8] >>> 0; 30106 const in9 = inValues[inPos + 9] >>> 0; 30107 const in10 = inValues[inPos + 10] >>> 0; 30108 out[op++] = in0 >>> 0 & 2047; 30109 out[op++] = in0 >>> 11 & 2047; 30110 out[op++] = (in0 >>> 22 | (in1 & 1) << 10) & 2047; 30111 out[op++] = in1 >>> 1 & 2047; 30112 out[op++] = in1 >>> 12 & 2047; 30113 out[op++] = (in1 >>> 23 | (in2 & 3) << 9) & 2047; 30114 out[op++] = in2 >>> 2 & 2047; 30115 out[op++] = in2 >>> 13 & 2047; 30116 out[op++] = (in2 >>> 24 | (in3 & 7) << 8) & 2047; 30117 out[op++] = in3 >>> 3 & 2047; 30118 out[op++] = in3 >>> 14 & 2047; 30119 out[op++] = (in3 >>> 25 | (in4 & 15) << 7) & 2047; 30120 out[op++] = in4 >>> 4 & 2047; 30121 out[op++] = in4 >>> 15 & 2047; 30122 out[op++] = (in4 >>> 26 | (in5 & 31) << 6) & 2047; 30123 out[op++] = in5 >>> 5 & 2047; 30124 out[op++] = in5 >>> 16 & 2047; 30125 out[op++] = (in5 >>> 27 | (in6 & 63) << 5) & 2047; 30126 out[op++] = in6 >>> 6 & 2047; 30127 out[op++] = in6 >>> 17 & 2047; 30128 out[op++] = (in6 >>> 28 | (in7 & 127) << 4) & 2047; 30129 out[op++] = in7 >>> 7 & 2047; 30130 out[op++] = in7 >>> 18 & 2047; 30131 out[op++] = (in7 >>> 29 | (in8 & 255) << 3) & 2047; 30132 out[op++] = in8 >>> 8 & 2047; 30133 out[op++] = in8 >>> 19 & 2047; 30134 out[op++] = (in8 >>> 30 | (in9 & 511) << 2) & 2047; 30135 out[op++] = in9 >>> 9 & 2047; 30136 out[op++] = in9 >>> 20 & 2047; 30137 out[op++] = (in9 >>> 31 | (in10 & 1023) << 1) & 2047; 30138 out[op++] = in10 >>> 10 & 2047; 30139 out[op] = in10 >>> 21 & 2047; 30140} 30141function fastUnpack32_12(inValues, inPos, out, outPos) { 30142 let op = outPos; 30143 const in0 = inValues[inPos] >>> 0; 30144 const in1 = inValues[inPos + 1] >>> 0; 30145 const in2 = inValues[inPos + 2] >>> 0; 30146 const in3 = inValues[inPos + 3] >>> 0; 30147 const in4 = inValues[inPos + 4] >>> 0; 30148 const in5 = inValues[inPos + 5] >>> 0; 30149 const in6 = inValues[inPos + 6] >>> 0; 30150 const in7 = inValues[inPos + 7] >>> 0; 30151 const in8 = inValues[inPos + 8] >>> 0; 30152 const in9 = inValues[inPos + 9] >>> 0; 30153 const in10 = inValues[inPos + 10] >>> 0; 30154 const in11 = inValues[inPos + 11] >>> 0; 30155 out[op++] = in0 >>> 0 & 4095; 30156 out[op++] = in0 >>> 12 & 4095; 30157 out[op++] = (in0 >>> 24 | (in1 & 15) << 8) & 4095; 30158 out[op++] = in1 >>> 4 & 4095; 30159 out[op++] = in1 >>> 16 & 4095; 30160 out[op++] = (in1 >>> 28 | (in2 & 255) << 4) & 4095; 30161 out[op++] = in2 >>> 8 & 4095; 30162 out[op++] = in2 >>> 20 & 4095; 30163 out[op++] = in3 >>> 0 & 4095; 30164 out[op++] = in3 >>> 12 & 4095; 30165 out[op++] = (in3 >>> 24 | (in4 & 15) << 8) & 4095; 30166 out[op++] = in4 >>> 4 & 4095; 30167 out[op++] = in4 >>> 16 & 4095; 30168 out[op++] = (in4 >>> 28 | (in5 & 255) << 4) & 4095; 30169 out[op++] = in5 >>> 8 & 4095; 30170 out[op++] = in5 >>> 20 & 4095; 30171 out[op++] = in6 >>> 0 & 4095; 30172 out[op++] = in6 >>> 12 & 4095; 30173 out[op++] = (in6 >>> 24 | (in7 & 15) << 8) & 4095; 30174 out[op++] = in7 >>> 4 & 4095; 30175 out[op++] = in7 >>> 16 & 4095; 30176 out[op++] = (in7 >>> 28 | (in8 & 255) << 4) & 4095; 30177 out[op++] = in8 >>> 8 & 4095; 30178 out[op++] = in8 >>> 20 & 4095; 30179 out[op++] = in9 >>> 0 & 4095; 30180 out[op++] = in9 >>> 12 & 4095; 30181 out[op++] = (in9 >>> 24 | (in10 & 15) << 8) & 4095; 30182 out[op++] = in10 >>> 4 & 4095; 30183 out[op++] = in10 >>> 16 & 4095; 30184 out[op++] = (in10 >>> 28 | (in11 & 255) << 4) & 4095; 30185 out[op++] = in11 >>> 8 & 4095; 30186 out[op] = in11 >>> 20 & 4095; 30187} 30188function fastUnpack32_16(inValues, inPos, out, outPos) { 30189 let op = outPos; 30190 const in0 = inValues[inPos] >>> 0; 30191 const in1 = inValues[inPos + 1] >>> 0; 30192 const in2 = inValues[inPos + 2] >>> 0; 30193 const in3 = inValues[inPos + 3] >>> 0; 30194 const in4 = inValues[inPos + 4] >>> 0; 30195 const in5 = inValues[inPos + 5] >>> 0; 30196 const in6 = inValues[inPos + 6] >>> 0; 30197 const in7 = inValues[inPos + 7] >>> 0; 30198 const in8 = inValues[inPos + 8] >>> 0; 30199 const in9 = inValues[inPos + 9] >>> 0; 30200 const in10 = inValues[inPos + 10] >>> 0; 30201 const in11 = inValues[inPos + 11] >>> 0; 30202 const in12 = inValues[inPos + 12] >>> 0; 30203 const in13 = inValues[inPos + 13] >>> 0; 30204 const in14 = inValues[inPos + 14] >>> 0; 30205 const in15 = inValues[inPos + 15] >>> 0; 30206 out[op++] = in0 >>> 0 & 65535; 30207 out[op++] = in0 >>> 16 & 65535; 30208 out[op++] = in1 >>> 0 & 65535; 30209 out[op++] = in1 >>> 16 & 65535; 30210 out[op++] = in2 >>> 0 & 65535; 30211 out[op++] = in2 >>> 16 & 65535; 30212 out[op++] = in3 >>> 0 & 65535; 30213 out[op++] = in3 >>> 16 & 65535; 30214 out[op++] = in4 >>> 0 & 65535; 30215 out[op++] = in4 >>> 16 & 65535; 30216 out[op++] = in5 >>> 0 & 65535; 30217 out[op++] = in5 >>> 16 & 65535; 30218 out[op++] = in6 >>> 0 & 65535; 30219 out[op++] = in6 >>> 16 & 65535; 30220 out[op++] = in7 >>> 0 & 65535; 30221 out[op++] = in7 >>> 16 & 65535; 30222 out[op++] = in8 >>> 0 & 65535; 30223 out[op++] = in8 >>> 16 & 65535; 30224 out[op++] = in9 >>> 0 & 65535; 30225 out[op++] = in9 >>> 16 & 65535; 30226 out[op++] = in10 >>> 0 & 65535; 30227 out[op++] = in10 >>> 16 & 65535; 30228 out[op++] = in11 >>> 0 & 65535; 30229 out[op++] = in11 >>> 16 & 65535; 30230 out[op++] = in12 >>> 0 & 65535; 30231 out[op++] = in12 >>> 16 & 65535; 30232 out[op++] = in13 >>> 0 & 65535; 30233 out[op++] = in13 >>> 16 & 65535; 30234 out[op++] = in14 >>> 0 & 65535; 30235 out[op++] = in14 >>> 16 & 65535; 30236 out[op++] = in15 >>> 0 & 65535; 30237 out[op] = in15 >>> 16 & 65535; 30238} 30239function fastUnpack256_1(inValues, inPos, out, outPos) { 30240 let op = outPos; 30241 let ip = inPos; 30242 for (let c = 0; c < 8; c++) { 30243 const in0 = inValues[ip++] >>> 0; 30244 out[op++] = in0 >>> 0 & 1; 30245 out[op++] = in0 >>> 1 & 1; 30246 out[op++] = in0 >>> 2 & 1; 30247 out[op++] = in0 >>> 3 & 1; 30248 out[op++] = in0 >>> 4 & 1; 30249 out[op++] = in0 >>> 5 & 1; 30250 out[op++] = in0 >>> 6 & 1; 30251 out[op++] = in0 >>> 7 & 1; 30252 out[op++] = in0 >>> 8 & 1; 30253 out[op++] = in0 >>> 9 & 1; 30254 out[op++] = in0 >>> 10 & 1; 30255 out[op++] = in0 >>> 11 & 1; 30256 out[op++] = in0 >>> 12 & 1; 30257 out[op++] = in0 >>> 13 & 1; 30258 out[op++] = in0 >>> 14 & 1; 30259 out[op++] = in0 >>> 15 & 1; 30260 out[op++] = in0 >>> 16 & 1; 30261 out[op++] = in0 >>> 17 & 1; 30262 out[op++] = in0 >>> 18 & 1; 30263 out[op++] = in0 >>> 19 & 1; 30264 out[op++] = in0 >>> 20 & 1; 30265 out[op++] = in0 >>> 21 & 1; 30266 out[op++] = in0 >>> 22 & 1; 30267 out[op++] = in0 >>> 23 & 1; 30268 out[op++] = in0 >>> 24 & 1; 30269 out[op++] = in0 >>> 25 & 1; 30270 out[op++] = in0 >>> 26 & 1; 30271 out[op++] = in0 >>> 27 & 1; 30272 out[op++] = in0 >>> 28 & 1; 30273 out[op++] = in0 >>> 29 & 1; 30274 out[op++] = in0 >>> 30 & 1; 30275 out[op++] = in0 >>> 31 & 1; 30276 } 30277} 30278function fastUnpack256_2(inValues, inPos, out, outPos) { 30279 let op = outPos; 30280 let ip = inPos; 30281 for (let c = 0; c < 8; c++) { 30282 const in0 = inValues[ip++] >>> 0; 30283 const in1 = inValues[ip++] >>> 0; 30284 out[op++] = in0 >>> 0 & 3; 30285 out[op++] = in0 >>> 2 & 3; 30286 out[op++] = in0 >>> 4 & 3; 30287 out[op++] = in0 >>> 6 & 3; 30288 out[op++] = in0 >>> 8 & 3; 30289 out[op++] = in0 >>> 10 & 3; 30290 out[op++] = in0 >>> 12 & 3; 30291 out[op++] = in0 >>> 14 & 3; 30292 out[op++] = in0 >>> 16 & 3; 30293 out[op++] = in0 >>> 18 & 3; 30294 out[op++] = in0 >>> 20 & 3; 30295 out[op++] = in0 >>> 22 & 3; 30296 out[op++] = in0 >>> 24 & 3; 30297 out[op++] = in0 >>> 26 & 3; 30298 out[op++] = in0 >>> 28 & 3; 30299 out[op++] = in0 >>> 30 & 3; 30300 out[op++] = in1 >>> 0 & 3; 30301 out[op++] = in1 >>> 2 & 3; 30302 out[op++] = in1 >>> 4 & 3; 30303 out[op++] = in1 >>> 6 & 3; 30304 out[op++] = in1 >>> 8 & 3; 30305 out[op++] = in1 >>> 10 & 3; 30306 out[op++] = in1 >>> 12 & 3; 30307 out[op++] = in1 >>> 14 & 3; 30308 out[op++] = in1 >>> 16 & 3; 30309 out[op++] = in1 >>> 18 & 3; 30310 out[op++] = in1 >>> 20 & 3; 30311 out[op++] = in1 >>> 22 & 3; 30312 out[op++] = in1 >>> 24 & 3; 30313 out[op++] = in1 >>> 26 & 3; 30314 out[op++] = in1 >>> 28 & 3; 30315 out[op++] = in1 >>> 30 & 3; 30316 } 30317} 30318function fastUnpack256_3(inValues, inPos, out, outPos) { 30319 let op = outPos; 30320 let ip = inPos; 30321 for (let c = 0; c < 8; c++) { 30322 const in0 = inValues[ip++] >>> 0; 30323 const in1 = inValues[ip++] >>> 0; 30324 const in2 = inValues[ip++] >>> 0; 30325 out[op++] = in0 >>> 0 & 7; 30326 out[op++] = in0 >>> 3 & 7; 30327 out[op++] = in0 >>> 6 & 7; 30328 out[op++] = in0 >>> 9 & 7; 30329 out[op++] = in0 >>> 12 & 7; 30330 out[op++] = in0 >>> 15 & 7; 30331 out[op++] = in0 >>> 18 & 7; 30332 out[op++] = in0 >>> 21 & 7; 30333 out[op++] = in0 >>> 24 & 7; 30334 out[op++] = in0 >>> 27 & 7; 30335 out[op++] = (in0 >>> 30 | (in1 & 1) << 2) & 7; 30336 out[op++] = in1 >>> 1 & 7; 30337 out[op++] = in1 >>> 4 & 7; 30338 out[op++] = in1 >>> 7 & 7; 30339 out[op++] = in1 >>> 10 & 7; 30340 out[op++] = in1 >>> 13 & 7; 30341 out[op++] = in1 >>> 16 & 7; 30342 out[op++] = in1 >>> 19 & 7; 30343 out[op++] = in1 >>> 22 & 7; 30344 out[op++] = in1 >>> 25 & 7; 30345 out[op++] = in1 >>> 28 & 7; 30346 out[op++] = (in1 >>> 31 | (in2 & 3) << 1) & 7; 30347 out[op++] = in2 >>> 2 & 7; 30348 out[op++] = in2 >>> 5 & 7; 30349 out[op++] = in2 >>> 8 & 7; 30350 out[op++] = in2 >>> 11 & 7; 30351 out[op++] = in2 >>> 14 & 7; 30352 out[op++] = in2 >>> 17 & 7; 30353 out[op++] = in2 >>> 20 & 7; 30354 out[op++] = in2 >>> 23 & 7; 30355 out[op++] = in2 >>> 26 & 7; 30356 out[op++] = in2 >>> 29 & 7; 30357 } 30358} 30359function fastUnpack256_4(inValues, inPos, out, outPos) { 30360 let op = outPos; 30361 let ip = inPos; 30362 for (let c = 0; c < 8; c++) { 30363 const in0 = inValues[ip++] >>> 0; 30364 const in1 = inValues[ip++] >>> 0; 30365 const in2 = inValues[ip++] >>> 0; 30366 const in3 = inValues[ip++] >>> 0; 30367 out[op++] = in0 >>> 0 & 15; 30368 out[op++] = in0 >>> 4 & 15; 30369 out[op++] = in0 >>> 8 & 15; 30370 out[op++] = in0 >>> 12 & 15; 30371 out[op++] = in0 >>> 16 & 15; 30372 out[op++] = in0 >>> 20 & 15; 30373 out[op++] = in0 >>> 24 & 15; 30374 out[op++] = in0 >>> 28 & 15; 30375 out[op++] = in1 >>> 0 & 15; 30376 out[op++] = in1 >>> 4 & 15; 30377 out[op++] = in1 >>> 8 & 15; 30378 out[op++] = in1 >>> 12 & 15; 30379 out[op++] = in1 >>> 16 & 15; 30380 out[op++] = in1 >>> 20 & 15; 30381 out[op++] = in1 >>> 24 & 15; 30382 out[op++] = in1 >>> 28 & 15; 30383 out[op++] = in2 >>> 0 & 15; 30384 out[op++] = in2 >>> 4 & 15; 30385 out[op++] = in2 >>> 8 & 15; 30386 out[op++] = in2 >>> 12 & 15; 30387 out[op++] = in2 >>> 16 & 15; 30388 out[op++] = in2 >>> 20 & 15; 30389 out[op++] = in2 >>> 24 & 15; 30390 out[op++] = in2 >>> 28 & 15; 30391 out[op++] = in3 >>> 0 & 15; 30392 out[op++] = in3 >>> 4 & 15; 30393 out[op++] = in3 >>> 8 & 15; 30394 out[op++] = in3 >>> 12 & 15; 30395 out[op++] = in3 >>> 16 & 15; 30396 out[op++] = in3 >>> 20 & 15; 30397 out[op++] = in3 >>> 24 & 15; 30398 out[op++] = in3 >>> 28 & 15; 30399 } 30400} 30401function fastUnpack256_5(inValues, inPos, out, outPos) { 30402 let op = outPos; 30403 let ip = inPos; 30404 for (let c = 0; c < 8; c++) { 30405 const in0 = inValues[ip++] >>> 0; 30406 const in1 = inValues[ip++] >>> 0; 30407 const in2 = inValues[ip++] >>> 0; 30408 const in3 = inValues[ip++] >>> 0; 30409 const in4 = inValues[ip++] >>> 0; 30410 out[op++] = in0 >>> 0 & 31; 30411 out[op++] = in0 >>> 5 & 31; 30412 out[op++] = in0 >>> 10 & 31; 30413 out[op++] = in0 >>> 15 & 31; 30414 out[op++] = in0 >>> 20 & 31; 30415 out[op++] = in0 >>> 25 & 31; 30416 out[op++] = (in0 >>> 30 | (in1 & 7) << 2) & 31; 30417 out[op++] = in1 >>> 3 & 31; 30418 out[op++] = in1 >>> 8 & 31; 30419 out[op++] = in1 >>> 13 & 31; 30420 out[op++] = in1 >>> 18 & 31; 30421 out[op++] = in1 >>> 23 & 31; 30422 out[op++] = (in1 >>> 28 | (in2 & 1) << 4) & 31; 30423 out[op++] = in2 >>> 1 & 31; 30424 out[op++] = in2 >>> 6 & 31; 30425 out[op++] = in2 >>> 11 & 31; 30426 out[op++] = in2 >>> 16 & 31; 30427 out[op++] = in2 >>> 21 & 31; 30428 out[op++] = in2 >>> 26 & 31; 30429 out[op++] = (in2 >>> 31 | (in3 & 15) << 1) & 31; 30430 out[op++] = in3 >>> 4 & 31; 30431 out[op++] = in3 >>> 9 & 31; 30432 out[op++] = in3 >>> 14 & 31; 30433 out[op++] = in3 >>> 19 & 31; 30434 out[op++] = in3 >>> 24 & 31; 30435 out[op++] = (in3 >>> 29 | (in4 & 3) << 3) & 31; 30436 out[op++] = in4 >>> 2 & 31; 30437 out[op++] = in4 >>> 7 & 31; 30438 out[op++] = in4 >>> 12 & 31; 30439 out[op++] = in4 >>> 17 & 31; 30440 out[op++] = in4 >>> 22 & 31; 30441 out[op++] = in4 >>> 27 & 31; 30442 } 30443} 30444function fastUnpack256_6(inValues, inPos, out, outPos) { 30445 let op = outPos; 30446 let ip = inPos; 30447 for (let c = 0; c < 8; c++) { 30448 const in0 = inValues[ip++] >>> 0; 30449 const in1 = inValues[ip++] >>> 0; 30450 const in2 = inValues[ip++] >>> 0; 30451 const in3 = inValues[ip++] >>> 0; 30452 const in4 = inValues[ip++] >>> 0; 30453 const in5 = inValues[ip++] >>> 0; 30454 out[op++] = in0 >>> 0 & 63; 30455 out[op++] = in0 >>> 6 & 63; 30456 out[op++] = in0 >>> 12 & 63; 30457 out[op++] = in0 >>> 18 & 63; 30458 out[op++] = in0 >>> 24 & 63; 30459 out[op++] = (in0 >>> 30 | (in1 & 15) << 2) & 63; 30460 out[op++] = in1 >>> 4 & 63; 30461 out[op++] = in1 >>> 10 & 63; 30462 out[op++] = in1 >>> 16 & 63; 30463 out[op++] = in1 >>> 22 & 63; 30464 out[op++] = (in1 >>> 28 | (in2 & 3) << 4) & 63; 30465 out[op++] = in2 >>> 2 & 63; 30466 out[op++] = in2 >>> 8 & 63; 30467 out[op++] = in2 >>> 14 & 63; 30468 out[op++] = in2 >>> 20 & 63; 30469 out[op++] = in2 >>> 26 & 63; 30470 out[op++] = in3 >>> 0 & 63; 30471 out[op++] = in3 >>> 6 & 63; 30472 out[op++] = in3 >>> 12 & 63; 30473 out[op++] = in3 >>> 18 & 63; 30474 out[op++] = in3 >>> 24 & 63; 30475 out[op++] = (in3 >>> 30 | (in4 & 15) << 2) & 63; 30476 out[op++] = in4 >>> 4 & 63; 30477 out[op++] = in4 >>> 10 & 63; 30478 out[op++] = in4 >>> 16 & 63; 30479 out[op++] = in4 >>> 22 & 63; 30480 out[op++] = (in4 >>> 28 | (in5 & 3) << 4) & 63; 30481 out[op++] = in5 >>> 2 & 63; 30482 out[op++] = in5 >>> 8 & 63; 30483 out[op++] = in5 >>> 14 & 63; 30484 out[op++] = in5 >>> 20 & 63; 30485 out[op++] = in5 >>> 26 & 63; 30486 } 30487} 30488function fastUnpack256_7(inValues, inPos, out, outPos) { 30489 let op = outPos; 30490 let ip = inPos; 30491 for (let c = 0; c < 8; c++) { 30492 const in0 = inValues[ip++] >>> 0; 30493 const in1 = inValues[ip++] >>> 0; 30494 const in2 = inValues[ip++] >>> 0; 30495 const in3 = inValues[ip++] >>> 0; 30496 const in4 = inValues[ip++] >>> 0; 30497 const in5 = inValues[ip++] >>> 0; 30498 const in6 = inValues[ip++] >>> 0; 30499 out[op++] = in0 >>> 0 & 127; 30500 out[op++] = in0 >>> 7 & 127; 30501 out[op++] = in0 >>> 14 & 127; 30502 out[op++] = in0 >>> 21 & 127; 30503 out[op++] = (in0 >>> 28 | (in1 & 7) << 4) & 127; 30504 out[op++] = in1 >>> 3 & 127; 30505 out[op++] = in1 >>> 10 & 127; 30506 out[op++] = in1 >>> 17 & 127; 30507 out[op++] = in1 >>> 24 & 127; 30508 out[op++] = (in1 >>> 31 | (in2 & 63) << 1) & 127; 30509 out[op++] = in2 >>> 6 & 127; 30510 out[op++] = in2 >>> 13 & 127; 30511 out[op++] = in2 >>> 20 & 127; 30512 out[op++] = (in2 >>> 27 | (in3 & 3) << 5) & 127; 30513 out[op++] = in3 >>> 2 & 127; 30514 out[op++] = in3 >>> 9 & 127; 30515 out[op++] = in3 >>> 16 & 127; 30516 out[op++] = in3 >>> 23 & 127; 30517 out[op++] = (in3 >>> 30 | (in4 & 31) << 2) & 127; 30518 out[op++] = in4 >>> 5 & 127; 30519 out[op++] = in4 >>> 12 & 127; 30520 out[op++] = in4 >>> 19 & 127; 30521 out[op++] = (in4 >>> 26 | (in5 & 1) << 6) & 127; 30522 out[op++] = in5 >>> 1 & 127; 30523 out[op++] = in5 >>> 8 & 127; 30524 out[op++] = in5 >>> 15 & 127; 30525 out[op++] = in5 >>> 22 & 127; 30526 out[op++] = (in5 >>> 29 | (in6 & 15) << 3) & 127; 30527 out[op++] = in6 >>> 4 & 127; 30528 out[op++] = in6 >>> 11 & 127; 30529 out[op++] = in6 >>> 18 & 127; 30530 out[op++] = in6 >>> 25 & 127; 30531 } 30532} 30533function fastUnpack256_8(inValues, inPos, out, outPos) { 30534 let op = outPos; 30535 let ip = inPos; 30536 for (let c = 0; c < 8; c++) { 30537 const in0 = inValues[ip++] >>> 0; 30538 const in1 = inValues[ip++] >>> 0; 30539 const in2 = inValues[ip++] >>> 0; 30540 const in3 = inValues[ip++] >>> 0; 30541 const in4 = inValues[ip++] >>> 0; 30542 const in5 = inValues[ip++] >>> 0; 30543 const in6 = inValues[ip++] >>> 0; 30544 const in7 = inValues[ip++] >>> 0; 30545 out[op++] = in0 >>> 0 & 255; 30546 out[op++] = in0 >>> 8 & 255; 30547 out[op++] = in0 >>> 16 & 255; 30548 out[op++] = in0 >>> 24 & 255; 30549 out[op++] = in1 >>> 0 & 255; 30550 out[op++] = in1 >>> 8 & 255; 30551 out[op++] = in1 >>> 16 & 255; 30552 out[op++] = in1 >>> 24 & 255; 30553 out[op++] = in2 >>> 0 & 255; 30554 out[op++] = in2 >>> 8 & 255; 30555 out[op++] = in2 >>> 16 & 255; 30556 out[op++] = in2 >>> 24 & 255; 30557 out[op++] = in3 >>> 0 & 255; 30558 out[op++] = in3 >>> 8 & 255; 30559 out[op++] = in3 >>> 16 & 255; 30560 out[op++] = in3 >>> 24 & 255; 30561 out[op++] = in4 >>> 0 & 255; 30562 out[op++] = in4 >>> 8 & 255; 30563 out[op++] = in4 >>> 16 & 255; 30564 out[op++] = in4 >>> 24 & 255; 30565 out[op++] = in5 >>> 0 & 255; 30566 out[op++] = in5 >>> 8 & 255; 30567 out[op++] = in5 >>> 16 & 255; 30568 out[op++] = in5 >>> 24 & 255; 30569 out[op++] = in6 >>> 0 & 255; 30570 out[op++] = in6 >>> 8 & 255; 30571 out[op++] = in6 >>> 16 & 255; 30572 out[op++] = in6 >>> 24 & 255; 30573 out[op++] = in7 >>> 0 & 255; 30574 out[op++] = in7 >>> 8 & 255; 30575 out[op++] = in7 >>> 16 & 255; 30576 out[op++] = in7 >>> 24 & 255; 30577 } 30578} 30579function fastUnpack256_16(inValues, inPos, out, outPos) { 30580 let op = outPos; 30581 let ip = inPos; 30582 for (let i = 0; i < 128; i++) { 30583 const in0 = inValues[ip++] >>> 0; 30584 out[op++] = in0 & 65535; 30585 out[op++] = in0 >>> 16 & 65535; 30586 } 30587} 30588function fastUnpack256_Generic(inValues, inPos, out, outPos, bitWidth) { 30589 const mask = MASKS[bitWidth] >>> 0; 30590 let inputWordIndex = inPos; 30591 let bitOffset = 0; 30592 let currentWord = inValues[inputWordIndex] >>> 0; 30593 let op = outPos; 30594 for (let c = 0; c < 8; c++) { 30595 for (let i = 0; i < 32; i++) if (bitOffset + bitWidth <= 32) { 30596 const value = currentWord >>> bitOffset & mask; 30597 out[op + i] = value | 0; 30598 bitOffset += bitWidth; 30599 if (bitOffset === 32) { 30600 bitOffset = 0; 30601 inputWordIndex++; 30602 if (i !== 31) currentWord = inValues[inputWordIndex] >>> 0; 30603 } 30604 } else { 30605 const lowBits = 32 - bitOffset; 30606 const low = currentWord >>> bitOffset; 30607 inputWordIndex++; 30608 currentWord = inValues[inputWordIndex] >>> 0; 30609 const highBits = bitWidth - lowBits; 30610 const highMask = -1 >>> 32 - highBits >>> 0; 30611 const value = (low | (currentWord & highMask) << lowBits) & mask; 30612 out[op + i] = value | 0; 30613 bitOffset = highBits; 30614 } 30615 op += 32; 30616 bitOffset = 0; 30617 if (c < 7) currentWord = inValues[inputWordIndex] >>> 0; 30618 } 30619} 30620//#endregion 30621//#region node_modules/@maplibre/mlt/dist/decoding/fastPforDecoder.js 30622const MAX_BIT_WIDTH$1 = 32; 30623const BIT_WIDTH_SLOTS$1 = 33; 30624const PAGE_SIZE$1 = normalizePageSize(DEFAULT_PAGE_SIZE); 30625const BYTE_CONTAINER_SIZE$1 = 3 * PAGE_SIZE$1 / 256 + PAGE_SIZE$1 | 0; 30626/** 30627* Creates an isolated workspace for decoding. 30628* Reusing a workspace across calls avoids repeated allocations. 30629*/ 30630function createDecoderWorkspace() { 30631 const byteContainer = new Uint8Array(BYTE_CONTAINER_SIZE$1); 30632 return { 30633 dataToBePacked: new Array(BIT_WIDTH_SLOTS$1), 30634 dataPointers: new Int32Array(BIT_WIDTH_SLOTS$1), 30635 byteContainer, 30636 byteContainerI32: new Int32Array(byteContainer.buffer, byteContainer.byteOffset, byteContainer.byteLength >>> 2), 30637 exceptionSizes: new Int32Array(BIT_WIDTH_SLOTS$1) 30638 }; 30639} 30640function createFastPforWireDecodeWorkspace(initialEncodedWordCapacity = 16) { 30641 if (initialEncodedWordCapacity < 0) throw new RangeError(`initialEncodedWordCapacity must be >= 0, got ${initialEncodedWordCapacity}`); 30642 const capacity = Math.max(16, initialEncodedWordCapacity | 0); 30643 return { 30644 encodedWords: new Uint32Array(capacity), 30645 decoderWorkspace: createDecoderWorkspace() 30646 }; 30647} 30648function ensureFastPforWireEncodedWordsCapacity(workspace, requiredWordCount) { 30649 if (requiredWordCount <= workspace.encodedWords.length) return workspace.encodedWords; 30650 const next = new Uint32Array(Math.max(16, requiredWordCount * 2)); 30651 workspace.encodedWords = next; 30652 return next; 30653} 30654function materializeByteContainer(inValues, byteContainerStart, byteSize, workspace) { 30655 if (workspace.byteContainer.length < byteSize) { 30656 workspace.byteContainer = new Uint8Array(byteSize * 2); 30657 workspace.byteContainerI32 = void 0; 30658 } 30659 const byteContainer = workspace.byteContainer; 30660 const numFullInts = byteSize >>> 2; 30661 if ((byteContainer.byteOffset & 3) === 0) { 30662 let intView = workspace.byteContainerI32; 30663 if (!intView || intView.buffer !== byteContainer.buffer || intView.byteOffset !== byteContainer.byteOffset || intView.length < numFullInts) intView = workspace.byteContainerI32 = new Int32Array(byteContainer.buffer, byteContainer.byteOffset, byteContainer.byteLength >>> 2); 30664 intView.set(inValues.subarray(byteContainerStart, byteContainerStart + numFullInts)); 30665 } else for (let i = 0; i < numFullInts; i = i + 1 | 0) { 30666 const val = inValues[byteContainerStart + i | 0] | 0; 30667 const base = i << 2; 30668 byteContainer[base] = val & 255; 30669 byteContainer[base + 1 | 0] = val >>> 8 & 255; 30670 byteContainer[base + 2 | 0] = val >>> 16 & 255; 30671 byteContainer[base + 3 | 0] = val >>> 24 & 255; 30672 } 30673 const remainder = byteSize & 3; 30674 if (remainder > 0) { 30675 const lastVal = inValues[byteContainerStart + numFullInts | 0] | 0; 30676 const base = numFullInts << 2; 30677 for (let r = 0; r < remainder; r = r + 1 | 0) byteContainer[base + r | 0] = lastVal >>> (r << 3) & 255; 30678 } 30679 return byteContainer; 30680} 30681/** 30682* Unpacks the per-bitWidth "exception streams" described by the page's bitmap. 30683* 30684* @remarks 30685* For each bit-width present in the bitmap, a stream header gives the count of outlier values for that 30686* bit-width, followed by packed bits representing those values. 30687* 30688* @param inValues - Packed input (32-bit words). 30689* @param inExcept - Offset (32-bit word index) where the exception bitmap starts. 30690* @param workspace - Decoder workspace used to store the unpacked exception streams. 30691* @returns The new input offset (32-bit word index) after consuming all exception streams. 30692*/ 30693function unpackExceptionStreams(inValues, inExcept, workspace) { 30694 const bitmap = inValues[inExcept++] | 0; 30695 const dataToBePacked = workspace.dataToBePacked; 30696 for (let bitWidth = 2; bitWidth <= MAX_BIT_WIDTH$1; bitWidth = bitWidth + 1 | 0) { 30697 if ((bitmap >>> bitWidth - 1 & 1) === 0) continue; 30698 if (inExcept >= inValues.length) throw new Error(`FastPFOR decode: truncated exception stream header (bitWidth=${bitWidth}, streamWordIndex=${inExcept}, needWords=1, availableWords=${inValues.length - inExcept}, encodedWords=${inValues.length})`); 30699 const size = inValues[inExcept++] >>> 0; 30700 const roundedUp = roundUpToMultipleOf32(size); 30701 const wordsNeeded = size * bitWidth + 31 >>> 5; 30702 if (inExcept + wordsNeeded > inValues.length) throw new Error(`FastPFOR decode: truncated exception stream (bitWidth=${bitWidth}, size=${size}, streamWordIndex=${inExcept}, needWords=${wordsNeeded}, availableWords=${inValues.length - inExcept}, encodedWords=${inValues.length})`); 30703 let exceptionStream = dataToBePacked[bitWidth]; 30704 if (!exceptionStream || exceptionStream.length < roundedUp) exceptionStream = dataToBePacked[bitWidth] = new Uint32Array(roundedUp); 30705 let j = 0; 30706 for (; j < size; j = j + 32 | 0) { 30707 fastUnpack32(inValues, inExcept, exceptionStream, j, bitWidth); 30708 inExcept = inExcept + bitWidth | 0; 30709 } 30710 const overflow = j - size | 0; 30711 inExcept = inExcept - (overflow * bitWidth >>> 5) | 0; 30712 workspace.exceptionSizes[bitWidth] = size; 30713 } 30714 return inExcept; 30715} 30716/** 30717* Unpacks one 256-value block from the packed bitstream using a specialized implementation for common widths. 30718* 30719* @param inValues - Packed input (32-bit words). 30720* @param inPos - Input offset (32-bit word index) where the packed block starts. 30721* @param out - Output buffer. 30722* @param outPos - Output offset where the 256 values will be written. 30723* @param bitWidth - Base bit-width used for this block. 30724* @returns The new input offset (32-bit word index) right after the packed block data. 30725*/ 30726function unpackBlock256(inValues, inPos, out, outPos, bitWidth) { 30727 switch (bitWidth) { 30728 case 1: 30729 fastUnpack256_1(inValues, inPos, out, outPos); 30730 break; 30731 case 2: 30732 fastUnpack256_2(inValues, inPos, out, outPos); 30733 break; 30734 case 3: 30735 fastUnpack256_3(inValues, inPos, out, outPos); 30736 break; 30737 case 4: 30738 fastUnpack256_4(inValues, inPos, out, outPos); 30739 break; 30740 case 5: 30741 fastUnpack256_5(inValues, inPos, out, outPos); 30742 break; 30743 case 6: 30744 fastUnpack256_6(inValues, inPos, out, outPos); 30745 break; 30746 case 7: 30747 fastUnpack256_7(inValues, inPos, out, outPos); 30748 break; 30749 case 8: 30750 fastUnpack256_8(inValues, inPos, out, outPos); 30751 break; 30752 case 16: 30753 fastUnpack256_16(inValues, inPos, out, outPos); 30754 break; 30755 default: fastUnpack256_Generic(inValues, inPos, out, outPos, bitWidth); 30756 } 30757 return inPos + (bitWidth << 3) | 0; 30758} 30759/** 30760* Reads and validates the 2-byte block header from the byteContainer. 30761* 30762* @remarks 30763* The header is `[bitWidth, exceptionCount]`, both stored as single bytes. 30764* 30765* @param byteContainer - Byte metadata buffer for the page. 30766* @param byteContainerLen - The valid byte length in `byteContainer` for this page. 30767* @param bytePosIn - Current offset in `byteContainer`. 30768* @param block - Block index within the page (for error messages). 30769* @returns The parsed header and the updated `bytePosIn`. 30770*/ 30771function readBlockHeader(byteContainer, byteContainerLen, bytePosIn, block) { 30772 if (bytePosIn + 2 > byteContainerLen) throw new Error(`FastPFOR decode: byteContainer underflow at block=${block} (need 2 bytes for [bitWidth, exceptionCount], bytePos=${bytePosIn}, byteSize=${byteContainerLen})`); 30773 const bitWidth = byteContainer[bytePosIn++]; 30774 const exceptionCount = byteContainer[bytePosIn++]; 30775 if (bitWidth > MAX_BIT_WIDTH$1) throw new Error(`FastPFOR decode: invalid bitWidth=${bitWidth} at block=${block} (expected 0..${MAX_BIT_WIDTH$1}). This likely indicates corrupted or truncated input.`); 30776 return { 30777 bitWidth, 30778 exceptionCount, 30779 bytePosIn 30780 }; 30781} 30782/** 30783* Reads and validates the exception header for a block. 30784* 30785* @remarks 30786* The header contains `maxBits` (1 byte), which defines the width of the outlier values as 30787* `exceptionBitWidth = maxBits - bitWidth`. 30788* 30789* @param byteContainer - Byte metadata buffer for the page. 30790* @param byteContainerLen - The valid byte length in `byteContainer` for this page. 30791* @param bytePosIn - Current offset in `byteContainer`. 30792* @param bitWidth - Base bit-width for the block. 30793* @param exceptionCount - Number of exceptions/outliers in this block. 30794* @param block - Block index within the page (for error messages). 30795* @returns Parsed `maxBits`, `exceptionBitWidth`, and the updated `bytePosIn`. 30796*/ 30797function readBlockExceptionHeader(byteContainer, byteContainerLen, bytePosIn, bitWidth, exceptionCount, block) { 30798 if (bytePosIn + 1 > byteContainerLen) throw new Error(`FastPFOR decode: exception header underflow at block=${block} (need 1 byte for maxBits, bytePos=${bytePosIn}, byteSize=${byteContainerLen})`); 30799 const maxBits = byteContainer[bytePosIn++]; 30800 if (maxBits < bitWidth || maxBits > MAX_BIT_WIDTH$1) throw new Error(`FastPFOR decode: invalid maxBits=${maxBits} at block=${block} (bitWidth=${bitWidth}, expected ${bitWidth}..${MAX_BIT_WIDTH$1})`); 30801 const exceptionBitWidth = maxBits - bitWidth | 0; 30802 if (exceptionBitWidth < 1 || exceptionBitWidth > MAX_BIT_WIDTH$1) throw new Error(`FastPFOR decode: invalid exceptionBitWidth=${exceptionBitWidth} at block=${block} (bitWidth=${bitWidth}, maxBits=${maxBits})`); 30803 if (bytePosIn + exceptionCount > byteContainerLen) throw new Error(`FastPFOR decode: exception positions underflow at block=${block} (need=${exceptionCount}, have=${byteContainerLen - bytePosIn})`); 30804 return { 30805 maxBits, 30806 exceptionBitWidth, 30807 bytePosIn 30808 }; 30809} 30810/** 30811* Applies (block-local) FastPFOR "exceptions" (outliers) to an already-unpacked base 256-value block. 30812* 30813* @param out - Output buffer containing the base unpacked values for the block. 30814* @param blockOutPos - Offset in `out` where the 256-value block starts. 30815* @param bitWidth - Base bit-width for the block. 30816* @param exceptionCount - Number of exceptions/outliers in this block. 30817* @param byteContainer - Byte metadata buffer for the page. 30818* @param byteContainerLen - The valid byte length in `byteContainer` for this page. 30819* @param bytePosIn - Current offset in `byteContainer` (right after `[bitWidth, exceptionCount]`). 30820* @param workspace - Decoder workspace holding the unpacked exception streams. 30821* @param block - Block index within the page (for error messages). 30822* @returns The updated `bytePosIn` after consuming the exception metadata bytes. 30823* 30824* The exception metadata is stored in `byteContainer`: 30825* - `maxBits` (1 byte): the maximum bit-width of any value in the block 30826* - `exceptionCount` exception positions (1 byte each, 0..255) 30827* 30828* The exception values themselves are read from the pre-unpacked exception streams stored in `workspace`. 30829* Returns the new position in the byteContainer after consuming the exception metadata bytes. 30830*/ 30831function applyBlockExceptions(out, blockOutPos, bitWidth, exceptionCount, byteContainer, byteContainerLen, bytePosIn, workspace, block) { 30832 const { maxBits, exceptionBitWidth, bytePosIn: afterHeaderPos } = readBlockExceptionHeader(byteContainer, byteContainerLen, bytePosIn, bitWidth, exceptionCount, block); 30833 bytePosIn = afterHeaderPos; 30834 if (exceptionBitWidth === 1) { 30835 const shift = 1 << bitWidth; 30836 for (let k = 0; k < exceptionCount; k = k + 1 | 0) { 30837 const pos = byteContainer[bytePosIn++]; 30838 out[pos + blockOutPos | 0] |= shift; 30839 } 30840 return bytePosIn; 30841 } 30842 const exceptionValues = workspace.dataToBePacked[exceptionBitWidth]; 30843 if (!exceptionValues) throw new Error(`FastPFOR decode: missing exception stream for exceptionBitWidth=${exceptionBitWidth} (bitWidth=${bitWidth}, maxBits=${maxBits}) at block ${block}`); 30844 const exceptionPointers = workspace.dataPointers; 30845 let exPtr = exceptionPointers[exceptionBitWidth] | 0; 30846 const exSize = workspace.exceptionSizes[exceptionBitWidth] | 0; 30847 if (exPtr + exceptionCount > exSize) throw new Error(`FastPFOR decode: exception stream overflow for exceptionBitWidth=${exceptionBitWidth} (ptr=${exPtr}, need ${exceptionCount}, size=${exSize}) at block ${block}`); 30848 for (let k = 0; k < exceptionCount; k = k + 1 | 0) { 30849 const pos = byteContainer[bytePosIn++]; 30850 const val = exceptionValues[exPtr++] | 0; 30851 out[pos + blockOutPos | 0] |= val << bitWidth; 30852 } 30853 exceptionPointers[exceptionBitWidth] = exPtr; 30854 return bytePosIn; 30855} 30856function decodePageBlocks(inValues, pageStart, inPos, packedEnd, out, outPos, blocks, byteContainer, byteContainerLen, workspace) { 30857 let tmpInPos = inPos | 0; 30858 let bytePosIn = 0; 30859 for (let run = 0; run < blocks; run = run + 1 | 0) { 30860 const header = readBlockHeader(byteContainer, byteContainerLen, bytePosIn, run); 30861 bytePosIn = header.bytePosIn; 30862 const bitWidth = header.bitWidth; 30863 const exceptionCount = header.exceptionCount; 30864 const blockOutPos = outPos + run * 256 | 0; 30865 switch (bitWidth) { 30866 case 0: 30867 out.fill(0, blockOutPos, blockOutPos + 256); 30868 break; 30869 case 32: 30870 for (let i = 0; i < 256; i = i + 1 | 0) out[blockOutPos + i | 0] = inValues[tmpInPos + i | 0] | 0; 30871 tmpInPos = tmpInPos + 256 | 0; 30872 break; 30873 default: tmpInPos = unpackBlock256(inValues, tmpInPos, out, blockOutPos, bitWidth); 30874 } 30875 if (exceptionCount > 0) bytePosIn = applyBlockExceptions(out, blockOutPos, bitWidth, exceptionCount, byteContainer, byteContainerLen, bytePosIn, workspace, run); 30876 } 30877 if (tmpInPos !== packedEnd) throw new Error(`FastPFOR decode: packed region mismatch (pageStart=${pageStart}, packedStart=${inPos}, consumedPackedEnd=${tmpInPos}, expectedPackedEnd=${packedEnd}, packedWords=${packedEnd - inPos}, encoded.length=${inValues.length})`); 30878} 30879/** 30880* Decodes one FastPFOR page (aligned to 256-value blocks). 30881*/ 30882function decodePage(inValues, out, inPos, outPos, thisSize, workspace) { 30883 const pageStart = inPos | 0; 30884 const whereMeta = inValues[pageStart] | 0; 30885 if (whereMeta <= 0 || pageStart + whereMeta > inValues.length - 1) throw new Error(`FastPFOR decode: invalid whereMeta=${whereMeta} at pageStart=${pageStart} (expected > 0 and pageStart+whereMeta < encoded.length=${inValues.length})`); 30886 const packedStart = pageStart + 1 | 0; 30887 const packedEnd = pageStart + whereMeta | 0; 30888 const byteSize = inValues[packedEnd] >>> 0; 30889 const metaInts = byteSize + 3 >>> 2; 30890 const byteContainerStart = packedEnd + 1; 30891 const bitmapPos = byteContainerStart + metaInts; 30892 if (bitmapPos >= inValues.length) throw new Error(`FastPFOR decode: invalid byteSize=${byteSize} (metaInts=${metaInts}, pageStart=${pageStart}, packedEnd=${packedEnd}, byteContainerStart=${byteContainerStart}) causes bitmapPos=${bitmapPos} out of bounds (encoded.length=${inValues.length})`); 30893 const byteContainer = materializeByteContainer(inValues, byteContainerStart, byteSize, workspace); 30894 const byteContainerLen = byteSize; 30895 const inExcept = unpackExceptionStreams(inValues, bitmapPos, workspace); 30896 workspace.dataPointers.fill(0); 30897 decodePageBlocks(inValues, pageStart, packedStart, packedEnd, out, outPos | 0, thisSize / 256 | 0, byteContainer, byteContainerLen, workspace); 30898 return inExcept; 30899} 30900function decodeAlignedPages(inValues, out, inPos, outPos, outLength, workspace) { 30901 const finalOut = outPos + greatestMultiple(outLength, 256); 30902 let tmpOutPos = outPos; 30903 let tmpInPos = inPos; 30904 while (tmpOutPos !== finalOut) { 30905 const thisSize = Math.min(PAGE_SIZE$1, finalOut - tmpOutPos); 30906 tmpInPos = decodePage(inValues, out, tmpInPos, tmpOutPos, thisSize, workspace); 30907 tmpOutPos = tmpOutPos + thisSize | 0; 30908 } 30909 return tmpInPos; 30910} 30911/** 30912* Decodes the VariableByte tail (MSB=1 terminator, opposite of Protobuf Varint). 30913*/ 30914function decodeVByte(inValues, inPos, inLength, out, outPos, expectedCount) { 30915 if (expectedCount === 0) return inPos; 30916 let bitOffset = 0; 30917 let wordIndex = inPos; 30918 const finalWordIndex = inPos + inLength; 30919 const outPos0 = outPos; 30920 let tmpOutPos = outPos; 30921 const targetOut = outPos + expectedCount; 30922 let accumulator = 0; 30923 let accumulatorShift = 0; 30924 while (wordIndex < finalWordIndex && tmpOutPos < targetOut) { 30925 const byte = inValues[wordIndex] >>> bitOffset & 255; 30926 bitOffset += 8; 30927 wordIndex += bitOffset >>> 5; 30928 bitOffset &= 31; 30929 accumulator |= (byte & 127) << accumulatorShift; 30930 if ((byte & 128) !== 0) { 30931 out[tmpOutPos++] = accumulator | 0; 30932 accumulator = 0; 30933 accumulatorShift = 0; 30934 } else { 30935 accumulatorShift += 7; 30936 if (accumulatorShift > 28) throw new Error(`FastPFOR VByte: unterminated value (expected MSB=1 terminator within 5 bytes; shift=${accumulatorShift}, partial=${accumulator}, decoded=${tmpOutPos - outPos0}/${expectedCount}, inPos=${wordIndex}, inEnd=${finalWordIndex})`); 30937 } 30938 } 30939 if (tmpOutPos !== targetOut) throw new Error(`FastPFOR VByte: truncated stream (decoded=${tmpOutPos - outPos0}, expected=${expectedCount}, consumedWords=${wordIndex - inPos}/${inLength}, vbyteStart=${inPos}, vbyteEnd=${finalWordIndex})`); 30940 return wordIndex; 30941} 30942/** 30943* Decodes a sequence of FastPFOR-encoded integers. 30944* 30945* @param encoded The input buffer containing FastPFOR encoded data. 30946* @param numValues The number of integers expected to be decoded. 30947* @param workspace Optional workspace for reuse across calls. If omitted, a new workspace is created per call. 30948*/ 30949function decodeFastPforInt32(encoded, numValues, workspace) { 30950 let inPos = 0; 30951 let outPos = 0; 30952 const decoded = new Uint32Array(numValues); 30953 const decoderWorkspace = workspace ?? createDecoderWorkspace(); 30954 if (encoded.length > 0) { 30955 const alignedLength = encoded[inPos] | 0; 30956 inPos = inPos + 1 | 0; 30957 if ((alignedLength & 255) !== 0) throw new Error(`FastPFOR decode: invalid alignedLength=${alignedLength} (expected multiple of 256)`); 30958 if (outPos + alignedLength > decoded.length) throw new Error(`FastPFOR decode: output buffer too small (outPos=${outPos}, alignedLength=${alignedLength}, out.length=${decoded.length})`); 30959 inPos = decodeAlignedPages(encoded, decoded, inPos, outPos, alignedLength, decoderWorkspace); 30960 outPos = outPos + alignedLength | 0; 30961 } 30962 const remainingLength = encoded.length - inPos | 0; 30963 const expectedTail = numValues - outPos | 0; 30964 decodeVByte(encoded, inPos, remainingLength, decoded, outPos, expectedTail); 30965 return decoded; 30966} 30967function fastUnpack32(inValues, inPos, out, outPos, bitWidth) { 30968 switch (bitWidth) { 30969 case 2: 30970 fastUnpack32_2(inValues, inPos, out, outPos); 30971 return; 30972 case 3: 30973 fastUnpack32_3(inValues, inPos, out, outPos); 30974 return; 30975 case 4: 30976 fastUnpack32_4(inValues, inPos, out, outPos); 30977 return; 30978 case 5: 30979 fastUnpack32_5(inValues, inPos, out, outPos); 30980 return; 30981 case 6: 30982 fastUnpack32_6(inValues, inPos, out, outPos); 30983 return; 30984 case 7: 30985 fastUnpack32_7(inValues, inPos, out, outPos); 30986 return; 30987 case 8: 30988 fastUnpack32_8(inValues, inPos, out, outPos); 30989 return; 30990 case 9: 30991 fastUnpack32_9(inValues, inPos, out, outPos); 30992 return; 30993 case 10: 30994 fastUnpack32_10(inValues, inPos, out, outPos); 30995 return; 30996 case 11: 30997 fastUnpack32_11(inValues, inPos, out, outPos); 30998 return; 30999 case 12: 31000 fastUnpack32_12(inValues, inPos, out, outPos); 31001 return; 31002 case 16: 31003 fastUnpack32_16(inValues, inPos, out, outPos); 31004 return; 31005 case 32: 31006 for (let i = 0; i < 32; i = i + 1 | 0) out[outPos + i | 0] = inValues[inPos + i | 0] | 0; 31007 return; 31008 } 31009 const valueMask = MASKS[bitWidth] >>> 0; 31010 let inputWordIndex = inPos; 31011 let bitOffset = 0; 31012 let currentWord = inValues[inputWordIndex] >>> 0; 31013 for (let i = 0; i < 32; i++) if (bitOffset + bitWidth <= 32) { 31014 const value = currentWord >>> bitOffset & valueMask; 31015 out[outPos + i] = value | 0; 31016 bitOffset += bitWidth; 31017 if (bitOffset === 32) { 31018 bitOffset = 0; 31019 inputWordIndex++; 31020 if (i !== 31) currentWord = inValues[inputWordIndex] >>> 0; 31021 } 31022 } else { 31023 const lowBits = 32 - bitOffset; 31024 const low = currentWord >>> bitOffset; 31025 inputWordIndex++; 31026 currentWord = inValues[inputWordIndex] >>> 0; 31027 const highMask = MASKS[bitWidth - lowBits] >>> 0; 31028 const value = (low | (currentWord & highMask) << lowBits) & valueMask; 31029 out[outPos + i] = value | 0; 31030 bitOffset = bitWidth - lowBits; 31031 } 31032} 31033//#endregion 31034//#region node_modules/@maplibre/mlt/dist/decoding/bigEndianDecode.js 31035/** 31036* Decodes big-endian bytes into `out` without allocating the output buffer. 31037* 31038* This function does not copy `bytes`; it writes decoded words into the provided `out` array. 31039* For aligned inputs it may create a temporary typed-array view (`Uint32Array`) over `bytes.buffer` 31040* to speed up decoding. 31041* 31042* If `byteLength` is not a multiple of 4, the final word is padded with zeros. 31043* 31044* @returns Number of int32 words written. 31045* @throws RangeError If `(offset, byteLength)` is out of bounds, or if `out` is too small. 31046*/ 31047function decodeBigEndianInt32sInto(bytes, offset, byteLength, out) { 31048 if (offset < 0 || byteLength < 0 || offset + byteLength > bytes.length) throw new RangeError(`decodeBigEndianInt32sInto: out of bounds (offset=${offset}, byteLength=${byteLength}, bytes.length=${bytes.length})`); 31049 const numCompleteInts = Math.floor(byteLength / 4); 31050 const hasTrailingBytes = byteLength % 4 !== 0; 31051 const numInts = hasTrailingBytes ? numCompleteInts + 1 : numCompleteInts; 31052 if (out.length < numInts) throw new RangeError(`decodeBigEndianInt32sInto: out.length=${out.length} < ${numInts}`); 31053 if (numCompleteInts > 0) { 31054 const absoluteOffset = bytes.byteOffset + offset; 31055 if ((absoluteOffset & 3) === 0) { 31056 const u32 = new Uint32Array(bytes.buffer, absoluteOffset, numCompleteInts); 31057 for (let i = 0; i < numCompleteInts; i++) out[i] = bswap32(u32[i]) | 0; 31058 } else for (let i = 0; i < numCompleteInts; i++) { 31059 const base = offset + i * 4; 31060 out[i] = bytes[base] << 24 | bytes[base + 1] << 16 | bytes[base + 2] << 8 | bytes[base + 3] | 0; 31061 } 31062 } 31063 if (hasTrailingBytes) { 31064 const base = offset + numCompleteInts * 4; 31065 const remaining = byteLength - numCompleteInts * 4; 31066 let v = 0; 31067 for (let i = 0; i < remaining; i++) v |= bytes[base + i] << 24 - i * 8; 31068 out[numCompleteInts] = v | 0; 31069 } 31070 return numInts; 31071} 31072//#endregion 31073//#region node_modules/@maplibre/mlt/dist/decoding/integerDecodingUtils.js 31074function decodeVarintInt32(buf, bufferOffset, numValues) { 31075 const dst = new Uint32Array(numValues); 31076 let dstOffset = 0; 31077 let offset = bufferOffset.get(); 31078 for (let i = 0; i < dst.length; i++) { 31079 let b = buf[offset++]; 31080 let val = b & 127; 31081 if (b < 128) { 31082 dst[dstOffset++] = val; 31083 continue; 31084 } 31085 b = buf[offset++]; 31086 val |= (b & 127) << 7; 31087 if (b < 128) { 31088 dst[dstOffset++] = val; 31089 continue; 31090 } 31091 b = buf[offset++]; 31092 val |= (b & 127) << 14; 31093 if (b < 128) { 31094 dst[dstOffset++] = val; 31095 continue; 31096 } 31097 b = buf[offset++]; 31098 val |= (b & 127) << 21; 31099 if (b < 128) { 31100 dst[dstOffset++] = val; 31101 continue; 31102 } 31103 b = buf[offset++]; 31104 val |= (b & 15) << 28; 31105 dst[dstOffset++] = val; 31106 } 31107 bufferOffset.set(offset); 31108 return dst; 31109} 31110function decodeVarintInt64(src, offset, numValues) { 31111 const dst = new BigUint64Array(numValues); 31112 for (let i = 0; i < dst.length; i++) dst[i] = decodeVarintInt64Value(src, offset); 31113 return dst; 31114} 31115function decodeVarintInt64Value(bytes, pos) { 31116 let value = 0n; 31117 let shift = 0; 31118 let index = pos.get(); 31119 while (index < bytes.length) { 31120 const b = bytes[index++]; 31121 value |= BigInt(b & 127) << BigInt(shift); 31122 if ((b & 128) === 0) break; 31123 shift += 7; 31124 if (shift >= 64) throw new Error("Varint too long"); 31125 } 31126 pos.set(index); 31127 return value; 31128} 31129function decodeVarintFloat64(src, offset, numValues) { 31130 const dst = new Float64Array(numValues); 31131 for (let i = 0; i < numValues; i++) dst[i] = decodeVarintFloat64Value(src, offset); 31132 return dst; 31133} 31134function decodeVarintFloat64Value(buf, offset) { 31135 let val; 31136 let b; 31137 b = buf[offset.get()]; 31138 offset.increment(); 31139 val = b & 127; 31140 if (b < 128) return val; 31141 b = buf[offset.get()]; 31142 offset.increment(); 31143 val |= (b & 127) << 7; 31144 if (b < 128) return val; 31145 b = buf[offset.get()]; 31146 offset.increment(); 31147 val |= (b & 127) << 14; 31148 if (b < 128) return val; 31149 b = buf[offset.get()]; 31150 offset.increment(); 31151 val |= (b & 127) << 21; 31152 if (b < 128) return val; 31153 b = buf[offset.get()]; 31154 val |= (b & 15) << 28; 31155 return decodeVarintRemainder(val, buf, offset); 31156} 31157function decodeVarintRemainder(l, buf, offset) { 31158 let h; 31159 let b; 31160 b = buf[offset.get()]; 31161 offset.increment(); 31162 h = (b & 112) >> 4; 31163 if (b < 128) return h * 4294967296 + (l >>> 0); 31164 b = buf[offset.get()]; 31165 offset.increment(); 31166 h |= (b & 127) << 3; 31167 if (b < 128) return h * 4294967296 + (l >>> 0); 31168 b = buf[offset.get()]; 31169 offset.increment(); 31170 h |= (b & 127) << 10; 31171 if (b < 128) return h * 4294967296 + (l >>> 0); 31172 b = buf[offset.get()]; 31173 offset.increment(); 31174 h |= (b & 127) << 17; 31175 if (b < 128) return h * 4294967296 + (l >>> 0); 31176 b = buf[offset.get()]; 31177 offset.increment(); 31178 h |= (b & 127) << 24; 31179 if (b < 128) return h * 4294967296 + (l >>> 0); 31180 b = buf[offset.get()]; 31181 offset.increment(); 31182 h |= (b & 1) << 31; 31183 if (b < 128) return h * 4294967296 + (l >>> 0); 31184 throw new Error("Expected varint not more than 10 bytes"); 31185} 31186function decodeFastPfor(encodedBytes, expectedValueCount, encodedByteLength, offset) { 31187 return decodeFastPforWithWorkspace(encodedBytes, expectedValueCount, encodedByteLength, offset, createFastPforWireDecodeWorkspace(encodedByteLength >>> 2)); 31188} 31189function decodeFastPforWithWorkspace(encodedBytes, expectedValueCount, encodedByteLength, offset, workspace) { 31190 const inputByteOffset = offset.get(); 31191 if ((encodedByteLength & 3) !== 0) throw new Error(`FastPFOR: invalid encodedByteLength=${encodedByteLength} at offset=${inputByteOffset} (encodedBytes.length=${encodedBytes.length}; expected a multiple of 4 bytes for an int32 big-endian word stream)`); 31192 const encodedWordCount = encodedByteLength >>> 2; 31193 const encodedWordBuffer = ensureFastPforWireEncodedWordsCapacity(workspace, encodedWordCount); 31194 decodeBigEndianInt32sInto(encodedBytes, inputByteOffset, encodedByteLength, encodedWordBuffer); 31195 const decodedValues = decodeFastPforInt32(encodedWordBuffer.subarray(0, encodedWordCount), expectedValueCount, workspace.decoderWorkspace); 31196 offset.add(encodedByteLength); 31197 return decodedValues; 31198} 31199function decodeZigZagInt32Value(encoded) { 31200 return encoded >>> 1 ^ -(encoded & 1); 31201} 31202function decodeZigZagInt64Value(encoded) { 31203 return encoded >> 1n ^ -(encoded & 1n); 31204} 31205function decodeZigZagFloat64Value(encoded) { 31206 return encoded % 2 === 1 ? (encoded + 1) / -2 : encoded / 2; 31207} 31208function decodeZigZagInt32(encodedData) { 31209 const decodedValues = new Int32Array(encodedData.length); 31210 for (let i = 0; i < encodedData.length; i++) decodedValues[i] = decodeZigZagInt32Value(encodedData[i]); 31211 return decodedValues; 31212} 31213function decodeZigZagInt64(encodedData) { 31214 const decodedValues = new BigInt64Array(encodedData.length); 31215 for (let i = 0; i < encodedData.length; i++) decodedValues[i] = decodeZigZagInt64Value(encodedData[i]); 31216 return decodedValues; 31217} 31218function decodeZigZagFloat64(encodedData) { 31219 for (let i = 0; i < encodedData.length; i++) encodedData[i] = decodeZigZagFloat64Value(encodedData[i]); 31220} 31221function decodeUnsignedRleInt32(encodedData, numRuns, numTotalValues) { 31222 if (numTotalValues === void 0) { 31223 numTotalValues = 0; 31224 for (let i = 0; i < numRuns; i++) numTotalValues += encodedData[i]; 31225 } 31226 const decodedValues = new Uint32Array(numTotalValues); 31227 let offset = 0; 31228 for (let i = 0; i < numRuns; i++) { 31229 const runLength = encodedData[i]; 31230 const value = encodedData[i + numRuns]; 31231 decodedValues.fill(value, offset, offset + runLength); 31232 offset += runLength; 31233 } 31234 return decodedValues; 31235} 31236function decodeUnsignedRleInt64(encodedData, numRuns, numTotalValues) { 31237 if (numTotalValues === void 0) { 31238 numTotalValues = 0; 31239 for (let i = 0; i < numRuns; i++) numTotalValues += Number(encodedData[i]); 31240 } 31241 const decodedValues = new BigUint64Array(numTotalValues); 31242 let offset = 0; 31243 for (let i = 0; i < numRuns; i++) { 31244 const runLength = Number(encodedData[i]); 31245 const value = encodedData[i + numRuns]; 31246 decodedValues.fill(value, offset, offset + runLength); 31247 offset += runLength; 31248 } 31249 return decodedValues; 31250} 31251function decodeUnsignedRleFloat64(encodedData, numRuns, numTotalValues) { 31252 const decodedValues = new Float64Array(numTotalValues); 31253 let offset = 0; 31254 for (let i = 0; i < numRuns; i++) { 31255 const runLength = encodedData[i]; 31256 const value = encodedData[i + numRuns]; 31257 decodedValues.fill(value, offset, offset + runLength); 31258 offset += runLength; 31259 } 31260 return decodedValues; 31261} 31262function decodeZigZagDeltaInt32(data) { 31263 const decodedValues = new Int32Array(data.length); 31264 decodedValues[0] = decodeZigZagInt32Value(data[0]); 31265 const sz0 = data.length / 4 * 4; 31266 let i = 1; 31267 if (sz0 >= 4) for (; i < sz0 - 4; i += 4) { 31268 const data1 = data[i]; 31269 const data2 = data[i + 1]; 31270 const data3 = data[i + 2]; 31271 const data4 = data[i + 3]; 31272 decodedValues[i] = decodeZigZagInt32Value(data1) + decodedValues[i - 1]; 31273 decodedValues[i + 1] = decodeZigZagInt32Value(data2) + decodedValues[i]; 31274 decodedValues[i + 2] = decodeZigZagInt32Value(data3) + decodedValues[i + 1]; 31275 decodedValues[i + 3] = decodeZigZagInt32Value(data4) + decodedValues[i + 2]; 31276 } 31277 for (; i !== data.length; ++i) decodedValues[i] = decodeZigZagInt32Value(data[i]) + decodedValues[i - 1]; 31278 return decodedValues; 31279} 31280function decodeZigZagDeltaInt64(data) { 31281 const decodedValues = new BigInt64Array(data.length); 31282 decodedValues[0] = decodeZigZagInt64Value(data[0]); 31283 const sz0 = data.length / 4 * 4; 31284 let i = 1; 31285 if (sz0 >= 4) for (; i < sz0 - 4; i += 4) { 31286 const data1 = data[i]; 31287 const data2 = data[i + 1]; 31288 const data3 = data[i + 2]; 31289 const data4 = data[i + 3]; 31290 decodedValues[i] = decodeZigZagInt64Value(data1) + decodedValues[i - 1]; 31291 decodedValues[i + 1] = decodeZigZagInt64Value(data2) + decodedValues[i]; 31292 decodedValues[i + 2] = decodeZigZagInt64Value(data3) + decodedValues[i + 1]; 31293 decodedValues[i + 3] = decodeZigZagInt64Value(data4) + decodedValues[i + 2]; 31294 } 31295 for (; i !== decodedValues.length; ++i) decodedValues[i] = decodeZigZagInt64Value(data[i]) + decodedValues[i - 1]; 31296 return decodedValues; 31297} 31298function decodeZigZagDeltaFloat64(data) { 31299 data[0] = decodeZigZagFloat64Value(data[0]); 31300 const sz0 = data.length / 4 * 4; 31301 let i = 1; 31302 if (sz0 >= 4) for (; i < sz0 - 4; i += 4) { 31303 const data1 = data[i]; 31304 const data2 = data[i + 1]; 31305 const data3 = data[i + 2]; 31306 const data4 = data[i + 3]; 31307 data[i] = decodeZigZagFloat64Value(data1) + data[i - 1]; 31308 data[i + 1] = decodeZigZagFloat64Value(data2) + data[i]; 31309 data[i + 2] = decodeZigZagFloat64Value(data3) + data[i + 1]; 31310 data[i + 3] = decodeZigZagFloat64Value(data4) + data[i + 2]; 31311 } 31312 for (; i !== data.length; ++i) data[i] = decodeZigZagFloat64Value(data[i]) + data[i - 1]; 31313} 31314function decodeZigZagRleInt32(data, numRuns, numTotalValues) { 31315 if (numTotalValues === void 0) { 31316 numTotalValues = 0; 31317 for (let i = 0; i < numRuns; i++) numTotalValues += data[i]; 31318 } 31319 const decodedValues = new Int32Array(numTotalValues); 31320 let offset = 0; 31321 for (let i = 0; i < numRuns; i++) { 31322 const runLength = data[i]; 31323 let value = data[i + numRuns]; 31324 value = decodeZigZagInt32Value(value); 31325 decodedValues.fill(value, offset, offset + runLength); 31326 offset += runLength; 31327 } 31328 return decodedValues; 31329} 31330function decodeZigZagRleInt64(data, numRuns, numTotalValues) { 31331 if (numTotalValues === void 0) { 31332 numTotalValues = 0; 31333 for (let i = 0; i < numRuns; i++) numTotalValues += Number(data[i]); 31334 } 31335 const decodedValues = new BigInt64Array(numTotalValues); 31336 let offset = 0; 31337 for (let i = 0; i < numRuns; i++) { 31338 const runLength = Number(data[i]); 31339 let value = data[i + numRuns]; 31340 value = decodeZigZagInt64Value(value); 31341 decodedValues.fill(value, offset, offset + runLength); 31342 offset += runLength; 31343 } 31344 return decodedValues; 31345} 31346function decodeZigZagRleFloat64(data, numRuns, numTotalValues) { 31347 const decodedValues = new Float64Array(numTotalValues); 31348 let offset = 0; 31349 for (let i = 0; i < numRuns; i++) { 31350 const runLength = data[i]; 31351 let value = data[i + numRuns]; 31352 value = decodeZigZagFloat64Value(value); 31353 decodedValues.fill(value, offset, offset + runLength); 31354 offset += runLength; 31355 } 31356 return decodedValues; 31357} 31358function fastInverseDelta(data) { 31359 const sz0 = data.length / 4 * 4; 31360 let i = 1; 31361 if (sz0 >= 4) for (let a = data[0]; i < sz0 - 4; i += 4) { 31362 a = data[i] += a; 31363 a = data[i + 1] += a; 31364 a = data[i + 2] += a; 31365 a = data[i + 3] += a; 31366 } 31367 while (i !== data.length) { 31368 data[i] += data[i - 1]; 31369 ++i; 31370 } 31371} 31372function inverseDelta(data) { 31373 let prevValue = 0; 31374 for (let i = 0; i < data.length; i++) { 31375 data[i] += prevValue; 31376 prevValue = data[i]; 31377 } 31378} 31379function decodeComponentwiseDeltaVec2(data) { 31380 if (data.length < 2) return new Int32Array(data); 31381 const decodedData = new Int32Array(data.length); 31382 decodedData[0] = decodeZigZagInt32Value(data[0]); 31383 decodedData[1] = decodeZigZagInt32Value(data[1]); 31384 const sz0 = data.length / 4 * 4; 31385 let i = 2; 31386 if (sz0 >= 4) for (; i < sz0 - 4; i += 4) { 31387 const x1 = data[i]; 31388 const y1 = data[i + 1]; 31389 const x2 = data[i + 2]; 31390 const y2 = data[i + 3]; 31391 decodedData[i] = decodeZigZagInt32Value(x1) + decodedData[i - 2]; 31392 decodedData[i + 1] = decodeZigZagInt32Value(y1) + decodedData[i - 1]; 31393 decodedData[i + 2] = decodeZigZagInt32Value(x2) + decodedData[i]; 31394 decodedData[i + 3] = decodeZigZagInt32Value(y2) + decodedData[i + 1]; 31395 } 31396 for (; i !== data.length; i += 2) { 31397 decodedData[i] = decodeZigZagInt32Value(data[i]) + decodedData[i - 2]; 31398 decodedData[i + 1] = decodeZigZagInt32Value(data[i + 1]) + decodedData[i - 1]; 31399 } 31400 return decodedData; 31401} 31402function decodeComponentwiseDeltaVec2Scaled(data, scale, min, max) { 31403 if (data.length < 2) return new Int32Array(data); 31404 const decodedData = new Int32Array(data.length); 31405 let previousVertexX = decodeZigZagInt32Value(data[0]); 31406 let previousVertexY = decodeZigZagInt32Value(data[1]); 31407 decodedData[0] = clamp(Math.round(previousVertexX * scale), min, max); 31408 decodedData[1] = clamp(Math.round(previousVertexY * scale), min, max); 31409 const sz0 = data.length / 16; 31410 let i = 2; 31411 if (sz0 >= 4) for (; i < sz0 - 4; i += 4) { 31412 const x1 = data[i]; 31413 const y1 = data[i + 1]; 31414 const currentVertexX = decodeZigZagInt32Value(x1) + previousVertexX; 31415 const currentVertexY = decodeZigZagInt32Value(y1) + previousVertexY; 31416 decodedData[i] = clamp(Math.round(currentVertexX * scale), min, max); 31417 decodedData[i + 1] = clamp(Math.round(currentVertexY * scale), min, max); 31418 const x2 = data[i + 2]; 31419 const y2 = data[i + 3]; 31420 previousVertexX = decodeZigZagInt32Value(x2) + currentVertexX; 31421 previousVertexY = decodeZigZagInt32Value(y2) + currentVertexY; 31422 decodedData[i + 2] = clamp(Math.round(previousVertexX * scale), min, max); 31423 decodedData[i + 3] = clamp(Math.round(previousVertexY * scale), min, max); 31424 } 31425 for (; i !== data.length; i += 2) { 31426 previousVertexX += decodeZigZagInt32Value(data[i]); 31427 previousVertexY += decodeZigZagInt32Value(data[i + 1]); 31428 decodedData[i] = clamp(Math.round(previousVertexX * scale), min, max); 31429 decodedData[i + 1] = clamp(Math.round(previousVertexY * scale), min, max); 31430 } 31431 return decodedData; 31432} 31433function clamp(n, min, max) { 31434 return Math.min(max, Math.max(min, n)); 31435} 31436function decodeZigZagDeltaOfDeltaInt32(data) { 31437 const decodedData = new Int32Array(data.length + 1); 31438 decodedData[0] = 0; 31439 decodedData[1] = decodeZigZagInt32Value(data[0]); 31440 let deltaSum = decodedData[1]; 31441 for (let i = 2; i !== decodedData.length; ++i) { 31442 const zigZagValue = data[i - 1]; 31443 const delta = decodeZigZagInt32Value(zigZagValue); 31444 deltaSum += delta; 31445 decodedData[i] = decodedData[i - 1] + deltaSum; 31446 } 31447 return new Uint32Array(decodedData); 31448} 31449function decodeZigZagRleDeltaInt32(data, numRuns, numTotalValues) { 31450 const decodedValues = new Int32Array(numTotalValues + 1); 31451 decodedValues[0] = 0; 31452 let offset = 1; 31453 let previousValue = decodedValues[0]; 31454 for (let i = 0; i < numRuns; i++) { 31455 const runLength = data[i]; 31456 let value = data[i + numRuns]; 31457 value = decodeZigZagInt32Value(value); 31458 for (let j = offset; j < offset + runLength; j++) { 31459 decodedValues[j] = value + previousValue; 31460 previousValue = decodedValues[j]; 31461 } 31462 offset += runLength; 31463 } 31464 return decodedValues; 31465} 31466function decodeRleDeltaInt32(data, numRuns, numTotalValues) { 31467 const decodedValues = new Uint32Array(numTotalValues + 1); 31468 decodedValues[0] = 0; 31469 let offset = 1; 31470 let previousValue = decodedValues[0]; 31471 for (let i = 0; i < numRuns; i++) { 31472 const runLength = data[i]; 31473 const value = data[i + numRuns]; 31474 for (let j = offset; j < offset + runLength; j++) { 31475 decodedValues[j] = value + previousValue; 31476 previousValue = decodedValues[j]; 31477 } 31478 offset += runLength; 31479 } 31480 return decodedValues; 31481} 31482/** 31483* Decode Delta-RLE with multiple runs by fully reconstructing values. 31484* 31485* @param data RLE encoded data: [run1, run2, ..., value1, value2, ...] 31486* @param numRuns Number of runs in the RLE encoding 31487* @param numValues Total number of values to reconstruct 31488* @returns Reconstructed values with deltas applied 31489*/ 31490function decodeDeltaRleInt32(data, numRuns, numValues) { 31491 const result = new Int32Array(numValues); 31492 let outPos = 0; 31493 let previousValue = 0; 31494 for (let i = 0; i < numRuns; i++) { 31495 const runLength = data[i]; 31496 const zigZagDelta = data[i + numRuns]; 31497 const delta = decodeZigZagInt32Value(zigZagDelta); 31498 for (let j = 0; j < runLength; j++) { 31499 previousValue += delta; 31500 result[outPos++] = previousValue; 31501 } 31502 } 31503 return result; 31504} 31505/** 31506* Decode Delta-RLE with multiple runs for 64-bit integers. 31507*/ 31508function decodeDeltaRleInt64(data, numRuns, numValues) { 31509 const result = new BigInt64Array(numValues); 31510 let outPos = 0; 31511 let previousValue = 0n; 31512 for (let i = 0; i < numRuns; i++) { 31513 const runLength = Number(data[i]); 31514 const zigZagDelta = data[i + numRuns]; 31515 const delta = decodeZigZagInt64Value(zigZagDelta); 31516 for (let j = 0; j < runLength; j++) { 31517 previousValue += delta; 31518 result[outPos++] = previousValue; 31519 } 31520 } 31521 return result; 31522} 31523function decodeUnsignedZigZagDeltaInt32(data) { 31524 const decodedValues = new Uint32Array(data.length); 31525 decodedValues[0] = decodeZigZagInt32Value(data[0]) >>> 0; 31526 for (let i = 1; i < data.length; i++) decodedValues[i] = decodedValues[i - 1] + decodeZigZagInt32Value(data[i]) >>> 0; 31527 return decodedValues; 31528} 31529function decodeUnsignedZigZagDeltaInt64(data) { 31530 const decodedValues = new BigUint64Array(data.length); 31531 decodedValues[0] = BigInt.asUintN(64, decodeZigZagInt64Value(data[0])); 31532 for (let i = 1; i < data.length; i++) decodedValues[i] = BigInt.asUintN(64, decodedValues[i - 1] + decodeZigZagInt64Value(data[i])); 31533 return decodedValues; 31534} 31535function decodeUnsignedComponentwiseDeltaVec2(data) { 31536 if (data.length < 2) return new Uint32Array(data); 31537 const decodedData = new Uint32Array(data.length); 31538 decodedData[0] = decodeZigZagInt32Value(data[0]) >>> 0; 31539 decodedData[1] = decodeZigZagInt32Value(data[1]) >>> 0; 31540 for (let i = 2; i < data.length; i += 2) { 31541 decodedData[i] = decodedData[i - 2] + decodeZigZagInt32Value(data[i]) >>> 0; 31542 decodedData[i + 1] = decodedData[i - 1] + decodeZigZagInt32Value(data[i + 1]) >>> 0; 31543 } 31544 return decodedData; 31545} 31546function decodeUnsignedComponentwiseDeltaVec2Scaled(data, scale, min, max) { 31547 const scaledValues = decodeComponentwiseDeltaVec2Scaled(data, scale, min, max); 31548 return new Uint32Array(scaledValues); 31549} 31550function decodeUnsignedConstRleInt32(data) { 31551 return data[1]; 31552} 31553function decodeZigZagConstRleInt32(data) { 31554 return decodeZigZagInt32Value(data[1]); 31555} 31556function decodeZigZagSequenceRleInt32(data) { 31557 if (data.length === 2) { 31558 const value = decodeZigZagInt32Value(data[1]); 31559 return [value, value]; 31560 } 31561 return [decodeZigZagInt32Value(data[2]), decodeZigZagInt32Value(data[3])]; 31562} 31563function decodeUnsignedConstRleInt64(data) { 31564 return data[1]; 31565} 31566function decodeZigZagConstRleInt64(data) { 31567 return decodeZigZagInt64Value(data[1]); 31568} 31569function decodeZigZagSequenceRleInt64(data) { 31570 if (data.length === 2) { 31571 const value = decodeZigZagInt64Value(data[1]); 31572 return [value, value]; 31573 } 31574 return [decodeZigZagInt64Value(data[2]), decodeZigZagInt64Value(data[3])]; 31575} 31576//#endregion 31577//#region node_modules/@maplibre/mlt/dist/metadata/tile/physicalStreamType.js 31578var PhysicalStreamType; 31579(function(PhysicalStreamType) { 31580 PhysicalStreamType["PRESENT"] = "PRESENT"; 31581 PhysicalStreamType["DATA"] = "DATA"; 31582 PhysicalStreamType["OFFSET"] = "OFFSET"; 31583 PhysicalStreamType["LENGTH"] = "LENGTH"; 31584})(PhysicalStreamType || (PhysicalStreamType = {})); 31585//#endregion 31586//#region node_modules/@maplibre/mlt/dist/metadata/tile/dictionaryType.js 31587var DictionaryType; 31588(function(DictionaryType) { 31589 DictionaryType["NONE"] = "NONE"; 31590 DictionaryType["SINGLE"] = "SINGLE"; 31591 DictionaryType["SHARED"] = "SHARED"; 31592 DictionaryType["VERTEX"] = "VERTEX"; 31593 DictionaryType["MORTON"] = "MORTON"; 31594 DictionaryType["FSST"] = "FSST"; 31595})(DictionaryType || (DictionaryType = {})); 31596//#endregion 31597//#region node_modules/@maplibre/mlt/dist/metadata/tile/offsetType.js 31598var OffsetType; 31599(function(OffsetType) { 31600 OffsetType["VERTEX"] = "VERTEX"; 31601 OffsetType["INDEX"] = "INDEX"; 31602 OffsetType["STRING"] = "STRING"; 31603 OffsetType["KEY"] = "KEY"; 31604})(OffsetType || (OffsetType = {})); 31605//#endregion 31606//#region node_modules/@maplibre/mlt/dist/metadata/tile/lengthType.js 31607var LengthType; 31608(function(LengthType) { 31609 LengthType["VAR_BINARY"] = "VAR_BINARY"; 31610 LengthType["GEOMETRIES"] = "GEOMETRIES"; 31611 LengthType["PARTS"] = "PARTS"; 31612 LengthType["RINGS"] = "RINGS"; 31613 LengthType["TRIANGLES"] = "TRIANGLES"; 31614 LengthType["SYMBOL"] = "SYMBOL"; 31615 LengthType["DICTIONARY"] = "DICTIONARY"; 31616})(LengthType || (LengthType = {})); 31617//#endregion 31618//#region node_modules/@maplibre/mlt/dist/metadata/tile/streamMetadataDecoder.js 31619const PHYSICAL_STREAM_TYPE_BY_ID = [ 31620 PhysicalStreamType.PRESENT, 31621 PhysicalStreamType.DATA, 31622 PhysicalStreamType.OFFSET, 31623 PhysicalStreamType.LENGTH 31624]; 31625const LOGICAL_LEVEL_TECHNIQUE_BY_ID = [ 31626 LogicalLevelTechnique.NONE, 31627 LogicalLevelTechnique.DELTA, 31628 LogicalLevelTechnique.COMPONENTWISE_DELTA, 31629 LogicalLevelTechnique.RLE, 31630 LogicalLevelTechnique.MORTON 31631]; 31632const PHYSICAL_LEVEL_TECHNIQUE_BY_ID = [ 31633 PhysicalLevelTechnique.NONE, 31634 PhysicalLevelTechnique.FAST_PFOR, 31635 PhysicalLevelTechnique.VARINT 31636]; 31637const DICTIONARY_TYPE_BY_ID = [ 31638 DictionaryType.NONE, 31639 DictionaryType.SINGLE, 31640 DictionaryType.SHARED, 31641 DictionaryType.VERTEX, 31642 DictionaryType.MORTON, 31643 DictionaryType.FSST 31644]; 31645const OFFSET_TYPE_BY_ID = [ 31646 OffsetType.VERTEX, 31647 OffsetType.INDEX, 31648 OffsetType.STRING, 31649 OffsetType.KEY 31650]; 31651const LENGTH_TYPE_BY_ID = [ 31652 LengthType.VAR_BINARY, 31653 LengthType.GEOMETRIES, 31654 LengthType.PARTS, 31655 LengthType.RINGS, 31656 LengthType.TRIANGLES, 31657 LengthType.SYMBOL, 31658 LengthType.DICTIONARY 31659]; 31660function decodeStreamMetadata(tile, offset) { 31661 const streamMetadata = decodeStreamMetadataInternal(tile, offset); 31662 if (streamMetadata.logicalLevelTechnique1 === LogicalLevelTechnique.MORTON) return decodePartialMortonEncodedStreamMetadata(streamMetadata, tile, offset); 31663 if ((LogicalLevelTechnique.RLE === streamMetadata.logicalLevelTechnique1 || LogicalLevelTechnique.RLE === streamMetadata.logicalLevelTechnique2) && PhysicalLevelTechnique.NONE !== streamMetadata.physicalLevelTechnique) return decodePartialRleEncodedStreamMetadata(streamMetadata, tile, offset); 31664 return streamMetadata; 31665} 31666function decodePartialMortonEncodedStreamMetadata(streamMetadata, tile, offset) { 31667 const mortonInfo = decodeVarintInt32(tile, offset, 2); 31668 return { 31669 physicalStreamType: streamMetadata.physicalStreamType, 31670 logicalStreamType: streamMetadata.logicalStreamType, 31671 logicalLevelTechnique1: streamMetadata.logicalLevelTechnique1, 31672 logicalLevelTechnique2: streamMetadata.logicalLevelTechnique2, 31673 physicalLevelTechnique: streamMetadata.physicalLevelTechnique, 31674 numValues: streamMetadata.numValues, 31675 byteLength: streamMetadata.byteLength, 31676 decompressedCount: streamMetadata.decompressedCount, 31677 numBits: mortonInfo[0], 31678 coordinateShift: mortonInfo[1] 31679 }; 31680} 31681function decodePartialRleEncodedStreamMetadata(streamMetadata, tile, offset) { 31682 const rleInfo = decodeVarintInt32(tile, offset, 2); 31683 return { 31684 physicalStreamType: streamMetadata.physicalStreamType, 31685 logicalStreamType: streamMetadata.logicalStreamType, 31686 logicalLevelTechnique1: streamMetadata.logicalLevelTechnique1, 31687 logicalLevelTechnique2: streamMetadata.logicalLevelTechnique2, 31688 physicalLevelTechnique: streamMetadata.physicalLevelTechnique, 31689 numValues: streamMetadata.numValues, 31690 byteLength: streamMetadata.byteLength, 31691 decompressedCount: rleInfo[1], 31692 runs: rleInfo[0], 31693 numRleValues: rleInfo[1] 31694 }; 31695} 31696function decodeStreamMetadataInternal(tile, offset) { 31697 const stream_type = tile[offset.get()]; 31698 const physicalStreamType = PHYSICAL_STREAM_TYPE_BY_ID[stream_type >> 4]; 31699 let logicalStreamType = {}; 31700 switch (physicalStreamType) { 31701 case PhysicalStreamType.DATA: 31702 logicalStreamType = { dictionaryType: DICTIONARY_TYPE_BY_ID[stream_type & 15] }; 31703 break; 31704 case PhysicalStreamType.OFFSET: 31705 logicalStreamType = { offsetType: OFFSET_TYPE_BY_ID[stream_type & 15] }; 31706 break; 31707 case PhysicalStreamType.LENGTH: logicalStreamType = { lengthType: LENGTH_TYPE_BY_ID[stream_type & 15] }; 31708 } 31709 offset.increment(); 31710 const encodings_header = tile[offset.get()]; 31711 const llt1 = LOGICAL_LEVEL_TECHNIQUE_BY_ID[encodings_header >> 5]; 31712 const llt2 = LOGICAL_LEVEL_TECHNIQUE_BY_ID[encodings_header >> 2 & 7]; 31713 const plt = PHYSICAL_LEVEL_TECHNIQUE_BY_ID[encodings_header & 3]; 31714 offset.increment(); 31715 const sizeInfo = decodeVarintInt32(tile, offset, 2); 31716 const numValues = sizeInfo[0]; 31717 const byteLength = sizeInfo[1]; 31718 return { 31719 physicalStreamType, 31720 logicalStreamType, 31721 logicalLevelTechnique1: llt1, 31722 logicalLevelTechnique2: llt2, 31723 physicalLevelTechnique: plt, 31724 numValues, 31725 byteLength, 31726 decompressedCount: numValues 31727 }; 31728} 31729//#endregion 31730//#region node_modules/@maplibre/mlt/dist/vector/vectorType.js 31731var VectorType; 31732(function(VectorType) { 31733 VectorType[VectorType["FLAT"] = 0] = "FLAT"; 31734 VectorType[VectorType["CONST"] = 1] = "CONST"; 31735 VectorType[VectorType["SEQUENCE"] = 2] = "SEQUENCE"; 31736 VectorType[VectorType["DICTIONARY"] = 3] = "DICTIONARY"; 31737 VectorType[VectorType["FSST_DICTIONARY"] = 4] = "FSST_DICTIONARY"; 31738})(VectorType || (VectorType = {})); 31739//#endregion 31740//#region node_modules/@maplibre/mlt/dist/vector/flat/bitVector.js 31741var BitVector = class { 31742 /** 31743 * @param values The byte buffer containing the bit values in least-significant bit (LSB) 31744 * numbering 31745 */ 31746 constructor(values, size) { 31747 this.values = values; 31748 this._size = size; 31749 } 31750 get(index) { 31751 const byteIndex = Math.floor(index / 8); 31752 const bitIndex = index % 8; 31753 return (this.values[byteIndex] >> bitIndex & 1) === 1; 31754 } 31755 set(index, value) { 31756 const byteIndex = Math.floor(index / 8); 31757 const bitIndex = index % 8; 31758 this.values[byteIndex] = this.values[byteIndex] | (value ? 1 : 0) << bitIndex; 31759 } 31760 getInt(index) { 31761 const byteIndex = Math.floor(index / 8); 31762 const bitIndex = index % 8; 31763 return this.values[byteIndex] >> bitIndex & 1; 31764 } 31765 size() { 31766 return this._size; 31767 } 31768 getBuffer() { 31769 return this.values; 31770 } 31771}; 31772//#endregion 31773//#region node_modules/@maplibre/mlt/dist/decoding/unpackNullableUtils.js 31774/** 31775* Generic unpacking function. 31776* Reconstructs the full array by inserting default values at null positions. 31777* 31778* @param dataStream The compact data stream containing only non-null values 31779* @param presentBits BitVector indicating which positions have values (null if non-nullable) 31780* @param defaultValue The default value to insert at null positions (0, 0n, etc.) 31781* @returns Full array with default values at null positions 31782*/ 31783function unpackNullable(dataStream, presentBits, defaultValue) { 31784 if (!presentBits) return dataStream; 31785 const size = presentBits.size(); 31786 const constructor = dataStream.constructor; 31787 const result = new constructor(size); 31788 let counter = 0; 31789 for (let i = 0; i < size; i++) result[i] = presentBits.get(i) ? dataStream[counter++] : defaultValue; 31790 return result; 31791} 31792/** 31793* Special case for boolean columns because BitVector is not directly compatible with TypedArray. 31794* 31795* @param dataStream The compact BitVector data containing only non-null boolean values 31796* @param dataStreamSize The number of actual values in dataStream 31797* @param presentBits BitVector indicating which positions have values (null if non-nullable) 31798* @returns Uint8Array buffer for BitVector with false at null positions 31799*/ 31800function unpackNullableBoolean(dataStream, dataStreamSize, presentBits) { 31801 if (!presentBits) return dataStream; 31802 const numFeatures = presentBits.size(); 31803 const bitVector = new BitVector(dataStream, dataStreamSize); 31804 const result = new BitVector(new Uint8Array(Math.ceil(numFeatures / 8)), numFeatures); 31805 let counter = 0; 31806 for (let i = 0; i < numFeatures; i++) { 31807 const value = presentBits.get(i) ? bitVector.get(counter++) : false; 31808 result.set(i, value); 31809 } 31810 return result.getBuffer(); 31811} 31812//#endregion 31813//#region node_modules/@maplibre/mlt/dist/decoding/decodingUtils.js 31814function skipColumn(numStreams, tile, offset) { 31815 for (let i = 0; i < numStreams; i++) { 31816 const streamMetadata = decodeStreamMetadata(tile, offset); 31817 offset.add(streamMetadata.byteLength); 31818 } 31819} 31820function decodeBooleanRle(buffer, numBooleans, byteLength, pos, nullabilityBuffer) { 31821 const values = decodeByteRle(buffer, Math.ceil(numBooleans / 8), byteLength, pos); 31822 if (nullabilityBuffer) return unpackNullableBoolean(values, numBooleans, nullabilityBuffer); 31823 return values; 31824} 31825function decodeByteRle(buffer, numBytes, byteLength, pos) { 31826 const values = new Uint8Array(numBytes); 31827 let valueOffset = 0; 31828 const streamEndPos = pos.get() + byteLength; 31829 while (valueOffset < numBytes) { 31830 if (pos.get() >= streamEndPos) break; 31831 const header = buffer[pos.increment()]; 31832 if (header <= 127) { 31833 const numRuns = header + 3; 31834 const value = buffer[pos.increment()]; 31835 const endValueOffset = Math.min(valueOffset + numRuns, numBytes); 31836 values.fill(value, valueOffset, endValueOffset); 31837 valueOffset = endValueOffset; 31838 } else { 31839 const numLiterals = 256 - header; 31840 for (let i = 0; i < numLiterals && valueOffset < numBytes; i++) values[valueOffset++] = buffer[pos.increment()]; 31841 } 31842 } 31843 pos.set(streamEndPos); 31844 return values; 31845} 31846function decodeFloatsLE(encodedValues, pos, numValues, nullabilityBuffer) { 31847 const currentPos = pos.get(); 31848 const newOffset = currentPos + numValues * Float32Array.BYTES_PER_ELEMENT; 31849 const newBuf = new Uint8Array(encodedValues.subarray(currentPos, newOffset)).buffer; 31850 const fb = new Float32Array(newBuf); 31851 pos.set(newOffset); 31852 if (nullabilityBuffer) return unpackNullable(fb, nullabilityBuffer, 0); 31853 return fb; 31854} 31855function decodeDoublesLE(encodedValues, pos, numValues, nullabilityBuffer) { 31856 const currentPos = pos.get(); 31857 const newOffset = currentPos + numValues * Float64Array.BYTES_PER_ELEMENT; 31858 const newBuf = new Uint8Array(encodedValues.subarray(currentPos, newOffset)).buffer; 31859 const fb = new Float64Array(newBuf); 31860 pos.set(newOffset); 31861 if (nullabilityBuffer) return unpackNullable(fb, nullabilityBuffer, 0); 31862 return fb; 31863} 31864function decodeUint32sLE(encodedValues, pos, numValues) { 31865 const currentPos = pos.get(); 31866 const byteLength = numValues * Uint32Array.BYTES_PER_ELEMENT; 31867 const view = new DataView(encodedValues.buffer, encodedValues.byteOffset, encodedValues.byteLength); 31868 const values = new Uint32Array(numValues); 31869 for (let i = 0; i < numValues; i++) values[i] = view.getUint32(currentPos + i * Uint32Array.BYTES_PER_ELEMENT, true); 31870 pos.add(byteLength); 31871 return values; 31872} 31873function decodeUint64sLE(encodedValues, pos, numValues) { 31874 const currentPos = pos.get(); 31875 const byteLength = numValues * BigUint64Array.BYTES_PER_ELEMENT; 31876 const view = new DataView(encodedValues.buffer, encodedValues.byteOffset, encodedValues.byteLength); 31877 const values = new BigUint64Array(numValues); 31878 for (let i = 0; i < numValues; i++) values[i] = view.getBigUint64(currentPos + i * BigUint64Array.BYTES_PER_ELEMENT, true); 31879 pos.add(byteLength); 31880 return values; 31881} 31882const TEXT_DECODER_MIN_LENGTH = 12; 31883const utf8TextDecoder = new TextDecoder(); 31884function decodeString$2(buf, pos, end) { 31885 if (end - pos >= TEXT_DECODER_MIN_LENGTH) return utf8TextDecoder.decode(buf.subarray(pos, end)); 31886 return readUtf8(buf, pos, end); 31887} 31888function readUtf8(buf, pos, end) { 31889 let str = ""; 31890 let i = pos; 31891 while (i < end) { 31892 const b0 = buf[i]; 31893 let c = null; 31894 let bytesPerSequence = b0 > 239 ? 4 : b0 > 223 ? 3 : b0 > 191 ? 2 : 1; 31895 if (i + bytesPerSequence > end) break; 31896 let b1; 31897 let b2; 31898 let b3; 31899 if (bytesPerSequence === 1) { 31900 if (b0 < 128) c = b0; 31901 } else if (bytesPerSequence === 2) { 31902 b1 = buf[i + 1]; 31903 if ((b1 & 192) === 128) { 31904 c = (b0 & 31) << 6 | b1 & 63; 31905 if (c <= 127) c = null; 31906 } 31907 } else if (bytesPerSequence === 3) { 31908 b1 = buf[i + 1]; 31909 b2 = buf[i + 2]; 31910 if ((b1 & 192) === 128 && (b2 & 192) === 128) { 31911 c = (b0 & 15) << 12 | (b1 & 63) << 6 | b2 & 63; 31912 if (c <= 2047 || c >= 55296 && c <= 57343) c = null; 31913 } 31914 } else if (bytesPerSequence === 4) { 31915 b1 = buf[i + 1]; 31916 b2 = buf[i + 2]; 31917 b3 = buf[i + 3]; 31918 if ((b1 & 192) === 128 && (b2 & 192) === 128 && (b3 & 192) === 128) { 31919 c = (b0 & 15) << 18 | (b1 & 63) << 12 | (b2 & 63) << 6 | b3 & 63; 31920 if (c <= 65535 || c >= 1114112) c = null; 31921 } 31922 } 31923 if (c === null) { 31924 c = 65533; 31925 bytesPerSequence = 1; 31926 } else if (c > 65535) { 31927 c -= 65536; 31928 str += String.fromCharCode(c >>> 10 & 1023 | 55296); 31929 c = 56320 | c & 1023; 31930 } 31931 str += String.fromCharCode(c); 31932 i += bytesPerSequence; 31933 } 31934 return str; 31935} 31936//#endregion 31937//#region node_modules/@maplibre/mlt/dist/decoding/integerStreamDecoder.js 31938function decodeSignedInt32Stream(data, offset, streamMetadata, scalingData, nullabilityBuffer) { 31939 return decodeSignedInt32(decodePhysicalLevelTechnique(data, offset, streamMetadata), streamMetadata, scalingData, nullabilityBuffer); 31940} 31941function decodeUnsignedInt32Stream(data, offset, streamMetadata, scalingData, nullabilityBuffer) { 31942 return decodeUnsignedInt32(decodePhysicalLevelTechnique(data, offset, streamMetadata), streamMetadata, scalingData, nullabilityBuffer); 31943} 31944function decodeLengthStreamToOffsetBuffer(data, offset, streamMetadata) { 31945 return decodeLengthToOffsetBuffer(decodePhysicalLevelTechnique(data, offset, streamMetadata), streamMetadata); 31946} 31947function decodePhysicalLevelTechnique(data, offset, streamMetadata) { 31948 const physicalLevelTechnique = streamMetadata.physicalLevelTechnique; 31949 switch (physicalLevelTechnique) { 31950 case PhysicalLevelTechnique.FAST_PFOR: return decodeFastPfor(data, streamMetadata.numValues, streamMetadata.byteLength, offset); 31951 case PhysicalLevelTechnique.VARINT: return decodeVarintInt32(data, offset, streamMetadata.numValues); 31952 case PhysicalLevelTechnique.NONE: return decodeUint32sLE(data, offset, streamMetadata.numValues); 31953 default: throw new Error(`Specified physicalLevelTechnique ${physicalLevelTechnique} is not supported (yet).`); 31954 } 31955} 31956function decodePhysicalLevelTechniqueInt64(data, offset, streamMetadata) { 31957 const physicalLevelTechnique = streamMetadata.physicalLevelTechnique; 31958 switch (physicalLevelTechnique) { 31959 case PhysicalLevelTechnique.VARINT: return decodeVarintInt64(data, offset, streamMetadata.numValues); 31960 case PhysicalLevelTechnique.NONE: return decodeUint64sLE(data, offset, streamMetadata.numValues); 31961 default: throw new Error(`Specified physicalLevelTechnique ${physicalLevelTechnique} is not supported (yet).`); 31962 } 31963} 31964function decodeSignedConstInt32Stream(data, offset, streamMetadata) { 31965 const values = decodePhysicalLevelTechnique(data, offset, streamMetadata); 31966 if (values.length === 1) return decodeZigZagInt32Value(values[0]); 31967 return decodeZigZagConstRleInt32(values); 31968} 31969function decodeUnsignedConstInt32Stream(data, offset, streamMetadata) { 31970 const values = decodePhysicalLevelTechnique(data, offset, streamMetadata); 31971 if (values.length === 1) { 31972 if (streamMetadata.logicalLevelTechnique1 === LogicalLevelTechnique.DELTA) return decodeZigZagInt32Value(values[0]); 31973 return values[0]; 31974 } 31975 return decodeUnsignedConstRleInt32(values); 31976} 31977function decodeSequenceInt32Stream(data, offset, streamMetadata) { 31978 return decodeZigZagSequenceRleInt32(decodePhysicalLevelTechnique(data, offset, streamMetadata)); 31979} 31980function decodeSequenceInt64Stream(data, offset, streamMetadata) { 31981 return decodeZigZagSequenceRleInt64(decodeVarintInt64(data, offset, streamMetadata.numValues)); 31982} 31983function decodeSignedInt64Stream(data, offset, streamMetadata, nullabilityBuffer) { 31984 return decodeSignedInt64(decodePhysicalLevelTechniqueInt64(data, offset, streamMetadata), streamMetadata, nullabilityBuffer); 31985} 31986function decodeUnsignedInt64Stream(data, offset, streamMetadata, nullabilityBuffer) { 31987 return decodeUnsignedInt64(decodePhysicalLevelTechniqueInt64(data, offset, streamMetadata), streamMetadata, nullabilityBuffer); 31988} 31989function decodeUnsignedInt64AsFloat64Stream(data, offset, streamMetadata, nullabilityBuffer) { 31990 const values = decodeInt64AsFloat64(data, offset, streamMetadata, false); 31991 return nullabilityBuffer ? unpackNullable(values, nullabilityBuffer, 0) : values; 31992} 31993function decodeInt64AsFloat64(data, offset, streamMetadata, isSigned) { 31994 if (streamMetadata.physicalLevelTechnique === PhysicalLevelTechnique.VARINT) return decodeFloat64Values(decodeVarintFloat64(data, offset, streamMetadata.numValues), streamMetadata, isSigned); 31995 const values = decodePhysicalLevelTechniqueInt64(data, offset, streamMetadata); 31996 const decodedValues = isSigned ? decodeSignedInt64(values, streamMetadata) : decodeUnsignedInt64(values, streamMetadata); 31997 return Float64Array.from(decodedValues, Number); 31998} 31999function decodeSignedConstInt64Stream(data, offset, streamMetadata) { 32000 const values = decodePhysicalLevelTechniqueInt64(data, offset, streamMetadata); 32001 if (values.length === 1) return decodeZigZagInt64Value(values[0]); 32002 return decodeZigZagConstRleInt64(values); 32003} 32004function decodeUnsignedConstInt64Stream(data, offset, streamMetadata) { 32005 const values = decodePhysicalLevelTechniqueInt64(data, offset, streamMetadata); 32006 if (values.length === 1) { 32007 if (streamMetadata.logicalLevelTechnique1 === LogicalLevelTechnique.DELTA) return decodeZigZagInt64Value(values[0]); 32008 return values[0]; 32009 } 32010 return decodeUnsignedConstRleInt64(values); 32011} 32012/** 32013* This method decodes integer streams. 32014* Currently the encoder uses only fixed combinations of encodings. 32015* For performance reasons it is also uses a fixed combination of the encodings on the decoding side. 32016* The following encodings and combinations are used: 32017* - Morton Delta -> always sorted so not ZigZag encoding needed 32018* - Delta -> currently always in combination with ZigZag encoding 32019* - Rle -> in combination with ZigZag encoding if data type is signed 32020* - Delta Rle 32021* - Componentwise Delta -> always ZigZag encoding is used 32022*/ 32023function decodeSignedInt32(values, streamMetadata, scalingData, nullabilityBuffer) { 32024 let decodedValues; 32025 switch (streamMetadata.logicalLevelTechnique1) { 32026 case LogicalLevelTechnique.DELTA: 32027 if (streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.RLE) { 32028 const rleMetadata = streamMetadata; 32029 if (!nullabilityBuffer) return decodeDeltaRleInt32(values, rleMetadata.runs, rleMetadata.numRleValues); 32030 values = decodeUnsignedRleInt32(values, rleMetadata.runs, rleMetadata.numRleValues); 32031 decodedValues = decodeZigZagDeltaInt32(values); 32032 } else decodedValues = decodeZigZagDeltaInt32(values); 32033 break; 32034 case LogicalLevelTechnique.RLE: 32035 decodedValues = decodeZigZagRleInt32(values, streamMetadata.runs, streamMetadata.numRleValues); 32036 break; 32037 case LogicalLevelTechnique.MORTON: 32038 fastInverseDelta(values); 32039 decodedValues = new Int32Array(values); 32040 break; 32041 case LogicalLevelTechnique.COMPONENTWISE_DELTA: 32042 if (scalingData && !nullabilityBuffer) return decodeComponentwiseDeltaVec2Scaled(values, scalingData.scale, scalingData.min, scalingData.max); 32043 decodedValues = decodeComponentwiseDeltaVec2(values); 32044 break; 32045 case LogicalLevelTechnique.NONE: 32046 decodedValues = decodeZigZagInt32(values); 32047 break; 32048 default: throw new Error(`The specified Logical level technique is not supported: ${streamMetadata.logicalLevelTechnique1}`); 32049 } 32050 if (nullabilityBuffer) return unpackNullable(decodedValues, nullabilityBuffer, 0); 32051 return decodedValues; 32052} 32053function decodeUnsignedInt32(values, streamMetadata, scalingData, nullabilityBuffer) { 32054 let decodedValues; 32055 switch (streamMetadata.logicalLevelTechnique1) { 32056 case LogicalLevelTechnique.DELTA: 32057 if (streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.RLE) { 32058 const rleMetadata = streamMetadata; 32059 decodedValues = decodeUnsignedZigZagDeltaInt32(decodeUnsignedRleInt32(values, rleMetadata.runs, rleMetadata.numRleValues)); 32060 } else decodedValues = decodeUnsignedZigZagDeltaInt32(values); 32061 break; 32062 case LogicalLevelTechnique.RLE: 32063 decodedValues = decodeUnsignedRleInt32(values, streamMetadata.runs, streamMetadata.numRleValues); 32064 break; 32065 case LogicalLevelTechnique.MORTON: 32066 fastInverseDelta(values); 32067 decodedValues = values; 32068 break; 32069 case LogicalLevelTechnique.COMPONENTWISE_DELTA: 32070 if (scalingData && !nullabilityBuffer) decodedValues = decodeUnsignedComponentwiseDeltaVec2Scaled(values, scalingData.scale, scalingData.min, scalingData.max); 32071 else decodedValues = decodeUnsignedComponentwiseDeltaVec2(values); 32072 break; 32073 case LogicalLevelTechnique.NONE: 32074 decodedValues = values; 32075 break; 32076 default: throw new Error(`The specified Logical level technique is not supported: ${streamMetadata.logicalLevelTechnique1}`); 32077 } 32078 if (nullabilityBuffer) return unpackNullable(decodedValues, nullabilityBuffer, 0); 32079 return decodedValues; 32080} 32081function decodeSignedInt64(values, streamMetadata, nullabilityBuffer) { 32082 let decodedValues; 32083 switch (streamMetadata.logicalLevelTechnique1) { 32084 case LogicalLevelTechnique.DELTA: 32085 if (streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.RLE) { 32086 const rleMetadata = streamMetadata; 32087 if (!nullabilityBuffer) return decodeDeltaRleInt64(values, rleMetadata.runs, rleMetadata.numRleValues); 32088 values = decodeUnsignedRleInt64(values, rleMetadata.runs, rleMetadata.numRleValues); 32089 decodedValues = decodeZigZagDeltaInt64(values); 32090 } else decodedValues = decodeZigZagDeltaInt64(values); 32091 break; 32092 case LogicalLevelTechnique.RLE: 32093 decodedValues = decodeZigZagRleInt64(values, streamMetadata.runs, streamMetadata.numRleValues); 32094 break; 32095 case LogicalLevelTechnique.NONE: 32096 decodedValues = decodeZigZagInt64(values); 32097 break; 32098 default: throw new Error(`The specified Logical level technique is not supported: ${streamMetadata.logicalLevelTechnique1}`); 32099 } 32100 if (nullabilityBuffer) return unpackNullable(decodedValues, nullabilityBuffer, 0n); 32101 return decodedValues; 32102} 32103function decodeUnsignedInt64(values, streamMetadata, nullabilityBuffer) { 32104 let decodedValues; 32105 switch (streamMetadata.logicalLevelTechnique1) { 32106 case LogicalLevelTechnique.DELTA: 32107 if (streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.RLE) { 32108 const rleMetadata = streamMetadata; 32109 decodedValues = decodeUnsignedZigZagDeltaInt64(decodeUnsignedRleInt64(values, rleMetadata.runs, rleMetadata.numRleValues)); 32110 } else decodedValues = decodeUnsignedZigZagDeltaInt64(values); 32111 break; 32112 case LogicalLevelTechnique.RLE: 32113 decodedValues = decodeUnsignedRleInt64(values, streamMetadata.runs, streamMetadata.numRleValues); 32114 break; 32115 case LogicalLevelTechnique.NONE: 32116 decodedValues = values; 32117 break; 32118 default: throw new Error(`The specified Logical level technique is not supported: ${streamMetadata.logicalLevelTechnique1}`); 32119 } 32120 if (nullabilityBuffer) return unpackNullable(decodedValues, nullabilityBuffer, 0n); 32121 return decodedValues; 32122} 32123function decodeFloat64Values(values, streamMetadata, isSigned) { 32124 switch (streamMetadata.logicalLevelTechnique1) { 32125 case LogicalLevelTechnique.DELTA: 32126 if (streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.RLE) { 32127 const rleMetadata = streamMetadata; 32128 values = decodeUnsignedRleFloat64(values, rleMetadata.runs, rleMetadata.numRleValues); 32129 } 32130 decodeZigZagDeltaFloat64(values); 32131 return values; 32132 case LogicalLevelTechnique.RLE: return decodeRleFloat64(values, streamMetadata, isSigned); 32133 case LogicalLevelTechnique.NONE: 32134 if (isSigned) decodeZigZagFloat64(values); 32135 return values; 32136 default: throw new Error(`The specified Logical level technique is not supported: ${streamMetadata.logicalLevelTechnique1}`); 32137 } 32138} 32139function decodeLengthToOffsetBuffer(values, streamMetadata) { 32140 if (streamMetadata.logicalLevelTechnique1 === LogicalLevelTechnique.DELTA && streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.NONE) return decodeZigZagDeltaOfDeltaInt32(values); 32141 if (streamMetadata.logicalLevelTechnique1 === LogicalLevelTechnique.RLE && streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.NONE) { 32142 const rleMetadata = streamMetadata; 32143 return decodeRleDeltaInt32(values, rleMetadata.runs, rleMetadata.numRleValues); 32144 } 32145 if (streamMetadata.logicalLevelTechnique1 === LogicalLevelTechnique.NONE && streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.NONE) { 32146 inverseDelta(values); 32147 const offsets = new Uint32Array(streamMetadata.numValues + 1); 32148 offsets[0] = 0; 32149 offsets.set(values, 1); 32150 return offsets; 32151 } 32152 if (streamMetadata.logicalLevelTechnique1 === LogicalLevelTechnique.DELTA && streamMetadata.logicalLevelTechnique2 === LogicalLevelTechnique.RLE) { 32153 const rleMetadata = streamMetadata; 32154 const decodedValues = decodeZigZagRleDeltaInt32(values, rleMetadata.runs, rleMetadata.numRleValues); 32155 fastInverseDelta(decodedValues); 32156 return new Uint32Array(decodedValues); 32157 } 32158 throw new Error("Only delta encoding is supported for transforming length to offset streams yet."); 32159} 32160function getVectorType(streamMetadata, sizeOrNullabilityBuffer, data, offset, varintWidth = "int32") { 32161 const logicalLevelTechnique1 = streamMetadata.logicalLevelTechnique1; 32162 if (logicalLevelTechnique1 === LogicalLevelTechnique.RLE) return streamMetadata.runs === 1 ? VectorType.CONST : VectorType.FLAT; 32163 if (logicalLevelTechnique1 !== LogicalLevelTechnique.DELTA || streamMetadata.logicalLevelTechnique2 !== LogicalLevelTechnique.RLE) return streamMetadata.numValues === 1 ? VectorType.CONST : VectorType.FLAT; 32164 const numFeatures = sizeOrNullabilityBuffer instanceof BitVector ? sizeOrNullabilityBuffer.size() : sizeOrNullabilityBuffer; 32165 const rleMetadata = streamMetadata; 32166 if (rleMetadata.numRleValues !== numFeatures) return VectorType.FLAT; 32167 if (rleMetadata.runs === 1) return VectorType.SEQUENCE; 32168 if (rleMetadata.runs !== 2) return streamMetadata.numValues === 1 ? VectorType.CONST : VectorType.FLAT; 32169 const savedOffset = offset.get(); 32170 if (streamMetadata.physicalLevelTechnique === PhysicalLevelTechnique.VARINT) { 32171 if (isDeltaRleSequenceVarintWidth(data, offset, varintWidth)) return VectorType.SEQUENCE; 32172 return streamMetadata.numValues === 1 ? VectorType.CONST : VectorType.FLAT; 32173 } 32174 const byteOffset = offset.get(); 32175 const values = new Int32Array(data.buffer, data.byteOffset + byteOffset, 4); 32176 offset.set(savedOffset); 32177 const zigZagOne = 2; 32178 if (values[2] === zigZagOne && values[3] === zigZagOne) return VectorType.SEQUENCE; 32179 return streamMetadata.numValues === 1 ? VectorType.CONST : VectorType.FLAT; 32180} 32181function isDeltaRleSequenceVarintWidth(data, offset, varintWidth) { 32182 const peekOffset = new IntWrapper(offset.get()); 32183 if (varintWidth === "int64") { 32184 const values = decodeVarintInt64(data, peekOffset, 4); 32185 return values[2] === 2n && values[3] === 2n; 32186 } 32187 const values = decodeVarintInt32(data, peekOffset, 4); 32188 return values[2] === 2 && values[3] === 2; 32189} 32190function decodeRleFloat64(data, streamMetadata, isSigned) { 32191 return isSigned ? decodeZigZagRleFloat64(data, streamMetadata.runs, streamMetadata.numRleValues) : decodeUnsignedRleFloat64(data, streamMetadata.runs, streamMetadata.numRleValues); 32192} 32193//#endregion 32194//#region node_modules/@maplibre/mlt/dist/vector/flat/int64FlatVector.js 32195var Int64FlatVector = class extends FixedSizeVector { 32196 getValueFromBuffer(index) { 32197 return this.dataBuffer[index]; 32198 } 32199}; 32200//#endregion 32201//#region node_modules/@maplibre/mlt/dist/vector/sequence/int64SequenceVector.js 32202var Int64SequenceVector = class extends SequenceVector { 32203 constructor(name, baseValue, delta, size, isSigned) { 32204 super(name, isSigned ? BigInt64Array.of(baseValue) : BigUint64Array.of(baseValue), delta, size); 32205 } 32206 getValueFromBuffer(index) { 32207 return this.dataBuffer[0] + BigInt(index) * this.delta; 32208 } 32209}; 32210//#endregion 32211//#region node_modules/@maplibre/mlt/dist/vector/geometry/zOrderCurve.js 32212function decodeZOrderCurve(mortonCode, numBits, coordinateShift) { 32213 return { 32214 x: decodeMorton(mortonCode, numBits) - coordinateShift, 32215 y: decodeMorton(mortonCode >> 1, numBits) - coordinateShift 32216 }; 32217} 32218function decodeMorton(code, numBits) { 32219 let coordinate = 0; 32220 for (let i = 0; i < numBits; i++) coordinate |= (code & 1 << 2 * i) >> i; 32221 return coordinate; 32222} 32223//#endregion 32224//#region node_modules/@maplibre/mlt/dist/vector/geometry/geometryType.js 32225var GEOMETRY_TYPE; 32226(function(GEOMETRY_TYPE) { 32227 GEOMETRY_TYPE[GEOMETRY_TYPE["POINT"] = 0] = "POINT"; 32228 GEOMETRY_TYPE[GEOMETRY_TYPE["LINESTRING"] = 1] = "LINESTRING"; 32229 GEOMETRY_TYPE[GEOMETRY_TYPE["POLYGON"] = 2] = "POLYGON"; 32230 GEOMETRY_TYPE[GEOMETRY_TYPE["MULTIPOINT"] = 3] = "MULTIPOINT"; 32231 GEOMETRY_TYPE[GEOMETRY_TYPE["MULTILINESTRING"] = 4] = "MULTILINESTRING"; 32232 GEOMETRY_TYPE[GEOMETRY_TYPE["MULTIPOLYGON"] = 5] = "MULTIPOLYGON"; 32233})(GEOMETRY_TYPE || (GEOMETRY_TYPE = {})); 32234var SINGLE_PART_GEOMETRY_TYPE; 32235(function(SINGLE_PART_GEOMETRY_TYPE) { 32236 SINGLE_PART_GEOMETRY_TYPE[SINGLE_PART_GEOMETRY_TYPE["POINT"] = 0] = "POINT"; 32237 SINGLE_PART_GEOMETRY_TYPE[SINGLE_PART_GEOMETRY_TYPE["LINESTRING"] = 1] = "LINESTRING"; 32238 SINGLE_PART_GEOMETRY_TYPE[SINGLE_PART_GEOMETRY_TYPE["POLYGON"] = 2] = "POLYGON"; 32239})(SINGLE_PART_GEOMETRY_TYPE || (SINGLE_PART_GEOMETRY_TYPE = {})); 32240//#endregion 32241//#region node_modules/@maplibre/mlt/dist/vector/geometry/vertexBufferType.js 32242var VertexBufferType; 32243(function(VertexBufferType) { 32244 VertexBufferType[VertexBufferType["MORTON"] = 0] = "MORTON"; 32245 VertexBufferType[VertexBufferType["VEC_2"] = 1] = "VEC_2"; 32246 VertexBufferType[VertexBufferType["VEC_3"] = 2] = "VEC_3"; 32247})(VertexBufferType || (VertexBufferType = {})); 32248//#endregion 32249//#region node_modules/@maplibre/mlt/dist/vector/geometry/geometryVectorConverter.js 32250function convertGeometryVector(geometryVector) { 32251 const geometries = new Array(geometryVector.numGeometries); 32252 let partOffsetCounter = 1; 32253 let ringOffsetsCounter = 1; 32254 let geometryOffsetsCounter = 1; 32255 let geometryCounter = 0; 32256 let vertexBufferOffset = 0; 32257 let vertexOffsetsOffset = 0; 32258 const mortonSettings = geometryVector.mortonSettings; 32259 const topologyVector = geometryVector.topologyVector; 32260 const geometryOffsets = topologyVector.geometryOffsets; 32261 const partOffsets = topologyVector.partOffsets; 32262 const ringOffsets = topologyVector.ringOffsets; 32263 const vertexOffsets = geometryVector.vertexOffsets; 32264 const nonOffset = !vertexOffsets || vertexOffsets.length === 0; 32265 const containsPolygon = geometryVector.containsPolygonGeometry(); 32266 const vertexBuffer = geometryVector.vertexBuffer; 32267 for (let i = 0; i < geometryVector.numGeometries; i++) { 32268 const geometryType = geometryVector.geometryType(i); 32269 switch (geometryType) { 32270 case GEOMETRY_TYPE.POINT: 32271 { 32272 let x; 32273 let y; 32274 if (nonOffset) { 32275 x = vertexBuffer[vertexBufferOffset++]; 32276 y = vertexBuffer[vertexBufferOffset++]; 32277 } else if (geometryVector.vertexBufferType === VertexBufferType.MORTON) { 32278 const mortonCode = vertexBuffer[vertexOffsets[vertexOffsetsOffset++]]; 32279 const vertex = decodeZOrderCurve(mortonCode, mortonSettings.numBits, mortonSettings.coordinateShift); 32280 x = vertex.x; 32281 y = vertex.y; 32282 } else { 32283 const offset = vertexOffsets[vertexOffsetsOffset++] * 2; 32284 x = vertexBuffer[offset]; 32285 y = vertexBuffer[offset + 1]; 32286 } 32287 geometries[geometryCounter++] = [[new Point(x, y)]]; 32288 if (geometryOffsets) geometryOffsetsCounter++; 32289 if (partOffsets) partOffsetCounter++; 32290 if (ringOffsets) ringOffsetsCounter++; 32291 } 32292 break; 32293 case GEOMETRY_TYPE.MULTIPOINT: 32294 { 32295 const numPoints = geometryOffsets[geometryOffsetsCounter] - geometryOffsets[geometryOffsetsCounter - 1]; 32296 geometryOffsetsCounter++; 32297 let points; 32298 if (nonOffset) { 32299 points = new Array(numPoints); 32300 for (let j = 0; j < numPoints; j++) { 32301 const x = vertexBuffer[vertexBufferOffset++]; 32302 const y = vertexBuffer[vertexBufferOffset++]; 32303 points[j] = new Point(x, y); 32304 } 32305 } else { 32306 points = decodeDictionaryEncodedVertices(geometryVector.vertexBufferType, vertexBuffer, vertexOffsets, vertexOffsetsOffset, numPoints, false, mortonSettings); 32307 vertexOffsetsOffset += numPoints; 32308 } 32309 geometries[geometryCounter++] = points.map((point) => [point]); 32310 partOffsetCounter += numPoints; 32311 ringOffsetsCounter += numPoints; 32312 } 32313 break; 32314 case GEOMETRY_TYPE.LINESTRING: 32315 { 32316 let numVertices; 32317 if (containsPolygon) { 32318 numVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1]; 32319 ringOffsetsCounter++; 32320 } else numVertices = partOffsets[partOffsetCounter] - partOffsets[partOffsetCounter - 1]; 32321 partOffsetCounter++; 32322 let vertices; 32323 if (nonOffset) { 32324 vertices = getLineStringOrRing(vertexBuffer, vertexBufferOffset, numVertices, false); 32325 vertexBufferOffset += numVertices * 2; 32326 } else { 32327 vertices = decodeDictionaryEncodedVertices(geometryVector.vertexBufferType, vertexBuffer, vertexOffsets, vertexOffsetsOffset, numVertices, false, mortonSettings); 32328 vertexOffsetsOffset += numVertices; 32329 } 32330 geometries[geometryCounter++] = [vertices]; 32331 if (geometryOffsets) geometryOffsetsCounter++; 32332 } 32333 break; 32334 case GEOMETRY_TYPE.POLYGON: 32335 { 32336 const numRings = partOffsets[partOffsetCounter] - partOffsets[partOffsetCounter - 1]; 32337 partOffsetCounter++; 32338 const rings = new Array(numRings - 1); 32339 let shell; 32340 let numVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1]; 32341 ringOffsetsCounter++; 32342 if (nonOffset) { 32343 shell = getLineStringOrRing(vertexBuffer, vertexBufferOffset, numVertices, true); 32344 vertexBufferOffset += numVertices * 2; 32345 for (let j = 0; j < rings.length; j++) { 32346 numVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1]; 32347 ringOffsetsCounter++; 32348 rings[j] = getLineStringOrRing(vertexBuffer, vertexBufferOffset, numVertices, true); 32349 vertexBufferOffset += numVertices * 2; 32350 } 32351 } else { 32352 shell = decodeDictionaryEncodedVertices(geometryVector.vertexBufferType, vertexBuffer, vertexOffsets, vertexOffsetsOffset, numVertices, true, mortonSettings); 32353 vertexOffsetsOffset += numVertices; 32354 for (let j = 0; j < rings.length; j++) { 32355 numVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1]; 32356 ringOffsetsCounter++; 32357 rings[j] = decodeDictionaryEncodedVertices(geometryVector.vertexBufferType, vertexBuffer, vertexOffsets, vertexOffsetsOffset, numVertices, true, mortonSettings); 32358 vertexOffsetsOffset += numVertices; 32359 } 32360 } 32361 geometries[geometryCounter++] = [shell].concat(rings); 32362 if (geometryOffsets) geometryOffsetsCounter++; 32363 } 32364 break; 32365 case GEOMETRY_TYPE.MULTILINESTRING: 32366 { 32367 const numLineStrings = geometryOffsets[geometryOffsetsCounter] - geometryOffsets[geometryOffsetsCounter - 1]; 32368 geometryOffsetsCounter++; 32369 const lineStrings = new Array(numLineStrings); 32370 for (let j = 0; j < numLineStrings; j++) { 32371 let numVertices; 32372 if (containsPolygon) { 32373 numVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1]; 32374 ringOffsetsCounter++; 32375 } else numVertices = partOffsets[partOffsetCounter] - partOffsets[partOffsetCounter - 1]; 32376 partOffsetCounter++; 32377 if (nonOffset) { 32378 lineStrings[j] = getLineStringOrRing(vertexBuffer, vertexBufferOffset, numVertices, false); 32379 vertexBufferOffset += numVertices * 2; 32380 } else { 32381 const vertices = decodeDictionaryEncodedVertices(geometryVector.vertexBufferType, vertexBuffer, vertexOffsets, vertexOffsetsOffset, numVertices, false, mortonSettings); 32382 lineStrings[j] = vertices; 32383 vertexOffsetsOffset += numVertices; 32384 } 32385 } 32386 geometries[geometryCounter++] = lineStrings; 32387 } 32388 break; 32389 case GEOMETRY_TYPE.MULTIPOLYGON: 32390 { 32391 const numPolygons = geometryOffsets[geometryOffsetsCounter] - geometryOffsets[geometryOffsetsCounter - 1]; 32392 geometryOffsetsCounter++; 32393 const polygons = new Array(numPolygons); 32394 for (let j = 0; j < numPolygons; j++) { 32395 const numRings = partOffsets[partOffsetCounter] - partOffsets[partOffsetCounter - 1]; 32396 partOffsetCounter++; 32397 let shell; 32398 const rings = new Array(numRings - 1); 32399 const numVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1]; 32400 ringOffsetsCounter++; 32401 if (nonOffset) { 32402 shell = getLineStringOrRing(vertexBuffer, vertexBufferOffset, numVertices, true); 32403 vertexBufferOffset += numVertices * 2; 32404 } else { 32405 shell = decodeDictionaryEncodedVertices(geometryVector.vertexBufferType, vertexBuffer, vertexOffsets, vertexOffsetsOffset, numVertices, true, mortonSettings); 32406 vertexOffsetsOffset += numVertices; 32407 } 32408 for (let k = 0; k < rings.length; k++) { 32409 const numRingVertices = ringOffsets[ringOffsetsCounter] - ringOffsets[ringOffsetsCounter - 1]; 32410 ringOffsetsCounter++; 32411 if (nonOffset) { 32412 rings[k] = getLineStringOrRing(vertexBuffer, vertexBufferOffset, numRingVertices, true); 32413 vertexBufferOffset += numRingVertices * 2; 32414 } else { 32415 rings[k] = decodeDictionaryEncodedVertices(geometryVector.vertexBufferType, vertexBuffer, vertexOffsets, vertexOffsetsOffset, numRingVertices, true, mortonSettings); 32416 vertexOffsetsOffset += numRingVertices; 32417 } 32418 } 32419 polygons[j] = [shell].concat(rings); 32420 } 32421 geometries[geometryCounter++] = polygons.flat(); 32422 } 32423 break; 32424 default: throw new Error(`The specified geometry type (${geometryType}) is currently not supported.`); 32425 } 32426 } 32427 return geometries; 32428} 32429function decodeDictionaryEncodedVertices(vertexBufferType, vertexBuffer, vertexOffsets, vertexOffset, numVertices, isRing, mortonSettings) { 32430 if (vertexBufferType === VertexBufferType.MORTON) return decodeMortonDictionaryEncodedVertices(vertexBuffer, vertexOffsets, vertexOffset, numVertices, isRing, mortonSettings); 32431 else return decodeVec2DictionaryEncodedVertices(vertexBuffer, vertexOffsets, vertexOffset, numVertices, isRing); 32432} 32433function getLineStringOrRing(vertexBuffer, startIndex, numVertices, isRing) { 32434 const vertices = new Array(isRing ? numVertices + 1 : numVertices); 32435 for (let i = 0; i < numVertices * 2; i += 2) { 32436 const x = vertexBuffer[startIndex + i]; 32437 const y = vertexBuffer[startIndex + i + 1]; 32438 vertices[i / 2] = new Point(x, y); 32439 } 32440 if (isRing) vertices[vertices.length - 1] = vertices[0]; 32441 return vertices; 32442} 32443function decodeVec2DictionaryEncodedVertices(vertexBuffer, vertexOffsets, vertexOffset, numVertices, isRing) { 32444 const vertices = new Array(isRing ? numVertices + 1 : numVertices); 32445 for (let i = 0; i < numVertices * 2; i += 2) { 32446 const offset = vertexOffsets[vertexOffset + i / 2] * 2; 32447 const x = vertexBuffer[offset]; 32448 const y = vertexBuffer[offset + 1]; 32449 vertices[i / 2] = new Point(x, y); 32450 } 32451 if (isRing) vertices[vertices.length - 1] = vertices[0]; 32452 return vertices; 32453} 32454function decodeMortonDictionaryEncodedVertices(vertexBuffer, vertexOffsets, vertexOffset, numVertices, isRing, mortonSettings) { 32455 const vertices = new Array(isRing ? numVertices + 1 : numVertices); 32456 for (let i = 0; i < numVertices; i++) { 32457 const mortonEncodedVertex = vertexBuffer[vertexOffsets[vertexOffset + i]]; 32458 const vertex = decodeZOrderCurve(mortonEncodedVertex, mortonSettings.numBits, mortonSettings.coordinateShift); 32459 vertices[i] = new Point(vertex.x, vertex.y); 32460 } 32461 if (isRing) vertices[vertices.length - 1] = vertices[0]; 32462 return vertices; 32463} 32464//#endregion 32465//#region node_modules/@maplibre/mlt/dist/vector/geometry/geometryVector.js 32466var GeometryVector = class { 32467 constructor(_vertexBufferType, _topologyVector, _vertexOffsets, _vertexBuffer, _mortonSettings) { 32468 this._vertexBufferType = _vertexBufferType; 32469 this._topologyVector = _topologyVector; 32470 this._vertexOffsets = _vertexOffsets; 32471 this._vertexBuffer = _vertexBuffer; 32472 this._mortonSettings = _mortonSettings; 32473 } 32474 get vertexBufferType() { 32475 return this._vertexBufferType; 32476 } 32477 get topologyVector() { 32478 return this._topologyVector; 32479 } 32480 get vertexOffsets() { 32481 return this._vertexOffsets; 32482 } 32483 get vertexBuffer() { 32484 return this._vertexBuffer; 32485 } 32486 getSimpleEncodedVertex(index) { 32487 const offset = this.vertexOffsets ? this.vertexOffsets[index] * 2 : index * 2; 32488 return [this.vertexBuffer[offset], this.vertexBuffer[offset + 1]]; 32489 } 32490 getVertex(index) { 32491 if (this.vertexOffsets && this.mortonSettings) { 32492 const vertexOffset = this.vertexOffsets[index]; 32493 const mortonEncodedVertex = this.vertexBuffer[vertexOffset]; 32494 const vertex = decodeZOrderCurve(mortonEncodedVertex, this.mortonSettings.numBits, this.mortonSettings.coordinateShift); 32495 return [vertex.x, vertex.y]; 32496 } 32497 const offset = this.vertexOffsets ? this.vertexOffsets[index] * 2 : index * 2; 32498 return [this.vertexBuffer[offset], this.vertexBuffer[offset + 1]]; 32499 } 32500 getGeometries() { 32501 return convertGeometryVector(this); 32502 } 32503 get mortonSettings() { 32504 return this._mortonSettings; 32505 } 32506}; 32507//#endregion 32508//#region node_modules/@maplibre/mlt/dist/vector/geometry/constGeometryVector.js 32509function createConstGeometryVector(numGeometries, geometryType, topologyVector, vertexOffsets, vertexBuffer) { 32510 return new ConstGeometryVector(numGeometries, geometryType, VertexBufferType.VEC_2, topologyVector, vertexOffsets, vertexBuffer); 32511} 32512function createMortonEncodedConstGeometryVector(numGeometries, geometryType, topologyVector, vertexOffsets, vertexBuffer, mortonInfo) { 32513 return new ConstGeometryVector(numGeometries, geometryType, VertexBufferType.MORTON, topologyVector, vertexOffsets, vertexBuffer, mortonInfo); 32514} 32515var ConstGeometryVector = class extends GeometryVector { 32516 constructor(_numGeometries, _geometryType, vertexBufferType, topologyVector, vertexOffsets, vertexBuffer, mortonSettings) { 32517 super(vertexBufferType, topologyVector, vertexOffsets, vertexBuffer, mortonSettings); 32518 this._numGeometries = _numGeometries; 32519 this._geometryType = _geometryType; 32520 } 32521 geometryType(_index) { 32522 return this._geometryType; 32523 } 32524 get numGeometries() { 32525 return this._numGeometries; 32526 } 32527 containsPolygonGeometry() { 32528 return this._geometryType === GEOMETRY_TYPE.POLYGON || this._geometryType === GEOMETRY_TYPE.MULTIPOLYGON; 32529 } 32530 containsSingleGeometryType() { 32531 return true; 32532 } 32533}; 32534//#endregion 32535//#region node_modules/@maplibre/mlt/dist/vector/geometry/flatGeometryVector.js 32536function createFlatGeometryVector(geometryTypes, topologyVector, vertexOffsets, vertexBuffer) { 32537 return new FlatGeometryVector(VertexBufferType.VEC_2, geometryTypes, topologyVector, vertexOffsets, vertexBuffer); 32538} 32539function createFlatGeometryVectorMortonEncoded(geometryTypes, topologyVector, vertexOffsets, vertexBuffer, mortonInfo) { 32540 return new FlatGeometryVector(VertexBufferType.MORTON, geometryTypes, topologyVector, vertexOffsets, vertexBuffer, mortonInfo); 32541} 32542var FlatGeometryVector = class extends GeometryVector { 32543 constructor(vertexBufferType, _geometryTypes, topologyVector, vertexOffsets, vertexBuffer, mortonSettings) { 32544 super(vertexBufferType, topologyVector, vertexOffsets, vertexBuffer, mortonSettings); 32545 this._geometryTypes = _geometryTypes; 32546 } 32547 geometryType(index) { 32548 return this._geometryTypes[index]; 32549 } 32550 get numGeometries() { 32551 return this._geometryTypes.length; 32552 } 32553 containsPolygonGeometry() { 32554 for (let i = 0; i < this.numGeometries; i++) if (this.geometryType(i) === GEOMETRY_TYPE.POLYGON || this.geometryType(i) === GEOMETRY_TYPE.MULTIPOLYGON) return true; 32555 return false; 32556 } 32557 containsSingleGeometryType() { 32558 return false; 32559 } 32560}; 32561//#endregion 32562//#region node_modules/@maplibre/mlt/dist/vector/geometry/gpuVector.js 32563var GpuVector = class { 32564 constructor(_triangleOffsets, _indexBuffer, _vertexBuffer, _topologyVector) { 32565 this._triangleOffsets = _triangleOffsets; 32566 this._indexBuffer = _indexBuffer; 32567 this._vertexBuffer = _vertexBuffer; 32568 this._topologyVector = _topologyVector; 32569 } 32570 get triangleOffsets() { 32571 return this._triangleOffsets; 32572 } 32573 get indexBuffer() { 32574 return this._indexBuffer; 32575 } 32576 get vertexBuffer() { 32577 return this._vertexBuffer; 32578 } 32579 get topologyVector() { 32580 return this._topologyVector; 32581 } 32582 getGeometries() { 32583 if (!this._topologyVector) throw new Error("Cannot convert GpuVector to coordinates without topology information"); 32584 const types = new Uint32Array(this.numGeometries); 32585 for (let i = 0; i < this.numGeometries; i++) types[i] = this.geometryType(i); 32586 return createFlatGeometryVector(types, this._topologyVector, void 0, this._vertexBuffer).getGeometries(); 32587 } 32588 [Symbol.iterator]() { 32589 return null; 32590 } 32591}; 32592//#endregion 32593//#region node_modules/@maplibre/mlt/dist/vector/geometry/constGpuVector.js 32594function createConstGpuVector(numGeometries, geometryType, triangleOffsets, indexBuffer, vertexBuffer, topologyVector) { 32595 return new ConstGpuVector(numGeometries, geometryType, triangleOffsets, indexBuffer, vertexBuffer, topologyVector); 32596} 32597var ConstGpuVector = class extends GpuVector { 32598 constructor(_numGeometries, _geometryType, triangleOffsets, indexBuffer, vertexBuffer, topologyVector) { 32599 super(triangleOffsets, indexBuffer, vertexBuffer, topologyVector); 32600 this._numGeometries = _numGeometries; 32601 this._geometryType = _geometryType; 32602 } 32603 geometryType(_index) { 32604 return this._geometryType; 32605 } 32606 get numGeometries() { 32607 return this._numGeometries; 32608 } 32609 containsSingleGeometryType() { 32610 return true; 32611 } 32612}; 32613//#endregion 32614//#region node_modules/@maplibre/mlt/dist/vector/geometry/flatGpuVector.js 32615function createFlatGpuVector(geometryTypes, triangleOffsets, indexBuffer, vertexBuffer, topologyVector) { 32616 return new FlatGpuVector(geometryTypes, triangleOffsets, indexBuffer, vertexBuffer, topologyVector); 32617} 32618var FlatGpuVector = class extends GpuVector { 32619 constructor(_geometryTypes, triangleOffsets, indexBuffer, vertexBuffer, topologyVector) { 32620 super(triangleOffsets, indexBuffer, vertexBuffer, topologyVector); 32621 this._geometryTypes = _geometryTypes; 32622 } 32623 geometryType(index) { 32624 return this._geometryTypes[index]; 32625 } 32626 get numGeometries() { 32627 return this._geometryTypes.length; 32628 } 32629 containsSingleGeometryType() { 32630 return false; 32631 } 32632}; 32633//#endregion 32634//#region node_modules/@maplibre/mlt/dist/decoding/geometryDecoder.js 32635function decodeGeometryColumn(tile, numStreams, offset, numFeatures, scalingData) { 32636 const geometryTypeMetadata = decodeStreamMetadata(tile, offset); 32637 const geometryTypesVectorType = getVectorType(geometryTypeMetadata, numFeatures, tile, offset); 32638 let vertexOffsets; 32639 let vertexBuffer; 32640 let mortonSettings; 32641 let indexBuffer; 32642 if (geometryTypesVectorType === VectorType.CONST) { 32643 const geometryType = decodeUnsignedConstInt32Stream(tile, offset, geometryTypeMetadata); 32644 let geometryOffsets; 32645 let partOffsets; 32646 let ringOffsets; 32647 let triangleOffsets; 32648 for (let i = 0; i < numStreams - 1; i++) { 32649 const geometryStreamMetadata = decodeStreamMetadata(tile, offset); 32650 switch (geometryStreamMetadata.physicalStreamType) { 32651 case PhysicalStreamType.LENGTH: 32652 switch (geometryStreamMetadata.logicalStreamType.lengthType) { 32653 case LengthType.GEOMETRIES: 32654 geometryOffsets = decodeLengthStreamToOffsetBuffer(tile, offset, geometryStreamMetadata); 32655 break; 32656 case LengthType.PARTS: 32657 partOffsets = decodeLengthStreamToOffsetBuffer(tile, offset, geometryStreamMetadata); 32658 break; 32659 case LengthType.RINGS: 32660 ringOffsets = decodeLengthStreamToOffsetBuffer(tile, offset, geometryStreamMetadata); 32661 break; 32662 case LengthType.TRIANGLES: triangleOffsets = decodeLengthStreamToOffsetBuffer(tile, offset, geometryStreamMetadata); 32663 } 32664 break; 32665 case PhysicalStreamType.OFFSET: 32666 switch (geometryStreamMetadata.logicalStreamType.offsetType) { 32667 case OffsetType.VERTEX: 32668 vertexOffsets = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata); 32669 break; 32670 case OffsetType.INDEX: indexBuffer = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata); 32671 } 32672 break; 32673 case PhysicalStreamType.DATA: if (DictionaryType.VERTEX === geometryStreamMetadata.logicalStreamType.dictionaryType) vertexBuffer = decodeSignedInt32Stream(tile, offset, geometryStreamMetadata, scalingData); 32674 else { 32675 const mortonMetadata = geometryStreamMetadata; 32676 mortonSettings = { 32677 numBits: mortonMetadata.numBits, 32678 coordinateShift: mortonMetadata.coordinateShift 32679 }; 32680 vertexBuffer = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata, scalingData); 32681 } 32682 } 32683 } 32684 if (indexBuffer) { 32685 if (geometryOffsets !== void 0 || partOffsets !== void 0) return createConstGpuVector(numFeatures, geometryType, triangleOffsets, indexBuffer, vertexBuffer, { 32686 geometryOffsets, 32687 partOffsets, 32688 ringOffsets 32689 }); 32690 return createConstGpuVector(numFeatures, geometryType, triangleOffsets, indexBuffer, vertexBuffer); 32691 } 32692 return mortonSettings === void 0 ? createConstGeometryVector(numFeatures, geometryType, { 32693 geometryOffsets, 32694 partOffsets, 32695 ringOffsets 32696 }, vertexOffsets, vertexBuffer) : createMortonEncodedConstGeometryVector(numFeatures, geometryType, { 32697 geometryOffsets, 32698 partOffsets, 32699 ringOffsets 32700 }, vertexOffsets, vertexBuffer, mortonSettings); 32701 } 32702 const geometryTypeVector = decodeUnsignedInt32Stream(tile, offset, geometryTypeMetadata); 32703 let geometryLengths; 32704 let partLengths; 32705 let ringLengths; 32706 let triangleOffsets; 32707 for (let i = 0; i < numStreams - 1; i++) { 32708 const geometryStreamMetadata = decodeStreamMetadata(tile, offset); 32709 switch (geometryStreamMetadata.physicalStreamType) { 32710 case PhysicalStreamType.LENGTH: 32711 switch (geometryStreamMetadata.logicalStreamType.lengthType) { 32712 case LengthType.GEOMETRIES: 32713 geometryLengths = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata); 32714 break; 32715 case LengthType.PARTS: 32716 partLengths = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata); 32717 break; 32718 case LengthType.RINGS: 32719 ringLengths = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata); 32720 break; 32721 case LengthType.TRIANGLES: triangleOffsets = decodeLengthStreamToOffsetBuffer(tile, offset, geometryStreamMetadata); 32722 } 32723 break; 32724 case PhysicalStreamType.OFFSET: 32725 switch (geometryStreamMetadata.logicalStreamType.offsetType) { 32726 case OffsetType.VERTEX: 32727 vertexOffsets = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata); 32728 break; 32729 case OffsetType.INDEX: indexBuffer = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata); 32730 } 32731 break; 32732 case PhysicalStreamType.DATA: if (DictionaryType.VERTEX === geometryStreamMetadata.logicalStreamType.dictionaryType) vertexBuffer = decodeSignedInt32Stream(tile, offset, geometryStreamMetadata, scalingData); 32733 else { 32734 const mortonMetadata = geometryStreamMetadata; 32735 mortonSettings = { 32736 numBits: mortonMetadata.numBits, 32737 coordinateShift: mortonMetadata.coordinateShift 32738 }; 32739 vertexBuffer = decodeUnsignedInt32Stream(tile, offset, geometryStreamMetadata, scalingData); 32740 } 32741 } 32742 } 32743 let geometryOffsets; 32744 let partOffsets; 32745 let ringOffsets; 32746 if (geometryLengths) { 32747 geometryOffsets = decodeRootLengthStream(geometryTypeVector, geometryLengths, 2); 32748 if (partLengths && ringLengths) { 32749 partOffsets = decodeLevel1LengthStream(geometryTypeVector, geometryOffsets, partLengths, false); 32750 ringOffsets = decodeLevel2LengthStream(geometryTypeVector, geometryOffsets, partOffsets, ringLengths); 32751 } else if (partLengths) partOffsets = decodeLevel1WithoutRingBufferLengthStream(geometryTypeVector, geometryOffsets, partLengths); 32752 } else if (partLengths && ringLengths) { 32753 partOffsets = decodeRootLengthStream(geometryTypeVector, partLengths, 1); 32754 ringOffsets = decodeLevel1LengthStream(geometryTypeVector, partOffsets, ringLengths, true); 32755 } else if (partLengths) partOffsets = decodeRootLengthStream(geometryTypeVector, partLengths, 0); 32756 if (indexBuffer && !partOffsets) return createFlatGpuVector(geometryTypeVector, triangleOffsets, indexBuffer, vertexBuffer); 32757 if (indexBuffer) return createFlatGpuVector(geometryTypeVector, triangleOffsets, indexBuffer, vertexBuffer, { 32758 geometryOffsets, 32759 partOffsets, 32760 ringOffsets 32761 }); 32762 return mortonSettings === void 0 ? createFlatGeometryVector(geometryTypeVector, { 32763 geometryOffsets, 32764 partOffsets, 32765 ringOffsets 32766 }, vertexOffsets, vertexBuffer) : createFlatGeometryVectorMortonEncoded(geometryTypeVector, { 32767 geometryOffsets, 32768 partOffsets, 32769 ringOffsets 32770 }, vertexOffsets, vertexBuffer, mortonSettings); 32771} 32772function decodeRootLengthStream(geometryTypes, rootLengthStream, bufferId) { 32773 const rootBufferOffsets = new Uint32Array(geometryTypes.length + 1); 32774 let previousOffset = 0; 32775 rootBufferOffsets[0] = previousOffset; 32776 let rootLengthCounter = 0; 32777 for (let i = 0; i < geometryTypes.length; i++) previousOffset = rootBufferOffsets[i + 1] = previousOffset + (geometryTypes[i] > bufferId ? rootLengthStream[rootLengthCounter++] : 1); 32778 return rootBufferOffsets; 32779} 32780function decodeLevel1LengthStream(geometryTypes, rootOffsetBuffer, level1LengthBuffer, isLineStringPresent) { 32781 const level1BufferOffsets = new Uint32Array(rootOffsetBuffer[rootOffsetBuffer.length - 1] + 1); 32782 let previousOffset = 0; 32783 level1BufferOffsets[0] = previousOffset; 32784 let level1BufferCounter = 1; 32785 let level1LengthBufferCounter = 0; 32786 for (let i = 0; i < geometryTypes.length; i++) { 32787 const geometryType = geometryTypes[i]; 32788 const numGeometries = rootOffsetBuffer[i + 1] - rootOffsetBuffer[i]; 32789 if (geometryType === 5 || geometryType === 2 || isLineStringPresent && (geometryType === 4 || geometryType === 1)) for (let j = 0; j < numGeometries; j++) previousOffset = level1BufferOffsets[level1BufferCounter++] = previousOffset + level1LengthBuffer[level1LengthBufferCounter++]; 32790 else for (let j = 0; j < numGeometries; j++) level1BufferOffsets[level1BufferCounter++] = ++previousOffset; 32791 } 32792 return level1BufferOffsets; 32793} 32794function decodeLevel1WithoutRingBufferLengthStream(geometryTypes, rootOffsetBuffer, level1LengthBuffer) { 32795 const level1BufferOffsets = new Uint32Array(rootOffsetBuffer[rootOffsetBuffer.length - 1] + 1); 32796 let previousOffset = 0; 32797 level1BufferOffsets[0] = previousOffset; 32798 let level1OffsetBufferCounter = 1; 32799 let level1LengthCounter = 0; 32800 for (let i = 0; i < geometryTypes.length; i++) { 32801 const geometryType = geometryTypes[i]; 32802 const numGeometries = rootOffsetBuffer[i + 1] - rootOffsetBuffer[i]; 32803 if (geometryType === 4 || geometryType === 1) for (let j = 0; j < numGeometries; j++) previousOffset = level1BufferOffsets[level1OffsetBufferCounter++] = previousOffset + level1LengthBuffer[level1LengthCounter++]; 32804 else for (let j = 0; j < numGeometries; j++) level1BufferOffsets[level1OffsetBufferCounter++] = ++previousOffset; 32805 } 32806 return level1BufferOffsets; 32807} 32808function decodeLevel2LengthStream(geometryTypes, rootOffsetBuffer, level1OffsetBuffer, level2LengthBuffer) { 32809 const level2BufferOffsets = new Uint32Array(level1OffsetBuffer[level1OffsetBuffer.length - 1] + 1); 32810 let previousOffset = 0; 32811 level2BufferOffsets[0] = previousOffset; 32812 let level1OffsetBufferCounter = 1; 32813 let level2OffsetBufferCounter = 1; 32814 let level2LengthBufferCounter = 0; 32815 for (let i = 0; i < geometryTypes.length; i++) { 32816 const geometryType = geometryTypes[i]; 32817 const numGeometries = rootOffsetBuffer[i + 1] - rootOffsetBuffer[i]; 32818 if (geometryType !== 0 && geometryType !== 3) for (let j = 0; j < numGeometries; j++) { 32819 const numParts = level1OffsetBuffer[level1OffsetBufferCounter] - level1OffsetBuffer[level1OffsetBufferCounter - 1]; 32820 level1OffsetBufferCounter++; 32821 for (let k = 0; k < numParts; k++) previousOffset = level2BufferOffsets[level2OffsetBufferCounter++] = previousOffset + level2LengthBuffer[level2LengthBufferCounter++]; 32822 } 32823 else for (let j = 0; j < numGeometries; j++) { 32824 level2BufferOffsets[level2OffsetBufferCounter++] = ++previousOffset; 32825 level1OffsetBufferCounter++; 32826 } 32827 } 32828 return level2BufferOffsets; 32829} 32830//#endregion 32831//#region node_modules/@maplibre/mlt/dist/vector/flat/booleanFlatVector.js 32832var BooleanFlatVector = class extends Vector { 32833 constructor(name, dataVector, sizeOrNullabilityBuffer) { 32834 super(name, dataVector.getBuffer(), sizeOrNullabilityBuffer); 32835 this.dataVector = dataVector; 32836 } 32837 getValueFromBuffer(index) { 32838 return this.dataVector.get(index); 32839 } 32840}; 32841//#endregion 32842//#region node_modules/@maplibre/mlt/dist/vector/flat/floatFlatVector.js 32843var FloatFlatVector = class extends FixedSizeVector { 32844 getValueFromBuffer(index) { 32845 return this.dataBuffer[index]; 32846 } 32847}; 32848//#endregion 32849//#region node_modules/@maplibre/mlt/dist/vector/constant/int64ConstVector.js 32850var Int64ConstVector = class extends Vector { 32851 constructor(name, value, sizeOrNullabilityBuffer, isSigned) { 32852 super(name, isSigned ? BigInt64Array.of(value) : BigUint64Array.of(value), sizeOrNullabilityBuffer); 32853 } 32854 getValueFromBuffer(_index) { 32855 return this.dataBuffer[0]; 32856 } 32857}; 32858//#endregion 32859//#region node_modules/@maplibre/mlt/dist/vector/variableSizeVector.js 32860var VariableSizeVector = class extends Vector { 32861 constructor(name, offsetBuffer, dataBuffer, sizeOrNullabilityBuffer) { 32862 super(name, dataBuffer, sizeOrNullabilityBuffer); 32863 this.offsetBuffer = offsetBuffer; 32864 } 32865}; 32866//#endregion 32867//#region node_modules/@maplibre/mlt/dist/vector/flat/stringFlatVector.js 32868var StringFlatVector = class extends VariableSizeVector { 32869 constructor(name, offsetBuffer, dataBuffer, nullabilityBuffer) { 32870 super(name, offsetBuffer, dataBuffer, nullabilityBuffer ?? offsetBuffer.length - 1); 32871 } 32872 getValueFromBuffer(index) { 32873 const start = this.offsetBuffer[index]; 32874 const end = this.offsetBuffer[index + 1]; 32875 return decodeString$2(this.dataBuffer, start, end); 32876 } 32877}; 32878//#endregion 32879//#region node_modules/@maplibre/mlt/dist/vector/dictionary/stringDictionaryVector.js 32880var StringDictionaryVector = class extends VariableSizeVector { 32881 constructor(name, indexBuffer, offsetBuffer, dictionaryBuffer, nullabilityBuffer) { 32882 super(name, offsetBuffer, dictionaryBuffer, nullabilityBuffer ?? indexBuffer.length); 32883 this.indexBuffer = indexBuffer; 32884 this.indexBuffer = indexBuffer; 32885 } 32886 getValueFromBuffer(index) { 32887 const offset = this.indexBuffer[index]; 32888 const start = this.offsetBuffer[offset]; 32889 const end = this.offsetBuffer[offset + 1]; 32890 return decodeString$2(this.dataBuffer, start, end); 32891 } 32892}; 32893//#endregion 32894//#region node_modules/@maplibre/mlt/dist/decoding/fsstDecoder.js 32895/** 32896* Calculates the exact output size before decoding. This allows one final 32897* `Uint8Array` allocation and avoids growing a JavaScript number array and 32898* copying it into a typed array afterward. Traversing the compressed data 32899* twice is always worthwhile here because it avoids those larger temporary 32900* allocations. 32901*/ 32902function getDecodedLength(symbolLengths, compressedData) { 32903 let decodedLength = 0; 32904 for (let i = 0; i < compressedData.length; i++) { 32905 const symbolIndex = compressedData[i]; 32906 if (symbolIndex === 255) { 32907 decodedLength++; 32908 i++; 32909 } else decodedLength += symbolLengths[symbolIndex]; 32910 } 32911 return decodedLength; 32912} 32913/** 32914* Decode FSST compressed data 32915* 32916* @param symbols Array of symbols, where each symbol can be between 1 and 8 bytes 32917* @param symbolLengths Array of symbol lengths, length of each symbol in symbols array 32918* @param compressedData FSST Compressed data, where each entry is an index to the symbols array 32919* @returns Decoded data as Uint8Array 32920*/ 32921function decodeFsst(symbols, symbolLengths, compressedData) { 32922 const symbolOffsets = new Uint32Array(symbolLengths.length); 32923 for (let i = 1; i < symbolLengths.length; i++) symbolOffsets[i] = symbolOffsets[i - 1] + symbolLengths[i - 1]; 32924 const decodedData = new Uint8Array(getDecodedLength(symbolLengths, compressedData)); 32925 let decodedOffset = 0; 32926 for (let i = 0; i < compressedData.length; i++) { 32927 const symbolIndex = compressedData[i]; 32928 if (symbolIndex === 255) { 32929 i++; 32930 decodedData[decodedOffset++] = compressedData[i]; 32931 } else { 32932 let symbolLength = symbolLengths[symbolIndex]; 32933 let symbolOffset = symbolOffsets[symbolIndex]; 32934 while (symbolLength-- > 0) decodedData[decodedOffset++] = symbols[symbolOffset++]; 32935 } 32936 } 32937 return decodedData; 32938} 32939//#endregion 32940//#region node_modules/@maplibre/mlt/dist/vector/fsst-dictionary/stringFsstDictionaryVector.js 32941var StringFsstDictionaryVector = class extends VariableSizeVector { 32942 constructor(name, indexBuffer, offsetBuffer, dictionaryBuffer, symbolOffsetBuffer, symbolTableBuffer, nullabilityBuffer, sharedDictionaryCache) { 32943 super(name, offsetBuffer, dictionaryBuffer, nullabilityBuffer ?? indexBuffer.length); 32944 this.indexBuffer = indexBuffer; 32945 this.symbolOffsetBuffer = symbolOffsetBuffer; 32946 this.symbolTableBuffer = symbolTableBuffer; 32947 this.sharedDictionaryCache = sharedDictionaryCache; 32948 } 32949 getValueFromBuffer(index) { 32950 if (this.decodedDictionary == null) { 32951 this.decodedDictionary = this.sharedDictionaryCache?.decodedDictionary; 32952 if (this.decodedDictionary == null) { 32953 this.decodedDictionary = this.decodeDictionary(); 32954 if (this.sharedDictionaryCache) this.sharedDictionaryCache.decodedDictionary = this.decodedDictionary; 32955 } 32956 } 32957 const offset = this.indexBuffer[index]; 32958 const start = this.offsetBuffer[offset]; 32959 const end = this.offsetBuffer[offset + 1]; 32960 return decodeString$2(this.decodedDictionary, start, end); 32961 } 32962 decodeDictionary() { 32963 if (this.symbolLengthBuffer == null) this.symbolLengthBuffer = this.offsetToLengthBuffer(this.symbolOffsetBuffer); 32964 return decodeFsst(this.symbolTableBuffer, this.symbolLengthBuffer, this.dataBuffer); 32965 } 32966 offsetToLengthBuffer(offsetBuffer) { 32967 const lengthBuffer = new Uint32Array(offsetBuffer.length - 1); 32968 let previousOffset = offsetBuffer[0]; 32969 for (let i = 1; i < offsetBuffer.length; i++) { 32970 const offset = offsetBuffer[i]; 32971 lengthBuffer[i - 1] = offset - previousOffset; 32972 previousOffset = offset; 32973 } 32974 return lengthBuffer; 32975 } 32976}; 32977//#endregion 32978//#region node_modules/@maplibre/mlt/dist/decoding/stringDecoder.js 32979function decodeString$1(name, data, offset, numStreams, bitVector) { 32980 let dictionaryLengthStream; 32981 let offsetStream; 32982 let dictionaryStream; 32983 let symbolLengthStream; 32984 let symbolTableStream; 32985 let nullabilityBuffer = bitVector; 32986 let plainLengthStream; 32987 let plainDataStream; 32988 for (let i = 0; i < numStreams; i++) { 32989 const streamMetadata = decodeStreamMetadata(data, offset); 32990 switch (streamMetadata.physicalStreamType) { 32991 case PhysicalStreamType.PRESENT: { 32992 const presentStream = new BitVector(decodeBooleanRle(data, streamMetadata.numValues, streamMetadata.byteLength, offset), streamMetadata.numValues); 32993 nullabilityBuffer = bitVector ?? presentStream; 32994 break; 32995 } 32996 case PhysicalStreamType.OFFSET: 32997 offsetStream = decodeUnsignedInt32Stream(data, offset, streamMetadata, void 0, nullabilityBuffer); 32998 break; 32999 case PhysicalStreamType.LENGTH: { 33000 const lengthStream = decodeLengthStreamToOffsetBuffer(data, offset, streamMetadata); 33001 if (LengthType.DICTIONARY === streamMetadata.logicalStreamType.lengthType) dictionaryLengthStream = lengthStream; 33002 else if (LengthType.SYMBOL === streamMetadata.logicalStreamType.lengthType) symbolLengthStream = lengthStream; 33003 else plainLengthStream = lengthStream; 33004 break; 33005 } 33006 case PhysicalStreamType.DATA: { 33007 const dataStream = data.subarray(offset.get(), offset.get() + streamMetadata.byteLength); 33008 offset.add(streamMetadata.byteLength); 33009 const dictType = streamMetadata.logicalStreamType.dictionaryType; 33010 if (DictionaryType.FSST === dictType) symbolTableStream = dataStream; 33011 else if (DictionaryType.SINGLE === dictType || DictionaryType.SHARED === dictType) dictionaryStream = dataStream; 33012 else if (DictionaryType.NONE === dictType) plainDataStream = dataStream; 33013 break; 33014 } 33015 } 33016 } 33017 return decodeFsstDictionaryVector(name, symbolTableStream, offsetStream, dictionaryLengthStream, dictionaryStream, symbolLengthStream, nullabilityBuffer) ?? decodeDictionaryVector(name, dictionaryStream, offsetStream, dictionaryLengthStream, nullabilityBuffer) ?? decodePlainStringVector(name, plainLengthStream, plainDataStream, offsetStream, nullabilityBuffer); 33018} 33019function decodeFsstDictionaryVector(name, symbolTableStream, offsetStream, dictionaryLengthStream, dictionaryStream, symbolLengthStream, nullabilityBuffer) { 33020 if (!symbolTableStream) return; 33021 if (!offsetStream || !dictionaryLengthStream || !dictionaryStream || !symbolLengthStream) throw new Error(`Incomplete FSST dictionary string column "${name}"`); 33022 return new StringFsstDictionaryVector(name, offsetStream, dictionaryLengthStream, dictionaryStream, symbolLengthStream, symbolTableStream, nullabilityBuffer); 33023} 33024function decodeDictionaryVector(name, dictionaryStream, offsetStream, dictionaryLengthStream, nullabilityBuffer) { 33025 if (!dictionaryStream) return; 33026 if (!offsetStream || !dictionaryLengthStream) throw new Error(`Incomplete dictionary string column "${name}"`); 33027 return nullabilityBuffer ? new StringDictionaryVector(name, offsetStream, dictionaryLengthStream, dictionaryStream, nullabilityBuffer) : new StringDictionaryVector(name, offsetStream, dictionaryLengthStream, dictionaryStream); 33028} 33029function decodePlainStringVector(name, plainLengthStream, plainDataStream, offsetStream, nullabilityBuffer) { 33030 if (!plainLengthStream || !plainDataStream) return; 33031 if (offsetStream) return nullabilityBuffer ? new StringDictionaryVector(name, offsetStream, plainLengthStream, plainDataStream, nullabilityBuffer) : new StringDictionaryVector(name, offsetStream, plainLengthStream, plainDataStream); 33032 if (nullabilityBuffer && nullabilityBuffer.size() !== plainLengthStream.length - 1) { 33033 const sparseOffsetStream = new Uint32Array(nullabilityBuffer.size()); 33034 let valueIndex = 0; 33035 for (let i = 0; i < nullabilityBuffer.size(); i++) if (nullabilityBuffer.get(i)) sparseOffsetStream[i] = valueIndex++; 33036 else sparseOffsetStream[i] = 0; 33037 return new StringDictionaryVector(name, sparseOffsetStream, plainLengthStream, plainDataStream, nullabilityBuffer); 33038 } 33039 return nullabilityBuffer ? new StringFlatVector(name, plainLengthStream, plainDataStream, nullabilityBuffer) : new StringFlatVector(name, plainLengthStream, plainDataStream); 33040} 33041function decodeSharedDictionary(data, offset, column, propertyColumnNames) { 33042 let dictionaryOffsetBuffer; 33043 let dictionaryBuffer; 33044 let symbolOffsetBuffer; 33045 let symbolTableBuffer; 33046 let dictionaryStreamDecoded = false; 33047 while (!dictionaryStreamDecoded) { 33048 const streamMetadata = decodeStreamMetadata(data, offset); 33049 switch (streamMetadata.physicalStreamType) { 33050 case PhysicalStreamType.LENGTH: 33051 if (LengthType.DICTIONARY === streamMetadata.logicalStreamType.lengthType) dictionaryOffsetBuffer = decodeLengthStreamToOffsetBuffer(data, offset, streamMetadata); 33052 else symbolOffsetBuffer = decodeLengthStreamToOffsetBuffer(data, offset, streamMetadata); 33053 break; 33054 case PhysicalStreamType.DATA: 33055 if (DictionaryType.SINGLE === streamMetadata.logicalStreamType.dictionaryType || DictionaryType.SHARED === streamMetadata.logicalStreamType.dictionaryType) { 33056 dictionaryBuffer = data.subarray(offset.get(), offset.get() + streamMetadata.byteLength); 33057 dictionaryStreamDecoded = true; 33058 } else symbolTableBuffer = data.subarray(offset.get(), offset.get() + streamMetadata.byteLength); 33059 offset.add(streamMetadata.byteLength); 33060 } 33061 } 33062 if (column.type !== "complexType") throw new Error(`Shared dictionary column ${column.name} must be a complex (struct) column.`); 33063 if (!dictionaryOffsetBuffer || !dictionaryBuffer) throw new Error(`Incomplete shared dictionary for column "${column.name}"`); 33064 const childFields = column.complexType.children; 33065 const stringDictionaryVectors = []; 33066 /** Shared by every FSST child-column vector in this SharedDict and populated on first access. */ 33067 const sharedDictionaryCache = symbolTableBuffer ? {} : void 0; 33068 let i = 0; 33069 for (const childField of childFields) { 33070 const numStreams = decodeVarintInt32(data, offset, 1)[0]; 33071 if (numStreams === 0) continue; 33072 const columnName = childField.name ? `${column.name}${childField.name}` : column.name; 33073 if (propertyColumnNames) { 33074 if (!propertyColumnNames.has(columnName)) { 33075 skipColumn(numStreams, data, offset); 33076 continue; 33077 } 33078 } 33079 if (childField.type !== "scalarField" || childField.scalarField.physicalType !== ScalarType.STRING) throw new Error("Currently only scalar string fields are implemented for a struct."); 33080 if (numStreams > 1 && !childField.nullable || numStreams === 1 && childField.nullable) throw new Error(`The number of streams for the child field ${childField.name} does not match its nullability. nullibilty: ${childField.nullable}, numStreams: ${numStreams}`); 33081 let presentStreamBitVector; 33082 if (childField.nullable) { 33083 const presentStreamMetadata = decodeStreamMetadata(data, offset); 33084 presentStreamBitVector = new BitVector(decodeBooleanRle(data, presentStreamMetadata.numValues, presentStreamMetadata.byteLength, offset), presentStreamMetadata.numValues); 33085 } 33086 const offsetStream = decodeUnsignedInt32Stream(data, offset, decodeStreamMetadata(data, offset), void 0, presentStreamBitVector); 33087 if (symbolTableBuffer) { 33088 if (!symbolOffsetBuffer) throw new Error(`Incomplete shared FSST dictionary for column "${columnName}"`); 33089 stringDictionaryVectors[i++] = new StringFsstDictionaryVector(columnName, offsetStream, dictionaryOffsetBuffer, dictionaryBuffer, symbolOffsetBuffer, symbolTableBuffer, presentStreamBitVector, sharedDictionaryCache); 33090 } else stringDictionaryVectors[i++] = new StringDictionaryVector(columnName, offsetStream, dictionaryOffsetBuffer, dictionaryBuffer, presentStreamBitVector); 33091 } 33092 return stringDictionaryVectors; 33093} 33094//#endregion 33095//#region node_modules/@maplibre/mlt/dist/vector/flat/objectFlatVector.js 33096/** 33097* Holds already-decoded values of arbitrary shape, one per feature. 33098* 33099* Unlike the other vectors there is no packed buffer to index into: nested property (MAP) columns 33100* decode to plain JavaScript maps, arrays and scalars, so the values are kept as-is. Features 33101* without a value are marked absent in the nullability buffer, so `has` reports them as missing and 33102* `getValue` returns `null`. 33103*/ 33104var ObjectFlatVector = class extends Vector { 33105 constructor(name, values, nullabilityBuffer) { 33106 super(name, /* @__PURE__ */ new Uint8Array(0), nullabilityBuffer ?? values.length); 33107 this.values = values; 33108 } 33109 getValueFromBuffer(index) { 33110 return this.values[index]; 33111 } 33112}; 33113//#endregion 33114//#region node_modules/@maplibre/mlt/dist/metadata/tile/mapMask.js 33115/** 33116* Bitmask written ahead of a nested property (MAP) column, marking which optional streams follow 33117* the mandatory length stream. Only one of INT32/INT64 and one of UINT32/UINT64 is ever set: the 33118* encoder picks the narrower width that fits every value. 33119*/ 33120var MapMask; 33121(function(MapMask) { 33122 MapMask[MapMask["STRING"] = 1] = "STRING"; 33123 MapMask[MapMask["INT32"] = 2] = "INT32"; 33124 MapMask[MapMask["UINT32"] = 4] = "UINT32"; 33125 MapMask[MapMask["INT64"] = 8] = "INT64"; 33126 MapMask[MapMask["UINT64"] = 16] = "UINT64"; 33127 MapMask[MapMask["FLOAT"] = 32] = "FLOAT"; 33128 MapMask[MapMask["DOUBLE"] = 64] = "DOUBLE"; 33129 MapMask[MapMask["PRESENCE"] = 128] = "PRESENCE"; 33130})(MapMask || (MapMask = {})); 33131//#endregion 33132//#region node_modules/@maplibre/mlt/dist/metadata/tile/mapControlValue.js 33133/** 33134* Tokens in the data stream of a nested property (MAP) column. Values below `COUNT` describe the 33135* structure; anything else is an index into the combined dictionary, offset by `COUNT`. Booleans are 33136* encoded directly as tokens rather than being added to a dictionary. 33137*/ 33138var MapControlValue; 33139(function(MapControlValue) { 33140 MapControlValue[MapControlValue["FALSE"] = 0] = "FALSE"; 33141 MapControlValue[MapControlValue["TRUE"] = 1] = "TRUE"; 33142 /** A nested map follows: this token, the payload length including these two tokens, the payload. */ 33143 MapControlValue[MapControlValue["START_MAP"] = 2] = "START_MAP"; 33144 /** A list follows, laid out the same way as START_MAP. */ 33145 MapControlValue[MapControlValue["START_LIST"] = 3] = "START_LIST"; 33146 /** Number of reserved tokens, i.e. the first dictionary index. */ 33147 MapControlValue[MapControlValue["COUNT"] = 4] = "COUNT"; 33148})(MapControlValue || (MapControlValue = {})); 33149//#endregion 33150//#region node_modules/@maplibre/mlt/dist/decoding/mapPropertyDecoder.js 33151/** 33152* Decodes a nested property (MAP) column into one vector per child column. 33153* 33154* The column is stored as a length stream (values per feature), a dictionary stream per value type 33155* present, an optional presence stream, and a data stream of dictionary indices interleaved with 33156* the control tokens that describe the map/list structure. 33157* 33158* Ported from the Java reference implementation (`MapPropertyDecoder`). 33159*/ 33160function decodeMapPropertyColumn(data, offset, columnMetadata, numStreams) { 33161 const columnNames = getMapColumnNames(columnMetadata); 33162 if (numStreams === 0) return columnNames.map((name) => new ObjectFlatVector(name, [])); 33163 const streams = decodeMapStreams(data, offset, numStreams); 33164 const featureCount = (streams.presentStream ? streams.presentCount : streams.lengthStream.length) / columnNames.length; 33165 const vectors = []; 33166 let countsCursor = 0; 33167 let valuesCursor = 0; 33168 for (let childIndex = 0; childIndex < columnNames.length; childIndex++) { 33169 const child = decodeChildColumn(streams, childIndex, featureCount, countsCursor, valuesCursor); 33170 vectors.push(new ObjectFlatVector(columnNames[childIndex], child.value, child.nullabilityBuffer)); 33171 countsCursor = child.countsEnd; 33172 valuesCursor = child.valuesEnd; 33173 } 33174 return vectors; 33175} 33176/** 33177* A single map column carries its own name. A shared column carries one child per sibling, whose 33178* full name is the parent name followed by the child name. 33179*/ 33180function getMapColumnNames(columnMetadata) { 33181 const children = columnMetadata.type === "complexType" ? columnMetadata.complexType.children : void 0; 33182 if (!children || children.length === 0) return [columnMetadata.name]; 33183 return children.map((child) => columnMetadata.name + (child.name ?? "")); 33184} 33185/** Reads the stream mask and every stream it announces, in the order the encoder wrote them. */ 33186function decodeMapStreams(data, offset, numStreams) { 33187 const dictionaryMask = data[offset.get()]; 33188 offset.add(1); 33189 const lengthStream = decodeUnsignedInt32Stream(data, offset, decodeStreamMetadata(data, offset)); 33190 let remainingStreams = numStreams - 1; 33191 const dictionary = []; 33192 if (dictionaryMask & MapMask.STRING) remainingStreams -= decodeStringDictionary(data, offset, dictionary); 33193 remainingStreams -= decodeIntegerDictionaries(data, offset, dictionaryMask, dictionary); 33194 remainingStreams -= decodeFloatingPointDictionaries(data, offset, dictionaryMask, dictionary); 33195 let presentStream; 33196 let presentCount = 0; 33197 if (dictionaryMask & MapMask.PRESENCE) { 33198 const presence = decodePresenceStream(data, offset); 33199 presentStream = presence.value; 33200 presentCount = presence.count; 33201 remainingStreams--; 33202 } 33203 let flattenedValues = /* @__PURE__ */ new Uint32Array(0); 33204 if (remainingStreams > 0) { 33205 flattenedValues = decodeUnsignedInt32Stream(data, offset, decodeStreamMetadata(data, offset)); 33206 remainingStreams--; 33207 } 33208 if (remainingStreams !== 0) throw new Error(`Unexpected number of remaining streams while decoding map column: ${remainingStreams}`); 33209 return { 33210 lengthStream, 33211 dictionary, 33212 presentStream, 33213 presentCount, 33214 flattenedValues 33215 }; 33216} 33217/** @returns the number of streams consumed, which the string encoding decides for itself. */ 33218function decodeStringDictionary(data, offset, dictionary) { 33219 const stringStreamCount = data[offset.get()]; 33220 offset.add(1); 33221 const strings = decodeString$1("", data, offset, stringStreamCount); 33222 if (strings) for (let i = 0; i < strings.size; i++) dictionary.push(strings.getValue(i)); 33223 return stringStreamCount; 33224} 33225/** 33226* Signed and unsigned integers each get at most one stream, whose width the encoder chose to fit 33227* the widest value. 33228* 33229* @returns the number of streams consumed. 33230*/ 33231function decodeIntegerDictionaries(data, offset, dictionaryMask, dictionary) { 33232 let consumed = 0; 33233 if (dictionaryMask & MapMask.INT32) { 33234 pushAll(dictionary, decodeSignedInt32Stream(data, offset, decodeStreamMetadata(data, offset))); 33235 consumed++; 33236 } else if (dictionaryMask & MapMask.INT64) { 33237 pushAll(dictionary, decodeSignedInt64Stream(data, offset, decodeStreamMetadata(data, offset))); 33238 consumed++; 33239 } 33240 if (dictionaryMask & MapMask.UINT32) { 33241 pushAll(dictionary, decodeUnsignedInt32Stream(data, offset, decodeStreamMetadata(data, offset))); 33242 consumed++; 33243 } else if (dictionaryMask & MapMask.UINT64) { 33244 pushAll(dictionary, decodeUnsignedInt64Stream(data, offset, decodeStreamMetadata(data, offset))); 33245 consumed++; 33246 } 33247 return consumed; 33248} 33249/** @returns the number of streams consumed. */ 33250function decodeFloatingPointDictionaries(data, offset, dictionaryMask, dictionary) { 33251 let consumed = 0; 33252 if (dictionaryMask & MapMask.FLOAT) { 33253 pushAll(dictionary, decodeFloatsLE(data, offset, decodeStreamMetadata(data, offset).numValues)); 33254 consumed++; 33255 } 33256 if (dictionaryMask & MapMask.DOUBLE) { 33257 pushAll(dictionary, decodeDoublesLE(data, offset, decodeStreamMetadata(data, offset).numValues)); 33258 consumed++; 33259 } 33260 return consumed; 33261} 33262function decodePresenceStream(data, offset) { 33263 const streamMetadata = decodeStreamMetadata(data, offset); 33264 if (streamMetadata.physicalStreamType !== PhysicalStreamType.PRESENT) throw new Error(`Expected PRESENT stream for map column but found: ${streamMetadata.physicalStreamType}`); 33265 const count = streamMetadata.numValues; 33266 const streamDataStart = offset.get(); 33267 const value = new BitVector(decodeBooleanRle(data, count, streamMetadata.byteLength, offset), count); 33268 offset.set(streamDataStart + streamMetadata.byteLength); 33269 return { 33270 value, 33271 count 33272 }; 33273} 33274/** 33275* Decodes one child column's per-feature values. 33276* 33277* Lengths, presence bits and tokens are all laid out child-major, so each child picks up where the 33278* previous one left off. 33279*/ 33280function decodeChildColumn(streams, childIndex, featureCount, countsCursor, valuesCursor) { 33281 const { lengthStream, flattenedValues, presentStream, dictionary } = streams; 33282 const presentOffset = childIndex * featureCount; 33283 let presentInChild = featureCount; 33284 let nullabilityBuffer; 33285 if (presentStream) { 33286 nullabilityBuffer = new BitVector(new Uint8Array(Math.ceil(featureCount / 8)), featureCount); 33287 presentInChild = 0; 33288 for (let i = 0; i < featureCount; i++) if (presentStream.get(presentOffset + i)) { 33289 nullabilityBuffer.set(i, true); 33290 presentInChild++; 33291 } 33292 } 33293 const countsEnd = countsCursor + presentInChild; 33294 if (countsEnd > lengthStream.length) throw new Error("Merged map counts underflow while decoding child streams"); 33295 const value = new Array(featureCount); 33296 let countCursor = countsCursor; 33297 let flattenedIndex = valuesCursor; 33298 for (let featureIndex = 0; featureIndex < featureCount; featureIndex++) { 33299 if (presentStream && !presentStream.get(presentOffset + featureIndex)) { 33300 value[featureIndex] = null; 33301 continue; 33302 } 33303 const endIndex = flattenedIndex + lengthStream[countCursor++]; 33304 if (endIndex > flattenedValues.length) throw new Error("Map value stream underflow while decoding feature payload"); 33305 const decoded = decodeFeatureValue(flattenedValues, flattenedIndex, endIndex, dictionary); 33306 value[featureIndex] = decoded.value; 33307 flattenedIndex = decoded.nextIndex; 33308 } 33309 let childValueCount = 0; 33310 for (let i = countsCursor; i < countsEnd; i++) childValueCount += lengthStream[i]; 33311 const valuesEnd = valuesCursor + childValueCount; 33312 if (flattenedIndex !== valuesEnd) throw new Error("Unused flattened map values remain after decode"); 33313 return { 33314 value, 33315 nullabilityBuffer, 33316 countsEnd, 33317 valuesEnd 33318 }; 33319} 33320/** 33321* A feature's payload is a bare sequence of map entries, unless it is a single token - a root-level 33322* scalar - or opens with a list token. Those two shapes are what distinguish it from map entries. 33323*/ 33324function decodeFeatureValue(flattenedValues, startIndex, endIndex, dictionary) { 33325 if (endIndex - startIndex === 1 || flattenedValues[startIndex] === MapControlValue.START_LIST) return decodeValue(flattenedValues, startIndex, endIndex, dictionary); 33326 return decodeMapEntries(flattenedValues, startIndex, endIndex, dictionary); 33327} 33328function decodeMapEntries(flattenedValues, startIndex, endIndex, dictionary) { 33329 const value = Object.create(null); 33330 let index = startIndex; 33331 while (index < endIndex) { 33332 const key = decodeScalarByIndex(flattenedValues[index++], dictionary); 33333 if (typeof key !== "string") throw new Error(`Map key dictionary index does not resolve to a string: ${key}`); 33334 const decoded = decodeValue(flattenedValues, index, endIndex, dictionary); 33335 value[key] = decoded.value; 33336 index = decoded.nextIndex; 33337 } 33338 return { 33339 value, 33340 nextIndex: index 33341 }; 33342} 33343function decodeValue(flattenedValues, startIndex, endIndex, dictionary) { 33344 if (startIndex >= endIndex) throw new Error("Unexpected end of map value stream"); 33345 const token = flattenedValues[startIndex]; 33346 if (token === MapControlValue.FALSE) return { 33347 value: false, 33348 nextIndex: startIndex + 1 33349 }; 33350 if (token === MapControlValue.TRUE) return { 33351 value: true, 33352 nextIndex: startIndex + 1 33353 }; 33354 if (token === MapControlValue.START_MAP) { 33355 const valueEndIndex = decodeNestedPayloadEnd(flattenedValues, startIndex, endIndex); 33356 return { 33357 value: decodeMapEntries(flattenedValues, startIndex + 2, valueEndIndex, dictionary).value, 33358 nextIndex: valueEndIndex 33359 }; 33360 } 33361 if (token === MapControlValue.START_LIST) { 33362 const valueEndIndex = decodeNestedPayloadEnd(flattenedValues, startIndex, endIndex); 33363 const value = []; 33364 let index = startIndex + 2; 33365 while (index < valueEndIndex) { 33366 const nested = decodeValue(flattenedValues, index, valueEndIndex, dictionary); 33367 value.push(nested.value); 33368 index = nested.nextIndex; 33369 } 33370 return { 33371 value, 33372 nextIndex: valueEndIndex 33373 }; 33374 } 33375 return { 33376 value: decodeScalarByIndex(token, dictionary), 33377 nextIndex: startIndex + 1 33378 }; 33379} 33380/** 33381* Reads the length prefix of a nested payload and returns where it ends, the counterpart of 33382* `encodeNestedPayloadLength`. The length covers the two header tokens as well. 33383*/ 33384function decodeNestedPayloadEnd(flattenedValues, startIndex, endIndex) { 33385 if (startIndex + 1 >= endIndex) throw new Error("Missing length for nested map/list payload"); 33386 const encodedLength = flattenedValues[startIndex + 1]; 33387 if (encodedLength < 2) throw new Error(`Invalid nested payload length: ${encodedLength}`); 33388 const valueEndIndex = startIndex + encodedLength; 33389 if (valueEndIndex > endIndex) throw new Error("Nested payload exceeds containing payload bounds"); 33390 return valueEndIndex; 33391} 33392function decodeScalarByIndex(token, dictionary) { 33393 const dictionaryIndex = token - MapControlValue.COUNT; 33394 if (dictionaryIndex < 0 || dictionaryIndex >= dictionary.length) throw new Error(`Scalar dictionary index out of range: ${token}`); 33395 return dictionary[dictionaryIndex]; 33396} 33397function pushAll(dictionary, values) { 33398 for (const value of values) dictionary.push(value); 33399} 33400//#endregion 33401//#region node_modules/@maplibre/mlt/dist/decoding/propertyDecoder.js 33402function decodePropertyColumn(data, offset, columnMetadata, numStreams, numFeatures, propertyColumnNames) { 33403 if (columnMetadata.type === "scalarType") { 33404 if (propertyColumnNames && !propertyColumnNames.has(columnMetadata.name)) { 33405 skipColumn(numStreams, data, offset); 33406 return null; 33407 } 33408 return decodeScalarPropertyColumn(numStreams, data, offset, numFeatures, columnMetadata.scalarType, columnMetadata); 33409 } 33410 if (columnMetadata.complexType?.physicalType === ComplexType.MAP) return decodeMapPropertyColumn(data, offset, columnMetadata, numStreams); 33411 if (numStreams === 0) return null; 33412 return decodeSharedDictionary(data, offset, columnMetadata, propertyColumnNames); 33413} 33414function decodeScalarPropertyColumn(numStreams, data, offset, numFeatures, column, columnMetadata) { 33415 let nullabilityBuffer; 33416 if (numStreams === 0) return null; 33417 if (columnMetadata.nullable) { 33418 const presentStreamMetadata = decodeStreamMetadata(data, offset); 33419 const numValues = presentStreamMetadata.numValues; 33420 const streamDataStart = offset.get(); 33421 const presentVector = decodeBooleanRle(data, numValues, presentStreamMetadata.byteLength, offset); 33422 offset.set(streamDataStart + presentStreamMetadata.byteLength); 33423 nullabilityBuffer = new BitVector(presentVector, presentStreamMetadata.numValues); 33424 } 33425 const sizeOrNullabilityBuffer = nullabilityBuffer ?? numFeatures; 33426 switch (column.physicalType) { 33427 case ScalarType.UINT_32: 33428 case ScalarType.INT_32: return decodeInt32Column(data, offset, columnMetadata, column, sizeOrNullabilityBuffer); 33429 case ScalarType.STRING: { 33430 const stringDataStreams = columnMetadata.nullable ? numStreams - 1 : numStreams; 33431 return decodeString$1(columnMetadata.name, data, offset, stringDataStreams, nullabilityBuffer) ?? null; 33432 } 33433 case ScalarType.BOOLEAN: return decodeBooleanColumn(data, offset, columnMetadata, numFeatures, sizeOrNullabilityBuffer); 33434 case ScalarType.UINT_64: 33435 case ScalarType.INT_64: return decodeInt64Column(data, offset, columnMetadata, sizeOrNullabilityBuffer, column); 33436 case ScalarType.FLOAT: return decodeFloatColumn(data, offset, columnMetadata, sizeOrNullabilityBuffer); 33437 case ScalarType.DOUBLE: return decodeDoubleColumn(data, offset, columnMetadata, sizeOrNullabilityBuffer); 33438 default: throw new Error(`The specified data type for the field is currently not supported: ${column}`); 33439 } 33440} 33441function decodeBooleanColumn(data, offset, column, _numFeatures, sizeOrNullabilityBuffer) { 33442 const dataStreamMetadata = decodeStreamMetadata(data, offset); 33443 const numValues = dataStreamMetadata.numValues; 33444 const streamDataStart = offset.get(); 33445 const nullabilityBuffer = isNullabilityBuffer(sizeOrNullabilityBuffer) ? sizeOrNullabilityBuffer : void 0; 33446 const dataStream = decodeBooleanRle(data, numValues, dataStreamMetadata.byteLength, offset, nullabilityBuffer); 33447 offset.set(streamDataStart + dataStreamMetadata.byteLength); 33448 const dataVector = new BitVector(dataStream, numValues); 33449 return new BooleanFlatVector(column.name, dataVector, sizeOrNullabilityBuffer); 33450} 33451function decodeFloatColumn(data, offset, column, sizeOrNullabilityBuffer) { 33452 const dataStreamMetadata = decodeStreamMetadata(data, offset); 33453 const nullabilityBuffer = isNullabilityBuffer(sizeOrNullabilityBuffer) ? sizeOrNullabilityBuffer : void 0; 33454 const dataStream = decodeFloatsLE(data, offset, dataStreamMetadata.numValues, nullabilityBuffer); 33455 return new FloatFlatVector(column.name, dataStream, sizeOrNullabilityBuffer); 33456} 33457function decodeDoubleColumn(data, offset, column, sizeOrNullabilityBuffer) { 33458 const dataStreamMetadata = decodeStreamMetadata(data, offset); 33459 const nullabilityBuffer = isNullabilityBuffer(sizeOrNullabilityBuffer) ? sizeOrNullabilityBuffer : void 0; 33460 const dataStream = decodeDoublesLE(data, offset, dataStreamMetadata.numValues, nullabilityBuffer); 33461 return new DoubleFlatVector(column.name, dataStream, sizeOrNullabilityBuffer); 33462} 33463function decodeInt64Column(data, offset, column, sizeOrNullabilityBuffer, scalarColumn) { 33464 const dataStreamMetadata = decodeStreamMetadata(data, offset); 33465 const vectorType = getVectorType(dataStreamMetadata, sizeOrNullabilityBuffer, data, offset, "int64"); 33466 const isSigned = scalarColumn.physicalType === ScalarType.INT_64; 33467 if (vectorType === VectorType.FLAT) { 33468 const nullabilityBuffer = isNullabilityBuffer(sizeOrNullabilityBuffer) ? sizeOrNullabilityBuffer : void 0; 33469 const dataStream = isSigned ? decodeSignedInt64Stream(data, offset, dataStreamMetadata, nullabilityBuffer) : decodeUnsignedInt64Stream(data, offset, dataStreamMetadata, nullabilityBuffer); 33470 return new Int64FlatVector(column.name, dataStream, sizeOrNullabilityBuffer); 33471 } 33472 if (vectorType === VectorType.SEQUENCE) { 33473 const id = decodeSequenceInt64Stream(data, offset, dataStreamMetadata); 33474 return new Int64SequenceVector(column.name, id[0], id[1], dataStreamMetadata.numRleValues, isSigned); 33475 } 33476 const constValue = isSigned ? decodeSignedConstInt64Stream(data, offset, dataStreamMetadata) : decodeUnsignedConstInt64Stream(data, offset, dataStreamMetadata); 33477 return new Int64ConstVector(column.name, constValue, sizeOrNullabilityBuffer, isSigned); 33478} 33479function decodeInt32Column(data, offset, column, scalarColumn, sizeOrNullabilityBuffer) { 33480 const dataStreamMetadata = decodeStreamMetadata(data, offset); 33481 const vectorType = getVectorType(dataStreamMetadata, sizeOrNullabilityBuffer, data, offset); 33482 const isSigned = scalarColumn.physicalType === ScalarType.INT_32; 33483 if (vectorType === VectorType.FLAT) { 33484 const nullabilityBuffer = isNullabilityBuffer(sizeOrNullabilityBuffer) ? sizeOrNullabilityBuffer : void 0; 33485 const dataStream = isSigned ? decodeSignedInt32Stream(data, offset, dataStreamMetadata, void 0, nullabilityBuffer) : decodeUnsignedInt32Stream(data, offset, dataStreamMetadata, void 0, nullabilityBuffer); 33486 return new Int32FlatVector(column.name, dataStream, sizeOrNullabilityBuffer); 33487 } 33488 if (vectorType === VectorType.SEQUENCE) { 33489 const id = decodeSequenceInt32Stream(data, offset, dataStreamMetadata); 33490 return new Int32SequenceVector(column.name, id[0], id[1], dataStreamMetadata.numRleValues, isSigned); 33491 } 33492 const constValue = isSigned ? decodeSignedConstInt32Stream(data, offset, dataStreamMetadata) : decodeUnsignedConstInt32Stream(data, offset, dataStreamMetadata); 33493 return new Int32ConstVector(column.name, constValue, sizeOrNullabilityBuffer, isSigned); 33494} 33495function isNullabilityBuffer(sizeOrNullabilityBuffer) { 33496 return sizeOrNullabilityBuffer instanceof BitVector; 33497} 33498//#endregion 33499//#region node_modules/@maplibre/mlt/dist/metadata/tileset/typeMap.js 33500/** 33501* The single varint32 that introduces every column in the tile metadata, identifying what kind of 33502* column follows. Ids occupy a small range of flagged codes, geometry has one code of its own, and 33503* scalar properties are laid out from `SCALAR_BASE` upwards, two codes per type. 33504*/ 33505const ColumnTypeCode = { 33506 /** Id columns occupy 0..3. */ 33507 ID: 0, 33508 /** Set on an id column whose values can be null. */ 33509 ID_NULLABLE: 1, 33510 /** Set on an id column holding 64-bit rather than 32-bit ids. */ 33511 ID_LONG: 2, 33512 GEOMETRY: 4, 33513 /** Scalar properties are `SCALAR_BASE + scalarType * 2 + (nullable ? 1 : 0)`. */ 33514 SCALAR_BASE: 10, 33515 STRUCT: 30, 33516 MAP: 31 33517}; 33518/** 33519* The type code is a single varint32 that encodes: 33520* - Physical or logical type 33521* - Nullable flag 33522* - Whether the column has a name (typeCode >= ColumnTypeCode.SCALAR_BASE) 33523* - Whether the column has children (typeCode == 30 for STRUCT) 33524* - For ID types: whether it uses long (64-bit) IDs 33525*/ 33526/** 33527* Decodes a type code into a Column structure. 33528* 33529* ID type codes (0..3): 33530* - Bit 0: nullable 33531* - Bit 1: longID (0/1 -> uint32 IDs, 2/3 -> uint64 IDs) 33532* 33533* ID columns are kept as logical types so they remain distinguishable 33534* from feature properties that may also be named "id". 33535*/ 33536function decodeColumnType(typeCode) { 33537 switch (typeCode) { 33538 case ColumnTypeCode.ID: 33539 case ColumnTypeCode.ID | ColumnTypeCode.ID_NULLABLE: 33540 case ColumnTypeCode.ID | ColumnTypeCode.ID_LONG: 33541 case ColumnTypeCode.ID | ColumnTypeCode.ID_LONG | ColumnTypeCode.ID_NULLABLE: return { 33542 nullable: (typeCode & ColumnTypeCode.ID_NULLABLE) !== 0, 33543 columnScope: ColumnScope.FEATURE, 33544 type: "scalarType", 33545 scalarType: { 33546 longID: (typeCode & ColumnTypeCode.ID_LONG) !== 0, 33547 type: "logicalType", 33548 logicalType: LogicalScalarType.ID 33549 } 33550 }; 33551 case ColumnTypeCode.GEOMETRY: return { 33552 nullable: false, 33553 columnScope: ColumnScope.FEATURE, 33554 type: "complexType", 33555 complexType: { 33556 type: "physicalType", 33557 physicalType: ComplexType.GEOMETRY, 33558 children: [] 33559 } 33560 }; 33561 case ColumnTypeCode.STRUCT: return { 33562 nullable: false, 33563 columnScope: ColumnScope.FEATURE, 33564 type: "complexType", 33565 complexType: { 33566 type: "physicalType", 33567 physicalType: ComplexType.STRUCT, 33568 children: [] 33569 } 33570 }; 33571 case ColumnTypeCode.MAP: return { 33572 nullable: true, 33573 columnScope: ColumnScope.FEATURE, 33574 type: "complexType", 33575 complexType: { 33576 type: "physicalType", 33577 physicalType: ComplexType.MAP, 33578 children: [] 33579 } 33580 }; 33581 default: return mapScalarType(typeCode); 33582 } 33583} 33584/** 33585* Returns true if this type code requires a name to be stored. 33586* ID (0-3) and GEOMETRY (4) columns have implicit names. 33587* All other types (>= ColumnTypeCode.SCALAR_BASE) require explicit names. 33588*/ 33589function columnTypeHasName(typeCode) { 33590 return typeCode >= ColumnTypeCode.SCALAR_BASE; 33591} 33592/** 33593* Returns true if this type code has child fields. 33594* STRUCT (typeCode 30) and MAP (typeCode 31) have children. 33595*/ 33596function columnTypeHasChildren(typeCode) { 33597 return typeCode === ColumnTypeCode.STRUCT || typeCode === ColumnTypeCode.MAP; 33598} 33599/** 33600* Determines if a stream count needs to be read for this column. 33601* Mirrors the logic in cpp/include/mlt/metadata/type_map.hpp lines 85-122 33602*/ 33603function hasStreamCount(column) { 33604 if (column.type === "scalarType") { 33605 const scalarCol = column.scalarType; 33606 if (scalarCol.type === "physicalType") switch (scalarCol.physicalType) { 33607 case ScalarType.BOOLEAN: 33608 case ScalarType.INT_8: 33609 case ScalarType.UINT_8: 33610 case ScalarType.INT_32: 33611 case ScalarType.UINT_32: 33612 case ScalarType.INT_64: 33613 case ScalarType.UINT_64: 33614 case ScalarType.FLOAT: 33615 case ScalarType.DOUBLE: return false; 33616 case ScalarType.STRING: return true; 33617 default: return false; 33618 } 33619 if (scalarCol.type === "logicalType") return false; 33620 } else if (column.type === "complexType") { 33621 const complexCol = column.complexType; 33622 if (complexCol.type === "physicalType") switch (complexCol.physicalType) { 33623 case ComplexType.GEOMETRY: 33624 case ComplexType.STRUCT: 33625 case ComplexType.MAP: return true; 33626 default: return false; 33627 } 33628 } 33629 console.warn("Unexpected column type in hasStreamCount", column); 33630 return false; 33631} 33632function isLogicalIdColumn(column) { 33633 return column.type === "scalarType" && column.scalarType?.type === "logicalType" && column.scalarType.logicalType === LogicalScalarType.ID; 33634} 33635function isGeometryColumn(column) { 33636 return column.type === "complexType" && column.complexType?.type === "physicalType" && column.complexType.physicalType === ComplexType.GEOMETRY; 33637} 33638/** 33639* Maps a scalar type code to a Column with ScalarType. 33640* Type codes 10-29 encode scalar types with nullable flag. 33641* Even codes are non-nullable, odd codes are nullable. 33642*/ 33643function mapScalarType(typeCode) { 33644 let physicalType; 33645 switch (typeCode) { 33646 case 10: 33647 case 11: 33648 physicalType = ScalarType.BOOLEAN; 33649 break; 33650 case 12: 33651 case 13: 33652 physicalType = ScalarType.INT_8; 33653 break; 33654 case 14: 33655 case 15: 33656 physicalType = ScalarType.UINT_8; 33657 break; 33658 case 16: 33659 case 17: 33660 physicalType = ScalarType.INT_32; 33661 break; 33662 case 18: 33663 case 19: 33664 physicalType = ScalarType.UINT_32; 33665 break; 33666 case 20: 33667 case 21: 33668 physicalType = ScalarType.INT_64; 33669 break; 33670 case 22: 33671 case 23: 33672 physicalType = ScalarType.UINT_64; 33673 break; 33674 case 24: 33675 case 25: 33676 physicalType = ScalarType.FLOAT; 33677 break; 33678 case 26: 33679 case 27: 33680 physicalType = ScalarType.DOUBLE; 33681 break; 33682 case 28: 33683 case 29: 33684 physicalType = ScalarType.STRING; 33685 break; 33686 default: return null; 33687 } 33688 return { 33689 nullable: (typeCode & 1) !== 0, 33690 columnScope: ColumnScope.FEATURE, 33691 type: "scalarType", 33692 scalarType: { 33693 longID: false, 33694 type: "physicalType", 33695 physicalType 33696 } 33697 }; 33698} 33699//#endregion 33700//#region node_modules/@maplibre/mlt/dist/metadata/tileset/embeddedTilesetMetadataDecoder.js 33701const textDecoder = new TextDecoder(); 33702const SUPPORTED_COLUMN_TYPES = "0-3(ID), 4(GEOMETRY), 10-29(scalars), 30(STRUCT), 31(MAP)"; 33703const SUPPORTED_FIELD_TYPES = "10-29(scalars), 30(STRUCT), 31(MAP)"; 33704/** 33705* Decodes a length-prefixed UTF-8 string. 33706* Layout: [len: varint32][bytes: len] 33707*/ 33708function decodeString(src, offset) { 33709 const length = decodeVarintInt32(src, offset, 1)[0]; 33710 if (length === 0) return ""; 33711 const start = offset.get(); 33712 const end = start + length; 33713 const view = src.subarray(start, end); 33714 offset.add(length); 33715 return textDecoder.decode(view); 33716} 33717/** 33718* Converts a Column to a Field. 33719* Used when decoding Field metadata which has the same format as Column. 33720*/ 33721function columnToField(column) { 33722 const name = column.name; 33723 const nullable = column.nullable; 33724 return column.type === "scalarType" ? { 33725 type: "scalarField", 33726 scalarField: column.scalarType, 33727 name, 33728 nullable 33729 } : { 33730 type: "complexField", 33731 complexField: column.complexType, 33732 name, 33733 nullable 33734 }; 33735} 33736/** 33737* Decodes a Field used as part of complex types (STRUCT children). 33738*/ 33739function decodeField(src, offset) { 33740 const typeCode = decodeVarintInt32(src, offset, 1)[0] >>> 0; 33741 const base = typeCode >= ColumnTypeCode.SCALAR_BASE ? decodeColumnType(typeCode) : null; 33742 if (!base) throw new Error(`Unsupported field type code ${typeCode}. Supported: ${SUPPORTED_FIELD_TYPES}`); 33743 const column = { 33744 ...base, 33745 name: decodeString(src, offset) 33746 }; 33747 if (column.type === "complexType" && columnTypeHasChildren(typeCode)) { 33748 const complexCol = column.complexType; 33749 const childCount = decodeVarintInt32(src, offset, 1)[0] >>> 0; 33750 complexCol.children = new Array(childCount); 33751 for (let i = 0; i < childCount; i++) complexCol.children[i] = decodeField(src, offset); 33752 } 33753 return columnToField(column); 33754} 33755/** 33756* The typeCode encodes the column type, nullable flag, and whether it has name/children. 33757*/ 33758function decodeColumn(src, offset) { 33759 const typeCode = decodeVarintInt32(src, offset, 1)[0] >>> 0; 33760 const base = decodeColumnType(typeCode); 33761 if (!base) throw new Error(`Unsupported column type code ${typeCode}. Supported: ${SUPPORTED_COLUMN_TYPES}`); 33762 let name; 33763 if (columnTypeHasName(typeCode)) name = decodeString(src, offset); 33764 else if (typeCode < ColumnTypeCode.GEOMETRY) name = "id"; 33765 else if (typeCode === ColumnTypeCode.GEOMETRY) name = "geometry"; 33766 else throw new Error(`Unsupported column type code ${typeCode}. Supported: ${SUPPORTED_COLUMN_TYPES}`); 33767 const column = { 33768 ...base, 33769 name 33770 }; 33771 if (column.type === "complexType" && columnTypeHasChildren(typeCode)) { 33772 const childCount = decodeVarintInt32(src, offset, 1)[0] >>> 0; 33773 const complexCol = column.complexType; 33774 complexCol.children = new Array(childCount); 33775 for (let i = 0; i < childCount; i++) complexCol.children[i] = decodeField(src, offset); 33776 } 33777 return column; 33778} 33779/** 33780* Top-level decoder for embedded tileset metadata. 33781* Reads exactly ONE FeatureTableSchema from the stream. 33782* 33783* @param bytes The byte array containing the metadata 33784* @param offset The current offset in the byte array (will be advanced) 33785*/ 33786function decodeEmbeddedTileSetMetadata(bytes, offset) { 33787 const meta = {}; 33788 meta.featureTables = []; 33789 const table = {}; 33790 table.name = decodeString(bytes, offset); 33791 if (table.name.length === 0) throw new Error("Missing layer name"); 33792 const extent = decodeVarintInt32(bytes, offset, 1)[0] >>> 0; 33793 const columnCount = decodeVarintInt32(bytes, offset, 1)[0] >>> 0; 33794 table.columns = new Array(columnCount); 33795 for (let j = 0; j < columnCount; j++) table.columns[j] = decodeColumn(bytes, offset); 33796 meta.featureTables.push(table); 33797 return [meta, extent]; 33798} 33799//#endregion 33800//#region node_modules/@maplibre/mlt/dist/mltDecoder.js 33801/** 33802* Decodes a tile with embedded metadata (Tag 0x01 format). 33803* This is the primary decoder function for MLT tiles. 33804* 33805* @param tile The tile data to decode (will be decompressed if gzip-compressed) 33806* @param geometryScaling Optional geometry scaling parameters 33807* @param idWithinMaxSafeInteger If true, limits ID values to JavaScript safe integer range (53 bits) 33808*/ 33809function decodeTile(tile, geometryScaling, idWithinMaxSafeInteger = true) { 33810 const offset = new IntWrapper(0); 33811 const featureTables = []; 33812 while (offset.get() < tile.length) { 33813 const blockLength = decodeVarintInt32(tile, offset, 1)[0] >>> 0; 33814 const blockEnd = offset.get() + blockLength; 33815 if (blockEnd > tile.length) throw new Error(`Block overruns tile: ${blockEnd} > ${tile.length}`); 33816 const tag = decodeVarintInt32(tile, offset, 1)[0] >>> 0; 33817 if (tag !== 1 && tag !== 2) { 33818 offset.set(blockEnd); 33819 continue; 33820 } 33821 const [metadata, extent] = decodeEmbeddedTileSetMetadata(tile, offset); 33822 const featureTableMetadata = metadata.featureTables[0]; 33823 let idVector = null; 33824 let geometryVector = null; 33825 const propertyVectors = []; 33826 let numFeatures = 0; 33827 for (const columnMetadata of featureTableMetadata.columns) { 33828 const columnName = columnMetadata.name; 33829 if (isLogicalIdColumn(columnMetadata)) { 33830 let nullabilityBuffer = null; 33831 if (columnMetadata.nullable) { 33832 const presentStreamMetadata = decodeStreamMetadata(tile, offset); 33833 const streamDataStart = offset.get(); 33834 const values = decodeBooleanRle(tile, presentStreamMetadata.numValues, presentStreamMetadata.byteLength, offset); 33835 offset.set(streamDataStart + presentStreamMetadata.byteLength); 33836 nullabilityBuffer = new BitVector(values, presentStreamMetadata.numValues); 33837 } 33838 const idDataStreamMetadata = decodeStreamMetadata(tile, offset); 33839 numFeatures = nullabilityBuffer ? nullabilityBuffer.size() : idDataStreamMetadata.decompressedCount; 33840 idVector = decodeIdColumn(tile, columnMetadata, offset, columnName, idDataStreamMetadata, nullabilityBuffer ?? numFeatures, idWithinMaxSafeInteger); 33841 } else if (isGeometryColumn(columnMetadata)) { 33842 const numStreams = decodeVarintInt32(tile, offset, 1)[0]; 33843 if (numFeatures === 0) { 33844 const savedOffset = offset.get(); 33845 numFeatures = decodeStreamMetadata(tile, offset).decompressedCount; 33846 offset.set(savedOffset); 33847 } 33848 if (geometryScaling) geometryScaling.scale = geometryScaling.extent / extent; 33849 geometryVector = decodeGeometryColumn(tile, numStreams, offset, numFeatures, geometryScaling); 33850 } else { 33851 const numStreams = hasStreamCount(columnMetadata) ? decodeVarintInt32(tile, offset, 1)[0] : 1; 33852 if (numStreams === 0) continue; 33853 const propertyVector = decodePropertyColumn(tile, offset, columnMetadata, numStreams, numFeatures, void 0); 33854 if (propertyVector) { 33855 if (Array.isArray(propertyVector)) for (const property of propertyVector) propertyVectors.push(property); 33856 else propertyVectors.push(propertyVector); 33857 } 33858 } 33859 } 33860 const featureTable = new FeatureTable(featureTableMetadata.name, geometryVector, idVector, propertyVectors, extent); 33861 featureTables.push(featureTable); 33862 offset.set(blockEnd); 33863 } 33864 return featureTables; 33865} 33866function decodeIdColumn(tile, columnMetadata, offset, columnName, idDataStreamMetadata, sizeOrNullabilityBuffer, idWithinMaxSafeInteger = false) { 33867 const idDataType = columnMetadata.scalarType?.longID ? ScalarType.UINT_64 : ScalarType.UINT_32; 33868 const nullabilityBuffer = typeof sizeOrNullabilityBuffer === "number" ? void 0 : sizeOrNullabilityBuffer; 33869 const vectorType = getVectorType(idDataStreamMetadata, sizeOrNullabilityBuffer, tile, offset, idDataType === ScalarType.UINT_64 ? "int64" : "int32"); 33870 if (idDataType === ScalarType.UINT_32) switch (vectorType) { 33871 case VectorType.FLAT: return new Int32FlatVector(columnName, decodeUnsignedInt32Stream(tile, offset, idDataStreamMetadata, void 0, nullabilityBuffer), sizeOrNullabilityBuffer); 33872 case VectorType.SEQUENCE: { 33873 const id = decodeSequenceInt32Stream(tile, offset, idDataStreamMetadata); 33874 return new Int32SequenceVector(columnName, id[0], id[1], idDataStreamMetadata.numRleValues, false); 33875 } 33876 case VectorType.CONST: return new Int32ConstVector(columnName, decodeUnsignedConstInt32Stream(tile, offset, idDataStreamMetadata), sizeOrNullabilityBuffer, false); 33877 } 33878 switch (vectorType) { 33879 case VectorType.FLAT: 33880 if (idWithinMaxSafeInteger) return new DoubleFlatVector(columnName, decodeUnsignedInt64AsFloat64Stream(tile, offset, idDataStreamMetadata, nullabilityBuffer), sizeOrNullabilityBuffer); 33881 return new Int64FlatVector(columnName, decodeUnsignedInt64Stream(tile, offset, idDataStreamMetadata, nullabilityBuffer), sizeOrNullabilityBuffer); 33882 case VectorType.SEQUENCE: { 33883 const id = decodeSequenceInt64Stream(tile, offset, idDataStreamMetadata); 33884 return new Int64SequenceVector(columnName, id[0], id[1], idDataStreamMetadata.numRleValues, false); 33885 } 33886 case VectorType.CONST: return new Int64ConstVector(columnName, decodeUnsignedConstInt64Stream(tile, offset, idDataStreamMetadata), sizeOrNullabilityBuffer, false); 33887 } 33888 throw new Error("Vector type not supported for id column."); 33889} 33890const PAGE_SIZE = normalizePageSize(DEFAULT_PAGE_SIZE); 33891PAGE_SIZE / 32 * 4; 338923 * PAGE_SIZE / 256 + PAGE_SIZE | 0; 33893//#endregion 33894//#region src/source/vector_tile_mlt.ts 33895var MLTVectorTileFeature = class { 33896 constructor(feature, extent) { 33897 this._featureData = feature; 33898 this.properties = this._featureData.properties || {}; 33899 switch (this._featureData.geometry?.type) { 33900 case GEOMETRY_TYPE.POINT: 33901 case GEOMETRY_TYPE.MULTIPOINT: 33902 this.type = 1; 33903 break; 33904 case GEOMETRY_TYPE.LINESTRING: 33905 case GEOMETRY_TYPE.MULTILINESTRING: 33906 this.type = 2; 33907 break; 33908 case GEOMETRY_TYPE.POLYGON: 33909 case GEOMETRY_TYPE.MULTIPOLYGON: 33910 this.type = 3; 33911 break; 33912 default: this.type = 0; 33913 } 33914 this.extent = extent; 33915 this.id = Number(this._featureData.id); 33916 } 33917 loadGeometry() { 33918 const points = []; 33919 for (const ring of this._featureData.geometry.coordinates) { 33920 const pointRing = []; 33921 for (const coord of ring) pointRing.push(new Point(coord.x, coord.y)); 33922 points.push(pointRing); 33923 } 33924 return points; 33925 } 33926}; 33927var MLTVectorTileLayer = class { 33928 constructor(featureTable) { 33929 this.features = []; 33930 this.featureTable = featureTable; 33931 this.name = featureTable.name; 33932 this.extent = featureTable.extent; 33933 this.version = 2; 33934 this.features = featureTable.getFeatures(); 33935 this.length = this.features.length; 33936 } 33937 feature(i) { 33938 return new MLTVectorTileFeature(this.features[i], this.extent); 33939 } 33940}; 33941var MLTVectorTile = class { 33942 constructor(buffer) { 33943 this.layers = {}; 33944 const features = decodeTile(new Uint8Array(buffer)); 33945 this.layers = features.reduce((acc, f) => ({ 33946 ...acc, 33947 [f.name]: new MLTVectorTileLayer(f) 33948 }), {}); 33949 } 33950}; 33951//#endregion 33952//#region src/data/feature_index.ts 33953/** 33954* An in memory index class to allow fast interaction with features 33955*/ 33956var FeatureIndex = class { 33957 constructor(tileID, promoteId) { 33958 this.tileID = tileID; 33959 this.x = tileID.canonical.x; 33960 this.y = tileID.canonical.y; 33961 this.z = tileID.canonical.z; 33962 this.grid = new TransferableGridIndex(EXTENT$1, 16, 0); 33963 this.grid3D = new TransferableGridIndex(EXTENT$1, 16, 0); 33964 this.featureIndexArray = new FeatureIndexArray(); 33965 this.promoteId = promoteId; 33966 } 33967 insert(feature, geometry, featureIndex, sourceLayerIndex, bucketIndex, is3D) { 33968 const key = this.featureIndexArray.length; 33969 this.featureIndexArray.emplaceBack(featureIndex, sourceLayerIndex, bucketIndex); 33970 const grid = is3D ? this.grid3D : this.grid; 33971 for (const ring of geometry) { 33972 const bbox = [ 33973 Infinity, 33974 Infinity, 33975 -Infinity, 33976 -Infinity 33977 ]; 33978 for (const p of ring) { 33979 bbox[0] = Math.min(bbox[0], p.x); 33980 bbox[1] = Math.min(bbox[1], p.y); 33981 bbox[2] = Math.max(bbox[2], p.x); 33982 bbox[3] = Math.max(bbox[3], p.y); 33983 } 33984 if (bbox[0] < 8192 && bbox[1] < 8192 && bbox[2] >= 0 && bbox[3] >= 0) grid.insert(key, bbox[0], bbox[1], bbox[2], bbox[3]); 33985 } 33986 } 33987 loadVTLayers() { 33988 if (!this.vtLayers) { 33989 switch (this.encoding) { 33990 case "mlt": 33991 this.vtLayers = new MLTVectorTile(this.rawTileData).layers; 33992 break; 33993 default: this.vtLayers = new VectorTile(new PbfReader(this.rawTileData)).layers; 33994 } 33995 this.sourceLayerCoder = new DictionaryCoder(this.vtLayers ? Object.keys(this.vtLayers).sort() : [GEOJSON_TILE_LAYER_NAME]); 33996 } 33997 return this.vtLayers; 33998 } 33999 query(args, styleLayers, serializedLayers, sourceFeatureState) { 34000 this.loadVTLayers(); 34001 const params = args.params; 34002 const pixelsToTileUnits = EXTENT$1 / args.tileSize / args.scale; 34003 const filter = featureFilter(params.filter, "queryRenderedFeatures filter", params.globalState); 34004 const queryGeometry = args.queryGeometry; 34005 const queryPadding = args.queryPadding * pixelsToTileUnits; 34006 const bounds = Bounds.fromPoints(queryGeometry); 34007 const matching = this.grid.query(bounds.minX - queryPadding, bounds.minY - queryPadding, bounds.maxX + queryPadding, bounds.maxY + queryPadding); 34008 const cameraBounds = Bounds.fromPoints(args.cameraQueryGeometry).expandBy(queryPadding); 34009 const matching3D = this.grid3D.query(cameraBounds.minX, cameraBounds.minY, cameraBounds.maxX, cameraBounds.maxY, (bx1, by1, bx2, by2) => { 34010 return polygonIntersectsBox(args.cameraQueryGeometry, bx1 - queryPadding, by1 - queryPadding, bx2 + queryPadding, by2 + queryPadding); 34011 }); 34012 for (const key of matching3D) matching.push(key); 34013 matching.sort(topDownFeatureComparator); 34014 const result = {}; 34015 let previousIndex; 34016 for (const index of matching) { 34017 if (index === previousIndex) continue; 34018 previousIndex = index; 34019 const match = this.featureIndexArray.get(index); 34020 let featureGeometry = null; 34021 this.loadMatchingFeature(result, match.bucketIndex, match.sourceLayerIndex, match.featureIndex, filter, params.layers, params.availableImages, styleLayers, serializedLayers, sourceFeatureState, (feature, styleLayer, featureState) => { 34022 featureGeometry ||= loadGeometry(feature); 34023 return styleLayer.queryIntersectsFeature({ 34024 queryGeometry, 34025 feature, 34026 featureState, 34027 geometry: featureGeometry, 34028 zoom: this.z, 34029 transform: args.transform, 34030 pixelsToTileUnits, 34031 pixelPosMatrix: args.pixelPosMatrix, 34032 unwrappedTileID: this.tileID.toUnwrapped(), 34033 getElevation: args.getElevation 34034 }); 34035 }); 34036 } 34037 return result; 34038 } 34039 loadMatchingFeature(result, bucketIndex, sourceLayerIndex, featureIndex, filter, filterLayerIDs, availableImages, styleLayers, serializedLayers, sourceFeatureState, intersectionTest) { 34040 const layerIDs = this.bucketLayerIDs[bucketIndex]; 34041 if (filterLayerIDs && !layerIDs.some((id) => filterLayerIDs.has(id))) return; 34042 const sourceLayerName = this.sourceLayerCoder.decode(sourceLayerIndex); 34043 const feature = this.vtLayers[sourceLayerName].feature(featureIndex); 34044 if (filter.needGeometry) { 34045 const evaluationFeature = toEvaluationFeature(feature, true); 34046 if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) return; 34047 } else if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) return; 34048 const id = this.getId(feature, sourceLayerName); 34049 for (const layerID of layerIDs) { 34050 if (filterLayerIDs && !filterLayerIDs.has(layerID)) continue; 34051 const styleLayer = styleLayers[layerID]; 34052 if (!styleLayer) continue; 34053 let featureState = {}; 34054 if (id && sourceFeatureState) featureState = sourceFeatureState.getState(styleLayer.sourceLayer || "_geojsonTileLayer", id); 34055 const serializedLayer = extend({}, serializedLayers[layerID]); 34056 serializedLayer.paint = evaluateProperties(serializedLayer.paint, styleLayer.paint, feature, featureState, availableImages); 34057 serializedLayer.layout = evaluateProperties(serializedLayer.layout, styleLayer.layout, feature, featureState, availableImages); 34058 const intersectionZ = !intersectionTest || intersectionTest(feature, styleLayer, featureState); 34059 if (!intersectionZ) continue; 34060 const geojsonFeature = new GeoJSONFeature(feature, this.z, this.x, this.y, id); 34061 geojsonFeature.layer = serializedLayer; 34062 let layerResult = result[layerID]; 34063 if (layerResult === void 0) layerResult = result[layerID] = []; 34064 layerResult.push({ 34065 featureIndex, 34066 feature: geojsonFeature, 34067 intersectionZ 34068 }); 34069 } 34070 } 34071 lookupSymbolFeatures(symbolFeatureIndexes, serializedLayers, bucketIndex, sourceLayerIndex, filterParams, filterLayerIDs, availableImages, styleLayers) { 34072 const result = {}; 34073 this.loadVTLayers(); 34074 const filter = featureFilter(filterParams.filterSpec, "queryRenderedFeatures symbol filter", filterParams.globalState); 34075 for (const symbolFeatureIndex of symbolFeatureIndexes) this.loadMatchingFeature(result, bucketIndex, sourceLayerIndex, symbolFeatureIndex, filter, filterLayerIDs, availableImages, styleLayers, serializedLayers); 34076 return result; 34077 } 34078 hasLayer(id) { 34079 for (const layerIDs of this.bucketLayerIDs) for (const layerID of layerIDs) if (id === layerID) return true; 34080 return false; 34081 } 34082 getId(feature, sourceLayerId) { 34083 let id = feature.id; 34084 if (this.promoteId) { 34085 const propName = typeof this.promoteId === "string" ? this.promoteId : this.promoteId[sourceLayerId]; 34086 id = feature.properties[propName]; 34087 if (typeof id === "boolean") id = Number(id); 34088 if (id === void 0 && feature.properties?.cluster && this.promoteId) id = Number(feature.properties.cluster_id); 34089 } 34090 return id; 34091 } 34092}; 34093register("FeatureIndex", FeatureIndex, { omit: ["rawTileData", "sourceLayerCoder"] }); 34094/** 34095* Whether a possibly-evaluated property still has to be evaluated against a feature, as a 34096* data-driven one does. 34097* 34098* A data-constant property is already the value it will be drawn with, and that value is often a 34099* primitive -- `'map'` for an alignment, a number for an opacity -- which the `in` operator throws 34100* on, so it is not reached for until the value is known to be an object. 34101*/ 34102function needsEvaluating(value) { 34103 return typeof value === "object" && value !== null && "evaluate" in value; 34104} 34105/** 34106* Evaluates a serialized layer's paint or layout properties against one feature, so that a queried 34107* feature reports the values it was actually drawn with. 34108* 34109* A property the layer does not carry as a possibly-evaluated value, or one that is already a plain 34110* value, is passed through as it is. 34111*/ 34112function evaluateProperties(serializedProperties, styleLayerProperties, feature, featureState, availableImages) { 34113 return mapObject(serializedProperties, (_property, key) => { 34114 const value = styleLayerProperties instanceof PossiblyEvaluated ? styleLayerProperties.get(key) : null; 34115 return needsEvaluating(value) ? value.evaluate(feature, featureState, void 0, availableImages) : value; 34116 }); 34117} 34118function topDownFeatureComparator(a, b) { 34119 return b - a; 34120} 34121//#endregion 34122//#region src/tile/tile_cache.ts 34123/** 34124* @internal 34125* A [least-recently-used cache](https://en.wikipedia.org/wiki/Cache_algorithms) 34126* with hash lookup made possible by keeping a list of keys in parallel to 34127* an array of dictionary of values 34128* 34129* TileManager offloads currently unused tiles to this cache, and when a tile gets used again, 34130* it is also removed from this cache. Thus addition is the only operation that counts as "usage" 34131* for the purposes of LRU behaviour. 34132*/ 34133var TileCache = class { 34134 /** 34135 * @param max - number of permitted values 34136 * @param onRemove - callback called with items when they expire 34137 */ 34138 constructor(max, onRemove) { 34139 this.max = max; 34140 this.onRemove = onRemove; 34141 this.reset(); 34142 } 34143 /** 34144 * Clear the cache 34145 * 34146 * @returns this cache 34147 */ 34148 reset() { 34149 for (const key in this.data) for (const removedData of this.data[key]) { 34150 if (removedData.timeout) clearTimeout(removedData.timeout); 34151 this.onRemove(removedData.value); 34152 } 34153 this.data = {}; 34154 this.order = []; 34155 return this; 34156 } 34157 /** 34158 * Add a key, value combination to the cache, trimming its size if this pushes 34159 * it over max length. 34160 * 34161 * @param tileID - lookup key for the item 34162 * @param data - tile data 34163 * 34164 * @returns this cache 34165 */ 34166 add(tileID, data, expiryTimeout) { 34167 const key = tileID.wrapped().key; 34168 if (this.data[key] === void 0) this.data[key] = []; 34169 const dataWrapper = { 34170 value: data, 34171 timeout: void 0 34172 }; 34173 if (expiryTimeout !== void 0) dataWrapper.timeout = setTimeout(() => { 34174 this.remove(tileID, dataWrapper); 34175 }, expiryTimeout); 34176 this.data[key].push(dataWrapper); 34177 this.order.push(key); 34178 if (this.order.length > this.max) { 34179 const removedData = this._getAndRemoveByKey(this.order[0]); 34180 if (removedData) this.onRemove(removedData); 34181 } 34182 return this; 34183 } 34184 /** 34185 * Determine whether the value attached to `key` is present 34186 * 34187 * @param tileID - the key to be looked-up 34188 * @returns whether the cache has this value 34189 */ 34190 has(tileID) { 34191 return tileID.wrapped().key in this.data; 34192 } 34193 /** 34194 * Get the value attached to a specific key and remove data from cache. 34195 * If the key is not found, returns `null` 34196 * 34197 * @param tileID - the key to look up 34198 * @returns the tile data, or null if it isn't found 34199 */ 34200 getAndRemove(tileID) { 34201 if (!this.has(tileID)) return null; 34202 return this._getAndRemoveByKey(tileID.wrapped().key); 34203 } 34204 _getAndRemoveByKey(key) { 34205 const data = this.data[key].shift(); 34206 if (data.timeout) clearTimeout(data.timeout); 34207 if (this.data[key].length === 0) delete this.data[key]; 34208 this.order.splice(this.order.indexOf(key), 1); 34209 return data.value; 34210 } 34211 getByKey(key) { 34212 const data = this.data[key]; 34213 return data ? data[0].value : null; 34214 } 34215 /** 34216 * Get the value attached to a specific key without removing data 34217 * from the cache. If the key is not found, returns `null` 34218 * 34219 * @param tileID - the key to look up 34220 * @returns the tile data, or null if it isn't found 34221 */ 34222 get(tileID) { 34223 if (!this.has(tileID)) return null; 34224 return this.data[tileID.wrapped().key][0].value; 34225 } 34226 /** 34227 * Remove a key/value combination from the cache. 34228 * 34229 * @param tileID - the key for the pair to delete 34230 * @param value - If a value is provided, remove that exact version of the value. 34231 * @returns this cache 34232 */ 34233 remove(tileID, value) { 34234 if (!this.has(tileID)) return this; 34235 const key = tileID.wrapped().key; 34236 const dataIndex = value === void 0 ? 0 : this.data[key].indexOf(value); 34237 const data = this.data[key][dataIndex]; 34238 this.data[key].splice(dataIndex, 1); 34239 if (data.timeout) clearTimeout(data.timeout); 34240 if (this.data[key].length === 0) delete this.data[key]; 34241 this.onRemove(data.value); 34242 this.order.splice(this.order.indexOf(key), 1); 34243 return this; 34244 } 34245 /** 34246 * Change the max size of the cache. 34247 * 34248 * @param max - the max size of the cache 34249 * @returns this cache 34250 */ 34251 setMaxSize(max) { 34252 this.max = max; 34253 while (this.order.length > this.max) { 34254 const removedData = this._getAndRemoveByKey(this.order[0]); 34255 if (removedData) this.onRemove(removedData); 34256 } 34257 return this; 34258 } 34259 /** 34260 * Remove entries that do not pass a filter function. Used for removing 34261 * stale tiles from the cache. 34262 * 34263 * @param filterFn - Determines whether the tile is filtered. If the supplied function returns false, the tile will be filtered out. 34264 */ 34265 filter(filterFn) { 34266 const removed = []; 34267 for (const key in this.data) for (const entry of this.data[key]) if (!filterFn(entry.value)) removed.push(entry); 34268 for (const r of removed) this.remove(r.value.tileID, r); 34269 } 34270}; 34271var BoundedLRUCache = class { 34272 constructor(maxEntries) { 34273 this.maxEntries = maxEntries; 34274 this.map = /* @__PURE__ */ new Map(); 34275 } 34276 get(key) { 34277 const value = this.map.get(key); 34278 if (value !== void 0) { 34279 this.map.delete(key); 34280 this.map.set(key, value); 34281 } 34282 return value; 34283 } 34284 set(key, value) { 34285 if (this.map.has(key)) this.map.delete(key); 34286 else if (this.map.size >= this.maxEntries) { 34287 const oldestKey = this.map.keys().next().value; 34288 this.map.delete(oldestKey); 34289 } 34290 this.map.set(key, value); 34291 } 34292 clear() { 34293 this.map.clear(); 34294 } 34295}; 34296//#endregion 34297export { projectToWorldCoordinates as $, differenceOfAnglesDegrees as $n, add$4 as $r, Transitionable as $t, evaluateSizeForZoom as A, rotateX$3 as Ai, addProtocol as An, scaleZoom as Ar, toEvaluationFeature as At, isCluster as B, rotate$4 as Bi, arrayBufferToImage as Bn, EXTENT$1 as Br, SegmentVector as Bt, addDynamicAttributes as C, exactEquals$5 as Ci, GLOBAL_DISPATCHER_ID as Cn, pointPlaneSignedDistance as Cr, HEATMAP_FULL_RENDER_FBO_KEY as Ct, clipGeometry as D, multiply$5 as Di, getVideo as Dn, remapSaturate as Dr, RGBAImage as Dt, TextAnchorEnum as E, invert$2 as Ei, getReferrer as En, readImageUsingVideoFrame as Er, AlphaImage as Et, potpack as F, create$6 as Fi, isAbortError as Fn, uniqueId as Fr, Uniform4f as Ft, GeoJSONVT as G, createIdentityMat4f32 as Gn, zero as Gr, PosArray as Gt, rtlWorkerPlugin as H, offscreenCanvasSupported as Hi, bezier as Hn, length as Hr, CollisionCircleLayoutArray as Ht, isStyleImageWebGLData as I, fromRotation$2 as Ii, throwIfAborted as In, warnOnce as Ir, UniformColor as It, cameraDirectionFromPitchBearing as J, createVec3f64 as Jn, multiply$2 as Jr, TriangleIndexArray as Jt, isFillExtrusionStyleLayer as K, createIdentityMat4f64 as Kn, fromEuler as Kr, QuadTriangleArray as Kt, renderStyleImage as L, create$8 as Li, JSON_PREFIX as Ln, wrap$1 as Lr, UniformColorArray as Lt, getAnchorAlignment as M, rotateZ$3 as Mi, removeProtocol as Mn, subscribe as Mr, Uniform1i as Mt, ImageAtlas as N, scale$5 as Ni, config as Nn, threePlaneIntersection as Nr, Uniform2f as Nt, clipLine as O, ortho as Oi, makeRequest as On, rollPitchBearingEqual as Or, isCircleStyleLayer as Ot, ImagePosition as P, translate$2 as Pi, AbortError as Pn, translatePosition as Pr, Uniform3f as Pt, maxMercatorHorizonAngle as Q, degreesToRadians as Qn, transformMat4$1 as Qr, Properties as Qt, parseGlyphPbf as R, determinant$3 as Ri, MAX_VALID_LATITUDE as Rn, zoomScale as Rr, UniformFloatArray as Rt, SymbolBucket as S, equals$6 as Si, AJAXError as Sn, pick as Sr, isHillshadeStyleLayer as St, getAnchorJustification as T, identity$2 as Ti, getJSON as Tn, rayPlaneIntersection as Tr, renderColorRamp as Tt, collisionCircleLayout as U, Point as Ui, clamp$2 as Un, scale as Ur, LineStripIndexArray as Ut, codePointUsesLocalIdeographFontFamily as V, isOffscreenCanvasDistorted as Vi, arrayBufferToImageBitmap as Vn, create as Vr, CollisionBoxArray as Vt, isLineStyleLayer as W, clone as Wn, sqrLen as Wr, Pos3dArray as Wt, cameraMercatorCoordinateFromCenterAndRotation as X, deepEqual$1 as Xn, mul$3 as Xr, isRasterStyleLayer as Xt, cameraMercatorCoordinate as Y, createVec4f64 as Yn, slerp as Yr, createLayout as Yt, getMercatorHorizon as Z, defaultEasing as Zn, scale$3 as Zr, DataConstantProperty as Zt, createStyleLayer as _, transformQuat$1 as _i, derefLayers as _n, lerp as _r, SubdivisionGranularityExpression as _t, GeoJSONFeature as a, length$4 as ai, validateAndEmit as an, findLineIntersection as ar, lngFromMercatorX as at, isBackgroundStyleLayer as b, copy$5 as bi, Event as bn, nextPowerOfTwo as br, DEMData as bt, GeoJSONWrapper as c, rotateX$2 as ci, emptyStyle as cn, getEdgeTiles as cr, mercatorZfromAltitude as ct, OverscaledTileID as d, scale$4 as di, createExpression as dn, isImageBitmap as dr, VectorTile as dt, clone$5 as ei, EvaluationParameters as en, distanceOfAnglesRadians as er, tileCoordinatesToMercatorCoordinates as et, UnwrappedTileID as f, scaleAndAdd$2 as fi, interpolateFactory as fn, isPointableEvent as fr, EXTENT_BOUNDS as ft, Actor as g, transformMat4$2 as gi, diff as gn, isWorker as gr, SOUTH_POLE_Y as gt, isInBoundsForZoomLngLat as h, transformMat3$1 as hi, ValidationError as hn, isTouchableOrPointableType as hr, NORTH_POLE_Y as ht, MLTVectorTile as i, len$4 as ii, emitValidationErrors as in, filterObject as ir, latFromMercatorY as it, WritingMode as j, rotateY$3 as ji, getProtocol as jn, sphericalToCartesian as jr, Uniform1f as jt, evaluateSizeForFeature as k, perspective as ki, sameOrigin as kn, rollPitchBearingToQuat as kr, polygonIntersectsPolygon as kt, fromVectorTileJs as l, rotateY$2 as li, groupByLayout as ln, getImageData as lr, LngLat as lt, compareTileId as m, subtract$2 as mi, Color as mn, isTouchableEvent as mr, isFillStyleLayer as mt, TileCache as n, distance$2 as ni, register as nn, evaluateZoomSnap as nr, MercatorCoordinate as nt, DictionaryCoder as o, negate$2 as oi, validateStyle as on, getAABB as or, mercatorXfromLng as ot, calculateTileKey as p, sub$2 as pi, ProjectionDefinition as pn, isSafari as pr, Bounds as pt, calculateTileMatrix as q, createMat4f64 as qn, fromValues$2 as qr, RasterBoundsArray as qt, FeatureIndex as r, dot$5 as ri, SPEC_SOURCE_TYPES as rn, extend as rr, altitudeFromMercatorZ as rt, GEOJSON_TILE_LAYER_NAME as s, normalize$4 as si, validateStyleAndEmit as sn, getAngleDelta as sr, mercatorYfromLat as st, BoundedLRUCache as t, cross$2 as ti, ZoomHistory as tn, ensureError as tr, unprojectFromWorldCoordinates as tt, CanonicalTileID as u, rotateZ$2 as ui, featureFilter as un, getRollPitchBearing as ur, earthRadius as ut, isCustomStyleLayer as v, zero$2 as vi, latest as vn, mapObject as vr, SubdivisionGranularitySetting as vt, getOverlapMode as w, fromScaling as wi, getArrayBuffer as wn, radiansToDegrees as wr, isHeatmapStyleLayer as wt, isSymbolStyleLayer as x, create$5 as xi, Evented as xn, parseCacheControl as xr, Texture as xt, validateCustomStyleLayer as y, clone$6 as yi, ErrorEvent as yn, mod as yr, isColorReliefStyleLayer as yt, PbfReader as z, invert$5 as zi, angleToRotateBetweenVectors2D as zn, pixelsToTileUnits as zr, UniformMatrix4f as zt }; 34298 34299//# sourceMappingURL=maplibre-gl-shared-dev.mjs.map
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.