diff --git a/build.js b/build.js index bcbb9aff..f1244f24 100644 --- a/build.js +++ b/build.js @@ -75,12 +75,15 @@ const buildIndex = { ], // Full source for environments with strong focus on biodiversity info newSource: [ - "src/client/css/mapbox-gl-draw.css", + "node_modules/@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.js", + "src/client/css/mapbox-gl-draw.css", // has our own overrides + "node_modules/papaparse/papaparse.min.js", "node_modules/pretty-checkbox/dist/pretty-checkbox.min.css", "node_modules/accessible-autocomplete/dist/accessible-autocomplete.min.js", "node_modules/accessible-autocomplete/dist/accessible-autocomplete.min.css", "src/lib/jquery-ui-widgets-tabs.js", "src/lib/point-in-polygon.js", + "src/geom/geoJSON.js", "src/utils/utils.js", "src/client/js/new/filters.js", "src/client/js/new/polygon-draw.js", diff --git a/docs/css/imerss-core.css b/docs/css/imerss-core.css index 0434cc74..eb8906ab 100644 --- a/docs/css/imerss-core.css +++ b/docs/css/imerss-core.css @@ -421,6 +421,12 @@ cursor: pointer; width: 20px; height: 20px; + border-radius: 6px; +} + +.imerss-filter-clear:hover { + /** TODO consolidate these, e.g. imerss-reset-filter */ + background: #d0d7de33; } .imerss-filter-clear.imerss-hidden { diff --git a/docs/css/imerss-viz-all.css b/docs/css/imerss-viz-all.css index 97783cef..ef0be61f 100644 --- a/docs/css/imerss-viz-all.css +++ b/docs/css/imerss-viz-all.css @@ -1117,6 +1117,12 @@ a.ui-button:active, cursor: pointer; width: 20px; height: 20px; + border-radius: 6px; +} + +.imerss-filter-clear:hover { + /** TODO consolidate these, e.g. imerss-reset-filter */ + background: #d0d7de33; } .imerss-filter-clear.imerss-hidden { diff --git a/docs/css/imerss-viz-lib.css b/docs/css/imerss-viz-lib.css index dafaa6dd..5d3651fa 100644 --- a/docs/css/imerss-viz-lib.css +++ b/docs/css/imerss-viz-lib.css @@ -1117,6 +1117,12 @@ a.ui-button:active, cursor: pointer; width: 20px; height: 20px; + border-radius: 6px; +} + +.imerss-filter-clear:hover { + /** TODO consolidate these, e.g. imerss-reset-filter */ + background: #d0d7de33; } .imerss-filter-clear.imerss-hidden { diff --git a/docs/indexBeasOBA.html b/docs/indexBeasOBA.html index 55f43c94..eef06a6a 100644 --- a/docs/indexBeasOBA.html +++ b/docs/indexBeasOBA.html @@ -6,14 +6,11 @@ Oregon Bee Atlas Plant-Pollinator Interactions - - - diff --git a/docs/js/imerss-viz-new-core.js b/docs/js/imerss-viz-new-core.js index a365c908..fb529d27 100644 --- a/docs/js/imerss-viz-new-core.js +++ b/docs/js/imerss-viz-new-core.js @@ -10,5 +10,5 @@ License: MIT * @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v4.0.2/LICENSE.txt */ (function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?module.exports=factory():typeof define==="function"&&define.amd?define(factory):(global=typeof globalThis!=="undefined"?globalThis:global||self,global.maplibregl=factory())})(this,(function(){"use strict";var maplibregl={};var modules={};function define(moduleName,_dependencies,moduleFactory){modules[moduleName]=moduleFactory;if(moduleName!=="index"){return}var workerBundleString="var sharedModule = {}; ("+modules.shared+")(sharedModule); ("+modules.worker+")(sharedModule);";var sharedModule={};modules.shared(sharedModule);modules.index(maplibregl,sharedModule);if(typeof window!=="undefined"){maplibregl.setWorkerUrl(window.URL.createObjectURL(new Blob([workerBundleString],{type:"text/javascript"})))}return maplibregl}define("shared",["exports"],(function(exports){"use strict";var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};function __extends(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}var __assign=function(){__assign=Object.assign||function __assign(t){for(var s,i=1,n=arguments.length;i=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r}function __param(paramIndex,decorator){return function(target,key){decorator(target,key,paramIndex)}}function __esDecorate(ctor,descriptorIn,decorators,contextIn,initializers,extraInitializers){function accept(f){if(f!==void 0&&typeof f!=="function")throw new TypeError("Function expected");return f}var kind=contextIn.kind,key=kind==="getter"?"get":kind==="setter"?"set":"value";var target=!descriptorIn&&ctor?contextIn["static"]?ctor:ctor.prototype:null;var descriptor=descriptorIn||(target?Object.getOwnPropertyDescriptor(target,contextIn.name):{});var _,done=false;for(var i=decorators.length-1;i>=0;i--){var context={};for(var p in contextIn)context[p]=p==="access"?{}:contextIn[p];for(var p in contextIn.access)context.access[p]=contextIn.access[p];context.addInitializer=function(f){if(done)throw new TypeError("Cannot add initializers after decoration has completed");extraInitializers.push(accept(f||null))};var result=(0,decorators[i])(kind==="accessor"?{get:descriptor.get,set:descriptor.set}:descriptor[key],context);if(kind==="accessor"){if(result===void 0)continue;if(result===null||typeof result!=="object")throw new TypeError("Object expected");if(_=accept(result.get))descriptor.get=_;if(_=accept(result.set))descriptor.set=_;if(_=accept(result.init))initializers.unshift(_)}else if(_=accept(result)){if(kind==="field")initializers.unshift(_);else descriptor[key]=_}}if(target)Object.defineProperty(target,contextIn.name,descriptor);done=true}function __runInitializers(thisArg,initializers,value){var useValue=arguments.length>2;for(var i=0;i0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]=o.length)o=void 0;return{value:o&&o[i++],done:!o}}};throw new TypeError(s?"Object is not iterable.":"Symbol.iterator is not defined.")}function __read(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar}function __spread(){for(var ar=[],i=0;i1||resume(n,v)}))}}function resume(n,v){try{step(g[n](v))}catch(e){settle(q[0][3],e)}}function step(r){r.value instanceof __await?Promise.resolve(r.value.v).then(fulfill,reject):settle(q[0][2],r)}function fulfill(value){resume("next",value)}function reject(value){resume("throw",value)}function settle(f,v){if(f(v),q.shift(),q.length)resume(q[0][0],q[0][1])}}function __asyncDelegator(o){var i,p;return i={},verb("next"),verb("throw",(function(e){throw e})),verb("return"),i[Symbol.iterator]=function(){return this},i;function verb(n,f){i[n]=o[n]?function(v){return(p=!p)?{value:__await(o[n](v)),done:false}:f?f(v):v}:f}}function __asyncValues(o){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var m=o[Symbol.asyncIterator],i;return m?m.call(o):(o=typeof __values==="function"?__values(o):o[Symbol.iterator](),i={},verb("next"),verb("throw"),verb("return"),i[Symbol.asyncIterator]=function(){return this},i);function verb(n){i[n]=o[n]&&function(v){return new Promise((function(resolve,reject){v=o[n](v),settle(resolve,reject,v.done,v.value)}))}}function settle(resolve,reject,d,v){Promise.resolve(v).then((function(v){resolve({value:v,done:d})}),reject)}}function __makeTemplateObject(cooked,raw){if(Object.defineProperty){Object.defineProperty(cooked,"raw",{value:raw})}else{cooked.raw=raw}return cooked}var __setModuleDefault=Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:true,value:v})}:function(o,v){o["default"]=v};function __importStar(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)if(k!=="default"&&Object.prototype.hasOwnProperty.call(mod,k))__createBinding(result,mod,k);__setModuleDefault(result,mod);return result}function __importDefault(mod){return mod&&mod.__esModule?mod:{default:mod}}function __classPrivateFieldGet(receiver,state,kind,f){if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f:kind==="a"?f.call(receiver):f?f.value:state.get(receiver)}function __classPrivateFieldSet(receiver,state,value,kind,f){if(kind==="m")throw new TypeError("Private method is not writable");if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kind==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value}function __classPrivateFieldIn(state,receiver){if(receiver===null||typeof receiver!=="object"&&typeof receiver!=="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof state==="function"?receiver===state:state.has(receiver)}function __addDisposableResource(env,value,async){if(value!==null&&value!==void 0){if(typeof value!=="object"&&typeof value!=="function")throw new TypeError("Object expected.");var dispose;if(async){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");dispose=value[Symbol.asyncDispose]}if(dispose===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");dispose=value[Symbol.dispose]}if(typeof dispose!=="function")throw new TypeError("Object not disposable.");env.stack.push({value:value,dispose:dispose,async:async})}else if(async){env.stack.push({async:true})}return value}var _SuppressedError=typeof SuppressedError==="function"?SuppressedError:function(error,suppressed,message){var e=new Error(message);return e.name="SuppressedError",e.error=error,e.suppressed=suppressed,e};function __disposeResources(env){function fail(e){env.error=env.hasError?new _SuppressedError(e,env.error,"An error was suppressed during disposal."):e;env.hasError=true}function next(){while(env.stack.length){var rec=env.stack.pop();try{var result=rec.dispose&&rec.dispose.call(rec.value);if(rec.async)return Promise.resolve(result).then(next,(function(e){fail(e);return next()}))}catch(e){fail(e)}}if(env.hasError)throw env.error}return next()}var tslib_es6={__extends:__extends,__assign:__assign,__rest:__rest,__decorate:__decorate,__param:__param,__metadata:__metadata,__awaiter:__awaiter,__generator:__generator,__createBinding:__createBinding,__exportStar:__exportStar,__values:__values,__read:__read,__spread:__spread,__spreadArrays:__spreadArrays,__spreadArray:__spreadArray,__await:__await,__asyncGenerator:__asyncGenerator,__asyncDelegator:__asyncDelegator,__asyncValues:__asyncValues,__makeTemplateObject:__makeTemplateObject,__importStar:__importStar,__importDefault:__importDefault,__classPrivateFieldGet:__classPrivateFieldGet,__classPrivateFieldSet:__classPrivateFieldSet,__classPrivateFieldIn:__classPrivateFieldIn,__addDisposableResource:__addDisposableResource,__disposeResources:__disposeResources};var commonjsGlobal=typeof globalThis!=="undefined"?globalThis:typeof window!=="undefined"?window:typeof global!=="undefined"?global:typeof self!=="undefined"?self:{};function getDefaultExportFromCjs$1(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x["default"]:x}function getDefaultExportFromNamespaceIfPresent(n){return n&&Object.prototype.hasOwnProperty.call(n,"default")?n["default"]:n}function getDefaultExportFromNamespaceIfNotNamed(n){return n&&Object.prototype.hasOwnProperty.call(n,"default")&&Object.keys(n).length===1?n["default"]:n}function getAugmentedNamespace(n){if(n.__esModule)return n;var f=n.default;if(typeof f=="function"){var a=function a(){if(this instanceof a){return Reflect.construct(f,arguments,this.constructor)}return f.apply(this,arguments)};a.prototype=f.prototype}else a={};Object.defineProperty(a,"__esModule",{value:true});Object.keys(n).forEach((function(k){var d=Object.getOwnPropertyDescriptor(n,k);Object.defineProperty(a,k,d.get?d:{enumerable:true,get:function(){return n[k]}})}));return a}"use strict";var pointGeometry=Point$1;function Point$1(x,y){this.x=x;this.y=y}Point$1.prototype={clone:function(){return new Point$1(this.x,this.y)},add:function(p){return this.clone()._add(p)},sub:function(p){return this.clone()._sub(p)},multByPoint:function(p){return this.clone()._multByPoint(p)},divByPoint:function(p){return this.clone()._divByPoint(p)},mult:function(k){return this.clone()._mult(k)},div:function(k){return this.clone()._div(k)},rotate:function(a){return this.clone()._rotate(a)},rotateAround:function(a,p){return this.clone()._rotateAround(a,p)},matMult:function(m){return this.clone()._matMult(m)},unit:function(){return this.clone()._unit()},perp:function(){return this.clone()._perp()},round:function(){return this.clone()._round()},mag:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals:function(other){return this.x===other.x&&this.y===other.y},dist:function(p){return Math.sqrt(this.distSqr(p))},distSqr:function(p){var dx=p.x-this.x,dy=p.y-this.y;return dx*dx+dy*dy},angle:function(){return Math.atan2(this.y,this.x)},angleTo:function(b){return Math.atan2(this.y-b.y,this.x-b.x)},angleWith:function(b){return this.angleWithSep(b.x,b.y)},angleWithSep:function(x,y){return Math.atan2(this.x*y-this.y*x,this.x*x+this.y*y)},_matMult:function(m){var x=m[0]*this.x+m[1]*this.y,y=m[2]*this.x+m[3]*this.y;this.x=x;this.y=y;return this},_add:function(p){this.x+=p.x;this.y+=p.y;return this},_sub:function(p){this.x-=p.x;this.y-=p.y;return this},_mult:function(k){this.x*=k;this.y*=k;return this},_div:function(k){this.x/=k;this.y/=k;return this},_multByPoint:function(p){this.x*=p.x;this.y*=p.y;return this},_divByPoint:function(p){this.x/=p.x;this.y/=p.y;return this},_unit:function(){this._div(this.mag());return this},_perp:function(){var y=this.y;this.y=this.x;this.x=-y;return this},_rotate:function(angle){var cos=Math.cos(angle),sin=Math.sin(angle),x=cos*this.x-sin*this.y,y=sin*this.x+cos*this.y;this.x=x;this.y=y;return this},_rotateAround:function(angle,p){var 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);this.x=x;this.y=y;return this},_round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);return this}};Point$1.convert=function(a){if(a instanceof Point$1){return a}if(Array.isArray(a)){return new Point$1(a[0],a[1])}return a};var Point$2=getDefaultExportFromCjs$1(pointGeometry);"use strict";var unitbezier$1=UnitBezier$2;function UnitBezier$2(p1x,p1y,p2x,p2y){this.cx=3*p1x;this.bx=3*(p2x-p1x)-this.cx;this.ax=1-this.cx-this.bx;this.cy=3*p1y;this.by=3*(p2y-p1y)-this.cy;this.ay=1-this.cy-this.by;this.p1x=p1x;this.p1y=p1y;this.p2x=p2x;this.p2y=p2y}UnitBezier$2.prototype={sampleCurveX:function(t){return((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return(3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(x,epsilon){if(epsilon===undefined)epsilon=1e-6;if(x<0)return 0;if(x>1)return 1;var t=x;for(var i=0;i<8;i++){var x2=this.sampleCurveX(t)-x;if(Math.abs(x2)x2){t0=t}else{t1=t}t=(t1-t0)*.5+t0}return t},solve:function(x,epsilon){return this.sampleCurveY(this.solveCurveX(x,epsilon))}};var UnitBezier$3=getDefaultExportFromCjs$1(unitbezier$1);let supportsOffscreenCanvas;function offscreenCanvasSupported(){if(supportsOffscreenCanvas==null){supportsOffscreenCanvas=typeof OffscreenCanvas!=="undefined"&&new OffscreenCanvas(1,1).getContext("2d")&&typeof createImageBitmap==="function"}return supportsOffscreenCanvas}let offscreenCanvasDistorted;function isOffscreenCanvasDistorted(){if(offscreenCanvasDistorted==null){offscreenCanvasDistorted=false;if(offscreenCanvasSupported()){const size=5;const canvas=new OffscreenCanvas(size,size);const context=canvas.getContext("2d",{willReadFrequently:true});if(context){for(let i=0;i=1)return 1;const t2=t*t,t3=t2*t;return 4*(t<.5?t3:3*(t-t2)+t3-.75)}function bezier$1(p1x,p1y,p2x,p2y){const bezier=new UnitBezier$3(p1x,p1y,p2x,p2y);return function(t){return bezier.solve(t)}}const defaultEasing=bezier$1(.25,.1,.25,1);function clamp$1(n,min,max){return Math.min(max,Math.max(min,n))}function wrap(n,min,max){const d=max-min;const w=((n-min)%d+d)%d+min;return w===min?max:w}function keysDifference(obj,other){const difference=[];for(const i in obj){if(!(i in other)){difference.push(i)}}return difference}function extend(dest,...sources){for(const src of sources){for(const k in src){dest[k]=src[k]}}return dest}function pick(src,properties){const result={};for(let i=0;i=0)return true}return false}const warnOnceHistory={};function warnOnce(message){if(!warnOnceHistory[message]){if(typeof console!=="undefined")console.warn(message);warnOnceHistory[message]=true}}function isCounterClockwise(a,b,c){return(c.y-a.y)*(b.x-a.x)>(b.y-a.y)*(c.x-a.x)}function findLineIntersection(a1,a2,b1,b2){const aDeltaY=a2.y-a1.y;const aDeltaX=a2.x-a1.x;const bDeltaY=b2.y-b1.y;const bDeltaX=b2.x-b1.x;const denominator=bDeltaY*aDeltaX-bDeltaX*aDeltaY;if(denominator===0){return null}const originDeltaY=a1.y-b1.y;const originDeltaX=a1.x-b1.x;const aInterpolation=(bDeltaX*originDeltaY-bDeltaY*originDeltaX)/denominator;return new Point$2(a1.x+aInterpolation*aDeltaX,a1.y+aInterpolation*aDeltaY)}function calculateSignedArea(ring){let sum=0;for(let i=0,len=ring.length,j=len-1,p1,p2;i0||Math.abs(p1.y-p2.y)>0){return false}return Math.abs(calculateSignedArea(points))>.01}function sphericalToCartesian([r,azimuthal,polar]){azimuthal+=90;azimuthal*=Math.PI/180;polar*=Math.PI/180;return{x:r*Math.cos(azimuthal)*Math.sin(polar),y:r*Math.sin(azimuthal)*Math.sin(polar),z:r*Math.cos(polar)}}function isWorker(self){return typeof WorkerGlobalScope!=="undefined"&&typeof self!=="undefined"&&self instanceof WorkerGlobalScope}function parseCacheControl(cacheControl){const re=/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g;const header={};cacheControl.replace(re,(($0,$1,$2,$3)=>{const value=$2||$3;header[$1]=value?value.toLowerCase():true;return""}));if(header["max-age"]){const maxAge=parseInt(header["max-age"],10);if(isNaN(maxAge))delete header["max-age"];else header["max-age"]=maxAge}return header}let _isSafari=null;function isSafari(scope){if(_isSafari==null){const userAgent=scope.navigator?scope.navigator.userAgent:null;_isSafari=!!scope.safari||!!(userAgent&&(/\b(iPad|iPhone|iPod)\b/.test(userAgent)||!!userAgent.match("Safari")&&!userAgent.match("Chrome")))}return _isSafari}function storageAvailable(type){try{const storage=window[type];storage.setItem("_mapbox_test_",1);storage.removeItem("_mapbox_test_");return true}catch(e){return false}}function b64EncodeUnicode(str){return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,((match,p1)=>String.fromCharCode(Number("0x"+p1)))))}function b64DecodeUnicode(str){return decodeURIComponent(atob(str).split("").map((c=>"%"+("00"+c.charCodeAt(0).toString(16)).slice(-2))).join(""))}function isImageBitmap(image){return typeof ImageBitmap!=="undefined"&&image instanceof ImageBitmap}const arrayBufferToImageBitmap=data=>__awaiter(void 0,void 0,void 0,(function*(){if(data.byteLength===0){return createImageBitmap(new ImageData(1,1))}const blob=new Blob([new Uint8Array(data)],{type:"image/png"});try{return createImageBitmap(blob)}catch(e){throw new Error(`Could not load image because of ${e.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`)}}));const transparentPngUrl="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";const arrayBufferToImage=data=>new Promise(((resolve,reject)=>{const img=new Image;img.onload=()=>{resolve(img);URL.revokeObjectURL(img.src);img.onload=null;window.requestAnimationFrame((()=>{img.src=transparentPngUrl}))};img.onerror=()=>reject(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."));const blob=new Blob([new Uint8Array(data)],{type:"image/png"});img.src=data.byteLength?URL.createObjectURL(blob):transparentPngUrl}));function computeVideoFrameParameters(image,x,y,width,height){const destRowOffset=Math.max(-x,0)*4;const firstSourceRow=Math.max(0,y);const firstDestRow=firstSourceRow-y;const offset=firstDestRow*width*4+destRowOffset;const stride=width*4;const sourceLeft=Math.max(0,x);const sourceTop=Math.max(0,y);const sourceRight=Math.min(image.width,x+width);const sourceBottom=Math.min(image.height,y+height);return{rect:{x:sourceLeft,y:sourceTop,width:sourceRight-sourceLeft,height:sourceBottom-sourceTop},layout:[{offset:offset,stride:stride}]}}function readImageUsingVideoFrame(image,x,y,width,height){return __awaiter(this,void 0,void 0,(function*(){if(typeof VideoFrame==="undefined"){throw new Error("VideoFrame not supported")}const frame=new VideoFrame(image,{timestamp:0});try{const format=frame===null||frame===void 0?void 0:frame.format;if(!format||!(format.startsWith("BGR")||format.startsWith("RGB"))){throw new Error(`Unrecognized format ${format}`)}const swapBR=format.startsWith("BGR");const result=new Uint8ClampedArray(width*height*4);yield frame.copyTo(result,computeVideoFrameParameters(image,x,y,width,height));if(swapBR){for(let i=0;i{target.removeEventListener(message,listener,options)}}}function degreesToRadians(degrees){return degrees*Math.PI/180}const ABORT_ERROR="AbortError";function isAbortError(error){return error.message===ABORT_ERROR}function createAbortError(){return new Error(ABORT_ERROR)}const config={MAX_PARALLEL_IMAGE_REQUESTS:16,MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:8,MAX_TILE_CACHE_ZOOM_LEVELS:5,REGISTERED_PROTOCOLS:{},WORKER_URL:""};function getProtocol(url){return config.REGISTERED_PROTOCOLS[url.substring(0,url.indexOf("://"))]}function addProtocol(customProtocol,loadFn){config.REGISTERED_PROTOCOLS[customProtocol]=loadFn}function removeProtocol(customProtocol){delete config.REGISTERED_PROTOCOLS[customProtocol]}const GLOBAL_DISPATCHER_ID="global-dispatcher";class AJAXError extends Error{constructor(status,statusText,url,body){super(`AJAXError: ${statusText} (${status}): ${url}`);this.status=status;this.statusText=statusText;this.url=url;this.body=body}}const getReferrer=()=>isWorker(self)?self.worker&&self.worker.referrer:(window.location.protocol==="blob:"?window.parent:window).location.href;const isFileURL=url=>/^file:/.test(url)||/^file:/.test(getReferrer())&&!/^\w+:/.test(url);function makeFetchRequest(requestParameters,abortController){return __awaiter(this,void 0,void 0,(function*(){const request=new Request(requestParameters.url,{method:requestParameters.method||"GET",body:requestParameters.body,credentials:requestParameters.credentials,headers:requestParameters.headers,cache:requestParameters.cache,referrer:getReferrer(),signal:abortController.signal});if(requestParameters.type==="json"){request.headers.set("Accept","application/json")}const response=yield fetch(request);if(!response.ok){const body=yield response.blob();throw new AJAXError(response.status,response.statusText,requestParameters.url,body)}const parsePromise=requestParameters.type==="arrayBuffer"||requestParameters.type==="image"?response.arrayBuffer():requestParameters.type==="json"?response.json():response.text();const result=yield parsePromise;if(abortController.signal.aborted){throw createAbortError()}return{data:result,cacheControl:response.headers.get("Cache-Control"),expires:response.headers.get("Expires")}}))}function makeXMLHttpRequest(requestParameters,abortController){return new Promise(((resolve,reject)=>{const xhr=new XMLHttpRequest;xhr.open(requestParameters.method||"GET",requestParameters.url,true);if(requestParameters.type==="arrayBuffer"||requestParameters.type==="image"){xhr.responseType="arraybuffer"}for(const k in requestParameters.headers){xhr.setRequestHeader(k,requestParameters.headers[k])}if(requestParameters.type==="json"){xhr.responseType="text";xhr.setRequestHeader("Accept","application/json")}xhr.withCredentials=requestParameters.credentials==="include";xhr.onerror=()=>{reject(new Error(xhr.statusText))};xhr.onload=()=>{if(abortController.signal.aborted){return}if((xhr.status>=200&&xhr.status<300||xhr.status===0)&&xhr.response!==null){let data=xhr.response;if(requestParameters.type==="json"){try{data=JSON.parse(xhr.response)}catch(err){reject(err);return}}resolve({data:data,cacheControl:xhr.getResponseHeader("Cache-Control"),expires:xhr.getResponseHeader("Expires")})}else{const body=new Blob([xhr.response],{type:xhr.getResponseHeader("Content-Type")});reject(new AJAXError(xhr.status,xhr.statusText,requestParameters.url,body))}};abortController.signal.addEventListener("abort",(()=>{xhr.abort();reject(createAbortError())}));xhr.send(requestParameters.body)}))}const makeRequest=function(requestParameters,abortController){if(/:\/\//.test(requestParameters.url)&&!/^https?:|^file:/.test(requestParameters.url)){const protocolLoadFn=getProtocol(requestParameters.url);if(protocolLoadFn){return protocolLoadFn(requestParameters,abortController)}if(isWorker(self)&&self.worker&&self.worker.actor){return self.worker.actor.sendAsync({type:"getResource",data:requestParameters,targetMapId:GLOBAL_DISPATCHER_ID},abortController)}}if(!isFileURL(requestParameters.url)){if(fetch&&Request&&AbortController&&Object.prototype.hasOwnProperty.call(Request.prototype,"signal")){return makeFetchRequest(requestParameters,abortController)}if(isWorker(self)&&self.worker&&self.worker.actor){return self.worker.actor.sendAsync({type:"getResource",data:requestParameters,mustQueue:true,targetMapId:GLOBAL_DISPATCHER_ID},abortController)}}return makeXMLHttpRequest(requestParameters,abortController)};const getJSON=(requestParameters,abortController)=>makeRequest(extend(requestParameters,{type:"json"}),abortController);const getArrayBuffer=(requestParameters,abortController)=>makeRequest(extend(requestParameters,{type:"arrayBuffer"}),abortController);function sameOrigin(inComingUrl){if(!inComingUrl||inComingUrl.indexOf("://")<=0||inComingUrl.indexOf("data:image/")===0||inComingUrl.indexOf("blob:")===0){return true}const urlObj=new URL(inComingUrl);const locationObj=window.location;return urlObj.protocol===locationObj.protocol&&urlObj.host===locationObj.host}const getVideo=urls=>{const video=window.document.createElement("video");video.muted=true;return new Promise((resolve=>{video.onloadstart=()=>{resolve(video)};for(const url of urls){const s=window.document.createElement("source");if(!sameOrigin(url)){video.crossOrigin="Anonymous"}s.src=url;video.appendChild(s)}}))};function _addEventListener(type,listener,listenerList){const listenerExists=listenerList[type]&&listenerList[type].indexOf(listener)!==-1;if(!listenerExists){listenerList[type]=listenerList[type]||[];listenerList[type].push(listener)}}function _removeEventListener(type,listener,listenerList){if(listenerList&&listenerList[type]){const index=listenerList[type].indexOf(listener);if(index!==-1){listenerList[type].splice(index,1)}}}class Event{constructor(type,data={}){extend(this,data);this.type=type}}class ErrorEvent extends Event{constructor(error,data={}){super("error",extend({error:error},data))}}class Evented{on(type,listener){this._listeners=this._listeners||{};_addEventListener(type,listener,this._listeners);return this}off(type,listener){_removeEventListener(type,listener,this._listeners);_removeEventListener(type,listener,this._oneTimeListeners);return this}once(type,listener){if(!listener){return new Promise((resolve=>this.once(type,resolve)))}this._oneTimeListeners=this._oneTimeListeners||{};_addEventListener(type,listener,this._oneTimeListeners);return this}fire(event,properties){if(typeof event==="string"){event=new Event(event,properties||{})}const type=event.type;if(this.listens(type)){event.target=this;const listeners=this._listeners&&this._listeners[type]?this._listeners[type].slice():[];for(const listener of listeners){listener.call(this,event)}const oneTimeListeners=this._oneTimeListeners&&this._oneTimeListeners[type]?this._oneTimeListeners[type].slice():[];for(const listener of oneTimeListeners){_removeEventListener(type,listener,this._oneTimeListeners);listener.call(this,event)}const parent=this._eventedParent;if(parent){extend(event,typeof this._eventedParentData==="function"?this._eventedParentData():this._eventedParentData);parent.fire(event)}}else if(event instanceof ErrorEvent){console.error(event.error)}return this}listens(type){return this._listeners&&this._listeners[type]&&this._listeners[type].length>0||this._oneTimeListeners&&this._oneTimeListeners[type]&&this._oneTimeListeners[type].length>0||this._eventedParent&&this._eventedParent.listens(type)}setEventedParent(parent,data){this._eventedParent=parent;this._eventedParentData=data;return this}}var $version=8;var $root={version:{required:true,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},light:{type:"light"},sky:{type:"sky"},terrain:{type:"terrain"},sources:{required:true,type:"sources"},sprite:{type:"sprite"},glyphs:{type:"string"},transition:{type:"transition"},layers:{required:true,type:"array",value:"layer"}};var sources={"*":{type:"source"}};var source=["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"];var source_vector={type:{required:true,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},volatile:{type:"boolean",default:false},"*":{type:"*"}};var source_raster={type:{required:true,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},volatile:{type:"boolean",default:false},"*":{type:"*"}};var source_raster_dem={type:{required:true,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{},custom:{}},default:"mapbox"},redFactor:{type:"number",default:1},blueFactor:{type:"number",default:1},greenFactor:{type:"number",default:1},baseShift:{type:"number",default:0},volatile:{type:"boolean",default:false},"*":{type:"*"}};var source_geojson={type:{required:true,type:"enum",values:{geojson:{}}},data:{required:true,type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},filter:{type:"*"},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:false},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterMinPoints:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:false},generateId:{type:"boolean",default:false},promoteId:{type:"promoteId"}};var source_video={type:{required:true,type:"enum",values:{video:{}}},urls:{required:true,type:"array",value:"string"},coordinates:{required:true,type:"array",length:4,value:{type:"array",length:2,value:"number"}}};var source_image={type:{required:true,type:"enum",values:{image:{}}},url:{required:true,type:"string"},coordinates:{required:true,type:"array",length:4,value:{type:"array",length:2,value:"number"}}};var layer={id:{type:"string",required:true},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},background:{}},required:true},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}};var layout$7=["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_background"];var layout_background={visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}};var layout_fill={"fill-sort-key":{type:"number",expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}};var layout_circle={"circle-sort-key":{type:"number",expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}};var layout_heatmap={visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}};var layout_line={"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"line-sort-key":{type:"number",expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}};var layout_symbol={"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:false,expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:false,requires:["icon-image",{"!":"icon-overlap"}],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["icon-image"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:false,requires:["icon-image"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:false,requires:["icon-image","text-field"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:true,expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"padding",default:[2],units:"pixels",requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-keep-upright":{type:"boolean",default:false,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},"viewport-glyph":{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:true,expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:true,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-variable-anchor-offset":{type:"variableAnchorOffsetCollection",requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:true,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:false,requires:["text-field",{"!":"text-overlap"}],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["text-field"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:false,requires:["text-field"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:false,requires:["text-field","icon-image"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}};var layout_raster={visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}};var layout_hillshade={visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}};var filter={type:"array",value:"*"};var filter_operator={type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{},within:{}}};var geometry_type={type:"enum",values:{Point:{},LineString:{},Polygon:{}}};var function_stop={type:"array",minimum:0,maximum:24,value:["number","color"],length:2};var expression$1={type:"array",value:"*",minimum:1};var light={anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:false,expression:{interpolated:false,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:true,expression:{interpolated:true,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:true,parameters:["zoom"]},transition:true},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:true,parameters:["zoom"]},transition:true}};var sky={"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:true,parameters:["zoom"]},transition:true},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:true,parameters:["zoom"]},transition:true},"fog-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:true,parameters:["zoom"]},transition:true},"horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:true,parameters:["zoom"]},transition:true}};var terrain={source:{type:"string",required:true},exaggeration:{type:"number",minimum:0,default:1}};var paint$9=["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_background"];var paint_fill={"fill-antialias":{type:"boolean",default:true,expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:true,requires:[{"!":"fill-pattern"}],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:true,requires:[{"!":"fill-pattern"},{"fill-antialias":true}],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:true,expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}};var paint_line={"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:true,requires:[{"!":"line-pattern"}],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:true,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:false,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:true,expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:false,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:true}}],expression:{interpolated:true,parameters:["line-progress"]},"property-type":"color-ramp"}};var paint_circle={"circle-radius":{type:"number",default:5,minimum:0,transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}};var paint_heatmap={"heatmap-radius":{type:"number",default:30,minimum:1,transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:false,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:false,expression:{interpolated:true,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"}};var paint_symbol={"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:true,requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:true,requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:true,units:"pixels",requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:true,units:"pixels",requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:true,units:"pixels",requires:["icon-image"],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:true,overridable:true,requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:true,requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:true,units:"pixels",requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:true,units:"pixels",requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:true,units:"pixels",requires:["text-field"],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"}};var paint_raster={"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:true,units:"degrees",expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:false,units:"milliseconds",expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"}};var paint_hillshade={"hillshade-illumination-direction":{type:"number",default:335,minimum:0,maximum:359,transition:false,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"color",default:"#000000",transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"color",default:"#FFFFFF",transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"}};var paint_background={"background-color":{type:"color",default:"#000000",transition:true,requires:[{"!":"background-pattern"}],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:true,expression:{interpolated:false,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"}};var transition={duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}};var promoteId={"*":{type:"string"}};var v8Spec={$version:$version,$root:$root,sources:sources,source:source,source_vector:source_vector,source_raster:source_raster,source_raster_dem:source_raster_dem,source_geojson:source_geojson,source_video:source_video,source_image:source_image,layer:layer,layout:layout$7,layout_background:layout_background,layout_fill:layout_fill,layout_circle:layout_circle,layout_heatmap:layout_heatmap,"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_line:layout_line,layout_symbol:layout_symbol,layout_raster:layout_raster,layout_hillshade:layout_hillshade,filter:filter,filter_operator:filter_operator,geometry_type:geometry_type,function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:false}},function_stop:function_stop,expression:expression$1,light:light,sky:sky,terrain:terrain,paint:paint$9,paint_fill:paint_fill,"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:true,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:true,expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:true,requires:["fill-extrusion-height"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:true,transition:false,expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:paint_line,paint_circle:paint_circle,paint_heatmap:paint_heatmap,paint_symbol:paint_symbol,paint_raster:paint_raster,paint_hillshade:paint_hillshade,paint_background:paint_background,transition:transition,"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:promoteId};const refProperties=["type","source","source-layer","minzoom","maxzoom","filter","layout"];function deref(layer,parent){const result={};for(const k in layer){if(k!=="ref"){result[k]=layer[k]}}refProperties.forEach((k=>{if(k in parent){result[k]=parent[k]}}));return result}function derefLayers(layers){layers=layers.slice();const map=Object.create(null);for(let i=0;i{if("source"in layer&&sourcesRemoved[layer.source]){commands.push({command:"removeLayer",args:[layer.id]})}else{beforeLayers.push(layer)}}))}commands=commands.concat(removeOrAddSourceCommands);diffLayers(beforeLayers,after.layers,commands)}catch(e){console.warn("Unable to compute style diff:",e);commands=[{command:"setStyle",args:[after]}]}return commands}class ValidationError{constructor(key,value,message,identifier){this.message=(key?`${key}: `:"")+message;if(identifier)this.identifier=identifier;if(value!==null&&value!==undefined&&value.__line__){this.line=value.__line__}}}class ParsingError{constructor(error){this.error=error;this.message=error.message;const match=error.message.match(/line (\d+)/);this.line=match?parseInt(match[1],10):0}}function extendBy(output,...inputs){for(const input of inputs){for(const k in input){output[k]=input[k]}}return output}class ExpressionParsingError extends Error{constructor(key,message){super(message);this.message=message;this.key=key}}class Scope{constructor(parent,bindings=[]){this.parent=parent;this.bindings={};for(const[name,expression]of bindings){this.bindings[name]=expression}}concat(bindings){return new Scope(this,bindings)}get(name){if(this.bindings[name]){return this.bindings[name]}if(this.parent){return this.parent.get(name)}throw new Error(`${name} not found in scope.`)}has(name){if(this.bindings[name])return true;return this.parent?this.parent.has(name):false}}const NullType={kind:"null"};const NumberType={kind:"number"};const StringType={kind:"string"};const BooleanType={kind:"boolean"};const ColorType={kind:"color"};const ObjectType={kind:"object"};const ValueType={kind:"value"};const ErrorType={kind:"error"};const CollatorType={kind:"collator"};const FormattedType={kind:"formatted"};const PaddingType={kind:"padding"};const ResolvedImageType={kind:"resolvedImage"};const VariableAnchorOffsetCollectionType={kind:"variableAnchorOffsetCollection"};function array$1(itemType,N){return{kind:"array",itemType:itemType,N:N}}function toString$1(type){if(type.kind==="array"){const itemType=toString$1(type.itemType);return typeof type.N==="number"?`array<${itemType}, ${type.N}>`:type.itemType.kind==="value"?"array":`array<${itemType}>`}else{return type.kind}}const valueMemberTypes=[NullType,NumberType,StringType,BooleanType,ColorType,FormattedType,ObjectType,array$1(ValueType),PaddingType,ResolvedImageType,VariableAnchorOffsetCollectionType];function checkSubtype(expected,t){if(t.kind==="error"){return null}else if(expected.kind==="array"){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}}else if(expected.kind===t.kind){return null}else if(expected.kind==="value"){for(const memberType of valueMemberTypes){if(!checkSubtype(memberType,t)){return null}}}return`Expected ${toString$1(expected)} but found ${toString$1(t)} instead.`}function isValidType(provided,allowedTypes){return allowedTypes.some((t=>t.kind===provided.kind))}function isValidNativeType(provided,allowedTypes){return allowedTypes.some((t=>{if(t==="null"){return provided===null}else if(t==="array"){return Array.isArray(provided)}else if(t==="object"){return provided&&!Array.isArray(provided)&&typeof provided==="object"}else{return t===typeof provided}}))}function verifyType(provided,sample){if(provided.kind==="array"&&sample.kind==="array"){return provided.itemType.kind===sample.itemType.kind&&typeof provided.N==="number"}return provided.kind===sample.kind}const Xn=.96422,Yn=1,Zn=.82521,t0=4/29,t1=6/29,t2=3*t1*t1,t3=t1*t1*t1,deg2rad=Math.PI/180,rad2deg=180/Math.PI;function constrainAngle(angle){angle=angle%360;if(angle<0){angle+=360}return angle}function rgbToLab([r,g,b,alpha]){r=rgb2xyz(r);g=rgb2xyz(g);b=rgb2xyz(b);let x,z;const y=xyz2lab((.2225045*r+.7168786*g+.0606169*b)/Yn);if(r===g&&g===b){x=z=y}else{x=xyz2lab((.4360747*r+.3850649*g+.1430804*b)/Xn);z=xyz2lab((.0139322*r+.0971045*g+.7141733*b)/Zn)}const l=116*y-16;return[l<0?0:l,500*(x-y),200*(y-z),alpha]}function rgb2xyz(x){return x<=.04045?x/12.92:Math.pow((x+.055)/1.055,2.4)}function xyz2lab(t){return t>t3?Math.pow(t,1/3):t/t2+t0}function labToRgb([l,a,b,alpha]){let y=(l+16)/116,x=isNaN(a)?y:y+a/500,z=isNaN(b)?y:y-b/200;y=Yn*lab2xyz(y);x=Xn*lab2xyz(x);z=Zn*lab2xyz(z);return[xyz2rgb(3.1338561*x-1.6168667*y-.4906146*z),xyz2rgb(-.9787684*x+1.9161415*y+.033454*z),xyz2rgb(.0719453*x-.2289914*y+1.4052427*z),alpha]}function xyz2rgb(x){x=x<=.00304?12.92*x:1.055*Math.pow(x,1/2.4)-.055;return x<0?0:x>1?1:x}function lab2xyz(t){return t>t1?t*t*t:t2*(t-t0)}function rgbToHcl(rgbColor){const[l,a,b,alpha]=rgbToLab(rgbColor);const c=Math.sqrt(a*a+b*b);const h=Math.round(c*1e4)?constrainAngle(Math.atan2(b,a)*rad2deg):NaN;return[h,c,l,alpha]}function hclToRgb([h,c,l,alpha]){h=isNaN(h)?0:h*deg2rad;return labToRgb([l,Math.cos(h)*c,Math.sin(h)*c,alpha])}function hslToRgb([h,s,l,alpha]){h=constrainAngle(h);s/=100;l/=100;function f(n){const k=(n+h/30)%12;const a=s*Math.min(l,1-l);return l-a*Math.max(-1,Math.min(k-3,9-k,1))}return[f(0),f(8),f(4),alpha]}function parseCssColor(input){input=input.toLowerCase().trim();if(input==="transparent"){return[0,0,0,0]}const namedColorsMatch=namedColors[input];if(namedColorsMatch){const[r,g,b]=namedColorsMatch;return[r/255,g/255,b/255,1]}if(input.startsWith("#")){const hexRegexp=/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/;if(hexRegexp.test(input)){const step=input.length<6?1:2;let i=1;return[parseHex(input.slice(i,i+=step)),parseHex(input.slice(i,i+=step)),parseHex(input.slice(i,i+=step)),parseHex(input.slice(i,i+step)||"ff")]}}if(input.startsWith("rgb")){const rgbRegExp=/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/;const rgbMatch=input.match(rgbRegExp);if(rgbMatch){const[_,r,rp,f1,g,gp,f2,b,bp,f3,a,ap]=rgbMatch;const argFormat=[f1||" ",f2||" ",f3].join("");if(argFormat===" "||argFormat===" /"||argFormat===",,"||argFormat===",,,"){const valFormat=[rp,gp,bp].join("");const maxValue=valFormat==="%%%"?100:valFormat===""?255:0;if(maxValue){const rgba=[clamp(+r/maxValue,0,1),clamp(+g/maxValue,0,1),clamp(+b/maxValue,0,1),a?parseAlpha(+a,ap):1];if(validateNumbers(rgba)){return rgba}}}return}}const hslRegExp=/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/;const hslMatch=input.match(hslRegExp);if(hslMatch){const[_,h,f1,s,f2,l,f3,a,ap]=hslMatch;const argFormat=[f1||" ",f2||" ",f3].join("");if(argFormat===" "||argFormat===" /"||argFormat===",,"||argFormat===",,,"){const hsla=[+h,clamp(+s,0,100),clamp(+l,0,100),a?parseAlpha(+a,ap):1];if(validateNumbers(hsla)){return hslToRgb(hsla)}}}}function parseHex(hex){return parseInt(hex.padEnd(2,hex),16)/255}function parseAlpha(a,asPercentage){return clamp(asPercentage?a/100:a,0,1)}function clamp(n,min,max){return Math.min(Math.max(min,n),max)}function validateNumbers(array){return!array.some(Number.isNaN)}const namedColors={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};class Color{constructor(r,g,b,alpha=1,premultiplied=true){this.r=r;this.g=g;this.b=b;this.a=alpha;if(!premultiplied){this.r*=alpha;this.g*=alpha;this.b*=alpha;if(!alpha){this.overwriteGetter("rgb",[r,g,b,alpha])}}}static parse(input){if(input instanceof Color){return input}if(typeof input!=="string"){return}const rgba=parseCssColor(input);if(rgba){return new Color(...rgba,false)}}get rgb(){const{r:r,g:g,b:b,a:a}=this;const f=a||Infinity;return this.overwriteGetter("rgb",[r/f,g/f,b/f,a])}get hcl(){return this.overwriteGetter("hcl",rgbToHcl(this.rgb))}get lab(){return this.overwriteGetter("lab",rgbToLab(this.rgb))}overwriteGetter(getterKey,lazyValue){Object.defineProperty(this,getterKey,{value:lazyValue});return lazyValue}toString(){const[r,g,b,a]=this.rgb;return`rgba(${[r,g,b].map((n=>Math.round(n*255))).join(",")},${a})`}}Color.black=new Color(0,0,0,1);Color.white=new Color(1,1,1,1);Color.transparent=new Color(0,0,0,0);Color.red=new Color(1,0,0,1);class Collator{constructor(caseSensitive,diacriticSensitive,locale){if(caseSensitive)this.sensitivity=diacriticSensitive?"variant":"case";else this.sensitivity=diacriticSensitive?"accent":"base";this.locale=locale;this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(lhs,rhs){return this.collator.compare(lhs,rhs)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class FormattedSection{constructor(text,image,scale,fontStack,textColor){this.text=text;this.image=image;this.scale=scale;this.fontStack=fontStack;this.textColor=textColor}}class Formatted{constructor(sections){this.sections=sections}static fromString(unformatted){return new Formatted([new FormattedSection(unformatted,null,null,null,null)])}isEmpty(){if(this.sections.length===0)return true;return!this.sections.some((section=>section.text.length!==0||section.image&§ion.image.name.length!==0))}static factory(text){if(text instanceof Formatted){return text}else{return Formatted.fromString(text)}}toString(){if(this.sections.length===0)return"";return this.sections.map((section=>section.text)).join("")}}class Padding{constructor(values){this.values=values.slice()}static parse(input){if(input instanceof Padding){return input}if(typeof input==="number"){return new Padding([input,input,input,input])}if(!Array.isArray(input)){return undefined}if(input.length<1||input.length>4){return undefined}for(const val of input){if(typeof val!=="number"){return undefined}}switch(input.length){case 1:input=[input[0],input[0],input[0],input[0]];break;case 2:input=[input[0],input[1],input[0],input[1]];break;case 3:input=[input[0],input[1],input[2],input[1]];break}return new Padding(input)}toString(){return JSON.stringify(this.values)}}const anchors=new Set(["center","left","right","top","bottom","top-left","top-right","bottom-left","bottom-right"]);class VariableAnchorOffsetCollection{constructor(values){this.values=values.slice()}static parse(input){if(input instanceof VariableAnchorOffsetCollection){return input}if(!Array.isArray(input)||input.length<1||input.length%2!==0){return undefined}for(let i=0;i=0&&r<=255&&typeof g==="number"&&g>=0&&g<=255&&typeof b==="number"&&b>=0&&b<=255)){const value=typeof a==="number"?[r,g,b,a]:[r,g,b];return`Invalid rgba value [${value.join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}if(!(typeof a==="undefined"||typeof a==="number"&&a>=0&&a<=1)){return`Invalid rgba value [${[r,g,b,a].join(", ")}]: 'a' must be between 0 and 1.`}return null}function isValue(mixed){if(mixed===null||typeof mixed==="string"||typeof mixed==="boolean"||typeof mixed==="number"||mixed instanceof Color||mixed instanceof Collator||mixed instanceof Formatted||mixed instanceof Padding||mixed instanceof VariableAnchorOffsetCollection||mixed instanceof ResolvedImage){return true}else if(Array.isArray(mixed)){for(const item of mixed){if(!isValue(item)){return false}}return true}else if(typeof mixed==="object"){for(const key in mixed){if(!isValue(mixed[key])){return false}}return true}else{return false}}function typeOf(value){if(value===null){return NullType}else if(typeof value==="string"){return StringType}else if(typeof value==="boolean"){return BooleanType}else if(typeof value==="number"){return NumberType}else if(value instanceof Color){return ColorType}else if(value instanceof Collator){return CollatorType}else if(value instanceof Formatted){return FormattedType}else if(value instanceof Padding){return PaddingType}else if(value instanceof VariableAnchorOffsetCollection){return VariableAnchorOffsetCollectionType}else if(value instanceof ResolvedImage){return ResolvedImageType}else if(Array.isArray(value)){const length=value.length;let itemType;for(const item of value){const t=typeOf(item);if(!itemType){itemType=t}else if(itemType===t){continue}else{itemType=ValueType;break}}return array$1(itemType||ValueType,length)}else{return ObjectType}}function toString(value){const type=typeof value;if(value===null){return""}else if(type==="string"||type==="number"||type==="boolean"){return String(value)}else if(value instanceof Color||value instanceof Formatted||value instanceof Padding||value instanceof VariableAnchorOffsetCollection||value instanceof ResolvedImage){return value.toString()}else{return JSON.stringify(value)}}class Literal{constructor(type,value){this.type=type;this.value=value}static parse(args,context){if(args.length!==2)return context.error(`'literal' expression requires exactly one argument, but found ${args.length-1} instead.`);if(!isValue(args[1]))return context.error("invalid value");const value=args[1];let type=typeOf(value);const expected=context.expectedType;if(type.kind==="array"&&type.N===0&&expected&&expected.kind==="array"&&(typeof expected.N!=="number"||expected.N===0)){type=expected}return new Literal(type,value)}evaluate(){return this.value}eachChild(){}outputDefined(){return true}}class RuntimeError{constructor(message){this.name="ExpressionEvaluationError";this.message=message}toJSON(){return this.message}}const types$1={string:StringType,number:NumberType,boolean:BooleanType,object:ObjectType};class Assertion{constructor(type,args){this.type=type;this.args=args}static parse(args,context){if(args.length<2)return context.error("Expected at least one argument.");let i=1;let type;const name=args[0];if(name==="array"){let itemType;if(args.length>2){const type=args[1];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);itemType=types$1[type];i++}else{itemType=ValueType}let N;if(args.length>3){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)}N=args[2];i++}type=array$1(itemType,N)}else{if(!types$1[name])throw new Error(`Types doesn't contain name = ${name}`);type=types$1[name]}const parsed=[];for(;iarg.outputDefined()))}}const types={"to-boolean":BooleanType,"to-color":ColorType,"to-number":NumberType,"to-string":StringType};class Coercion{constructor(type,args){this.type=type;this.args=args}static parse(args,context){if(args.length<2)return context.error("Expected at least one argument.");const name=args[0];if(!types[name])throw new Error(`Can't parse ${name} as it is not part of the known types`);if((name==="to-boolean"||name==="to-string")&&args.length!==2)return context.error("Expected one argument.");const type=types[name];const parsed=[];for(let i=1;i4){error=`Invalid rbga value ${JSON.stringify(input)}: expected an array containing either three or four numeric values.`}else{error=validateRGBA(input[0],input[1],input[2],input[3])}if(!error){return new Color(input[0]/255,input[1]/255,input[2]/255,input[3])}}}throw new RuntimeError(error||`Could not parse color from value '${typeof input==="string"?input:JSON.stringify(input)}'`)}case"padding":{let input;for(const arg of this.args){input=arg.evaluate(ctx);const pad=Padding.parse(input);if(pad){return pad}}throw new RuntimeError(`Could not parse padding from value '${typeof input==="string"?input:JSON.stringify(input)}'`)}case"variableAnchorOffsetCollection":{let input;for(const arg of this.args){input=arg.evaluate(ctx);const coll=VariableAnchorOffsetCollection.parse(input);if(coll){return coll}}throw new RuntimeError(`Could not parse variableAnchorOffsetCollection from value '${typeof input==="string"?input:JSON.stringify(input)}'`)}case"number":{let value=null;for(const arg of this.args){value=arg.evaluate(ctx);if(value===null)return 0;const num=Number(value);if(isNaN(num))continue;return num}throw new RuntimeError(`Could not convert ${JSON.stringify(value)} to number.`)}case"formatted":return Formatted.fromString(toString(this.args[0].evaluate(ctx)));case"resolvedImage":return ResolvedImage.fromString(toString(this.args[0].evaluate(ctx)));default:return toString(this.args[0].evaluate(ctx))}}eachChild(fn){this.args.forEach(fn)}outputDefined(){return this.args.every((arg=>arg.outputDefined()))}}const geometryTypes=["Unknown","Point","LineString","Polygon"];class EvaluationContext{constructor(){this.globals=null;this.feature=null;this.featureState=null;this.formattedSection=null;this._parseColorCache={};this.availableImages=null;this.canonical=null}id(){return this.feature&&"id"in this.feature?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type==="number"?geometryTypes[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}parseColor(input){let cached=this._parseColorCache[input];if(!cached){cached=this._parseColorCache[input]=Color.parse(input)}return cached}}class ParsingContext{constructor(registry,isConstantFunc,path=[],expectedType,scope=new Scope,errors=[]){this.registry=registry;this.path=path;this.key=path.map((part=>`[${part}]`)).join("");this.scope=scope;this.errors=errors;this.expectedType=expectedType;this._isConstant=isConstantFunc}parse(expr,index,expectedType,bindings,options={}){if(index){return this.concat(index,expectedType,bindings)._parse(expr,options)}return this._parse(expr,options)}_parse(expr,options){if(expr===null||typeof expr==="string"||typeof expr==="boolean"||typeof expr==="number"){expr=["literal",expr]}function annotate(parsed,type,typeAnnotation){if(typeAnnotation==="assert"){return new Assertion(type,[parsed])}else if(typeAnnotation==="coerce"){return new Coercion(type,[parsed])}else{return parsed}}if(Array.isArray(expr)){if(expr.length===0){return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].')}const op=expr[0];if(typeof op!=="string"){this.error(`Expression name must be a string, but found ${typeof op} instead. If you wanted a literal array, use ["literal", [...]].`,0);return null}const Expr=this.registry[op];if(Expr){let parsed=Expr.parse(expr,this);if(!parsed)return null;if(this.expectedType){const expected=this.expectedType;const actual=parsed.type;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")}else if((expected.kind==="color"||expected.kind==="formatted"||expected.kind==="resolvedImage")&&(actual.kind==="value"||actual.kind==="string")){parsed=annotate(parsed,expected,options.typeAnnotation||"coerce")}else if(expected.kind==="padding"&&(actual.kind==="value"||actual.kind==="number"||actual.kind==="array")){parsed=annotate(parsed,expected,options.typeAnnotation||"coerce")}else if(expected.kind==="variableAnchorOffsetCollection"&&(actual.kind==="value"||actual.kind==="array")){parsed=annotate(parsed,expected,options.typeAnnotation||"coerce")}else if(this.checkSubtype(expected,actual)){return null}}if(!(parsed instanceof Literal)&&parsed.type.kind!=="resolvedImage"&&this._isConstant(parsed)){const ec=new EvaluationContext;try{parsed=new Literal(parsed.type,parsed.evaluate(ec))}catch(e){this.error(e.message);return null}}return parsed}return this.error(`Unknown expression "${op}". If you wanted a literal array, use ["literal", [...]].`,0)}else if(typeof expr==="undefined"){return this.error("'undefined' value invalid. Use null instead.")}else if(typeof expr==="object"){return this.error('Bare objects invalid. Use ["literal", {...}] instead.')}else{return this.error(`Expected an array, but found ${typeof expr} instead.`)}}concat(index,expectedType,bindings){const path=typeof index==="number"?this.path.concat(index):this.path;const scope=bindings?this.scope.concat(bindings):this.scope;return new ParsingContext(this.registry,this._isConstant,path,expectedType||null,scope,this.errors)}error(error,...keys){const key=`${this.key}${keys.map((k=>`[${k}]`)).join("")}`;this.errors.push(new ExpressionParsingError(key,error))}checkSubtype(expected,t){const error=checkSubtype(expected,t);if(error)this.error(error);return error}}class CollatorExpression{constructor(caseSensitive,diacriticSensitive,locale){this.type=CollatorType;this.locale=locale;this.caseSensitive=caseSensitive;this.diacriticSensitive=diacriticSensitive}static parse(args,context){if(args.length!==2)return context.error("Expected one argument.");const options=args[1];if(typeof options!=="object"||Array.isArray(options))return context.error("Collator options argument must be an object.");const caseSensitive=context.parse(options["case-sensitive"]===undefined?false:options["case-sensitive"],1,BooleanType);if(!caseSensitive)return null;const diacriticSensitive=context.parse(options["diacritic-sensitive"]===undefined?false:options["diacritic-sensitive"],1,BooleanType);if(!diacriticSensitive)return null;let locale=null;if(options["locale"]){locale=context.parse(options["locale"],1,StringType);if(!locale)return null}return new CollatorExpression(caseSensitive,diacriticSensitive,locale)}evaluate(ctx){return new Collator(this.caseSensitive.evaluate(ctx),this.diacriticSensitive.evaluate(ctx),this.locale?this.locale.evaluate(ctx):null)}eachChild(fn){fn(this.caseSensitive);fn(this.diacriticSensitive);if(this.locale){fn(this.locale)}}outputDefined(){return false}}const EXTENT$1=8192;function updateBBox(bbox,coord){bbox[0]=Math.min(bbox[0],coord[0]);bbox[1]=Math.min(bbox[1],coord[1]);bbox[2]=Math.max(bbox[2],coord[0]);bbox[3]=Math.max(bbox[3],coord[1])}function mercatorXfromLng$1(lng){return(180+lng)/360}function mercatorYfromLat$1(lat){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+lat*Math.PI/360)))/360}function boxWithinBox(bbox1,bbox2){if(bbox1[0]<=bbox2[0])return false;if(bbox1[2]>=bbox2[2])return false;if(bbox1[1]<=bbox2[1])return false;if(bbox1[3]>=bbox2[3])return false;return true}function getTileCoordinates(p,canonical){const x=mercatorXfromLng$1(p[0]);const y=mercatorYfromLat$1(p[1]);const tilesAtZoom=Math.pow(2,canonical.z);return[Math.round(x*tilesAtZoom*EXTENT$1),Math.round(y*tilesAtZoom*EXTENT$1)]}function onBoundary(p,p1,p2){const x1=p[0]-p1[0];const y1=p[1]-p1[1];const x2=p[0]-p2[0];const y2=p[1]-p2[1];return x1*y2-x2*y1===0&&x1*x2<=0&&y1*y2<=0}function rayIntersect(p,p1,p2){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]}function pointWithinPolygon(point,rings){let inside=false;for(let i=0,len=rings.length;i0&&det2<0||det1<0&&det2>0)return true;return false}function lineIntersectLine(a,b,c,d){const vectorP=[b[0]-a[0],b[1]-a[1]];const vectorQ=[d[0]-c[0],d[1]-c[1]];if(perp(vectorQ,vectorP)===0)return false;if(twoSided(a,b,c,d)&&twoSided(c,d,a,b))return true;return false}function lineIntersectPolygon(p1,p2,polygon){for(const ring of polygon){for(let j=0;jpolyBBox[2]){const halfWorldSize=worldSize*.5;let shift=p[0]-polyBBox[0]>halfWorldSize?-worldSize:polyBBox[0]-p[0]>halfWorldSize?worldSize:0;if(shift===0){shift=p[0]-polyBBox[2]>halfWorldSize?-worldSize:polyBBox[2]-p[0]>halfWorldSize?worldSize:0}p[0]+=shift}updateBBox(bbox,p)}function resetBBox(bbox){bbox[0]=bbox[1]=Infinity;bbox[2]=bbox[3]=-Infinity}function getTilePoints(geometry,pointBBox,polyBBox,canonical){const worldSize=Math.pow(2,canonical.z)*EXTENT$1;const shifts=[canonical.x*EXTENT$1,canonical.y*EXTENT$1];const tilePoints=[];for(const points of geometry){for(const point of points){const p=[point.x+shifts[0],point.y+shifts[1]];updatePoint(p,pointBBox,polyBBox,worldSize);tilePoints.push(p)}}return tilePoints}function getTileLines(geometry,lineBBox,polyBBox,canonical){const worldSize=Math.pow(2,canonical.z)*EXTENT$1;const shifts=[canonical.x*EXTENT$1,canonical.y*EXTENT$1];const tileLines=[];for(const line of geometry){const tileLine=[];for(const point of line){const p=[point.x+shifts[0],point.y+shifts[1]];updateBBox(lineBBox,p);tileLine.push(p)}tileLines.push(tileLine)}if(lineBBox[2]-lineBBox[0]<=worldSize/2){resetBBox(lineBBox);for(const line of tileLines){for(const p of line){updatePoint(p,lineBBox,polyBBox,worldSize)}}}return tileLines}function pointsWithinPolygons(ctx,polygonGeometry){const pointBBox=[Infinity,Infinity,-Infinity,-Infinity];const polyBBox=[Infinity,Infinity,-Infinity,-Infinity];const canonical=ctx.canonicalID();if(polygonGeometry.type==="Polygon"){const tilePolygon=getTilePolygon(polygonGeometry.coordinates,polyBBox,canonical);const tilePoints=getTilePoints(ctx.geometry(),pointBBox,polyBBox,canonical);if(!boxWithinBox(pointBBox,polyBBox))return false;for(const point of tilePoints){if(!pointWithinPolygon(point,tilePolygon))return false}}if(polygonGeometry.type==="MultiPolygon"){const tilePolygons=getTilePolygons(polygonGeometry.coordinates,polyBBox,canonical);const tilePoints=getTilePoints(ctx.geometry(),pointBBox,polyBBox,canonical);if(!boxWithinBox(pointBBox,polyBBox))return false;for(const point of tilePoints){if(!pointWithinPolygons(point,tilePolygons))return false}}return true}function linesWithinPolygons(ctx,polygonGeometry){const lineBBox=[Infinity,Infinity,-Infinity,-Infinity];const polyBBox=[Infinity,Infinity,-Infinity,-Infinity];const canonical=ctx.canonicalID();if(polygonGeometry.type==="Polygon"){const tilePolygon=getTilePolygon(polygonGeometry.coordinates,polyBBox,canonical);const tileLines=getTileLines(ctx.geometry(),lineBBox,polyBBox,canonical);if(!boxWithinBox(lineBBox,polyBBox))return false;for(const line of tileLines){if(!lineStringWithinPolygon(line,tilePolygon))return false}}if(polygonGeometry.type==="MultiPolygon"){const tilePolygons=getTilePolygons(polygonGeometry.coordinates,polyBBox,canonical);const tileLines=getTileLines(ctx.geometry(),lineBBox,polyBBox,canonical);if(!boxWithinBox(lineBBox,polyBBox))return false;for(const line of tileLines){if(!lineStringWithinPolygons(line,tilePolygons))return false}}return true}class Within{constructor(geojson,geometries){this.type=BooleanType;this.geojson=geojson;this.geometries=geometries}static parse(args,context){if(args.length!==2)return context.error(`'within' expression requires exactly one argument, but found ${args.length-1} instead.`);if(isValue(args[1])){const geojson=args[1];if(geojson.type==="FeatureCollection"){const polygonsCoords=[];for(const polygon of geojson.features){const{type:type,coordinates:coordinates}=polygon.geometry;if(type==="Polygon"){polygonsCoords.push(coordinates)}if(type==="MultiPolygon"){polygonsCoords.push(...coordinates)}}if(polygonsCoords.length){const multipolygonWrapper={type:"MultiPolygon",coordinates:polygonsCoords};return new Within(geojson,multipolygonWrapper)}}else if(geojson.type==="Feature"){const type=geojson.geometry.type;if(type==="Polygon"||type==="MultiPolygon"){return new Within(geojson,geojson.geometry)}}else if(geojson.type==="Polygon"||geojson.type==="MultiPolygon"){return new Within(geojson,geojson)}}return context.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(ctx){if(ctx.geometry()!=null&&ctx.canonicalID()!=null){if(ctx.geometryType()==="Point"){return pointsWithinPolygons(ctx,this.geometries)}else if(ctx.geometryType()==="LineString"){return linesWithinPolygons(ctx,this.geometries)}}return false}eachChild(){}outputDefined(){return true}}class Var{constructor(name,boundExpression){this.type=boundExpression.type;this.name=name;this.boundExpression=boundExpression}static parse(args,context){if(args.length!==2||typeof args[1]!=="string")return context.error("'var' expression requires exactly one string literal argument.");const name=args[1];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)}return new Var(name,context.scope.get(name))}evaluate(ctx){return this.boundExpression.evaluate(ctx)}eachChild(){}outputDefined(){return false}}class CompoundExpression{constructor(name,type,evaluate,args){this.name=name;this.type=type;this._evaluate=evaluate;this.args=args}evaluate(ctx){return this._evaluate(ctx,this.args)}eachChild(fn){this.args.forEach(fn)}outputDefined(){return false}static parse(args,context){const op=args[0];const definition=CompoundExpression.definitions[op];if(!definition){return context.error(`Unknown expression "${op}". If you wanted a literal array, use ["literal", [...]].`,0)}const type=Array.isArray(definition)?definition[0]:definition.type;const availableOverloads=Array.isArray(definition)?[[definition[1],definition[2]]]:definition.overloads;const overloads=availableOverloads.filter((([signature])=>!Array.isArray(signature)||signature.length===args.length-1));let signatureContext=null;for(const[params,evaluate]of overloads){signatureContext=new ParsingContext(context.registry,isExpressionConstant,context.path,null,context.scope);const parsedArgs=[];let argParseFailed=false;for(let i=1;istringifySignature(params))).join(" | ");const actualTypes=[];for(let i=1;i{if(isTypeAnnotation){childrenConstant=childrenConstant&&isExpressionConstant(child)}else{childrenConstant=childrenConstant&&child instanceof Literal}}));if(!childrenConstant){return false}return isFeatureConstant(expression)&&isGlobalPropertyConstant(expression,["zoom","heatmap-density","line-progress","accumulated","is-supported-script"])}function isFeatureConstant(e){if(e instanceof CompoundExpression){if(e.name==="get"&&e.args.length===1){return false}else if(e.name==="feature-state"){return false}else if(e.name==="has"&&e.args.length===1){return false}else if(e.name==="properties"||e.name==="geometry-type"||e.name==="id"){return false}else if(/^filter-/.test(e.name)){return false}}if(e instanceof Within){return false}let result=true;e.eachChild((arg=>{if(result&&!isFeatureConstant(arg)){result=false}}));return result}function isStateConstant(e){if(e instanceof CompoundExpression){if(e.name==="feature-state"){return false}}let result=true;e.eachChild((arg=>{if(result&&!isStateConstant(arg)){result=false}}));return result}function isGlobalPropertyConstant(e,properties){if(e instanceof CompoundExpression&&properties.indexOf(e.name)>=0){return false}let result=true;e.eachChild((arg=>{if(result&&!isGlobalPropertyConstant(arg,properties)){result=false}}));return result}function findStopLessThanOrEqualTo(stops,input){const lastIndex=stops.length-1;let lowerIndex=0;let upperIndex=lastIndex;let currentIndex=0;let currentValue,nextValue;while(lowerIndex<=upperIndex){currentIndex=Math.floor((lowerIndex+upperIndex)/2);currentValue=stops[currentIndex];nextValue=stops[currentIndex+1];if(currentValue<=input){if(currentIndex===lastIndex||inputinput){upperIndex=currentIndex-1}else{throw new RuntimeError("Input is not a number.")}}return 0}class Step{constructor(type,input,stops){this.type=type;this.input=input;this.labels=[];this.outputs=[];for(const[label,expression]of stops){this.labels.push(label);this.outputs.push(expression)}}static parse(args,context){if(args.length-1<4){return context.error(`Expected at least 4 arguments, but found only ${args.length-1}.`)}if((args.length-1)%2!==0){return context.error("Expected an even number of arguments.")}const input=context.parse(args[1],1,NumberType);if(!input)return null;const stops=[];let outputType=null;if(context.expectedType&&context.expectedType.kind!=="value"){outputType=context.expectedType}for(let i=1;i=label){return context.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',labelKey)}const parsed=context.parse(value,valueKey,outputType);if(!parsed)return null;outputType=outputType||parsed.type;stops.push([label,parsed])}return new Step(outputType,input,stops)}evaluate(ctx){const labels=this.labels;const outputs=this.outputs;if(labels.length===1){return outputs[0].evaluate(ctx)}const value=this.input.evaluate(ctx);if(value<=labels[0]){return outputs[0].evaluate(ctx)}const stopCount=labels.length;if(value>=labels[stopCount-1]){return outputs[stopCount-1].evaluate(ctx)}const index=findStopLessThanOrEqualTo(labels,value);return outputs[index].evaluate(ctx)}eachChild(fn){fn(this.input);for(const expression of this.outputs){fn(expression)}}outputDefined(){return this.outputs.every((out=>out.outputDefined()))}}function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x["default"]:x}var unitbezier=UnitBezier;function UnitBezier(p1x,p1y,p2x,p2y){this.cx=3*p1x;this.bx=3*(p2x-p1x)-this.cx;this.ax=1-this.cx-this.bx;this.cy=3*p1y;this.by=3*(p2y-p1y)-this.cy;this.ay=1-this.cy-this.by;this.p1x=p1x;this.p1y=p1y;this.p2x=p2x;this.p2y=p2y}UnitBezier.prototype={sampleCurveX:function(t){return((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return(3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(x,epsilon){if(epsilon===undefined)epsilon=1e-6;if(x<0)return 0;if(x>1)return 1;var t=x;for(var i=0;i<8;i++){var x2=this.sampleCurveX(t)-x;if(Math.abs(x2)x2){t0=t}else{t1=t}t=(t1-t0)*.5+t0}return t},solve:function(x,epsilon){return this.sampleCurveY(this.solveCurveX(x,epsilon))}};var UnitBezier$1=getDefaultExportFromCjs(unitbezier);function isSupportedInterpolationColorSpace(colorSpace){return colorSpace==="rgb"||colorSpace==="hcl"||colorSpace==="lab"}const interpolateFactory=interpolationType=>{switch(interpolationType){case"number":return number;case"color":return color;case"array":return array;case"padding":return padding;case"variableAnchorOffsetCollection":return variableAnchorOffsetCollection}};function number(from,to,t){return from+t*(to-from)}function color(from,to,t,spaceKey="rgb"){switch(spaceKey){case"rgb":{const[r,g,b,alpha]=array(from.rgb,to.rgb,t);return new Color(r,g,b,alpha,false)}case"hcl":{const[hue0,chroma0,light0,alphaF]=from.hcl;const[hue1,chroma1,light1,alphaT]=to.hcl;let hue,chroma;if(!isNaN(hue0)&&!isNaN(hue1)){let dh=hue1-hue0;if(hue1>hue0&&dh>180){dh-=360}else if(hue1180){dh+=360}hue=hue0+t*dh}else if(!isNaN(hue0)){hue=hue0;if(light1===1||light1===0)chroma=chroma0}else if(!isNaN(hue1)){hue=hue1;if(light0===1||light0===0)chroma=chroma1}else{hue=NaN}const[r,g,b,alpha]=hclToRgb([hue,chroma!==null&&chroma!==void 0?chroma:number(chroma0,chroma1,t),number(light0,light1,t),number(alphaF,alphaT,t)]);return new Color(r,g,b,alpha,false)}case"lab":{const[r,g,b,alpha]=labToRgb(array(from.lab,to.lab,t));return new Color(r,g,b,alpha,false)}}}function array(from,to,t){return from.map(((d,i)=>number(d,to[i],t)))}function padding(from,to,t){return new Padding(array(from.values,to.values,t))}function variableAnchorOffsetCollection(from,to,t){const fromValues=from.values;const toValues=to.values;if(fromValues.length!==toValues.length){throw new RuntimeError(`Cannot interpolate values of different length. from: ${from.toString()}, to: ${to.toString()}`)}const output=[];for(let i=0;itypeof t!=="number"||t<0||t>1))){return context.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1)}interpolation={name:"cubic-bezier",controlPoints:controlPoints}}else{return context.error(`Unknown interpolation type ${String(interpolation[0])}`,1,0)}if(args.length-1<4){return context.error(`Expected at least 4 arguments, but found only ${args.length-1}.`)}if((args.length-1)%2!==0){return context.error("Expected an even number of arguments.")}input=context.parse(input,2,NumberType);if(!input)return null;const stops=[];let outputType=null;if(operator==="interpolate-hcl"||operator==="interpolate-lab"){outputType=ColorType}else if(context.expectedType&&context.expectedType.kind!=="value"){outputType=context.expectedType}for(let i=0;i=label){return context.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',labelKey)}const parsed=context.parse(value,valueKey,outputType);if(!parsed)return null;outputType=outputType||parsed.type;stops.push([label,parsed])}if(!verifyType(outputType,NumberType)&&!verifyType(outputType,ColorType)&&!verifyType(outputType,PaddingType)&&!verifyType(outputType,VariableAnchorOffsetCollectionType)&&!verifyType(outputType,array$1(NumberType))){return context.error(`Type ${toString$1(outputType)} is not interpolatable.`)}return new Interpolate(outputType,operator,interpolation,input,stops)}evaluate(ctx){const labels=this.labels;const outputs=this.outputs;if(labels.length===1){return outputs[0].evaluate(ctx)}const value=this.input.evaluate(ctx);if(value<=labels[0]){return outputs[0].evaluate(ctx)}const stopCount=labels.length;if(value>=labels[stopCount-1]){return outputs[stopCount-1].evaluate(ctx)}const index=findStopLessThanOrEqualTo(labels,value);const lower=labels[index];const upper=labels[index+1];const t=Interpolate.interpolationFactor(this.interpolation,value,lower,upper);const outputLower=outputs[index].evaluate(ctx);const outputUpper=outputs[index+1].evaluate(ctx);switch(this.operator){case"interpolate":return interpolate[this.type.kind](outputLower,outputUpper,t);case"interpolate-hcl":return interpolate.color(outputLower,outputUpper,t,"hcl");case"interpolate-lab":return interpolate.color(outputLower,outputUpper,t,"lab")}}eachChild(fn){fn(this.input);for(const expression of this.outputs){fn(expression)}}outputDefined(){return this.outputs.every((out=>out.outputDefined()))}}function exponentialInterpolation(input,base,lowerValue,upperValue){const difference=upperValue-lowerValue;const progress=input-lowerValue;if(difference===0){return 0}else if(base===1){return progress/difference}else{return(Math.pow(base,progress)-1)/(Math.pow(base,difference)-1)}}class Coalesce{constructor(type,args){this.type=type;this.args=args}static parse(args,context){if(args.length<2){return context.error("Expectected at least one argument.")}let outputType=null;const expectedType=context.expectedType;if(expectedType&&expectedType.kind!=="value"){outputType=expectedType}const parsedArgs=[];for(const arg of args.slice(1)){const parsed=context.parse(arg,1+parsedArgs.length,outputType,undefined,{typeAnnotation:"omit"});if(!parsed)return null;outputType=outputType||parsed.type;parsedArgs.push(parsed)}if(!outputType)throw new Error("No output type");const needsAnnotation=expectedType&&parsedArgs.some((arg=>checkSubtype(expectedType,arg.type)));return needsAnnotation?new Coalesce(ValueType,parsedArgs):new Coalesce(outputType,parsedArgs)}evaluate(ctx){let result=null;let argCount=0;let requestedImageName;for(const arg of this.args){argCount++;result=arg.evaluate(ctx);if(result&&result instanceof ResolvedImage&&!result.available){if(!requestedImageName){requestedImageName=result.name}result=null;if(argCount===this.args.length){result=requestedImageName}}if(result!==null)break}return result}eachChild(fn){this.args.forEach(fn)}outputDefined(){return this.args.every((arg=>arg.outputDefined()))}}class Let{constructor(bindings,result){this.type=result.type;this.bindings=[].concat(bindings);this.result=result}evaluate(ctx){return this.result.evaluate(ctx)}eachChild(fn){for(const binding of this.bindings){fn(binding[1])}fn(this.result)}static parse(args,context){if(args.length<4)return context.error(`Expected at least 3 arguments, but found ${args.length-1} instead.`);const bindings=[];for(let i=1;i=array.length){throw new RuntimeError(`Array index out of bounds: ${index} > ${array.length-1}.`)}if(index!==Math.floor(index)){throw new RuntimeError(`Array index must be an integer, but found ${index} instead.`)}return array[index]}eachChild(fn){fn(this.index);fn(this.input)}outputDefined(){return false}}class In{constructor(needle,haystack){this.type=BooleanType;this.needle=needle;this.haystack=haystack}static parse(args,context){if(args.length!==3){return context.error(`Expected 2 arguments, but found ${args.length-1} instead.`)}const needle=context.parse(args[1],1,ValueType);const haystack=context.parse(args[2],2,ValueType);if(!needle||!haystack)return null;if(!isValidType(needle.type,[BooleanType,StringType,NumberType,NullType,ValueType])){return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(needle.type)} instead`)}return new In(needle,haystack)}evaluate(ctx){const needle=this.needle.evaluate(ctx);const haystack=this.haystack.evaluate(ctx);if(!haystack)return false;if(!isValidNativeType(needle,["boolean","string","number","null"])){throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(typeOf(needle))} instead.`)}if(!isValidNativeType(haystack,["string","array"])){throw new RuntimeError(`Expected second argument to be of type array or string, but found ${toString$1(typeOf(haystack))} instead.`)}return haystack.indexOf(needle)>=0}eachChild(fn){fn(this.needle);fn(this.haystack)}outputDefined(){return true}}class IndexOf{constructor(needle,haystack,fromIndex){this.type=NumberType;this.needle=needle;this.haystack=haystack;this.fromIndex=fromIndex}static parse(args,context){if(args.length<=2||args.length>=5){return context.error(`Expected 3 or 4 arguments, but found ${args.length-1} instead.`)}const needle=context.parse(args[1],1,ValueType);const haystack=context.parse(args[2],2,ValueType);if(!needle||!haystack)return null;if(!isValidType(needle.type,[BooleanType,StringType,NumberType,NullType,ValueType])){return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(needle.type)} instead`)}if(args.length===4){const fromIndex=context.parse(args[3],3,NumberType);if(!fromIndex)return null;return new IndexOf(needle,haystack,fromIndex)}else{return new IndexOf(needle,haystack)}}evaluate(ctx){const needle=this.needle.evaluate(ctx);const haystack=this.haystack.evaluate(ctx);if(!isValidNativeType(needle,["boolean","string","number","null"])){throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(typeOf(needle))} instead.`)}if(!isValidNativeType(haystack,["string","array"])){throw new RuntimeError(`Expected second argument to be of type array or string, but found ${toString$1(typeOf(haystack))} instead.`)}if(this.fromIndex){const fromIndex=this.fromIndex.evaluate(ctx);return haystack.indexOf(needle,fromIndex)}return haystack.indexOf(needle)}eachChild(fn){fn(this.needle);fn(this.haystack);if(this.fromIndex){fn(this.fromIndex)}}outputDefined(){return false}}class Match{constructor(inputType,outputType,input,cases,outputs,otherwise){this.inputType=inputType;this.type=outputType;this.input=input;this.cases=cases;this.outputs=outputs;this.otherwise=otherwise}static parse(args,context){if(args.length<5)return context.error(`Expected at least 4 arguments, but found only ${args.length-1}.`);if(args.length%2!==1)return context.error("Expected an even number of arguments.");let inputType;let outputType;if(context.expectedType&&context.expectedType.kind!=="value"){outputType=context.expectedType}const cases={};const outputs=[];for(let i=2;iNumber.MAX_SAFE_INTEGER){return labelContext.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`)}else if(typeof label==="number"&&Math.floor(label)!==label){return labelContext.error("Numeric branch labels must be integer values.")}else if(!inputType){inputType=typeOf(label)}else if(labelContext.checkSubtype(inputType,typeOf(label))){return null}if(typeof cases[String(label)]!=="undefined"){return labelContext.error("Branch labels must be unique.")}cases[String(label)]=outputs.length}const result=context.parse(value,i,outputType);if(!result)return null;outputType=outputType||result.type;outputs.push(result)}const input=context.parse(args[1],1,ValueType);if(!input)return null;const otherwise=context.parse(args[args.length-1],args.length-1,outputType);if(!otherwise)return null;if(input.type.kind!=="value"&&context.concat(1).checkSubtype(inputType,input.type)){return null}return new Match(inputType,outputType,input,cases,outputs,otherwise)}evaluate(ctx){const input=this.input.evaluate(ctx);const output=typeOf(input)===this.inputType&&this.outputs[this.cases[input]]||this.otherwise;return output.evaluate(ctx)}eachChild(fn){fn(this.input);this.outputs.forEach(fn);fn(this.otherwise)}outputDefined(){return this.outputs.every((out=>out.outputDefined()))&&this.otherwise.outputDefined()}}class Case{constructor(type,branches,otherwise){this.type=type;this.branches=branches;this.otherwise=otherwise}static parse(args,context){if(args.length<4)return context.error(`Expected at least 3 arguments, but found only ${args.length-1}.`);if(args.length%2!==0)return context.error("Expected an odd number of arguments.");let outputType;if(context.expectedType&&context.expectedType.kind!=="value"){outputType=context.expectedType}const branches=[];for(let i=1;iout.outputDefined()))&&this.otherwise.outputDefined()}}class Slice{constructor(type,input,beginIndex,endIndex){this.type=type;this.input=input;this.beginIndex=beginIndex;this.endIndex=endIndex}static parse(args,context){if(args.length<=2||args.length>=5){return context.error(`Expected 3 or 4 arguments, but found ${args.length-1} instead.`)}const input=context.parse(args[1],1,ValueType);const beginIndex=context.parse(args[2],2,NumberType);if(!input||!beginIndex)return null;if(!isValidType(input.type,[array$1(ValueType),StringType,ValueType])){return context.error(`Expected first argument to be of type array or string, but found ${toString$1(input.type)} instead`)}if(args.length===4){const endIndex=context.parse(args[3],3,NumberType);if(!endIndex)return null;return new Slice(input.type,input,beginIndex,endIndex)}else{return new Slice(input.type,input,beginIndex)}}evaluate(ctx){const input=this.input.evaluate(ctx);const beginIndex=this.beginIndex.evaluate(ctx);if(!isValidNativeType(input,["string","array"])){throw new RuntimeError(`Expected first argument to be of type array or string, but found ${toString$1(typeOf(input))} instead.`)}if(this.endIndex){const endIndex=this.endIndex.evaluate(ctx);return input.slice(beginIndex,endIndex)}return input.slice(beginIndex)}eachChild(fn){fn(this.input);fn(this.beginIndex);if(this.endIndex){fn(this.endIndex)}}outputDefined(){return false}}function isComparableType(op,type){if(op==="=="||op==="!="){return type.kind==="boolean"||type.kind==="string"||type.kind==="number"||type.kind==="null"||type.kind==="value"}else{return type.kind==="string"||type.kind==="number"||type.kind==="value"}}function eq(ctx,a,b){return a===b}function neq(ctx,a,b){return a!==b}function lt(ctx,a,b){return ab}function lteq(ctx,a,b){return a<=b}function gteq(ctx,a,b){return a>=b}function eqCollate(ctx,a,b,c){return c.compare(a,b)===0}function neqCollate(ctx,a,b,c){return!eqCollate(ctx,a,b,c)}function ltCollate(ctx,a,b,c){return c.compare(a,b)<0}function gtCollate(ctx,a,b,c){return c.compare(a,b)>0}function lteqCollate(ctx,a,b,c){return c.compare(a,b)<=0}function gteqCollate(ctx,a,b,c){return c.compare(a,b)>=0}function makeComparison(op,compareBasic,compareWithCollator){const isOrderComparison=op!=="=="&&op!=="!=";return class Comparison{constructor(lhs,rhs,collator){this.type=BooleanType;this.lhs=lhs;this.rhs=rhs;this.collator=collator;this.hasUntypedArgument=lhs.type.kind==="value"||rhs.type.kind==="value"}static parse(args,context){if(args.length!==3&&args.length!==4)return context.error("Expected two or three arguments.");const op=args[0];let lhs=context.parse(args[1],1,ValueType);if(!lhs)return null;if(!isComparableType(op,lhs.type)){return context.concat(1).error(`"${op}" comparisons are not supported for type '${toString$1(lhs.type)}'.`)}let rhs=context.parse(args[2],2,ValueType);if(!rhs)return null;if(!isComparableType(op,rhs.type)){return context.concat(2).error(`"${op}" comparisons are not supported for type '${toString$1(rhs.type)}'.`)}if(lhs.type.kind!==rhs.type.kind&&lhs.type.kind!=="value"&&rhs.type.kind!=="value"){return context.error(`Cannot compare types '${toString$1(lhs.type)}' and '${toString$1(rhs.type)}'.`)}if(isOrderComparison){if(lhs.type.kind==="value"&&rhs.type.kind!=="value"){lhs=new Assertion(rhs.type,[lhs])}else if(lhs.type.kind!=="value"&&rhs.type.kind==="value"){rhs=new Assertion(lhs.type,[rhs])}}let collator=null;if(args.length===4){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.")}collator=context.parse(args[3],3,CollatorType);if(!collator)return null}return new Comparison(lhs,rhs,collator)}evaluate(ctx){const lhs=this.lhs.evaluate(ctx);const rhs=this.rhs.evaluate(ctx);if(isOrderComparison&&this.hasUntypedArgument){const lt=typeOf(lhs);const rt=typeOf(rhs);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.`)}}if(this.collator&&!isOrderComparison&&this.hasUntypedArgument){const lt=typeOf(lhs);const rt=typeOf(rhs);if(lt.kind!=="string"||rt.kind!=="string"){return compareBasic(ctx,lhs,rhs)}}return this.collator?compareWithCollator(ctx,lhs,rhs,this.collator.evaluate(ctx)):compareBasic(ctx,lhs,rhs)}eachChild(fn){fn(this.lhs);fn(this.rhs);if(this.collator){fn(this.collator)}}outputDefined(){return true}}}const Equals=makeComparison("==",eq,eqCollate);const NotEquals=makeComparison("!=",neq,neqCollate);const LessThan=makeComparison("<",lt,ltCollate);const GreaterThan=makeComparison(">",gt,gtCollate);const LessThanOrEqual=makeComparison("<=",lteq,lteqCollate);const GreaterThanOrEqual=makeComparison(">=",gteq,gteqCollate);class NumberFormat{constructor(number,locale,currency,minFractionDigits,maxFractionDigits){this.type=StringType;this.number=number;this.locale=locale;this.currency=currency;this.minFractionDigits=minFractionDigits;this.maxFractionDigits=maxFractionDigits}static parse(args,context){if(args.length!==3)return context.error("Expected two arguments.");const number=context.parse(args[1],1,NumberType);if(!number)return null;const options=args[2];if(typeof options!=="object"||Array.isArray(options))return context.error("NumberFormat options argument must be an object.");let locale=null;if(options["locale"]){locale=context.parse(options["locale"],1,StringType);if(!locale)return null}let currency=null;if(options["currency"]){currency=context.parse(options["currency"],1,StringType);if(!currency)return null}let minFractionDigits=null;if(options["min-fraction-digits"]){minFractionDigits=context.parse(options["min-fraction-digits"],1,NumberType);if(!minFractionDigits)return null}let maxFractionDigits=null;if(options["max-fraction-digits"]){maxFractionDigits=context.parse(options["max-fraction-digits"],1,NumberType);if(!maxFractionDigits)return null}return new NumberFormat(number,locale,currency,minFractionDigits,maxFractionDigits)}evaluate(ctx){return new Intl.NumberFormat(this.locale?this.locale.evaluate(ctx):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(ctx):undefined,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(ctx):undefined,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(ctx):undefined}).format(this.number.evaluate(ctx))}eachChild(fn){fn(this.number);if(this.locale){fn(this.locale)}if(this.currency){fn(this.currency)}if(this.minFractionDigits){fn(this.minFractionDigits)}if(this.maxFractionDigits){fn(this.maxFractionDigits)}}outputDefined(){return false}}class FormatExpression{constructor(sections){this.type=FormattedType;this.sections=sections}static parse(args,context){if(args.length<2){return context.error("Expected at least one argument.")}const firstArg=args[1];if(!Array.isArray(firstArg)&&typeof firstArg==="object"){return context.error("First argument must be an image or text section.")}const sections=[];let nextTokenMayBeObject=false;for(let i=1;i<=args.length-1;++i){const arg=args[i];if(nextTokenMayBeObject&&typeof arg==="object"&&!Array.isArray(arg)){nextTokenMayBeObject=false;let scale=null;if(arg["font-scale"]){scale=context.parse(arg["font-scale"],1,NumberType);if(!scale)return null}let font=null;if(arg["text-font"]){font=context.parse(arg["text-font"],1,array$1(StringType));if(!font)return null}let textColor=null;if(arg["text-color"]){textColor=context.parse(arg["text-color"],1,ColorType);if(!textColor)return null}const lastExpression=sections[sections.length-1];lastExpression.scale=scale;lastExpression.font=font;lastExpression.textColor=textColor}else{const content=context.parse(args[i],1,ValueType);if(!content)return null;const kind=content.type.kind;if(kind!=="string"&&kind!=="value"&&kind!=="null"&&kind!=="resolvedImage")return context.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");nextTokenMayBeObject=true;sections.push({content:content,scale:null,font:null,textColor:null})}}return new FormatExpression(sections)}evaluate(ctx){const evaluateSection=section=>{const evaluatedContent=section.content.evaluate(ctx);if(typeOf(evaluatedContent)===ResolvedImageType){return new FormattedSection("",evaluatedContent,null,null,null)}return new FormattedSection(toString(evaluatedContent),null,section.scale?section.scale.evaluate(ctx):null,section.font?section.font.evaluate(ctx).join(","):null,section.textColor?section.textColor.evaluate(ctx):null)};return new Formatted(this.sections.map(evaluateSection))}eachChild(fn){for(const section of this.sections){fn(section.content);if(section.scale){fn(section.scale)}if(section.font){fn(section.font)}if(section.textColor){fn(section.textColor)}}}outputDefined(){return false}}class ImageExpression{constructor(input){this.type=ResolvedImageType;this.input=input}static parse(args,context){if(args.length!==2){return context.error("Expected two arguments.")}const name=context.parse(args[1],1,StringType);if(!name)return context.error("No image name provided.");return new ImageExpression(name)}evaluate(ctx){const evaluatedImageName=this.input.evaluate(ctx);const value=ResolvedImage.fromString(evaluatedImageName);if(value&&ctx.availableImages)value.available=ctx.availableImages.indexOf(evaluatedImageName)>-1;return value}eachChild(fn){fn(this.input)}outputDefined(){return false}}class Length{constructor(input){this.type=NumberType;this.input=input}static parse(args,context){if(args.length!==2)return context.error(`Expected 1 argument, but found ${args.length-1} instead.`);const input=context.parse(args[1],1);if(!input)return null;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 ${toString$1(input.type)} instead.`);return new Length(input)}evaluate(ctx){const input=this.input.evaluate(ctx);if(typeof input==="string"){return input.length}else if(Array.isArray(input)){return input.length}else{throw new RuntimeError(`Expected value to be of type string or array, but found ${toString$1(typeOf(input))} instead.`)}}eachChild(fn){fn(this.input)}outputDefined(){return false}}const expressions$1={"==":Equals,"!=":NotEquals,">":GreaterThan,"<":LessThan,">=":GreaterThanOrEqual,"<=":LessThanOrEqual,array:Assertion,at:At,boolean:Assertion,case:Case,coalesce:Coalesce,collator:CollatorExpression,format:FormatExpression,image:ImageExpression,in:In,"index-of":IndexOf,interpolate:Interpolate,"interpolate-hcl":Interpolate,"interpolate-lab":Interpolate,length:Length,let:Let,literal:Literal,match:Match,number:Assertion,"number-format":NumberFormat,object:Assertion,slice:Slice,step:Step,string:Assertion,"to-boolean":Coercion,"to-color":Coercion,"to-number":Coercion,"to-string":Coercion,var:Var,within:Within};function rgba(ctx,[r,g,b,a]){r=r.evaluate(ctx);g=g.evaluate(ctx);b=b.evaluate(ctx);const alpha=a?a.evaluate(ctx):1;const error=validateRGBA(r,g,b,alpha);if(error)throw new RuntimeError(error);return new Color(r/255,g/255,b/255,alpha,false)}function has(key,obj){return key in obj}function get(key,obj){const v=obj[key];return typeof v==="undefined"?null:v}function binarySearch(v,a,i,j){while(i<=j){const m=i+j>>1;if(a[m]===v)return true;if(a[m]>v)j=m-1;else i=m+1}return false}function varargs(type){return{type:type}}CompoundExpression.register(expressions$1,{error:[ErrorType,[StringType],(ctx,[v])=>{throw new RuntimeError(v.evaluate(ctx))}],typeof:[StringType,[ValueType],(ctx,[v])=>toString$1(typeOf(v.evaluate(ctx)))],"to-rgba":[array$1(NumberType,4),[ColorType],(ctx,[v])=>{const[r,g,b,a]=v.evaluate(ctx).rgb;return[r*255,g*255,b*255,a]}],rgb:[ColorType,[NumberType,NumberType,NumberType],rgba],rgba:[ColorType,[NumberType,NumberType,NumberType,NumberType],rgba],has:{type:BooleanType,overloads:[[[StringType],(ctx,[key])=>has(key.evaluate(ctx),ctx.properties())],[[StringType,ObjectType],(ctx,[key,obj])=>has(key.evaluate(ctx),obj.evaluate(ctx))]]},get:{type:ValueType,overloads:[[[StringType],(ctx,[key])=>get(key.evaluate(ctx),ctx.properties())],[[StringType,ObjectType],(ctx,[key,obj])=>get(key.evaluate(ctx),obj.evaluate(ctx))]]},"feature-state":[ValueType,[StringType],(ctx,[key])=>get(key.evaluate(ctx),ctx.featureState||{})],properties:[ObjectType,[],ctx=>ctx.properties()],"geometry-type":[StringType,[],ctx=>ctx.geometryType()],id:[ValueType,[],ctx=>ctx.id()],zoom:[NumberType,[],ctx=>ctx.globals.zoom],"heatmap-density":[NumberType,[],ctx=>ctx.globals.heatmapDensity||0],"line-progress":[NumberType,[],ctx=>ctx.globals.lineProgress||0],accumulated:[ValueType,[],ctx=>ctx.globals.accumulated===undefined?null:ctx.globals.accumulated],"+":[NumberType,varargs(NumberType),(ctx,args)=>{let result=0;for(const arg of args){result+=arg.evaluate(ctx)}return result}],"*":[NumberType,varargs(NumberType),(ctx,args)=>{let result=1;for(const arg of args){result*=arg.evaluate(ctx)}return result}],"-":{type:NumberType,overloads:[[[NumberType,NumberType],(ctx,[a,b])=>a.evaluate(ctx)-b.evaluate(ctx)],[[NumberType],(ctx,[a])=>-a.evaluate(ctx)]]},"/":[NumberType,[NumberType,NumberType],(ctx,[a,b])=>a.evaluate(ctx)/b.evaluate(ctx)],"%":[NumberType,[NumberType,NumberType],(ctx,[a,b])=>a.evaluate(ctx)%b.evaluate(ctx)],ln2:[NumberType,[],()=>Math.LN2],pi:[NumberType,[],()=>Math.PI],e:[NumberType,[],()=>Math.E],"^":[NumberType,[NumberType,NumberType],(ctx,[b,e])=>Math.pow(b.evaluate(ctx),e.evaluate(ctx))],sqrt:[NumberType,[NumberType],(ctx,[x])=>Math.sqrt(x.evaluate(ctx))],log10:[NumberType,[NumberType],(ctx,[n])=>Math.log(n.evaluate(ctx))/Math.LN10],ln:[NumberType,[NumberType],(ctx,[n])=>Math.log(n.evaluate(ctx))],log2:[NumberType,[NumberType],(ctx,[n])=>Math.log(n.evaluate(ctx))/Math.LN2],sin:[NumberType,[NumberType],(ctx,[n])=>Math.sin(n.evaluate(ctx))],cos:[NumberType,[NumberType],(ctx,[n])=>Math.cos(n.evaluate(ctx))],tan:[NumberType,[NumberType],(ctx,[n])=>Math.tan(n.evaluate(ctx))],asin:[NumberType,[NumberType],(ctx,[n])=>Math.asin(n.evaluate(ctx))],acos:[NumberType,[NumberType],(ctx,[n])=>Math.acos(n.evaluate(ctx))],atan:[NumberType,[NumberType],(ctx,[n])=>Math.atan(n.evaluate(ctx))],min:[NumberType,varargs(NumberType),(ctx,args)=>Math.min(...args.map((arg=>arg.evaluate(ctx))))],max:[NumberType,varargs(NumberType),(ctx,args)=>Math.max(...args.map((arg=>arg.evaluate(ctx))))],abs:[NumberType,[NumberType],(ctx,[n])=>Math.abs(n.evaluate(ctx))],round:[NumberType,[NumberType],(ctx,[n])=>{const v=n.evaluate(ctx);return v<0?-Math.round(-v):Math.round(v)}],floor:[NumberType,[NumberType],(ctx,[n])=>Math.floor(n.evaluate(ctx))],ceil:[NumberType,[NumberType],(ctx,[n])=>Math.ceil(n.evaluate(ctx))],"filter-==":[BooleanType,[StringType,ValueType],(ctx,[k,v])=>ctx.properties()[k.value]===v.value],"filter-id-==":[BooleanType,[ValueType],(ctx,[v])=>ctx.id()===v.value],"filter-type-==":[BooleanType,[StringType],(ctx,[v])=>ctx.geometryType()===v.value],"filter-<":[BooleanType,[StringType,ValueType],(ctx,[k,v])=>{const a=ctx.properties()[k.value];const b=v.value;return typeof a===typeof b&&a{const a=ctx.id();const b=v.value;return typeof a===typeof b&&a":[BooleanType,[StringType,ValueType],(ctx,[k,v])=>{const a=ctx.properties()[k.value];const b=v.value;return typeof a===typeof b&&a>b}],"filter-id->":[BooleanType,[ValueType],(ctx,[v])=>{const a=ctx.id();const b=v.value;return typeof a===typeof b&&a>b}],"filter-<=":[BooleanType,[StringType,ValueType],(ctx,[k,v])=>{const a=ctx.properties()[k.value];const b=v.value;return typeof a===typeof b&&a<=b}],"filter-id-<=":[BooleanType,[ValueType],(ctx,[v])=>{const a=ctx.id();const b=v.value;return typeof a===typeof b&&a<=b}],"filter->=":[BooleanType,[StringType,ValueType],(ctx,[k,v])=>{const a=ctx.properties()[k.value];const b=v.value;return typeof a===typeof b&&a>=b}],"filter-id->=":[BooleanType,[ValueType],(ctx,[v])=>{const a=ctx.id();const b=v.value;return typeof a===typeof b&&a>=b}],"filter-has":[BooleanType,[ValueType],(ctx,[k])=>k.value in ctx.properties()],"filter-has-id":[BooleanType,[],ctx=>ctx.id()!==null&&ctx.id()!==undefined],"filter-type-in":[BooleanType,[array$1(StringType)],(ctx,[v])=>v.value.indexOf(ctx.geometryType())>=0],"filter-id-in":[BooleanType,[array$1(ValueType)],(ctx,[v])=>v.value.indexOf(ctx.id())>=0],"filter-in-small":[BooleanType,[StringType,array$1(ValueType)],(ctx,[k,v])=>v.value.indexOf(ctx.properties()[k.value])>=0],"filter-in-large":[BooleanType,[StringType,array$1(ValueType)],(ctx,[k,v])=>binarySearch(ctx.properties()[k.value],v.value,0,v.value.length-1)],all:{type:BooleanType,overloads:[[[BooleanType,BooleanType],(ctx,[a,b])=>a.evaluate(ctx)&&b.evaluate(ctx)],[varargs(BooleanType),(ctx,args)=>{for(const arg of args){if(!arg.evaluate(ctx))return false}return true}]]},any:{type:BooleanType,overloads:[[[BooleanType,BooleanType],(ctx,[a,b])=>a.evaluate(ctx)||b.evaluate(ctx)],[varargs(BooleanType),(ctx,args)=>{for(const arg of args){if(arg.evaluate(ctx))return true}return false}]]},"!":[BooleanType,[BooleanType],(ctx,[b])=>!b.evaluate(ctx)],"is-supported-script":[BooleanType,[StringType],(ctx,[s])=>{const isSupportedScript=ctx.globals&&ctx.globals.isSupportedScript;if(isSupportedScript){return isSupportedScript(s.evaluate(ctx))}return true}],upcase:[StringType,[StringType],(ctx,[s])=>s.evaluate(ctx).toUpperCase()],downcase:[StringType,[StringType],(ctx,[s])=>s.evaluate(ctx).toLowerCase()],concat:[StringType,varargs(ValueType),(ctx,args)=>args.map((arg=>toString(arg.evaluate(ctx)))).join("")],"resolved-locale":[StringType,[CollatorType],(ctx,[collator])=>collator.evaluate(ctx).resolvedLocale()]});function success(value){return{result:"success",value:value}}function error(value){return{result:"error",value:value}}function supportsPropertyExpression(spec){return spec["property-type"]==="data-driven"||spec["property-type"]==="cross-faded-data-driven"}function supportsZoomExpression(spec){return!!spec.expression&&spec.expression.parameters.indexOf("zoom")>-1}function supportsInterpolation(spec){return!!spec.expression&&spec.expression.interpolated}function getType(val){if(val instanceof Number){return"number"}else if(val instanceof String){return"string"}else if(val instanceof Boolean){return"boolean"}else if(Array.isArray(val)){return"array"}else if(val===null){return"null"}else{return typeof val}}function isFunction$1(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function identityFunction(x){return x}function createFunction(parameters,propertySpec){const isColor=propertySpec.type==="color";const zoomAndFeatureDependent=parameters.stops&&typeof parameters.stops[0][0]==="object";const featureDependent=zoomAndFeatureDependent||parameters.property!==undefined;const zoomDependent=zoomAndFeatureDependent||!featureDependent;const type=parameters.type||(supportsInterpolation(propertySpec)?"exponential":"interval");if(isColor||propertySpec.type==="padding"){const parseFn=isColor?Color.parse:Padding.parse;parameters=extendBy({},parameters);if(parameters.stops){parameters.stops=parameters.stops.map((stop=>[stop[0],parseFn(stop[1])]))}if(parameters.default){parameters.default=parseFn(parameters.default)}else{parameters.default=parseFn(propertySpec.default)}}if(parameters.colorSpace&&!isSupportedInterpolationColorSpace(parameters.colorSpace)){throw new Error(`Unknown color space: "${parameters.colorSpace}"`)}let innerFun;let hashedStops;let categoricalKeyType;if(type==="exponential"){innerFun=evaluateExponentialFunction}else if(type==="interval"){innerFun=evaluateIntervalFunction}else if(type==="categorical"){innerFun=evaluateCategoricalFunction;hashedStops=Object.create(null);for(const stop of parameters.stops){hashedStops[stop[0]]=stop[1]}categoricalKeyType=typeof parameters.stops[0][0]}else if(type==="identity"){innerFun=evaluateIdentityFunction}else{throw new Error(`Unknown function type "${type}"`)}if(zoomAndFeatureDependent){const featureFunctions={};const zoomStops=[];for(let s=0;ss[0])),evaluate({zoom:zoom},properties){return evaluateExponentialFunction({stops:featureFunctionStops,base:parameters.base},propertySpec,zoom).evaluate(zoom,properties)}}}else if(zoomDependent){const interpolationType=type==="exponential"?{name:"exponential",base:parameters.base!==undefined?parameters.base:1}:null;return{kind:"camera",interpolationType:interpolationType,interpolationFactor:Interpolate.interpolationFactor.bind(undefined,interpolationType),zoomStops:parameters.stops.map((s=>s[0])),evaluate:({zoom:zoom})=>innerFun(parameters,propertySpec,zoom,hashedStops,categoricalKeyType)}}else{return{kind:"source",evaluate(_,feature){const value=feature&&feature.properties?feature.properties[parameters.property]:undefined;if(value===undefined){return coalesce$1(parameters.default,propertySpec.default)}return innerFun(parameters,propertySpec,value,hashedStops,categoricalKeyType)}}}}function coalesce$1(a,b,c){if(a!==undefined)return a;if(b!==undefined)return b;if(c!==undefined)return c}function evaluateCategoricalFunction(parameters,propertySpec,input,hashedStops,keyType){const evaluated=typeof input===keyType?hashedStops[input]:undefined;return coalesce$1(evaluated,parameters.default,propertySpec.default)}function evaluateIntervalFunction(parameters,propertySpec,input){if(getType(input)!=="number")return coalesce$1(parameters.default,propertySpec.default);const n=parameters.stops.length;if(n===1)return parameters.stops[0][1];if(input<=parameters.stops[0][0])return parameters.stops[0][1];if(input>=parameters.stops[n-1][0])return parameters.stops[n-1][1];const index=findStopLessThanOrEqualTo(parameters.stops.map((stop=>stop[0])),input);return parameters.stops[index][1]}function evaluateExponentialFunction(parameters,propertySpec,input){const base=parameters.base!==undefined?parameters.base:1;if(getType(input)!=="number")return coalesce$1(parameters.default,propertySpec.default);const n=parameters.stops.length;if(n===1)return parameters.stops[0][1];if(input<=parameters.stops[0][0])return parameters.stops[0][1];if(input>=parameters.stops[n-1][0])return parameters.stops[n-1][1];const index=findStopLessThanOrEqualTo(parameters.stops.map((stop=>stop[0])),input);const t=interpolationFactor(input,base,parameters.stops[index][0],parameters.stops[index+1][0]);const outputLower=parameters.stops[index][1];const outputUpper=parameters.stops[index+1][1];const interp=interpolate[propertySpec.type]||identityFunction;if(typeof outputLower.evaluate==="function"){return{evaluate(...args){const evaluatedLower=outputLower.evaluate.apply(undefined,args);const evaluatedUpper=outputUpper.evaluate.apply(undefined,args);if(evaluatedLower===undefined||evaluatedUpper===undefined){return undefined}return interp(evaluatedLower,evaluatedUpper,t,parameters.colorSpace)}}}return interp(outputLower,outputUpper,t,parameters.colorSpace)}function evaluateIdentityFunction(parameters,propertySpec,input){switch(propertySpec.type){case"color":input=Color.parse(input);break;case"formatted":input=Formatted.fromString(input.toString());break;case"resolvedImage":input=ResolvedImage.fromString(input.toString());break;case"padding":input=Padding.parse(input);break;default:if(getType(input)!==propertySpec.type&&(propertySpec.type!=="enum"||!propertySpec.values[input])){input=undefined}}return coalesce$1(input,parameters.default,propertySpec.default)}function interpolationFactor(input,base,lowerValue,upperValue){const difference=upperValue-lowerValue;const progress=input-lowerValue;if(difference===0){return 0}else if(base===1){return progress/difference}else{return(Math.pow(base,progress)-1)/(Math.pow(base,difference)-1)}}class StyleExpression{constructor(expression,propertySpec){this.expression=expression;this._warningHistory={};this._evaluator=new EvaluationContext;this._defaultValue=propertySpec?getDefaultValue(propertySpec):null;this._enumValues=propertySpec&&propertySpec.type==="enum"?propertySpec.values:null}evaluateWithoutErrorHandling(globals,feature,featureState,canonical,availableImages,formattedSection){this._evaluator.globals=globals;this._evaluator.feature=feature;this._evaluator.featureState=featureState;this._evaluator.canonical=canonical;this._evaluator.availableImages=availableImages||null;this._evaluator.formattedSection=formattedSection;return this.expression.evaluate(this._evaluator)}evaluate(globals,feature,featureState,canonical,availableImages,formattedSection){this._evaluator.globals=globals;this._evaluator.feature=feature||null;this._evaluator.featureState=featureState||null;this._evaluator.canonical=canonical;this._evaluator.availableImages=availableImages||null;this._evaluator.formattedSection=formattedSection||null;try{const val=this.expression.evaluate(this._evaluator);if(val===null||val===undefined||typeof val==="number"&&val!==val){return this._defaultValue}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.`)}return val}catch(e){if(!this._warningHistory[e.message]){this._warningHistory[e.message]=true;if(typeof console!=="undefined"){console.warn(e.message)}}return this._defaultValue}}}function isExpression(expression){return Array.isArray(expression)&&expression.length>0&&typeof expression[0]==="string"&&expression[0]in expressions$1}function createExpression(expression,propertySpec){const parser=new ParsingContext(expressions$1,isExpressionConstant,[],propertySpec?getExpectedType(propertySpec):undefined);const parsed=parser.parse(expression,undefined,undefined,undefined,propertySpec&&propertySpec.type==="string"?{typeAnnotation:"coerce"}:undefined);if(!parsed){return error(parser.errors)}return success(new StyleExpression(parsed,propertySpec))}class ZoomConstantExpression{constructor(kind,expression){this.kind=kind;this._styleExpression=expression;this.isStateDependent=kind!=="constant"&&!isStateConstant(expression.expression)}evaluateWithoutErrorHandling(globals,feature,featureState,canonical,availableImages,formattedSection){return this._styleExpression.evaluateWithoutErrorHandling(globals,feature,featureState,canonical,availableImages,formattedSection)}evaluate(globals,feature,featureState,canonical,availableImages,formattedSection){return this._styleExpression.evaluate(globals,feature,featureState,canonical,availableImages,formattedSection)}}class ZoomDependentExpression{constructor(kind,expression,zoomStops,interpolationType){this.kind=kind;this.zoomStops=zoomStops;this._styleExpression=expression;this.isStateDependent=kind!=="camera"&&!isStateConstant(expression.expression);this.interpolationType=interpolationType}evaluateWithoutErrorHandling(globals,feature,featureState,canonical,availableImages,formattedSection){return this._styleExpression.evaluateWithoutErrorHandling(globals,feature,featureState,canonical,availableImages,formattedSection)}evaluate(globals,feature,featureState,canonical,availableImages,formattedSection){return this._styleExpression.evaluate(globals,feature,featureState,canonical,availableImages,formattedSection)}interpolationFactor(input,lower,upper){if(this.interpolationType){return Interpolate.interpolationFactor(this.interpolationType,input,lower,upper)}else{return 0}}}function isZoomExpression(expression){return expression._styleExpression!==undefined}function createPropertyExpression(expressionInput,propertySpec){const expression=createExpression(expressionInput,propertySpec);if(expression.result==="error"){return expression}const parsed=expression.value.expression;const isFeatureConstantResult=isFeatureConstant(parsed);if(!isFeatureConstantResult&&!supportsPropertyExpression(propertySpec)){return error([new ExpressionParsingError("","data expressions not supported")])}const isZoomConstant=isGlobalPropertyConstant(parsed,["zoom"]);if(!isZoomConstant&&!supportsZoomExpression(propertySpec)){return error([new ExpressionParsingError("","zoom expressions not supported")])}const zoomCurve=findZoomCurve(parsed);if(!zoomCurve&&!isZoomConstant){return error([new ExpressionParsingError("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}else if(zoomCurve instanceof ExpressionParsingError){return error([zoomCurve])}else if(zoomCurve instanceof Interpolate&&!supportsInterpolation(propertySpec)){return error([new ExpressionParsingError("",'"interpolate" expressions cannot be used with this property')])}if(!zoomCurve){return success(isFeatureConstantResult?new ZoomConstantExpression("constant",expression.value):new ZoomConstantExpression("source",expression.value))}const interpolationType=zoomCurve instanceof Interpolate?zoomCurve.interpolation:undefined;return success(isFeatureConstantResult?new ZoomDependentExpression("camera",expression.value,zoomCurve.labels,interpolationType):new ZoomDependentExpression("composite",expression.value,zoomCurve.labels,interpolationType))}class StylePropertyFunction{constructor(parameters,specification){this._parameters=parameters;this._specification=specification;extendBy(this,createFunction(this._parameters,this._specification))}static deserialize(serialized){return new StylePropertyFunction(serialized._parameters,serialized._specification)}static serialize(input){return{_parameters:input._parameters,_specification:input._specification}}}function normalizePropertyExpression(value,specification){if(isFunction$1(value)){return new StylePropertyFunction(value,specification)}else if(isExpression(value)){const expression=createPropertyExpression(value,specification);if(expression.result==="error"){throw new Error(expression.value.map((err=>`${err.key}: ${err.message}`)).join(", "))}return expression.value}else{let constant=value;if(specification.type==="color"&&typeof value==="string"){constant=Color.parse(value)}else if(specification.type==="padding"&&(typeof value==="number"||Array.isArray(value))){constant=Padding.parse(value)}else if(specification.type==="variableAnchorOffsetCollection"&&Array.isArray(value)){constant=VariableAnchorOffsetCollection.parse(value)}return{kind:"constant",evaluate:()=>constant}}}function findZoomCurve(expression){let result=null;if(expression instanceof Let){result=findZoomCurve(expression.result)}else if(expression instanceof Coalesce){for(const arg of expression.args){result=findZoomCurve(arg);if(result){break}}}else if((expression instanceof Step||expression instanceof Interpolate)&&expression.input instanceof CompoundExpression&&expression.input.name==="zoom"){result=expression}if(result instanceof ExpressionParsingError){return result}expression.eachChild((child=>{const childResult=findZoomCurve(child);if(childResult instanceof ExpressionParsingError){result=childResult}else if(!result&&childResult){result=new ExpressionParsingError("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')}else if(result&&childResult&&result!==childResult){result=new ExpressionParsingError("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.')}}));return result}function getExpectedType(spec){const types={color:ColorType,string:StringType,number:NumberType,enum:StringType,boolean:BooleanType,formatted:FormattedType,padding:PaddingType,resolvedImage:ResolvedImageType,variableAnchorOffsetCollection:VariableAnchorOffsetCollectionType};if(spec.type==="array"){return array$1(types[spec.value]||ValueType,spec.length)}return types[spec.type]}function getDefaultValue(spec){if(spec.type==="color"&&isFunction$1(spec.default)){return new Color(0,0,0,0)}else if(spec.type==="color"){return Color.parse(spec.default)||null}else if(spec.type==="padding"){return Padding.parse(spec.default)||null}else if(spec.type==="variableAnchorOffsetCollection"){return VariableAnchorOffsetCollection.parse(spec.default)||null}else if(spec.default===undefined){return null}else{return spec.default}}function isExpressionFilter(filter){if(filter===true||filter===false){return true}if(!Array.isArray(filter)||filter.length===0){return false}switch(filter[0]){case"has":return filter.length>=2&&filter[1]!=="$id"&&filter[1]!=="$type";case"in":return filter.length>=3&&(typeof filter[1]!=="string"||Array.isArray(filter[2]));case"!in":case"!has":case"none":return false;case"==":case"!=":case">":case">=":case"<":case"<=":return filter.length!==3||(Array.isArray(filter[1])||Array.isArray(filter[2]));case"any":case"all":for(const f of filter.slice(1)){if(!isExpressionFilter(f)&&typeof f!=="boolean"){return false}}return true;default:return true}}const filterSpec={type:"boolean",default:false,transition:false,"property-type":"data-driven",expression:{interpolated:false,parameters:["zoom","feature"]}};function createFilter(filter){if(filter===null||filter===undefined){return{filter:()=>true,needGeometry:false}}if(!isExpressionFilter(filter)){filter=convertFilter$1(filter)}const compiled=createExpression(filter,filterSpec);if(compiled.result==="error"){throw new Error(compiled.value.map((err=>`${err.key}: ${err.message}`)).join(", "))}else{const needGeometry=geometryNeeded(filter);return{filter:(globalProperties,feature,canonical)=>compiled.value.evaluate(globalProperties,feature,{},canonical),needGeometry:needGeometry}}}function compare(a,b){return ab?1:0}function geometryNeeded(filter){if(!Array.isArray(filter))return false;if(filter[0]==="within")return true;for(let index=1;index"||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])):op==="within"?filter:true;return converted}function convertComparisonOp$1(property,value,op){switch(property){case"$type":return[`filter-type-${op}`,value];case"$id":return[`filter-id-${op}`,value];default:return[`filter-${op}`,property,value]}}function convertDisjunctionOp(filters){return["any"].concat(filters.map(convertFilter$1))}function convertInOp$1(property,values){if(values.length===0){return false}switch(property){case"$type":return["filter-type-in",["literal",values]];case"$id":return["filter-id-in",["literal",values]];default:if(values.length>200&&!values.some((v=>typeof v!==typeof values[0]))){return["filter-in-large",property,["literal",values.sort(compare)]]}else{return["filter-in-small",property,["literal",values]]}}}function convertHasOp$1(property){switch(property){case"$type":return true;case"$id":return["filter-has-id"];default:return["filter-has",property]}}function convertNegation(filter){return["!",filter]}function convertFilter(filter,expectedTypes={}){if(isExpressionFilter(filter))return filter;if(!filter)return true;const legacyFilter=filter;const legacyOp=legacyFilter[0];if(filter.length<=1)return legacyOp!=="any";switch(legacyOp){case"==":case"!=":case"<":case">":case"<=":case">=":{const[,property,value]=filter;return convertComparisonOp(property,value,legacyOp,expectedTypes)}case"any":{const[,...conditions]=legacyFilter;const children=conditions.map((f=>{const types={};const child=convertFilter(f,types);const typechecks=runtimeTypeChecks(types);return typechecks===true?child:["case",typechecks,child,false]}));return["any",...children]}case"all":{const[,...conditions]=legacyFilter;const children=conditions.map((f=>convertFilter(f,expectedTypes)));return children.length>1?["all",...children]:children[0]}case"none":{const[,...conditions]=legacyFilter;return["!",convertFilter(["any",...conditions],{})]}case"in":{const[,property,...values]=legacyFilter;return convertInOp(property,values)}case"!in":{const[,property,...values]=legacyFilter;return convertInOp(property,values,true)}case"has":return convertHasOp(legacyFilter[1]);case"!has":return["!",convertHasOp(legacyFilter[1])];default:return true}}function runtimeTypeChecks(expectedTypes){const conditions=[];for(const property in expectedTypes){const get=property==="$id"?["id"]:["get",property];conditions.push(["==",["typeof",get],expectedTypes[property]])}if(conditions.length===0)return true;if(conditions.length===1)return conditions[0];return["all",...conditions]}function convertComparisonOp(property,value,op,expectedTypes){let get;if(property==="$type"){return[op,["geometry-type"],value]}else if(property==="$id"){get=["id"]}else{get=["get",property]}if(expectedTypes&&value!==null){const type=typeof value;expectedTypes[property]=type}if(op==="=="&&property!=="$id"&&value===null){return["all",["has",property],["==",get,null]]}else if(op==="!="&&property!=="$id"&&value===null){return["any",["!",["has",property]],["!=",get,null]]}return[op,get,value]}function convertInOp(property,values,negate=false){if(values.length===0)return negate;let get;if(property==="$type"){get=["geometry-type"]}else if(property==="$id"){get=["id"]}else{get=["get",property]}let uniformTypes=true;const type=typeof values[0];for(const value of values){if(typeof value!==type){uniformTypes=false;break}}if(uniformTypes&&(type==="string"||type==="number")){const uniqueValues=values.sort().filter(((v,i)=>i===0||values[i-1]!==v));return["match",get,uniqueValues,!negate,negate]}if(negate){return["all",...values.map((v=>["!=",get,v]))]}else{return["any",...values.map((v=>["==",get,v]))]}}function convertHasOp(property){if(property==="$type"){return true}else if(property==="$id"){return["!=",["id"],null]}else{return["has",property]}}function convertLiteral(value){return typeof value==="object"?["literal",value]:value}function convertFunction(parameters,propertySpec){let stops=parameters.stops;if(!stops){return convertIdentityFunction(parameters,propertySpec)}const zoomAndFeatureDependent=stops&&typeof stops[0][0]==="object";const featureDependent=zoomAndFeatureDependent||parameters.property!==undefined;const zoomDependent=zoomAndFeatureDependent||!featureDependent;stops=stops.map((stop=>{if(!featureDependent&&propertySpec.tokens&&typeof stop[1]==="string"){return[stop[0],convertTokenString(stop[1])]}return[stop[0],convertLiteral(stop[1])]}));if(zoomAndFeatureDependent){return convertZoomAndPropertyFunction(parameters,propertySpec,stops)}else if(zoomDependent){return convertZoomFunction(parameters,propertySpec,stops)}else{return convertPropertyFunction(parameters,propertySpec,stops)}}function convertIdentityFunction(parameters,propertySpec){const get=["get",parameters.property];if(parameters.default===undefined){return propertySpec.type==="string"?["string",get]:get}else if(propertySpec.type==="enum"){return["match",get,Object.keys(propertySpec.values),get,parameters.default]}else{const expression=[propertySpec.type==="color"?"to-color":propertySpec.type,get,convertLiteral(parameters.default)];if(propertySpec.type==="array"){expression.splice(1,0,propertySpec.value,propertySpec.length||null)}return expression}}function getInterpolateOperator(parameters){switch(parameters.colorSpace){case"hcl":return"interpolate-hcl";case"lab":return"interpolate-lab";default:return"interpolate"}}function convertZoomAndPropertyFunction(parameters,propertySpec,stops){const featureFunctionParameters={};const featureFunctionStops={};const zoomStops=[];for(let s=0;s3&&input===curve[curve.length-2]){return}if(!(isStep&&curve.length===2)){curve.push(input)}curve.push(output)}function getFunctionType(parameters,propertySpec){if(parameters.type){return parameters.type}else{return propertySpec.expression.interpolated?"exponential":"interval"}}function convertTokenString(s){const result=["concat"];const re=/{([^{}]+)}/g;let pos=0;for(let match=re.exec(s);match!==null;match=re.exec(s)){const literal=s.slice(pos,re.lastIndex-match[0].length);pos=re.lastIndex;if(literal.length>0)result.push(literal);result.push(["get",match[1]])}if(result.length===1){return s}if(pos{callback({path:[layer.id,propertyType,key],key:key,value:properties[key],reference:getPropertyReference(key),set(x){properties[key]=x}})}))}eachLayer(style,(layer=>{if(options.paint){inner(layer,"paint")}if(options.layout){inner(layer,"layout")}}))}function stringify$1(obj){const type=typeof obj;if(type==="number"||type==="boolean"||type==="string"||obj===undefined||obj===null)return JSON.stringify(obj);if(Array.isArray(obj)){let str="[";for(const val of obj){str+=`${stringify$1(val)},`}return`${str}]`}const keys=Object.keys(obj).sort();let str="{";for(let i=0;ivalueSpec.maximum){return[new ValidationError(key,value,`${value} is greater than the maximum value ${valueSpec.maximum}`)]}return[]}function validateFunction(options){const functionValueSpec=options.valueSpec;const functionType=unbundle(options.value.type);let stopKeyType;let stopDomainValues={};let previousStopDomainValue;let previousStopDomainZoom;const isZoomFunction=functionType!=="categorical"&&options.value.property===undefined;const isPropertyFunction=!isZoomFunction;const isZoomAndPropertyFunction=getType(options.value.stops)==="array"&&getType(options.value.stops[0])==="array"&&getType(options.value.stops[0][0])==="object";const errors=validateObject({key:options.key,value:options.value,valueSpec:options.styleSpec.function,validateSpec:options.validateSpec,style:options.style,styleSpec:options.styleSpec,objectElementValidators:{stops:validateFunctionStops,default:validateFunctionDefault}});if(functionType==="identity"&&isZoomFunction){errors.push(new ValidationError(options.key,options.value,'missing required property "property"'))}if(functionType!=="identity"&&!options.value.stops){errors.push(new ValidationError(options.key,options.value,'missing required property "stops"'))}if(functionType==="exponential"&&options.valueSpec.expression&&!supportsInterpolation(options.valueSpec)){errors.push(new ValidationError(options.key,options.value,"exponential functions not supported"))}if(options.styleSpec.$version>=8){if(isPropertyFunction&&!supportsPropertyExpression(options.valueSpec)){errors.push(new ValidationError(options.key,options.value,"property functions not supported"))}else if(isZoomFunction&&!supportsZoomExpression(options.valueSpec)){errors.push(new ValidationError(options.key,options.value,"zoom functions not supported"))}}if((functionType==="categorical"||isZoomAndPropertyFunction)&&options.value.property===undefined){errors.push(new ValidationError(options.key,options.value,'"property" property is required'))}return errors;function validateFunctionStops(options){if(functionType==="identity"){return[new ValidationError(options.key,options.value,'identity function may not have a "stops" property')]}let errors=[];const value=options.value;errors=errors.concat(validateArray({key:options.key,value:value,valueSpec:options.valueSpec,validateSpec:options.validateSpec,style:options.style,styleSpec:options.styleSpec,arrayElementValidator:validateFunctionStop}));if(getType(value)==="array"&&value.length===0){errors.push(new ValidationError(options.key,value,"array must have at least one stop"))}return errors}function validateFunctionStop(options){let errors=[];const value=options.value;const key=options.key;if(getType(value)!=="array"){return[new ValidationError(key,value,`array expected, ${getType(value)} found`)]}if(value.length!==2){return[new ValidationError(key,value,`array length 2 expected, length ${value.length} found`)]}if(isZoomAndPropertyFunction){if(getType(value[0])!=="object"){return[new ValidationError(key,value,`object expected, ${getType(value[0])} found`)]}if(value[0].zoom===undefined){return[new ValidationError(key,value,"object stop key must have zoom")]}if(value[0].value===undefined){return[new ValidationError(key,value,"object stop key must have value")]}if(previousStopDomainZoom&&previousStopDomainZoom>unbundle(value[0].zoom)){return[new ValidationError(key,value[0].zoom,"stop zoom values must appear in ascending order")]}if(unbundle(value[0].zoom)!==previousStopDomainZoom){previousStopDomainZoom=unbundle(value[0].zoom);previousStopDomainValue=undefined;stopDomainValues={}}errors=errors.concat(validateObject({key:`${key}[0]`,value:value[0],valueSpec:{zoom:{}},validateSpec:options.validateSpec,style:options.style,styleSpec:options.styleSpec,objectElementValidators:{zoom:validateNumber,value:validateStopDomainValue}}))}else{errors=errors.concat(validateStopDomainValue({key:`${key}[0]`,value:value[0],valueSpec:{},validateSpec:options.validateSpec,style:options.style,styleSpec:options.styleSpec},value))}if(isExpression(deepUnbundle(value[1]))){return errors.concat([new ValidationError(`${key}[1]`,value[1],"expressions are not allowed in function stops.")])}return errors.concat(options.validateSpec({key:`${key}[1]`,value:value[1],valueSpec:functionValueSpec,validateSpec:options.validateSpec,style:options.style,styleSpec:options.styleSpec}))}function validateStopDomainValue(options,stop){const type=getType(options.value);const value=unbundle(options.value);const reportValue=options.value!==null?options.value:stop;if(!stopKeyType){stopKeyType=type}else if(type!==stopKeyType){return[new ValidationError(options.key,reportValue,`${type} stop domain type must match previous stop domain type ${stopKeyType}`)]}if(type!=="number"&&type!=="string"&&type!=="boolean"){return[new ValidationError(options.key,reportValue,"stop domain value must be a number, string, or boolean")]}if(type!=="number"&&functionType!=="categorical"){let message=`number expected, ${type} found`;if(supportsPropertyExpression(functionValueSpec)&&functionType===undefined){message+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'}return[new ValidationError(options.key,reportValue,message)]}if(functionType==="categorical"&&type==="number"&&(!isFinite(value)||Math.floor(value)!==value)){return[new ValidationError(options.key,reportValue,`integer expected, found ${value}`)]}if(functionType!=="categorical"&&type==="number"&&previousStopDomainValue!==undefined&&valuenew ValidationError(`${options.key}${error.key}`,options.value,error.message)))}const expressionObj=expression.value.expression||expression.value._styleExpression.expression;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.`)]}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.')]}if(options.expressionContext==="filter"&&!isStateConstant(expressionObj)){return[new ValidationError(options.key,options.value,'"feature-state" data expressions are not supported with filters.')]}if(options.expressionContext&&options.expressionContext.indexOf("cluster")===0){if(!isGlobalPropertyConstant(expressionObj,["zoom","feature-state"])){return[new ValidationError(options.key,options.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')]}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.")]}}return[]}function validateBoolean(options){const value=options.value;const key=options.key;const type=getType(value);if(type!=="boolean"){return[new ValidationError(key,value,`boolean expected, ${type} found`)]}return[]}function validateColor(options){const key=options.key;const value=options.value;const type=getType(value);if(type!=="string"){return[new ValidationError(key,value,`color expected, ${type} found`)]}if(!Color.parse(String(value))){return[new ValidationError(key,value,`color expected, "${value}" found`)]}return[]}function validateEnum(options){const key=options.key;const value=options.value;const valueSpec=options.valueSpec;const errors=[];if(Array.isArray(valueSpec.values)){if(valueSpec.values.indexOf(unbundle(value))===-1){errors.push(new ValidationError(key,value,`expected one of [${valueSpec.values.join(", ")}], ${JSON.stringify(value)} found`))}}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`))}}return errors}function validateFilter$1(options){if(isExpressionFilter(deepUnbundle(options.value))){return validateExpression(extendBy({},options,{expressionContext:"filter",valueSpec:{value:"boolean"}}))}else{return validateNonExpressionFilter(options)}}function validateNonExpressionFilter(options){const value=options.value;const key=options.key;if(getType(value)!=="array"){return[new ValidationError(key,value,`array expected, ${getType(value)} found`)]}const styleSpec=options.styleSpec;let type;let errors=[];if(value.length<1){return[new ValidationError(key,value,"filter array must have at least 1 element")]}errors=errors.concat(validateEnum({key:`${key}[0]`,value:value[0],valueSpec:styleSpec.filter_operator,style:options.style,styleSpec:options.styleSpec}));switch(unbundle(value[0])){case"<":case"<=":case">":case">=":if(value.length>=2&&unbundle(value[1])==="$type"){errors.push(new ValidationError(key,value,`"$type" cannot be use with operator "${value[0]}"`))}case"==":case"!=":if(value.length!==3){errors.push(new ValidationError(key,value,`filter array for operator "${value[0]}" must have 3 elements`))}case"in":case"!in":if(value.length>=2){type=getType(value[1]);if(type!=="string"){errors.push(new ValidationError(`${key}[1]`,value[1],`string expected, ${type} found`))}}for(let i=2;i{if(p in layer){errors.push(new ValidationError(key,layer[p],`"${p}" is prohibited for ref layers`))}}));let parent;style.layers.forEach((layer=>{if(unbundle(layer.id)===ref)parent=layer}));if(!parent){errors.push(new ValidationError(key,layer.ref,`ref layer "${ref}" not found`))}else if(parent.ref){errors.push(new ValidationError(key,layer.ref,"ref cannot reference another ref layer"))}else{type=unbundle(parent.type)}}else if(type!=="background"){if(!layer.source){errors.push(new ValidationError(key,layer,'missing required property "source"'))}else{const source=style.sources&&style.sources[layer.source];const sourceType=source&&unbundle(source.type);if(!source){errors.push(new ValidationError(key,layer.source,`source "${layer.source}" not found`))}else if(sourceType==="vector"&&type==="raster"){errors.push(new ValidationError(key,layer.source,`layer "${layer.id}" requires a raster source`))}else if(sourceType!=="raster-dem"&&type==="hillshade"){errors.push(new ValidationError(key,layer.source,`layer "${layer.id}" requires a raster-dem source`))}else if(sourceType==="raster"&&type!=="raster"){errors.push(new ValidationError(key,layer.source,`layer "${layer.id}" requires a vector source`))}else if(sourceType==="vector"&&!layer["source-layer"]){errors.push(new ValidationError(key,layer,`layer "${layer.id}" must specify a "source-layer"`))}else if(sourceType==="raster-dem"&&type!=="hillshade"){errors.push(new ValidationError(key,layer.source,"raster-dem source can only be used with layer type 'hillshade'."))}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.`))}}}errors=errors.concat(validateObject({key:key,value:layer,valueSpec:styleSpec.layer,style:options.style,styleSpec:options.styleSpec,validateSpec:options.validateSpec,objectElementValidators:{"*"(){return[]},type(){return options.validateSpec({key:`${key}.type`,value:layer.type,valueSpec:styleSpec.layer.type,style:options.style,styleSpec:options.styleSpec,validateSpec:options.validateSpec,object:layer,objectKey:"type"})},filter:validateFilter$1,layout(options){return validateObject({layer:layer,key:options.key,value:options.value,style:options.style,styleSpec:options.styleSpec,validateSpec:options.validateSpec,objectElementValidators:{"*"(options){return validateLayoutProperty$1(extendBy({layerType:type},options))}}})},paint(options){return validateObject({layer:layer,key:options.key,value:options.value,style:options.style,styleSpec:options.styleSpec,validateSpec:options.validateSpec,objectElementValidators:{"*"(options){return validatePaintProperty$1(extendBy({layerType:type},options))}}})}}}));return errors}function validateString(options){const value=options.value;const key=options.key;const type=getType(value);if(type!=="string"){return[new ValidationError(key,value,`string expected, ${type} found`)]}return[]}function validateRasterDEMSource(options){var _a;const sourceName=(_a=options.sourceName)!==null&&_a!==void 0?_a:"";const rasterDEM=options.value;const styleSpec=options.styleSpec;const rasterDEMSpec=styleSpec.source_raster_dem;const style=options.style;let errors=[];const rootType=getType(rasterDEM);if(rasterDEM===undefined){return errors}else if(rootType!=="object"){errors.push(new ValidationError("source_raster_dem",rasterDEM,`object expected, ${rootType} found`));return errors}const encoding=unbundle(rasterDEM.encoding);const isCustomEncoding=encoding==="custom";const customEncodingKeys=["redFactor","greenFactor","blueFactor","baseShift"];const encodingName=options.value.encoding?`"${options.value.encoding}"`:"Default";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`))}else if(rasterDEMSpec[key]){errors=errors.concat(options.validateSpec({key:key,value:rasterDEM[key],valueSpec:rasterDEMSpec[key],validateSpec:options.validateSpec,style:style,styleSpec:styleSpec}))}else{errors.push(new ValidationError(key,rasterDEM[key],`unknown property "${key}"`))}}return errors}const objectElementValidators={promoteId:validatePromoteId};function validateSource$1(options){const value=options.value;const key=options.key;const styleSpec=options.styleSpec;const style=options.style;const validateSpec=options.validateSpec;if(!value.type){return[new ValidationError(key,value,'"type" is required')]}const type=unbundle(value.type);let errors;switch(type){case"vector":case"raster":errors=validateObject({key:key,value:value,valueSpec:styleSpec[`source_${type.replace("-","_")}`],style:options.style,styleSpec:styleSpec,objectElementValidators:objectElementValidators,validateSpec:validateSpec});return errors;case"raster-dem":errors=validateRasterDEMSource({sourceName:key,value:value,style:options.style,styleSpec:styleSpec,validateSpec:validateSpec});return errors;case"geojson":errors=validateObject({key:key,value:value,valueSpec:styleSpec.source_geojson,style:style,styleSpec:styleSpec,validateSpec:validateSpec,objectElementValidators:objectElementValidators});if(value.cluster){for(const prop in value.clusterProperties){const[operator,mapExpr]=value.clusterProperties[prop];const reduceExpr=typeof operator==="string"?[operator,["accumulated"],["get",prop]]:operator;errors.push(...validateExpression({key:`${key}.${prop}.map`,value:mapExpr,validateSpec:validateSpec,expressionContext:"cluster-map"}));errors.push(...validateExpression({key:`${key}.${prop}.reduce`,value:reduceExpr,validateSpec:validateSpec,expressionContext:"cluster-reduce"}))}}return errors;case"video":return validateObject({key:key,value:value,valueSpec:styleSpec.source_video,style:style,validateSpec:validateSpec,styleSpec:styleSpec});case"image":return validateObject({key:key,value:value,valueSpec:styleSpec.source_image,style:style,validateSpec:validateSpec,styleSpec:styleSpec});case"canvas":return[new ValidationError(key,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return validateEnum({key:`${key}.type`,value:value.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]},style:style,validateSpec:validateSpec,styleSpec:styleSpec})}}function validatePromoteId({key:key,value:value}){if(getType(value)==="string"){return validateString({key:key,value:value})}else{const errors=[];for(const prop in value){errors.push(...validateString({key:`${key}.${prop}`,value:value[prop]}))}return errors}}function validateLight$1(options){const light=options.value;const styleSpec=options.styleSpec;const lightSpec=styleSpec.light;const style=options.style;let errors=[];const rootType=getType(light);if(light===undefined){return errors}else if(rootType!=="object"){errors=errors.concat([new ValidationError("light",light,`object expected, ${rootType} found`)]);return errors}for(const key in light){const transitionMatch=key.match(/^(.*)-transition$/);if(transitionMatch&&lightSpec[transitionMatch[1]]&&lightSpec[transitionMatch[1]].transition){errors=errors.concat(options.validateSpec({key:key,value:light[key],valueSpec:styleSpec.transition,validateSpec:options.validateSpec,style:style,styleSpec:styleSpec}))}else if(lightSpec[key]){errors=errors.concat(options.validateSpec({key:key,value:light[key],valueSpec:lightSpec[key],validateSpec:options.validateSpec,style:style,styleSpec:styleSpec}))}else{errors=errors.concat([new ValidationError(key,light[key],`unknown property "${key}"`)])}}return errors}function validateSky(options){const sky=options.value;const styleSpec=options.styleSpec;const skySpec=styleSpec.sky;const style=options.style;const rootType=getType(sky);if(sky===undefined){return[]}else if(rootType!=="object"){return[new ValidationError("sky",sky,`object expected, ${rootType} found`)]}let errors=[];for(const key in sky){if(skySpec[key]){errors=errors.concat(validate({key:key,value:sky[key],valueSpec:skySpec[key],style:style,styleSpec:styleSpec}))}else{errors=errors.concat([new ValidationError(key,sky[key],`unknown property "${key}"`)])}}return errors}function validateTerrain$1(options){const terrain=options.value;const styleSpec=options.styleSpec;const terrainSpec=styleSpec.terrain;const style=options.style;let errors=[];const rootType=getType(terrain);if(terrain===undefined){return errors}else if(rootType!=="object"){errors=errors.concat([new ValidationError("terrain",terrain,`object expected, ${rootType} found`)]);return errors}for(const key in terrain){if(terrainSpec[key]){errors=errors.concat(options.validateSpec({key:key,value:terrain[key],valueSpec:terrainSpec[key],validateSpec:options.validateSpec,style:style,styleSpec:styleSpec}))}else{errors=errors.concat([new ValidationError(key,terrain[key],`unknown property "${key}"`)])}}return errors}function validateFormatted(options){if(validateString(options).length===0){return[]}return validateExpression(options)}function validateImage(options){if(validateString(options).length===0){return[]}return validateExpression(options)}function validatePadding(options){const key=options.key;const value=options.value;const type=getType(value);if(type==="array"){if(value.length<1||value.length>4){return[new ValidationError(key,value,`padding requires 1 to 4 values; ${value.length} values found`)]}const arrayElementSpec={type:"number"};let errors=[];for(let i=0;ia.line-b.line))}function wrapCleanErrors(inner){return function(...args){return sortErrors(inner.apply(this,args))}}const stringOrChar=/("(?:[^\\"]|\\.)*")|[:,]/g;function stringify(passedObj,options={}){const indent=JSON.stringify([1],undefined,options.indent===undefined?2:options.indent).slice(2,-3);const maxLength=indent===""?Infinity:options.maxLength===undefined?80:options.maxLength;let{replacer:replacer}=options;return function _stringify(obj,currentIndent,reserved){if(obj&&typeof obj.toJSON==="function"){obj=obj.toJSON()}const string=JSON.stringify(obj,replacer);if(string===undefined){return string}const length=maxLength-currentIndent.length-reserved;if(string.length<=length){const prettified=string.replace(stringOrChar,((match,stringLiteral)=>stringLiteral||`${match} `));if(prettified.length<=length){return prettified}}if(replacer!=null){obj=JSON.parse(string);replacer=undefined}if(typeof obj==="object"&&obj!==null){const nextIndent=currentIndent+indent;const items=[];let index=0;let start;let end;if(Array.isArray(obj)){start="[";end="]";const{length:length}=obj;for(;index0){return[start,indent+items.join(`,\n${nextIndent}`),end].join(`\n${currentIndent}`)}}return string}(passedObj,"",0)}function sortKeysBy(obj,reference){const result={};for(const key in reference){if(obj[key]!==undefined){result[key]=obj[key]}}for(const key in obj){if(result[key]===undefined){result[key]=obj[key]}}return result}function format(style,space=2){style=sortKeysBy(style,v8Spec.$root);if(style.layers){style.layers=style.layers.map((layer=>sortKeysBy(layer,v8Spec.layer)))}return stringify(style,{indent:space})}function eachLayout(layer,callback){for(const k in layer){if(k.indexOf("layout")===0){callback(layer[k],k)}}}function eachPaint(layer,callback){for(const k in layer){if(k.indexOf("paint")===0){callback(layer[k],k)}}}function resolveConstant(style,value){if(typeof value==="string"&&value[0]==="@"){return resolveConstant(style,style.constants[value])}else{return value}}function isFunction(value){return Array.isArray(value.stops)}function renameProperty(obj,from,to){obj[to]=obj[from];delete obj[from]}function migrateV8(style){style.version=8;eachSource(style,(source=>{if(source.type==="video"&&source["url"]!==undefined){renameProperty(source,"url","urls")}if(source.type==="video"){source.coordinates.forEach((coord=>coord.reverse()))}}));eachLayer(style,(layer=>{eachLayout(layer,(layout=>{if(layout["symbol-min-distance"]!==undefined){renameProperty(layout,"symbol-min-distance","symbol-spacing")}}));eachPaint(layer,(paint=>{if(paint["background-image"]!==undefined){renameProperty(paint,"background-image","background-pattern")}if(paint["line-image"]!==undefined){renameProperty(paint,"line-image","line-pattern")}if(paint["fill-image"]!==undefined){renameProperty(paint,"fill-image","fill-pattern")}}))}));eachProperty(style,{paint:true,layout:true},(property=>{const value=resolveConstant(style,property.value);if(isFunction(value)){value.stops.forEach((stop=>{stop[1]=resolveConstant(style,stop[1])}))}property.set(value)}));delete style["constants"];eachLayer(style,(layer=>{eachLayout(layer,(layout=>{delete layout["text-max-size"];delete layout["icon-max-size"]}));eachPaint(layer,(paint=>{if(paint["text-size"]){if(!layer.layout)layer.layout={};layer.layout["text-size"]=paint["text-size"];delete paint["text-size"]}if(paint["icon-size"]){if(!layer.layout)layer.layout={};layer.layout["icon-size"]=paint["icon-size"];delete paint["icon-size"]}}))}));function migrateFontStack(font){function splitAndTrim(string){return string.split(",").map((s=>s.trim()))}if(Array.isArray(font)){return font}else if(typeof font==="string"){return splitAndTrim(font)}else if(typeof font==="object"){font.stops.forEach((stop=>{stop[1]=splitAndTrim(stop[1])}));return font}else{throw new Error("unexpected font value")}}eachLayer(style,(layer=>{eachLayout(layer,(layout=>{if(layout["text-font"]){layout["text-font"]=migrateFontStack(layout["text-font"])}}))}));let firstSymbolLayer=0;for(let i=style.layers.length-1;i>=0;i--){const layer=style.layers[i];if(layer.type!=="symbol"){firstSymbolLayer=i+1;break}}const symbolLayers=style.layers.splice(firstSymbolLayer);symbolLayers.reverse();style.layers=style.layers.concat(symbolLayers);return style}function expressions(style){const converted=[];eachLayer(style,(layer=>{if(layer.filter){layer.filter=convertFilter(layer.filter)}}));eachProperty(style,{paint:true,layout:true},(({path:path,value:value,reference:reference,set:set})=>{if(isExpression(value))return;if(typeof value==="object"&&!Array.isArray(value)){set(convertFunction(value,reference));converted.push(path.join("."))}else if(reference.tokens&&typeof value==="string"){set(convertTokenString(value))}}));return style}function migrateColors(colorToMigrate){return JSON.parse(migrateHslColors(JSON.stringify(colorToMigrate)))}function migrateHslColors(colorToMigrate){return colorToMigrate.replace(/"hsla?\((.+?)\)"/gi,((match,hslArgs)=>{const argsMatch=hslArgs.match(/^(.+?)\s*,\s*(.+?)\s*,\s*(.+?)(?:\s*,\s*(.+))?$/i);if(argsMatch){let[h,s,l,a]=argsMatch.slice(1);[s,l]=[s,l].map((v=>v.endsWith("%")?v:`${parseFloat(v)*100}%`));return`"hsl${typeof a==="string"?"a":""}(${[h,s,l,a].filter(Boolean).join(",")})"`}return match}))}function migrate(style){let migrated=false;if(style.version===7){style=migrateV8(style);migrated=true}if(style.version===8){migrated=!!expressions(style);migrated=true}eachProperty(style,{paint:true,layout:true},(({value:value,reference:reference,set:set})=>{if(reference.type==="color"){set(migrateColors(value))}}));if(!migrated){throw new Error(`Cannot migrate from ${style.version}`)}return style}const v8=v8Spec;const expression={StyleExpression:StyleExpression,StylePropertyFunction:StylePropertyFunction,ZoomConstantExpression:ZoomConstantExpression,ZoomDependentExpression:ZoomDependentExpression,createExpression:createExpression,createPropertyExpression:createPropertyExpression,isExpression:isExpression,isExpressionFilter:isExpressionFilter,isZoomExpression:isZoomExpression,normalizePropertyExpression:normalizePropertyExpression};const styleFunction={convertFunction:convertFunction,createFunction:createFunction,isFunction:isFunction$1};const visit={eachLayer:eachLayer,eachProperty:eachProperty,eachSource:eachSource};const validateStyle=validateStyleMin;const validateSource=validateStyle.source;const validateLight=validateStyle.light;const validateTerrain=validateStyle.terrain;const validateFilter=validateStyle.filter;const validatePaintProperty=validateStyle.paintProperty;const validateLayoutProperty=validateStyle.layoutProperty;function emitValidationErrors(emitter,errors){let hasErrors=false;if(errors&&errors.length){for(const error of errors){emitter.fire(new ErrorEvent(new Error(error.message)));hasErrors=true}}return hasErrors}const NUM_PARAMS=3;class TransferableGridIndex{constructor(extent,n,padding){const cells=this.cells=[];if(extent instanceof ArrayBuffer){this.arrayBuffer=extent;const array=new Int32Array(this.arrayBuffer);extent=array[0];n=array[1];padding=array[2];this.d=n+2*padding;for(let k=0;k=bboxes[offset+0]&&y2>=bboxes[offset+1]){seenUids[uid]=true;result.push(keys[uid])}else{seenUids[uid]=false}}}}}_forEachCell(x1,y1,x2,y2,fn,arg1,arg2,intersectionTest){const cx1=this._convertToCellCoord(x1);const cy1=this._convertToCellCoord(y1);const cx2=this._convertToCellCoord(x2);const cy2=this._convertToCellCoord(y2);for(let x=cx1;x<=cx2;x++){for(let y=cy1;y<=cy2;y++){const cellIndex=this.d*y+x;if(intersectionTest&&!intersectionTest(this._convertFromCellCoord(x),this._convertFromCellCoord(y),this._convertFromCellCoord(x+1),this._convertFromCellCoord(y+1)))continue;if(fn.call(this,x1,y1,x2,y2,cellIndex,arg1,arg2,intersectionTest))return}}}_convertFromCellCoord(x){return(x-this.padding)/this.scale}_convertToCellCoord(x){return Math.max(0,Math.min(this.d-1,Math.floor(x*this.scale)+this.padding))}toArrayBuffer(){if(this.arrayBuffer)return this.arrayBuffer;const cells=this.cells;const metadataLength=NUM_PARAMS+this.cells.length+1+1;let totalCellLength=0;for(let i=0;i=0)continue;const property=input[key];properties[key]=registry[name].shallow.indexOf(key)>=0?property:serialize(property,transferables)}if(input instanceof Error){properties.message=input.message}}else{if(transferables&&properties===transferables[transferables.length-1]){throw new Error("statically serialized object won't survive transfer of $name property")}}if(properties.$name){throw new Error("$name property is reserved for worker serialization logic.")}if(name!=="Object"){properties.$name=name}return properties}throw new Error(`can't serialize object of type ${typeof input}`)}function deserialize(input){if(input===null||input===undefined||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){return input}if(Array.isArray(input)){return input.map(deserialize)}if(typeof input==="object"){const name=input.$name||"Object";if(!registry[name]){throw new Error(`can't deserialize unregistered class ${name}`)}const{klass:klass}=registry[name];if(!klass){throw new Error(`can't deserialize unregistered class ${name}`)}if(klass.deserialize){return klass.deserialize(input)}const result=Object.create(klass.prototype);for(const key of Object.keys(input)){if(key==="$name")continue;const value=input[key];result[key]=registry[name].shallow.indexOf(key)>=0?value:deserialize(value)}return result}throw new Error(`can't deserialize object of type ${typeof input}`)}class ZoomHistory{constructor(){this.first=true}update(z,now){const floorZ=Math.floor(z);if(this.first){this.first=false;this.lastIntegerZoom=floorZ;this.lastIntegerZoomTime=0;this.lastZoom=z;this.lastFloorZoom=floorZ;return true}if(this.lastFloorZoom>floorZ){this.lastIntegerZoom=floorZ+1;this.lastIntegerZoomTime=now}else if(this.lastFloorZoomchar>=128&&char<=255,Arabic:char=>char>=1536&&char<=1791,"Arabic Supplement":char=>char>=1872&&char<=1919,"Arabic Extended-A":char=>char>=2208&&char<=2303,"Hangul Jamo":char=>char>=4352&&char<=4607,"Unified Canadian Aboriginal Syllabics":char=>char>=5120&&char<=5759,Khmer:char=>char>=6016&&char<=6143,"Unified Canadian Aboriginal Syllabics Extended":char=>char>=6320&&char<=6399,"General Punctuation":char=>char>=8192&&char<=8303,"Letterlike Symbols":char=>char>=8448&&char<=8527,"Number Forms":char=>char>=8528&&char<=8591,"Miscellaneous Technical":char=>char>=8960&&char<=9215,"Control Pictures":char=>char>=9216&&char<=9279,"Optical Character Recognition":char=>char>=9280&&char<=9311,"Enclosed Alphanumerics":char=>char>=9312&&char<=9471,"Geometric Shapes":char=>char>=9632&&char<=9727,"Miscellaneous Symbols":char=>char>=9728&&char<=9983,"Miscellaneous Symbols and Arrows":char=>char>=11008&&char<=11263,"CJK Radicals Supplement":char=>char>=11904&&char<=12031,"Kangxi Radicals":char=>char>=12032&&char<=12255,"Ideographic Description Characters":char=>char>=12272&&char<=12287,"CJK Symbols and Punctuation":char=>char>=12288&&char<=12351,Hiragana:char=>char>=12352&&char<=12447,Katakana:char=>char>=12448&&char<=12543,Bopomofo:char=>char>=12544&&char<=12591,"Hangul Compatibility Jamo":char=>char>=12592&&char<=12687,Kanbun:char=>char>=12688&&char<=12703,"Bopomofo Extended":char=>char>=12704&&char<=12735,"CJK Strokes":char=>char>=12736&&char<=12783,"Katakana Phonetic Extensions":char=>char>=12784&&char<=12799,"Enclosed CJK Letters and Months":char=>char>=12800&&char<=13055,"CJK Compatibility":char=>char>=13056&&char<=13311,"CJK Unified Ideographs Extension A":char=>char>=13312&&char<=19903,"Yijing Hexagram Symbols":char=>char>=19904&&char<=19967,"CJK Unified Ideographs":char=>char>=19968&&char<=40959,"Yi Syllables":char=>char>=40960&&char<=42127,"Yi Radicals":char=>char>=42128&&char<=42191,"Hangul Jamo Extended-A":char=>char>=43360&&char<=43391,"Hangul Syllables":char=>char>=44032&&char<=55215,"Hangul Jamo Extended-B":char=>char>=55216&&char<=55295,"Private Use Area":char=>char>=57344&&char<=63743,"CJK Compatibility Ideographs":char=>char>=63744&&char<=64255,"Arabic Presentation Forms-A":char=>char>=64336&&char<=65023,"Vertical Forms":char=>char>=65040&&char<=65055,"CJK Compatibility Forms":char=>char>=65072&&char<=65103,"Small Form Variants":char=>char>=65104&&char<=65135,"Arabic Presentation Forms-B":char=>char>=65136&&char<=65279,"Halfwidth and Fullwidth Forms":char=>char>=65280&&char<=65519};function allowsIdeographicBreaking(chars){for(const char of chars){if(!charAllowsIdeographicBreaking(char.charCodeAt(0)))return false}return true}function allowsVerticalWritingMode(chars){for(const char of chars){if(charHasUprightVerticalOrientation(char.charCodeAt(0)))return true}return false}function allowsLetterSpacing(chars){for(const char of chars){if(!charAllowsLetterSpacing(char.charCodeAt(0)))return false}return true}function charAllowsLetterSpacing(char){if(unicodeBlockLookup["Arabic"](char))return false;if(unicodeBlockLookup["Arabic Supplement"](char))return false;if(unicodeBlockLookup["Arabic Extended-A"](char))return false;if(unicodeBlockLookup["Arabic Presentation Forms-A"](char))return false;if(unicodeBlockLookup["Arabic Presentation Forms-B"](char))return false;return true}function charAllowsIdeographicBreaking(char){if(char<11904)return false;if(unicodeBlockLookup["Bopomofo Extended"](char))return true;if(unicodeBlockLookup["Bopomofo"](char))return true;if(unicodeBlockLookup["CJK Compatibility Forms"](char))return true;if(unicodeBlockLookup["CJK Compatibility Ideographs"](char))return true;if(unicodeBlockLookup["CJK Compatibility"](char))return true;if(unicodeBlockLookup["CJK Radicals Supplement"](char))return true;if(unicodeBlockLookup["CJK Strokes"](char))return true;if(unicodeBlockLookup["CJK Symbols and Punctuation"](char))return true;if(unicodeBlockLookup["CJK Unified Ideographs Extension A"](char))return true;if(unicodeBlockLookup["CJK Unified Ideographs"](char))return true;if(unicodeBlockLookup["Enclosed CJK Letters and Months"](char))return true;if(unicodeBlockLookup["Halfwidth and Fullwidth Forms"](char))return true;if(unicodeBlockLookup["Hiragana"](char))return true;if(unicodeBlockLookup["Ideographic Description Characters"](char))return true;if(unicodeBlockLookup["Kangxi Radicals"](char))return true;if(unicodeBlockLookup["Katakana Phonetic Extensions"](char))return true;if(unicodeBlockLookup["Katakana"](char))return true;if(unicodeBlockLookup["Vertical Forms"](char))return true;if(unicodeBlockLookup["Yi Radicals"](char))return true;if(unicodeBlockLookup["Yi Syllables"](char))return true;return false}function charHasUprightVerticalOrientation(char){if(char===746||char===747){return true}if(char<4352)return false;if(unicodeBlockLookup["Bopomofo Extended"](char))return true;if(unicodeBlockLookup["Bopomofo"](char))return true;if(unicodeBlockLookup["CJK Compatibility Forms"](char)){if(!(char>=65097&&char<=65103)){return true}}if(unicodeBlockLookup["CJK Compatibility Ideographs"](char))return true;if(unicodeBlockLookup["CJK Compatibility"](char))return true;if(unicodeBlockLookup["CJK Radicals Supplement"](char))return true;if(unicodeBlockLookup["CJK Strokes"](char))return true;if(unicodeBlockLookup["CJK Symbols and Punctuation"](char)){if(!(char>=12296&&char<=12305)&&!(char>=12308&&char<=12319)&&char!==12336){return true}}if(unicodeBlockLookup["CJK Unified Ideographs Extension A"](char))return true;if(unicodeBlockLookup["CJK Unified Ideographs"](char))return true;if(unicodeBlockLookup["Enclosed CJK Letters and Months"](char))return true;if(unicodeBlockLookup["Hangul Compatibility Jamo"](char))return true;if(unicodeBlockLookup["Hangul Jamo Extended-A"](char))return true;if(unicodeBlockLookup["Hangul Jamo Extended-B"](char))return true;if(unicodeBlockLookup["Hangul Jamo"](char))return true;if(unicodeBlockLookup["Hangul Syllables"](char))return true;if(unicodeBlockLookup["Hiragana"](char))return true;if(unicodeBlockLookup["Ideographic Description Characters"](char))return true;if(unicodeBlockLookup["Kanbun"](char))return true;if(unicodeBlockLookup["Kangxi Radicals"](char))return true;if(unicodeBlockLookup["Katakana Phonetic Extensions"](char))return true;if(unicodeBlockLookup["Katakana"](char)){if(char!==12540){return true}}if(unicodeBlockLookup["Halfwidth and Fullwidth Forms"](char)){if(char!==65288&&char!==65289&&char!==65293&&!(char>=65306&&char<=65310)&&char!==65339&&char!==65341&&char!==65343&&!(char>=65371&&char<=65503)&&char!==65507&&!(char>=65512&&char<=65519)){return true}}if(unicodeBlockLookup["Small Form Variants"](char)){if(!(char>=65112&&char<=65118)&&!(char>=65123&&char<=65126)){return true}}if(unicodeBlockLookup["Unified Canadian Aboriginal Syllabics"](char))return true;if(unicodeBlockLookup["Unified Canadian Aboriginal Syllabics Extended"](char))return true;if(unicodeBlockLookup["Vertical Forms"](char))return true;if(unicodeBlockLookup["Yijing Hexagram Symbols"](char))return true;if(unicodeBlockLookup["Yi Syllables"](char))return true;if(unicodeBlockLookup["Yi Radicals"](char))return true;return false}function charHasNeutralVerticalOrientation(char){if(unicodeBlockLookup["Latin-1 Supplement"](char)){if(char===167||char===169||char===174||char===177||char===188||char===189||char===190||char===215||char===247){return true}}if(unicodeBlockLookup["General Punctuation"](char)){if(char===8214||char===8224||char===8225||char===8240||char===8241||char===8251||char===8252||char===8258||char===8263||char===8264||char===8265||char===8273){return true}}if(unicodeBlockLookup["Letterlike Symbols"](char))return true;if(unicodeBlockLookup["Number Forms"](char))return true;if(unicodeBlockLookup["Miscellaneous Technical"](char)){if(char>=8960&&char<=8967||char>=8972&&char<=8991||char>=8996&&char<=9e3||char===9003||char>=9085&&char<=9114||char>=9150&&char<=9165||char===9167||char>=9169&&char<=9179||char>=9186&&char<=9215){return true}}if(unicodeBlockLookup["Control Pictures"](char)&&char!==9251)return true;if(unicodeBlockLookup["Optical Character Recognition"](char))return true;if(unicodeBlockLookup["Enclosed Alphanumerics"](char))return true;if(unicodeBlockLookup["Geometric Shapes"](char))return true;if(unicodeBlockLookup["Miscellaneous Symbols"](char)){if(!(char>=9754&&char<=9759)){return true}}if(unicodeBlockLookup["Miscellaneous Symbols and Arrows"](char)){if(char>=11026&&char<=11055||char>=11088&&char<=11097||char>=11192&&char<=11243){return true}}if(unicodeBlockLookup["CJK Symbols and Punctuation"](char))return true;if(unicodeBlockLookup["Katakana"](char))return true;if(unicodeBlockLookup["Private Use Area"](char))return true;if(unicodeBlockLookup["CJK Compatibility Forms"](char))return true;if(unicodeBlockLookup["Small Form Variants"](char))return true;if(unicodeBlockLookup["Halfwidth and Fullwidth Forms"](char))return true;if(char===8734||char===8756||char===8757||char>=9984&&char<=10087||char>=10102&&char<=10131||char===65532||char===65533){return true}return false}function charHasRotatedVerticalOrientation(char){return!(charHasUprightVerticalOrientation(char)||charHasNeutralVerticalOrientation(char))}function charInComplexShapingScript(char){return unicodeBlockLookup["Arabic"](char)||unicodeBlockLookup["Arabic Supplement"](char)||unicodeBlockLookup["Arabic Extended-A"](char)||unicodeBlockLookup["Arabic Presentation Forms-A"](char)||unicodeBlockLookup["Arabic Presentation Forms-B"](char)}function charInRTLScript(char){return char>=1424&&char<=2303||unicodeBlockLookup["Arabic Presentation Forms-A"](char)||unicodeBlockLookup["Arabic Presentation Forms-B"](char)}function charInSupportedScript(char,canRenderRTL){if(!canRenderRTL&&charInRTLScript(char)){return false}if(char>=2304&&char<=3583||char>=3840&&char<=4255||unicodeBlockLookup["Khmer"](char)){return false}return true}function stringContainsRTLText(chars){for(const char of chars){if(charInRTLScript(char.charCodeAt(0))){return true}}return false}function isStringInSupportedScript(chars,canRenderRTL){for(const char of chars){if(!charInSupportedScript(char.charCodeAt(0),canRenderRTL)){return false}}return true}class RTLWorkerPlugin{constructor(){this.applyArabicShaping=null;this.processBidirectionalText=null;this.processStyledBidirectionalText=null;this.pluginStatus="unavailable";this.pluginURL=null}setState(state){this.pluginStatus=state.pluginStatus;this.pluginURL=state.pluginURL}setMethods(rtlTextPlugin){this.applyArabicShaping=rtlTextPlugin.applyArabicShaping;this.processBidirectionalText=rtlTextPlugin.processBidirectionalText;this.processStyledBidirectionalText=rtlTextPlugin.processStyledBidirectionalText}isParsed(){return this.applyArabicShaping!=null&&this.processBidirectionalText!=null&&this.processStyledBidirectionalText!=null}getPluginURL(){return this.pluginURL}getRTLTextPluginStatus(){return this.pluginStatus}}const rtlWorkerPlugin=new RTLWorkerPlugin;class EvaluationParameters{constructor(zoom,options){this.zoom=zoom;if(options){this.now=options.now;this.fadeDuration=options.fadeDuration;this.zoomHistory=options.zoomHistory;this.transition=options.transition}else{this.now=0;this.fadeDuration=0;this.zoomHistory=new ZoomHistory;this.transition={}}}isSupportedScript(str){return isStringInSupportedScript(str,rtlWorkerPlugin.getRTLTextPluginStatus()==="loaded")}crossFadingFactor(){if(this.fadeDuration===0){return 1}else{return Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)}}getCrossfadeParameters(){const z=this.zoom;const fraction=z-Math.floor(z);const t=this.crossFadingFactor();return z>this.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:fraction+(1-fraction)*t}:{fromScale:.5,toScale:1,t:1-(1-t)*fraction}}}class PropertyValue{constructor(property,value){this.property=property;this.value=value;this.expression=normalizePropertyExpression(value===undefined?property.specification.default:value,property.specification)}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(parameters,canonical,availableImages){return this.property.possiblyEvaluate(this,parameters,canonical,availableImages)}}class TransitionablePropertyValue{constructor(property){this.property=property;this.value=new PropertyValue(property,undefined)}transitioned(parameters,prior){return new TransitioningPropertyValue(this.property,this.value,prior,extend({},parameters.transition,this.transition),parameters.now)}untransitioned(){return new TransitioningPropertyValue(this.property,this.value,null,{},0)}}class Transitionable{constructor(properties){this._properties=properties;this._values=Object.create(properties.defaultTransitionablePropertyValues)}getValue(name){return clone$9(this._values[name].value.value)}setValue(name,value){if(!Object.prototype.hasOwnProperty.call(this._values,name)){this._values[name]=new TransitionablePropertyValue(this._values[name].property)}this._values[name].value=new PropertyValue(this._values[name].property,value===null?undefined:clone$9(value))}getTransition(name){return clone$9(this._values[name].transition)}setTransition(name,value){if(!Object.prototype.hasOwnProperty.call(this._values,name)){this._values[name]=new TransitionablePropertyValue(this._values[name].property)}this._values[name].transition=clone$9(value)||undefined}serialize(){const result={};for(const property of Object.keys(this._values)){const value=this.getValue(property);if(value!==undefined){result[property]=value}const transition=this.getTransition(property);if(transition!==undefined){result[`${property}-transition`]=transition}}return result}transitioned(parameters,prior){const result=new Transitioning(this._properties);for(const property of Object.keys(this._values)){result._values[property]=this._values[property].transitioned(parameters,prior._values[property])}return result}untransitioned(){const result=new Transitioning(this._properties);for(const property of Object.keys(this._values)){result._values[property]=this._values[property].untransitioned()}return result}}class TransitioningPropertyValue{constructor(property,value,prior,transition,now){this.property=property;this.value=value;this.begin=now+transition.delay||0;this.end=this.begin+transition.duration||0;if(property.specification.transition&&(transition.delay||transition.duration)){this.prior=prior}}possiblyEvaluate(parameters,canonical,availableImages){const now=parameters.now||0;const finalValue=this.value.possiblyEvaluate(parameters,canonical,availableImages);const prior=this.prior;if(!prior){return finalValue}else if(now>this.end){this.prior=null;return finalValue}else if(this.value.isDataDriven()){this.prior=null;return finalValue}else if(nowparameters.zoomHistory.lastIntegerZoom?{from:min,to:mid}:{from:max,to:mid}}interpolate(a){return a}}class CrossFadedProperty{constructor(specification){this.specification=specification}possiblyEvaluate(value,parameters,canonical,availableImages){if(value.value===undefined){return undefined}else if(value.expression.kind==="constant"){const constant=value.expression.evaluate(parameters,null,{},canonical,availableImages);return this._calculate(constant,constant,constant,parameters)}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)}}_calculate(min,mid,max,parameters){const z=parameters.zoom;return z>parameters.zoomHistory.lastIntegerZoom?{from:min,to:mid}:{from:max,to:mid}}interpolate(a){return a}}class ColorRampProperty{constructor(specification){this.specification=specification}possiblyEvaluate(value,parameters,canonical,availableImages){return!!value.expression.evaluate(parameters,null,{},canonical,availableImages)}interpolate(){return false}}class Properties{constructor(properties){this.properties=properties;this.defaultPropertyValues={};this.defaultTransitionablePropertyValues={};this.defaultTransitioningPropertyValues={};this.defaultPossiblyEvaluatedValues={};this.overridableProperties=[];for(const property in properties){const prop=properties[property];if(prop.specification.overridable){this.overridableProperties.push(property)}const defaultPropertyValue=this.defaultPropertyValues[property]=new PropertyValue(prop,undefined);const defaultTransitionablePropertyValue=this.defaultTransitionablePropertyValues[property]=new TransitionablePropertyValue(prop);this.defaultTransitioningPropertyValues[property]=defaultTransitionablePropertyValue.untransitioned();this.defaultPossiblyEvaluatedValues[property]=defaultPropertyValue.possiblyEvaluate({})}}}register("DataDrivenProperty",DataDrivenProperty);register("DataConstantProperty",DataConstantProperty);register("CrossFadedDataDrivenProperty",CrossFadedDataDrivenProperty);register("CrossFadedProperty",CrossFadedProperty);register("ColorRampProperty",ColorRampProperty);const TRANSITION_SUFFIX="-transition";class StyleLayer extends Evented{constructor(layer,properties){super();this.id=layer.id;this.type=layer.type;this._featureFilter={filter:()=>true,needGeometry:false};if(layer.type==="custom")return;layer=layer;this.metadata=layer.metadata;this.minzoom=layer.minzoom;this.maxzoom=layer.maxzoom;if(layer.type!=="background"){this.source=layer.source;this.sourceLayer=layer["source-layer"];this.filter=layer.filter}if(properties.layout){this._unevaluatedLayout=new Layout(properties.layout)}if(properties.paint){this._transitionablePaint=new Transitionable(properties.paint);for(const property in layer.paint){this.setPaintProperty(property,layer.paint[property],{validate:false})}for(const property in layer.layout){this.setLayoutProperty(property,layer.layout[property],{validate:false})}this._transitioningPaint=this._transitionablePaint.untransitioned();this.paint=new PossiblyEvaluated(properties.paint)}}getCrossfadeParameters(){return this._crossfadeParameters}getLayoutProperty(name){if(name==="visibility"){return this.visibility}return this._unevaluatedLayout.getValue(name)}setLayoutProperty(name,value,options={}){if(value!==null&&value!==undefined){const key=`layers.${this.id}.layout.${name}`;if(this._validate(validateLayoutProperty,key,name,value,options)){return}}if(name==="visibility"){this.visibility=value;return}this._unevaluatedLayout.setValue(name,value)}getPaintProperty(name){if(name.endsWith(TRANSITION_SUFFIX)){return this._transitionablePaint.getTransition(name.slice(0,-TRANSITION_SUFFIX.length))}else{return this._transitionablePaint.getValue(name)}}setPaintProperty(name,value,options={}){if(value!==null&&value!==undefined){const key=`layers.${this.id}.paint.${name}`;if(this._validate(validatePaintProperty,key,name,value,options)){return false}}if(name.endsWith(TRANSITION_SUFFIX)){this._transitionablePaint.setTransition(name.slice(0,-TRANSITION_SUFFIX.length),value||undefined);return false}else{const transitionable=this._transitionablePaint._values[name];const isCrossFadedProperty=transitionable.property.specification["property-type"]==="cross-faded-data-driven";const wasDataDriven=transitionable.value.isDataDriven();const oldValue=transitionable.value;this._transitionablePaint.setValue(name,value);this._handleSpecialPaintPropertyUpdate(name);const newValue=this._transitionablePaint._values[name].value;const isDataDriven=newValue.isDataDriven();return isDataDriven||wasDataDriven||isCrossFadedProperty||this._handleOverridablePaintPropertyUpdate(name,oldValue,newValue)}}_handleSpecialPaintPropertyUpdate(_){}_handleOverridablePaintPropertyUpdate(name,oldValue,newValue){return false}isHidden(zoom){if(this.minzoom&&zoom=this.maxzoom)return true;return this.visibility==="none"}updateTransitions(parameters){this._transitioningPaint=this._transitionablePaint.transitioned(parameters,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(parameters,availableImages){if(parameters.getCrossfadeParameters){this._crossfadeParameters=parameters.getCrossfadeParameters()}if(this._unevaluatedLayout){this.layout=this._unevaluatedLayout.possiblyEvaluate(parameters,undefined,availableImages)}this.paint=this._transitioningPaint.possiblyEvaluate(parameters,undefined,availableImages)}serialize(){const output={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};if(this.visibility){output.layout=output.layout||{};output.layout.visibility=this.visibility}return filterObject(output,((value,key)=>value!==undefined&&!(key==="layout"&&!Object.keys(value).length)&&!(key==="paint"&&!Object.keys(value).length)))}_validate(validate,key,name,value,options={}){if(options&&options.validate===false){return false}return emitValidationErrors(this,validate.call(validateStyle,{key:key,layerType:this.type,objectKey:name,value:value,styleSpec:v8Spec,style:{glyphs:true,sprite:true}}))}is3D(){return false}isTileClipped(){return false}hasOffscreenPass(){return false}resize(){}isStateDependent(){for(const property in this.paint._values){const value=this.paint.get(property);if(!(value instanceof PossiblyEvaluatedPropertyValue)||!supportsPropertyExpression(value.property.specification)){continue}if((value.value.kind==="source"||value.value.kind==="composite")&&value.value.isStateDependent){return true}}return false}}const viewTypes={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class Struct{constructor(structArray,index){this._structArray=structArray;this._pos1=index*this.size;this._pos2=this._pos1/2;this._pos4=this._pos1/4;this._pos8=this._pos1/8}}const DEFAULT_CAPACITY=128;const RESIZE_MULTIPLIER=5;class StructArray{constructor(){this.isTransferred=false;this.capacity=-1;this.resize(0)}static serialize(array,transferables){array._trim();if(transferables){array.isTransferred=true;transferables.push(array.arrayBuffer)}return{length:array.length,arrayBuffer:array.arrayBuffer}}static deserialize(input){const structArray=Object.create(this.prototype);structArray.arrayBuffer=input.arrayBuffer;structArray.length=input.length;structArray.capacity=input.arrayBuffer.byteLength/structArray.bytesPerElement;structArray._refreshViews();return structArray}_trim(){if(this.length!==this.capacity){this.capacity=this.length;this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement);this._refreshViews()}}clear(){this.length=0}resize(n){this.reserve(n);this.length=n}reserve(n){if(n>this.capacity){this.capacity=Math.max(n,Math.floor(this.capacity*RESIZE_MULTIPLIER),DEFAULT_CAPACITY);this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const oldUint8Array=this.uint8;this._refreshViews();if(oldUint8Array)this.uint8.set(oldUint8Array)}}_refreshViews(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")}}function createLayout(members,alignment=1){let offset=0;let maxSize=0;const layoutMembers=members.map((member=>{const typeSize=sizeOf(member.type);const memberOffset=offset=align$1(offset,Math.max(alignment,typeSize));const components=member.components||1;maxSize=Math.max(maxSize,typeSize);offset+=typeSize*components;return{name:member.name,type:member.type,components:components,offset:memberOffset}}));const size=align$1(offset,Math.max(maxSize,alignment));return{members:layoutMembers,size:size,alignment:alignment}}function sizeOf(type){return viewTypes[type].BYTES_PER_ELEMENT}function align$1(offset,size){return Math.ceil(offset/size)*size}class StructArrayLayout2i4 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(v0,v1){const i=this.length;this.resize(i+1);return this.emplace(i,v0,v1)}emplace(i,v0,v1){const o2=i*2;this.int16[o2+0]=v0;this.int16[o2+1]=v1;return i}}StructArrayLayout2i4.prototype.bytesPerElement=4;register("StructArrayLayout2i4",StructArrayLayout2i4);class StructArrayLayout3i6 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(v0,v1,v2){const i=this.length;this.resize(i+1);return this.emplace(i,v0,v1,v2)}emplace(i,v0,v1,v2){const o2=i*3;this.int16[o2+0]=v0;this.int16[o2+1]=v1;this.int16[o2+2]=v2;return i}}StructArrayLayout3i6.prototype.bytesPerElement=6;register("StructArrayLayout3i6",StructArrayLayout3i6);class StructArrayLayout4i8 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(v0,v1,v2,v3){const i=this.length;this.resize(i+1);return this.emplace(i,v0,v1,v2,v3)}emplace(i,v0,v1,v2,v3){const o2=i*4;this.int16[o2+0]=v0;this.int16[o2+1]=v1;this.int16[o2+2]=v2;this.int16[o2+3]=v3;return i}}StructArrayLayout4i8.prototype.bytesPerElement=8;register("StructArrayLayout4i8",StructArrayLayout4i8);class StructArrayLayout2i4i12 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(v0,v1,v2,v3,v4,v5){const i=this.length;this.resize(i+1);return this.emplace(i,v0,v1,v2,v3,v4,v5)}emplace(i,v0,v1,v2,v3,v4,v5){const o2=i*6;this.int16[o2+0]=v0;this.int16[o2+1]=v1;this.int16[o2+2]=v2;this.int16[o2+3]=v3;this.int16[o2+4]=v4;this.int16[o2+5]=v5;return i}}StructArrayLayout2i4i12.prototype.bytesPerElement=12;register("StructArrayLayout2i4i12",StructArrayLayout2i4i12);class StructArrayLayout2i4ub8 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(v0,v1,v2,v3,v4,v5){const i=this.length;this.resize(i+1);return this.emplace(i,v0,v1,v2,v3,v4,v5)}emplace(i,v0,v1,v2,v3,v4,v5){const o2=i*4;const o1=i*8;this.int16[o2+0]=v0;this.int16[o2+1]=v1;this.uint8[o1+4]=v2;this.uint8[o1+5]=v3;this.uint8[o1+6]=v4;this.uint8[o1+7]=v5;return i}}StructArrayLayout2i4ub8.prototype.bytesPerElement=8;register("StructArrayLayout2i4ub8",StructArrayLayout2i4ub8);class StructArrayLayout2f8 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(v0,v1){const i=this.length;this.resize(i+1);return this.emplace(i,v0,v1)}emplace(i,v0,v1){const o4=i*2;this.float32[o4+0]=v0;this.float32[o4+1]=v1;return i}}StructArrayLayout2f8.prototype.bytesPerElement=8;register("StructArrayLayout2f8",StructArrayLayout2f8);class StructArrayLayout10ui20 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(v0,v1,v2,v3,v4,v5,v6,v7,v8,v9){const i=this.length;this.resize(i+1);return this.emplace(i,v0,v1,v2,v3,v4,v5,v6,v7,v8,v9)}emplace(i,v0,v1,v2,v3,v4,v5,v6,v7,v8,v9){const o2=i*10;this.uint16[o2+0]=v0;this.uint16[o2+1]=v1;this.uint16[o2+2]=v2;this.uint16[o2+3]=v3;this.uint16[o2+4]=v4;this.uint16[o2+5]=v5;this.uint16[o2+6]=v6;this.uint16[o2+7]=v7;this.uint16[o2+8]=v8;this.uint16[o2+9]=v9;return i}}StructArrayLayout10ui20.prototype.bytesPerElement=20;register("StructArrayLayout10ui20",StructArrayLayout10ui20);class StructArrayLayout4i4ui4i24 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.int16=new Int16Array(this.arrayBuffer);this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(v0,v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11){const i=this.length;this.resize(i+1);return this.emplace(i,v0,v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11)}emplace(i,v0,v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11){const o2=i*12;this.int16[o2+0]=v0;this.int16[o2+1]=v1;this.int16[o2+2]=v2;this.int16[o2+3]=v3;this.uint16[o2+4]=v4;this.uint16[o2+5]=v5;this.uint16[o2+6]=v6;this.uint16[o2+7]=v7;this.int16[o2+8]=v8;this.int16[o2+9]=v9;this.int16[o2+10]=v10;this.int16[o2+11]=v11;return i}}StructArrayLayout4i4ui4i24.prototype.bytesPerElement=24;register("StructArrayLayout4i4ui4i24",StructArrayLayout4i4ui4i24);class StructArrayLayout3f12 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(v0,v1,v2){const i=this.length;this.resize(i+1);return this.emplace(i,v0,v1,v2)}emplace(i,v0,v1,v2){const o4=i*3;this.float32[o4+0]=v0;this.float32[o4+1]=v1;this.float32[o4+2]=v2;return i}}StructArrayLayout3f12.prototype.bytesPerElement=12;register("StructArrayLayout3f12",StructArrayLayout3f12);class StructArrayLayout1ul4 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(v0){const i=this.length;this.resize(i+1);return this.emplace(i,v0)}emplace(i,v0){const o4=i*1;this.uint32[o4+0]=v0;return i}}StructArrayLayout1ul4.prototype.bytesPerElement=4;register("StructArrayLayout1ul4",StructArrayLayout1ul4);class StructArrayLayout6i1ul2ui20 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.int16=new Int16Array(this.arrayBuffer);this.uint32=new Uint32Array(this.arrayBuffer);this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(v0,v1,v2,v3,v4,v5,v6,v7,v8){const i=this.length;this.resize(i+1);return this.emplace(i,v0,v1,v2,v3,v4,v5,v6,v7,v8)}emplace(i,v0,v1,v2,v3,v4,v5,v6,v7,v8){const o2=i*10;const o4=i*5;this.int16[o2+0]=v0;this.int16[o2+1]=v1;this.int16[o2+2]=v2;this.int16[o2+3]=v3;this.int16[o2+4]=v4;this.int16[o2+5]=v5;this.uint32[o4+3]=v6;this.uint16[o2+8]=v7;this.uint16[o2+9]=v8;return i}}StructArrayLayout6i1ul2ui20.prototype.bytesPerElement=20;register("StructArrayLayout6i1ul2ui20",StructArrayLayout6i1ul2ui20);class StructArrayLayout2i2i2i12 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(v0,v1,v2,v3,v4,v5){const i=this.length;this.resize(i+1);return this.emplace(i,v0,v1,v2,v3,v4,v5)}emplace(i,v0,v1,v2,v3,v4,v5){const o2=i*6;this.int16[o2+0]=v0;this.int16[o2+1]=v1;this.int16[o2+2]=v2;this.int16[o2+3]=v3;this.int16[o2+4]=v4;this.int16[o2+5]=v5;return i}}StructArrayLayout2i2i2i12.prototype.bytesPerElement=12;register("StructArrayLayout2i2i2i12",StructArrayLayout2i2i2i12);class StructArrayLayout2f1f2i16 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.float32=new Float32Array(this.arrayBuffer);this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(v0,v1,v2,v3,v4){const i=this.length;this.resize(i+1);return this.emplace(i,v0,v1,v2,v3,v4)}emplace(i,v0,v1,v2,v3,v4){const o4=i*4;const o2=i*8;this.float32[o4+0]=v0;this.float32[o4+1]=v1;this.float32[o4+2]=v2;this.int16[o2+6]=v3;this.int16[o2+7]=v4;return i}}StructArrayLayout2f1f2i16.prototype.bytesPerElement=16;register("StructArrayLayout2f1f2i16",StructArrayLayout2f1f2i16);class StructArrayLayout2ub2f12 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(v0,v1,v2,v3){const i=this.length;this.resize(i+1);return this.emplace(i,v0,v1,v2,v3)}emplace(i,v0,v1,v2,v3){const o1=i*12;const o4=i*3;this.uint8[o1+0]=v0;this.uint8[o1+1]=v1;this.float32[o4+1]=v2;this.float32[o4+2]=v3;return i}}StructArrayLayout2ub2f12.prototype.bytesPerElement=12;register("StructArrayLayout2ub2f12",StructArrayLayout2ub2f12);class StructArrayLayout3ui6 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(v0,v1,v2){const i=this.length;this.resize(i+1);return this.emplace(i,v0,v1,v2)}emplace(i,v0,v1,v2){const o2=i*3;this.uint16[o2+0]=v0;this.uint16[o2+1]=v1;this.uint16[o2+2]=v2;return i}}StructArrayLayout3ui6.prototype.bytesPerElement=6;register("StructArrayLayout3ui6",StructArrayLayout3ui6);class StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.int16=new Int16Array(this.arrayBuffer);this.uint16=new Uint16Array(this.arrayBuffer);this.uint32=new Uint32Array(this.arrayBuffer);this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(v0,v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11,v12,v13,v14,v15,v16){const i=this.length;this.resize(i+1);return this.emplace(i,v0,v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11,v12,v13,v14,v15,v16)}emplace(i,v0,v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11,v12,v13,v14,v15,v16){const o2=i*24;const o4=i*12;const o1=i*48;this.int16[o2+0]=v0;this.int16[o2+1]=v1;this.uint16[o2+2]=v2;this.uint16[o2+3]=v3;this.uint32[o4+2]=v4;this.uint32[o4+3]=v5;this.uint32[o4+4]=v6;this.uint16[o2+10]=v7;this.uint16[o2+11]=v8;this.uint16[o2+12]=v9;this.float32[o4+7]=v10;this.float32[o4+8]=v11;this.uint8[o1+36]=v12;this.uint8[o1+37]=v13;this.uint8[o1+38]=v14;this.uint32[o4+10]=v15;this.int16[o2+22]=v16;return i}}StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48.prototype.bytesPerElement=48;register("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48);class StructArrayLayout8i15ui1ul2f2ui64 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.int16=new Int16Array(this.arrayBuffer);this.uint16=new Uint16Array(this.arrayBuffer);this.uint32=new Uint32Array(this.arrayBuffer);this.float32=new Float32Array(this.arrayBuffer)}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){const i=this.length;this.resize(i+1);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)}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){const o2=i*32;const o4=i*16;this.int16[o2+0]=v0;this.int16[o2+1]=v1;this.int16[o2+2]=v2;this.int16[o2+3]=v3;this.int16[o2+4]=v4;this.int16[o2+5]=v5;this.int16[o2+6]=v6;this.int16[o2+7]=v7;this.uint16[o2+8]=v8;this.uint16[o2+9]=v9;this.uint16[o2+10]=v10;this.uint16[o2+11]=v11;this.uint16[o2+12]=v12;this.uint16[o2+13]=v13;this.uint16[o2+14]=v14;this.uint16[o2+15]=v15;this.uint16[o2+16]=v16;this.uint16[o2+17]=v17;this.uint16[o2+18]=v18;this.uint16[o2+19]=v19;this.uint16[o2+20]=v20;this.uint16[o2+21]=v21;this.uint16[o2+22]=v22;this.uint32[o4+12]=v23;this.float32[o4+13]=v24;this.float32[o4+14]=v25;this.uint16[o2+30]=v26;this.uint16[o2+31]=v27;return i}}StructArrayLayout8i15ui1ul2f2ui64.prototype.bytesPerElement=64;register("StructArrayLayout8i15ui1ul2f2ui64",StructArrayLayout8i15ui1ul2f2ui64);class StructArrayLayout1f4 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(v0){const i=this.length;this.resize(i+1);return this.emplace(i,v0)}emplace(i,v0){const o4=i*1;this.float32[o4+0]=v0;return i}}StructArrayLayout1f4.prototype.bytesPerElement=4;register("StructArrayLayout1f4",StructArrayLayout1f4);class StructArrayLayout1ui2f12 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.uint16=new Uint16Array(this.arrayBuffer);this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(v0,v1,v2){const i=this.length;this.resize(i+1);return this.emplace(i,v0,v1,v2)}emplace(i,v0,v1,v2){const o2=i*6;const o4=i*3;this.uint16[o2+0]=v0;this.float32[o4+1]=v1;this.float32[o4+2]=v2;return i}}StructArrayLayout1ui2f12.prototype.bytesPerElement=12;register("StructArrayLayout1ui2f12",StructArrayLayout1ui2f12);class StructArrayLayout1ul2ui8 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.uint32=new Uint32Array(this.arrayBuffer);this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(v0,v1,v2){const i=this.length;this.resize(i+1);return this.emplace(i,v0,v1,v2)}emplace(i,v0,v1,v2){const o4=i*2;const o2=i*4;this.uint32[o4+0]=v0;this.uint16[o2+2]=v1;this.uint16[o2+3]=v2;return i}}StructArrayLayout1ul2ui8.prototype.bytesPerElement=8;register("StructArrayLayout1ul2ui8",StructArrayLayout1ul2ui8);class StructArrayLayout2ui4 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(v0,v1){const i=this.length;this.resize(i+1);return this.emplace(i,v0,v1)}emplace(i,v0,v1){const o2=i*2;this.uint16[o2+0]=v0;this.uint16[o2+1]=v1;return i}}StructArrayLayout2ui4.prototype.bytesPerElement=4;register("StructArrayLayout2ui4",StructArrayLayout2ui4);class StructArrayLayout1ui2 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(v0){const i=this.length;this.resize(i+1);return this.emplace(i,v0)}emplace(i,v0){const o2=i*1;this.uint16[o2+0]=v0;return i}}StructArrayLayout1ui2.prototype.bytesPerElement=2;register("StructArrayLayout1ui2",StructArrayLayout1ui2);class StructArrayLayout4f16 extends StructArray{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer);this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(v0,v1,v2,v3){const i=this.length;this.resize(i+1);return this.emplace(i,v0,v1,v2,v3)}emplace(i,v0,v1,v2,v3){const o4=i*4;this.float32[o4+0]=v0;this.float32[o4+1]=v1;this.float32[o4+2]=v2;this.float32[o4+3]=v3;return i}}StructArrayLayout4f16.prototype.bytesPerElement=16;register("StructArrayLayout4f16",StructArrayLayout4f16);class CollisionBoxStruct extends Struct{get anchorPointX(){return this._structArray.int16[this._pos2+0]}get anchorPointY(){return this._structArray.int16[this._pos2+1]}get x1(){return this._structArray.int16[this._pos2+2]}get y1(){return this._structArray.int16[this._pos2+3]}get x2(){return this._structArray.int16[this._pos2+4]}get y2(){return this._structArray.int16[this._pos2+5]}get featureIndex(){return this._structArray.uint32[this._pos4+3]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+8]}get bucketIndex(){return this._structArray.uint16[this._pos2+9]}get anchorPoint(){return new Point$2(this.anchorPointX,this.anchorPointY)}}CollisionBoxStruct.prototype.size=20;class CollisionBoxArray extends StructArrayLayout6i1ul2ui20{get(index){return new CollisionBoxStruct(this,index)}}register("CollisionBoxArray",CollisionBoxArray);class PlacedSymbolStruct extends Struct{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+2]}get numGlyphs(){return this._structArray.uint16[this._pos2+3]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+2]}get lineStartIndex(){return this._structArray.uint32[this._pos4+3]}get lineLength(){return this._structArray.uint32[this._pos4+4]}get segment(){return this._structArray.uint16[this._pos2+10]}get lowerSize(){return this._structArray.uint16[this._pos2+11]}get upperSize(){return this._structArray.uint16[this._pos2+12]}get lineOffsetX(){return this._structArray.float32[this._pos4+7]}get lineOffsetY(){return this._structArray.float32[this._pos4+8]}get writingMode(){return this._structArray.uint8[this._pos1+36]}get placedOrientation(){return this._structArray.uint8[this._pos1+37]}set placedOrientation(x){this._structArray.uint8[this._pos1+37]=x}get hidden(){return this._structArray.uint8[this._pos1+38]}set hidden(x){this._structArray.uint8[this._pos1+38]=x}get crossTileID(){return this._structArray.uint32[this._pos4+10]}set crossTileID(x){this._structArray.uint32[this._pos4+10]=x}get associatedIconIndex(){return this._structArray.int16[this._pos2+22]}}PlacedSymbolStruct.prototype.size=48;class PlacedSymbolArray extends StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48{get(index){return new PlacedSymbolStruct(this,index)}}register("PlacedSymbolArray",PlacedSymbolArray);class SymbolInstanceStruct extends Struct{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+2]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+3]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+4]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+5]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+6]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+7]}get key(){return this._structArray.uint16[this._pos2+8]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+9]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+10]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+11]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+12]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+13]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+14]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+15]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+16]}get featureIndex(){return this._structArray.uint16[this._pos2+17]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+18]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+19]}get numIconVertices(){return this._structArray.uint16[this._pos2+20]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+21]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+22]}get crossTileID(){return this._structArray.uint32[this._pos4+12]}set crossTileID(x){this._structArray.uint32[this._pos4+12]=x}get textBoxScale(){return this._structArray.float32[this._pos4+13]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+14]}get textAnchorOffsetStartIndex(){return this._structArray.uint16[this._pos2+30]}get textAnchorOffsetEndIndex(){return this._structArray.uint16[this._pos2+31]}}SymbolInstanceStruct.prototype.size=64;class SymbolInstanceArray extends StructArrayLayout8i15ui1ul2f2ui64{get(index){return new SymbolInstanceStruct(this,index)}}register("SymbolInstanceArray",SymbolInstanceArray);class GlyphOffsetArray extends StructArrayLayout1f4{getoffsetX(index){return this.float32[index*1+0]}}register("GlyphOffsetArray",GlyphOffsetArray);class SymbolLineVertexArray extends StructArrayLayout3i6{getx(index){return this.int16[index*3+0]}gety(index){return this.int16[index*3+1]}gettileUnitDistanceFromAnchor(index){return this.int16[index*3+2]}}register("SymbolLineVertexArray",SymbolLineVertexArray);class TextAnchorOffsetStruct extends Struct{get textAnchor(){return this._structArray.uint16[this._pos2+0]}get textOffset0(){return this._structArray.float32[this._pos4+1]}get textOffset1(){return this._structArray.float32[this._pos4+2]}}TextAnchorOffsetStruct.prototype.size=12;class TextAnchorOffsetArray extends StructArrayLayout1ui2f12{get(index){return new TextAnchorOffsetStruct(this,index)}}register("TextAnchorOffsetArray",TextAnchorOffsetArray);class FeatureIndexStruct extends Struct{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}}FeatureIndexStruct.prototype.size=8;class FeatureIndexArray extends StructArrayLayout1ul2ui8{get(index){return new FeatureIndexStruct(this,index)}}register("FeatureIndexArray",FeatureIndexArray);class PosArray extends StructArrayLayout2i4{}class Pos3dArray extends StructArrayLayout3i6{}class RasterBoundsArray extends StructArrayLayout4i8{}class CircleLayoutArray extends StructArrayLayout2i4{}class FillLayoutArray extends StructArrayLayout2i4{}class FillExtrusionLayoutArray extends StructArrayLayout2i4i12{}class HeatmapLayoutArray extends StructArrayLayout2i4{}class LineLayoutArray extends StructArrayLayout2i4ub8{}class LineExtLayoutArray extends StructArrayLayout2f8{}class PatternLayoutArray extends StructArrayLayout10ui20{}class SymbolLayoutArray extends StructArrayLayout4i4ui4i24{}class SymbolDynamicLayoutArray extends StructArrayLayout3f12{}class SymbolOpacityArray extends StructArrayLayout1ul4{}class CollisionBoxLayoutArray extends StructArrayLayout2i2i2i12{}class CollisionCircleLayoutArray extends StructArrayLayout2f1f2i16{}class CollisionVertexArray extends StructArrayLayout2ub2f12{}class QuadTriangleArray extends StructArrayLayout3ui6{}class TriangleIndexArray extends StructArrayLayout3ui6{}class LineIndexArray extends StructArrayLayout2ui4{}class LineStripIndexArray extends StructArrayLayout1ui2{}const layout$6=createLayout([{name:"a_pos",components:2,type:"Int16"}],4);const{members:members$4,size:size$4,alignment:alignment$4}=layout$6;class SegmentVector{constructor(segments=[]){this.segments=segments}prepareSegment(numVertices,layoutVertexArray,indexArray,sortKey){let segment=this.segments[this.segments.length-1];if(numVertices>SegmentVector.MAX_VERTEX_ARRAY_LENGTH)warnOnce(`Max vertices per segment is ${SegmentVector.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${numVertices}`);if(!segment||segment.vertexLength+numVertices>SegmentVector.MAX_VERTEX_ARRAY_LENGTH||segment.sortKey!==sortKey){segment={vertexOffset:layoutVertexArray.length,primitiveOffset:indexArray.length,vertexLength:0,primitiveLength:0};if(sortKey!==undefined)segment.sortKey=sortKey;this.segments.push(segment)}return segment}get(){return this.segments}destroy(){for(const segment of this.segments){for(const k in segment.vaos){segment.vaos[k].destroy()}}}static simpleSegment(vertexOffset,primitiveOffset,vertexLength,primitiveLength){return new SegmentVector([{vertexOffset:vertexOffset,primitiveOffset:primitiveOffset,vertexLength:vertexLength,primitiveLength:primitiveLength,vaos:{},sortKey:0}])}}SegmentVector.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1;register("SegmentVector",SegmentVector);function packUint8ToFloat(a,b){a=clamp$1(Math.floor(a),0,255);b=clamp$1(Math.floor(b),0,255);return 256*a+b}const patternAttributes=createLayout([{name:"a_pattern_from",components:4,type:"Uint16"},{name:"a_pattern_to",components:4,type:"Uint16"},{name:"a_pixel_ratio_from",components:1,type:"Uint16"},{name:"a_pixel_ratio_to",components:1,type:"Uint16"}]);var murmurhashJs$1={exports:{}};var murmurhash3_gc$2={exports:{}};var murmurhash3_gc=murmurhash3_gc$2.exports;(function(module){function murmurhash3_32_gc(key,seed){var remainder,bytes,h1,h1b,c1,c1b,c2,c2b,k1,i;remainder=key.length&3;bytes=key.length-remainder;h1=seed;c1=3432918353;c2=461845907;i=0;while(i>>16)*c1&65535)<<16)&4294967295;k1=k1<<15|k1>>>17;k1=(k1&65535)*c2+(((k1>>>16)*c2&65535)<<16)&4294967295;h1^=k1;h1=h1<<13|h1>>>19;h1b=(h1&65535)*5+(((h1>>>16)*5&65535)<<16)&4294967295;h1=(h1b&65535)+27492+(((h1b>>>16)+58964&65535)<<16)}k1=0;switch(remainder){case 3:k1^=(key.charCodeAt(i+2)&255)<<16;case 2:k1^=(key.charCodeAt(i+1)&255)<<8;case 1:k1^=key.charCodeAt(i)&255;k1=(k1&65535)*c1+(((k1>>>16)*c1&65535)<<16)&4294967295;k1=k1<<15|k1>>>17;k1=(k1&65535)*c2+(((k1>>>16)*c2&65535)<<16)&4294967295;h1^=k1}h1^=key.length;h1^=h1>>>16;h1=(h1&65535)*2246822507+(((h1>>>16)*2246822507&65535)<<16)&4294967295;h1^=h1>>>13;h1=(h1&65535)*3266489909+(((h1>>>16)*3266489909&65535)<<16)&4294967295;h1^=h1>>>16;return h1>>>0}if("object"!=="undefined"){module.exports=murmurhash3_32_gc}})(murmurhash3_gc$2);var murmurhash3_gcExports=murmurhash3_gc$2.exports;var murmurhash3_gc$1=getDefaultExportFromCjs$1(murmurhash3_gcExports);var murmurhash2_gc$2={exports:{}};var murmurhash2_gc=murmurhash2_gc$2.exports;(function(module){function murmurhash2_32_gc(str,seed){var l=str.length,h=seed^l,i=0,k;while(l>=4){k=str.charCodeAt(i)&255|(str.charCodeAt(++i)&255)<<8|(str.charCodeAt(++i)&255)<<16|(str.charCodeAt(++i)&255)<<24;k=(k&65535)*1540483477+(((k>>>16)*1540483477&65535)<<16);k^=k>>>24;k=(k&65535)*1540483477+(((k>>>16)*1540483477&65535)<<16);h=(h&65535)*1540483477+(((h>>>16)*1540483477&65535)<<16)^k;l-=4;++i}switch(l){case 3:h^=(str.charCodeAt(i+2)&255)<<16;case 2:h^=(str.charCodeAt(i+1)&255)<<8;case 1:h^=str.charCodeAt(i)&255;h=(h&65535)*1540483477+(((h>>>16)*1540483477&65535)<<16)}h^=h>>>13;h=(h&65535)*1540483477+(((h>>>16)*1540483477&65535)<<16);h^=h>>>15;return h>>>0}if("object"!==undefined){module.exports=murmurhash2_32_gc}})(murmurhash2_gc$2);var murmurhash2_gcExports=murmurhash2_gc$2.exports;var murmurhash2_gc$1=getDefaultExportFromCjs$1(murmurhash2_gcExports);var murmurhashJs=murmurhashJs$1.exports;var murmur3=murmurhash3_gcExports;var murmur2=murmurhash2_gcExports;murmurhashJs$1.exports=murmur3;var murmur3_1=murmurhashJs$1.exports.murmur3=murmur3;var murmur2_1=murmurhashJs$1.exports.murmur2=murmur2;var murmurhashJsExports=murmurhashJs$1.exports;var murmur3$1=getDefaultExportFromCjs$1(murmurhashJsExports);class FeaturePositionMap{constructor(){this.ids=[];this.positions=[];this.indexed=false}add(id,index,start,end){this.ids.push(getNumericId(id));this.positions.push(index,start,end)}getPositions(id){if(!this.indexed)throw new Error("Trying to get index, but feature positions are not indexed");const intId=getNumericId(id);let i=0;let j=this.ids.length-1;while(i>1;if(this.ids[m]>=intId){j=m}else{i=m+1}}const positions=[];while(this.ids[i]===intId){const index=this.positions[3*i];const start=this.positions[3*i+1];const end=this.positions[3*i+2];positions.push({index:index,start:start,end:end});i++}return positions}static serialize(map,transferables){const ids=new Float64Array(map.ids);const positions=new Uint32Array(map.positions);sort$1(ids,positions,0,ids.length-1);if(transferables){transferables.push(ids.buffer,positions.buffer)}return{ids:ids,positions:positions}}static deserialize(obj){const map=new FeaturePositionMap;map.ids=obj.ids;map.positions=obj.positions;map.indexed=true;return map}}function getNumericId(value){const numValue=+value;if(!isNaN(numValue)&&numValue<=Number.MAX_SAFE_INTEGER){return numValue}return murmur3$1(String(value))}function sort$1(ids,positions,left,right){while(left>1];let i=left-1;let j=right+1;while(true){do{i++}while(ids[i]pivot);if(i>=j)break;swap$2(ids,i,j);swap$2(positions,3*i,3*j);swap$2(positions,3*i+1,3*j+1);swap$2(positions,3*i+2,3*j+2)}if(j-left`u_${name}`));this.type=type}setUniform(uniform,globals,currentValue){uniform.set(currentValue.constantOr(this.value))}getBinding(context,location,_){return this.type==="color"?new UniformColor(context,location):new Uniform1f(context,location)}}class CrossFadedConstantBinder{constructor(value,names){this.uniformNames=names.map((name=>`u_${name}`));this.patternFrom=null;this.patternTo=null;this.pixelRatioFrom=1;this.pixelRatioTo=1}setConstantPatternPositions(posTo,posFrom){this.pixelRatioFrom=posFrom.pixelRatio;this.pixelRatioTo=posTo.pixelRatio;this.patternFrom=posFrom.tlbr;this.patternTo=posTo.tlbr}setUniform(uniform,globals,currentValue,uniformName){const pos=uniformName==="u_pattern_to"?this.patternTo:uniformName==="u_pattern_from"?this.patternFrom:uniformName==="u_pixel_ratio_to"?this.pixelRatioTo:uniformName==="u_pixel_ratio_from"?this.pixelRatioFrom:null;if(pos)uniform.set(pos)}getBinding(context,location,name){return name.substr(0,9)==="u_pattern"?new Uniform4f(context,location):new Uniform1f(context,location)}}class SourceExpressionBinder{constructor(expression,names,type,PaintVertexArray){this.expression=expression;this.type=type;this.maxValue=0;this.paintVertexAttributes=names.map((name=>({name:`a_${name}`,type:"Float32",components:type==="color"?2:1,offset:0})));this.paintVertexArray=new PaintVertexArray}populatePaintArray(newLength,feature,imagePositions,canonical,formattedSection){const start=this.paintVertexArray.length;const value=this.expression.evaluate(new EvaluationParameters(0),feature,{},canonical,[],formattedSection);this.paintVertexArray.resize(newLength);this._setPaintValue(start,newLength,value)}updatePaintArray(start,end,feature,featureState){const value=this.expression.evaluate({zoom:0},feature,featureState);this._setPaintValue(start,end,value)}_setPaintValue(start,end,value){if(this.type==="color"){const color=packColor(value);for(let i=start;i`u_${name}_t`));this.type=type;this.useIntegerZoom=useIntegerZoom;this.zoom=zoom;this.maxValue=0;this.paintVertexAttributes=names.map((name=>({name:`a_${name}`,type:"Float32",components:type==="color"?4:2,offset:0})));this.paintVertexArray=new PaintVertexArray}populatePaintArray(newLength,feature,imagePositions,canonical,formattedSection){const min=this.expression.evaluate(new EvaluationParameters(this.zoom),feature,{},canonical,[],formattedSection);const max=this.expression.evaluate(new EvaluationParameters(this.zoom+1),feature,{},canonical,[],formattedSection);const start=this.paintVertexArray.length;this.paintVertexArray.resize(newLength);this._setPaintValue(start,newLength,min,max)}updatePaintArray(start,end,feature,featureState){const min=this.expression.evaluate({zoom:this.zoom},feature,featureState);const max=this.expression.evaluate({zoom:this.zoom+1},feature,featureState);this._setPaintValue(start,end,min,max)}_setPaintValue(start,end,min,max){if(this.type==="color"){const minColor=packColor(min);const maxColor=packColor(max);for(let i=start;i`#define HAS_UNIFORM_${name}`)))}}return result}getBinderAttributes(){const result=[];for(const property in this.binders){const binder=this.binders[property];if(binder instanceof SourceExpressionBinder||binder instanceof CompositeExpressionBinder){for(let i=0;itrue)){this.programConfigurations={};for(const layer of layers){this.programConfigurations[layer.id]=new ProgramConfiguration(layer,zoom,filterProperties)}this.needsUpload=false;this._featureMap=new FeaturePositionMap;this._bufferOffset=0}populatePaintArrays(length,feature,index,imagePositions,canonical,formattedSection){for(const key in this.programConfigurations){this.programConfigurations[key].populatePaintArrays(length,feature,imagePositions,canonical,formattedSection)}if(feature.id!==undefined){this._featureMap.add(feature.id,index,this._bufferOffset,length)}this._bufferOffset=length;this.needsUpload=true}updatePaintArrays(featureStates,vtLayer,layers,imagePositions){for(const layer of layers){this.needsUpload=this.programConfigurations[layer.id].updatePaintArrays(featureStates,this._featureMap,vtLayer,layer,imagePositions)||this.needsUpload}}get(layerId){return this.programConfigurations[layerId]}upload(context){if(!this.needsUpload)return;for(const layerId in this.programConfigurations){this.programConfigurations[layerId].upload(context)}this.needsUpload=false}destroy(){for(const layerId in this.programConfigurations){this.programConfigurations[layerId].destroy()}}}function paintAttributeNames(property,type){const attributeNameExceptions={"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"line-gap-width":["gapwidth"],"line-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-extrusion-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"]};return attributeNameExceptions[property]||[property.replace(`${type}-`,"").replace(/-/g,"_")]}function getLayoutException(property){const propertyExceptions={"line-pattern":{source:PatternLayoutArray,composite:PatternLayoutArray},"fill-pattern":{source:PatternLayoutArray,composite:PatternLayoutArray},"fill-extrusion-pattern":{source:PatternLayoutArray,composite:PatternLayoutArray}};return propertyExceptions[property]}function layoutType(property,type,binderType){const defaultLayouts={color:{source:StructArrayLayout2f8,composite:StructArrayLayout4f16},number:{source:StructArrayLayout1f4,composite:StructArrayLayout2f8}};const layoutException=getLayoutException(property);return layoutException&&layoutException[binderType]||defaultLayouts[type][binderType]}register("ConstantBinder",ConstantBinder);register("CrossFadedConstantBinder",CrossFadedConstantBinder);register("SourceExpressionBinder",SourceExpressionBinder);register("CrossFadedCompositeBinder",CrossFadedCompositeBinder);register("CompositeExpressionBinder",CompositeExpressionBinder);register("ProgramConfiguration",ProgramConfiguration,{omit:["_buffers"]});register("ProgramConfigurationSet",ProgramConfigurationSet);const EXTENT=8192;const BITS=15;const MAX=Math.pow(2,BITS-1)-1;const MIN=-MAX-1;function loadGeometry(feature){const scale=EXTENT/feature.extent;const geometry=feature.loadGeometry();for(let r=0;rpoint.x+1||ypoint.y+1){warnOnce("Geometry exceeds allowed extent, reduce your vector tile buffer size")}}}return geometry}function toEvaluationFeature(feature,needGeometry){return{type:feature.type,id:feature.id,properties:feature.properties,geometry:needGeometry?loadGeometry(feature):[]}}function addCircleVertex(layoutVertexArray,x,y,extrudeX,extrudeY){layoutVertexArray.emplaceBack(x*2+(extrudeX+1)/2,y*2+(extrudeY+1)/2)}class CircleBucket{constructor(options){this.zoom=options.zoom;this.overscaling=options.overscaling;this.layers=options.layers;this.layerIds=this.layers.map((layer=>layer.id));this.index=options.index;this.hasPattern=false;this.layoutVertexArray=new CircleLayoutArray;this.indexArray=new TriangleIndexArray;this.segments=new SegmentVector;this.programConfigurations=new ProgramConfigurationSet(options.layers,options.zoom);this.stateDependentLayerIds=this.layers.filter((l=>l.isStateDependent())).map((l=>l.id))}populate(features,options,canonical){const styleLayer=this.layers[0];const bucketFeatures=[];let circleSortKey=null;let sortFeaturesByKey=false;if(styleLayer.type==="circle"){circleSortKey=styleLayer.layout.get("circle-sort-key");sortFeaturesByKey=!circleSortKey.isConstant()}for(const{feature:feature,id:id,index:index,sourceLayerIndex:sourceLayerIndex}of features){const needGeometry=this.layers[0]._featureFilter.needGeometry;const evaluationFeature=toEvaluationFeature(feature,needGeometry);if(!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom),evaluationFeature,canonical))continue;const sortKey=sortFeaturesByKey?circleSortKey.evaluate(evaluationFeature,{},canonical):undefined;const bucketFeature={id:id,properties:feature.properties,type:feature.type,sourceLayerIndex:sourceLayerIndex,index:index,geometry:needGeometry?evaluationFeature.geometry:loadGeometry(feature),patterns:{},sortKey:sortKey};bucketFeatures.push(bucketFeature)}if(sortFeaturesByKey){bucketFeatures.sort(((a,b)=>a.sortKey-b.sortKey))}for(const bucketFeature of bucketFeatures){const{geometry:geometry,index:index,sourceLayerIndex:sourceLayerIndex}=bucketFeature;const feature=features[index].feature;this.addFeature(bucketFeature,geometry,index,canonical);options.featureIndex.insert(feature,geometry,index,sourceLayerIndex,this.index)}}update(states,vtLayer,imagePositions){if(!this.stateDependentLayers.length)return;this.programConfigurations.updatePaintArrays(states,vtLayer,this.stateDependentLayers,imagePositions)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(context){if(!this.uploaded){this.layoutVertexBuffer=context.createVertexBuffer(this.layoutVertexArray,members$4);this.indexBuffer=context.createIndexBuffer(this.indexArray)}this.programConfigurations.upload(context);this.uploaded=true}destroy(){if(!this.layoutVertexBuffer)return;this.layoutVertexBuffer.destroy();this.indexBuffer.destroy();this.programConfigurations.destroy();this.segments.destroy()}addFeature(feature,geometry,index,canonical){for(const ring of geometry){for(const point of ring){const x=point.x;const y=point.y;if(x<0||x>=EXTENT||y<0||y>=EXTENT)continue;const segment=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,feature.sortKey);const index=segment.vertexLength;addCircleVertex(this.layoutVertexArray,x,y,-1,-1);addCircleVertex(this.layoutVertexArray,x,y,1,-1);addCircleVertex(this.layoutVertexArray,x,y,1,1);addCircleVertex(this.layoutVertexArray,x,y,-1,1);this.indexArray.emplaceBack(index,index+1,index+2);this.indexArray.emplaceBack(index,index+3,index+2);segment.vertexLength+=4;segment.primitiveLength+=2}}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,feature,index,{},canonical)}}register("CircleBucket",CircleBucket,{omit:["layers"]});function polygonIntersectsPolygon(polygonA,polygonB){for(let i=0;i=3){for(let k=0;k1){if(lineIntersectsLine(lineA,lineB))return true;for(let j=0;j1)return p.distSqr(w);return p.distSqr(w.sub(v)._mult(t)._add(v))}function multiPolygonContainsPoint(rings,p){let c=false,ring,p1,p2;for(let k=0;kp.y!==p2.y>p.y&&p.x<(p2.x-p1.x)*(p.y-p1.y)/(p2.y-p1.y)+p1.x){c=!c}}}return c}function polygonContainsPoint(ring,p){let c=false;for(let i=0,j=ring.length-1;ip.y!==p2.y>p.y&&p.x<(p2.x-p1.x)*(p.y-p1.y)/(p2.y-p1.y)+p1.x){c=!c}}return c}function polygonIntersectsBox(ring,boxX1,boxY1,boxX2,boxY2){for(const p of ring){if(boxX1<=p.x&&boxY1<=p.y&&boxX2>=p.x&&boxY2>=p.y)return true}const corners=[new Point$2(boxX1,boxY1),new Point$2(boxX1,boxY2),new Point$2(boxX2,boxY2),new Point$2(boxX2,boxY1)];if(ring.length>2){for(const corner of corners){if(polygonContainsPoint(ring,corner))return true}}for(let i=0;ibr.x&&e2.x>br.x||e1.ybr.y&&e2.y>br.y)return false;const dir=isCounterClockwise(e1,e2,corners[0]);return dir!==isCounterClockwise(e1,e2,corners[1])||dir!==isCounterClockwise(e1,e2,corners[2])||dir!==isCounterClockwise(e1,e2,corners[3])}function getMaximumPaintValue(property,layer,bucket){const value=layer.paint.get(property).value;if(value.kind==="constant"){return value.value}else{return bucket.programConfigurations.get(layer.id).getMaxValue(property)}}function translateDistance(translate){return Math.sqrt(translate[0]*translate[0]+translate[1]*translate[1])}function translate$4(queryGeometry,translate,translateAnchor,bearing,pixelsToTileUnits){if(!translate[0]&&!translate[1]){return queryGeometry}const pt=Point$2.convert(translate)._mult(pixelsToTileUnits);if(translateAnchor==="viewport"){pt._rotate(-bearing)}const translated=[];for(let i=0;ilayout$5=layout$5||new Properties({"circle-sort-key":new DataDrivenProperty(v8Spec["layout_circle"]["circle-sort-key"])});let paint$8;const getPaint$8=()=>paint$8=paint$8||new Properties({"circle-radius":new DataDrivenProperty(v8Spec["paint_circle"]["circle-radius"]),"circle-color":new DataDrivenProperty(v8Spec["paint_circle"]["circle-color"]),"circle-blur":new DataDrivenProperty(v8Spec["paint_circle"]["circle-blur"]),"circle-opacity":new DataDrivenProperty(v8Spec["paint_circle"]["circle-opacity"]),"circle-translate":new DataConstantProperty(v8Spec["paint_circle"]["circle-translate"]),"circle-translate-anchor":new DataConstantProperty(v8Spec["paint_circle"]["circle-translate-anchor"]),"circle-pitch-scale":new DataConstantProperty(v8Spec["paint_circle"]["circle-pitch-scale"]),"circle-pitch-alignment":new DataConstantProperty(v8Spec["paint_circle"]["circle-pitch-alignment"]),"circle-stroke-width":new DataDrivenProperty(v8Spec["paint_circle"]["circle-stroke-width"]),"circle-stroke-color":new DataDrivenProperty(v8Spec["paint_circle"]["circle-stroke-color"]),"circle-stroke-opacity":new DataDrivenProperty(v8Spec["paint_circle"]["circle-stroke-opacity"])});var properties$8={get paint(){return getPaint$8()},get layout(){return getLayout$3()}};var EPSILON=1e-6;var ARRAY_TYPE=typeof Float32Array!=="undefined"?Float32Array:Array;var RANDOM=Math.random;function setMatrixArrayType(type){ARRAY_TYPE=type}var degree=Math.PI/180;function toRadian(a){return a*degree}function equals$a(a,b){return Math.abs(a-b)<=EPSILON*Math.max(1,Math.abs(a),Math.abs(b))}if(!Math.hypot)Math.hypot=function(){var y=0,i=arguments.length;while(i--){y+=arguments[i]*arguments[i]}return Math.sqrt(y)};var common=Object.freeze({__proto__:null,get ARRAY_TYPE(){return ARRAY_TYPE},EPSILON:EPSILON,RANDOM:RANDOM,equals:equals$a,setMatrixArrayType:setMatrixArrayType,toRadian:toRadian});function create$8(){var out=new ARRAY_TYPE(4);if(ARRAY_TYPE!=Float32Array){out[1]=0;out[2]=0}out[0]=1;out[3]=1;return out}function clone$8(a){var out=new ARRAY_TYPE(4);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];return out}function copy$8(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];return out}function identity$5(out){out[0]=1;out[1]=0;out[2]=0;out[3]=1;return out}function fromValues$8(m00,m01,m10,m11){var out=new ARRAY_TYPE(4);out[0]=m00;out[1]=m01;out[2]=m10;out[3]=m11;return out}function set$8(out,m00,m01,m10,m11){out[0]=m00;out[1]=m01;out[2]=m10;out[3]=m11;return out}function transpose$2(out,a){if(out===a){var a1=a[1];out[1]=a[2];out[2]=a1}else{out[0]=a[0];out[1]=a[2];out[2]=a[1];out[3]=a[3]}return out}function invert$5(out,a){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var det=a0*a3-a2*a1;if(!det){return null}det=1/det;out[0]=a3*det;out[1]=-a1*det;out[2]=-a2*det;out[3]=a0*det;return out}function adjoint$2(out,a){var a0=a[0];out[0]=a[3];out[1]=-a[1];out[2]=-a[2];out[3]=a0;return out}function determinant$3(a){return a[0]*a[3]-a[2]*a[1]}function multiply$8(out,a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var b0=b[0],b1=b[1],b2=b[2],b3=b[3];out[0]=a0*b0+a2*b1;out[1]=a1*b0+a3*b1;out[2]=a0*b2+a2*b3;out[3]=a1*b2+a3*b3;return out}function rotate$4(out,a,rad){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var s=Math.sin(rad);var c=Math.cos(rad);out[0]=a0*c+a2*s;out[1]=a1*c+a3*s;out[2]=a0*-s+a2*c;out[3]=a1*-s+a3*c;return out}function scale$8(out,a,v){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var v0=v[0],v1=v[1];out[0]=a0*v0;out[1]=a1*v0;out[2]=a2*v1;out[3]=a3*v1;return out}function fromRotation$4(out,rad){var s=Math.sin(rad);var c=Math.cos(rad);out[0]=c;out[1]=s;out[2]=-s;out[3]=c;return out}function fromScaling$3(out,v){out[0]=v[0];out[1]=0;out[2]=0;out[3]=v[1];return out}function str$8(a){return"mat2("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+")"}function frob$3(a){return Math.hypot(a[0],a[1],a[2],a[3])}function LDU(L,D,U,a){L[2]=a[2]/a[0];U[0]=a[0];U[1]=a[1];U[3]=a[3]-L[2]*U[1];return[L,D,U]}function add$8(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=a[2]+b[2];out[3]=a[3]+b[3];return out}function subtract$6(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];out[2]=a[2]-b[2];out[3]=a[3]-b[3];return out}function exactEquals$8(a,b){return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]}function equals$9(a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var b0=b[0],b1=b[1],b2=b[2],b3=b[3];return Math.abs(a0-b0)<=EPSILON*Math.max(1,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=EPSILON*Math.max(1,Math.abs(a1),Math.abs(b1))&&Math.abs(a2-b2)<=EPSILON*Math.max(1,Math.abs(a2),Math.abs(b2))&&Math.abs(a3-b3)<=EPSILON*Math.max(1,Math.abs(a3),Math.abs(b3))}function multiplyScalar$3(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;out[3]=a[3]*b;return out}function multiplyScalarAndAdd$3(out,a,b,scale){out[0]=a[0]+b[0]*scale;out[1]=a[1]+b[1]*scale;out[2]=a[2]+b[2]*scale;out[3]=a[3]+b[3]*scale;return out}var mul$8=multiply$8;var sub$6=subtract$6;var mat2=Object.freeze({__proto__:null,LDU:LDU,add:add$8,adjoint:adjoint$2,clone:clone$8,copy:copy$8,create:create$8,determinant:determinant$3,equals:equals$9,exactEquals:exactEquals$8,frob:frob$3,fromRotation:fromRotation$4,fromScaling:fromScaling$3,fromValues:fromValues$8,identity:identity$5,invert:invert$5,mul:mul$8,multiply:multiply$8,multiplyScalar:multiplyScalar$3,multiplyScalarAndAdd:multiplyScalarAndAdd$3,rotate:rotate$4,scale:scale$8,set:set$8,str:str$8,sub:sub$6,subtract:subtract$6,transpose:transpose$2});function create$7(){var out=new ARRAY_TYPE(6);if(ARRAY_TYPE!=Float32Array){out[1]=0;out[2]=0;out[4]=0;out[5]=0}out[0]=1;out[3]=1;return out}function clone$7(a){var out=new ARRAY_TYPE(6);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];return out}function copy$7(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];return out}function identity$4(out){out[0]=1;out[1]=0;out[2]=0;out[3]=1;out[4]=0;out[5]=0;return out}function fromValues$7(a,b,c,d,tx,ty){var out=new ARRAY_TYPE(6);out[0]=a;out[1]=b;out[2]=c;out[3]=d;out[4]=tx;out[5]=ty;return out}function set$7(out,a,b,c,d,tx,ty){out[0]=a;out[1]=b;out[2]=c;out[3]=d;out[4]=tx;out[5]=ty;return out}function invert$4(out,a){var aa=a[0],ab=a[1],ac=a[2],ad=a[3];var atx=a[4],aty=a[5];var det=aa*ad-ab*ac;if(!det){return null}det=1/det;out[0]=ad*det;out[1]=-ab*det;out[2]=-ac*det;out[3]=aa*det;out[4]=(ac*aty-ad*atx)*det;out[5]=(ab*atx-aa*aty)*det;return out}function determinant$2(a){return a[0]*a[3]-a[1]*a[2]}function multiply$7(out,a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5];var b0=b[0],b1=b[1],b2=b[2],b3=b[3],b4=b[4],b5=b[5];out[0]=a0*b0+a2*b1;out[1]=a1*b0+a3*b1;out[2]=a0*b2+a2*b3;out[3]=a1*b2+a3*b3;out[4]=a0*b4+a2*b5+a4;out[5]=a1*b4+a3*b5+a5;return out}function rotate$3(out,a,rad){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5];var s=Math.sin(rad);var c=Math.cos(rad);out[0]=a0*c+a2*s;out[1]=a1*c+a3*s;out[2]=a0*-s+a2*c;out[3]=a1*-s+a3*c;out[4]=a4;out[5]=a5;return out}function scale$7(out,a,v){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5];var v0=v[0],v1=v[1];out[0]=a0*v0;out[1]=a1*v0;out[2]=a2*v1;out[3]=a3*v1;out[4]=a4;out[5]=a5;return out}function translate$3(out,a,v){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5];var v0=v[0],v1=v[1];out[0]=a0;out[1]=a1;out[2]=a2;out[3]=a3;out[4]=a0*v0+a2*v1+a4;out[5]=a1*v0+a3*v1+a5;return out}function fromRotation$3(out,rad){var s=Math.sin(rad),c=Math.cos(rad);out[0]=c;out[1]=s;out[2]=-s;out[3]=c;out[4]=0;out[5]=0;return out}function fromScaling$2(out,v){out[0]=v[0];out[1]=0;out[2]=0;out[3]=v[1];out[4]=0;out[5]=0;return out}function fromTranslation$3(out,v){out[0]=1;out[1]=0;out[2]=0;out[3]=1;out[4]=v[0];out[5]=v[1];return out}function str$7(a){return"mat2d("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+", "+a[4]+", "+a[5]+")"}function frob$2(a){return Math.hypot(a[0],a[1],a[2],a[3],a[4],a[5],1)}function add$7(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=a[2]+b[2];out[3]=a[3]+b[3];out[4]=a[4]+b[4];out[5]=a[5]+b[5];return out}function subtract$5(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];out[2]=a[2]-b[2];out[3]=a[3]-b[3];out[4]=a[4]-b[4];out[5]=a[5]-b[5];return out}function multiplyScalar$2(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;out[3]=a[3]*b;out[4]=a[4]*b;out[5]=a[5]*b;return out}function multiplyScalarAndAdd$2(out,a,b,scale){out[0]=a[0]+b[0]*scale;out[1]=a[1]+b[1]*scale;out[2]=a[2]+b[2]*scale;out[3]=a[3]+b[3]*scale;out[4]=a[4]+b[4]*scale;out[5]=a[5]+b[5]*scale;return out}function exactEquals$7(a,b){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]}function equals$8(a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5];var b0=b[0],b1=b[1],b2=b[2],b3=b[3],b4=b[4],b5=b[5];return Math.abs(a0-b0)<=EPSILON*Math.max(1,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=EPSILON*Math.max(1,Math.abs(a1),Math.abs(b1))&&Math.abs(a2-b2)<=EPSILON*Math.max(1,Math.abs(a2),Math.abs(b2))&&Math.abs(a3-b3)<=EPSILON*Math.max(1,Math.abs(a3),Math.abs(b3))&&Math.abs(a4-b4)<=EPSILON*Math.max(1,Math.abs(a4),Math.abs(b4))&&Math.abs(a5-b5)<=EPSILON*Math.max(1,Math.abs(a5),Math.abs(b5))}var mul$7=multiply$7;var sub$5=subtract$5;var mat2d=Object.freeze({__proto__:null,add:add$7,clone:clone$7,copy:copy$7,create:create$7,determinant:determinant$2,equals:equals$8,exactEquals:exactEquals$7,frob:frob$2,fromRotation:fromRotation$3,fromScaling:fromScaling$2,fromTranslation:fromTranslation$3,fromValues:fromValues$7,identity:identity$4,invert:invert$4,mul:mul$7,multiply:multiply$7,multiplyScalar:multiplyScalar$2,multiplyScalarAndAdd:multiplyScalarAndAdd$2,rotate:rotate$3,scale:scale$7,set:set$7,str:str$7,sub:sub$5,subtract:subtract$5,translate:translate$3});function create$6(){var out=new ARRAY_TYPE(9);if(ARRAY_TYPE!=Float32Array){out[1]=0;out[2]=0;out[3]=0;out[5]=0;out[6]=0;out[7]=0}out[0]=1;out[4]=1;out[8]=1;return out}function fromMat4$1(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[4];out[4]=a[5];out[5]=a[6];out[6]=a[8];out[7]=a[9];out[8]=a[10];return out}function clone$6(a){var out=new ARRAY_TYPE(9);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];return out}function copy$6(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];return out}function fromValues$6(m00,m01,m02,m10,m11,m12,m20,m21,m22){var out=new ARRAY_TYPE(9);out[0]=m00;out[1]=m01;out[2]=m02;out[3]=m10;out[4]=m11;out[5]=m12;out[6]=m20;out[7]=m21;out[8]=m22;return out}function set$6(out,m00,m01,m02,m10,m11,m12,m20,m21,m22){out[0]=m00;out[1]=m01;out[2]=m02;out[3]=m10;out[4]=m11;out[5]=m12;out[6]=m20;out[7]=m21;out[8]=m22;return out}function identity$3(out){out[0]=1;out[1]=0;out[2]=0;out[3]=0;out[4]=1;out[5]=0;out[6]=0;out[7]=0;out[8]=1;return out}function transpose$1(out,a){if(out===a){var a01=a[1],a02=a[2],a12=a[5];out[1]=a[3];out[2]=a[6];out[3]=a01;out[5]=a[7];out[6]=a02;out[7]=a12}else{out[0]=a[0];out[1]=a[3];out[2]=a[6];out[3]=a[1];out[4]=a[4];out[5]=a[7];out[6]=a[2];out[7]=a[5];out[8]=a[8]}return out}function invert$3(out,a){var a00=a[0],a01=a[1],a02=a[2];var a10=a[3],a11=a[4],a12=a[5];var a20=a[6],a21=a[7],a22=a[8];var b01=a22*a11-a12*a21;var b11=-a22*a10+a12*a20;var b21=a21*a10-a11*a20;var det=a00*b01+a01*b11+a02*b21;if(!det){return null}det=1/det;out[0]=b01*det;out[1]=(-a22*a01+a02*a21)*det;out[2]=(a12*a01-a02*a11)*det;out[3]=b11*det;out[4]=(a22*a00-a02*a20)*det;out[5]=(-a12*a00+a02*a10)*det;out[6]=b21*det;out[7]=(-a21*a00+a01*a20)*det;out[8]=(a11*a00-a01*a10)*det;return out}function adjoint$1(out,a){var a00=a[0],a01=a[1],a02=a[2];var a10=a[3],a11=a[4],a12=a[5];var a20=a[6],a21=a[7],a22=a[8];out[0]=a11*a22-a12*a21;out[1]=a02*a21-a01*a22;out[2]=a01*a12-a02*a11;out[3]=a12*a20-a10*a22;out[4]=a00*a22-a02*a20;out[5]=a02*a10-a00*a12;out[6]=a10*a21-a11*a20;out[7]=a01*a20-a00*a21;out[8]=a00*a11-a01*a10;return out}function determinant$1(a){var a00=a[0],a01=a[1],a02=a[2];var a10=a[3],a11=a[4],a12=a[5];var a20=a[6],a21=a[7],a22=a[8];return a00*(a22*a11-a12*a21)+a01*(-a22*a10+a12*a20)+a02*(a21*a10-a11*a20)}function multiply$6(out,a,b){var a00=a[0],a01=a[1],a02=a[2];var a10=a[3],a11=a[4],a12=a[5];var a20=a[6],a21=a[7],a22=a[8];var b00=b[0],b01=b[1],b02=b[2];var b10=b[3],b11=b[4],b12=b[5];var b20=b[6],b21=b[7],b22=b[8];out[0]=b00*a00+b01*a10+b02*a20;out[1]=b00*a01+b01*a11+b02*a21;out[2]=b00*a02+b01*a12+b02*a22;out[3]=b10*a00+b11*a10+b12*a20;out[4]=b10*a01+b11*a11+b12*a21;out[5]=b10*a02+b11*a12+b12*a22;out[6]=b20*a00+b21*a10+b22*a20;out[7]=b20*a01+b21*a11+b22*a21;out[8]=b20*a02+b21*a12+b22*a22;return out}function translate$2(out,a,v){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8],x=v[0],y=v[1];out[0]=a00;out[1]=a01;out[2]=a02;out[3]=a10;out[4]=a11;out[5]=a12;out[6]=x*a00+y*a10+a20;out[7]=x*a01+y*a11+a21;out[8]=x*a02+y*a12+a22;return out}function rotate$2(out,a,rad){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8],s=Math.sin(rad),c=Math.cos(rad);out[0]=c*a00+s*a10;out[1]=c*a01+s*a11;out[2]=c*a02+s*a12;out[3]=c*a10-s*a00;out[4]=c*a11-s*a01;out[5]=c*a12-s*a02;out[6]=a20;out[7]=a21;out[8]=a22;return out}function scale$6(out,a,v){var x=v[0],y=v[1];out[0]=x*a[0];out[1]=x*a[1];out[2]=x*a[2];out[3]=y*a[3];out[4]=y*a[4];out[5]=y*a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];return out}function fromTranslation$2(out,v){out[0]=1;out[1]=0;out[2]=0;out[3]=0;out[4]=1;out[5]=0;out[6]=v[0];out[7]=v[1];out[8]=1;return out}function fromRotation$2(out,rad){var s=Math.sin(rad),c=Math.cos(rad);out[0]=c;out[1]=s;out[2]=0;out[3]=-s;out[4]=c;out[5]=0;out[6]=0;out[7]=0;out[8]=1;return out}function fromScaling$1(out,v){out[0]=v[0];out[1]=0;out[2]=0;out[3]=0;out[4]=v[1];out[5]=0;out[6]=0;out[7]=0;out[8]=1;return out}function fromMat2d(out,a){out[0]=a[0];out[1]=a[1];out[2]=0;out[3]=a[2];out[4]=a[3];out[5]=0;out[6]=a[4];out[7]=a[5];out[8]=1;return out}function fromQuat$1(out,q){var x=q[0],y=q[1],z=q[2],w=q[3];var x2=x+x;var y2=y+y;var z2=z+z;var xx=x*x2;var yx=y*x2;var yy=y*y2;var zx=z*x2;var zy=z*y2;var zz=z*z2;var wx=w*x2;var wy=w*y2;var wz=w*z2;out[0]=1-yy-zz;out[3]=yx-wz;out[6]=zx+wy;out[1]=yx+wz;out[4]=1-xx-zz;out[7]=zy-wx;out[2]=zx-wy;out[5]=zy+wx;out[8]=1-xx-yy;return out}function normalFromMat4(out,a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3];var a10=a[4],a11=a[5],a12=a[6],a13=a[7];var a20=a[8],a21=a[9],a22=a[10],a23=a[11];var a30=a[12],a31=a[13],a32=a[14],a33=a[15];var b00=a00*a11-a01*a10;var b01=a00*a12-a02*a10;var b02=a00*a13-a03*a10;var b03=a01*a12-a02*a11;var b04=a01*a13-a03*a11;var b05=a02*a13-a03*a12;var b06=a20*a31-a21*a30;var b07=a20*a32-a22*a30;var b08=a20*a33-a23*a30;var b09=a21*a32-a22*a31;var b10=a21*a33-a23*a31;var b11=a22*a33-a23*a32;var det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;if(!det){return null}det=1/det;out[0]=(a11*b11-a12*b10+a13*b09)*det;out[1]=(a12*b08-a10*b11-a13*b07)*det;out[2]=(a10*b10-a11*b08+a13*b06)*det;out[3]=(a02*b10-a01*b11-a03*b09)*det;out[4]=(a00*b11-a02*b08+a03*b07)*det;out[5]=(a01*b08-a00*b10-a03*b06)*det;out[6]=(a31*b05-a32*b04+a33*b03)*det;out[7]=(a32*b02-a30*b05-a33*b01)*det;out[8]=(a30*b04-a31*b02+a33*b00)*det;return out}function projection(out,width,height){out[0]=2/width;out[1]=0;out[2]=0;out[3]=0;out[4]=-2/height;out[5]=0;out[6]=-1;out[7]=1;out[8]=1;return out}function str$6(a){return"mat3("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+", "+a[4]+", "+a[5]+", "+a[6]+", "+a[7]+", "+a[8]+")"}function frob$1(a){return Math.hypot(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8])}function add$6(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=a[2]+b[2];out[3]=a[3]+b[3];out[4]=a[4]+b[4];out[5]=a[5]+b[5];out[6]=a[6]+b[6];out[7]=a[7]+b[7];out[8]=a[8]+b[8];return out}function subtract$4(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];out[2]=a[2]-b[2];out[3]=a[3]-b[3];out[4]=a[4]-b[4];out[5]=a[5]-b[5];out[6]=a[6]-b[6];out[7]=a[7]-b[7];out[8]=a[8]-b[8];return out}function multiplyScalar$1(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;out[3]=a[3]*b;out[4]=a[4]*b;out[5]=a[5]*b;out[6]=a[6]*b;out[7]=a[7]*b;out[8]=a[8]*b;return out}function multiplyScalarAndAdd$1(out,a,b,scale){out[0]=a[0]+b[0]*scale;out[1]=a[1]+b[1]*scale;out[2]=a[2]+b[2]*scale;out[3]=a[3]+b[3]*scale;out[4]=a[4]+b[4]*scale;out[5]=a[5]+b[5]*scale;out[6]=a[6]+b[6]*scale;out[7]=a[7]+b[7]*scale;out[8]=a[8]+b[8]*scale;return out}function exactEquals$6(a,b){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]}function equals$7(a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5],a6=a[6],a7=a[7],a8=a[8];var b0=b[0],b1=b[1],b2=b[2],b3=b[3],b4=b[4],b5=b[5],b6=b[6],b7=b[7],b8=b[8];return Math.abs(a0-b0)<=EPSILON*Math.max(1,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=EPSILON*Math.max(1,Math.abs(a1),Math.abs(b1))&&Math.abs(a2-b2)<=EPSILON*Math.max(1,Math.abs(a2),Math.abs(b2))&&Math.abs(a3-b3)<=EPSILON*Math.max(1,Math.abs(a3),Math.abs(b3))&&Math.abs(a4-b4)<=EPSILON*Math.max(1,Math.abs(a4),Math.abs(b4))&&Math.abs(a5-b5)<=EPSILON*Math.max(1,Math.abs(a5),Math.abs(b5))&&Math.abs(a6-b6)<=EPSILON*Math.max(1,Math.abs(a6),Math.abs(b6))&&Math.abs(a7-b7)<=EPSILON*Math.max(1,Math.abs(a7),Math.abs(b7))&&Math.abs(a8-b8)<=EPSILON*Math.max(1,Math.abs(a8),Math.abs(b8))}var mul$6=multiply$6;var sub$4=subtract$4;var mat3=Object.freeze({__proto__:null,add:add$6,adjoint:adjoint$1,clone:clone$6,copy:copy$6,create:create$6,determinant:determinant$1,equals:equals$7,exactEquals:exactEquals$6,frob:frob$1,fromMat2d:fromMat2d,fromMat4:fromMat4$1,fromQuat:fromQuat$1,fromRotation:fromRotation$2,fromScaling:fromScaling$1,fromTranslation:fromTranslation$2,fromValues:fromValues$6,identity:identity$3,invert:invert$3,mul:mul$6,multiply:multiply$6,multiplyScalar:multiplyScalar$1,multiplyScalarAndAdd:multiplyScalarAndAdd$1,normalFromMat4:normalFromMat4,projection:projection,rotate:rotate$2,scale:scale$6,set:set$6,str:str$6,sub:sub$4,subtract:subtract$4,translate:translate$2,transpose:transpose$1});function create$5(){var out=new ARRAY_TYPE(16);if(ARRAY_TYPE!=Float32Array){out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[11]=0;out[12]=0;out[13]=0;out[14]=0}out[0]=1;out[5]=1;out[10]=1;out[15]=1;return out}function clone$5(a){var out=new ARRAY_TYPE(16);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];out[9]=a[9];out[10]=a[10];out[11]=a[11];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];return out}function copy$5(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];out[9]=a[9];out[10]=a[10];out[11]=a[11];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];return out}function fromValues$5(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33){var out=new ARRAY_TYPE(16);out[0]=m00;out[1]=m01;out[2]=m02;out[3]=m03;out[4]=m10;out[5]=m11;out[6]=m12;out[7]=m13;out[8]=m20;out[9]=m21;out[10]=m22;out[11]=m23;out[12]=m30;out[13]=m31;out[14]=m32;out[15]=m33;return out}function set$5(out,m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33){out[0]=m00;out[1]=m01;out[2]=m02;out[3]=m03;out[4]=m10;out[5]=m11;out[6]=m12;out[7]=m13;out[8]=m20;out[9]=m21;out[10]=m22;out[11]=m23;out[12]=m30;out[13]=m31;out[14]=m32;out[15]=m33;return out}function identity$2(out){out[0]=1;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=1;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=1;out[11]=0;out[12]=0;out[13]=0;out[14]=0;out[15]=1;return out}function transpose(out,a){if(out===a){var a01=a[1],a02=a[2],a03=a[3];var a12=a[6],a13=a[7];var a23=a[11];out[1]=a[4];out[2]=a[8];out[3]=a[12];out[4]=a01;out[6]=a[9];out[7]=a[13];out[8]=a02;out[9]=a12;out[11]=a[14];out[12]=a03;out[13]=a13;out[14]=a23}else{out[0]=a[0];out[1]=a[4];out[2]=a[8];out[3]=a[12];out[4]=a[1];out[5]=a[5];out[6]=a[9];out[7]=a[13];out[8]=a[2];out[9]=a[6];out[10]=a[10];out[11]=a[14];out[12]=a[3];out[13]=a[7];out[14]=a[11];out[15]=a[15]}return out}function invert$2(out,a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3];var a10=a[4],a11=a[5],a12=a[6],a13=a[7];var a20=a[8],a21=a[9],a22=a[10],a23=a[11];var a30=a[12],a31=a[13],a32=a[14],a33=a[15];var b00=a00*a11-a01*a10;var b01=a00*a12-a02*a10;var b02=a00*a13-a03*a10;var b03=a01*a12-a02*a11;var b04=a01*a13-a03*a11;var b05=a02*a13-a03*a12;var b06=a20*a31-a21*a30;var b07=a20*a32-a22*a30;var b08=a20*a33-a23*a30;var b09=a21*a32-a22*a31;var b10=a21*a33-a23*a31;var b11=a22*a33-a23*a32;var det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;if(!det){return null}det=1/det;out[0]=(a11*b11-a12*b10+a13*b09)*det;out[1]=(a02*b10-a01*b11-a03*b09)*det;out[2]=(a31*b05-a32*b04+a33*b03)*det;out[3]=(a22*b04-a21*b05-a23*b03)*det;out[4]=(a12*b08-a10*b11-a13*b07)*det;out[5]=(a00*b11-a02*b08+a03*b07)*det;out[6]=(a32*b02-a30*b05-a33*b01)*det;out[7]=(a20*b05-a22*b02+a23*b01)*det;out[8]=(a10*b10-a11*b08+a13*b06)*det;out[9]=(a01*b08-a00*b10-a03*b06)*det;out[10]=(a30*b04-a31*b02+a33*b00)*det;out[11]=(a21*b02-a20*b04-a23*b00)*det;out[12]=(a11*b07-a10*b09-a12*b06)*det;out[13]=(a00*b09-a01*b07+a02*b06)*det;out[14]=(a31*b01-a30*b03-a32*b00)*det;out[15]=(a20*b03-a21*b01+a22*b00)*det;return out}function adjoint(out,a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3];var a10=a[4],a11=a[5],a12=a[6],a13=a[7];var a20=a[8],a21=a[9],a22=a[10],a23=a[11];var a30=a[12],a31=a[13],a32=a[14],a33=a[15];out[0]=a11*(a22*a33-a23*a32)-a21*(a12*a33-a13*a32)+a31*(a12*a23-a13*a22);out[1]=-(a01*(a22*a33-a23*a32)-a21*(a02*a33-a03*a32)+a31*(a02*a23-a03*a22));out[2]=a01*(a12*a33-a13*a32)-a11*(a02*a33-a03*a32)+a31*(a02*a13-a03*a12);out[3]=-(a01*(a12*a23-a13*a22)-a11*(a02*a23-a03*a22)+a21*(a02*a13-a03*a12));out[4]=-(a10*(a22*a33-a23*a32)-a20*(a12*a33-a13*a32)+a30*(a12*a23-a13*a22));out[5]=a00*(a22*a33-a23*a32)-a20*(a02*a33-a03*a32)+a30*(a02*a23-a03*a22);out[6]=-(a00*(a12*a33-a13*a32)-a10*(a02*a33-a03*a32)+a30*(a02*a13-a03*a12));out[7]=a00*(a12*a23-a13*a22)-a10*(a02*a23-a03*a22)+a20*(a02*a13-a03*a12);out[8]=a10*(a21*a33-a23*a31)-a20*(a11*a33-a13*a31)+a30*(a11*a23-a13*a21);out[9]=-(a00*(a21*a33-a23*a31)-a20*(a01*a33-a03*a31)+a30*(a01*a23-a03*a21));out[10]=a00*(a11*a33-a13*a31)-a10*(a01*a33-a03*a31)+a30*(a01*a13-a03*a11);out[11]=-(a00*(a11*a23-a13*a21)-a10*(a01*a23-a03*a21)+a20*(a01*a13-a03*a11));out[12]=-(a10*(a21*a32-a22*a31)-a20*(a11*a32-a12*a31)+a30*(a11*a22-a12*a21));out[13]=a00*(a21*a32-a22*a31)-a20*(a01*a32-a02*a31)+a30*(a01*a22-a02*a21);out[14]=-(a00*(a11*a32-a12*a31)-a10*(a01*a32-a02*a31)+a30*(a01*a12-a02*a11));out[15]=a00*(a11*a22-a12*a21)-a10*(a01*a22-a02*a21)+a20*(a01*a12-a02*a11);return out}function determinant(a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3];var a10=a[4],a11=a[5],a12=a[6],a13=a[7];var a20=a[8],a21=a[9],a22=a[10],a23=a[11];var a30=a[12],a31=a[13],a32=a[14],a33=a[15];var b00=a00*a11-a01*a10;var b01=a00*a12-a02*a10;var b02=a00*a13-a03*a10;var b03=a01*a12-a02*a11;var b04=a01*a13-a03*a11;var b05=a02*a13-a03*a12;var b06=a20*a31-a21*a30;var b07=a20*a32-a22*a30;var b08=a20*a33-a23*a30;var b09=a21*a32-a22*a31;var b10=a21*a33-a23*a31;var b11=a22*a33-a23*a32;return b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06}function multiply$5(out,a,b){var a00=a[0],a01=a[1],a02=a[2],a03=a[3];var a10=a[4],a11=a[5],a12=a[6],a13=a[7];var a20=a[8],a21=a[9],a22=a[10],a23=a[11];var a30=a[12],a31=a[13],a32=a[14],a33=a[15];var b0=b[0],b1=b[1],b2=b[2],b3=b[3];out[0]=b0*a00+b1*a10+b2*a20+b3*a30;out[1]=b0*a01+b1*a11+b2*a21+b3*a31;out[2]=b0*a02+b1*a12+b2*a22+b3*a32;out[3]=b0*a03+b1*a13+b2*a23+b3*a33;b0=b[4];b1=b[5];b2=b[6];b3=b[7];out[4]=b0*a00+b1*a10+b2*a20+b3*a30;out[5]=b0*a01+b1*a11+b2*a21+b3*a31;out[6]=b0*a02+b1*a12+b2*a22+b3*a32;out[7]=b0*a03+b1*a13+b2*a23+b3*a33;b0=b[8];b1=b[9];b2=b[10];b3=b[11];out[8]=b0*a00+b1*a10+b2*a20+b3*a30;out[9]=b0*a01+b1*a11+b2*a21+b3*a31;out[10]=b0*a02+b1*a12+b2*a22+b3*a32;out[11]=b0*a03+b1*a13+b2*a23+b3*a33;b0=b[12];b1=b[13];b2=b[14];b3=b[15];out[12]=b0*a00+b1*a10+b2*a20+b3*a30;out[13]=b0*a01+b1*a11+b2*a21+b3*a31;out[14]=b0*a02+b1*a12+b2*a22+b3*a32;out[15]=b0*a03+b1*a13+b2*a23+b3*a33;return out}function translate$1(out,a,v){var x=v[0],y=v[1],z=v[2];var a00,a01,a02,a03;var a10,a11,a12,a13;var a20,a21,a22,a23;if(a===out){out[12]=a[0]*x+a[4]*y+a[8]*z+a[12];out[13]=a[1]*x+a[5]*y+a[9]*z+a[13];out[14]=a[2]*x+a[6]*y+a[10]*z+a[14];out[15]=a[3]*x+a[7]*y+a[11]*z+a[15]}else{a00=a[0];a01=a[1];a02=a[2];a03=a[3];a10=a[4];a11=a[5];a12=a[6];a13=a[7];a20=a[8];a21=a[9];a22=a[10];a23=a[11];out[0]=a00;out[1]=a01;out[2]=a02;out[3]=a03;out[4]=a10;out[5]=a11;out[6]=a12;out[7]=a13;out[8]=a20;out[9]=a21;out[10]=a22;out[11]=a23;out[12]=a00*x+a10*y+a20*z+a[12];out[13]=a01*x+a11*y+a21*z+a[13];out[14]=a02*x+a12*y+a22*z+a[14];out[15]=a03*x+a13*y+a23*z+a[15]}return out}function scale$5(out,a,v){var x=v[0],y=v[1],z=v[2];out[0]=a[0]*x;out[1]=a[1]*x;out[2]=a[2]*x;out[3]=a[3]*x;out[4]=a[4]*y;out[5]=a[5]*y;out[6]=a[6]*y;out[7]=a[7]*y;out[8]=a[8]*z;out[9]=a[9]*z;out[10]=a[10]*z;out[11]=a[11]*z;out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];return out}function rotate$1(out,a,rad,axis){var x=axis[0],y=axis[1],z=axis[2];var len=Math.hypot(x,y,z);var s,c,t;var a00,a01,a02,a03;var a10,a11,a12,a13;var a20,a21,a22,a23;var b00,b01,b02;var b10,b11,b12;var b20,b21,b22;if(len0){translation[0]=(ax*bw+aw*bx+ay*bz-az*by)*2/magnitude;translation[1]=(ay*bw+aw*by+az*bx-ax*bz)*2/magnitude;translation[2]=(az*bw+aw*bz+ax*by-ay*bx)*2/magnitude}else{translation[0]=(ax*bw+aw*bx+ay*bz-az*by)*2;translation[1]=(ay*bw+aw*by+az*bx-ax*bz)*2;translation[2]=(az*bw+aw*bz+ax*by-ay*bx)*2}fromRotationTranslation$1(out,a,translation);return out}function getTranslation$1(out,mat){out[0]=mat[12];out[1]=mat[13];out[2]=mat[14];return out}function getScaling(out,mat){var m11=mat[0];var m12=mat[1];var m13=mat[2];var m21=mat[4];var m22=mat[5];var m23=mat[6];var m31=mat[8];var m32=mat[9];var m33=mat[10];out[0]=Math.hypot(m11,m12,m13);out[1]=Math.hypot(m21,m22,m23);out[2]=Math.hypot(m31,m32,m33);return out}function getRotation(out,mat){var scaling=new ARRAY_TYPE(3);getScaling(scaling,mat);var is1=1/scaling[0];var is2=1/scaling[1];var is3=1/scaling[2];var sm11=mat[0]*is1;var sm12=mat[1]*is2;var sm13=mat[2]*is3;var sm21=mat[4]*is1;var sm22=mat[5]*is2;var sm23=mat[6]*is3;var sm31=mat[8]*is1;var sm32=mat[9]*is2;var sm33=mat[10]*is3;var trace=sm11+sm22+sm33;var S=0;if(trace>0){S=Math.sqrt(trace+1)*2;out[3]=.25*S;out[0]=(sm23-sm32)/S;out[1]=(sm31-sm13)/S;out[2]=(sm12-sm21)/S}else if(sm11>sm22&&sm11>sm33){S=Math.sqrt(1+sm11-sm22-sm33)*2;out[3]=(sm23-sm32)/S;out[0]=.25*S;out[1]=(sm12+sm21)/S;out[2]=(sm31+sm13)/S}else if(sm22>sm33){S=Math.sqrt(1+sm22-sm11-sm33)*2;out[3]=(sm31-sm13)/S;out[0]=(sm12+sm21)/S;out[1]=.25*S;out[2]=(sm23+sm32)/S}else{S=Math.sqrt(1+sm33-sm11-sm22)*2;out[3]=(sm12-sm21)/S;out[0]=(sm31+sm13)/S;out[1]=(sm23+sm32)/S;out[2]=.25*S}return out}function fromRotationTranslationScale(out,q,v,s){var x=q[0],y=q[1],z=q[2],w=q[3];var x2=x+x;var y2=y+y;var z2=z+z;var xx=x*x2;var xy=x*y2;var xz=x*z2;var yy=y*y2;var yz=y*z2;var zz=z*z2;var wx=w*x2;var wy=w*y2;var wz=w*z2;var sx=s[0];var sy=s[1];var sz=s[2];out[0]=(1-(yy+zz))*sx;out[1]=(xy+wz)*sx;out[2]=(xz-wy)*sx;out[3]=0;out[4]=(xy-wz)*sy;out[5]=(1-(xx+zz))*sy;out[6]=(yz+wx)*sy;out[7]=0;out[8]=(xz+wy)*sz;out[9]=(yz-wx)*sz;out[10]=(1-(xx+yy))*sz;out[11]=0;out[12]=v[0];out[13]=v[1];out[14]=v[2];out[15]=1;return out}function fromRotationTranslationScaleOrigin(out,q,v,s,o){var x=q[0],y=q[1],z=q[2],w=q[3];var x2=x+x;var y2=y+y;var z2=z+z;var xx=x*x2;var xy=x*y2;var xz=x*z2;var yy=y*y2;var yz=y*z2;var zz=z*z2;var wx=w*x2;var wy=w*y2;var wz=w*z2;var sx=s[0];var sy=s[1];var sz=s[2];var ox=o[0];var oy=o[1];var oz=o[2];var out0=(1-(yy+zz))*sx;var out1=(xy+wz)*sx;var out2=(xz-wy)*sx;var out4=(xy-wz)*sy;var out5=(1-(xx+zz))*sy;var out6=(yz+wx)*sy;var out8=(xz+wy)*sz;var out9=(yz-wx)*sz;var out10=(1-(xx+yy))*sz;out[0]=out0;out[1]=out1;out[2]=out2;out[3]=0;out[4]=out4;out[5]=out5;out[6]=out6;out[7]=0;out[8]=out8;out[9]=out9;out[10]=out10;out[11]=0;out[12]=v[0]+ox-(out0*ox+out4*oy+out8*oz);out[13]=v[1]+oy-(out1*ox+out5*oy+out9*oz);out[14]=v[2]+oz-(out2*ox+out6*oy+out10*oz);out[15]=1;return out}function fromQuat(out,q){var x=q[0],y=q[1],z=q[2],w=q[3];var x2=x+x;var y2=y+y;var z2=z+z;var xx=x*x2;var yx=y*x2;var yy=y*y2;var zx=z*x2;var zy=z*y2;var zz=z*z2;var wx=w*x2;var wy=w*y2;var wz=w*z2;out[0]=1-yy-zz;out[1]=yx+wz;out[2]=zx-wy;out[3]=0;out[4]=yx-wz;out[5]=1-xx-zz;out[6]=zy+wx;out[7]=0;out[8]=zx+wy;out[9]=zy-wx;out[10]=1-xx-yy;out[11]=0;out[12]=0;out[13]=0;out[14]=0;out[15]=1;return out}function frustum(out,left,right,bottom,top,near,far){var rl=1/(right-left);var tb=1/(top-bottom);var nf=1/(near-far);out[0]=near*2*rl;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=near*2*tb;out[6]=0;out[7]=0;out[8]=(right+left)*rl;out[9]=(top+bottom)*tb;out[10]=(far+near)*nf;out[11]=-1;out[12]=0;out[13]=0;out[14]=far*near*2*nf;out[15]=0;return out}function perspectiveNO(out,fovy,aspect,near,far){var f=1/Math.tan(fovy/2),nf;out[0]=f/aspect;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=f;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[11]=-1;out[12]=0;out[13]=0;out[15]=0;if(far!=null&&far!==Infinity){nf=1/(near-far);out[10]=(far+near)*nf;out[14]=2*far*near*nf}else{out[10]=-1;out[14]=-2*near}return out}var perspective=perspectiveNO;function perspectiveZO(out,fovy,aspect,near,far){var f=1/Math.tan(fovy/2),nf;out[0]=f/aspect;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=f;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[11]=-1;out[12]=0;out[13]=0;out[15]=0;if(far!=null&&far!==Infinity){nf=1/(near-far);out[10]=far*nf;out[14]=far*near*nf}else{out[10]=-1;out[14]=-near}return out}function perspectiveFromFieldOfView(out,fov,near,far){var upTan=Math.tan(fov.upDegrees*Math.PI/180);var downTan=Math.tan(fov.downDegrees*Math.PI/180);var leftTan=Math.tan(fov.leftDegrees*Math.PI/180);var rightTan=Math.tan(fov.rightDegrees*Math.PI/180);var xScale=2/(leftTan+rightTan);var yScale=2/(upTan+downTan);out[0]=xScale;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=yScale;out[6]=0;out[7]=0;out[8]=-((leftTan-rightTan)*xScale*.5);out[9]=(upTan-downTan)*yScale*.5;out[10]=far/(near-far);out[11]=-1;out[12]=0;out[13]=0;out[14]=far*near/(near-far);out[15]=0;return out}function orthoNO(out,left,right,bottom,top,near,far){var lr=1/(left-right);var bt=1/(bottom-top);var nf=1/(near-far);out[0]=-2*lr;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=-2*bt;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=2*nf;out[11]=0;out[12]=(left+right)*lr;out[13]=(top+bottom)*bt;out[14]=(far+near)*nf;out[15]=1;return out}var ortho=orthoNO;function orthoZO(out,left,right,bottom,top,near,far){var lr=1/(left-right);var bt=1/(bottom-top);var nf=1/(near-far);out[0]=-2*lr;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=-2*bt;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=nf;out[11]=0;out[12]=(left+right)*lr;out[13]=(top+bottom)*bt;out[14]=near*nf;out[15]=1;return out}function lookAt(out,eye,center,up){var x0,x1,x2,y0,y1,y2,z0,z1,z2,len;var eyex=eye[0];var eyey=eye[1];var eyez=eye[2];var upx=up[0];var upy=up[1];var upz=up[2];var centerx=center[0];var centery=center[1];var centerz=center[2];if(Math.abs(eyex-centerx)0){len=1/Math.sqrt(len);z0*=len;z1*=len;z2*=len}var x0=upy*z2-upz*z1,x1=upz*z0-upx*z2,x2=upx*z1-upy*z0;len=x0*x0+x1*x1+x2*x2;if(len>0){len=1/Math.sqrt(len);x0*=len;x1*=len;x2*=len}out[0]=x0;out[1]=x1;out[2]=x2;out[3]=0;out[4]=z1*x2-z2*x1;out[5]=z2*x0-z0*x2;out[6]=z0*x1-z1*x0;out[7]=0;out[8]=z0;out[9]=z1;out[10]=z2;out[11]=0;out[12]=eyex;out[13]=eyey;out[14]=eyez;out[15]=1;return out}function str$5(a){return"mat4("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+", "+a[4]+", "+a[5]+", "+a[6]+", "+a[7]+", "+a[8]+", "+a[9]+", "+a[10]+", "+a[11]+", "+a[12]+", "+a[13]+", "+a[14]+", "+a[15]+")"}function frob(a){return Math.hypot(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],a[10],a[11],a[12],a[13],a[14],a[15])}function add$5(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=a[2]+b[2];out[3]=a[3]+b[3];out[4]=a[4]+b[4];out[5]=a[5]+b[5];out[6]=a[6]+b[6];out[7]=a[7]+b[7];out[8]=a[8]+b[8];out[9]=a[9]+b[9];out[10]=a[10]+b[10];out[11]=a[11]+b[11];out[12]=a[12]+b[12];out[13]=a[13]+b[13];out[14]=a[14]+b[14];out[15]=a[15]+b[15];return out}function subtract$3(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];out[2]=a[2]-b[2];out[3]=a[3]-b[3];out[4]=a[4]-b[4];out[5]=a[5]-b[5];out[6]=a[6]-b[6];out[7]=a[7]-b[7];out[8]=a[8]-b[8];out[9]=a[9]-b[9];out[10]=a[10]-b[10];out[11]=a[11]-b[11];out[12]=a[12]-b[12];out[13]=a[13]-b[13];out[14]=a[14]-b[14];out[15]=a[15]-b[15];return out}function multiplyScalar(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;out[3]=a[3]*b;out[4]=a[4]*b;out[5]=a[5]*b;out[6]=a[6]*b;out[7]=a[7]*b;out[8]=a[8]*b;out[9]=a[9]*b;out[10]=a[10]*b;out[11]=a[11]*b;out[12]=a[12]*b;out[13]=a[13]*b;out[14]=a[14]*b;out[15]=a[15]*b;return out}function multiplyScalarAndAdd(out,a,b,scale){out[0]=a[0]+b[0]*scale;out[1]=a[1]+b[1]*scale;out[2]=a[2]+b[2]*scale;out[3]=a[3]+b[3]*scale;out[4]=a[4]+b[4]*scale;out[5]=a[5]+b[5]*scale;out[6]=a[6]+b[6]*scale;out[7]=a[7]+b[7]*scale;out[8]=a[8]+b[8]*scale;out[9]=a[9]+b[9]*scale;out[10]=a[10]+b[10]*scale;out[11]=a[11]+b[11]*scale;out[12]=a[12]+b[12]*scale;out[13]=a[13]+b[13]*scale;out[14]=a[14]+b[14]*scale;out[15]=a[15]+b[15]*scale;return out}function exactEquals$5(a,b){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]}function equals$6(a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var a4=a[4],a5=a[5],a6=a[6],a7=a[7];var a8=a[8],a9=a[9],a10=a[10],a11=a[11];var a12=a[12],a13=a[13],a14=a[14],a15=a[15];var b0=b[0],b1=b[1],b2=b[2],b3=b[3];var b4=b[4],b5=b[5],b6=b[6],b7=b[7];var b8=b[8],b9=b[9],b10=b[10],b11=b[11];var b12=b[12],b13=b[13],b14=b[14],b15=b[15];return Math.abs(a0-b0)<=EPSILON*Math.max(1,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=EPSILON*Math.max(1,Math.abs(a1),Math.abs(b1))&&Math.abs(a2-b2)<=EPSILON*Math.max(1,Math.abs(a2),Math.abs(b2))&&Math.abs(a3-b3)<=EPSILON*Math.max(1,Math.abs(a3),Math.abs(b3))&&Math.abs(a4-b4)<=EPSILON*Math.max(1,Math.abs(a4),Math.abs(b4))&&Math.abs(a5-b5)<=EPSILON*Math.max(1,Math.abs(a5),Math.abs(b5))&&Math.abs(a6-b6)<=EPSILON*Math.max(1,Math.abs(a6),Math.abs(b6))&&Math.abs(a7-b7)<=EPSILON*Math.max(1,Math.abs(a7),Math.abs(b7))&&Math.abs(a8-b8)<=EPSILON*Math.max(1,Math.abs(a8),Math.abs(b8))&&Math.abs(a9-b9)<=EPSILON*Math.max(1,Math.abs(a9),Math.abs(b9))&&Math.abs(a10-b10)<=EPSILON*Math.max(1,Math.abs(a10),Math.abs(b10))&&Math.abs(a11-b11)<=EPSILON*Math.max(1,Math.abs(a11),Math.abs(b11))&&Math.abs(a12-b12)<=EPSILON*Math.max(1,Math.abs(a12),Math.abs(b12))&&Math.abs(a13-b13)<=EPSILON*Math.max(1,Math.abs(a13),Math.abs(b13))&&Math.abs(a14-b14)<=EPSILON*Math.max(1,Math.abs(a14),Math.abs(b14))&&Math.abs(a15-b15)<=EPSILON*Math.max(1,Math.abs(a15),Math.abs(b15))}var mul$5=multiply$5;var sub$3=subtract$3;var mat4=Object.freeze({__proto__:null,add:add$5,adjoint:adjoint,clone:clone$5,copy:copy$5,create:create$5,determinant:determinant,equals:equals$6,exactEquals:exactEquals$5,frob:frob,fromQuat:fromQuat,fromQuat2:fromQuat2,fromRotation:fromRotation$1,fromRotationTranslation:fromRotationTranslation$1,fromRotationTranslationScale:fromRotationTranslationScale,fromRotationTranslationScaleOrigin:fromRotationTranslationScaleOrigin,fromScaling:fromScaling,fromTranslation:fromTranslation$1,fromValues:fromValues$5,fromXRotation:fromXRotation,fromYRotation:fromYRotation,fromZRotation:fromZRotation,frustum:frustum,getRotation:getRotation,getScaling:getScaling,getTranslation:getTranslation$1,identity:identity$2,invert:invert$2,lookAt:lookAt,mul:mul$5,multiply:multiply$5,multiplyScalar:multiplyScalar,multiplyScalarAndAdd:multiplyScalarAndAdd,ortho:ortho,orthoNO:orthoNO,orthoZO:orthoZO,perspective:perspective,perspectiveFromFieldOfView:perspectiveFromFieldOfView,perspectiveNO:perspectiveNO,perspectiveZO:perspectiveZO,rotate:rotate$1,rotateX:rotateX$3,rotateY:rotateY$3,rotateZ:rotateZ$3,scale:scale$5,set:set$5,str:str$5,sub:sub$3,subtract:subtract$3,targetTo:targetTo,translate:translate$1,transpose:transpose});function create$4(){var out=new ARRAY_TYPE(3);if(ARRAY_TYPE!=Float32Array){out[0]=0;out[1]=0;out[2]=0}return out}function clone$4(a){var out=new ARRAY_TYPE(3);out[0]=a[0];out[1]=a[1];out[2]=a[2];return out}function length$4(a){var x=a[0];var y=a[1];var z=a[2];return Math.hypot(x,y,z)}function fromValues$4(x,y,z){var out=new ARRAY_TYPE(3);out[0]=x;out[1]=y;out[2]=z;return out}function copy$4(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];return out}function set$4(out,x,y,z){out[0]=x;out[1]=y;out[2]=z;return out}function add$4(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=a[2]+b[2];return out}function subtract$2(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];out[2]=a[2]-b[2];return out}function multiply$4(out,a,b){out[0]=a[0]*b[0];out[1]=a[1]*b[1];out[2]=a[2]*b[2];return out}function divide$2(out,a,b){out[0]=a[0]/b[0];out[1]=a[1]/b[1];out[2]=a[2]/b[2];return out}function ceil$2(out,a){out[0]=Math.ceil(a[0]);out[1]=Math.ceil(a[1]);out[2]=Math.ceil(a[2]);return out}function floor$2(out,a){out[0]=Math.floor(a[0]);out[1]=Math.floor(a[1]);out[2]=Math.floor(a[2]);return out}function min$2(out,a,b){out[0]=Math.min(a[0],b[0]);out[1]=Math.min(a[1],b[1]);out[2]=Math.min(a[2],b[2]);return out}function max$2(out,a,b){out[0]=Math.max(a[0],b[0]);out[1]=Math.max(a[1],b[1]);out[2]=Math.max(a[2],b[2]);return out}function round$2(out,a){out[0]=Math.round(a[0]);out[1]=Math.round(a[1]);out[2]=Math.round(a[2]);return out}function scale$4(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;return out}function scaleAndAdd$2(out,a,b,scale){out[0]=a[0]+b[0]*scale;out[1]=a[1]+b[1]*scale;out[2]=a[2]+b[2]*scale;return out}function distance$2(a,b){var x=b[0]-a[0];var y=b[1]-a[1];var z=b[2]-a[2];return Math.hypot(x,y,z)}function squaredDistance$2(a,b){var x=b[0]-a[0];var y=b[1]-a[1];var z=b[2]-a[2];return x*x+y*y+z*z}function squaredLength$4(a){var x=a[0];var y=a[1];var z=a[2];return x*x+y*y+z*z}function negate$2(out,a){out[0]=-a[0];out[1]=-a[1];out[2]=-a[2];return out}function inverse$2(out,a){out[0]=1/a[0];out[1]=1/a[1];out[2]=1/a[2];return out}function normalize$4(out,a){var x=a[0];var y=a[1];var z=a[2];var len=x*x+y*y+z*z;if(len>0){len=1/Math.sqrt(len)}out[0]=a[0]*len;out[1]=a[1]*len;out[2]=a[2]*len;return out}function dot$5(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]}function cross$2(out,a,b){var ax=a[0],ay=a[1],az=a[2];var bx=b[0],by=b[1],bz=b[2];out[0]=ay*bz-az*by;out[1]=az*bx-ax*bz;out[2]=ax*by-ay*bx;return out}function lerp$4(out,a,b,t){var ax=a[0];var ay=a[1];var az=a[2];out[0]=ax+t*(b[0]-ax);out[1]=ay+t*(b[1]-ay);out[2]=az+t*(b[2]-az);return out}function hermite(out,a,b,c,d,t){var factorTimes2=t*t;var factor1=factorTimes2*(2*t-3)+1;var factor2=factorTimes2*(t-2)+t;var factor3=factorTimes2*(t-1);var factor4=factorTimes2*(3-2*t);out[0]=a[0]*factor1+b[0]*factor2+c[0]*factor3+d[0]*factor4;out[1]=a[1]*factor1+b[1]*factor2+c[1]*factor3+d[1]*factor4;out[2]=a[2]*factor1+b[2]*factor2+c[2]*factor3+d[2]*factor4;return out}function bezier(out,a,b,c,d,t){var inverseFactor=1-t;var inverseFactorTimesTwo=inverseFactor*inverseFactor;var factorTimes2=t*t;var factor1=inverseFactorTimesTwo*inverseFactor;var factor2=3*t*inverseFactorTimesTwo;var factor3=3*factorTimes2*inverseFactor;var factor4=factorTimes2*t;out[0]=a[0]*factor1+b[0]*factor2+c[0]*factor3+d[0]*factor4;out[1]=a[1]*factor1+b[1]*factor2+c[1]*factor3+d[1]*factor4;out[2]=a[2]*factor1+b[2]*factor2+c[2]*factor3+d[2]*factor4;return out}function random$3(out,scale){scale=scale||1;var r=RANDOM()*2*Math.PI;var z=RANDOM()*2-1;var zScale=Math.sqrt(1-z*z)*scale;out[0]=Math.cos(r)*zScale;out[1]=Math.sin(r)*zScale;out[2]=z*scale;return out}function transformMat4$2(out,a,m){var x=a[0],y=a[1],z=a[2];var w=m[3]*x+m[7]*y+m[11]*z+m[15];w=w||1;out[0]=(m[0]*x+m[4]*y+m[8]*z+m[12])/w;out[1]=(m[1]*x+m[5]*y+m[9]*z+m[13])/w;out[2]=(m[2]*x+m[6]*y+m[10]*z+m[14])/w;return out}function transformMat3$1(out,a,m){var x=a[0],y=a[1],z=a[2];out[0]=x*m[0]+y*m[3]+z*m[6];out[1]=x*m[1]+y*m[4]+z*m[7];out[2]=x*m[2]+y*m[5]+z*m[8];return out}function transformQuat$1(out,a,q){var qx=q[0],qy=q[1],qz=q[2],qw=q[3];var x=a[0],y=a[1],z=a[2];var uvx=qy*z-qz*y,uvy=qz*x-qx*z,uvz=qx*y-qy*x;var uuvx=qy*uvz-qz*uvy,uuvy=qz*uvx-qx*uvz,uuvz=qx*uvy-qy*uvx;var w2=qw*2;uvx*=w2;uvy*=w2;uvz*=w2;uuvx*=2;uuvy*=2;uuvz*=2;out[0]=x+uvx+uuvx;out[1]=y+uvy+uuvy;out[2]=z+uvz+uuvz;return out}function rotateX$2(out,a,b,rad){var p=[],r=[];p[0]=a[0]-b[0];p[1]=a[1]-b[1];p[2]=a[2]-b[2];r[0]=p[0];r[1]=p[1]*Math.cos(rad)-p[2]*Math.sin(rad);r[2]=p[1]*Math.sin(rad)+p[2]*Math.cos(rad);out[0]=r[0]+b[0];out[1]=r[1]+b[1];out[2]=r[2]+b[2];return out}function rotateY$2(out,a,b,rad){var p=[],r=[];p[0]=a[0]-b[0];p[1]=a[1]-b[1];p[2]=a[2]-b[2];r[0]=p[2]*Math.sin(rad)+p[0]*Math.cos(rad);r[1]=p[1];r[2]=p[2]*Math.cos(rad)-p[0]*Math.sin(rad);out[0]=r[0]+b[0];out[1]=r[1]+b[1];out[2]=r[2]+b[2];return out}function rotateZ$2(out,a,b,rad){var p=[],r=[];p[0]=a[0]-b[0];p[1]=a[1]-b[1];p[2]=a[2]-b[2];r[0]=p[0]*Math.cos(rad)-p[1]*Math.sin(rad);r[1]=p[0]*Math.sin(rad)+p[1]*Math.cos(rad);r[2]=p[2];out[0]=r[0]+b[0];out[1]=r[1]+b[1];out[2]=r[2]+b[2];return out}function angle$1(a,b){var ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag1=Math.sqrt(ax*ax+ay*ay+az*az),mag2=Math.sqrt(bx*bx+by*by+bz*bz),mag=mag1*mag2,cosine=mag&&dot$5(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))}function zero$2(out){out[0]=0;out[1]=0;out[2]=0;return out}function str$4(a){return"vec3("+a[0]+", "+a[1]+", "+a[2]+")"}function exactEquals$4(a,b){return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]}function equals$5(a,b){var a0=a[0],a1=a[1],a2=a[2];var b0=b[0],b1=b[1],b2=b[2];return Math.abs(a0-b0)<=EPSILON*Math.max(1,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=EPSILON*Math.max(1,Math.abs(a1),Math.abs(b1))&&Math.abs(a2-b2)<=EPSILON*Math.max(1,Math.abs(a2),Math.abs(b2))}var sub$2=subtract$2;var mul$4=multiply$4;var div$2=divide$2;var dist$2=distance$2;var sqrDist$2=squaredDistance$2;var len$4=length$4;var sqrLen$4=squaredLength$4;var forEach$2=function(){var vec=create$4();return function(a,stride,offset,count,fn,arg){var i,l;if(!stride){stride=3}if(!offset){offset=0}if(count){l=Math.min(count*stride+offset,a.length)}else{l=a.length}for(i=offset;i0){len=1/Math.sqrt(len)}out[0]=x*len;out[1]=y*len;out[2]=z*len;out[3]=w*len;return out}function dot$4(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}function cross$1(out,u,v,w){var A=v[0]*w[1]-v[1]*w[0],B=v[0]*w[2]-v[2]*w[0],C=v[0]*w[3]-v[3]*w[0],D=v[1]*w[2]-v[2]*w[1],E=v[1]*w[3]-v[3]*w[1],F=v[2]*w[3]-v[3]*w[2];var G=u[0];var H=u[1];var I=u[2];var J=u[3];out[0]=H*F-I*E+J*D;out[1]=-(G*F)+I*C-J*B;out[2]=G*E-H*C+J*A;out[3]=-(G*D)+H*B-I*A;return out}function lerp$3(out,a,b,t){var ax=a[0];var ay=a[1];var az=a[2];var aw=a[3];out[0]=ax+t*(b[0]-ax);out[1]=ay+t*(b[1]-ay);out[2]=az+t*(b[2]-az);out[3]=aw+t*(b[3]-aw);return out}function random$2(out,scale){scale=scale||1;var v1,v2,v3,v4;var s1,s2;do{v1=RANDOM()*2-1;v2=RANDOM()*2-1;s1=v1*v1+v2*v2}while(s1>=1);do{v3=RANDOM()*2-1;v4=RANDOM()*2-1;s2=v3*v3+v4*v4}while(s2>=1);var d=Math.sqrt((1-s1)/s2);out[0]=scale*v1;out[1]=scale*v2;out[2]=scale*v3*d;out[3]=scale*v4*d;return out}function transformMat4$1(out,a,m){var x=a[0],y=a[1],z=a[2],w=a[3];out[0]=m[0]*x+m[4]*y+m[8]*z+m[12]*w;out[1]=m[1]*x+m[5]*y+m[9]*z+m[13]*w;out[2]=m[2]*x+m[6]*y+m[10]*z+m[14]*w;out[3]=m[3]*x+m[7]*y+m[11]*z+m[15]*w;return out}function transformQuat(out,a,q){var x=a[0],y=a[1],z=a[2];var qx=q[0],qy=q[1],qz=q[2],qw=q[3];var ix=qw*x+qy*z-qz*y;var iy=qw*y+qz*x-qx*z;var iz=qw*z+qx*y-qy*x;var iw=-qx*x-qy*y-qz*z;out[0]=ix*qw+iw*-qx+iy*-qz-iz*-qy;out[1]=iy*qw+iw*-qy+iz*-qx-ix*-qz;out[2]=iz*qw+iw*-qz+ix*-qy-iy*-qx;out[3]=a[3];return out}function zero$1(out){out[0]=0;out[1]=0;out[2]=0;out[3]=0;return out}function str$3(a){return"vec4("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+")"}function exactEquals$3(a,b){return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]}function equals$4(a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var b0=b[0],b1=b[1],b2=b[2],b3=b[3];return Math.abs(a0-b0)<=EPSILON*Math.max(1,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=EPSILON*Math.max(1,Math.abs(a1),Math.abs(b1))&&Math.abs(a2-b2)<=EPSILON*Math.max(1,Math.abs(a2),Math.abs(b2))&&Math.abs(a3-b3)<=EPSILON*Math.max(1,Math.abs(a3),Math.abs(b3))}var sub$1=subtract$1;var mul$3=multiply$3;var div$1=divide$1;var dist$1=distance$1;var sqrDist$1=squaredDistance$1;var len$3=length$3;var sqrLen$3=squaredLength$3;var forEach$1=function(){var vec=create$3();return function(a,stride,offset,count,fn,arg){var i,l;if(!stride){stride=4}if(!offset){offset=0}if(count){l=Math.min(count*stride+offset,a.length)}else{l=a.length}for(i=offset;iEPSILON){out_axis[0]=q[0]/s;out_axis[1]=q[1]/s;out_axis[2]=q[2]/s}else{out_axis[0]=1;out_axis[1]=0;out_axis[2]=0}return rad}function getAngle(a,b){var dotproduct=dot$3(a,b);return Math.acos(2*dotproduct*dotproduct-1)}function multiply$2(out,a,b){var ax=a[0],ay=a[1],az=a[2],aw=a[3];var bx=b[0],by=b[1],bz=b[2],bw=b[3];out[0]=ax*bw+aw*bx+ay*bz-az*by;out[1]=ay*bw+aw*by+az*bx-ax*bz;out[2]=az*bw+aw*bz+ax*by-ay*bx;out[3]=aw*bw-ax*bx-ay*by-az*bz;return out}function rotateX$1(out,a,rad){rad*=.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3];var bx=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw+aw*bx;out[1]=ay*bw+az*bx;out[2]=az*bw-ay*bx;out[3]=aw*bw-ax*bx;return out}function rotateY$1(out,a,rad){rad*=.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3];var by=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw-az*by;out[1]=ay*bw+aw*by;out[2]=az*bw+ax*by;out[3]=aw*bw-ay*by;return out}function rotateZ$1(out,a,rad){rad*=.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3];var bz=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw+ay*bz;out[1]=ay*bw-ax*bz;out[2]=az*bw+aw*bz;out[3]=aw*bw-az*bz;return out}function calculateW(out,a){var x=a[0],y=a[1],z=a[2];out[0]=x;out[1]=y;out[2]=z;out[3]=Math.sqrt(Math.abs(1-x*x-y*y-z*z));return out}function exp(out,a){var x=a[0],y=a[1],z=a[2],w=a[3];var r=Math.sqrt(x*x+y*y+z*z);var et=Math.exp(w);var s=r>0?et*Math.sin(r)/r:0;out[0]=x*s;out[1]=y*s;out[2]=z*s;out[3]=et*Math.cos(r);return out}function ln(out,a){var x=a[0],y=a[1],z=a[2],w=a[3];var r=Math.sqrt(x*x+y*y+z*z);var t=r>0?Math.atan2(r,w)/r:0;out[0]=x*t;out[1]=y*t;out[2]=z*t;out[3]=.5*Math.log(x*x+y*y+z*z+w*w);return out}function pow(out,a,b){ln(out,a);scale$2(out,out,b);exp(out,out);return out}function slerp(out,a,b,t){var ax=a[0],ay=a[1],az=a[2],aw=a[3];var bx=b[0],by=b[1],bz=b[2],bw=b[3];var omega,cosom,sinom,scale0,scale1;cosom=ax*bx+ay*by+az*bz+aw*bw;if(cosom<0){cosom=-cosom;bx=-bx;by=-by;bz=-bz;bw=-bw}if(1-cosom>EPSILON){omega=Math.acos(cosom);sinom=Math.sin(omega);scale0=Math.sin((1-t)*omega)/sinom;scale1=Math.sin(t*omega)/sinom}else{scale0=1-t;scale1=t}out[0]=scale0*ax+scale1*bx;out[1]=scale0*ay+scale1*by;out[2]=scale0*az+scale1*bz;out[3]=scale0*aw+scale1*bw;return out}function random$1(out){var u1=RANDOM();var u2=RANDOM();var u3=RANDOM();var sqrt1MinusU1=Math.sqrt(1-u1);var sqrtU1=Math.sqrt(u1);out[0]=sqrt1MinusU1*Math.sin(2*Math.PI*u2);out[1]=sqrt1MinusU1*Math.cos(2*Math.PI*u2);out[2]=sqrtU1*Math.sin(2*Math.PI*u3);out[3]=sqrtU1*Math.cos(2*Math.PI*u3);return out}function invert$1(out,a){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var dot=a0*a0+a1*a1+a2*a2+a3*a3;var invDot=dot?1/dot:0;out[0]=-a0*invDot;out[1]=-a1*invDot;out[2]=-a2*invDot;out[3]=a3*invDot;return out}function conjugate$1(out,a){out[0]=-a[0];out[1]=-a[1];out[2]=-a[2];out[3]=a[3];return out}function fromMat3(out,m){var fTrace=m[0]+m[4]+m[8];var fRoot;if(fTrace>0){fRoot=Math.sqrt(fTrace+1);out[3]=.5*fRoot;fRoot=.5/fRoot;out[0]=(m[5]-m[7])*fRoot;out[1]=(m[6]-m[2])*fRoot;out[2]=(m[1]-m[3])*fRoot}else{var i=0;if(m[4]>m[0])i=1;if(m[8]>m[i*3+i])i=2;var j=(i+1)%3;var k=(i+2)%3;fRoot=Math.sqrt(m[i*3+i]-m[j*3+j]-m[k*3+k]+1);out[i]=.5*fRoot;fRoot=.5/fRoot;out[3]=(m[j*3+k]-m[k*3+j])*fRoot;out[j]=(m[j*3+i]+m[i*3+j])*fRoot;out[k]=(m[k*3+i]+m[i*3+k])*fRoot}return out}function fromEuler(out,x,y,z){var halfToRad=.5*Math.PI/180;x*=halfToRad;y*=halfToRad;z*=halfToRad;var sx=Math.sin(x);var cx=Math.cos(x);var sy=Math.sin(y);var cy=Math.cos(y);var sz=Math.sin(z);var cz=Math.cos(z);out[0]=sx*cy*cz-cx*sy*sz;out[1]=cx*sy*cz+sx*cy*sz;out[2]=cx*cy*sz-sx*sy*cz;out[3]=cx*cy*cz+sx*sy*sz;return out}function str$2(a){return"quat("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+")"}var clone$2=clone$3;var fromValues$2=fromValues$3;var copy$2=copy$3;var set$2=set$3;var add$2=add$3;var mul$2=multiply$2;var scale$2=scale$3;var dot$3=dot$4;var lerp$2=lerp$3;var length$2=length$3;var len$2=length$2;var squaredLength$2=squaredLength$3;var sqrLen$2=squaredLength$2;var normalize$2=normalize$3;var exactEquals$2=exactEquals$3;var equals$3=equals$4;var rotationTo=function(){var tmpvec3=create$4();var xUnitVec3=fromValues$4(1,0,0);var yUnitVec3=fromValues$4(0,1,0);return function(out,a,b){var dot=dot$5(a,b);if(dot<-.999999){cross$2(tmpvec3,xUnitVec3,a);if(len$4(tmpvec3)<1e-6)cross$2(tmpvec3,yUnitVec3,a);normalize$4(tmpvec3,tmpvec3);setAxisAngle(out,tmpvec3,Math.PI);return out}else if(dot>.999999){out[0]=0;out[1]=0;out[2]=0;out[3]=1;return out}else{cross$2(tmpvec3,a,b);out[0]=tmpvec3[0];out[1]=tmpvec3[1];out[2]=tmpvec3[2];out[3]=1+dot;return normalize$2(out,out)}}}();var sqlerp=function(){var temp1=create$2();var temp2=create$2();return function(out,a,b,c,d,t){slerp(temp1,a,d,t);slerp(temp2,b,c,t);slerp(out,temp1,temp2,2*t*(1-t));return out}}();var setAxes=function(){var matr=create$6();return function(out,view,right,up){matr[0]=right[0];matr[3]=right[1];matr[6]=right[2];matr[1]=up[0];matr[4]=up[1];matr[7]=up[2];matr[2]=-view[0];matr[5]=-view[1];matr[8]=-view[2];return normalize$2(out,fromMat3(out,matr))}}();var quat=Object.freeze({__proto__:null,add:add$2,calculateW:calculateW,clone:clone$2,conjugate:conjugate$1,copy:copy$2,create:create$2,dot:dot$3,equals:equals$3,exactEquals:exactEquals$2,exp:exp,fromEuler:fromEuler,fromMat3:fromMat3,fromValues:fromValues$2,getAngle:getAngle,getAxisAngle:getAxisAngle,identity:identity$1,invert:invert$1,len:len$2,length:length$2,lerp:lerp$2,ln:ln,mul:mul$2,multiply:multiply$2,normalize:normalize$2,pow:pow,random:random$1,rotateX:rotateX$1,rotateY:rotateY$1,rotateZ:rotateZ$1,rotationTo:rotationTo,scale:scale$2,set:set$2,setAxes:setAxes,setAxisAngle:setAxisAngle,slerp:slerp,sqlerp:sqlerp,sqrLen:sqrLen$2,squaredLength:squaredLength$2,str:str$2});function create$1(){var dq=new ARRAY_TYPE(8);if(ARRAY_TYPE!=Float32Array){dq[0]=0;dq[1]=0;dq[2]=0;dq[4]=0;dq[5]=0;dq[6]=0;dq[7]=0}dq[3]=1;return dq}function clone$1(a){var dq=new ARRAY_TYPE(8);dq[0]=a[0];dq[1]=a[1];dq[2]=a[2];dq[3]=a[3];dq[4]=a[4];dq[5]=a[5];dq[6]=a[6];dq[7]=a[7];return dq}function fromValues$1(x1,y1,z1,w1,x2,y2,z2,w2){var dq=new ARRAY_TYPE(8);dq[0]=x1;dq[1]=y1;dq[2]=z1;dq[3]=w1;dq[4]=x2;dq[5]=y2;dq[6]=z2;dq[7]=w2;return dq}function fromRotationTranslationValues(x1,y1,z1,w1,x2,y2,z2){var dq=new ARRAY_TYPE(8);dq[0]=x1;dq[1]=y1;dq[2]=z1;dq[3]=w1;var ax=x2*.5,ay=y2*.5,az=z2*.5;dq[4]=ax*w1+ay*z1-az*y1;dq[5]=ay*w1+az*x1-ax*z1;dq[6]=az*w1+ax*y1-ay*x1;dq[7]=-ax*x1-ay*y1-az*z1;return dq}function fromRotationTranslation(out,q,t){var ax=t[0]*.5,ay=t[1]*.5,az=t[2]*.5,bx=q[0],by=q[1],bz=q[2],bw=q[3];out[0]=bx;out[1]=by;out[2]=bz;out[3]=bw;out[4]=ax*bw+ay*bz-az*by;out[5]=ay*bw+az*bx-ax*bz;out[6]=az*bw+ax*by-ay*bx;out[7]=-ax*bx-ay*by-az*bz;return out}function fromTranslation(out,t){out[0]=0;out[1]=0;out[2]=0;out[3]=1;out[4]=t[0]*.5;out[5]=t[1]*.5;out[6]=t[2]*.5;out[7]=0;return out}function fromRotation(out,q){out[0]=q[0];out[1]=q[1];out[2]=q[2];out[3]=q[3];out[4]=0;out[5]=0;out[6]=0;out[7]=0;return out}function fromMat4(out,a){var outer=create$2();getRotation(outer,a);var t=new ARRAY_TYPE(3);getTranslation$1(t,a);fromRotationTranslation(out,outer,t);return out}function copy$1(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];return out}function identity(out){out[0]=0;out[1]=0;out[2]=0;out[3]=1;out[4]=0;out[5]=0;out[6]=0;out[7]=0;return out}function set$1(out,x1,y1,z1,w1,x2,y2,z2,w2){out[0]=x1;out[1]=y1;out[2]=z1;out[3]=w1;out[4]=x2;out[5]=y2;out[6]=z2;out[7]=w2;return out}var getReal=copy$2;function getDual(out,a){out[0]=a[4];out[1]=a[5];out[2]=a[6];out[3]=a[7];return out}var setReal=copy$2;function setDual(out,q){out[4]=q[0];out[5]=q[1];out[6]=q[2];out[7]=q[3];return out}function getTranslation(out,a){var ax=a[4],ay=a[5],az=a[6],aw=a[7],bx=-a[0],by=-a[1],bz=-a[2],bw=a[3];out[0]=(ax*bw+aw*bx+ay*bz-az*by)*2;out[1]=(ay*bw+aw*by+az*bx-ax*bz)*2;out[2]=(az*bw+aw*bz+ax*by-ay*bx)*2;return out}function translate(out,a,v){var ax1=a[0],ay1=a[1],az1=a[2],aw1=a[3],bx1=v[0]*.5,by1=v[1]*.5,bz1=v[2]*.5,ax2=a[4],ay2=a[5],az2=a[6],aw2=a[7];out[0]=ax1;out[1]=ay1;out[2]=az1;out[3]=aw1;out[4]=aw1*bx1+ay1*bz1-az1*by1+ax2;out[5]=aw1*by1+az1*bx1-ax1*bz1+ay2;out[6]=aw1*bz1+ax1*by1-ay1*bx1+az2;out[7]=-ax1*bx1-ay1*by1-az1*bz1+aw2;return out}function rotateX(out,a,rad){var bx=-a[0],by=-a[1],bz=-a[2],bw=a[3],ax=a[4],ay=a[5],az=a[6],aw=a[7],ax1=ax*bw+aw*bx+ay*bz-az*by,ay1=ay*bw+aw*by+az*bx-ax*bz,az1=az*bw+aw*bz+ax*by-ay*bx,aw1=aw*bw-ax*bx-ay*by-az*bz;rotateX$1(out,a,rad);bx=out[0];by=out[1];bz=out[2];bw=out[3];out[4]=ax1*bw+aw1*bx+ay1*bz-az1*by;out[5]=ay1*bw+aw1*by+az1*bx-ax1*bz;out[6]=az1*bw+aw1*bz+ax1*by-ay1*bx;out[7]=aw1*bw-ax1*bx-ay1*by-az1*bz;return out}function rotateY(out,a,rad){var bx=-a[0],by=-a[1],bz=-a[2],bw=a[3],ax=a[4],ay=a[5],az=a[6],aw=a[7],ax1=ax*bw+aw*bx+ay*bz-az*by,ay1=ay*bw+aw*by+az*bx-ax*bz,az1=az*bw+aw*bz+ax*by-ay*bx,aw1=aw*bw-ax*bx-ay*by-az*bz;rotateY$1(out,a,rad);bx=out[0];by=out[1];bz=out[2];bw=out[3];out[4]=ax1*bw+aw1*bx+ay1*bz-az1*by;out[5]=ay1*bw+aw1*by+az1*bx-ax1*bz;out[6]=az1*bw+aw1*bz+ax1*by-ay1*bx;out[7]=aw1*bw-ax1*bx-ay1*by-az1*bz;return out}function rotateZ(out,a,rad){var bx=-a[0],by=-a[1],bz=-a[2],bw=a[3],ax=a[4],ay=a[5],az=a[6],aw=a[7],ax1=ax*bw+aw*bx+ay*bz-az*by,ay1=ay*bw+aw*by+az*bx-ax*bz,az1=az*bw+aw*bz+ax*by-ay*bx,aw1=aw*bw-ax*bx-ay*by-az*bz;rotateZ$1(out,a,rad);bx=out[0];by=out[1];bz=out[2];bw=out[3];out[4]=ax1*bw+aw1*bx+ay1*bz-az1*by;out[5]=ay1*bw+aw1*by+az1*bx-ax1*bz;out[6]=az1*bw+aw1*bz+ax1*by-ay1*bx;out[7]=aw1*bw-ax1*bx-ay1*by-az1*bz;return out}function rotateByQuatAppend(out,a,q){var qx=q[0],qy=q[1],qz=q[2],qw=q[3],ax=a[0],ay=a[1],az=a[2],aw=a[3];out[0]=ax*qw+aw*qx+ay*qz-az*qy;out[1]=ay*qw+aw*qy+az*qx-ax*qz;out[2]=az*qw+aw*qz+ax*qy-ay*qx;out[3]=aw*qw-ax*qx-ay*qy-az*qz;ax=a[4];ay=a[5];az=a[6];aw=a[7];out[4]=ax*qw+aw*qx+ay*qz-az*qy;out[5]=ay*qw+aw*qy+az*qx-ax*qz;out[6]=az*qw+aw*qz+ax*qy-ay*qx;out[7]=aw*qw-ax*qx-ay*qy-az*qz;return out}function rotateByQuatPrepend(out,q,a){var qx=q[0],qy=q[1],qz=q[2],qw=q[3],bx=a[0],by=a[1],bz=a[2],bw=a[3];out[0]=qx*bw+qw*bx+qy*bz-qz*by;out[1]=qy*bw+qw*by+qz*bx-qx*bz;out[2]=qz*bw+qw*bz+qx*by-qy*bx;out[3]=qw*bw-qx*bx-qy*by-qz*bz;bx=a[4];by=a[5];bz=a[6];bw=a[7];out[4]=qx*bw+qw*bx+qy*bz-qz*by;out[5]=qy*bw+qw*by+qz*bx-qx*bz;out[6]=qz*bw+qw*bz+qx*by-qy*bx;out[7]=qw*bw-qx*bx-qy*by-qz*bz;return out}function rotateAroundAxis(out,a,axis,rad){if(Math.abs(rad)0){magnitude=Math.sqrt(magnitude);var a0=a[0]/magnitude;var a1=a[1]/magnitude;var a2=a[2]/magnitude;var a3=a[3]/magnitude;var b0=a[4];var b1=a[5];var b2=a[6];var b3=a[7];var a_dot_b=a0*b0+a1*b1+a2*b2+a3*b3;out[0]=a0;out[1]=a1;out[2]=a2;out[3]=a3;out[4]=(b0-a0*a_dot_b)/magnitude;out[5]=(b1-a1*a_dot_b)/magnitude;out[6]=(b2-a2*a_dot_b)/magnitude;out[7]=(b3-a3*a_dot_b)/magnitude}return out}function str$1(a){return"quat2("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+", "+a[4]+", "+a[5]+", "+a[6]+", "+a[7]+")"}function exactEquals$1(a,b){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]}function equals$2(a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5],a6=a[6],a7=a[7];var b0=b[0],b1=b[1],b2=b[2],b3=b[3],b4=b[4],b5=b[5],b6=b[6],b7=b[7];return Math.abs(a0-b0)<=EPSILON*Math.max(1,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=EPSILON*Math.max(1,Math.abs(a1),Math.abs(b1))&&Math.abs(a2-b2)<=EPSILON*Math.max(1,Math.abs(a2),Math.abs(b2))&&Math.abs(a3-b3)<=EPSILON*Math.max(1,Math.abs(a3),Math.abs(b3))&&Math.abs(a4-b4)<=EPSILON*Math.max(1,Math.abs(a4),Math.abs(b4))&&Math.abs(a5-b5)<=EPSILON*Math.max(1,Math.abs(a5),Math.abs(b5))&&Math.abs(a6-b6)<=EPSILON*Math.max(1,Math.abs(a6),Math.abs(b6))&&Math.abs(a7-b7)<=EPSILON*Math.max(1,Math.abs(a7),Math.abs(b7))}var quat2=Object.freeze({__proto__:null,add:add$1,clone:clone$1,conjugate:conjugate,copy:copy$1,create:create$1,dot:dot$2,equals:equals$2,exactEquals:exactEquals$1,fromMat4:fromMat4,fromRotation:fromRotation,fromRotationTranslation:fromRotationTranslation,fromRotationTranslationValues:fromRotationTranslationValues,fromTranslation:fromTranslation,fromValues:fromValues$1,getDual:getDual,getReal:getReal,getTranslation:getTranslation,identity:identity,invert:invert,len:len$1,length:length$1,lerp:lerp$1,mul:mul$1,multiply:multiply$1,normalize:normalize$1,rotateAroundAxis:rotateAroundAxis,rotateByQuatAppend:rotateByQuatAppend,rotateByQuatPrepend:rotateByQuatPrepend,rotateX:rotateX,rotateY:rotateY,rotateZ:rotateZ,scale:scale$1,set:set$1,setDual:setDual,setReal:setReal,sqrLen:sqrLen$1,squaredLength:squaredLength$1,str:str$1,translate:translate});function create(){var out=new ARRAY_TYPE(2);if(ARRAY_TYPE!=Float32Array){out[0]=0;out[1]=0}return out}function clone(a){var out=new ARRAY_TYPE(2);out[0]=a[0];out[1]=a[1];return out}function fromValues(x,y){var out=new ARRAY_TYPE(2);out[0]=x;out[1]=y;return out}function copy(out,a){out[0]=a[0];out[1]=a[1];return out}function set(out,x,y){out[0]=x;out[1]=y;return out}function add(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];return out}function subtract(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];return out}function multiply(out,a,b){out[0]=a[0]*b[0];out[1]=a[1]*b[1];return out}function divide(out,a,b){out[0]=a[0]/b[0];out[1]=a[1]/b[1];return out}function ceil(out,a){out[0]=Math.ceil(a[0]);out[1]=Math.ceil(a[1]);return out}function floor(out,a){out[0]=Math.floor(a[0]);out[1]=Math.floor(a[1]);return out}function min(out,a,b){out[0]=Math.min(a[0],b[0]);out[1]=Math.min(a[1],b[1]);return out}function max(out,a,b){out[0]=Math.max(a[0],b[0]);out[1]=Math.max(a[1],b[1]);return out}function round(out,a){out[0]=Math.round(a[0]);out[1]=Math.round(a[1]);return out}function scale(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;return out}function scaleAndAdd(out,a,b,scale){out[0]=a[0]+b[0]*scale;out[1]=a[1]+b[1]*scale;return out}function distance(a,b){var x=b[0]-a[0],y=b[1]-a[1];return Math.hypot(x,y)}function squaredDistance(a,b){var x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y}function length(a){var x=a[0],y=a[1];return Math.hypot(x,y)}function squaredLength(a){var x=a[0],y=a[1];return x*x+y*y}function negate(out,a){out[0]=-a[0];out[1]=-a[1];return out}function inverse(out,a){out[0]=1/a[0];out[1]=1/a[1];return out}function normalize(out,a){var x=a[0],y=a[1];var len=x*x+y*y;if(len>0){len=1/Math.sqrt(len)}out[0]=a[0]*len;out[1]=a[1]*len;return out}function dot$1(a,b){return a[0]*b[0]+a[1]*b[1]}function cross(out,a,b){var z=a[0]*b[1]-a[1]*b[0];out[0]=out[1]=0;out[2]=z;return out}function lerp(out,a,b,t){var ax=a[0],ay=a[1];out[0]=ax+t*(b[0]-ax);out[1]=ay+t*(b[1]-ay);return out}function random(out,scale){scale=scale||1;var r=RANDOM()*2*Math.PI;out[0]=Math.cos(r)*scale;out[1]=Math.sin(r)*scale;return out}function transformMat2(out,a,m){var x=a[0],y=a[1];out[0]=m[0]*x+m[2]*y;out[1]=m[1]*x+m[3]*y;return out}function transformMat2d(out,a,m){var x=a[0],y=a[1];out[0]=m[0]*x+m[2]*y+m[4];out[1]=m[1]*x+m[3]*y+m[5];return out}function transformMat3(out,a,m){var x=a[0],y=a[1];out[0]=m[0]*x+m[3]*y+m[6];out[1]=m[1]*x+m[4]*y+m[7];return out}function transformMat4(out,a,m){var x=a[0];var y=a[1];out[0]=m[0]*x+m[4]*y+m[12];out[1]=m[1]*x+m[5]*y+m[13];return out}function rotate(out,a,b,rad){var p0=a[0]-b[0],p1=a[1]-b[1],sinC=Math.sin(rad),cosC=Math.cos(rad);out[0]=p0*cosC-p1*sinC+b[0];out[1]=p0*sinC+p1*cosC+b[1];return out}function angle(a,b){var x1=a[0],y1=a[1],x2=b[0],y2=b[1],mag=Math.sqrt(x1*x1+y1*y1)*Math.sqrt(x2*x2+y2*y2),cosine=mag&&(x1*x2+y1*y2)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))}function zero(out){out[0]=0;out[1]=0;return out}function str(a){return"vec2("+a[0]+", "+a[1]+")"}function exactEquals(a,b){return a[0]===b[0]&&a[1]===b[1]}function equals$1(a,b){var a0=a[0],a1=a[1];var b0=b[0],b1=b[1];return Math.abs(a0-b0)<=EPSILON*Math.max(1,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=EPSILON*Math.max(1,Math.abs(a1),Math.abs(b1))}var len=length;var sub=subtract;var mul=multiply;var div=divide;var dist=distance;var sqrDist=squaredDistance;var sqrLen=squaredLength;var forEach=function(){var vec=create();return function(a,stride,offset,count,fn,arg){var i,l;if(!stride){stride=2}if(!offset){offset=0}if(count){l=Math.min(count*stride+offset,a.length)}else{l=a.length}for(i=offset;iprojectPoint(p,pixelPosMatrix)))}class HeatmapBucket extends CircleBucket{}register("HeatmapBucket",HeatmapBucket,{omit:["layers"]});let paint$7;const getPaint$7=()=>paint$7=paint$7||new Properties({"heatmap-radius":new DataDrivenProperty(v8Spec["paint_heatmap"]["heatmap-radius"]),"heatmap-weight":new DataDrivenProperty(v8Spec["paint_heatmap"]["heatmap-weight"]),"heatmap-intensity":new DataConstantProperty(v8Spec["paint_heatmap"]["heatmap-intensity"]),"heatmap-color":new ColorRampProperty(v8Spec["paint_heatmap"]["heatmap-color"]),"heatmap-opacity":new DataConstantProperty(v8Spec["paint_heatmap"]["heatmap-opacity"])});var properties$7={get paint(){return getPaint$7()}};function createImage(image,{width:width,height:height},channels,data){if(!data){data=new Uint8Array(width*height*channels)}else if(data instanceof Uint8ClampedArray){data=new Uint8Array(data.buffer)}else if(data.length!==width*height*channels){throw new RangeError(`mismatched image size. expected: ${data.length} but got: ${width*height*channels}`)}image.width=width;image.height=height;image.data=data;return image}function resizeImage(image,{width:width,height:height},channels){if(width===image.width&&height===image.height){return}const newImage=createImage({},{width:width,height:height},channels);copyImage(image,newImage,{x:0,y:0},{x:0,y:0},{width:Math.min(image.width,width),height:Math.min(image.height,height)},channels);image.width=width;image.height=height;image.data=newImage.data}function copyImage(srcImg,dstImg,srcPt,dstPt,size,channels){if(size.width===0||size.height===0){return dstImg}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")}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")}const srcData=srcImg.data;const dstData=dstImg.data;if(srcData===dstData)throw new Error("srcData equals dstData, so image is already copied");for(let y=0;y{evaluationGlobals[params.evaluationKey]=progress;const pxColor=params.expression.evaluate(evaluationGlobals);image.data[stride+index+0]=Math.floor(pxColor.r*255/pxColor.a);image.data[stride+index+1]=Math.floor(pxColor.g*255/pxColor.a);image.data[stride+index+2]=Math.floor(pxColor.b*255/pxColor.a);image.data[stride+index+3]=Math.floor(pxColor.a*255)};if(!params.clips){for(let i=0,j=0;ipaint$6=paint$6||new Properties({"hillshade-illumination-direction":new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-illumination-direction"]),"hillshade-illumination-anchor":new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-illumination-anchor"]),"hillshade-exaggeration":new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-exaggeration"]),"hillshade-shadow-color":new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-shadow-color"]),"hillshade-highlight-color":new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-highlight-color"]),"hillshade-accent-color":new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-accent-color"])});var properties$6={get paint(){return getPaint$6()}};class HillshadeStyleLayer extends StyleLayer{constructor(layer){super(layer,properties$6)}hasOffscreenPass(){return this.paint.get("hillshade-exaggeration")!==0&&this.visibility!=="none"}}const layout$4=createLayout([{name:"a_pos",components:2,type:"Int16"}],4);const{members:members$3,size:size$3,alignment:alignment$3}=layout$4;var earcut$2={exports:{}};var earcut_1=earcut$2.exports;"use strict";earcut$2.exports=earcut;var _default=earcut$2.exports.default=earcut;function earcut(data,holeIndices,dim){dim=dim||2;var hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length,outerNode=linkedList(data,0,outerLen,dim,true),triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;var minX,minY,maxX,maxY,x,y,invSize;if(hasHoles)outerNode=eliminateHoles(data,holeIndices,outerNode,dim);if(data.length>80*dim){minX=maxX=data[0];minY=maxY=data[1];for(var i=dim;imaxX)maxX=x;if(y>maxY)maxY=y}invSize=Math.max(maxX-minX,maxY-minY);invSize=invSize!==0?32767/invSize:0}earcutLinked(outerNode,triangles,dim,minX,minY,invSize,0);return triangles}function linkedList(data,start,end,dim,clockwise){var i,last;if(clockwise===signedArea$1(data,start,end,dim)>0){for(i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last)}if(last&&equals(last,last.next)){removeNode(last);last=last.next}return last}function filterPoints(start,end){if(!start)return start;if(!end)end=start;var p=start,again;do{again=false;if(!p.steiner&&(equals(p,p.next)||area(p.prev,p,p.next)===0)){removeNode(p);p=end=p.prev;if(p===p.next)break;again=true}else{p=p.next}}while(again||p!==end);return end}function earcutLinked(ear,triangles,dim,minX,minY,invSize,pass){if(!ear)return;if(!pass&&invSize)indexCurve(ear,minX,minY,invSize);var stop=ear,prev,next;while(ear.prev!==ear.next){prev=ear.prev;next=ear.next;if(invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear)){triangles.push(prev.i/dim|0);triangles.push(ear.i/dim|0);triangles.push(next.i/dim|0);removeNode(ear);ear=next.next;stop=next.next;continue}ear=next;if(ear===stop){if(!pass){earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1)}else if(pass===1){ear=cureLocalIntersections(filterPoints(ear),triangles,dim);earcutLinked(ear,triangles,dim,minX,minY,invSize,2)}else if(pass===2){splitEarcut(ear,triangles,dim,minX,minY,invSize)}break}}}function isEar(ear){var a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return false;var ax=a.x,bx=b.x,cx=c.x,ay=a.y,by=b.y,cy=c.y;var x0=axbx?ax>cx?ax:cx:bx>cx?bx:cx,y1=ay>by?ay>cy?ay:cy:by>cy?by:cy;var p=c.next;while(p!==a){if(p.x>=x0&&p.x<=x1&&p.y>=y0&&p.y<=y1&&pointInTriangle(ax,ay,bx,by,cx,cy,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.next}return true}function isEarHashed(ear,minX,minY,invSize){var a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return false;var ax=a.x,bx=b.x,cx=c.x,ay=a.y,by=b.y,cy=c.y;var x0=axbx?ax>cx?ax:cx:bx>cx?bx:cx,y1=ay>by?ay>cy?ay:cy:by>cy?by:cy;var minZ=zOrder(x0,y0,minX,minY,invSize),maxZ=zOrder(x1,y1,minX,minY,invSize);var p=ear.prevZ,n=ear.nextZ;while(p&&p.z>=minZ&&n&&n.z<=maxZ){if(p.x>=x0&&p.x<=x1&&p.y>=y0&&p.y<=y1&&p!==a&&p!==c&&pointInTriangle(ax,ay,bx,by,cx,cy,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.prevZ;if(n.x>=x0&&n.x<=x1&&n.y>=y0&&n.y<=y1&&n!==a&&n!==c&&pointInTriangle(ax,ay,bx,by,cx,cy,n.x,n.y)&&area(n.prev,n,n.next)>=0)return false;n=n.nextZ}while(p&&p.z>=minZ){if(p.x>=x0&&p.x<=x1&&p.y>=y0&&p.y<=y1&&p!==a&&p!==c&&pointInTriangle(ax,ay,bx,by,cx,cy,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.prevZ}while(n&&n.z<=maxZ){if(n.x>=x0&&n.x<=x1&&n.y>=y0&&n.y<=y1&&n!==a&&n!==c&&pointInTriangle(ax,ay,bx,by,cx,cy,n.x,n.y)&&area(n.prev,n,n.next)>=0)return false;n=n.nextZ}return true}function cureLocalIntersections(start,triangles,dim){var p=start;do{var a=p.prev,b=p.next.next;if(!equals(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)){triangles.push(a.i/dim|0);triangles.push(p.i/dim|0);triangles.push(b.i/dim|0);removeNode(p);removeNode(p.next);p=start=b}p=p.next}while(p!==start);return filterPoints(p)}function splitEarcut(start,triangles,dim,minX,minY,invSize){var a=start;do{var b=a.next.next;while(b!==a.prev){if(a.i!==b.i&&isValidDiagonal(a,b)){var c=splitPolygon(a,b);a=filterPoints(a,a.next);c=filterPoints(c,c.next);earcutLinked(a,triangles,dim,minX,minY,invSize,0);earcutLinked(c,triangles,dim,minX,minY,invSize,0);return}b=b.next}a=a.next}while(a!==start)}function eliminateHoles(data,holeIndices,outerNode,dim){var queue=[],i,len,start,end,list;for(i=0,len=holeIndices.length;i=p.next.y&&p.next.y!==p.y){var x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){qx=x;m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))){m=p;tanMin=tan}}p=p.next}while(p!==stop);return m}function sectorContainsSector(m,p){return area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0}function indexCurve(start,minX,minY,invSize){var p=start;do{if(p.z===0)p.z=zOrder(p.x,p.y,minX,minY,invSize);p.prevZ=p.prev;p.nextZ=p.next;p=p.next}while(p!==start);p.prevZ.nextZ=null;p.prevZ=null;sortLinked(p)}function sortLinked(list){var i,p,q,e,tail,numMerges,pSize,qSize,inSize=1;do{p=list;list=null;tail=null;numMerges=0;while(p){numMerges++;q=p;pSize=0;for(i=0;i0||qSize>0&&q){if(pSize!==0&&(qSize===0||!q||p.z<=q.z)){e=p;p=p.nextZ;pSize--}else{e=q;q=q.nextZ;qSize--}if(tail)tail.nextZ=e;else list=e;e.prevZ=tail;tail=e}p=q}tail.nextZ=null;inSize*=2}while(numMerges>1);return list}function zOrder(x,y,minX,minY,invSize){x=(x-minX)*invSize|0;y=(y-minY)*invSize|0;x=(x|x<<8)&16711935;x=(x|x<<4)&252645135;x=(x|x<<2)&858993459;x=(x|x<<1)&1431655765;y=(y|y<<8)&16711935;y=(y|y<<4)&252645135;y=(y|y<<2)&858993459;y=(y|y<<1)&1431655765;return x|y<<1}function getLeftmost(start){var p=start,leftmost=start;do{if(p.x=(ax-px)*(cy-py)&&(ax-px)*(by-py)>=(bx-px)*(ay-py)&&(bx-px)*(cy-py)>=(cx-px)*(by-py)}function isValidDiagonal(a,b){return a.next.i!==b.i&&a.prev.i!==b.i&&!intersectsPolygon(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&middleInside(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0)}function area(p,q,r){return(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y)}function equals(p1,p2){return p1.x===p2.x&&p1.y===p2.y}function intersects(p1,q1,p2,q2){var o1=sign(area(p1,q1,p2));var o2=sign(area(p1,q1,q2));var o3=sign(area(p2,q2,p1));var o4=sign(area(p2,q2,q1));if(o1!==o2&&o3!==o4)return true;if(o1===0&&onSegment(p1,p2,q1))return true;if(o2===0&&onSegment(p1,q2,q1))return true;if(o3===0&&onSegment(p2,p1,q2))return true;if(o4===0&&onSegment(p2,q1,q2))return true;return false}function onSegment(p,q,r){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)}function sign(num){return num>0?1:num<0?-1:0}function intersectsPolygon(a,b){var p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return true;p=p.next}while(p!==a);return false}function locallyInside(a,b){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}function middleInside(a,b){var p=a,inside=false,px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{if(p.y>py!==p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x)inside=!inside;p=p.next}while(p!==a);return inside}function splitPolygon(a,b){var a2=new Node(a.i,a.x,a.y),b2=new Node(b.i,b.x,b.y),an=a.next,bp=b.prev;a.next=b;b.prev=a;a2.next=an;an.prev=a2;b2.next=a2;a2.prev=b2;bp.next=b2;b2.prev=bp;return b2}function insertNode(i,x,y,last){var p=new Node(i,x,y);if(!last){p.prev=p;p.next=p}else{p.next=last.next;p.prev=last;last.next.prev=p;last.next=p}return p}function removeNode(p){p.next.prev=p.prev;p.prev.next=p.next;if(p.prevZ)p.prevZ.nextZ=p.nextZ;if(p.nextZ)p.nextZ.prevZ=p.prevZ}function Node(i,x,y){this.i=i;this.x=x;this.y=y;this.prev=null;this.next=null;this.z=0;this.prevZ=null;this.nextZ=null;this.steiner=false}earcut.deviation=function(data,holeIndices,dim,triangles){var hasHoles=holeIndices&&holeIndices.length;var outerLen=hasHoles?holeIndices[0]*dim:data.length;var polygonArea=Math.abs(signedArea$1(data,0,outerLen,dim));if(hasHoles){for(var i=0,len=holeIndices.length;i0){holeIndex+=data[i-1].length;result.holes.push(holeIndex)}}return result};var earcutExports=earcut$2.exports;var earcut$1=getDefaultExportFromCjs$1(earcutExports);function quickselect(arr,k,left,right,compare){quickselectStep(arr,k,left||0,right||arr.length-1,compare||defaultCompare$1)}function quickselectStep(arr,k,left,right,compare){while(right>left){if(right-left>600){var n=right-left+1;var m=k-left+1;var z=Math.log(n);var s=.5*Math.exp(2*z/3);var sd=.5*Math.sqrt(z*s*(n-s)/n)*(m-n/2<0?-1:1);var newLeft=Math.max(left,Math.floor(k-m*s/n+sd));var newRight=Math.min(right,Math.floor(k+(n-m)*s/n+sd));quickselectStep(arr,k,newLeft,newRight,compare)}var t=arr[k];var i=left;var j=right;swap$1(arr,left,k);if(compare(arr[right],t)>0)swap$1(arr,left,right);while(i0)j--}if(compare(arr[left],t)===0)swap$1(arr,left,j);else{j++;swap$1(arr,j,right)}if(j<=k)left=j+1;if(k<=j)right=j-1}}function swap$1(arr,i,j){var tmp=arr[i];arr[i]=arr[j];arr[j]=tmp}function defaultCompare$1(a,b){return ab?1:0}function classifyRings$1(rings,maxRings){const len=rings.length;if(len<=1)return[rings];const polygons=[];let polygon,ccw;for(let i=0;i1){for(let j=0;jlayer.id));this.index=options.index;this.hasPattern=false;this.patternFeatures=[];this.layoutVertexArray=new FillLayoutArray;this.indexArray=new TriangleIndexArray;this.indexArray2=new LineIndexArray;this.programConfigurations=new ProgramConfigurationSet(options.layers,options.zoom);this.segments=new SegmentVector;this.segments2=new SegmentVector;this.stateDependentLayerIds=this.layers.filter((l=>l.isStateDependent())).map((l=>l.id))}populate(features,options,canonical){this.hasPattern=hasPattern("fill",this.layers,options);const fillSortKey=this.layers[0].layout.get("fill-sort-key");const sortFeaturesByKey=!fillSortKey.isConstant();const bucketFeatures=[];for(const{feature:feature,id:id,index:index,sourceLayerIndex:sourceLayerIndex}of features){const needGeometry=this.layers[0]._featureFilter.needGeometry;const evaluationFeature=toEvaluationFeature(feature,needGeometry);if(!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom),evaluationFeature,canonical))continue;const sortKey=sortFeaturesByKey?fillSortKey.evaluate(evaluationFeature,{},canonical,options.availableImages):undefined;const bucketFeature={id:id,properties:feature.properties,type:feature.type,sourceLayerIndex:sourceLayerIndex,index:index,geometry:needGeometry?evaluationFeature.geometry:loadGeometry(feature),patterns:{},sortKey:sortKey};bucketFeatures.push(bucketFeature)}if(sortFeaturesByKey){bucketFeatures.sort(((a,b)=>a.sortKey-b.sortKey))}for(const bucketFeature of bucketFeatures){const{geometry:geometry,index:index,sourceLayerIndex:sourceLayerIndex}=bucketFeature;if(this.hasPattern){const patternFeature=addPatternDependencies("fill",this.layers,bucketFeature,this.zoom,options);this.patternFeatures.push(patternFeature)}else{this.addFeature(bucketFeature,geometry,index,canonical,{})}const feature=features[index].feature;options.featureIndex.insert(feature,geometry,index,sourceLayerIndex,this.index)}}update(states,vtLayer,imagePositions){if(!this.stateDependentLayers.length)return;this.programConfigurations.updatePaintArrays(states,vtLayer,this.stateDependentLayers,imagePositions)}addFeatures(options,canonical,imagePositions){for(const feature of this.patternFeatures){this.addFeature(feature,feature.geometry,feature.index,canonical,imagePositions)}}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(context){if(!this.uploaded){this.layoutVertexBuffer=context.createVertexBuffer(this.layoutVertexArray,members$3);this.indexBuffer=context.createIndexBuffer(this.indexArray);this.indexBuffer2=context.createIndexBuffer(this.indexArray2)}this.programConfigurations.upload(context);this.uploaded=true}destroy(){if(!this.layoutVertexBuffer)return;this.layoutVertexBuffer.destroy();this.indexBuffer.destroy();this.indexBuffer2.destroy();this.programConfigurations.destroy();this.segments.destroy();this.segments2.destroy()}addFeature(feature,geometry,index,canonical,imagePositions){for(const polygon of classifyRings$1(geometry,EARCUT_MAX_RINGS$1)){let numVertices=0;for(const ring of polygon){numVertices+=ring.length}const triangleSegment=this.segments.prepareSegment(numVertices,this.layoutVertexArray,this.indexArray);const triangleIndex=triangleSegment.vertexLength;const flattened=[];const holeIndices=[];for(const ring of polygon){if(ring.length===0){continue}if(ring!==polygon[0]){holeIndices.push(flattened.length/2)}const lineSegment=this.segments2.prepareSegment(ring.length,this.layoutVertexArray,this.indexArray2);const lineIndex=lineSegment.vertexLength;this.layoutVertexArray.emplaceBack(ring[0].x,ring[0].y);this.indexArray2.emplaceBack(lineIndex+ring.length-1,lineIndex);flattened.push(ring[0].x);flattened.push(ring[0].y);for(let i=1;ilayout$3=layout$3||new Properties({"fill-sort-key":new DataDrivenProperty(v8Spec["layout_fill"]["fill-sort-key"])});let paint$5;const getPaint$5=()=>paint$5=paint$5||new Properties({"fill-antialias":new DataConstantProperty(v8Spec["paint_fill"]["fill-antialias"]),"fill-opacity":new DataDrivenProperty(v8Spec["paint_fill"]["fill-opacity"]),"fill-color":new DataDrivenProperty(v8Spec["paint_fill"]["fill-color"]),"fill-outline-color":new DataDrivenProperty(v8Spec["paint_fill"]["fill-outline-color"]),"fill-translate":new DataConstantProperty(v8Spec["paint_fill"]["fill-translate"]),"fill-translate-anchor":new DataConstantProperty(v8Spec["paint_fill"]["fill-translate-anchor"]),"fill-pattern":new CrossFadedDataDrivenProperty(v8Spec["paint_fill"]["fill-pattern"])});var properties$5={get paint(){return getPaint$5()},get layout(){return getLayout$2()}};class FillStyleLayer extends StyleLayer{constructor(layer){super(layer,properties$5)}recalculate(parameters,availableImages){super.recalculate(parameters,availableImages);const outlineColor=this.paint._values["fill-outline-color"];if(outlineColor.value.kind==="constant"&&outlineColor.value.value===undefined){this.paint._values["fill-outline-color"]=this.paint._values["fill-color"]}}createBucket(parameters){return new FillBucket(parameters)}queryRadius(){return translateDistance(this.paint.get("fill-translate"))}queryIntersectsFeature(queryGeometry,feature,featureState,geometry,zoom,transform,pixelsToTileUnits){const translatedPolygon=translate$4(queryGeometry,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),transform.angle,pixelsToTileUnits);return polygonIntersectsMultiPolygon(translatedPolygon,geometry)}isTileClipped(){return true}}const layout$2=createLayout([{name:"a_pos",components:2,type:"Int16"},{name:"a_normal_ed",components:4,type:"Int16"}],4);const centroidAttributes=createLayout([{name:"a_centroid",components:2,type:"Int16"}],4);const{members:members$2,size:size$2,alignment:alignment$2}=layout$2;var vectorTile={};"use strict";var Point=pointGeometry;var vectortilefeature=VectorTileFeature$2;function VectorTileFeature$2(pbf,end,extent,keys,values){this.properties={};this.extent=extent;this.type=0;this._pbf=pbf;this._geometry=-1;this._keys=keys;this._values=values;pbf.readFields(readFeature,this,end)}function readFeature(tag,feature,pbf){if(tag==1)feature.id=pbf.readVarint();else if(tag==2)readTag(pbf,feature);else if(tag==3)feature.type=pbf.readVarint();else if(tag==4)feature._geometry=pbf.pos}function readTag(pbf,feature){var end=pbf.readVarint()+pbf.pos;while(pbf.pos>3}length--;if(cmd===1||cmd===2){x+=pbf.readSVarint();y+=pbf.readSVarint();if(cmd===1){if(line)lines.push(line);line=[]}line.push(new Point(x,y))}else if(cmd===7){if(line){line.push(line[0].clone())}}else{throw new Error("unknown command "+cmd)}}if(line)lines.push(line);return lines};VectorTileFeature$2.prototype.bbox=function(){var pbf=this._pbf;pbf.pos=this._geometry;var end=pbf.readVarint()+pbf.pos,cmd=1,length=0,x=0,y=0,x1=Infinity,x2=-Infinity,y1=Infinity,y2=-Infinity;while(pbf.pos>3}length--;if(cmd===1||cmd===2){x+=pbf.readSVarint();y+=pbf.readSVarint();if(xx2)x2=x;if(yy2)y2=y}else if(cmd!==7){throw new Error("unknown command "+cmd)}}return[x1,y1,x2,y2]};VectorTileFeature$2.prototype.toGeoJSON=function(x,y,z){var size=this.extent*Math.pow(2,z),x0=this.extent*x,y0=this.extent*y,coords=this.loadGeometry(),type=VectorTileFeature$2.types[this.type],i,j;function project(line){for(var j=0;j>3;value=tag===1?pbf.readString():tag===2?pbf.readFloat():tag===3?pbf.readDouble():tag===4?pbf.readVarint64():tag===5?pbf.readVarint():tag===6?pbf.readSVarint():tag===7?pbf.readBoolean():null}return value}VectorTileLayer$2.prototype.feature=function(i){if(i<0||i>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[i];var end=this._pbf.readVarint()+this._pbf.pos;return new VectorTileFeature$1(this._pbf,end,this.extent,this._keys,this._values)};var vectortilelayer$1=getDefaultExportFromCjs$1(vectortilelayer);"use strict";var VectorTileLayer$1=vectortilelayer;var vectortile=VectorTile$1;function VectorTile$1(pbf,end){this.layers=pbf.readFields(readTile,{},end)}function readTile(tag,layers,pbf){if(tag===3){var layer=new VectorTileLayer$1(pbf,pbf.readVarint()+pbf.pos);if(layer.length)layers[layer.name]=layer}}var vectortile$1=getDefaultExportFromCjs$1(vectortile);var VectorTile=vectorTile.VectorTile=vectortile;var VectorTileFeature=vectorTile.VectorTileFeature=vectortilefeature;var VectorTileLayer=vectorTile.VectorTileLayer=vectortilelayer;const vectorTileFeatureTypes$2=vectorTile.VectorTileFeature.types;const EARCUT_MAX_RINGS=500;const FACTOR=Math.pow(2,13);function addVertex$1(vertexArray,x,y,nx,ny,nz,t,e){vertexArray.emplaceBack(x,y,Math.floor(nx*FACTOR)*2+t,ny*FACTOR*2,nz*FACTOR*2,Math.round(e))}class FillExtrusionBucket{constructor(options){this.zoom=options.zoom;this.overscaling=options.overscaling;this.layers=options.layers;this.layerIds=this.layers.map((layer=>layer.id));this.index=options.index;this.hasPattern=false;this.layoutVertexArray=new FillExtrusionLayoutArray;this.centroidVertexArray=new PosArray;this.indexArray=new TriangleIndexArray;this.programConfigurations=new ProgramConfigurationSet(options.layers,options.zoom);this.segments=new SegmentVector;this.stateDependentLayerIds=this.layers.filter((l=>l.isStateDependent())).map((l=>l.id))}populate(features,options,canonical){this.features=[];this.hasPattern=hasPattern("fill-extrusion",this.layers,options);for(const{feature:feature,id:id,index:index,sourceLayerIndex:sourceLayerIndex}of features){const needGeometry=this.layers[0]._featureFilter.needGeometry;const evaluationFeature=toEvaluationFeature(feature,needGeometry);if(!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom),evaluationFeature,canonical))continue;const bucketFeature={id:id,sourceLayerIndex:sourceLayerIndex,index:index,geometry:needGeometry?evaluationFeature.geometry:loadGeometry(feature),properties:feature.properties,type:feature.type,patterns:{}};if(this.hasPattern){this.features.push(addPatternDependencies("fill-extrusion",this.layers,bucketFeature,this.zoom,options))}else{this.addFeature(bucketFeature,bucketFeature.geometry,index,canonical,{})}options.featureIndex.insert(feature,bucketFeature.geometry,index,sourceLayerIndex,this.index,true)}}addFeatures(options,canonical,imagePositions){for(const feature of this.features){const{geometry:geometry}=feature;this.addFeature(feature,geometry,feature.index,canonical,imagePositions)}}update(states,vtLayer,imagePositions){if(!this.stateDependentLayers.length)return;this.programConfigurations.updatePaintArrays(states,vtLayer,this.stateDependentLayers,imagePositions)}isEmpty(){return this.layoutVertexArray.length===0&&this.centroidVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(context){if(!this.uploaded){this.layoutVertexBuffer=context.createVertexBuffer(this.layoutVertexArray,members$2);this.centroidVertexBuffer=context.createVertexBuffer(this.centroidVertexArray,centroidAttributes.members,true);this.indexBuffer=context.createIndexBuffer(this.indexArray)}this.programConfigurations.upload(context);this.uploaded=true}destroy(){if(!this.layoutVertexBuffer)return;this.layoutVertexBuffer.destroy();this.indexBuffer.destroy();this.programConfigurations.destroy();this.segments.destroy();this.centroidVertexBuffer.destroy()}addFeature(feature,geometry,index,canonical,imagePositions){const centroid={x:0,y:0,vertexCount:0};for(const polygon of classifyRings$1(geometry,EARCUT_MAX_RINGS)){let numVertices=0;for(const ring of polygon){numVertices+=ring.length}let segment=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray);for(const ring of polygon){if(ring.length===0){continue}if(isEntirelyOutside(ring)){continue}let edgeDistance=0;for(let p=0;p=1){const p2=ring[p-1];if(!isBoundaryEdge(p1,p2)){if(segment.vertexLength+4>SegmentVector.MAX_VERTEX_ARRAY_LENGTH){segment=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray)}const perp=p1.sub(p2)._perp()._unit();const dist=p2.dist(p1);if(edgeDistance+dist>32768)edgeDistance=0;addVertex$1(this.layoutVertexArray,p1.x,p1.y,perp.x,perp.y,0,0,edgeDistance);addVertex$1(this.layoutVertexArray,p1.x,p1.y,perp.x,perp.y,0,1,edgeDistance);centroid.x+=2*p1.x;centroid.y+=2*p1.y;centroid.vertexCount+=2;edgeDistance+=dist;addVertex$1(this.layoutVertexArray,p2.x,p2.y,perp.x,perp.y,0,0,edgeDistance);addVertex$1(this.layoutVertexArray,p2.x,p2.y,perp.x,perp.y,0,1,edgeDistance);centroid.x+=2*p2.x;centroid.y+=2*p2.y;centroid.vertexCount+=2;const bottomRight=segment.vertexLength;this.indexArray.emplaceBack(bottomRight,bottomRight+2,bottomRight+1);this.indexArray.emplaceBack(bottomRight+1,bottomRight+2,bottomRight+3);segment.vertexLength+=4;segment.primitiveLength+=2}}}}if(segment.vertexLength+numVertices>SegmentVector.MAX_VERTEX_ARRAY_LENGTH){segment=this.segments.prepareSegment(numVertices,this.layoutVertexArray,this.indexArray)}if(vectorTileFeatureTypes$2[feature.type]!=="Polygon")continue;const flattened=[];const holeIndices=[];const triangleIndex=segment.vertexLength;for(const ring of polygon){if(ring.length===0){continue}if(ring!==polygon[0]){holeIndices.push(flattened.length/2)}for(let i=0;iEXTENT)||p1.y===p2.y&&(p1.y<0||p1.y>EXTENT)}function isEntirelyOutside(ring){return ring.every((p=>p.x<0))||ring.every((p=>p.x>EXTENT))||ring.every((p=>p.y<0))||ring.every((p=>p.y>EXTENT))}let paint$4;const getPaint$4=()=>paint$4=paint$4||new Properties({"fill-extrusion-opacity":new DataConstantProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new DataDrivenProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new DataConstantProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new DataConstantProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new CrossFadedDataDrivenProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new DataDrivenProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new DataDrivenProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-vertical-gradient":new DataConstantProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])});var properties$4={get paint(){return getPaint$4()}};class Point3D extends Point$2{}class FillExtrusionStyleLayer extends StyleLayer{constructor(layer){super(layer,properties$4)}createBucket(parameters){return new FillExtrusionBucket(parameters)}queryRadius(){return translateDistance(this.paint.get("fill-extrusion-translate"))}is3D(){return true}queryIntersectsFeature(queryGeometry,feature,featureState,geometry,zoom,transform,pixelsToTileUnits,pixelPosMatrix){const translatedPolygon=translate$4(queryGeometry,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),transform.angle,pixelsToTileUnits);const height=this.paint.get("fill-extrusion-height").evaluate(feature,featureState);const base=this.paint.get("fill-extrusion-base").evaluate(feature,featureState);const projectedQueryGeometry=projectQueryGeometry(translatedPolygon,pixelPosMatrix,transform,0);const projected=projectExtrusion(geometry,base,height,pixelPosMatrix);const projectedBase=projected[0];const projectedTop=projected[1];return checkIntersection(projectedBase,projectedTop,projectedQueryGeometry)}}function dot(a,b){return a.x*b.x+a.y*b.y}function getIntersectionDistance(projectedQueryGeometry,projectedFace){if(projectedQueryGeometry.length===1){let i=0;const a=projectedFace[i++];let b;while(!b||a.equals(b)){b=projectedFace[i++];if(!b)return Infinity}for(;ilayer.id));this.index=options.index;this.hasPattern=false;this.patternFeatures=[];this.lineClipsArray=[];this.gradients={};this.layers.forEach((layer=>{this.gradients[layer.id]={}}));this.layoutVertexArray=new LineLayoutArray;this.layoutVertexArray2=new LineExtLayoutArray;this.indexArray=new TriangleIndexArray;this.programConfigurations=new ProgramConfigurationSet(options.layers,options.zoom);this.segments=new SegmentVector;this.maxLineLength=0;this.stateDependentLayerIds=this.layers.filter((l=>l.isStateDependent())).map((l=>l.id))}populate(features,options,canonical){this.hasPattern=hasPattern("line",this.layers,options);const lineSortKey=this.layers[0].layout.get("line-sort-key");const sortFeaturesByKey=!lineSortKey.isConstant();const bucketFeatures=[];for(const{feature:feature,id:id,index:index,sourceLayerIndex:sourceLayerIndex}of features){const needGeometry=this.layers[0]._featureFilter.needGeometry;const evaluationFeature=toEvaluationFeature(feature,needGeometry);if(!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom),evaluationFeature,canonical))continue;const sortKey=sortFeaturesByKey?lineSortKey.evaluate(evaluationFeature,{},canonical):undefined;const bucketFeature={id:id,properties:feature.properties,type:feature.type,sourceLayerIndex:sourceLayerIndex,index:index,geometry:needGeometry?evaluationFeature.geometry:loadGeometry(feature),patterns:{},sortKey:sortKey};bucketFeatures.push(bucketFeature)}if(sortFeaturesByKey){bucketFeatures.sort(((a,b)=>a.sortKey-b.sortKey))}for(const bucketFeature of bucketFeatures){const{geometry:geometry,index:index,sourceLayerIndex:sourceLayerIndex}=bucketFeature;if(this.hasPattern){const patternBucketFeature=addPatternDependencies("line",this.layers,bucketFeature,this.zoom,options);this.patternFeatures.push(patternBucketFeature)}else{this.addFeature(bucketFeature,geometry,index,canonical,{})}const feature=features[index].feature;options.featureIndex.insert(feature,geometry,index,sourceLayerIndex,this.index)}}update(states,vtLayer,imagePositions){if(!this.stateDependentLayers.length)return;this.programConfigurations.updatePaintArrays(states,vtLayer,this.stateDependentLayers,imagePositions)}addFeatures(options,canonical,imagePositions){for(const feature of this.patternFeatures){this.addFeature(feature,feature.geometry,feature.index,canonical,imagePositions)}}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(context){if(!this.uploaded){if(this.layoutVertexArray2.length!==0){this.layoutVertexBuffer2=context.createVertexBuffer(this.layoutVertexArray2,members)}this.layoutVertexBuffer=context.createVertexBuffer(this.layoutVertexArray,members$1);this.indexBuffer=context.createIndexBuffer(this.indexArray)}this.programConfigurations.upload(context);this.uploaded=true}destroy(){if(!this.layoutVertexBuffer)return;this.layoutVertexBuffer.destroy();this.indexBuffer.destroy();this.programConfigurations.destroy();this.segments.destroy()}lineFeatureClips(feature){if(!!feature.properties&&Object.prototype.hasOwnProperty.call(feature.properties,"mapbox_clip_start")&&Object.prototype.hasOwnProperty.call(feature.properties,"mapbox_clip_end")){const start=+feature.properties["mapbox_clip_start"];const end=+feature.properties["mapbox_clip_end"];return{start:start,end:end}}}addFeature(feature,geometry,index,canonical,imagePositions){const layout=this.layers[0].layout;const join=layout.get("line-join").evaluate(feature,{});const cap=layout.get("line-cap");const miterLimit=layout.get("line-miter-limit");const roundLimit=layout.get("line-round-limit");this.lineClips=this.lineFeatureClips(feature);for(const line of geometry){this.addLine(line,feature,join,cap,miterLimit,roundLimit)}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,feature,index,imagePositions,canonical)}addLine(vertices,feature,join,cap,miterLimit,roundLimit){this.distance=0;this.scaledDistance=0;this.totalDistance=0;if(this.lineClips){this.lineClipsArray.push(this.lineClips);for(let i=0;i=2&&vertices[len-1].equals(vertices[len-2])){len--}let first=0;while(first0;if(isSharpCorner&&i>first){const prevSegmentLength=currentVertex.dist(prevVertex);if(prevSegmentLength>2*sharpCornerOffset){const newPrevVertex=currentVertex.sub(currentVertex.sub(prevVertex)._mult(sharpCornerOffset/prevSegmentLength)._round());this.updateDistance(prevVertex,newPrevVertex);this.addCurrentVertex(newPrevVertex,prevNormal,0,0,segment);prevVertex=newPrevVertex}}const middleVertex=prevVertex&&nextVertex;let currentJoin=middleVertex?join:isPolygon?"butt":cap;if(middleVertex&¤tJoin==="round"){if(miterLengthmiterLimit){currentJoin="bevel"}if(currentJoin==="bevel"){if(miterLength>2)currentJoin="flipbevel";if(miterLength100){joinNormal=nextNormal.mult(-1)}else{const bevelLength=miterLength*prevNormal.add(nextNormal).mag()/prevNormal.sub(nextNormal).mag();joinNormal._perp()._mult(bevelLength*(lineTurnsLeft?-1:1))}this.addCurrentVertex(currentVertex,joinNormal,0,0,segment);this.addCurrentVertex(currentVertex,joinNormal.mult(-1),0,0,segment)}else if(currentJoin==="bevel"||currentJoin==="fakeround"){const offset=-Math.sqrt(miterLength*miterLength-1);const offsetA=lineTurnsLeft?offset:0;const offsetB=lineTurnsLeft?0:offset;if(prevVertex){this.addCurrentVertex(currentVertex,prevNormal,offsetA,offsetB,segment)}if(currentJoin==="fakeround"){const n=Math.round(approxAngle*180/Math.PI/DEG_PER_TRIANGLE);for(let m=1;m2*sharpCornerOffset){const newCurrentVertex=currentVertex.add(nextVertex.sub(currentVertex)._mult(sharpCornerOffset/nextSegmentLength)._round());this.updateDistance(currentVertex,newCurrentVertex);this.addCurrentVertex(newCurrentVertex,nextNormal,0,0,segment);currentVertex=newCurrentVertex}}}}addCurrentVertex(p,normal,endLeft,endRight,segment,round=false){const leftX=normal.x+normal.y*endLeft;const leftY=normal.y-normal.x*endLeft;const rightX=-normal.x+normal.y*endRight;const rightY=-normal.y-normal.x*endRight;this.addHalfVertex(p,leftX,leftY,round,false,endLeft,segment);this.addHalfVertex(p,rightX,rightY,round,true,-endRight,segment);if(this.distance>MAX_LINE_DISTANCE/2&&this.totalDistance===0){this.distance=0;this.updateScaledDistance();this.addCurrentVertex(p,normal,endLeft,endRight,segment,round)}}addHalfVertex({x:x,y:y},extrudeX,extrudeY,round,up,dir,segment){const totalDistance=this.lineClips?this.scaledDistance*(MAX_LINE_DISTANCE-1):this.scaledDistance;const linesofarScaled=totalDistance*LINE_DISTANCE_SCALE;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);if(this.lineClips){const progressRealigned=this.scaledDistance-this.lineClips.start;const endClipRealigned=this.lineClips.end-this.lineClips.start;const uvX=progressRealigned/endClipRealigned;this.layoutVertexArray2.emplaceBack(uvX,this.lineClipsArray.length)}const e=segment.vertexLength++;if(this.e1>=0&&this.e2>=0){this.indexArray.emplaceBack(this.e1,this.e2,e);segment.primitiveLength++}if(up){this.e2=e}else{this.e1=e}}updateScaledDistance(){this.scaledDistance=this.lineClips?this.lineClips.start+(this.lineClips.end-this.lineClips.start)*this.distance/this.totalDistance:this.distance}updateDistance(prev,next){this.distance+=prev.dist(next);this.updateScaledDistance()}}register("LineBucket",LineBucket,{omit:["layers","patternFeatures"]});let layout$1;const getLayout$1=()=>layout$1=layout$1||new Properties({"line-cap":new DataConstantProperty(v8Spec["layout_line"]["line-cap"]),"line-join":new DataDrivenProperty(v8Spec["layout_line"]["line-join"]),"line-miter-limit":new DataConstantProperty(v8Spec["layout_line"]["line-miter-limit"]),"line-round-limit":new DataConstantProperty(v8Spec["layout_line"]["line-round-limit"]),"line-sort-key":new DataDrivenProperty(v8Spec["layout_line"]["line-sort-key"])});let paint$3;const getPaint$3=()=>paint$3=paint$3||new Properties({"line-opacity":new DataDrivenProperty(v8Spec["paint_line"]["line-opacity"]),"line-color":new DataDrivenProperty(v8Spec["paint_line"]["line-color"]),"line-translate":new DataConstantProperty(v8Spec["paint_line"]["line-translate"]),"line-translate-anchor":new DataConstantProperty(v8Spec["paint_line"]["line-translate-anchor"]),"line-width":new DataDrivenProperty(v8Spec["paint_line"]["line-width"]),"line-gap-width":new DataDrivenProperty(v8Spec["paint_line"]["line-gap-width"]),"line-offset":new DataDrivenProperty(v8Spec["paint_line"]["line-offset"]),"line-blur":new DataDrivenProperty(v8Spec["paint_line"]["line-blur"]),"line-dasharray":new CrossFadedProperty(v8Spec["paint_line"]["line-dasharray"]),"line-pattern":new CrossFadedDataDrivenProperty(v8Spec["paint_line"]["line-pattern"]),"line-gradient":new ColorRampProperty(v8Spec["paint_line"]["line-gradient"])});var properties$3={get paint(){return getPaint$3()},get layout(){return getLayout$1()}};class LineFloorwidthProperty extends DataDrivenProperty{possiblyEvaluate(value,parameters){parameters=new EvaluationParameters(Math.floor(parameters.zoom),{now:parameters.now,fadeDuration:parameters.fadeDuration,zoomHistory:parameters.zoomHistory,transition:parameters.transition});return super.possiblyEvaluate(value,parameters)}evaluate(value,globals,feature,featureState){globals=extend({},globals,{zoom:Math.floor(globals.zoom)});return super.evaluate(value,globals,feature,featureState)}}let lineFloorwidthProperty;class LineStyleLayer extends StyleLayer{constructor(layer){super(layer,properties$3);this.gradientVersion=0;if(!lineFloorwidthProperty){lineFloorwidthProperty=new LineFloorwidthProperty(properties$3.paint.properties["line-width"].specification);lineFloorwidthProperty.useIntegerZoom=true}}_handleSpecialPaintPropertyUpdate(name){if(name==="line-gradient"){const expression=this.gradientExpression();if(isZoomExpression(expression)){this.stepInterpolant=expression._styleExpression.expression instanceof Step}else{this.stepInterpolant=false}this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}recalculate(parameters,availableImages){super.recalculate(parameters,availableImages);this.paint._values["line-floorwidth"]=lineFloorwidthProperty.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,parameters)}createBucket(parameters){return new LineBucket(parameters)}queryRadius(bucket){const lineBucket=bucket;const width=getLineWidth(getMaximumPaintValue("line-width",this,lineBucket),getMaximumPaintValue("line-gap-width",this,lineBucket));const offset=getMaximumPaintValue("line-offset",this,lineBucket);return width/2+Math.abs(offset)+translateDistance(this.paint.get("line-translate"))}queryIntersectsFeature(queryGeometry,feature,featureState,geometry,zoom,transform,pixelsToTileUnits){const translatedPolygon=translate$4(queryGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),transform.angle,pixelsToTileUnits);const halfWidth=pixelsToTileUnits/2*getLineWidth(this.paint.get("line-width").evaluate(feature,featureState),this.paint.get("line-gap-width").evaluate(feature,featureState));const lineOffset=this.paint.get("line-offset").evaluate(feature,featureState);if(lineOffset){geometry=offsetLine(geometry,lineOffset*pixelsToTileUnits)}return polygonIntersectsBufferedMultiLine(translatedPolygon,geometry,halfWidth)}isTileClipped(){return true}}function getLineWidth(lineWidth,lineGapWidth){if(lineGapWidth>0){return lineGapWidth+2*lineWidth}else{return lineWidth}}const symbolLayoutAttributes=createLayout([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4);const dynamicLayoutAttributes=createLayout([{name:"a_projected_pos",components:3,type:"Float32"}],4);const placementOpacityAttributes=createLayout([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const collisionVertexAttributes=createLayout([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"}]);const collisionBox=createLayout([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]);const collisionBoxLayout=createLayout([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4);const collisionCircleLayout=createLayout([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);const quadTriangle=createLayout([{name:"triangle",components:3,type:"Uint16"}]);const placement=createLayout([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]);const symbolInstance=createLayout([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",name:"collisionCircleDiameter"},{type:"Uint16",name:"textAnchorOffsetStartIndex"},{type:"Uint16",name:"textAnchorOffsetEndIndex"}]);const glyphOffset=createLayout([{type:"Float32",name:"offsetX"}]);const lineVertex=createLayout([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]);const textAnchorOffset=createLayout([{type:"Uint16",name:"textAnchor"},{type:"Float32",components:2,name:"textOffset"}]);function transformTextInternal(text,layer,feature){const transform=layer.layout.get("text-transform").evaluate(feature,{});if(transform==="uppercase"){text=text.toLocaleUpperCase()}else if(transform==="lowercase"){text=text.toLocaleLowerCase()}if(rtlWorkerPlugin.applyArabicShaping){text=rtlWorkerPlugin.applyArabicShaping(text)}return text}function transformText(text,layer,feature){text.sections.forEach((section=>{section.text=transformTextInternal(section.text,layer,feature)}));return text}function mergeLines(features){const leftIndex={};const rightIndex={};const mergedFeatures=[];let mergedIndex=0;function add(k){mergedFeatures.push(features[k]);mergedIndex++}function mergeFromRight(leftKey,rightKey,geom){const i=rightIndex[leftKey];delete rightIndex[leftKey];rightIndex[rightKey]=i;mergedFeatures[i].geometry[0].pop();mergedFeatures[i].geometry[0]=mergedFeatures[i].geometry[0].concat(geom[0]);return i}function mergeFromLeft(leftKey,rightKey,geom){const i=leftIndex[rightKey];delete leftIndex[rightKey];leftIndex[leftKey]=i;mergedFeatures[i].geometry[0].shift();mergedFeatures[i].geometry[0]=geom[0].concat(mergedFeatures[i].geometry[0]);return i}function getKey(text,geom,onRight){const point=onRight?geom[0][geom[0].length-1]:geom[0][0];return`${text}:${point.x}:${point.y}`}for(let k=0;kf.geometry))}const verticalizedCharacterMap={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"};function verticalizePunctuation(input){let output="";for(let i=0;i */var read=ieee754$1.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};var write=ieee754$1.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128};"use strict";var pbf=Pbf;var ieee754=ieee754$1;function Pbf(buf){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(buf)?buf:new Uint8Array(buf||0);this.pos=0;this.type=0;this.length=this.buf.length}Pbf.Varint=0;Pbf.Fixed64=1;Pbf.Bytes=2;Pbf.Fixed32=5;var SHIFT_LEFT_32=(1<<16)*(1<<16),SHIFT_RIGHT_32=1/SHIFT_LEFT_32;var TEXT_DECODER_MIN_LENGTH=12;var utf8TextDecoder=typeof TextDecoder==="undefined"?null:new TextDecoder("utf8");Pbf.prototype={destroy:function(){this.buf=null},readFields:function(readField,result,end){end=end||this.length;while(this.pos>3,startPos=this.pos;this.type=val&7;readField(tag,result,this);if(this.pos===startPos)this.skip(val)}return result},readMessage:function(readField,result){return this.readFields(readField,result,this.readVarint()+this.pos)},readFixed32:function(){var val=readUInt32(this.buf,this.pos);this.pos+=4;return val},readSFixed32:function(){var val=readInt32(this.buf,this.pos);this.pos+=4;return val},readFixed64:function(){var val=readUInt32(this.buf,this.pos)+readUInt32(this.buf,this.pos+4)*SHIFT_LEFT_32;this.pos+=8;return val},readSFixed64:function(){var val=readUInt32(this.buf,this.pos)+readInt32(this.buf,this.pos+4)*SHIFT_LEFT_32;this.pos+=8;return val},readFloat:function(){var val=ieee754.read(this.buf,this.pos,true,23,4);this.pos+=4;return val},readDouble:function(){var val=ieee754.read(this.buf,this.pos,true,52,8);this.pos+=8;return val},readVarint:function(isSigned){var buf=this.buf,val,b;b=buf[this.pos++];val=b&127;if(b<128)return val;b=buf[this.pos++];val|=(b&127)<<7;if(b<128)return val;b=buf[this.pos++];val|=(b&127)<<14;if(b<128)return val;b=buf[this.pos++];val|=(b&127)<<21;if(b<128)return val;b=buf[this.pos];val|=(b&15)<<28;return readVarintRemainder(val,isSigned,this)},readVarint64:function(){return this.readVarint(true)},readSVarint:function(){var num=this.readVarint();return num%2===1?(num+1)/-2:num/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var end=this.readVarint()+this.pos;var pos=this.pos;this.pos=end;if(end-pos>=TEXT_DECODER_MIN_LENGTH&&utf8TextDecoder){return readUtf8TextDecoder(this.buf,pos,end)}return readUtf8(this.buf,pos,end)},readBytes:function(){var end=this.readVarint()+this.pos,buffer=this.buf.subarray(this.pos,end);this.pos=end;return buffer},readPackedVarint:function(arr,isSigned){if(this.type!==Pbf.Bytes)return arr.push(this.readVarint(isSigned));var end=readPackedEnd(this);arr=arr||[];while(this.pos127){}else if(type===Pbf.Bytes)this.pos=this.readVarint()+this.pos;else if(type===Pbf.Fixed32)this.pos+=4;else if(type===Pbf.Fixed64)this.pos+=8;else throw new Error("Unimplemented type: "+type)},writeTag:function(tag,type){this.writeVarint(tag<<3|type)},realloc:function(min){var length=this.length||16;while(length268435455||val<0){writeBigVarint(val,this);return}this.realloc(4);this.buf[this.pos++]=val&127|(val>127?128:0);if(val<=127)return;this.buf[this.pos++]=(val>>>=7)&127|(val>127?128:0);if(val<=127)return;this.buf[this.pos++]=(val>>>=7)&127|(val>127?128:0);if(val<=127)return;this.buf[this.pos++]=val>>>7&127},writeSVarint:function(val){this.writeVarint(val<0?-val*2-1:val*2)},writeBoolean:function(val){this.writeVarint(Boolean(val))},writeString:function(str){str=String(str);this.realloc(str.length*4);this.pos++;var startPos=this.pos;this.pos=writeUtf8(this.buf,str,this.pos);var len=this.pos-startPos;if(len>=128)makeRoomForExtraLength(startPos,len,this);this.pos=startPos-1;this.writeVarint(len);this.pos+=len},writeFloat:function(val){this.realloc(4);ieee754.write(this.buf,val,this.pos,true,23,4);this.pos+=4},writeDouble:function(val){this.realloc(8);ieee754.write(this.buf,val,this.pos,true,52,8);this.pos+=8},writeBytes:function(buffer){var len=buffer.length;this.writeVarint(len);this.realloc(len);for(var i=0;i=128)makeRoomForExtraLength(startPos,len,this);this.pos=startPos-1;this.writeVarint(len);this.pos+=len},writeMessage:function(tag,fn,obj){this.writeTag(tag,Pbf.Bytes);this.writeRawMessage(fn,obj)},writePackedVarint:function(tag,arr){if(arr.length)this.writeMessage(tag,writePackedVarint,arr)},writePackedSVarint:function(tag,arr){if(arr.length)this.writeMessage(tag,writePackedSVarint,arr)},writePackedBoolean:function(tag,arr){if(arr.length)this.writeMessage(tag,writePackedBoolean,arr)},writePackedFloat:function(tag,arr){if(arr.length)this.writeMessage(tag,writePackedFloat,arr)},writePackedDouble:function(tag,arr){if(arr.length)this.writeMessage(tag,writePackedDouble,arr)},writePackedFixed32:function(tag,arr){if(arr.length)this.writeMessage(tag,writePackedFixed32,arr)},writePackedSFixed32:function(tag,arr){if(arr.length)this.writeMessage(tag,writePackedSFixed32,arr)},writePackedFixed64:function(tag,arr){if(arr.length)this.writeMessage(tag,writePackedFixed64,arr)},writePackedSFixed64:function(tag,arr){if(arr.length)this.writeMessage(tag,writePackedSFixed64,arr)},writeBytesField:function(tag,buffer){this.writeTag(tag,Pbf.Bytes);this.writeBytes(buffer)},writeFixed32Field:function(tag,val){this.writeTag(tag,Pbf.Fixed32);this.writeFixed32(val)},writeSFixed32Field:function(tag,val){this.writeTag(tag,Pbf.Fixed32);this.writeSFixed32(val)},writeFixed64Field:function(tag,val){this.writeTag(tag,Pbf.Fixed64);this.writeFixed64(val)},writeSFixed64Field:function(tag,val){this.writeTag(tag,Pbf.Fixed64);this.writeSFixed64(val)},writeVarintField:function(tag,val){this.writeTag(tag,Pbf.Varint);this.writeVarint(val)},writeSVarintField:function(tag,val){this.writeTag(tag,Pbf.Varint);this.writeSVarint(val)},writeStringField:function(tag,str){this.writeTag(tag,Pbf.Bytes);this.writeString(str)},writeFloatField:function(tag,val){this.writeTag(tag,Pbf.Fixed32);this.writeFloat(val)},writeDoubleField:function(tag,val){this.writeTag(tag,Pbf.Fixed64);this.writeDouble(val)},writeBooleanField:function(tag,val){this.writeVarintField(tag,Boolean(val))}};function readVarintRemainder(l,s,p){var buf=p.buf,h,b;b=buf[p.pos++];h=(b&112)>>4;if(b<128)return toNum(l,h,s);b=buf[p.pos++];h|=(b&127)<<3;if(b<128)return toNum(l,h,s);b=buf[p.pos++];h|=(b&127)<<10;if(b<128)return toNum(l,h,s);b=buf[p.pos++];h|=(b&127)<<17;if(b<128)return toNum(l,h,s);b=buf[p.pos++];h|=(b&127)<<24;if(b<128)return toNum(l,h,s);b=buf[p.pos++];h|=(b&1)<<31;if(b<128)return toNum(l,h,s);throw new Error("Expected varint not more than 10 bytes")}function readPackedEnd(pbf){return pbf.type===Pbf.Bytes?pbf.readVarint()+pbf.pos:pbf.pos+1}function toNum(low,high,isSigned){if(isSigned){return high*4294967296+(low>>>0)}return(high>>>0)*4294967296+(low>>>0)}function writeBigVarint(val,pbf){var low,high;if(val>=0){low=val%4294967296|0;high=val/4294967296|0}else{low=~(-val%4294967296);high=~(-val/4294967296);if(low^4294967295){low=low+1|0}else{low=0;high=high+1|0}}if(val>=0x10000000000000000||val<-0x10000000000000000){throw new Error("Given varint doesn't fit into 10 bytes")}pbf.realloc(10);writeBigVarintLow(low,high,pbf);writeBigVarintHigh(high,pbf)}function writeBigVarintLow(low,high,pbf){pbf.buf[pbf.pos++]=low&127|128;low>>>=7;pbf.buf[pbf.pos++]=low&127|128;low>>>=7;pbf.buf[pbf.pos++]=low&127|128;low>>>=7;pbf.buf[pbf.pos++]=low&127|128;low>>>=7;pbf.buf[pbf.pos]=low&127}function writeBigVarintHigh(high,pbf){var lsb=(high&7)<<4;pbf.buf[pbf.pos++]|=lsb|((high>>>=3)?128:0);if(!high)return;pbf.buf[pbf.pos++]=high&127|((high>>>=7)?128:0);if(!high)return;pbf.buf[pbf.pos++]=high&127|((high>>>=7)?128:0);if(!high)return;pbf.buf[pbf.pos++]=high&127|((high>>>=7)?128:0);if(!high)return;pbf.buf[pbf.pos++]=high&127|((high>>>=7)?128:0);if(!high)return;pbf.buf[pbf.pos++]=high&127}function makeRoomForExtraLength(startPos,len,pbf){var extraLen=len<=16383?1:len<=2097151?2:len<=268435455?3:Math.floor(Math.log(len)/(Math.LN2*7));pbf.realloc(extraLen);for(var i=pbf.pos-1;i>=startPos;i--)pbf.buf[i+extraLen]=pbf.buf[i]}function writePackedVarint(arr,pbf){for(var i=0;i>>8;buf[pos+2]=val>>>16;buf[pos+3]=val>>>24}function readInt32(buf,pos){return(buf[pos]|buf[pos+1]<<8|buf[pos+2]<<16)+(buf[pos+3]<<24)}function readUtf8(buf,pos,end){var str="";var i=pos;while(i239?4:b0>223?3:b0>191?2:1;if(i+bytesPerSequence>end)break;var b1,b2,b3;if(bytesPerSequence===1){if(b0<128){c=b0}}else if(bytesPerSequence===2){b1=buf[i+1];if((b1&192)===128){c=(b0&31)<<6|b1&63;if(c<=127){c=null}}}else if(bytesPerSequence===3){b1=buf[i+1];b2=buf[i+2];if((b1&192)===128&&(b2&192)===128){c=(b0&15)<<12|(b1&63)<<6|b2&63;if(c<=2047||c>=55296&&c<=57343){c=null}}}else if(bytesPerSequence===4){b1=buf[i+1];b2=buf[i+2];b3=buf[i+3];if((b1&192)===128&&(b2&192)===128&&(b3&192)===128){c=(b0&15)<<18|(b1&63)<<12|(b2&63)<<6|b3&63;if(c<=65535||c>=1114112){c=null}}}if(c===null){c=65533;bytesPerSequence=1}else if(c>65535){c-=65536;str+=String.fromCharCode(c>>>10&1023|55296);c=56320|c&1023}str+=String.fromCharCode(c);i+=bytesPerSequence}return str}function readUtf8TextDecoder(buf,pos,end){return utf8TextDecoder.decode(buf.subarray(pos,end))}function writeUtf8(buf,str,pos){for(var i=0,c,lead;i55295&&c<57344){if(lead){if(c<56320){buf[pos++]=239;buf[pos++]=191;buf[pos++]=189;lead=c;continue}else{c=lead-55296<<10|c-56320|65536;lead=null}}else{if(c>56319||i+1===str.length){buf[pos++]=239;buf[pos++]=191;buf[pos++]=189}else{lead=c}continue}}else if(lead){buf[pos++]=239;buf[pos++]=191;buf[pos++]=189;lead=null}if(c<128){buf[pos++]=c}else{if(c<2048){buf[pos++]=c>>6|192}else{if(c<65536){buf[pos++]=c>>12|224}else{buf[pos++]=c>>18|240;buf[pos++]=c>>12&63|128}buf[pos++]=c>>6&63|128}buf[pos++]=c&63|128}}return pos}var Protobuf=getDefaultExportFromCjs$1(pbf);const border$1=3;function readFontstacks(tag,glyphs,pbf){if(tag===1){pbf.readMessage(readFontstack,glyphs)}}function readFontstack(tag,glyphs,pbf){if(tag===3){const{id:id,bitmap:bitmap,width:width,height:height,left:left,top:top,advance:advance}=pbf.readMessage(readGlyph,{});glyphs.push({id:id,bitmap:new AlphaImage({width:width+2*border$1,height:height+2*border$1},bitmap),metrics:{width:width,height:height,left:left,top:top,advance:advance}})}}function readGlyph(tag,glyph,pbf){if(tag===1)glyph.id=pbf.readVarint();else if(tag===2)glyph.bitmap=pbf.readBytes();else if(tag===3)glyph.width=pbf.readVarint();else if(tag===4)glyph.height=pbf.readVarint();else if(tag===5)glyph.left=pbf.readSVarint();else if(tag===6)glyph.top=pbf.readSVarint();else if(tag===7)glyph.advance=pbf.readVarint()}function parseGlyphPbf(data){return new Protobuf(data).readFields(readFontstacks,[])}const GLYPH_PBF_BORDER=border$1;function potpack(boxes){let area=0;let maxWidth=0;for(const box of boxes){area+=box.w*box.h;maxWidth=Math.max(maxWidth,box.w)}boxes.sort(((a,b)=>b.h-a.h));const startWidth=Math.max(Math.ceil(Math.sqrt(area/.95)),maxWidth);const spaces=[{x:0,y:0,w:startWidth,h:Infinity}];let width=0;let height=0;for(const box of boxes){for(let i=spaces.length-1;i>=0;i--){const space=spaces[i];if(box.w>space.w||box.h>space.h)continue;box.x=space.x;box.y=space.y;height=Math.max(height,box.y+box.h);width=Math.max(width,box.x+box.w);if(box.w===space.w&&box.h===space.h){const last=spaces.pop();if(i=0&&i>=beginningWhitespace&&whitespace[this.text.charCodeAt(i)];i--){trailingWhitespace--}this.text=this.text.substring(beginningWhitespace,trailingWhitespace);this.sectionIndex=this.sectionIndex.slice(beginningWhitespace,trailingWhitespace)}substring(start,end){const substring=new TaggedString;substring.text=this.text.substring(start,end);substring.sectionIndex=this.sectionIndex.slice(start,end);substring.sections=this.sections;return substring}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce(((max,index)=>Math.max(max,this.sections[index].scale)),0)}addTextSection(section,defaultFontStack){this.text+=section.text;this.sections.push(SectionOptions.forText(section.scale,section.fontStack||defaultFontStack));const index=this.sections.length-1;for(let i=0;i=PUAend)return null;return++this.imageSectionID}}function breakLines(input,lineBreakPoints){const lines=[];const text=input.text;let start=0;for(const lineBreak of lineBreakPoints){lines.push(input.substring(start,lineBreak));start=lineBreak}if(start=0;let currentX=0;for(let i=0;i0&&offset>lineOffset){lineOffset=offset}}if(!vertical){positionedGlyphs.push({glyph:codePoint,imageName:imageName,x:x,y:y+baselineOffset,vertical:vertical,scale:section.scale,fontStack:section.fontStack,sectionIndex:sectionIndex,metrics:metrics,rect:rect});x+=metrics.advance*section.scale+spacing}else{shaping.verticalizable=true;positionedGlyphs.push({glyph:codePoint,imageName:imageName,x:x,y:y+baselineOffset,vertical:vertical,scale:section.scale,fontStack:section.fontStack,sectionIndex:sectionIndex,metrics:metrics,rect:rect});x+=verticalAdvance*section.scale+spacing}}if(positionedGlyphs.length!==0){const lineLength=x-spacing;maxLineLength=Math.max(lineLength,maxLineLength);justifyLine(positionedGlyphs,0,positionedGlyphs.length-1,justify,lineOffset)}x=0;const currentLineHeight=lineHeight*lineMaxScale+lineOffset;positionedLine.lineOffset=Math.max(lineOffset,maxLineOffset);y+=currentLineHeight;maxLineHeight=Math.max(currentLineHeight,maxLineHeight);++lineIndex}const height=y-SHAPING_DEFAULT_OFFSET;const{horizontalAlign:horizontalAlign,verticalAlign:verticalAlign}=getAnchorAlignment(textAnchor);align(shaping.positionedLines,justify,horizontalAlign,verticalAlign,maxLineLength,maxLineHeight,lineHeight,height,lines.length);shaping.top+=-verticalAlign*height;shaping.bottom=shaping.top+height;shaping.left+=-horizontalAlign*maxLineLength;shaping.right=shaping.left+maxLineLength}function justifyLine(positionedGlyphs,start,end,justify,lineOffset){if(!justify&&!lineOffset)return;const lastPositionedGlyph=positionedGlyphs[end];const lastAdvance=lastPositionedGlyph.metrics.advance*lastPositionedGlyph.scale;const lineIndent=(positionedGlyphs[end].x+lastAdvance)*justify;for(let j=start;j<=end;j++){positionedGlyphs[j].x-=lineIndent;positionedGlyphs[j].y+=lineOffset}}function align(positionedLines,justify,horizontalAlign,verticalAlign,maxLineLength,maxLineHeight,lineHeight,blockHeight,lineCount){const shiftX=(justify-horizontalAlign)*maxLineLength;let shiftY=0;if(maxLineHeight!==lineHeight){shiftY=-blockHeight*verticalAlign-SHAPING_DEFAULT_OFFSET}else{shiftY=(-verticalAlign*lineCount+.5)*lineHeight}for(const line of positionedLines){for(const positionedGlyph of line.positionedGlyphs){positionedGlyph.x+=shiftX;positionedGlyph.y+=shiftY}}}function shapeIcon(image,iconOffset,iconAnchor){const{horizontalAlign:horizontalAlign,verticalAlign:verticalAlign}=getAnchorAlignment(iconAnchor);const dx=iconOffset[0];const dy=iconOffset[1];const x1=dx-image.displaySize[0]*horizontalAlign;const x2=x1+image.displaySize[0];const y1=dy-image.displaySize[1]*verticalAlign;const y2=y1+image.displaySize[1];return{image:image,top:y1,bottom:y2,left:x1,right:x2}}function fitIconToText(shapedIcon,shapedText,textFit,padding,iconOffset,fontScale){const image=shapedIcon.image;let collisionPadding;if(image.content){const content=image.content;const pixelRatio=image.pixelRatio||1;collisionPadding=[content[0]/pixelRatio,content[1]/pixelRatio,image.displaySize[0]-content[2]/pixelRatio,image.displaySize[1]-content[3]/pixelRatio]}const textLeft=shapedText.left*fontScale;const textRight=shapedText.right*fontScale;let top,right,bottom,left;if(textFit==="width"||textFit==="both"){left=iconOffset[0]+textLeft-padding[3];right=iconOffset[0]+textRight+padding[1]}else{left=iconOffset[0]+(textLeft+textRight-image.displaySize[0])/2;right=left+image.displaySize[0]}const textTop=shapedText.top*fontScale;const textBottom=shapedText.bottom*fontScale;if(textFit==="height"||textFit==="both"){top=iconOffset[1]+textTop-padding[0];bottom=iconOffset[1]+textBottom+padding[2]}else{top=iconOffset[1]+(textTop+textBottom-image.displaySize[1])/2;bottom=top+image.displaySize[1]}return{image:image,top:top,right:right,bottom:bottom,left:left,collisionPadding:collisionPadding}}const MAX_GLYPH_ICON_SIZE=255;const SIZE_PACK_FACTOR=128;const MAX_PACKED_SIZE=MAX_GLYPH_ICON_SIZE*SIZE_PACK_FACTOR;function getSizeData(tileZoom,value){const{expression:expression}=value;if(expression.kind==="constant"){const layoutSize=expression.evaluate(new EvaluationParameters(tileZoom+1));return{kind:"constant",layoutSize:layoutSize}}else if(expression.kind==="source"){return{kind:"source"}}else{const{zoomStops:zoomStops,interpolationType:interpolationType}=expression;let lower=0;while(lowerlayer.id));this.index=options.index;this.pixelRatio=options.pixelRatio;this.sourceLayerIndex=options.sourceLayerIndex;this.hasPattern=false;this.hasRTLText=false;this.sortKeyRanges=[];this.collisionCircleArray=[];this.placementInvProjMatrix=identity$2([]);this.placementViewportMatrix=identity$2([]);const layer=this.layers[0];const unevaluatedLayoutValues=layer._unevaluatedLayout._values;this.textSizeData=getSizeData(this.zoom,unevaluatedLayoutValues["text-size"]);this.iconSizeData=getSizeData(this.zoom,unevaluatedLayoutValues["icon-size"]);const layout=this.layers[0].layout;const sortKey=layout.get("symbol-sort-key");const zOrder=layout.get("symbol-z-order");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");this.sortFeaturesByKey=zOrder!=="viewport-y"&&!sortKey.isConstant();const zOrderByViewportY=zOrder==="viewport-y"||zOrder==="auto"&&!this.sortFeaturesByKey;this.sortFeaturesByY=zOrderByViewportY&&this.canOverlap;if(layout.get("symbol-placement")==="point"){this.writingModes=layout.get("text-writing-mode").map((wm=>exports.WritingMode[wm]))}this.stateDependentLayerIds=this.layers.filter((l=>l.isStateDependent())).map((l=>l.id));this.sourceID=options.sourceID}createArrays(){this.text=new SymbolBuffers(new ProgramConfigurationSet(this.layers,this.zoom,(property=>/^text/.test(property))));this.icon=new SymbolBuffers(new ProgramConfigurationSet(this.layers,this.zoom,(property=>/^icon/.test(property))));this.glyphOffsetArray=new GlyphOffsetArray;this.lineVertexArray=new SymbolLineVertexArray;this.symbolInstances=new SymbolInstanceArray;this.textAnchorOffsets=new TextAnchorOffsetArray}calculateGlyphDependencies(text,stack,textAlongLine,allowVerticalPlacement,doesAllowVerticalWritingMode){for(let i=0;i0)&&(textFont.value.kind!=="constant"||textFont.value.value.length>0);const hasIcon=iconImage.value.kind!=="constant"||!!iconImage.value.value||Object.keys(iconImage.parameters).length>0;const symbolSortKey=layout.get("symbol-sort-key");this.features=[];if(!hasText&&!hasIcon){return}const icons=options.iconDependencies;const stacks=options.glyphDependencies;const availableImages=options.availableImages;const globalProperties=new EvaluationParameters(this.zoom);for(const{feature:feature,id:id,index:index,sourceLayerIndex:sourceLayerIndex}of features){const needGeometry=layer._featureFilter.needGeometry;const evaluationFeature=toEvaluationFeature(feature,needGeometry);if(!layer._featureFilter.filter(globalProperties,evaluationFeature,canonical)){continue}if(!needGeometry)evaluationFeature.geometry=loadGeometry(feature);let text;if(hasText){const resolvedTokens=layer.getValueAndResolveTokens("text-field",evaluationFeature,canonical,availableImages);const formattedText=Formatted.factory(resolvedTokens);if(containsRTLText(formattedText)){this.hasRTLText=true}if(!this.hasRTLText||rtlWorkerPlugin.getRTLTextPluginStatus()==="unavailable"||this.hasRTLText&&rtlWorkerPlugin.isParsed()){text=transformText(formattedText,layer,evaluationFeature)}}let icon;if(hasIcon){const resolvedTokens=layer.getValueAndResolveTokens("icon-image",evaluationFeature,canonical,availableImages);if(resolvedTokens instanceof ResolvedImage){icon=resolvedTokens}else{icon=ResolvedImage.fromString(resolvedTokens)}}if(!text&&!icon){continue}const sortKey=this.sortFeaturesByKey?symbolSortKey.evaluate(evaluationFeature,{},canonical):undefined;const symbolFeature={id:id,text:text,icon:icon,index:index,sourceLayerIndex:sourceLayerIndex,geometry:evaluationFeature.geometry,properties:feature.properties,type:vectorTileFeatureTypes[feature.type],sortKey:sortKey};this.features.push(symbolFeature);if(icon){icons[icon.name]=true}if(text){const fontStack=textFont.evaluate(evaluationFeature,{},canonical).join(",");const textAlongLine=layout.get("text-rotation-alignment")!=="viewport"&&layout.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(exports.WritingMode.vertical)>=0;for(const section of text.sections){if(!section.image){const doesAllowVerticalWritingMode=allowsVerticalWritingMode(text.toString());const sectionFont=section.fontStack||fontStack;const sectionStack=stacks[sectionFont]=stacks[sectionFont]||{};this.calculateGlyphDependencies(section.text,sectionStack,textAlongLine,this.allowVerticalPlacement,doesAllowVerticalWritingMode)}else{icons[section.image.name]=true}}}}if(layout.get("symbol-placement")==="line"){this.features=mergeLines(this.features)}if(this.sortFeaturesByKey){this.features.sort(((a,b)=>a.sortKey-b.sortKey))}}update(states,vtLayer,imagePositions){if(!this.stateDependentLayers.length)return;this.text.programConfigurations.updatePaintArrays(states,vtLayer,this.layers,imagePositions);this.icon.programConfigurations.updatePaintArrays(states,vtLayer,this.layers,imagePositions)}isEmpty(){return this.symbolInstances.length===0&&!this.hasRTLText}uploadPending(){return!this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(context){if(!this.uploaded&&this.hasDebugData()){this.textCollisionBox.upload(context);this.iconCollisionBox.upload(context)}this.text.upload(context,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload);this.icon.upload(context,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload);this.uploaded=true}destroyDebugData(){this.textCollisionBox.destroy();this.iconCollisionBox.destroy()}destroy(){this.text.destroy();this.icon.destroy();if(this.hasDebugData()){this.destroyDebugData()}}addToLineVertexArray(anchor,line){const lineStartIndex=this.lineVertexArray.length;if(anchor.segment!==undefined){let sumForwardLength=anchor.dist(line[anchor.segment+1]);let sumBackwardLength=anchor.dist(line[anchor.segment]);const vertices={};for(let i=anchor.segment+1;i=0;i--){vertices[i]={x:line[i].x,y:line[i].y,tileUnitDistanceFromAnchor:sumBackwardLength};if(i>0){sumBackwardLength+=line[i-1].dist(line[i])}}for(let i=0;i0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}addIndicesForPlacedSymbol(iconOrText,placedSymbolIndex){const placedSymbol=iconOrText.placedSymbolArray.get(placedSymbolIndex);const endIndex=placedSymbol.vertexStartIndex+placedSymbol.numGlyphs*4;for(let vertexIndex=placedSymbol.vertexStartIndex;vertexIndexrotatedYs[aIndex]-rotatedYs[bIndex]||featureIndexes[bIndex]-featureIndexes[aIndex]));return result}addToSortKeyRanges(symbolInstanceIndex,sortKey){const last=this.sortKeyRanges[this.sortKeyRanges.length-1];if(last&&last.sortKey===sortKey){last.symbolInstanceEnd=symbolInstanceIndex+1}else{this.sortKeyRanges.push({sortKey:sortKey,symbolInstanceStart:symbolInstanceIndex,symbolInstanceEnd:symbolInstanceIndex+1})}}sortFeatures(angle){if(!this.sortFeaturesByY)return;if(this.sortedAngle===angle)return;if(this.text.segments.get().length>1||this.icon.segments.get().length>1)return;this.symbolInstanceIndexes=this.getSortedSymbolIndexes(angle);this.sortedAngle=angle;this.text.indexArray.clear();this.icon.indexArray.clear();this.featureSortOrder=[];for(const i of this.symbolInstanceIndexes){const symbolInstance=this.symbolInstances.get(i);this.featureSortOrder.push(symbolInstance.featureIndex);[symbolInstance.rightJustifiedTextSymbolIndex,symbolInstance.centerJustifiedTextSymbolIndex,symbolInstance.leftJustifiedTextSymbolIndex].forEach(((index,i,array)=>{if(index>=0&&array.indexOf(index)===i){this.addIndicesForPlacedSymbol(this.text,index)}}));if(symbolInstance.verticalPlacedTextSymbolIndex>=0){this.addIndicesForPlacedSymbol(this.text,symbolInstance.verticalPlacedTextSymbolIndex)}if(symbolInstance.placedIconSymbolIndex>=0){this.addIndicesForPlacedSymbol(this.icon,symbolInstance.placedIconSymbolIndex)}if(symbolInstance.verticalPlacedIconSymbolIndex>=0){this.addIndicesForPlacedSymbol(this.icon,symbolInstance.verticalPlacedIconSymbolIndex)}}if(this.text.indexBuffer)this.text.indexBuffer.updateData(this.text.indexArray);if(this.icon.indexBuffer)this.icon.indexBuffer.updateData(this.icon.indexArray)}}register("SymbolBucket",SymbolBucket,{omit:["layers","collisionBoxArray","features","compareText"]});SymbolBucket.MAX_GLYPHS=65535;SymbolBucket.addDynamicAttributes=addDynamicAttributes;function resolveTokens(properties,text){return text.replace(/{([^{}]+)}/g,((match,key)=>properties&&key in properties?String(properties[key]):""))}let layout;const getLayout=()=>layout=layout||new Properties({"symbol-placement":new DataConstantProperty(v8Spec["layout_symbol"]["symbol-placement"]),"symbol-spacing":new DataConstantProperty(v8Spec["layout_symbol"]["symbol-spacing"]),"symbol-avoid-edges":new DataConstantProperty(v8Spec["layout_symbol"]["symbol-avoid-edges"]),"symbol-sort-key":new DataDrivenProperty(v8Spec["layout_symbol"]["symbol-sort-key"]),"symbol-z-order":new DataConstantProperty(v8Spec["layout_symbol"]["symbol-z-order"]),"icon-allow-overlap":new DataConstantProperty(v8Spec["layout_symbol"]["icon-allow-overlap"]),"icon-overlap":new DataConstantProperty(v8Spec["layout_symbol"]["icon-overlap"]),"icon-ignore-placement":new DataConstantProperty(v8Spec["layout_symbol"]["icon-ignore-placement"]),"icon-optional":new DataConstantProperty(v8Spec["layout_symbol"]["icon-optional"]),"icon-rotation-alignment":new DataConstantProperty(v8Spec["layout_symbol"]["icon-rotation-alignment"]),"icon-size":new DataDrivenProperty(v8Spec["layout_symbol"]["icon-size"]),"icon-text-fit":new DataConstantProperty(v8Spec["layout_symbol"]["icon-text-fit"]),"icon-text-fit-padding":new DataConstantProperty(v8Spec["layout_symbol"]["icon-text-fit-padding"]),"icon-image":new DataDrivenProperty(v8Spec["layout_symbol"]["icon-image"]),"icon-rotate":new DataDrivenProperty(v8Spec["layout_symbol"]["icon-rotate"]),"icon-padding":new DataDrivenProperty(v8Spec["layout_symbol"]["icon-padding"]),"icon-keep-upright":new DataConstantProperty(v8Spec["layout_symbol"]["icon-keep-upright"]),"icon-offset":new DataDrivenProperty(v8Spec["layout_symbol"]["icon-offset"]),"icon-anchor":new DataDrivenProperty(v8Spec["layout_symbol"]["icon-anchor"]),"icon-pitch-alignment":new DataConstantProperty(v8Spec["layout_symbol"]["icon-pitch-alignment"]),"text-pitch-alignment":new DataConstantProperty(v8Spec["layout_symbol"]["text-pitch-alignment"]),"text-rotation-alignment":new DataConstantProperty(v8Spec["layout_symbol"]["text-rotation-alignment"]),"text-field":new DataDrivenProperty(v8Spec["layout_symbol"]["text-field"]),"text-font":new DataDrivenProperty(v8Spec["layout_symbol"]["text-font"]),"text-size":new DataDrivenProperty(v8Spec["layout_symbol"]["text-size"]),"text-max-width":new DataDrivenProperty(v8Spec["layout_symbol"]["text-max-width"]),"text-line-height":new DataConstantProperty(v8Spec["layout_symbol"]["text-line-height"]),"text-letter-spacing":new DataDrivenProperty(v8Spec["layout_symbol"]["text-letter-spacing"]),"text-justify":new DataDrivenProperty(v8Spec["layout_symbol"]["text-justify"]),"text-radial-offset":new DataDrivenProperty(v8Spec["layout_symbol"]["text-radial-offset"]),"text-variable-anchor":new DataConstantProperty(v8Spec["layout_symbol"]["text-variable-anchor"]),"text-variable-anchor-offset":new DataDrivenProperty(v8Spec["layout_symbol"]["text-variable-anchor-offset"]),"text-anchor":new DataDrivenProperty(v8Spec["layout_symbol"]["text-anchor"]),"text-max-angle":new DataConstantProperty(v8Spec["layout_symbol"]["text-max-angle"]),"text-writing-mode":new DataConstantProperty(v8Spec["layout_symbol"]["text-writing-mode"]),"text-rotate":new DataDrivenProperty(v8Spec["layout_symbol"]["text-rotate"]),"text-padding":new DataConstantProperty(v8Spec["layout_symbol"]["text-padding"]),"text-keep-upright":new DataConstantProperty(v8Spec["layout_symbol"]["text-keep-upright"]),"text-transform":new DataDrivenProperty(v8Spec["layout_symbol"]["text-transform"]),"text-offset":new DataDrivenProperty(v8Spec["layout_symbol"]["text-offset"]),"text-allow-overlap":new DataConstantProperty(v8Spec["layout_symbol"]["text-allow-overlap"]),"text-overlap":new DataConstantProperty(v8Spec["layout_symbol"]["text-overlap"]),"text-ignore-placement":new DataConstantProperty(v8Spec["layout_symbol"]["text-ignore-placement"]),"text-optional":new DataConstantProperty(v8Spec["layout_symbol"]["text-optional"])});let paint$2;const getPaint$2=()=>paint$2=paint$2||new Properties({"icon-opacity":new DataDrivenProperty(v8Spec["paint_symbol"]["icon-opacity"]),"icon-color":new DataDrivenProperty(v8Spec["paint_symbol"]["icon-color"]),"icon-halo-color":new DataDrivenProperty(v8Spec["paint_symbol"]["icon-halo-color"]),"icon-halo-width":new DataDrivenProperty(v8Spec["paint_symbol"]["icon-halo-width"]),"icon-halo-blur":new DataDrivenProperty(v8Spec["paint_symbol"]["icon-halo-blur"]),"icon-translate":new DataConstantProperty(v8Spec["paint_symbol"]["icon-translate"]),"icon-translate-anchor":new DataConstantProperty(v8Spec["paint_symbol"]["icon-translate-anchor"]),"text-opacity":new DataDrivenProperty(v8Spec["paint_symbol"]["text-opacity"]),"text-color":new DataDrivenProperty(v8Spec["paint_symbol"]["text-color"],{runtimeType:ColorType,getOverride:o=>o.textColor,hasOverride:o=>!!o.textColor}),"text-halo-color":new DataDrivenProperty(v8Spec["paint_symbol"]["text-halo-color"]),"text-halo-width":new DataDrivenProperty(v8Spec["paint_symbol"]["text-halo-width"]),"text-halo-blur":new DataDrivenProperty(v8Spec["paint_symbol"]["text-halo-blur"]),"text-translate":new DataConstantProperty(v8Spec["paint_symbol"]["text-translate"]),"text-translate-anchor":new DataConstantProperty(v8Spec["paint_symbol"]["text-translate-anchor"])});var properties$2={get paint(){return getPaint$2()},get layout(){return getLayout()}};class FormatSectionOverride{constructor(defaultValue){if(defaultValue.property.overrides===undefined)throw new Error("overrides must be provided to instantiate FormatSectionOverride class");this.type=defaultValue.property.overrides?defaultValue.property.overrides.runtimeType:NullType;this.defaultValue=defaultValue}evaluate(ctx){if(ctx.formattedSection){const overrides=this.defaultValue.property.overrides;if(overrides&&overrides.hasOverride(ctx.formattedSection)){return overrides.getOverride(ctx.formattedSection)}}if(ctx.feature&&ctx.featureState){return this.defaultValue.evaluate(ctx.feature,ctx.featureState)}return this.defaultValue.property.specification.default}eachChild(fn){if(!this.defaultValue.isConstant()){const expr=this.defaultValue.value;fn(expr._styleExpression.expression)}}outputDefined(){return false}serialize(){return null}}register("FormatSectionOverride",FormatSectionOverride,{omit:["defaultValue"]});class SymbolStyleLayer extends StyleLayer{constructor(layer){super(layer,properties$2)}recalculate(parameters,availableImages){super.recalculate(parameters,availableImages);if(this.layout.get("icon-rotation-alignment")==="auto"){if(this.layout.get("symbol-placement")!=="point"){this.layout._values["icon-rotation-alignment"]="map"}else{this.layout._values["icon-rotation-alignment"]="viewport"}}if(this.layout.get("text-rotation-alignment")==="auto"){if(this.layout.get("symbol-placement")!=="point"){this.layout._values["text-rotation-alignment"]="map"}else{this.layout._values["text-rotation-alignment"]="viewport"}}if(this.layout.get("text-pitch-alignment")==="auto"){this.layout._values["text-pitch-alignment"]=this.layout.get("text-rotation-alignment")==="map"?"map":"viewport"}if(this.layout.get("icon-pitch-alignment")==="auto"){this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")}if(this.layout.get("symbol-placement")==="point"){const writingModes=this.layout.get("text-writing-mode");if(writingModes){const deduped=[];for(const m of writingModes){if(deduped.indexOf(m)<0)deduped.push(m)}this.layout._values["text-writing-mode"]=deduped}else{this.layout._values["text-writing-mode"]=["horizontal"]}}this._setPaintOverrides()}getValueAndResolveTokens(name,feature,canonical,availableImages){const value=this.layout.get(name).evaluate(feature,{},canonical,availableImages);const unevaluated=this._unevaluatedLayout._values[name];if(!unevaluated.isDataDriven()&&!isExpression(unevaluated.value)&&value){return resolveTokens(feature.properties,value)}return value}createBucket(parameters){return new SymbolBucket(parameters)}queryRadius(){return 0}queryIntersectsFeature(){throw new Error("Should take a different path in FeatureIndex")}_setPaintOverrides(){for(const overridable of properties$2.paint.overridableProperties){if(!SymbolStyleLayer.hasPaintOverride(this.layout,overridable)){continue}const overriden=this.paint.get(overridable);const override=new FormatSectionOverride(overriden);const styleExpression=new StyleExpression(override,overriden.property.specification);let expression=null;if(overriden.value.kind==="constant"||overriden.value.kind==="source"){expression=new ZoomConstantExpression("source",styleExpression)}else{expression=new ZoomDependentExpression("composite",styleExpression,overriden.value.zoomStops)}this.paint._values[overridable]=new PossiblyEvaluatedPropertyValue(overriden.property,expression,overriden.parameters)}}_handleOverridablePaintPropertyUpdate(name,oldValue,newValue){if(!this.layout||oldValue.isDataDriven()||newValue.isDataDriven()){return false}return SymbolStyleLayer.hasPaintOverride(this.layout,name)}static hasPaintOverride(layout,propertyName){const textField=layout.get("text-field");const property=properties$2.paint.properties[propertyName];let hasOverrides=false;const checkSections=sections=>{for(const section of sections){if(property.overrides&&property.overrides.hasOverride(section)){hasOverrides=true;return}}};if(textField.value.kind==="constant"&&textField.value.value instanceof Formatted){checkSections(textField.value.value.sections)}else if(textField.value.kind==="source"){const checkExpression=expression=>{if(hasOverrides)return;if(expression instanceof Literal&&typeOf(expression.value)===FormattedType){const formatted=expression.value;checkSections(formatted.sections)}else if(expression instanceof FormatExpression){checkSections(expression.sections)}else{expression.eachChild(checkExpression)}};const expr=textField.value;if(expr._styleExpression){checkExpression(expr._styleExpression.expression)}}return hasOverrides}}function getIconPadding(layout,feature,canonical,pixelRatio=1){const result=layout.get("icon-padding").evaluate(feature,{},canonical);const values=result&&result.values;return[values[0]*pixelRatio,values[1]*pixelRatio,values[2]*pixelRatio,values[3]*pixelRatio]}let paint$1;const getPaint$1=()=>paint$1=paint$1||new Properties({"background-color":new DataConstantProperty(v8Spec["paint_background"]["background-color"]),"background-pattern":new CrossFadedProperty(v8Spec["paint_background"]["background-pattern"]),"background-opacity":new DataConstantProperty(v8Spec["paint_background"]["background-opacity"])});var properties$1={get paint(){return getPaint$1()}};class BackgroundStyleLayer extends StyleLayer{constructor(layer){super(layer,properties$1)}}let paint;const getPaint=()=>paint=paint||new Properties({"raster-opacity":new DataConstantProperty(v8Spec["paint_raster"]["raster-opacity"]),"raster-hue-rotate":new DataConstantProperty(v8Spec["paint_raster"]["raster-hue-rotate"]),"raster-brightness-min":new DataConstantProperty(v8Spec["paint_raster"]["raster-brightness-min"]),"raster-brightness-max":new DataConstantProperty(v8Spec["paint_raster"]["raster-brightness-max"]),"raster-saturation":new DataConstantProperty(v8Spec["paint_raster"]["raster-saturation"]),"raster-contrast":new DataConstantProperty(v8Spec["paint_raster"]["raster-contrast"]),"raster-resampling":new DataConstantProperty(v8Spec["paint_raster"]["raster-resampling"]),"raster-fade-duration":new DataConstantProperty(v8Spec["paint_raster"]["raster-fade-duration"])});var properties={get paint(){return getPaint()}};class RasterStyleLayer extends StyleLayer{constructor(layer){super(layer,properties)}}function validateCustomStyleLayer(layerObject){const errors=[];const id=layerObject.id;if(id===undefined){errors.push({message:`layers.${id}: missing required property "id"`})}if(layerObject.render===undefined){errors.push({message:`layers.${id}: missing required method "render"`})}if(layerObject.renderingMode&&layerObject.renderingMode!=="2d"&&layerObject.renderingMode!=="3d"){errors.push({message:`layers.${id}: property "renderingMode" must be either "2d" or "3d"`})}return errors}class CustomStyleLayer extends StyleLayer{constructor(implementation){super(implementation,{});this.onAdd=map=>{if(this.implementation.onAdd){this.implementation.onAdd(map,map.painter.context.gl)}};this.onRemove=map=>{if(this.implementation.onRemove){this.implementation.onRemove(map,map.painter.context.gl)}};this.implementation=implementation}is3D(){return this.implementation.renderingMode==="3d"}hasOffscreenPass(){return this.implementation.prerender!==undefined}recalculate(){}updateTransitions(){}hasTransition(){return false}serialize(){throw new Error("Custom layers cannot be serialized")}}function createStyleLayer(layer){if(layer.type==="custom"){return new CustomStyleLayer(layer)}switch(layer.type){case"background":return new BackgroundStyleLayer(layer);case"circle":return new CircleStyleLayer(layer);case"fill":return new FillStyleLayer(layer);case"fill-extrusion":return new FillExtrusionStyleLayer(layer);case"heatmap":return new HeatmapStyleLayer(layer);case"hillshade":return new HillshadeStyleLayer(layer);case"line":return new LineStyleLayer(layer);case"raster":return new RasterStyleLayer(layer);case"symbol":return new SymbolStyleLayer(layer)}}class ThrottledInvoker{constructor(methodToThrottle){this._methodToThrottle=methodToThrottle;this._triggered=false;if(typeof MessageChannel!=="undefined"){this._channel=new MessageChannel;this._channel.port2.onmessage=()=>{this._triggered=false;this._methodToThrottle()}}}trigger(){if(this._triggered){return}this._triggered=true;if(this._channel){this._channel.port1.postMessage(true)}else{setTimeout((()=>{this._triggered=false;this._methodToThrottle()}),0)}}remove(){delete this._channel;this._methodToThrottle=()=>{}}}class Actor{constructor(target,mapId){this.target=target;this.mapId=mapId;this.resolveRejects={};this.tasks={};this.taskQueue=[];this.abortControllers={};this.messageHandlers={};this.invoker=new ThrottledInvoker((()=>this.process()));this.subscription=subscribe(this.target,"message",(message=>this.receive(message)),false);this.globalScope=isWorker(self)?target:window}registerMessageHandler(type,handler){this.messageHandlers[type]=handler}sendAsync(message,abortController){return new Promise(((resolve,reject)=>{const id=Math.round(Math.random()*1e18).toString(36).substring(0,10);this.resolveRejects[id]={resolve:resolve,reject:reject};if(abortController){abortController.signal.addEventListener("abort",(()=>{delete this.resolveRejects[id];const cancelMessage={id:id,type:"",origin:location.origin,targetMapId:message.targetMapId,sourceMapId:this.mapId};this.target.postMessage(cancelMessage)}),{once:true})}const buffers=[];const messageToPost=Object.assign(Object.assign({},message),{id:id,sourceMapId:this.mapId,origin:location.origin,data:serialize(message.data,buffers)});this.target.postMessage(messageToPost,{transfer:buffers})}))}receive(message){const data=message.data;const id=data.id;if(data.origin!=="file://"&&location.origin!=="file://"&&data.origin!==location.origin){return}if(data.targetMapId&&this.mapId!==data.targetMapId){return}if(data.type===""){delete this.tasks[id];const abortController=this.abortControllers[id];delete this.abortControllers[id];if(abortController){abortController.abort()}return}if(isWorker(self)||data.mustQueue){this.tasks[id]=data;this.taskQueue.push(id);this.invoker.trigger();return}this.processTask(id,data)}process(){if(this.taskQueue.length===0){return}const id=this.taskQueue.shift();const task=this.tasks[id];delete this.tasks[id];if(this.taskQueue.length>0){this.invoker.trigger()}if(!task){return}this.processTask(id,task)}processTask(id,task){return __awaiter(this,void 0,void 0,(function*(){if(task.type===""){const resolveReject=this.resolveRejects[id];delete this.resolveRejects[id];if(!resolveReject){return}if(task.error){resolveReject.reject(deserialize(task.error))}else{resolveReject.resolve(deserialize(task.data))}return}if(!this.messageHandlers[task.type]){this.completeTask(id,new Error(`Could not find a registered handler for ${task.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(", ")}`));return}const params=deserialize(task.data);const abortController=new AbortController;this.abortControllers[id]=abortController;try{const data=yield this.messageHandlers[task.type](task.sourceMapId,params,abortController);this.completeTask(id,null,data)}catch(err){this.completeTask(id,err)}}))}completeTask(id,err,data){const buffers=[];delete this.abortControllers[id];const responseMessage={id:id,type:"",sourceMapId:this.mapId,origin:location.origin,error:err?serialize(err):null,data:serialize(data,buffers)};this.target.postMessage(responseMessage,{transfer:buffers})}remove(){this.invoker.remove();this.subscription.unsubscribe()}}const earthRadius=6371008.8;class LngLat{constructor(lng,lat){if(isNaN(lng)||isNaN(lat)){throw new Error(`Invalid LngLat object: (${lng}, ${lat})`)}this.lng=+lng;this.lat=+lat;if(this.lat>90||this.lat<-90){throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}}wrap(){return new LngLat(wrap(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(lngLat){const rad=Math.PI/180;const lat1=this.lat*rad;const lat2=lngLat.lat*rad;const a=Math.sin(lat1)*Math.sin(lat2)+Math.cos(lat1)*Math.cos(lat2)*Math.cos((lngLat.lng-this.lng)*rad);const maxMeters=earthRadius*Math.acos(Math.min(a,1));return maxMeters}static convert(input){if(input instanceof LngLat){return input}if(Array.isArray(input)&&(input.length===2||input.length===3)){return new LngLat(Number(input[0]),Number(input[1]))}if(!Array.isArray(input)&&typeof input==="object"&&input!==null){return new LngLat(Number("lng"in input?input.lng:input.lon),Number(input.lat))}throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}const earthCircumfrence=2*Math.PI*earthRadius;function circumferenceAtLatitude(latitude){return earthCircumfrence*Math.cos(latitude*Math.PI/180)}function mercatorXfromLng(lng){return(180+lng)/360}function mercatorYfromLat(lat){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+lat*Math.PI/360)))/360}function mercatorZfromAltitude(altitude,lat){return altitude/circumferenceAtLatitude(lat)}function lngFromMercatorX(x){return x*360-180}function latFromMercatorY(y){const y2=180-y*360;return 360/Math.PI*Math.atan(Math.exp(y2*Math.PI/180))-90}function altitudeFromMercatorZ(z,y){return z*circumferenceAtLatitude(latFromMercatorY(y))}function mercatorScale(lat){return 1/Math.cos(lat*Math.PI/180)}class MercatorCoordinate{constructor(x,y,z=0){this.x=+x;this.y=+y;this.z=+z}static fromLngLat(lngLatLike,altitude=0){const lngLat=LngLat.convert(lngLatLike);return new MercatorCoordinate(mercatorXfromLng(lngLat.lng),mercatorYfromLat(lngLat.lat),mercatorZfromAltitude(altitude,lngLat.lat))}toLngLat(){return new LngLat(lngFromMercatorX(this.x),latFromMercatorY(this.y))}toAltitude(){return altitudeFromMercatorZ(this.z,this.y)}meterInMercatorCoordinateUnits(){return 1/earthCircumfrence*mercatorScale(latFromMercatorY(this.y))}}function getURL(baseUrl,layer,x,y,z,options){options=options||{};var url=baseUrl+"?"+["bbox="+getTileBBox(x,y,z),"format="+(options.format||"image/png"),"service="+(options.service||"WMS"),"version="+(options.version||"1.1.1"),"request="+(options.request||"GetMap"),"srs="+(options.srs||"EPSG:3857"),"width="+(options.width||256),"height="+(options.height||256),"layers="+layer].join("&");return url}function getTileBBox(x,y,z){y=Math.pow(2,z)-y-1;var min=getMercCoords(x*256,y*256,z),max=getMercCoords((x+1)*256,(y+1)*256,z);return min[0]+","+min[1]+","+max[0]+","+max[1]}function getMercCoords(x,y,z){var resolution=2*Math.PI*6378137/256/Math.pow(2,z),merc_x=x*resolution-2*Math.PI*6378137/2,merc_y=y*resolution-2*Math.PI*6378137/2;return[merc_x,merc_y]}class CanonicalTileID{constructor(z,x,y){if(z<0||z>25||y<0||y>=Math.pow(2,z)||x<0||x>=Math.pow(2,z)){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 `)}this.z=z;this.x=x;this.y=y;this.key=calculateKey(0,z,z,x,y)}equals(id){return this.z===id.z&&this.x===id.x&&this.y===id.y}url(urls,pixelRatio,scheme){const bbox=getTileBBox(this.x,this.y,this.z);const quadkey=getQuadkey(this.z,this.x,this.y);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)}isChildOf(parent){const dz=this.z-parent.z;return dz>0&&parent.x===this.x>>dz&&parent.y===this.y>>dz}getTilePoint(coord){const tilesAtZoom=Math.pow(2,this.z);return new Point$2((coord.x*tilesAtZoom-this.x)*EXTENT,(coord.y*tilesAtZoom-this.y)*EXTENT)}toString(){return`${this.z}/${this.x}/${this.y}`}}class UnwrappedTileID{constructor(wrap,canonical){this.wrap=wrap;this.canonical=canonical;this.key=calculateKey(wrap,canonical.z,canonical.z,canonical.x,canonical.y)}}class OverscaledTileID{constructor(overscaledZ,wrap,z,x,y){if(overscaledZ= z; overscaledZ = ${overscaledZ}; z = ${z}`);this.overscaledZ=overscaledZ;this.wrap=wrap;this.canonical=new CanonicalTileID(z,+x,+y);this.key=calculateKey(wrap,overscaledZ,z,x,y)}clone(){return new OverscaledTileID(this.overscaledZ,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)}equals(id){return this.overscaledZ===id.overscaledZ&&this.wrap===id.wrap&&this.canonical.equals(id.canonical)}scaledTo(targetZ){if(targetZ>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${targetZ}; overscaledZ = ${this.overscaledZ}`);const zDifference=this.canonical.z-targetZ;if(targetZ>this.canonical.z){return new OverscaledTileID(targetZ,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)}else{return new OverscaledTileID(targetZ,this.wrap,targetZ,this.canonical.x>>zDifference,this.canonical.y>>zDifference)}}calculateScaledKey(targetZ,withWrap){if(targetZ>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${targetZ}; overscaledZ = ${this.overscaledZ}`);const zDifference=this.canonical.z-targetZ;if(targetZ>this.canonical.z){return calculateKey(this.wrap*+withWrap,targetZ,this.canonical.z,this.canonical.x,this.canonical.y)}else{return calculateKey(this.wrap*+withWrap,targetZ,targetZ,this.canonical.x>>zDifference,this.canonical.y>>zDifference)}}isChildOf(parent){if(parent.wrap!==this.wrap){return false}const zDifference=this.canonical.z-parent.canonical.z;return parent.overscaledZ===0||parent.overscaledZ>zDifference&&parent.canonical.y===this.canonical.y>>zDifference}children(sourceMaxZoom){if(this.overscaledZ>=sourceMaxZoom){return[new OverscaledTileID(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)]}const z=this.canonical.z+1;const x=this.canonical.x*2;const y=this.canonical.y*2;return[new OverscaledTileID(z,this.wrap,z,x,y),new OverscaledTileID(z,this.wrap,z,x+1,y),new OverscaledTileID(z,this.wrap,z,x,y+1),new OverscaledTileID(z,this.wrap,z,x+1,y+1)]}isLessThan(rhs){if(this.wraprhs.wrap)return false;if(this.overscaledZrhs.overscaledZ)return false;if(this.canonical.xrhs.canonical.x)return false;if(this.canonical.y0;i--){mask=1<this.max)this.max=ele;if(ele=this.dim+1||y<-1||y>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(y+1)*this.stride+(x+1)}unpack(r,g,b){return r*this.redFactor+g*this.greenFactor+b*this.blueFactor-this.baseShift}getPixels(){return new RGBAImage({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))}backfillBorder(borderTile,dx,dy){if(this.dim!==borderTile.dim)throw new Error("dem dimension mismatch");let xMin=dx*this.dim,xMax=dx*this.dim+this.dim,yMin=dy*this.dim,yMax=dy*this.dim+this.dim;switch(dx){case-1:xMin=xMax-1;break;case 1:xMax=xMin+1;break}switch(dy){case-1:yMin=yMax-1;break;case 1:yMax=yMin+1;break}const ox=-dx*this.dim;const oy=-dy*this.dim;for(let y=yMin;y=this._numberToString.length)throw new Error(`Out of bounds. Index requested n=${n} can't be >= this._numberToString.length ${this._numberToString.length}`);return this._numberToString[n]}}class GeoJSONFeature{constructor(vectorTileFeature,z,x,y,id){this.type="Feature";this._vectorTileFeature=vectorTileFeature;vectorTileFeature._z=z;vectorTileFeature._x=x;vectorTileFeature._y=y;this.properties=vectorTileFeature.properties;this.id=id}get geometry(){if(this._geometry===undefined){this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry}return this._geometry}set geometry(g){this._geometry=g}toJSON(){const json={geometry:this.geometry};for(const i in this){if(i==="_geometry"||i==="_vectorTileFeature")continue;json[i]=this[i]}return json}}class FeatureIndex{constructor(tileID,promoteId){this.tileID=tileID;this.x=tileID.canonical.x;this.y=tileID.canonical.y;this.z=tileID.canonical.z;this.grid=new TransferableGridIndex(EXTENT,16,0);this.grid3D=new TransferableGridIndex(EXTENT,16,0);this.featureIndexArray=new FeatureIndexArray;this.promoteId=promoteId}insert(feature,geometry,featureIndex,sourceLayerIndex,bucketIndex,is3D){const key=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(featureIndex,sourceLayerIndex,bucketIndex);const grid=is3D?this.grid3D:this.grid;for(let r=0;r=0&&bbox[3]>=0){grid.insert(key,bbox[0],bbox[1],bbox[2],bbox[3])}}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new vectorTile.VectorTile(new Protobuf(this.rawTileData)).layers;this.sourceLayerCoder=new DictionaryCoder(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])}return this.vtLayers}query(args,styleLayers,serializedLayers,sourceFeatureState){this.loadVTLayers();const params=args.params||{},pixelsToTileUnits=EXTENT/args.tileSize/args.scale,filter=createFilter(params.filter);const queryGeometry=args.queryGeometry;const queryPadding=args.queryPadding*pixelsToTileUnits;const bounds=getBounds(queryGeometry);const matching=this.grid.query(bounds.minX-queryPadding,bounds.minY-queryPadding,bounds.maxX+queryPadding,bounds.maxY+queryPadding);const cameraBounds=getBounds(args.cameraQueryGeometry);const matching3D=this.grid3D.query(cameraBounds.minX-queryPadding,cameraBounds.minY-queryPadding,cameraBounds.maxX+queryPadding,cameraBounds.maxY+queryPadding,((bx1,by1,bx2,by2)=>polygonIntersectsBox(args.cameraQueryGeometry,bx1-queryPadding,by1-queryPadding,bx2+queryPadding,by2+queryPadding)));for(const key of matching3D){matching.push(key)}matching.sort(topDownFeatureComparator);const result={};let previousIndex;for(let k=0;k{if(!featureGeometry){featureGeometry=loadGeometry(feature)}return styleLayer.queryIntersectsFeature(queryGeometry,feature,featureState,featureGeometry,this.z,args.transform,pixelsToTileUnits,args.pixelPosMatrix)}))}return result}loadMatchingFeature(result,bucketIndex,sourceLayerIndex,featureIndex,filter,filterLayerIDs,availableImages,styleLayers,serializedLayers,sourceFeatureState,intersectionTest){const layerIDs=this.bucketLayerIDs[bucketIndex];if(filterLayerIDs&&!arraysIntersect(filterLayerIDs,layerIDs))return;const sourceLayerName=this.sourceLayerCoder.decode(sourceLayerIndex);const sourceLayer=this.vtLayers[sourceLayerName];const feature=sourceLayer.feature(featureIndex);if(filter.needGeometry){const evaluationFeature=toEvaluationFeature(feature,true);if(!filter.filter(new EvaluationParameters(this.tileID.overscaledZ),evaluationFeature,this.tileID.canonical)){return}}else if(!filter.filter(new EvaluationParameters(this.tileID.overscaledZ),feature)){return}const id=this.getId(feature,sourceLayerName);for(let l=0;l{const prop=styleLayerProperties instanceof PossiblyEvaluated?styleLayerProperties.get(key):null;return prop&&prop.evaluate?prop.evaluate(feature,featureState,availableImages):prop}))}function getBounds(geometry){let minX=Infinity;let minY=Infinity;let maxX=-Infinity;let maxY=-Infinity;for(const p of geometry){minX=Math.min(minX,p.x);minY=Math.min(minY,p.y);maxX=Math.max(maxX,p.x);maxY=Math.max(maxY,p.y)}return{minX:minX,minY:minY,maxX:maxX,maxY:maxY}}function topDownFeatureComparator(a,b){return b-a}function clipLine(lines,x1,y1,x2,y2){const clippedLines=[];for(let l=0;l=x2&&p1.x>=x2){continue}else if(p0.x>=x2){p0=new Point$2(x2,p0.y+(p1.y-p0.y)*((x2-p0.x)/(p1.x-p0.x)))._round()}else if(p1.x>=x2){p1=new Point$2(x2,p0.y+(p1.y-p0.y)*((x2-p0.x)/(p1.x-p0.x)))._round()}if(p0.y>=y2&&p1.y>=y2){continue}else if(p0.y>=y2){p0=new Point$2(p0.x+(p1.x-p0.x)*((y2-p0.y)/(p1.y-p0.y)),y2)._round()}else if(p1.y>=y2){p1=new Point$2(p0.x+(p1.x-p0.x)*((y2-p0.y)/(p1.y-p0.y)),y2)._round()}if(!clippedLine||!p0.equals(clippedLine[clippedLine.length-1])){clippedLine=[p0];clippedLines.push(clippedLine)}clippedLine.push(p1)}}return clippedLines}class Anchor extends Point$2{constructor(x,y,angle,segment){super(x,y);this.angle=angle;if(segment!==undefined){this.segment=segment}}clone(){return new Anchor(this.x,this.y,this.angle,this.segment)}}register("Anchor",Anchor);function checkMaxAngle(line,anchor,labelLength,windowSize,maxAngle){if(anchor.segment===undefined||labelLength===0)return true;let p=anchor;let index=anchor.segment+1;let anchorDistance=0;while(anchorDistance>-labelLength/2){index--;if(index<0)return false;anchorDistance-=line[index].dist(p);p=line[index]}anchorDistance+=line[index].dist(line[index+1]);index++;const recentCorners=[];let recentAngleDelta=0;while(anchorDistancewindowSize){recentAngleDelta-=recentCorners.shift().angleDelta}if(recentAngleDelta>maxAngle)return false;index++;anchorDistance+=current.dist(next)}return true}function getLineLength(line){let lineLength=0;for(let k=0;kcenterDistance){const t=(centerDistance-prevDistance)/segmentDistance,x=interpolate.number(a.x,b.x,t),y=interpolate.number(a.y,b.y,t);const anchor=new Anchor(x,y,b.angleTo(a),i);anchor._round();if(!angleWindowSize||checkMaxAngle(line,anchor,labelLength,angleWindowSize,maxAngle)){return anchor}else{return}}prevDistance+=segmentDistance}}function getAnchors(line,spacing,maxAngle,shapedText,shapedIcon,glyphSize,boxScale,overscaling,tileExtent){const angleWindowSize=getAngleWindowSize(shapedText,glyphSize,boxScale);const shapedLabelLength=getShapedLabelLength(shapedText,shapedIcon);const labelLength=shapedLabelLength*boxScale;const isLineContinued=line[0].x===0||line[0].x===tileExtent||line[0].y===0||line[0].y===tileExtent;if(spacing-labelLength=0&&x=0&&y=0&&markedDistance+halfLabelLength<=lineLength){const anchor=new Anchor(x,y,angle,i);anchor._round();if(!angleWindowSize||checkMaxAngle(line,anchor,labelLength,angleWindowSize,maxAngle)){anchors.push(anchor)}}}distance+=segmentDist}if(!placeAtMiddle&&!anchors.length&&!isLineContinued){anchors=resample(line,distance/2,spacing,angleWindowSize,maxAngle,labelLength,isLineContinued,true,tileExtent)}return anchors}const border=IMAGE_PADDING;function getIconQuads(shapedIcon,iconRotate,isSDFIcon,hasIconTextFit){const quads=[];const image=shapedIcon.image;const pixelRatio=image.pixelRatio;const imageWidth=image.paddedRect.w-2*border;const imageHeight=image.paddedRect.h-2*border;const iconWidth=shapedIcon.right-shapedIcon.left;const iconHeight=shapedIcon.bottom-shapedIcon.top;const stretchX=image.stretchX||[[0,imageWidth]];const stretchY=image.stretchY||[[0,imageHeight]];const reduceRanges=(sum,range)=>sum+range[1]-range[0];const stretchWidth=stretchX.reduce(reduceRanges,0);const stretchHeight=stretchY.reduce(reduceRanges,0);const fixedWidth=imageWidth-stretchWidth;const fixedHeight=imageHeight-stretchHeight;let stretchOffsetX=0;let stretchContentWidth=stretchWidth;let stretchOffsetY=0;let stretchContentHeight=stretchHeight;let fixedOffsetX=0;let fixedContentWidth=fixedWidth;let fixedOffsetY=0;let fixedContentHeight=fixedHeight;if(image.content&&hasIconTextFit){const content=image.content;stretchOffsetX=sumWithinRange(stretchX,0,content[0]);stretchOffsetY=sumWithinRange(stretchY,0,content[1]);stretchContentWidth=sumWithinRange(stretchX,content[0],content[2]);stretchContentHeight=sumWithinRange(stretchY,content[1],content[3]);fixedOffsetX=content[0]-stretchOffsetX;fixedOffsetY=content[1]-stretchOffsetY;fixedContentWidth=content[2]-content[0]-stretchContentWidth;fixedContentHeight=content[3]-content[1]-stretchContentHeight}const makeBox=(left,top,right,bottom)=>{const leftEm=getEmOffset(left.stretch-stretchOffsetX,stretchContentWidth,iconWidth,shapedIcon.left);const leftPx=getPxOffset(left.fixed-fixedOffsetX,fixedContentWidth,left.stretch,stretchWidth);const topEm=getEmOffset(top.stretch-stretchOffsetY,stretchContentHeight,iconHeight,shapedIcon.top);const topPx=getPxOffset(top.fixed-fixedOffsetY,fixedContentHeight,top.stretch,stretchHeight);const rightEm=getEmOffset(right.stretch-stretchOffsetX,stretchContentWidth,iconWidth,shapedIcon.left);const rightPx=getPxOffset(right.fixed-fixedOffsetX,fixedContentWidth,right.stretch,stretchWidth);const bottomEm=getEmOffset(bottom.stretch-stretchOffsetY,stretchContentHeight,iconHeight,shapedIcon.top);const bottomPx=getPxOffset(bottom.fixed-fixedOffsetY,fixedContentHeight,bottom.stretch,stretchHeight);const tl=new Point$2(leftEm,topEm);const tr=new Point$2(rightEm,topEm);const br=new Point$2(rightEm,bottomEm);const bl=new Point$2(leftEm,bottomEm);const pixelOffsetTL=new Point$2(leftPx/pixelRatio,topPx/pixelRatio);const pixelOffsetBR=new Point$2(rightPx/pixelRatio,bottomPx/pixelRatio);const angle=iconRotate*Math.PI/180;if(angle){const sin=Math.sin(angle),cos=Math.cos(angle),matrix=[cos,-sin,sin,cos];tl._matMult(matrix);tr._matMult(matrix);bl._matMult(matrix);br._matMult(matrix)}const x1=left.stretch+left.fixed;const x2=right.stretch+right.fixed;const y1=top.stretch+top.fixed;const y2=bottom.stretch+bottom.fixed;const subRect={x:image.paddedRect.x+border+x1,y:image.paddedRect.y+border+y1,w:x2-x1,h:y2-y1};const minFontScaleX=fixedContentWidth/pixelRatio/iconWidth;const minFontScaleY=fixedContentHeight/pixelRatio/iconHeight;return{tl:tl,tr:tr,bl:bl,br:br,tex:subRect,writingMode:undefined,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:pixelOffsetTL,pixelOffsetBR:pixelOffsetBR,minFontScaleX:minFontScaleX,minFontScaleY:minFontScaleY,isSDF:isSDFIcon}};if(!hasIconTextFit||!image.stretchX&&!image.stretchY){quads.push(makeBox({fixed:0,stretch:-1},{fixed:0,stretch:-1},{fixed:0,stretch:imageWidth+1},{fixed:0,stretch:imageHeight+1}))}else{const xCuts=stretchZonesToCuts(stretchX,fixedWidth,stretchWidth);const yCuts=stretchZonesToCuts(stretchY,fixedHeight,stretchHeight);for(let xi=0;xi0){height=Math.max(10,height);this.circleDiameter=height}}else{let y1=shaped.top*boxScale-padding[0];let y2=shaped.bottom*boxScale+padding[2];let x1=shaped.left*boxScale-padding[3];let x2=shaped.right*boxScale+padding[1];const collisionPadding=shaped.collisionPadding;if(collisionPadding){x1-=collisionPadding[0]*boxScale;y1-=collisionPadding[1]*boxScale;x2+=collisionPadding[2]*boxScale;y2+=collisionPadding[3]*boxScale}if(rotate){const tl=new Point$2(x1,y1);const tr=new Point$2(x2,y1);const bl=new Point$2(x1,y2);const br=new Point$2(x2,y2);const rotateRadians=rotate*Math.PI/180;tl._rotate(rotateRadians);tr._rotate(rotateRadians);bl._rotate(rotateRadians);br._rotate(rotateRadians);x1=Math.min(tl.x,tr.x,bl.x,br.x);x2=Math.max(tl.x,tr.x,bl.x,br.x);y1=Math.min(tl.y,tr.y,bl.y,br.y);y2=Math.max(tl.y,tr.y,bl.y,br.y)}collisionBoxArray.emplaceBack(anchor.x,anchor.y,x1,y1,x2,y2,featureIndex,sourceLayerIndex,bucketIndex)}this.boxEndIndex=collisionBoxArray.length}}class TinyQueue{constructor(data=[],compare=defaultCompare){this.data=data;this.length=this.data.length;this.compare=compare;if(this.length>0){for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}}push(item){this.data.push(item);this.length++;this._up(this.length-1)}pop(){if(this.length===0)return undefined;const top=this.data[0];const bottom=this.data.pop();this.length--;if(this.length>0){this.data[0]=bottom;this._down(0)}return top}peek(){return this.data[0]}_up(pos){const{data:data,compare:compare}=this;const item=data[pos];while(pos>0){const parent=pos-1>>1;const current=data[parent];if(compare(item,current)>=0)break;data[pos]=current;pos=parent}data[pos]=item}_down(pos){const{data:data,compare:compare}=this;const halfLength=this.length>>1;const item=data[pos];while(pos=0)break;data[pos]=best;pos=left}data[pos]=item}}function defaultCompare(a,b){return ab?1:0}function findPoleOfInaccessibility(polygonRings,precision=1,debug=false){let minX=Infinity,minY=Infinity,maxX=-Infinity,maxY=-Infinity;const outerRing=polygonRings[0];for(let i=0;imaxX)maxX=p.x;if(!i||p.y>maxY)maxY=p.y}const width=maxX-minX;const height=maxY-minY;const cellSize=Math.min(width,height);let h=cellSize/2;const cellQueue=new TinyQueue([],compareMax);if(cellSize===0)return new Point$2(minX,minY);for(let x=minX;xbestCell.d||!bestCell.d){bestCell=cell;if(debug)console.log("found best %d after %d probes",Math.round(1e4*cell.d)/1e4,numProbes)}if(cell.max-bestCell.d<=precision)continue;h=cell.h/2;cellQueue.push(new Cell(cell.p.x-h,cell.p.y-h,h,polygonRings));cellQueue.push(new Cell(cell.p.x+h,cell.p.y-h,h,polygonRings));cellQueue.push(new Cell(cell.p.x-h,cell.p.y+h,h,polygonRings));cellQueue.push(new Cell(cell.p.x+h,cell.p.y+h,h,polygonRings));numProbes+=4}if(debug){console.log(`num probes: ${numProbes}`);console.log(`best distance: ${bestCell.d}`)}return bestCell.p}function compareMax(a,b){return b.max-a.max}function Cell(x,y,h,polygon){this.p=new Point$2(x,y);this.h=h;this.d=pointToPolygonDist(this.p,polygon);this.max=this.d+this.h*Math.SQRT2}function pointToPolygonDist(p,polygon){let inside=false;let minDistSq=Infinity;for(let k=0;kp.y!==b.y>p.y&&p.x<(b.x-a.x)*(p.y-a.y)/(b.y-a.y)+a.x)inside=!inside;minDistSq=Math.min(minDistSq,distToSegmentSquared(p,a,b))}}return(inside?1:-1)*Math.sqrt(minDistSq)}function getCentroidCell(polygon){let area=0;let x=0;let y=0;const points=polygon[0];for(let i=0,len=points.length,j=len-1;it*ONE_EM));if(anchor.startsWith("top")){offset[1]-=baselineOffset}else if(anchor.startsWith("bottom")){offset[1]+=baselineOffset}destValues[i+1]=offset}return new VariableAnchorOffsetCollection(destValues)}const variableAnchor=layout.get("text-variable-anchor");if(variableAnchor){let textOffset;const unevaluatedLayout=layer._unevaluatedLayout;if(unevaluatedLayout.getValue("text-radial-offset")!==undefined){textOffset=[layout.get("text-radial-offset").evaluate(feature,{},canonical)*ONE_EM,INVALID_TEXT_OFFSET]}else{textOffset=layout.get("text-offset").evaluate(feature,{},canonical).map((t=>t*ONE_EM))}const anchorOffsets=[];for(const anchor of variableAnchor){anchorOffsets.push(anchor,evaluateVariableOffset(anchor,textOffset))}return new VariableAnchorOffsetCollection(anchorOffsets)}return null}function performSymbolLayout(args){args.bucket.createArrays();const tileSize=512*args.bucket.overscaling;args.bucket.tilePixelRatio=EXTENT/tileSize;args.bucket.compareText={};args.bucket.iconsNeedLinear=false;const layer=args.bucket.layers[0];const layout=layer.layout;const unevaluatedLayoutValues=layer._unevaluatedLayout._values;const sizes={layoutIconSize:unevaluatedLayoutValues["icon-size"].possiblyEvaluate(new EvaluationParameters(args.bucket.zoom+1),args.canonical),layoutTextSize:unevaluatedLayoutValues["text-size"].possiblyEvaluate(new EvaluationParameters(args.bucket.zoom+1),args.canonical),textMaxSize:unevaluatedLayoutValues["text-size"].possiblyEvaluate(new EvaluationParameters(18))};if(args.bucket.textSizeData.kind==="composite"){const{minZoom:minZoom,maxZoom:maxZoom}=args.bucket.textSizeData;sizes.compositeTextSizes=[unevaluatedLayoutValues["text-size"].possiblyEvaluate(new EvaluationParameters(minZoom),args.canonical),unevaluatedLayoutValues["text-size"].possiblyEvaluate(new EvaluationParameters(maxZoom),args.canonical)]}if(args.bucket.iconSizeData.kind==="composite"){const{minZoom:minZoom,maxZoom:maxZoom}=args.bucket.iconSizeData;sizes.compositeIconSizes=[unevaluatedLayoutValues["icon-size"].possiblyEvaluate(new EvaluationParameters(minZoom),args.canonical),unevaluatedLayoutValues["icon-size"].possiblyEvaluate(new EvaluationParameters(maxZoom),args.canonical)]}const lineHeight=layout.get("text-line-height")*ONE_EM;const textAlongLine=layout.get("text-rotation-alignment")!=="viewport"&&layout.get("symbol-placement")!=="point";const keepUpright=layout.get("text-keep-upright");const textSize=layout.get("text-size");for(const feature of args.bucket.features){const fontstack=layout.get("text-font").evaluate(feature,{},args.canonical).join(",");const layoutTextSizeThisZoom=textSize.evaluate(feature,{},args.canonical);const layoutTextSize=sizes.layoutTextSize.evaluate(feature,{},args.canonical);const layoutIconSize=sizes.layoutIconSize.evaluate(feature,{},args.canonical);const shapedTextOrientations={horizontal:{},vertical:undefined};const text=feature.text;let textOffset=[0,0];if(text){const unformattedText=text.toString();const spacing=layout.get("text-letter-spacing").evaluate(feature,{},args.canonical)*ONE_EM;const spacingIfAllowed=allowsLetterSpacing(unformattedText)?spacing:0;const textAnchor=layout.get("text-anchor").evaluate(feature,{},args.canonical);const variableAnchorOffset=getTextVariableAnchorOffset(layer,feature,args.canonical);if(!variableAnchorOffset){const radialOffset=layout.get("text-radial-offset").evaluate(feature,{},args.canonical);if(radialOffset){textOffset=evaluateVariableOffset(textAnchor,[radialOffset*ONE_EM,INVALID_TEXT_OFFSET])}else{textOffset=layout.get("text-offset").evaluate(feature,{},args.canonical).map((t=>t*ONE_EM))}}let textJustify=textAlongLine?"center":layout.get("text-justify").evaluate(feature,{},args.canonical);const symbolPlacement=layout.get("symbol-placement");const maxWidth=symbolPlacement==="point"?layout.get("text-max-width").evaluate(feature,{},args.canonical)*ONE_EM:0;const addVerticalShapingForPointLabelIfNeeded=()=>{if(args.bucket.allowVerticalPlacement&&allowsVerticalWritingMode(unformattedText)){shapedTextOrientations.vertical=shapeText(text,args.glyphMap,args.glyphPositions,args.imagePositions,fontstack,maxWidth,lineHeight,textAnchor,"left",spacingIfAllowed,textOffset,exports.WritingMode.vertical,true,symbolPlacement,layoutTextSize,layoutTextSizeThisZoom)}};if(!textAlongLine&&variableAnchorOffset){const justifications=new Set;if(textJustify==="auto"){for(let i=0;i{if(anchor.x<0||anchor.x>=EXTENT||anchor.y<0||anchor.y>=EXTENT){return}addSymbol(bucket,anchor,line,shapedTextOrientations,shapedIcon,imageMap,verticallyShapedIcon,bucket.layers[0],bucket.collisionBoxArray,feature.index,feature.sourceLayerIndex,bucket.index,textBoxScale,[textPadding,textPadding,textPadding,textPadding],textAlongLine,textOffset,iconBoxScale,iconPadding,iconAlongLine,iconOffset,feature,sizes,isSDFIcon,canonical,layoutTextSize)};if(symbolPlacement==="line"){for(const line of clipLine(feature.geometry,0,0,EXTENT,EXTENT)){const anchors=getAnchors(line,symbolMinDistance,textMaxAngle,shapedTextOrientations.vertical||defaultHorizontalShaping,shapedIcon,glyphSize,textMaxBoxScale,bucket.overscaling,EXTENT);for(const anchor of anchors){const shapedText=defaultHorizontalShaping;if(!shapedText||!anchorIsTooClose(bucket,shapedText.text,textRepeatDistance,anchor)){addSymbolAtAnchor(line,anchor)}}}}else if(symbolPlacement==="line-center"){for(const line of feature.geometry){if(line.length>1){const anchor=getCenterAnchor(line,textMaxAngle,shapedTextOrientations.vertical||defaultHorizontalShaping,shapedIcon,glyphSize,textMaxBoxScale);if(anchor){addSymbolAtAnchor(line,anchor)}}}}else if(feature.type==="Polygon"){for(const polygon of classifyRings$1(feature.geometry,0)){const poi=findPoleOfInaccessibility(polygon,16);addSymbolAtAnchor(polygon[0],new Anchor(poi.x,poi.y,0))}}else if(feature.type==="LineString"){for(const line of feature.geometry){addSymbolAtAnchor(line,new Anchor(line[0].x,line[0].y,0))}}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))}}}}function addTextVariableAnchorOffsets(textAnchorOffsets,variableAnchorOffset){const startIndex=textAnchorOffsets.length;const values=variableAnchorOffset===null||variableAnchorOffset===void 0?void 0:variableAnchorOffset.values;if((values===null||values===void 0?void 0:values.length)>0){for(let i=0;iMAX_PACKED_SIZE){warnOnce(`${bucket.layerIds[0]}: Value for "text-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "text-size".`)}}else if(sizeData.kind==="composite"){textSizeData=[SIZE_PACK_FACTOR*sizes.compositeTextSizes[0].evaluate(feature,{},canonical),SIZE_PACK_FACTOR*sizes.compositeTextSizes[1].evaluate(feature,{},canonical)];if(textSizeData[0]>MAX_PACKED_SIZE||textSizeData[1]>MAX_PACKED_SIZE){warnOnce(`${bucket.layerIds[0]}: Value for "text-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "text-size".`)}}bucket.addSymbols(bucket.text,glyphQuads,textSizeData,textOffset,textAlongLine,feature,writingMode,anchor,lineArray.lineStartIndex,lineArray.lineLength,placedIconIndex,canonical);for(const placementType of placementTypes){placedTextSymbolIndices[placementType]=bucket.text.placedSymbolArray.length-1}return glyphQuads.length*4}function getDefaultHorizontalShaping(horizontalShaping){for(const justification in horizontalShaping){return horizontalShaping[justification]}return null}function 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){const lineArray=bucket.addToLineVertexArray(anchor,line);let textCollisionFeature,iconCollisionFeature,verticalTextCollisionFeature,verticalIconCollisionFeature;let numIconVertices=0;let numVerticalIconVertices=0;let numHorizontalGlyphVertices=0;let numVerticalGlyphVertices=0;let placedIconSymbolIndex=-1;let verticalPlacedIconSymbolIndex=-1;const placedTextSymbolIndices={};let key=murmur3$1("");if(bucket.allowVerticalPlacement&&shapedTextOrientations.vertical){const textRotation=layer.layout.get("text-rotate").evaluate(feature,{},canonical);const verticalTextRotation=textRotation+90;const verticalShaping=shapedTextOrientations.vertical;verticalTextCollisionFeature=new CollisionFeature(collisionBoxArray,anchor,featureIndex,sourceLayerIndex,bucketIndex,verticalShaping,textBoxScale,textPadding,textAlongLine,verticalTextRotation);if(verticallyShapedIcon){verticalIconCollisionFeature=new CollisionFeature(collisionBoxArray,anchor,featureIndex,sourceLayerIndex,bucketIndex,verticallyShapedIcon,iconBoxScale,iconPadding,textAlongLine,verticalTextRotation)}}if(shapedIcon){const iconRotate=layer.layout.get("icon-rotate").evaluate(feature,{});const hasIconTextFit=layer.layout.get("icon-text-fit")!=="none";const iconQuads=getIconQuads(shapedIcon,iconRotate,isSDFIcon,hasIconTextFit);const verticalIconQuads=verticallyShapedIcon?getIconQuads(verticallyShapedIcon,iconRotate,isSDFIcon,hasIconTextFit):undefined;iconCollisionFeature=new CollisionFeature(collisionBoxArray,anchor,featureIndex,sourceLayerIndex,bucketIndex,shapedIcon,iconBoxScale,iconPadding,false,iconRotate);numIconVertices=iconQuads.length*4;const sizeData=bucket.iconSizeData;let iconSizeData=null;if(sizeData.kind==="source"){iconSizeData=[SIZE_PACK_FACTOR*layer.layout.get("icon-size").evaluate(feature,{})];if(iconSizeData[0]>MAX_PACKED_SIZE){warnOnce(`${bucket.layerIds[0]}: Value for "icon-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "icon-size".`)}}else if(sizeData.kind==="composite"){iconSizeData=[SIZE_PACK_FACTOR*sizes.compositeIconSizes[0].evaluate(feature,{},canonical),SIZE_PACK_FACTOR*sizes.compositeIconSizes[1].evaluate(feature,{},canonical)];if(iconSizeData[0]>MAX_PACKED_SIZE||iconSizeData[1]>MAX_PACKED_SIZE){warnOnce(`${bucket.layerIds[0]}: Value for "icon-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "icon-size".`)}}bucket.addSymbols(bucket.icon,iconQuads,iconSizeData,iconOffset,iconAlongLine,feature,exports.WritingMode.none,anchor,lineArray.lineStartIndex,lineArray.lineLength,-1,canonical);placedIconSymbolIndex=bucket.icon.placedSymbolArray.length-1;if(verticalIconQuads){numVerticalIconVertices=verticalIconQuads.length*4;bucket.addSymbols(bucket.icon,verticalIconQuads,iconSizeData,iconOffset,iconAlongLine,feature,exports.WritingMode.vertical,anchor,lineArray.lineStartIndex,lineArray.lineLength,-1,canonical);verticalPlacedIconSymbolIndex=bucket.icon.placedSymbolArray.length-1}}const justifications=Object.keys(shapedTextOrientations.horizontal);for(const justification of justifications){const shaping=shapedTextOrientations.horizontal[justification];if(!textCollisionFeature){key=murmur3$1(shaping.text);const textRotate=layer.layout.get("text-rotate").evaluate(feature,{},canonical);textCollisionFeature=new CollisionFeature(collisionBoxArray,anchor,featureIndex,sourceLayerIndex,bucketIndex,shaping,textBoxScale,textPadding,textAlongLine,textRotate)}const singleLine=shaping.positionedLines.length===1;numHorizontalGlyphVertices+=addTextVertices(bucket,anchor,shaping,imageMap,layer,textAlongLine,feature,textOffset,lineArray,shapedTextOrientations.vertical?exports.WritingMode.horizontal:exports.WritingMode.horizontalOnly,singleLine?justifications:[justification],placedTextSymbolIndices,placedIconSymbolIndex,sizes,canonical);if(singleLine){break}}if(shapedTextOrientations.vertical){numVerticalGlyphVertices+=addTextVertices(bucket,anchor,shapedTextOrientations.vertical,imageMap,layer,textAlongLine,feature,textOffset,lineArray,exports.WritingMode.vertical,["vertical"],placedTextSymbolIndices,verticalPlacedIconSymbolIndex,sizes,canonical)}const textBoxStartIndex=textCollisionFeature?textCollisionFeature.boxStartIndex:bucket.collisionBoxArray.length;const textBoxEndIndex=textCollisionFeature?textCollisionFeature.boxEndIndex:bucket.collisionBoxArray.length;const verticalTextBoxStartIndex=verticalTextCollisionFeature?verticalTextCollisionFeature.boxStartIndex:bucket.collisionBoxArray.length;const verticalTextBoxEndIndex=verticalTextCollisionFeature?verticalTextCollisionFeature.boxEndIndex:bucket.collisionBoxArray.length;const iconBoxStartIndex=iconCollisionFeature?iconCollisionFeature.boxStartIndex:bucket.collisionBoxArray.length;const iconBoxEndIndex=iconCollisionFeature?iconCollisionFeature.boxEndIndex:bucket.collisionBoxArray.length;const verticalIconBoxStartIndex=verticalIconCollisionFeature?verticalIconCollisionFeature.boxStartIndex:bucket.collisionBoxArray.length;const verticalIconBoxEndIndex=verticalIconCollisionFeature?verticalIconCollisionFeature.boxEndIndex:bucket.collisionBoxArray.length;let collisionCircleDiameter=-1;const getCollisionCircleHeight=(feature,prevHeight)=>{if(feature&&feature.circleDiameter)return Math.max(feature.circleDiameter,prevHeight);return prevHeight};collisionCircleDiameter=getCollisionCircleHeight(textCollisionFeature,collisionCircleDiameter);collisionCircleDiameter=getCollisionCircleHeight(verticalTextCollisionFeature,collisionCircleDiameter);collisionCircleDiameter=getCollisionCircleHeight(iconCollisionFeature,collisionCircleDiameter);collisionCircleDiameter=getCollisionCircleHeight(verticalIconCollisionFeature,collisionCircleDiameter);const useRuntimeCollisionCircles=collisionCircleDiameter>-1?1:0;if(useRuntimeCollisionCircles)collisionCircleDiameter*=layoutTextSize/ONE_EM;if(bucket.glyphOffsetArray.length>=SymbolBucket.MAX_GLYPHS)warnOnce("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907");if(feature.sortKey!==undefined){bucket.addToSortKeyRanges(bucket.symbolInstances.length,feature.sortKey)}const variableAnchorOffset=getTextVariableAnchorOffset(layer,feature,canonical);const[textAnchorOffsetStartIndex,textAnchorOffsetEndIndex]=addTextVariableAnchorOffsets(bucket.textAnchorOffsets,variableAnchorOffset);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)}function anchorIsTooClose(bucket,text,repeatDistance,anchor){const compareText=bucket.compareText;if(!(text in compareText)){compareText[text]=[]}else{const otherAnchors=compareText[text];for(let k=otherAnchors.length-1;k>=0;k--){if(anchor.dist(otherAnchors[k])>4;if(version!==VERSION){throw new Error(`Got v${version} data when expected v${VERSION}.`)}const ArrayType=ARRAY_TYPES[versionAndType&15];if(!ArrayType){throw new Error("Unrecognized array type.")}const[nodeSize]=new Uint16Array(data,2,1);const[numItems]=new Uint32Array(data,4,1);return new KDBush(numItems,nodeSize,ArrayType,data)}constructor(numItems,nodeSize=64,ArrayType=Float64Array,data){if(isNaN(numItems)||numItems<0)throw new Error(`Unpexpected numItems value: ${numItems}.`);this.numItems=+numItems;this.nodeSize=Math.min(Math.max(+nodeSize,2),65535);this.ArrayType=ArrayType;this.IndexArrayType=numItems<65536?Uint16Array:Uint32Array;const arrayTypeIndex=ARRAY_TYPES.indexOf(this.ArrayType);const coordsByteSize=numItems*2*this.ArrayType.BYTES_PER_ELEMENT;const idsByteSize=numItems*this.IndexArrayType.BYTES_PER_ELEMENT;const padCoords=(8-idsByteSize%8)%8;if(arrayTypeIndex<0){throw new Error(`Unexpected typed array class: ${ArrayType}.`)}if(data&&data instanceof ArrayBuffer){this.data=data;this.ids=new this.IndexArrayType(this.data,HEADER_SIZE,numItems);this.coords=new this.ArrayType(this.data,HEADER_SIZE+idsByteSize+padCoords,numItems*2);this._pos=numItems*2;this._finished=true}else{this.data=new ArrayBuffer(HEADER_SIZE+coordsByteSize+idsByteSize+padCoords);this.ids=new this.IndexArrayType(this.data,HEADER_SIZE,numItems);this.coords=new this.ArrayType(this.data,HEADER_SIZE+idsByteSize+padCoords,numItems*2);this._pos=0;this._finished=false;new Uint8Array(this.data,0,2).set([219,(VERSION<<4)+arrayTypeIndex]);new Uint16Array(this.data,2,1)[0]=nodeSize;new Uint32Array(this.data,4,1)[0]=numItems}}add(x,y){const index=this._pos>>1;this.ids[index]=index;this.coords[this._pos++]=x;this.coords[this._pos++]=y;return index}finish(){const numAdded=this._pos>>1;if(numAdded!==this.numItems){throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`)}sort(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0);this._finished=true;return this}range(minX,minY,maxX,maxY){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:ids,coords:coords,nodeSize:nodeSize}=this;const stack=[0,ids.length-1,0];const result=[];while(stack.length){const axis=stack.pop()||0;const right=stack.pop()||0;const left=stack.pop()||0;if(right-left<=nodeSize){for(let i=left;i<=right;i++){const x=coords[2*i];const y=coords[2*i+1];if(x>=minX&&x<=maxX&&y>=minY&&y<=maxY)result.push(ids[i])}continue}const m=left+right>>1;const x=coords[2*m];const y=coords[2*m+1];if(x>=minX&&x<=maxX&&y>=minY&&y<=maxY)result.push(ids[m]);if(axis===0?minX<=x:minY<=y){stack.push(left);stack.push(m-1);stack.push(1-axis)}if(axis===0?maxX>=x:maxY>=y){stack.push(m+1);stack.push(right);stack.push(1-axis)}}return result}within(qx,qy,r){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:ids,coords:coords,nodeSize:nodeSize}=this;const stack=[0,ids.length-1,0];const result=[];const r2=r*r;while(stack.length){const axis=stack.pop()||0;const right=stack.pop()||0;const left=stack.pop()||0;if(right-left<=nodeSize){for(let i=left;i<=right;i++){if(sqDist(coords[2*i],coords[2*i+1],qx,qy)<=r2)result.push(ids[i])}continue}const m=left+right>>1;const x=coords[2*m];const y=coords[2*m+1];if(sqDist(x,y,qx,qy)<=r2)result.push(ids[m]);if(axis===0?qx-r<=x:qy-r<=y){stack.push(left);stack.push(m-1);stack.push(1-axis)}if(axis===0?qx+r>=x:qy+r>=y){stack.push(m+1);stack.push(right);stack.push(1-axis)}}return result}}function sort(ids,coords,nodeSize,left,right,axis){if(right-left<=nodeSize)return;const m=left+right>>1;select(ids,coords,m,left,right,axis);sort(ids,coords,nodeSize,left,m-1,1-axis);sort(ids,coords,nodeSize,m+1,right,1-axis)}function select(ids,coords,k,left,right,axis){while(right>left){if(right-left>600){const n=right-left+1;const m=k-left+1;const z=Math.log(n);const s=.5*Math.exp(2*z/3);const sd=.5*Math.sqrt(z*s*(n-s)/n)*(m-n/2<0?-1:1);const newLeft=Math.max(left,Math.floor(k-m*s/n+sd));const newRight=Math.min(right,Math.floor(k+(n-m)*s/n+sd));select(ids,coords,k,newLeft,newRight,axis)}const t=coords[2*k+axis];let i=left;let j=right;swapItem(ids,coords,left,k);if(coords[2*right+axis]>t)swapItem(ids,coords,left,right);while(it)j--}if(coords[2*left+axis]===t)swapItem(ids,coords,left,j);else{j++;swapItem(ids,coords,j,right)}if(j<=k)left=j+1;if(k<=j)right=j-1}}function swapItem(ids,coords,i,j){swap(ids,i,j);swap(coords,2*i,2*j);swap(coords,2*i+1,2*j+1)}function swap(arr,i,j){const tmp=arr[i];arr[i]=arr[j];arr[j]=tmp}function sqDist(ax,ay,bx,by){const dx=ax-bx;const dy=ay-by;return dx*dx+dy*dy}exports.PerformanceMarkers=void 0;(function(PerformanceMarkers){PerformanceMarkers["create"]="create";PerformanceMarkers["load"]="load";PerformanceMarkers["fullLoad"]="fullLoad"})(exports.PerformanceMarkers||(exports.PerformanceMarkers={}));let lastFrameTime=null;let frameTimes=[];const minFramerateTarget=60;const frameTimeTarget=1e3/minFramerateTarget;const loadTimeKey="loadTime";const fullLoadTimeKey="fullLoadTime";const PerformanceUtils={mark(marker){performance.mark(marker)},frame(timestamp){const currTimestamp=timestamp;if(lastFrameTime!=null){const frameTime=currTimestamp-lastFrameTime;frameTimes.push(frameTime)}lastFrameTime=currTimestamp},clearMetrics(){lastFrameTime=null;frameTimes=[];performance.clearMeasures(loadTimeKey);performance.clearMeasures(fullLoadTimeKey);for(const marker in exports.PerformanceMarkers){performance.clearMarks(exports.PerformanceMarkers[marker])}},getPerformanceMetrics(){performance.measure(loadTimeKey,exports.PerformanceMarkers.create,exports.PerformanceMarkers.load);performance.measure(fullLoadTimeKey,exports.PerformanceMarkers.create,exports.PerformanceMarkers.fullLoad);const loadTime=performance.getEntriesByName(loadTimeKey)[0].duration;const fullLoadTime=performance.getEntriesByName(fullLoadTimeKey)[0].duration;const totalFrames=frameTimes.length;const avgFrameTime=frameTimes.reduce(((prev,curr)=>prev+curr),0)/totalFrames/1e3;const fps=1/avgFrameTime;const droppedFrames=frameTimes.filter((frameTime=>frameTime>frameTimeTarget)).reduce(((acc,curr)=>acc+(curr-frameTimeTarget)/frameTimeTarget),0);const percentDroppedFrames=droppedFrames/(totalFrames+droppedFrames)*100;return{loadTime:loadTime,fullLoadTime:fullLoadTime,fps:fps,percentDroppedFrames:percentDroppedFrames,totalFrames:totalFrames}}};class RequestPerformance{constructor(request){this._marks={start:[request.url,"start"].join("#"),end:[request.url,"end"].join("#"),measure:request.url.toString()};performance.mark(this._marks.start)}finish(){performance.mark(this._marks.end);let resourceTimingData=performance.getEntriesByName(this._marks.measure);if(resourceTimingData.length===0){performance.measure(this._marks.measure,this._marks.start,this._marks.end);resourceTimingData=performance.getEntriesByName(this._marks.measure);performance.clearMarks(this._marks.start);performance.clearMarks(this._marks.end);performance.clearMeasures(this._marks.measure)}return resourceTimingData}}var performance$1=performance;exports.AJAXError=AJAXError;exports.Actor=Actor;exports.AlphaImage=AlphaImage;exports.CanonicalTileID=CanonicalTileID;exports.CollisionBoxArray=CollisionBoxArray;exports.CollisionCircleLayoutArray=CollisionCircleLayoutArray;exports.Color=Color;exports.DEMData=DEMData;exports.DataConstantProperty=DataConstantProperty;exports.DictionaryCoder=DictionaryCoder;exports.EXTENT=EXTENT;exports.ErrorEvent=ErrorEvent;exports.EvaluationParameters=EvaluationParameters;exports.Event=Event;exports.Evented=Evented;exports.FeatureIndex=FeatureIndex;exports.FillBucket=FillBucket;exports.FillExtrusionBucket=FillExtrusionBucket;exports.GLOBAL_DISPATCHER_ID=GLOBAL_DISPATCHER_ID;exports.GeoJSONFeature=GeoJSONFeature;exports.ImageAtlas=ImageAtlas;exports.ImagePosition=ImagePosition;exports.KDBush=KDBush;exports.LineBucket=LineBucket;exports.LineStripIndexArray=LineStripIndexArray;exports.LngLat=LngLat;exports.MercatorCoordinate=MercatorCoordinate;exports.ONE_EM=ONE_EM;exports.OverscaledTileID=OverscaledTileID;exports.PerformanceUtils=PerformanceUtils;exports.Point=Point$2;exports.Pos3dArray=Pos3dArray;exports.PosArray=PosArray;exports.Properties=Properties;exports.Protobuf=Protobuf;exports.QuadTriangleArray=QuadTriangleArray;exports.RGBAImage=RGBAImage;exports.RasterBoundsArray=RasterBoundsArray;exports.RequestPerformance=RequestPerformance;exports.SegmentVector=SegmentVector;exports.SymbolBucket=SymbolBucket;exports.Transitionable=Transitionable;exports.TriangleIndexArray=TriangleIndexArray;exports.Uniform1f=Uniform1f;exports.Uniform1i=Uniform1i;exports.Uniform2f=Uniform2f;exports.Uniform3f=Uniform3f;exports.Uniform4f=Uniform4f;exports.UniformColor=UniformColor;exports.UniformMatrix4f=UniformMatrix4f;exports.UnwrappedTileID=UnwrappedTileID;exports.ValidationError=ValidationError;exports.ZoomHistory=ZoomHistory;exports.__awaiter=__awaiter;exports.add=add$4;exports.addDynamicAttributes=addDynamicAttributes;exports.addProtocol=addProtocol;exports.arrayBufferToImage=arrayBufferToImage;exports.arrayBufferToImageBitmap=arrayBufferToImageBitmap;exports.bezier=bezier$1;exports.clamp=clamp$1;exports.clipLine=clipLine;exports.clone=clone$5;exports.clone$1=clone$9;exports.clone$2=clone$4;exports.collisionCircleLayout=collisionCircleLayout;exports.config=config;exports.copy=copy$5;exports.create=create$5;exports.create$1=create$6;exports.create$2=create$8;exports.createAbortError=createAbortError;exports.createExpression=createExpression;exports.createFilter=createFilter;exports.createLayout=createLayout;exports.createStyleLayer=createStyleLayer;exports.cross=cross$2;exports.deepEqual=deepEqual$1;exports.defaultEasing=defaultEasing;exports.degreesToRadians=degreesToRadians;exports.derefLayers=derefLayers;exports.diffStyles=diffStyles;exports.dot=dot$5;exports.dot$1=dot$4;exports.earthRadius=earthRadius;exports.emitValidationErrors=emitValidationErrors;exports.emptyStyle=emptyStyle;exports.equals=equals$6;exports.evaluateSizeForFeature=evaluateSizeForFeature;exports.evaluateSizeForZoom=evaluateSizeForZoom;exports.extend=extend;exports.filterObject=filterObject;exports.findLineIntersection=findLineIntersection;exports.fromRotation=fromRotation$2;exports.fromScaling=fromScaling;exports.getAnchorAlignment=getAnchorAlignment;exports.getAnchorJustification=getAnchorJustification;exports.getArrayBuffer=getArrayBuffer;exports.getDefaultExportFromCjs=getDefaultExportFromCjs$1;exports.getImageData=getImageData;exports.getJSON=getJSON;exports.getOverlapMode=getOverlapMode;exports.getProtocol=getProtocol;exports.getReferrer=getReferrer;exports.getVideo=getVideo;exports.groupByLayout=groupByLayout;exports.identity=identity$2;exports.interpolate=interpolate;exports.invert=invert$2;exports.isAbortError=isAbortError;exports.isImageBitmap=isImageBitmap;exports.isOffscreenCanvasDistorted=isOffscreenCanvasDistorted;exports.isSafari=isSafari;exports.isWorker=isWorker;exports.keysDifference=keysDifference;exports.makeRequest=makeRequest;exports.mapObject=mapObject;exports.mercatorXfromLng=mercatorXfromLng;exports.mercatorYfromLat=mercatorYfromLat;exports.mercatorZfromAltitude=mercatorZfromAltitude;exports.mul=mul$5;exports.mul$1=mul$3;exports.multiply=multiply$5;exports.nextPowerOfTwo=nextPowerOfTwo;exports.normalize=normalize$4;exports.offscreenCanvasSupported=offscreenCanvasSupported;exports.ortho=ortho;exports.parseCacheControl=parseCacheControl;exports.parseGlyphPbf=parseGlyphPbf;exports.pbf=pbf;exports.performSymbolLayout=performSymbolLayout;exports.perspective=perspective;exports.pick=pick;exports.pointGeometry=pointGeometry;exports.polygonIntersectsPolygon=polygonIntersectsPolygon;exports.potpack=potpack;exports.readImageUsingVideoFrame=readImageUsingVideoFrame;exports.register=register;exports.removeProtocol=removeProtocol;exports.renderColorRamp=renderColorRamp;exports.rotate=rotate$4;exports.rotateX=rotateX$3;exports.rotateZ=rotateZ$3;exports.rtlWorkerPlugin=rtlWorkerPlugin;exports.sameOrigin=sameOrigin;exports.scale=scale$5;exports.scale$1=scale$4;exports.sphericalToCartesian=sphericalToCartesian;exports.sqrLen=sqrLen;exports.sub=sub$2;exports.toEvaluationFeature=toEvaluationFeature;exports.transformMat3=transformMat3$1;exports.transformMat4=transformMat4$1;exports.transformMat4$1=transformMat4;exports.translate=translate$1;exports.unicodeBlockLookup=unicodeBlockLookup;exports.uniqueId=uniqueId;exports.v8Spec=v8Spec;exports.validateCustomStyleLayer=validateCustomStyleLayer;exports.validateLight=validateLight;exports.validateStyle=validateStyle;exports.vectorTile=vectorTile;exports.warnOnce=warnOnce;exports.wrap=wrap}));define("worker",["./shared"],(function(performance){"use strict";class StyleLayerIndex{constructor(layerConfigs){this.keyCache={};if(layerConfigs){this.replace(layerConfigs)}}replace(layerConfigs){this._layerConfigs={};this._layers={};this.update(layerConfigs,[])}update(layerConfigs,removedIds){for(const layerConfig of layerConfigs){this._layerConfigs[layerConfig.id]=layerConfig;const layer=this._layers[layerConfig.id]=performance.createStyleLayer(layerConfig);layer._featureFilter=performance.createFilter(layer.filter);if(this.keyCache[layerConfig.id])delete this.keyCache[layerConfig.id]}for(const id of removedIds){delete this.keyCache[id];delete this._layerConfigs[id];delete this._layers[id]}this.familiesBySource={};const groups=performance.groupByLayout(Object.values(this._layerConfigs),this.keyCache);for(const layerConfigs of groups){const layers=layerConfigs.map((layerConfig=>this._layers[layerConfig.id]));const layer=layers[0];if(layer.visibility==="none"){continue}const sourceId=layer.source||"";let sourceGroup=this.familiesBySource[sourceId];if(!sourceGroup){sourceGroup=this.familiesBySource[sourceId]={}}const sourceLayerId=layer.sourceLayer||"_geojsonTileLayer";let sourceLayerFamilies=sourceGroup[sourceLayerId];if(!sourceLayerFamilies){sourceLayerFamilies=sourceGroup[sourceLayerId]=[]}sourceLayerFamilies.push(layers)}}}const padding=1;class GlyphAtlas{constructor(stacks){const positions={};const bins=[];for(const stack in stacks){const glyphs=stacks[stack];const stackPositions=positions[stack]={};for(const id in glyphs){const src=glyphs[+id];if(!src||src.bitmap.width===0||src.bitmap.height===0)continue;const bin={x:0,y:0,w:src.bitmap.width+2*padding,h:src.bitmap.height+2*padding};bins.push(bin);stackPositions[id]={rect:bin,metrics:src.metrics}}}const{w:w,h:h}=performance.potpack(bins);const image=new performance.AlphaImage({width:w||1,height:h||1});for(const stack in stacks){const glyphs=stacks[stack];for(const id in glyphs){const src=glyphs[+id];if(!src||src.bitmap.width===0||src.bitmap.height===0)continue;const bin=positions[stack][id].rect;performance.AlphaImage.copy(src.bitmap,image,{x:0,y:0},{x:bin.x+padding,y:bin.y+padding},src.bitmap)}}this.image=image;this.positions=positions}}performance.register("GlyphAtlas",GlyphAtlas);class WorkerTile{constructor(params){this.tileID=new performance.OverscaledTileID(params.tileID.overscaledZ,params.tileID.wrap,params.tileID.canonical.z,params.tileID.canonical.x,params.tileID.canonical.y);this.uid=params.uid;this.zoom=params.zoom;this.pixelRatio=params.pixelRatio;this.tileSize=params.tileSize;this.source=params.source;this.overscaling=this.tileID.overscaleFactor();this.showCollisionBoxes=params.showCollisionBoxes;this.collectResourceTiming=!!params.collectResourceTiming;this.returnDependencies=!!params.returnDependencies;this.promoteId=params.promoteId;this.inFlightDependencies=[]}parse(data,layerIndex,availableImages,actor){return performance.__awaiter(this,void 0,void 0,(function*(){this.status="parsing";this.data=data;this.collisionBoxArray=new performance.CollisionBoxArray;const sourceLayerCoder=new performance.DictionaryCoder(Object.keys(data.layers).sort());const featureIndex=new performance.FeatureIndex(this.tileID,this.promoteId);featureIndex.bucketLayerIDs=[];const buckets={};const options={featureIndex:featureIndex,iconDependencies:{},patternDependencies:{},glyphDependencies:{},availableImages:availableImages};const layerFamilies=layerIndex.familiesBySource[this.source];for(const sourceLayerId in layerFamilies){const sourceLayer=data.layers[sourceLayerId];if(!sourceLayer){continue}if(sourceLayer.version===1){performance.warnOnce(`Vector tile source "${this.source}" layer "${sourceLayerId}" `+"does not use vector tile spec v2 and therefore may have some rendering errors.")}const sourceLayerIndex=sourceLayerCoder.encode(sourceLayerId);const features=[];for(let index=0;index=layer.maxzoom)continue;if(layer.visibility==="none")continue;recalculateLayers(family,this.zoom,availableImages);const bucket=buckets[layer.id]=layer.createBucket({index:featureIndex.bucketLayerIDs.length,layers:family,zoom:this.zoom,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:sourceLayerIndex,sourceID:this.source});bucket.populate(features,options,this.tileID.canonical);featureIndex.bucketLayerIDs.push(family.map((l=>l.id)))}}const stacks=performance.mapObject(options.glyphDependencies,(glyphs=>Object.keys(glyphs).map(Number)));this.inFlightDependencies.forEach((request=>request===null||request===void 0?void 0:request.abort()));this.inFlightDependencies=[];let getGlyphsPromise=Promise.resolve({});if(Object.keys(stacks).length){const abortController=new AbortController;this.inFlightDependencies.push(abortController);getGlyphsPromise=actor.sendAsync({type:"getGlyphs",data:{stacks:stacks,source:this.source,tileID:this.tileID,type:"glyphs"}},abortController)}const icons=Object.keys(options.iconDependencies);let getIconsPromise=Promise.resolve({});if(icons.length){const abortController=new AbortController;this.inFlightDependencies.push(abortController);getIconsPromise=actor.sendAsync({type:"getImages",data:{icons:icons,source:this.source,tileID:this.tileID,type:"icons"}},abortController)}const patterns=Object.keys(options.patternDependencies);let getPatternsPromise=Promise.resolve({});if(patterns.length){const abortController=new AbortController;this.inFlightDependencies.push(abortController);getPatternsPromise=actor.sendAsync({type:"getImages",data:{icons:patterns,source:this.source,tileID:this.tileID,type:"patterns"}},abortController)}const[glyphMap,iconMap,patternMap]=yield Promise.all([getGlyphsPromise,getIconsPromise,getPatternsPromise]);const glyphAtlas=new GlyphAtlas(glyphMap);const imageAtlas=new performance.ImageAtlas(iconMap,patternMap);for(const key in buckets){const bucket=buckets[key];if(bucket instanceof performance.SymbolBucket){recalculateLayers(bucket.layers,this.zoom,availableImages);performance.performSymbolLayout({bucket:bucket,glyphMap:glyphMap,glyphPositions:glyphAtlas.positions,imageMap:iconMap,imagePositions:imageAtlas.iconPositions,showCollisionBoxes:this.showCollisionBoxes,canonical:this.tileID.canonical})}else if(bucket.hasPattern&&(bucket instanceof performance.LineBucket||bucket instanceof performance.FillBucket||bucket instanceof performance.FillExtrusionBucket)){recalculateLayers(bucket.layers,this.zoom,availableImages);bucket.addFeatures(options,this.tileID.canonical,imageAtlas.patternPositions)}}this.status="done";return{buckets:Object.values(buckets).filter((b=>!b.isEmpty())),featureIndex:featureIndex,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:glyphAtlas.image,imageAtlas:imageAtlas,glyphMap:this.returnDependencies?glyphMap:null,iconMap:this.returnDependencies?iconMap:null,glyphPositions:this.returnDependencies?glyphAtlas.positions:null}}))}}function recalculateLayers(layers,zoom,availableImages){const parameters=new performance.EvaluationParameters(zoom);for(const layer of layers){layer.recalculate(parameters,availableImages)}}class VectorTileWorkerSource{constructor(actor,layerIndex,availableImages){this.actor=actor;this.layerIndex=layerIndex;this.availableImages=availableImages;this.fetching={};this.loading={};this.loaded={}}loadVectorTile(params,abortController){return performance.__awaiter(this,void 0,void 0,(function*(){const response=yield performance.getArrayBuffer(params.request,abortController);try{const vectorTile=new performance.vectorTile.VectorTile(new performance.Protobuf(response.data));return{vectorTile:vectorTile,rawData:response.data,cacheControl:response.cacheControl,expires:response.expires}}catch(ex){const bytes=new Uint8Array(response.data);const isGzipped=bytes[0]===31&&bytes[1]===139;let errorMessage=`Unable to parse the tile at ${params.request.url}, `;if(isGzipped){errorMessage+="please make sure the data is not gzipped and that you have configured the relevant header in the server"}else{errorMessage+=`got error: ${ex.messge}`}throw new Error(errorMessage)}}))}loadTile(params){return performance.__awaiter(this,void 0,void 0,(function*(){const tileUid=params.uid;const perf=params&¶ms.request&¶ms.request.collectResourceTiming?new performance.RequestPerformance(params.request):false;const workerTile=new WorkerTile(params);this.loading[tileUid]=workerTile;const abortController=new AbortController;workerTile.abort=abortController;try{const response=yield this.loadVectorTile(params,abortController);delete this.loading[tileUid];if(!response){return null}const rawTileData=response.rawData;const cacheControl={};if(response.expires)cacheControl.expires=response.expires;if(response.cacheControl)cacheControl.cacheControl=response.cacheControl;const resourceTiming={};if(perf){const resourceTimingData=perf.finish();if(resourceTimingData)resourceTiming.resourceTiming=JSON.parse(JSON.stringify(resourceTimingData))}workerTile.vectorTile=response.vectorTile;const parsePromise=workerTile.parse(response.vectorTile,this.layerIndex,this.availableImages,this.actor);this.loaded[tileUid]=workerTile;this.fetching[tileUid]={rawTileData:rawTileData,cacheControl:cacheControl,resourceTiming:resourceTiming};try{const result=yield parsePromise;return performance.extend({rawTileData:rawTileData.slice(0)},result,cacheControl,resourceTiming)}finally{delete this.fetching[tileUid]}}catch(err){delete this.loading[tileUid];workerTile.status="done";this.loaded[tileUid]=workerTile;throw err}}))}reloadTile(params){return performance.__awaiter(this,void 0,void 0,(function*(){const uid=params.uid;if(!this.loaded||!this.loaded[uid]){throw new Error("Should not be trying to reload a tile that was never loaded or has been removed")}const workerTile=this.loaded[uid];workerTile.showCollisionBoxes=params.showCollisionBoxes;if(workerTile.status==="parsing"){const result=yield workerTile.parse(workerTile.vectorTile,this.layerIndex,this.availableImages,this.actor);let parseResult;if(this.fetching[uid]){const{rawTileData:rawTileData,cacheControl:cacheControl,resourceTiming:resourceTiming}=this.fetching[uid];delete this.fetching[uid];parseResult=performance.extend({rawTileData:rawTileData.slice(0)},result,cacheControl,resourceTiming)}else{parseResult=result}return parseResult}if(workerTile.status==="done"&&workerTile.vectorTile){return workerTile.parse(workerTile.vectorTile,this.layerIndex,this.availableImages,this.actor)}}))}abortTile(params){return performance.__awaiter(this,void 0,void 0,(function*(){const loading=this.loading;const uid=params.uid;if(loading&&loading[uid]&&loading[uid].abort){loading[uid].abort.abort();delete loading[uid]}}))}removeTile(params){return performance.__awaiter(this,void 0,void 0,(function*(){if(this.loaded&&this.loaded[params.uid]){delete this.loaded[params.uid]}}))}}class RasterDEMTileWorkerSource{constructor(){this.loaded={}}loadTile(params){return performance.__awaiter(this,void 0,void 0,(function*(){const{uid:uid,encoding:encoding,rawImageData:rawImageData,redFactor:redFactor,greenFactor:greenFactor,blueFactor:blueFactor,baseShift:baseShift}=params;const width=rawImageData.width+2;const height=rawImageData.height+2;const imagePixels=performance.isImageBitmap(rawImageData)?new performance.RGBAImage({width:width,height:height},yield performance.getImageData(rawImageData,-1,-1,width,height)):rawImageData;const dem=new performance.DEMData(uid,imagePixels,encoding,redFactor,greenFactor,blueFactor,baseShift);this.loaded=this.loaded||{};this.loaded[uid]=dem;return dem}))}removeTile(params){const loaded=this.loaded,uid=params.uid;if(loaded&&loaded[uid]){delete loaded[uid]}}}var geojsonRewind=rewind$1;function rewind$1(gj,outer){var type=gj&&gj.type,i;if(type==="FeatureCollection"){for(i=0;i=Math.abs(k)?area-m+k:k-m+area;area=m}if(area+err>=0!==!!dir)ring.reverse()}var rewind$2=performance.getDefaultExportFromCjs(geojsonRewind);const toGeoJSON=performance.vectorTile.VectorTileFeature.prototype.toGeoJSON;let FeatureWrapper$1=class FeatureWrapper{constructor(feature){this._feature=feature;this.extent=performance.EXTENT;this.type=feature.type;this.properties=feature.tags;if("id"in feature&&!isNaN(feature.id)){this.id=parseInt(feature.id,10)}}loadGeometry(){if(this._feature.type===1){const geometry=[];for(const point of this._feature.geometry){geometry.push([new performance.Point(point[0],point[1])])}return geometry}else{const geometry=[];for(const ring of this._feature.geometry){const newRing=[];for(const point of ring){newRing.push(new performance.Point(point[0],point[1]))}geometry.push(newRing)}return geometry}}toGeoJSON(x,y,z){return toGeoJSON.call(this,x,y,z)}};let GeoJSONWrapper$2=class GeoJSONWrapper{constructor(features){this.layers={_geojsonTileLayer:this};this.name="_geojsonTileLayer";this.extent=performance.EXTENT;this.length=features.length;this._features=features}feature(i){return new FeatureWrapper$1(this._features[i])}};var vtPbf$1={exports:{}};"use strict";var Point=performance.pointGeometry;var VectorTileFeature=performance.vectorTile.VectorTileFeature;var geojson_wrapper=GeoJSONWrapper$1;function GeoJSONWrapper$1(features,options){this.options=options||{};this.features=features;this.length=features.length}GeoJSONWrapper$1.prototype.feature=function(i){return new FeatureWrapper(this.features[i],this.options.extent)};function FeatureWrapper(feature,extent){this.id=typeof feature.id==="number"?feature.id:undefined;this.type=feature.type;this.rawGeometry=feature.type===1?[feature.geometry]:feature.geometry;this.properties=feature.tags;this.extent=extent||4096}FeatureWrapper.prototype.loadGeometry=function(){var rings=this.rawGeometry;this.geometry=[];for(var i=0;i>31}function writeGeometry(feature,pbf){var geometry=feature.loadGeometry();var type=feature.type;var x=0;var y=0;var rings=geometry.length;for(var r=0;rprops};const fround=Math.fround||(tmp=>x=>{tmp[0]=+x;return tmp[0]})(new Float32Array(1));const OFFSET_ZOOM=2;const OFFSET_ID=3;const OFFSET_PARENT=4;const OFFSET_NUM=5;const OFFSET_PROP=6;class Supercluster{constructor(options){this.options=Object.assign(Object.create(defaultOptions),options);this.trees=new Array(this.options.maxZoom+1);this.stride=this.options.reduce?7:6;this.clusterProps=[]}load(points){const{log:log,minZoom:minZoom,maxZoom:maxZoom}=this.options;if(log)console.time("total time");const timerId=`prepare ${points.length} points`;if(log)console.time(timerId);this.points=points;const data=[];for(let i=0;i=minZoom;z--){const now=+Date.now();tree=this.trees[z]=this._createTree(this._cluster(tree,z));if(log)console.log("z%d: %d clusters in %dms",z,tree.numItems,+Date.now()-now)}if(log)console.timeEnd("total time");return this}getClusters(bbox,zoom){let minLng=((bbox[0]+180)%360+360)%360-180;const minLat=Math.max(-90,Math.min(90,bbox[1]));let maxLng=bbox[2]===180?180:((bbox[2]+180)%360+360)%360-180;const maxLat=Math.max(-90,Math.min(90,bbox[3]));if(bbox[2]-bbox[0]>=360){minLng=-180;maxLng=180}else if(minLng>maxLng){const easternHem=this.getClusters([minLng,minLat,180,maxLat],zoom);const westernHem=this.getClusters([-180,minLat,maxLng,maxLat],zoom);return easternHem.concat(westernHem)}const tree=this.trees[this._limitZoom(zoom)];const ids=tree.range(lngX(minLng),latY(maxLat),lngX(maxLng),latY(minLat));const data=tree.data;const clusters=[];for(const id of ids){const k=this.stride*id;clusters.push(data[k+OFFSET_NUM]>1?getClusterJSON(data,k,this.clusterProps):this.points[data[k+OFFSET_ID]])}return clusters}getChildren(clusterId){const originId=this._getOriginId(clusterId);const originZoom=this._getOriginZoom(clusterId);const errorMsg="No cluster with the specified id.";const tree=this.trees[originZoom];if(!tree)throw new Error(errorMsg);const data=tree.data;if(originId*this.stride>=data.length)throw new Error(errorMsg);const r=this.options.radius/(this.options.extent*Math.pow(2,originZoom-1));const x=data[originId*this.stride];const y=data[originId*this.stride+1];const ids=tree.within(x,y,r);const children=[];for(const id of ids){const k=id*this.stride;if(data[k+OFFSET_PARENT]===clusterId){children.push(data[k+OFFSET_NUM]>1?getClusterJSON(data,k,this.clusterProps):this.points[data[k+OFFSET_ID]])}}if(children.length===0)throw new Error(errorMsg);return children}getLeaves(clusterId,limit,offset){limit=limit||10;offset=offset||0;const leaves=[];this._appendLeaves(leaves,clusterId,limit,offset,0);return leaves}getTile(z,x,y){const tree=this.trees[this._limitZoom(z)];const z2=Math.pow(2,z);const{extent:extent,radius:radius}=this.options;const p=radius/extent;const top=(y-p)/z2;const bottom=(y+1+p)/z2;const tile={features:[]};this._addTileFeatures(tree.range((x-p)/z2,top,(x+1+p)/z2,bottom),tree.data,x,y,z2,tile);if(x===0){this._addTileFeatures(tree.range(1-p/z2,top,1,bottom),tree.data,z2,y,z2,tile)}if(x===z2-1){this._addTileFeatures(tree.range(0,top,p/z2,bottom),tree.data,-1,y,z2,tile)}return tile.features.length?tile:null}getClusterExpansionZoom(clusterId){let expansionZoom=this._getOriginZoom(clusterId)-1;while(expansionZoom<=this.options.maxZoom){const children=this.getChildren(clusterId);expansionZoom++;if(children.length!==1)break;clusterId=children[0].properties.cluster_id}return expansionZoom}_appendLeaves(result,clusterId,limit,offset,skipped){const children=this.getChildren(clusterId);for(const child of children){const props=child.properties;if(props&&props.cluster){if(skipped+props.point_count<=offset){skipped+=props.point_count}else{skipped=this._appendLeaves(result,props.cluster_id,limit,offset,skipped)}}else if(skipped1;let tags,px,py;if(isCluster){tags=getClusterProperties(data,k,this.clusterProps);px=data[k];py=data[k+1]}else{const p=this.points[data[k+OFFSET_ID]];tags=p.properties;const[lng,lat]=p.geometry.coordinates;px=lngX(lng);py=latY(lat)}const f={type:1,geometry:[[Math.round(this.options.extent*(px*z2-x)),Math.round(this.options.extent*(py*z2-y))]],tags:tags};let id;if(isCluster||this.options.generateId){id=data[k+OFFSET_ID]}else{id=this.points[data[k+OFFSET_ID]].id}if(id!==undefined)f.id=id;tile.features.push(f)}}_limitZoom(z){return Math.max(this.options.minZoom,Math.min(Math.floor(+z),this.options.maxZoom+1))}_cluster(tree,zoom){const{radius:radius,extent:extent,reduce:reduce,minPoints:minPoints}=this.options;const r=radius/(extent*Math.pow(2,zoom));const data=tree.data;const nextData=[];const stride=this.stride;for(let i=0;izoom)numPoints+=data[k+OFFSET_NUM]}if(numPoints>numPointsOrigin&&numPoints>=minPoints){let wx=x*numPointsOrigin;let wy=y*numPointsOrigin;let clusterProperties;let clusterPropIndex=-1;const id=((i/stride|0)<<5)+(zoom+1)+this.points.length;for(const neighborId of neighborIds){const k=neighborId*stride;if(data[k+OFFSET_ZOOM]<=zoom)continue;data[k+OFFSET_ZOOM]=zoom;const numPoints2=data[k+OFFSET_NUM];wx+=data[k]*numPoints2;wy+=data[k+1]*numPoints2;data[k+OFFSET_PARENT]=id;if(reduce){if(!clusterProperties){clusterProperties=this._map(data,i,true);clusterPropIndex=this.clusterProps.length;this.clusterProps.push(clusterProperties)}reduce(clusterProperties,this._map(data,k))}}data[i+OFFSET_PARENT]=id;nextData.push(wx/numPoints,wy/numPoints,Infinity,id,-1,numPoints);if(reduce)nextData.push(clusterPropIndex)}else{for(let j=0;j1){for(const neighborId of neighborIds){const k=neighborId*stride;if(data[k+OFFSET_ZOOM]<=zoom)continue;data[k+OFFSET_ZOOM]=zoom;for(let j=0;j>5}_getOriginZoom(clusterId){return(clusterId-this.points.length)%32}_map(data,i,clone){if(data[i+OFFSET_NUM]>1){const props=this.clusterProps[data[i+OFFSET_PROP]];return clone?Object.assign({},props):props}const original=this.points[data[i+OFFSET_ID]].properties;const result=this.options.map(original);return clone&&result===original?Object.assign({},result):result}}function getClusterJSON(data,i,clusterProps){return{type:"Feature",id:data[i+OFFSET_ID],properties:getClusterProperties(data,i,clusterProps),geometry:{type:"Point",coordinates:[xLng(data[i]),yLat(data[i+1])]}}}function getClusterProperties(data,i,clusterProps){const count=data[i+OFFSET_NUM];const abbrev=count>=1e4?`${Math.round(count/1e3)}k`:count>=1e3?`${Math.round(count/100)/10}k`:count;const propIndex=data[i+OFFSET_PROP];const properties=propIndex===-1?{}:Object.assign({},clusterProps[propIndex]);return Object.assign(properties,{cluster:true,cluster_id:data[i+OFFSET_ID],point_count:count,point_count_abbreviated:abbrev})}function lngX(lng){return lng/360+.5}function latY(lat){const sin=Math.sin(lat*Math.PI/180);const y=.5-.25*Math.log((1+sin)/(1-sin))/Math.PI;return y<0?0:y>1?1:y}function xLng(x){return(x-.5)*360}function yLat(y){const y2=(180-y*360)*Math.PI/180;return 360*Math.atan(Math.exp(y2))/Math.PI-90}function simplify(coords,first,last,sqTolerance){var maxSqDist=sqTolerance;var mid=last-first>>1;var minPosToMid=last-first;var index;var ax=coords[first];var ay=coords[first+1];var bx=coords[last];var by=coords[last+1];for(var i=first+3;imaxSqDist){index=i;maxSqDist=d}else if(d===maxSqDist){var posToMid=Math.abs(i-mid);if(posToMidsqTolerance){if(index-first>3)simplify(coords,first,index,sqTolerance);coords[index+2]=maxSqDist;if(last-index>3)simplify(coords,index,last,sqTolerance)}}function getSqSegDist(px,py,x,y,bx,by){var dx=bx-x;var dy=by-y;if(dx!==0||dy!==0){var t=((px-x)*dx+(py-y)*dy)/(dx*dx+dy*dy);if(t>1){x=bx;y=by}else if(t>0){x+=dx*t;y+=dy*t}}dx=px-x;dy=py-y;return dx*dx+dy*dy}function createFeature(id,type,geom,tags){var feature={id:typeof id==="undefined"?null:id,type:type,geometry:geom,tags:tags,minX:Infinity,minY:Infinity,maxX:-Infinity,maxY:-Infinity};calcBBox(feature);return feature}function calcBBox(feature){var geom=feature.geometry;var type=feature.type;if(type==="Point"||type==="MultiPoint"||type==="LineString"){calcLineBBox(feature,geom)}else if(type==="Polygon"||type==="MultiLineString"){for(var i=0;i0){if(isPolygon){size+=(x0*y-x*y0)/2}else{size+=Math.sqrt(Math.pow(x-x0,2)+Math.pow(y-y0,2))}}x0=x;y0=y}var last=out.length-3;out[2]=1;simplify(out,0,last,tolerance);out[last+2]=1;out.size=Math.abs(size);out.start=0;out.end=out.size}function convertLines(rings,out,tolerance,isPolygon){for(var i=0;i1?1:y2}function clip(features,scale,k1,k2,axis,minAll,maxAll,options){k1/=scale;k2/=scale;if(minAll>=k1&&maxAll=k2)return null;var clipped=[];for(var i=0;i=k1&&max=k2){continue}var newGeometry=[];if(type==="Point"||type==="MultiPoint"){clipPoints(geometry,newGeometry,k1,k2,axis)}else if(type==="LineString"){clipLine(geometry,newGeometry,k1,k2,axis,false,options.lineMetrics)}else if(type==="MultiLineString"){clipLines(geometry,newGeometry,k1,k2,axis,false)}else if(type==="Polygon"){clipLines(geometry,newGeometry,k1,k2,axis,true)}else if(type==="MultiPolygon"){for(var j=0;j=k1&&a<=k2){newGeom.push(geom[i]);newGeom.push(geom[i+1]);newGeom.push(geom[i+2])}}}function clipLine(geom,newGeom,k1,k2,axis,isPolygon,trackMetrics){var slice=newSlice(geom);var intersect=axis===0?intersectX:intersectY;var len=geom.start;var segLen,t;for(var i=0;ik1){t=intersect(slice,ax,ay,bx,by,k1);if(trackMetrics)slice.start=len+segLen*t}}else if(a>k2){if(b=k1){t=intersect(slice,ax,ay,bx,by,k1);exited=true}if(b>k2&&a<=k2){t=intersect(slice,ax,ay,bx,by,k2);exited=true}if(!isPolygon&&exited){if(trackMetrics)slice.end=len+segLen*t;newGeom.push(slice);slice=newSlice(geom)}if(trackMetrics)len+=segLen}var last=geom.length-3;ax=geom[last];ay=geom[last+1];az=geom[last+2];a=axis===0?ax:ay;if(a>=k1&&a<=k2)addPoint(slice,ax,ay,az);last=slice.length-3;if(isPolygon&&last>=3&&(slice[last]!==slice[0]||slice[last+1]!==slice[1])){addPoint(slice,slice[0],slice[1],slice[2])}if(slice.length){newGeom.push(slice)}}function newSlice(line){var slice=[];slice.size=line.size;slice.start=line.start;slice.end=line.end;return slice}function clipLines(geom,newGeom,k1,k2,axis,isPolygon){for(var i=0;itile.maxX)tile.maxX=maxX;if(maxY>tile.maxY)tile.maxY=maxY}return tile}function addFeature(tile,feature,tolerance,options){var geom=feature.geometry,type=feature.type,simplified=[];if(type==="Point"||type==="MultiPoint"){for(var i=0;i0&&geom.size<(isPolygon?sqTolerance:tolerance)){tile.numPoints+=geom.length/3;return}var ring=[];for(var i=0;isqTolerance){tile.numSimplified++;ring.push(geom[i]);ring.push(geom[i+1])}tile.numPoints++}if(isPolygon)rewind(ring,isOuter);result.push(ring)}function rewind(ring,clockwise){var area=0;for(var i=0,len=ring.length,j=len-2;i0===clockwise){for(i=0,len=ring.length;i24)throw new Error("maxZoom should be in the 0-24 range");if(options.promoteId&&options.generateId)throw new Error("promoteId and generateId cannot be used together.");var features=convert(data,options);this.tiles={};this.tileCoords=[];if(debug){console.timeEnd("preprocess data");console.log("index: maxZoom: %d, maxPoints: %d",options.indexMaxZoom,options.indexMaxPoints);console.time("generate tiles");this.stats={};this.total=0}features=wrap(features,options);if(features.length)this.splitTile(features,0,0,0);if(debug){if(features.length)console.log("features: %d, points: %d",this.tiles[0].numFeatures,this.tiles[0].numPoints);console.timeEnd("generate tiles");console.log("tiles generated:",this.total,JSON.stringify(this.stats))}}GeoJSONVT.prototype.options={maxZoom:14,indexMaxZoom:5,indexMaxPoints:1e5,tolerance:3,extent:4096,buffer:64,lineMetrics:false,promoteId:null,generateId:false,debug:0};GeoJSONVT.prototype.splitTile=function(features,z,x,y,cz,cx,cy){var stack=[features,z,x,y],options=this.options,debug=options.debug;while(stack.length){y=stack.pop();x=stack.pop();z=stack.pop();features=stack.pop();var z2=1<1)console.time("creation");tile=this.tiles[id]=createTile(features,z,x,y,options);this.tileCoords.push({z:z,x:x,y:y});if(debug){if(debug>1){console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",z,x,y,tile.numFeatures,tile.numPoints,tile.numSimplified);console.timeEnd("creation")}var key="z"+z;this.stats[key]=(this.stats[key]||0)+1;this.total++}}tile.source=features;if(!cz){if(z===options.indexMaxZoom||tile.numPoints<=options.indexMaxPoints)continue}else{if(z===options.maxZoom||z===cz)continue;var m=1<1)console.time("clipping");var k1=.5*options.buffer/options.extent,k2=.5-k1,k3=.5+k1,k4=1+k1,tl,bl,tr,br,left,right;tl=bl=tr=br=null;left=clip(features,z2,x-k1,x+k3,0,tile.minX,tile.maxX,options);right=clip(features,z2,x+k2,x+k4,0,tile.minX,tile.maxX,options);features=null;if(left){tl=clip(left,z2,y-k1,y+k3,1,tile.minY,tile.maxY,options);bl=clip(left,z2,y+k2,y+k4,1,tile.minY,tile.maxY,options);left=null}if(right){tr=clip(right,z2,y-k1,y+k3,1,tile.minY,tile.maxY,options);br=clip(right,z2,y+k2,y+k4,1,tile.minY,tile.maxY,options);right=null}if(debug>1)console.timeEnd("clipping");stack.push(tl||[],z+1,x*2,y*2);stack.push(bl||[],z+1,x*2,y*2+1);stack.push(tr||[],z+1,x*2+1,y*2);stack.push(br||[],z+1,x*2+1,y*2+1)}};GeoJSONVT.prototype.getTile=function(z,x,y){var options=this.options,extent=options.extent,debug=options.debug;if(z<0||z>24)return null;var z2=1<1)console.log("drilling down to z%d-%d-%d",z,x,y);var z0=z,x0=x,y0=y,parent;while(!parent&&z0>0){z0--;x0=Math.floor(x0/2);y0=Math.floor(y0/2);parent=this.tiles[toID(z0,x0,y0)]}if(!parent||!parent.source)return null;if(debug>1)console.log("found parent tile z%d-%d-%d",z0,x0,y0);if(debug>1)console.time("drilling down");this.splitTile(parent.source,z0,x0,y0,z,x,y);if(debug>1)console.timeEnd("drilling down");return this.tiles[id]?transformTile(this.tiles[id],extent):null};function toID(z,x,y){return((1<0||((_b=update.addOrUpdateProperties)===null||_b===void 0?void 0:_b.length)>0);if(cloneFeature||cloneProperties){feature=Object.assign({},feature);updateable.set(update.id,feature);if(cloneProperties){feature.properties=Object.assign({},feature.properties)}}if(update.newGeometry){feature.geometry=update.newGeometry}if(update.removeAllProperties){feature.properties={}}else if(((_c=update.removeProperties)===null||_c===void 0?void 0:_c.length)>0){for(const prop of update.removeProperties){if(Object.prototype.hasOwnProperty.call(feature.properties,prop)){delete feature.properties[prop]}}}if(((_d=update.addOrUpdateProperties)===null||_d===void 0?void 0:_d.length)>0){for(const{key:key,value:value}of update.addOrUpdateProperties){feature.properties[key]=value}}}}}class GeoJSONWorkerSource extends VectorTileWorkerSource{constructor(){super(...arguments);this._dataUpdateable=new Map}loadVectorTile(params,_abortController){return performance.__awaiter(this,void 0,void 0,(function*(){const canonical=params.tileID.canonical;if(!this._geoJSONIndex){throw new Error("Unable to parse the data into a cluster or geojson")}const geoJSONTile=this._geoJSONIndex.getTile(canonical.z,canonical.x,canonical.y);if(!geoJSONTile){return null}const geojsonWrapper=new GeoJSONWrapper$2(geoJSONTile.features);let pbf=vtpbf(geojsonWrapper);if(pbf.byteOffset!==0||pbf.byteLength!==pbf.buffer.byteLength){pbf=new Uint8Array(pbf)}return{vectorTile:geojsonWrapper,rawData:pbf.buffer}}))}loadData(params){var _a;return performance.__awaiter(this,void 0,void 0,(function*(){(_a=this._pendingRequest)===null||_a===void 0?void 0:_a.abort();const perf=params&¶ms.request&¶ms.request.collectResourceTiming?new performance.RequestPerformance(params.request):false;this._pendingRequest=new AbortController;try{let data=yield this.loadGeoJSON(params,this._pendingRequest);delete this._pendingRequest;if(typeof data!=="object"){throw new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`)}rewind$2(data,true);if(params.filter){const compiled=performance.createExpression(params.filter,{type:"boolean","property-type":"data-driven",overridable:false,transition:false});if(compiled.result==="error")throw new Error(compiled.value.map((err=>`${err.key}: ${err.message}`)).join(", "));const features=data.features.filter((feature=>compiled.value.evaluate({zoom:0},feature)));data={type:"FeatureCollection",features:features}}this._geoJSONIndex=params.cluster?new Supercluster(getSuperclusterOptions(params)).load(data.features):geojsonvt(data,params.geojsonVtOptions);this.loaded={};const result={};if(perf){const resourceTimingData=perf.finish();if(resourceTimingData){result.resourceTiming={};result.resourceTiming[params.source]=JSON.parse(JSON.stringify(resourceTimingData))}}return result}catch(err){delete this._pendingRequest;if(performance.isAbortError(err)){return{abandoned:true}}throw err}}))}reloadTile(params){const loaded=this.loaded,uid=params.uid;if(loaded&&loaded[uid]){return super.reloadTile(params)}else{return this.loadTile(params)}}loadGeoJSON(params,abortController){return performance.__awaiter(this,void 0,void 0,(function*(){const{promoteId:promoteId}=params;if(params.request){const response=yield performance.getJSON(params.request,abortController);this._dataUpdateable=isUpdateableGeoJSON(response.data,promoteId)?toUpdateable(response.data,promoteId):undefined;return response.data}if(typeof params.data==="string"){try{const parsed=JSON.parse(params.data);this._dataUpdateable=isUpdateableGeoJSON(parsed,promoteId)?toUpdateable(parsed,promoteId):undefined;return parsed}catch(e){throw new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`)}}if(!params.dataDiff){throw new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`)}if(!this._dataUpdateable){throw new Error(`Cannot update existing geojson data in ${params.source}`)}applySourceDiff(this._dataUpdateable,params.dataDiff,promoteId);return{type:"FeatureCollection",features:Array.from(this._dataUpdateable.values())}}))}removeSource(_params){return performance.__awaiter(this,void 0,void 0,(function*(){if(this._pendingRequest){this._pendingRequest.abort()}}))}getClusterExpansionZoom(params){return this._geoJSONIndex.getClusterExpansionZoom(params.clusterId)}getClusterChildren(params){return this._geoJSONIndex.getChildren(params.clusterId)}getClusterLeaves(params){return this._geoJSONIndex.getLeaves(params.clusterId,params.limit,params.offset)}}function getSuperclusterOptions({superclusterOptions:superclusterOptions,clusterProperties:clusterProperties}){if(!clusterProperties||!superclusterOptions)return superclusterOptions;const mapExpressions={};const reduceExpressions={};const globals={accumulated:null,zoom:0};const feature={properties:null};const propertyNames=Object.keys(clusterProperties);for(const key of propertyNames){const[operator,mapExpression]=clusterProperties[key];const mapExpressionParsed=performance.createExpression(mapExpression);const reduceExpressionParsed=performance.createExpression(typeof operator==="string"?[operator,["accumulated"],["get",key]]:operator);mapExpressions[key]=mapExpressionParsed.value;reduceExpressions[key]=reduceExpressionParsed.value}superclusterOptions.map=pointProperties=>{feature.properties=pointProperties;const properties={};for(const key of propertyNames){properties[key]=mapExpressions[key].evaluate(globals,feature)}return properties};superclusterOptions.reduce=(accumulated,clusterProperties)=>{feature.properties=clusterProperties;for(const key of propertyNames){globals.accumulated=accumulated[key];accumulated[key]=reduceExpressions[key].evaluate(globals,feature)}};return superclusterOptions}class Worker{constructor(self){this.self=self;this.actor=new performance.Actor(self);this.layerIndexes={};this.availableImages={};this.workerSources={};this.demWorkerSources={};this.externalWorkerSourceTypes={};this.self.registerWorkerSource=(name,WorkerSource)=>{if(this.externalWorkerSourceTypes[name]){throw new Error(`Worker source with name "${name}" already registered.`)}this.externalWorkerSourceTypes[name]=WorkerSource};this.self.addProtocol=performance.addProtocol;this.self.removeProtocol=performance.removeProtocol;this.self.registerRTLTextPlugin=rtlTextPlugin=>{if(performance.rtlWorkerPlugin.isParsed()){throw new Error("RTL text plugin already registered.")}performance.rtlWorkerPlugin.setMethods(rtlTextPlugin)};this.actor.registerMessageHandler("loadDEMTile",((mapId,params)=>this._getDEMWorkerSource(mapId,params.source).loadTile(params)));this.actor.registerMessageHandler("removeDEMTile",((mapId,params)=>performance.__awaiter(this,void 0,void 0,(function*(){this._getDEMWorkerSource(mapId,params.source).removeTile(params)}))));this.actor.registerMessageHandler("getClusterExpansionZoom",((mapId,params)=>performance.__awaiter(this,void 0,void 0,(function*(){return this._getWorkerSource(mapId,params.type,params.source).getClusterExpansionZoom(params)}))));this.actor.registerMessageHandler("getClusterChildren",((mapId,params)=>performance.__awaiter(this,void 0,void 0,(function*(){return this._getWorkerSource(mapId,params.type,params.source).getClusterChildren(params)}))));this.actor.registerMessageHandler("getClusterLeaves",((mapId,params)=>performance.__awaiter(this,void 0,void 0,(function*(){return this._getWorkerSource(mapId,params.type,params.source).getClusterLeaves(params)}))));this.actor.registerMessageHandler("loadData",((mapId,params)=>this._getWorkerSource(mapId,params.type,params.source).loadData(params)));this.actor.registerMessageHandler("loadTile",((mapId,params)=>this._getWorkerSource(mapId,params.type,params.source).loadTile(params)));this.actor.registerMessageHandler("reloadTile",((mapId,params)=>this._getWorkerSource(mapId,params.type,params.source).reloadTile(params)));this.actor.registerMessageHandler("abortTile",((mapId,params)=>this._getWorkerSource(mapId,params.type,params.source).abortTile(params)));this.actor.registerMessageHandler("removeTile",((mapId,params)=>this._getWorkerSource(mapId,params.type,params.source).removeTile(params)));this.actor.registerMessageHandler("removeSource",((mapId,params)=>performance.__awaiter(this,void 0,void 0,(function*(){if(!this.workerSources[mapId]||!this.workerSources[mapId][params.type]||!this.workerSources[mapId][params.type][params.source]){return}const worker=this.workerSources[mapId][params.type][params.source];delete this.workerSources[mapId][params.type][params.source];if(worker.removeSource!==undefined){worker.removeSource(params)}}))));this.actor.registerMessageHandler("setReferrer",((_mapId,params)=>performance.__awaiter(this,void 0,void 0,(function*(){this.referrer=params}))));this.actor.registerMessageHandler("syncRTLPluginState",((mapId,params)=>this._syncRTLPluginState(mapId,params)));this.actor.registerMessageHandler("importScript",((_mapId,params)=>performance.__awaiter(this,void 0,void 0,(function*(){this.self.importScripts(params)}))));this.actor.registerMessageHandler("setImages",((mapId,params)=>this._setImages(mapId,params)));this.actor.registerMessageHandler("updateLayers",((mapId,params)=>performance.__awaiter(this,void 0,void 0,(function*(){this._getLayerIndex(mapId).update(params.layers,params.removedIds)}))));this.actor.registerMessageHandler("setLayers",((mapId,params)=>performance.__awaiter(this,void 0,void 0,(function*(){this._getLayerIndex(mapId).replace(params)}))))}_setImages(mapId,images){return performance.__awaiter(this,void 0,void 0,(function*(){this.availableImages[mapId]=images;for(const workerSource in this.workerSources[mapId]){const ws=this.workerSources[mapId][workerSource];for(const source in ws){ws[source].availableImages=images}}}))}_syncRTLPluginState(map,state){return performance.__awaiter(this,void 0,void 0,(function*(){performance.rtlWorkerPlugin.setState(state);const pluginURL=performance.rtlWorkerPlugin.getPluginURL();if(state.pluginStatus==="loaded"&&!performance.rtlWorkerPlugin.isParsed()&&pluginURL!=null){this.self.importScripts(pluginURL);const complete=performance.rtlWorkerPlugin.isParsed();if(complete){return complete}throw new Error(`RTL Text Plugin failed to import scripts from ${pluginURL}`)}return false}))}_getAvailableImages(mapId){let availableImages=this.availableImages[mapId];if(!availableImages){availableImages=[]}return availableImages}_getLayerIndex(mapId){let layerIndexes=this.layerIndexes[mapId];if(!layerIndexes){layerIndexes=this.layerIndexes[mapId]=new StyleLayerIndex}return layerIndexes}_getWorkerSource(mapId,sourceType,sourceName){if(!this.workerSources[mapId])this.workerSources[mapId]={};if(!this.workerSources[mapId][sourceType])this.workerSources[mapId][sourceType]={};if(!this.workerSources[mapId][sourceType][sourceName]){const actor={sendAsync:(message,abortController)=>{message.targetMapId=mapId;return this.actor.sendAsync(message,abortController)}};switch(sourceType){case"vector":this.workerSources[mapId][sourceType][sourceName]=new VectorTileWorkerSource(actor,this._getLayerIndex(mapId),this._getAvailableImages(mapId));break;case"geojson":this.workerSources[mapId][sourceType][sourceName]=new GeoJSONWorkerSource(actor,this._getLayerIndex(mapId),this._getAvailableImages(mapId));break;default:this.workerSources[mapId][sourceType][sourceName]=new this.externalWorkerSourceTypes[sourceType](actor,this._getLayerIndex(mapId),this._getAvailableImages(mapId));break}}return this.workerSources[mapId][sourceType][sourceName]}_getDEMWorkerSource(mapId,sourceType){if(!this.demWorkerSources[mapId])this.demWorkerSources[mapId]={};if(!this.demWorkerSources[mapId][sourceType]){this.demWorkerSources[mapId][sourceType]=new RasterDEMTileWorkerSource}return this.demWorkerSources[mapId][sourceType]}}if(performance.isWorker(self)){self.worker=new Worker(self)}return Worker}));define("index",["exports","./shared"],(function(exports,performance$1){"use strict";var name="maplibre-gl";var description="BSD licensed community fork of mapbox-gl, a WebGL interactive maps library";var version$2="4.0.2";var main="dist/maplibre-gl.js";var style="dist/maplibre-gl.css";var license="BSD-3-Clause";var funding="https://github.com/maplibre/maplibre-gl-js?sponsor=1";var repository={type:"git",url:"git://github.com/maplibre/maplibre-gl-js.git"};var types="dist/maplibre-gl.d.ts";var type="module";var dependencies={"@mapbox/geojson-rewind":"^0.5.2","@mapbox/jsonlint-lines-primitives":"^2.0.2","@mapbox/point-geometry":"^0.1.0","@mapbox/tiny-sdf":"^2.0.6","@mapbox/unitbezier":"^0.0.1","@mapbox/vector-tile":"^1.3.1","@mapbox/whoots-js":"^3.1.0","@maplibre/maplibre-gl-style-spec":"^20.1.1","@types/geojson":"^7946.0.14","@types/geojson-vt":"3.2.5","@types/mapbox__point-geometry":"^0.1.4","@types/mapbox__vector-tile":"^1.3.4","@types/pbf":"^3.0.5","@types/supercluster":"^7.1.3",earcut:"^2.2.4","geojson-vt":"^3.2.1","gl-matrix":"^3.4.3","global-prefix":"^3.0.0",kdbush:"^4.0.2","murmurhash-js":"^1.0.0",pbf:"^3.2.1",potpack:"^2.0.0",quickselect:"^2.0.0",supercluster:"^8.0.1",tinyqueue:"^2.0.3","vt-pbf":"^3.1.3"};var devDependencies={"@mapbox/mapbox-gl-rtl-text":"^0.2.3","@mapbox/mvt-fixtures":"^3.10.0","@rollup/plugin-commonjs":"^25.0.7","@rollup/plugin-json":"^6.1.0","@rollup/plugin-node-resolve":"^15.2.3","@rollup/plugin-replace":"^5.0.5","@rollup/plugin-strip":"^3.0.4","@rollup/plugin-terser":"^0.4.4","@rollup/plugin-typescript":"^11.1.6","@types/benchmark":"^2.1.5","@types/cssnano":"^5.0.0","@types/d3":"^7.4.3","@types/diff":"^5.0.9","@types/earcut":"^2.1.4","@types/eslint":"^8.56.2","@types/gl":"^6.0.5","@types/glob":"^8.1.0","@types/jest":"^29.5.12","@types/jsdom":"^21.1.6","@types/minimist":"^1.2.5","@types/murmurhash-js":"^1.0.6","@types/nise":"^1.4.4","@types/node":"^20.11.19","@types/offscreencanvas":"^2019.7.3","@types/pixelmatch":"^5.2.6","@types/pngjs":"^6.0.4","@types/react":"^18.2.56","@types/react-dom":"^18.2.19","@types/request":"^2.48.12","@types/shuffle-seed":"^1.1.3","@types/window-or-global":"^1.0.6","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^6.21.0",address:"^2.0.1",benchmark:"^2.1.4",canvas:"^2.11.2",cssnano:"^6.0.3",d3:"^7.8.5","d3-queue":"^3.0.7","devtools-protocol":"^0.0.1262051",diff:"^5.2.0","dts-bundle-generator":"^9.3.1",eslint:"^8.56.0","eslint-config-mourner":"^3.0.0","eslint-plugin-html":"^8.0.0","eslint-plugin-import":"^2.29.1","eslint-plugin-jest":"^27.9.0","eslint-plugin-react":"^7.33.2","eslint-plugin-tsdoc":"0.2.17",expect:"^29.7.0",glob:"^10.3.10","is-builtin-module":"^3.2.1",jest:"^29.7.0","jest-environment-jsdom":"^29.7.0","jest-monocart-coverage":"^1.0.2","jest-webgl-canvas-mock":"^2.5.3",jsdom:"^24.0.0","json-stringify-pretty-compact":"^4.0.0",minimist:"^1.2.8","mock-geolocation":"^1.0.11","monocart-coverage-reports":"^2.5.0",nise:"^5.1.9","npm-font-open-sans":"^1.1.0","npm-run-all":"^4.1.5","pdf-merger-js":"^5.1.1",pixelmatch:"^5.3.0",pngjs:"^7.0.0",postcss:"^8.4.35","postcss-cli":"^11.0.0","postcss-inline-svg":"^6.0.0","pretty-bytes":"^6.1.1",puppeteer:"^22.1.0",react:"^18.2.0","react-dom":"^18.2.0",rollup:"^4.12.0","rollup-plugin-sourcemaps":"^0.6.3",rw:"^1.3.3",semver:"^7.6.0","shuffle-seed":"^1.1.6","source-map-explorer":"^2.5.3",st:"^3.0.0",stylelint:"^16.2.1","stylelint-config-standard":"^36.0.0","ts-jest":"^29.1.2","ts-node":"^10.9.2",tslib:"^2.6.2",typedoc:"^0.25.8","typedoc-plugin-markdown":"^3.17.1","typedoc-plugin-missing-exports":"^2.2.0",typescript:"^5.3.3"};var overrides={"postcss-inline-svg":{"css-select":"^5.1.0","dom-serializer":"^2.0.0",htmlparser2:"^8.0.1","postcss-value-parser":"^4.2.0"}};var scripts={"generate-dist-package":"node --no-warnings --loader ts-node/esm build/generate-dist-package.js","generate-shaders":"node --no-warnings --loader ts-node/esm build/generate-shaders.ts","generate-struct-arrays":"node --no-warnings --loader ts-node/esm build/generate-struct-arrays.ts","generate-style-code":"node --no-warnings --loader ts-node/esm build/generate-style-code.ts","generate-typings":"dts-bundle-generator --export-referenced-types --umd-module-name=maplibregl -o ./dist/maplibre-gl.d.ts ./src/index.ts","generate-docs":"typedoc && node --no-warnings --loader ts-node/esm build/generate-docs.ts","generate-images":"node --no-warnings --loader ts-node/esm build/generate-doc-images.ts","build-dist":"npm run build-css && npm run generate-typings && npm run build-dev && npm run build-csp-dev && npm run build-prod && npm run build-csp","build-dev":"rollup --configPlugin @rollup/plugin-typescript -c --environment BUILD:dev","watch-dev":"rollup --configPlugin @rollup/plugin-typescript -c --environment BUILD:dev --watch","build-prod":"rollup --configPlugin @rollup/plugin-typescript -c --environment BUILD:production","build-csp":"rollup --configPlugin @rollup/plugin-typescript -c rollup.config.csp.ts","build-csp-dev":"rollup --configPlugin @rollup/plugin-typescript -c rollup.config.csp.ts --environment BUILD:dev","build-css":"postcss -o dist/maplibre-gl.css src/css/maplibre-gl.css","watch-css":"postcss --watch -o dist/maplibre-gl.css src/css/maplibre-gl.css","build-benchmarks":"npm run build-dev && rollup --configPlugin @rollup/plugin-typescript -c test/bench/rollup_config_benchmarks.ts","watch-benchmarks":"rollup --configPlugin @rollup/plugin-typescript -c test/bench/rollup_config_benchmarks.ts --watch","start-server":"st --no-cache -H 0.0.0.0 --port 9966 .","start-docs":"docker run --rm -it -p 8000:8000 -v ${PWD}:/docs squidfunk/mkdocs-material",start:"run-p watch-css watch-dev start-server","start-bench":"run-p watch-css watch-benchmarks start-server",lint:"eslint --cache --ext .ts,.tsx,.js,.html --ignore-path .gitignore .","lint-css":"stylelint src/css/maplibre-gl.css",test:"run-p lint lint-css test-render jest",jest:"jest","test-build":"jest --selectProjects=build --reporters=default","test-build-ci":"jest --selectProjects=build","test-integration":"jest --selectProjects=integration --reporters=default","test-integration-ci":"jest --selectProjects=integration","test-render":"node --no-warnings --loader ts-node/esm test/integration/render/run_render_tests.ts","test-unit":"jest --selectProjects=unit --reporters=default","test-unit-ci":"jest --coverage --selectProjects unit","test-watch-roots":"jest --watch",codegen:"run-p --print-label generate-dist-package generate-style-code generate-struct-arrays generate-shaders && npm run generate-typings",benchmark:"node --no-warnings --loader ts-node/esm test/bench/run-benchmarks.ts","gl-stats":"node --no-warnings --loader ts-node/esm test/bench/gl-stats.ts",prepare:"npm run codegen",typecheck:"tsc --noEmit && tsc --project tsconfig.dist.json",tsnode:"node --experimental-loader=ts-node/esm --no-warnings"};var files=["build/","dist/*","src/"];var engines={npm:">=8.1.0",node:">=16.14.0"};var packageJSON={name:name,description:description,version:version$2,main:main,style:style,license:license,funding:funding,repository:repository,types:types,type:type,dependencies:dependencies,devDependencies:devDependencies,overrides:overrides,scripts:scripts,files:files,engines:engines};const now=typeof performance!=="undefined"&&performance&&performance.now?performance.now.bind(performance):Date.now.bind(Date);let linkEl;let reducedMotionQuery;const browser={now:now,frameAsync(abortController){return new Promise(((resolve,reject)=>{const frame=requestAnimationFrame(resolve);abortController.signal.addEventListener("abort",(()=>{cancelAnimationFrame(frame);reject(performance$1.createAbortError())}))}))},getImageData(img,padding=0){const context=this.getImageCanvasContext(img);return context.getImageData(-padding,-padding,img.width+2*padding,img.height+2*padding)},getImageCanvasContext(img){const canvas=window.document.createElement("canvas");const context=canvas.getContext("2d",{willReadFrequently:true});if(!context){throw new Error("failed to create canvas 2d context")}canvas.width=img.width;canvas.height=img.height;context.drawImage(img,0,0,img.width,img.height);return context},resolveURL(path){if(!linkEl)linkEl=document.createElement("a");linkEl.href=path;return linkEl.href},hardwareConcurrency:typeof navigator!=="undefined"&&navigator.hardwareConcurrency||4,get prefersReducedMotion(){if(!matchMedia)return false;if(reducedMotionQuery==null){reducedMotionQuery=matchMedia("(prefers-reduced-motion: reduce)")}return reducedMotionQuery.matches}};class DOM{static testProp(props){if(!DOM.docStyle)return props[0];for(let i=0;i{window.removeEventListener("click",DOM.suppressClickInternal,true)}),0)}static getScale(element){const rect=element.getBoundingClientRect();return{x:rect.width/element.offsetWidth||1,y:rect.height/element.offsetHeight||1,boundingClientRect:rect}}static getPoint(el,scale,e){const rect=scale.boundingClientRect;return new performance$1.Point((e.clientX-rect.left)/scale.x-el.clientLeft,(e.clientY-rect.top)/scale.y-el.clientTop)}static mousePos(el,e){const scale=DOM.getScale(el);return DOM.getPoint(el,scale,e)}static touchPos(el,touches){const points=[];const scale=DOM.getScale(el);for(let i=0;i{imageRequestQueue=[];currentParallelImageRequests=0;throttleControlCallbackHandleCounter=0;throttleControlCallbacks={}};ImageRequest.addThrottleControl=callback=>{const handle=throttleControlCallbackHandleCounter++;throttleControlCallbacks[handle]=callback;return handle};ImageRequest.removeThrottleControl=callbackHandle=>{delete throttleControlCallbacks[callbackHandle];processQueue()};const isThrottled=()=>{for(const key of Object.keys(throttleControlCallbacks)){if(throttleControlCallbacks[key]()){return true}}return false};ImageRequest.getImage=(requestParameters,abortController,supportImageRefresh=true)=>new Promise(((resolve,reject)=>{if(webpSupported.supported){if(!requestParameters.headers){requestParameters.headers={}}requestParameters.headers.accept="image/webp,*/*"}performance$1.extend(requestParameters,{type:"image"});const request={abortController:abortController,requestParameters:requestParameters,supportImageRefresh:supportImageRefresh,state:"queued",onError:error=>{reject(error)},onSuccess:response=>{resolve(response)}};imageRequestQueue.push(request);processQueue()}));const arrayBufferToCanvasImageSource=data=>{const imageBitmapSupported=typeof createImageBitmap==="function";if(imageBitmapSupported){return performance$1.arrayBufferToImageBitmap(data)}else{return performance$1.arrayBufferToImage(data)}};const doImageRequest=itemInQueue=>performance$1.__awaiter(this,void 0,void 0,(function*(){itemInQueue.state="running";const{requestParameters:requestParameters,supportImageRefresh:supportImageRefresh,onError:onError,onSuccess:onSuccess,abortController:abortController}=itemInQueue;const canUseHTMLImageElement=supportImageRefresh===false&&!performance$1.isWorker(self)&&!performance$1.getProtocol(requestParameters.url)&&(!requestParameters.headers||Object.keys(requestParameters.headers).reduce(((acc,item)=>acc&&item==="accept"),true));currentParallelImageRequests++;const getImagePromise=canUseHTMLImageElement?getImageUsingHtmlImage(requestParameters,abortController):performance$1.makeRequest(requestParameters,abortController);try{const response=yield getImagePromise;delete itemInQueue.abortController;itemInQueue.state="completed";if(response.data instanceof HTMLImageElement||performance$1.isImageBitmap(response.data)){onSuccess(response)}else if(response.data){const img=yield arrayBufferToCanvasImageSource(response.data);onSuccess({data:img,cacheControl:response.cacheControl,expires:response.expires})}}catch(err){delete itemInQueue.abortController;onError(err)}finally{currentParallelImageRequests--;processQueue()}}));const processQueue=()=>{const maxImageRequests=isThrottled()?performance$1.config.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:performance$1.config.MAX_PARALLEL_IMAGE_REQUESTS;for(let numImageRequests=currentParallelImageRequests;numImageRequests0;numImageRequests++){const topItemInQueue=imageRequestQueue.shift();if(topItemInQueue.abortController.signal.aborted){numImageRequests--;continue}doImageRequest(topItemInQueue)}};const getImageUsingHtmlImage=(requestParameters,abortController)=>new Promise(((resolve,reject)=>{const image=new Image;const url=requestParameters.url;const credentials=requestParameters.credentials;if(credentials&&credentials==="include"){image.crossOrigin="use-credentials"}else if(credentials&&credentials==="same-origin"||!performance$1.sameOrigin(url)){image.crossOrigin="anonymous"}abortController.signal.addEventListener("abort",(()=>{image.src="";reject(performance$1.createAbortError())}));image.fetchPriority="high";image.onload=()=>{image.onerror=image.onload=null;resolve({data:image})};image.onerror=()=>{image.onerror=image.onload=null;if(abortController.signal.aborted){return}reject(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."))};image.src=url}))})(ImageRequest||(ImageRequest={}));ImageRequest.resetRequestQueue();var ResourceType;(function(ResourceType){ResourceType["Glyphs"]="Glyphs";ResourceType["Image"]="Image";ResourceType["Source"]="Source";ResourceType["SpriteImage"]="SpriteImage";ResourceType["SpriteJSON"]="SpriteJSON";ResourceType["Style"]="Style";ResourceType["Tile"]="Tile";ResourceType["Unknown"]="Unknown"})(ResourceType||(ResourceType={}));class RequestManager{constructor(transformRequestFn){this._transformRequestFn=transformRequestFn}transformRequest(url,type){if(this._transformRequestFn){return this._transformRequestFn(url,type)||{url:url}}return{url:url}}normalizeSpriteURL(url,format,extension){const urlObject=parseUrl(url);urlObject.path+=`${format}${extension}`;return formatUrl(urlObject)}setTransformRequest(transformRequest){this._transformRequestFn=transformRequest}}const urlRe=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function parseUrl(url){const parts=url.match(urlRe);if(!parts){throw new Error(`Unable to parse URL "${url}"`)}return{protocol:parts[1],authority:parts[2],path:parts[3]||"/",params:parts[4]?parts[4].split("&"):[]}}function formatUrl(obj){const params=obj.params.length?`?${obj.params.join("&")}`:"";return`${obj.protocol}://${obj.authority}${obj.path}${params}`}function coerceSpriteToArray(sprite){const resultArray=[];if(typeof sprite==="string"){resultArray.push({id:"default",url:sprite})}else if(sprite&&sprite.length>0){const dedupArray=[];for(const{id:id,url:url}of sprite){const key=`${id}${url}`;if(dedupArray.indexOf(key)===-1){dedupArray.push(key);resultArray.push({id:id,url:url})}}}return resultArray}function loadSprite(originalSprite,requestManager,pixelRatio,abortController){return performance$1.__awaiter(this,void 0,void 0,(function*(){const spriteArray=coerceSpriteToArray(originalSprite);const format=pixelRatio>1?"@2x":"";const jsonsMap={};const imagesMap={};for(const{id:id,url:url}of spriteArray){const jsonRequestParameters=requestManager.transformRequest(requestManager.normalizeSpriteURL(url,format,".json"),ResourceType.SpriteJSON);jsonsMap[id]=performance$1.getJSON(jsonRequestParameters,abortController);const imageRequestParameters=requestManager.transformRequest(requestManager.normalizeSpriteURL(url,format,".png"),ResourceType.SpriteImage);imagesMap[id]=ImageRequest.getImage(imageRequestParameters,abortController)}yield Promise.all([...Object.values(jsonsMap),...Object.values(imagesMap)]);return doOnceCompleted(jsonsMap,imagesMap)}))}function doOnceCompleted(jsonsMap,imagesMap){return performance$1.__awaiter(this,void 0,void 0,(function*(){const result={};for(const spriteName in jsonsMap){result[spriteName]={};const context=browser.getImageCanvasContext((yield imagesMap[spriteName]).data);const json=(yield jsonsMap[spriteName]).data;for(const id in json){const{width:width,height:height,x:x,y:y,sdf:sdf,pixelRatio:pixelRatio,stretchX:stretchX,stretchY:stretchY,content:content}=json[id];const spriteData={width:width,height:height,x:x,y:y,context:context};result[spriteName][id]={data:null,pixelRatio:pixelRatio,sdf:sdf,stretchX:stretchX,stretchY:stretchY,content:content,spriteData:spriteData}}}return result}))}class Texture{constructor(context,image,format,options){this.context=context;this.format=format;this.texture=context.gl.createTexture();this.update(image,options)}update(image,options,position){const{width:width,height:height}=image;const resize=(!this.size||this.size[0]!==width||this.size[1]!==height)&&!position;const{context:context}=this;const{gl:gl}=context;this.useMipmap=Boolean(options&&options.useMipmap);gl.bindTexture(gl.TEXTURE_2D,this.texture);context.pixelStoreUnpackFlipY.set(false);context.pixelStoreUnpack.set(1);context.pixelStoreUnpackPremultiplyAlpha.set(this.format===gl.RGBA&&(!options||options.premultiply!==false));if(resize){this.size=[width,height];if(image instanceof HTMLImageElement||image instanceof HTMLCanvasElement||image instanceof HTMLVideoElement||image instanceof ImageData||performance$1.isImageBitmap(image)){gl.texImage2D(gl.TEXTURE_2D,0,this.format,this.format,gl.UNSIGNED_BYTE,image)}else{gl.texImage2D(gl.TEXTURE_2D,0,this.format,width,height,0,this.format,gl.UNSIGNED_BYTE,image.data)}}else{const{x:x,y:y}=position||{x:0,y:0};if(image instanceof HTMLImageElement||image instanceof HTMLCanvasElement||image instanceof HTMLVideoElement||image instanceof ImageData||performance$1.isImageBitmap(image)){gl.texSubImage2D(gl.TEXTURE_2D,0,x,y,gl.RGBA,gl.UNSIGNED_BYTE,image)}else{gl.texSubImage2D(gl.TEXTURE_2D,0,x,y,width,height,gl.RGBA,gl.UNSIGNED_BYTE,image.data)}}if(this.useMipmap&&this.isSizePowerOfTwo()){gl.generateMipmap(gl.TEXTURE_2D)}}bind(filter,wrap,minFilter){const{context:context}=this;const{gl:gl}=context;gl.bindTexture(gl.TEXTURE_2D,this.texture);if(minFilter===gl.LINEAR_MIPMAP_NEAREST&&!this.isSizePowerOfTwo()){minFilter=gl.LINEAR}if(filter!==this.filter){gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,filter);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,minFilter||filter);this.filter=filter}if(wrap!==this.wrap){gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,wrap);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,wrap);this.wrap=wrap}}isSizePowerOfTwo(){return this.size[0]===this.size[1]&&Math.log(this.size[0])/Math.LN2%1===0}destroy(){const{gl:gl}=this.context;gl.deleteTexture(this.texture);this.texture=null}}function renderStyleImage(image){const{userImage:userImage}=image;if(userImage&&userImage.render){const updated=userImage.render();if(updated){image.data.replace(new Uint8Array(userImage.data.buffer));return true}}return false}const padding=1;class ImageManager extends performance$1.Evented{constructor(){super();this.images={};this.updatedImages={};this.callbackDispatchedThisFrame={};this.loaded=false;this.requestors=[];this.patterns={};this.atlasImage=new performance$1.RGBAImage({width:1,height:1});this.dirty=true}isLoaded(){return this.loaded}setLoaded(loaded){if(this.loaded===loaded){return}this.loaded=loaded;if(loaded){for(const{ids:ids,promiseResolve:promiseResolve}of this.requestors){promiseResolve(this._getImagesForIds(ids))}this.requestors=[]}}getImage(id){const image=this.images[id];if(image&&!image.data&&image.spriteData){const spriteData=image.spriteData;image.data=new performance$1.RGBAImage({width:spriteData.width,height:spriteData.height},spriteData.context.getImageData(spriteData.x,spriteData.y,spriteData.width,spriteData.height).data);image.spriteData=null}return image}addImage(id,image){if(this.images[id])throw new Error(`Image id ${id} already exist, use updateImage instead`);if(this._validate(id,image)){this.images[id]=image}}_validate(id,image){let valid=true;const data=image.data||image.spriteData;if(!this._validateStretch(image.stretchX,data&&data.width)){this.fire(new performance$1.ErrorEvent(new Error(`Image "${id}" has invalid "stretchX" value`)));valid=false}if(!this._validateStretch(image.stretchY,data&&data.height)){this.fire(new performance$1.ErrorEvent(new Error(`Image "${id}" has invalid "stretchY" value`)));valid=false}if(!this._validateContent(image.content,image)){this.fire(new performance$1.ErrorEvent(new Error(`Image "${id}" has invalid "content" value`)));valid=false}return valid}_validateStretch(stretch,size){if(!stretch)return true;let last=0;for(const part of stretch){if(part[0]{let hasAllDependencies=true;if(!this.isLoaded()){for(const id of ids){if(!this.images[id]){hasAllDependencies=false}}}if(this.isLoaded()||hasAllDependencies){resolve(this._getImagesForIds(ids))}else{this.requestors.push({ids:ids,promiseResolve:resolve})}}))}_getImagesForIds(ids){const response={};for(const id of ids){let image=this.getImage(id);if(!image){this.fire(new performance$1.Event("styleimagemissing",{id:id}));image=this.getImage(id)}if(image){response[id]={data:image.data.clone(),pixelRatio:image.pixelRatio,sdf:image.sdf,version:image.version,stretchX:image.stretchX,stretchY:image.stretchY,content:image.content,hasRenderCallback:Boolean(image.userImage&&image.userImage.render)}}else{performance$1.warnOnce(`Image "${id}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`)}}return response}getPixelSize(){const{width:width,height:height}=this.atlasImage;return{width:width,height:height}}getPattern(id){const pattern=this.patterns[id];const image=this.getImage(id);if(!image){return null}if(pattern&&pattern.position.version===image.version){return pattern.position}if(!pattern){const w=image.data.width+padding*2;const h=image.data.height+padding*2;const bin={w:w,h:h,x:0,y:0};const position=new performance$1.ImagePosition(bin,image);this.patterns[id]={bin:bin,position:position}}else{pattern.position.version=image.version}this._updatePatternAtlas();return this.patterns[id].position}bind(context){const gl=context.gl;if(!this.atlasTexture){this.atlasTexture=new Texture(context,this.atlasImage,gl.RGBA)}else if(this.dirty){this.atlasTexture.update(this.atlasImage);this.dirty=false}this.atlasTexture.bind(gl.LINEAR,gl.CLAMP_TO_EDGE)}_updatePatternAtlas(){const bins=[];for(const id in this.patterns){bins.push(this.patterns[id].bin)}const{w:w,h:h}=performance$1.potpack(bins);const dst=this.atlasImage;dst.resize({width:w||1,height:h||1});for(const id in this.patterns){const{bin:bin}=this.patterns[id];const x=bin.x+padding;const y=bin.y+padding;const src=this.getImage(id).data;const w=src.width;const h=src.height;performance$1.RGBAImage.copy(src,dst,{x:0,y:0},{x:x,y:y},{width:w,height:h});performance$1.RGBAImage.copy(src,dst,{x:0,y:h-1},{x:x,y:y-1},{width:w,height:1});performance$1.RGBAImage.copy(src,dst,{x:0,y:0},{x:x,y:y+h},{width:w,height:1});performance$1.RGBAImage.copy(src,dst,{x:w-1,y:0},{x:x-1,y:y},{width:1,height:h});performance$1.RGBAImage.copy(src,dst,{x:0,y:0},{x:x+w,y:y},{width:1,height:h})}this.dirty=true}beginFrame(){this.callbackDispatchedThisFrame={}}dispatchRenderCallbacks(ids){for(const id of ids){if(this.callbackDispatchedThisFrame[id])continue;this.callbackDispatchedThisFrame[id]=true;const image=this.getImage(id);if(!image)performance$1.warnOnce(`Image with ID: "${id}" was not found`);const updated=renderStyleImage(image);if(updated){this.updateImage(id,image)}}}}function loadGlyphRange(fontstack,range,urlTemplate,requestManager){return performance$1.__awaiter(this,void 0,void 0,(function*(){const begin=range*256;const end=begin+255;const request=requestManager.transformRequest(urlTemplate.replace("{fontstack}",fontstack).replace("{range}",`${begin}-${end}`),ResourceType.Glyphs);const response=yield performance$1.getArrayBuffer(request,new AbortController);if(!response||!response.data){throw new Error(`Could not load glyph range. range: ${range}, ${begin}-${end}`)}const glyphs={};for(const glyph of performance$1.parseGlyphPbf(response.data)){glyphs[glyph.id]=glyph}return glyphs}))}const INF=1e20;class TinySDF{constructor({fontSize:fontSize=24,buffer:buffer=3,radius:radius=8,cutoff:cutoff=.25,fontFamily:fontFamily="sans-serif",fontWeight:fontWeight="normal",fontStyle:fontStyle="normal"}={}){this.buffer=buffer;this.cutoff=cutoff;this.radius=radius;const size=this.size=fontSize+buffer*4;const canvas=this._createCanvas(size);const ctx=this.ctx=canvas.getContext("2d",{willReadFrequently:true});ctx.font=`${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`;ctx.textBaseline="alphabetic";ctx.textAlign="left";ctx.fillStyle="black";this.gridOuter=new Float64Array(size*size);this.gridInner=new Float64Array(size*size);this.f=new Float64Array(size);this.z=new Float64Array(size+1);this.v=new Uint16Array(size)}_createCanvas(size){const canvas=document.createElement("canvas");canvas.width=canvas.height=size;return canvas}draw(char){const{width:glyphAdvance,actualBoundingBoxAscent:actualBoundingBoxAscent,actualBoundingBoxDescent:actualBoundingBoxDescent,actualBoundingBoxLeft:actualBoundingBoxLeft,actualBoundingBoxRight:actualBoundingBoxRight}=this.ctx.measureText(char);const glyphTop=Math.ceil(actualBoundingBoxAscent);const glyphLeft=0;const glyphWidth=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(actualBoundingBoxRight-actualBoundingBoxLeft)));const glyphHeight=Math.min(this.size-this.buffer,glyphTop+Math.ceil(actualBoundingBoxDescent));const width=glyphWidth+2*this.buffer;const height=glyphHeight+2*this.buffer;const len=Math.max(width*height,0);const data=new Uint8ClampedArray(len);const glyph={data:data,width:width,height:height,glyphWidth:glyphWidth,glyphHeight:glyphHeight,glyphTop:glyphTop,glyphLeft:glyphLeft,glyphAdvance:glyphAdvance};if(glyphWidth===0||glyphHeight===0)return glyph;const{ctx:ctx,buffer:buffer,gridInner:gridInner,gridOuter:gridOuter}=this;ctx.clearRect(buffer,buffer,glyphWidth,glyphHeight);ctx.fillText(char,buffer,buffer+glyphTop);const imgData=ctx.getImageData(buffer,buffer,glyphWidth,glyphHeight);gridOuter.fill(INF,0,len);gridInner.fill(0,0,len);for(let y=0;y0?d*d:0;gridInner[j]=d<0?d*d:0}}}edt(gridOuter,0,0,width,height,width,this.f,this.v,this.z);edt(gridInner,buffer,buffer,glyphWidth,glyphHeight,width,this.f,this.v,this.z);for(let i=0;i-1);k++;v[k]=q;z[k]=s;z[k+1]=INF}for(let q=0,k=0;q65535){throw new Error("glyphs > 65535 not supported")}if(entry.ranges[range]){return{stack:stack,id:id,glyph:glyph}}if(!this.url){throw new Error("glyphsUrl is not set")}if(!entry.requests[range]){const promise=GlyphManager.loadGlyphRange(stack,range,this.url,this.requestManager);entry.requests[range]=promise}const response=yield entry.requests[range];for(const id in response){if(!this._doesCharSupportLocalGlyph(+id)){entry.glyphs[+id]=response[+id]}}entry.ranges[range]=true;return{stack:stack,id:id,glyph:response[id]||null}}))}_doesCharSupportLocalGlyph(id){return!!this.localIdeographFontFamily&&(performance$1.unicodeBlockLookup["CJK Unified Ideographs"](id)||performance$1.unicodeBlockLookup["Hangul Syllables"](id)||performance$1.unicodeBlockLookup["Hiragana"](id)||performance$1.unicodeBlockLookup["Katakana"](id))}_tinySDF(entry,stack,id){const fontFamily=this.localIdeographFontFamily;if(!fontFamily){return}if(!this._doesCharSupportLocalGlyph(id)){return}const textureScale=2;let tinySDF=entry.tinySDF;if(!tinySDF){let fontWeight="400";if(/bold/i.test(stack)){fontWeight="900"}else if(/medium/i.test(stack)){fontWeight="500"}else if(/light/i.test(stack)){fontWeight="200"}tinySDF=entry.tinySDF=new GlyphManager.TinySDF({fontSize:24*textureScale,buffer:3*textureScale,radius:8*textureScale,cutoff:.25,fontFamily:fontFamily,fontWeight:fontWeight})}const char=tinySDF.draw(String.fromCharCode(id));const topAdjustment=27.5;const leftAdjustment=.5;return{id:id,bitmap:new performance$1.AlphaImage({width:char.width||30*textureScale,height:char.height||30*textureScale},char.data),metrics:{width:char.glyphWidth/textureScale||24,height:char.glyphHeight/textureScale||24,left:char.glyphLeft/textureScale+leftAdjustment||0,top:char.glyphTop/textureScale-topAdjustment||-8,advance:char.glyphAdvance/textureScale||24,isDoubleResolution:true}}}}GlyphManager.loadGlyphRange=loadGlyphRange;GlyphManager.TinySDF=TinySDF;class LightPositionProperty{constructor(){this.specification=performance$1.v8Spec.light.position}possiblyEvaluate(value,parameters){return performance$1.sphericalToCartesian(value.expression.evaluate(parameters))}interpolate(a,b,t){return{x:performance$1.interpolate.number(a.x,b.x,t),y:performance$1.interpolate.number(a.y,b.y,t),z:performance$1.interpolate.number(a.z,b.z,t)}}}const TRANSITION_SUFFIX="-transition";let lightProperties;class Light extends performance$1.Evented{constructor(lightOptions){super();lightProperties=lightProperties||new performance$1.Properties({anchor:new performance$1.DataConstantProperty(performance$1.v8Spec.light.anchor),position:new LightPositionProperty,color:new performance$1.DataConstantProperty(performance$1.v8Spec.light.color),intensity:new performance$1.DataConstantProperty(performance$1.v8Spec.light.intensity)});this._transitionable=new performance$1.Transitionable(lightProperties);this.setLight(lightOptions);this._transitioning=this._transitionable.untransitioned()}getLight(){return this._transitionable.serialize()}setLight(light,options={}){if(this._validate(performance$1.validateLight,light,options)){return}for(const name in light){const value=light[name];if(name.endsWith(TRANSITION_SUFFIX)){this._transitionable.setTransition(name.slice(0,-TRANSITION_SUFFIX.length),value)}else{this._transitionable.setValue(name,value)}}}updateTransitions(parameters){this._transitioning=this._transitionable.transitioned(parameters,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(parameters){this.properties=this._transitioning.possiblyEvaluate(parameters)}_validate(validate,value,options){if(options&&options.validate===false){return false}return performance$1.emitValidationErrors(this,validate.call(performance$1.validateStyle,{value:value,style:{glyphs:true,sprite:true},styleSpec:performance$1.v8Spec}))}}class LineAtlas{constructor(width,height){this.width=width;this.height=height;this.nextRow=0;this.data=new Uint8Array(this.width*this.height);this.dashEntry={}}getDash(dasharray,round){const key=dasharray.join(",")+String(round);if(!this.dashEntry[key]){this.dashEntry[key]=this.addDash(dasharray,round)}return this.dashEntry[key]}getDashRanges(dasharray,lineAtlasWidth,stretch){const oddDashArray=dasharray.length%2===1;const ranges=[];let left=oddDashArray?-dasharray[dasharray.length-1]*stretch:0;let right=dasharray[0]*stretch;let isDash=true;ranges.push({left:left,right:right,isDash:isDash,zeroLength:dasharray[0]===0});let currentDashLength=dasharray[0];for(let i=1;i1){range=ranges[++currIndex]}const distLeft=Math.abs(x-range.left);const distRight=Math.abs(x-range.right);const minDist=Math.min(distLeft,distRight);let signedDistance;const distMiddle=y/n*(halfStretch+1);if(range.isDash){const distEdge=halfStretch-Math.abs(distMiddle);signedDistance=Math.sqrt(minDist*minDist+distEdge*distEdge)}else{signedDistance=halfStretch-Math.sqrt(minDist*minDist+distMiddle*distMiddle)}this.data[index+x]=Math.max(0,Math.min(255,signedDistance+128))}}}addRegularDash(ranges){for(let i=ranges.length-1;i>=0;--i){const part=ranges[i];const next=ranges[i+1];if(part.zeroLength){ranges.splice(i,1)}else if(next&&next.isDash===part.isDash){next.left=part.left;ranges.splice(i,1)}}const first=ranges[0];const last=ranges[ranges.length-1];if(first.isDash===last.isDash){first.left=last.left-this.width;last.right=first.right+this.width}const index=this.width*this.nextRow;let currIndex=0;let range=ranges[currIndex];for(let x=0;x1){range=ranges[++currIndex]}const distLeft=Math.abs(x-range.left);const distRight=Math.abs(x-range.right);const minDist=Math.min(distLeft,distRight);const signedDistance=range.isDash?minDist:-minDist;this.data[index+x]=Math.max(0,Math.min(255,signedDistance+128))}}addDash(dasharray,round){const n=round?7:0;const height=2*n+1;if(this.nextRow+height>this.height){performance$1.warnOnce("LineAtlas out of space");return null}let length=0;for(let i=0;i{w.terminate()}));this.workers=null}}isPreloaded(){return!!this.active[PRELOAD_POOL_ID]}numActive(){return Object.keys(this.active).length}}const availableLogicalProcessors=Math.floor(browser.hardwareConcurrency/2);WorkerPool.workerCount=performance$1.isSafari(globalThis)?Math.max(Math.min(availableLogicalProcessors,3),1):1;let globalWorkerPool;function getGlobalWorkerPool(){if(!globalWorkerPool){globalWorkerPool=new WorkerPool}return globalWorkerPool}function prewarm(){const workerPool=getGlobalWorkerPool();workerPool.acquire(PRELOAD_POOL_ID)}function clearPrewarmedResources(){const pool=globalWorkerPool;if(pool){if(pool.isPreloaded()&&pool.numActive()===1){pool.release(PRELOAD_POOL_ID);globalWorkerPool=null}else{console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()")}}}class Dispatcher{constructor(workerPool,mapId){this.workerPool=workerPool;this.actors=[];this.currentActor=0;this.id=mapId;const workers=this.workerPool.acquire(mapId);for(let i=0;i{actor.remove()}));this.actors=[];if(mapRemoved)this.workerPool.release(this.id)}registerMessageHandler(type,handler){for(const actor of this.actors){actor.registerMessageHandler(type,handler)}}}let globalDispatcher;function getGlobalDispatcher(){if(!globalDispatcher){globalDispatcher=new Dispatcher(getGlobalWorkerPool(),performance$1.GLOBAL_DISPATCHER_ID);globalDispatcher.registerMessageHandler("getResource",((_mapId,params,abortController)=>performance$1.makeRequest(params,abortController)))}return globalDispatcher}function getPixelPosMatrix(transform,tileID){const t=performance$1.create();performance$1.translate(t,t,[1,1,0]);performance$1.scale(t,t,[transform.width*.5,transform.height*.5,1]);return performance$1.multiply(t,t,transform.calculatePosMatrix(tileID.toUnwrapped()))}function queryIncludes3DLayer(layers,styleLayers,sourceID){if(layers){for(const layerID of layers){const layer=styleLayers[layerID];if(layer&&layer.source===sourceID&&layer.type==="fill-extrusion"){return true}}}else{for(const key in styleLayers){const layer=styleLayers[key];if(layer.source===sourceID&&layer.type==="fill-extrusion"){return true}}}return false}function queryRenderedFeatures(sourceCache,styleLayers,serializedLayers,queryGeometry,params,transform){const has3DLayer=queryIncludes3DLayer(params&¶ms.layers,styleLayers,sourceCache.id);const maxPitchScaleFactor=transform.maxPitchScaleFactor();const tilesIn=sourceCache.tilesIn(queryGeometry,maxPitchScaleFactor,has3DLayer);tilesIn.sort(sortTilesIn);const renderedFeatureLayers=[];for(const tileIn of tilesIn){renderedFeatureLayers.push({wrappedTileID:tileIn.tileID.wrapped().key,queryResults:tileIn.tile.queryRenderedFeatures(styleLayers,serializedLayers,sourceCache._state,tileIn.queryGeometry,tileIn.cameraQueryGeometry,tileIn.scale,params,transform,maxPitchScaleFactor,getPixelPosMatrix(sourceCache.transform,tileIn.tileID))})}const result=mergeRenderedFeatureLayers(renderedFeatureLayers);for(const layerID in result){result[layerID].forEach((featureWrapper=>{const feature=featureWrapper.feature;const state=sourceCache.getFeatureState(feature.layer["source-layer"],feature.id);feature.source=feature.layer.source;if(feature.layer["source-layer"]){feature.sourceLayer=feature.layer["source-layer"]}feature.state=state}))}return result}function queryRenderedSymbols(styleLayers,serializedLayers,sourceCaches,queryGeometry,params,collisionIndex,retainedQueryData){const result={};const renderedSymbols=collisionIndex.queryRenderedSymbols(queryGeometry);const bucketQueryData=[];for(const bucketInstanceId of Object.keys(renderedSymbols).map(Number)){bucketQueryData.push(retainedQueryData[bucketInstanceId])}bucketQueryData.sort(sortTilesIn);for(const queryData of bucketQueryData){const bucketSymbols=queryData.featureIndex.lookupSymbolFeatures(renderedSymbols[queryData.bucketInstanceId],serializedLayers,queryData.bucketIndex,queryData.sourceLayerIndex,params.filter,params.layers,params.availableImages,styleLayers);for(const layerID in bucketSymbols){const resultFeatures=result[layerID]=result[layerID]||[];const layerSymbols=bucketSymbols[layerID];layerSymbols.sort(((a,b)=>{const featureSortOrder=queryData.featureSortOrder;if(featureSortOrder){const sortedA=featureSortOrder.indexOf(a.featureIndex);const sortedB=featureSortOrder.indexOf(b.featureIndex);return sortedB-sortedA}else{return b.featureIndex-a.featureIndex}}));for(const symbolFeature of layerSymbols){resultFeatures.push(symbolFeature)}}}for(const layerName in result){result[layerName].forEach((featureWrapper=>{const feature=featureWrapper.feature;const layer=styleLayers[layerName];const sourceCache=sourceCaches[layer.source];const state=sourceCache.getFeatureState(feature.layer["source-layer"],feature.id);feature.source=feature.layer.source;if(feature.layer["source-layer"]){feature.sourceLayer=feature.layer["source-layer"]}feature.state=state}))}return result}function querySourceFeatures(sourceCache,params){const tiles=sourceCache.getRenderableIds().map((id=>sourceCache.getTileByID(id)));const result=[];const dataTiles={};for(let i=0;ilayer.id))}return result}))}class LngLatBounds{constructor(sw,ne){if(!sw){}else if(ne){this.setSouthWest(sw).setNorthEast(ne)}else if(Array.isArray(sw)){if(sw.length===4){this.setSouthWest([sw[0],sw[1]]).setNorthEast([sw[2],sw[3]])}else{this.setSouthWest(sw[0]).setNorthEast(sw[1])}}}setNorthEast(ne){this._ne=ne instanceof performance$1.LngLat?new performance$1.LngLat(ne.lng,ne.lat):performance$1.LngLat.convert(ne);return this}setSouthWest(sw){this._sw=sw instanceof performance$1.LngLat?new performance$1.LngLat(sw.lng,sw.lat):performance$1.LngLat.convert(sw);return this}extend(obj){const sw=this._sw,ne=this._ne;let sw2,ne2;if(obj instanceof performance$1.LngLat){sw2=obj;ne2=obj}else if(obj instanceof LngLatBounds){sw2=obj._sw;ne2=obj._ne;if(!sw2||!ne2)return this}else{if(Array.isArray(obj)){if(obj.length===4||obj.every(Array.isArray)){const lngLatBoundsObj=obj;return this.extend(LngLatBounds.convert(lngLatBoundsObj))}else{const lngLatObj=obj;return this.extend(performance$1.LngLat.convert(lngLatObj))}}else if(obj&&("lng"in obj||"lon"in obj)&&"lat"in obj){return this.extend(performance$1.LngLat.convert(obj))}return this}if(!sw&&!ne){this._sw=new performance$1.LngLat(sw2.lng,sw2.lat);this._ne=new performance$1.LngLat(ne2.lng,ne2.lat)}else{sw.lng=Math.min(sw2.lng,sw.lng);sw.lat=Math.min(sw2.lat,sw.lat);ne.lng=Math.max(ne2.lng,ne.lng);ne.lat=Math.max(ne2.lat,ne.lat)}return this}getCenter(){return new performance$1.LngLat((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new performance$1.LngLat(this.getWest(),this.getNorth())}getSouthEast(){return new performance$1.LngLat(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return[this._sw.toArray(),this._ne.toArray()]}toString(){return`LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return!(this._sw&&this._ne)}contains(lnglat){const{lng:lng,lat:lat}=performance$1.LngLat.convert(lnglat);const containsLatitude=this._sw.lat<=lat&&lat<=this._ne.lat;let containsLongitude=this._sw.lng<=lng&&lng<=this._ne.lng;if(this._sw.lng>this._ne.lng){containsLongitude=this._sw.lng>=lng&&lng>=this._ne.lng}return containsLatitude&&containsLongitude}static convert(input){if(input instanceof LngLatBounds)return input;if(!input)return input;return new LngLatBounds(input)}static fromLngLat(center,radius=0){const earthCircumferenceInMetersAtEquator=40075017;const latAccuracy=360*radius/earthCircumferenceInMetersAtEquator,lngAccuracy=latAccuracy/Math.cos(Math.PI/180*center.lat);return new LngLatBounds(new performance$1.LngLat(center.lng-lngAccuracy,center.lat-latAccuracy),new performance$1.LngLat(center.lng+lngAccuracy,center.lat+latAccuracy))}}class TileBounds{constructor(bounds,minzoom,maxzoom){this.bounds=LngLatBounds.convert(this.validateBounds(bounds));this.minzoom=minzoom||0;this.maxzoom=maxzoom||24}validateBounds(bounds){if(!Array.isArray(bounds)||bounds.length!==4)return[-180,-90,180,90];return[Math.max(-180,bounds[0]),Math.max(-90,bounds[1]),Math.min(180,bounds[2]),Math.min(90,bounds[3])]}contains(tileID){const worldSize=Math.pow(2,tileID.z);const level={minX:Math.floor(performance$1.mercatorXfromLng(this.bounds.getWest())*worldSize),minY:Math.floor(performance$1.mercatorYfromLat(this.bounds.getNorth())*worldSize),maxX:Math.ceil(performance$1.mercatorXfromLng(this.bounds.getEast())*worldSize),maxY:Math.ceil(performance$1.mercatorYfromLat(this.bounds.getSouth())*worldSize)};const hit=tileID.x>=level.minX&&tileID.x=level.minY&&tileID.y{this._options.tiles=tiles}));return this}setUrl(url){this.setSourceProperty((()=>{this.url=url;this._options.url=url}));return this}onRemove(){if(this._tileJSONRequest){this._tileJSONRequest.abort();this._tileJSONRequest=null}}serialize(){return performance$1.extend({},this._options)}loadTile(tile){return performance$1.__awaiter(this,void 0,void 0,(function*(){const url=tile.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);const params={request:this.map._requestManager.transformRequest(url,ResourceType.Tile),uid:tile.uid,tileID:tile.tileID,zoom:tile.tileID.overscaledZ,tileSize:this.tileSize*tile.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId};params.request.collectResourceTiming=this._collectResourceTiming;let messageType="reloadTile";if(!tile.actor||tile.state==="expired"){tile.actor=this.dispatcher.getActor();messageType="loadTile"}else if(tile.state==="loading"){return new Promise(((resolve,reject)=>{tile.reloadPromise={resolve:resolve,reject:reject}}))}tile.abortController=new AbortController;try{const data=yield tile.actor.sendAsync({type:messageType,data:params},tile.abortController);delete tile.abortController;if(tile.aborted){return}this._afterTileLoadWorkerResponse(tile,data)}catch(err){delete tile.abortController;if(tile.aborted){return}if(err&&err.status!==404){throw err}this._afterTileLoadWorkerResponse(tile,null)}}))}_afterTileLoadWorkerResponse(tile,data){if(data&&data.resourceTiming){tile.resourceTiming=data.resourceTiming}if(data&&this.map._refreshExpiredTiles){tile.setExpiryData(data)}tile.loadVectorData(data,this.map.painter);if(tile.reloadPromise){const reloadPromise=tile.reloadPromise;tile.reloadPromise=null;this.loadTile(tile).then(reloadPromise.resolve).catch(reloadPromise.reject)}}abortTile(tile){return performance$1.__awaiter(this,void 0,void 0,(function*(){if(tile.abortController){tile.abortController.abort();delete tile.abortController}if(tile.actor){yield tile.actor.sendAsync({type:"abortTile",data:{uid:tile.uid,type:this.type,source:this.id}})}}))}unloadTile(tile){return performance$1.__awaiter(this,void 0,void 0,(function*(){tile.unloadVectorData();if(tile.actor){yield tile.actor.sendAsync({type:"removeTile",data:{uid:tile.uid,type:this.type,source:this.id}})}}))}hasTransition(){return false}}class RasterTileSource extends performance$1.Evented{constructor(id,options,dispatcher,eventedParent){super();this.id=id;this.dispatcher=dispatcher;this.setEventedParent(eventedParent);this.type="raster";this.minzoom=0;this.maxzoom=22;this.roundZoom=true;this.scheme="xyz";this.tileSize=512;this._loaded=false;this._options=performance$1.extend({type:"raster"},options);performance$1.extend(this,performance$1.pick(options,["url","scheme","tileSize"]))}load(){return performance$1.__awaiter(this,void 0,void 0,(function*(){this._loaded=false;this.fire(new performance$1.Event("dataloading",{dataType:"source"}));this._tileJSONRequest=new AbortController;try{const tileJSON=yield loadTileJson(this._options,this.map._requestManager,this._tileJSONRequest);this._tileJSONRequest=null;this._loaded=true;if(tileJSON){performance$1.extend(this,tileJSON);if(tileJSON.bounds)this.tileBounds=new TileBounds(tileJSON.bounds,this.minzoom,this.maxzoom);this.fire(new performance$1.Event("data",{dataType:"source",sourceDataType:"metadata"}));this.fire(new performance$1.Event("data",{dataType:"source",sourceDataType:"content"}))}}catch(err){this._tileJSONRequest=null;this.fire(new performance$1.ErrorEvent(err))}}))}loaded(){return this._loaded}onAdd(map){this.map=map;this.load()}onRemove(){if(this._tileJSONRequest){this._tileJSONRequest.abort();this._tileJSONRequest=null}}setSourceProperty(callback){if(this._tileJSONRequest){this._tileJSONRequest.abort();this._tileJSONRequest=null}callback();this.load()}setTiles(tiles){this.setSourceProperty((()=>{this._options.tiles=tiles}));return this}setUrl(url){this.setSourceProperty((()=>{this.url=url;this._options.url=url}));return this}serialize(){return performance$1.extend({},this._options)}hasTile(tileID){return!this.tileBounds||this.tileBounds.contains(tileID.canonical)}loadTile(tile){return performance$1.__awaiter(this,void 0,void 0,(function*(){const url=tile.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);tile.abortController=new AbortController;try{const response=yield ImageRequest.getImage(this.map._requestManager.transformRequest(url,ResourceType.Tile),tile.abortController,this.map._refreshExpiredTiles);delete tile.abortController;if(tile.aborted){tile.state="unloaded";return}if(response&&response.data){if(this.map._refreshExpiredTiles&&response.cacheControl&&response.expires){tile.setExpiryData({cacheControl:response.cacheControl,expires:response.expires})}const context=this.map.painter.context;const gl=context.gl;const img=response.data;tile.texture=this.map.painter.getTileTexture(img.width);if(tile.texture){tile.texture.update(img,{useMipmap:true})}else{tile.texture=new Texture(context,img,gl.RGBA,{useMipmap:true});tile.texture.bind(gl.LINEAR,gl.CLAMP_TO_EDGE,gl.LINEAR_MIPMAP_NEAREST);if(context.extTextureFilterAnisotropic){gl.texParameterf(gl.TEXTURE_2D,context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,context.extTextureFilterAnisotropicMax)}}tile.state="loaded"}}catch(err){delete tile.abortController;if(tile.aborted){tile.state="unloaded"}else if(err){tile.state="errored";throw err}}}))}abortTile(tile){return performance$1.__awaiter(this,void 0,void 0,(function*(){if(tile.abortController){tile.abortController.abort();delete tile.abortController}}))}unloadTile(tile){return performance$1.__awaiter(this,void 0,void 0,(function*(){if(tile.texture){this.map.painter.saveTileTexture(tile.texture)}}))}hasTransition(){return false}}class RasterDEMTileSource extends RasterTileSource{constructor(id,options,dispatcher,eventedParent){super(id,options,dispatcher,eventedParent);this.type="raster-dem";this.maxzoom=22;this._options=performance$1.extend({type:"raster-dem"},options);this.encoding=options.encoding||"mapbox";this.redFactor=options.redFactor;this.greenFactor=options.greenFactor;this.blueFactor=options.blueFactor;this.baseShift=options.baseShift}loadTile(tile){return performance$1.__awaiter(this,void 0,void 0,(function*(){const url=tile.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);const request=this.map._requestManager.transformRequest(url,ResourceType.Tile);tile.neighboringTiles=this._getNeighboringTiles(tile.tileID);tile.abortController=new AbortController;try{const response=yield ImageRequest.getImage(request,tile.abortController,this.map._refreshExpiredTiles);delete tile.abortController;if(tile.aborted){tile.state="unloaded";return}if(response&&response.data){const img=response.data;if(this.map._refreshExpiredTiles&&response.cacheControl&&response.expires){tile.setExpiryData({cacheControl:response.cacheControl,expires:response.expires})}const transfer=performance$1.isImageBitmap(img)&&performance$1.offscreenCanvasSupported();const rawImageData=transfer?img:yield this.readImageNow(img);const params={type:this.type,uid:tile.uid,source:this.id,rawImageData:rawImageData,encoding:this.encoding,redFactor:this.redFactor,greenFactor:this.greenFactor,blueFactor:this.blueFactor,baseShift:this.baseShift};if(!tile.actor||tile.state==="expired"){tile.actor=this.dispatcher.getActor();const data=yield tile.actor.sendAsync({type:"loadDEMTile",data:params});tile.dem=data;tile.needsHillshadePrepare=true;tile.needsTerrainPrepare=true;tile.state="loaded"}}}catch(err){delete tile.abortController;if(tile.aborted){tile.state="unloaded"}else if(err){tile.state="errored";throw err}}}))}readImageNow(img){return performance$1.__awaiter(this,void 0,void 0,(function*(){if(typeof VideoFrame!=="undefined"&&performance$1.isOffscreenCanvasDistorted()){const width=img.width+2;const height=img.height+2;try{return new performance$1.RGBAImage({width:width,height:height},yield performance$1.readImageUsingVideoFrame(img,-1,-1,width,height))}catch(e){}}return browser.getImageData(img,1)}))}_getNeighboringTiles(tileID){const canonical=tileID.canonical;const dim=Math.pow(2,canonical.z);const px=(canonical.x-1+dim)%dim;const pxw=canonical.x===0?tileID.wrap-1:tileID.wrap;const nx=(canonical.x+1+dim)%dim;const nxw=canonical.x+1===dim?tileID.wrap+1:tileID.wrap;const neighboringTiles={};neighboringTiles[new performance$1.OverscaledTileID(tileID.overscaledZ,pxw,canonical.z,px,canonical.y).key]={backfilled:false};neighboringTiles[new performance$1.OverscaledTileID(tileID.overscaledZ,nxw,canonical.z,nx,canonical.y).key]={backfilled:false};if(canonical.y>0){neighboringTiles[new performance$1.OverscaledTileID(tileID.overscaledZ,pxw,canonical.z,px,canonical.y-1).key]={backfilled:false};neighboringTiles[new performance$1.OverscaledTileID(tileID.overscaledZ,tileID.wrap,canonical.z,canonical.x,canonical.y-1).key]={backfilled:false};neighboringTiles[new performance$1.OverscaledTileID(tileID.overscaledZ,nxw,canonical.z,nx,canonical.y-1).key]={backfilled:false}}if(canonical.y+10){performance$1.extend(data,{resourceTiming:resourceTiming})}this.fire(new performance$1.Event("data",Object.assign(Object.assign({},data),{sourceDataType:"metadata"})));this.fire(new performance$1.Event("data",Object.assign(Object.assign({},data),{sourceDataType:"content"})))}catch(err){this._pendingLoads--;if(this._removed){this.fire(new performance$1.Event("dataabort",{dataType:"source"}));return}this.fire(new performance$1.ErrorEvent(err))}}))}loaded(){return this._pendingLoads===0}loadTile(tile){return performance$1.__awaiter(this,void 0,void 0,(function*(){const message=!tile.actor?"loadTile":"reloadTile";tile.actor=this.actor;const params={type:this.type,uid:tile.uid,tileID:tile.tileID,zoom:tile.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId};tile.abortController=new AbortController;const data=yield this.actor.sendAsync({type:message,data:params},tile.abortController);delete tile.abortController;tile.unloadVectorData();if(!tile.aborted){tile.loadVectorData(data,this.map.painter,message==="reloadTile")}}))}abortTile(tile){return performance$1.__awaiter(this,void 0,void 0,(function*(){if(tile.abortController){tile.abortController.abort();delete tile.abortController}tile.aborted=true}))}unloadTile(tile){return performance$1.__awaiter(this,void 0,void 0,(function*(){tile.unloadVectorData();yield this.actor.sendAsync({type:"removeTile",data:{uid:tile.uid,type:this.type,source:this.id}})}))}onRemove(){this._removed=true;this.actor.sendAsync({type:"removeSource",data:{type:this.type,source:this.id}})}serialize(){return performance$1.extend({},this._options,{type:this.type,data:this._data})}hasTransition(){return false}}var rasterBoundsAttributes=performance$1.createLayout([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]);class ImageSource extends performance$1.Evented{constructor(id,options,dispatcher,eventedParent){super();this.id=id;this.dispatcher=dispatcher;this.coordinates=options.coordinates;this.type="image";this.minzoom=0;this.maxzoom=22;this.tileSize=512;this.tiles={};this._loaded=false;this.setEventedParent(eventedParent);this.options=options}load(newCoordinates){return performance$1.__awaiter(this,void 0,void 0,(function*(){this._loaded=false;this.fire(new performance$1.Event("dataloading",{dataType:"source"}));this.url=this.options.url;this._request=new AbortController;try{const image=yield ImageRequest.getImage(this.map._requestManager.transformRequest(this.url,ResourceType.Image),this._request);this._request=null;this._loaded=true;if(image&&image.data){this.image=image.data;if(newCoordinates){this.coordinates=newCoordinates}this._finishLoading()}}catch(err){this._request=null;this.fire(new performance$1.ErrorEvent(err))}}))}loaded(){return this._loaded}updateImage(options){if(!options.url){return this}if(this._request){this._request.abort();this._request=null}this.options.url=options.url;this.load(options.coordinates).finally((()=>{this.texture=null}));return this}_finishLoading(){if(this.map){this.setCoordinates(this.coordinates);this.fire(new performance$1.Event("data",{dataType:"source",sourceDataType:"metadata"}))}}onAdd(map){this.map=map;this.load()}onRemove(){if(this._request){this._request.abort();this._request=null}}setCoordinates(coordinates){this.coordinates=coordinates;const cornerCoords=coordinates.map(performance$1.MercatorCoordinate.fromLngLat);this.tileID=getCoordinatesCenterTileID(cornerCoords);this.minzoom=this.maxzoom=this.tileID.z;const tileCoords=cornerCoords.map((coord=>this.tileID.getTilePoint(coord)._round()));this._boundsArray=new performance$1.RasterBoundsArray;this._boundsArray.emplaceBack(tileCoords[0].x,tileCoords[0].y,0,0);this._boundsArray.emplaceBack(tileCoords[1].x,tileCoords[1].y,performance$1.EXTENT,0);this._boundsArray.emplaceBack(tileCoords[3].x,tileCoords[3].y,0,performance$1.EXTENT);this._boundsArray.emplaceBack(tileCoords[2].x,tileCoords[2].y,performance$1.EXTENT,performance$1.EXTENT);if(this.boundsBuffer){this.boundsBuffer.destroy();delete this.boundsBuffer}this.fire(new performance$1.Event("data",{dataType:"source",sourceDataType:"content"}));return this}prepare(){if(Object.keys(this.tiles).length===0||!this.image){return}const context=this.map.painter.context;const gl=context.gl;if(!this.boundsBuffer){this.boundsBuffer=context.createVertexBuffer(this._boundsArray,rasterBoundsAttributes.members)}if(!this.boundsSegments){this.boundsSegments=performance$1.SegmentVector.simpleSegment(0,0,4,2)}if(!this.texture){this.texture=new Texture(context,this.image,gl.RGBA);this.texture.bind(gl.LINEAR,gl.CLAMP_TO_EDGE)}let newTilesLoaded=false;for(const w in this.tiles){const tile=this.tiles[w];if(tile.state!=="loaded"){tile.state="loaded";tile.texture=this.texture;newTilesLoaded=true}}if(newTilesLoaded){this.fire(new performance$1.Event("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}))}}loadTile(tile){return performance$1.__awaiter(this,void 0,void 0,(function*(){if(this.tileID&&this.tileID.equals(tile.tileID.canonical)){this.tiles[String(tile.tileID.wrap)]=tile;tile.buckets={}}else{tile.state="errored"}}))}serialize(){return{type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return false}}function getCoordinatesCenterTileID(coords){let minX=Infinity;let minY=Infinity;let maxX=-Infinity;let maxY=-Infinity;for(const coord of coords){minX=Math.min(minX,coord.x);minY=Math.min(minY,coord.y);maxX=Math.max(maxX,coord.x);maxY=Math.max(maxY,coord.y)}const dx=maxX-minX;const dy=maxY-minY;const dMax=Math.max(dx,dy);const zoom=Math.max(0,Math.floor(-Math.log(dMax)/Math.LN2));const tilesAtZoom=Math.pow(2,zoom);return new performance$1.CanonicalTileID(zoom,Math.floor((minX+maxX)/2*tilesAtZoom),Math.floor((minY+maxY)/2*tilesAtZoom))}class VideoSource extends ImageSource{constructor(id,options,dispatcher,eventedParent){super(id,options,dispatcher,eventedParent);this.roundZoom=true;this.type="video";this.options=options}load(){return performance$1.__awaiter(this,void 0,void 0,(function*(){this._loaded=false;const options=this.options;this.urls=[];for(const url of options.urls){this.urls.push(this.map._requestManager.transformRequest(url,ResourceType.Source).url)}try{const video=yield performance$1.getVideo(this.urls);this._loaded=true;if(!video){return}this.video=video;this.video.loop=true;this.video.addEventListener("playing",(()=>{this.map.triggerRepaint()}));if(this.map){this.video.play()}this._finishLoading()}catch(err){this.fire(new performance$1.ErrorEvent(err))}}))}pause(){if(this.video){this.video.pause()}}play(){if(this.video){this.video.play()}}seek(seconds){if(this.video){const seekableRange=this.video.seekable;if(secondsseekableRange.end(0)){this.fire(new performance$1.ErrorEvent(new performance$1.ValidationError(`sources.${this.id}`,null,`Playback for this video can be set only between the ${seekableRange.start(0)} and ${seekableRange.end(0)}-second mark.`)))}else this.video.currentTime=seconds}}getVideo(){return this.video}onAdd(map){if(this.map)return;this.map=map;this.load();if(this.video){this.video.play();this.setCoordinates(this.coordinates)}}prepare(){if(Object.keys(this.tiles).length===0||this.video.readyState<2){return}const context=this.map.painter.context;const gl=context.gl;if(!this.boundsBuffer){this.boundsBuffer=context.createVertexBuffer(this._boundsArray,rasterBoundsAttributes.members)}if(!this.boundsSegments){this.boundsSegments=performance$1.SegmentVector.simpleSegment(0,0,4,2)}if(!this.texture){this.texture=new Texture(context,this.video,gl.RGBA);this.texture.bind(gl.LINEAR,gl.CLAMP_TO_EDGE)}else if(!this.video.paused){this.texture.bind(gl.LINEAR,gl.CLAMP_TO_EDGE);gl.texSubImage2D(gl.TEXTURE_2D,0,0,0,gl.RGBA,gl.UNSIGNED_BYTE,this.video)}let newTilesLoaded=false;for(const w in this.tiles){const tile=this.tiles[w];if(tile.state!=="loaded"){tile.state="loaded";tile.texture=this.texture;newTilesLoaded=true}}if(newTilesLoaded){this.fire(new performance$1.Event("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}))}}serialize(){return{type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}}class CanvasSource extends ImageSource{constructor(id,options,dispatcher,eventedParent){super(id,options,dispatcher,eventedParent);if(!options.coordinates){this.fire(new performance$1.ErrorEvent(new performance$1.ValidationError(`sources.${id}`,null,'missing required property "coordinates"')))}else if(!Array.isArray(options.coordinates)||options.coordinates.length!==4||options.coordinates.some((c=>!Array.isArray(c)||c.length!==2||c.some((l=>typeof l!=="number"))))){this.fire(new performance$1.ErrorEvent(new performance$1.ValidationError(`sources.${id}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs')))}if(options.animate&&typeof options.animate!=="boolean"){this.fire(new performance$1.ErrorEvent(new performance$1.ValidationError(`sources.${id}`,null,'optional "animate" property must be a boolean value')))}if(!options.canvas){this.fire(new performance$1.ErrorEvent(new performance$1.ValidationError(`sources.${id}`,null,'missing required property "canvas"')))}else if(typeof options.canvas!=="string"&&!(options.canvas instanceof HTMLCanvasElement)){this.fire(new performance$1.ErrorEvent(new performance$1.ValidationError(`sources.${id}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance')))}this.options=options;this.animate=options.animate!==undefined?options.animate:true}load(){return performance$1.__awaiter(this,void 0,void 0,(function*(){this._loaded=true;if(!this.canvas){this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)}this.width=this.canvas.width;this.height=this.canvas.height;if(this._hasInvalidDimensions()){this.fire(new performance$1.ErrorEvent(new Error("Canvas dimensions cannot be less than or equal to zero.")));return}this.play=function(){this._playing=true;this.map.triggerRepaint()};this.pause=function(){if(this._playing){this.prepare();this._playing=false}};this._finishLoading()}))}getCanvas(){return this.canvas}onAdd(map){this.map=map;this.load();if(this.canvas){if(this.animate)this.play()}}onRemove(){this.pause()}prepare(){let resize=false;if(this.canvas.width!==this.width){this.width=this.canvas.width;resize=true}if(this.canvas.height!==this.height){this.height=this.canvas.height;resize=true}if(this._hasInvalidDimensions())return;if(Object.keys(this.tiles).length===0)return;const context=this.map.painter.context;const gl=context.gl;if(!this.boundsBuffer){this.boundsBuffer=context.createVertexBuffer(this._boundsArray,rasterBoundsAttributes.members)}if(!this.boundsSegments){this.boundsSegments=performance$1.SegmentVector.simpleSegment(0,0,4,2)}if(!this.texture){this.texture=new Texture(context,this.canvas,gl.RGBA,{premultiply:true})}else if(resize||this._playing){this.texture.update(this.canvas,{premultiply:true})}let newTilesLoaded=false;for(const w in this.tiles){const tile=this.tiles[w];if(tile.state!=="loaded"){tile.state="loaded";tile.texture=this.texture;newTilesLoaded=true}}if(newTilesLoaded){this.fire(new performance$1.Event("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}))}}serialize(){return{type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const x of[this.canvas.width,this.canvas.height]){if(isNaN(x)||x<=0)return true}return false}}const registeredSources={};const create=(id,specification,dispatcher,eventedParent)=>{const Class=getSourceType(specification.type);const source=new Class(id,specification,dispatcher,eventedParent);if(source.id!==id){throw new Error(`Expected Source id to be ${id} instead of ${source.id}`)}return source};const getSourceType=name=>{switch(name){case"geojson":return GeoJSONSource;case"image":return ImageSource;case"raster":return RasterTileSource;case"raster-dem":return RasterDEMTileSource;case"vector":return VectorTileSource;case"video":return VideoSource;case"canvas":return CanvasSource}return registeredSources[name]};const setSourceType=(name,type)=>{registeredSources[name]=type};const addSourceType=(name,SourceType)=>performance$1.__awaiter(void 0,void 0,void 0,(function*(){if(getSourceType(name)){throw new Error(`A source type called "${name}" already exists.`)}setSourceType(name,SourceType)}));function deserialize(input,style){const output={};if(!style)return output;for(const bucket of input){const layers=bucket.layerIds.map((id=>style.getLayer(id))).filter(Boolean);if(layers.length===0){continue}bucket.layers=layers;if(bucket.stateDependentLayerIds){bucket.stateDependentLayers=bucket.stateDependentLayerIds.map((lId=>layers.filter((l=>l.id===lId))[0]))}for(const layer of layers){output[layer.id]=bucket}}return output}class RTLMainThreadPlugin extends performance$1.Evented{constructor(){super(...arguments);this.pluginStatus="unavailable";this.pluginURL=null;this.dispatcher=getGlobalDispatcher();this.queue=[]}_sendPluginStateToWorker(){return performance$1.__awaiter(this,void 0,void 0,(function*(){yield this.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:this.pluginStatus,pluginURL:this.pluginURL});this.fire(new performance$1.Event("pluginStateChange",{pluginStatus:this.pluginStatus,pluginURL:this.pluginURL}))}))}getRTLTextPluginStatus(){return this.pluginStatus}clearRTLTextPlugin(){this.pluginStatus="unavailable";this.pluginURL=null}setRTLTextPlugin(url,deferred=false){return performance$1.__awaiter(this,void 0,void 0,(function*(){if(this.pluginStatus==="deferred"||this.pluginStatus==="loading"||this.pluginStatus==="loaded"){throw new Error("setRTLTextPlugin cannot be called multiple times.")}this.pluginURL=browser.resolveURL(url);this.pluginStatus="deferred";yield this._sendPluginStateToWorker();if(!deferred){yield this._downloadRTLTextPlugin()}}))}_downloadRTLTextPlugin(){return performance$1.__awaiter(this,void 0,void 0,(function*(){if(this.pluginStatus!=="deferred"||!this.pluginURL){throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified")}try{this.pluginStatus="loading";yield this._sendPluginStateToWorker();yield performance$1.getArrayBuffer({url:this.pluginURL},new AbortController);this.pluginStatus="loaded"}catch(_a){this.pluginStatus="error"}yield this._sendPluginStateToWorker()}))}lazyLoadRTLTextPlugin(){return performance$1.__awaiter(this,void 0,void 0,(function*(){if(this.pluginStatus==="deferred"){yield this._downloadRTLTextPlugin()}}))}}let rtlMainThreadPlugin=null;function rtlMainThreadPluginFactory(){if(!rtlMainThreadPlugin){rtlMainThreadPlugin=new RTLMainThreadPlugin}return rtlMainThreadPlugin}const CLOCK_SKEW_RETRY_TIMEOUT=3e4;class Tile{constructor(tileID,size){this.timeAdded=0;this.fadeEndTime=0;this.tileID=tileID;this.uid=performance$1.uniqueId();this.uses=0;this.tileSize=size;this.buckets={};this.expirationTime=null;this.queryPadding=0;this.hasSymbolBuckets=false;this.hasRTLText=false;this.dependencies={};this.rtt=[];this.rttCoords={};this.expiredRequestCount=0;this.state="loading"}registerFadeDuration(duration){const fadeEndTime=duration+this.timeAdded;if(fadeEndTimenow){isExpired=false}else if(!prior){isExpired=true}else if(this.expirationTime{this.remove(tileID,dataWrapper)}),expiryTimeout)}this.data[key].push(dataWrapper);this.order.push(key);if(this.order.length>this.max){const removedData=this._getAndRemoveByKey(this.order[0]);if(removedData)this.onRemove(removedData)}return this}has(tileID){return tileID.wrapped().key in this.data}getAndRemove(tileID){if(!this.has(tileID)){return null}return this._getAndRemoveByKey(tileID.wrapped().key)}_getAndRemoveByKey(key){const data=this.data[key].shift();if(data.timeout)clearTimeout(data.timeout);if(this.data[key].length===0){delete this.data[key]}this.order.splice(this.order.indexOf(key),1);return data.value}getByKey(key){const data=this.data[key];return data?data[0].value:null}get(tileID){if(!this.has(tileID)){return null}const data=this.data[tileID.wrapped().key][0];return data.value}remove(tileID,value){if(!this.has(tileID)){return this}const key=tileID.wrapped().key;const dataIndex=value===undefined?0:this.data[key].indexOf(value);const data=this.data[key][dataIndex];this.data[key].splice(dataIndex,1);if(data.timeout)clearTimeout(data.timeout);if(this.data[key].length===0){delete this.data[key]}this.onRemove(data.value);this.order.splice(this.order.indexOf(key),1);return this}setMaxSize(max){this.max=max;while(this.order.length>this.max){const removedData=this._getAndRemoveByKey(this.order[0]);if(removedData)this.onRemove(removedData)}return this}filter(filterFn){const removed=[];for(const key in this.data){for(const entry of this.data[key]){if(!filterFn(entry.value)){removed.push(entry)}}}for(const r of removed){this.remove(r.value.tileID,r)}}}class SourceFeatureState{constructor(){this.state={};this.stateChanges={};this.deletedStates={}}updateState(sourceLayer,featureId,newState){const feature=String(featureId);this.stateChanges[sourceLayer]=this.stateChanges[sourceLayer]||{};this.stateChanges[sourceLayer][feature]=this.stateChanges[sourceLayer][feature]||{};performance$1.extend(this.stateChanges[sourceLayer][feature],newState);if(this.deletedStates[sourceLayer]===null){this.deletedStates[sourceLayer]={};for(const ft in this.state[sourceLayer]){if(ft!==feature)this.deletedStates[sourceLayer][ft]=null}}else{const featureDeletionQueued=this.deletedStates[sourceLayer]&&this.deletedStates[sourceLayer][feature]===null;if(featureDeletionQueued){this.deletedStates[sourceLayer][feature]={};for(const prop in this.state[sourceLayer][feature]){if(!newState[prop])this.deletedStates[sourceLayer][feature][prop]=null}}else{for(const key in newState){const deletionInQueue=this.deletedStates[sourceLayer]&&this.deletedStates[sourceLayer][feature]&&this.deletedStates[sourceLayer][feature][key]===null;if(deletionInQueue)delete this.deletedStates[sourceLayer][feature][key]}}}}removeFeatureState(sourceLayer,featureId,key){const sourceLayerDeleted=this.deletedStates[sourceLayer]===null;if(sourceLayerDeleted)return;const feature=String(featureId);this.deletedStates[sourceLayer]=this.deletedStates[sourceLayer]||{};if(key&&featureId!==undefined){if(this.deletedStates[sourceLayer][feature]!==null){this.deletedStates[sourceLayer][feature]=this.deletedStates[sourceLayer][feature]||{};this.deletedStates[sourceLayer][feature][key]=null}}else if(featureId!==undefined){const updateInQueue=this.stateChanges[sourceLayer]&&this.stateChanges[sourceLayer][feature];if(updateInQueue){this.deletedStates[sourceLayer][feature]={};for(key in this.stateChanges[sourceLayer][feature])this.deletedStates[sourceLayer][feature][key]=null}else{this.deletedStates[sourceLayer][feature]=null}}else{this.deletedStates[sourceLayer]=null}}getState(sourceLayer,featureId){const feature=String(featureId);const base=this.state[sourceLayer]||{};const changes=this.stateChanges[sourceLayer]||{};const reconciledState=performance$1.extend({},base[feature],changes[feature]);if(this.deletedStates[sourceLayer]===null)return{};else if(this.deletedStates[sourceLayer]){const featureDeletions=this.deletedStates[sourceLayer][featureId];if(featureDeletions===null)return{};for(const prop in featureDeletions)delete reconciledState[prop]}return reconciledState}initializeTileState(tile,painter){tile.setFeatureState(this.state,painter)}coalesceChanges(tiles,painter){const featuresChanged={};for(const sourceLayer in this.stateChanges){this.state[sourceLayer]=this.state[sourceLayer]||{};const layerStates={};for(const feature in this.stateChanges[sourceLayer]){if(!this.state[sourceLayer][feature])this.state[sourceLayer][feature]={};performance$1.extend(this.state[sourceLayer][feature],this.stateChanges[sourceLayer][feature]);layerStates[feature]=this.state[sourceLayer][feature]}featuresChanged[sourceLayer]=layerStates}for(const sourceLayer in this.deletedStates){this.state[sourceLayer]=this.state[sourceLayer]||{};const layerStates={};if(this.deletedStates[sourceLayer]===null){for(const ft in this.state[sourceLayer]){layerStates[ft]={};this.state[sourceLayer][ft]={}}}else{for(const feature in this.deletedStates[sourceLayer]){const deleteWholeFeatureState=this.deletedStates[sourceLayer][feature]===null;if(deleteWholeFeatureState)this.state[sourceLayer][feature]={};else{for(const key of Object.keys(this.deletedStates[sourceLayer][feature])){delete this.state[sourceLayer][feature][key]}}layerStates[feature]=this.state[sourceLayer][feature]}}featuresChanged[sourceLayer]=featuresChanged[sourceLayer]||{};performance$1.extend(featuresChanged[sourceLayer],layerStates)}this.stateChanges={};this.deletedStates={};if(Object.keys(featuresChanged).length===0)return;for(const id in tiles){const tile=tiles[id];tile.setFeatureState(featuresChanged,painter)}}}class SourceCache extends performance$1.Evented{constructor(id,options,dispatcher){super();this.id=id;this.dispatcher=dispatcher;this.on("data",(e=>{if(e.dataType==="source"&&e.sourceDataType==="metadata")this._sourceLoaded=true;if(this._sourceLoaded&&!this._paused&&e.dataType==="source"&&e.sourceDataType==="content"){this.reload();if(this.transform){this.update(this.transform,this.terrain)}this._didEmitContent=true}}));this.on("dataloading",(()=>{this._sourceErrored=false}));this.on("error",(()=>{this._sourceErrored=this._source.loaded()}));this._source=create(id,options,dispatcher,this);this._tiles={};this._cache=new TileCache(0,(tile=>this._unloadTile(tile)));this._timers={};this._cacheTimers={};this._maxTileCacheSize=null;this._maxTileCacheZoomLevels=null;this._loadedParentTiles={};this._coveredTiles={};this._state=new SourceFeatureState;this._didEmitContent=false;this._updated=false}onAdd(map){this.map=map;this._maxTileCacheSize=map?map._maxTileCacheSize:null;this._maxTileCacheZoomLevels=map?map._maxTileCacheZoomLevels:null;if(this._source&&this._source.onAdd){this._source.onAdd(map)}}onRemove(map){this.clearTiles();if(this._source&&this._source.onRemove){this._source.onRemove(map)}}loaded(){if(this._sourceErrored){return true}if(!this._sourceLoaded){return false}if(!this._source.loaded()){return false}if((this.used!==undefined||this.usedForTerrain!==undefined)&&!this.used&&!this.usedForTerrain){return true}if(!this._updated){return false}for(const t in this._tiles){const tile=this._tiles[t];if(tile.state!=="loaded"&&tile.state!=="errored")return false}return true}getSource(){return this._source}pause(){this._paused=true}resume(){if(!this._paused)return;const shouldReload=this._shouldReloadOnResume;this._paused=false;this._shouldReloadOnResume=false;if(shouldReload)this.reload();if(this.transform)this.update(this.transform,this.terrain)}_loadTile(tile,id,state){return performance$1.__awaiter(this,void 0,void 0,(function*(){try{yield this._source.loadTile(tile);this._tileLoaded(tile,id,state)}catch(err){tile.state="errored";if(err.status!==404){this._source.fire(new performance$1.ErrorEvent(err,{tile:tile}))}else{this.update(this.transform,this.terrain)}}}))}_unloadTile(tile){if(this._source.unloadTile)this._source.unloadTile(tile)}_abortTile(tile){if(this._source.abortTile)this._source.abortTile(tile);this._source.fire(new performance$1.Event("dataabort",{tile:tile,coord:tile.tileID,dataType:"source"}))}serialize(){return this._source.serialize()}prepare(context){if(this._source.prepare){this._source.prepare()}this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const i in this._tiles){const tile=this._tiles[i];tile.upload(context);tile.prepare(this.map.style.imageManager)}}getIds(){return Object.values(this._tiles).map((tile=>tile.tileID)).sort(compareTileId).map((id=>id.key))}getRenderableIds(symbolLayer){const renderables=[];for(const id in this._tiles){if(this._isIdRenderable(id,symbolLayer))renderables.push(this._tiles[id])}if(symbolLayer){return renderables.sort(((a_,b_)=>{const a=a_.tileID;const b=b_.tileID;const rotatedA=new performance$1.Point(a.canonical.x,a.canonical.y)._rotate(this.transform.angle);const rotatedB=new performance$1.Point(b.canonical.x,b.canonical.y)._rotate(this.transform.angle);return a.overscaledZ-b.overscaledZ||rotatedB.y-rotatedA.y||rotatedB.x-rotatedA.x})).map((tile=>tile.tileID.key))}return renderables.map((tile=>tile.tileID)).sort(compareTileId).map((id=>id.key))}hasRenderableParent(tileID){const parentTile=this.findLoadedParent(tileID,0);if(parentTile){return this._isIdRenderable(parentTile.tileID.key)}return false}_isIdRenderable(id,symbolLayer){return this._tiles[id]&&this._tiles[id].hasData()&&!this._coveredTiles[id]&&(symbolLayer||!this._tiles[id].holdingForFade())}reload(){if(this._paused){this._shouldReloadOnResume=true;return}this._cache.reset();for(const i in this._tiles){if(this._tiles[i].state!=="errored")this._reloadTile(i,"reloading")}}_reloadTile(id,state){return performance$1.__awaiter(this,void 0,void 0,(function*(){const tile=this._tiles[id];if(!tile)return;if(tile.state!=="loading"){tile.state=state}yield this._loadTile(tile,id,state)}))}_tileLoaded(tile,id,previousState){tile.timeAdded=browser.now();if(previousState==="expired")tile.refreshedUponExpiration=true;this._setTileReloadTimer(id,tile);if(this.getSource().type==="raster-dem"&&tile.dem)this._backfillDEM(tile);this._state.initializeTileState(tile,this.map?this.map.painter:null);if(!tile.aborted){this._source.fire(new performance$1.Event("data",{dataType:"source",tile:tile,coord:tile.tileID}))}}_backfillDEM(tile){const renderables=this.getRenderableIds();for(let i=0;i1){return}if(Math.abs(dx)>1){if(Math.abs(dx+dim)===1){dx+=dim}else if(Math.abs(dx-dim)===1){dx-=dim}}if(!borderTile.dem||!tile.dem)return;tile.dem.backfillBorder(borderTile.dem,dx,dy);if(tile.neighboringTiles&&tile.neighboringTiles[borderId])tile.neighboringTiles[borderId].backfilled=true}}getTile(tileID){return this.getTileByID(tileID.key)}getTileByID(id){return this._tiles[id]}_retainLoadedChildren(idealTiles,zoom,maxCoveringZoom,retain){for(const id in this._tiles){let tile=this._tiles[id];if(retain[id]||!tile.hasData()||tile.tileID.overscaledZ<=zoom||tile.tileID.overscaledZ>maxCoveringZoom)continue;let topmostLoadedID=tile.tileID;while(tile&&tile.tileID.overscaledZ>zoom+1){const parentID=tile.tileID.scaledTo(tile.tileID.overscaledZ-1);tile=this._tiles[parentID.key];if(tile&&tile.hasData()){topmostLoadedID=parentID}}let tileID=topmostLoadedID;while(tileID.overscaledZ>zoom){tileID=tileID.scaledTo(tileID.overscaledZ-1);if(idealTiles[tileID.key]){retain[topmostLoadedID.key]=topmostLoadedID;break}}}}findLoadedParent(tileID,minCoveringZoom){if(tileID.key in this._loadedParentTiles){const parent=this._loadedParentTiles[tileID.key];if(parent&&parent.tileID.overscaledZ>=minCoveringZoom){return parent}else{return null}}for(let z=tileID.overscaledZ-1;z>=minCoveringZoom;z--){const parentTileID=tileID.scaledTo(z);const tile=this._getLoadedTile(parentTileID);if(tile){return tile}}}_getLoadedTile(tileID){const tile=this._tiles[tileID.key];if(tile&&tile.hasData()){return tile}const cachedTile=this._cache.getByKey(tileID.wrapped().key);return cachedTile}updateCacheSize(transform){const widthInTiles=Math.ceil(transform.width/this._source.tileSize)+1;const heightInTiles=Math.ceil(transform.height/this._source.tileSize)+1;const approxTilesInView=widthInTiles*heightInTiles;const commonZoomRange=this._maxTileCacheZoomLevels===null?performance$1.config.MAX_TILE_CACHE_ZOOM_LEVELS:this._maxTileCacheZoomLevels;const viewDependentMaxSize=Math.floor(approxTilesInView*commonZoomRange);const maxSize=typeof this._maxTileCacheSize==="number"?Math.min(this._maxTileCacheSize,viewDependentMaxSize):viewDependentMaxSize;this._cache.setMaxSize(maxSize)}handleWrapJump(lng){const prevLng=this._prevLng===undefined?lng:this._prevLng;const lngDifference=lng-prevLng;const worldDifference=lngDifference/360;const wrapDelta=Math.round(worldDifference);this._prevLng=lng;if(wrapDelta){const tiles={};for(const key in this._tiles){const tile=this._tiles[key];tile.tileID=tile.tileID.unwrapTo(tile.tileID.wrap+wrapDelta);tiles[tile.tileID.key]=tile}this._tiles=tiles;for(const id in this._timers){clearTimeout(this._timers[id]);delete this._timers[id]}for(const id in this._tiles){const tile=this._tiles[id];this._setTileReloadTimer(id,tile)}}}update(transform,terrain){this.transform=transform;this.terrain=terrain;if(!this._sourceLoaded||this._paused){return}this.updateCacheSize(transform);this.handleWrapJump(this.transform.center.lng);this._coveredTiles={};let idealTileIDs;if(!this.used&&!this.usedForTerrain){idealTileIDs=[]}else if(this._source.tileID){idealTileIDs=transform.getVisibleUnwrappedCoordinates(this._source.tileID).map((unwrapped=>new performance$1.OverscaledTileID(unwrapped.canonical.z,unwrapped.wrap,unwrapped.canonical.z,unwrapped.canonical.x,unwrapped.canonical.y)))}else{idealTileIDs=transform.coveringTiles({tileSize:this.usedForTerrain?this.tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this.usedForTerrain?false:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled,terrain:terrain});if(this._source.hasTile){idealTileIDs=idealTileIDs.filter((coord=>this._source.hasTile(coord)))}}const zoom=transform.coveringZoomLevel(this._source);const minCoveringZoom=Math.max(zoom-SourceCache.maxOverzooming,this._source.minzoom);const maxCoveringZoom=Math.max(zoom+SourceCache.maxUnderzooming,this._source.minzoom);if(this.usedForTerrain){const parents={};for(const tileID of idealTileIDs){if(tileID.canonical.z>this._source.minzoom){const parent=tileID.scaledTo(tileID.canonical.z-1);parents[parent.key]=parent;const parent2=tileID.scaledTo(Math.max(this._source.minzoom,Math.min(tileID.canonical.z,5)));parents[parent2.key]=parent2}}idealTileIDs=idealTileIDs.concat(Object.values(parents))}const noPendingDataEmissions=idealTileIDs.length===0&&!this._updated&&this._didEmitContent;this._updated=true;if(noPendingDataEmissions){this.fire(new performance$1.Event("data",{sourceDataType:"idle",dataType:"source",sourceId:this.id}))}const retain=this._updateRetainedTiles(idealTileIDs,zoom);if(isRasterType(this._source.type)){const parentsForFading={};const fadingTiles={};const ids=Object.keys(retain);const now=browser.now();for(const id of ids){const tileID=retain[id];const tile=this._tiles[id];if(!tile||tile.fadeEndTime!==0&&tile.fadeEndTime<=now){continue}const parentTile=this.findLoadedParent(tileID,minCoveringZoom);if(parentTile){this._addTile(parentTile.tileID);parentsForFading[parentTile.tileID.key]=parentTile.tileID}fadingTiles[id]=tileID}this._retainLoadedChildren(fadingTiles,zoom,maxCoveringZoom,retain);for(const id in parentsForFading){if(!retain[id]){this._coveredTiles[id]=true;retain[id]=parentsForFading[id]}}if(terrain){const idealRasterTileIDs={};const missingTileIDs={};for(const tileID of idealTileIDs){if(this._tiles[tileID.key].hasData())idealRasterTileIDs[tileID.key]=tileID;else missingTileIDs[tileID.key]=tileID}for(const key in missingTileIDs){const children=missingTileIDs[key].children(this._source.maxzoom);if(this._tiles[children[0].key]&&this._tiles[children[1].key]&&this._tiles[children[2].key]&&this._tiles[children[3].key]){idealRasterTileIDs[children[0].key]=retain[children[0].key]=children[0];idealRasterTileIDs[children[1].key]=retain[children[1].key]=children[1];idealRasterTileIDs[children[2].key]=retain[children[2].key]=children[2];idealRasterTileIDs[children[3].key]=retain[children[3].key]=children[3];delete missingTileIDs[key]}}for(const key in missingTileIDs){const parent=this.findLoadedParent(missingTileIDs[key],this._source.minzoom);if(parent){idealRasterTileIDs[parent.tileID.key]=retain[parent.tileID.key]=parent.tileID;for(const key in idealRasterTileIDs){if(idealRasterTileIDs[key].isChildOf(parent.tileID))delete idealRasterTileIDs[key]}}}for(const key in this._tiles){if(!idealRasterTileIDs[key])this._coveredTiles[key]=true}}}for(const retainedId in retain){this._tiles[retainedId].clearFadeHold()}const remove=performance$1.keysDifference(this._tiles,retain);for(const tileID of remove){const tile=this._tiles[tileID];if(tile.hasSymbolBuckets&&!tile.holdingForFade()){tile.setHoldDuration(this.map._fadeDuration)}else if(!tile.hasSymbolBuckets||tile.symbolFadeFinished()){this._removeTile(tileID)}}this._updateLoadedParentTileCache()}releaseSymbolFadeTiles(){for(const id in this._tiles){if(this._tiles[id].holdingForFade()){this._removeTile(id)}}}_updateRetainedTiles(idealTileIDs,zoom){const retain={};const checked={};const minCoveringZoom=Math.max(zoom-SourceCache.maxOverzooming,this._source.minzoom);const maxCoveringZoom=Math.max(zoom+SourceCache.maxUnderzooming,this._source.minzoom);const missingTiles={};for(const tileID of idealTileIDs){const tile=this._addTile(tileID);retain[tileID.key]=tileID;if(tile.hasData())continue;if(zoomthis._source.maxzoom){const childCoord=tileID.children(this._source.maxzoom)[0];const childTile=this.getTile(childCoord);if(!!childTile&&childTile.hasData()){retain[childCoord.key]=childCoord;continue}}else{const children=tileID.children(this._source.maxzoom);if(retain[children[0].key]&&retain[children[1].key]&&retain[children[2].key]&&retain[children[3].key])continue}let parentWasRequested=tile.wasRequested();for(let overscaledZ=tileID.overscaledZ-1;overscaledZ>=minCoveringZoom;--overscaledZ){const parentId=tileID.scaledTo(overscaledZ);if(checked[parentId.key])break;checked[parentId.key]=true;tile=this.getTile(parentId);if(!tile&&parentWasRequested){tile=this._addTile(parentId)}if(tile){const hasData=tile.hasData();if(parentWasRequested||hasData){retain[parentId.key]=parentId}parentWasRequested=tile.wasRequested();if(hasData)break}}}return retain}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const tileKey in this._tiles){const path=[];let parentTile;let currentId=this._tiles[tileKey].tileID;while(currentId.overscaledZ>0){if(currentId.key in this._loadedParentTiles){parentTile=this._loadedParentTiles[currentId.key];break}path.push(currentId.key);const parentId=currentId.scaledTo(currentId.overscaledZ-1);parentTile=this._getLoadedTile(parentId);if(parentTile){break}currentId=parentId}for(const key of path){this._loadedParentTiles[key]=parentTile}}}_addTile(tileID){let tile=this._tiles[tileID.key];if(tile)return tile;tile=this._cache.getAndRemove(tileID);if(tile){this._setTileReloadTimer(tileID.key,tile);tile.tileID=tileID;this._state.initializeTileState(tile,this.map?this.map.painter:null);if(this._cacheTimers[tileID.key]){clearTimeout(this._cacheTimers[tileID.key]);delete this._cacheTimers[tileID.key];this._setTileReloadTimer(tileID.key,tile)}}const cached=tile;if(!tile){tile=new Tile(tileID,this._source.tileSize*tileID.overscaleFactor());this._loadTile(tile,tileID.key,tile.state)}tile.uses++;this._tiles[tileID.key]=tile;if(!cached){this._source.fire(new performance$1.Event("dataloading",{tile:tile,coord:tile.tileID,dataType:"source"}))}return tile}_setTileReloadTimer(id,tile){if(id in this._timers){clearTimeout(this._timers[id]);delete this._timers[id]}const expiryTimeout=tile.getExpiryTimeout();if(expiryTimeout){this._timers[id]=setTimeout((()=>{this._reloadTile(id,"expired");delete this._timers[id]}),expiryTimeout)}}_removeTile(id){const tile=this._tiles[id];if(!tile)return;tile.uses--;delete this._tiles[id];if(this._timers[id]){clearTimeout(this._timers[id]);delete this._timers[id]}if(tile.uses>0)return;if(tile.hasData()&&tile.state!=="reloading"){this._cache.add(tile.tileID,tile,tile.getExpiryTimeout())}else{tile.aborted=true;this._abortTile(tile);this._unloadTile(tile)}}clearTiles(){this._shouldReloadOnResume=false;this._paused=false;for(const id in this._tiles)this._removeTile(id);this._cache.reset()}tilesIn(pointQueryGeometry,maxPitchScaleFactor,has3DLayer){const tileResults=[];const transform=this.transform;if(!transform)return tileResults;const cameraPointQueryGeometry=has3DLayer?transform.getCameraQueryGeometry(pointQueryGeometry):pointQueryGeometry;const queryGeometry=pointQueryGeometry.map((p=>transform.pointCoordinate(p,this.terrain)));const cameraQueryGeometry=cameraPointQueryGeometry.map((p=>transform.pointCoordinate(p,this.terrain)));const ids=this.getIds();let minX=Infinity;let minY=Infinity;let maxX=-Infinity;let maxY=-Infinity;for(const p of cameraQueryGeometry){minX=Math.min(minX,p.x);minY=Math.min(minY,p.y);maxX=Math.max(maxX,p.x);maxY=Math.max(maxY,p.y)}for(let i=0;i=0&&tileSpaceBounds[1].y+queryPadding>=0){const tileSpaceQueryGeometry=queryGeometry.map((c=>tileID.getTilePoint(c)));const tileSpaceCameraQueryGeometry=cameraQueryGeometry.map((c=>tileID.getTilePoint(c)));tileResults.push({tile:tile,tileID:tileID,queryGeometry:tileSpaceQueryGeometry,cameraQueryGeometry:tileSpaceCameraQueryGeometry,scale:scale})}}return tileResults}getVisibleCoordinates(symbolLayer){const coords=this.getRenderableIds(symbolLayer).map((id=>this._tiles[id].tileID));for(const coord of coords){coord.posMatrix=this.transform.calculatePosMatrix(coord.toUnwrapped())}return coords}hasTransition(){if(this._source.hasTransition()){return true}if(isRasterType(this._source.type)){const now=browser.now();for(const id in this._tiles){const tile=this._tiles[id];if(tile.fadeEndTime>=now){return true}}}return false}setFeatureState(sourceLayer,featureId,state){sourceLayer=sourceLayer||"_geojsonTileLayer";this._state.updateState(sourceLayer,featureId,state)}removeFeatureState(sourceLayer,featureId,key){sourceLayer=sourceLayer||"_geojsonTileLayer";this._state.removeFeatureState(sourceLayer,featureId,key)}getFeatureState(sourceLayer,featureId){sourceLayer=sourceLayer||"_geojsonTileLayer";return this._state.getState(sourceLayer,featureId)}setDependencies(tileKey,namespace,dependencies){const tile=this._tiles[tileKey];if(tile){tile.setDependencies(namespace,dependencies)}}reloadTilesForDependencies(namespaces,keys){for(const id in this._tiles){const tile=this._tiles[id];if(tile.hasDependency(namespaces,keys)){this._reloadTile(id,"reloading")}}this._cache.filter((tile=>!tile.hasDependency(namespaces,keys)))}}SourceCache.maxOverzooming=10;SourceCache.maxUnderzooming=3;function compareTileId(a,b){const aWrap=Math.abs(a.wrap*2)-+(a.wrap<0);const bWrap=Math.abs(b.wrap*2)-+(b.wrap<0);return a.overscaledZ-b.overscaledZ||bWrap-aWrap||b.canonical.y-a.canonical.y||b.canonical.x-a.canonical.x}function isRasterType(type){return type==="raster"||type==="image"||type==="video"}class PathInterpolator{constructor(points_,padding_){this.reset(points_,padding_)}reset(points_,padding_){this.points=points_||[];this._distances=[0];for(let i=1;i0?(distToTarget-distOfPrevIdx)/segmentLength:0;return this.points[idxOfPrevPoint].mult(1-segmentT).add(this.points[currentIndex].mult(segmentT))}}function overlapAllowed(overlapA,overlapB){let allowed=true;if(overlapA==="always"){}else if(overlapA==="never"||overlapB==="never"){allowed=false}return allowed}class GridIndex{constructor(width,height,cellSize){const boxCells=this.boxCells=[];const circleCells=this.circleCells=[];this.xCellCount=Math.ceil(width/cellSize);this.yCellCount=Math.ceil(height/cellSize);for(let i=0;ithis.width||y2<0||y1>this.height){return[]}const result=[];if(x1<=0&&y1<=0&&this.width<=x2&&this.height<=y2){if(hitTest){return[{key:null,x1:x1,y1:y1,x2:x2,y2:y2}]}for(let boxUid=0;boxUid0}hitTestCircle(x,y,radius,overlapMode,predicate){const x1=x-radius;const x2=x+radius;const y1=y-radius;const y2=y+radius;if(x2<0||x1>this.width||y2<0||y1>this.height){return false}const result=[];const queryArgs={hitTest:true,overlapMode:overlapMode,circle:{x:x,y:y,radius:radius},seenUids:{box:{},circle:{}}};this._forEachCell(x1,y1,x2,y2,this._queryCellCircle,result,queryArgs,predicate);return result.length>0}_queryCell(x1,y1,x2,y2,cellIndex,result,queryArgs,predicate){const{seenUids:seenUids,hitTest:hitTest,overlapMode:overlapMode}=queryArgs;const boxCell=this.boxCells[cellIndex];if(boxCell!==null){const bboxes=this.bboxes;for(const boxUid of boxCell){if(!seenUids.box[boxUid]){seenUids.box[boxUid]=true;const offset=boxUid*4;const key=this.boxKeys[boxUid];if(x1<=bboxes[offset+2]&&y1<=bboxes[offset+3]&&x2>=bboxes[offset+0]&&y2>=bboxes[offset+1]&&(!predicate||predicate(key))){if(!hitTest||!overlapAllowed(overlapMode,key.overlapMode)){result.push({key:key,x1:bboxes[offset],y1:bboxes[offset+1],x2:bboxes[offset+2],y2:bboxes[offset+3]});if(hitTest){return true}}}}}}const circleCell=this.circleCells[cellIndex];if(circleCell!==null){const circles=this.circles;for(const circleUid of circleCell){if(!seenUids.circle[circleUid]){seenUids.circle[circleUid]=true;const offset=circleUid*3;const key=this.circleKeys[circleUid];if(this._circleAndRectCollide(circles[offset],circles[offset+1],circles[offset+2],x1,y1,x2,y2)&&(!predicate||predicate(key))){if(!hitTest||!overlapAllowed(overlapMode,key.overlapMode)){const x=circles[offset];const y=circles[offset+1];const radius=circles[offset+2];result.push({key:key,x1:x-radius,y1:y-radius,x2:x+radius,y2:y+radius});if(hitTest){return true}}}}}}return false}_queryCellCircle(x1,y1,x2,y2,cellIndex,result,queryArgs,predicate){const{circle:circle,seenUids:seenUids,overlapMode:overlapMode}=queryArgs;const boxCell=this.boxCells[cellIndex];if(boxCell!==null){const bboxes=this.bboxes;for(const boxUid of boxCell){if(!seenUids.box[boxUid]){seenUids.box[boxUid]=true;const offset=boxUid*4;const key=this.boxKeys[boxUid];if(this._circleAndRectCollide(circle.x,circle.y,circle.radius,bboxes[offset+0],bboxes[offset+1],bboxes[offset+2],bboxes[offset+3])&&(!predicate||predicate(key))&&!overlapAllowed(overlapMode,key.overlapMode)){result.push(true);return true}}}}const circleCell=this.circleCells[cellIndex];if(circleCell!==null){const circles=this.circles;for(const circleUid of circleCell){if(!seenUids.circle[circleUid]){seenUids.circle[circleUid]=true;const offset=circleUid*3;const key=this.circleKeys[circleUid];if(this._circlesCollide(circles[offset],circles[offset+1],circles[offset+2],circle.x,circle.y,circle.radius)&&(!predicate||predicate(key))&&!overlapAllowed(overlapMode,key.overlapMode)){result.push(true);return true}}}}}_forEachCell(x1,y1,x2,y2,fn,arg1,arg2,predicate){const cx1=this._convertToXCellCoord(x1);const cy1=this._convertToYCellCoord(y1);const cx2=this._convertToXCellCoord(x2);const cy2=this._convertToYCellCoord(y2);for(let x=cx1;x<=cx2;x++){for(let y=cy1;y<=cy2;y++){const cellIndex=this.xCellCount*y+x;if(fn.call(this,x1,y1,x2,y2,cellIndex,arg1,arg2,predicate))return}}}_convertToXCellCoord(x){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(x*this.xScale)))}_convertToYCellCoord(y){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(y*this.yScale)))}_circlesCollide(x1,y1,r1,x2,y2,r2){const dx=x2-x1;const dy=y2-y1;const bothRadii=r1+r2;return bothRadii*bothRadii>dx*dx+dy*dy}_circleAndRectCollide(circleX,circleY,radius,x1,y1,x2,y2){const halfRectWidth=(x2-x1)/2;const distX=Math.abs(circleX-(x1+halfRectWidth));if(distX>halfRectWidth+radius){return false}const halfRectHeight=(y2-y1)/2;const distY=Math.abs(circleY-(y1+halfRectHeight));if(distY>halfRectHeight+radius){return false}if(distX<=halfRectWidth||distY<=halfRectHeight){return true}const dx=distX-halfRectWidth;const dy=distY-halfRectHeight;return dx*dx+dy*dy<=radius*radius}}function getLabelPlaneMatrix(posMatrix,pitchWithMap,rotateWithMap,transform,pixelsToTileUnits){const m=performance$1.create();if(pitchWithMap){performance$1.scale(m,m,[1/pixelsToTileUnits,1/pixelsToTileUnits,1]);if(!rotateWithMap){performance$1.rotateZ(m,m,transform.angle)}}else{performance$1.multiply(m,transform.labelPlaneMatrix,posMatrix)}return m}function getGlCoordMatrix(posMatrix,pitchWithMap,rotateWithMap,transform,pixelsToTileUnits){if(pitchWithMap){const m=performance$1.clone(posMatrix);performance$1.scale(m,m,[pixelsToTileUnits,pixelsToTileUnits,1]);if(!rotateWithMap){performance$1.rotateZ(m,m,-transform.angle)}return m}else{return transform.glCoordMatrix}}function project(point,matrix,getElevation){let pos;if(getElevation){pos=[point.x,point.y,getElevation(point.x,point.y),1];performance$1.transformMat4(pos,pos,matrix)}else{pos=[point.x,point.y,0,1];xyTransformMat4(pos,pos,matrix)}const w=pos[3];return{point:new performance$1.Point(pos[0]/w,pos[1]/w),signedDistanceFromCamera:w}}function getPerspectiveRatio(cameraToCenterDistance,signedDistanceFromCamera){return.5+.5*(cameraToCenterDistance/signedDistanceFromCamera)}function isVisible(anchorPos,clippingBuffer){const x=anchorPos[0]/anchorPos[3];const y=anchorPos[1]/anchorPos[3];const inPaddedViewport=x>=-clippingBuffer[0]&&x<=clippingBuffer[0]&&y>=-clippingBuffer[1]&&y<=clippingBuffer[1];return inPaddedViewport}function updateLineLabels(bucket,posMatrix,painter,isText,labelPlaneMatrix,glCoordMatrix,pitchWithMap,keepUpright,rotateToLine,getElevation){const sizeData=isText?bucket.textSizeData:bucket.iconSizeData;const partiallyEvaluatedSize=performance$1.evaluateSizeForZoom(sizeData,painter.transform.zoom);const clippingBuffer=[256/painter.width*2+1,256/painter.height*2+1];const dynamicLayoutVertexArray=isText?bucket.text.dynamicLayoutVertexArray:bucket.icon.dynamicLayoutVertexArray;dynamicLayoutVertexArray.clear();const lineVertexArray=bucket.lineVertexArray;const placedSymbols=isText?bucket.text.placedSymbolArray:bucket.icon.placedSymbolArray;const aspectRatio=painter.transform.width/painter.transform.height;let useVertical=false;for(let s=0;srun){return{useVertical:true}}}if(writingMode===performance$1.WritingMode.vertical?firstPoint.ylastPoint.x){return{needsFlipping:true}}return null}function placeGlyphsAlongLine(symbol,fontSize,flip,keepUpright,posMatrix,labelPlaneMatrix,glCoordMatrix,glyphOffsetArray,lineVertexArray,dynamicLayoutVertexArray,anchorPoint,tileAnchorPoint,projectionCache,aspectRatio,rotateToLine,getElevation){const fontScale=fontSize/24;const lineOffsetX=symbol.lineOffsetX*fontScale;const lineOffsetY=symbol.lineOffsetY*fontScale;let placedGlyphs;if(symbol.numGlyphs>1){const glyphEndIndex=symbol.glyphStartIndex+symbol.numGlyphs;const lineStartIndex=symbol.lineStartIndex;const lineEndIndex=symbol.lineStartIndex+symbol.lineLength;const firstAndLastGlyph=placeFirstAndLastGlyph(fontScale,glyphOffsetArray,lineOffsetX,lineOffsetY,flip,anchorPoint,tileAnchorPoint,symbol,lineVertexArray,labelPlaneMatrix,projectionCache,rotateToLine,getElevation);if(!firstAndLastGlyph){return{notEnoughRoom:true}}const firstPoint=project(firstAndLastGlyph.first.point,glCoordMatrix,getElevation).point;const lastPoint=project(firstAndLastGlyph.last.point,glCoordMatrix,getElevation).point;if(keepUpright&&!flip){const orientationChange=requiresOrientationChange(symbol.writingMode,firstPoint,lastPoint,aspectRatio);if(orientationChange){return orientationChange}}placedGlyphs=[firstAndLastGlyph.first];for(let glyphIndex=symbol.glyphStartIndex+1;glyphIndex0?projectedVertex.point:projectTruncatedLineSegment(tileAnchorPoint,tileSegmentEnd,a,1,posMatrix,getElevation);const orientationChange=requiresOrientationChange(symbol.writingMode,a,b,aspectRatio);if(orientationChange){return orientationChange}}const singleGlyph=placeGlyphAlongLine(fontScale*glyphOffsetArray.getoffsetX(symbol.glyphStartIndex),lineOffsetX,lineOffsetY,flip,anchorPoint,tileAnchorPoint,symbol.segment,symbol.lineStartIndex,symbol.lineStartIndex+symbol.lineLength,lineVertexArray,labelPlaneMatrix,projectionCache,rotateToLine,getElevation);if(!singleGlyph)return{notEnoughRoom:true};placedGlyphs=[singleGlyph]}for(const glyph of placedGlyphs){performance$1.addDynamicAttributes(dynamicLayoutVertexArray,glyph.point,glyph.angle)}return{}}function projectTruncatedLineSegment(previousTilePoint,currentTilePoint,previousProjectedPoint,minimumLength,projectionMatrix,getElevation){const projectedUnitVertex=project(previousTilePoint.add(previousTilePoint.sub(currentTilePoint)._unit()),projectionMatrix,getElevation).point;const projectedUnitSegment=previousProjectedPoint.sub(projectedUnitVertex);return previousProjectedPoint.add(projectedUnitSegment._mult(minimumLength/projectedUnitSegment.mag()))}function projectVertexToViewport(index,projectionArgs){const{projectionCache:projectionCache,lineVertexArray:lineVertexArray,labelPlaneMatrix:labelPlaneMatrix,tileAnchorPoint:tileAnchorPoint,distanceFromAnchor:distanceFromAnchor,getElevation:getElevation,previousVertex:previousVertex,direction:direction,absOffsetX:absOffsetX}=projectionArgs;if(projectionCache.projections[index]){return projectionCache.projections[index]}const currentVertex=new performance$1.Point(lineVertexArray.getx(index),lineVertexArray.gety(index));const projection=project(currentVertex,labelPlaneMatrix,getElevation);if(projection.signedDistanceFromCamera>0){projectionCache.projections[index]=projection.point;return projection.point}const previousLineVertexIndex=index-direction;const previousTilePoint=distanceFromAnchor===0?tileAnchorPoint:new performance$1.Point(lineVertexArray.getx(previousLineVertexIndex),lineVertexArray.gety(previousLineVertexIndex));return projectTruncatedLineSegment(previousTilePoint,currentVertex,previousVertex,absOffsetX-distanceFromAnchor+1,labelPlaneMatrix,getElevation)}function transformToOffsetNormal(segmentVector,offset,direction){return segmentVector._unit()._perp()._mult(offset*direction)}function findOffsetIntersectionPoint(index,prevToCurrentOffsetNormal,currentVertex,lineStartIndex,lineEndIndex,offsetPreviousVertex,lineOffsetY,projectionArgs){const{projectionCache:projectionCache,direction:direction}=projectionArgs;if(projectionCache.offsets[index]){return projectionCache.offsets[index]}const offsetCurrentVertex=currentVertex.add(prevToCurrentOffsetNormal);if(index+direction=lineEndIndex){projectionCache.offsets[index]=offsetCurrentVertex;return offsetCurrentVertex}const nextVertex=projectVertexToViewport(index+direction,projectionArgs);const currentToNextOffsetNormal=transformToOffsetNormal(nextVertex.sub(currentVertex),lineOffsetY,direction);const offsetNextSegmentBegin=currentVertex.add(currentToNextOffsetNormal);const offsetNextSegmentEnd=nextVertex.add(currentToNextOffsetNormal);projectionCache.offsets[index]=performance$1.findLineIntersection(offsetPreviousVertex,offsetCurrentVertex,offsetNextSegmentBegin,offsetNextSegmentEnd)||offsetCurrentVertex;return projectionCache.offsets[index]}function placeGlyphAlongLine(offsetX,lineOffsetX,lineOffsetY,flip,anchorPoint,tileAnchorPoint,anchorSegment,lineStartIndex,lineEndIndex,lineVertexArray,labelPlaneMatrix,projectionCache,rotateToLine,getElevation){const combinedOffsetX=flip?offsetX-lineOffsetX:offsetX+lineOffsetX;let direction=combinedOffsetX>0?1:-1;let angle=0;if(flip){direction*=-1;angle=Math.PI}if(direction<0)angle+=Math.PI;let currentIndex=direction>0?lineStartIndex+anchorSegment:lineStartIndex+anchorSegment+1;let currentVertex=anchorPoint;let previousVertex=anchorPoint;let offsetIntersectionPoint;let offsetPreviousVertex;let distanceFromAnchor=0;let currentSegmentDistance=0;const absOffsetX=Math.abs(combinedOffsetX);const pathVertices=[];let currentLineSegment;while(distanceFromAnchor+currentSegmentDistance<=absOffsetX){currentIndex+=direction;if(currentIndex=lineEndIndex)return null;distanceFromAnchor+=currentSegmentDistance;previousVertex=currentVertex;offsetPreviousVertex=offsetIntersectionPoint;const projectionArgs={projectionCache:projectionCache,lineVertexArray:lineVertexArray,labelPlaneMatrix:labelPlaneMatrix,tileAnchorPoint:tileAnchorPoint,distanceFromAnchor:distanceFromAnchor,getElevation:getElevation,previousVertex:previousVertex,direction:direction,absOffsetX:absOffsetX};currentVertex=projectVertexToViewport(currentIndex,projectionArgs);if(lineOffsetY===0){pathVertices.push(previousVertex);currentLineSegment=currentVertex.sub(previousVertex)}else{let prevToCurrentOffsetNormal;const prevToCurrent=currentVertex.sub(previousVertex);if(prevToCurrent.mag()===0){const nextVertex=projectVertexToViewport(currentIndex+direction,projectionArgs);prevToCurrentOffsetNormal=transformToOffsetNormal(nextVertex.sub(currentVertex),lineOffsetY,direction)}else{prevToCurrentOffsetNormal=transformToOffsetNormal(prevToCurrent,lineOffsetY,direction)}if(!offsetPreviousVertex)offsetPreviousVertex=previousVertex.add(prevToCurrentOffsetNormal);offsetIntersectionPoint=findOffsetIntersectionPoint(currentIndex,prevToCurrentOffsetNormal,currentVertex,lineStartIndex,lineEndIndex,offsetPreviousVertex,lineOffsetY,projectionArgs);pathVertices.push(offsetPreviousVertex);currentLineSegment=offsetIntersectionPoint.sub(offsetPreviousVertex)}currentSegmentDistance=currentLineSegment.mag()}const segmentInterpolationT=(absOffsetX-distanceFromAnchor)/currentSegmentDistance;const p=currentLineSegment._mult(segmentInterpolationT)._add(offsetPreviousVertex||previousVertex);const segmentAngle=angle+Math.atan2(currentVertex.y-previousVertex.y,currentVertex.x-previousVertex.x);pathVertices.push(p);return{point:p,angle:rotateToLine?segmentAngle:0,path:pathVertices}}const hiddenGlyphAttributes=new Float32Array([-Infinity,-Infinity,0,-Infinity,-Infinity,0,-Infinity,-Infinity,0,-Infinity,-Infinity,0]);function hideGlyphs(num,dynamicLayoutVertexArray){for(let i=0;i=1;i--){projectedPath.push(first.path[i])}for(let i=1;iproject(p,labelToScreenMatrix,getElevation)));if(screenSpacePath.some((point=>point.signedDistanceFromCamera<=0))){projectedPath=[]}else{projectedPath=screenSpacePath.map((p=>p.point))}}let segments=[];if(projectedPath.length>0){const minPoint=projectedPath[0].clone();const maxPoint=projectedPath[0].clone();for(let i=1;i=screenPlaneMin.x&&maxPoint.x<=screenPlaneMax.x&&minPoint.y>=screenPlaneMin.y&&maxPoint.y<=screenPlaneMax.y){segments=[projectedPath]}else if(maxPoint.xscreenPlaneMax.x||maxPoint.yscreenPlaneMax.y){segments=[]}else{segments=performance$1.clipLine([projectedPath],screenPlaneMin.x,screenPlaneMin.y,screenPlaneMax.x,screenPlaneMax.y)}}for(const seg of segments){interpolator.reset(seg,radius*.25);let numCircles=0;if(interpolator.length<=.5*radius){numCircles=1}else{numCircles=Math.ceil(interpolator.paddedLength/circleDist)+1}for(let i=0;i=this.screenRightBoundary||y2this.screenBottomBoundary}isInsideGrid(x1,y1,x2,y2){return x2>=0&&x1=0&&y1key.collisionGroupID===nextGroupID}}return this.collisionGroups[sourceID]}else{return{ID:0,predicate:null}}}}function calculateVariableLayoutShift(anchor,width,height,textOffset,textBoxScale){const{horizontalAlign:horizontalAlign,verticalAlign:verticalAlign}=performance$1.getAnchorAlignment(anchor);const shiftX=-(horizontalAlign-.5)*width;const shiftY=-(verticalAlign-.5)*height;return new performance$1.Point(shiftX+textOffset[0]*textBoxScale,shiftY+textOffset[1]*textBoxScale)}function shiftVariableCollisionBox(collisionBox,shiftX,shiftY,rotateWithMap,pitchWithMap,angle){const{x1:x1,x2:x2,y1:y1,y2:y2,anchorPointX:anchorPointX,anchorPointY:anchorPointY}=collisionBox;const rotatedOffset=new performance$1.Point(shiftX,shiftY);if(rotateWithMap){rotatedOffset._rotate(pitchWithMap?angle:-angle)}return{x1:x1+rotatedOffset.x,y1:y1+rotatedOffset.y,x2:x2+rotatedOffset.x,y2:y2+rotatedOffset.y,anchorPointX:anchorPointX,anchorPointY:anchorPointY}}class Placement{constructor(transform,terrain,fadeDuration,crossSourceCollisions,prevPlacement){this.transform=transform.clone();this.terrain=terrain;this.collisionIndex=new CollisionIndex(this.transform);this.placements={};this.opacities={};this.variableOffsets={};this.stale=false;this.commitTime=0;this.fadeDuration=fadeDuration;this.retainedQueryData={};this.collisionGroups=new CollisionGroups(crossSourceCollisions);this.collisionCircleArrays={};this.prevPlacement=prevPlacement;if(prevPlacement){prevPlacement.prevPlacement=undefined}this.placedOrientations={}}getBucketParts(results,styleLayer,tile,sortAcrossTiles){const symbolBucket=tile.getBucket(styleLayer);const bucketFeatureIndex=tile.latestFeatureIndex;if(!symbolBucket||!bucketFeatureIndex||styleLayer.id!==symbolBucket.layerIds[0])return;const collisionBoxArray=tile.collisionBoxArray;const layout=symbolBucket.layers[0].layout;const scale=Math.pow(2,this.transform.zoom-tile.tileID.overscaledZ);const textPixelRatio=tile.tileSize/performance$1.EXTENT;const posMatrix=this.transform.calculatePosMatrix(tile.tileID.toUnwrapped());const pitchWithMap=layout.get("text-pitch-alignment")==="map";const rotateWithMap=layout.get("text-rotation-alignment")==="map";const pixelsToTiles=pixelsToTileUnits(tile,1,this.transform.zoom);const textLabelPlaneMatrix=getLabelPlaneMatrix(posMatrix,pitchWithMap,rotateWithMap,this.transform,pixelsToTiles);let labelToScreenMatrix=null;if(pitchWithMap){const glMatrix=getGlCoordMatrix(posMatrix,pitchWithMap,rotateWithMap,this.transform,pixelsToTiles);labelToScreenMatrix=performance$1.multiply([],this.transform.labelPlaneMatrix,glMatrix)}this.retainedQueryData[symbolBucket.bucketInstanceId]=new RetainedQueryData(symbolBucket.bucketInstanceId,bucketFeatureIndex,symbolBucket.sourceLayerIndex,symbolBucket.index,tile.tileID);const parameters={bucket:symbolBucket,layout:layout,posMatrix:posMatrix,textLabelPlaneMatrix:textLabelPlaneMatrix,labelToScreenMatrix:labelToScreenMatrix,scale:scale,textPixelRatio:textPixelRatio,holdingForFade:tile.holdingForFade(),collisionBoxArray:collisionBoxArray,partiallyEvaluatedTextSize:performance$1.evaluateSizeForZoom(symbolBucket.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(symbolBucket.sourceID)};if(sortAcrossTiles){for(const range of symbolBucket.sortKeyRanges){const{sortKey:sortKey,symbolInstanceStart:symbolInstanceStart,symbolInstanceEnd:symbolInstanceEnd}=range;results.push({sortKey:sortKey,symbolInstanceStart:symbolInstanceStart,symbolInstanceEnd:symbolInstanceEnd,parameters:parameters})}}else{results.push({symbolInstanceStart:0,symbolInstanceEnd:symbolBucket.symbolInstances.length,parameters:parameters})}}attemptAnchorPlacement(textAnchorOffset,textBox,width,height,textBoxScale,rotateWithMap,pitchWithMap,textPixelRatio,posMatrix,collisionGroup,textOverlapMode,symbolInstance,bucket,orientation,iconBox,getElevation){const anchor=performance$1.TextAnchorEnum[textAnchorOffset.textAnchor];const textOffset=[textAnchorOffset.textOffset0,textAnchorOffset.textOffset1];const shift=calculateVariableLayoutShift(anchor,width,height,textOffset,textBoxScale);const placedGlyphBoxes=this.collisionIndex.placeCollisionBox(shiftVariableCollisionBox(textBox,shift.x,shift.y,rotateWithMap,pitchWithMap,this.transform.angle),textOverlapMode,textPixelRatio,posMatrix,collisionGroup.predicate,getElevation);if(iconBox){const placedIconBoxes=this.collisionIndex.placeCollisionBox(shiftVariableCollisionBox(iconBox,shift.x,shift.y,rotateWithMap,pitchWithMap,this.transform.angle),textOverlapMode,textPixelRatio,posMatrix,collisionGroup.predicate,getElevation);if(placedIconBoxes.box.length===0)return}if(placedGlyphBoxes.box.length>0){let prevAnchor;if(this.prevPlacement&&this.prevPlacement.variableOffsets[symbolInstance.crossTileID]&&this.prevPlacement.placements[symbolInstance.crossTileID]&&this.prevPlacement.placements[symbolInstance.crossTileID].text){prevAnchor=this.prevPlacement.variableOffsets[symbolInstance.crossTileID].anchor}if(symbolInstance.crossTileID===0)throw new Error("symbolInstance.crossTileID can't be 0");this.variableOffsets[symbolInstance.crossTileID]={textOffset:textOffset,width:width,height:height,anchor:anchor,textBoxScale:textBoxScale,prevAnchor:prevAnchor};this.markUsedJustification(bucket,anchor,symbolInstance,orientation);if(bucket.allowVerticalPlacement){this.markUsedOrientation(bucket,orientation,symbolInstance);this.placedOrientations[symbolInstance.crossTileID]=orientation}return{shift:shift,placedGlyphBoxes:placedGlyphBoxes}}}placeLayerBucketPart(bucketPart,seenCrossTileIDs,showCollisionBoxes){const{bucket:bucket,layout:layout,posMatrix:posMatrix,textLabelPlaneMatrix:textLabelPlaneMatrix,labelToScreenMatrix:labelToScreenMatrix,textPixelRatio:textPixelRatio,holdingForFade:holdingForFade,collisionBoxArray:collisionBoxArray,partiallyEvaluatedTextSize:partiallyEvaluatedTextSize,collisionGroup:collisionGroup}=bucketPart.parameters;const textOptional=layout.get("text-optional");const iconOptional=layout.get("icon-optional");const textOverlapMode=performance$1.getOverlapMode(layout,"text-overlap","text-allow-overlap");const textAlwaysOverlap=textOverlapMode==="always";const iconOverlapMode=performance$1.getOverlapMode(layout,"icon-overlap","icon-allow-overlap");const iconAlwaysOverlap=iconOverlapMode==="always";const rotateWithMap=layout.get("text-rotation-alignment")==="map";const pitchWithMap=layout.get("text-pitch-alignment")==="map";const hasIconTextFit=layout.get("icon-text-fit")!=="none";const zOrderByViewportY=layout.get("symbol-z-order")==="viewport-y";const alwaysShowText=textAlwaysOverlap&&(iconAlwaysOverlap||!bucket.hasIconData()||iconOptional);const alwaysShowIcon=iconAlwaysOverlap&&(textAlwaysOverlap||!bucket.hasTextData()||textOptional);if(!bucket.collisionArrays&&collisionBoxArray){bucket.deserializeCollisionBoxes(collisionBoxArray)}const tileID=this.retainedQueryData[bucket.bucketInstanceId].tileID;const getElevation=this.terrain?(x,y)=>this.terrain.getElevation(tileID,x,y):null;const placeSymbol=(symbolInstance,collisionArrays)=>{var _a,_b;if(seenCrossTileIDs[symbolInstance.crossTileID])return;if(holdingForFade){this.placements[symbolInstance.crossTileID]=new JointPlacement(false,false,false);return}let placeText=false;let placeIcon=false;let offscreen=true;let shift=null;let placed={box:null,offscreen:null};let placedVerticalText={box:null,offscreen:null};let placedGlyphBoxes=null;let placedGlyphCircles=null;let placedIconBoxes=null;let textFeatureIndex=0;let verticalTextFeatureIndex=0;let iconFeatureIndex=0;if(collisionArrays.textFeatureIndex){textFeatureIndex=collisionArrays.textFeatureIndex}else if(symbolInstance.useRuntimeCollisionCircles){textFeatureIndex=symbolInstance.featureIndex}if(collisionArrays.verticalTextFeatureIndex){verticalTextFeatureIndex=collisionArrays.verticalTextFeatureIndex}const textBox=collisionArrays.textBox;if(textBox){const updatePreviousOrientationIfNotPlaced=isPlaced=>{let previousOrientation=performance$1.WritingMode.horizontal;if(bucket.allowVerticalPlacement&&!isPlaced&&this.prevPlacement){const prevPlacedOrientation=this.prevPlacement.placedOrientations[symbolInstance.crossTileID];if(prevPlacedOrientation){this.placedOrientations[symbolInstance.crossTileID]=prevPlacedOrientation;previousOrientation=prevPlacedOrientation;this.markUsedOrientation(bucket,previousOrientation,symbolInstance)}}return previousOrientation};const placeTextForPlacementModes=(placeHorizontalFn,placeVerticalFn)=>{if(bucket.allowVerticalPlacement&&symbolInstance.numVerticalGlyphVertices>0&&collisionArrays.verticalTextBox){for(const placementMode of bucket.writingModes){if(placementMode===performance$1.WritingMode.vertical){placed=placeVerticalFn();placedVerticalText=placed}else{placed=placeHorizontalFn()}if(placed&&placed.box&&placed.box.length)break}}else{placed=placeHorizontalFn()}};const textAnchorOffsetStart=symbolInstance.textAnchorOffsetStartIndex;const textAnchorOffsetEnd=symbolInstance.textAnchorOffsetEndIndex;if(textAnchorOffsetEnd===textAnchorOffsetStart){const placeBox=(collisionTextBox,orientation)=>{const placedFeature=this.collisionIndex.placeCollisionBox(collisionTextBox,textOverlapMode,textPixelRatio,posMatrix,collisionGroup.predicate,getElevation);if(placedFeature&&placedFeature.box&&placedFeature.box.length){this.markUsedOrientation(bucket,orientation,symbolInstance);this.placedOrientations[symbolInstance.crossTileID]=orientation}return placedFeature};const placeHorizontal=()=>placeBox(textBox,performance$1.WritingMode.horizontal);const placeVertical=()=>{const verticalTextBox=collisionArrays.verticalTextBox;if(bucket.allowVerticalPlacement&&symbolInstance.numVerticalGlyphVertices>0&&verticalTextBox){return placeBox(verticalTextBox,performance$1.WritingMode.vertical)}return{box:null,offscreen:null}};placeTextForPlacementModes(placeHorizontal,placeVertical);updatePreviousOrientationIfNotPlaced(placed&&placed.box&&placed.box.length)}else{let prevAnchor=performance$1.TextAnchorEnum[(_b=(_a=this.prevPlacement)===null||_a===void 0?void 0:_a.variableOffsets[symbolInstance.crossTileID])===null||_b===void 0?void 0:_b.anchor];const placeBoxForVariableAnchors=(collisionTextBox,collisionIconBox,orientation)=>{const width=collisionTextBox.x2-collisionTextBox.x1;const height=collisionTextBox.y2-collisionTextBox.y1;const textBoxScale=symbolInstance.textBoxScale;const variableIconBox=hasIconTextFit&&iconOverlapMode==="never"?collisionIconBox:null;let placedBox={box:[],offscreen:false};let placementPasses=textOverlapMode==="never"?1:2;let overlapMode="never";if(prevAnchor){placementPasses++}for(let pass=0;passplaceBoxForVariableAnchors(textBox,collisionArrays.iconBox,performance$1.WritingMode.horizontal);const placeVertical=()=>{const verticalTextBox=collisionArrays.verticalTextBox;const wasPlaced=placed&&placed.box&&placed.box.length;if(bucket.allowVerticalPlacement&&!wasPlaced&&symbolInstance.numVerticalGlyphVertices>0&&verticalTextBox){return placeBoxForVariableAnchors(verticalTextBox,collisionArrays.verticalIconBox,performance$1.WritingMode.vertical)}return{box:null,offscreen:null}};placeTextForPlacementModes(placeHorizontal,placeVertical);if(placed){placeText=placed.box;offscreen=placed.offscreen}const prevOrientation=updatePreviousOrientationIfNotPlaced(placed&&placed.box);if(!placeText&&this.prevPlacement){const prevOffset=this.prevPlacement.variableOffsets[symbolInstance.crossTileID];if(prevOffset){this.variableOffsets[symbolInstance.crossTileID]=prevOffset;this.markUsedJustification(bucket,prevOffset.anchor,symbolInstance,prevOrientation)}}}}placedGlyphBoxes=placed;placeText=placedGlyphBoxes&&placedGlyphBoxes.box&&placedGlyphBoxes.box.length>0;offscreen=placedGlyphBoxes&&placedGlyphBoxes.offscreen;if(symbolInstance.useRuntimeCollisionCircles){const placedSymbol=bucket.text.placedSymbolArray.get(symbolInstance.centerJustifiedTextSymbolIndex);const fontSize=performance$1.evaluateSizeForFeature(bucket.textSizeData,partiallyEvaluatedTextSize,placedSymbol);const textPixelPadding=layout.get("text-padding");const circlePixelDiameter=symbolInstance.collisionCircleDiameter;placedGlyphCircles=this.collisionIndex.placeCollisionCircles(textOverlapMode,placedSymbol,bucket.lineVertexArray,bucket.glyphOffsetArray,fontSize,posMatrix,textLabelPlaneMatrix,labelToScreenMatrix,showCollisionBoxes,pitchWithMap,collisionGroup.predicate,circlePixelDiameter,textPixelPadding,getElevation);if(placedGlyphCircles.circles.length&&placedGlyphCircles.collisionDetected&&!showCollisionBoxes){performance$1.warnOnce("Collisions detected, but collision boxes are not shown")}placeText=textAlwaysOverlap||placedGlyphCircles.circles.length>0&&!placedGlyphCircles.collisionDetected;offscreen=offscreen&&placedGlyphCircles.offscreen}if(collisionArrays.iconFeatureIndex){iconFeatureIndex=collisionArrays.iconFeatureIndex}if(collisionArrays.iconBox){const placeIconFeature=iconBox=>{const shiftedIconBox=hasIconTextFit&&shift?shiftVariableCollisionBox(iconBox,shift.x,shift.y,rotateWithMap,pitchWithMap,this.transform.angle):iconBox;return this.collisionIndex.placeCollisionBox(shiftedIconBox,iconOverlapMode,textPixelRatio,posMatrix,collisionGroup.predicate,getElevation)};if(placedVerticalText&&placedVerticalText.box&&placedVerticalText.box.length&&collisionArrays.verticalIconBox){placedIconBoxes=placeIconFeature(collisionArrays.verticalIconBox);placeIcon=placedIconBoxes.box.length>0}else{placedIconBoxes=placeIconFeature(collisionArrays.iconBox);placeIcon=placedIconBoxes.box.length>0}offscreen=offscreen&&placedIconBoxes.offscreen}const iconWithoutText=textOptional||symbolInstance.numHorizontalGlyphVertices===0&&symbolInstance.numVerticalGlyphVertices===0;const textWithoutIcon=iconOptional||symbolInstance.numIconVertices===0;if(!iconWithoutText&&!textWithoutIcon){placeIcon=placeText=placeIcon&&placeText}else if(!textWithoutIcon){placeText=placeIcon&&placeText}else if(!iconWithoutText){placeIcon=placeIcon&&placeText}if(placeText&&placedGlyphBoxes&&placedGlyphBoxes.box){if(placedVerticalText&&placedVerticalText.box&&verticalTextFeatureIndex){this.collisionIndex.insertCollisionBox(placedGlyphBoxes.box,textOverlapMode,layout.get("text-ignore-placement"),bucket.bucketInstanceId,verticalTextFeatureIndex,collisionGroup.ID)}else{this.collisionIndex.insertCollisionBox(placedGlyphBoxes.box,textOverlapMode,layout.get("text-ignore-placement"),bucket.bucketInstanceId,textFeatureIndex,collisionGroup.ID)}}if(placeIcon&&placedIconBoxes){this.collisionIndex.insertCollisionBox(placedIconBoxes.box,iconOverlapMode,layout.get("icon-ignore-placement"),bucket.bucketInstanceId,iconFeatureIndex,collisionGroup.ID)}if(placedGlyphCircles){if(placeText){this.collisionIndex.insertCollisionCircles(placedGlyphCircles.circles,textOverlapMode,layout.get("text-ignore-placement"),bucket.bucketInstanceId,textFeatureIndex,collisionGroup.ID)}if(showCollisionBoxes){const id=bucket.bucketInstanceId;let circleArray=this.collisionCircleArrays[id];if(circleArray===undefined)circleArray=this.collisionCircleArrays[id]=new CollisionCircleArray;for(let i=0;i=0;--i){const symbolIndex=symbolIndexes[i];placeSymbol(bucket.symbolInstances.get(symbolIndex),bucket.collisionArrays[symbolIndex])}}else{for(let i=bucketPart.symbolInstanceStart;i=0){if(autoIndex>=0&&index!==autoIndex){bucket.text.placedSymbolArray.get(index).crossTileID=0}else{bucket.text.placedSymbolArray.get(index).crossTileID=symbolInstance.crossTileID}}}}markUsedOrientation(bucket,orientation,symbolInstance){const horizontal=orientation===performance$1.WritingMode.horizontal||orientation===performance$1.WritingMode.horizontalOnly?orientation:0;const vertical=orientation===performance$1.WritingMode.vertical?orientation:0;const horizontalIndexes=[symbolInstance.leftJustifiedTextSymbolIndex,symbolInstance.centerJustifiedTextSymbolIndex,symbolInstance.rightJustifiedTextSymbolIndex];for(const index of horizontalIndexes){bucket.text.placedSymbolArray.get(index).placedOrientation=horizontal}if(symbolInstance.verticalPlacedTextSymbolIndex){bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).placedOrientation=vertical}}commit(now){this.commitTime=now;this.zoomAtLastRecencyCheck=this.transform.zoom;const prevPlacement=this.prevPlacement;let placementChanged=false;this.prevZoomAdjustment=prevPlacement?prevPlacement.zoomAdjustment(this.transform.zoom):0;const increment=prevPlacement?prevPlacement.symbolFadeChange(now):1;const prevOpacities=prevPlacement?prevPlacement.opacities:{};const prevOffsets=prevPlacement?prevPlacement.variableOffsets:{};const prevOrientations=prevPlacement?prevPlacement.placedOrientations:{};for(const crossTileID in this.placements){const jointPlacement=this.placements[crossTileID];const prevOpacity=prevOpacities[crossTileID];if(prevOpacity){this.opacities[crossTileID]=new JointOpacityState(prevOpacity,increment,jointPlacement.text,jointPlacement.icon);placementChanged=placementChanged||jointPlacement.text!==prevOpacity.text.placed||jointPlacement.icon!==prevOpacity.icon.placed}else{this.opacities[crossTileID]=new JointOpacityState(null,increment,jointPlacement.text,jointPlacement.icon,jointPlacement.skipFade);placementChanged=placementChanged||jointPlacement.text||jointPlacement.icon}}for(const crossTileID in prevOpacities){const prevOpacity=prevOpacities[crossTileID];if(!this.opacities[crossTileID]){const jointOpacity=new JointOpacityState(prevOpacity,increment,false,false);if(!jointOpacity.isHidden()){this.opacities[crossTileID]=jointOpacity;placementChanged=placementChanged||prevOpacity.text.placed||prevOpacity.icon.placed}}}for(const crossTileID in prevOffsets){if(!this.variableOffsets[crossTileID]&&this.opacities[crossTileID]&&!this.opacities[crossTileID].isHidden()){this.variableOffsets[crossTileID]=prevOffsets[crossTileID]}}for(const crossTileID in prevOrientations){if(!this.placedOrientations[crossTileID]&&this.opacities[crossTileID]&&!this.opacities[crossTileID].isHidden()){this.placedOrientations[crossTileID]=prevOrientations[crossTileID]}}if(prevPlacement&&prevPlacement.lastPlacementChangeTime===undefined){throw new Error("Last placement time for previous placement is not defined")}if(placementChanged){this.lastPlacementChangeTime=now}else if(typeof this.lastPlacementChangeTime!=="number"){this.lastPlacementChangeTime=prevPlacement?prevPlacement.lastPlacementChangeTime:now}}updateLayerOpacities(styleLayer,tiles){const seenCrossTileIDs={};for(const tile of tiles){const symbolBucket=tile.getBucket(styleLayer);if(symbolBucket&&tile.latestFeatureIndex&&styleLayer.id===symbolBucket.layerIds[0]){this.updateBucketOpacities(symbolBucket,seenCrossTileIDs,tile.collisionBoxArray)}}}updateBucketOpacities(bucket,seenCrossTileIDs,collisionBoxArray){if(bucket.hasTextData()){bucket.text.opacityVertexArray.clear();bucket.text.hasVisibleVertices=false}if(bucket.hasIconData()){bucket.icon.opacityVertexArray.clear();bucket.icon.hasVisibleVertices=false}if(bucket.hasIconCollisionBoxData())bucket.iconCollisionBox.collisionVertexArray.clear();if(bucket.hasTextCollisionBoxData())bucket.textCollisionBox.collisionVertexArray.clear();const layer=bucket.layers[0];const layout=layer.layout;const duplicateOpacityState=new JointOpacityState(null,0,false,false,true);const textAllowOverlap=layout.get("text-allow-overlap");const iconAllowOverlap=layout.get("icon-allow-overlap");const hasVariablePlacement=layer._unevaluatedLayout.hasValue("text-variable-anchor")||layer._unevaluatedLayout.hasValue("text-variable-anchor-offset");const rotateWithMap=layout.get("text-rotation-alignment")==="map";const pitchWithMap=layout.get("text-pitch-alignment")==="map";const hasIconTextFit=layout.get("icon-text-fit")!=="none";const defaultOpacityState=new JointOpacityState(null,0,textAllowOverlap&&(iconAllowOverlap||!bucket.hasIconData()||layout.get("icon-optional")),iconAllowOverlap&&(textAllowOverlap||!bucket.hasTextData()||layout.get("text-optional")),true);if(!bucket.collisionArrays&&collisionBoxArray&&(bucket.hasIconCollisionBoxData()||bucket.hasTextCollisionBoxData())){bucket.deserializeCollisionBoxes(collisionBoxArray)}const addOpacities=(iconOrText,numVertices,opacity)=>{for(let i=0;i0||numVerticalGlyphVertices>0;const hasIcon=symbolInstance.numIconVertices>0;const placedOrientation=this.placedOrientations[symbolInstance.crossTileID];const horizontalHidden=placedOrientation===performance$1.WritingMode.vertical;const verticalHidden=placedOrientation===performance$1.WritingMode.horizontal||placedOrientation===performance$1.WritingMode.horizontalOnly;if(hasText){const packedOpacity=packOpacity(opacityState.text);const horizontalOpacity=horizontalHidden?PACKED_HIDDEN_OPACITY:packedOpacity;addOpacities(bucket.text,numHorizontalGlyphVertices,horizontalOpacity);const verticalOpacity=verticalHidden?PACKED_HIDDEN_OPACITY:packedOpacity;addOpacities(bucket.text,numVerticalGlyphVertices,verticalOpacity);const symbolHidden=opacityState.text.isHidden();[symbolInstance.rightJustifiedTextSymbolIndex,symbolInstance.centerJustifiedTextSymbolIndex,symbolInstance.leftJustifiedTextSymbolIndex].forEach((index=>{if(index>=0){bucket.text.placedSymbolArray.get(index).hidden=symbolHidden||horizontalHidden?1:0}}));if(symbolInstance.verticalPlacedTextSymbolIndex>=0){bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).hidden=symbolHidden||verticalHidden?1:0}const prevOffset=this.variableOffsets[symbolInstance.crossTileID];if(prevOffset){this.markUsedJustification(bucket,prevOffset.anchor,symbolInstance,placedOrientation)}const prevOrientation=this.placedOrientations[symbolInstance.crossTileID];if(prevOrientation){this.markUsedJustification(bucket,"left",symbolInstance,prevOrientation);this.markUsedOrientation(bucket,prevOrientation,symbolInstance)}}if(hasIcon){const packedOpacity=packOpacity(opacityState.icon);const useHorizontal=!(hasIconTextFit&&symbolInstance.verticalPlacedIconSymbolIndex&&horizontalHidden);if(symbolInstance.placedIconSymbolIndex>=0){const horizontalOpacity=useHorizontal?packedOpacity:PACKED_HIDDEN_OPACITY;addOpacities(bucket.icon,symbolInstance.numIconVertices,horizontalOpacity);bucket.icon.placedSymbolArray.get(symbolInstance.placedIconSymbolIndex).hidden=opacityState.icon.isHidden()}if(symbolInstance.verticalPlacedIconSymbolIndex>=0){const verticalOpacity=!useHorizontal?packedOpacity:PACKED_HIDDEN_OPACITY;addOpacities(bucket.icon,symbolInstance.numVerticalIconVertices,verticalOpacity);bucket.icon.placedSymbolArray.get(symbolInstance.verticalPlacedIconSymbolIndex).hidden=opacityState.icon.isHidden()}}if(bucket.hasIconCollisionBoxData()||bucket.hasTextCollisionBoxData()){const collisionArrays=bucket.collisionArrays[s];if(collisionArrays){let shift=new performance$1.Point(0,0);if(collisionArrays.textBox||collisionArrays.verticalTextBox){let used=true;if(hasVariablePlacement){const variableOffset=this.variableOffsets[crossTileID];if(variableOffset){shift=calculateVariableLayoutShift(variableOffset.anchor,variableOffset.width,variableOffset.height,variableOffset.textOffset,variableOffset.textBoxScale);if(rotateWithMap){shift._rotate(pitchWithMap?this.transform.angle:-this.transform.angle)}}else{used=false}}if(collisionArrays.textBox){updateCollisionVertices(bucket.textCollisionBox.collisionVertexArray,opacityState.text.placed,!used||horizontalHidden,shift.x,shift.y)}if(collisionArrays.verticalTextBox){updateCollisionVertices(bucket.textCollisionBox.collisionVertexArray,opacityState.text.placed,!used||verticalHidden,shift.x,shift.y)}}const verticalIconUsed=Boolean(!verticalHidden&&collisionArrays.verticalIconBox);if(collisionArrays.iconBox){updateCollisionVertices(bucket.iconCollisionBox.collisionVertexArray,opacityState.icon.placed,verticalIconUsed,hasIconTextFit?shift.x:0,hasIconTextFit?shift.y:0)}if(collisionArrays.verticalIconBox){updateCollisionVertices(bucket.iconCollisionBox.collisionVertexArray,opacityState.icon.placed,!verticalIconUsed,hasIconTextFit?shift.x:0,hasIconTextFit?shift.y:0)}}}}bucket.sortFeatures(this.transform.angle);if(this.retainedQueryData[bucket.bucketInstanceId]){this.retainedQueryData[bucket.bucketInstanceId].featureSortOrder=bucket.featureSortOrder}if(bucket.hasTextData()&&bucket.text.opacityVertexBuffer){bucket.text.opacityVertexBuffer.updateData(bucket.text.opacityVertexArray)}if(bucket.hasIconData()&&bucket.icon.opacityVertexBuffer){bucket.icon.opacityVertexBuffer.updateData(bucket.icon.opacityVertexArray)}if(bucket.hasIconCollisionBoxData()&&bucket.iconCollisionBox.collisionVertexBuffer){bucket.iconCollisionBox.collisionVertexBuffer.updateData(bucket.iconCollisionBox.collisionVertexArray)}if(bucket.hasTextCollisionBoxData()&&bucket.textCollisionBox.collisionVertexBuffer){bucket.textCollisionBox.collisionVertexBuffer.updateData(bucket.textCollisionBox.collisionVertexArray)}if(bucket.text.opacityVertexArray.length!==bucket.text.layoutVertexArray.length/4)throw new Error(`bucket.text.opacityVertexArray.length (= ${bucket.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${bucket.text.layoutVertexArray.length}) / 4`);if(bucket.icon.opacityVertexArray.length!==bucket.icon.layoutVertexArray.length/4)throw new Error(`bucket.icon.opacityVertexArray.length (= ${bucket.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${bucket.icon.layoutVertexArray.length}) / 4`);if(bucket.bucketInstanceId in this.collisionCircleArrays){const instance=this.collisionCircleArrays[bucket.bucketInstanceId];bucket.placementInvProjMatrix=instance.invProjMatrix;bucket.placementViewportMatrix=instance.viewportMatrix;bucket.collisionCircleArray=instance.circles;delete this.collisionCircleArrays[bucket.bucketInstanceId]}}symbolFadeChange(now){return this.fadeDuration===0?1:(now-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(zoom){return Math.max(0,(this.transform.zoom-zoom)/1.5)}hasTransitions(now){return this.stale||now-this.lastPlacementChangeTimenow}setStale(){this.stale=true}}function updateCollisionVertices(collisionVertexArray,placed,notUsed,shiftX,shiftY){collisionVertexArray.emplaceBack(placed?1:0,notUsed?1:0,shiftX||0,shiftY||0);collisionVertexArray.emplaceBack(placed?1:0,notUsed?1:0,shiftX||0,shiftY||0);collisionVertexArray.emplaceBack(placed?1:0,notUsed?1:0,shiftX||0,shiftY||0);collisionVertexArray.emplaceBack(placed?1:0,notUsed?1:0,shiftX||0,shiftY||0)}const shift25=Math.pow(2,25);const shift24=Math.pow(2,24);const shift17=Math.pow(2,17);const shift16=Math.pow(2,16);const shift9=Math.pow(2,9);const shift8=Math.pow(2,8);const shift1=Math.pow(2,1);function packOpacity(opacityState){if(opacityState.opacity===0&&!opacityState.placed){return 0}else if(opacityState.opacity===1&&opacityState.placed){return 4294967295}const targetBit=opacityState.placed?1:0;const opacityBits=Math.floor(opacityState.opacity*127);return opacityBits*shift25+targetBit*shift24+opacityBits*shift17+targetBit*shift16+opacityBits*shift9+targetBit*shift8+opacityBits*shift1+targetBit}const PACKED_HIDDEN_OPACITY=0;class LayerPlacement{constructor(styleLayer){this._sortAcrossTiles=styleLayer.layout.get("symbol-z-order")!=="viewport-y"&&!styleLayer.layout.get("symbol-sort-key").isConstant();this._currentTileIndex=0;this._currentPartIndex=0;this._seenCrossTileIDs={};this._bucketParts=[]}continuePlacement(tiles,placement,showCollisionBoxes,styleLayer,shouldPausePlacement){const bucketParts=this._bucketParts;while(this._currentTileIndexa.sortKey-b.sortKey))}while(this._currentPartIndexthis._forceFullPlacement?false:browser.now()-startTime>2;while(this._currentPlacementIndex>=0){const layerId=order[this._currentPlacementIndex];const layer=layers[layerId];const placementZoom=this.placement.collisionIndex.transform.zoom;if(layer.type==="symbol"&&(!layer.minzoom||layer.minzoom<=placementZoom)&&(!layer.maxzoom||layer.maxzoom>placementZoom)){if(!this._inProgressLayer){this._inProgressLayer=new LayerPlacement(layer)}const pausePlacement=this._inProgressLayer.continuePlacement(layerTiles[layer.source],this.placement,this._showCollisionBoxes,layer,shouldPausePlacement);if(pausePlacement){return}delete this._inProgressLayer}this._currentPlacementIndex--}this._done=true}commit(now){this.placement.commit(now);return this.placement}}const roundingFactor=512/performance$1.EXTENT/2;const KDBUSH_THRESHHOLD=128;class TileLayerIndex{constructor(tileID,symbolInstances,bucketInstanceId){this.tileID=tileID;this.bucketInstanceId=bucketInstanceId;this._symbolsByKey={};const symbolInstancesByKey=new Map;for(let i=0;i({x:Math.floor(symbolInstance.anchorX*roundingFactor),y:Math.floor(symbolInstance.anchorY*roundingFactor)})));const crossTileIDs=symbols.map((v=>v.crossTileID));const entry={positions:positions,crossTileIDs:crossTileIDs};if(entry.positions.length>KDBUSH_THRESHHOLD){const index=new performance$1.KDBush(entry.positions.length,16,Uint16Array);for(const{x:x,y:y}of entry.positions)index.add(x,y);index.finish();delete entry.positions;entry.index=index}this._symbolsByKey[key]=entry}}getScaledCoordinates(symbolInstance,childTileID){const{x:localX,y:localY,z:localZ}=this.tileID.canonical;const{x:x,y:y,z:z}=childTileID.canonical;const zDifference=z-localZ;const scale=roundingFactor/Math.pow(2,zDifference);const xWorld=(x*performance$1.EXTENT+symbolInstance.anchorX)*scale;const yWorld=(y*performance$1.EXTENT+symbolInstance.anchorY)*scale;const xOffset=localX*performance$1.EXTENT*roundingFactor;const yOffset=localY*performance$1.EXTENT*roundingFactor;const result={x:Math.floor(xWorld-xOffset),y:Math.floor(yWorld-yOffset)};return result}findMatches(symbolInstances,newTileID,zoomCrossTileIDs){const tolerance=this.tileID.canonical.zcrossTileIDs))}}class CrossTileIDs{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class CrossTileSymbolLayerIndex{constructor(){this.indexes={};this.usedCrossTileIDs={};this.lng=0}handleWrapJump(lng){const wrapDelta=Math.round((lng-this.lng)/360);if(wrapDelta!==0){for(const zoom in this.indexes){const zoomIndexes=this.indexes[zoom];const newZoomIndex={};for(const key in zoomIndexes){const index=zoomIndexes[key];index.tileID=index.tileID.unwrapTo(index.tileID.wrap+wrapDelta);newZoomIndex[index.tileID.key]=index}this.indexes[zoom]=newZoomIndex}}this.lng=lng}addBucket(tileID,bucket,crossTileIDs){if(this.indexes[tileID.overscaledZ]&&this.indexes[tileID.overscaledZ][tileID.key]){if(this.indexes[tileID.overscaledZ][tileID.key].bucketInstanceId===bucket.bucketInstanceId){return false}else{this.removeBucketCrossTileIDs(tileID.overscaledZ,this.indexes[tileID.overscaledZ][tileID.key])}}for(let i=0;itileID.overscaledZ){for(const id in zoomIndexes){const childIndex=zoomIndexes[id];if(childIndex.tileID.isChildOf(tileID)){childIndex.findMatches(bucket.symbolInstances,tileID,zoomCrossTileIDs)}}}else{const parentCoord=tileID.scaledTo(Number(zoom));const parentIndex=zoomIndexes[parentCoord.key];if(parentIndex){parentIndex.findMatches(bucket.symbolInstances,tileID,zoomCrossTileIDs)}}}for(let i=0;i{usedLayerMap[usedLayer]=true}));for(const layerId in this.layerIndexes){if(!usedLayerMap[layerId]){delete this.layerIndexes[layerId]}}}}const emitValidationErrors=(evented,errors)=>performance$1.emitValidationErrors(evented,errors&&errors.filter((error=>error.identifier!=="source.canvas")));const empty=performance$1.emptyStyle();class Style extends performance$1.Evented{constructor(map,options={}){super();this._rtlTextPluginStateChange=()=>{for(const id in this.sourceCaches){const sourceType=this.sourceCaches[id].getSource().type;if(sourceType==="vector"||sourceType==="geojson"){this.sourceCaches[id].reload()}}};this.map=map;this.dispatcher=new Dispatcher(getGlobalWorkerPool(),map._getMapId());this.dispatcher.registerMessageHandler("getGlyphs",((mapId,params)=>this.getGlyphs(mapId,params)));this.dispatcher.registerMessageHandler("getImages",((mapId,params)=>this.getImages(mapId,params)));this.imageManager=new ImageManager;this.imageManager.setEventedParent(this);this.glyphManager=new GlyphManager(map._requestManager,options.localIdeographFontFamily);this.lineAtlas=new LineAtlas(256,512);this.crossTileSymbolIndex=new CrossTileSymbolIndex;this._spritesImagesIds={};this._layers={};this._order=[];this.sourceCaches={};this.zoomHistory=new performance$1.ZoomHistory;this._loaded=false;this._availableImages=[];this._resetUpdates();this.dispatcher.broadcast("setReferrer",performance$1.getReferrer());rtlMainThreadPluginFactory().on("pluginStateChange",this._rtlTextPluginStateChange);this.on("data",(event=>{if(event.dataType!=="source"||event.sourceDataType!=="metadata"){return}const sourceCache=this.sourceCaches[event.sourceId];if(!sourceCache){return}const source=sourceCache.getSource();if(!source||!source.vectorLayerIds){return}for(const layerId in this._layers){const layer=this._layers[layerId];if(layer.source===source.id){this._validateLayer(layer)}}}))}loadURL(url,options={},previousStyle){this.fire(new performance$1.Event("dataloading",{dataType:"style"}));options.validate=typeof options.validate==="boolean"?options.validate:true;const request=this.map._requestManager.transformRequest(url,ResourceType.Style);this._loadStyleRequest=new AbortController;performance$1.getJSON(request,this._loadStyleRequest).then((response=>{this._loadStyleRequest=null;this._load(response.data,options,previousStyle)})).catch((error=>{this._loadStyleRequest=null;if(error){this.fire(new performance$1.ErrorEvent(error))}}))}loadJSON(json,options={},previousStyle){this.fire(new performance$1.Event("dataloading",{dataType:"style"}));this._frameRequest=new AbortController;browser.frameAsync(this._frameRequest).then((()=>{this._frameRequest=null;options.validate=options.validate!==false;this._load(json,options,previousStyle)})).catch((()=>{}))}loadEmpty(){this.fire(new performance$1.Event("dataloading",{dataType:"style"}));this._load(empty,{validate:false})}_load(json,options,previousStyle){var _a;const nextState=options.transformStyle?options.transformStyle(previousStyle,json):json;if(options.validate&&emitValidationErrors(this,performance$1.validateStyle(nextState))){return}this._loaded=true;this.stylesheet=nextState;for(const id in nextState.sources){this.addSource(id,nextState.sources[id],{validate:false})}if(nextState.sprite){this._loadSprite(nextState.sprite)}else{this.imageManager.setLoaded(true)}this.glyphManager.setURL(nextState.glyphs);this._createLayers();this.light=new Light(this.stylesheet.light);this.map.setTerrain((_a=this.stylesheet.terrain)!==null&&_a!==void 0?_a:null);this.fire(new performance$1.Event("data",{dataType:"style"}));this.fire(new performance$1.Event("style.load"))}_createLayers(){const dereferencedLayers=performance$1.derefLayers(this.stylesheet.layers);this.dispatcher.broadcast("setLayers",dereferencedLayers);this._order=dereferencedLayers.map((layer=>layer.id));this._layers={};this._serializedLayers=null;for(const layer of dereferencedLayers){const styledLayer=performance$1.createStyleLayer(layer);styledLayer.setEventedParent(this,{layer:{id:layer.id}});this._layers[layer.id]=styledLayer}}_loadSprite(sprite,isUpdate=false,completion=undefined){this.imageManager.setLoaded(false);this._spriteRequest=new AbortController;let err;loadSprite(sprite,this.map._requestManager,this.map.getPixelRatio(),this._spriteRequest).then((images=>{this._spriteRequest=null;if(images){for(const spriteId in images){this._spritesImagesIds[spriteId]=[];const imagesToRemove=this._spritesImagesIds[spriteId]?this._spritesImagesIds[spriteId].filter((id=>!(id in images))):[];for(const id of imagesToRemove){this.imageManager.removeImage(id);this._changedImages[id]=true}for(const id in images[spriteId]){const imageId=spriteId==="default"?id:`${spriteId}:${id}`;this._spritesImagesIds[spriteId].push(imageId);if(imageId in this.imageManager.images){this.imageManager.updateImage(imageId,images[spriteId][id],false)}else{this.imageManager.addImage(imageId,images[spriteId][id])}if(isUpdate){this._changedImages[imageId]=true}}}}})).catch((error=>{this._spriteRequest=null;err=error;this.fire(new performance$1.ErrorEvent(err))})).finally((()=>{this.imageManager.setLoaded(true);this._availableImages=this.imageManager.listImages();if(isUpdate){this._changed=true}this.dispatcher.broadcast("setImages",this._availableImages);this.fire(new performance$1.Event("data",{dataType:"style"}));if(completion){completion(err)}}))}_unloadSprite(){for(const id of Object.values(this._spritesImagesIds).flat()){this.imageManager.removeImage(id);this._changedImages[id]=true}this._spritesImagesIds={};this._availableImages=this.imageManager.listImages();this._changed=true;this.dispatcher.broadcast("setImages",this._availableImages);this.fire(new performance$1.Event("data",{dataType:"style"}))}_validateLayer(layer){const sourceCache=this.sourceCaches[layer.source];if(!sourceCache){return}const sourceLayer=layer.sourceLayer;if(!sourceLayer){return}const source=sourceCache.getSource();if(source.type==="geojson"||source.vectorLayerIds&&source.vectorLayerIds.indexOf(sourceLayer)===-1){this.fire(new performance$1.ErrorEvent(new Error(`Source layer "${sourceLayer}" `+`does not exist on source "${source.id}" `+`as specified by style layer "${layer.id}".`)))}}loaded(){if(!this._loaded)return false;if(Object.keys(this._updatedSources).length)return false;for(const id in this.sourceCaches)if(!this.sourceCaches[id].loaded())return false;if(!this.imageManager.isLoaded())return false;return true}_serializeByIds(ids){const serializedLayersDictionary=this._serializedAllLayers();if(!ids||ids.length===0){return Object.values(serializedLayersDictionary)}const serializedLayers=[];for(const id of ids){if(serializedLayersDictionary[id]){serializedLayers.push(serializedLayersDictionary[id])}}return serializedLayers}_serializedAllLayers(){let serializedLayers=this._serializedLayers;if(serializedLayers){return serializedLayers}serializedLayers=this._serializedLayers={};const allLayerIds=Object.keys(this._layers);for(const layerId of allLayerIds){const layer=this._layers[layerId];if(layer.type!=="custom"){serializedLayers[layerId]=layer.serialize()}}return serializedLayers}hasTransitions(){if(this.light&&this.light.hasTransition()){return true}for(const id in this.sourceCaches){if(this.sourceCaches[id].hasTransition()){return true}}for(const id in this._layers){if(this._layers[id].hasTransition()){return true}}return false}_checkLoaded(){if(!this._loaded){throw new Error("Style is not done loading.")}}update(parameters){if(!this._loaded){return}const changed=this._changed;if(this._changed){const updatedIds=Object.keys(this._updatedLayers);const removedIds=Object.keys(this._removedLayers);if(updatedIds.length||removedIds.length){this._updateWorkerLayers(updatedIds,removedIds)}for(const id in this._updatedSources){const action=this._updatedSources[id];if(action==="reload"){this._reloadSource(id)}else if(action==="clear"){this._clearSource(id)}else{throw new Error(`Invalid action ${action}`)}}this._updateTilesForChangedImages();this._updateTilesForChangedGlyphs();for(const id in this._updatedPaintProps){this._layers[id].updateTransitions(parameters)}this.light.updateTransitions(parameters);this._resetUpdates()}const sourcesUsedBefore={};for(const sourceId in this.sourceCaches){const sourceCache=this.sourceCaches[sourceId];sourcesUsedBefore[sourceId]=sourceCache.used;sourceCache.used=false}for(const layerId of this._order){const layer=this._layers[layerId];layer.recalculate(parameters,this._availableImages);if(!layer.isHidden(parameters.zoom)&&layer.source){this.sourceCaches[layer.source].used=true}}for(const sourceId in sourcesUsedBefore){const sourceCache=this.sourceCaches[sourceId];if(sourcesUsedBefore[sourceId]!==sourceCache.used){sourceCache.fire(new performance$1.Event("data",{sourceDataType:"visibility",dataType:"source",sourceId:sourceId}))}}this.light.recalculate(parameters);this.z=parameters.zoom;if(changed){this.fire(new performance$1.Event("data",{dataType:"style"}))}}_updateTilesForChangedImages(){const changedImages=Object.keys(this._changedImages);if(changedImages.length){for(const name in this.sourceCaches){this.sourceCaches[name].reloadTilesForDependencies(["icons","patterns"],changedImages)}this._changedImages={}}}_updateTilesForChangedGlyphs(){if(this._glyphsDidChange){for(const name in this.sourceCaches){this.sourceCaches[name].reloadTilesForDependencies(["glyphs"],[""])}this._glyphsDidChange=false}}_updateWorkerLayers(updatedIds,removedIds){this.dispatcher.broadcast("updateLayers",{layers:this._serializeByIds(updatedIds),removedIds:removedIds})}_resetUpdates(){this._changed=false;this._updatedLayers={};this._removedLayers={};this._updatedSources={};this._updatedPaintProps={};this._changedImages={};this._glyphsDidChange=false}setState(nextState,options={}){var _a;this._checkLoaded();const serializedStyle=this.serialize();nextState=options.transformStyle?options.transformStyle(serializedStyle,nextState):nextState;const validate=(_a=options.validate)!==null&&_a!==void 0?_a:true;if(validate&&emitValidationErrors(this,performance$1.validateStyle(nextState)))return false;nextState=performance$1.clone$1(nextState);nextState.layers=performance$1.derefLayers(nextState.layers);const changes=performance$1.diffStyles(serializedStyle,nextState);const operations=this._getOperationsToPerform(changes);if(operations.unimplemented.length>0){throw new Error(`Unimplemented: ${operations.unimplemented.join(", ")}.`)}if(operations.operations.length===0){return false}for(const styleChangeOperation of operations.operations){styleChangeOperation()}this.stylesheet=nextState;this._serializedLayers=null;return true}_getOperationsToPerform(diff){const operations=[];const unimplemented=[];for(const op of diff){switch(op.command){case"setCenter":case"setZoom":case"setBearing":case"setPitch":continue;case"addLayer":operations.push((()=>this.addLayer.apply(this,op.args)));break;case"removeLayer":operations.push((()=>this.removeLayer.apply(this,op.args)));break;case"setPaintProperty":operations.push((()=>this.setPaintProperty.apply(this,op.args)));break;case"setLayoutProperty":operations.push((()=>this.setLayoutProperty.apply(this,op.args)));break;case"setFilter":operations.push((()=>this.setFilter.apply(this,op.args)));break;case"addSource":operations.push((()=>this.addSource.apply(this,op.args)));break;case"removeSource":operations.push((()=>this.removeSource.apply(this,op.args)));break;case"setLayerZoomRange":operations.push((()=>this.setLayerZoomRange.apply(this,op.args)));break;case"setLight":operations.push((()=>this.setLight.apply(this,op.args)));break;case"setGeoJSONSourceData":operations.push((()=>this.setGeoJSONSourceData.apply(this,op.args)));break;case"setGlyphs":operations.push((()=>this.setGlyphs.apply(this,op.args)));break;case"setSprite":operations.push((()=>this.setSprite.apply(this,op.args)));break;case"setTerrain":operations.push((()=>this.map.setTerrain.apply(this,op.args)));break;case"setTransition":operations.push((()=>{}));break;default:unimplemented.push(op.command);break}}return{operations:operations,unimplemented:unimplemented}}addImage(id,image){if(this.getImage(id)){return this.fire(new performance$1.ErrorEvent(new Error(`An image named "${id}" already exists.`)))}this.imageManager.addImage(id,image);this._afterImageUpdated(id)}updateImage(id,image){this.imageManager.updateImage(id,image)}getImage(id){return this.imageManager.getImage(id)}removeImage(id){if(!this.getImage(id)){return this.fire(new performance$1.ErrorEvent(new Error(`An image named "${id}" does not exist.`)))}this.imageManager.removeImage(id);this._afterImageUpdated(id)}_afterImageUpdated(id){this._availableImages=this.imageManager.listImages();this._changedImages[id]=true;this._changed=true;this.dispatcher.broadcast("setImages",this._availableImages);this.fire(new performance$1.Event("data",{dataType:"style"}))}listImages(){this._checkLoaded();return this.imageManager.listImages()}addSource(id,source,options={}){this._checkLoaded();if(this.sourceCaches[id]!==undefined){throw new Error(`Source "${id}" already exists.`)}if(!source.type){throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(source).join(", ")}.`)}const builtIns=["vector","raster","geojson","video","image"];const shouldValidate=builtIns.indexOf(source.type)>=0;if(shouldValidate&&this._validate(performance$1.validateStyle.source,`sources.${id}`,source,null,options))return;if(this.map&&this.map._collectResourceTiming)source.collectResourceTiming=true;const sourceCache=this.sourceCaches[id]=new SourceCache(id,source,this.dispatcher);sourceCache.style=this;sourceCache.setEventedParent(this,(()=>({isSourceLoaded:sourceCache.loaded(),source:sourceCache.serialize(),sourceId:id})));sourceCache.onAdd(this.map);this._changed=true}removeSource(id){this._checkLoaded();if(this.sourceCaches[id]===undefined){throw new Error("There is no source with this ID")}for(const layerId in this._layers){if(this._layers[layerId].source===id){return this.fire(new performance$1.ErrorEvent(new Error(`Source "${id}" cannot be removed while layer "${layerId}" is using it.`)))}}const sourceCache=this.sourceCaches[id];delete this.sourceCaches[id];delete this._updatedSources[id];sourceCache.fire(new performance$1.Event("data",{sourceDataType:"metadata",dataType:"source",sourceId:id}));sourceCache.setEventedParent(null);sourceCache.onRemove(this.map);this._changed=true}setGeoJSONSourceData(id,data){this._checkLoaded();if(this.sourceCaches[id]===undefined)throw new Error(`There is no source with this ID=${id}`);const geojsonSource=this.sourceCaches[id].getSource();if(geojsonSource.type!=="geojson")throw new Error(`geojsonSource.type is ${geojsonSource.type}, which is !== 'geojson`);geojsonSource.setData(data);this._changed=true}getSource(id){return this.sourceCaches[id]&&this.sourceCaches[id].getSource()}addLayer(layerObject,before,options={}){this._checkLoaded();const id=layerObject.id;if(this.getLayer(id)){this.fire(new performance$1.ErrorEvent(new Error(`Layer "${id}" already exists on this map.`)));return}let layer;if(layerObject.type==="custom"){if(emitValidationErrors(this,performance$1.validateCustomStyleLayer(layerObject)))return;layer=performance$1.createStyleLayer(layerObject)}else{if("source"in layerObject&&typeof layerObject.source==="object"){this.addSource(id,layerObject.source);layerObject=performance$1.clone$1(layerObject);layerObject=performance$1.extend(layerObject,{source:id})}if(this._validate(performance$1.validateStyle.layer,`layers.${id}`,layerObject,{arrayIndex:-1},options))return;layer=performance$1.createStyleLayer(layerObject);this._validateLayer(layer);layer.setEventedParent(this,{layer:{id:id}})}const index=before?this._order.indexOf(before):this._order.length;if(before&&index===-1){this.fire(new performance$1.ErrorEvent(new Error(`Cannot add layer "${id}" before non-existing layer "${before}".`)));return}this._order.splice(index,0,id);this._layerOrderChanged=true;this._layers[id]=layer;if(this._removedLayers[id]&&layer.source&&layer.type!=="custom"){const removed=this._removedLayers[id];delete this._removedLayers[id];if(removed.type!==layer.type){this._updatedSources[layer.source]="clear"}else{this._updatedSources[layer.source]="reload";this.sourceCaches[layer.source].pause()}}this._updateLayer(layer);if(layer.onAdd){layer.onAdd(this.map)}}moveLayer(id,before){this._checkLoaded();this._changed=true;const layer=this._layers[id];if(!layer){this.fire(new performance$1.ErrorEvent(new Error(`The layer '${id}' does not exist in the map's style and cannot be moved.`)));return}if(id===before){return}const index=this._order.indexOf(id);this._order.splice(index,1);const newIndex=before?this._order.indexOf(before):this._order.length;if(before&&newIndex===-1){this.fire(new performance$1.ErrorEvent(new Error(`Cannot move layer "${id}" before non-existing layer "${before}".`)));return}this._order.splice(newIndex,0,id);this._layerOrderChanged=true}removeLayer(id){this._checkLoaded();const layer=this._layers[id];if(!layer){this.fire(new performance$1.ErrorEvent(new Error(`Cannot remove non-existing layer "${id}".`)));return}layer.setEventedParent(null);const index=this._order.indexOf(id);this._order.splice(index,1);this._layerOrderChanged=true;this._changed=true;this._removedLayers[id]=layer;delete this._layers[id];if(this._serializedLayers){delete this._serializedLayers[id]}delete this._updatedLayers[id];delete this._updatedPaintProps[id];if(layer.onRemove){layer.onRemove(this.map)}}getLayer(id){return this._layers[id]}getLayersOrder(){return[...this._order]}hasLayer(id){return id in this._layers}setLayerZoomRange(layerId,minzoom,maxzoom){this._checkLoaded();const layer=this.getLayer(layerId);if(!layer){this.fire(new performance$1.ErrorEvent(new Error(`Cannot set the zoom range of non-existing layer "${layerId}".`)));return}if(layer.minzoom===minzoom&&layer.maxzoom===maxzoom)return;if(minzoom!=null){layer.minzoom=minzoom}if(maxzoom!=null){layer.maxzoom=maxzoom}this._updateLayer(layer)}setFilter(layerId,filter,options={}){this._checkLoaded();const layer=this.getLayer(layerId);if(!layer){this.fire(new performance$1.ErrorEvent(new Error(`Cannot filter non-existing layer "${layerId}".`)));return}if(performance$1.deepEqual(layer.filter,filter)){return}if(filter===null||filter===undefined){layer.filter=undefined;this._updateLayer(layer);return}if(this._validate(performance$1.validateStyle.filter,`layers.${layer.id}.filter`,filter,null,options)){return}layer.filter=performance$1.clone$1(filter);this._updateLayer(layer)}getFilter(layer){return performance$1.clone$1(this.getLayer(layer).filter)}setLayoutProperty(layerId,name,value,options={}){this._checkLoaded();const layer=this.getLayer(layerId);if(!layer){this.fire(new performance$1.ErrorEvent(new Error(`Cannot style non-existing layer "${layerId}".`)));return}if(performance$1.deepEqual(layer.getLayoutProperty(name),value))return;layer.setLayoutProperty(name,value,options);this._updateLayer(layer)}getLayoutProperty(layerId,name){const layer=this.getLayer(layerId);if(!layer){this.fire(new performance$1.ErrorEvent(new Error(`Cannot get style of non-existing layer "${layerId}".`)));return}return layer.getLayoutProperty(name)}setPaintProperty(layerId,name,value,options={}){this._checkLoaded();const layer=this.getLayer(layerId);if(!layer){this.fire(new performance$1.ErrorEvent(new Error(`Cannot style non-existing layer "${layerId}".`)));return}if(performance$1.deepEqual(layer.getPaintProperty(name),value))return;const requiresRelayout=layer.setPaintProperty(name,value,options);if(requiresRelayout){this._updateLayer(layer)}this._changed=true;this._updatedPaintProps[layerId]=true}getPaintProperty(layer,name){return this.getLayer(layer).getPaintProperty(name)}setFeatureState(target,state){this._checkLoaded();const sourceId=target.source;const sourceLayer=target.sourceLayer;const sourceCache=this.sourceCaches[sourceId];if(sourceCache===undefined){this.fire(new performance$1.ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`)));return}const sourceType=sourceCache.getSource().type;if(sourceType==="geojson"&&sourceLayer){this.fire(new performance$1.ErrorEvent(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));return}if(sourceType==="vector"&&!sourceLayer){this.fire(new performance$1.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));return}if(target.id===undefined){this.fire(new performance$1.ErrorEvent(new Error("The feature id parameter must be provided.")))}sourceCache.setFeatureState(sourceLayer,target.id,state)}removeFeatureState(target,key){this._checkLoaded();const sourceId=target.source;const sourceCache=this.sourceCaches[sourceId];if(sourceCache===undefined){this.fire(new performance$1.ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`)));return}const sourceType=sourceCache.getSource().type;const sourceLayer=sourceType==="vector"?target.sourceLayer:undefined;if(sourceType==="vector"&&!sourceLayer){this.fire(new performance$1.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));return}if(key&&(typeof target.id!=="string"&&typeof target.id!=="number")){this.fire(new performance$1.ErrorEvent(new Error("A feature id is required to remove its specific state property.")));return}sourceCache.removeFeatureState(sourceLayer,target.id,key)}getFeatureState(target){this._checkLoaded();const sourceId=target.source;const sourceLayer=target.sourceLayer;const sourceCache=this.sourceCaches[sourceId];if(sourceCache===undefined){this.fire(new performance$1.ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`)));return}const sourceType=sourceCache.getSource().type;if(sourceType==="vector"&&!sourceLayer){this.fire(new performance$1.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));return}if(target.id===undefined){this.fire(new performance$1.ErrorEvent(new Error("The feature id parameter must be provided.")))}return sourceCache.getFeatureState(sourceLayer,target.id)}getTransition(){return performance$1.extend({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)}serialize(){if(!this._loaded)return;const sources=performance$1.mapObject(this.sourceCaches,(source=>source.serialize()));const layers=this._serializeByIds(this._order);const terrain=this.map.getTerrain()||undefined;const myStyleSheet=this.stylesheet;return performance$1.filterObject({version:myStyleSheet.version,name:myStyleSheet.name,metadata:myStyleSheet.metadata,light:myStyleSheet.light,center:myStyleSheet.center,zoom:myStyleSheet.zoom,bearing:myStyleSheet.bearing,pitch:myStyleSheet.pitch,sprite:myStyleSheet.sprite,glyphs:myStyleSheet.glyphs,transition:myStyleSheet.transition,sources:sources,layers:layers,terrain:terrain},(value=>value!==undefined))}_updateLayer(layer){this._updatedLayers[layer.id]=true;if(layer.source&&!this._updatedSources[layer.source]&&this.sourceCaches[layer.source].getSource().type!=="raster"){this._updatedSources[layer.source]="reload";this.sourceCaches[layer.source].pause()}this._serializedLayers=null;this._changed=true}_flattenAndSortRenderedFeatures(sourceResults){const isLayer3D=layerId=>this._layers[layerId].type==="fill-extrusion";const layerIndex={};const features3D=[];for(let l=this._order.length-1;l>=0;l--){const layerId=this._order[l];if(isLayer3D(layerId)){layerIndex[layerId]=l;for(const sourceResult of sourceResults){const layerFeatures=sourceResult[layerId];if(layerFeatures){for(const featureWrapper of layerFeatures){features3D.push(featureWrapper)}}}}}features3D.sort(((a,b)=>b.intersectionZ-a.intersectionZ));const features=[];for(let l=this._order.length-1;l>=0;l--){const layerId=this._order[l];if(isLayer3D(layerId)){for(let i=features3D.length-1;i>=0;i--){const topmost3D=features3D[i].feature;if(layerIndex[topmost3D.layer.id]sourceCache.getTileByID(id))).sort(((a,b)=>b.tileID.overscaledZ-a.tileID.overscaledZ||(a.tileID.isLessThan(b.tileID)?-1:1)))}const layerBucketsChanged=this.crossTileSymbolIndex.addLayer(styleLayer,layerTiles[styleLayer.source],transform.center.lng);symbolBucketsChanged=symbolBucketsChanged||layerBucketsChanged}this.crossTileSymbolIndex.pruneUnusedLayers(this._order);forceFullPlacement=forceFullPlacement||this._layerOrderChanged||fadeDuration===0;if(forceFullPlacement||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(browser.now(),transform.zoom)){this.pauseablePlacement=new PauseablePlacement(transform,this.map.terrain,this._order,forceFullPlacement,showCollisionBoxes,fadeDuration,crossSourceCollisions,this.placement);this._layerOrderChanged=false}if(this.pauseablePlacement.isDone()){this.placement.setStale()}else{this.pauseablePlacement.continuePlacement(this._order,this._layers,layerTiles);if(this.pauseablePlacement.isDone()){this.placement=this.pauseablePlacement.commit(browser.now());placementCommitted=true}if(symbolBucketsChanged){this.pauseablePlacement.placement.setStale()}}if(placementCommitted||symbolBucketsChanged){for(const layerID of this._order){const styleLayer=this._layers[layerID];if(styleLayer.type!=="symbol")continue;this.placement.updateLayerOpacities(styleLayer,layerTiles[styleLayer.source])}}const needsRerender=!this.pauseablePlacement.isDone()||this.placement.hasTransitions(browser.now());return needsRerender}_releaseSymbolFadeTiles(){for(const id in this.sourceCaches){this.sourceCaches[id].releaseSymbolFadeTiles()}}getImages(mapId,params){return performance$1.__awaiter(this,void 0,void 0,(function*(){const images=yield this.imageManager.getImages(params.icons);this._updateTilesForChangedImages();const sourceCache=this.sourceCaches[params.source];if(sourceCache){sourceCache.setDependencies(params.tileID.key,params.type,params.icons)}return images}))}getGlyphs(mapId,params){return performance$1.__awaiter(this,void 0,void 0,(function*(){const glypgs=yield this.glyphManager.getGlyphs(params.stacks);const sourceCache=this.sourceCaches[params.source];if(sourceCache){sourceCache.setDependencies(params.tileID.key,params.type,[""])}return glypgs}))}getGlyphsUrl(){return this.stylesheet.glyphs||null}setGlyphs(glyphsUrl,options={}){this._checkLoaded();if(glyphsUrl&&this._validate(performance$1.validateStyle.glyphs,"glyphs",glyphsUrl,null,options)){return}this._glyphsDidChange=true;this.stylesheet.glyphs=glyphsUrl;this.glyphManager.entries={};this.glyphManager.setURL(glyphsUrl)}addSprite(id,url,options={},completion){this._checkLoaded();const spriteToAdd=[{id:id,url:url}];const updatedSprite=[...coerceSpriteToArray(this.stylesheet.sprite),...spriteToAdd];if(this._validate(performance$1.validateStyle.sprite,"sprite",updatedSprite,null,options))return;this.stylesheet.sprite=updatedSprite;this._loadSprite(spriteToAdd,true,completion)}removeSprite(id){this._checkLoaded();const internalSpriteRepresentation=coerceSpriteToArray(this.stylesheet.sprite);if(!internalSpriteRepresentation.find((sprite=>sprite.id===id))){this.fire(new performance$1.ErrorEvent(new Error(`Sprite "${id}" doesn't exists on this map.`)));return}if(this._spritesImagesIds[id]){for(const imageId of this._spritesImagesIds[id]){this.imageManager.removeImage(imageId);this._changedImages[imageId]=true}}internalSpriteRepresentation.splice(internalSpriteRepresentation.findIndex((sprite=>sprite.id===id)),1);this.stylesheet.sprite=internalSpriteRepresentation.length>0?internalSpriteRepresentation:undefined;delete this._spritesImagesIds[id];this._availableImages=this.imageManager.listImages();this._changed=true;this.dispatcher.broadcast("setImages",this._availableImages);this.fire(new performance$1.Event("data",{dataType:"style"}))}getSprite(){return coerceSpriteToArray(this.stylesheet.sprite)}setSprite(sprite,options={},completion){this._checkLoaded();if(sprite&&this._validate(performance$1.validateStyle.sprite,"sprite",sprite,null,options)){return}this.stylesheet.sprite=sprite;if(sprite){this._loadSprite(sprite,true,completion)}else{this._unloadSprite();if(completion){completion(null)}}}}var posAttributes=performance$1.createLayout([{name:"a_pos",type:"Int16",components:2}]);var preludeFrag="#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\n";var preludeVert="#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}\n#ifdef TERRAIN3D\nuniform sampler2D u_terrain;uniform float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\n#endif\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\n#ifdef TERRAIN3D\nhighp float d=unpack(texture2D(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\n#else\nreturn 1.0;\n#endif\n}float calculate_visibility(vec4 pos) {\n#ifdef TERRAIN3D\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\n#else\nreturn 1.0;\n#endif\n}float ele(vec2 pos) {\n#ifdef TERRAIN3D\nvec4 rgb=(texture2D(u_terrain,pos)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\n#else\nreturn 0.0;\n#endif\n}float get_elevation(vec2 pos) {\n#ifdef TERRAIN3D\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.0;vec2 f=fract(coord);vec2 c=(floor(coord)+0.5)/(u_terrain_dim+2.0);float d=1.0/(u_terrain_dim+2.0);float tl=ele(c);float tr=ele(c+vec2(d,0.0));float bl=ele(c+vec2(0.0,d));float br=ele(c+vec2(d,d));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\n#else\nreturn 0.0;\n#endif\n}";var backgroundFrag="uniform vec4 u_color;uniform float u_opacity;void main() {gl_FragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var backgroundVert="attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}";var backgroundPatternFrag="uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var backgroundPatternVert="uniform mat4 u_matrix;uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}";var circleFrag="varying vec3 v_data;varying float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);lowp float antialiasblur=v_data.z;float antialiased_blur=-max(blur,antialiasblur);float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));gl_FragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var circleVert="uniform mat4 u_matrix;uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;attribute vec2 a_pos;varying vec3 v_data;varying float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=vec2(mod(a_pos,2.0)*2.0-1.0);vec2 circle_center=floor(a_pos*0.5);float ele=get_elevation(circle_center);v_visibility=calculate_visibility(u_matrix*vec4(circle_center,ele,1.0));if (u_pitch_with_map) {vec2 corner_position=circle_center;if (u_scale_with_map) {corner_position+=extrude*(radius+stroke_width)*u_extrude_scale;} else {vec4 projected_center=u_matrix*vec4(circle_center,0,1);corner_position+=extrude*(radius+stroke_width)*u_extrude_scale*(projected_center.w/u_camera_to_center_distance);}gl_Position=u_matrix*vec4(corner_position,ele,1);} else {gl_Position=u_matrix*vec4(circle_center,ele,1);if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}lowp float antialiasblur=1.0/u_device_pixel_ratio/(radius+stroke_width);v_data=vec3(extrude.x,extrude.y,antialiasblur);}";var clippingMaskFrag="void main() {gl_FragColor=vec4(1.0);}";var clippingMaskVert="attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}";var heatmapFrag="uniform highp float u_intensity;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);gl_FragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var heatmapVert="uniform mat4 u_matrix;uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;attribute vec2 a_pos;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 unscaled_extrude=vec2(mod(a_pos,2.0)*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec4 pos=vec4(floor(a_pos*0.5)+extrude,0,1);gl_Position=u_matrix*pos;}";var heatmapTextureFrag="uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;varying vec2 v_pos;void main() {float t=texture2D(u_image,v_pos).r;vec4 color=texture2D(u_color_ramp,vec2(t,0.5));gl_FragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(0.0);\n#endif\n}";var heatmapTextureVert="uniform mat4 u_matrix;uniform vec2 u_world;attribute vec2 a_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}";var collisionBoxFrag="varying float v_placed;varying float v_notUsed;void main() {float alpha=0.5;gl_FragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {gl_FragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {gl_FragColor*=.1;}}";var collisionBoxVert="attribute vec2 a_pos;attribute vec2 a_anchor_pos;attribute vec2 a_extrude;attribute vec2 a_placed;attribute vec2 a_shift;uniform mat4 u_matrix;uniform vec2 u_extrude_scale;uniform float u_camera_to_center_distance;varying float v_placed;varying float v_notUsed;void main() {vec4 projectedPoint=u_matrix*vec4(a_anchor_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float collision_perspective_ratio=clamp(0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);gl_Position=u_matrix*vec4(a_pos,get_elevation(a_pos),1.0);gl_Position.xy+=(a_extrude+a_shift)*u_extrude_scale*gl_Position.w*collision_perspective_ratio;v_placed=a_placed.x;v_notUsed=a_placed.y;}";var collisionCircleFrag="varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;void main() {float alpha=0.5*min(v_perspective_ratio,1.0);float stroke_radius=0.9*max(v_perspective_ratio,1.0);float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);gl_FragColor=color*alpha*opacity_t;}";var collisionCircleVert="attribute vec2 a_pos;attribute float a_radius;attribute vec2 a_flags;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform vec2 u_viewport_size;uniform float u_camera_to_center_distance;varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;vec3 toTilePosition(vec2 screenPos) {vec4 rayStart=u_inv_matrix*vec4(screenPos,-1.0,1.0);vec4 rayEnd =u_inv_matrix*vec4(screenPos, 1.0,1.0);rayStart.xyz/=rayStart.w;rayEnd.xyz /=rayEnd.w;highp float t=(0.0-rayStart.z)/(rayEnd.z-rayStart.z);return mix(rayStart.xyz,rayEnd.xyz,t);}void main() {vec2 quadCenterPos=a_pos;float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;vec3 tilePos=toTilePosition(quadCenterPos);vec4 clipPos=u_matrix*vec4(tilePos,1.0);highp float camera_to_anchor_distance=clipPos.w;highp float collision_perspective_ratio=clamp(0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_perspective_ratio=collision_perspective_ratio;v_collision=collision;gl_Position=vec4(clipPos.xyz/clipPos.w,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}";var debugFrag="uniform highp vec4 u_color;uniform sampler2D u_overlay;varying vec2 v_uv;void main() {vec4 overlay_color=texture2D(u_overlay,v_uv);gl_FragColor=mix(u_color,overlay_color,overlay_color.a);}";var debugVert="attribute vec2 a_pos;varying vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=u_matrix*vec4(a_pos*u_overlay_scale,get_elevation(a_pos),1);}";var fillFrag="#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_FragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var fillVert="attribute vec2 a_pos;uniform mat4 u_matrix;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);}";var fillOutlineFrag="varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=outline_color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var fillOutlineVert="attribute vec2 a_pos;uniform mat4 u_matrix;uniform vec2 u_world;varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}";var fillOutlinePatternFrag="uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var fillOutlinePatternVert="uniform mat4 u_matrix;uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=u_matrix*vec4(a_pos,0,1);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}";var fillPatternFrag="#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var fillPatternVert="uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}";var fillExtrusionFrag="varying vec4 v_color;void main() {gl_FragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var fillExtrusionVert="uniform mat4 u_matrix;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;attribute vec2 a_pos;attribute vec4 a_normal_ed;\n#ifdef TERRAIN3D\nattribute vec2 a_centroid;\n#endif\nvarying vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);gl_Position=u_matrix*vec4(a_pos,t > 0.0 ? height : base,1);float colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;float directional=clamp(dot(normal/16384.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}";var fillExtrusionPatternFrag="uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);gl_FragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var fillExtrusionPatternVert="uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;attribute vec2 a_pos;attribute vec4 a_normal_ed;\n#ifdef TERRAIN3D\nattribute vec2 a_centroid;\n#endif\nvarying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float z=t > 0.0 ? height : base;gl_Position=u_matrix*vec4(a_pos,z,1);vec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,z*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}";var hillshadePrepareFrag="#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture2D(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack)/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))/pow(2.0,exaggeration+(19.2562-u_zoom));gl_FragColor=clamp(vec4(deriv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var hillshadePrepareVert="uniform mat4 u_matrix;uniform vec2 u_dimension;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}";var hillshadeFrag="uniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;\n#define PI 3.141592653589793\nvoid main() {vec4 pixel=texture2D(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);gl_FragColor=accent_color*(1.0-shade_color.a)+shade_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var hillshadeVert="uniform mat4 u_matrix;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=a_texture_pos/8192.0;}";var lineFrag="uniform lowp float u_device_pixel_ratio;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var lineVert="\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp float v_linesofar;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}";var lineGradientFrag="uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;varying highp vec2 v_uv;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture2D(u_image,v_uv);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var lineGradientVert="\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;attribute float a_uv_x;attribute float a_split_index;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp vec2 v_uv;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}";var linePatternFrag="#ifdef GL_ES\nprecision highp float;\n#endif\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture2D(u_image,pos_a),texture2D(u_image,pos_b),u_fade);gl_FragColor=color*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var linePatternVert="\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}";var lineSDFFrag="uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture2D(u_image,v_tex_a).a;float sdfdist_b=texture2D(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var lineSDFVert="\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}";var rasterFrag="uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;varying vec2 v_pos0;varying vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture2D(u_image0,v_pos0);vec4 color1=texture2D(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);gl_FragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var rasterVert="uniform mat4 u_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos0;varying vec2 v_pos1;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos0=(((a_texture_pos/8192.0)-0.5)/u_buffer_scale )+0.5;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}";var symbolIconFrag="uniform sampler2D u_texture;varying vec2 v_tex;varying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;gl_FragColor=texture2D(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var symbolIconVert="const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;varying vec2 v_tex;varying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,ele,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),ele,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,ele,1.0);float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0),z,1.0);v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float visibility=calculate_visibility(projectedPoint);v_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));}";var symbolSDFFrag="#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;varying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);inner_edge=inner_edge+gamma*gamma_scale;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);if (u_is_halo) {lowp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha=min(smoothstep(halo_edge-gamma_scaled,halo_edge+gamma_scaled,dist),1.0-alpha);}gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var symbolSDFVert="const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;varying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,ele,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),ele,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,ele,1.0);float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset),z,1.0);float gamma_scale=gl_Position.w;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}";var symbolTextAndIconFrag="#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;varying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;gl_FragColor=texture2D(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var symbolTextAndIconVert="const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;varying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,ele,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),ele,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,ele,1.0);float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale),z,1.0);float gamma_scale=gl_Position.w;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}";var terrainDepthFrag="varying float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {gl_FragColor=pack(v_depth);}";var terrainCoordsFrag="precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;varying vec2 v_texture_pos;void main() {vec4 rgba=texture2D(u_texture,v_texture_pos);gl_FragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}";var terrainFrag="uniform sampler2D u_texture;varying vec2 v_texture_pos;void main() {gl_FragColor=texture2D(u_texture,v_texture_pos);}";var terrainVert="attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform float u_ele_delta;varying vec2 v_texture_pos;varying float v_depth;void main() {float extent=8192.0;float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/extent;gl_Position=u_matrix*vec4(a_pos3d.xy,get_elevation(a_pos3d.xy)-ele_delta,1.0);v_depth=gl_Position.z/gl_Position.w;}";const shaders={prelude:compile(preludeFrag,preludeVert),background:compile(backgroundFrag,backgroundVert),backgroundPattern:compile(backgroundPatternFrag,backgroundPatternVert),circle:compile(circleFrag,circleVert),clippingMask:compile(clippingMaskFrag,clippingMaskVert),heatmap:compile(heatmapFrag,heatmapVert),heatmapTexture:compile(heatmapTextureFrag,heatmapTextureVert),collisionBox:compile(collisionBoxFrag,collisionBoxVert),collisionCircle:compile(collisionCircleFrag,collisionCircleVert),debug:compile(debugFrag,debugVert),fill:compile(fillFrag,fillVert),fillOutline:compile(fillOutlineFrag,fillOutlineVert),fillOutlinePattern:compile(fillOutlinePatternFrag,fillOutlinePatternVert),fillPattern:compile(fillPatternFrag,fillPatternVert),fillExtrusion:compile(fillExtrusionFrag,fillExtrusionVert),fillExtrusionPattern:compile(fillExtrusionPatternFrag,fillExtrusionPatternVert),hillshadePrepare:compile(hillshadePrepareFrag,hillshadePrepareVert),hillshade:compile(hillshadeFrag,hillshadeVert),line:compile(lineFrag,lineVert),lineGradient:compile(lineGradientFrag,lineGradientVert),linePattern:compile(linePatternFrag,linePatternVert),lineSDF:compile(lineSDFFrag,lineSDFVert),raster:compile(rasterFrag,rasterVert),symbolIcon:compile(symbolIconFrag,symbolIconVert),symbolSDF:compile(symbolSDFFrag,symbolSDFVert),symbolTextAndIcon:compile(symbolTextAndIconFrag,symbolTextAndIconVert),terrain:compile(terrainFrag,terrainVert),terrainDepth:compile(terrainDepthFrag,terrainVert),terrainCoords:compile(terrainCoordsFrag,terrainVert)};function compile(fragmentSource,vertexSource){const re=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g;const staticAttributes=vertexSource.match(/attribute ([\w]+) ([\w]+)/g);const fragmentUniforms=fragmentSource.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g);const vertexUniforms=vertexSource.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g);const staticUniforms=vertexUniforms?vertexUniforms.concat(fragmentUniforms):fragmentUniforms;const fragmentPragmas={};fragmentSource=fragmentSource.replace(re,((match,operation,precision,type,name)=>{fragmentPragmas[name]=true;if(operation==="define"){return`\n#ifndef HAS_UNIFORM_u_${name}\nvarying ${precision} ${type} ${name};\n#else\nuniform ${precision} ${type} u_${name};\n#endif\n`}else{return`\n#ifdef HAS_UNIFORM_u_${name}\n ${precision} ${type} ${name} = u_${name};\n#endif\n`}}));vertexSource=vertexSource.replace(re,((match,operation,precision,type,name)=>{const attrType=type==="float"?"vec2":"vec4";const unpackType=name.match(/color/)?"color":attrType;if(fragmentPragmas[name]){if(operation==="define"){return`\n#ifndef HAS_UNIFORM_u_${name}\nuniform lowp float u_${name}_t;\nattribute ${precision} ${attrType} a_${name};\nvarying ${precision} ${type} ${name};\n#else\nuniform ${precision} ${type} u_${name};\n#endif\n`}else{if(unpackType==="vec4"){return`\n#ifndef HAS_UNIFORM_u_${name}\n ${name} = a_${name};\n#else\n ${precision} ${type} ${name} = u_${name};\n#endif\n`}else{return`\n#ifndef HAS_UNIFORM_u_${name}\n ${name} = unpack_mix_${unpackType}(a_${name}, u_${name}_t);\n#else\n ${precision} ${type} ${name} = u_${name};\n#endif\n`}}}else{if(operation==="define"){return`\n#ifndef HAS_UNIFORM_u_${name}\nuniform lowp float u_${name}_t;\nattribute ${precision} ${attrType} a_${name};\n#else\nuniform ${precision} ${type} u_${name};\n#endif\n`}else{if(unpackType==="vec4"){return`\n#ifndef HAS_UNIFORM_u_${name}\n ${precision} ${type} ${name} = a_${name};\n#else\n ${precision} ${type} ${name} = u_${name};\n#endif\n`}else{return`\n#ifndef HAS_UNIFORM_u_${name}\n ${precision} ${type} ${name} = unpack_mix_${unpackType}(a_${name}, u_${name}_t);\n#else\n ${precision} ${type} ${name} = u_${name};\n#endif\n`}}}}));return{fragmentSource:fragmentSource,vertexSource:vertexSource,staticAttributes:staticAttributes,staticUniforms:staticUniforms}}class VertexArrayObject{constructor(){this.boundProgram=null;this.boundLayoutVertexBuffer=null;this.boundPaintVertexBuffers=[];this.boundIndexBuffer=null;this.boundVertexOffset=null;this.boundDynamicVertexBuffer=null;this.vao=null}bind(context,program,layoutVertexBuffer,paintVertexBuffers,indexBuffer,vertexOffset,dynamicVertexBuffer,dynamicVertexBuffer2,dynamicVertexBuffer3){this.context=context;let paintBuffersDiffer=this.boundPaintVertexBuffers.length!==paintVertexBuffers.length;for(let i=0;!paintBuffersDiffer&&i({u_depth:new performance$1.Uniform1i(context,locations.u_depth),u_terrain:new performance$1.Uniform1i(context,locations.u_terrain),u_terrain_dim:new performance$1.Uniform1f(context,locations.u_terrain_dim),u_terrain_matrix:new performance$1.UniformMatrix4f(context,locations.u_terrain_matrix),u_terrain_unpack:new performance$1.Uniform4f(context,locations.u_terrain_unpack),u_terrain_exaggeration:new performance$1.Uniform1f(context,locations.u_terrain_exaggeration)});const terrainUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_texture:new performance$1.Uniform1i(context,locations.u_texture),u_ele_delta:new performance$1.Uniform1f(context,locations.u_ele_delta)});const terrainDepthUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_ele_delta:new performance$1.Uniform1f(context,locations.u_ele_delta)});const terrainCoordsUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_texture:new performance$1.Uniform1i(context,locations.u_texture),u_terrain_coords_id:new performance$1.Uniform1f(context,locations.u_terrain_coords_id),u_ele_delta:new performance$1.Uniform1f(context,locations.u_ele_delta)});const terrainUniformValues=(matrix,eleDelta)=>({u_matrix:matrix,u_texture:0,u_ele_delta:eleDelta});const terrainDepthUniformValues=(matrix,eleDelta)=>({u_matrix:matrix,u_ele_delta:eleDelta});const terrainCoordsUniformValues=(matrix,coordsId,eleDelta)=>({u_matrix:matrix,u_terrain_coords_id:coordsId/255,u_texture:0,u_ele_delta:eleDelta});function getTokenizedAttributesAndUniforms(array){const result=[];for(let i=0;i>16,pixelY>>16],u_pixel_coord_lower:[pixelX&65535,pixelY&65535]}}function bgPatternUniformValues(image,crossfade,painter,tile){const imagePosA=painter.imageManager.getPattern(image.from.toString());const imagePosB=painter.imageManager.getPattern(image.to.toString());const{width:width,height:height}=painter.imageManager.getPixelSize();const numTiles=Math.pow(2,tile.tileID.overscaledZ);const tileSizeAtNearestZoom=tile.tileSize*Math.pow(2,painter.transform.tileZoom)/numTiles;const pixelX=tileSizeAtNearestZoom*(tile.tileID.canonical.x+tile.tileID.wrap*numTiles);const pixelY=tileSizeAtNearestZoom*tile.tileID.canonical.y;return{u_image:0,u_pattern_tl_a:imagePosA.tl,u_pattern_br_a:imagePosA.br,u_pattern_tl_b:imagePosB.tl,u_pattern_br_b:imagePosB.br,u_texsize:[width,height],u_mix:crossfade.t,u_pattern_size_a:imagePosA.displaySize,u_pattern_size_b:imagePosB.displaySize,u_scale_a:crossfade.fromScale,u_scale_b:crossfade.toScale,u_tile_units_to_pixels:1/pixelsToTileUnits(tile,1,painter.transform.tileZoom),u_pixel_coord_upper:[pixelX>>16,pixelY>>16],u_pixel_coord_lower:[pixelX&65535,pixelY&65535]}}const fillExtrusionUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_lightpos:new performance$1.Uniform3f(context,locations.u_lightpos),u_lightintensity:new performance$1.Uniform1f(context,locations.u_lightintensity),u_lightcolor:new performance$1.Uniform3f(context,locations.u_lightcolor),u_vertical_gradient:new performance$1.Uniform1f(context,locations.u_vertical_gradient),u_opacity:new performance$1.Uniform1f(context,locations.u_opacity)});const fillExtrusionPatternUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_lightpos:new performance$1.Uniform3f(context,locations.u_lightpos),u_lightintensity:new performance$1.Uniform1f(context,locations.u_lightintensity),u_lightcolor:new performance$1.Uniform3f(context,locations.u_lightcolor),u_vertical_gradient:new performance$1.Uniform1f(context,locations.u_vertical_gradient),u_height_factor:new performance$1.Uniform1f(context,locations.u_height_factor),u_image:new performance$1.Uniform1i(context,locations.u_image),u_texsize:new performance$1.Uniform2f(context,locations.u_texsize),u_pixel_coord_upper:new performance$1.Uniform2f(context,locations.u_pixel_coord_upper),u_pixel_coord_lower:new performance$1.Uniform2f(context,locations.u_pixel_coord_lower),u_scale:new performance$1.Uniform3f(context,locations.u_scale),u_fade:new performance$1.Uniform1f(context,locations.u_fade),u_opacity:new performance$1.Uniform1f(context,locations.u_opacity)});const fillExtrusionUniformValues=(matrix,painter,shouldUseVerticalGradient,opacity)=>{const light=painter.style.light;const _lp=light.properties.get("position");const lightPos=[_lp.x,_lp.y,_lp.z];const lightMat=performance$1.create$1();if(light.properties.get("anchor")==="viewport"){performance$1.fromRotation(lightMat,-painter.transform.angle)}performance$1.transformMat3(lightPos,lightPos,lightMat);const lightColor=light.properties.get("color");return{u_matrix:matrix,u_lightpos:lightPos,u_lightintensity:light.properties.get("intensity"),u_lightcolor:[lightColor.r,lightColor.g,lightColor.b],u_vertical_gradient:+shouldUseVerticalGradient,u_opacity:opacity}};const fillExtrusionPatternUniformValues=(matrix,painter,shouldUseVerticalGradient,opacity,coord,crossfade,tile)=>performance$1.extend(fillExtrusionUniformValues(matrix,painter,shouldUseVerticalGradient,opacity),patternUniformValues(crossfade,painter,tile),{u_height_factor:-Math.pow(2,coord.overscaledZ)/tile.tileSize/8});const fillUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix)});const fillPatternUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_image:new performance$1.Uniform1i(context,locations.u_image),u_texsize:new performance$1.Uniform2f(context,locations.u_texsize),u_pixel_coord_upper:new performance$1.Uniform2f(context,locations.u_pixel_coord_upper),u_pixel_coord_lower:new performance$1.Uniform2f(context,locations.u_pixel_coord_lower),u_scale:new performance$1.Uniform3f(context,locations.u_scale),u_fade:new performance$1.Uniform1f(context,locations.u_fade)});const fillOutlineUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_world:new performance$1.Uniform2f(context,locations.u_world)});const fillOutlinePatternUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_world:new performance$1.Uniform2f(context,locations.u_world),u_image:new performance$1.Uniform1i(context,locations.u_image),u_texsize:new performance$1.Uniform2f(context,locations.u_texsize),u_pixel_coord_upper:new performance$1.Uniform2f(context,locations.u_pixel_coord_upper),u_pixel_coord_lower:new performance$1.Uniform2f(context,locations.u_pixel_coord_lower),u_scale:new performance$1.Uniform3f(context,locations.u_scale),u_fade:new performance$1.Uniform1f(context,locations.u_fade)});const fillUniformValues=matrix=>({u_matrix:matrix});const fillPatternUniformValues=(matrix,painter,crossfade,tile)=>performance$1.extend(fillUniformValues(matrix),patternUniformValues(crossfade,painter,tile));const fillOutlineUniformValues=(matrix,drawingBufferSize)=>({u_matrix:matrix,u_world:drawingBufferSize});const fillOutlinePatternUniformValues=(matrix,painter,crossfade,tile,drawingBufferSize)=>performance$1.extend(fillPatternUniformValues(matrix,painter,crossfade,tile),{u_world:drawingBufferSize});const circleUniforms=(context,locations)=>({u_camera_to_center_distance:new performance$1.Uniform1f(context,locations.u_camera_to_center_distance),u_scale_with_map:new performance$1.Uniform1i(context,locations.u_scale_with_map),u_pitch_with_map:new performance$1.Uniform1i(context,locations.u_pitch_with_map),u_extrude_scale:new performance$1.Uniform2f(context,locations.u_extrude_scale),u_device_pixel_ratio:new performance$1.Uniform1f(context,locations.u_device_pixel_ratio),u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix)});const circleUniformValues=(painter,coord,tile,layer)=>{const transform=painter.transform;let pitchWithMap,extrudeScale;if(layer.paint.get("circle-pitch-alignment")==="map"){const pixelRatio=pixelsToTileUnits(tile,1,transform.zoom);pitchWithMap=true;extrudeScale=[pixelRatio,pixelRatio]}else{pitchWithMap=false;extrudeScale=transform.pixelsToGLUnits}return{u_camera_to_center_distance:transform.cameraToCenterDistance,u_scale_with_map:+(layer.paint.get("circle-pitch-scale")==="map"),u_matrix:painter.translatePosMatrix(coord.posMatrix,tile,layer.paint.get("circle-translate"),layer.paint.get("circle-translate-anchor")),u_pitch_with_map:+pitchWithMap,u_device_pixel_ratio:painter.pixelRatio,u_extrude_scale:extrudeScale}};const collisionUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_camera_to_center_distance:new performance$1.Uniform1f(context,locations.u_camera_to_center_distance),u_pixels_to_tile_units:new performance$1.Uniform1f(context,locations.u_pixels_to_tile_units),u_extrude_scale:new performance$1.Uniform2f(context,locations.u_extrude_scale),u_overscale_factor:new performance$1.Uniform1f(context,locations.u_overscale_factor)});const collisionCircleUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_inv_matrix:new performance$1.UniformMatrix4f(context,locations.u_inv_matrix),u_camera_to_center_distance:new performance$1.Uniform1f(context,locations.u_camera_to_center_distance),u_viewport_size:new performance$1.Uniform2f(context,locations.u_viewport_size)});const collisionUniformValues=(matrix,transform,tile)=>{const pixelRatio=pixelsToTileUnits(tile,1,transform.zoom);const scale=Math.pow(2,transform.zoom-tile.tileID.overscaledZ);const overscaleFactor=tile.tileID.overscaleFactor();return{u_matrix:matrix,u_camera_to_center_distance:transform.cameraToCenterDistance,u_pixels_to_tile_units:pixelRatio,u_extrude_scale:[transform.pixelsToGLUnits[0]/(pixelRatio*scale),transform.pixelsToGLUnits[1]/(pixelRatio*scale)],u_overscale_factor:overscaleFactor}};const collisionCircleUniformValues=(matrix,invMatrix,transform)=>({u_matrix:matrix,u_inv_matrix:invMatrix,u_camera_to_center_distance:transform.cameraToCenterDistance,u_viewport_size:[transform.width,transform.height]});const debugUniforms=(context,locations)=>({u_color:new performance$1.UniformColor(context,locations.u_color),u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_overlay:new performance$1.Uniform1i(context,locations.u_overlay),u_overlay_scale:new performance$1.Uniform1f(context,locations.u_overlay_scale)});const debugUniformValues=(matrix,color,scaleRatio=1)=>({u_matrix:matrix,u_color:color,u_overlay:0,u_overlay_scale:scaleRatio});const clippingMaskUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix)});const clippingMaskUniformValues=matrix=>({u_matrix:matrix});const heatmapUniforms=(context,locations)=>({u_extrude_scale:new performance$1.Uniform1f(context,locations.u_extrude_scale),u_intensity:new performance$1.Uniform1f(context,locations.u_intensity),u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix)});const heatmapTextureUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_world:new performance$1.Uniform2f(context,locations.u_world),u_image:new performance$1.Uniform1i(context,locations.u_image),u_color_ramp:new performance$1.Uniform1i(context,locations.u_color_ramp),u_opacity:new performance$1.Uniform1f(context,locations.u_opacity)});const heatmapUniformValues=(matrix,tile,zoom,intensity)=>({u_matrix:matrix,u_extrude_scale:pixelsToTileUnits(tile,1,zoom),u_intensity:intensity});const heatmapTextureUniformValues=(painter,layer,textureUnit,colorRampUnit)=>{const matrix=performance$1.create();performance$1.ortho(matrix,0,painter.width,painter.height,0,0,1);const gl=painter.context.gl;return{u_matrix:matrix,u_world:[gl.drawingBufferWidth,gl.drawingBufferHeight],u_image:textureUnit,u_color_ramp:colorRampUnit,u_opacity:layer.paint.get("heatmap-opacity")}};const hillshadeUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_image:new performance$1.Uniform1i(context,locations.u_image),u_latrange:new performance$1.Uniform2f(context,locations.u_latrange),u_light:new performance$1.Uniform2f(context,locations.u_light),u_shadow:new performance$1.UniformColor(context,locations.u_shadow),u_highlight:new performance$1.UniformColor(context,locations.u_highlight),u_accent:new performance$1.UniformColor(context,locations.u_accent)});const hillshadePrepareUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_image:new performance$1.Uniform1i(context,locations.u_image),u_dimension:new performance$1.Uniform2f(context,locations.u_dimension),u_zoom:new performance$1.Uniform1f(context,locations.u_zoom),u_unpack:new performance$1.Uniform4f(context,locations.u_unpack)});const hillshadeUniformValues=(painter,tile,layer,coord)=>{const shadow=layer.paint.get("hillshade-shadow-color");const highlight=layer.paint.get("hillshade-highlight-color");const accent=layer.paint.get("hillshade-accent-color");let azimuthal=layer.paint.get("hillshade-illumination-direction")*(Math.PI/180);if(layer.paint.get("hillshade-illumination-anchor")==="viewport"){azimuthal-=painter.transform.angle}const align=!painter.options.moving;return{u_matrix:coord?coord.posMatrix:painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped(),align),u_image:0,u_latrange:getTileLatRange(painter,tile.tileID),u_light:[layer.paint.get("hillshade-exaggeration"),azimuthal],u_shadow:shadow,u_highlight:highlight,u_accent:accent}};const hillshadeUniformPrepareValues=(tileID,dem)=>{const stride=dem.stride;const matrix=performance$1.create();performance$1.ortho(matrix,0,performance$1.EXTENT,-performance$1.EXTENT,0,0,1);performance$1.translate(matrix,matrix,[0,-performance$1.EXTENT,0]);return{u_matrix:matrix,u_image:1,u_dimension:[stride,stride],u_zoom:tileID.overscaledZ,u_unpack:dem.getUnpackVector()}};function getTileLatRange(painter,tileID){const tilesAtZoom=Math.pow(2,tileID.canonical.z);const y=tileID.canonical.y;return[new performance$1.MercatorCoordinate(0,y/tilesAtZoom).toLngLat().lat,new performance$1.MercatorCoordinate(0,(y+1)/tilesAtZoom).toLngLat().lat]}const lineUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_ratio:new performance$1.Uniform1f(context,locations.u_ratio),u_device_pixel_ratio:new performance$1.Uniform1f(context,locations.u_device_pixel_ratio),u_units_to_pixels:new performance$1.Uniform2f(context,locations.u_units_to_pixels)});const lineGradientUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_ratio:new performance$1.Uniform1f(context,locations.u_ratio),u_device_pixel_ratio:new performance$1.Uniform1f(context,locations.u_device_pixel_ratio),u_units_to_pixels:new performance$1.Uniform2f(context,locations.u_units_to_pixels),u_image:new performance$1.Uniform1i(context,locations.u_image),u_image_height:new performance$1.Uniform1f(context,locations.u_image_height)});const linePatternUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_texsize:new performance$1.Uniform2f(context,locations.u_texsize),u_ratio:new performance$1.Uniform1f(context,locations.u_ratio),u_device_pixel_ratio:new performance$1.Uniform1f(context,locations.u_device_pixel_ratio),u_image:new performance$1.Uniform1i(context,locations.u_image),u_units_to_pixels:new performance$1.Uniform2f(context,locations.u_units_to_pixels),u_scale:new performance$1.Uniform3f(context,locations.u_scale),u_fade:new performance$1.Uniform1f(context,locations.u_fade)});const lineSDFUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_ratio:new performance$1.Uniform1f(context,locations.u_ratio),u_device_pixel_ratio:new performance$1.Uniform1f(context,locations.u_device_pixel_ratio),u_units_to_pixels:new performance$1.Uniform2f(context,locations.u_units_to_pixels),u_patternscale_a:new performance$1.Uniform2f(context,locations.u_patternscale_a),u_patternscale_b:new performance$1.Uniform2f(context,locations.u_patternscale_b),u_sdfgamma:new performance$1.Uniform1f(context,locations.u_sdfgamma),u_image:new performance$1.Uniform1i(context,locations.u_image),u_tex_y_a:new performance$1.Uniform1f(context,locations.u_tex_y_a),u_tex_y_b:new performance$1.Uniform1f(context,locations.u_tex_y_b),u_mix:new performance$1.Uniform1f(context,locations.u_mix)});const lineUniformValues=(painter,tile,layer,coord)=>{const transform=painter.transform;return{u_matrix:calculateMatrix(painter,tile,layer,coord),u_ratio:1/pixelsToTileUnits(tile,1,transform.zoom),u_device_pixel_ratio:painter.pixelRatio,u_units_to_pixels:[1/transform.pixelsToGLUnits[0],1/transform.pixelsToGLUnits[1]]}};const lineGradientUniformValues=(painter,tile,layer,imageHeight,coord)=>performance$1.extend(lineUniformValues(painter,tile,layer,coord),{u_image:0,u_image_height:imageHeight});const linePatternUniformValues=(painter,tile,layer,crossfade,coord)=>{const transform=painter.transform;const tileZoomRatio=calculateTileRatio(tile,transform);return{u_matrix:calculateMatrix(painter,tile,layer,coord),u_texsize:tile.imageAtlasTexture.size,u_ratio:1/pixelsToTileUnits(tile,1,transform.zoom),u_device_pixel_ratio:painter.pixelRatio,u_image:0,u_scale:[tileZoomRatio,crossfade.fromScale,crossfade.toScale],u_fade:crossfade.t,u_units_to_pixels:[1/transform.pixelsToGLUnits[0],1/transform.pixelsToGLUnits[1]]}};const lineSDFUniformValues=(painter,tile,layer,dasharray,crossfade,coord)=>{const transform=painter.transform;const lineAtlas=painter.lineAtlas;const tileRatio=calculateTileRatio(tile,transform);const round=layer.layout.get("line-cap")==="round";const posA=lineAtlas.getDash(dasharray.from,round);const posB=lineAtlas.getDash(dasharray.to,round);const widthA=posA.width*crossfade.fromScale;const widthB=posB.width*crossfade.toScale;return performance$1.extend(lineUniformValues(painter,tile,layer,coord),{u_patternscale_a:[tileRatio/widthA,-posA.height/2],u_patternscale_b:[tileRatio/widthB,-posB.height/2],u_sdfgamma:lineAtlas.width/(Math.min(widthA,widthB)*256*painter.pixelRatio)/2,u_image:0,u_tex_y_a:posA.y,u_tex_y_b:posB.y,u_mix:crossfade.t})};function calculateTileRatio(tile,transform){return 1/pixelsToTileUnits(tile,1,transform.tileZoom)}function calculateMatrix(painter,tile,layer,coord){return painter.translatePosMatrix(coord?coord.posMatrix:tile.tileID.posMatrix,tile,layer.paint.get("line-translate"),layer.paint.get("line-translate-anchor"))}const rasterUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_tl_parent:new performance$1.Uniform2f(context,locations.u_tl_parent),u_scale_parent:new performance$1.Uniform1f(context,locations.u_scale_parent),u_buffer_scale:new performance$1.Uniform1f(context,locations.u_buffer_scale),u_fade_t:new performance$1.Uniform1f(context,locations.u_fade_t),u_opacity:new performance$1.Uniform1f(context,locations.u_opacity),u_image0:new performance$1.Uniform1i(context,locations.u_image0),u_image1:new performance$1.Uniform1i(context,locations.u_image1),u_brightness_low:new performance$1.Uniform1f(context,locations.u_brightness_low),u_brightness_high:new performance$1.Uniform1f(context,locations.u_brightness_high),u_saturation_factor:new performance$1.Uniform1f(context,locations.u_saturation_factor),u_contrast_factor:new performance$1.Uniform1f(context,locations.u_contrast_factor),u_spin_weights:new performance$1.Uniform3f(context,locations.u_spin_weights)});const rasterUniformValues=(matrix,parentTL,parentScaleBy,fade,layer)=>({u_matrix:matrix,u_tl_parent:parentTL,u_scale_parent:parentScaleBy,u_buffer_scale:1,u_fade_t:fade.mix,u_opacity:fade.opacity*layer.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:layer.paint.get("raster-brightness-min"),u_brightness_high:layer.paint.get("raster-brightness-max"),u_saturation_factor:saturationFactor(layer.paint.get("raster-saturation")),u_contrast_factor:contrastFactor(layer.paint.get("raster-contrast")),u_spin_weights:spinWeights(layer.paint.get("raster-hue-rotate"))});function spinWeights(angle){angle*=Math.PI/180;const s=Math.sin(angle);const c=Math.cos(angle);return[(2*c+1)/3,(-Math.sqrt(3)*s-c+1)/3,(Math.sqrt(3)*s-c+1)/3]}function contrastFactor(contrast){return contrast>0?1/(1-contrast):1+contrast}function saturationFactor(saturation){return saturation>0?1-1/(1.001-saturation):-saturation}const symbolIconUniforms=(context,locations)=>({u_is_size_zoom_constant:new performance$1.Uniform1i(context,locations.u_is_size_zoom_constant),u_is_size_feature_constant:new performance$1.Uniform1i(context,locations.u_is_size_feature_constant),u_size_t:new performance$1.Uniform1f(context,locations.u_size_t),u_size:new performance$1.Uniform1f(context,locations.u_size),u_camera_to_center_distance:new performance$1.Uniform1f(context,locations.u_camera_to_center_distance),u_pitch:new performance$1.Uniform1f(context,locations.u_pitch),u_rotate_symbol:new performance$1.Uniform1i(context,locations.u_rotate_symbol),u_aspect_ratio:new performance$1.Uniform1f(context,locations.u_aspect_ratio),u_fade_change:new performance$1.Uniform1f(context,locations.u_fade_change),u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_label_plane_matrix:new performance$1.UniformMatrix4f(context,locations.u_label_plane_matrix),u_coord_matrix:new performance$1.UniformMatrix4f(context,locations.u_coord_matrix),u_is_text:new performance$1.Uniform1i(context,locations.u_is_text),u_pitch_with_map:new performance$1.Uniform1i(context,locations.u_pitch_with_map),u_texsize:new performance$1.Uniform2f(context,locations.u_texsize),u_texture:new performance$1.Uniform1i(context,locations.u_texture)});const symbolSDFUniforms=(context,locations)=>({u_is_size_zoom_constant:new performance$1.Uniform1i(context,locations.u_is_size_zoom_constant),u_is_size_feature_constant:new performance$1.Uniform1i(context,locations.u_is_size_feature_constant),u_size_t:new performance$1.Uniform1f(context,locations.u_size_t),u_size:new performance$1.Uniform1f(context,locations.u_size),u_camera_to_center_distance:new performance$1.Uniform1f(context,locations.u_camera_to_center_distance),u_pitch:new performance$1.Uniform1f(context,locations.u_pitch),u_rotate_symbol:new performance$1.Uniform1i(context,locations.u_rotate_symbol),u_aspect_ratio:new performance$1.Uniform1f(context,locations.u_aspect_ratio),u_fade_change:new performance$1.Uniform1f(context,locations.u_fade_change),u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_label_plane_matrix:new performance$1.UniformMatrix4f(context,locations.u_label_plane_matrix),u_coord_matrix:new performance$1.UniformMatrix4f(context,locations.u_coord_matrix),u_is_text:new performance$1.Uniform1i(context,locations.u_is_text),u_pitch_with_map:new performance$1.Uniform1i(context,locations.u_pitch_with_map),u_texsize:new performance$1.Uniform2f(context,locations.u_texsize),u_texture:new performance$1.Uniform1i(context,locations.u_texture),u_gamma_scale:new performance$1.Uniform1f(context,locations.u_gamma_scale),u_device_pixel_ratio:new performance$1.Uniform1f(context,locations.u_device_pixel_ratio),u_is_halo:new performance$1.Uniform1i(context,locations.u_is_halo)});const symbolTextAndIconUniforms=(context,locations)=>({u_is_size_zoom_constant:new performance$1.Uniform1i(context,locations.u_is_size_zoom_constant),u_is_size_feature_constant:new performance$1.Uniform1i(context,locations.u_is_size_feature_constant),u_size_t:new performance$1.Uniform1f(context,locations.u_size_t),u_size:new performance$1.Uniform1f(context,locations.u_size),u_camera_to_center_distance:new performance$1.Uniform1f(context,locations.u_camera_to_center_distance),u_pitch:new performance$1.Uniform1f(context,locations.u_pitch),u_rotate_symbol:new performance$1.Uniform1i(context,locations.u_rotate_symbol),u_aspect_ratio:new performance$1.Uniform1f(context,locations.u_aspect_ratio),u_fade_change:new performance$1.Uniform1f(context,locations.u_fade_change),u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_label_plane_matrix:new performance$1.UniformMatrix4f(context,locations.u_label_plane_matrix),u_coord_matrix:new performance$1.UniformMatrix4f(context,locations.u_coord_matrix),u_is_text:new performance$1.Uniform1i(context,locations.u_is_text),u_pitch_with_map:new performance$1.Uniform1i(context,locations.u_pitch_with_map),u_texsize:new performance$1.Uniform2f(context,locations.u_texsize),u_texsize_icon:new performance$1.Uniform2f(context,locations.u_texsize_icon),u_texture:new performance$1.Uniform1i(context,locations.u_texture),u_texture_icon:new performance$1.Uniform1i(context,locations.u_texture_icon),u_gamma_scale:new performance$1.Uniform1f(context,locations.u_gamma_scale),u_device_pixel_ratio:new performance$1.Uniform1f(context,locations.u_device_pixel_ratio),u_is_halo:new performance$1.Uniform1i(context,locations.u_is_halo)});const symbolIconUniformValues=(functionType,size,rotateInShader,pitchWithMap,painter,matrix,labelPlaneMatrix,glCoordMatrix,isText,texSize)=>{const transform=painter.transform;return{u_is_size_zoom_constant:+(functionType==="constant"||functionType==="source"),u_is_size_feature_constant:+(functionType==="constant"||functionType==="camera"),u_size_t:size?size.uSizeT:0,u_size:size?size.uSize:0,u_camera_to_center_distance:transform.cameraToCenterDistance,u_pitch:transform.pitch/360*2*Math.PI,u_rotate_symbol:+rotateInShader,u_aspect_ratio:transform.width/transform.height,u_fade_change:painter.options.fadeDuration?painter.symbolFadeChange:1,u_matrix:matrix,u_label_plane_matrix:labelPlaneMatrix,u_coord_matrix:glCoordMatrix,u_is_text:+isText,u_pitch_with_map:+pitchWithMap,u_texsize:texSize,u_texture:0}};const symbolSDFUniformValues=(functionType,size,rotateInShader,pitchWithMap,painter,matrix,labelPlaneMatrix,glCoordMatrix,isText,texSize,isHalo)=>{const transform=painter.transform;return performance$1.extend(symbolIconUniformValues(functionType,size,rotateInShader,pitchWithMap,painter,matrix,labelPlaneMatrix,glCoordMatrix,isText,texSize),{u_gamma_scale:pitchWithMap?Math.cos(transform._pitch)*transform.cameraToCenterDistance:1,u_device_pixel_ratio:painter.pixelRatio,u_is_halo:+isHalo})};const symbolTextAndIconUniformValues=(functionType,size,rotateInShader,pitchWithMap,painter,matrix,labelPlaneMatrix,glCoordMatrix,texSizeSDF,texSizeIcon)=>performance$1.extend(symbolSDFUniformValues(functionType,size,rotateInShader,pitchWithMap,painter,matrix,labelPlaneMatrix,glCoordMatrix,true,texSizeSDF,true),{u_texsize_icon:texSizeIcon,u_texture_icon:1});const backgroundUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_opacity:new performance$1.Uniform1f(context,locations.u_opacity),u_color:new performance$1.UniformColor(context,locations.u_color)});const backgroundPatternUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_opacity:new performance$1.Uniform1f(context,locations.u_opacity),u_image:new performance$1.Uniform1i(context,locations.u_image),u_pattern_tl_a:new performance$1.Uniform2f(context,locations.u_pattern_tl_a),u_pattern_br_a:new performance$1.Uniform2f(context,locations.u_pattern_br_a),u_pattern_tl_b:new performance$1.Uniform2f(context,locations.u_pattern_tl_b),u_pattern_br_b:new performance$1.Uniform2f(context,locations.u_pattern_br_b),u_texsize:new performance$1.Uniform2f(context,locations.u_texsize),u_mix:new performance$1.Uniform1f(context,locations.u_mix),u_pattern_size_a:new performance$1.Uniform2f(context,locations.u_pattern_size_a),u_pattern_size_b:new performance$1.Uniform2f(context,locations.u_pattern_size_b),u_scale_a:new performance$1.Uniform1f(context,locations.u_scale_a),u_scale_b:new performance$1.Uniform1f(context,locations.u_scale_b),u_pixel_coord_upper:new performance$1.Uniform2f(context,locations.u_pixel_coord_upper),u_pixel_coord_lower:new performance$1.Uniform2f(context,locations.u_pixel_coord_lower),u_tile_units_to_pixels:new performance$1.Uniform1f(context,locations.u_tile_units_to_pixels)});const backgroundUniformValues=(matrix,opacity,color)=>({u_matrix:matrix,u_opacity:opacity,u_color:color});const backgroundPatternUniformValues=(matrix,opacity,painter,image,tile,crossfade)=>performance$1.extend(bgPatternUniformValues(image,crossfade,painter,tile),{u_matrix:matrix,u_opacity:opacity});const programUniforms={fillExtrusion:fillExtrusionUniforms,fillExtrusionPattern:fillExtrusionPatternUniforms,fill:fillUniforms,fillPattern:fillPatternUniforms,fillOutline:fillOutlineUniforms,fillOutlinePattern:fillOutlinePatternUniforms,circle:circleUniforms,collisionBox:collisionUniforms,collisionCircle:collisionCircleUniforms,debug:debugUniforms,clippingMask:clippingMaskUniforms,heatmap:heatmapUniforms,heatmapTexture:heatmapTextureUniforms,hillshade:hillshadeUniforms,hillshadePrepare:hillshadePrepareUniforms,line:lineUniforms,lineGradient:lineGradientUniforms,linePattern:linePatternUniforms,lineSDF:lineSDFUniforms,raster:rasterUniforms,symbolIcon:symbolIconUniforms,symbolSDF:symbolSDFUniforms,symbolTextAndIcon:symbolTextAndIconUniforms,background:backgroundUniforms,backgroundPattern:backgroundPatternUniforms,terrain:terrainUniforms,terrainDepth:terrainDepthUniforms,terrainCoords:terrainCoordsUniforms};class IndexBuffer{constructor(context,array,dynamicDraw){this.context=context;const gl=context.gl;this.buffer=gl.createBuffer();this.dynamicDraw=Boolean(dynamicDraw);this.context.unbindVAO();context.bindElementBuffer.set(this.buffer);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,array.arrayBuffer,this.dynamicDraw?gl.DYNAMIC_DRAW:gl.STATIC_DRAW);if(!this.dynamicDraw){delete array.arrayBuffer}}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(array){const gl=this.context.gl;if(!this.dynamicDraw)throw new Error("Attempted to update data while not in dynamic mode.");this.context.unbindVAO();this.bind();gl.bufferSubData(gl.ELEMENT_ARRAY_BUFFER,0,array.arrayBuffer)}destroy(){const gl=this.context.gl;if(this.buffer){gl.deleteBuffer(this.buffer);delete this.buffer}}}const AttributeType={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class VertexBuffer{constructor(context,array,attributes,dynamicDraw){this.length=array.length;this.attributes=attributes;this.itemSize=array.bytesPerElement;this.dynamicDraw=dynamicDraw;this.context=context;const gl=context.gl;this.buffer=gl.createBuffer();context.bindVertexBuffer.set(this.buffer);gl.bufferData(gl.ARRAY_BUFFER,array.arrayBuffer,this.dynamicDraw?gl.DYNAMIC_DRAW:gl.STATIC_DRAW);if(!this.dynamicDraw){delete array.arrayBuffer}}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(array){if(array.length!==this.length)throw new Error(`Length of new data is ${array.length}, which doesn't match current length of ${this.length}`);const gl=this.context.gl;this.bind();gl.bufferSubData(gl.ARRAY_BUFFER,0,array.arrayBuffer)}enableAttributes(gl,program){for(let j=0;j0){const invTransform=performance$1.create();const transform=posMatrix;performance$1.mul(invTransform,bucket.placementInvProjMatrix,painter.transform.glCoordMatrix);performance$1.mul(invTransform,invTransform,bucket.placementViewportMatrix);tileBatches.push({circleArray:circleArray,circleOffset:circleOffset,transform:transform,invTransform:invTransform,coord:coord});circleCount+=circleArray.length/4;circleOffset=circleCount}if(!buffers)continue;program.draw(context,gl.LINES,DepthMode.disabled,StencilMode.disabled,painter.colorModeForRenderPass(),CullFaceMode.disabled,collisionUniformValues(posMatrix,painter.transform,tile),painter.style.map.terrain&&painter.style.map.terrain.getTerrainData(coord),layer.id,buffers.layoutVertexBuffer,buffers.indexBuffer,buffers.segments,null,painter.transform.zoom,null,null,buffers.collisionVertexBuffer)}if(!isText||!tileBatches.length){return}const circleProgram=painter.useProgram("collisionCircle");const vertexData=new performance$1.CollisionCircleLayoutArray;vertexData.resize(circleCount*4);vertexData._trim();let vertexOffset=0;for(const batch of tileBatches){for(let i=0;ipainter.style.map.terrain.getElevation(coord,x,y):null;updateVariableAnchorsForBucket(bucket,rotateWithMap,pitchWithMap,variableOffsets,tr,labelPlaneMatrix,coord.posMatrix,tileScale,size,updateTextFitIcon,getElevation)}}}function updateVariableAnchorsForBucket(bucket,rotateWithMap,pitchWithMap,variableOffsets,transform,labelPlaneMatrix,posMatrix,tileScale,size,updateTextFitIcon,getElevation){const placedSymbols=bucket.text.placedSymbolArray;const dynamicTextLayoutVertexArray=bucket.text.dynamicLayoutVertexArray;const dynamicIconLayoutVertexArray=bucket.icon.dynamicLayoutVertexArray;const placedTextShifts={};dynamicTextLayoutVertexArray.clear();for(let s=0;s=0){placedTextShifts[symbol.associatedIconIndex]={shiftedAnchor:shiftedAnchor,angle:angle}}}}if(updateTextFitIcon){dynamicIconLayoutVertexArray.clear();const placedIcons=bucket.icon.placedSymbolArray;for(let i=0;ipainter.style.map.terrain.getElevation(coord,x,y):null;const rotateToLine=layer.layout.get("text-rotation-alignment")==="map";updateLineLabels(bucket,coord.posMatrix,painter,isText,labelPlaneMatrix,glCoordMatrix,pitchWithMap,keepUpright,rotateToLine,getElevation)}const matrix=painter.translatePosMatrix(coord.posMatrix,tile,translate,translateAnchor),uLabelPlaneMatrix=alongLine||isText&&hasVariablePlacement||updateTextFitIcon?identityMat4:labelPlaneMatrix,uglCoordMatrix=painter.translatePosMatrix(glCoordMatrix,tile,translate,translateAnchor,true);const hasHalo=isSDF&&layer.paint.get(isText?"text-halo-width":"icon-halo-width").constantOr(1)!==0;let uniformValues;if(isSDF){if(!bucket.iconsInText){uniformValues=symbolSDFUniformValues(sizeData.kind,size,rotateInShader,pitchWithMap,painter,matrix,uLabelPlaneMatrix,uglCoordMatrix,isText,texSize,true)}else{uniformValues=symbolTextAndIconUniformValues(sizeData.kind,size,rotateInShader,pitchWithMap,painter,matrix,uLabelPlaneMatrix,uglCoordMatrix,texSize,texSizeIcon)}}else{uniformValues=symbolIconUniformValues(sizeData.kind,size,rotateInShader,pitchWithMap,painter,matrix,uLabelPlaneMatrix,uglCoordMatrix,isText,texSize)}const state={program:program,buffers:buffers,uniformValues:uniformValues,atlasTexture:atlasTexture,atlasTextureIcon:atlasTextureIcon,atlasInterpolation:atlasInterpolation,atlasInterpolationIcon:atlasInterpolationIcon,isSDF:isSDF,hasHalo:hasHalo};if(hasSortKey&&bucket.canOverlap){sortFeaturesByKey=true;const oldSegments=buffers.segments.get();for(const segment of oldSegments){tileRenderState.push({segments:new performance$1.SegmentVector([segment]),sortKey:segment.sortKey,state:state,terrainData:terrainData})}}else{tileRenderState.push({segments:buffers.segments,sortKey:0,state:state,terrainData:terrainData})}}if(sortFeaturesByKey){tileRenderState.sort(((a,b)=>a.sortKey-b.sortKey))}for(const segmentState of tileRenderState){const state=segmentState.state;context.activeTexture.set(gl.TEXTURE0);state.atlasTexture.bind(state.atlasInterpolation,gl.CLAMP_TO_EDGE);if(state.atlasTextureIcon){context.activeTexture.set(gl.TEXTURE1);if(state.atlasTextureIcon){state.atlasTextureIcon.bind(state.atlasInterpolationIcon,gl.CLAMP_TO_EDGE)}}if(state.isSDF){const uniformValues=state.uniformValues;if(state.hasHalo){uniformValues["u_is_halo"]=1;drawSymbolElements(state.buffers,segmentState.segments,layer,painter,state.program,depthMode,stencilMode,colorMode,uniformValues,segmentState.terrainData)}uniformValues["u_is_halo"]=0}drawSymbolElements(state.buffers,segmentState.segments,layer,painter,state.program,depthMode,stencilMode,colorMode,state.uniformValues,segmentState.terrainData)}}function drawSymbolElements(buffers,segments,layer,painter,program,depthMode,stencilMode,colorMode,uniformValues,terrainData){const context=painter.context;const gl=context.gl;program.draw(context,gl.TRIANGLES,depthMode,stencilMode,colorMode,CullFaceMode.disabled,uniformValues,terrainData,layer.id,buffers.layoutVertexBuffer,buffers.indexBuffer,segments,layer.paint,painter.transform.zoom,buffers.programConfigurations.get(layer.id),buffers.dynamicLayoutVertexBuffer,buffers.opacityVertexBuffer)}function drawCircles(painter,sourceCache,layer,coords){if(painter.renderPass!=="translucent")return;const opacity=layer.paint.get("circle-opacity");const strokeWidth=layer.paint.get("circle-stroke-width");const strokeOpacity=layer.paint.get("circle-stroke-opacity");const sortFeaturesByKey=!layer.layout.get("circle-sort-key").isConstant();if(opacity.constantOr(1)===0&&(strokeWidth.constantOr(1)===0||strokeOpacity.constantOr(1)===0)){return}const context=painter.context;const gl=context.gl;const depthMode=painter.depthModeForSublayer(0,DepthMode.ReadOnly);const stencilMode=StencilMode.disabled;const colorMode=painter.colorModeForRenderPass();const segmentsRenderStates=[];for(let i=0;ia.sortKey-b.sortKey))}for(const segmentsState of segmentsRenderStates){const{programConfiguration:programConfiguration,program:program,layoutVertexBuffer:layoutVertexBuffer,indexBuffer:indexBuffer,uniformValues:uniformValues,terrainData:terrainData}=segmentsState.state;const segments=segmentsState.segments;program.draw(context,gl.TRIANGLES,depthMode,stencilMode,colorMode,CullFaceMode.disabled,uniformValues,terrainData,layer.id,layoutVertexBuffer,indexBuffer,segments,layer.paint,painter.transform.zoom,programConfiguration)}}function drawHeatmap(painter,sourceCache,layer,coords){if(layer.paint.get("heatmap-opacity")===0){return}if(painter.renderPass==="offscreen"){const context=painter.context;const gl=context.gl;const stencilMode=StencilMode.disabled;const colorMode=new ColorMode([gl.ONE,gl.ONE],performance$1.Color.transparent,[true,true,true,true]);bindFramebuffer(context,painter,layer);context.clear({color:performance$1.Color.transparent});for(let i=0;i0){const now=browser.now();const sinceTile=(now-tile.timeAdded)/fadeDuration;const sinceParent=parentTile?(now-parentTile.timeAdded)/fadeDuration:-1;const source=sourceCache.getSource();const idealZ=transform.coveringZoomLevel({tileSize:source.tileSize,roundZoom:source.roundZoom});const fadeIn=!parentTile||Math.abs(parentTile.tileID.overscaledZ-idealZ)>Math.abs(tile.tileID.overscaledZ-idealZ);const childOpacity=fadeIn&&tile.refreshedUponExpiration?1:performance$1.clamp(fadeIn?sinceTile:1-sinceParent,0,1);if(tile.refreshedUponExpiration&&sinceTile>=1)tile.refreshedUponExpiration=false;if(parentTile){return{opacity:1,mix:1-childOpacity}}else{return{opacity:childOpacity,mix:0}}}else{return{opacity:1,mix:0}}}function drawBackground(painter,sourceCache,layer,coords){const color=layer.paint.get("background-color");const opacity=layer.paint.get("background-opacity");if(opacity===0)return;const context=painter.context;const gl=context.gl;const transform=painter.transform;const tileSize=transform.tileSize;const image=layer.paint.get("background-pattern");if(painter.isPatternMissing(image))return;const pass=!image&&color.a===1&&opacity===1&&painter.opaquePassEnabledForLayer()?"opaque":"translucent";if(painter.renderPass!==pass)return;const stencilMode=StencilMode.disabled;const depthMode=painter.depthModeForSublayer(0,pass==="opaque"?DepthMode.ReadWrite:DepthMode.ReadOnly);const colorMode=painter.colorModeForRenderPass();const program=painter.useProgram(image?"backgroundPattern":"background");const tileIDs=coords?coords:transform.coveringTiles({tileSize:tileSize,terrain:painter.style.map.terrain});if(image){context.activeTexture.set(gl.TEXTURE0);painter.imageManager.bind(painter.context)}const crossfade=layer.getCrossfadeParameters();for(const tileID of tileIDs){const matrix=coords?tileID.posMatrix:painter.transform.calculatePosMatrix(tileID.toUnwrapped());const uniformValues=image?backgroundPatternUniformValues(matrix,opacity,painter,image,{tileID:tileID,tileSize:tileSize},crossfade):backgroundUniformValues(matrix,opacity,color);const terrainData=painter.style.map.terrain&&painter.style.map.terrain.getTerrainData(tileID);program.draw(context,gl.TRIANGLES,depthMode,stencilMode,colorMode,CullFaceMode.disabled,uniformValues,terrainData,layer.id,painter.tileExtentBuffer,painter.quadTriangleIndexBuffer,painter.tileExtentSegments)}}const topColor=new performance$1.Color(1,0,0,1);const btmColor=new performance$1.Color(0,1,0,1);const leftColor=new performance$1.Color(0,0,1,1);const rightColor=new performance$1.Color(1,0,1,1);const centerColor=new performance$1.Color(0,1,1,1);function drawDebugPadding(painter){const padding=painter.transform.padding;const lineWidth=3;drawHorizontalLine(painter,painter.transform.height-(padding.top||0),lineWidth,topColor);drawHorizontalLine(painter,padding.bottom||0,lineWidth,btmColor);drawVerticalLine(painter,padding.left||0,lineWidth,leftColor);drawVerticalLine(painter,painter.transform.width-(padding.right||0),lineWidth,rightColor);const center=painter.transform.centerPoint;drawCrosshair(painter,center.x,painter.transform.height-center.y,centerColor)}function drawCrosshair(painter,x,y,color){const size=20;const lineWidth=2;drawDebugSSRect(painter,x-lineWidth/2,y-size/2,lineWidth,size,color);drawDebugSSRect(painter,x-size/2,y-lineWidth/2,size,lineWidth,color)}function drawHorizontalLine(painter,y,lineWidth,color){drawDebugSSRect(painter,0,y+lineWidth/2,painter.transform.width,lineWidth,color)}function drawVerticalLine(painter,x,lineWidth,color){drawDebugSSRect(painter,x-lineWidth/2,0,lineWidth,painter.transform.height,color)}function drawDebugSSRect(painter,x,y,width,height,color){const context=painter.context;const gl=context.gl;gl.enable(gl.SCISSOR_TEST);gl.scissor(x*painter.pixelRatio,y*painter.pixelRatio,width*painter.pixelRatio,height*painter.pixelRatio);context.clear({color:color});gl.disable(gl.SCISSOR_TEST)}function drawDebug(painter,sourceCache,coords){for(let i=0;i ${coord.overscaledZ}`}const tileLabel=`${tileIdText} ${tileSizeKb}kB`;drawTextToOverlay(painter,tileLabel);program.draw(context,gl.TRIANGLES,depthMode,stencilMode,ColorMode.alphaBlended,CullFaceMode.disabled,debugUniformValues(posMatrix,performance$1.Color.transparent,scaleRatio),null,id,painter.debugBuffer,painter.quadTriangleIndexBuffer,painter.debugSegments);program.draw(context,gl.LINE_STRIP,depthMode,stencilMode,colorMode,CullFaceMode.disabled,debugUniformValues(posMatrix,performance$1.Color.red),terrainData,id,painter.debugBuffer,painter.tileBorderIndexBuffer,painter.debugSegments)}function drawTextToOverlay(painter,text){painter.initDebugOverlayCanvas();const canvas=painter.debugOverlayCanvas;const gl=painter.context.gl;const ctx2d=painter.debugOverlayCanvas.getContext("2d");ctx2d.clearRect(0,0,canvas.width,canvas.height);ctx2d.shadowColor="white";ctx2d.shadowBlur=2;ctx2d.lineWidth=1.5;ctx2d.strokeStyle="white";ctx2d.textBaseline="top";ctx2d.font=`bold ${36}px Open Sans, sans-serif`;ctx2d.fillText(text,5,5);ctx2d.strokeText(text,5,5);painter.debugOverlayTexture.update(canvas);painter.debugOverlayTexture.bind(gl.LINEAR,gl.CLAMP_TO_EDGE)}function selectDebugSource(style,zoom){let selectedSource=null;const layers=Object.values(style._layers);const sources=layers.flatMap((layer=>{if(layer.source&&!layer.isHidden(zoom)){const sourceCache=style.sourceCaches[layer.source];return[sourceCache]}else{return[]}}));const vectorSources=sources.filter((source=>source.getSource().type==="vector"));const otherSources=sources.filter((source=>source.getSource().type!=="vector"));const considerSource=source=>{if(!selectedSource||selectedSource.getSource().maxzoomconsiderSource(source)));if(!selectedSource){otherSources.forEach((source=>considerSource(source)))}return selectedSource}function drawCustom(painter,sourceCache,layer){const context=painter.context;const implementation=layer.implementation;if(painter.renderPass==="offscreen"){const prerender=implementation.prerender;if(prerender){painter.setCustomLayerDefaults();context.setColorMode(painter.colorModeForRenderPass());prerender.call(implementation,context.gl,painter.transform.customLayerMatrix());context.setDirty();painter.setBaseState()}}else if(painter.renderPass==="translucent"){painter.setCustomLayerDefaults();context.setColorMode(painter.colorModeForRenderPass());context.setStencilMode(StencilMode.disabled);const depthMode=implementation.renderingMode==="3d"?new DepthMode(painter.context.gl.LEQUAL,DepthMode.ReadWrite,painter.depthRangeFor3D):painter.depthModeForSublayer(0,DepthMode.ReadOnly);context.setDepthMode(depthMode);implementation.render(context.gl,painter.transform.customLayerMatrix());context.setDirty();painter.setBaseState();context.bindFramebuffer.set(null)}}function drawDepth(painter,terrain){const context=painter.context;const gl=context.gl;const colorMode=ColorMode.unblended;const depthMode=new DepthMode(gl.LEQUAL,DepthMode.ReadWrite,[0,1]);const mesh=terrain.getTerrainMesh();const tiles=terrain.sourceCache.getRenderableTiles();const program=painter.useProgram("terrainDepth");context.bindFramebuffer.set(terrain.getFramebuffer("depth").framebuffer);context.viewport.set([0,0,painter.width/devicePixelRatio,painter.height/devicePixelRatio]);context.clear({color:performance$1.Color.transparent,depth:1});for(const tile of tiles){const terrainData=terrain.getTerrainData(tile.tileID);const posMatrix=painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped());const uniformValues=terrainDepthUniformValues(posMatrix,terrain.getMeshFrameDelta(painter.transform.zoom));program.draw(context,gl.TRIANGLES,depthMode,StencilMode.disabled,colorMode,CullFaceMode.backCCW,uniformValues,terrainData,"terrain",mesh.vertexBuffer,mesh.indexBuffer,mesh.segments)}context.bindFramebuffer.set(null);context.viewport.set([0,0,painter.width,painter.height])}function drawCoords(painter,terrain){const context=painter.context;const gl=context.gl;const colorMode=ColorMode.unblended;const depthMode=new DepthMode(gl.LEQUAL,DepthMode.ReadWrite,[0,1]);const mesh=terrain.getTerrainMesh();const coords=terrain.getCoordsTexture();const tiles=terrain.sourceCache.getRenderableTiles();const program=painter.useProgram("terrainCoords");context.bindFramebuffer.set(terrain.getFramebuffer("coords").framebuffer);context.viewport.set([0,0,painter.width/devicePixelRatio,painter.height/devicePixelRatio]);context.clear({color:performance$1.Color.transparent,depth:1});terrain.coordsIndex=[];for(const tile of tiles){const terrainData=terrain.getTerrainData(tile.tileID);context.activeTexture.set(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,coords.texture);const posMatrix=painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped());const uniformValues=terrainCoordsUniformValues(posMatrix,255-terrain.coordsIndex.length,terrain.getMeshFrameDelta(painter.transform.zoom));program.draw(context,gl.TRIANGLES,depthMode,StencilMode.disabled,colorMode,CullFaceMode.backCCW,uniformValues,terrainData,"terrain",mesh.vertexBuffer,mesh.indexBuffer,mesh.segments);terrain.coordsIndex.push(tile.tileID.key)}context.bindFramebuffer.set(null);context.viewport.set([0,0,painter.width,painter.height])}function drawTerrain(painter,terrain,tiles){const context=painter.context;const gl=context.gl;const colorMode=painter.colorModeForRenderPass();const depthMode=new DepthMode(gl.LEQUAL,DepthMode.ReadWrite,painter.depthRangeFor3D);const program=painter.useProgram("terrain");const mesh=terrain.getTerrainMesh();context.bindFramebuffer.set(null);context.viewport.set([0,0,painter.width,painter.height]);for(const tile of tiles){const texture=painter.renderToTexture.getTexture(tile);const terrainData=terrain.getTerrainData(tile.tileID);context.activeTexture.set(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,texture.texture);const posMatrix=painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped());const uniformValues=terrainUniformValues(posMatrix,terrain.getMeshFrameDelta(painter.transform.zoom));program.draw(context,gl.TRIANGLES,depthMode,StencilMode.disabled,colorMode,CullFaceMode.backCCW,uniformValues,terrainData,"terrain",mesh.vertexBuffer,mesh.indexBuffer,mesh.segments)}}class Painter{constructor(gl,transform){this.context=new Context(gl);this.transform=transform;this._tileTextures={};this.terrainFacilitator={dirty:true,matrix:performance$1.create(),renderTime:0};this.setup();this.numSublayers=SourceCache.maxUnderzooming+SourceCache.maxOverzooming+1;this.depthEpsilon=1/Math.pow(2,16);this.crossTileSymbolIndex=new CrossTileSymbolIndex}resize(width,height,pixelRatio){this.width=Math.floor(width*pixelRatio);this.height=Math.floor(height*pixelRatio);this.pixelRatio=pixelRatio;this.context.viewport.set([0,0,this.width,this.height]);if(this.style){for(const layerId of this.style._order){this.style._layers[layerId].resize()}}}setup(){const context=this.context;const tileExtentArray=new performance$1.PosArray;tileExtentArray.emplaceBack(0,0);tileExtentArray.emplaceBack(performance$1.EXTENT,0);tileExtentArray.emplaceBack(0,performance$1.EXTENT);tileExtentArray.emplaceBack(performance$1.EXTENT,performance$1.EXTENT);this.tileExtentBuffer=context.createVertexBuffer(tileExtentArray,posAttributes.members);this.tileExtentSegments=performance$1.SegmentVector.simpleSegment(0,0,4,2);const debugArray=new performance$1.PosArray;debugArray.emplaceBack(0,0);debugArray.emplaceBack(performance$1.EXTENT,0);debugArray.emplaceBack(0,performance$1.EXTENT);debugArray.emplaceBack(performance$1.EXTENT,performance$1.EXTENT);this.debugBuffer=context.createVertexBuffer(debugArray,posAttributes.members);this.debugSegments=performance$1.SegmentVector.simpleSegment(0,0,4,5);const rasterBoundsArray=new performance$1.RasterBoundsArray;rasterBoundsArray.emplaceBack(0,0,0,0);rasterBoundsArray.emplaceBack(performance$1.EXTENT,0,performance$1.EXTENT,0);rasterBoundsArray.emplaceBack(0,performance$1.EXTENT,0,performance$1.EXTENT);rasterBoundsArray.emplaceBack(performance$1.EXTENT,performance$1.EXTENT,performance$1.EXTENT,performance$1.EXTENT);this.rasterBoundsBuffer=context.createVertexBuffer(rasterBoundsArray,rasterBoundsAttributes.members);this.rasterBoundsSegments=performance$1.SegmentVector.simpleSegment(0,0,4,2);const viewportArray=new performance$1.PosArray;viewportArray.emplaceBack(0,0);viewportArray.emplaceBack(1,0);viewportArray.emplaceBack(0,1);viewportArray.emplaceBack(1,1);this.viewportBuffer=context.createVertexBuffer(viewportArray,posAttributes.members);this.viewportSegments=performance$1.SegmentVector.simpleSegment(0,0,4,2);const tileLineStripIndices=new performance$1.LineStripIndexArray;tileLineStripIndices.emplaceBack(0);tileLineStripIndices.emplaceBack(1);tileLineStripIndices.emplaceBack(3);tileLineStripIndices.emplaceBack(2);tileLineStripIndices.emplaceBack(0);this.tileBorderIndexBuffer=context.createIndexBuffer(tileLineStripIndices);const quadTriangleIndices=new performance$1.TriangleIndexArray;quadTriangleIndices.emplaceBack(0,1,2);quadTriangleIndices.emplaceBack(2,1,3);this.quadTriangleIndexBuffer=context.createIndexBuffer(quadTriangleIndices);const gl=this.context.gl;this.stencilClearMode=new StencilMode({func:gl.ALWAYS,mask:0},0,255,gl.ZERO,gl.ZERO,gl.ZERO)}clearStencil(){const context=this.context;const gl=context.gl;this.nextStencilID=1;this.currentStencilSource=undefined;const matrix=performance$1.create();performance$1.ortho(matrix,0,this.width,this.height,0,0,1);performance$1.scale(matrix,matrix,[gl.drawingBufferWidth,gl.drawingBufferHeight,0]);this.useProgram("clippingMask").draw(context,gl.TRIANGLES,DepthMode.disabled,this.stencilClearMode,ColorMode.disabled,CullFaceMode.disabled,clippingMaskUniformValues(matrix),null,"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}_renderTileClippingMasks(layer,tileIDs){if(this.currentStencilSource===layer.source||!layer.isTileClipped()||!tileIDs||!tileIDs.length)return;this.currentStencilSource=layer.source;const context=this.context;const gl=context.gl;if(this.nextStencilID+tileIDs.length>256){this.clearStencil()}context.setColorMode(ColorMode.disabled);context.setDepthMode(DepthMode.disabled);const program=this.useProgram("clippingMask");this._tileClippingMaskIDs={};for(const tileID of tileIDs){const id=this._tileClippingMaskIDs[tileID.key]=this.nextStencilID++;const terrainData=this.style.map.terrain&&this.style.map.terrain.getTerrainData(tileID);program.draw(context,gl.TRIANGLES,DepthMode.disabled,new StencilMode({func:gl.ALWAYS,mask:0},id,255,gl.KEEP,gl.KEEP,gl.REPLACE),ColorMode.disabled,CullFaceMode.disabled,clippingMaskUniformValues(tileID.posMatrix),terrainData,"$clipping",this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments)}}stencilModeFor3D(){this.currentStencilSource=undefined;if(this.nextStencilID+1>256){this.clearStencil()}const id=this.nextStencilID++;const gl=this.context.gl;return new StencilMode({func:gl.NOTEQUAL,mask:255},id,255,gl.KEEP,gl.KEEP,gl.REPLACE)}stencilModeForClipping(tileID){const gl=this.context.gl;return new StencilMode({func:gl.EQUAL,mask:255},this._tileClippingMaskIDs[tileID.key],0,gl.KEEP,gl.KEEP,gl.REPLACE)}stencilConfigForOverlap(tileIDs){const gl=this.context.gl;const coords=tileIDs.sort(((a,b)=>b.overscaledZ-a.overscaledZ));const minTileZ=coords[coords.length-1].overscaledZ;const stencilValues=coords[0].overscaledZ-minTileZ+1;if(stencilValues>1){this.currentStencilSource=undefined;if(this.nextStencilID+stencilValues>256){this.clearStencil()}const zToStencilMode={};for(let i=0;i=0;this.currentLayer--){const layer=this.style._layers[layerIds[this.currentLayer]];const sourceCache=sourceCaches[layer.source];const coords=coordsAscending[layer.source];this._renderTileClippingMasks(layer,coords);this.renderLayer(this,sourceCache,layer,coords)}}this.renderPass="translucent";for(this.currentLayer=0;this.currentLayer0?textures.pop():null}isPatternMissing(image){if(!image)return false;if(!image.from||!image.to)return true;const imagePosA=this.imageManager.getPattern(image.from.toString());const imagePosB=this.imageManager.getPattern(image.to.toString());return!imagePosA||!imagePosB}useProgram(name,programConfiguration){this.cache=this.cache||{};const key=name+(programConfiguration?programConfiguration.cacheKey:"")+(this._showOverdrawInspector?"/overdraw":"")+(this.style.map.terrain?"/terrain":"");if(!this.cache[key]){this.cache[key]=new Program(this.context,shaders[name],programConfiguration,programUniforms[name],this._showOverdrawInspector,this.style.map.terrain)}return this.cache[key]}setCustomLayerDefaults(){this.context.unbindVAO();this.context.cullFace.setDefault();this.context.activeTexture.setDefault();this.context.pixelStoreUnpack.setDefault();this.context.pixelStoreUnpackPremultiplyAlpha.setDefault();this.context.pixelStoreUnpackFlipY.setDefault()}setBaseState(){const gl=this.context.gl;this.context.cullFace.set(false);this.context.viewport.set([0,0,this.width,this.height]);this.context.blendEquation.set(gl.FUNC_ADD)}initDebugOverlayCanvas(){if(this.debugOverlayCanvas==null){this.debugOverlayCanvas=document.createElement("canvas");this.debugOverlayCanvas.width=512;this.debugOverlayCanvas.height=512;const gl=this.context.gl;this.debugOverlayTexture=new Texture(this.context,this.debugOverlayCanvas,gl.RGBA)}}destroy(){if(this.debugOverlayTexture){this.debugOverlayTexture.destroy()}}overLimit(){const{drawingBufferWidth:drawingBufferWidth,drawingBufferHeight:drawingBufferHeight}=this.context.gl;return this.width!==drawingBufferWidth||this.height!==drawingBufferHeight}}class Frustum{constructor(points,planes){this.points=points;this.planes=planes}static fromInvProjectionMatrix(invProj,worldSize,zoom){const clipSpaceCorners=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]];const scale=Math.pow(2,zoom);const frustumCoords=clipSpaceCorners.map((v=>{v=performance$1.transformMat4([],v,invProj);const s=1/v[3]/worldSize*scale;return performance$1.mul$1(v,v,[s,s,1/v[3],s])}));const frustumPlanePointIndices=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]];const frustumPlanes=frustumPlanePointIndices.map((p=>{const a=performance$1.sub([],frustumCoords[p[0]],frustumCoords[p[1]]);const b=performance$1.sub([],frustumCoords[p[2]],frustumCoords[p[1]]);const n=performance$1.normalize([],performance$1.cross([],a,b));const d=-performance$1.dot(n,frustumCoords[p[1]]);return n.concat(d)}));return new Frustum(frustumCoords,frustumPlanes)}}class Aabb{constructor(min_,max_){this.min=min_;this.max=max_;this.center=performance$1.scale$1([],performance$1.add([],this.min,this.max),.5)}quadrant(index){const split=[index%2===0,index<2];const qMin=performance$1.clone$2(this.min);const qMax=performance$1.clone$2(this.max);for(let axis=0;axis=0){pointsInside++}}if(pointsInside===0)return 0;if(pointsInside!==aabbPoints.length)fullyInside=false}if(fullyInside)return 2;for(let axis=0;axis<3;axis++){let projMin=Number.MAX_VALUE;let projMax=-Number.MAX_VALUE;for(let p=0;pthis.max[axis]-this.min[axis])return 0}return 1}}class EdgeInsets{constructor(top=0,bottom=0,left=0,right=0){if(isNaN(top)||top<0||isNaN(bottom)||bottom<0||isNaN(left)||left<0||isNaN(right)||right<0){throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers")}this.top=top;this.bottom=bottom;this.left=left;this.right=right}interpolate(start,target,t){if(target.top!=null&&start.top!=null)this.top=performance$1.interpolate.number(start.top,target.top,t);if(target.bottom!=null&&start.bottom!=null)this.bottom=performance$1.interpolate.number(start.bottom,target.bottom,t);if(target.left!=null&&start.left!=null)this.left=performance$1.interpolate.number(start.left,target.left,t);if(target.right!=null&&start.right!=null)this.right=performance$1.interpolate.number(start.right,target.right,t);return this}getCenter(width,height){const x=performance$1.clamp((this.left+width-this.right)/2,0,width);const y=performance$1.clamp((this.top+height-this.bottom)/2,0,height);return new performance$1.Point(x,y)}equals(other){return this.top===other.top&&this.bottom===other.bottom&&this.left===other.left&&this.right===other.right}clone(){return new EdgeInsets(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}class Transform{constructor(minZoom,maxZoom,minPitch,maxPitch,renderWorldCopies){this.tileSize=512;this.maxValidLatitude=85.051129;this._renderWorldCopies=renderWorldCopies===undefined?true:!!renderWorldCopies;this._minZoom=minZoom||0;this._maxZoom=maxZoom||22;this._minPitch=minPitch===undefined||minPitch===null?0:minPitch;this._maxPitch=maxPitch===undefined||maxPitch===null?60:maxPitch;this.setMaxBounds();this.width=0;this.height=0;this._center=new performance$1.LngLat(0,0);this._elevation=0;this.zoom=0;this.angle=0;this._fov=.6435011087932844;this._pitch=0;this._unmodified=true;this._edgeInsets=new EdgeInsets;this._posMatrixCache={};this._alignedPosMatrixCache={};this.minElevationForCurrentTile=0}clone(){const clone=new Transform(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies);clone.apply(this);return clone}apply(that){this.tileSize=that.tileSize;this.latRange=that.latRange;this.width=that.width;this.height=that.height;this._center=that._center;this._elevation=that._elevation;this.minElevationForCurrentTile=that.minElevationForCurrentTile;this.zoom=that.zoom;this.angle=that.angle;this._fov=that._fov;this._pitch=that._pitch;this._unmodified=that._unmodified;this._edgeInsets=that._edgeInsets.clone();this._calcMatrices()}get minZoom(){return this._minZoom}set minZoom(zoom){if(this._minZoom===zoom)return;this._minZoom=zoom;this.zoom=Math.max(this.zoom,zoom)}get maxZoom(){return this._maxZoom}set maxZoom(zoom){if(this._maxZoom===zoom)return;this._maxZoom=zoom;this.zoom=Math.min(this.zoom,zoom)}get minPitch(){return this._minPitch}set minPitch(pitch){if(this._minPitch===pitch)return;this._minPitch=pitch;this.pitch=Math.max(this.pitch,pitch)}get maxPitch(){return this._maxPitch}set maxPitch(pitch){if(this._maxPitch===pitch)return;this._maxPitch=pitch;this.pitch=Math.min(this.pitch,pitch)}get renderWorldCopies(){return this._renderWorldCopies}set renderWorldCopies(renderWorldCopies){if(renderWorldCopies===undefined){renderWorldCopies=true}else if(renderWorldCopies===null){renderWorldCopies=false}this._renderWorldCopies=renderWorldCopies}get worldSize(){return this.tileSize*this.scale}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new performance$1.Point(this.width,this.height)}get bearing(){return-this.angle/Math.PI*180}set bearing(bearing){const b=-performance$1.wrap(bearing,-180,180)*Math.PI/180;if(this.angle===b)return;this._unmodified=false;this.angle=b;this._calcMatrices();this.rotationMatrix=performance$1.create$2();performance$1.rotate(this.rotationMatrix,this.rotationMatrix,this.angle)}get pitch(){return this._pitch/Math.PI*180}set pitch(pitch){const p=performance$1.clamp(pitch,this.minPitch,this.maxPitch)/180*Math.PI;if(this._pitch===p)return;this._unmodified=false;this._pitch=p;this._calcMatrices()}get fov(){return this._fov/Math.PI*180}set fov(fov){fov=Math.max(.01,Math.min(60,fov));if(this._fov===fov)return;this._unmodified=false;this._fov=fov/180*Math.PI;this._calcMatrices()}get zoom(){return this._zoom}set zoom(zoom){const constrainedZoom=Math.min(Math.max(zoom,this.minZoom),this.maxZoom);if(this._zoom===constrainedZoom)return;this._unmodified=false;this._zoom=constrainedZoom;this.tileZoom=Math.max(0,Math.floor(constrainedZoom));this.scale=this.zoomScale(constrainedZoom);this._constrain();this._calcMatrices()}get center(){return this._center}set center(center){if(center.lat===this._center.lat&¢er.lng===this._center.lng)return;this._unmodified=false;this._center=center;this._constrain();this._calcMatrices()}get elevation(){return this._elevation}set elevation(elevation){if(elevation===this._elevation)return;this._elevation=elevation;this._constrain();this._calcMatrices()}get padding(){return this._edgeInsets.toJSON()}set padding(padding){if(this._edgeInsets.equals(padding))return;this._unmodified=false;this._edgeInsets.interpolate(this._edgeInsets,padding,1);this._calcMatrices()}get centerPoint(){return this._edgeInsets.getCenter(this.width,this.height)}isPaddingEqual(padding){return this._edgeInsets.equals(padding)}interpolatePadding(start,target,t){this._unmodified=false;this._edgeInsets.interpolate(start,target,t);this._constrain();this._calcMatrices()}coveringZoomLevel(options){const z=(options.roundZoom?Math.round:Math.floor)(this.zoom+this.scaleZoom(this.tileSize/options.tileSize));return Math.max(0,z)}getVisibleUnwrappedCoordinates(tileID){const result=[new performance$1.UnwrappedTileID(0,tileID)];if(this._renderWorldCopies){const utl=this.pointCoordinate(new performance$1.Point(0,0));const utr=this.pointCoordinate(new performance$1.Point(this.width,0));const ubl=this.pointCoordinate(new performance$1.Point(this.width,this.height));const ubr=this.pointCoordinate(new performance$1.Point(0,this.height));const w0=Math.floor(Math.min(utl.x,utr.x,ubl.x,ubr.x));const w1=Math.floor(Math.max(utl.x,utr.x,ubl.x,ubr.x));const extraWorldCopy=1;for(let w=w0-extraWorldCopy;w<=w1+extraWorldCopy;w++){if(w===0)continue;result.push(new performance$1.UnwrappedTileID(w,tileID))}}return result}coveringTiles(options){var _a,_b;let z=this.coveringZoomLevel(options);const actualZ=z;if(options.minzoom!==undefined&&zoptions.maxzoom)z=options.maxzoom;const cameraCoord=this.pointCoordinate(this.getCameraPoint());const centerCoord=performance$1.MercatorCoordinate.fromLngLat(this.center);const numTiles=Math.pow(2,z);const cameraPoint=[numTiles*cameraCoord.x,numTiles*cameraCoord.y,0];const centerPoint=[numTiles*centerCoord.x,numTiles*centerCoord.y,0];const cameraFrustum=Frustum.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,z);let minZoom=options.minzoom||0;if(!options.terrain&&this.pitch<=60&&this._edgeInsets.top<.1)minZoom=z;const radiusOfMaxLvlLodInTiles=options.terrain?2/Math.min(this.tileSize,options.tileSize)*this.tileSize:3;const newRootTile=wrap=>({aabb:new Aabb([wrap*numTiles,0,0],[(wrap+1)*numTiles,numTiles,0]),zoom:0,x:0,y:0,wrap:wrap,fullyVisible:false});const stack=[];const result=[];const maxZoom=z;const overscaledZ=options.reparseOverscaled?actualZ:z;if(this._renderWorldCopies){for(let i=1;i<=3;i++){stack.push(newRootTile(-i));stack.push(newRootTile(i))}}stack.push(newRootTile(0));while(stack.length>0){const it=stack.pop();const x=it.x;const y=it.y;let fullyVisible=it.fullyVisible;if(!fullyVisible){const intersectResult=it.aabb.intersects(cameraFrustum);if(intersectResult===0)continue;fullyVisible=intersectResult===2}const refPoint=options.terrain?cameraPoint:centerPoint;const distanceX=it.aabb.distanceX(refPoint);const distanceY=it.aabb.distanceY(refPoint);const longestDim=Math.max(Math.abs(distanceX),Math.abs(distanceY));const distToSplit=radiusOfMaxLvlLodInTiles+(1<distToSplit&&it.zoom>=minZoom){const dz=maxZoom-it.zoom,dx=cameraPoint[0]-.5-(x<>1);const childZ=it.zoom+1;let quadrant=it.aabb.quadrant(i);if(options.terrain){const tileID=new performance$1.OverscaledTileID(childZ,it.wrap,childZ,childX,childY);const minMax=options.terrain.getMinMaxElevation(tileID);const minElevation=(_a=minMax.minElevation)!==null&&_a!==void 0?_a:this.elevation;const maxElevation=(_b=minMax.maxElevation)!==null&&_b!==void 0?_b:this.elevation;quadrant=new Aabb([quadrant.min[0],quadrant.min[1],minElevation],[quadrant.max[0],quadrant.max[1],maxElevation])}stack.push({aabb:quadrant,zoom:childZ,x:childX,y:childY,wrap:it.wrap,fullyVisible:fullyVisible})}}return result.sort(((a,b)=>a.distanceSq-b.distanceSq)).map((a=>a.tileID))}resize(width,height){this.width=width;this.height=height;this.pixelsToGLUnits=[2/width,-2/height];this._constrain();this._calcMatrices()}get unmodified(){return this._unmodified}zoomScale(zoom){return Math.pow(2,zoom)}scaleZoom(scale){return Math.log(scale)/Math.LN2}project(lnglat){const lat=performance$1.clamp(lnglat.lat,-this.maxValidLatitude,this.maxValidLatitude);return new performance$1.Point(performance$1.mercatorXfromLng(lnglat.lng)*this.worldSize,performance$1.mercatorYfromLat(lat)*this.worldSize)}unproject(point){return new performance$1.MercatorCoordinate(point.x/this.worldSize,point.y/this.worldSize).toLngLat()}get point(){return this.project(this.center)}getCameraPosition(){const lngLat=this.pointLocation(this.getCameraPoint());const altitude=Math.cos(this._pitch)*this.cameraToCenterDistance/this._pixelPerMeter;return{lngLat:lngLat,altitude:altitude+this.elevation}}recalculateZoom(terrain){const center=this.pointLocation(this.centerPoint,terrain);const elevation=terrain.getElevationForLngLatZoom(center,this.tileZoom);const deltaElevation=this.elevation-elevation;if(!deltaElevation)return;const cameraPosition=this.getCameraPosition();const camera=performance$1.MercatorCoordinate.fromLngLat(cameraPosition.lngLat,cameraPosition.altitude);const target=performance$1.MercatorCoordinate.fromLngLat(center,elevation);const dx=camera.x-target.x,dy=camera.y-target.y,dz=camera.z-target.z;const distance=Math.sqrt(dx*dx+dy*dy+dz*dz);const zoom=this.scaleZoom(this.cameraToCenterDistance/distance/this.tileSize);this._elevation=elevation;this._center=center;this.zoom=zoom}setLocationAtPoint(lnglat,point){const a=this.pointCoordinate(point);const b=this.pointCoordinate(this.centerPoint);const loc=this.locationCoordinate(lnglat);const newCenter=new performance$1.MercatorCoordinate(loc.x-(a.x-b.x),loc.y-(a.y-b.y));this.center=this.coordinateLocation(newCenter);if(this._renderWorldCopies){this.center=this.center.wrap()}}locationPoint(lnglat,terrain){return terrain?this.coordinatePoint(this.locationCoordinate(lnglat),terrain.getElevationForLngLatZoom(lnglat,this.tileZoom),this.pixelMatrix3D):this.coordinatePoint(this.locationCoordinate(lnglat))}pointLocation(p,terrain){return this.coordinateLocation(this.pointCoordinate(p,terrain))}locationCoordinate(lnglat){return performance$1.MercatorCoordinate.fromLngLat(lnglat)}coordinateLocation(coord){return coord&&coord.toLngLat()}pointCoordinate(p,terrain){if(terrain){const coordinate=terrain.pointCoordinate(p);if(coordinate!=null){return coordinate}}const targetZ=0;const coord0=[p.x,p.y,0,1];const coord1=[p.x,p.y,1,1];performance$1.transformMat4(coord0,coord0,this.pixelMatrixInverse);performance$1.transformMat4(coord1,coord1,this.pixelMatrixInverse);const w0=coord0[3];const w1=coord1[3];const x0=coord0[0]/w0;const x1=coord1[0]/w1;const y0=coord0[1]/w0;const y1=coord1[1]/w1;const z0=coord0[2]/w0;const z1=coord1[2]/w1;const t=z0===z1?0:(targetZ-z0)/(z1-z0);return new performance$1.MercatorCoordinate(performance$1.interpolate.number(x0,x1,t)/this.worldSize,performance$1.interpolate.number(y0,y1,t)/this.worldSize)}coordinatePoint(coord,elevation=0,pixelMatrix=this.pixelMatrix){const p=[coord.x*this.worldSize,coord.y*this.worldSize,elevation,1];performance$1.transformMat4(p,p,pixelMatrix);return new performance$1.Point(p[0]/p[3],p[1]/p[3])}getBounds(){const top=Math.max(0,this.height/2-this.getHorizon());return(new LngLatBounds).extend(this.pointLocation(new performance$1.Point(0,top))).extend(this.pointLocation(new performance$1.Point(this.width,top))).extend(this.pointLocation(new performance$1.Point(this.width,this.height))).extend(this.pointLocation(new performance$1.Point(0,this.height)))}getMaxBounds(){if(!this.latRange||this.latRange.length!==2||!this.lngRange||this.lngRange.length!==2)return null;return new LngLatBounds([this.lngRange[0],this.latRange[0]],[this.lngRange[1],this.latRange[1]])}getHorizon(){return Math.tan(Math.PI/2-this._pitch)*this.cameraToCenterDistance*.85}setMaxBounds(bounds){if(bounds){this.lngRange=[bounds.getWest(),bounds.getEast()];this.latRange=[bounds.getSouth(),bounds.getNorth()];this._constrain()}else{this.lngRange=null;this.latRange=[-this.maxValidLatitude,this.maxValidLatitude]}}calculatePosMatrix(unwrappedTileID,aligned=false){const posMatrixKey=unwrappedTileID.key;const cache=aligned?this._alignedPosMatrixCache:this._posMatrixCache;if(cache[posMatrixKey]){return cache[posMatrixKey]}const canonical=unwrappedTileID.canonical;const scale=this.worldSize/this.zoomScale(canonical.z);const unwrappedX=canonical.x+Math.pow(2,canonical.z)*unwrappedTileID.wrap;const posMatrix=performance$1.identity(new Float64Array(16));performance$1.translate(posMatrix,posMatrix,[unwrappedX*scale,canonical.y*scale,0]);performance$1.scale(posMatrix,posMatrix,[scale/performance$1.EXTENT,scale/performance$1.EXTENT,1]);performance$1.multiply(posMatrix,aligned?this.alignedProjMatrix:this.projMatrix,posMatrix);cache[posMatrixKey]=new Float32Array(posMatrix);return cache[posMatrixKey]}customLayerMatrix(){return this.mercatorMatrix.slice()}_constrain(){if(!this.center||!this.width||!this.height||this._constraining)return;this._constraining=true;let minY=-90;let maxY=90;let minX=-180;let maxX=180;let sy,sx,x2,y2;const size=this.size,unmodified=this._unmodified;if(this.latRange){const latRange=this.latRange;minY=performance$1.mercatorYfromLat(latRange[1])*this.worldSize;maxY=performance$1.mercatorYfromLat(latRange[0])*this.worldSize;sy=maxY-minYmaxY)y2=maxY-h2}if(this.lngRange){const centerX=(minX+maxX)/2;const x=performance$1.wrap(point.x,centerX-this.worldSize/2,centerX+this.worldSize/2);const w2=size.x/2;if(x-w2maxX)x2=maxX-w2}if(x2!==undefined||y2!==undefined){this.center=this.unproject(new performance$1.Point(x2!==undefined?x2:point.x,y2!==undefined?y2:point.y)).wrap()}this._unmodified=unmodified;this._constraining=false}_calcMatrices(){if(!this.height)return;const halfFov=this._fov/2;const offset=this.centerOffset;const x=this.point.x,y=this.point.y;this.cameraToCenterDistance=.5/Math.tan(halfFov)*this.height;this._pixelPerMeter=performance$1.mercatorZfromAltitude(1,this.center.lat)*this.worldSize;let m=performance$1.identity(new Float64Array(16));performance$1.scale(m,m,[this.width/2,-this.height/2,1]);performance$1.translate(m,m,[1,-1,0]);this.labelPlaneMatrix=m;m=performance$1.identity(new Float64Array(16));performance$1.scale(m,m,[1,-1,1]);performance$1.translate(m,m,[-1,-1,0]);performance$1.scale(m,m,[2/this.width,2/this.height,1]);this.glCoordMatrix=m;const cameraToSeaLevelDistance=this.cameraToCenterDistance+this._elevation*this._pixelPerMeter/Math.cos(this._pitch);const minElevation=Math.min(this.elevation,this.minElevationForCurrentTile);const cameraToLowestPointDistance=cameraToSeaLevelDistance-minElevation*this._pixelPerMeter/Math.cos(this._pitch);const lowestPlane=minElevation<0?cameraToLowestPointDistance:cameraToSeaLevelDistance;const groundAngle=Math.PI/2+this._pitch;const fovAboveCenter=this._fov*(.5+offset.y/this.height);const topHalfSurfaceDistance=Math.sin(fovAboveCenter)*lowestPlane/Math.sin(performance$1.clamp(Math.PI-groundAngle-fovAboveCenter,.01,Math.PI-.01));const horizon=this.getHorizon();const horizonAngle=Math.atan(horizon/this.cameraToCenterDistance);const fovCenterToHorizon=2*horizonAngle*(.5+offset.y/(horizon*2));const topHalfSurfaceDistanceHorizon=Math.sin(fovCenterToHorizon)*lowestPlane/Math.sin(performance$1.clamp(Math.PI-groundAngle-fovCenterToHorizon,.01,Math.PI-.01));const topHalfMinDistance=Math.min(topHalfSurfaceDistance,topHalfSurfaceDistanceHorizon);const farZ=(Math.cos(Math.PI/2-this._pitch)*topHalfMinDistance+lowestPlane)*1.01;const nearZ=this.height/50;m=new Float64Array(16);performance$1.perspective(m,this._fov,this.width/this.height,nearZ,farZ);m[8]=-offset.x*2/this.width;m[9]=offset.y*2/this.height;performance$1.scale(m,m,[1,-1,1]);performance$1.translate(m,m,[0,0,-this.cameraToCenterDistance]);performance$1.rotateX(m,m,this._pitch);performance$1.rotateZ(m,m,this.angle);performance$1.translate(m,m,[-x,-y,0]);this.mercatorMatrix=performance$1.scale([],m,[this.worldSize,this.worldSize,this.worldSize]);performance$1.scale(m,m,[1,1,this._pixelPerMeter]);this.pixelMatrix=performance$1.multiply(new Float64Array(16),this.labelPlaneMatrix,m);performance$1.translate(m,m,[0,0,-this.elevation]);this.projMatrix=m;this.invProjMatrix=performance$1.invert([],m);this.pixelMatrix3D=performance$1.multiply(new Float64Array(16),this.labelPlaneMatrix,m);const xShift=this.width%2/2,yShift=this.height%2/2,angleCos=Math.cos(this.angle),angleSin=Math.sin(this.angle),dx=x-Math.round(x)+angleCos*xShift+angleSin*yShift,dy=y-Math.round(y)+angleCos*yShift+angleSin*xShift;const alignedM=new Float64Array(m);performance$1.translate(alignedM,alignedM,[dx>.5?dx-1:dx,dy>.5?dy-1:dy,0]);this.alignedProjMatrix=alignedM;m=performance$1.invert(new Float64Array(16),this.pixelMatrix);if(!m)throw new Error("failed to invert matrix");this.pixelMatrixInverse=m;this._posMatrixCache={};this._alignedPosMatrixCache={}}maxPitchScaleFactor(){if(!this.pixelMatrixInverse)return 1;const coord=this.pointCoordinate(new performance$1.Point(0,0));const p=[coord.x*this.worldSize,coord.y*this.worldSize,0,1];const topPoint=performance$1.transformMat4(p,p,this.pixelMatrix);return topPoint[3]/this.cameraToCenterDistance}getCameraPoint(){const pitch=this._pitch;const yOffset=Math.tan(pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new performance$1.Point(0,yOffset))}getCameraQueryGeometry(queryGeometry){const c=this.getCameraPoint();if(queryGeometry.length===1){return[queryGeometry[0],c]}else{let minX=c.x;let minY=c.y;let maxX=c.x;let maxY=c.y;for(const p of queryGeometry){minX=Math.min(minX,p.x);minY=Math.min(minY,p.y);maxX=Math.max(maxX,p.x);maxY=Math.max(maxY,p.y)}return[new performance$1.Point(minX,minY),new performance$1.Point(maxX,minY),new performance$1.Point(maxX,maxY),new performance$1.Point(minX,maxY),new performance$1.Point(minX,minY)]}}lngLatToCameraDepth(lngLat,elevation){const coord=this.locationCoordinate(lngLat);const p=[coord.x*this.worldSize,coord.y*this.worldSize,elevation,1];performance$1.transformMat4(p,p,this.projMatrix);return p[2]/p[3]}}function throttle(fn,time){let pending=false;let timerId=null;let lastCallContext=null;let lastCallArgs;const later=()=>{timerId=null;if(pending){fn.apply(lastCallContext,lastCallArgs);timerId=setTimeout(later,time);pending=false}};return(...args)=>{pending=true;lastCallContext=this;lastCallArgs=args;if(!timerId){later()}return timerId}}class Hash{constructor(hashName){this._getCurrentHash=()=>{const hash=window.location.hash.replace("#","");if(this._hashName){let keyval;hash.split("&").map((part=>part.split("="))).forEach((part=>{if(part[0]===this._hashName){keyval=part}}));return(keyval?keyval[1]||"":"").split("/")}return hash.split("/")};this._onHashChange=()=>{const loc=this._getCurrentHash();if(loc.length>=3&&!loc.some((v=>isNaN(v)))){const bearing=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(loc[3]||0):this._map.getBearing();this._map.jumpTo({center:[+loc[2],+loc[1]],zoom:+loc[0],bearing:bearing,pitch:+(loc[4]||0)});return true}return false};this._updateHashUnthrottled=()=>{const location=window.location.href.replace(/(#.+)?$/,this.getHashString());try{window.history.replaceState(window.history.state,null,location)}catch(SecurityError){}};this._updateHash=throttle(this._updateHashUnthrottled,30*1e3/100);this._hashName=hashName&&encodeURIComponent(hashName)}addTo(map){this._map=map;addEventListener("hashchange",this._onHashChange,false);this._map.on("moveend",this._updateHash);return this}remove(){removeEventListener("hashchange",this._onHashChange,false);this._map.off("moveend",this._updateHash);clearTimeout(this._updateHash());delete this._map;return this}getHashString(mapFeedback){const center=this._map.getCenter(),zoom=Math.round(this._map.getZoom()*100)/100,precision=Math.ceil((zoom*Math.LN2+Math.log(512/360/.5))/Math.LN10),m=Math.pow(10,precision),lng=Math.round(center.lng*m)/m,lat=Math.round(center.lat*m)/m,bearing=this._map.getBearing(),pitch=this._map.getPitch();let hash="";if(mapFeedback){hash+=`/${lng}/${lat}/${zoom}`}else{hash+=`${zoom}/${lat}/${lng}`}if(bearing||pitch)hash+=`/${Math.round(bearing*10)/10}`;if(pitch)hash+=`/${Math.round(pitch)}`;if(this._hashName){const hashName=this._hashName;let found=false;const parts=window.location.hash.slice(1).split("&").map((part=>{const key=part.split("=")[0];if(key===hashName){found=true;return`${key}=${hash}`}return part})).filter((a=>a));if(!found){parts.push(`${hashName}=${hash}`)}return`#${parts.join("&")}`}return`#${hash}`}}const defaultInertiaOptions={linearity:.3,easing:performance$1.bezier(0,0,.3,1)};const defaultPanInertiaOptions=performance$1.extend({deceleration:2500,maxSpeed:1400},defaultInertiaOptions);const defaultZoomInertiaOptions=performance$1.extend({deceleration:20,maxSpeed:1400},defaultInertiaOptions);const defaultBearingInertiaOptions=performance$1.extend({deceleration:1e3,maxSpeed:360},defaultInertiaOptions);const defaultPitchInertiaOptions=performance$1.extend({deceleration:1e3,maxSpeed:90},defaultInertiaOptions);class HandlerInertia{constructor(map){this._map=map;this.clear()}clear(){this._inertiaBuffer=[]}record(settings){this._drainInertiaBuffer();this._inertiaBuffer.push({time:browser.now(),settings:settings})}_drainInertiaBuffer(){const inertia=this._inertiaBuffer,now=browser.now(),cutoff=160;while(inertia.length>0&&now-inertia[0].time>cutoff)inertia.shift()}_onMoveEnd(panInertiaOptions){this._drainInertiaBuffer();if(this._inertiaBuffer.length<2){return}const deltas={zoom:0,bearing:0,pitch:0,pan:new performance$1.Point(0,0),pinchAround:undefined,around:undefined};for(const{settings:settings}of this._inertiaBuffer){deltas.zoom+=settings.zoomDelta||0;deltas.bearing+=settings.bearingDelta||0;deltas.pitch+=settings.pitchDelta||0;if(settings.panDelta)deltas.pan._add(settings.panDelta);if(settings.around)deltas.around=settings.around;if(settings.pinchAround)deltas.pinchAround=settings.pinchAround}const lastEntry=this._inertiaBuffer[this._inertiaBuffer.length-1];const duration=lastEntry.time-this._inertiaBuffer[0].time;const easeOptions={};if(deltas.pan.mag()){const result=calculateEasing(deltas.pan.mag(),duration,performance$1.extend({},defaultPanInertiaOptions,panInertiaOptions||{}));easeOptions.offset=deltas.pan.mult(result.amount/deltas.pan.mag());easeOptions.center=this._map.transform.center;extendDuration(easeOptions,result)}if(deltas.zoom){const result=calculateEasing(deltas.zoom,duration,defaultZoomInertiaOptions);easeOptions.zoom=this._map.transform.zoom+result.amount;extendDuration(easeOptions,result)}if(deltas.bearing){const result=calculateEasing(deltas.bearing,duration,defaultBearingInertiaOptions);easeOptions.bearing=this._map.transform.bearing+performance$1.clamp(result.amount,-179,179);extendDuration(easeOptions,result)}if(deltas.pitch){const result=calculateEasing(deltas.pitch,duration,defaultPitchInertiaOptions);easeOptions.pitch=this._map.transform.pitch+result.amount;extendDuration(easeOptions,result)}if(easeOptions.zoom||easeOptions.bearing){const last=deltas.pinchAround===undefined?deltas.around:deltas.pinchAround;easeOptions.around=last?this._map.unproject(last):this._map.getCenter()}this.clear();return performance$1.extend(easeOptions,{noMoveStart:true})}}function extendDuration(easeOptions,result){if(!easeOptions.duration||easeOptions.durationmap.unproject(t)));const point=points.reduce(((prev,curr,i,arr)=>prev.add(curr.div(arr.length))),new performance$1.Point(0,0));const lngLat=map.unproject(point);super(type,{points:points,point:point,lngLats:lngLats,lngLat:lngLat,originalEvent:originalEvent});this._defaultPrevented=false}}class MapWheelEvent extends performance$1.Event{preventDefault(){this._defaultPrevented=true}get defaultPrevented(){return this._defaultPrevented}constructor(type,map,originalEvent){super(type,{originalEvent:originalEvent});this._defaultPrevented=false}}class MapEventHandler{constructor(map,options){this._map=map;this._clickTolerance=options.clickTolerance}reset(){delete this._mousedownPos}wheel(e){return this._firePreventable(new MapWheelEvent(e.type,this._map,e))}mousedown(e,point){this._mousedownPos=point;return this._firePreventable(new MapMouseEvent(e.type,this._map,e))}mouseup(e){this._map.fire(new MapMouseEvent(e.type,this._map,e))}click(e,point){if(this._mousedownPos&&this._mousedownPos.dist(point)>=this._clickTolerance)return;this._map.fire(new MapMouseEvent(e.type,this._map,e))}dblclick(e){return this._firePreventable(new MapMouseEvent(e.type,this._map,e))}mouseover(e){this._map.fire(new MapMouseEvent(e.type,this._map,e))}mouseout(e){this._map.fire(new MapMouseEvent(e.type,this._map,e))}touchstart(e){return this._firePreventable(new MapTouchEvent(e.type,this._map,e))}touchmove(e){this._map.fire(new MapTouchEvent(e.type,this._map,e))}touchend(e){this._map.fire(new MapTouchEvent(e.type,this._map,e))}touchcancel(e){this._map.fire(new MapTouchEvent(e.type,this._map,e))}_firePreventable(mapEvent){this._map.fire(mapEvent);if(mapEvent.defaultPrevented){return{}}}isEnabled(){return true}isActive(){return false}enable(){}disable(){}}class BlockableMapEventHandler{constructor(map){this._map=map}reset(){this._delayContextMenu=false;this._ignoreContextMenu=true;delete this._contextMenuEvent}mousemove(e){this._map.fire(new MapMouseEvent(e.type,this._map,e))}mousedown(){this._delayContextMenu=true;this._ignoreContextMenu=false}mouseup(){this._delayContextMenu=false;if(this._contextMenuEvent){this._map.fire(new MapMouseEvent("contextmenu",this._map,this._contextMenuEvent));delete this._contextMenuEvent}}contextmenu(e){if(this._delayContextMenu){this._contextMenuEvent=e}else if(!this._ignoreContextMenu){this._map.fire(new MapMouseEvent(e.type,this._map,e))}if(this._map.listens("contextmenu")){e.preventDefault()}}isEnabled(){return true}isActive(){return false}enable(){}disable(){}}class TransformProvider{constructor(map){this._map=map}get transform(){return this._map._requestedCameraState||this._map.transform}get center(){return{lng:this.transform.center.lng,lat:this.transform.center.lat}}get zoom(){return this.transform.zoom}get pitch(){return this.transform.pitch}get bearing(){return this.transform.bearing}unproject(point){return this.transform.pointLocation(performance$1.Point.convert(point),this._map.terrain)}}class BoxZoomHandler{constructor(map,options){this._map=map;this._tr=new TransformProvider(map);this._el=map.getCanvasContainer();this._container=map.getContainer();this._clickTolerance=options.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){if(this.isEnabled())return;this._enabled=true}disable(){if(!this.isEnabled())return;this._enabled=false}mousedown(e,point){if(!this.isEnabled())return;if(!(e.shiftKey&&e.button===0))return;DOM.disableDrag();this._startPos=this._lastPos=point;this._active=true}mousemoveWindow(e,point){if(!this._active)return;const pos=point;if(this._lastPos.equals(pos)||!this._box&&pos.dist(this._startPos)map.fitScreenCoordinates(p0,p1,this._tr.bearing,{linear:true})}}}keydown(e){if(!this._active)return;if(e.keyCode===27){this.reset();this._fireEvent("boxzoomcancel",e)}}reset(){this._active=false;this._container.classList.remove("maplibregl-crosshair");if(this._box){DOM.remove(this._box);this._box=null}DOM.enableDrag();delete this._startPos;delete this._lastPos}_fireEvent(type,e){return this._map.fire(new performance$1.Event(type,{originalEvent:e}))}}function indexTouches(touches,points){if(touches.length!==points.length)throw new Error(`The number of touches and points are not equal - touches ${touches.length}, points ${points.length}`);const obj={};for(let i=0;ithis.numTouches){this.aborted=true}if(this.aborted){return}if(this.startTime===undefined){this.startTime=e.timeStamp}if(mapTouches.length===this.numTouches){this.centroid=getCentroid(points);this.touches=indexTouches(mapTouches,points)}}touchmove(e,points,mapTouches){if(this.aborted||!this.centroid)return;const newTouches=indexTouches(mapTouches,points);for(const id in this.touches){const prevPos=this.touches[id];const pos=newTouches[id];if(!pos||pos.dist(prevPos)>MAX_DIST){this.aborted=true}}}touchend(e,points,mapTouches){if(!this.centroid||e.timeStamp-this.startTime>MAX_TOUCH_TIME){this.aborted=true}if(mapTouches.length===0){const centroid=!this.aborted&&this.centroid;this.reset();if(centroid)return centroid}}}class TapRecognizer{constructor(options){this.singleTap=new SingleTapRecognizer(options);this.numTaps=options.numTaps;this.reset()}reset(){this.lastTime=Infinity;delete this.lastTap;this.count=0;this.singleTap.reset()}touchstart(e,points,mapTouches){this.singleTap.touchstart(e,points,mapTouches)}touchmove(e,points,mapTouches){this.singleTap.touchmove(e,points,mapTouches)}touchend(e,points,mapTouches){const tap=this.singleTap.touchend(e,points,mapTouches);if(tap){const soonEnough=e.timeStamp-this.lastTimethis.reset()),0);return{cameraAnimation:map=>map.easeTo({duration:300,zoom:tr.zoom+1,around:tr.unproject(zoomInPoint)},{originalEvent:e})}}else if(zoomOutPoint){this._active=true;e.preventDefault();setTimeout((()=>this.reset()),0);return{cameraAnimation:map=>map.easeTo({duration:300,zoom:tr.zoom-1,around:tr.unproject(zoomOutPoint)},{originalEvent:e})}}}touchcancel(){this.reset()}enable(){this._enabled=true}disable(){this._enabled=false;this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class DragHandler{constructor(options){this._enabled=!!options.enable;this._moveStateManager=options.moveStateManager;this._clickTolerance=options.clickTolerance||1;this._moveFunction=options.move;this._activateOnStart=!!options.activateOnStart;options.assignEvents(this);this.reset()}reset(e){this._active=false;this._moved=false;delete this._lastPoint;this._moveStateManager.endMove(e)}_move(...params){const move=this._moveFunction(...params);if(move.bearingDelta||move.pitchDelta||move.around||move.panDelta){this._active=true;return move}}dragStart(e,point){if(!this.isEnabled()||this._lastPoint)return;if(!this._moveStateManager.isValidStartEvent(e))return;this._moveStateManager.startMove(e);this._lastPoint=point["length"]?point[0]:point;if(this._activateOnStart&&this._lastPoint)this._active=true}dragMove(e,point){if(!this.isEnabled())return;const lastPoint=this._lastPoint;if(!lastPoint)return;e.preventDefault();if(!this._moveStateManager.isValidMoveEvent(e)){this.reset(e);return}const movePoint=point["length"]?point[0]:point;if(!this._moved&&movePoint.dist(lastPoint){handler.mousedown=handler.dragStart;handler.mousemoveWindow=handler.dragMove;handler.mouseup=handler.dragEnd;handler.contextmenu=function(e){e.preventDefault()}};const generateMousePanHandler=({enable:enable,clickTolerance:clickTolerance})=>{const mouseMoveStateManager=new MouseMoveStateManager({checkCorrectEvent:e=>DOM.mouseButton(e)===LEFT_BUTTON&&!e.ctrlKey});return new DragHandler({clickTolerance:clickTolerance,move:(lastPoint,point)=>({around:point,panDelta:point.sub(lastPoint)}),activateOnStart:true,moveStateManager:mouseMoveStateManager,enable:enable,assignEvents:assignEvents$1})};const generateMouseRotationHandler=({enable:enable,clickTolerance:clickTolerance,bearingDegreesPerPixelMoved:bearingDegreesPerPixelMoved=.8})=>{const mouseMoveStateManager=new MouseMoveStateManager({checkCorrectEvent:e=>DOM.mouseButton(e)===LEFT_BUTTON&&e.ctrlKey||DOM.mouseButton(e)===RIGHT_BUTTON});return new DragHandler({clickTolerance:clickTolerance,move:(lastPoint,point)=>({bearingDelta:(point.x-lastPoint.x)*bearingDegreesPerPixelMoved}),moveStateManager:mouseMoveStateManager,enable:enable,assignEvents:assignEvents$1})};const generateMousePitchHandler=({enable:enable,clickTolerance:clickTolerance,pitchDegreesPerPixelMoved:pitchDegreesPerPixelMoved=-.5})=>{const mouseMoveStateManager=new MouseMoveStateManager({checkCorrectEvent:e=>DOM.mouseButton(e)===LEFT_BUTTON&&e.ctrlKey||DOM.mouseButton(e)===RIGHT_BUTTON});return new DragHandler({clickTolerance:clickTolerance,move:(lastPoint,point)=>({pitchDelta:(point.y-lastPoint.y)*pitchDegreesPerPixelMoved}),moveStateManager:mouseMoveStateManager,enable:enable,assignEvents:assignEvents$1})};class TouchPanHandler{constructor(options,map){this._clickTolerance=options.clickTolerance||1;this._map=map;this.reset()}reset(){this._active=false;this._touches={};this._sum=new performance$1.Point(0,0)}minTouchs(){return this._map.cooperativeGestures.isEnabled()?2:1}touchstart(e,points,mapTouches){return this._calculateTransform(e,points,mapTouches)}touchmove(e,points,mapTouches){if(!this._active||mapTouches.length0)this._active=true;const touches=indexTouches(mapTouches,points);const touchPointSum=new performance$1.Point(0,0);const touchDeltaSum=new performance$1.Point(0,0);let touchDeltaCount=0;for(const identifier in touches){const point=touches[identifier];const prevPoint=this._touches[identifier];if(prevPoint){touchPointSum._add(point);touchDeltaSum._add(point.sub(prevPoint));touchDeltaCount++;touches[identifier]=point}}this._touches=touches;if(touchDeltaCountMath.abs(vector.x)}const ALLOWED_SINGLE_TOUCH_TIME=100;class TwoFingersTouchPitchHandler extends TwoFingersTouchHandler{constructor(map){super();this._currentTouchCount=0;this._map=map}reset(){super.reset();this._valid=undefined;delete this._firstMove;delete this._lastPoints}touchstart(e,points,mapTouches){super.touchstart(e,points,mapTouches);this._currentTouchCount=mapTouches.length}_start(points){this._lastPoints=points;if(isVertical(points[0].sub(points[1]))){this._valid=false}}_move(points,center,e){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3){return}const vectorA=points[0].sub(this._lastPoints[0]);const vectorB=points[1].sub(this._lastPoints[1]);this._valid=this.gestureBeginsVertically(vectorA,vectorB,e.timeStamp);if(!this._valid)return;this._lastPoints=points;this._active=true;const yDeltaAverage=(vectorA.y+vectorB.y)/2;const degreesPerPixelMoved=-.5;return{pitchDelta:yDeltaAverage*degreesPerPixelMoved}}gestureBeginsVertically(vectorA,vectorB,timeStamp){if(this._valid!==undefined)return this._valid;const threshold=2;const movedA=vectorA.mag()>=threshold;const movedB=vectorB.mag()>=threshold;if(!movedA&&!movedB)return;if(!movedA||!movedB){if(this._firstMove===undefined){this._firstMove=timeStamp}if(timeStamp-this._firstMove0===vectorB.y>0;return isVertical(vectorA)&&isVertical(vectorB)&&isSameDirection}}const defaultOptions$5={panStep:100,bearingStep:15,pitchStep:10};class KeyboardHandler{constructor(map){this._tr=new TransformProvider(map);const stepOptions=defaultOptions$5;this._panStep=stepOptions.panStep;this._bearingStep=stepOptions.bearingStep;this._pitchStep=stepOptions.pitchStep;this._rotationDisabled=false}reset(){this._active=false}keydown(e){if(e.altKey||e.ctrlKey||e.metaKey)return;let zoomDir=0;let bearingDir=0;let pitchDir=0;let xDir=0;let yDir=0;switch(e.keyCode){case 61:case 107:case 171:case 187:zoomDir=1;break;case 189:case 109:case 173:zoomDir=-1;break;case 37:if(e.shiftKey){bearingDir=-1}else{e.preventDefault();xDir=-1}break;case 39:if(e.shiftKey){bearingDir=1}else{e.preventDefault();xDir=1}break;case 38:if(e.shiftKey){pitchDir=1}else{e.preventDefault();yDir=-1}break;case 40:if(e.shiftKey){pitchDir=-1}else{e.preventDefault();yDir=1}break;default:return}if(this._rotationDisabled){bearingDir=0;pitchDir=0}return{cameraAnimation:map=>{const tr=this._tr;map.easeTo({duration:300,easeId:"keyboardHandler",easing:easeOut,zoom:zoomDir?Math.round(tr.zoom)+zoomDir*(e.shiftKey?2:1):tr.zoom,bearing:tr.bearing+bearingDir*this._bearingStep,pitch:tr.pitch+pitchDir*this._pitchStep,offset:[-xDir*this._panStep,-yDir*this._panStep],center:tr.center},{originalEvent:e})}}}enable(){this._enabled=true}disable(){this._enabled=false;this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=true}enableRotation(){this._rotationDisabled=false}}function easeOut(t){return t*(2-t)}const wheelZoomDelta=4.000244140625;const defaultZoomRate=1/100;const wheelZoomRate=1/450;const maxScalePerFrame=2;class ScrollZoomHandler{constructor(map,triggerRenderFrame){this._onTimeout=initialEvent=>{this._type="wheel";this._delta-=this._lastValue;if(!this._active){this._start(initialEvent)}};this._map=map;this._tr=new TransformProvider(map);this._triggerRenderFrame=triggerRenderFrame;this._delta=0;this._defaultZoomRate=defaultZoomRate;this._wheelZoomRate=wheelZoomRate}setZoomRate(zoomRate){this._defaultZoomRate=zoomRate}setWheelZoomRate(wheelZoomRate){this._wheelZoomRate=wheelZoomRate}isEnabled(){return!!this._enabled}isActive(){return!!this._active||this._finishTimeout!==undefined}isZooming(){return!!this._zooming}enable(options){if(this.isEnabled())return;this._enabled=true;this._aroundCenter=!!options&&options.around==="center"}disable(){if(!this.isEnabled())return;this._enabled=false}wheel(e){if(!this.isEnabled())return;if(this._map.cooperativeGestures.isEnabled()&&!e[this._map.cooperativeGestures._bypassKey]){return}let value=e.deltaMode===WheelEvent.DOM_DELTA_LINE?e.deltaY*40:e.deltaY;const now=browser.now(),timeDelta=now-(this._lastWheelEventTime||0);this._lastWheelEventTime=now;if(value!==0&&value%wheelZoomDelta===0){this._type="wheel"}else if(value!==0&&Math.abs(value)<4){this._type="trackpad"}else if(timeDelta>400){this._type=null;this._lastValue=value;this._timeout=setTimeout(this._onTimeout,40,e)}else if(!this._type){this._type=Math.abs(timeDelta*value)<200?"trackpad":"wheel";if(this._timeout){clearTimeout(this._timeout);this._timeout=null;value+=this._lastValue}}if(e.shiftKey&&value)value=value/4;if(this._type){this._lastWheelEvent=e;this._delta-=value;if(!this._active){this._start(e)}}e.preventDefault()}_start(e){if(!this._delta)return;if(this._frameId){this._frameId=null}this._active=true;if(!this.isZooming()){this._zooming=true}if(this._finishTimeout){clearTimeout(this._finishTimeout);delete this._finishTimeout}const pos=DOM.mousePos(this._map.getCanvas(),e);const tr=this._tr;if(pos.y>tr.transform.height/2-tr.transform.getHorizon()){this._around=performance$1.LngLat.convert(this._aroundCenter?tr.center:tr.unproject(pos))}else{this._around=performance$1.LngLat.convert(tr.center)}this._aroundPoint=tr.transform.locationPoint(this._around);if(!this._frameId){this._frameId=true;this._triggerRenderFrame()}}renderFrame(){if(!this._frameId)return;this._frameId=null;if(!this.isActive())return;const tr=this._tr.transform;if(this._delta!==0){const zoomRate=this._type==="wheel"&&Math.abs(this._delta)>wheelZoomDelta?this._wheelZoomRate:this._defaultZoomRate;let scale=maxScalePerFrame/(1+Math.exp(-Math.abs(this._delta*zoomRate)));if(this._delta<0&&scale!==0){scale=1/scale}const fromScale=typeof this._targetZoom==="number"?tr.zoomScale(this._targetZoom):tr.scale;this._targetZoom=Math.min(tr.maxZoom,Math.max(tr.minZoom,tr.scaleZoom(fromScale*scale)));if(this._type==="wheel"){this._startZoom=tr.zoom;this._easing=this._smoothOutEasing(200)}this._delta=0}const targetZoom=typeof this._targetZoom==="number"?this._targetZoom:tr.zoom;const startZoom=this._startZoom;const easing=this._easing;let finished=false;let zoom;if(this._type==="wheel"&&startZoom&&easing){const t=Math.min((browser.now()-this._lastWheelEventTime)/200,1);const k=easing(t);zoom=performance$1.interpolate.number(startZoom,targetZoom,k);if(t<1){if(!this._frameId){this._frameId=true}}else{finished=true}}else{zoom=targetZoom;finished=true}this._active=true;if(finished){this._active=false;this._finishTimeout=setTimeout((()=>{this._zooming=false;this._triggerRenderFrame();delete this._targetZoom;delete this._finishTimeout}),200)}return{noInertia:true,needsRenderFrame:!finished,zoomDelta:zoom-tr.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(duration){let easing=performance$1.defaultEasing;if(this._prevEase){const currentEase=this._prevEase;const t=(browser.now()-currentEase.start)/currentEase.duration;const speed=currentEase.easing(t+.01)-currentEase.easing(t);const x=.27/Math.sqrt(speed*speed+1e-4)*.01;const y=Math.sqrt(.27*.27-x*x);easing=performance$1.bezier(x,y,.25,1)}this._prevEase={start:browser.now(),duration:duration,easing:easing};return easing}reset(){this._active=false;this._zooming=false;delete this._targetZoom;if(this._finishTimeout){clearTimeout(this._finishTimeout);delete this._finishTimeout}}}class DoubleClickZoomHandler{constructor(clickZoom,TapZoom){this._clickZoom=clickZoom;this._tapZoom=TapZoom}enable(){this._clickZoom.enable();this._tapZoom.enable()}disable(){this._clickZoom.disable();this._tapZoom.disable()}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class ClickZoomHandler{constructor(map){this._tr=new TransformProvider(map);this.reset()}reset(){this._active=false}dblclick(e,point){e.preventDefault();return{cameraAnimation:map=>{map.easeTo({duration:300,zoom:this._tr.zoom+(e.shiftKey?-1:1),around:this._tr.unproject(point)},{originalEvent:e})}}}enable(){this._enabled=true}disable(){this._enabled=false;this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class TapDragZoomHandler{constructor(){this._tap=new TapRecognizer({numTouches:1,numTaps:1});this.reset()}reset(){this._active=false;delete this._swipePoint;delete this._swipeTouch;delete this._tapTime;delete this._tapPoint;this._tap.reset()}touchstart(e,points,mapTouches){if(this._swipePoint)return;if(!this._tapTime){this._tap.touchstart(e,points,mapTouches)}else{const swipePoint=points[0];const soonEnough=e.timeStamp-this._tapTime0){this._swipePoint=swipePoint;this._swipeTouch=mapTouches[0].identifier}}}touchmove(e,points,mapTouches){if(!this._tapTime){this._tap.touchmove(e,points,mapTouches)}else if(this._swipePoint){if(mapTouches[0].identifier!==this._swipeTouch){return}const newSwipePoint=points[0];const dist=newSwipePoint.y-this._swipePoint.y;this._swipePoint=newSwipePoint;e.preventDefault();this._active=true;return{zoomDelta:dist/128}}}touchend(e,points,mapTouches){if(!this._tapTime){const point=this._tap.touchend(e,points,mapTouches);if(point){this._tapTime=e.timeStamp;this._tapPoint=point}}else if(this._swipePoint){if(mapTouches.length===0){this.reset()}}}touchcancel(){this.reset()}enable(){this._enabled=true}disable(){this._enabled=false;this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class DragPanHandler{constructor(el,mousePan,touchPan){this._el=el;this._mousePan=mousePan;this._touchPan=touchPan}enable(options){this._inertiaOptions=options||{};this._mousePan.enable();this._touchPan.enable();this._el.classList.add("maplibregl-touch-drag-pan")}disable(){this._mousePan.disable();this._touchPan.disable();this._el.classList.remove("maplibregl-touch-drag-pan")}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class DragRotateHandler{constructor(options,mouseRotate,mousePitch){this._pitchWithRotate=options.pitchWithRotate;this._mouseRotate=mouseRotate;this._mousePitch=mousePitch}enable(){this._mouseRotate.enable();if(this._pitchWithRotate)this._mousePitch.enable()}disable(){this._mouseRotate.disable();this._mousePitch.disable()}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()}}class TwoFingersTouchZoomRotateHandler{constructor(el,touchZoom,touchRotate,tapDragZoom){this._el=el;this._touchZoom=touchZoom;this._touchRotate=touchRotate;this._tapDragZoom=tapDragZoom;this._rotationDisabled=false;this._enabled=true}enable(options){this._touchZoom.enable(options);if(!this._rotationDisabled)this._touchRotate.enable(options);this._tapDragZoom.enable();this._el.classList.add("maplibregl-touch-zoom-rotate")}disable(){this._touchZoom.disable();this._touchRotate.disable();this._tapDragZoom.disable();this._el.classList.remove("maplibregl-touch-zoom-rotate")}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=true;this._touchRotate.disable()}enableRotation(){this._rotationDisabled=false;if(this._touchZoom.isEnabled())this._touchRotate.enable()}}class CooperativeGesturesHandler{constructor(map,options){this._bypassKey=navigator.userAgent.indexOf("Mac")!==-1?"metaKey":"ctrlKey";this._map=map;this._options=options;this._enabled=false}isActive(){return false}reset(){}_setupUI(){if(this._container)return;const mapCanvasContainer=this._map.getCanvasContainer();mapCanvasContainer.classList.add("maplibregl-cooperative-gestures");this._container=DOM.create("div","maplibregl-cooperative-gesture-screen",mapCanvasContainer);let desktopMessage=this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");if(this._bypassKey==="metaKey"){desktopMessage=this._map._getUIString("CooperativeGesturesHandler.MacHelpText")}const mobileMessage=this._map._getUIString("CooperativeGesturesHandler.MobileHelpText");const desktopDiv=document.createElement("div");desktopDiv.className="maplibregl-desktop-message";desktopDiv.textContent=desktopMessage;this._container.appendChild(desktopDiv);const mobileDiv=document.createElement("div");mobileDiv.className="maplibregl-mobile-message";mobileDiv.textContent=mobileMessage;this._container.appendChild(mobileDiv);this._container.setAttribute("aria-hidden","true")}_destoryUI(){if(this._container){DOM.remove(this._container);const mapCanvasContainer=this._map.getCanvasContainer();mapCanvasContainer.classList.remove("maplibregl-cooperative-gestures")}delete this._container}enable(){this._setupUI();this._enabled=true}disable(){this._enabled=false;this._destoryUI()}isEnabled(){return this._enabled}touchmove(e){this._onCooperativeGesture(e.touches.length===1)}wheel(e){if(!this._map.scrollZoom.isEnabled()){return}this._onCooperativeGesture(!e[this._bypassKey])}_onCooperativeGesture(showNotification){if(!this._enabled||!showNotification)return;this._container.classList.add("maplibregl-show");setTimeout((()=>{this._container.classList.remove("maplibregl-show")}),100)}}const isMoving=p=>p.zoom||p.drag||p.pitch||p.rotate;class RenderFrameEvent extends performance$1.Event{}function hasChange(result){return result.panDelta&&result.panDelta.mag()||result.zoomDelta||result.bearingDelta||result.pitchDelta}class HandlerManager{constructor(map,options){this.handleWindowEvent=e=>{this.handleEvent(e,`${e.type}Window`)};this.handleEvent=(e,eventName)=>{if(e.type==="blur"){this.stop(true);return}this._updatingCamera=true;const inputEvent=e.type==="renderFrame"?undefined:e;const mergedHandlerResult={needsRenderFrame:false};const eventsInProgress={};const activeHandlers={};const eventTouches=e.touches;const mapTouches=eventTouches?this._getMapTouches(eventTouches):undefined;const points=mapTouches?DOM.touchPos(this._map.getCanvas(),mapTouches):DOM.mousePos(this._map.getCanvas(),e);for(const{handlerName:handlerName,handler:handler,allowed:allowed}of this._handlers){if(!handler.isEnabled())continue;let data;if(this._blockedByActive(activeHandlers,allowed,handlerName)){handler.reset()}else{if(handler[eventName||e.type]){data=handler[eventName||e.type](e,points,mapTouches);this.mergeHandlerResult(mergedHandlerResult,eventsInProgress,data,handlerName,inputEvent);if(data&&data.needsRenderFrame){this._triggerRenderFrame()}}}if(data||handler.isActive()){activeHandlers[handlerName]=handler}}const deactivatedHandlers={};for(const name in this._previousActiveHandlers){if(!activeHandlers[name]){deactivatedHandlers[name]=inputEvent}}this._previousActiveHandlers=activeHandlers;if(Object.keys(deactivatedHandlers).length||hasChange(mergedHandlerResult)){this._changes.push([mergedHandlerResult,eventsInProgress,deactivatedHandlers]);this._triggerRenderFrame()}if(Object.keys(activeHandlers).length||hasChange(mergedHandlerResult)){this._map._stop(true)}this._updatingCamera=false;const{cameraAnimation:cameraAnimation}=mergedHandlerResult;if(cameraAnimation){this._inertia.clear();this._fireEvents({},{},true);this._changes=[];cameraAnimation(this._map)}};this._map=map;this._el=this._map.getCanvasContainer();this._handlers=[];this._handlersById={};this._changes=[];this._inertia=new HandlerInertia(map);this._bearingSnap=options.bearingSnap;this._previousActiveHandlers={};this._eventsInProgress={};this._addDefaultHandlers(options);const el=this._el;this._listeners=[[el,"touchstart",{passive:true}],[el,"touchmove",{passive:false}],[el,"touchend",undefined],[el,"touchcancel",undefined],[el,"mousedown",undefined],[el,"mousemove",undefined],[el,"mouseup",undefined],[document,"mousemove",{capture:true}],[document,"mouseup",undefined],[el,"mouseover",undefined],[el,"mouseout",undefined],[el,"dblclick",undefined],[el,"click",undefined],[el,"keydown",{capture:false}],[el,"keyup",undefined],[el,"wheel",{passive:false}],[el,"contextmenu",undefined],[window,"blur",undefined]];for(const[target,type,listenerOptions]of this._listeners){DOM.addEventListener(target,type,target===document?this.handleWindowEvent:this.handleEvent,listenerOptions)}}destroy(){for(const[target,type,listenerOptions]of this._listeners){DOM.removeEventListener(target,type,target===document?this.handleWindowEvent:this.handleEvent,listenerOptions)}}_addDefaultHandlers(options){const map=this._map;const el=map.getCanvasContainer();this._add("mapEvent",new MapEventHandler(map,options));const boxZoom=map.boxZoom=new BoxZoomHandler(map,options);this._add("boxZoom",boxZoom);if(options.interactive&&options.boxZoom){boxZoom.enable()}const cooperativeGestures=map.cooperativeGestures=new CooperativeGesturesHandler(map,options.cooperativeGestures);this._add("cooperativeGestures",cooperativeGestures);if(options.cooperativeGestures){cooperativeGestures.enable()}const tapZoom=new TapZoomHandler(map);const clickZoom=new ClickZoomHandler(map);map.doubleClickZoom=new DoubleClickZoomHandler(clickZoom,tapZoom);this._add("tapZoom",tapZoom);this._add("clickZoom",clickZoom);if(options.interactive&&options.doubleClickZoom){map.doubleClickZoom.enable()}const tapDragZoom=new TapDragZoomHandler;this._add("tapDragZoom",tapDragZoom);const touchPitch=map.touchPitch=new TwoFingersTouchPitchHandler(map);this._add("touchPitch",touchPitch);if(options.interactive&&options.touchPitch){map.touchPitch.enable(options.touchPitch)}const mouseRotate=generateMouseRotationHandler(options);const mousePitch=generateMousePitchHandler(options);map.dragRotate=new DragRotateHandler(options,mouseRotate,mousePitch);this._add("mouseRotate",mouseRotate,["mousePitch"]);this._add("mousePitch",mousePitch,["mouseRotate"]);if(options.interactive&&options.dragRotate){map.dragRotate.enable()}const mousePan=generateMousePanHandler(options);const touchPan=new TouchPanHandler(options,map);map.dragPan=new DragPanHandler(el,mousePan,touchPan);this._add("mousePan",mousePan);this._add("touchPan",touchPan,["touchZoom","touchRotate"]);if(options.interactive&&options.dragPan){map.dragPan.enable(options.dragPan)}const touchRotate=new TwoFingersTouchRotateHandler;const touchZoom=new TwoFingersTouchZoomHandler;map.touchZoomRotate=new TwoFingersTouchZoomRotateHandler(el,touchZoom,touchRotate,tapDragZoom);this._add("touchRotate",touchRotate,["touchPan","touchZoom"]);this._add("touchZoom",touchZoom,["touchPan","touchRotate"]);if(options.interactive&&options.touchZoomRotate){map.touchZoomRotate.enable(options.touchZoomRotate)}const scrollZoom=map.scrollZoom=new ScrollZoomHandler(map,(()=>this._triggerRenderFrame()));this._add("scrollZoom",scrollZoom,["mousePan"]);if(options.interactive&&options.scrollZoom){map.scrollZoom.enable(options.scrollZoom)}const keyboard=map.keyboard=new KeyboardHandler(map);this._add("keyboard",keyboard);if(options.interactive&&options.keyboard){map.keyboard.enable()}this._add("blockableMapEvent",new BlockableMapEventHandler(map))}_add(handlerName,handler,allowed){this._handlers.push({handlerName:handlerName,handler:handler,allowed:allowed});this._handlersById[handlerName]=handler}stop(allowEndAnimation){if(this._updatingCamera)return;for(const{handler:handler}of this._handlers){handler.reset()}this._inertia.clear();this._fireEvents({},{},allowEndAnimation);this._changes=[]}isActive(){for(const{handler:handler}of this._handlers){if(handler.isActive())return true}return false}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return Boolean(isMoving(this._eventsInProgress))||this.isZooming()}_blockedByActive(activeHandlers,allowed,myName){for(const name in activeHandlers){if(name===myName)continue;if(!allowed||allowed.indexOf(name)<0){return true}}return false}_getMapTouches(touches){const mapTouches=[];for(const t of touches){const target=t.target;if(this._el.contains(target)){mapTouches.push(t)}}return mapTouches}mergeHandlerResult(mergedHandlerResult,eventsInProgress,handlerResult,name,e){if(!handlerResult)return;performance$1.extend(mergedHandlerResult,handlerResult);const eventData={handlerName:name,originalEvent:handlerResult.originalEvent||e};if(handlerResult.zoomDelta!==undefined){eventsInProgress.zoom=eventData}if(handlerResult.panDelta!==undefined){eventsInProgress.drag=eventData}if(handlerResult.pitchDelta!==undefined){eventsInProgress.pitch=eventData}if(handlerResult.bearingDelta!==undefined){eventsInProgress.rotate=eventData}}_applyChanges(){const combined={};const combinedEventsInProgress={};const combinedDeactivatedHandlers={};for(const[change,eventsInProgress,deactivatedHandlers]of this._changes){if(change.panDelta)combined.panDelta=(combined.panDelta||new performance$1.Point(0,0))._add(change.panDelta);if(change.zoomDelta)combined.zoomDelta=(combined.zoomDelta||0)+change.zoomDelta;if(change.bearingDelta)combined.bearingDelta=(combined.bearingDelta||0)+change.bearingDelta;if(change.pitchDelta)combined.pitchDelta=(combined.pitchDelta||0)+change.pitchDelta;if(change.around!==undefined)combined.around=change.around;if(change.pinchAround!==undefined)combined.pinchAround=change.pinchAround;if(change.noInertia)combined.noInertia=change.noInertia;performance$1.extend(combinedEventsInProgress,eventsInProgress);performance$1.extend(combinedDeactivatedHandlers,deactivatedHandlers)}this._updateMapTransform(combined,combinedEventsInProgress,combinedDeactivatedHandlers);this._changes=[]}_updateMapTransform(combinedResult,combinedEventsInProgress,deactivatedHandlers){const map=this._map;const tr=map._getTransformForUpdate();const terrain=map.terrain;if(!hasChange(combinedResult)&&!(terrain&&this._terrainMovement)){return this._fireEvents(combinedEventsInProgress,deactivatedHandlers,true)}let{panDelta:panDelta,zoomDelta:zoomDelta,bearingDelta:bearingDelta,pitchDelta:pitchDelta,around:around,pinchAround:pinchAround}=combinedResult;if(pinchAround!==undefined){around=pinchAround}map._stop(true);around=around||map.transform.centerPoint;const loc=tr.pointLocation(panDelta?around.sub(panDelta):around);if(bearingDelta)tr.bearing+=bearingDelta;if(pitchDelta)tr.pitch+=pitchDelta;if(zoomDelta)tr.zoom+=zoomDelta;if(!terrain){tr.setLocationAtPoint(loc,around)}else{if(!this._terrainMovement&&(combinedEventsInProgress.drag||combinedEventsInProgress.zoom)){this._terrainMovement=true;this._map._elevationFreeze=true;tr.setLocationAtPoint(loc,around);this._map.once("moveend",(()=>{this._map._elevationFreeze=false;this._terrainMovement=false;tr.recalculateZoom(map.terrain)}))}else if(combinedEventsInProgress.drag&&this._terrainMovement){tr.center=tr.pointLocation(tr.centerPoint.sub(panDelta))}else{tr.setLocationAtPoint(loc,around)}}map._applyUpdatedTransform(tr);this._map._update();if(!combinedResult.noInertia)this._inertia.record(combinedResult);this._fireEvents(combinedEventsInProgress,deactivatedHandlers,true)}_fireEvents(newEventsInProgress,deactivatedHandlers,allowEndAnimation){const wasMoving=isMoving(this._eventsInProgress);const nowMoving=isMoving(newEventsInProgress);const startEvents={};for(const eventName in newEventsInProgress){const{originalEvent:originalEvent}=newEventsInProgress[eventName];if(!this._eventsInProgress[eventName]){startEvents[`${eventName}start`]=originalEvent}this._eventsInProgress[eventName]=newEventsInProgress[eventName]}if(!wasMoving&&nowMoving){this._fireEvent("movestart",nowMoving.originalEvent)}for(const name in startEvents){this._fireEvent(name,startEvents[name])}if(nowMoving){this._fireEvent("move",nowMoving.originalEvent)}for(const eventName in newEventsInProgress){const{originalEvent:originalEvent}=newEventsInProgress[eventName];this._fireEvent(eventName,originalEvent)}const endEvents={};let originalEndEvent;for(const eventName in this._eventsInProgress){const{handlerName:handlerName,originalEvent:originalEvent}=this._eventsInProgress[eventName];if(!this._handlersById[handlerName].isActive()){delete this._eventsInProgress[eventName];originalEndEvent=deactivatedHandlers[handlerName]||originalEvent;endEvents[`${eventName}end`]=originalEndEvent}}for(const name in endEvents){this._fireEvent(name,endEvents[name])}const stillMoving=isMoving(this._eventsInProgress);if(allowEndAnimation&&(wasMoving||nowMoving)&&!stillMoving){this._updatingCamera=true;const inertialEase=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions);const shouldSnapToNorth=bearing=>bearing!==0&&-this._bearingSnap{delete this._frameId;this.handleEvent(new RenderFrameEvent("renderFrame",{timeStamp:timeStamp}));this._applyChanges()}))}_triggerRenderFrame(){if(this._frameId===undefined){this._frameId=this._requestFrame()}}}class Camera extends performance$1.Evented{constructor(transform,options){super();this._renderFrameCallback=()=>{const t=Math.min((browser.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(t));if(t<1&&this._easeFrameId){this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback)}else{this.stop()}};this._moving=false;this._zooming=false;this.transform=transform;this._bearingSnap=options.bearingSnap;this.on("moveend",(()=>{delete this._requestedCameraState}))}getCenter(){return new performance$1.LngLat(this.transform.center.lng,this.transform.center.lat)}setCenter(center,eventData){return this.jumpTo({center:center},eventData)}panBy(offset,options,eventData){offset=performance$1.Point.convert(offset).mult(-1);return this.panTo(this.transform.center,performance$1.extend({offset:offset},options),eventData)}panTo(lnglat,options,eventData){return this.easeTo(performance$1.extend({center:lnglat},options),eventData)}getZoom(){return this.transform.zoom}setZoom(zoom,eventData){this.jumpTo({zoom:zoom},eventData);return this}zoomTo(zoom,options,eventData){return this.easeTo(performance$1.extend({zoom:zoom},options),eventData)}zoomIn(options,eventData){this.zoomTo(this.getZoom()+1,options,eventData);return this}zoomOut(options,eventData){this.zoomTo(this.getZoom()-1,options,eventData);return this}getBearing(){return this.transform.bearing}setBearing(bearing,eventData){this.jumpTo({bearing:bearing},eventData);return this}getPadding(){return this.transform.padding}setPadding(padding,eventData){this.jumpTo({padding:padding},eventData);return this}rotateTo(bearing,options,eventData){return this.easeTo(performance$1.extend({bearing:bearing},options),eventData)}resetNorth(options,eventData){this.rotateTo(0,performance$1.extend({duration:1e3},options),eventData);return this}resetNorthPitch(options,eventData){this.easeTo(performance$1.extend({bearing:0,pitch:0,duration:1e3},options),eventData);return this}snapToNorth(options,eventData){if(Math.abs(this.getBearing()){if(this._zooming){tr.zoom=performance$1.interpolate.number(startZoom,zoom,k)}if(this._rotating){tr.bearing=performance$1.interpolate.number(startBearing,bearing,k)}if(this._pitching){tr.pitch=performance$1.interpolate.number(startPitch,pitch,k)}if(this._padding){tr.interpolatePadding(startPadding,padding,k);pointAtOffset=tr.centerPoint.add(offsetAsPoint)}if(this.terrain&&!options.freezeElevation)this._updateElevation(k);if(around){tr.setLocationAtPoint(around,aroundPoint)}else{const scale=tr.zoomScale(tr.zoom-startZoom);const base=zoom>startZoom?Math.min(2,finalScale):Math.max(.5,finalScale);const speedup=Math.pow(base,1-k);const newCenter=tr.unproject(from.add(delta.mult(k*speedup)).mult(scale));tr.setLocationAtPoint(tr.renderWorldCopies?newCenter.wrap():newCenter,pointAtOffset)}this._applyUpdatedTransform(tr);this._fireMoveEvents(eventData)}),(interruptingEaseId=>{if(this.terrain)this._finalizeElevation();this._afterEase(eventData,interruptingEaseId)}),options);return this}_prepareEase(eventData,noMoveStart,currently={}){this._moving=true;if(!noMoveStart&&!currently.moving){this.fire(new performance$1.Event("movestart",eventData))}if(this._zooming&&!currently.zooming){this.fire(new performance$1.Event("zoomstart",eventData))}if(this._rotating&&!currently.rotating){this.fire(new performance$1.Event("rotatestart",eventData))}if(this._pitching&&!currently.pitching){this.fire(new performance$1.Event("pitchstart",eventData))}}_prepareElevation(center){this._elevationCenter=center;this._elevationStart=this.transform.elevation;this._elevationTarget=this.terrain.getElevationForLngLatZoom(center,this.transform.tileZoom);this._elevationFreeze=true}_updateElevation(k){this.transform.minElevationForCurrentTile=this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);const elevation=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(k<1&&elevation!==this._elevationTarget){const pitch1=this._elevationTarget-this._elevationStart;const pitch2=(elevation-(pitch1*k+this._elevationStart))/(1-k);this._elevationStart+=k*(pitch1-pitch2);this._elevationTarget=elevation}this.transform.elevation=performance$1.interpolate.number(this._elevationStart,this._elevationTarget,k)}_finalizeElevation(){this._elevationFreeze=false;this.transform.recalculateZoom(this.terrain)}_getTransformForUpdate(){if(!this.transformCameraUpdate)return this.transform;if(!this._requestedCameraState){this._requestedCameraState=this.transform.clone()}return this._requestedCameraState}_applyUpdatedTransform(tr){if(!this.transformCameraUpdate)return;const nextTransform=tr.clone();const{center:center,zoom:zoom,pitch:pitch,bearing:bearing,elevation:elevation}=this.transformCameraUpdate(nextTransform);if(center)nextTransform.center=center;if(zoom!==undefined)nextTransform.zoom=zoom;if(pitch!==undefined)nextTransform.pitch=pitch;if(bearing!==undefined)nextTransform.bearing=bearing;if(elevation!==undefined)nextTransform.elevation=elevation;this.transform.apply(nextTransform)}_fireMoveEvents(eventData){this.fire(new performance$1.Event("move",eventData));if(this._zooming){this.fire(new performance$1.Event("zoom",eventData))}if(this._rotating){this.fire(new performance$1.Event("rotate",eventData))}if(this._pitching){this.fire(new performance$1.Event("pitch",eventData))}}_afterEase(eventData,easeId){if(this._easeId&&easeId&&this._easeId===easeId){return}delete this._easeId;const wasZooming=this._zooming;const wasRotating=this._rotating;const wasPitching=this._pitching;this._moving=false;this._zooming=false;this._rotating=false;this._pitching=false;this._padding=false;if(wasZooming){this.fire(new performance$1.Event("zoomend",eventData))}if(wasRotating){this.fire(new performance$1.Event("rotateend",eventData))}if(wasPitching){this.fire(new performance$1.Event("pitchend",eventData))}this.fire(new performance$1.Event("moveend",eventData))}flyTo(options,eventData){if(!options.essential&&browser.prefersReducedMotion){const coercedOptions=performance$1.pick(options,["center","zoom","bearing","pitch","around"]);return this.jumpTo(coercedOptions,eventData)}this.stop();options=performance$1.extend({offset:[0,0],speed:1.2,curve:1.42,easing:performance$1.defaultEasing},options);const tr=this._getTransformForUpdate(),startZoom=this.getZoom(),startBearing=this.getBearing(),startPitch=this.getPitch(),startPadding=this.getPadding();const zoom="zoom"in options?performance$1.clamp(+options.zoom,tr.minZoom,tr.maxZoom):startZoom;const bearing="bearing"in options?this._normalizeBearing(options.bearing,startBearing):startBearing;const pitch="pitch"in options?+options.pitch:startPitch;const padding="padding"in options?options.padding:tr.padding;const scale=tr.zoomScale(zoom-startZoom);const offsetAsPoint=performance$1.Point.convert(options.offset);let pointAtOffset=tr.centerPoint.add(offsetAsPoint);const locationAtOffset=tr.pointLocation(pointAtOffset);const center=performance$1.LngLat.convert(options.center||locationAtOffset);this._normalizeCenter(center);const from=tr.project(locationAtOffset);const delta=tr.project(center).sub(from);let rho=options.curve;const w0=Math.max(tr.width,tr.height),w1=w0/scale,u1=delta.mag();if("minZoom"in options){const minZoom=performance$1.clamp(Math.min(options.minZoom,startZoom,zoom),tr.minZoom,tr.maxZoom);const wMax=w0/tr.zoomScale(minZoom-startZoom);rho=Math.sqrt(wMax/u1*2)}const rho2=rho*rho;function zoomOutFactor(descent){const b=(w1*w1-w0*w0+(descent?-1:1)*rho2*rho2*u1*u1)/(2*(descent?w1:w0)*rho2*u1);return Math.log(Math.sqrt(b*b+1)-b)}function sinh(n){return(Math.exp(n)-Math.exp(-n))/2}function cosh(n){return(Math.exp(n)+Math.exp(-n))/2}function tanh(n){return sinh(n)/cosh(n)}const r0=zoomOutFactor(false);let w=function(s){return cosh(r0)/cosh(r0+rho*s)};let u=function(s){return w0*((cosh(r0)*tanh(r0+rho*s)-sinh(r0))/rho2)/u1};let S=(zoomOutFactor(true)-r0)/rho;if(Math.abs(u1)<1e-6||!isFinite(S)){if(Math.abs(w0-w1)<1e-6)return this.easeTo(options,eventData);const k=w1options.maxDuration){options.duration=0}this._zooming=true;this._rotating=startBearing!==bearing;this._pitching=pitch!==startPitch;this._padding=!tr.isPaddingEqual(padding);this._prepareEase(eventData,false);if(this.terrain)this._prepareElevation(center);this._ease((k=>{const s=k*S;const scale=1/w(s);tr.zoom=k===1?zoom:startZoom+tr.scaleZoom(scale);if(this._rotating){tr.bearing=performance$1.interpolate.number(startBearing,bearing,k)}if(this._pitching){tr.pitch=performance$1.interpolate.number(startPitch,pitch,k)}if(this._padding){tr.interpolatePadding(startPadding,padding,k);pointAtOffset=tr.centerPoint.add(offsetAsPoint)}if(this.terrain&&!options.freezeElevation)this._updateElevation(k);const newCenter=k===1?center:tr.unproject(from.add(delta.mult(u(s))).mult(scale));tr.setLocationAtPoint(tr.renderWorldCopies?newCenter.wrap():newCenter,pointAtOffset);this._applyUpdatedTransform(tr);this._fireMoveEvents(eventData)}),(()=>{if(this.terrain)this._finalizeElevation();this._afterEase(eventData)}),options);return this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_stop(allowGestures,easeId){if(this._easeFrameId){this._cancelRenderFrame(this._easeFrameId);delete this._easeFrameId;delete this._onEaseFrame}if(this._onEaseEnd){const onEaseEnd=this._onEaseEnd;delete this._onEaseEnd;onEaseEnd.call(this,easeId)}if(!allowGestures){const handlers=this.handlers;if(handlers)handlers.stop(false)}return this}_ease(frame,finish,options){if(options.animate===false||options.duration===0){frame(1);finish()}else{this._easeStart=browser.now();this._easeOptions=options;this._onEaseFrame=frame;this._onEaseEnd=finish;this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback)}}_normalizeBearing(bearing,currentBearing){bearing=performance$1.wrap(bearing,-180,180);const diff=Math.abs(bearing-currentBearing);if(Math.abs(bearing-360-currentBearing)180?-360:delta<-180?360:0}queryTerrainElevation(lngLatLike){if(!this.terrain){return null}const elevation=this.terrain.getElevationForLngLatZoom(performance$1.LngLat.convert(lngLatLike),this.transform.tileZoom);return elevation-this.transform.elevation}}const defaultAtributionControlOptions={compact:true,customAttribution:'MapLibre'};class AttributionControl{constructor(options=defaultAtributionControlOptions){this._toggleAttribution=()=>{if(this._container.classList.contains("maplibregl-compact")){if(this._container.classList.contains("maplibregl-compact-show")){this._container.setAttribute("open","");this._container.classList.remove("maplibregl-compact-show")}else{this._container.classList.add("maplibregl-compact-show");this._container.removeAttribute("open")}}};this._updateData=e=>{if(e&&(e.sourceDataType==="metadata"||e.sourceDataType==="visibility"||e.dataType==="style"||e.type==="terrain")){this._updateAttributions()}};this._updateCompact=()=>{if(this._map.getCanvasContainer().offsetWidth<=640||this._compact){if(this._compact===false){this._container.setAttribute("open","")}else if(!this._container.classList.contains("maplibregl-compact")&&!this._container.classList.contains("maplibregl-attrib-empty")){this._container.setAttribute("open","");this._container.classList.add("maplibregl-compact","maplibregl-compact-show")}}else{this._container.setAttribute("open","");if(this._container.classList.contains("maplibregl-compact")){this._container.classList.remove("maplibregl-compact","maplibregl-compact-show")}}};this._updateCompactMinimize=()=>{if(this._container.classList.contains("maplibregl-compact")){if(this._container.classList.contains("maplibregl-compact-show")){this._container.classList.remove("maplibregl-compact-show")}}};this.options=options}getDefaultPosition(){return"bottom-right"}onAdd(map){this._map=map;this._compact=this.options.compact;this._container=DOM.create("details","maplibregl-ctrl maplibregl-ctrl-attrib");this._compactButton=DOM.create("summary","maplibregl-ctrl-attrib-button",this._container);this._compactButton.addEventListener("click",this._toggleAttribution);this._setElementTitle(this._compactButton,"ToggleAttribution");this._innerContainer=DOM.create("div","maplibregl-ctrl-attrib-inner",this._container);this._updateAttributions();this._updateCompact();this._map.on("styledata",this._updateData);this._map.on("sourcedata",this._updateData);this._map.on("terrain",this._updateData);this._map.on("resize",this._updateCompact);this._map.on("drag",this._updateCompactMinimize);return this._container}onRemove(){DOM.remove(this._container);this._map.off("styledata",this._updateData);this._map.off("sourcedata",this._updateData);this._map.off("terrain",this._updateData);this._map.off("resize",this._updateCompact);this._map.off("drag",this._updateCompactMinimize);this._map=undefined;this._compact=undefined;this._attribHTML=undefined}_setElementTitle(element,title){const str=this._map._getUIString(`AttributionControl.${title}`);element.title=str;element.setAttribute("aria-label",str)}_updateAttributions(){if(!this._map.style)return;let attributions=[];if(this.options.customAttribution){if(Array.isArray(this.options.customAttribution)){attributions=attributions.concat(this.options.customAttribution.map((attribution=>{if(typeof attribution!=="string")return"";return attribution})))}else if(typeof this.options.customAttribution==="string"){attributions.push(this.options.customAttribution)}}if(this._map.style.stylesheet){const stylesheet=this._map.style.stylesheet;this.styleOwner=stylesheet.owner;this.styleId=stylesheet.id}const sourceCaches=this._map.style.sourceCaches;for(const id in sourceCaches){const sourceCache=sourceCaches[id];if(sourceCache.used||sourceCache.usedForTerrain){const source=sourceCache.getSource();if(source.attribution&&attributions.indexOf(source.attribution)<0){attributions.push(source.attribution)}}}attributions=attributions.filter((e=>String(e).trim()));attributions.sort(((a,b)=>a.length-b.length));attributions=attributions.filter(((attrib,i)=>{for(let j=i+1;j=0){return false}}return true}));const attribHTML=attributions.join(" | ");if(attribHTML===this._attribHTML)return;this._attribHTML=attribHTML;if(attributions.length){this._innerContainer.innerHTML=attribHTML;this._container.classList.remove("maplibregl-attrib-empty")}else{this._container.classList.add("maplibregl-attrib-empty")}this._updateCompact();this._editLink=null}}class LogoControl{constructor(options={}){this._updateCompact=()=>{const containerChildren=this._container.children;if(containerChildren.length){const anchor=containerChildren[0];if(this._map.getCanvasContainer().offsetWidth<=640||this._compact){if(this._compact!==false){anchor.classList.add("maplibregl-compact")}}else{anchor.classList.remove("maplibregl-compact")}}};this.options=options}getDefaultPosition(){return"bottom-left"}onAdd(map){this._map=map;this._compact=this.options&&this.options.compact;this._container=DOM.create("div","maplibregl-ctrl");const anchor=DOM.create("a","maplibregl-ctrl-logo");anchor.target="_blank";anchor.rel="noopener nofollow";anchor.href="https://maplibre.org/";anchor.setAttribute("aria-label",this._map._getUIString("LogoControl.Title"));anchor.setAttribute("rel","noopener nofollow");this._container.appendChild(anchor);this._container.style.display="block";this._map.on("resize",this._updateCompact);this._updateCompact();return this._container}onRemove(){DOM.remove(this._container);this._map.off("resize",this._updateCompact);this._map=undefined;this._compact=undefined}}class TaskQueue{constructor(){this._queue=[];this._id=0;this._cleared=false;this._currentlyRunning=false}add(callback){const id=++this._id;const queue=this._queue;queue.push({callback:callback,id:id,cancelled:false});return id}remove(id){const running=this._currentlyRunning;const queue=running?this._queue.concat(running):this._queue;for(const task of queue){if(task.id===id){task.cancelled=true;return}}}run(timeStamp=0){if(this._currentlyRunning)throw new Error("Attempting to run(), but is already running.");const queue=this._currentlyRunning=this._queue;this._queue=[];for(const task of queue){if(task.cancelled)continue;task.callback(timeStamp);if(this._cleared)break}this._cleared=false;this._currentlyRunning=false}clear(){if(this._currentlyRunning){this._cleared=true}this._queue=[]}}var pos3dAttributes=performance$1.createLayout([{name:"a_pos3d",type:"Int16",components:3}]);class TerrainSourceCache extends performance$1.Evented{constructor(sourceCache){super();this.sourceCache=sourceCache;this._tiles={};this._renderableTilesKeys=[];this._sourceTileCache={};this.minzoom=0;this.maxzoom=22;this.tileSize=512;this.deltaZoom=1;sourceCache.usedForTerrain=true;sourceCache.tileSize=this.tileSize*2**this.deltaZoom}destruct(){this.sourceCache.usedForTerrain=false;this.sourceCache.tileSize=null}update(transform,terrain){this.sourceCache.update(transform,terrain);this._renderableTilesKeys=[];const keys={};for(const tileID of transform.coveringTiles({tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:false,terrain:terrain})){keys[tileID.key]=true;this._renderableTilesKeys.push(tileID.key);if(!this._tiles[tileID.key]){tileID.posMatrix=new Float64Array(16);performance$1.ortho(tileID.posMatrix,0,performance$1.EXTENT,0,performance$1.EXTENT,0,1);this._tiles[tileID.key]=new Tile(tileID,this.tileSize)}}for(const key in this._tiles){if(!keys[key])delete this._tiles[key]}}freeRtt(tileID){for(const key in this._tiles){const tile=this._tiles[key];if(!tileID||tile.tileID.equals(tileID)||tile.tileID.isChildOf(tileID)||tileID.isChildOf(tile.tileID))tile.rtt=[]}}getRenderableTiles(){return this._renderableTilesKeys.map((key=>this.getTileByID(key)))}getTileByID(id){return this._tiles[id]}getTerrainCoords(tileID){const coords={};for(const key of this._renderableTilesKeys){const _tileID=this._tiles[key].tileID;if(_tileID.canonical.equals(tileID.canonical)){const coord=tileID.clone();coord.posMatrix=new Float64Array(16);performance$1.ortho(coord.posMatrix,0,performance$1.EXTENT,0,performance$1.EXTENT,0,1);coords[key]=coord}else if(_tileID.canonical.isChildOf(tileID.canonical)){const coord=tileID.clone();coord.posMatrix=new Float64Array(16);const dz=_tileID.canonical.z-tileID.canonical.z;const dx=_tileID.canonical.x-(_tileID.canonical.x>>dz<>dz<>dz;performance$1.ortho(coord.posMatrix,0,size,0,size,0,1);performance$1.translate(coord.posMatrix,coord.posMatrix,[-dx*size,-dy*size,0]);coords[key]=coord}else if(tileID.canonical.isChildOf(_tileID.canonical)){const coord=tileID.clone();coord.posMatrix=new Float64Array(16);const dz=tileID.canonical.z-_tileID.canonical.z;const dx=tileID.canonical.x-(tileID.canonical.x>>dz<>dz<>dz;performance$1.ortho(coord.posMatrix,0,performance$1.EXTENT,0,performance$1.EXTENT,0,1);performance$1.translate(coord.posMatrix,coord.posMatrix,[dx*size,dy*size,0]);performance$1.scale(coord.posMatrix,coord.posMatrix,[1/2**dz,1/2**dz,0]);coords[key]=coord}}return coords}getSourceTile(tileID,searchForDEM){const source=this.sourceCache._source;let z=tileID.overscaledZ-this.deltaZoom;if(z>source.maxzoom)z=source.maxzoom;if(z=source.minzoom&&!(tile&&tile.dem))tile=this.sourceCache.getTileByID(tileID.scaledTo(z--).key);return tile}tilesAfterTime(time=Date.now()){return Object.values(this._tiles).filter((t=>t.timeAdded>=time))}}class Terrain{constructor(painter,sourceCache,options){this.painter=painter;this.sourceCache=new TerrainSourceCache(sourceCache);this.options=options;this.exaggeration=typeof options.exaggeration==="number"?options.exaggeration:1;this.qualityFactor=2;this.meshSize=128;this._demMatrixCache={};this.coordsIndex=[];this._coordsTextureSize=1024}getDEMElevation(tileID,x,y,extent=performance$1.EXTENT){var _a;if(!(x>=0&&x=0&&ytileID.canonical.z){if(tileID.canonical.z>=maxzoom)dz=tileID.canonical.z-maxzoom;else performance$1.warnOnce("cannot calculate elevation if elevation maxzoom > source.maxzoom")}const dx=tileID.canonical.x-(tileID.canonical.x>>dz<>dz<>8<<4|y>>8;data[i+3]=0}const image=new performance$1.RGBAImage({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(data.buffer));const texture=new Texture(context,image,context.gl.RGBA,{premultiply:false});texture.bind(context.gl.NEAREST,context.gl.CLAMP_TO_EDGE);this._coordsTexture=texture;return texture}pointCoordinate(p){const rgba=new Uint8Array(4);const context=this.painter.context,gl=context.gl;context.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer);gl.readPixels(p.x,this.painter.height/devicePixelRatio-p.y-1,1,1,gl.RGBA,gl.UNSIGNED_BYTE,rgba);context.bindFramebuffer.set(null);const x=rgba[0]+(rgba[2]>>4<<8);const y=rgba[1]+((rgba[2]&15)<<8);const tileID=this.coordsIndex[255-rgba[3]];const tile=tileID&&this.sourceCache.getTileByID(tileID);if(!tile)return null;const coordsSize=this._coordsTextureSize;const worldSize=(1<obj.id!==id));this._recentlyUsed.push(obj.id)}stampObject(obj){obj.stamp=++this._stamp}getOrCreateFreeObject(){for(const id of this._recentlyUsed){if(!this._objects[id].inUse)return this._objects[id]}if(this._objects.length>=this._size)throw new Error("No free RenderPool available, call freeAllObjects() required!");const obj=this._createObject(this._objects.length);this._objects.push(obj);return obj}freeObject(obj){obj.inUse=false}freeAllObjects(){for(const obj of this._objects)this.freeObject(obj)}isFull(){if(this._objects.length!o.inUse))===false}}const LAYERS={background:true,fill:true,line:true,raster:true,hillshade:true};class RenderToTexture{constructor(painter,terrain){this.painter=painter;this.terrain=terrain;this.pool=new RenderPool(painter.context,30,terrain.sourceCache.tileSize*terrain.qualityFactor)}destruct(){this.pool.destruct()}getTexture(tile){return this.pool.getObjectForId(tile.rtt[this._stacks.length-1].id).texture}prepareForRender(style,zoom){this._stacks=[];this._prevType=null;this._rttTiles=[];this._renderableTiles=this.terrain.sourceCache.getRenderableTiles();this._renderableLayerIds=style._order.filter((id=>!style._layers[id].isHidden(zoom)));this._coordsDescendingInv={};for(const id in style.sourceCaches){this._coordsDescendingInv[id]={};const tileIDs=style.sourceCaches[id].getVisibleCoordinates();for(const tileID of tileIDs){const keys=this.terrain.sourceCache.getTerrainCoords(tileID);for(const key in keys){if(!this._coordsDescendingInv[id][key])this._coordsDescendingInv[id][key]=[];this._coordsDescendingInv[id][key].push(keys[key])}}}this._coordsDescendingInvStr={};for(const id of style._order){const layer=style._layers[id],source=layer.source;if(LAYERS[layer.type]){if(!this._coordsDescendingInvStr[source]){this._coordsDescendingInvStr[source]={};for(const key in this._coordsDescendingInv[source])this._coordsDescendingInvStr[source][key]=this._coordsDescendingInv[source][key].map((c=>c.key)).sort().join()}}}for(const tile of this._renderableTiles){for(const source in this._coordsDescendingInvStr){const coords=this._coordsDescendingInvStr[source][tile.tileID.key];if(coords&&coords!==tile.rttCoords[source])tile.rtt=[]}}}renderLayer(layer){if(layer.isHidden(this.painter.transform.zoom))return false;const type=layer.type;const painter=this.painter;const isLastLayer=this._renderableLayerIds[this._renderableLayerIds.length-1]===layer.id;if(LAYERS[type]){if(!this._prevType||!LAYERS[this._prevType])this._stacks.push([]);this._prevType=type;this._stacks[this._stacks.length-1].push(layer.id);if(!isLastLayer)return true}if(LAYERS[this._prevType]||LAYERS[type]&&isLastLayer){this._prevType=type;const stack=this._stacks.length-1,layers=this._stacks[stack]||[];for(const tile of this._renderableTiles){if(this.pool.isFull()){drawTerrain(this.painter,this.terrain,this._rttTiles);this._rttTiles=[];this.pool.freeAllObjects()}this._rttTiles.push(tile);if(tile.rtt[stack]){const obj=this.pool.getObjectForId(tile.rtt[stack].id);if(obj.stamp===tile.rtt[stack].stamp){this.pool.useObject(obj);continue}}const obj=this.pool.getOrCreateFreeObject();this.pool.useObject(obj);this.pool.stampObject(obj);tile.rtt[stack]={id:obj.id,stamp:obj.stamp};painter.context.bindFramebuffer.set(obj.fbo.framebuffer);painter.context.clear({color:performance$1.Color.transparent,stencil:0});painter.currentStencilSource=undefined;for(let l=0;loptions.maxZoom){throw new Error("maxZoom must be greater than or equal to minZoom")}if(options.minPitch!=null&&options.maxPitch!=null&&options.minPitch>options.maxPitch){throw new Error("maxPitch must be greater than or equal to minPitch")}if(options.minPitch!=null&&options.minPitchmaxPitchThreshold){throw new Error(`maxPitch must be less than or equal to ${maxPitchThreshold}`)}const transform=new Transform(options.minZoom,options.maxZoom,options.minPitch,options.maxPitch,options.renderWorldCopies);super(transform,{bearingSnap:options.bearingSnap});this._contextLost=event=>{event.preventDefault();if(this._frameRequest){this._frameRequest.abort();this._frameRequest=null}this.fire(new performance$1.Event("webglcontextlost",{originalEvent:event}))};this._contextRestored=event=>{this._setupPainter();this.resize();this._update();this.fire(new performance$1.Event("webglcontextrestored",{originalEvent:event}))};this._onMapScroll=event=>{if(event.target!==this._container)return;this._container.scrollTop=0;this._container.scrollLeft=0;return false};this._onWindowOnline=()=>{this._update()};this._interactive=options.interactive;this._maxTileCacheSize=options.maxTileCacheSize;this._maxTileCacheZoomLevels=options.maxTileCacheZoomLevels;this._failIfMajorPerformanceCaveat=options.failIfMajorPerformanceCaveat;this._preserveDrawingBuffer=options.preserveDrawingBuffer;this._antialias=options.antialias;this._trackResize=options.trackResize;this._bearingSnap=options.bearingSnap;this._refreshExpiredTiles=options.refreshExpiredTiles;this._fadeDuration=options.fadeDuration;this._crossSourceCollisions=options.crossSourceCollisions;this._crossFadingFactor=1;this._collectResourceTiming=options.collectResourceTiming;this._renderTaskQueue=new TaskQueue;this._controls=[];this._mapId=performance$1.uniqueId();this._locale=performance$1.extend({},defaultLocale,options.locale);this._clickTolerance=options.clickTolerance;this._overridePixelRatio=options.pixelRatio;this._maxCanvasSize=options.maxCanvasSize;this.transformCameraUpdate=options.transformCameraUpdate;this._imageQueueHandle=ImageRequest.addThrottleControl((()=>this.isMoving()));this._requestManager=new RequestManager(options.transformRequest);if(typeof options.container==="string"){this._container=document.getElementById(options.container);if(!this._container){throw new Error(`Container '${options.container}' not found.`)}}else if(options.container instanceof HTMLElement){this._container=options.container}else{throw new Error("Invalid type: 'container' must be a String or HTMLElement.")}if(options.maxBounds){this.setMaxBounds(options.maxBounds)}this._setupContainer();this._setupPainter();this.on("move",(()=>this._update(false)));this.on("moveend",(()=>this._update(false)));this.on("zoom",(()=>this._update(true)));this.on("terrain",(()=>{this.painter.terrainFacilitator.dirty=true;this._update(true)}));this.once("idle",(()=>{this._idleTriggered=true}));if(typeof window!=="undefined"){addEventListener("online",this._onWindowOnline,false);let initialResizeEventCaptured=false;const throttledResizeCallback=throttle((entries=>{if(this._trackResize&&!this._removed){this.resize(entries)._update()}}),50);this._resizeObserver=new ResizeObserver((entries=>{if(!initialResizeEventCaptured){initialResizeEventCaptured=true;return}throttledResizeCallback(entries)}));this._resizeObserver.observe(this._container)}this.handlers=new HandlerManager(this,options);const hashName=typeof options.hash==="string"&&options.hash||undefined;this._hash=options.hash&&new Hash(hashName).addTo(this);if(!this._hash||!this._hash._onHashChange()){this.jumpTo({center:options.center,zoom:options.zoom,bearing:options.bearing,pitch:options.pitch});if(options.bounds){this.resize();this.fitBounds(options.bounds,performance$1.extend({},options.fitBoundsOptions,{duration:0}))}}this.resize();this._localIdeographFontFamily=options.localIdeographFontFamily;this._validateStyle=options.validateStyle;if(options.style)this.setStyle(options.style,{localIdeographFontFamily:options.localIdeographFontFamily});if(options.attributionControl)this.addControl(new AttributionControl(typeof options.attributionControl==="boolean"?undefined:options.attributionControl));if(options.maplibreLogo)this.addControl(new LogoControl,options.logoPosition);this.on("style.load",(()=>{if(this.transform.unmodified){this.jumpTo(this.style.stylesheet)}}));this.on("data",(event=>{this._update(event.dataType==="style");this.fire(new performance$1.Event(`${event.dataType}data`,event))}));this.on("dataloading",(event=>{this.fire(new performance$1.Event(`${event.dataType}dataloading`,event))}));this.on("dataabort",(event=>{this.fire(new performance$1.Event("sourcedataabort",event))}))}_getMapId(){return this._mapId}addControl(control,position){if(position===undefined){if(control.getDefaultPosition){position=control.getDefaultPosition()}else{position="top-right"}}if(!control||!control.onAdd){return this.fire(new performance$1.ErrorEvent(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")))}const controlElement=control.onAdd(this);this._controls.push(control);const positionContainer=this._controlPositions[position];if(position.indexOf("bottom")!==-1){positionContainer.insertBefore(controlElement,positionContainer.firstChild)}else{positionContainer.appendChild(controlElement)}return this}removeControl(control){if(!control||!control.onRemove){return this.fire(new performance$1.ErrorEvent(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")))}const ci=this._controls.indexOf(control);if(ci>-1)this._controls.splice(ci,1);control.onRemove(this);return this}hasControl(control){return this._controls.indexOf(control)>-1}calculateCameraOptionsFromTo(from,altitudeFrom,to,altitudeTo){if(altitudeTo==null&&this.terrain){altitudeTo=this.terrain.getElevationForLngLatZoom(to,this.transform.tileZoom)}return super.calculateCameraOptionsFromTo(from,altitudeFrom,to,altitudeTo)}resize(eventData){var _a;const dimensions=this._containerDimensions();const width=dimensions[0];const height=dimensions[1];const clampedPixelRatio=this._getClampedPixelRatio(width,height);this._resizeCanvas(width,height,clampedPixelRatio);this.painter.resize(width,height,clampedPixelRatio);if(this.painter.overLimit()){const gl=this.painter.context.gl;this._maxCanvasSize=[gl.drawingBufferWidth,gl.drawingBufferHeight];const clampedPixelRatio=this._getClampedPixelRatio(width,height);this._resizeCanvas(width,height,clampedPixelRatio);this.painter.resize(width,height,clampedPixelRatio)}this.transform.resize(width,height);(_a=this._requestedCameraState)===null||_a===void 0?void 0:_a.resize(width,height);const fireMoving=!this._moving;if(fireMoving){this.stop();this.fire(new performance$1.Event("movestart",eventData)).fire(new performance$1.Event("move",eventData))}this.fire(new performance$1.Event("resize",eventData));if(fireMoving)this.fire(new performance$1.Event("moveend",eventData));return this}_getClampedPixelRatio(width,height){const{0:maxCanvasWidth,1:maxCanvasHeight}=this._maxCanvasSize;const pixelRatio=this.getPixelRatio();const canvasWidth=width*pixelRatio;const canvasHeight=height*pixelRatio;const widthScaleFactor=canvasWidth>maxCanvasWidth?maxCanvasWidth/canvasWidth:1;const heightScaleFactor=canvasHeight>maxCanvasHeight?maxCanvasHeight/canvasHeight:1;return Math.min(widthScaleFactor,heightScaleFactor)*pixelRatio}getPixelRatio(){var _a;return(_a=this._overridePixelRatio)!==null&&_a!==void 0?_a:devicePixelRatio}setPixelRatio(pixelRatio){this._overridePixelRatio=pixelRatio;this.resize()}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(bounds){this.transform.setMaxBounds(LngLatBounds.convert(bounds));return this._update()}setMinZoom(minZoom){minZoom=minZoom===null||minZoom===undefined?defaultMinZoom:minZoom;if(minZoom>=defaultMinZoom&&minZoom<=this.transform.maxZoom){this.transform.minZoom=minZoom;this._update();if(this.getZoom()=this.transform.minZoom){this.transform.maxZoom=maxZoom;this._update();if(this.getZoom()>maxZoom)this.setZoom(maxZoom);return this}else throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(minPitch){minPitch=minPitch===null||minPitch===undefined?defaultMinPitch:minPitch;if(minPitch=defaultMinPitch&&minPitch<=this.transform.maxPitch){this.transform.minPitch=minPitch;this._update();if(this.getPitch()maxPitchThreshold){throw new Error(`maxPitch must be less than or equal to ${maxPitchThreshold}`)}if(maxPitch>=this.transform.minPitch){this.transform.maxPitch=maxPitch;this._update();if(this.getPitch()>maxPitch)this.setPitch(maxPitch);return this}else throw new Error("maxPitch must be greater than the current minPitch")}getMaxPitch(){return this.transform.maxPitch}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(renderWorldCopies){this.transform.renderWorldCopies=renderWorldCopies;return this._update()}project(lnglat){return this.transform.locationPoint(performance$1.LngLat.convert(lnglat),this.style&&this.terrain)}unproject(point){return this.transform.pointLocation(performance$1.Point.convert(point),this.terrain)}isMoving(){var _a;return this._moving||((_a=this.handlers)===null||_a===void 0?void 0:_a.isMoving())}isZooming(){var _a;return this._zooming||((_a=this.handlers)===null||_a===void 0?void 0:_a.isZooming())}isRotating(){var _a;return this._rotating||((_a=this.handlers)===null||_a===void 0?void 0:_a.isRotating())}_createDelegatedListener(type,layerId,listener){if(type==="mouseenter"||type==="mouseover"){let mousein=false;const mousemove=e=>{const features=this.getLayer(layerId)?this.queryRenderedFeatures(e.point,{layers:[layerId]}):[];if(!features.length){mousein=false}else if(!mousein){mousein=true;listener.call(this,new MapMouseEvent(type,this,e.originalEvent,{features:features}))}};const mouseout=()=>{mousein=false};return{layer:layerId,listener:listener,delegates:{mousemove:mousemove,mouseout:mouseout}}}else if(type==="mouseleave"||type==="mouseout"){let mousein=false;const mousemove=e=>{const features=this.getLayer(layerId)?this.queryRenderedFeatures(e.point,{layers:[layerId]}):[];if(features.length){mousein=true}else if(mousein){mousein=false;listener.call(this,new MapMouseEvent(type,this,e.originalEvent))}};const mouseout=e=>{if(mousein){mousein=false;listener.call(this,new MapMouseEvent(type,this,e.originalEvent))}};return{layer:layerId,listener:listener,delegates:{mousemove:mousemove,mouseout:mouseout}}}else{const delegate=e=>{const features=this.getLayer(layerId)?this.queryRenderedFeatures(e.point,{layers:[layerId]}):[];if(features.length){e.features=features;listener.call(this,e);delete e.features}};return{layer:layerId,listener:listener,delegates:{[type]:delegate}}}}on(type,layerIdOrListener,listener){if(listener===undefined){return super.on(type,layerIdOrListener)}const delegatedListener=this._createDelegatedListener(type,layerIdOrListener,listener);this._delegatedListeners=this._delegatedListeners||{};this._delegatedListeners[type]=this._delegatedListeners[type]||[];this._delegatedListeners[type].push(delegatedListener);for(const event in delegatedListener.delegates){this.on(event,delegatedListener.delegates[event])}return this}once(type,layerIdOrListener,listener){if(listener===undefined){return super.once(type,layerIdOrListener)}const delegatedListener=this._createDelegatedListener(type,layerIdOrListener,listener);for(const event in delegatedListener.delegates){this.once(event,delegatedListener.delegates[event])}return this}off(type,layerIdOrListener,listener){if(listener===undefined){return super.off(type,layerIdOrListener)}const removeDelegatedListener=delegatedListeners=>{const listeners=delegatedListeners[type];for(let i=0;ithis._updateStyle(style,options)));return}const previousStyle=this.style&&options.transformStyle?this.style.serialize():undefined;if(this.style){this.style.setEventedParent(null);this.style._remove(!style)}if(!style){delete this.style;return this}else{this.style=new Style(this,options||{})}this.style.setEventedParent(this,{style:this.style});if(typeof style==="string"){this.style.loadURL(style,options,previousStyle)}else{this.style.loadJSON(style,options,previousStyle)}return this}_lazyInitEmptyStyle(){if(!this.style){this.style=new Style(this,{});this.style.setEventedParent(this,{style:this.style});this.style.loadEmpty()}}_diffStyle(style,options){if(typeof style==="string"){const url=style;const request=this._requestManager.transformRequest(url,ResourceType.Style);performance$1.getJSON(request,new AbortController).then((response=>{this._updateDiff(response.data,options)})).catch((error=>{if(error){this.fire(new performance$1.ErrorEvent(error))}}))}else if(typeof style==="object"){this._updateDiff(style,options)}}_updateDiff(style,options){try{if(this.style.setState(style,options)){this._update(true)}}catch(e){performance$1.warnOnce(`Unable to perform style diff: ${e.message||e.error||e}. Rebuilding the style from scratch.`);this._updateStyle(style,options)}}getStyle(){if(this.style){return this.style.serialize()}}isStyleLoaded(){if(!this.style)return performance$1.warnOnce("There is no style added to the map.");return this.style.loaded()}addSource(id,source){this._lazyInitEmptyStyle();this.style.addSource(id,source);return this._update(true)}isSourceLoaded(id){const source=this.style&&this.style.sourceCaches[id];if(source===undefined){this.fire(new performance$1.ErrorEvent(new Error(`There is no source with ID '${id}'`)));return}return source.loaded()}setTerrain(options){this.style._checkLoaded();if(this._terrainDataCallback)this.style.off("data",this._terrainDataCallback);if(!options){if(this.terrain)this.terrain.sourceCache.destruct();this.terrain=null;if(this.painter.renderToTexture)this.painter.renderToTexture.destruct();this.painter.renderToTexture=null;this.transform.minElevationForCurrentTile=0;this.transform.elevation=0}else{const sourceCache=this.style.sourceCaches[options.source];if(!sourceCache)throw new Error(`cannot load terrain, because there exists no source with ID: ${options.source}`);if(this.terrain===null)sourceCache.reload();for(const index in this.style._layers){const thisLayer=this.style._layers[index];if(thisLayer.type==="hillshade"&&thisLayer.source===options.source){performance$1.warnOnce("You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.")}}this.terrain=new Terrain(this.painter,sourceCache,options);this.painter.renderToTexture=new RenderToTexture(this.painter,this.terrain);this.transform.minElevationForCurrentTile=this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom);this.transform.elevation=this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom);this._terrainDataCallback=e=>{if(e.dataType==="style"){this.terrain.sourceCache.freeRtt()}else if(e.dataType==="source"&&e.tile){if(e.sourceId===options.source&&!this._elevationFreeze){this.transform.minElevationForCurrentTile=this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom);this.transform.elevation=this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)}this.terrain.sourceCache.freeRtt(e.tile.tileID)}};this.style.on("data",this._terrainDataCallback)}this.fire(new performance$1.Event("terrain",{terrain:options}));return this}getTerrain(){var _a,_b;return(_b=(_a=this.terrain)===null||_a===void 0?void 0:_a.options)!==null&&_b!==void 0?_b:null}areTilesLoaded(){const sources=this.style&&this.style.sourceCaches;for(const id in sources){const source=sources[id];const tiles=source._tiles;for(const t in tiles){const tile=tiles[t];if(!(tile.state==="loaded"||tile.state==="errored"))return false}}return true}removeSource(id){this.style.removeSource(id);return this._update(true)}getSource(id){return this.style.getSource(id)}addImage(id,image,options={}){const{pixelRatio:pixelRatio=1,sdf:sdf=false,stretchX:stretchX,stretchY:stretchY,content:content}=options;this._lazyInitEmptyStyle();const version=0;if(image instanceof HTMLImageElement||performance$1.isImageBitmap(image)){const{width:width,height:height,data:data}=browser.getImageData(image);this.style.addImage(id,{data:new performance$1.RGBAImage({width:width,height:height},data),pixelRatio:pixelRatio,stretchX:stretchX,stretchY:stretchY,content:content,sdf:sdf,version:version})}else if(image.width===undefined||image.height===undefined){return this.fire(new performance$1.ErrorEvent(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, "+"or object with `width`, `height`, and `data` properties with the same format as `ImageData`")))}else{const{width:width,height:height,data:data}=image;const userImage=image;this.style.addImage(id,{data:new performance$1.RGBAImage({width:width,height:height},new Uint8Array(data)),pixelRatio:pixelRatio,stretchX:stretchX,stretchY:stretchY,content:content,sdf:sdf,version:version,userImage:userImage});if(userImage.onAdd){userImage.onAdd(this,id)}return this}}updateImage(id,image){const existingImage=this.style.getImage(id);if(!existingImage){return this.fire(new performance$1.ErrorEvent(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")))}const imageData=image instanceof HTMLImageElement||performance$1.isImageBitmap(image)?browser.getImageData(image):image;const{width:width,height:height,data:data}=imageData;if(width===undefined||height===undefined){return this.fire(new performance$1.ErrorEvent(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, "+"or object with `width`, `height`, and `data` properties with the same format as `ImageData`")))}if(width!==existingImage.data.width||height!==existingImage.data.height){return this.fire(new performance$1.ErrorEvent(new Error("The width and height of the updated image must be that same as the previous version of the image")))}const copy=!(image instanceof HTMLImageElement||performance$1.isImageBitmap(image));existingImage.data.replace(data,copy);this.style.updateImage(id,existingImage);return this}getImage(id){return this.style.getImage(id)}hasImage(id){if(!id){this.fire(new performance$1.ErrorEvent(new Error("Missing required image id")));return false}return!!this.style.getImage(id)}removeImage(id){this.style.removeImage(id)}loadImage(url){return ImageRequest.getImage(this._requestManager.transformRequest(url,ResourceType.Image),new AbortController)}listImages(){return this.style.listImages()}addLayer(layer,beforeId){this._lazyInitEmptyStyle();this.style.addLayer(layer,beforeId);return this._update(true)}moveLayer(id,beforeId){this.style.moveLayer(id,beforeId);return this._update(true)}removeLayer(id){this.style.removeLayer(id);return this._update(true)}getLayer(id){return this.style.getLayer(id)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(layerId,minzoom,maxzoom){this.style.setLayerZoomRange(layerId,minzoom,maxzoom);return this._update(true)}setFilter(layerId,filter,options={}){this.style.setFilter(layerId,filter,options);return this._update(true)}getFilter(layerId){return this.style.getFilter(layerId)}setPaintProperty(layerId,name,value,options={}){this.style.setPaintProperty(layerId,name,value,options);return this._update(true)}getPaintProperty(layerId,name){return this.style.getPaintProperty(layerId,name)}setLayoutProperty(layerId,name,value,options={}){this.style.setLayoutProperty(layerId,name,value,options);return this._update(true)}getLayoutProperty(layerId,name){return this.style.getLayoutProperty(layerId,name)}setGlyphs(glyphsUrl,options={}){this._lazyInitEmptyStyle();this.style.setGlyphs(glyphsUrl,options);return this._update(true)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(id,url,options={}){this._lazyInitEmptyStyle();this.style.addSprite(id,url,options,(err=>{if(!err){this._update(true)}}));return this}removeSprite(id){this._lazyInitEmptyStyle();this.style.removeSprite(id);return this._update(true)}getSprite(){return this.style.getSprite()}setSprite(spriteUrl,options={}){this._lazyInitEmptyStyle();this.style.setSprite(spriteUrl,options,(err=>{if(!err){this._update(true)}}));return this}setLight(light,options={}){this._lazyInitEmptyStyle();this.style.setLight(light,options);return this._update(true)}getLight(){return this.style.getLight()}setFeatureState(feature,state){this.style.setFeatureState(feature,state);return this._update()}removeFeatureState(target,key){this.style.removeFeatureState(target,key);return this._update()}getFeatureState(feature){return this.style.getFeatureState(feature)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let width=0;let height=0;if(this._container){width=this._container.clientWidth||400;height=this._container.clientHeight||300}return[width,height]}_setupContainer(){const container=this._container;container.classList.add("maplibregl-map");const canvasContainer=this._canvasContainer=DOM.create("div","maplibregl-canvas-container",container);if(this._interactive){canvasContainer.classList.add("maplibregl-interactive")}this._canvas=DOM.create("canvas","maplibregl-canvas",canvasContainer);this._canvas.addEventListener("webglcontextlost",this._contextLost,false);this._canvas.addEventListener("webglcontextrestored",this._contextRestored,false);this._canvas.setAttribute("tabindex","0");this._canvas.setAttribute("aria-label","Map");this._canvas.setAttribute("role","region");const dimensions=this._containerDimensions();const clampedPixelRatio=this._getClampedPixelRatio(dimensions[0],dimensions[1]);this._resizeCanvas(dimensions[0],dimensions[1],clampedPixelRatio);const controlContainer=this._controlContainer=DOM.create("div","maplibregl-control-container",container);const positions=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach((positionName=>{positions[positionName]=DOM.create("div",`maplibregl-ctrl-${positionName} `,controlContainer)}));this._container.addEventListener("scroll",this._onMapScroll,false)}_resizeCanvas(width,height,pixelRatio){this._canvas.width=Math.floor(pixelRatio*width);this._canvas.height=Math.floor(pixelRatio*height);this._canvas.style.width=`${width}px`;this._canvas.style.height=`${height}px`}_setupPainter(){const attributes={alpha:true,stencil:true,depth:true,failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||false};let webglcontextcreationerrorDetailObject=null;this._canvas.addEventListener("webglcontextcreationerror",(args=>{webglcontextcreationerrorDetailObject={requestedAttributes:attributes};if(args){webglcontextcreationerrorDetailObject.statusMessage=args.statusMessage;webglcontextcreationerrorDetailObject.type=args.type}}),{once:true});const gl=this._canvas.getContext("webgl2",attributes)||this._canvas.getContext("webgl",attributes);if(!gl){const msg="Failed to initialize WebGL";if(webglcontextcreationerrorDetailObject){webglcontextcreationerrorDetailObject.message=msg;throw new Error(JSON.stringify(webglcontextcreationerrorDetailObject))}else{throw new Error(msg)}}this.painter=new Painter(gl,this.transform);webpSupported.testSupport(gl)}loaded(){return!this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(updateStyle){if(!this.style||!this.style._loaded)return this;this._styleDirty=this._styleDirty||updateStyle;this._sourcesDirty=true;this.triggerRepaint();return this}_requestRenderFrame(callback){this._update();return this._renderTaskQueue.add(callback)}_cancelRenderFrame(id){this._renderTaskQueue.remove(id)}_render(paintStartTimeStamp){const fadeDuration=this._idleTriggered?this._fadeDuration:0;this.painter.context.setDirty();this.painter.setBaseState();this._renderTaskQueue.run(paintStartTimeStamp);if(this._removed)return;let crossFading=false;if(this.style&&this._styleDirty){this._styleDirty=false;const zoom=this.transform.zoom;const now=browser.now();this.style.zoomHistory.update(zoom,now);const parameters=new performance$1.EvaluationParameters(zoom,{now:now,fadeDuration:fadeDuration,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()});const factor=parameters.crossFadingFactor();if(factor!==1||factor!==this._crossFadingFactor){crossFading=true;this._crossFadingFactor=factor}this.style.update(parameters)}if(this.style&&this._sourcesDirty){this._sourcesDirty=false;this.style._updateSources(this.transform)}if(this.terrain){this.terrain.sourceCache.update(this.transform,this.terrain);this.transform.minElevationForCurrentTile=this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom);if(!this._elevationFreeze){this.transform.elevation=this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)}}else{this.transform.minElevationForCurrentTile=0;this.transform.elevation=0}this._placementDirty=this.style&&this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,fadeDuration,this._crossSourceCollisions);this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:fadeDuration,showPadding:this.showPadding});this.fire(new performance$1.Event("render"));if(this.loaded()&&!this._loaded){this._loaded=true;performance$1.PerformanceUtils.mark(performance$1.PerformanceMarkers.load);this.fire(new performance$1.Event("load"))}if(this.style&&(this.style.hasTransitions()||crossFading)){this._styleDirty=true}if(this.style&&!this._placementDirty){this.style._releaseSymbolFadeTiles()}const somethingDirty=this._sourcesDirty||this._styleDirty||this._placementDirty;if(somethingDirty||this._repaint){this.triggerRepaint()}else if(!this.isMoving()&&this.loaded()){this.fire(new performance$1.Event("idle"))}if(this._loaded&&!this._fullyLoaded&&!somethingDirty){this._fullyLoaded=true;performance$1.PerformanceUtils.mark(performance$1.PerformanceMarkers.fullLoad)}return this}redraw(){if(this.style){if(this._frameRequest){this._frameRequest.abort();this._frameRequest=null}this._render(0)}return this}remove(){var _a;if(this._hash)this._hash.remove();for(const control of this._controls)control.onRemove(this);this._controls=[];if(this._frameRequest){this._frameRequest.abort();this._frameRequest=null}this._renderTaskQueue.clear();this.painter.destroy();this.handlers.destroy();delete this.handlers;this.setStyle(null);if(typeof window!=="undefined"){removeEventListener("online",this._onWindowOnline,false)}ImageRequest.removeThrottleControl(this._imageQueueHandle);(_a=this._resizeObserver)===null||_a===void 0?void 0:_a.disconnect();const extension=this.painter.context.gl.getExtension("WEBGL_lose_context");if(extension)extension.loseContext();this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,false);this._canvas.removeEventListener("webglcontextlost",this._contextLost,false);DOM.remove(this._canvasContainer);DOM.remove(this._controlContainer);this._container.classList.remove("maplibregl-map");performance$1.PerformanceUtils.clearMetrics();this._removed=true;this.fire(new performance$1.Event("remove"))}triggerRepaint(){if(this.style&&!this._frameRequest){this._frameRequest=new AbortController;browser.frameAsync(this._frameRequest).then((paintStartTimeStamp=>{performance$1.PerformanceUtils.frame(paintStartTimeStamp);this._frameRequest=null;this._render(paintStartTimeStamp)})).catch((()=>{}))}}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(value){if(this._showTileBoundaries===value)return;this._showTileBoundaries=value;this._update()}get showPadding(){return!!this._showPadding}set showPadding(value){if(this._showPadding===value)return;this._showPadding=value;this._update()}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(value){if(this._showCollisionBoxes===value)return;this._showCollisionBoxes=value;if(value){this.style._generateCollisionBoxes()}else{this._update()}}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(value){if(this._showOverdrawInspector===value)return;this._showOverdrawInspector=value;this._update()}get repaint(){return!!this._repaint}set repaint(value){if(this._repaint!==value){this._repaint=value;this.triggerRepaint()}}get vertices(){return!!this._vertices}set vertices(value){this._vertices=value;this._update()}get version(){return version$1}getCameraTargetElevation(){return this.transform.elevation}};const assignEvents=handler=>{handler.touchstart=handler.dragStart;handler.touchmoveWindow=handler.dragMove;handler.touchend=handler.dragEnd};const generateOneFingerTouchRotationHandler=({enable:enable,clickTolerance:clickTolerance,bearingDegreesPerPixelMoved:bearingDegreesPerPixelMoved=.8})=>{const touchMoveStateManager=new OneFingerTouchMoveStateManager;return new DragHandler({clickTolerance:clickTolerance,move:(lastPoint,point)=>({bearingDelta:(point.x-lastPoint.x)*bearingDegreesPerPixelMoved}),moveStateManager:touchMoveStateManager,enable:enable,assignEvents:assignEvents})};const generateOneFingerTouchPitchHandler=({enable:enable,clickTolerance:clickTolerance,pitchDegreesPerPixelMoved:pitchDegreesPerPixelMoved=-.5})=>{const touchMoveStateManager=new OneFingerTouchMoveStateManager;return new DragHandler({clickTolerance:clickTolerance,move:(lastPoint,point)=>({pitchDelta:(point.y-lastPoint.y)*pitchDegreesPerPixelMoved}),moveStateManager:touchMoveStateManager,enable:enable,assignEvents:assignEvents})};const defaultOptions$3={showCompass:true,showZoom:true,visualizePitch:false};class NavigationControl{constructor(options){this._updateZoomButtons=()=>{const zoom=this._map.getZoom();const isMax=zoom===this._map.getMaxZoom();const isMin=zoom===this._map.getMinZoom();this._zoomInButton.disabled=isMax;this._zoomOutButton.disabled=isMin;this._zoomInButton.setAttribute("aria-disabled",isMax.toString());this._zoomOutButton.setAttribute("aria-disabled",isMin.toString())};this._rotateCompassArrow=()=>{const rotate=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(this._map.transform.pitch*(Math.PI/180)),.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${this._map.transform.angle*(180/Math.PI)}deg)`:`rotate(${this._map.transform.angle*(180/Math.PI)}deg)`;this._compassIcon.style.transform=rotate};this._setButtonTitle=(button,title)=>{const str=this._map._getUIString(`NavigationControl.${title}`);button.title=str;button.setAttribute("aria-label",str)};this.options=performance$1.extend({},defaultOptions$3,options);this._container=DOM.create("div","maplibregl-ctrl maplibregl-ctrl-group");this._container.addEventListener("contextmenu",(e=>e.preventDefault()));if(this.options.showZoom){this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(e=>this._map.zoomIn({},{originalEvent:e})));DOM.create("span","maplibregl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true");this._zoomOutButton=this._createButton("maplibregl-ctrl-zoom-out",(e=>this._map.zoomOut({},{originalEvent:e})));DOM.create("span","maplibregl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")}if(this.options.showCompass){this._compass=this._createButton("maplibregl-ctrl-compass",(e=>{if(this.options.visualizePitch){this._map.resetNorthPitch({},{originalEvent:e})}else{this._map.resetNorth({},{originalEvent:e})}}));this._compassIcon=DOM.create("span","maplibregl-ctrl-icon",this._compass);this._compassIcon.setAttribute("aria-hidden","true")}}onAdd(map){this._map=map;if(this.options.showZoom){this._setButtonTitle(this._zoomInButton,"ZoomIn");this._setButtonTitle(this._zoomOutButton,"ZoomOut");this._map.on("zoom",this._updateZoomButtons);this._updateZoomButtons()}if(this.options.showCompass){this._setButtonTitle(this._compass,"ResetBearing");if(this.options.visualizePitch){this._map.on("pitch",this._rotateCompassArrow)}this._map.on("rotate",this._rotateCompassArrow);this._rotateCompassArrow();this._handler=new MouseRotateWrapper(this._map,this._compass,this.options.visualizePitch)}return this._container}onRemove(){DOM.remove(this._container);if(this.options.showZoom){this._map.off("zoom",this._updateZoomButtons)}if(this.options.showCompass){if(this.options.visualizePitch){this._map.off("pitch",this._rotateCompassArrow)}this._map.off("rotate",this._rotateCompassArrow);this._handler.off();delete this._handler}delete this._map}_createButton(className,fn){const a=DOM.create("button",className,this._container);a.type="button";a.addEventListener("click",fn);return a}}class MouseRotateWrapper{constructor(map,element,pitch=false){this.mousedown=e=>{this.startMouse(performance$1.extend({},e,{ctrlKey:true,preventDefault:()=>e.preventDefault()}),DOM.mousePos(this.element,e));DOM.addEventListener(window,"mousemove",this.mousemove);DOM.addEventListener(window,"mouseup",this.mouseup)};this.mousemove=e=>{this.moveMouse(e,DOM.mousePos(this.element,e))};this.mouseup=e=>{this.mouseRotate.dragEnd(e);if(this.mousePitch)this.mousePitch.dragEnd(e);this.offTemp()};this.touchstart=e=>{if(e.targetTouches.length!==1){this.reset()}else{this._startPos=this._lastPos=DOM.touchPos(this.element,e.targetTouches)[0];this.startTouch(e,this._startPos);DOM.addEventListener(window,"touchmove",this.touchmove,{passive:false});DOM.addEventListener(window,"touchend",this.touchend)}};this.touchmove=e=>{if(e.targetTouches.length!==1){this.reset()}else{this._lastPos=DOM.touchPos(this.element,e.targetTouches)[0];this.moveTouch(e,this._lastPos)}};this.touchend=e=>{if(e.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos){this.mouseRotate.reset();if(this.mousePitch)this.mousePitch.reset();this.touchRotate.reset();if(this.touchPitch)this.touchPitch.reset();delete this._startPos;delete this._lastPos;this.offTemp()};this._clickTolerance=10;const mapRotateTolerance=map.dragRotate._mouseRotate.getClickTolerance();const mapPitchTolerance=map.dragRotate._mousePitch.getClickTolerance();this.element=element;this.mouseRotate=generateMouseRotationHandler({clickTolerance:mapRotateTolerance,enable:true});this.touchRotate=generateOneFingerTouchRotationHandler({clickTolerance:mapRotateTolerance,enable:true});this.map=map;if(pitch){this.mousePitch=generateMousePitchHandler({clickTolerance:mapPitchTolerance,enable:true});this.touchPitch=generateOneFingerTouchPitchHandler({clickTolerance:mapPitchTolerance,enable:true})}DOM.addEventListener(element,"mousedown",this.mousedown);DOM.addEventListener(element,"touchstart",this.touchstart,{passive:false});DOM.addEventListener(element,"touchcancel",this.reset)}startMouse(e,point){this.mouseRotate.dragStart(e,point);if(this.mousePitch)this.mousePitch.dragStart(e,point);DOM.disableDrag()}startTouch(e,point){this.touchRotate.dragStart(e,point);if(this.touchPitch)this.touchPitch.dragStart(e,point);DOM.disableDrag()}moveMouse(e,point){const map=this.map;const{bearingDelta:bearingDelta}=this.mouseRotate.dragMove(e,point)||{};if(bearingDelta)map.setBearing(map.getBearing()+bearingDelta);if(this.mousePitch){const{pitchDelta:pitchDelta}=this.mousePitch.dragMove(e,point)||{};if(pitchDelta)map.setPitch(map.getPitch()+pitchDelta)}}moveTouch(e,point){const map=this.map;const{bearingDelta:bearingDelta}=this.touchRotate.dragMove(e,point)||{};if(bearingDelta)map.setBearing(map.getBearing()+bearingDelta);if(this.touchPitch){const{pitchDelta:pitchDelta}=this.touchPitch.dragMove(e,point)||{};if(pitchDelta)map.setPitch(map.getPitch()+pitchDelta)}}off(){const element=this.element;DOM.removeEventListener(element,"mousedown",this.mousedown);DOM.removeEventListener(element,"touchstart",this.touchstart,{passive:false});DOM.removeEventListener(window,"touchmove",this.touchmove,{passive:false});DOM.removeEventListener(window,"touchend",this.touchend);DOM.removeEventListener(element,"touchcancel",this.reset);this.offTemp()}offTemp(){DOM.enableDrag();DOM.removeEventListener(window,"mousemove",this.mousemove);DOM.removeEventListener(window,"mouseup",this.mouseup);DOM.removeEventListener(window,"touchmove",this.touchmove,{passive:false});DOM.removeEventListener(window,"touchend",this.touchend)}}let supportsGeolocation;function checkGeolocationSupport(forceRecalculation=false){return performance$1.__awaiter(this,void 0,void 0,(function*(){if(supportsGeolocation!==undefined&&!forceRecalculation){return supportsGeolocation}if(window.navigator.permissions===undefined){supportsGeolocation=!!window.navigator.geolocation;return supportsGeolocation}try{const permissions=yield window.navigator.permissions.query({name:"geolocation"});supportsGeolocation=permissions.state!=="denied"}catch(_a){supportsGeolocation=!!window.navigator.geolocation}return supportsGeolocation}))}function smartWrap(lngLat,priorPos,transform){const originalLngLat=new performance$1.LngLat(lngLat.lng,lngLat.lat);lngLat=new performance$1.LngLat(lngLat.lng,lngLat.lat);if(priorPos){const left=new performance$1.LngLat(lngLat.lng-360,lngLat.lat);const right=new performance$1.LngLat(lngLat.lng+360,lngLat.lat);const delta=transform.locationPoint(lngLat).distSqr(priorPos);if(transform.locationPoint(left).distSqr(priorPos)180){const pos=transform.locationPoint(lngLat);if(pos.x>=0&&pos.y>=0&&pos.x<=transform.width&&pos.y<=transform.height){break}if(lngLat.lng>transform.center.lng){lngLat.lng-=360}else{lngLat.lng+=360}}if(lngLat.lng!==originalLngLat.lng&&transform.locationPoint(lngLat).y>transform.height/2-transform.getHorizon()){return lngLat}return originalLngLat}const anchorTranslate={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function applyAnchorClass(element,anchor,prefix){const classList=element.classList;for(const key in anchorTranslate){classList.remove(`maplibregl-${prefix}-anchor-${key}`)}classList.add(`maplibregl-${prefix}-anchor-${anchor}`)}class Marker extends performance$1.Evented{constructor(options){super();this._onKeyPress=e=>{const code=e.code;const legacyCode=e.charCode||e.keyCode;if(code==="Space"||code==="Enter"||legacyCode===32||legacyCode===13){this.togglePopup()}};this._onMapClick=e=>{const targetElement=e.originalEvent.target;const element=this._element;if(this._popup&&(targetElement===element||element.contains(targetElement))){this.togglePopup()}};this._update=e=>{if(!this._map)return;const isFullyLoaded=this._map.loaded()&&!this._map.isMoving();if((e===null||e===void 0?void 0:e.type)==="terrain"||(e===null||e===void 0?void 0:e.type)==="render"&&!isFullyLoaded){this._map.once("render",this._update)}if(this._map.transform.renderWorldCopies){this._lngLat=smartWrap(this._lngLat,this._flatPos,this._map.transform)}this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset);if(this._map.terrain){this._flatPos=this._map.transform.locationPoint(this._lngLat)._add(this._offset)}let rotation="";if(this._rotationAlignment==="viewport"||this._rotationAlignment==="auto"){rotation=`rotateZ(${this._rotation}deg)`}else if(this._rotationAlignment==="map"){rotation=`rotateZ(${this._rotation-this._map.getBearing()}deg)`}let pitch="";if(this._pitchAlignment==="viewport"||this._pitchAlignment==="auto"){pitch="rotateX(0deg)"}else if(this._pitchAlignment==="map"){pitch=`rotateX(${this._map.getPitch()}deg)`}if(!e||e.type==="moveend"){this._pos=this._pos.round()}DOM.setTransform(this._element,`${anchorTranslate[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${pitch} ${rotation}`);browser.frameAsync(new AbortController).then((()=>{this._updateOpacity(e&&e.type==="moveend")})).catch((()=>{}))};this._onMove=e=>{if(!this._isDragging){const clickTolerance=this._clickTolerance||this._map._clickTolerance;this._isDragging=e.point.dist(this._pointerdownPos)>=clickTolerance}if(!this._isDragging)return;this._pos=e.point.sub(this._positionDelta);this._lngLat=this._map.unproject(this._pos);this.setLngLat(this._lngLat);this._element.style.pointerEvents="none";if(this._state==="pending"){this._state="active";this.fire(new performance$1.Event("dragstart"))}this.fire(new performance$1.Event("drag"))};this._onUp=()=>{this._element.style.pointerEvents="auto";this._positionDelta=null;this._pointerdownPos=null;this._isDragging=false;this._map.off("mousemove",this._onMove);this._map.off("touchmove",this._onMove);if(this._state==="active"){this.fire(new performance$1.Event("dragend"))}this._state="inactive"};this._addDragHandler=e=>{if(this._element.contains(e.originalEvent.target)){e.preventDefault();this._positionDelta=e.point.sub(this._pos).add(this._offset);this._pointerdownPos=e.point;this._state="pending";this._map.on("mousemove",this._onMove);this._map.on("touchmove",this._onMove);this._map.once("mouseup",this._onUp);this._map.once("touchend",this._onUp)}};this._anchor=options&&options.anchor||"center";this._color=options&&options.color||"#3FB1CE";this._scale=options&&options.scale||1;this._draggable=options&&options.draggable||false;this._clickTolerance=options&&options.clickTolerance||0;this._isDragging=false;this._state="inactive";this._rotation=options&&options.rotation||0;this._rotationAlignment=options&&options.rotationAlignment||"auto";this._pitchAlignment=options&&options.pitchAlignment&&options.pitchAlignment!=="auto"?options.pitchAlignment:this._rotationAlignment;this.setOpacity();this.setOpacity(options===null||options===void 0?void 0:options.opacity,options===null||options===void 0?void 0:options.opacityWhenCovered);if(!options||!options.element){this._defaultMarker=true;this._element=DOM.create("div");this._element.setAttribute("aria-label","Map marker");const svg=DOM.createNS("http://www.w3.org/2000/svg","svg");const defaultHeight=41;const defaultWidth=27;svg.setAttributeNS(null,"display","block");svg.setAttributeNS(null,"height",`${defaultHeight}px`);svg.setAttributeNS(null,"width",`${defaultWidth}px`);svg.setAttributeNS(null,"viewBox",`0 0 ${defaultWidth} ${defaultHeight}`);const markerLarge=DOM.createNS("http://www.w3.org/2000/svg","g");markerLarge.setAttributeNS(null,"stroke","none");markerLarge.setAttributeNS(null,"stroke-width","1");markerLarge.setAttributeNS(null,"fill","none");markerLarge.setAttributeNS(null,"fill-rule","evenodd");const page1=DOM.createNS("http://www.w3.org/2000/svg","g");page1.setAttributeNS(null,"fill-rule","nonzero");const shadow=DOM.createNS("http://www.w3.org/2000/svg","g");shadow.setAttributeNS(null,"transform","translate(3.0, 29.0)");shadow.setAttributeNS(null,"fill","#000000");const ellipses=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];for(const data of ellipses){const ellipse=DOM.createNS("http://www.w3.org/2000/svg","ellipse");ellipse.setAttributeNS(null,"opacity","0.04");ellipse.setAttributeNS(null,"cx","10.5");ellipse.setAttributeNS(null,"cy","5.80029008");ellipse.setAttributeNS(null,"rx",data["rx"]);ellipse.setAttributeNS(null,"ry",data["ry"]);shadow.appendChild(ellipse)}const background=DOM.createNS("http://www.w3.org/2000/svg","g");background.setAttributeNS(null,"fill",this._color);const bgPath=DOM.createNS("http://www.w3.org/2000/svg","path");bgPath.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z");background.appendChild(bgPath);const border=DOM.createNS("http://www.w3.org/2000/svg","g");border.setAttributeNS(null,"opacity","0.25");border.setAttributeNS(null,"fill","#000000");const borderPath=DOM.createNS("http://www.w3.org/2000/svg","path");borderPath.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z");border.appendChild(borderPath);const maki=DOM.createNS("http://www.w3.org/2000/svg","g");maki.setAttributeNS(null,"transform","translate(6.0, 7.0)");maki.setAttributeNS(null,"fill","#FFFFFF");const circleContainer=DOM.createNS("http://www.w3.org/2000/svg","g");circleContainer.setAttributeNS(null,"transform","translate(8.0, 8.0)");const circle1=DOM.createNS("http://www.w3.org/2000/svg","circle");circle1.setAttributeNS(null,"fill","#000000");circle1.setAttributeNS(null,"opacity","0.25");circle1.setAttributeNS(null,"cx","5.5");circle1.setAttributeNS(null,"cy","5.5");circle1.setAttributeNS(null,"r","5.4999962");const circle2=DOM.createNS("http://www.w3.org/2000/svg","circle");circle2.setAttributeNS(null,"fill","#FFFFFF");circle2.setAttributeNS(null,"cx","5.5");circle2.setAttributeNS(null,"cy","5.5");circle2.setAttributeNS(null,"r","5.4999962");circleContainer.appendChild(circle1);circleContainer.appendChild(circle2);page1.appendChild(shadow);page1.appendChild(background);page1.appendChild(border);page1.appendChild(maki);page1.appendChild(circleContainer);svg.appendChild(page1);svg.setAttributeNS(null,"height",`${defaultHeight*this._scale}px`);svg.setAttributeNS(null,"width",`${defaultWidth*this._scale}px`);this._element.appendChild(svg);this._offset=performance$1.Point.convert(options&&options.offset||[0,-14])}else{this._element=options.element;this._offset=performance$1.Point.convert(options&&options.offset||[0,0])}this._element.classList.add("maplibregl-marker");this._element.addEventListener("dragstart",(e=>{e.preventDefault()}));this._element.addEventListener("mousedown",(e=>{e.preventDefault()}));applyAnchorClass(this._element,this._anchor,"marker");if(options&&options.className){for(const name of options.className.split(" ")){this._element.classList.add(name)}}this._popup=null}addTo(map){this.remove();this._map=map;map.getCanvasContainer().appendChild(this._element);map.on("move",this._update);map.on("moveend",this._update);map.on("terrain",this._update);this.setDraggable(this._draggable);this._update();this._map.on("click",this._onMapClick);return this}remove(){if(this._opacityTimeout){clearTimeout(this._opacityTimeout);delete this._opacityTimeout}if(this._map){this._map.off("click",this._onMapClick);this._map.off("move",this._update);this._map.off("moveend",this._update);this._map.off("mousedown",this._addDragHandler);this._map.off("touchstart",this._addDragHandler);this._map.off("mouseup",this._onUp);this._map.off("touchend",this._onUp);this._map.off("mousemove",this._onMove);this._map.off("touchmove",this._onMove);delete this._map}DOM.remove(this._element);if(this._popup)this._popup.remove();return this}getLngLat(){return this._lngLat}setLngLat(lnglat){this._lngLat=performance$1.LngLat.convert(lnglat);this._pos=null;if(this._popup)this._popup.setLngLat(this._lngLat);this._update();return this}getElement(){return this._element}setPopup(popup){if(this._popup){this._popup.remove();this._popup=null;this._element.removeEventListener("keypress",this._onKeyPress);if(!this._originalTabIndex){this._element.removeAttribute("tabindex")}}if(popup){if(!("offset"in popup.options)){const markerHeight=41-5.8/2;const markerRadius=13.5;const linearOffset=Math.abs(markerRadius)/Math.SQRT2;popup.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-markerHeight],"bottom-left":[linearOffset,(markerHeight-markerRadius+linearOffset)*-1],"bottom-right":[-linearOffset,(markerHeight-markerRadius+linearOffset)*-1],left:[markerRadius,(markerHeight-markerRadius)*-1],right:[-markerRadius,(markerHeight-markerRadius)*-1]}:this._offset}this._popup=popup;if(this._lngLat)this._popup.setLngLat(this._lngLat);this._originalTabIndex=this._element.getAttribute("tabindex");if(!this._originalTabIndex){this._element.setAttribute("tabindex","0")}this._element.addEventListener("keypress",this._onKeyPress)}return this}getPopup(){return this._popup}togglePopup(){const popup=this._popup;if(!popup)return this;else if(popup.isOpen())popup.remove();else popup.addTo(this._map);return this}_updateOpacity(force=false){var _a;const terrain=(_a=this._map)===null||_a===void 0?void 0:_a.terrain;if(!terrain){if(this._element.style.opacity!==this._opacity){this._element.style.opacity=this._opacity}return}if(force){this._opacityTimeout=null}else{if(this._opacityTimeout){return}this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null}),100)}const map=this._map;const terrainDistance=map.terrain.depthAtPoint(this._pos);const elevation=map.terrain.getElevationForLngLatZoom(this._lngLat,map.transform.tileZoom);const markerDistance=map.transform.lngLatToCameraDepth(this._lngLat,elevation);const forgiveness=.006;if(markerDistance-terrainDistanceforgiveness;this._element.style.opacity=centerIsInvisible?this._opacityWhenCovered:this._opacity}getOffset(){return this._offset}setOffset(offset){this._offset=performance$1.Point.convert(offset);this._update();return this}addClassName(className){this._element.classList.add(className)}removeClassName(className){this._element.classList.remove(className)}toggleClassName(className){return this._element.classList.toggle(className)}setDraggable(shouldBeDraggable){this._draggable=!!shouldBeDraggable;if(this._map){if(shouldBeDraggable){this._map.on("mousedown",this._addDragHandler);this._map.on("touchstart",this._addDragHandler)}else{this._map.off("mousedown",this._addDragHandler);this._map.off("touchstart",this._addDragHandler)}}return this}isDraggable(){return this._draggable}setRotation(rotation){this._rotation=rotation||0;this._update();return this}getRotation(){return this._rotation}setRotationAlignment(alignment){this._rotationAlignment=alignment||"auto";this._update();return this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(alignment){this._pitchAlignment=alignment&&alignment!=="auto"?alignment:this._rotationAlignment;this._update();return this}getPitchAlignment(){return this._pitchAlignment}setOpacity(opacity,opacityWhenCovered){if(opacity===undefined&&opacityWhenCovered===undefined){this._opacity="1";this._opacityWhenCovered="0.2"}if(opacity!==undefined){this._opacity=opacity}if(opacityWhenCovered!==undefined){this._opacityWhenCovered=opacityWhenCovered}if(this._map){this._updateOpacity(true)}return this}}const defaultOptions$2={positionOptions:{enableHighAccuracy:false,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:false,showAccuracyCircle:true,showUserLocation:true};let numberOfWatches=0;let noTimeout=false;class GeolocateControl extends performance$1.Evented{constructor(options){super();this._onSuccess=position=>{if(!this._map){return}if(this._isOutOfMapMaxBounds(position)){this._setErrorState();this.fire(new performance$1.Event("outofmaxbounds",position));this._updateMarker();this._finish();return}if(this.options.trackUserLocation){this._lastKnownPosition=position;switch(this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK";this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting");this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error");this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND";this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting");this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error");this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}}if(this.options.showUserLocation&&this._watchState!=="OFF"){this._updateMarker(position)}if(!this.options.trackUserLocation||this._watchState==="ACTIVE_LOCK"){this._updateCamera(position)}if(this.options.showUserLocation){this._dotElement.classList.remove("maplibregl-user-location-dot-stale")}this.fire(new performance$1.Event("geolocate",position));this._finish()};this._updateCamera=position=>{const center=new performance$1.LngLat(position.coords.longitude,position.coords.latitude);const radius=position.coords.accuracy;const bearing=this._map.getBearing();const options=performance$1.extend({bearing:bearing},this.options.fitBoundsOptions);const newBounds=LngLatBounds.fromLngLat(center,radius);this._map.fitBounds(newBounds,options,{geolocateSource:true})};this._updateMarker=position=>{if(position){const center=new performance$1.LngLat(position.coords.longitude,position.coords.latitude);this._accuracyCircleMarker.setLngLat(center).addTo(this._map);this._userLocationDotMarker.setLngLat(center).addTo(this._map);this._accuracy=position.coords.accuracy;if(this.options.showUserLocation&&this.options.showAccuracyCircle){this._updateCircleRadius()}}else{this._userLocationDotMarker.remove();this._accuracyCircleMarker.remove()}};this._onZoom=()=>{if(this.options.showUserLocation&&this.options.showAccuracyCircle){this._updateCircleRadius()}};this._onError=error=>{if(!this._map){return}if(this.options.trackUserLocation){if(error.code===1){this._watchState="OFF";this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting");this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active");this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error");this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background");this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error");this._geolocateButton.disabled=true;const title=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=title;this._geolocateButton.setAttribute("aria-label",title);if(this._geolocationWatchID!==undefined){this._clearWatch()}}else if(error.code===3&&noTimeout){return}else{this._setErrorState()}}if(this._watchState!=="OFF"&&this.options.showUserLocation){this._dotElement.classList.add("maplibregl-user-location-dot-stale")}this.fire(new performance$1.Event("error",error));this._finish()};this._finish=()=>{if(this._timeoutId){clearTimeout(this._timeoutId)}this._timeoutId=undefined};this._setupUI=supported=>{if(!this._map){return}this._container.addEventListener("contextmenu",(e=>e.preventDefault()));this._geolocateButton=DOM.create("button","maplibregl-ctrl-geolocate",this._container);DOM.create("span","maplibregl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true");this._geolocateButton.type="button";if(supported===false){performance$1.warnOnce("Geolocation support is not available so the GeolocateControl will be disabled.");const title=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=true;this._geolocateButton.title=title;this._geolocateButton.setAttribute("aria-label",title)}else{const title=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.title=title;this._geolocateButton.setAttribute("aria-label",title)}if(this.options.trackUserLocation){this._geolocateButton.setAttribute("aria-pressed","false");this._watchState="OFF"}if(this.options.showUserLocation){this._dotElement=DOM.create("div","maplibregl-user-location-dot");this._userLocationDotMarker=new Marker({element:this._dotElement});this._circleElement=DOM.create("div","maplibregl-user-location-accuracy-circle");this._accuracyCircleMarker=new Marker({element:this._circleElement,pitchAlignment:"map"});if(this.options.trackUserLocation)this._watchState="OFF";this._map.on("zoom",this._onZoom)}this._geolocateButton.addEventListener("click",(()=>this.trigger()));this._setup=true;if(this.options.trackUserLocation){this._map.on("movestart",(event=>{const fromResize=event.originalEvent&&event.originalEvent.type==="resize";if(!event.geolocateSource&&this._watchState==="ACTIVE_LOCK"&&!fromResize){this._watchState="BACKGROUND";this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active");this.fire(new performance$1.Event("trackuserlocationend"))}}))}};this.options=performance$1.extend({},defaultOptions$2,options)}onAdd(map){this._map=map;this._container=DOM.create("div","maplibregl-ctrl maplibregl-ctrl-group");checkGeolocationSupport().then((supported=>this._setupUI(supported)));return this._container}onRemove(){if(this._geolocationWatchID!==undefined){window.navigator.geolocation.clearWatch(this._geolocationWatchID);this._geolocationWatchID=undefined}if(this.options.showUserLocation&&this._userLocationDotMarker){this._userLocationDotMarker.remove()}if(this.options.showAccuracyCircle&&this._accuracyCircleMarker){this._accuracyCircleMarker.remove()}DOM.remove(this._container);this._map.off("zoom",this._onZoom);this._map=undefined;numberOfWatches=0;noTimeout=false}_isOutOfMapMaxBounds(position){const bounds=this._map.getMaxBounds();const coordinates=position.coords;return bounds&&(coordinates.longitudebounds.getEast()||coordinates.latitudebounds.getNorth())}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR";this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active");this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR";this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active");this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR";this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background");this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background-error");this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case"ACTIVE_ERROR":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}}_updateCircleRadius(){const bounds=this._map.getBounds();const southEastPoint=bounds.getSouthEast();const northEastPoint=bounds.getNorthEast();const mapHeightInMeters=southEastPoint.distanceTo(northEastPoint);const mapHeightInPixels=this._map._container.clientHeight;const circleDiameter=Math.ceil(2*(this._accuracy/(mapHeightInMeters/mapHeightInPixels)));this._circleElement.style.width=`${circleDiameter}px`;this._circleElement.style.height=`${circleDiameter}px`}trigger(){if(!this._setup){performance$1.warnOnce("Geolocate control triggered before added to a map");return false}if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE";this.fire(new performance$1.Event("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":numberOfWatches--;noTimeout=false;this._watchState="OFF";this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting");this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active");this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error");this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background");this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error");this.fire(new performance$1.Event("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK";this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background");if(this._lastKnownPosition)this._updateCamera(this._lastKnownPosition);this.fire(new performance$1.Event("trackuserlocationstart"));break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"OFF":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}if(this._watchState==="OFF"&&this._geolocationWatchID!==undefined){this._clearWatch()}else if(this._geolocationWatchID===undefined){this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");this._geolocateButton.setAttribute("aria-pressed","true");numberOfWatches++;let positionOptions;if(numberOfWatches>1){positionOptions={maximumAge:6e5,timeout:0};noTimeout=true}else{positionOptions=this.options.positionOptions;noTimeout=false}this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,positionOptions)}}else{window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions);this._timeoutId=setTimeout(this._finish,1e4)}return true}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID);this._geolocationWatchID=undefined;this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting");this._geolocateButton.setAttribute("aria-pressed","false");if(this.options.showUserLocation){this._updateMarker(null)}}}const defaultOptions$1={maxWidth:100,unit:"metric"};class ScaleControl{constructor(options){this._onMove=()=>{updateScale(this._map,this._container,this.options)};this.setUnit=unit=>{this.options.unit=unit;updateScale(this._map,this._container,this.options)};this.options=performance$1.extend({},defaultOptions$1,options)}getDefaultPosition(){return"bottom-left"}onAdd(map){this._map=map;this._container=DOM.create("div","maplibregl-ctrl maplibregl-ctrl-scale",map.getContainer());this._map.on("move",this._onMove);this._onMove();return this._container}onRemove(){DOM.remove(this._container);this._map.off("move",this._onMove);this._map=undefined}}function updateScale(map,container,options){const maxWidth=options&&options.maxWidth||100;const y=map._container.clientHeight/2;const left=map.unproject([0,y]);const right=map.unproject([maxWidth,y]);const maxMeters=left.distanceTo(right);if(options&&options.unit==="imperial"){const maxFeet=3.2808*maxMeters;if(maxFeet>5280){const maxMiles=maxFeet/5280;setScale(container,maxWidth,maxMiles,map._getUIString("ScaleControl.Miles"))}else{setScale(container,maxWidth,maxFeet,map._getUIString("ScaleControl.Feet"))}}else if(options&&options.unit==="nautical"){const maxNauticals=maxMeters/1852;setScale(container,maxWidth,maxNauticals,map._getUIString("ScaleControl.NauticalMiles"))}else if(maxMeters>=1e3){setScale(container,maxWidth,maxMeters/1e3,map._getUIString("ScaleControl.Kilometers"))}else{setScale(container,maxWidth,maxMeters,map._getUIString("ScaleControl.Meters"))}}function setScale(container,maxWidth,maxDistance,unit){const distance=getRoundNum(maxDistance);const ratio=distance/maxDistance;container.style.width=`${maxWidth*ratio}px`;container.innerHTML=`${distance} ${unit}`}function getDecimalRoundNum(d){const multiplier=Math.pow(10,Math.ceil(-Math.log(d)/Math.LN10));return Math.round(d*multiplier)/multiplier}function getRoundNum(num){const pow10=Math.pow(10,`${Math.floor(num)}`.length-1);let d=num/pow10;d=d>=10?10:d>=5?5:d>=3?3:d>=2?2:d>=1?1:getDecimalRoundNum(d);return pow10*d}class FullscreenControl extends performance$1.Evented{constructor(options={}){super();this._onFullscreenChange=()=>{const fullscreenElement=window.document.fullscreenElement||window.document.mozFullScreenElement||window.document.webkitFullscreenElement||window.document.msFullscreenElement;if(fullscreenElement===this._container!==this._fullscreen){this._handleFullscreenChange()}};this._onClickFullscreen=()=>{if(this._isFullscreen()){this._exitFullscreen()}else{this._requestFullscreen()}};this._fullscreen=false;if(options&&options.container){if(options.container instanceof HTMLElement){this._container=options.container}else{performance$1.warnOnce("Full screen control 'container' must be a DOM element.")}}if("onfullscreenchange"in document){this._fullscreenchange="fullscreenchange"}else if("onmozfullscreenchange"in document){this._fullscreenchange="mozfullscreenchange"}else if("onwebkitfullscreenchange"in document){this._fullscreenchange="webkitfullscreenchange"}else if("onmsfullscreenchange"in document){this._fullscreenchange="MSFullscreenChange"}}onAdd(map){this._map=map;if(!this._container)this._container=this._map.getContainer();this._controlContainer=DOM.create("div","maplibregl-ctrl maplibregl-ctrl-group");this._setupUI();return this._controlContainer}onRemove(){DOM.remove(this._controlContainer);this._map=null;window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange)}_setupUI(){const button=this._fullscreenButton=DOM.create("button","maplibregl-ctrl-fullscreen",this._controlContainer);DOM.create("span","maplibregl-ctrl-icon",button).setAttribute("aria-hidden","true");button.type="button";this._updateTitle();this._fullscreenButton.addEventListener("click",this._onClickFullscreen);window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange)}_updateTitle(){const title=this._getTitle();this._fullscreenButton.setAttribute("aria-label",title);this._fullscreenButton.title=title}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_handleFullscreenChange(){this._fullscreen=!this._fullscreen;this._fullscreenButton.classList.toggle("maplibregl-ctrl-shrink");this._fullscreenButton.classList.toggle("maplibregl-ctrl-fullscreen");this._updateTitle();if(this._fullscreen){this.fire(new performance$1.Event("fullscreenstart"));this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled();this._map.cooperativeGestures.disable()}else{this.fire(new performance$1.Event("fullscreenend"));if(this._prevCooperativeGesturesEnabled){this._map.cooperativeGestures.enable()}}}_exitFullscreen(){if(window.document.exitFullscreen){window.document.exitFullscreen()}else if(window.document.mozCancelFullScreen){window.document.mozCancelFullScreen()}else if(window.document.msExitFullscreen){window.document.msExitFullscreen()}else if(window.document.webkitCancelFullScreen){window.document.webkitCancelFullScreen()}else{this._togglePseudoFullScreen()}}_requestFullscreen(){if(this._container.requestFullscreen){this._container.requestFullscreen()}else if(this._container.mozRequestFullScreen){this._container.mozRequestFullScreen()}else if(this._container.msRequestFullscreen){this._container.msRequestFullscreen()}else if(this._container.webkitRequestFullscreen){this._container.webkitRequestFullscreen()}else{this._togglePseudoFullScreen()}}_togglePseudoFullScreen(){this._container.classList.toggle("maplibregl-pseudo-fullscreen");this._handleFullscreenChange();this._map.resize()}}class TerrainControl{constructor(options){this._toggleTerrain=()=>{if(this._map.getTerrain()){this._map.setTerrain(null)}else{this._map.setTerrain(this.options)}this._updateTerrainIcon()};this._updateTerrainIcon=()=>{this._terrainButton.classList.remove("maplibregl-ctrl-terrain");this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled");if(this._map.terrain){this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled");this._terrainButton.title=this._map._getUIString("TerrainControl.Disable")}else{this._terrainButton.classList.add("maplibregl-ctrl-terrain");this._terrainButton.title=this._map._getUIString("TerrainControl.Enable")}};this.options=options}onAdd(map){this._map=map;this._container=DOM.create("div","maplibregl-ctrl maplibregl-ctrl-group");this._terrainButton=DOM.create("button","maplibregl-ctrl-terrain",this._container);DOM.create("span","maplibregl-ctrl-icon",this._terrainButton).setAttribute("aria-hidden","true");this._terrainButton.type="button";this._terrainButton.addEventListener("click",this._toggleTerrain);this._updateTerrainIcon();this._map.on("terrain",this._updateTerrainIcon);return this._container}onRemove(){DOM.remove(this._container);this._map.off("terrain",this._updateTerrainIcon);this._map=undefined}}const defaultOptions={closeButton:true,closeOnClick:true,focusAfterOpen:true,className:"",maxWidth:"240px"};const focusQuerySelector=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");class Popup extends performance$1.Evented{constructor(options){super();this.remove=()=>{if(this._content){DOM.remove(this._content)}if(this._container){DOM.remove(this._container);delete this._container}if(this._map){this._map.off("move",this._update);this._map.off("move",this._onClose);this._map.off("click",this._onClose);this._map.off("remove",this.remove);this._map.off("mousemove",this._onMouseMove);this._map.off("mouseup",this._onMouseUp);this._map.off("drag",this._onDrag);this._map._canvasContainer.classList.remove("maplibregl-track-pointer");delete this._map}this.fire(new performance$1.Event("close"));return this};this._onMouseUp=event=>{this._update(event.point)};this._onMouseMove=event=>{this._update(event.point)};this._onDrag=event=>{this._update(event.point)};this._update=cursor=>{const hasPosition=this._lngLat||this._trackPointer;if(!this._map||!hasPosition||!this._content){return}if(!this._container){this._container=DOM.create("div","maplibregl-popup",this._map.getContainer());this._tip=DOM.create("div","maplibregl-popup-tip",this._container);this._container.appendChild(this._content);if(this.options.className){for(const name of this.options.className.split(" ")){this._container.classList.add(name)}}if(this._trackPointer){this._container.classList.add("maplibregl-popup-track-pointer")}}if(this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth){this._container.style.maxWidth=this.options.maxWidth}if(this._map.transform.renderWorldCopies&&!this._trackPointer){this._lngLat=smartWrap(this._lngLat,this._flatPos,this._map.transform)}if(this._trackPointer&&!cursor)return;const pos=this._flatPos=this._pos=this._trackPointer&&cursor?cursor:this._map.project(this._lngLat);if(this._map.terrain){this._flatPos=this._trackPointer&&cursor?cursor:this._map.transform.locationPoint(this._lngLat)}let anchor=this.options.anchor;const offset=normalizeOffset(this.options.offset);if(!anchor){const width=this._container.offsetWidth;const height=this._container.offsetHeight;let anchorComponents;if(pos.y+offset.bottom.ythis._map.transform.height-height){anchorComponents=["bottom"]}else{anchorComponents=[]}if(pos.xthis._map.transform.width-width/2){anchorComponents.push("right")}if(anchorComponents.length===0){anchor="bottom"}else{anchor=anchorComponents.join("-")}}const offsetedPos=pos.add(offset[anchor]).round();DOM.setTransform(this._container,`${anchorTranslate[anchor]} translate(${offsetedPos.x}px,${offsetedPos.y}px)`);applyAnchorClass(this._container,anchor,"popup")};this._onClose=()=>{this.remove()};this.options=performance$1.extend(Object.create(defaultOptions),options)}addTo(map){if(this._map)this.remove();this._map=map;if(this.options.closeOnClick){this._map.on("click",this._onClose)}if(this.options.closeOnMove){this._map.on("move",this._onClose)}this._map.on("remove",this.remove);this._update();this._focusFirstElement();if(this._trackPointer){this._map.on("mousemove",this._onMouseMove);this._map.on("mouseup",this._onMouseUp);if(this._container){this._container.classList.add("maplibregl-popup-track-pointer")}this._map._canvasContainer.classList.add("maplibregl-track-pointer")}else{this._map.on("move",this._update)}this.fire(new performance$1.Event("open"));return this}isOpen(){return!!this._map}getLngLat(){return this._lngLat}setLngLat(lnglat){this._lngLat=performance$1.LngLat.convert(lnglat);this._pos=null;this._trackPointer=false;this._update();if(this._map){this._map.on("move",this._update);this._map.off("mousemove",this._onMouseMove);if(this._container){this._container.classList.remove("maplibregl-popup-track-pointer")}this._map._canvasContainer.classList.remove("maplibregl-track-pointer")}return this}trackPointer(){this._trackPointer=true;this._pos=null;this._update();if(this._map){this._map.off("move",this._update);this._map.on("mousemove",this._onMouseMove);this._map.on("drag",this._onDrag);if(this._container){this._container.classList.add("maplibregl-popup-track-pointer")}this._map._canvasContainer.classList.add("maplibregl-track-pointer")}return this}getElement(){return this._container}setText(text){return this.setDOMContent(document.createTextNode(text))}setHTML(html){const frag=document.createDocumentFragment();const temp=document.createElement("body");let child;temp.innerHTML=html;while(true){child=temp.firstChild;if(!child)break;frag.appendChild(child)}return this.setDOMContent(frag)}getMaxWidth(){var _a;return(_a=this._container)===null||_a===void 0?void 0:_a.style.maxWidth}setMaxWidth(maxWidth){this.options.maxWidth=maxWidth;this._update();return this}setDOMContent(htmlNode){if(this._content){while(this._content.hasChildNodes()){if(this._content.firstChild){this._content.removeChild(this._content.firstChild)}}}else{this._content=DOM.create("div","maplibregl-popup-content",this._container)}this._content.appendChild(htmlNode);this._createCloseButton();this._update();this._focusFirstElement();return this}addClassName(className){if(this._container){this._container.classList.add(className)}}removeClassName(className){if(this._container){this._container.classList.remove(className)}}setOffset(offset){this.options.offset=offset;this._update();return this}toggleClassName(className){if(this._container){return this._container.classList.toggle(className)}}_createCloseButton(){if(this.options.closeButton){this._closeButton=DOM.create("button","maplibregl-popup-close-button",this._content);this._closeButton.type="button";this._closeButton.setAttribute("aria-label","Close popup");this._closeButton.innerHTML="×";this._closeButton.addEventListener("click",this._onClose)}}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const firstFocusable=this._container.querySelector(focusQuerySelector);if(firstFocusable)firstFocusable.focus()}}function normalizeOffset(offset){if(!offset){return normalizeOffset(new performance$1.Point(0,0))}else if(typeof offset==="number"){const cornerOffset=Math.round(Math.abs(offset)/Math.SQRT2);return{center:new performance$1.Point(0,0),top:new performance$1.Point(0,offset),"top-left":new performance$1.Point(cornerOffset,cornerOffset),"top-right":new performance$1.Point(-cornerOffset,cornerOffset),bottom:new performance$1.Point(0,-offset),"bottom-left":new performance$1.Point(cornerOffset,-cornerOffset),"bottom-right":new performance$1.Point(-cornerOffset,-cornerOffset),left:new performance$1.Point(offset,0),right:new performance$1.Point(-offset,0)}}else if(offset instanceof performance$1.Point||Array.isArray(offset)){const convertedOffset=performance$1.Point.convert(offset);return{center:convertedOffset,top:convertedOffset,"top-left":convertedOffset,"top-right":convertedOffset,bottom:convertedOffset,"bottom-left":convertedOffset,"bottom-right":convertedOffset,left:convertedOffset,right:convertedOffset}}else{return{center:performance$1.Point.convert(offset["center"]||[0,0]),top:performance$1.Point.convert(offset["top"]||[0,0]),"top-left":performance$1.Point.convert(offset["top-left"]||[0,0]),"top-right":performance$1.Point.convert(offset["top-right"]||[0,0]),bottom:performance$1.Point.convert(offset["bottom"]||[0,0]),"bottom-left":performance$1.Point.convert(offset["bottom-left"]||[0,0]),"bottom-right":performance$1.Point.convert(offset["bottom-right"]||[0,0]),left:performance$1.Point.convert(offset["left"]||[0,0]),right:performance$1.Point.convert(offset["right"]||[0,0])}}}const version=packageJSON.version;function setRTLTextPlugin(pluginURL,lazy){return rtlMainThreadPluginFactory().setRTLTextPlugin(pluginURL,lazy)}function getRTLTextPluginStatus(){return rtlMainThreadPluginFactory().getRTLTextPluginStatus()}function getVersion(){return version}function getWorkerCount(){return WorkerPool.workerCount}function setWorkerCount(count){WorkerPool.workerCount=count}function getMaxParallelImageRequests(){return performance$1.config.MAX_PARALLEL_IMAGE_REQUESTS}function setMaxParallelImageRequests(numRequests){performance$1.config.MAX_PARALLEL_IMAGE_REQUESTS=numRequests}function getWorkerUrl(){return performance$1.config.WORKER_URL}function setWorkerUrl(value){performance$1.config.WORKER_URL=value}function importScriptInWorkers(workerUrl){return getGlobalDispatcher().broadcast("importScript",workerUrl)}exports.AJAXError=performance$1.AJAXError;exports.Evented=performance$1.Evented;exports.LngLat=performance$1.LngLat;exports.MercatorCoordinate=performance$1.MercatorCoordinate;exports.Point=performance$1.Point;exports.addProtocol=performance$1.addProtocol;exports.config=performance$1.config;exports.removeProtocol=performance$1.removeProtocol;exports.AttributionControl=AttributionControl;exports.BoxZoomHandler=BoxZoomHandler;exports.CanvasSource=CanvasSource;exports.CooperativeGesturesHandler=CooperativeGesturesHandler;exports.DoubleClickZoomHandler=DoubleClickZoomHandler;exports.DragPanHandler=DragPanHandler;exports.DragRotateHandler=DragRotateHandler;exports.EdgeInsets=EdgeInsets;exports.FullscreenControl=FullscreenControl;exports.GeoJSONSource=GeoJSONSource;exports.GeolocateControl=GeolocateControl;exports.Hash=Hash;exports.ImageSource=ImageSource;exports.KeyboardHandler=KeyboardHandler;exports.LngLatBounds=LngLatBounds;exports.LogoControl=LogoControl;exports.Map=Map$1;exports.MapMouseEvent=MapMouseEvent;exports.MapTouchEvent=MapTouchEvent;exports.MapWheelEvent=MapWheelEvent;exports.Marker=Marker;exports.NavigationControl=NavigationControl;exports.Popup=Popup;exports.RasterDEMTileSource=RasterDEMTileSource;exports.RasterTileSource=RasterTileSource;exports.ScaleControl=ScaleControl;exports.ScrollZoomHandler=ScrollZoomHandler;exports.Style=Style;exports.TerrainControl=TerrainControl;exports.TwoFingersTouchPitchHandler=TwoFingersTouchPitchHandler;exports.TwoFingersTouchRotateHandler=TwoFingersTouchRotateHandler;exports.TwoFingersTouchZoomHandler=TwoFingersTouchZoomHandler;exports.TwoFingersTouchZoomRotateHandler=TwoFingersTouchZoomRotateHandler;exports.VectorTileSource=VectorTileSource;exports.VideoSource=VideoSource;exports.addSourceType=addSourceType;exports.clearPrewarmedResources=clearPrewarmedResources;exports.getMaxParallelImageRequests=getMaxParallelImageRequests;exports.getRTLTextPluginStatus=getRTLTextPluginStatus;exports.getVersion=getVersion;exports.getWorkerCount=getWorkerCount;exports.getWorkerUrl=getWorkerUrl;exports.importScriptInWorkers=importScriptInWorkers;exports.prewarm=prewarm;exports.setMaxParallelImageRequests=setMaxParallelImageRequests;exports.setRTLTextPlugin=setRTLTextPlugin;exports.setWorkerCount=setWorkerCount;exports.setWorkerUrl=setWorkerUrl}));var maplibregl$1=maplibregl;return maplibregl$1}));"use strict";var hortis=fluid.registerNamespace("hortis");hortis.taxonDisplayLookup={iNaturalistTaxonName:"Taxon Name:",observationCount:"Observation Count:",iNaturalistObsLink:"Observation:",taxonLink:"iNaturalist Taxon:",commonName:"",reportingStatus:"Status:",hulqName:"Hul'qumi'num name:",wikipediaSummary:"Wikipedia Summary",media:"Media",observationData:"Observation Data",iNaturalistTaxonImage:"iNaturalist Taxon Image:",phyloPic:"Taxon Icon:",taxonPic:"Taxon Picture:",taxonPicDescription:"Taxon Picture Description:"};hortis.friendlyDisplayLookup={...hortis.taxonDisplayLookup,iNaturalistTaxonName:"Species:"};hortis.commonFields=["commonName","wikipediaSummary"];hortis.dumpRow=function(key,value,markup,extraClazz,valueClazz,options){if(value){const toLook=options?.friendlyNames?hortis.friendlyDisplayLookup:hortis.taxonDisplayLookup;const keyName=key?toLook[key]||hortis.capitalize(key):"";valueClazz=valueClazz||"";const openPanel=options?.openTaxonPanels[key];const isRemainder=extraClazz&&extraClazz.includes("taxonDisplay-expandable-remainder");const clazz="taxonDisplay-row "+(extraClazz||"")+(openPanel?" taxonDisplay-expanded":" taxonDisplay-unexpanded");return fluid.stringTemplate(markup.taxonDisplayRow,{key:isRemainder?"":keyName,value:value,rootAttrs:'class="'+clazz+'"',valueClazz:valueClazz})}else{return""}};hortis.renderDate=function(date){return new Date(date).toISOString().substring(0,10)};hortis.expandButtonMarkup='';hortis.expandableBlock='
%blockName'+hortis.expandButtonMarkup+"
"+'
%block
';hortis.sourceTable={iNat:"iNaturalist",PMLS:"Pacific Marine Life Surveys",RBCM:"Royal British Columbia Museum",CMN:"Canadian Museum of Nature",BCCSN:"British Columbia Cetacean Sightings Network","Gal-Salm":"Erickson",CHU2010:"Chu and Leys (2010)",CHU2012:"Chu and Leys (2012)",Hunterston:"Hunterston Farms BioBlitz 2010"};hortis.sourceFromId=function(obsId){const colpos=obsId?obsId.indexOf(":"):-1;return colpos===-1?null:obsId.substring(0,colpos)};hortis.datasetIdFromObs=function(obsId){const colpos=obsId.indexOf(":");return obsId.substring(0,colpos)};hortis.localIdFromObs=function(obsId){const colpos=obsId.indexOf(":");return obsId.substring(colpos+1)};hortis.renderObsId=function(obsId){const dataset=hortis.datasetIdFromObs(obsId);if(dataset==="iNat"){const localId=hortis.localIdFromObs(obsId);return fluid.stringTemplate(' (%obsId)',{obsId:localId})}else{return obsId}};hortis.renderObsBound=function(row,prefix,markup,options){const date=row[prefix+"Timestamp"];if(date){const capPrefix=prefix==="since"?"":hortis.capitalize(prefix);const recordedBy=row[prefix+"RecordedBy"];const catalogueNumber=row[prefix+"CatalogueNumber"];const value=hortis.renderDate(row[prefix+"Timestamp"])+(recordedBy&&!options.suppressObsAuthors?" by "+recordedBy:"");const row1=hortis.dumpRow(capPrefix+(prefix==="since"?"First Observed:":" Reported:"),value,markup);const obsId=row[prefix+"ObservationId"];const collection=row[prefix+"Collection"];const institutionCode=row[prefix+"InstitutionCode"];const obsIdCollection=hortis.sourceFromId(row[prefix+"ObservationId"]);const renderedCollection=institutionCode||hortis.sourceTable[obsIdCollection||collection]||collection;let source=renderedCollection+(catalogueNumber&&institutionCode!=="iNaturalist"?" ("+catalogueNumber+")":"");if(obsId&&obsIdCollection==="iNat"){source+=hortis.renderObsId(obsId)}if(catalogueNumber&&institutionCode==="iNaturalist"){source+=hortis.renderObsId("iNat:"+catalogueNumber)}const row2=hortis.dumpRow("Source:",source,markup);return row1+row2}else{return""}};hortis.mediaBlock='
%mediaName
'+'
'+'
%mediaText
';hortis.renderOneMedium=function(medium){return fluid.stringTemplate(hortis.mediaBlock,{mediaName:medium.Name,mediaTarget:medium.URL,mediaImage:medium.Thumbnail,mediaText:medium.Description})};hortis.renderExpandable=function(terms,expanded){const allTerms={...terms,state:expanded?"taxonDisplay-expanded":"taxonDisplay-unexpanded"};return fluid.stringTemplate(hortis.expandableBlock,allTerms)};hortis.renderMedia=function(media){const mediaBlocks=media.map((oneMedium=>hortis.renderOneMedium(oneMedium)));return mediaBlocks.join("\n")};hortis.hulqValues=["Food","Medicinal","Spiritual","Material","Trade","Indicator"];hortis.hulqValueItem=`\n
\n \n
%label
\n
`;hortis.hulqValueBlock=`
%valueBlocks
`;hortis.drivePlayerTemplate=``;hortis.audioPlayerTemplate=``;hortis.driveToPreview=function(url){const lastSlash=url.lastIndexOf("/");return url.substring(0,lastSlash)+"/preview"};hortis.renderAudioLink=function(audioLink){return audioLink?fluid.stringTemplate(hortis.audioPlayerTemplate,{url:audioLink}):""};hortis.dumpHulqName=function(row,hulqName,markup){const player=hortis.renderAudioLink(row.audioLink);const nameRow=hortis.dumpRow("hulqName",`
${hulqName}
`+player,markup);return nameRow};hortis.dumpHulqValues=function(row,markup){const valueBlocks=hortis.hulqValues.map((function(value){return row[value.toLowerCase()+"Value"]==="1"?value:"missing"})).map((function(img,index){return img==="missing"?"":fluid.stringTemplate(hortis.hulqValueItem,{img:img.toLowerCase(),label:hortis.hulqValues[index]})}));const valueBlock=fluid.stringTemplate(hortis.hulqValueBlock,{valueBlocks:valueBlocks.join("\n")});const valueRow1=hortis.dumpRow("Cultural values"," ",markup,"taxonDisplay-empty-header");const valueRow2=hortis.dumpRow("",valueBlock,markup,"taxonDisplay-empty-row");return valueRow1+valueRow2};hortis.iNatExtern=`iNaturalist`;hortis.imageTemplate=`\n
\n
\n %iNatExtern\n
\n
\n %photoCaption\n
\n
`;hortis.idToTaxonLink=function(taxonId){return"https://www.inaturalist.org/taxa/"+taxonId};hortis.renderTaxonDisplay=function(row,accessRow,markup,options){if(!row){return null}let togo=markup.taxonDisplayHeader;const dumpRow=function(keyName,value,extraClazz,options){if(keyName==="wikipediaSummary"&&value){const row1=hortis.dumpRow("Wikipedia Summary",hortis.expandButtonMarkup,markup,"taxonDisplay-expandable-header taxonDisplay-unexpanded taxonDisplay-runon-header");const row2=hortis.dumpRow("",value,markup,"taxonDisplay-expandable-remainder taxonDisplay-unexpanded taxonDisplay-runon-remainder","taxonDisplay-wikipediaSummary");togo+=row1+row2}else{togo+=hortis.dumpRow(keyName,value,markup,extraClazz,undefined,options)}};const dumpImage=function(keyName,url,taxonId,photoCaption){const imageMarkup=fluid.stringTemplate(markup.imageTemplate,{imgUrl:url,photoCaption:photoCaption,iNatExtern:taxonId?fluid.stringTemplate(hortis.iNatExtern,{iNatLink:hortis.idToTaxonLink(taxonId)}):""});togo+=imageMarkup};const dumpPhyloPic=function(keyName,url){togo+=hortis.dumpRow(keyName,`
Taxon photo
`,markup)};const photoCaption=`
${accessRow.featuredName}
`+hortis.renderAudioLink(row.audioLink);if(!row.taxonName){if(row.iNaturalistTaxonImage&&!row.taxonPic){dumpImage("iNaturalistTaxonImage",row.iNaturalistTaxonImage,row.id,photoCaption)}else if(row.taxonPic){dumpImage("taxonPic",row.taxonPic)}if(row.phyloPicUrl){dumpPhyloPic("phyloPic",row.phyloPicUrl)}dumpRow(row.rank,accessRow.scientificName,"taxonDisplay-rank");hortis.commonFields.forEach((function(field){dumpRow(field,row[field])}));dumpRow("taxonPicDescription",row.taxonPicDescription);dumpRow("Species:",row.childCount);dumpRow("observationCount",row.observationCount)}else{if(row.iNaturalistTaxonImage&&!row.obsPhotoLink){dumpImage("iNaturalistTaxonImage",row.iNaturalistTaxonImage,row.id,photoCaption)}if(row.species){dumpRow("iNaturalistTaxonName",(row.taxonName||row.iNaturalistTaxonName)+(row.authority?" "+row.authority:""),"taxonDisplay-rank",options)}if(accessRow.commonName!==accessRow.featuredName){dumpRow("commonName",row.commonName&&hortis.capitalize(row.commonName))}if(accessRow.nativeName&&options.culturalValues){togo+=hortis.dumpHulqValues(row,markup)}if(row.media){const mediaPanel=hortis.renderMedia(row.media,"");togo+=hortis.dumpRow("media",hortis.expandButtonMarkup,markup,"taxonDisplay-expandable-header",null,options);togo+=hortis.dumpRow("media",mediaPanel,markup,"taxonDisplay-expandable-remainder taxonDisplay-runon-remainder",null,options)}dumpRow("wikipediaSummary",row.wikipediaSummary);let obsPanel="";obsPanel+=hortis.dumpRow("reportingStatus",row.reportingStatus&&hortis.capitalize(row.reportingStatus),markup);obsPanel+=hortis.renderObsBound(row,"first",markup,options);obsPanel+=hortis.renderObsBound(row,"last",markup,options);obsPanel+=hortis.renderObsBound(row,"since",markup,options);if(row.iNaturalistObsLink){obsPanel+=hortis.dumpRow("iNaturalistObsLink",`${row.iNaturalistObsLink}`,markup)}obsPanel+=hortis.dumpRow("observationCount",row.observationCount,markup);togo+=hortis.dumpRow("observationData",hortis.expandButtonMarkup,markup,"taxonDisplay-expandable-header",null,options);togo+=hortis.dumpRow("observationData",obsPanel,markup,"taxonDisplay-expandable-remainder taxonDisplay-runon-remainder",null,options);if(row.obsPhotoLink){dumpImage("Observation photo",row.obsPhotoLink)}}togo+=markup.taxonDisplayFooter;return togo};hortis.bindRowExpander=function(that){that.container.on("click",".taxonDisplay-expand",(function(e){const target=$(e.target);const header=target.closest(".taxonDisplay-expandable-header");header.toggleClass("taxonDisplay-expanded");header.toggleClass("taxonDisplay-unexpanded");const showing=header.hasClass("taxonDisplay-expanded");const siblings=header.parent().children();const ownIndex=header.index();const next=$(siblings[ownIndex+1]);if(next.hasClass("taxonDisplay-expandable-remainder")){next.toggleClass("taxonDisplay-expanded",showing);next.toggleClass("taxonDisplay-unexpanded",!showing)}}))};hortis.updateTaxonDisplay=function(that,taxonRow){const content=taxonRow?hortis.renderTaxonDisplay(taxonRow,that.accessRow(taxonRow),that.options.markup,that.options):null;const taxonDisplay=that.container[0];taxonDisplay.innerHTML=content||""};fluid.defaults("hortis.taxonDisplay",{gradeNames:"fluid.viewComponent",listeners:{"onCreate.bindRowExpander":{funcName:"hortis.bindRowExpander",args:["{that}"]}},invokers:{accessRow:{funcName:"hortis.accessRowHulq"}},markup:{taxonDisplayHeader:"",taxonDisplayRow:'
%key%value
',taxonDisplayFooter:"",imageTemplate:hortis.imageTemplate},members:{selectedTaxonId:"@expand:signal()",obsRows:"@expand:signal()",taxaById:"@expand:signal()",obsForTaxonId:"@expand:fluid.computed(hortis.obsForTaxon, {that}.obsRows, {that}.selectedTaxonId)",taxonRow:"@expand:fluid.computed(hortis.computeTaxonDisplayRow, {that}.obsForTaxonId, {that}.taxaById, {that}.selectedTaxonId)",updateDisplay:"@expand:fluid.effect(hortis.updateTaxonDisplay, {that}, {that}.taxonRow)"},openTaxonPanels:{observationData:true,media:true}});hortis.byField=function(fieldName){return(a,b)=>a[fieldName]>b[fieldName]?1:-1};hortis.obsForTaxon=function(obsRows,taxonId){return obsRows.filter((row=>row["iNaturalist taxon ID"]===taxonId)).sort(hortis.byField("Date observed"))};hortis.obsToSummaryFields={RecordedBy:"Recorded by",ObservationId:"observationId",Timestamp:"Date observed"};hortis.computeTaxonDisplayRow=function(taxonObs,taxaById,taxonId){if(taxonId){const togo=Object.assign({},taxaById[taxonId]);const obsToFields=function(target,prefix,row){Object.entries(hortis.obsToSummaryFields).forEach((([key,value])=>{target[prefix+key]=row[value]}))};if(taxonObs.length>0){obsToFields(togo,"first",taxonObs[0]);obsToFields(togo,"last",fluid.peek(taxonObs))}return togo}else{return null}};"use strict";var hortis=fluid.registerNamespace("hortis");var{effect:effect,batch:batch}=preactSignalsCore;fluid.defaults("hortis.bareResourceLoader",{gradeNames:"fluid.component",members:{completionPromise:"@expand:fluid.promise()"}});fluid.defaults("hortis.csvReader",{gradeNames:"hortis.bareResourceLoader",csvOptions:{header:true,skipEmptyLines:true},members:{rows:"@expand:signal()"},events:{},listeners:{"onCreate.parse":"hortis.csvReader.parse({that}, {that}.options.csvOptions, {that}.options.url)"}});Object.defineProperty(fluid,"log",{get:function(){return fluid.isLogging()?console.log.bind(window.console,fluid.renderTimestamp(new Date)+": "):function(){}}});hortis.toggleClass=function(container,clazz,value,inverse){container.classList[value^inverse?"add":"remove"](clazz)};hortis.csvReader.parse=function(that,csvOptions,url){const options={...csvOptions,complete:function(results){that.parsed=results;that.data=results.data;that.headers=results.meta.fields;that.completionPromise.resolve(that.data);that.rows.value=that.data},error:function(err){that.completionPromise.reject();fluid.fail("Error parsing CSV file ",url,": ",err)}};Papa.parse(url,options)};fluid.defaults("hortis.urlCsvReader",{gradeNames:"hortis.csvReader",csvOptions:{download:true}});fluid.defaults("hortis.vizLoader",{gradeNames:["fluid.component"],components:{taxaLoader:{type:"hortis.urlCsvReader",options:{url:"{vizLoader}.options.taxaFile"}},obsLoader:{type:"hortis.urlCsvReader",options:{url:"{vizLoader}.options.obsFile"}},taxa:{type:"hortis.taxa",options:{members:{rows:"{vizLoader}.taxaRows"}}}},events:{onResourcesLoaded:null},members:{resourcesLoaded:"@expand:signal()",taxaRows:"@expand:signal()",obsRows:"@expand:signal()",filteredObs:"{that}.obsRows",finalFilteredObs:"@expand:fluid.computed({that}.filterObsByTaxa, {that}.filteredObs)"},invokers:{filterObs:fluid.identity,filterObsByTaxa:fluid.identity},listeners:{"onCreate.bindResources":"hortis.vizLoader.bindResources"}});hortis.vizLoader.bindResources=async function(that){const resourceLoaders=fluid.queryIoCSelector(that,"hortis.bareResourceLoader",true);const promises=resourceLoaders.map((resourceLoader=>resourceLoader.completionPromise));const[taxa,obs]=await Promise.all(promises);batch((()=>{that.taxaRows.value=taxa;that.obsRows.value=obs;that.resourcesLoaded.value=true;that.events.onResourcesLoaded.fire()}))};hortis.taxonTooltipTemplate=`
\n
\n
%taxonRank: %taxonNames
\n
`;hortis.capitalize=function(string){return string.charAt(0).toUpperCase()+string.slice(1)};hortis.renderTaxonTooltip=function(that,hoverId){const row=that.rowById.value[hoverId];const terms={imgUrl:row.iNaturalistTaxonImage||""};if(row.rank){terms.taxonRank=hortis.capitalize(row.rank)}else{terms.taxonRank="Species"}const names=[row.taxonName||row.iNaturalistTaxonName,row.commonName,row.hulqName].filter((name=>name));terms.taxonNames=names.join(" / ");return fluid.stringTemplate(hortis.taxonTooltipTemplate,terms)};hortis.isInDocument=function(node){const dokkument=fluid.getDocument(node),container=node[0];return $.contains(dokkument,container)||dokkument===container};hortis.clearAllTooltips=function(that){hortis.clearTooltip(that);$(".ui-tooltip").remove();that[that.options.tooltipKey].value=null};hortis.clearTooltip=function(that){const tooltipTarget=that.tooltipTarget;if(tooltipTarget){that.tooltipTarget=null;if(hortis.isInDocument(tooltipTarget)){tooltipTarget.tooltip("destroy")}else{hortis.clearAllTooltips(that)}}};hortis.updateTooltip=function(that,id){const content=id?that.renderTooltip(id):null;hortis.clearTooltip(that);if(content){const target=$(that.hoverEvent.target);target.tooltip({items:target});target.tooltip("option","content",content||"");target.tooltip("option","track",true);target.tooltip("open",that.hoverEvent);that.tooltipTarget=target}else{that.hoverEvent=null}};hortis.subscribeHover=function(that){const tooltipKey=that.options.tooltipKey;return effect((()=>{hortis.updateTooltip(that,that[tooltipKey].value)}))};fluid.defaults("hortis.withTooltip",{invokers:{renderTooltip:"fluid.notImplemented"},members:{subscribeHover:"@expand:hortis.subscribeHover({that})"}});fluid.defaults("hortis.checkbox",{gradeNames:"fluid.stringTemplateRenderingView",members:{value:"@expand:signal()",valueToDom:"@expand:fluid.effect(hortis.checkbox.valueToDom, {that}.value, {that}.dom.control.0)"},selectors:{control:"input"},elideParent:false,markup:{container:`\n \n \n \n \n \n \n `},listeners:{"onCreate.listenCheck":"hortis.checkbox.listenCheck"}});hortis.checkbox.valueToDom=function(value,node){const state=value?"selected":"unselected";node.checked=state==="selected";node.setAttribute("indeterminate",state==="indeterminate");const holder=node.closest(".p-icon");const ui=holder.querySelector(".icon");$(ui).toggleClass("mdi-check",state!=="indeterminate")};hortis.checkbox.listenCheck=function(that){that.dom.locate("control").on("click",(function(){that.value.value=this.checked}))};hortis.closeParentTaxa=function(rowFocus,rowById){Object.keys(rowFocus).forEach((function(id){let row=rowById[id];while(row){rowFocus[row.id]=true;row=row.parent}}));return rowFocus};hortis.taxaFromObs=function(filteredObs,rowById){const taxonIds={};filteredObs.forEach((row=>{taxonIds[row["iNaturalist taxon ID"]]=true}));return hortis.closeParentTaxa(taxonIds,rowById)};hortis.bindTaxonHover=function(that,layoutHolder){const hoverable=that.options.selectors.hoverable;that.container.on("mouseenter",hoverable,(function(e){const id=this.dataset.rowId;layoutHolder.hoverEvent=e;layoutHolder.hoverId.value=id}));that.container.on("mouseleave",hoverable,(function(){layoutHolder.hoverId.value=null}));that.container.on("click",hoverable,(function(){const id=this.dataset.rowId;layoutHolder.events.taxonSelect.fire(id)}))};fluid.defaults("hortis.taxa",{gradeNames:"fluid.component",members:{rowByIdPre:"@expand:fluid.computed(hortis.indexTree, {that}.rows)",rowById:"@expand:fluid.computed(hortis.taxa.map, {that}.rows, {that}.rowByIdPre)",entries:"@expand:fluid.computed(hortis.computeEntries, {that}.rows, {that}.acceptRow)",entryById:"@expand:fluid.computed(hortis.indexEntries, {that}.entries)"},invokers:{acceptRow:"hortis.acceptRow({that}, {arguments}.0)"}});hortis.acceptRow=function(){return true};hortis.computeEntries=function(rows,acceptRow){const togo=[];fluid.each(rows,(function(row){if(acceptRow(row)){togo.push({row:row,children:hortis.computeEntries(row.children,acceptRow)})}else{const dChildren=hortis.computeEntries(row.children,acceptRow);Array.prototype.push.apply(togo,dChildren)}}));return hortis.sortChecklistLevel(togo)};hortis.indexEntries=function(entries){const index={};entries.forEach((function(entry){index[entry.row.id]=entry}));return index};hortis.indexTree=function(flatTree){const index={};flatTree.forEach((function(row){index[row.id]=row}));return index};hortis.taxa.map=function(rows,byId){rows.forEach(((row,i)=>{row.flatIndex=i;if(!row.children){row.children=[]}if(row.parentId){const parent=byId[row.parentId];row.parent=parent;fluid.pushArray(parent,"children",row)}}));const assignDepth=function(node,depth){node.depth=depth;node.children.forEach((child=>assignDepth(child,depth+1)))};if(rows.length>0){assignDepth(rows[0],0)}return byId};fluid.defaults("hortis.layoutHolder",{gradeNames:["fluid.modelComponent","hortis.withTooltip"],tooltipKey:"hoverId",events:{taxonSelect:null},members:{taxonHistory:"@expand:signal([])",historyIndex:"@expand:signal(0)",rootId:"@expand:signal({that}.options.rootId)",rowFocus:"@expand:signal({})",rowSelection:"@expand:signal({})",selectedId:"@expand:signal(null)",hoverId:"@expand:signal(null)"},modelRelay:{isAtRoot:{target:"isAtRoot",args:["{that}.model.layoutId","{that}.options.rootId"],func:(x,y)=>x===y}},invokers:{renderTooltip:"hortis.renderTaxonTooltip({that}, {arguments}.0)"}});fluid.defaults("hortis.vizLoaderWithMap",{gradeNames:["fluid.viewComponent","hortis.vizLoader"],selectors:{map:".imerss-map"},components:{map:{type:"hortis.libreMap",container:"{that}.dom.map",options:{gradeNames:"{vizLoader}.options.mapGrades"}}}});hortis.projectBounds={Galiano:[[48.855,-123.65],[49.005,-123.25]],Valdes:[[49,-123.798],[49.144,-123.504]],Xetthecum:[[48.93713,-123.511],[48.9511,-123.498]],Pepiowelh:[[48.565,-123.1575],[48.598,-123.1266]],HoweSound:[[49.16,-124.281],[50.17,-122.05]],SalishSea:[[47.568,-124.2],[49.134,-122.059]]};hortis.initBounds=function(){const bounds=[[90,180],[-90,-180]];return bounds};hortis.updateBounds=function(bounds,lat,long){bounds[0][0]=Math.min(bounds[0][0],lat);bounds[0][1]=Math.min(bounds[0][1],long);bounds[1][0]=Math.max(bounds[1][0],lat);bounds[1][1]=Math.max(bounds[1][1],long)};hortis.expandBounds=function(bounds,factor,latMin,longMin){const longSpan=bounds[1][1]-bounds[0][1];const latSpan=bounds[1][0]-bounds[0][0];const longD=Math.max(longSpan*factor,longMin/2);const latD=Math.max(latSpan*factor,latMin/2);if(longSpan<360){bounds[1][1]+=longD;bounds[0][1]-=longD;bounds[1][0]+=latD;bounds[0][0]-=latD}};fluid.defaults("hortis.libreMap",{gradeNames:"fluid.viewComponent",zoomDuration:1e3,mapOptions:{style:{version:8,layers:[],sources:{}}},members:{map:"@expand:hortis.libreMap.make({that}.container.0, {that}.options.mapOptions, {that}.options.zoomDuration, {that}.mapLoaded)",mapLoaded:"@expand:signal()"}});const initNavigationControl=function(options){this.options=options;this._container=fluid.h("div",{class:"maplibregl-ctrl maplibregl-ctrl-group"});this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(e=>this._map.zoomIn({duration:options.zoomDuration,essential:true},{originalEvent:e})));this._zoomInButton.appendChild(fluid.h("span",{class:"maplibregl-ctrl-icon","aria-hidden":true}));this._zoomOutButton=this._createButton("maplibregl-ctrl-zoom-out",(e=>this._map.zoomOut({duration:options.zoomDuration,essential:true},{originalEvent:e})));this._zoomOutButton.appendChild(fluid.h("span",{class:"maplibregl-ctrl-icon","aria-hidden":true}));this._updateZoomButtons=()=>{const zoom=this._map.getZoom();const isMax=zoom===this._map.getMaxZoom();const isMin=zoom===this._map.getMinZoom();this._zoomInButton.disabled=isMax;this._zoomOutButton.disabled=isMin;this._zoomInButton.setAttribute("aria-disabled",isMax.toString());this._zoomOutButton.setAttribute("aria-disabled",isMin.toString())};this._setButtonTitle=(button,title)=>{const str=this._map._getUIString(`NavigationControl.${title}`);button.title=str;button.setAttribute("aria-label",str)}};const makeNavigationControl=function(options){const inst=Object.create(maplibregl.NavigationControl.prototype);initNavigationControl.bind(inst)(options);return inst};hortis.libreMap.zoomControls=function(map,zoomDuration){map.addControl(makeNavigationControl({showCompass:false,showZoom:true,zoomDuration:zoomDuration}));map.dragRotate.disable();map.touchZoomRotate.disableRotation()};hortis.libreMap.make=function(container,mapOptions,zoomDuration,mapLoaded){const map=new maplibregl.Map({container:container,...mapOptions});map.on("load",(function(){console.log("Map loaded");mapLoaded.value=1}));hortis.libreMap.zoomControls(map,zoomDuration);return map};fluid.defaults("hortis.libreMap.withTiles",{addTiles:"@expand:fluid.effect(hortis.libreMap.addTileLayers, {that}.map, {that}.options.tileSets, {that}.mapLoaded)"});fluid.defaults("hortis.libreMap.streetmapTiles",{tileSets:{baseMap:{tiles:["https://tile.openstreetmap.org/{z}/{x}/{y}.png"],attribution:'© OpenStreetMap contributors',tileSize:256}}});fluid.defaults("hortis.libreMap.usEcoL3Tiles",{tileSets:{ecoL3:{tiles:["https://usda-nifa-b-team.github.io/b-team/tiles/us_eco_l3_tiles/{z}/{x}/{y}.png"],tileSize:512,maxzoom:8,paint:{"raster-opacity":.3}}}});hortis.libreMap.addTileLayers=function(map,tileSets){const tileKeys=Object.keys(tileSets);tileKeys.reverse().forEach((function(key){const tileSet=tileSets[key];const paint=tileSet.paint||{};map.addSource(key,{type:"raster",...fluid.censorKeys(tileSet,["paint"])});map.addLayer({id:key,type:"raster",source:key,paint:paint})}))};hortis.libreMap.viridisStops=[[0,"#440154"],[.2,"#414487"],[.4,"#2a788e"],[.6,"#22a884"],[.8,"#7ad151"],[1,"#fde725"]];hortis.libreMap.natureStops=[[0,"#ffffff"],[1,"#09326d"]];fluid.defaults("hortis.libreMap.withObsGrid",{gradeNames:["hortis.withTooltip"],tooltipKey:"hoverCell",fillStops:hortis.libreMap.viridisStops,fillOpacity:.4,outlineColour:"black",legendStops:5,members:{gridBounds:"@expand:fluid.derefSignal({obsQuantiser}.grid, bounds)",updateObsGrid:"@expand:fluid.effect(hortis.libreMap.updateObsGrid, {that}, {obsQuantiser}, {obsQuantiser}.grid, {that}.mapLoaded)",fitBounds:"@expand:fluid.effect(hortis.libreMap.fitBounds, {that}, {that}.gridBounds, {that}.mapLoaded)",memoStops:"@expand:fluid.colour.memoStops({that}.options.fillStops, 256)",control:"@expand:hortis.libreMap.withObsGrid.addLegendControl({map}, {obsQuantiser}.grid, {that}.gridVisible)",hoverCell:"@expand:signal(null)",gridVisible:"@expand:signal(true)"},invokers:{drawObsGridLegend:"hortis.libreMap.withObsGrid.drawLegend({map}, {obsQuantiser}.grid, {that}.gridVisible)"},listeners:{"onCreate.bindGridSelect":"hortis.libreMap.bindGridSelect({that})"}});fluid.registerNamespace("hortis.legend");hortis.legend.rowTemplate=`\n
\n \n \n %keyLabel\n
`;hortis.libreMap.withObsGrid.addLegendControl=function(map){const control=map.drawObsGridLegend();control.onAdd=()=>control.container;control.onRemove=()=>{console.log("Cleaning up legend attached to ",control.container);control.cleanup()};map.map.addControl(control,"bottom-right");return control};hortis.libreMap.withObsGrid.drawLegend=function(map,gridSignal,gridVisibleSignal){const quant=map.obsQuantiser;const container=document.createElement("div");container.classList.add("imerss-legend");const cstops=map.options.legendStops;const stops=fluid.iota(cstops);const legendStopProps=fluid.iota(cstops+1).map((stop=>stop/cstops));const renderLegend=function(grid){const propToLevel=prop=>Math.floor(prop*grid.maxObsCount);const regionMarkupRows=stops.map((function(stop){const midProp=(legendStopProps[stop]+legendStopProps[stop+1])/2;const colour=fluid.colour.lookupStop(map.memoStops,midProp);const label=propToLevel(legendStopProps[stop])+" - "+propToLevel(legendStopProps[stop+1]);return fluid.stringTemplate(hortis.legend.rowTemplate,{previewStyle:"background-color: "+colour,keyLabel:label})}));const longRes=quant.longResolution.value;const baseLat=quant.baseLatitude.value;const longLen=Math.floor(longRes*hortis.longitudeLength(baseLat));const markup=`
Observation count
`+regionMarkupRows.join("\n")+`
Cell size: ${longLen}m
`;container.innerHTML=markup};fluid.effect(renderLegend,gridSignal);fluid.effect((isVisible=>hortis.toggleClass(container,"imerss-hidden",!isVisible)),gridVisibleSignal);return{container:container}};hortis.capitalize=function(string){return string.charAt(0).toUpperCase()+string.slice(1)};hortis.renderTaxonTooltip=function(that,hoverId){const row=that.rowById.value[hoverId];const terms={imgUrl:row.iNaturalistTaxonImage||""};if(row.rank){terms.taxonRank=hortis.capitalize(row.rank)}else{terms.taxonRank="Species"}const names=[row.taxonName||row.iNaturalistTaxonName,row.commonName,row.hulqName].filter((name=>name));terms.taxonNames=names.join(" / ");return fluid.stringTemplate(hortis.taxonTooltipTemplate,terms)};hortis.libreMap.bindGridSelect=function(that){const map=that.map;map.on("mousemove",(e=>{const features=map.queryRenderedFeatures(e.point);const visibleFeatures=features.filter((feature=>feature.properties.cellId));that.hoverEvent=e.originalEvent;const cellId=visibleFeatures[0]?.properties.cellId||null;that.hoverCell.value=cellId;map.getCanvas().style.cursor=cellId?"default":""}));map.getCanvas().addEventListener("mouseleave",(()=>hortis.clearAllTooltips(that)))};hortis.libreMap.rectFromCorner=function(lat,long,latres,longres){return[[long,lat],[long+longres,lat],[long+longres,lat+latres],[long,lat+latres],[long,lat]]};hortis.libreMap.obsGridFeature=function(map,obsQuantiser,grid){const buckets=grid.buckets,latres=obsQuantiser.latResolution.value,longres=obsQuantiser.longResolution.value;return{type:"FeatureCollection",features:Object.entries(buckets).map((function([key,bucket]){const[lat,long]=hortis.obsQuantiser.indexToCoord(key,latres,longres);return{type:"Feature",geometry:{type:"Polygon",coordinates:[hortis.libreMap.rectFromCorner(lat,long,latres,longres)]},properties:{cellId:key,obsprop:bucket.obsCount/grid.maxObsCount}}}))}};hortis.libreMap.updateObsGrid=function(map,obsQuantiser,grid){const geojson=hortis.libreMap.obsGridFeature(map,obsQuantiser,grid);let source=map.map.getSource("obsgrid-source");if(source){source.setData(geojson)}else{map.map.addSource("obsgrid-source",{type:"geojson",data:geojson})}const layer=map.map.getLayer("obsgrid-layer");if(!layer){const layer={id:"obsgrid-layer",type:"fill",source:"obsgrid-source",paint:{"fill-color":{property:"obsprop",stops:map.options.fillStops},"fill-opacity":map.options.fillOpacity,"fill-outline-color":map.options.outlineColour}};map.map.addLayer(layer)}};hortis.libreMap.swapCoords=function(coords){return[coords[1],coords[0]]};hortis.libreMap.swapBounds=function(bounds){return bounds.map(hortis.libreMap.swapCoords)};hortis.libreMap.fitBounds=function(that,fitBounds){const swapped=hortis.libreMap.swapBounds(fitBounds);that.map.fitBounds(swapped,{duration:that.options.zoomDuration,essential:true})};hortis.WGS84a=6378137;hortis.WGS84b=6356752.3142;hortis.WGS84e2=(hortis.WGS84a*hortis.WGS84a-hortis.WGS84b*hortis.WGS84b)/(hortis.WGS84a*hortis.WGS84a);hortis.longitudeLength=function(latitude){const latrad=Math.PI*latitude/180;const sinrad=Math.sin(latrad);return Math.PI*hortis.WGS84a*Math.cos(latrad)/(180*Math.sqrt(1-hortis.WGS84e2*sinrad*sinrad))};hortis.latitudeLength=function(latitude){const latrad=Math.PI*latitude/180;const sinrad=Math.sin(latrad);return Math.PI*hortis.WGS84a*(1-hortis.WGS84e2)/(180*Math.pow(1-hortis.WGS84e2*sinrad*sinrad,1.5))};hortis.longToLat=function(lng,lat){const longLength=hortis.longitudeLength(lat);const latLength=hortis.latitudeLength(lat);return lng*longLength/latLength};fluid.registerNamespace("hortis.obsQuantiser");hortis.obsQuantiser.initGrid=function(){const grid={};grid.bounds=hortis.initBounds();grid.maxObsCount=0;grid.buckets={};return grid};hortis.gridBucket=()=>({obsCount:0,byTaxonId:{}});hortis.indexObs=function(bucket,row,index){fluid.pushArray(bucket.byTaxonId,row.iNatTaxonId,index)};fluid.defaults("hortis.obsQuantiser",{gradeNames:"fluid.modelComponent",members:{newBucket:hortis.gridBucket,indexObs:hortis.indexObs,baseLatitude:"@expand:signal(37.5)",longResolution:"@expand:signal(0.005)",latResolution:"@expand:fluid.computed(hortis.longToLat, {that}.longResolution, {that}.baseLatitude)",maxBounds:"@expand:fluid.computed(hortis.obsBounds, {vizLoader}.obsRows)",grid:{expander:{funcName:"fluid.computed",args:["hortis.obsQuantiser.indexObs","{that}","{vizLoader}.finalFilteredObs","{that}.latResolution","{that}.longResolution"]}}}});hortis.obsQuantiser.indexToCoord=function(index,latres,longres){const coords=index.split("|");return[coords[0]*latres,coords[1]*longres]};hortis.obsQuantiser.coordToIndex=function(lat,long,latres,longres){const latq=Math.floor(lat/latres);const longq=Math.floor(long/longres);return latq+"|"+longq};hortis.obsBounds=function(rows){const bounds=hortis.initBounds();rows.forEach((function(row){hortis.updateBounds(bounds,row.decimalLatitude,row.decimalLongitude)}));return bounds};hortis.obsQuantiser.indexObs=function(that,rows,latRes,longRes){const grid=hortis.obsQuantiser.initGrid();const now=Date.now();rows.forEach((function(row,index){const coordIndex=hortis.obsQuantiser.coordToIndex(row.decimalLatitude,row.decimalLongitude,latRes,longRes);hortis.updateBounds(grid.bounds,row.decimalLatitude,row.decimalLongitude);let bucket=grid.buckets[coordIndex];if(!bucket){bucket=grid.buckets[coordIndex]=that.newBucket()}bucket.obsCount++;grid.maxObsCount=Math.max(grid.maxObsCount,bucket.obsCount);that.indexObs(bucket,row,index)}));if(rows.length===0){grid.bounds=[...that.maxBounds.value]}hortis.expandBounds(grid.bounds,.1,latRes*6,longRes*6);const delay=Date.now()-now;fluid.log("Gridded "+rows.length+" rows in "+delay+" ms: "+1e3*(delay/rows.length)+" us/row");return grid};fluid.defaults("hortis.libreObsMap",{gradeNames:["hortis.libreMap","hortis.libreMap.withObsGrid"],components:{obsQuantiser:{type:"hortis.obsQuantiser",options:{members:{longResolution:"@expand:signal(0.075)"}}}}});"use strict";var hortis=fluid.registerNamespace("hortis");var{signal:signal,effect:effect,batch:batch}=preactSignalsCore;hortis.sppAnnotations=["agg.","aff.","s.lat.","cf","sp.nov.","var.","sp.","ssp.","spp.","complex"];hortis.annoteRegex=new RegExp("("+hortis.sppAnnotations.map((annot=>annot.replace(".","\\."))).join("|")+")","g");hortis.renderSpeciesName=function(name){return name.replace(hortis.annoteRegex,`$1`)};hortis.encodeHTML=function(str){return str.replace(/[&<>'"]/g,(function(tag){return{"&":"&","<":"<",">":">","'":"'",'"':"""}[tag]}))};hortis.rowToScientific=function(row){return row.taxonName||row.iNaturalistTaxonName};hortis.accessRowHulq=function(row){const togo={nativeName:row.hulquminumName,scientificName:hortis.rowToScientific(row),commonName:row.commonName};togo.featuredName=togo.nativeName||togo.commonName;return togo};hortis.rowFold=function(rowid,folded){const foldChar=folded==="folded"?"chevron-right":folded==="unfolded"?"chevron-down":"none";const active=foldChar==="none"?"":" active";return`\n \n \n \n \n \n `};hortis.rowCheckbox=function(id,state){const checked=state==="selected"?"checked":"";const indeterminate=`indeterminate="${state==="indeterminate"}"`;const rowid=` data-row-id="${id}"`;return`\n \n \n \n \n \n \n `};hortis.resetChecks=function(parent){[...parent.querySelectorAll(".pretty input")].forEach((input=>input.checked=false))};hortis.checklistItem=function(entry,options,state){const record=entry.row,id=record.id;const rowid=`data-row-id="${id}"`;const rank=record.rank&&!(options.simple&&record.taxonName)?record.rank:"species";const selectedClass=rank==="species"&&record.id===state.selectedId?" checklist-selected":"";const header=`
  • `;const accessed=options.accessRow(record);const render=rank==="species"?hortis.renderSpeciesName:fluid.identity;const names={};if(accessed.nativeName){names.nativeName=`

    ${accessed.nativeName}

    `}if(accessed.scientificName){names.scientificName=`

    ${render(hortis.encodeHTML(accessed.scientificName))}

    `}if(accessed.commonName){names.commonName=`

    ${accessed.commonName}

    `}const name=Object.values(names).join(" - ");const rowState=state.idToState[id];const subList=hortis.checklistList(rowState.folded==="folded"?[]:entry.children,options,state);const footer="
  • ";const fold=options.unfoldable?hortis.rowFold(rowid,rowState.folded):"";const check=options.selectable?hortis.rowCheckbox(id,rowState.selected):"";return header+fold+check+name+subList+footer};hortis.checklistList=function(entries,options,state){return entries.length?"
      "+entries.map((function(entry){return hortis.checklistItem(entry,options,state)})).join("")+"
    ":""};hortis.checklistRowForId=function(container,id){return container.find(`[data-row-id=${id}]`).closest("li")};hortis.updateChecklistSelection=function(container,newSelectedId,oldSelectedId,rowById){if(newSelectedId===null){return}const oldSelected=hortis.checklistRowForId(container,oldSelectedId);oldSelected.removeClass("checklist-selected");const row=rowById[newSelectedId];if(row&&row.species){const newSelected=hortis.checklistRowForId(container,newSelectedId);newSelected.addClass("checklist-selected")}};hortis.alwaysRejectRanks=[];hortis.acceptChecklistRowAS=function(row,filterRanks,rowFocus){const acceptBasic=!filterRanks||filterRanks.includes(row.rank)||row.species;const alwaysReject=hortis.alwaysRejectRanks.includes(row.rank);const rejectSpecies=row.rank==="species"&&row.children.length>0;const acceptChecklist=row.taxonName;return rowFocus[row.id]&&(acceptBasic&&!rejectSpecies&&!alwaysReject||acceptChecklist)};hortis.acceptChecklistRowOBA=function(row,filterRanks,idToState,rowFocus){const acceptBasic=!filterRanks||filterRanks.includes(row.rank);const alwaysReject=hortis.alwaysRejectRanks.includes(row.rank);return rowFocus[row.id]&&acceptBasic&&!alwaysReject};hortis.scientificComparator=function(entrya,entryb){return hortis.rowToScientific(entrya.row)>hortis.rowToScientific(entryb.row)?1:-1};hortis.sortChecklistLevel=function(entries){return entries.sort(hortis.scientificComparator)};hortis.filterTaxonomy=function(rows,depth,acceptChecklistRow,filterTaxonomy,showRoot){const togo=[];fluid.each(rows,(function(row){if(acceptChecklistRow(row)||depth===0&&showRoot){togo.push({row:row,children:filterTaxonomy(row.children,depth+1)})}else{const dChildren=filterTaxonomy(row.children,depth+1);Array.prototype.push.apply(togo,dChildren)}}));return hortis.sortChecklistLevel(togo)};fluid.defaults("hortis.checklist",{gradeNames:["hortis.withPanelLabel","fluid.viewComponent"],filterRanks:false,showRoot:false,selectable:false,unfoldable:false,selectors:{hoverable:"p",checklist:".imerss-checklist"},invokers:{accessRow:{funcName:"hortis.accessRowHulq"},foldByDefault:{args:["{that}.options.disclosableRanks","{arguments}.0"],func:(disclosableRanks,row)=>disclosableRanks&&disclosableRanks.includes(row.rank)},acceptChecklistRow:{funcName:"hortis.acceptChecklistRowAS",args:["{arguments}.0","{that}.options.filterRanks","{that}.rowFocus.value"]},filterTaxonomy:{funcName:"hortis.filterTaxonomy",args:["{arguments}.0","{arguments}.1","{that}.acceptChecklistRow","{that}.filterTaxonomy","{that}.options.showRoot"]},generate:{funcName:"hortis.checklist.generate",args:["{that}","{that}.dom.checklist","{that}.idToState.value","{that}.rootEntry.value","{that}.selectedId.value"]},check:"hortis.checklist.check({that}, {arguments}.0, {arguments}.1)",toggleFold:"hortis.checklist.toggleFold({that}, {arguments}.0)",reset:"hortis.checklist.reset({that})"},members:{idToEntry:{},rootEntry:"@expand:fluid.computed(hortis.checklist.computeRootEntry, {that}, {that}.rowById, {that}.rootId, {that}.filterTaxonomy)",idToStateUIOld:null,idToStateUI:"@expand:signal(null)",scheduleRender:"@expand:signal()",subscribeScheduleRender:"@expand:fluid.effect({that}.generate, {that}.scheduleRender)",idToStateOld:null,idToState:"@expand:fluid.computed(hortis.checklist.idToState, {that}, {that}.idToStateUI, {that}.rootEntry, {that}.rowFocus)",rowSelection:"@expand:fluid.computed(hortis.checklist.checksToSelection, {that}.idToState)",subscribeChecks:"@expand:fluid.effect(hortis.checklist.subscribeChecks, {that}, {that}.idToStateUI)",subscribeSelected:"@expand:hortis.checklist.subscribeSelected({that}, {that}.selectedId, {that}.rowById)",allLeaves:"@expand:fluid.computed(hortis.checklist.computeLeaves, {that}.idToEntry, {that}.rowSelection)",renderEffect:"@expand:fluid.effect(fluid.identity, {that}.idToState)"},listeners:{"onCreate.bindTaxonHover":"hortis.bindTaxonHover({that}, {layoutHolder})","onCreate.bindCheckboxClick":"hortis.checklist.bindCheckboxClick({that}, {that}.dom.checklist)"}});fluid.defaults("hortis.checklist.withOBA",{invokers:{acceptChecklistRow:{funcName:"hortis.acceptChecklistRowOBA",args:["{arguments}.0","{that}.options.filterRanks","{that}.oldIdToState","{that}.rowFocus.value"]}}});fluid.defaults("hortis.checklist.withCopy",{selectors:{copyButton:".imerss-copy-checklist"},components:{copyButton:{type:"fluid.viewComponent",container:"{that}.dom.copyButton",options:{gradeNames:"hortis.withTooltip",tooltipKey:"tooltipKey",members:{hovered:"@expand:signal(null)",inCopy:"@expand:signal(null)",tooltipKey:"@expand:fluid.computed(hortis.checklist.withCopy.deriveTooltipKey, {that}.hovered, {that}.inCopy)",inCopyEffect:"@expand:fluid.effect(hortis.checklist.withCopy.inCopyEffect, {that}.container.0, {that}.inCopy)"},invokers:{renderTooltip:"hortis.checklist.withCopy.renderTooltip({copyButton}, {hortis.checklist})",copyToClipboard:"hortis.checklist.withCopy.copyToClipboard({copyButton},{hortis.checklist})"},listeners:{"onCreate.bindHover":"hortis.checklist.withCopy.bindHover"}}}}});hortis.checklist.withCopy.bindHover=function(that){that.container.on("mouseenter",(function(e){that.hoverEvent=e;that.hovered.value=true}));that.container.on("mouseleave",(function(){that.hovered.value=null}));that.container.on("click",that.copyToClipboard)};hortis.checklist.withCopy.deriveTooltipKey=function(hovered,inCopy){return inCopy?"inCopy":hovered};hortis.checklist.withCopy.inCopyEffect=function(container,inCopy){const node=container.querySelector("use");if(inCopy){node.setAttribute("href","#copy-check");container.classList.add("imerss-copy-checklist-copied")}else{node.setAttribute("href","#copy-clipboard");container.classList.remove("imerss-copy-checklist-copied")}};hortis.checklist.withCopy.renderTooltip=function(copyButton,checklist){if(copyButton.inCopy.value){return"Copied!"}else{const leaves=checklist.allLeaves.value;const limit=5;const truncate=leaves.length>limit;const message=fluid.stringTemplate(checklist.options.copyButtonMessage,{rows:leaves.length})+":\n"+(truncate?[...leaves.slice(0,limit),"..."].join("\n"):leaves.join("\n"));return message.replaceAll("\n","
    ")}};hortis.checklist.withCopy.copyToClipboard=function(copyButton,checklist){copyButton.inCopy.value=true;window.setTimeout((()=>copyButton.inCopy.value=null),2e3);const leaves=checklist.allLeaves.value.join("\n");navigator.clipboard.writeText(leaves).then((function(){console.log("Copying to clipboard was successful!")}),(function(err){console.error("Could not copy text: ",err)}))};hortis.checklist.bindCheckboxClick=function(checklist,checklistContainer){checklistContainer.on("click",".pretty input",(function(){const id=this.dataset.rowId;fluid.log("Checkbox clicked with row "+id);checklist.check(id,this.checked)}));checklistContainer.on("click",".checklist-fold-control.active",(function(){const id=this.dataset.rowId;fluid.log("Fold clicked with row "+id);checklist.toggleFold(id)}))};hortis.checklist.stateToCheck=function(checklist,state,id){const node=checklist.idToNode?.[id];if(node){node.checked=state.selected==="selected";node.setAttribute("indeterminate",state.selected==="indeterminate");const holder=node.closest(".p-icon");const ui=holder.querySelector(".icon");$(ui).toggleClass("mdi-check",state.selected!=="indeterminate")}};hortis.checklist.subscribeChecks=function(checklist,idToStateUI){const oldIdToState=checklist.idToStateUIOld;fluid.each(idToStateUI,((newState,id)=>{const oldState=oldIdToState[id];if(newState!==oldState){hortis.checklist.stateToCheck(checklist,newState,id)}}));checklist.idToStateUIOld=idToStateUI};hortis.checklist.allChildrenState=function(idToState,entry,state){return entry.children.find((child=>idToState[child.row.id].selected!==state))===undefined};hortis.checklist.check=function(checklist,id,checked){const idToStateUp=fluid.copy(checklist.idToStateUI.value);const upState=checked?"selected":"unselected";const entry=checklist.idToEntry[id];const setChildState=function(entry,state){idToStateUp[entry.row.id].selected=state;entry.children.forEach((child=>setChildState(child,state)))};setChildState(entry,upState);let parent=entry.parent;while(parent.row){const allChildrenState=hortis.checklist.allChildrenState(idToStateUp,parent,upState);idToStateUp[parent.row.id].selected=allChildrenState?upState:"indeterminate";parent=parent.parent}batch((()=>{checklist.idToStateUI.value=idToStateUp;if(upState==="selected"&&idToStateUp[id].folded==="folded"){hortis.checklist.toggleFold(checklist,id)}}))};hortis.checklist.reset=function(checklist){const rootId=checklist.rootEntry.value.children[0].row.id;hortis.checklist.check(checklist,rootId,false)};hortis.checklist.toggleFold=function(checklist,id){const idToStateUp=fluid.copy(checklist.idToStateUI.value);const state=idToStateUp[id];const newFolded=state.folded==="folded"?"unfolded":"folded";state.folded=newFolded;const entry=checklist.idToEntry[id];const defaultNewFold=entry=>entry.children.length===0?"fixed":"folded";entry.children.forEach((child=>idToStateUp[child.row.id].folded=newFolded==="folded"?"hidden":defaultNewFold(child)));checklist.idToStateUI.value=idToStateUp;checklist.scheduleRender.value=true};hortis.checklist.subscribeSelected=function(that,selectedIdSignal,rowByIdSignal){let oldSelectedId=undefined;return fluid.effect((function(newSelectedId,rowById){hortis.updateChecklistSelection(that.container,newSelectedId,oldSelectedId,rowById);oldSelectedId=newSelectedId}),selectedIdSignal,rowByIdSignal)};hortis.checklist.computeRootEntry=function(that,rowById,rootId,filterTaxonomy){const rootRow=rowById[rootId];fluid.log("Generating checklist for id "+rootId);const filteredEntries=filterTaxonomy([rootRow],0);const idToEntry=that.idToEntry;fluid.clear(idToEntry);let entryIndex=0;const indexEntry=function(entry,parent){idToEntry[entry.row.id]=entry;entry.index=entryIndex++;entry.parent=parent;entry.children.forEach((child=>indexEntry(child,entry)))};filteredEntries.forEach(indexEntry);return{children:filteredEntries}};hortis.checklist.idToState=function(that,idToStateUI,rootEntry,rowFocus){const idToStateOld=that.idToStateOld;let togo;if(idToStateOld===idToStateUI){togo=hortis.checklist.computeInitialModel(rootEntry,rowFocus,idToStateOld,that.options.unfoldable,that.foldByDefault);fluid.invokeLater((()=>that.scheduleRender.value=true))}else{togo=idToStateUI;that.idToStateOld=togo}return togo};hortis.checklist.generate=function(that,element,idToState,rootEntry,selectedId){const selectable=that.options.selectable,unfoldable=that.options.unfoldable,simple=!!that.options.filterRanks;const rootEntries=rootEntry.children;const options={simple:simple,selectable:selectable,unfoldable:unfoldable,accessRow:that.accessRow};const state={selectedId:selectedId,idToState:idToState};const markup=hortis.checklistList(rootEntries,options,state);element[0].innerHTML=markup;if(selectable){const checks=element[0].querySelectorAll(".checklist-check");const idToNode={};checks.forEach((check=>idToNode[check.dataset.rowId]=check));that.idToNode=idToNode}that.scheduleRender.value=undefined;that.idToStateUIOld=idToState;that.idToStateUI.value=idToState};hortis.checklist.ROOT_ID=Number.NEGATIVE_INFINITY;hortis.checklist.defaultFold=function(entry,unfoldable,foldByDefault){return entry.children.length===0||!unfoldable?"fixed":entry.children.every((child=>foldByDefault(child.row)))?"folded":"unfolded"};hortis.checklist.computeInitialModel=function(rootEntry,rowFocus,oldIdToState,unfoldable,foldByDefault){const idToState={};const indexEntry=function(entry,parentFolded){const id=entry.row.id;if(!id){fluid.log("Warning, discarding row ",entry.row," without id set")}else if(rowFocus[id]){const defaultFolded=parentFolded==="folded"||parentFolded==="hidden"?"hidden":parentFolded==="root"?"fixed":hortis.checklist.defaultFold(entry,unfoldable,foldByDefault);idToState[id]=oldIdToState?.[id]||{selected:"unselected",folded:defaultFolded}}const folded=idToState[id].folded;entry.children.forEach((childEntry=>indexEntry(childEntry,folded)))};rootEntry.children.forEach((childEntry=>indexEntry(childEntry,"root")));return idToState};fluid.defaults("hortis.checklist.withHolder",{gradeNames:["hortis.layoutHolder","hortis.checklist"]});hortis.checklist.checksToSelection=function(idToState){const selection={};const selectAll={};let selected=0;fluid.each(idToState,((state,key)=>{if(state.folded!=="hidden"){if(state.selected==="selected"){++selected;selection[key]=true}selectAll[key]=true}}));return selected===0?selectAll:selection};hortis.checklist.computeLeaves=function(idToEntry,selection){const leaves=[];const appendLeaves=function(id){const entry=idToEntry[id];if(entry.children.length===0){leaves.push(entry.row.iNaturalistTaxonName)}else{entry.children.forEach((child=>appendLeaves(child.row.id)))}};Object.keys(selection).forEach((id=>appendLeaves(id)));return leaves}; +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */var read=ieee754$1.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};var write=ieee754$1.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128};"use strict";var pbf=Pbf;var ieee754=ieee754$1;function Pbf(buf){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(buf)?buf:new Uint8Array(buf||0);this.pos=0;this.type=0;this.length=this.buf.length}Pbf.Varint=0;Pbf.Fixed64=1;Pbf.Bytes=2;Pbf.Fixed32=5;var SHIFT_LEFT_32=(1<<16)*(1<<16),SHIFT_RIGHT_32=1/SHIFT_LEFT_32;var TEXT_DECODER_MIN_LENGTH=12;var utf8TextDecoder=typeof TextDecoder==="undefined"?null:new TextDecoder("utf8");Pbf.prototype={destroy:function(){this.buf=null},readFields:function(readField,result,end){end=end||this.length;while(this.pos>3,startPos=this.pos;this.type=val&7;readField(tag,result,this);if(this.pos===startPos)this.skip(val)}return result},readMessage:function(readField,result){return this.readFields(readField,result,this.readVarint()+this.pos)},readFixed32:function(){var val=readUInt32(this.buf,this.pos);this.pos+=4;return val},readSFixed32:function(){var val=readInt32(this.buf,this.pos);this.pos+=4;return val},readFixed64:function(){var val=readUInt32(this.buf,this.pos)+readUInt32(this.buf,this.pos+4)*SHIFT_LEFT_32;this.pos+=8;return val},readSFixed64:function(){var val=readUInt32(this.buf,this.pos)+readInt32(this.buf,this.pos+4)*SHIFT_LEFT_32;this.pos+=8;return val},readFloat:function(){var val=ieee754.read(this.buf,this.pos,true,23,4);this.pos+=4;return val},readDouble:function(){var val=ieee754.read(this.buf,this.pos,true,52,8);this.pos+=8;return val},readVarint:function(isSigned){var buf=this.buf,val,b;b=buf[this.pos++];val=b&127;if(b<128)return val;b=buf[this.pos++];val|=(b&127)<<7;if(b<128)return val;b=buf[this.pos++];val|=(b&127)<<14;if(b<128)return val;b=buf[this.pos++];val|=(b&127)<<21;if(b<128)return val;b=buf[this.pos];val|=(b&15)<<28;return readVarintRemainder(val,isSigned,this)},readVarint64:function(){return this.readVarint(true)},readSVarint:function(){var num=this.readVarint();return num%2===1?(num+1)/-2:num/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var end=this.readVarint()+this.pos;var pos=this.pos;this.pos=end;if(end-pos>=TEXT_DECODER_MIN_LENGTH&&utf8TextDecoder){return readUtf8TextDecoder(this.buf,pos,end)}return readUtf8(this.buf,pos,end)},readBytes:function(){var end=this.readVarint()+this.pos,buffer=this.buf.subarray(this.pos,end);this.pos=end;return buffer},readPackedVarint:function(arr,isSigned){if(this.type!==Pbf.Bytes)return arr.push(this.readVarint(isSigned));var end=readPackedEnd(this);arr=arr||[];while(this.pos127){}else if(type===Pbf.Bytes)this.pos=this.readVarint()+this.pos;else if(type===Pbf.Fixed32)this.pos+=4;else if(type===Pbf.Fixed64)this.pos+=8;else throw new Error("Unimplemented type: "+type)},writeTag:function(tag,type){this.writeVarint(tag<<3|type)},realloc:function(min){var length=this.length||16;while(length268435455||val<0){writeBigVarint(val,this);return}this.realloc(4);this.buf[this.pos++]=val&127|(val>127?128:0);if(val<=127)return;this.buf[this.pos++]=(val>>>=7)&127|(val>127?128:0);if(val<=127)return;this.buf[this.pos++]=(val>>>=7)&127|(val>127?128:0);if(val<=127)return;this.buf[this.pos++]=val>>>7&127},writeSVarint:function(val){this.writeVarint(val<0?-val*2-1:val*2)},writeBoolean:function(val){this.writeVarint(Boolean(val))},writeString:function(str){str=String(str);this.realloc(str.length*4);this.pos++;var startPos=this.pos;this.pos=writeUtf8(this.buf,str,this.pos);var len=this.pos-startPos;if(len>=128)makeRoomForExtraLength(startPos,len,this);this.pos=startPos-1;this.writeVarint(len);this.pos+=len},writeFloat:function(val){this.realloc(4);ieee754.write(this.buf,val,this.pos,true,23,4);this.pos+=4},writeDouble:function(val){this.realloc(8);ieee754.write(this.buf,val,this.pos,true,52,8);this.pos+=8},writeBytes:function(buffer){var len=buffer.length;this.writeVarint(len);this.realloc(len);for(var i=0;i=128)makeRoomForExtraLength(startPos,len,this);this.pos=startPos-1;this.writeVarint(len);this.pos+=len},writeMessage:function(tag,fn,obj){this.writeTag(tag,Pbf.Bytes);this.writeRawMessage(fn,obj)},writePackedVarint:function(tag,arr){if(arr.length)this.writeMessage(tag,writePackedVarint,arr)},writePackedSVarint:function(tag,arr){if(arr.length)this.writeMessage(tag,writePackedSVarint,arr)},writePackedBoolean:function(tag,arr){if(arr.length)this.writeMessage(tag,writePackedBoolean,arr)},writePackedFloat:function(tag,arr){if(arr.length)this.writeMessage(tag,writePackedFloat,arr)},writePackedDouble:function(tag,arr){if(arr.length)this.writeMessage(tag,writePackedDouble,arr)},writePackedFixed32:function(tag,arr){if(arr.length)this.writeMessage(tag,writePackedFixed32,arr)},writePackedSFixed32:function(tag,arr){if(arr.length)this.writeMessage(tag,writePackedSFixed32,arr)},writePackedFixed64:function(tag,arr){if(arr.length)this.writeMessage(tag,writePackedFixed64,arr)},writePackedSFixed64:function(tag,arr){if(arr.length)this.writeMessage(tag,writePackedSFixed64,arr)},writeBytesField:function(tag,buffer){this.writeTag(tag,Pbf.Bytes);this.writeBytes(buffer)},writeFixed32Field:function(tag,val){this.writeTag(tag,Pbf.Fixed32);this.writeFixed32(val)},writeSFixed32Field:function(tag,val){this.writeTag(tag,Pbf.Fixed32);this.writeSFixed32(val)},writeFixed64Field:function(tag,val){this.writeTag(tag,Pbf.Fixed64);this.writeFixed64(val)},writeSFixed64Field:function(tag,val){this.writeTag(tag,Pbf.Fixed64);this.writeSFixed64(val)},writeVarintField:function(tag,val){this.writeTag(tag,Pbf.Varint);this.writeVarint(val)},writeSVarintField:function(tag,val){this.writeTag(tag,Pbf.Varint);this.writeSVarint(val)},writeStringField:function(tag,str){this.writeTag(tag,Pbf.Bytes);this.writeString(str)},writeFloatField:function(tag,val){this.writeTag(tag,Pbf.Fixed32);this.writeFloat(val)},writeDoubleField:function(tag,val){this.writeTag(tag,Pbf.Fixed64);this.writeDouble(val)},writeBooleanField:function(tag,val){this.writeVarintField(tag,Boolean(val))}};function readVarintRemainder(l,s,p){var buf=p.buf,h,b;b=buf[p.pos++];h=(b&112)>>4;if(b<128)return toNum(l,h,s);b=buf[p.pos++];h|=(b&127)<<3;if(b<128)return toNum(l,h,s);b=buf[p.pos++];h|=(b&127)<<10;if(b<128)return toNum(l,h,s);b=buf[p.pos++];h|=(b&127)<<17;if(b<128)return toNum(l,h,s);b=buf[p.pos++];h|=(b&127)<<24;if(b<128)return toNum(l,h,s);b=buf[p.pos++];h|=(b&1)<<31;if(b<128)return toNum(l,h,s);throw new Error("Expected varint not more than 10 bytes")}function readPackedEnd(pbf){return pbf.type===Pbf.Bytes?pbf.readVarint()+pbf.pos:pbf.pos+1}function toNum(low,high,isSigned){if(isSigned){return high*4294967296+(low>>>0)}return(high>>>0)*4294967296+(low>>>0)}function writeBigVarint(val,pbf){var low,high;if(val>=0){low=val%4294967296|0;high=val/4294967296|0}else{low=~(-val%4294967296);high=~(-val/4294967296);if(low^4294967295){low=low+1|0}else{low=0;high=high+1|0}}if(val>=0x10000000000000000||val<-0x10000000000000000){throw new Error("Given varint doesn't fit into 10 bytes")}pbf.realloc(10);writeBigVarintLow(low,high,pbf);writeBigVarintHigh(high,pbf)}function writeBigVarintLow(low,high,pbf){pbf.buf[pbf.pos++]=low&127|128;low>>>=7;pbf.buf[pbf.pos++]=low&127|128;low>>>=7;pbf.buf[pbf.pos++]=low&127|128;low>>>=7;pbf.buf[pbf.pos++]=low&127|128;low>>>=7;pbf.buf[pbf.pos]=low&127}function writeBigVarintHigh(high,pbf){var lsb=(high&7)<<4;pbf.buf[pbf.pos++]|=lsb|((high>>>=3)?128:0);if(!high)return;pbf.buf[pbf.pos++]=high&127|((high>>>=7)?128:0);if(!high)return;pbf.buf[pbf.pos++]=high&127|((high>>>=7)?128:0);if(!high)return;pbf.buf[pbf.pos++]=high&127|((high>>>=7)?128:0);if(!high)return;pbf.buf[pbf.pos++]=high&127|((high>>>=7)?128:0);if(!high)return;pbf.buf[pbf.pos++]=high&127}function makeRoomForExtraLength(startPos,len,pbf){var extraLen=len<=16383?1:len<=2097151?2:len<=268435455?3:Math.floor(Math.log(len)/(Math.LN2*7));pbf.realloc(extraLen);for(var i=pbf.pos-1;i>=startPos;i--)pbf.buf[i+extraLen]=pbf.buf[i]}function writePackedVarint(arr,pbf){for(var i=0;i>>8;buf[pos+2]=val>>>16;buf[pos+3]=val>>>24}function readInt32(buf,pos){return(buf[pos]|buf[pos+1]<<8|buf[pos+2]<<16)+(buf[pos+3]<<24)}function readUtf8(buf,pos,end){var str="";var i=pos;while(i239?4:b0>223?3:b0>191?2:1;if(i+bytesPerSequence>end)break;var b1,b2,b3;if(bytesPerSequence===1){if(b0<128){c=b0}}else if(bytesPerSequence===2){b1=buf[i+1];if((b1&192)===128){c=(b0&31)<<6|b1&63;if(c<=127){c=null}}}else if(bytesPerSequence===3){b1=buf[i+1];b2=buf[i+2];if((b1&192)===128&&(b2&192)===128){c=(b0&15)<<12|(b1&63)<<6|b2&63;if(c<=2047||c>=55296&&c<=57343){c=null}}}else if(bytesPerSequence===4){b1=buf[i+1];b2=buf[i+2];b3=buf[i+3];if((b1&192)===128&&(b2&192)===128&&(b3&192)===128){c=(b0&15)<<18|(b1&63)<<12|(b2&63)<<6|b3&63;if(c<=65535||c>=1114112){c=null}}}if(c===null){c=65533;bytesPerSequence=1}else if(c>65535){c-=65536;str+=String.fromCharCode(c>>>10&1023|55296);c=56320|c&1023}str+=String.fromCharCode(c);i+=bytesPerSequence}return str}function readUtf8TextDecoder(buf,pos,end){return utf8TextDecoder.decode(buf.subarray(pos,end))}function writeUtf8(buf,str,pos){for(var i=0,c,lead;i55295&&c<57344){if(lead){if(c<56320){buf[pos++]=239;buf[pos++]=191;buf[pos++]=189;lead=c;continue}else{c=lead-55296<<10|c-56320|65536;lead=null}}else{if(c>56319||i+1===str.length){buf[pos++]=239;buf[pos++]=191;buf[pos++]=189}else{lead=c}continue}}else if(lead){buf[pos++]=239;buf[pos++]=191;buf[pos++]=189;lead=null}if(c<128){buf[pos++]=c}else{if(c<2048){buf[pos++]=c>>6|192}else{if(c<65536){buf[pos++]=c>>12|224}else{buf[pos++]=c>>18|240;buf[pos++]=c>>12&63|128}buf[pos++]=c>>6&63|128}buf[pos++]=c&63|128}}return pos}var Protobuf=getDefaultExportFromCjs$1(pbf);const border$1=3;function readFontstacks(tag,glyphs,pbf){if(tag===1){pbf.readMessage(readFontstack,glyphs)}}function readFontstack(tag,glyphs,pbf){if(tag===3){const{id:id,bitmap:bitmap,width:width,height:height,left:left,top:top,advance:advance}=pbf.readMessage(readGlyph,{});glyphs.push({id:id,bitmap:new AlphaImage({width:width+2*border$1,height:height+2*border$1},bitmap),metrics:{width:width,height:height,left:left,top:top,advance:advance}})}}function readGlyph(tag,glyph,pbf){if(tag===1)glyph.id=pbf.readVarint();else if(tag===2)glyph.bitmap=pbf.readBytes();else if(tag===3)glyph.width=pbf.readVarint();else if(tag===4)glyph.height=pbf.readVarint();else if(tag===5)glyph.left=pbf.readSVarint();else if(tag===6)glyph.top=pbf.readSVarint();else if(tag===7)glyph.advance=pbf.readVarint()}function parseGlyphPbf(data){return new Protobuf(data).readFields(readFontstacks,[])}const GLYPH_PBF_BORDER=border$1;function potpack(boxes){let area=0;let maxWidth=0;for(const box of boxes){area+=box.w*box.h;maxWidth=Math.max(maxWidth,box.w)}boxes.sort(((a,b)=>b.h-a.h));const startWidth=Math.max(Math.ceil(Math.sqrt(area/.95)),maxWidth);const spaces=[{x:0,y:0,w:startWidth,h:Infinity}];let width=0;let height=0;for(const box of boxes){for(let i=spaces.length-1;i>=0;i--){const space=spaces[i];if(box.w>space.w||box.h>space.h)continue;box.x=space.x;box.y=space.y;height=Math.max(height,box.y+box.h);width=Math.max(width,box.x+box.w);if(box.w===space.w&&box.h===space.h){const last=spaces.pop();if(i=0&&i>=beginningWhitespace&&whitespace[this.text.charCodeAt(i)];i--){trailingWhitespace--}this.text=this.text.substring(beginningWhitespace,trailingWhitespace);this.sectionIndex=this.sectionIndex.slice(beginningWhitespace,trailingWhitespace)}substring(start,end){const substring=new TaggedString;substring.text=this.text.substring(start,end);substring.sectionIndex=this.sectionIndex.slice(start,end);substring.sections=this.sections;return substring}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce(((max,index)=>Math.max(max,this.sections[index].scale)),0)}addTextSection(section,defaultFontStack){this.text+=section.text;this.sections.push(SectionOptions.forText(section.scale,section.fontStack||defaultFontStack));const index=this.sections.length-1;for(let i=0;i=PUAend)return null;return++this.imageSectionID}}function breakLines(input,lineBreakPoints){const lines=[];const text=input.text;let start=0;for(const lineBreak of lineBreakPoints){lines.push(input.substring(start,lineBreak));start=lineBreak}if(start=0;let currentX=0;for(let i=0;i0&&offset>lineOffset){lineOffset=offset}}if(!vertical){positionedGlyphs.push({glyph:codePoint,imageName:imageName,x:x,y:y+baselineOffset,vertical:vertical,scale:section.scale,fontStack:section.fontStack,sectionIndex:sectionIndex,metrics:metrics,rect:rect});x+=metrics.advance*section.scale+spacing}else{shaping.verticalizable=true;positionedGlyphs.push({glyph:codePoint,imageName:imageName,x:x,y:y+baselineOffset,vertical:vertical,scale:section.scale,fontStack:section.fontStack,sectionIndex:sectionIndex,metrics:metrics,rect:rect});x+=verticalAdvance*section.scale+spacing}}if(positionedGlyphs.length!==0){const lineLength=x-spacing;maxLineLength=Math.max(lineLength,maxLineLength);justifyLine(positionedGlyphs,0,positionedGlyphs.length-1,justify,lineOffset)}x=0;const currentLineHeight=lineHeight*lineMaxScale+lineOffset;positionedLine.lineOffset=Math.max(lineOffset,maxLineOffset);y+=currentLineHeight;maxLineHeight=Math.max(currentLineHeight,maxLineHeight);++lineIndex}const height=y-SHAPING_DEFAULT_OFFSET;const{horizontalAlign:horizontalAlign,verticalAlign:verticalAlign}=getAnchorAlignment(textAnchor);align(shaping.positionedLines,justify,horizontalAlign,verticalAlign,maxLineLength,maxLineHeight,lineHeight,height,lines.length);shaping.top+=-verticalAlign*height;shaping.bottom=shaping.top+height;shaping.left+=-horizontalAlign*maxLineLength;shaping.right=shaping.left+maxLineLength}function justifyLine(positionedGlyphs,start,end,justify,lineOffset){if(!justify&&!lineOffset)return;const lastPositionedGlyph=positionedGlyphs[end];const lastAdvance=lastPositionedGlyph.metrics.advance*lastPositionedGlyph.scale;const lineIndent=(positionedGlyphs[end].x+lastAdvance)*justify;for(let j=start;j<=end;j++){positionedGlyphs[j].x-=lineIndent;positionedGlyphs[j].y+=lineOffset}}function align(positionedLines,justify,horizontalAlign,verticalAlign,maxLineLength,maxLineHeight,lineHeight,blockHeight,lineCount){const shiftX=(justify-horizontalAlign)*maxLineLength;let shiftY=0;if(maxLineHeight!==lineHeight){shiftY=-blockHeight*verticalAlign-SHAPING_DEFAULT_OFFSET}else{shiftY=(-verticalAlign*lineCount+.5)*lineHeight}for(const line of positionedLines){for(const positionedGlyph of line.positionedGlyphs){positionedGlyph.x+=shiftX;positionedGlyph.y+=shiftY}}}function shapeIcon(image,iconOffset,iconAnchor){const{horizontalAlign:horizontalAlign,verticalAlign:verticalAlign}=getAnchorAlignment(iconAnchor);const dx=iconOffset[0];const dy=iconOffset[1];const x1=dx-image.displaySize[0]*horizontalAlign;const x2=x1+image.displaySize[0];const y1=dy-image.displaySize[1]*verticalAlign;const y2=y1+image.displaySize[1];return{image:image,top:y1,bottom:y2,left:x1,right:x2}}function fitIconToText(shapedIcon,shapedText,textFit,padding,iconOffset,fontScale){const image=shapedIcon.image;let collisionPadding;if(image.content){const content=image.content;const pixelRatio=image.pixelRatio||1;collisionPadding=[content[0]/pixelRatio,content[1]/pixelRatio,image.displaySize[0]-content[2]/pixelRatio,image.displaySize[1]-content[3]/pixelRatio]}const textLeft=shapedText.left*fontScale;const textRight=shapedText.right*fontScale;let top,right,bottom,left;if(textFit==="width"||textFit==="both"){left=iconOffset[0]+textLeft-padding[3];right=iconOffset[0]+textRight+padding[1]}else{left=iconOffset[0]+(textLeft+textRight-image.displaySize[0])/2;right=left+image.displaySize[0]}const textTop=shapedText.top*fontScale;const textBottom=shapedText.bottom*fontScale;if(textFit==="height"||textFit==="both"){top=iconOffset[1]+textTop-padding[0];bottom=iconOffset[1]+textBottom+padding[2]}else{top=iconOffset[1]+(textTop+textBottom-image.displaySize[1])/2;bottom=top+image.displaySize[1]}return{image:image,top:top,right:right,bottom:bottom,left:left,collisionPadding:collisionPadding}}const MAX_GLYPH_ICON_SIZE=255;const SIZE_PACK_FACTOR=128;const MAX_PACKED_SIZE=MAX_GLYPH_ICON_SIZE*SIZE_PACK_FACTOR;function getSizeData(tileZoom,value){const{expression:expression}=value;if(expression.kind==="constant"){const layoutSize=expression.evaluate(new EvaluationParameters(tileZoom+1));return{kind:"constant",layoutSize:layoutSize}}else if(expression.kind==="source"){return{kind:"source"}}else{const{zoomStops:zoomStops,interpolationType:interpolationType}=expression;let lower=0;while(lowerlayer.id));this.index=options.index;this.pixelRatio=options.pixelRatio;this.sourceLayerIndex=options.sourceLayerIndex;this.hasPattern=false;this.hasRTLText=false;this.sortKeyRanges=[];this.collisionCircleArray=[];this.placementInvProjMatrix=identity$2([]);this.placementViewportMatrix=identity$2([]);const layer=this.layers[0];const unevaluatedLayoutValues=layer._unevaluatedLayout._values;this.textSizeData=getSizeData(this.zoom,unevaluatedLayoutValues["text-size"]);this.iconSizeData=getSizeData(this.zoom,unevaluatedLayoutValues["icon-size"]);const layout=this.layers[0].layout;const sortKey=layout.get("symbol-sort-key");const zOrder=layout.get("symbol-z-order");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");this.sortFeaturesByKey=zOrder!=="viewport-y"&&!sortKey.isConstant();const zOrderByViewportY=zOrder==="viewport-y"||zOrder==="auto"&&!this.sortFeaturesByKey;this.sortFeaturesByY=zOrderByViewportY&&this.canOverlap;if(layout.get("symbol-placement")==="point"){this.writingModes=layout.get("text-writing-mode").map((wm=>exports.WritingMode[wm]))}this.stateDependentLayerIds=this.layers.filter((l=>l.isStateDependent())).map((l=>l.id));this.sourceID=options.sourceID}createArrays(){this.text=new SymbolBuffers(new ProgramConfigurationSet(this.layers,this.zoom,(property=>/^text/.test(property))));this.icon=new SymbolBuffers(new ProgramConfigurationSet(this.layers,this.zoom,(property=>/^icon/.test(property))));this.glyphOffsetArray=new GlyphOffsetArray;this.lineVertexArray=new SymbolLineVertexArray;this.symbolInstances=new SymbolInstanceArray;this.textAnchorOffsets=new TextAnchorOffsetArray}calculateGlyphDependencies(text,stack,textAlongLine,allowVerticalPlacement,doesAllowVerticalWritingMode){for(let i=0;i0)&&(textFont.value.kind!=="constant"||textFont.value.value.length>0);const hasIcon=iconImage.value.kind!=="constant"||!!iconImage.value.value||Object.keys(iconImage.parameters).length>0;const symbolSortKey=layout.get("symbol-sort-key");this.features=[];if(!hasText&&!hasIcon){return}const icons=options.iconDependencies;const stacks=options.glyphDependencies;const availableImages=options.availableImages;const globalProperties=new EvaluationParameters(this.zoom);for(const{feature:feature,id:id,index:index,sourceLayerIndex:sourceLayerIndex}of features){const needGeometry=layer._featureFilter.needGeometry;const evaluationFeature=toEvaluationFeature(feature,needGeometry);if(!layer._featureFilter.filter(globalProperties,evaluationFeature,canonical)){continue}if(!needGeometry)evaluationFeature.geometry=loadGeometry(feature);let text;if(hasText){const resolvedTokens=layer.getValueAndResolveTokens("text-field",evaluationFeature,canonical,availableImages);const formattedText=Formatted.factory(resolvedTokens);if(containsRTLText(formattedText)){this.hasRTLText=true}if(!this.hasRTLText||rtlWorkerPlugin.getRTLTextPluginStatus()==="unavailable"||this.hasRTLText&&rtlWorkerPlugin.isParsed()){text=transformText(formattedText,layer,evaluationFeature)}}let icon;if(hasIcon){const resolvedTokens=layer.getValueAndResolveTokens("icon-image",evaluationFeature,canonical,availableImages);if(resolvedTokens instanceof ResolvedImage){icon=resolvedTokens}else{icon=ResolvedImage.fromString(resolvedTokens)}}if(!text&&!icon){continue}const sortKey=this.sortFeaturesByKey?symbolSortKey.evaluate(evaluationFeature,{},canonical):undefined;const symbolFeature={id:id,text:text,icon:icon,index:index,sourceLayerIndex:sourceLayerIndex,geometry:evaluationFeature.geometry,properties:feature.properties,type:vectorTileFeatureTypes[feature.type],sortKey:sortKey};this.features.push(symbolFeature);if(icon){icons[icon.name]=true}if(text){const fontStack=textFont.evaluate(evaluationFeature,{},canonical).join(",");const textAlongLine=layout.get("text-rotation-alignment")!=="viewport"&&layout.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(exports.WritingMode.vertical)>=0;for(const section of text.sections){if(!section.image){const doesAllowVerticalWritingMode=allowsVerticalWritingMode(text.toString());const sectionFont=section.fontStack||fontStack;const sectionStack=stacks[sectionFont]=stacks[sectionFont]||{};this.calculateGlyphDependencies(section.text,sectionStack,textAlongLine,this.allowVerticalPlacement,doesAllowVerticalWritingMode)}else{icons[section.image.name]=true}}}}if(layout.get("symbol-placement")==="line"){this.features=mergeLines(this.features)}if(this.sortFeaturesByKey){this.features.sort(((a,b)=>a.sortKey-b.sortKey))}}update(states,vtLayer,imagePositions){if(!this.stateDependentLayers.length)return;this.text.programConfigurations.updatePaintArrays(states,vtLayer,this.layers,imagePositions);this.icon.programConfigurations.updatePaintArrays(states,vtLayer,this.layers,imagePositions)}isEmpty(){return this.symbolInstances.length===0&&!this.hasRTLText}uploadPending(){return!this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(context){if(!this.uploaded&&this.hasDebugData()){this.textCollisionBox.upload(context);this.iconCollisionBox.upload(context)}this.text.upload(context,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload);this.icon.upload(context,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload);this.uploaded=true}destroyDebugData(){this.textCollisionBox.destroy();this.iconCollisionBox.destroy()}destroy(){this.text.destroy();this.icon.destroy();if(this.hasDebugData()){this.destroyDebugData()}}addToLineVertexArray(anchor,line){const lineStartIndex=this.lineVertexArray.length;if(anchor.segment!==undefined){let sumForwardLength=anchor.dist(line[anchor.segment+1]);let sumBackwardLength=anchor.dist(line[anchor.segment]);const vertices={};for(let i=anchor.segment+1;i=0;i--){vertices[i]={x:line[i].x,y:line[i].y,tileUnitDistanceFromAnchor:sumBackwardLength};if(i>0){sumBackwardLength+=line[i-1].dist(line[i])}}for(let i=0;i0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}addIndicesForPlacedSymbol(iconOrText,placedSymbolIndex){const placedSymbol=iconOrText.placedSymbolArray.get(placedSymbolIndex);const endIndex=placedSymbol.vertexStartIndex+placedSymbol.numGlyphs*4;for(let vertexIndex=placedSymbol.vertexStartIndex;vertexIndexrotatedYs[aIndex]-rotatedYs[bIndex]||featureIndexes[bIndex]-featureIndexes[aIndex]));return result}addToSortKeyRanges(symbolInstanceIndex,sortKey){const last=this.sortKeyRanges[this.sortKeyRanges.length-1];if(last&&last.sortKey===sortKey){last.symbolInstanceEnd=symbolInstanceIndex+1}else{this.sortKeyRanges.push({sortKey:sortKey,symbolInstanceStart:symbolInstanceIndex,symbolInstanceEnd:symbolInstanceIndex+1})}}sortFeatures(angle){if(!this.sortFeaturesByY)return;if(this.sortedAngle===angle)return;if(this.text.segments.get().length>1||this.icon.segments.get().length>1)return;this.symbolInstanceIndexes=this.getSortedSymbolIndexes(angle);this.sortedAngle=angle;this.text.indexArray.clear();this.icon.indexArray.clear();this.featureSortOrder=[];for(const i of this.symbolInstanceIndexes){const symbolInstance=this.symbolInstances.get(i);this.featureSortOrder.push(symbolInstance.featureIndex);[symbolInstance.rightJustifiedTextSymbolIndex,symbolInstance.centerJustifiedTextSymbolIndex,symbolInstance.leftJustifiedTextSymbolIndex].forEach(((index,i,array)=>{if(index>=0&&array.indexOf(index)===i){this.addIndicesForPlacedSymbol(this.text,index)}}));if(symbolInstance.verticalPlacedTextSymbolIndex>=0){this.addIndicesForPlacedSymbol(this.text,symbolInstance.verticalPlacedTextSymbolIndex)}if(symbolInstance.placedIconSymbolIndex>=0){this.addIndicesForPlacedSymbol(this.icon,symbolInstance.placedIconSymbolIndex)}if(symbolInstance.verticalPlacedIconSymbolIndex>=0){this.addIndicesForPlacedSymbol(this.icon,symbolInstance.verticalPlacedIconSymbolIndex)}}if(this.text.indexBuffer)this.text.indexBuffer.updateData(this.text.indexArray);if(this.icon.indexBuffer)this.icon.indexBuffer.updateData(this.icon.indexArray)}}register("SymbolBucket",SymbolBucket,{omit:["layers","collisionBoxArray","features","compareText"]});SymbolBucket.MAX_GLYPHS=65535;SymbolBucket.addDynamicAttributes=addDynamicAttributes;function resolveTokens(properties,text){return text.replace(/{([^{}]+)}/g,((match,key)=>properties&&key in properties?String(properties[key]):""))}let layout;const getLayout=()=>layout=layout||new Properties({"symbol-placement":new DataConstantProperty(v8Spec["layout_symbol"]["symbol-placement"]),"symbol-spacing":new DataConstantProperty(v8Spec["layout_symbol"]["symbol-spacing"]),"symbol-avoid-edges":new DataConstantProperty(v8Spec["layout_symbol"]["symbol-avoid-edges"]),"symbol-sort-key":new DataDrivenProperty(v8Spec["layout_symbol"]["symbol-sort-key"]),"symbol-z-order":new DataConstantProperty(v8Spec["layout_symbol"]["symbol-z-order"]),"icon-allow-overlap":new DataConstantProperty(v8Spec["layout_symbol"]["icon-allow-overlap"]),"icon-overlap":new DataConstantProperty(v8Spec["layout_symbol"]["icon-overlap"]),"icon-ignore-placement":new DataConstantProperty(v8Spec["layout_symbol"]["icon-ignore-placement"]),"icon-optional":new DataConstantProperty(v8Spec["layout_symbol"]["icon-optional"]),"icon-rotation-alignment":new DataConstantProperty(v8Spec["layout_symbol"]["icon-rotation-alignment"]),"icon-size":new DataDrivenProperty(v8Spec["layout_symbol"]["icon-size"]),"icon-text-fit":new DataConstantProperty(v8Spec["layout_symbol"]["icon-text-fit"]),"icon-text-fit-padding":new DataConstantProperty(v8Spec["layout_symbol"]["icon-text-fit-padding"]),"icon-image":new DataDrivenProperty(v8Spec["layout_symbol"]["icon-image"]),"icon-rotate":new DataDrivenProperty(v8Spec["layout_symbol"]["icon-rotate"]),"icon-padding":new DataDrivenProperty(v8Spec["layout_symbol"]["icon-padding"]),"icon-keep-upright":new DataConstantProperty(v8Spec["layout_symbol"]["icon-keep-upright"]),"icon-offset":new DataDrivenProperty(v8Spec["layout_symbol"]["icon-offset"]),"icon-anchor":new DataDrivenProperty(v8Spec["layout_symbol"]["icon-anchor"]),"icon-pitch-alignment":new DataConstantProperty(v8Spec["layout_symbol"]["icon-pitch-alignment"]),"text-pitch-alignment":new DataConstantProperty(v8Spec["layout_symbol"]["text-pitch-alignment"]),"text-rotation-alignment":new DataConstantProperty(v8Spec["layout_symbol"]["text-rotation-alignment"]),"text-field":new DataDrivenProperty(v8Spec["layout_symbol"]["text-field"]),"text-font":new DataDrivenProperty(v8Spec["layout_symbol"]["text-font"]),"text-size":new DataDrivenProperty(v8Spec["layout_symbol"]["text-size"]),"text-max-width":new DataDrivenProperty(v8Spec["layout_symbol"]["text-max-width"]),"text-line-height":new DataConstantProperty(v8Spec["layout_symbol"]["text-line-height"]),"text-letter-spacing":new DataDrivenProperty(v8Spec["layout_symbol"]["text-letter-spacing"]),"text-justify":new DataDrivenProperty(v8Spec["layout_symbol"]["text-justify"]),"text-radial-offset":new DataDrivenProperty(v8Spec["layout_symbol"]["text-radial-offset"]),"text-variable-anchor":new DataConstantProperty(v8Spec["layout_symbol"]["text-variable-anchor"]),"text-variable-anchor-offset":new DataDrivenProperty(v8Spec["layout_symbol"]["text-variable-anchor-offset"]),"text-anchor":new DataDrivenProperty(v8Spec["layout_symbol"]["text-anchor"]),"text-max-angle":new DataConstantProperty(v8Spec["layout_symbol"]["text-max-angle"]),"text-writing-mode":new DataConstantProperty(v8Spec["layout_symbol"]["text-writing-mode"]),"text-rotate":new DataDrivenProperty(v8Spec["layout_symbol"]["text-rotate"]),"text-padding":new DataConstantProperty(v8Spec["layout_symbol"]["text-padding"]),"text-keep-upright":new DataConstantProperty(v8Spec["layout_symbol"]["text-keep-upright"]),"text-transform":new DataDrivenProperty(v8Spec["layout_symbol"]["text-transform"]),"text-offset":new DataDrivenProperty(v8Spec["layout_symbol"]["text-offset"]),"text-allow-overlap":new DataConstantProperty(v8Spec["layout_symbol"]["text-allow-overlap"]),"text-overlap":new DataConstantProperty(v8Spec["layout_symbol"]["text-overlap"]),"text-ignore-placement":new DataConstantProperty(v8Spec["layout_symbol"]["text-ignore-placement"]),"text-optional":new DataConstantProperty(v8Spec["layout_symbol"]["text-optional"])});let paint$2;const getPaint$2=()=>paint$2=paint$2||new Properties({"icon-opacity":new DataDrivenProperty(v8Spec["paint_symbol"]["icon-opacity"]),"icon-color":new DataDrivenProperty(v8Spec["paint_symbol"]["icon-color"]),"icon-halo-color":new DataDrivenProperty(v8Spec["paint_symbol"]["icon-halo-color"]),"icon-halo-width":new DataDrivenProperty(v8Spec["paint_symbol"]["icon-halo-width"]),"icon-halo-blur":new DataDrivenProperty(v8Spec["paint_symbol"]["icon-halo-blur"]),"icon-translate":new DataConstantProperty(v8Spec["paint_symbol"]["icon-translate"]),"icon-translate-anchor":new DataConstantProperty(v8Spec["paint_symbol"]["icon-translate-anchor"]),"text-opacity":new DataDrivenProperty(v8Spec["paint_symbol"]["text-opacity"]),"text-color":new DataDrivenProperty(v8Spec["paint_symbol"]["text-color"],{runtimeType:ColorType,getOverride:o=>o.textColor,hasOverride:o=>!!o.textColor}),"text-halo-color":new DataDrivenProperty(v8Spec["paint_symbol"]["text-halo-color"]),"text-halo-width":new DataDrivenProperty(v8Spec["paint_symbol"]["text-halo-width"]),"text-halo-blur":new DataDrivenProperty(v8Spec["paint_symbol"]["text-halo-blur"]),"text-translate":new DataConstantProperty(v8Spec["paint_symbol"]["text-translate"]),"text-translate-anchor":new DataConstantProperty(v8Spec["paint_symbol"]["text-translate-anchor"])});var properties$2={get paint(){return getPaint$2()},get layout(){return getLayout()}};class FormatSectionOverride{constructor(defaultValue){if(defaultValue.property.overrides===undefined)throw new Error("overrides must be provided to instantiate FormatSectionOverride class");this.type=defaultValue.property.overrides?defaultValue.property.overrides.runtimeType:NullType;this.defaultValue=defaultValue}evaluate(ctx){if(ctx.formattedSection){const overrides=this.defaultValue.property.overrides;if(overrides&&overrides.hasOverride(ctx.formattedSection)){return overrides.getOverride(ctx.formattedSection)}}if(ctx.feature&&ctx.featureState){return this.defaultValue.evaluate(ctx.feature,ctx.featureState)}return this.defaultValue.property.specification.default}eachChild(fn){if(!this.defaultValue.isConstant()){const expr=this.defaultValue.value;fn(expr._styleExpression.expression)}}outputDefined(){return false}serialize(){return null}}register("FormatSectionOverride",FormatSectionOverride,{omit:["defaultValue"]});class SymbolStyleLayer extends StyleLayer{constructor(layer){super(layer,properties$2)}recalculate(parameters,availableImages){super.recalculate(parameters,availableImages);if(this.layout.get("icon-rotation-alignment")==="auto"){if(this.layout.get("symbol-placement")!=="point"){this.layout._values["icon-rotation-alignment"]="map"}else{this.layout._values["icon-rotation-alignment"]="viewport"}}if(this.layout.get("text-rotation-alignment")==="auto"){if(this.layout.get("symbol-placement")!=="point"){this.layout._values["text-rotation-alignment"]="map"}else{this.layout._values["text-rotation-alignment"]="viewport"}}if(this.layout.get("text-pitch-alignment")==="auto"){this.layout._values["text-pitch-alignment"]=this.layout.get("text-rotation-alignment")==="map"?"map":"viewport"}if(this.layout.get("icon-pitch-alignment")==="auto"){this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")}if(this.layout.get("symbol-placement")==="point"){const writingModes=this.layout.get("text-writing-mode");if(writingModes){const deduped=[];for(const m of writingModes){if(deduped.indexOf(m)<0)deduped.push(m)}this.layout._values["text-writing-mode"]=deduped}else{this.layout._values["text-writing-mode"]=["horizontal"]}}this._setPaintOverrides()}getValueAndResolveTokens(name,feature,canonical,availableImages){const value=this.layout.get(name).evaluate(feature,{},canonical,availableImages);const unevaluated=this._unevaluatedLayout._values[name];if(!unevaluated.isDataDriven()&&!isExpression(unevaluated.value)&&value){return resolveTokens(feature.properties,value)}return value}createBucket(parameters){return new SymbolBucket(parameters)}queryRadius(){return 0}queryIntersectsFeature(){throw new Error("Should take a different path in FeatureIndex")}_setPaintOverrides(){for(const overridable of properties$2.paint.overridableProperties){if(!SymbolStyleLayer.hasPaintOverride(this.layout,overridable)){continue}const overriden=this.paint.get(overridable);const override=new FormatSectionOverride(overriden);const styleExpression=new StyleExpression(override,overriden.property.specification);let expression=null;if(overriden.value.kind==="constant"||overriden.value.kind==="source"){expression=new ZoomConstantExpression("source",styleExpression)}else{expression=new ZoomDependentExpression("composite",styleExpression,overriden.value.zoomStops)}this.paint._values[overridable]=new PossiblyEvaluatedPropertyValue(overriden.property,expression,overriden.parameters)}}_handleOverridablePaintPropertyUpdate(name,oldValue,newValue){if(!this.layout||oldValue.isDataDriven()||newValue.isDataDriven()){return false}return SymbolStyleLayer.hasPaintOverride(this.layout,name)}static hasPaintOverride(layout,propertyName){const textField=layout.get("text-field");const property=properties$2.paint.properties[propertyName];let hasOverrides=false;const checkSections=sections=>{for(const section of sections){if(property.overrides&&property.overrides.hasOverride(section)){hasOverrides=true;return}}};if(textField.value.kind==="constant"&&textField.value.value instanceof Formatted){checkSections(textField.value.value.sections)}else if(textField.value.kind==="source"){const checkExpression=expression=>{if(hasOverrides)return;if(expression instanceof Literal&&typeOf(expression.value)===FormattedType){const formatted=expression.value;checkSections(formatted.sections)}else if(expression instanceof FormatExpression){checkSections(expression.sections)}else{expression.eachChild(checkExpression)}};const expr=textField.value;if(expr._styleExpression){checkExpression(expr._styleExpression.expression)}}return hasOverrides}}function getIconPadding(layout,feature,canonical,pixelRatio=1){const result=layout.get("icon-padding").evaluate(feature,{},canonical);const values=result&&result.values;return[values[0]*pixelRatio,values[1]*pixelRatio,values[2]*pixelRatio,values[3]*pixelRatio]}let paint$1;const getPaint$1=()=>paint$1=paint$1||new Properties({"background-color":new DataConstantProperty(v8Spec["paint_background"]["background-color"]),"background-pattern":new CrossFadedProperty(v8Spec["paint_background"]["background-pattern"]),"background-opacity":new DataConstantProperty(v8Spec["paint_background"]["background-opacity"])});var properties$1={get paint(){return getPaint$1()}};class BackgroundStyleLayer extends StyleLayer{constructor(layer){super(layer,properties$1)}}let paint;const getPaint=()=>paint=paint||new Properties({"raster-opacity":new DataConstantProperty(v8Spec["paint_raster"]["raster-opacity"]),"raster-hue-rotate":new DataConstantProperty(v8Spec["paint_raster"]["raster-hue-rotate"]),"raster-brightness-min":new DataConstantProperty(v8Spec["paint_raster"]["raster-brightness-min"]),"raster-brightness-max":new DataConstantProperty(v8Spec["paint_raster"]["raster-brightness-max"]),"raster-saturation":new DataConstantProperty(v8Spec["paint_raster"]["raster-saturation"]),"raster-contrast":new DataConstantProperty(v8Spec["paint_raster"]["raster-contrast"]),"raster-resampling":new DataConstantProperty(v8Spec["paint_raster"]["raster-resampling"]),"raster-fade-duration":new DataConstantProperty(v8Spec["paint_raster"]["raster-fade-duration"])});var properties={get paint(){return getPaint()}};class RasterStyleLayer extends StyleLayer{constructor(layer){super(layer,properties)}}function validateCustomStyleLayer(layerObject){const errors=[];const id=layerObject.id;if(id===undefined){errors.push({message:`layers.${id}: missing required property "id"`})}if(layerObject.render===undefined){errors.push({message:`layers.${id}: missing required method "render"`})}if(layerObject.renderingMode&&layerObject.renderingMode!=="2d"&&layerObject.renderingMode!=="3d"){errors.push({message:`layers.${id}: property "renderingMode" must be either "2d" or "3d"`})}return errors}class CustomStyleLayer extends StyleLayer{constructor(implementation){super(implementation,{});this.onAdd=map=>{if(this.implementation.onAdd){this.implementation.onAdd(map,map.painter.context.gl)}};this.onRemove=map=>{if(this.implementation.onRemove){this.implementation.onRemove(map,map.painter.context.gl)}};this.implementation=implementation}is3D(){return this.implementation.renderingMode==="3d"}hasOffscreenPass(){return this.implementation.prerender!==undefined}recalculate(){}updateTransitions(){}hasTransition(){return false}serialize(){throw new Error("Custom layers cannot be serialized")}}function createStyleLayer(layer){if(layer.type==="custom"){return new CustomStyleLayer(layer)}switch(layer.type){case"background":return new BackgroundStyleLayer(layer);case"circle":return new CircleStyleLayer(layer);case"fill":return new FillStyleLayer(layer);case"fill-extrusion":return new FillExtrusionStyleLayer(layer);case"heatmap":return new HeatmapStyleLayer(layer);case"hillshade":return new HillshadeStyleLayer(layer);case"line":return new LineStyleLayer(layer);case"raster":return new RasterStyleLayer(layer);case"symbol":return new SymbolStyleLayer(layer)}}class ThrottledInvoker{constructor(methodToThrottle){this._methodToThrottle=methodToThrottle;this._triggered=false;if(typeof MessageChannel!=="undefined"){this._channel=new MessageChannel;this._channel.port2.onmessage=()=>{this._triggered=false;this._methodToThrottle()}}}trigger(){if(this._triggered){return}this._triggered=true;if(this._channel){this._channel.port1.postMessage(true)}else{setTimeout((()=>{this._triggered=false;this._methodToThrottle()}),0)}}remove(){delete this._channel;this._methodToThrottle=()=>{}}}class Actor{constructor(target,mapId){this.target=target;this.mapId=mapId;this.resolveRejects={};this.tasks={};this.taskQueue=[];this.abortControllers={};this.messageHandlers={};this.invoker=new ThrottledInvoker((()=>this.process()));this.subscription=subscribe(this.target,"message",(message=>this.receive(message)),false);this.globalScope=isWorker(self)?target:window}registerMessageHandler(type,handler){this.messageHandlers[type]=handler}sendAsync(message,abortController){return new Promise(((resolve,reject)=>{const id=Math.round(Math.random()*1e18).toString(36).substring(0,10);this.resolveRejects[id]={resolve:resolve,reject:reject};if(abortController){abortController.signal.addEventListener("abort",(()=>{delete this.resolveRejects[id];const cancelMessage={id:id,type:"",origin:location.origin,targetMapId:message.targetMapId,sourceMapId:this.mapId};this.target.postMessage(cancelMessage)}),{once:true})}const buffers=[];const messageToPost=Object.assign(Object.assign({},message),{id:id,sourceMapId:this.mapId,origin:location.origin,data:serialize(message.data,buffers)});this.target.postMessage(messageToPost,{transfer:buffers})}))}receive(message){const data=message.data;const id=data.id;if(data.origin!=="file://"&&location.origin!=="file://"&&data.origin!==location.origin){return}if(data.targetMapId&&this.mapId!==data.targetMapId){return}if(data.type===""){delete this.tasks[id];const abortController=this.abortControllers[id];delete this.abortControllers[id];if(abortController){abortController.abort()}return}if(isWorker(self)||data.mustQueue){this.tasks[id]=data;this.taskQueue.push(id);this.invoker.trigger();return}this.processTask(id,data)}process(){if(this.taskQueue.length===0){return}const id=this.taskQueue.shift();const task=this.tasks[id];delete this.tasks[id];if(this.taskQueue.length>0){this.invoker.trigger()}if(!task){return}this.processTask(id,task)}processTask(id,task){return __awaiter(this,void 0,void 0,(function*(){if(task.type===""){const resolveReject=this.resolveRejects[id];delete this.resolveRejects[id];if(!resolveReject){return}if(task.error){resolveReject.reject(deserialize(task.error))}else{resolveReject.resolve(deserialize(task.data))}return}if(!this.messageHandlers[task.type]){this.completeTask(id,new Error(`Could not find a registered handler for ${task.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(", ")}`));return}const params=deserialize(task.data);const abortController=new AbortController;this.abortControllers[id]=abortController;try{const data=yield this.messageHandlers[task.type](task.sourceMapId,params,abortController);this.completeTask(id,null,data)}catch(err){this.completeTask(id,err)}}))}completeTask(id,err,data){const buffers=[];delete this.abortControllers[id];const responseMessage={id:id,type:"",sourceMapId:this.mapId,origin:location.origin,error:err?serialize(err):null,data:serialize(data,buffers)};this.target.postMessage(responseMessage,{transfer:buffers})}remove(){this.invoker.remove();this.subscription.unsubscribe()}}const earthRadius=6371008.8;class LngLat{constructor(lng,lat){if(isNaN(lng)||isNaN(lat)){throw new Error(`Invalid LngLat object: (${lng}, ${lat})`)}this.lng=+lng;this.lat=+lat;if(this.lat>90||this.lat<-90){throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}}wrap(){return new LngLat(wrap(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(lngLat){const rad=Math.PI/180;const lat1=this.lat*rad;const lat2=lngLat.lat*rad;const a=Math.sin(lat1)*Math.sin(lat2)+Math.cos(lat1)*Math.cos(lat2)*Math.cos((lngLat.lng-this.lng)*rad);const maxMeters=earthRadius*Math.acos(Math.min(a,1));return maxMeters}static convert(input){if(input instanceof LngLat){return input}if(Array.isArray(input)&&(input.length===2||input.length===3)){return new LngLat(Number(input[0]),Number(input[1]))}if(!Array.isArray(input)&&typeof input==="object"&&input!==null){return new LngLat(Number("lng"in input?input.lng:input.lon),Number(input.lat))}throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}const earthCircumfrence=2*Math.PI*earthRadius;function circumferenceAtLatitude(latitude){return earthCircumfrence*Math.cos(latitude*Math.PI/180)}function mercatorXfromLng(lng){return(180+lng)/360}function mercatorYfromLat(lat){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+lat*Math.PI/360)))/360}function mercatorZfromAltitude(altitude,lat){return altitude/circumferenceAtLatitude(lat)}function lngFromMercatorX(x){return x*360-180}function latFromMercatorY(y){const y2=180-y*360;return 360/Math.PI*Math.atan(Math.exp(y2*Math.PI/180))-90}function altitudeFromMercatorZ(z,y){return z*circumferenceAtLatitude(latFromMercatorY(y))}function mercatorScale(lat){return 1/Math.cos(lat*Math.PI/180)}class MercatorCoordinate{constructor(x,y,z=0){this.x=+x;this.y=+y;this.z=+z}static fromLngLat(lngLatLike,altitude=0){const lngLat=LngLat.convert(lngLatLike);return new MercatorCoordinate(mercatorXfromLng(lngLat.lng),mercatorYfromLat(lngLat.lat),mercatorZfromAltitude(altitude,lngLat.lat))}toLngLat(){return new LngLat(lngFromMercatorX(this.x),latFromMercatorY(this.y))}toAltitude(){return altitudeFromMercatorZ(this.z,this.y)}meterInMercatorCoordinateUnits(){return 1/earthCircumfrence*mercatorScale(latFromMercatorY(this.y))}}function getURL(baseUrl,layer,x,y,z,options){options=options||{};var url=baseUrl+"?"+["bbox="+getTileBBox(x,y,z),"format="+(options.format||"image/png"),"service="+(options.service||"WMS"),"version="+(options.version||"1.1.1"),"request="+(options.request||"GetMap"),"srs="+(options.srs||"EPSG:3857"),"width="+(options.width||256),"height="+(options.height||256),"layers="+layer].join("&");return url}function getTileBBox(x,y,z){y=Math.pow(2,z)-y-1;var min=getMercCoords(x*256,y*256,z),max=getMercCoords((x+1)*256,(y+1)*256,z);return min[0]+","+min[1]+","+max[0]+","+max[1]}function getMercCoords(x,y,z){var resolution=2*Math.PI*6378137/256/Math.pow(2,z),merc_x=x*resolution-2*Math.PI*6378137/2,merc_y=y*resolution-2*Math.PI*6378137/2;return[merc_x,merc_y]}class CanonicalTileID{constructor(z,x,y){if(z<0||z>25||y<0||y>=Math.pow(2,z)||x<0||x>=Math.pow(2,z)){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 `)}this.z=z;this.x=x;this.y=y;this.key=calculateKey(0,z,z,x,y)}equals(id){return this.z===id.z&&this.x===id.x&&this.y===id.y}url(urls,pixelRatio,scheme){const bbox=getTileBBox(this.x,this.y,this.z);const quadkey=getQuadkey(this.z,this.x,this.y);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)}isChildOf(parent){const dz=this.z-parent.z;return dz>0&&parent.x===this.x>>dz&&parent.y===this.y>>dz}getTilePoint(coord){const tilesAtZoom=Math.pow(2,this.z);return new Point$2((coord.x*tilesAtZoom-this.x)*EXTENT,(coord.y*tilesAtZoom-this.y)*EXTENT)}toString(){return`${this.z}/${this.x}/${this.y}`}}class UnwrappedTileID{constructor(wrap,canonical){this.wrap=wrap;this.canonical=canonical;this.key=calculateKey(wrap,canonical.z,canonical.z,canonical.x,canonical.y)}}class OverscaledTileID{constructor(overscaledZ,wrap,z,x,y){if(overscaledZ= z; overscaledZ = ${overscaledZ}; z = ${z}`);this.overscaledZ=overscaledZ;this.wrap=wrap;this.canonical=new CanonicalTileID(z,+x,+y);this.key=calculateKey(wrap,overscaledZ,z,x,y)}clone(){return new OverscaledTileID(this.overscaledZ,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)}equals(id){return this.overscaledZ===id.overscaledZ&&this.wrap===id.wrap&&this.canonical.equals(id.canonical)}scaledTo(targetZ){if(targetZ>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${targetZ}; overscaledZ = ${this.overscaledZ}`);const zDifference=this.canonical.z-targetZ;if(targetZ>this.canonical.z){return new OverscaledTileID(targetZ,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)}else{return new OverscaledTileID(targetZ,this.wrap,targetZ,this.canonical.x>>zDifference,this.canonical.y>>zDifference)}}calculateScaledKey(targetZ,withWrap){if(targetZ>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${targetZ}; overscaledZ = ${this.overscaledZ}`);const zDifference=this.canonical.z-targetZ;if(targetZ>this.canonical.z){return calculateKey(this.wrap*+withWrap,targetZ,this.canonical.z,this.canonical.x,this.canonical.y)}else{return calculateKey(this.wrap*+withWrap,targetZ,targetZ,this.canonical.x>>zDifference,this.canonical.y>>zDifference)}}isChildOf(parent){if(parent.wrap!==this.wrap){return false}const zDifference=this.canonical.z-parent.canonical.z;return parent.overscaledZ===0||parent.overscaledZ>zDifference&&parent.canonical.y===this.canonical.y>>zDifference}children(sourceMaxZoom){if(this.overscaledZ>=sourceMaxZoom){return[new OverscaledTileID(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)]}const z=this.canonical.z+1;const x=this.canonical.x*2;const y=this.canonical.y*2;return[new OverscaledTileID(z,this.wrap,z,x,y),new OverscaledTileID(z,this.wrap,z,x+1,y),new OverscaledTileID(z,this.wrap,z,x,y+1),new OverscaledTileID(z,this.wrap,z,x+1,y+1)]}isLessThan(rhs){if(this.wraprhs.wrap)return false;if(this.overscaledZrhs.overscaledZ)return false;if(this.canonical.xrhs.canonical.x)return false;if(this.canonical.y0;i--){mask=1<this.max)this.max=ele;if(ele=this.dim+1||y<-1||y>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(y+1)*this.stride+(x+1)}unpack(r,g,b){return r*this.redFactor+g*this.greenFactor+b*this.blueFactor-this.baseShift}getPixels(){return new RGBAImage({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))}backfillBorder(borderTile,dx,dy){if(this.dim!==borderTile.dim)throw new Error("dem dimension mismatch");let xMin=dx*this.dim,xMax=dx*this.dim+this.dim,yMin=dy*this.dim,yMax=dy*this.dim+this.dim;switch(dx){case-1:xMin=xMax-1;break;case 1:xMax=xMin+1;break}switch(dy){case-1:yMin=yMax-1;break;case 1:yMax=yMin+1;break}const ox=-dx*this.dim;const oy=-dy*this.dim;for(let y=yMin;y=this._numberToString.length)throw new Error(`Out of bounds. Index requested n=${n} can't be >= this._numberToString.length ${this._numberToString.length}`);return this._numberToString[n]}}class GeoJSONFeature{constructor(vectorTileFeature,z,x,y,id){this.type="Feature";this._vectorTileFeature=vectorTileFeature;vectorTileFeature._z=z;vectorTileFeature._x=x;vectorTileFeature._y=y;this.properties=vectorTileFeature.properties;this.id=id}get geometry(){if(this._geometry===undefined){this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry}return this._geometry}set geometry(g){this._geometry=g}toJSON(){const json={geometry:this.geometry};for(const i in this){if(i==="_geometry"||i==="_vectorTileFeature")continue;json[i]=this[i]}return json}}class FeatureIndex{constructor(tileID,promoteId){this.tileID=tileID;this.x=tileID.canonical.x;this.y=tileID.canonical.y;this.z=tileID.canonical.z;this.grid=new TransferableGridIndex(EXTENT,16,0);this.grid3D=new TransferableGridIndex(EXTENT,16,0);this.featureIndexArray=new FeatureIndexArray;this.promoteId=promoteId}insert(feature,geometry,featureIndex,sourceLayerIndex,bucketIndex,is3D){const key=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(featureIndex,sourceLayerIndex,bucketIndex);const grid=is3D?this.grid3D:this.grid;for(let r=0;r=0&&bbox[3]>=0){grid.insert(key,bbox[0],bbox[1],bbox[2],bbox[3])}}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new vectorTile.VectorTile(new Protobuf(this.rawTileData)).layers;this.sourceLayerCoder=new DictionaryCoder(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])}return this.vtLayers}query(args,styleLayers,serializedLayers,sourceFeatureState){this.loadVTLayers();const params=args.params||{},pixelsToTileUnits=EXTENT/args.tileSize/args.scale,filter=createFilter(params.filter);const queryGeometry=args.queryGeometry;const queryPadding=args.queryPadding*pixelsToTileUnits;const bounds=getBounds(queryGeometry);const matching=this.grid.query(bounds.minX-queryPadding,bounds.minY-queryPadding,bounds.maxX+queryPadding,bounds.maxY+queryPadding);const cameraBounds=getBounds(args.cameraQueryGeometry);const matching3D=this.grid3D.query(cameraBounds.minX-queryPadding,cameraBounds.minY-queryPadding,cameraBounds.maxX+queryPadding,cameraBounds.maxY+queryPadding,((bx1,by1,bx2,by2)=>polygonIntersectsBox(args.cameraQueryGeometry,bx1-queryPadding,by1-queryPadding,bx2+queryPadding,by2+queryPadding)));for(const key of matching3D){matching.push(key)}matching.sort(topDownFeatureComparator);const result={};let previousIndex;for(let k=0;k{if(!featureGeometry){featureGeometry=loadGeometry(feature)}return styleLayer.queryIntersectsFeature(queryGeometry,feature,featureState,featureGeometry,this.z,args.transform,pixelsToTileUnits,args.pixelPosMatrix)}))}return result}loadMatchingFeature(result,bucketIndex,sourceLayerIndex,featureIndex,filter,filterLayerIDs,availableImages,styleLayers,serializedLayers,sourceFeatureState,intersectionTest){const layerIDs=this.bucketLayerIDs[bucketIndex];if(filterLayerIDs&&!arraysIntersect(filterLayerIDs,layerIDs))return;const sourceLayerName=this.sourceLayerCoder.decode(sourceLayerIndex);const sourceLayer=this.vtLayers[sourceLayerName];const feature=sourceLayer.feature(featureIndex);if(filter.needGeometry){const evaluationFeature=toEvaluationFeature(feature,true);if(!filter.filter(new EvaluationParameters(this.tileID.overscaledZ),evaluationFeature,this.tileID.canonical)){return}}else if(!filter.filter(new EvaluationParameters(this.tileID.overscaledZ),feature)){return}const id=this.getId(feature,sourceLayerName);for(let l=0;l{const prop=styleLayerProperties instanceof PossiblyEvaluated?styleLayerProperties.get(key):null;return prop&&prop.evaluate?prop.evaluate(feature,featureState,availableImages):prop}))}function getBounds(geometry){let minX=Infinity;let minY=Infinity;let maxX=-Infinity;let maxY=-Infinity;for(const p of geometry){minX=Math.min(minX,p.x);minY=Math.min(minY,p.y);maxX=Math.max(maxX,p.x);maxY=Math.max(maxY,p.y)}return{minX:minX,minY:minY,maxX:maxX,maxY:maxY}}function topDownFeatureComparator(a,b){return b-a}function clipLine(lines,x1,y1,x2,y2){const clippedLines=[];for(let l=0;l=x2&&p1.x>=x2){continue}else if(p0.x>=x2){p0=new Point$2(x2,p0.y+(p1.y-p0.y)*((x2-p0.x)/(p1.x-p0.x)))._round()}else if(p1.x>=x2){p1=new Point$2(x2,p0.y+(p1.y-p0.y)*((x2-p0.x)/(p1.x-p0.x)))._round()}if(p0.y>=y2&&p1.y>=y2){continue}else if(p0.y>=y2){p0=new Point$2(p0.x+(p1.x-p0.x)*((y2-p0.y)/(p1.y-p0.y)),y2)._round()}else if(p1.y>=y2){p1=new Point$2(p0.x+(p1.x-p0.x)*((y2-p0.y)/(p1.y-p0.y)),y2)._round()}if(!clippedLine||!p0.equals(clippedLine[clippedLine.length-1])){clippedLine=[p0];clippedLines.push(clippedLine)}clippedLine.push(p1)}}return clippedLines}class Anchor extends Point$2{constructor(x,y,angle,segment){super(x,y);this.angle=angle;if(segment!==undefined){this.segment=segment}}clone(){return new Anchor(this.x,this.y,this.angle,this.segment)}}register("Anchor",Anchor);function checkMaxAngle(line,anchor,labelLength,windowSize,maxAngle){if(anchor.segment===undefined||labelLength===0)return true;let p=anchor;let index=anchor.segment+1;let anchorDistance=0;while(anchorDistance>-labelLength/2){index--;if(index<0)return false;anchorDistance-=line[index].dist(p);p=line[index]}anchorDistance+=line[index].dist(line[index+1]);index++;const recentCorners=[];let recentAngleDelta=0;while(anchorDistancewindowSize){recentAngleDelta-=recentCorners.shift().angleDelta}if(recentAngleDelta>maxAngle)return false;index++;anchorDistance+=current.dist(next)}return true}function getLineLength(line){let lineLength=0;for(let k=0;kcenterDistance){const t=(centerDistance-prevDistance)/segmentDistance,x=interpolate.number(a.x,b.x,t),y=interpolate.number(a.y,b.y,t);const anchor=new Anchor(x,y,b.angleTo(a),i);anchor._round();if(!angleWindowSize||checkMaxAngle(line,anchor,labelLength,angleWindowSize,maxAngle)){return anchor}else{return}}prevDistance+=segmentDistance}}function getAnchors(line,spacing,maxAngle,shapedText,shapedIcon,glyphSize,boxScale,overscaling,tileExtent){const angleWindowSize=getAngleWindowSize(shapedText,glyphSize,boxScale);const shapedLabelLength=getShapedLabelLength(shapedText,shapedIcon);const labelLength=shapedLabelLength*boxScale;const isLineContinued=line[0].x===0||line[0].x===tileExtent||line[0].y===0||line[0].y===tileExtent;if(spacing-labelLength=0&&x=0&&y=0&&markedDistance+halfLabelLength<=lineLength){const anchor=new Anchor(x,y,angle,i);anchor._round();if(!angleWindowSize||checkMaxAngle(line,anchor,labelLength,angleWindowSize,maxAngle)){anchors.push(anchor)}}}distance+=segmentDist}if(!placeAtMiddle&&!anchors.length&&!isLineContinued){anchors=resample(line,distance/2,spacing,angleWindowSize,maxAngle,labelLength,isLineContinued,true,tileExtent)}return anchors}const border=IMAGE_PADDING;function getIconQuads(shapedIcon,iconRotate,isSDFIcon,hasIconTextFit){const quads=[];const image=shapedIcon.image;const pixelRatio=image.pixelRatio;const imageWidth=image.paddedRect.w-2*border;const imageHeight=image.paddedRect.h-2*border;const iconWidth=shapedIcon.right-shapedIcon.left;const iconHeight=shapedIcon.bottom-shapedIcon.top;const stretchX=image.stretchX||[[0,imageWidth]];const stretchY=image.stretchY||[[0,imageHeight]];const reduceRanges=(sum,range)=>sum+range[1]-range[0];const stretchWidth=stretchX.reduce(reduceRanges,0);const stretchHeight=stretchY.reduce(reduceRanges,0);const fixedWidth=imageWidth-stretchWidth;const fixedHeight=imageHeight-stretchHeight;let stretchOffsetX=0;let stretchContentWidth=stretchWidth;let stretchOffsetY=0;let stretchContentHeight=stretchHeight;let fixedOffsetX=0;let fixedContentWidth=fixedWidth;let fixedOffsetY=0;let fixedContentHeight=fixedHeight;if(image.content&&hasIconTextFit){const content=image.content;stretchOffsetX=sumWithinRange(stretchX,0,content[0]);stretchOffsetY=sumWithinRange(stretchY,0,content[1]);stretchContentWidth=sumWithinRange(stretchX,content[0],content[2]);stretchContentHeight=sumWithinRange(stretchY,content[1],content[3]);fixedOffsetX=content[0]-stretchOffsetX;fixedOffsetY=content[1]-stretchOffsetY;fixedContentWidth=content[2]-content[0]-stretchContentWidth;fixedContentHeight=content[3]-content[1]-stretchContentHeight}const makeBox=(left,top,right,bottom)=>{const leftEm=getEmOffset(left.stretch-stretchOffsetX,stretchContentWidth,iconWidth,shapedIcon.left);const leftPx=getPxOffset(left.fixed-fixedOffsetX,fixedContentWidth,left.stretch,stretchWidth);const topEm=getEmOffset(top.stretch-stretchOffsetY,stretchContentHeight,iconHeight,shapedIcon.top);const topPx=getPxOffset(top.fixed-fixedOffsetY,fixedContentHeight,top.stretch,stretchHeight);const rightEm=getEmOffset(right.stretch-stretchOffsetX,stretchContentWidth,iconWidth,shapedIcon.left);const rightPx=getPxOffset(right.fixed-fixedOffsetX,fixedContentWidth,right.stretch,stretchWidth);const bottomEm=getEmOffset(bottom.stretch-stretchOffsetY,stretchContentHeight,iconHeight,shapedIcon.top);const bottomPx=getPxOffset(bottom.fixed-fixedOffsetY,fixedContentHeight,bottom.stretch,stretchHeight);const tl=new Point$2(leftEm,topEm);const tr=new Point$2(rightEm,topEm);const br=new Point$2(rightEm,bottomEm);const bl=new Point$2(leftEm,bottomEm);const pixelOffsetTL=new Point$2(leftPx/pixelRatio,topPx/pixelRatio);const pixelOffsetBR=new Point$2(rightPx/pixelRatio,bottomPx/pixelRatio);const angle=iconRotate*Math.PI/180;if(angle){const sin=Math.sin(angle),cos=Math.cos(angle),matrix=[cos,-sin,sin,cos];tl._matMult(matrix);tr._matMult(matrix);bl._matMult(matrix);br._matMult(matrix)}const x1=left.stretch+left.fixed;const x2=right.stretch+right.fixed;const y1=top.stretch+top.fixed;const y2=bottom.stretch+bottom.fixed;const subRect={x:image.paddedRect.x+border+x1,y:image.paddedRect.y+border+y1,w:x2-x1,h:y2-y1};const minFontScaleX=fixedContentWidth/pixelRatio/iconWidth;const minFontScaleY=fixedContentHeight/pixelRatio/iconHeight;return{tl:tl,tr:tr,bl:bl,br:br,tex:subRect,writingMode:undefined,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:pixelOffsetTL,pixelOffsetBR:pixelOffsetBR,minFontScaleX:minFontScaleX,minFontScaleY:minFontScaleY,isSDF:isSDFIcon}};if(!hasIconTextFit||!image.stretchX&&!image.stretchY){quads.push(makeBox({fixed:0,stretch:-1},{fixed:0,stretch:-1},{fixed:0,stretch:imageWidth+1},{fixed:0,stretch:imageHeight+1}))}else{const xCuts=stretchZonesToCuts(stretchX,fixedWidth,stretchWidth);const yCuts=stretchZonesToCuts(stretchY,fixedHeight,stretchHeight);for(let xi=0;xi0){height=Math.max(10,height);this.circleDiameter=height}}else{let y1=shaped.top*boxScale-padding[0];let y2=shaped.bottom*boxScale+padding[2];let x1=shaped.left*boxScale-padding[3];let x2=shaped.right*boxScale+padding[1];const collisionPadding=shaped.collisionPadding;if(collisionPadding){x1-=collisionPadding[0]*boxScale;y1-=collisionPadding[1]*boxScale;x2+=collisionPadding[2]*boxScale;y2+=collisionPadding[3]*boxScale}if(rotate){const tl=new Point$2(x1,y1);const tr=new Point$2(x2,y1);const bl=new Point$2(x1,y2);const br=new Point$2(x2,y2);const rotateRadians=rotate*Math.PI/180;tl._rotate(rotateRadians);tr._rotate(rotateRadians);bl._rotate(rotateRadians);br._rotate(rotateRadians);x1=Math.min(tl.x,tr.x,bl.x,br.x);x2=Math.max(tl.x,tr.x,bl.x,br.x);y1=Math.min(tl.y,tr.y,bl.y,br.y);y2=Math.max(tl.y,tr.y,bl.y,br.y)}collisionBoxArray.emplaceBack(anchor.x,anchor.y,x1,y1,x2,y2,featureIndex,sourceLayerIndex,bucketIndex)}this.boxEndIndex=collisionBoxArray.length}}class TinyQueue{constructor(data=[],compare=defaultCompare){this.data=data;this.length=this.data.length;this.compare=compare;if(this.length>0){for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}}push(item){this.data.push(item);this.length++;this._up(this.length-1)}pop(){if(this.length===0)return undefined;const top=this.data[0];const bottom=this.data.pop();this.length--;if(this.length>0){this.data[0]=bottom;this._down(0)}return top}peek(){return this.data[0]}_up(pos){const{data:data,compare:compare}=this;const item=data[pos];while(pos>0){const parent=pos-1>>1;const current=data[parent];if(compare(item,current)>=0)break;data[pos]=current;pos=parent}data[pos]=item}_down(pos){const{data:data,compare:compare}=this;const halfLength=this.length>>1;const item=data[pos];while(pos=0)break;data[pos]=best;pos=left}data[pos]=item}}function defaultCompare(a,b){return ab?1:0}function findPoleOfInaccessibility(polygonRings,precision=1,debug=false){let minX=Infinity,minY=Infinity,maxX=-Infinity,maxY=-Infinity;const outerRing=polygonRings[0];for(let i=0;imaxX)maxX=p.x;if(!i||p.y>maxY)maxY=p.y}const width=maxX-minX;const height=maxY-minY;const cellSize=Math.min(width,height);let h=cellSize/2;const cellQueue=new TinyQueue([],compareMax);if(cellSize===0)return new Point$2(minX,minY);for(let x=minX;xbestCell.d||!bestCell.d){bestCell=cell;if(debug)console.log("found best %d after %d probes",Math.round(1e4*cell.d)/1e4,numProbes)}if(cell.max-bestCell.d<=precision)continue;h=cell.h/2;cellQueue.push(new Cell(cell.p.x-h,cell.p.y-h,h,polygonRings));cellQueue.push(new Cell(cell.p.x+h,cell.p.y-h,h,polygonRings));cellQueue.push(new Cell(cell.p.x-h,cell.p.y+h,h,polygonRings));cellQueue.push(new Cell(cell.p.x+h,cell.p.y+h,h,polygonRings));numProbes+=4}if(debug){console.log(`num probes: ${numProbes}`);console.log(`best distance: ${bestCell.d}`)}return bestCell.p}function compareMax(a,b){return b.max-a.max}function Cell(x,y,h,polygon){this.p=new Point$2(x,y);this.h=h;this.d=pointToPolygonDist(this.p,polygon);this.max=this.d+this.h*Math.SQRT2}function pointToPolygonDist(p,polygon){let inside=false;let minDistSq=Infinity;for(let k=0;kp.y!==b.y>p.y&&p.x<(b.x-a.x)*(p.y-a.y)/(b.y-a.y)+a.x)inside=!inside;minDistSq=Math.min(minDistSq,distToSegmentSquared(p,a,b))}}return(inside?1:-1)*Math.sqrt(minDistSq)}function getCentroidCell(polygon){let area=0;let x=0;let y=0;const points=polygon[0];for(let i=0,len=points.length,j=len-1;it*ONE_EM));if(anchor.startsWith("top")){offset[1]-=baselineOffset}else if(anchor.startsWith("bottom")){offset[1]+=baselineOffset}destValues[i+1]=offset}return new VariableAnchorOffsetCollection(destValues)}const variableAnchor=layout.get("text-variable-anchor");if(variableAnchor){let textOffset;const unevaluatedLayout=layer._unevaluatedLayout;if(unevaluatedLayout.getValue("text-radial-offset")!==undefined){textOffset=[layout.get("text-radial-offset").evaluate(feature,{},canonical)*ONE_EM,INVALID_TEXT_OFFSET]}else{textOffset=layout.get("text-offset").evaluate(feature,{},canonical).map((t=>t*ONE_EM))}const anchorOffsets=[];for(const anchor of variableAnchor){anchorOffsets.push(anchor,evaluateVariableOffset(anchor,textOffset))}return new VariableAnchorOffsetCollection(anchorOffsets)}return null}function performSymbolLayout(args){args.bucket.createArrays();const tileSize=512*args.bucket.overscaling;args.bucket.tilePixelRatio=EXTENT/tileSize;args.bucket.compareText={};args.bucket.iconsNeedLinear=false;const layer=args.bucket.layers[0];const layout=layer.layout;const unevaluatedLayoutValues=layer._unevaluatedLayout._values;const sizes={layoutIconSize:unevaluatedLayoutValues["icon-size"].possiblyEvaluate(new EvaluationParameters(args.bucket.zoom+1),args.canonical),layoutTextSize:unevaluatedLayoutValues["text-size"].possiblyEvaluate(new EvaluationParameters(args.bucket.zoom+1),args.canonical),textMaxSize:unevaluatedLayoutValues["text-size"].possiblyEvaluate(new EvaluationParameters(18))};if(args.bucket.textSizeData.kind==="composite"){const{minZoom:minZoom,maxZoom:maxZoom}=args.bucket.textSizeData;sizes.compositeTextSizes=[unevaluatedLayoutValues["text-size"].possiblyEvaluate(new EvaluationParameters(minZoom),args.canonical),unevaluatedLayoutValues["text-size"].possiblyEvaluate(new EvaluationParameters(maxZoom),args.canonical)]}if(args.bucket.iconSizeData.kind==="composite"){const{minZoom:minZoom,maxZoom:maxZoom}=args.bucket.iconSizeData;sizes.compositeIconSizes=[unevaluatedLayoutValues["icon-size"].possiblyEvaluate(new EvaluationParameters(minZoom),args.canonical),unevaluatedLayoutValues["icon-size"].possiblyEvaluate(new EvaluationParameters(maxZoom),args.canonical)]}const lineHeight=layout.get("text-line-height")*ONE_EM;const textAlongLine=layout.get("text-rotation-alignment")!=="viewport"&&layout.get("symbol-placement")!=="point";const keepUpright=layout.get("text-keep-upright");const textSize=layout.get("text-size");for(const feature of args.bucket.features){const fontstack=layout.get("text-font").evaluate(feature,{},args.canonical).join(",");const layoutTextSizeThisZoom=textSize.evaluate(feature,{},args.canonical);const layoutTextSize=sizes.layoutTextSize.evaluate(feature,{},args.canonical);const layoutIconSize=sizes.layoutIconSize.evaluate(feature,{},args.canonical);const shapedTextOrientations={horizontal:{},vertical:undefined};const text=feature.text;let textOffset=[0,0];if(text){const unformattedText=text.toString();const spacing=layout.get("text-letter-spacing").evaluate(feature,{},args.canonical)*ONE_EM;const spacingIfAllowed=allowsLetterSpacing(unformattedText)?spacing:0;const textAnchor=layout.get("text-anchor").evaluate(feature,{},args.canonical);const variableAnchorOffset=getTextVariableAnchorOffset(layer,feature,args.canonical);if(!variableAnchorOffset){const radialOffset=layout.get("text-radial-offset").evaluate(feature,{},args.canonical);if(radialOffset){textOffset=evaluateVariableOffset(textAnchor,[radialOffset*ONE_EM,INVALID_TEXT_OFFSET])}else{textOffset=layout.get("text-offset").evaluate(feature,{},args.canonical).map((t=>t*ONE_EM))}}let textJustify=textAlongLine?"center":layout.get("text-justify").evaluate(feature,{},args.canonical);const symbolPlacement=layout.get("symbol-placement");const maxWidth=symbolPlacement==="point"?layout.get("text-max-width").evaluate(feature,{},args.canonical)*ONE_EM:0;const addVerticalShapingForPointLabelIfNeeded=()=>{if(args.bucket.allowVerticalPlacement&&allowsVerticalWritingMode(unformattedText)){shapedTextOrientations.vertical=shapeText(text,args.glyphMap,args.glyphPositions,args.imagePositions,fontstack,maxWidth,lineHeight,textAnchor,"left",spacingIfAllowed,textOffset,exports.WritingMode.vertical,true,symbolPlacement,layoutTextSize,layoutTextSizeThisZoom)}};if(!textAlongLine&&variableAnchorOffset){const justifications=new Set;if(textJustify==="auto"){for(let i=0;i{if(anchor.x<0||anchor.x>=EXTENT||anchor.y<0||anchor.y>=EXTENT){return}addSymbol(bucket,anchor,line,shapedTextOrientations,shapedIcon,imageMap,verticallyShapedIcon,bucket.layers[0],bucket.collisionBoxArray,feature.index,feature.sourceLayerIndex,bucket.index,textBoxScale,[textPadding,textPadding,textPadding,textPadding],textAlongLine,textOffset,iconBoxScale,iconPadding,iconAlongLine,iconOffset,feature,sizes,isSDFIcon,canonical,layoutTextSize)};if(symbolPlacement==="line"){for(const line of clipLine(feature.geometry,0,0,EXTENT,EXTENT)){const anchors=getAnchors(line,symbolMinDistance,textMaxAngle,shapedTextOrientations.vertical||defaultHorizontalShaping,shapedIcon,glyphSize,textMaxBoxScale,bucket.overscaling,EXTENT);for(const anchor of anchors){const shapedText=defaultHorizontalShaping;if(!shapedText||!anchorIsTooClose(bucket,shapedText.text,textRepeatDistance,anchor)){addSymbolAtAnchor(line,anchor)}}}}else if(symbolPlacement==="line-center"){for(const line of feature.geometry){if(line.length>1){const anchor=getCenterAnchor(line,textMaxAngle,shapedTextOrientations.vertical||defaultHorizontalShaping,shapedIcon,glyphSize,textMaxBoxScale);if(anchor){addSymbolAtAnchor(line,anchor)}}}}else if(feature.type==="Polygon"){for(const polygon of classifyRings$1(feature.geometry,0)){const poi=findPoleOfInaccessibility(polygon,16);addSymbolAtAnchor(polygon[0],new Anchor(poi.x,poi.y,0))}}else if(feature.type==="LineString"){for(const line of feature.geometry){addSymbolAtAnchor(line,new Anchor(line[0].x,line[0].y,0))}}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))}}}}function addTextVariableAnchorOffsets(textAnchorOffsets,variableAnchorOffset){const startIndex=textAnchorOffsets.length;const values=variableAnchorOffset===null||variableAnchorOffset===void 0?void 0:variableAnchorOffset.values;if((values===null||values===void 0?void 0:values.length)>0){for(let i=0;iMAX_PACKED_SIZE){warnOnce(`${bucket.layerIds[0]}: Value for "text-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "text-size".`)}}else if(sizeData.kind==="composite"){textSizeData=[SIZE_PACK_FACTOR*sizes.compositeTextSizes[0].evaluate(feature,{},canonical),SIZE_PACK_FACTOR*sizes.compositeTextSizes[1].evaluate(feature,{},canonical)];if(textSizeData[0]>MAX_PACKED_SIZE||textSizeData[1]>MAX_PACKED_SIZE){warnOnce(`${bucket.layerIds[0]}: Value for "text-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "text-size".`)}}bucket.addSymbols(bucket.text,glyphQuads,textSizeData,textOffset,textAlongLine,feature,writingMode,anchor,lineArray.lineStartIndex,lineArray.lineLength,placedIconIndex,canonical);for(const placementType of placementTypes){placedTextSymbolIndices[placementType]=bucket.text.placedSymbolArray.length-1}return glyphQuads.length*4}function getDefaultHorizontalShaping(horizontalShaping){for(const justification in horizontalShaping){return horizontalShaping[justification]}return null}function 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){const lineArray=bucket.addToLineVertexArray(anchor,line);let textCollisionFeature,iconCollisionFeature,verticalTextCollisionFeature,verticalIconCollisionFeature;let numIconVertices=0;let numVerticalIconVertices=0;let numHorizontalGlyphVertices=0;let numVerticalGlyphVertices=0;let placedIconSymbolIndex=-1;let verticalPlacedIconSymbolIndex=-1;const placedTextSymbolIndices={};let key=murmur3$1("");if(bucket.allowVerticalPlacement&&shapedTextOrientations.vertical){const textRotation=layer.layout.get("text-rotate").evaluate(feature,{},canonical);const verticalTextRotation=textRotation+90;const verticalShaping=shapedTextOrientations.vertical;verticalTextCollisionFeature=new CollisionFeature(collisionBoxArray,anchor,featureIndex,sourceLayerIndex,bucketIndex,verticalShaping,textBoxScale,textPadding,textAlongLine,verticalTextRotation);if(verticallyShapedIcon){verticalIconCollisionFeature=new CollisionFeature(collisionBoxArray,anchor,featureIndex,sourceLayerIndex,bucketIndex,verticallyShapedIcon,iconBoxScale,iconPadding,textAlongLine,verticalTextRotation)}}if(shapedIcon){const iconRotate=layer.layout.get("icon-rotate").evaluate(feature,{});const hasIconTextFit=layer.layout.get("icon-text-fit")!=="none";const iconQuads=getIconQuads(shapedIcon,iconRotate,isSDFIcon,hasIconTextFit);const verticalIconQuads=verticallyShapedIcon?getIconQuads(verticallyShapedIcon,iconRotate,isSDFIcon,hasIconTextFit):undefined;iconCollisionFeature=new CollisionFeature(collisionBoxArray,anchor,featureIndex,sourceLayerIndex,bucketIndex,shapedIcon,iconBoxScale,iconPadding,false,iconRotate);numIconVertices=iconQuads.length*4;const sizeData=bucket.iconSizeData;let iconSizeData=null;if(sizeData.kind==="source"){iconSizeData=[SIZE_PACK_FACTOR*layer.layout.get("icon-size").evaluate(feature,{})];if(iconSizeData[0]>MAX_PACKED_SIZE){warnOnce(`${bucket.layerIds[0]}: Value for "icon-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "icon-size".`)}}else if(sizeData.kind==="composite"){iconSizeData=[SIZE_PACK_FACTOR*sizes.compositeIconSizes[0].evaluate(feature,{},canonical),SIZE_PACK_FACTOR*sizes.compositeIconSizes[1].evaluate(feature,{},canonical)];if(iconSizeData[0]>MAX_PACKED_SIZE||iconSizeData[1]>MAX_PACKED_SIZE){warnOnce(`${bucket.layerIds[0]}: Value for "icon-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "icon-size".`)}}bucket.addSymbols(bucket.icon,iconQuads,iconSizeData,iconOffset,iconAlongLine,feature,exports.WritingMode.none,anchor,lineArray.lineStartIndex,lineArray.lineLength,-1,canonical);placedIconSymbolIndex=bucket.icon.placedSymbolArray.length-1;if(verticalIconQuads){numVerticalIconVertices=verticalIconQuads.length*4;bucket.addSymbols(bucket.icon,verticalIconQuads,iconSizeData,iconOffset,iconAlongLine,feature,exports.WritingMode.vertical,anchor,lineArray.lineStartIndex,lineArray.lineLength,-1,canonical);verticalPlacedIconSymbolIndex=bucket.icon.placedSymbolArray.length-1}}const justifications=Object.keys(shapedTextOrientations.horizontal);for(const justification of justifications){const shaping=shapedTextOrientations.horizontal[justification];if(!textCollisionFeature){key=murmur3$1(shaping.text);const textRotate=layer.layout.get("text-rotate").evaluate(feature,{},canonical);textCollisionFeature=new CollisionFeature(collisionBoxArray,anchor,featureIndex,sourceLayerIndex,bucketIndex,shaping,textBoxScale,textPadding,textAlongLine,textRotate)}const singleLine=shaping.positionedLines.length===1;numHorizontalGlyphVertices+=addTextVertices(bucket,anchor,shaping,imageMap,layer,textAlongLine,feature,textOffset,lineArray,shapedTextOrientations.vertical?exports.WritingMode.horizontal:exports.WritingMode.horizontalOnly,singleLine?justifications:[justification],placedTextSymbolIndices,placedIconSymbolIndex,sizes,canonical);if(singleLine){break}}if(shapedTextOrientations.vertical){numVerticalGlyphVertices+=addTextVertices(bucket,anchor,shapedTextOrientations.vertical,imageMap,layer,textAlongLine,feature,textOffset,lineArray,exports.WritingMode.vertical,["vertical"],placedTextSymbolIndices,verticalPlacedIconSymbolIndex,sizes,canonical)}const textBoxStartIndex=textCollisionFeature?textCollisionFeature.boxStartIndex:bucket.collisionBoxArray.length;const textBoxEndIndex=textCollisionFeature?textCollisionFeature.boxEndIndex:bucket.collisionBoxArray.length;const verticalTextBoxStartIndex=verticalTextCollisionFeature?verticalTextCollisionFeature.boxStartIndex:bucket.collisionBoxArray.length;const verticalTextBoxEndIndex=verticalTextCollisionFeature?verticalTextCollisionFeature.boxEndIndex:bucket.collisionBoxArray.length;const iconBoxStartIndex=iconCollisionFeature?iconCollisionFeature.boxStartIndex:bucket.collisionBoxArray.length;const iconBoxEndIndex=iconCollisionFeature?iconCollisionFeature.boxEndIndex:bucket.collisionBoxArray.length;const verticalIconBoxStartIndex=verticalIconCollisionFeature?verticalIconCollisionFeature.boxStartIndex:bucket.collisionBoxArray.length;const verticalIconBoxEndIndex=verticalIconCollisionFeature?verticalIconCollisionFeature.boxEndIndex:bucket.collisionBoxArray.length;let collisionCircleDiameter=-1;const getCollisionCircleHeight=(feature,prevHeight)=>{if(feature&&feature.circleDiameter)return Math.max(feature.circleDiameter,prevHeight);return prevHeight};collisionCircleDiameter=getCollisionCircleHeight(textCollisionFeature,collisionCircleDiameter);collisionCircleDiameter=getCollisionCircleHeight(verticalTextCollisionFeature,collisionCircleDiameter);collisionCircleDiameter=getCollisionCircleHeight(iconCollisionFeature,collisionCircleDiameter);collisionCircleDiameter=getCollisionCircleHeight(verticalIconCollisionFeature,collisionCircleDiameter);const useRuntimeCollisionCircles=collisionCircleDiameter>-1?1:0;if(useRuntimeCollisionCircles)collisionCircleDiameter*=layoutTextSize/ONE_EM;if(bucket.glyphOffsetArray.length>=SymbolBucket.MAX_GLYPHS)warnOnce("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907");if(feature.sortKey!==undefined){bucket.addToSortKeyRanges(bucket.symbolInstances.length,feature.sortKey)}const variableAnchorOffset=getTextVariableAnchorOffset(layer,feature,canonical);const[textAnchorOffsetStartIndex,textAnchorOffsetEndIndex]=addTextVariableAnchorOffsets(bucket.textAnchorOffsets,variableAnchorOffset);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)}function anchorIsTooClose(bucket,text,repeatDistance,anchor){const compareText=bucket.compareText;if(!(text in compareText)){compareText[text]=[]}else{const otherAnchors=compareText[text];for(let k=otherAnchors.length-1;k>=0;k--){if(anchor.dist(otherAnchors[k])>4;if(version!==VERSION){throw new Error(`Got v${version} data when expected v${VERSION}.`)}const ArrayType=ARRAY_TYPES[versionAndType&15];if(!ArrayType){throw new Error("Unrecognized array type.")}const[nodeSize]=new Uint16Array(data,2,1);const[numItems]=new Uint32Array(data,4,1);return new KDBush(numItems,nodeSize,ArrayType,data)}constructor(numItems,nodeSize=64,ArrayType=Float64Array,data){if(isNaN(numItems)||numItems<0)throw new Error(`Unpexpected numItems value: ${numItems}.`);this.numItems=+numItems;this.nodeSize=Math.min(Math.max(+nodeSize,2),65535);this.ArrayType=ArrayType;this.IndexArrayType=numItems<65536?Uint16Array:Uint32Array;const arrayTypeIndex=ARRAY_TYPES.indexOf(this.ArrayType);const coordsByteSize=numItems*2*this.ArrayType.BYTES_PER_ELEMENT;const idsByteSize=numItems*this.IndexArrayType.BYTES_PER_ELEMENT;const padCoords=(8-idsByteSize%8)%8;if(arrayTypeIndex<0){throw new Error(`Unexpected typed array class: ${ArrayType}.`)}if(data&&data instanceof ArrayBuffer){this.data=data;this.ids=new this.IndexArrayType(this.data,HEADER_SIZE,numItems);this.coords=new this.ArrayType(this.data,HEADER_SIZE+idsByteSize+padCoords,numItems*2);this._pos=numItems*2;this._finished=true}else{this.data=new ArrayBuffer(HEADER_SIZE+coordsByteSize+idsByteSize+padCoords);this.ids=new this.IndexArrayType(this.data,HEADER_SIZE,numItems);this.coords=new this.ArrayType(this.data,HEADER_SIZE+idsByteSize+padCoords,numItems*2);this._pos=0;this._finished=false;new Uint8Array(this.data,0,2).set([219,(VERSION<<4)+arrayTypeIndex]);new Uint16Array(this.data,2,1)[0]=nodeSize;new Uint32Array(this.data,4,1)[0]=numItems}}add(x,y){const index=this._pos>>1;this.ids[index]=index;this.coords[this._pos++]=x;this.coords[this._pos++]=y;return index}finish(){const numAdded=this._pos>>1;if(numAdded!==this.numItems){throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`)}sort(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0);this._finished=true;return this}range(minX,minY,maxX,maxY){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:ids,coords:coords,nodeSize:nodeSize}=this;const stack=[0,ids.length-1,0];const result=[];while(stack.length){const axis=stack.pop()||0;const right=stack.pop()||0;const left=stack.pop()||0;if(right-left<=nodeSize){for(let i=left;i<=right;i++){const x=coords[2*i];const y=coords[2*i+1];if(x>=minX&&x<=maxX&&y>=minY&&y<=maxY)result.push(ids[i])}continue}const m=left+right>>1;const x=coords[2*m];const y=coords[2*m+1];if(x>=minX&&x<=maxX&&y>=minY&&y<=maxY)result.push(ids[m]);if(axis===0?minX<=x:minY<=y){stack.push(left);stack.push(m-1);stack.push(1-axis)}if(axis===0?maxX>=x:maxY>=y){stack.push(m+1);stack.push(right);stack.push(1-axis)}}return result}within(qx,qy,r){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:ids,coords:coords,nodeSize:nodeSize}=this;const stack=[0,ids.length-1,0];const result=[];const r2=r*r;while(stack.length){const axis=stack.pop()||0;const right=stack.pop()||0;const left=stack.pop()||0;if(right-left<=nodeSize){for(let i=left;i<=right;i++){if(sqDist(coords[2*i],coords[2*i+1],qx,qy)<=r2)result.push(ids[i])}continue}const m=left+right>>1;const x=coords[2*m];const y=coords[2*m+1];if(sqDist(x,y,qx,qy)<=r2)result.push(ids[m]);if(axis===0?qx-r<=x:qy-r<=y){stack.push(left);stack.push(m-1);stack.push(1-axis)}if(axis===0?qx+r>=x:qy+r>=y){stack.push(m+1);stack.push(right);stack.push(1-axis)}}return result}}function sort(ids,coords,nodeSize,left,right,axis){if(right-left<=nodeSize)return;const m=left+right>>1;select(ids,coords,m,left,right,axis);sort(ids,coords,nodeSize,left,m-1,1-axis);sort(ids,coords,nodeSize,m+1,right,1-axis)}function select(ids,coords,k,left,right,axis){while(right>left){if(right-left>600){const n=right-left+1;const m=k-left+1;const z=Math.log(n);const s=.5*Math.exp(2*z/3);const sd=.5*Math.sqrt(z*s*(n-s)/n)*(m-n/2<0?-1:1);const newLeft=Math.max(left,Math.floor(k-m*s/n+sd));const newRight=Math.min(right,Math.floor(k+(n-m)*s/n+sd));select(ids,coords,k,newLeft,newRight,axis)}const t=coords[2*k+axis];let i=left;let j=right;swapItem(ids,coords,left,k);if(coords[2*right+axis]>t)swapItem(ids,coords,left,right);while(it)j--}if(coords[2*left+axis]===t)swapItem(ids,coords,left,j);else{j++;swapItem(ids,coords,j,right)}if(j<=k)left=j+1;if(k<=j)right=j-1}}function swapItem(ids,coords,i,j){swap(ids,i,j);swap(coords,2*i,2*j);swap(coords,2*i+1,2*j+1)}function swap(arr,i,j){const tmp=arr[i];arr[i]=arr[j];arr[j]=tmp}function sqDist(ax,ay,bx,by){const dx=ax-bx;const dy=ay-by;return dx*dx+dy*dy}exports.PerformanceMarkers=void 0;(function(PerformanceMarkers){PerformanceMarkers["create"]="create";PerformanceMarkers["load"]="load";PerformanceMarkers["fullLoad"]="fullLoad"})(exports.PerformanceMarkers||(exports.PerformanceMarkers={}));let lastFrameTime=null;let frameTimes=[];const minFramerateTarget=60;const frameTimeTarget=1e3/minFramerateTarget;const loadTimeKey="loadTime";const fullLoadTimeKey="fullLoadTime";const PerformanceUtils={mark(marker){performance.mark(marker)},frame(timestamp){const currTimestamp=timestamp;if(lastFrameTime!=null){const frameTime=currTimestamp-lastFrameTime;frameTimes.push(frameTime)}lastFrameTime=currTimestamp},clearMetrics(){lastFrameTime=null;frameTimes=[];performance.clearMeasures(loadTimeKey);performance.clearMeasures(fullLoadTimeKey);for(const marker in exports.PerformanceMarkers){performance.clearMarks(exports.PerformanceMarkers[marker])}},getPerformanceMetrics(){performance.measure(loadTimeKey,exports.PerformanceMarkers.create,exports.PerformanceMarkers.load);performance.measure(fullLoadTimeKey,exports.PerformanceMarkers.create,exports.PerformanceMarkers.fullLoad);const loadTime=performance.getEntriesByName(loadTimeKey)[0].duration;const fullLoadTime=performance.getEntriesByName(fullLoadTimeKey)[0].duration;const totalFrames=frameTimes.length;const avgFrameTime=frameTimes.reduce(((prev,curr)=>prev+curr),0)/totalFrames/1e3;const fps=1/avgFrameTime;const droppedFrames=frameTimes.filter((frameTime=>frameTime>frameTimeTarget)).reduce(((acc,curr)=>acc+(curr-frameTimeTarget)/frameTimeTarget),0);const percentDroppedFrames=droppedFrames/(totalFrames+droppedFrames)*100;return{loadTime:loadTime,fullLoadTime:fullLoadTime,fps:fps,percentDroppedFrames:percentDroppedFrames,totalFrames:totalFrames}}};class RequestPerformance{constructor(request){this._marks={start:[request.url,"start"].join("#"),end:[request.url,"end"].join("#"),measure:request.url.toString()};performance.mark(this._marks.start)}finish(){performance.mark(this._marks.end);let resourceTimingData=performance.getEntriesByName(this._marks.measure);if(resourceTimingData.length===0){performance.measure(this._marks.measure,this._marks.start,this._marks.end);resourceTimingData=performance.getEntriesByName(this._marks.measure);performance.clearMarks(this._marks.start);performance.clearMarks(this._marks.end);performance.clearMeasures(this._marks.measure)}return resourceTimingData}}var performance$1=performance;exports.AJAXError=AJAXError;exports.Actor=Actor;exports.AlphaImage=AlphaImage;exports.CanonicalTileID=CanonicalTileID;exports.CollisionBoxArray=CollisionBoxArray;exports.CollisionCircleLayoutArray=CollisionCircleLayoutArray;exports.Color=Color;exports.DEMData=DEMData;exports.DataConstantProperty=DataConstantProperty;exports.DictionaryCoder=DictionaryCoder;exports.EXTENT=EXTENT;exports.ErrorEvent=ErrorEvent;exports.EvaluationParameters=EvaluationParameters;exports.Event=Event;exports.Evented=Evented;exports.FeatureIndex=FeatureIndex;exports.FillBucket=FillBucket;exports.FillExtrusionBucket=FillExtrusionBucket;exports.GLOBAL_DISPATCHER_ID=GLOBAL_DISPATCHER_ID;exports.GeoJSONFeature=GeoJSONFeature;exports.ImageAtlas=ImageAtlas;exports.ImagePosition=ImagePosition;exports.KDBush=KDBush;exports.LineBucket=LineBucket;exports.LineStripIndexArray=LineStripIndexArray;exports.LngLat=LngLat;exports.MercatorCoordinate=MercatorCoordinate;exports.ONE_EM=ONE_EM;exports.OverscaledTileID=OverscaledTileID;exports.PerformanceUtils=PerformanceUtils;exports.Point=Point$2;exports.Pos3dArray=Pos3dArray;exports.PosArray=PosArray;exports.Properties=Properties;exports.Protobuf=Protobuf;exports.QuadTriangleArray=QuadTriangleArray;exports.RGBAImage=RGBAImage;exports.RasterBoundsArray=RasterBoundsArray;exports.RequestPerformance=RequestPerformance;exports.SegmentVector=SegmentVector;exports.SymbolBucket=SymbolBucket;exports.Transitionable=Transitionable;exports.TriangleIndexArray=TriangleIndexArray;exports.Uniform1f=Uniform1f;exports.Uniform1i=Uniform1i;exports.Uniform2f=Uniform2f;exports.Uniform3f=Uniform3f;exports.Uniform4f=Uniform4f;exports.UniformColor=UniformColor;exports.UniformMatrix4f=UniformMatrix4f;exports.UnwrappedTileID=UnwrappedTileID;exports.ValidationError=ValidationError;exports.ZoomHistory=ZoomHistory;exports.__awaiter=__awaiter;exports.add=add$4;exports.addDynamicAttributes=addDynamicAttributes;exports.addProtocol=addProtocol;exports.arrayBufferToImage=arrayBufferToImage;exports.arrayBufferToImageBitmap=arrayBufferToImageBitmap;exports.bezier=bezier$1;exports.clamp=clamp$1;exports.clipLine=clipLine;exports.clone=clone$5;exports.clone$1=clone$9;exports.clone$2=clone$4;exports.collisionCircleLayout=collisionCircleLayout;exports.config=config;exports.copy=copy$5;exports.create=create$5;exports.create$1=create$6;exports.create$2=create$8;exports.createAbortError=createAbortError;exports.createExpression=createExpression;exports.createFilter=createFilter;exports.createLayout=createLayout;exports.createStyleLayer=createStyleLayer;exports.cross=cross$2;exports.deepEqual=deepEqual$1;exports.defaultEasing=defaultEasing;exports.degreesToRadians=degreesToRadians;exports.derefLayers=derefLayers;exports.diffStyles=diffStyles;exports.dot=dot$5;exports.dot$1=dot$4;exports.earthRadius=earthRadius;exports.emitValidationErrors=emitValidationErrors;exports.emptyStyle=emptyStyle;exports.equals=equals$6;exports.evaluateSizeForFeature=evaluateSizeForFeature;exports.evaluateSizeForZoom=evaluateSizeForZoom;exports.extend=extend;exports.filterObject=filterObject;exports.findLineIntersection=findLineIntersection;exports.fromRotation=fromRotation$2;exports.fromScaling=fromScaling;exports.getAnchorAlignment=getAnchorAlignment;exports.getAnchorJustification=getAnchorJustification;exports.getArrayBuffer=getArrayBuffer;exports.getDefaultExportFromCjs=getDefaultExportFromCjs$1;exports.getImageData=getImageData;exports.getJSON=getJSON;exports.getOverlapMode=getOverlapMode;exports.getProtocol=getProtocol;exports.getReferrer=getReferrer;exports.getVideo=getVideo;exports.groupByLayout=groupByLayout;exports.identity=identity$2;exports.interpolate=interpolate;exports.invert=invert$2;exports.isAbortError=isAbortError;exports.isImageBitmap=isImageBitmap;exports.isOffscreenCanvasDistorted=isOffscreenCanvasDistorted;exports.isSafari=isSafari;exports.isWorker=isWorker;exports.keysDifference=keysDifference;exports.makeRequest=makeRequest;exports.mapObject=mapObject;exports.mercatorXfromLng=mercatorXfromLng;exports.mercatorYfromLat=mercatorYfromLat;exports.mercatorZfromAltitude=mercatorZfromAltitude;exports.mul=mul$5;exports.mul$1=mul$3;exports.multiply=multiply$5;exports.nextPowerOfTwo=nextPowerOfTwo;exports.normalize=normalize$4;exports.offscreenCanvasSupported=offscreenCanvasSupported;exports.ortho=ortho;exports.parseCacheControl=parseCacheControl;exports.parseGlyphPbf=parseGlyphPbf;exports.pbf=pbf;exports.performSymbolLayout=performSymbolLayout;exports.perspective=perspective;exports.pick=pick;exports.pointGeometry=pointGeometry;exports.polygonIntersectsPolygon=polygonIntersectsPolygon;exports.potpack=potpack;exports.readImageUsingVideoFrame=readImageUsingVideoFrame;exports.register=register;exports.removeProtocol=removeProtocol;exports.renderColorRamp=renderColorRamp;exports.rotate=rotate$4;exports.rotateX=rotateX$3;exports.rotateZ=rotateZ$3;exports.rtlWorkerPlugin=rtlWorkerPlugin;exports.sameOrigin=sameOrigin;exports.scale=scale$5;exports.scale$1=scale$4;exports.sphericalToCartesian=sphericalToCartesian;exports.sqrLen=sqrLen;exports.sub=sub$2;exports.toEvaluationFeature=toEvaluationFeature;exports.transformMat3=transformMat3$1;exports.transformMat4=transformMat4$1;exports.transformMat4$1=transformMat4;exports.translate=translate$1;exports.unicodeBlockLookup=unicodeBlockLookup;exports.uniqueId=uniqueId;exports.v8Spec=v8Spec;exports.validateCustomStyleLayer=validateCustomStyleLayer;exports.validateLight=validateLight;exports.validateStyle=validateStyle;exports.vectorTile=vectorTile;exports.warnOnce=warnOnce;exports.wrap=wrap}));define("worker",["./shared"],(function(performance){"use strict";class StyleLayerIndex{constructor(layerConfigs){this.keyCache={};if(layerConfigs){this.replace(layerConfigs)}}replace(layerConfigs){this._layerConfigs={};this._layers={};this.update(layerConfigs,[])}update(layerConfigs,removedIds){for(const layerConfig of layerConfigs){this._layerConfigs[layerConfig.id]=layerConfig;const layer=this._layers[layerConfig.id]=performance.createStyleLayer(layerConfig);layer._featureFilter=performance.createFilter(layer.filter);if(this.keyCache[layerConfig.id])delete this.keyCache[layerConfig.id]}for(const id of removedIds){delete this.keyCache[id];delete this._layerConfigs[id];delete this._layers[id]}this.familiesBySource={};const groups=performance.groupByLayout(Object.values(this._layerConfigs),this.keyCache);for(const layerConfigs of groups){const layers=layerConfigs.map((layerConfig=>this._layers[layerConfig.id]));const layer=layers[0];if(layer.visibility==="none"){continue}const sourceId=layer.source||"";let sourceGroup=this.familiesBySource[sourceId];if(!sourceGroup){sourceGroup=this.familiesBySource[sourceId]={}}const sourceLayerId=layer.sourceLayer||"_geojsonTileLayer";let sourceLayerFamilies=sourceGroup[sourceLayerId];if(!sourceLayerFamilies){sourceLayerFamilies=sourceGroup[sourceLayerId]=[]}sourceLayerFamilies.push(layers)}}}const padding=1;class GlyphAtlas{constructor(stacks){const positions={};const bins=[];for(const stack in stacks){const glyphs=stacks[stack];const stackPositions=positions[stack]={};for(const id in glyphs){const src=glyphs[+id];if(!src||src.bitmap.width===0||src.bitmap.height===0)continue;const bin={x:0,y:0,w:src.bitmap.width+2*padding,h:src.bitmap.height+2*padding};bins.push(bin);stackPositions[id]={rect:bin,metrics:src.metrics}}}const{w:w,h:h}=performance.potpack(bins);const image=new performance.AlphaImage({width:w||1,height:h||1});for(const stack in stacks){const glyphs=stacks[stack];for(const id in glyphs){const src=glyphs[+id];if(!src||src.bitmap.width===0||src.bitmap.height===0)continue;const bin=positions[stack][id].rect;performance.AlphaImage.copy(src.bitmap,image,{x:0,y:0},{x:bin.x+padding,y:bin.y+padding},src.bitmap)}}this.image=image;this.positions=positions}}performance.register("GlyphAtlas",GlyphAtlas);class WorkerTile{constructor(params){this.tileID=new performance.OverscaledTileID(params.tileID.overscaledZ,params.tileID.wrap,params.tileID.canonical.z,params.tileID.canonical.x,params.tileID.canonical.y);this.uid=params.uid;this.zoom=params.zoom;this.pixelRatio=params.pixelRatio;this.tileSize=params.tileSize;this.source=params.source;this.overscaling=this.tileID.overscaleFactor();this.showCollisionBoxes=params.showCollisionBoxes;this.collectResourceTiming=!!params.collectResourceTiming;this.returnDependencies=!!params.returnDependencies;this.promoteId=params.promoteId;this.inFlightDependencies=[]}parse(data,layerIndex,availableImages,actor){return performance.__awaiter(this,void 0,void 0,(function*(){this.status="parsing";this.data=data;this.collisionBoxArray=new performance.CollisionBoxArray;const sourceLayerCoder=new performance.DictionaryCoder(Object.keys(data.layers).sort());const featureIndex=new performance.FeatureIndex(this.tileID,this.promoteId);featureIndex.bucketLayerIDs=[];const buckets={};const options={featureIndex:featureIndex,iconDependencies:{},patternDependencies:{},glyphDependencies:{},availableImages:availableImages};const layerFamilies=layerIndex.familiesBySource[this.source];for(const sourceLayerId in layerFamilies){const sourceLayer=data.layers[sourceLayerId];if(!sourceLayer){continue}if(sourceLayer.version===1){performance.warnOnce(`Vector tile source "${this.source}" layer "${sourceLayerId}" `+"does not use vector tile spec v2 and therefore may have some rendering errors.")}const sourceLayerIndex=sourceLayerCoder.encode(sourceLayerId);const features=[];for(let index=0;index=layer.maxzoom)continue;if(layer.visibility==="none")continue;recalculateLayers(family,this.zoom,availableImages);const bucket=buckets[layer.id]=layer.createBucket({index:featureIndex.bucketLayerIDs.length,layers:family,zoom:this.zoom,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:sourceLayerIndex,sourceID:this.source});bucket.populate(features,options,this.tileID.canonical);featureIndex.bucketLayerIDs.push(family.map((l=>l.id)))}}const stacks=performance.mapObject(options.glyphDependencies,(glyphs=>Object.keys(glyphs).map(Number)));this.inFlightDependencies.forEach((request=>request===null||request===void 0?void 0:request.abort()));this.inFlightDependencies=[];let getGlyphsPromise=Promise.resolve({});if(Object.keys(stacks).length){const abortController=new AbortController;this.inFlightDependencies.push(abortController);getGlyphsPromise=actor.sendAsync({type:"getGlyphs",data:{stacks:stacks,source:this.source,tileID:this.tileID,type:"glyphs"}},abortController)}const icons=Object.keys(options.iconDependencies);let getIconsPromise=Promise.resolve({});if(icons.length){const abortController=new AbortController;this.inFlightDependencies.push(abortController);getIconsPromise=actor.sendAsync({type:"getImages",data:{icons:icons,source:this.source,tileID:this.tileID,type:"icons"}},abortController)}const patterns=Object.keys(options.patternDependencies);let getPatternsPromise=Promise.resolve({});if(patterns.length){const abortController=new AbortController;this.inFlightDependencies.push(abortController);getPatternsPromise=actor.sendAsync({type:"getImages",data:{icons:patterns,source:this.source,tileID:this.tileID,type:"patterns"}},abortController)}const[glyphMap,iconMap,patternMap]=yield Promise.all([getGlyphsPromise,getIconsPromise,getPatternsPromise]);const glyphAtlas=new GlyphAtlas(glyphMap);const imageAtlas=new performance.ImageAtlas(iconMap,patternMap);for(const key in buckets){const bucket=buckets[key];if(bucket instanceof performance.SymbolBucket){recalculateLayers(bucket.layers,this.zoom,availableImages);performance.performSymbolLayout({bucket:bucket,glyphMap:glyphMap,glyphPositions:glyphAtlas.positions,imageMap:iconMap,imagePositions:imageAtlas.iconPositions,showCollisionBoxes:this.showCollisionBoxes,canonical:this.tileID.canonical})}else if(bucket.hasPattern&&(bucket instanceof performance.LineBucket||bucket instanceof performance.FillBucket||bucket instanceof performance.FillExtrusionBucket)){recalculateLayers(bucket.layers,this.zoom,availableImages);bucket.addFeatures(options,this.tileID.canonical,imageAtlas.patternPositions)}}this.status="done";return{buckets:Object.values(buckets).filter((b=>!b.isEmpty())),featureIndex:featureIndex,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:glyphAtlas.image,imageAtlas:imageAtlas,glyphMap:this.returnDependencies?glyphMap:null,iconMap:this.returnDependencies?iconMap:null,glyphPositions:this.returnDependencies?glyphAtlas.positions:null}}))}}function recalculateLayers(layers,zoom,availableImages){const parameters=new performance.EvaluationParameters(zoom);for(const layer of layers){layer.recalculate(parameters,availableImages)}}class VectorTileWorkerSource{constructor(actor,layerIndex,availableImages){this.actor=actor;this.layerIndex=layerIndex;this.availableImages=availableImages;this.fetching={};this.loading={};this.loaded={}}loadVectorTile(params,abortController){return performance.__awaiter(this,void 0,void 0,(function*(){const response=yield performance.getArrayBuffer(params.request,abortController);try{const vectorTile=new performance.vectorTile.VectorTile(new performance.Protobuf(response.data));return{vectorTile:vectorTile,rawData:response.data,cacheControl:response.cacheControl,expires:response.expires}}catch(ex){const bytes=new Uint8Array(response.data);const isGzipped=bytes[0]===31&&bytes[1]===139;let errorMessage=`Unable to parse the tile at ${params.request.url}, `;if(isGzipped){errorMessage+="please make sure the data is not gzipped and that you have configured the relevant header in the server"}else{errorMessage+=`got error: ${ex.messge}`}throw new Error(errorMessage)}}))}loadTile(params){return performance.__awaiter(this,void 0,void 0,(function*(){const tileUid=params.uid;const perf=params&¶ms.request&¶ms.request.collectResourceTiming?new performance.RequestPerformance(params.request):false;const workerTile=new WorkerTile(params);this.loading[tileUid]=workerTile;const abortController=new AbortController;workerTile.abort=abortController;try{const response=yield this.loadVectorTile(params,abortController);delete this.loading[tileUid];if(!response){return null}const rawTileData=response.rawData;const cacheControl={};if(response.expires)cacheControl.expires=response.expires;if(response.cacheControl)cacheControl.cacheControl=response.cacheControl;const resourceTiming={};if(perf){const resourceTimingData=perf.finish();if(resourceTimingData)resourceTiming.resourceTiming=JSON.parse(JSON.stringify(resourceTimingData))}workerTile.vectorTile=response.vectorTile;const parsePromise=workerTile.parse(response.vectorTile,this.layerIndex,this.availableImages,this.actor);this.loaded[tileUid]=workerTile;this.fetching[tileUid]={rawTileData:rawTileData,cacheControl:cacheControl,resourceTiming:resourceTiming};try{const result=yield parsePromise;return performance.extend({rawTileData:rawTileData.slice(0)},result,cacheControl,resourceTiming)}finally{delete this.fetching[tileUid]}}catch(err){delete this.loading[tileUid];workerTile.status="done";this.loaded[tileUid]=workerTile;throw err}}))}reloadTile(params){return performance.__awaiter(this,void 0,void 0,(function*(){const uid=params.uid;if(!this.loaded||!this.loaded[uid]){throw new Error("Should not be trying to reload a tile that was never loaded or has been removed")}const workerTile=this.loaded[uid];workerTile.showCollisionBoxes=params.showCollisionBoxes;if(workerTile.status==="parsing"){const result=yield workerTile.parse(workerTile.vectorTile,this.layerIndex,this.availableImages,this.actor);let parseResult;if(this.fetching[uid]){const{rawTileData:rawTileData,cacheControl:cacheControl,resourceTiming:resourceTiming}=this.fetching[uid];delete this.fetching[uid];parseResult=performance.extend({rawTileData:rawTileData.slice(0)},result,cacheControl,resourceTiming)}else{parseResult=result}return parseResult}if(workerTile.status==="done"&&workerTile.vectorTile){return workerTile.parse(workerTile.vectorTile,this.layerIndex,this.availableImages,this.actor)}}))}abortTile(params){return performance.__awaiter(this,void 0,void 0,(function*(){const loading=this.loading;const uid=params.uid;if(loading&&loading[uid]&&loading[uid].abort){loading[uid].abort.abort();delete loading[uid]}}))}removeTile(params){return performance.__awaiter(this,void 0,void 0,(function*(){if(this.loaded&&this.loaded[params.uid]){delete this.loaded[params.uid]}}))}}class RasterDEMTileWorkerSource{constructor(){this.loaded={}}loadTile(params){return performance.__awaiter(this,void 0,void 0,(function*(){const{uid:uid,encoding:encoding,rawImageData:rawImageData,redFactor:redFactor,greenFactor:greenFactor,blueFactor:blueFactor,baseShift:baseShift}=params;const width=rawImageData.width+2;const height=rawImageData.height+2;const imagePixels=performance.isImageBitmap(rawImageData)?new performance.RGBAImage({width:width,height:height},yield performance.getImageData(rawImageData,-1,-1,width,height)):rawImageData;const dem=new performance.DEMData(uid,imagePixels,encoding,redFactor,greenFactor,blueFactor,baseShift);this.loaded=this.loaded||{};this.loaded[uid]=dem;return dem}))}removeTile(params){const loaded=this.loaded,uid=params.uid;if(loaded&&loaded[uid]){delete loaded[uid]}}}var geojsonRewind=rewind$1;function rewind$1(gj,outer){var type=gj&&gj.type,i;if(type==="FeatureCollection"){for(i=0;i=Math.abs(k)?area-m+k:k-m+area;area=m}if(area+err>=0!==!!dir)ring.reverse()}var rewind$2=performance.getDefaultExportFromCjs(geojsonRewind);const toGeoJSON=performance.vectorTile.VectorTileFeature.prototype.toGeoJSON;let FeatureWrapper$1=class FeatureWrapper{constructor(feature){this._feature=feature;this.extent=performance.EXTENT;this.type=feature.type;this.properties=feature.tags;if("id"in feature&&!isNaN(feature.id)){this.id=parseInt(feature.id,10)}}loadGeometry(){if(this._feature.type===1){const geometry=[];for(const point of this._feature.geometry){geometry.push([new performance.Point(point[0],point[1])])}return geometry}else{const geometry=[];for(const ring of this._feature.geometry){const newRing=[];for(const point of ring){newRing.push(new performance.Point(point[0],point[1]))}geometry.push(newRing)}return geometry}}toGeoJSON(x,y,z){return toGeoJSON.call(this,x,y,z)}};let GeoJSONWrapper$2=class GeoJSONWrapper{constructor(features){this.layers={_geojsonTileLayer:this};this.name="_geojsonTileLayer";this.extent=performance.EXTENT;this.length=features.length;this._features=features}feature(i){return new FeatureWrapper$1(this._features[i])}};var vtPbf$1={exports:{}};"use strict";var Point=performance.pointGeometry;var VectorTileFeature=performance.vectorTile.VectorTileFeature;var geojson_wrapper=GeoJSONWrapper$1;function GeoJSONWrapper$1(features,options){this.options=options||{};this.features=features;this.length=features.length}GeoJSONWrapper$1.prototype.feature=function(i){return new FeatureWrapper(this.features[i],this.options.extent)};function FeatureWrapper(feature,extent){this.id=typeof feature.id==="number"?feature.id:undefined;this.type=feature.type;this.rawGeometry=feature.type===1?[feature.geometry]:feature.geometry;this.properties=feature.tags;this.extent=extent||4096}FeatureWrapper.prototype.loadGeometry=function(){var rings=this.rawGeometry;this.geometry=[];for(var i=0;i>31}function writeGeometry(feature,pbf){var geometry=feature.loadGeometry();var type=feature.type;var x=0;var y=0;var rings=geometry.length;for(var r=0;rprops};const fround=Math.fround||(tmp=>x=>{tmp[0]=+x;return tmp[0]})(new Float32Array(1));const OFFSET_ZOOM=2;const OFFSET_ID=3;const OFFSET_PARENT=4;const OFFSET_NUM=5;const OFFSET_PROP=6;class Supercluster{constructor(options){this.options=Object.assign(Object.create(defaultOptions),options);this.trees=new Array(this.options.maxZoom+1);this.stride=this.options.reduce?7:6;this.clusterProps=[]}load(points){const{log:log,minZoom:minZoom,maxZoom:maxZoom}=this.options;if(log)console.time("total time");const timerId=`prepare ${points.length} points`;if(log)console.time(timerId);this.points=points;const data=[];for(let i=0;i=minZoom;z--){const now=+Date.now();tree=this.trees[z]=this._createTree(this._cluster(tree,z));if(log)console.log("z%d: %d clusters in %dms",z,tree.numItems,+Date.now()-now)}if(log)console.timeEnd("total time");return this}getClusters(bbox,zoom){let minLng=((bbox[0]+180)%360+360)%360-180;const minLat=Math.max(-90,Math.min(90,bbox[1]));let maxLng=bbox[2]===180?180:((bbox[2]+180)%360+360)%360-180;const maxLat=Math.max(-90,Math.min(90,bbox[3]));if(bbox[2]-bbox[0]>=360){minLng=-180;maxLng=180}else if(minLng>maxLng){const easternHem=this.getClusters([minLng,minLat,180,maxLat],zoom);const westernHem=this.getClusters([-180,minLat,maxLng,maxLat],zoom);return easternHem.concat(westernHem)}const tree=this.trees[this._limitZoom(zoom)];const ids=tree.range(lngX(minLng),latY(maxLat),lngX(maxLng),latY(minLat));const data=tree.data;const clusters=[];for(const id of ids){const k=this.stride*id;clusters.push(data[k+OFFSET_NUM]>1?getClusterJSON(data,k,this.clusterProps):this.points[data[k+OFFSET_ID]])}return clusters}getChildren(clusterId){const originId=this._getOriginId(clusterId);const originZoom=this._getOriginZoom(clusterId);const errorMsg="No cluster with the specified id.";const tree=this.trees[originZoom];if(!tree)throw new Error(errorMsg);const data=tree.data;if(originId*this.stride>=data.length)throw new Error(errorMsg);const r=this.options.radius/(this.options.extent*Math.pow(2,originZoom-1));const x=data[originId*this.stride];const y=data[originId*this.stride+1];const ids=tree.within(x,y,r);const children=[];for(const id of ids){const k=id*this.stride;if(data[k+OFFSET_PARENT]===clusterId){children.push(data[k+OFFSET_NUM]>1?getClusterJSON(data,k,this.clusterProps):this.points[data[k+OFFSET_ID]])}}if(children.length===0)throw new Error(errorMsg);return children}getLeaves(clusterId,limit,offset){limit=limit||10;offset=offset||0;const leaves=[];this._appendLeaves(leaves,clusterId,limit,offset,0);return leaves}getTile(z,x,y){const tree=this.trees[this._limitZoom(z)];const z2=Math.pow(2,z);const{extent:extent,radius:radius}=this.options;const p=radius/extent;const top=(y-p)/z2;const bottom=(y+1+p)/z2;const tile={features:[]};this._addTileFeatures(tree.range((x-p)/z2,top,(x+1+p)/z2,bottom),tree.data,x,y,z2,tile);if(x===0){this._addTileFeatures(tree.range(1-p/z2,top,1,bottom),tree.data,z2,y,z2,tile)}if(x===z2-1){this._addTileFeatures(tree.range(0,top,p/z2,bottom),tree.data,-1,y,z2,tile)}return tile.features.length?tile:null}getClusterExpansionZoom(clusterId){let expansionZoom=this._getOriginZoom(clusterId)-1;while(expansionZoom<=this.options.maxZoom){const children=this.getChildren(clusterId);expansionZoom++;if(children.length!==1)break;clusterId=children[0].properties.cluster_id}return expansionZoom}_appendLeaves(result,clusterId,limit,offset,skipped){const children=this.getChildren(clusterId);for(const child of children){const props=child.properties;if(props&&props.cluster){if(skipped+props.point_count<=offset){skipped+=props.point_count}else{skipped=this._appendLeaves(result,props.cluster_id,limit,offset,skipped)}}else if(skipped1;let tags,px,py;if(isCluster){tags=getClusterProperties(data,k,this.clusterProps);px=data[k];py=data[k+1]}else{const p=this.points[data[k+OFFSET_ID]];tags=p.properties;const[lng,lat]=p.geometry.coordinates;px=lngX(lng);py=latY(lat)}const f={type:1,geometry:[[Math.round(this.options.extent*(px*z2-x)),Math.round(this.options.extent*(py*z2-y))]],tags:tags};let id;if(isCluster||this.options.generateId){id=data[k+OFFSET_ID]}else{id=this.points[data[k+OFFSET_ID]].id}if(id!==undefined)f.id=id;tile.features.push(f)}}_limitZoom(z){return Math.max(this.options.minZoom,Math.min(Math.floor(+z),this.options.maxZoom+1))}_cluster(tree,zoom){const{radius:radius,extent:extent,reduce:reduce,minPoints:minPoints}=this.options;const r=radius/(extent*Math.pow(2,zoom));const data=tree.data;const nextData=[];const stride=this.stride;for(let i=0;izoom)numPoints+=data[k+OFFSET_NUM]}if(numPoints>numPointsOrigin&&numPoints>=minPoints){let wx=x*numPointsOrigin;let wy=y*numPointsOrigin;let clusterProperties;let clusterPropIndex=-1;const id=((i/stride|0)<<5)+(zoom+1)+this.points.length;for(const neighborId of neighborIds){const k=neighborId*stride;if(data[k+OFFSET_ZOOM]<=zoom)continue;data[k+OFFSET_ZOOM]=zoom;const numPoints2=data[k+OFFSET_NUM];wx+=data[k]*numPoints2;wy+=data[k+1]*numPoints2;data[k+OFFSET_PARENT]=id;if(reduce){if(!clusterProperties){clusterProperties=this._map(data,i,true);clusterPropIndex=this.clusterProps.length;this.clusterProps.push(clusterProperties)}reduce(clusterProperties,this._map(data,k))}}data[i+OFFSET_PARENT]=id;nextData.push(wx/numPoints,wy/numPoints,Infinity,id,-1,numPoints);if(reduce)nextData.push(clusterPropIndex)}else{for(let j=0;j1){for(const neighborId of neighborIds){const k=neighborId*stride;if(data[k+OFFSET_ZOOM]<=zoom)continue;data[k+OFFSET_ZOOM]=zoom;for(let j=0;j>5}_getOriginZoom(clusterId){return(clusterId-this.points.length)%32}_map(data,i,clone){if(data[i+OFFSET_NUM]>1){const props=this.clusterProps[data[i+OFFSET_PROP]];return clone?Object.assign({},props):props}const original=this.points[data[i+OFFSET_ID]].properties;const result=this.options.map(original);return clone&&result===original?Object.assign({},result):result}}function getClusterJSON(data,i,clusterProps){return{type:"Feature",id:data[i+OFFSET_ID],properties:getClusterProperties(data,i,clusterProps),geometry:{type:"Point",coordinates:[xLng(data[i]),yLat(data[i+1])]}}}function getClusterProperties(data,i,clusterProps){const count=data[i+OFFSET_NUM];const abbrev=count>=1e4?`${Math.round(count/1e3)}k`:count>=1e3?`${Math.round(count/100)/10}k`:count;const propIndex=data[i+OFFSET_PROP];const properties=propIndex===-1?{}:Object.assign({},clusterProps[propIndex]);return Object.assign(properties,{cluster:true,cluster_id:data[i+OFFSET_ID],point_count:count,point_count_abbreviated:abbrev})}function lngX(lng){return lng/360+.5}function latY(lat){const sin=Math.sin(lat*Math.PI/180);const y=.5-.25*Math.log((1+sin)/(1-sin))/Math.PI;return y<0?0:y>1?1:y}function xLng(x){return(x-.5)*360}function yLat(y){const y2=(180-y*360)*Math.PI/180;return 360*Math.atan(Math.exp(y2))/Math.PI-90}function simplify(coords,first,last,sqTolerance){var maxSqDist=sqTolerance;var mid=last-first>>1;var minPosToMid=last-first;var index;var ax=coords[first];var ay=coords[first+1];var bx=coords[last];var by=coords[last+1];for(var i=first+3;imaxSqDist){index=i;maxSqDist=d}else if(d===maxSqDist){var posToMid=Math.abs(i-mid);if(posToMidsqTolerance){if(index-first>3)simplify(coords,first,index,sqTolerance);coords[index+2]=maxSqDist;if(last-index>3)simplify(coords,index,last,sqTolerance)}}function getSqSegDist(px,py,x,y,bx,by){var dx=bx-x;var dy=by-y;if(dx!==0||dy!==0){var t=((px-x)*dx+(py-y)*dy)/(dx*dx+dy*dy);if(t>1){x=bx;y=by}else if(t>0){x+=dx*t;y+=dy*t}}dx=px-x;dy=py-y;return dx*dx+dy*dy}function createFeature(id,type,geom,tags){var feature={id:typeof id==="undefined"?null:id,type:type,geometry:geom,tags:tags,minX:Infinity,minY:Infinity,maxX:-Infinity,maxY:-Infinity};calcBBox(feature);return feature}function calcBBox(feature){var geom=feature.geometry;var type=feature.type;if(type==="Point"||type==="MultiPoint"||type==="LineString"){calcLineBBox(feature,geom)}else if(type==="Polygon"||type==="MultiLineString"){for(var i=0;i0){if(isPolygon){size+=(x0*y-x*y0)/2}else{size+=Math.sqrt(Math.pow(x-x0,2)+Math.pow(y-y0,2))}}x0=x;y0=y}var last=out.length-3;out[2]=1;simplify(out,0,last,tolerance);out[last+2]=1;out.size=Math.abs(size);out.start=0;out.end=out.size}function convertLines(rings,out,tolerance,isPolygon){for(var i=0;i1?1:y2}function clip(features,scale,k1,k2,axis,minAll,maxAll,options){k1/=scale;k2/=scale;if(minAll>=k1&&maxAll=k2)return null;var clipped=[];for(var i=0;i=k1&&max=k2){continue}var newGeometry=[];if(type==="Point"||type==="MultiPoint"){clipPoints(geometry,newGeometry,k1,k2,axis)}else if(type==="LineString"){clipLine(geometry,newGeometry,k1,k2,axis,false,options.lineMetrics)}else if(type==="MultiLineString"){clipLines(geometry,newGeometry,k1,k2,axis,false)}else if(type==="Polygon"){clipLines(geometry,newGeometry,k1,k2,axis,true)}else if(type==="MultiPolygon"){for(var j=0;j=k1&&a<=k2){newGeom.push(geom[i]);newGeom.push(geom[i+1]);newGeom.push(geom[i+2])}}}function clipLine(geom,newGeom,k1,k2,axis,isPolygon,trackMetrics){var slice=newSlice(geom);var intersect=axis===0?intersectX:intersectY;var len=geom.start;var segLen,t;for(var i=0;ik1){t=intersect(slice,ax,ay,bx,by,k1);if(trackMetrics)slice.start=len+segLen*t}}else if(a>k2){if(b=k1){t=intersect(slice,ax,ay,bx,by,k1);exited=true}if(b>k2&&a<=k2){t=intersect(slice,ax,ay,bx,by,k2);exited=true}if(!isPolygon&&exited){if(trackMetrics)slice.end=len+segLen*t;newGeom.push(slice);slice=newSlice(geom)}if(trackMetrics)len+=segLen}var last=geom.length-3;ax=geom[last];ay=geom[last+1];az=geom[last+2];a=axis===0?ax:ay;if(a>=k1&&a<=k2)addPoint(slice,ax,ay,az);last=slice.length-3;if(isPolygon&&last>=3&&(slice[last]!==slice[0]||slice[last+1]!==slice[1])){addPoint(slice,slice[0],slice[1],slice[2])}if(slice.length){newGeom.push(slice)}}function newSlice(line){var slice=[];slice.size=line.size;slice.start=line.start;slice.end=line.end;return slice}function clipLines(geom,newGeom,k1,k2,axis,isPolygon){for(var i=0;itile.maxX)tile.maxX=maxX;if(maxY>tile.maxY)tile.maxY=maxY}return tile}function addFeature(tile,feature,tolerance,options){var geom=feature.geometry,type=feature.type,simplified=[];if(type==="Point"||type==="MultiPoint"){for(var i=0;i0&&geom.size<(isPolygon?sqTolerance:tolerance)){tile.numPoints+=geom.length/3;return}var ring=[];for(var i=0;isqTolerance){tile.numSimplified++;ring.push(geom[i]);ring.push(geom[i+1])}tile.numPoints++}if(isPolygon)rewind(ring,isOuter);result.push(ring)}function rewind(ring,clockwise){var area=0;for(var i=0,len=ring.length,j=len-2;i0===clockwise){for(i=0,len=ring.length;i24)throw new Error("maxZoom should be in the 0-24 range");if(options.promoteId&&options.generateId)throw new Error("promoteId and generateId cannot be used together.");var features=convert(data,options);this.tiles={};this.tileCoords=[];if(debug){console.timeEnd("preprocess data");console.log("index: maxZoom: %d, maxPoints: %d",options.indexMaxZoom,options.indexMaxPoints);console.time("generate tiles");this.stats={};this.total=0}features=wrap(features,options);if(features.length)this.splitTile(features,0,0,0);if(debug){if(features.length)console.log("features: %d, points: %d",this.tiles[0].numFeatures,this.tiles[0].numPoints);console.timeEnd("generate tiles");console.log("tiles generated:",this.total,JSON.stringify(this.stats))}}GeoJSONVT.prototype.options={maxZoom:14,indexMaxZoom:5,indexMaxPoints:1e5,tolerance:3,extent:4096,buffer:64,lineMetrics:false,promoteId:null,generateId:false,debug:0};GeoJSONVT.prototype.splitTile=function(features,z,x,y,cz,cx,cy){var stack=[features,z,x,y],options=this.options,debug=options.debug;while(stack.length){y=stack.pop();x=stack.pop();z=stack.pop();features=stack.pop();var z2=1<1)console.time("creation");tile=this.tiles[id]=createTile(features,z,x,y,options);this.tileCoords.push({z:z,x:x,y:y});if(debug){if(debug>1){console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",z,x,y,tile.numFeatures,tile.numPoints,tile.numSimplified);console.timeEnd("creation")}var key="z"+z;this.stats[key]=(this.stats[key]||0)+1;this.total++}}tile.source=features;if(!cz){if(z===options.indexMaxZoom||tile.numPoints<=options.indexMaxPoints)continue}else{if(z===options.maxZoom||z===cz)continue;var m=1<1)console.time("clipping");var k1=.5*options.buffer/options.extent,k2=.5-k1,k3=.5+k1,k4=1+k1,tl,bl,tr,br,left,right;tl=bl=tr=br=null;left=clip(features,z2,x-k1,x+k3,0,tile.minX,tile.maxX,options);right=clip(features,z2,x+k2,x+k4,0,tile.minX,tile.maxX,options);features=null;if(left){tl=clip(left,z2,y-k1,y+k3,1,tile.minY,tile.maxY,options);bl=clip(left,z2,y+k2,y+k4,1,tile.minY,tile.maxY,options);left=null}if(right){tr=clip(right,z2,y-k1,y+k3,1,tile.minY,tile.maxY,options);br=clip(right,z2,y+k2,y+k4,1,tile.minY,tile.maxY,options);right=null}if(debug>1)console.timeEnd("clipping");stack.push(tl||[],z+1,x*2,y*2);stack.push(bl||[],z+1,x*2,y*2+1);stack.push(tr||[],z+1,x*2+1,y*2);stack.push(br||[],z+1,x*2+1,y*2+1)}};GeoJSONVT.prototype.getTile=function(z,x,y){var options=this.options,extent=options.extent,debug=options.debug;if(z<0||z>24)return null;var z2=1<1)console.log("drilling down to z%d-%d-%d",z,x,y);var z0=z,x0=x,y0=y,parent;while(!parent&&z0>0){z0--;x0=Math.floor(x0/2);y0=Math.floor(y0/2);parent=this.tiles[toID(z0,x0,y0)]}if(!parent||!parent.source)return null;if(debug>1)console.log("found parent tile z%d-%d-%d",z0,x0,y0);if(debug>1)console.time("drilling down");this.splitTile(parent.source,z0,x0,y0,z,x,y);if(debug>1)console.timeEnd("drilling down");return this.tiles[id]?transformTile(this.tiles[id],extent):null};function toID(z,x,y){return((1<0||((_b=update.addOrUpdateProperties)===null||_b===void 0?void 0:_b.length)>0);if(cloneFeature||cloneProperties){feature=Object.assign({},feature);updateable.set(update.id,feature);if(cloneProperties){feature.properties=Object.assign({},feature.properties)}}if(update.newGeometry){feature.geometry=update.newGeometry}if(update.removeAllProperties){feature.properties={}}else if(((_c=update.removeProperties)===null||_c===void 0?void 0:_c.length)>0){for(const prop of update.removeProperties){if(Object.prototype.hasOwnProperty.call(feature.properties,prop)){delete feature.properties[prop]}}}if(((_d=update.addOrUpdateProperties)===null||_d===void 0?void 0:_d.length)>0){for(const{key:key,value:value}of update.addOrUpdateProperties){feature.properties[key]=value}}}}}class GeoJSONWorkerSource extends VectorTileWorkerSource{constructor(){super(...arguments);this._dataUpdateable=new Map}loadVectorTile(params,_abortController){return performance.__awaiter(this,void 0,void 0,(function*(){const canonical=params.tileID.canonical;if(!this._geoJSONIndex){throw new Error("Unable to parse the data into a cluster or geojson")}const geoJSONTile=this._geoJSONIndex.getTile(canonical.z,canonical.x,canonical.y);if(!geoJSONTile){return null}const geojsonWrapper=new GeoJSONWrapper$2(geoJSONTile.features);let pbf=vtpbf(geojsonWrapper);if(pbf.byteOffset!==0||pbf.byteLength!==pbf.buffer.byteLength){pbf=new Uint8Array(pbf)}return{vectorTile:geojsonWrapper,rawData:pbf.buffer}}))}loadData(params){var _a;return performance.__awaiter(this,void 0,void 0,(function*(){(_a=this._pendingRequest)===null||_a===void 0?void 0:_a.abort();const perf=params&¶ms.request&¶ms.request.collectResourceTiming?new performance.RequestPerformance(params.request):false;this._pendingRequest=new AbortController;try{let data=yield this.loadGeoJSON(params,this._pendingRequest);delete this._pendingRequest;if(typeof data!=="object"){throw new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`)}rewind$2(data,true);if(params.filter){const compiled=performance.createExpression(params.filter,{type:"boolean","property-type":"data-driven",overridable:false,transition:false});if(compiled.result==="error")throw new Error(compiled.value.map((err=>`${err.key}: ${err.message}`)).join(", "));const features=data.features.filter((feature=>compiled.value.evaluate({zoom:0},feature)));data={type:"FeatureCollection",features:features}}this._geoJSONIndex=params.cluster?new Supercluster(getSuperclusterOptions(params)).load(data.features):geojsonvt(data,params.geojsonVtOptions);this.loaded={};const result={};if(perf){const resourceTimingData=perf.finish();if(resourceTimingData){result.resourceTiming={};result.resourceTiming[params.source]=JSON.parse(JSON.stringify(resourceTimingData))}}return result}catch(err){delete this._pendingRequest;if(performance.isAbortError(err)){return{abandoned:true}}throw err}}))}reloadTile(params){const loaded=this.loaded,uid=params.uid;if(loaded&&loaded[uid]){return super.reloadTile(params)}else{return this.loadTile(params)}}loadGeoJSON(params,abortController){return performance.__awaiter(this,void 0,void 0,(function*(){const{promoteId:promoteId}=params;if(params.request){const response=yield performance.getJSON(params.request,abortController);this._dataUpdateable=isUpdateableGeoJSON(response.data,promoteId)?toUpdateable(response.data,promoteId):undefined;return response.data}if(typeof params.data==="string"){try{const parsed=JSON.parse(params.data);this._dataUpdateable=isUpdateableGeoJSON(parsed,promoteId)?toUpdateable(parsed,promoteId):undefined;return parsed}catch(e){throw new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`)}}if(!params.dataDiff){throw new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`)}if(!this._dataUpdateable){throw new Error(`Cannot update existing geojson data in ${params.source}`)}applySourceDiff(this._dataUpdateable,params.dataDiff,promoteId);return{type:"FeatureCollection",features:Array.from(this._dataUpdateable.values())}}))}removeSource(_params){return performance.__awaiter(this,void 0,void 0,(function*(){if(this._pendingRequest){this._pendingRequest.abort()}}))}getClusterExpansionZoom(params){return this._geoJSONIndex.getClusterExpansionZoom(params.clusterId)}getClusterChildren(params){return this._geoJSONIndex.getChildren(params.clusterId)}getClusterLeaves(params){return this._geoJSONIndex.getLeaves(params.clusterId,params.limit,params.offset)}}function getSuperclusterOptions({superclusterOptions:superclusterOptions,clusterProperties:clusterProperties}){if(!clusterProperties||!superclusterOptions)return superclusterOptions;const mapExpressions={};const reduceExpressions={};const globals={accumulated:null,zoom:0};const feature={properties:null};const propertyNames=Object.keys(clusterProperties);for(const key of propertyNames){const[operator,mapExpression]=clusterProperties[key];const mapExpressionParsed=performance.createExpression(mapExpression);const reduceExpressionParsed=performance.createExpression(typeof operator==="string"?[operator,["accumulated"],["get",key]]:operator);mapExpressions[key]=mapExpressionParsed.value;reduceExpressions[key]=reduceExpressionParsed.value}superclusterOptions.map=pointProperties=>{feature.properties=pointProperties;const properties={};for(const key of propertyNames){properties[key]=mapExpressions[key].evaluate(globals,feature)}return properties};superclusterOptions.reduce=(accumulated,clusterProperties)=>{feature.properties=clusterProperties;for(const key of propertyNames){globals.accumulated=accumulated[key];accumulated[key]=reduceExpressions[key].evaluate(globals,feature)}};return superclusterOptions}class Worker{constructor(self){this.self=self;this.actor=new performance.Actor(self);this.layerIndexes={};this.availableImages={};this.workerSources={};this.demWorkerSources={};this.externalWorkerSourceTypes={};this.self.registerWorkerSource=(name,WorkerSource)=>{if(this.externalWorkerSourceTypes[name]){throw new Error(`Worker source with name "${name}" already registered.`)}this.externalWorkerSourceTypes[name]=WorkerSource};this.self.addProtocol=performance.addProtocol;this.self.removeProtocol=performance.removeProtocol;this.self.registerRTLTextPlugin=rtlTextPlugin=>{if(performance.rtlWorkerPlugin.isParsed()){throw new Error("RTL text plugin already registered.")}performance.rtlWorkerPlugin.setMethods(rtlTextPlugin)};this.actor.registerMessageHandler("loadDEMTile",((mapId,params)=>this._getDEMWorkerSource(mapId,params.source).loadTile(params)));this.actor.registerMessageHandler("removeDEMTile",((mapId,params)=>performance.__awaiter(this,void 0,void 0,(function*(){this._getDEMWorkerSource(mapId,params.source).removeTile(params)}))));this.actor.registerMessageHandler("getClusterExpansionZoom",((mapId,params)=>performance.__awaiter(this,void 0,void 0,(function*(){return this._getWorkerSource(mapId,params.type,params.source).getClusterExpansionZoom(params)}))));this.actor.registerMessageHandler("getClusterChildren",((mapId,params)=>performance.__awaiter(this,void 0,void 0,(function*(){return this._getWorkerSource(mapId,params.type,params.source).getClusterChildren(params)}))));this.actor.registerMessageHandler("getClusterLeaves",((mapId,params)=>performance.__awaiter(this,void 0,void 0,(function*(){return this._getWorkerSource(mapId,params.type,params.source).getClusterLeaves(params)}))));this.actor.registerMessageHandler("loadData",((mapId,params)=>this._getWorkerSource(mapId,params.type,params.source).loadData(params)));this.actor.registerMessageHandler("loadTile",((mapId,params)=>this._getWorkerSource(mapId,params.type,params.source).loadTile(params)));this.actor.registerMessageHandler("reloadTile",((mapId,params)=>this._getWorkerSource(mapId,params.type,params.source).reloadTile(params)));this.actor.registerMessageHandler("abortTile",((mapId,params)=>this._getWorkerSource(mapId,params.type,params.source).abortTile(params)));this.actor.registerMessageHandler("removeTile",((mapId,params)=>this._getWorkerSource(mapId,params.type,params.source).removeTile(params)));this.actor.registerMessageHandler("removeSource",((mapId,params)=>performance.__awaiter(this,void 0,void 0,(function*(){if(!this.workerSources[mapId]||!this.workerSources[mapId][params.type]||!this.workerSources[mapId][params.type][params.source]){return}const worker=this.workerSources[mapId][params.type][params.source];delete this.workerSources[mapId][params.type][params.source];if(worker.removeSource!==undefined){worker.removeSource(params)}}))));this.actor.registerMessageHandler("setReferrer",((_mapId,params)=>performance.__awaiter(this,void 0,void 0,(function*(){this.referrer=params}))));this.actor.registerMessageHandler("syncRTLPluginState",((mapId,params)=>this._syncRTLPluginState(mapId,params)));this.actor.registerMessageHandler("importScript",((_mapId,params)=>performance.__awaiter(this,void 0,void 0,(function*(){this.self.importScripts(params)}))));this.actor.registerMessageHandler("setImages",((mapId,params)=>this._setImages(mapId,params)));this.actor.registerMessageHandler("updateLayers",((mapId,params)=>performance.__awaiter(this,void 0,void 0,(function*(){this._getLayerIndex(mapId).update(params.layers,params.removedIds)}))));this.actor.registerMessageHandler("setLayers",((mapId,params)=>performance.__awaiter(this,void 0,void 0,(function*(){this._getLayerIndex(mapId).replace(params)}))))}_setImages(mapId,images){return performance.__awaiter(this,void 0,void 0,(function*(){this.availableImages[mapId]=images;for(const workerSource in this.workerSources[mapId]){const ws=this.workerSources[mapId][workerSource];for(const source in ws){ws[source].availableImages=images}}}))}_syncRTLPluginState(map,state){return performance.__awaiter(this,void 0,void 0,(function*(){performance.rtlWorkerPlugin.setState(state);const pluginURL=performance.rtlWorkerPlugin.getPluginURL();if(state.pluginStatus==="loaded"&&!performance.rtlWorkerPlugin.isParsed()&&pluginURL!=null){this.self.importScripts(pluginURL);const complete=performance.rtlWorkerPlugin.isParsed();if(complete){return complete}throw new Error(`RTL Text Plugin failed to import scripts from ${pluginURL}`)}return false}))}_getAvailableImages(mapId){let availableImages=this.availableImages[mapId];if(!availableImages){availableImages=[]}return availableImages}_getLayerIndex(mapId){let layerIndexes=this.layerIndexes[mapId];if(!layerIndexes){layerIndexes=this.layerIndexes[mapId]=new StyleLayerIndex}return layerIndexes}_getWorkerSource(mapId,sourceType,sourceName){if(!this.workerSources[mapId])this.workerSources[mapId]={};if(!this.workerSources[mapId][sourceType])this.workerSources[mapId][sourceType]={};if(!this.workerSources[mapId][sourceType][sourceName]){const actor={sendAsync:(message,abortController)=>{message.targetMapId=mapId;return this.actor.sendAsync(message,abortController)}};switch(sourceType){case"vector":this.workerSources[mapId][sourceType][sourceName]=new VectorTileWorkerSource(actor,this._getLayerIndex(mapId),this._getAvailableImages(mapId));break;case"geojson":this.workerSources[mapId][sourceType][sourceName]=new GeoJSONWorkerSource(actor,this._getLayerIndex(mapId),this._getAvailableImages(mapId));break;default:this.workerSources[mapId][sourceType][sourceName]=new this.externalWorkerSourceTypes[sourceType](actor,this._getLayerIndex(mapId),this._getAvailableImages(mapId));break}}return this.workerSources[mapId][sourceType][sourceName]}_getDEMWorkerSource(mapId,sourceType){if(!this.demWorkerSources[mapId])this.demWorkerSources[mapId]={};if(!this.demWorkerSources[mapId][sourceType]){this.demWorkerSources[mapId][sourceType]=new RasterDEMTileWorkerSource}return this.demWorkerSources[mapId][sourceType]}}if(performance.isWorker(self)){self.worker=new Worker(self)}return Worker}));define("index",["exports","./shared"],(function(exports,performance$1){"use strict";var name="maplibre-gl";var description="BSD licensed community fork of mapbox-gl, a WebGL interactive maps library";var version$2="4.0.2";var main="dist/maplibre-gl.js";var style="dist/maplibre-gl.css";var license="BSD-3-Clause";var funding="https://github.com/maplibre/maplibre-gl-js?sponsor=1";var repository={type:"git",url:"git://github.com/maplibre/maplibre-gl-js.git"};var types="dist/maplibre-gl.d.ts";var type="module";var dependencies={"@mapbox/geojson-rewind":"^0.5.2","@mapbox/jsonlint-lines-primitives":"^2.0.2","@mapbox/point-geometry":"^0.1.0","@mapbox/tiny-sdf":"^2.0.6","@mapbox/unitbezier":"^0.0.1","@mapbox/vector-tile":"^1.3.1","@mapbox/whoots-js":"^3.1.0","@maplibre/maplibre-gl-style-spec":"^20.1.1","@types/geojson":"^7946.0.14","@types/geojson-vt":"3.2.5","@types/mapbox__point-geometry":"^0.1.4","@types/mapbox__vector-tile":"^1.3.4","@types/pbf":"^3.0.5","@types/supercluster":"^7.1.3",earcut:"^2.2.4","geojson-vt":"^3.2.1","gl-matrix":"^3.4.3","global-prefix":"^3.0.0",kdbush:"^4.0.2","murmurhash-js":"^1.0.0",pbf:"^3.2.1",potpack:"^2.0.0",quickselect:"^2.0.0",supercluster:"^8.0.1",tinyqueue:"^2.0.3","vt-pbf":"^3.1.3"};var devDependencies={"@mapbox/mapbox-gl-rtl-text":"^0.2.3","@mapbox/mvt-fixtures":"^3.10.0","@rollup/plugin-commonjs":"^25.0.7","@rollup/plugin-json":"^6.1.0","@rollup/plugin-node-resolve":"^15.2.3","@rollup/plugin-replace":"^5.0.5","@rollup/plugin-strip":"^3.0.4","@rollup/plugin-terser":"^0.4.4","@rollup/plugin-typescript":"^11.1.6","@types/benchmark":"^2.1.5","@types/cssnano":"^5.0.0","@types/d3":"^7.4.3","@types/diff":"^5.0.9","@types/earcut":"^2.1.4","@types/eslint":"^8.56.2","@types/gl":"^6.0.5","@types/glob":"^8.1.0","@types/jest":"^29.5.12","@types/jsdom":"^21.1.6","@types/minimist":"^1.2.5","@types/murmurhash-js":"^1.0.6","@types/nise":"^1.4.4","@types/node":"^20.11.19","@types/offscreencanvas":"^2019.7.3","@types/pixelmatch":"^5.2.6","@types/pngjs":"^6.0.4","@types/react":"^18.2.56","@types/react-dom":"^18.2.19","@types/request":"^2.48.12","@types/shuffle-seed":"^1.1.3","@types/window-or-global":"^1.0.6","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^6.21.0",address:"^2.0.1",benchmark:"^2.1.4",canvas:"^2.11.2",cssnano:"^6.0.3",d3:"^7.8.5","d3-queue":"^3.0.7","devtools-protocol":"^0.0.1262051",diff:"^5.2.0","dts-bundle-generator":"^9.3.1",eslint:"^8.56.0","eslint-config-mourner":"^3.0.0","eslint-plugin-html":"^8.0.0","eslint-plugin-import":"^2.29.1","eslint-plugin-jest":"^27.9.0","eslint-plugin-react":"^7.33.2","eslint-plugin-tsdoc":"0.2.17",expect:"^29.7.0",glob:"^10.3.10","is-builtin-module":"^3.2.1",jest:"^29.7.0","jest-environment-jsdom":"^29.7.0","jest-monocart-coverage":"^1.0.2","jest-webgl-canvas-mock":"^2.5.3",jsdom:"^24.0.0","json-stringify-pretty-compact":"^4.0.0",minimist:"^1.2.8","mock-geolocation":"^1.0.11","monocart-coverage-reports":"^2.5.0",nise:"^5.1.9","npm-font-open-sans":"^1.1.0","npm-run-all":"^4.1.5","pdf-merger-js":"^5.1.1",pixelmatch:"^5.3.0",pngjs:"^7.0.0",postcss:"^8.4.35","postcss-cli":"^11.0.0","postcss-inline-svg":"^6.0.0","pretty-bytes":"^6.1.1",puppeteer:"^22.1.0",react:"^18.2.0","react-dom":"^18.2.0",rollup:"^4.12.0","rollup-plugin-sourcemaps":"^0.6.3",rw:"^1.3.3",semver:"^7.6.0","shuffle-seed":"^1.1.6","source-map-explorer":"^2.5.3",st:"^3.0.0",stylelint:"^16.2.1","stylelint-config-standard":"^36.0.0","ts-jest":"^29.1.2","ts-node":"^10.9.2",tslib:"^2.6.2",typedoc:"^0.25.8","typedoc-plugin-markdown":"^3.17.1","typedoc-plugin-missing-exports":"^2.2.0",typescript:"^5.3.3"};var overrides={"postcss-inline-svg":{"css-select":"^5.1.0","dom-serializer":"^2.0.0",htmlparser2:"^8.0.1","postcss-value-parser":"^4.2.0"}};var scripts={"generate-dist-package":"node --no-warnings --loader ts-node/esm build/generate-dist-package.js","generate-shaders":"node --no-warnings --loader ts-node/esm build/generate-shaders.ts","generate-struct-arrays":"node --no-warnings --loader ts-node/esm build/generate-struct-arrays.ts","generate-style-code":"node --no-warnings --loader ts-node/esm build/generate-style-code.ts","generate-typings":"dts-bundle-generator --export-referenced-types --umd-module-name=maplibregl -o ./dist/maplibre-gl.d.ts ./src/index.ts","generate-docs":"typedoc && node --no-warnings --loader ts-node/esm build/generate-docs.ts","generate-images":"node --no-warnings --loader ts-node/esm build/generate-doc-images.ts","build-dist":"npm run build-css && npm run generate-typings && npm run build-dev && npm run build-csp-dev && npm run build-prod && npm run build-csp","build-dev":"rollup --configPlugin @rollup/plugin-typescript -c --environment BUILD:dev","watch-dev":"rollup --configPlugin @rollup/plugin-typescript -c --environment BUILD:dev --watch","build-prod":"rollup --configPlugin @rollup/plugin-typescript -c --environment BUILD:production","build-csp":"rollup --configPlugin @rollup/plugin-typescript -c rollup.config.csp.ts","build-csp-dev":"rollup --configPlugin @rollup/plugin-typescript -c rollup.config.csp.ts --environment BUILD:dev","build-css":"postcss -o dist/maplibre-gl.css src/css/maplibre-gl.css","watch-css":"postcss --watch -o dist/maplibre-gl.css src/css/maplibre-gl.css","build-benchmarks":"npm run build-dev && rollup --configPlugin @rollup/plugin-typescript -c test/bench/rollup_config_benchmarks.ts","watch-benchmarks":"rollup --configPlugin @rollup/plugin-typescript -c test/bench/rollup_config_benchmarks.ts --watch","start-server":"st --no-cache -H 0.0.0.0 --port 9966 .","start-docs":"docker run --rm -it -p 8000:8000 -v ${PWD}:/docs squidfunk/mkdocs-material",start:"run-p watch-css watch-dev start-server","start-bench":"run-p watch-css watch-benchmarks start-server",lint:"eslint --cache --ext .ts,.tsx,.js,.html --ignore-path .gitignore .","lint-css":"stylelint src/css/maplibre-gl.css",test:"run-p lint lint-css test-render jest",jest:"jest","test-build":"jest --selectProjects=build --reporters=default","test-build-ci":"jest --selectProjects=build","test-integration":"jest --selectProjects=integration --reporters=default","test-integration-ci":"jest --selectProjects=integration","test-render":"node --no-warnings --loader ts-node/esm test/integration/render/run_render_tests.ts","test-unit":"jest --selectProjects=unit --reporters=default","test-unit-ci":"jest --coverage --selectProjects unit","test-watch-roots":"jest --watch",codegen:"run-p --print-label generate-dist-package generate-style-code generate-struct-arrays generate-shaders && npm run generate-typings",benchmark:"node --no-warnings --loader ts-node/esm test/bench/run-benchmarks.ts","gl-stats":"node --no-warnings --loader ts-node/esm test/bench/gl-stats.ts",prepare:"npm run codegen",typecheck:"tsc --noEmit && tsc --project tsconfig.dist.json",tsnode:"node --experimental-loader=ts-node/esm --no-warnings"};var files=["build/","dist/*","src/"];var engines={npm:">=8.1.0",node:">=16.14.0"};var packageJSON={name:name,description:description,version:version$2,main:main,style:style,license:license,funding:funding,repository:repository,types:types,type:type,dependencies:dependencies,devDependencies:devDependencies,overrides:overrides,scripts:scripts,files:files,engines:engines};const now=typeof performance!=="undefined"&&performance&&performance.now?performance.now.bind(performance):Date.now.bind(Date);let linkEl;let reducedMotionQuery;const browser={now:now,frameAsync(abortController){return new Promise(((resolve,reject)=>{const frame=requestAnimationFrame(resolve);abortController.signal.addEventListener("abort",(()=>{cancelAnimationFrame(frame);reject(performance$1.createAbortError())}))}))},getImageData(img,padding=0){const context=this.getImageCanvasContext(img);return context.getImageData(-padding,-padding,img.width+2*padding,img.height+2*padding)},getImageCanvasContext(img){const canvas=window.document.createElement("canvas");const context=canvas.getContext("2d",{willReadFrequently:true});if(!context){throw new Error("failed to create canvas 2d context")}canvas.width=img.width;canvas.height=img.height;context.drawImage(img,0,0,img.width,img.height);return context},resolveURL(path){if(!linkEl)linkEl=document.createElement("a");linkEl.href=path;return linkEl.href},hardwareConcurrency:typeof navigator!=="undefined"&&navigator.hardwareConcurrency||4,get prefersReducedMotion(){if(!matchMedia)return false;if(reducedMotionQuery==null){reducedMotionQuery=matchMedia("(prefers-reduced-motion: reduce)")}return reducedMotionQuery.matches}};class DOM{static testProp(props){if(!DOM.docStyle)return props[0];for(let i=0;i{window.removeEventListener("click",DOM.suppressClickInternal,true)}),0)}static getScale(element){const rect=element.getBoundingClientRect();return{x:rect.width/element.offsetWidth||1,y:rect.height/element.offsetHeight||1,boundingClientRect:rect}}static getPoint(el,scale,e){const rect=scale.boundingClientRect;return new performance$1.Point((e.clientX-rect.left)/scale.x-el.clientLeft,(e.clientY-rect.top)/scale.y-el.clientTop)}static mousePos(el,e){const scale=DOM.getScale(el);return DOM.getPoint(el,scale,e)}static touchPos(el,touches){const points=[];const scale=DOM.getScale(el);for(let i=0;i{imageRequestQueue=[];currentParallelImageRequests=0;throttleControlCallbackHandleCounter=0;throttleControlCallbacks={}};ImageRequest.addThrottleControl=callback=>{const handle=throttleControlCallbackHandleCounter++;throttleControlCallbacks[handle]=callback;return handle};ImageRequest.removeThrottleControl=callbackHandle=>{delete throttleControlCallbacks[callbackHandle];processQueue()};const isThrottled=()=>{for(const key of Object.keys(throttleControlCallbacks)){if(throttleControlCallbacks[key]()){return true}}return false};ImageRequest.getImage=(requestParameters,abortController,supportImageRefresh=true)=>new Promise(((resolve,reject)=>{if(webpSupported.supported){if(!requestParameters.headers){requestParameters.headers={}}requestParameters.headers.accept="image/webp,*/*"}performance$1.extend(requestParameters,{type:"image"});const request={abortController:abortController,requestParameters:requestParameters,supportImageRefresh:supportImageRefresh,state:"queued",onError:error=>{reject(error)},onSuccess:response=>{resolve(response)}};imageRequestQueue.push(request);processQueue()}));const arrayBufferToCanvasImageSource=data=>{const imageBitmapSupported=typeof createImageBitmap==="function";if(imageBitmapSupported){return performance$1.arrayBufferToImageBitmap(data)}else{return performance$1.arrayBufferToImage(data)}};const doImageRequest=itemInQueue=>performance$1.__awaiter(this,void 0,void 0,(function*(){itemInQueue.state="running";const{requestParameters:requestParameters,supportImageRefresh:supportImageRefresh,onError:onError,onSuccess:onSuccess,abortController:abortController}=itemInQueue;const canUseHTMLImageElement=supportImageRefresh===false&&!performance$1.isWorker(self)&&!performance$1.getProtocol(requestParameters.url)&&(!requestParameters.headers||Object.keys(requestParameters.headers).reduce(((acc,item)=>acc&&item==="accept"),true));currentParallelImageRequests++;const getImagePromise=canUseHTMLImageElement?getImageUsingHtmlImage(requestParameters,abortController):performance$1.makeRequest(requestParameters,abortController);try{const response=yield getImagePromise;delete itemInQueue.abortController;itemInQueue.state="completed";if(response.data instanceof HTMLImageElement||performance$1.isImageBitmap(response.data)){onSuccess(response)}else if(response.data){const img=yield arrayBufferToCanvasImageSource(response.data);onSuccess({data:img,cacheControl:response.cacheControl,expires:response.expires})}}catch(err){delete itemInQueue.abortController;onError(err)}finally{currentParallelImageRequests--;processQueue()}}));const processQueue=()=>{const maxImageRequests=isThrottled()?performance$1.config.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:performance$1.config.MAX_PARALLEL_IMAGE_REQUESTS;for(let numImageRequests=currentParallelImageRequests;numImageRequests0;numImageRequests++){const topItemInQueue=imageRequestQueue.shift();if(topItemInQueue.abortController.signal.aborted){numImageRequests--;continue}doImageRequest(topItemInQueue)}};const getImageUsingHtmlImage=(requestParameters,abortController)=>new Promise(((resolve,reject)=>{const image=new Image;const url=requestParameters.url;const credentials=requestParameters.credentials;if(credentials&&credentials==="include"){image.crossOrigin="use-credentials"}else if(credentials&&credentials==="same-origin"||!performance$1.sameOrigin(url)){image.crossOrigin="anonymous"}abortController.signal.addEventListener("abort",(()=>{image.src="";reject(performance$1.createAbortError())}));image.fetchPriority="high";image.onload=()=>{image.onerror=image.onload=null;resolve({data:image})};image.onerror=()=>{image.onerror=image.onload=null;if(abortController.signal.aborted){return}reject(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."))};image.src=url}))})(ImageRequest||(ImageRequest={}));ImageRequest.resetRequestQueue();var ResourceType;(function(ResourceType){ResourceType["Glyphs"]="Glyphs";ResourceType["Image"]="Image";ResourceType["Source"]="Source";ResourceType["SpriteImage"]="SpriteImage";ResourceType["SpriteJSON"]="SpriteJSON";ResourceType["Style"]="Style";ResourceType["Tile"]="Tile";ResourceType["Unknown"]="Unknown"})(ResourceType||(ResourceType={}));class RequestManager{constructor(transformRequestFn){this._transformRequestFn=transformRequestFn}transformRequest(url,type){if(this._transformRequestFn){return this._transformRequestFn(url,type)||{url:url}}return{url:url}}normalizeSpriteURL(url,format,extension){const urlObject=parseUrl(url);urlObject.path+=`${format}${extension}`;return formatUrl(urlObject)}setTransformRequest(transformRequest){this._transformRequestFn=transformRequest}}const urlRe=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function parseUrl(url){const parts=url.match(urlRe);if(!parts){throw new Error(`Unable to parse URL "${url}"`)}return{protocol:parts[1],authority:parts[2],path:parts[3]||"/",params:parts[4]?parts[4].split("&"):[]}}function formatUrl(obj){const params=obj.params.length?`?${obj.params.join("&")}`:"";return`${obj.protocol}://${obj.authority}${obj.path}${params}`}function coerceSpriteToArray(sprite){const resultArray=[];if(typeof sprite==="string"){resultArray.push({id:"default",url:sprite})}else if(sprite&&sprite.length>0){const dedupArray=[];for(const{id:id,url:url}of sprite){const key=`${id}${url}`;if(dedupArray.indexOf(key)===-1){dedupArray.push(key);resultArray.push({id:id,url:url})}}}return resultArray}function loadSprite(originalSprite,requestManager,pixelRatio,abortController){return performance$1.__awaiter(this,void 0,void 0,(function*(){const spriteArray=coerceSpriteToArray(originalSprite);const format=pixelRatio>1?"@2x":"";const jsonsMap={};const imagesMap={};for(const{id:id,url:url}of spriteArray){const jsonRequestParameters=requestManager.transformRequest(requestManager.normalizeSpriteURL(url,format,".json"),ResourceType.SpriteJSON);jsonsMap[id]=performance$1.getJSON(jsonRequestParameters,abortController);const imageRequestParameters=requestManager.transformRequest(requestManager.normalizeSpriteURL(url,format,".png"),ResourceType.SpriteImage);imagesMap[id]=ImageRequest.getImage(imageRequestParameters,abortController)}yield Promise.all([...Object.values(jsonsMap),...Object.values(imagesMap)]);return doOnceCompleted(jsonsMap,imagesMap)}))}function doOnceCompleted(jsonsMap,imagesMap){return performance$1.__awaiter(this,void 0,void 0,(function*(){const result={};for(const spriteName in jsonsMap){result[spriteName]={};const context=browser.getImageCanvasContext((yield imagesMap[spriteName]).data);const json=(yield jsonsMap[spriteName]).data;for(const id in json){const{width:width,height:height,x:x,y:y,sdf:sdf,pixelRatio:pixelRatio,stretchX:stretchX,stretchY:stretchY,content:content}=json[id];const spriteData={width:width,height:height,x:x,y:y,context:context};result[spriteName][id]={data:null,pixelRatio:pixelRatio,sdf:sdf,stretchX:stretchX,stretchY:stretchY,content:content,spriteData:spriteData}}}return result}))}class Texture{constructor(context,image,format,options){this.context=context;this.format=format;this.texture=context.gl.createTexture();this.update(image,options)}update(image,options,position){const{width:width,height:height}=image;const resize=(!this.size||this.size[0]!==width||this.size[1]!==height)&&!position;const{context:context}=this;const{gl:gl}=context;this.useMipmap=Boolean(options&&options.useMipmap);gl.bindTexture(gl.TEXTURE_2D,this.texture);context.pixelStoreUnpackFlipY.set(false);context.pixelStoreUnpack.set(1);context.pixelStoreUnpackPremultiplyAlpha.set(this.format===gl.RGBA&&(!options||options.premultiply!==false));if(resize){this.size=[width,height];if(image instanceof HTMLImageElement||image instanceof HTMLCanvasElement||image instanceof HTMLVideoElement||image instanceof ImageData||performance$1.isImageBitmap(image)){gl.texImage2D(gl.TEXTURE_2D,0,this.format,this.format,gl.UNSIGNED_BYTE,image)}else{gl.texImage2D(gl.TEXTURE_2D,0,this.format,width,height,0,this.format,gl.UNSIGNED_BYTE,image.data)}}else{const{x:x,y:y}=position||{x:0,y:0};if(image instanceof HTMLImageElement||image instanceof HTMLCanvasElement||image instanceof HTMLVideoElement||image instanceof ImageData||performance$1.isImageBitmap(image)){gl.texSubImage2D(gl.TEXTURE_2D,0,x,y,gl.RGBA,gl.UNSIGNED_BYTE,image)}else{gl.texSubImage2D(gl.TEXTURE_2D,0,x,y,width,height,gl.RGBA,gl.UNSIGNED_BYTE,image.data)}}if(this.useMipmap&&this.isSizePowerOfTwo()){gl.generateMipmap(gl.TEXTURE_2D)}}bind(filter,wrap,minFilter){const{context:context}=this;const{gl:gl}=context;gl.bindTexture(gl.TEXTURE_2D,this.texture);if(minFilter===gl.LINEAR_MIPMAP_NEAREST&&!this.isSizePowerOfTwo()){minFilter=gl.LINEAR}if(filter!==this.filter){gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,filter);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,minFilter||filter);this.filter=filter}if(wrap!==this.wrap){gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,wrap);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,wrap);this.wrap=wrap}}isSizePowerOfTwo(){return this.size[0]===this.size[1]&&Math.log(this.size[0])/Math.LN2%1===0}destroy(){const{gl:gl}=this.context;gl.deleteTexture(this.texture);this.texture=null}}function renderStyleImage(image){const{userImage:userImage}=image;if(userImage&&userImage.render){const updated=userImage.render();if(updated){image.data.replace(new Uint8Array(userImage.data.buffer));return true}}return false}const padding=1;class ImageManager extends performance$1.Evented{constructor(){super();this.images={};this.updatedImages={};this.callbackDispatchedThisFrame={};this.loaded=false;this.requestors=[];this.patterns={};this.atlasImage=new performance$1.RGBAImage({width:1,height:1});this.dirty=true}isLoaded(){return this.loaded}setLoaded(loaded){if(this.loaded===loaded){return}this.loaded=loaded;if(loaded){for(const{ids:ids,promiseResolve:promiseResolve}of this.requestors){promiseResolve(this._getImagesForIds(ids))}this.requestors=[]}}getImage(id){const image=this.images[id];if(image&&!image.data&&image.spriteData){const spriteData=image.spriteData;image.data=new performance$1.RGBAImage({width:spriteData.width,height:spriteData.height},spriteData.context.getImageData(spriteData.x,spriteData.y,spriteData.width,spriteData.height).data);image.spriteData=null}return image}addImage(id,image){if(this.images[id])throw new Error(`Image id ${id} already exist, use updateImage instead`);if(this._validate(id,image)){this.images[id]=image}}_validate(id,image){let valid=true;const data=image.data||image.spriteData;if(!this._validateStretch(image.stretchX,data&&data.width)){this.fire(new performance$1.ErrorEvent(new Error(`Image "${id}" has invalid "stretchX" value`)));valid=false}if(!this._validateStretch(image.stretchY,data&&data.height)){this.fire(new performance$1.ErrorEvent(new Error(`Image "${id}" has invalid "stretchY" value`)));valid=false}if(!this._validateContent(image.content,image)){this.fire(new performance$1.ErrorEvent(new Error(`Image "${id}" has invalid "content" value`)));valid=false}return valid}_validateStretch(stretch,size){if(!stretch)return true;let last=0;for(const part of stretch){if(part[0]{let hasAllDependencies=true;if(!this.isLoaded()){for(const id of ids){if(!this.images[id]){hasAllDependencies=false}}}if(this.isLoaded()||hasAllDependencies){resolve(this._getImagesForIds(ids))}else{this.requestors.push({ids:ids,promiseResolve:resolve})}}))}_getImagesForIds(ids){const response={};for(const id of ids){let image=this.getImage(id);if(!image){this.fire(new performance$1.Event("styleimagemissing",{id:id}));image=this.getImage(id)}if(image){response[id]={data:image.data.clone(),pixelRatio:image.pixelRatio,sdf:image.sdf,version:image.version,stretchX:image.stretchX,stretchY:image.stretchY,content:image.content,hasRenderCallback:Boolean(image.userImage&&image.userImage.render)}}else{performance$1.warnOnce(`Image "${id}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`)}}return response}getPixelSize(){const{width:width,height:height}=this.atlasImage;return{width:width,height:height}}getPattern(id){const pattern=this.patterns[id];const image=this.getImage(id);if(!image){return null}if(pattern&&pattern.position.version===image.version){return pattern.position}if(!pattern){const w=image.data.width+padding*2;const h=image.data.height+padding*2;const bin={w:w,h:h,x:0,y:0};const position=new performance$1.ImagePosition(bin,image);this.patterns[id]={bin:bin,position:position}}else{pattern.position.version=image.version}this._updatePatternAtlas();return this.patterns[id].position}bind(context){const gl=context.gl;if(!this.atlasTexture){this.atlasTexture=new Texture(context,this.atlasImage,gl.RGBA)}else if(this.dirty){this.atlasTexture.update(this.atlasImage);this.dirty=false}this.atlasTexture.bind(gl.LINEAR,gl.CLAMP_TO_EDGE)}_updatePatternAtlas(){const bins=[];for(const id in this.patterns){bins.push(this.patterns[id].bin)}const{w:w,h:h}=performance$1.potpack(bins);const dst=this.atlasImage;dst.resize({width:w||1,height:h||1});for(const id in this.patterns){const{bin:bin}=this.patterns[id];const x=bin.x+padding;const y=bin.y+padding;const src=this.getImage(id).data;const w=src.width;const h=src.height;performance$1.RGBAImage.copy(src,dst,{x:0,y:0},{x:x,y:y},{width:w,height:h});performance$1.RGBAImage.copy(src,dst,{x:0,y:h-1},{x:x,y:y-1},{width:w,height:1});performance$1.RGBAImage.copy(src,dst,{x:0,y:0},{x:x,y:y+h},{width:w,height:1});performance$1.RGBAImage.copy(src,dst,{x:w-1,y:0},{x:x-1,y:y},{width:1,height:h});performance$1.RGBAImage.copy(src,dst,{x:0,y:0},{x:x+w,y:y},{width:1,height:h})}this.dirty=true}beginFrame(){this.callbackDispatchedThisFrame={}}dispatchRenderCallbacks(ids){for(const id of ids){if(this.callbackDispatchedThisFrame[id])continue;this.callbackDispatchedThisFrame[id]=true;const image=this.getImage(id);if(!image)performance$1.warnOnce(`Image with ID: "${id}" was not found`);const updated=renderStyleImage(image);if(updated){this.updateImage(id,image)}}}}function loadGlyphRange(fontstack,range,urlTemplate,requestManager){return performance$1.__awaiter(this,void 0,void 0,(function*(){const begin=range*256;const end=begin+255;const request=requestManager.transformRequest(urlTemplate.replace("{fontstack}",fontstack).replace("{range}",`${begin}-${end}`),ResourceType.Glyphs);const response=yield performance$1.getArrayBuffer(request,new AbortController);if(!response||!response.data){throw new Error(`Could not load glyph range. range: ${range}, ${begin}-${end}`)}const glyphs={};for(const glyph of performance$1.parseGlyphPbf(response.data)){glyphs[glyph.id]=glyph}return glyphs}))}const INF=1e20;class TinySDF{constructor({fontSize:fontSize=24,buffer:buffer=3,radius:radius=8,cutoff:cutoff=.25,fontFamily:fontFamily="sans-serif",fontWeight:fontWeight="normal",fontStyle:fontStyle="normal"}={}){this.buffer=buffer;this.cutoff=cutoff;this.radius=radius;const size=this.size=fontSize+buffer*4;const canvas=this._createCanvas(size);const ctx=this.ctx=canvas.getContext("2d",{willReadFrequently:true});ctx.font=`${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`;ctx.textBaseline="alphabetic";ctx.textAlign="left";ctx.fillStyle="black";this.gridOuter=new Float64Array(size*size);this.gridInner=new Float64Array(size*size);this.f=new Float64Array(size);this.z=new Float64Array(size+1);this.v=new Uint16Array(size)}_createCanvas(size){const canvas=document.createElement("canvas");canvas.width=canvas.height=size;return canvas}draw(char){const{width:glyphAdvance,actualBoundingBoxAscent:actualBoundingBoxAscent,actualBoundingBoxDescent:actualBoundingBoxDescent,actualBoundingBoxLeft:actualBoundingBoxLeft,actualBoundingBoxRight:actualBoundingBoxRight}=this.ctx.measureText(char);const glyphTop=Math.ceil(actualBoundingBoxAscent);const glyphLeft=0;const glyphWidth=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(actualBoundingBoxRight-actualBoundingBoxLeft)));const glyphHeight=Math.min(this.size-this.buffer,glyphTop+Math.ceil(actualBoundingBoxDescent));const width=glyphWidth+2*this.buffer;const height=glyphHeight+2*this.buffer;const len=Math.max(width*height,0);const data=new Uint8ClampedArray(len);const glyph={data:data,width:width,height:height,glyphWidth:glyphWidth,glyphHeight:glyphHeight,glyphTop:glyphTop,glyphLeft:glyphLeft,glyphAdvance:glyphAdvance};if(glyphWidth===0||glyphHeight===0)return glyph;const{ctx:ctx,buffer:buffer,gridInner:gridInner,gridOuter:gridOuter}=this;ctx.clearRect(buffer,buffer,glyphWidth,glyphHeight);ctx.fillText(char,buffer,buffer+glyphTop);const imgData=ctx.getImageData(buffer,buffer,glyphWidth,glyphHeight);gridOuter.fill(INF,0,len);gridInner.fill(0,0,len);for(let y=0;y0?d*d:0;gridInner[j]=d<0?d*d:0}}}edt(gridOuter,0,0,width,height,width,this.f,this.v,this.z);edt(gridInner,buffer,buffer,glyphWidth,glyphHeight,width,this.f,this.v,this.z);for(let i=0;i-1);k++;v[k]=q;z[k]=s;z[k+1]=INF}for(let q=0,k=0;q65535){throw new Error("glyphs > 65535 not supported")}if(entry.ranges[range]){return{stack:stack,id:id,glyph:glyph}}if(!this.url){throw new Error("glyphsUrl is not set")}if(!entry.requests[range]){const promise=GlyphManager.loadGlyphRange(stack,range,this.url,this.requestManager);entry.requests[range]=promise}const response=yield entry.requests[range];for(const id in response){if(!this._doesCharSupportLocalGlyph(+id)){entry.glyphs[+id]=response[+id]}}entry.ranges[range]=true;return{stack:stack,id:id,glyph:response[id]||null}}))}_doesCharSupportLocalGlyph(id){return!!this.localIdeographFontFamily&&(performance$1.unicodeBlockLookup["CJK Unified Ideographs"](id)||performance$1.unicodeBlockLookup["Hangul Syllables"](id)||performance$1.unicodeBlockLookup["Hiragana"](id)||performance$1.unicodeBlockLookup["Katakana"](id))}_tinySDF(entry,stack,id){const fontFamily=this.localIdeographFontFamily;if(!fontFamily){return}if(!this._doesCharSupportLocalGlyph(id)){return}const textureScale=2;let tinySDF=entry.tinySDF;if(!tinySDF){let fontWeight="400";if(/bold/i.test(stack)){fontWeight="900"}else if(/medium/i.test(stack)){fontWeight="500"}else if(/light/i.test(stack)){fontWeight="200"}tinySDF=entry.tinySDF=new GlyphManager.TinySDF({fontSize:24*textureScale,buffer:3*textureScale,radius:8*textureScale,cutoff:.25,fontFamily:fontFamily,fontWeight:fontWeight})}const char=tinySDF.draw(String.fromCharCode(id));const topAdjustment=27.5;const leftAdjustment=.5;return{id:id,bitmap:new performance$1.AlphaImage({width:char.width||30*textureScale,height:char.height||30*textureScale},char.data),metrics:{width:char.glyphWidth/textureScale||24,height:char.glyphHeight/textureScale||24,left:char.glyphLeft/textureScale+leftAdjustment||0,top:char.glyphTop/textureScale-topAdjustment||-8,advance:char.glyphAdvance/textureScale||24,isDoubleResolution:true}}}}GlyphManager.loadGlyphRange=loadGlyphRange;GlyphManager.TinySDF=TinySDF;class LightPositionProperty{constructor(){this.specification=performance$1.v8Spec.light.position}possiblyEvaluate(value,parameters){return performance$1.sphericalToCartesian(value.expression.evaluate(parameters))}interpolate(a,b,t){return{x:performance$1.interpolate.number(a.x,b.x,t),y:performance$1.interpolate.number(a.y,b.y,t),z:performance$1.interpolate.number(a.z,b.z,t)}}}const TRANSITION_SUFFIX="-transition";let lightProperties;class Light extends performance$1.Evented{constructor(lightOptions){super();lightProperties=lightProperties||new performance$1.Properties({anchor:new performance$1.DataConstantProperty(performance$1.v8Spec.light.anchor),position:new LightPositionProperty,color:new performance$1.DataConstantProperty(performance$1.v8Spec.light.color),intensity:new performance$1.DataConstantProperty(performance$1.v8Spec.light.intensity)});this._transitionable=new performance$1.Transitionable(lightProperties);this.setLight(lightOptions);this._transitioning=this._transitionable.untransitioned()}getLight(){return this._transitionable.serialize()}setLight(light,options={}){if(this._validate(performance$1.validateLight,light,options)){return}for(const name in light){const value=light[name];if(name.endsWith(TRANSITION_SUFFIX)){this._transitionable.setTransition(name.slice(0,-TRANSITION_SUFFIX.length),value)}else{this._transitionable.setValue(name,value)}}}updateTransitions(parameters){this._transitioning=this._transitionable.transitioned(parameters,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(parameters){this.properties=this._transitioning.possiblyEvaluate(parameters)}_validate(validate,value,options){if(options&&options.validate===false){return false}return performance$1.emitValidationErrors(this,validate.call(performance$1.validateStyle,{value:value,style:{glyphs:true,sprite:true},styleSpec:performance$1.v8Spec}))}}class LineAtlas{constructor(width,height){this.width=width;this.height=height;this.nextRow=0;this.data=new Uint8Array(this.width*this.height);this.dashEntry={}}getDash(dasharray,round){const key=dasharray.join(",")+String(round);if(!this.dashEntry[key]){this.dashEntry[key]=this.addDash(dasharray,round)}return this.dashEntry[key]}getDashRanges(dasharray,lineAtlasWidth,stretch){const oddDashArray=dasharray.length%2===1;const ranges=[];let left=oddDashArray?-dasharray[dasharray.length-1]*stretch:0;let right=dasharray[0]*stretch;let isDash=true;ranges.push({left:left,right:right,isDash:isDash,zeroLength:dasharray[0]===0});let currentDashLength=dasharray[0];for(let i=1;i1){range=ranges[++currIndex]}const distLeft=Math.abs(x-range.left);const distRight=Math.abs(x-range.right);const minDist=Math.min(distLeft,distRight);let signedDistance;const distMiddle=y/n*(halfStretch+1);if(range.isDash){const distEdge=halfStretch-Math.abs(distMiddle);signedDistance=Math.sqrt(minDist*minDist+distEdge*distEdge)}else{signedDistance=halfStretch-Math.sqrt(minDist*minDist+distMiddle*distMiddle)}this.data[index+x]=Math.max(0,Math.min(255,signedDistance+128))}}}addRegularDash(ranges){for(let i=ranges.length-1;i>=0;--i){const part=ranges[i];const next=ranges[i+1];if(part.zeroLength){ranges.splice(i,1)}else if(next&&next.isDash===part.isDash){next.left=part.left;ranges.splice(i,1)}}const first=ranges[0];const last=ranges[ranges.length-1];if(first.isDash===last.isDash){first.left=last.left-this.width;last.right=first.right+this.width}const index=this.width*this.nextRow;let currIndex=0;let range=ranges[currIndex];for(let x=0;x1){range=ranges[++currIndex]}const distLeft=Math.abs(x-range.left);const distRight=Math.abs(x-range.right);const minDist=Math.min(distLeft,distRight);const signedDistance=range.isDash?minDist:-minDist;this.data[index+x]=Math.max(0,Math.min(255,signedDistance+128))}}addDash(dasharray,round){const n=round?7:0;const height=2*n+1;if(this.nextRow+height>this.height){performance$1.warnOnce("LineAtlas out of space");return null}let length=0;for(let i=0;i{w.terminate()}));this.workers=null}}isPreloaded(){return!!this.active[PRELOAD_POOL_ID]}numActive(){return Object.keys(this.active).length}}const availableLogicalProcessors=Math.floor(browser.hardwareConcurrency/2);WorkerPool.workerCount=performance$1.isSafari(globalThis)?Math.max(Math.min(availableLogicalProcessors,3),1):1;let globalWorkerPool;function getGlobalWorkerPool(){if(!globalWorkerPool){globalWorkerPool=new WorkerPool}return globalWorkerPool}function prewarm(){const workerPool=getGlobalWorkerPool();workerPool.acquire(PRELOAD_POOL_ID)}function clearPrewarmedResources(){const pool=globalWorkerPool;if(pool){if(pool.isPreloaded()&&pool.numActive()===1){pool.release(PRELOAD_POOL_ID);globalWorkerPool=null}else{console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()")}}}class Dispatcher{constructor(workerPool,mapId){this.workerPool=workerPool;this.actors=[];this.currentActor=0;this.id=mapId;const workers=this.workerPool.acquire(mapId);for(let i=0;i{actor.remove()}));this.actors=[];if(mapRemoved)this.workerPool.release(this.id)}registerMessageHandler(type,handler){for(const actor of this.actors){actor.registerMessageHandler(type,handler)}}}let globalDispatcher;function getGlobalDispatcher(){if(!globalDispatcher){globalDispatcher=new Dispatcher(getGlobalWorkerPool(),performance$1.GLOBAL_DISPATCHER_ID);globalDispatcher.registerMessageHandler("getResource",((_mapId,params,abortController)=>performance$1.makeRequest(params,abortController)))}return globalDispatcher}function getPixelPosMatrix(transform,tileID){const t=performance$1.create();performance$1.translate(t,t,[1,1,0]);performance$1.scale(t,t,[transform.width*.5,transform.height*.5,1]);return performance$1.multiply(t,t,transform.calculatePosMatrix(tileID.toUnwrapped()))}function queryIncludes3DLayer(layers,styleLayers,sourceID){if(layers){for(const layerID of layers){const layer=styleLayers[layerID];if(layer&&layer.source===sourceID&&layer.type==="fill-extrusion"){return true}}}else{for(const key in styleLayers){const layer=styleLayers[key];if(layer.source===sourceID&&layer.type==="fill-extrusion"){return true}}}return false}function queryRenderedFeatures(sourceCache,styleLayers,serializedLayers,queryGeometry,params,transform){const has3DLayer=queryIncludes3DLayer(params&¶ms.layers,styleLayers,sourceCache.id);const maxPitchScaleFactor=transform.maxPitchScaleFactor();const tilesIn=sourceCache.tilesIn(queryGeometry,maxPitchScaleFactor,has3DLayer);tilesIn.sort(sortTilesIn);const renderedFeatureLayers=[];for(const tileIn of tilesIn){renderedFeatureLayers.push({wrappedTileID:tileIn.tileID.wrapped().key,queryResults:tileIn.tile.queryRenderedFeatures(styleLayers,serializedLayers,sourceCache._state,tileIn.queryGeometry,tileIn.cameraQueryGeometry,tileIn.scale,params,transform,maxPitchScaleFactor,getPixelPosMatrix(sourceCache.transform,tileIn.tileID))})}const result=mergeRenderedFeatureLayers(renderedFeatureLayers);for(const layerID in result){result[layerID].forEach((featureWrapper=>{const feature=featureWrapper.feature;const state=sourceCache.getFeatureState(feature.layer["source-layer"],feature.id);feature.source=feature.layer.source;if(feature.layer["source-layer"]){feature.sourceLayer=feature.layer["source-layer"]}feature.state=state}))}return result}function queryRenderedSymbols(styleLayers,serializedLayers,sourceCaches,queryGeometry,params,collisionIndex,retainedQueryData){const result={};const renderedSymbols=collisionIndex.queryRenderedSymbols(queryGeometry);const bucketQueryData=[];for(const bucketInstanceId of Object.keys(renderedSymbols).map(Number)){bucketQueryData.push(retainedQueryData[bucketInstanceId])}bucketQueryData.sort(sortTilesIn);for(const queryData of bucketQueryData){const bucketSymbols=queryData.featureIndex.lookupSymbolFeatures(renderedSymbols[queryData.bucketInstanceId],serializedLayers,queryData.bucketIndex,queryData.sourceLayerIndex,params.filter,params.layers,params.availableImages,styleLayers);for(const layerID in bucketSymbols){const resultFeatures=result[layerID]=result[layerID]||[];const layerSymbols=bucketSymbols[layerID];layerSymbols.sort(((a,b)=>{const featureSortOrder=queryData.featureSortOrder;if(featureSortOrder){const sortedA=featureSortOrder.indexOf(a.featureIndex);const sortedB=featureSortOrder.indexOf(b.featureIndex);return sortedB-sortedA}else{return b.featureIndex-a.featureIndex}}));for(const symbolFeature of layerSymbols){resultFeatures.push(symbolFeature)}}}for(const layerName in result){result[layerName].forEach((featureWrapper=>{const feature=featureWrapper.feature;const layer=styleLayers[layerName];const sourceCache=sourceCaches[layer.source];const state=sourceCache.getFeatureState(feature.layer["source-layer"],feature.id);feature.source=feature.layer.source;if(feature.layer["source-layer"]){feature.sourceLayer=feature.layer["source-layer"]}feature.state=state}))}return result}function querySourceFeatures(sourceCache,params){const tiles=sourceCache.getRenderableIds().map((id=>sourceCache.getTileByID(id)));const result=[];const dataTiles={};for(let i=0;ilayer.id))}return result}))}class LngLatBounds{constructor(sw,ne){if(!sw){}else if(ne){this.setSouthWest(sw).setNorthEast(ne)}else if(Array.isArray(sw)){if(sw.length===4){this.setSouthWest([sw[0],sw[1]]).setNorthEast([sw[2],sw[3]])}else{this.setSouthWest(sw[0]).setNorthEast(sw[1])}}}setNorthEast(ne){this._ne=ne instanceof performance$1.LngLat?new performance$1.LngLat(ne.lng,ne.lat):performance$1.LngLat.convert(ne);return this}setSouthWest(sw){this._sw=sw instanceof performance$1.LngLat?new performance$1.LngLat(sw.lng,sw.lat):performance$1.LngLat.convert(sw);return this}extend(obj){const sw=this._sw,ne=this._ne;let sw2,ne2;if(obj instanceof performance$1.LngLat){sw2=obj;ne2=obj}else if(obj instanceof LngLatBounds){sw2=obj._sw;ne2=obj._ne;if(!sw2||!ne2)return this}else{if(Array.isArray(obj)){if(obj.length===4||obj.every(Array.isArray)){const lngLatBoundsObj=obj;return this.extend(LngLatBounds.convert(lngLatBoundsObj))}else{const lngLatObj=obj;return this.extend(performance$1.LngLat.convert(lngLatObj))}}else if(obj&&("lng"in obj||"lon"in obj)&&"lat"in obj){return this.extend(performance$1.LngLat.convert(obj))}return this}if(!sw&&!ne){this._sw=new performance$1.LngLat(sw2.lng,sw2.lat);this._ne=new performance$1.LngLat(ne2.lng,ne2.lat)}else{sw.lng=Math.min(sw2.lng,sw.lng);sw.lat=Math.min(sw2.lat,sw.lat);ne.lng=Math.max(ne2.lng,ne.lng);ne.lat=Math.max(ne2.lat,ne.lat)}return this}getCenter(){return new performance$1.LngLat((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new performance$1.LngLat(this.getWest(),this.getNorth())}getSouthEast(){return new performance$1.LngLat(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return[this._sw.toArray(),this._ne.toArray()]}toString(){return`LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return!(this._sw&&this._ne)}contains(lnglat){const{lng:lng,lat:lat}=performance$1.LngLat.convert(lnglat);const containsLatitude=this._sw.lat<=lat&&lat<=this._ne.lat;let containsLongitude=this._sw.lng<=lng&&lng<=this._ne.lng;if(this._sw.lng>this._ne.lng){containsLongitude=this._sw.lng>=lng&&lng>=this._ne.lng}return containsLatitude&&containsLongitude}static convert(input){if(input instanceof LngLatBounds)return input;if(!input)return input;return new LngLatBounds(input)}static fromLngLat(center,radius=0){const earthCircumferenceInMetersAtEquator=40075017;const latAccuracy=360*radius/earthCircumferenceInMetersAtEquator,lngAccuracy=latAccuracy/Math.cos(Math.PI/180*center.lat);return new LngLatBounds(new performance$1.LngLat(center.lng-lngAccuracy,center.lat-latAccuracy),new performance$1.LngLat(center.lng+lngAccuracy,center.lat+latAccuracy))}}class TileBounds{constructor(bounds,minzoom,maxzoom){this.bounds=LngLatBounds.convert(this.validateBounds(bounds));this.minzoom=minzoom||0;this.maxzoom=maxzoom||24}validateBounds(bounds){if(!Array.isArray(bounds)||bounds.length!==4)return[-180,-90,180,90];return[Math.max(-180,bounds[0]),Math.max(-90,bounds[1]),Math.min(180,bounds[2]),Math.min(90,bounds[3])]}contains(tileID){const worldSize=Math.pow(2,tileID.z);const level={minX:Math.floor(performance$1.mercatorXfromLng(this.bounds.getWest())*worldSize),minY:Math.floor(performance$1.mercatorYfromLat(this.bounds.getNorth())*worldSize),maxX:Math.ceil(performance$1.mercatorXfromLng(this.bounds.getEast())*worldSize),maxY:Math.ceil(performance$1.mercatorYfromLat(this.bounds.getSouth())*worldSize)};const hit=tileID.x>=level.minX&&tileID.x=level.minY&&tileID.y{this._options.tiles=tiles}));return this}setUrl(url){this.setSourceProperty((()=>{this.url=url;this._options.url=url}));return this}onRemove(){if(this._tileJSONRequest){this._tileJSONRequest.abort();this._tileJSONRequest=null}}serialize(){return performance$1.extend({},this._options)}loadTile(tile){return performance$1.__awaiter(this,void 0,void 0,(function*(){const url=tile.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);const params={request:this.map._requestManager.transformRequest(url,ResourceType.Tile),uid:tile.uid,tileID:tile.tileID,zoom:tile.tileID.overscaledZ,tileSize:this.tileSize*tile.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId};params.request.collectResourceTiming=this._collectResourceTiming;let messageType="reloadTile";if(!tile.actor||tile.state==="expired"){tile.actor=this.dispatcher.getActor();messageType="loadTile"}else if(tile.state==="loading"){return new Promise(((resolve,reject)=>{tile.reloadPromise={resolve:resolve,reject:reject}}))}tile.abortController=new AbortController;try{const data=yield tile.actor.sendAsync({type:messageType,data:params},tile.abortController);delete tile.abortController;if(tile.aborted){return}this._afterTileLoadWorkerResponse(tile,data)}catch(err){delete tile.abortController;if(tile.aborted){return}if(err&&err.status!==404){throw err}this._afterTileLoadWorkerResponse(tile,null)}}))}_afterTileLoadWorkerResponse(tile,data){if(data&&data.resourceTiming){tile.resourceTiming=data.resourceTiming}if(data&&this.map._refreshExpiredTiles){tile.setExpiryData(data)}tile.loadVectorData(data,this.map.painter);if(tile.reloadPromise){const reloadPromise=tile.reloadPromise;tile.reloadPromise=null;this.loadTile(tile).then(reloadPromise.resolve).catch(reloadPromise.reject)}}abortTile(tile){return performance$1.__awaiter(this,void 0,void 0,(function*(){if(tile.abortController){tile.abortController.abort();delete tile.abortController}if(tile.actor){yield tile.actor.sendAsync({type:"abortTile",data:{uid:tile.uid,type:this.type,source:this.id}})}}))}unloadTile(tile){return performance$1.__awaiter(this,void 0,void 0,(function*(){tile.unloadVectorData();if(tile.actor){yield tile.actor.sendAsync({type:"removeTile",data:{uid:tile.uid,type:this.type,source:this.id}})}}))}hasTransition(){return false}}class RasterTileSource extends performance$1.Evented{constructor(id,options,dispatcher,eventedParent){super();this.id=id;this.dispatcher=dispatcher;this.setEventedParent(eventedParent);this.type="raster";this.minzoom=0;this.maxzoom=22;this.roundZoom=true;this.scheme="xyz";this.tileSize=512;this._loaded=false;this._options=performance$1.extend({type:"raster"},options);performance$1.extend(this,performance$1.pick(options,["url","scheme","tileSize"]))}load(){return performance$1.__awaiter(this,void 0,void 0,(function*(){this._loaded=false;this.fire(new performance$1.Event("dataloading",{dataType:"source"}));this._tileJSONRequest=new AbortController;try{const tileJSON=yield loadTileJson(this._options,this.map._requestManager,this._tileJSONRequest);this._tileJSONRequest=null;this._loaded=true;if(tileJSON){performance$1.extend(this,tileJSON);if(tileJSON.bounds)this.tileBounds=new TileBounds(tileJSON.bounds,this.minzoom,this.maxzoom);this.fire(new performance$1.Event("data",{dataType:"source",sourceDataType:"metadata"}));this.fire(new performance$1.Event("data",{dataType:"source",sourceDataType:"content"}))}}catch(err){this._tileJSONRequest=null;this.fire(new performance$1.ErrorEvent(err))}}))}loaded(){return this._loaded}onAdd(map){this.map=map;this.load()}onRemove(){if(this._tileJSONRequest){this._tileJSONRequest.abort();this._tileJSONRequest=null}}setSourceProperty(callback){if(this._tileJSONRequest){this._tileJSONRequest.abort();this._tileJSONRequest=null}callback();this.load()}setTiles(tiles){this.setSourceProperty((()=>{this._options.tiles=tiles}));return this}setUrl(url){this.setSourceProperty((()=>{this.url=url;this._options.url=url}));return this}serialize(){return performance$1.extend({},this._options)}hasTile(tileID){return!this.tileBounds||this.tileBounds.contains(tileID.canonical)}loadTile(tile){return performance$1.__awaiter(this,void 0,void 0,(function*(){const url=tile.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);tile.abortController=new AbortController;try{const response=yield ImageRequest.getImage(this.map._requestManager.transformRequest(url,ResourceType.Tile),tile.abortController,this.map._refreshExpiredTiles);delete tile.abortController;if(tile.aborted){tile.state="unloaded";return}if(response&&response.data){if(this.map._refreshExpiredTiles&&response.cacheControl&&response.expires){tile.setExpiryData({cacheControl:response.cacheControl,expires:response.expires})}const context=this.map.painter.context;const gl=context.gl;const img=response.data;tile.texture=this.map.painter.getTileTexture(img.width);if(tile.texture){tile.texture.update(img,{useMipmap:true})}else{tile.texture=new Texture(context,img,gl.RGBA,{useMipmap:true});tile.texture.bind(gl.LINEAR,gl.CLAMP_TO_EDGE,gl.LINEAR_MIPMAP_NEAREST);if(context.extTextureFilterAnisotropic){gl.texParameterf(gl.TEXTURE_2D,context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,context.extTextureFilterAnisotropicMax)}}tile.state="loaded"}}catch(err){delete tile.abortController;if(tile.aborted){tile.state="unloaded"}else if(err){tile.state="errored";throw err}}}))}abortTile(tile){return performance$1.__awaiter(this,void 0,void 0,(function*(){if(tile.abortController){tile.abortController.abort();delete tile.abortController}}))}unloadTile(tile){return performance$1.__awaiter(this,void 0,void 0,(function*(){if(tile.texture){this.map.painter.saveTileTexture(tile.texture)}}))}hasTransition(){return false}}class RasterDEMTileSource extends RasterTileSource{constructor(id,options,dispatcher,eventedParent){super(id,options,dispatcher,eventedParent);this.type="raster-dem";this.maxzoom=22;this._options=performance$1.extend({type:"raster-dem"},options);this.encoding=options.encoding||"mapbox";this.redFactor=options.redFactor;this.greenFactor=options.greenFactor;this.blueFactor=options.blueFactor;this.baseShift=options.baseShift}loadTile(tile){return performance$1.__awaiter(this,void 0,void 0,(function*(){const url=tile.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);const request=this.map._requestManager.transformRequest(url,ResourceType.Tile);tile.neighboringTiles=this._getNeighboringTiles(tile.tileID);tile.abortController=new AbortController;try{const response=yield ImageRequest.getImage(request,tile.abortController,this.map._refreshExpiredTiles);delete tile.abortController;if(tile.aborted){tile.state="unloaded";return}if(response&&response.data){const img=response.data;if(this.map._refreshExpiredTiles&&response.cacheControl&&response.expires){tile.setExpiryData({cacheControl:response.cacheControl,expires:response.expires})}const transfer=performance$1.isImageBitmap(img)&&performance$1.offscreenCanvasSupported();const rawImageData=transfer?img:yield this.readImageNow(img);const params={type:this.type,uid:tile.uid,source:this.id,rawImageData:rawImageData,encoding:this.encoding,redFactor:this.redFactor,greenFactor:this.greenFactor,blueFactor:this.blueFactor,baseShift:this.baseShift};if(!tile.actor||tile.state==="expired"){tile.actor=this.dispatcher.getActor();const data=yield tile.actor.sendAsync({type:"loadDEMTile",data:params});tile.dem=data;tile.needsHillshadePrepare=true;tile.needsTerrainPrepare=true;tile.state="loaded"}}}catch(err){delete tile.abortController;if(tile.aborted){tile.state="unloaded"}else if(err){tile.state="errored";throw err}}}))}readImageNow(img){return performance$1.__awaiter(this,void 0,void 0,(function*(){if(typeof VideoFrame!=="undefined"&&performance$1.isOffscreenCanvasDistorted()){const width=img.width+2;const height=img.height+2;try{return new performance$1.RGBAImage({width:width,height:height},yield performance$1.readImageUsingVideoFrame(img,-1,-1,width,height))}catch(e){}}return browser.getImageData(img,1)}))}_getNeighboringTiles(tileID){const canonical=tileID.canonical;const dim=Math.pow(2,canonical.z);const px=(canonical.x-1+dim)%dim;const pxw=canonical.x===0?tileID.wrap-1:tileID.wrap;const nx=(canonical.x+1+dim)%dim;const nxw=canonical.x+1===dim?tileID.wrap+1:tileID.wrap;const neighboringTiles={};neighboringTiles[new performance$1.OverscaledTileID(tileID.overscaledZ,pxw,canonical.z,px,canonical.y).key]={backfilled:false};neighboringTiles[new performance$1.OverscaledTileID(tileID.overscaledZ,nxw,canonical.z,nx,canonical.y).key]={backfilled:false};if(canonical.y>0){neighboringTiles[new performance$1.OverscaledTileID(tileID.overscaledZ,pxw,canonical.z,px,canonical.y-1).key]={backfilled:false};neighboringTiles[new performance$1.OverscaledTileID(tileID.overscaledZ,tileID.wrap,canonical.z,canonical.x,canonical.y-1).key]={backfilled:false};neighboringTiles[new performance$1.OverscaledTileID(tileID.overscaledZ,nxw,canonical.z,nx,canonical.y-1).key]={backfilled:false}}if(canonical.y+10){performance$1.extend(data,{resourceTiming:resourceTiming})}this.fire(new performance$1.Event("data",Object.assign(Object.assign({},data),{sourceDataType:"metadata"})));this.fire(new performance$1.Event("data",Object.assign(Object.assign({},data),{sourceDataType:"content"})))}catch(err){this._pendingLoads--;if(this._removed){this.fire(new performance$1.Event("dataabort",{dataType:"source"}));return}this.fire(new performance$1.ErrorEvent(err))}}))}loaded(){return this._pendingLoads===0}loadTile(tile){return performance$1.__awaiter(this,void 0,void 0,(function*(){const message=!tile.actor?"loadTile":"reloadTile";tile.actor=this.actor;const params={type:this.type,uid:tile.uid,tileID:tile.tileID,zoom:tile.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId};tile.abortController=new AbortController;const data=yield this.actor.sendAsync({type:message,data:params},tile.abortController);delete tile.abortController;tile.unloadVectorData();if(!tile.aborted){tile.loadVectorData(data,this.map.painter,message==="reloadTile")}}))}abortTile(tile){return performance$1.__awaiter(this,void 0,void 0,(function*(){if(tile.abortController){tile.abortController.abort();delete tile.abortController}tile.aborted=true}))}unloadTile(tile){return performance$1.__awaiter(this,void 0,void 0,(function*(){tile.unloadVectorData();yield this.actor.sendAsync({type:"removeTile",data:{uid:tile.uid,type:this.type,source:this.id}})}))}onRemove(){this._removed=true;this.actor.sendAsync({type:"removeSource",data:{type:this.type,source:this.id}})}serialize(){return performance$1.extend({},this._options,{type:this.type,data:this._data})}hasTransition(){return false}}var rasterBoundsAttributes=performance$1.createLayout([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]);class ImageSource extends performance$1.Evented{constructor(id,options,dispatcher,eventedParent){super();this.id=id;this.dispatcher=dispatcher;this.coordinates=options.coordinates;this.type="image";this.minzoom=0;this.maxzoom=22;this.tileSize=512;this.tiles={};this._loaded=false;this.setEventedParent(eventedParent);this.options=options}load(newCoordinates){return performance$1.__awaiter(this,void 0,void 0,(function*(){this._loaded=false;this.fire(new performance$1.Event("dataloading",{dataType:"source"}));this.url=this.options.url;this._request=new AbortController;try{const image=yield ImageRequest.getImage(this.map._requestManager.transformRequest(this.url,ResourceType.Image),this._request);this._request=null;this._loaded=true;if(image&&image.data){this.image=image.data;if(newCoordinates){this.coordinates=newCoordinates}this._finishLoading()}}catch(err){this._request=null;this.fire(new performance$1.ErrorEvent(err))}}))}loaded(){return this._loaded}updateImage(options){if(!options.url){return this}if(this._request){this._request.abort();this._request=null}this.options.url=options.url;this.load(options.coordinates).finally((()=>{this.texture=null}));return this}_finishLoading(){if(this.map){this.setCoordinates(this.coordinates);this.fire(new performance$1.Event("data",{dataType:"source",sourceDataType:"metadata"}))}}onAdd(map){this.map=map;this.load()}onRemove(){if(this._request){this._request.abort();this._request=null}}setCoordinates(coordinates){this.coordinates=coordinates;const cornerCoords=coordinates.map(performance$1.MercatorCoordinate.fromLngLat);this.tileID=getCoordinatesCenterTileID(cornerCoords);this.minzoom=this.maxzoom=this.tileID.z;const tileCoords=cornerCoords.map((coord=>this.tileID.getTilePoint(coord)._round()));this._boundsArray=new performance$1.RasterBoundsArray;this._boundsArray.emplaceBack(tileCoords[0].x,tileCoords[0].y,0,0);this._boundsArray.emplaceBack(tileCoords[1].x,tileCoords[1].y,performance$1.EXTENT,0);this._boundsArray.emplaceBack(tileCoords[3].x,tileCoords[3].y,0,performance$1.EXTENT);this._boundsArray.emplaceBack(tileCoords[2].x,tileCoords[2].y,performance$1.EXTENT,performance$1.EXTENT);if(this.boundsBuffer){this.boundsBuffer.destroy();delete this.boundsBuffer}this.fire(new performance$1.Event("data",{dataType:"source",sourceDataType:"content"}));return this}prepare(){if(Object.keys(this.tiles).length===0||!this.image){return}const context=this.map.painter.context;const gl=context.gl;if(!this.boundsBuffer){this.boundsBuffer=context.createVertexBuffer(this._boundsArray,rasterBoundsAttributes.members)}if(!this.boundsSegments){this.boundsSegments=performance$1.SegmentVector.simpleSegment(0,0,4,2)}if(!this.texture){this.texture=new Texture(context,this.image,gl.RGBA);this.texture.bind(gl.LINEAR,gl.CLAMP_TO_EDGE)}let newTilesLoaded=false;for(const w in this.tiles){const tile=this.tiles[w];if(tile.state!=="loaded"){tile.state="loaded";tile.texture=this.texture;newTilesLoaded=true}}if(newTilesLoaded){this.fire(new performance$1.Event("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}))}}loadTile(tile){return performance$1.__awaiter(this,void 0,void 0,(function*(){if(this.tileID&&this.tileID.equals(tile.tileID.canonical)){this.tiles[String(tile.tileID.wrap)]=tile;tile.buckets={}}else{tile.state="errored"}}))}serialize(){return{type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return false}}function getCoordinatesCenterTileID(coords){let minX=Infinity;let minY=Infinity;let maxX=-Infinity;let maxY=-Infinity;for(const coord of coords){minX=Math.min(minX,coord.x);minY=Math.min(minY,coord.y);maxX=Math.max(maxX,coord.x);maxY=Math.max(maxY,coord.y)}const dx=maxX-minX;const dy=maxY-minY;const dMax=Math.max(dx,dy);const zoom=Math.max(0,Math.floor(-Math.log(dMax)/Math.LN2));const tilesAtZoom=Math.pow(2,zoom);return new performance$1.CanonicalTileID(zoom,Math.floor((minX+maxX)/2*tilesAtZoom),Math.floor((minY+maxY)/2*tilesAtZoom))}class VideoSource extends ImageSource{constructor(id,options,dispatcher,eventedParent){super(id,options,dispatcher,eventedParent);this.roundZoom=true;this.type="video";this.options=options}load(){return performance$1.__awaiter(this,void 0,void 0,(function*(){this._loaded=false;const options=this.options;this.urls=[];for(const url of options.urls){this.urls.push(this.map._requestManager.transformRequest(url,ResourceType.Source).url)}try{const video=yield performance$1.getVideo(this.urls);this._loaded=true;if(!video){return}this.video=video;this.video.loop=true;this.video.addEventListener("playing",(()=>{this.map.triggerRepaint()}));if(this.map){this.video.play()}this._finishLoading()}catch(err){this.fire(new performance$1.ErrorEvent(err))}}))}pause(){if(this.video){this.video.pause()}}play(){if(this.video){this.video.play()}}seek(seconds){if(this.video){const seekableRange=this.video.seekable;if(secondsseekableRange.end(0)){this.fire(new performance$1.ErrorEvent(new performance$1.ValidationError(`sources.${this.id}`,null,`Playback for this video can be set only between the ${seekableRange.start(0)} and ${seekableRange.end(0)}-second mark.`)))}else this.video.currentTime=seconds}}getVideo(){return this.video}onAdd(map){if(this.map)return;this.map=map;this.load();if(this.video){this.video.play();this.setCoordinates(this.coordinates)}}prepare(){if(Object.keys(this.tiles).length===0||this.video.readyState<2){return}const context=this.map.painter.context;const gl=context.gl;if(!this.boundsBuffer){this.boundsBuffer=context.createVertexBuffer(this._boundsArray,rasterBoundsAttributes.members)}if(!this.boundsSegments){this.boundsSegments=performance$1.SegmentVector.simpleSegment(0,0,4,2)}if(!this.texture){this.texture=new Texture(context,this.video,gl.RGBA);this.texture.bind(gl.LINEAR,gl.CLAMP_TO_EDGE)}else if(!this.video.paused){this.texture.bind(gl.LINEAR,gl.CLAMP_TO_EDGE);gl.texSubImage2D(gl.TEXTURE_2D,0,0,0,gl.RGBA,gl.UNSIGNED_BYTE,this.video)}let newTilesLoaded=false;for(const w in this.tiles){const tile=this.tiles[w];if(tile.state!=="loaded"){tile.state="loaded";tile.texture=this.texture;newTilesLoaded=true}}if(newTilesLoaded){this.fire(new performance$1.Event("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}))}}serialize(){return{type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}}class CanvasSource extends ImageSource{constructor(id,options,dispatcher,eventedParent){super(id,options,dispatcher,eventedParent);if(!options.coordinates){this.fire(new performance$1.ErrorEvent(new performance$1.ValidationError(`sources.${id}`,null,'missing required property "coordinates"')))}else if(!Array.isArray(options.coordinates)||options.coordinates.length!==4||options.coordinates.some((c=>!Array.isArray(c)||c.length!==2||c.some((l=>typeof l!=="number"))))){this.fire(new performance$1.ErrorEvent(new performance$1.ValidationError(`sources.${id}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs')))}if(options.animate&&typeof options.animate!=="boolean"){this.fire(new performance$1.ErrorEvent(new performance$1.ValidationError(`sources.${id}`,null,'optional "animate" property must be a boolean value')))}if(!options.canvas){this.fire(new performance$1.ErrorEvent(new performance$1.ValidationError(`sources.${id}`,null,'missing required property "canvas"')))}else if(typeof options.canvas!=="string"&&!(options.canvas instanceof HTMLCanvasElement)){this.fire(new performance$1.ErrorEvent(new performance$1.ValidationError(`sources.${id}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance')))}this.options=options;this.animate=options.animate!==undefined?options.animate:true}load(){return performance$1.__awaiter(this,void 0,void 0,(function*(){this._loaded=true;if(!this.canvas){this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)}this.width=this.canvas.width;this.height=this.canvas.height;if(this._hasInvalidDimensions()){this.fire(new performance$1.ErrorEvent(new Error("Canvas dimensions cannot be less than or equal to zero.")));return}this.play=function(){this._playing=true;this.map.triggerRepaint()};this.pause=function(){if(this._playing){this.prepare();this._playing=false}};this._finishLoading()}))}getCanvas(){return this.canvas}onAdd(map){this.map=map;this.load();if(this.canvas){if(this.animate)this.play()}}onRemove(){this.pause()}prepare(){let resize=false;if(this.canvas.width!==this.width){this.width=this.canvas.width;resize=true}if(this.canvas.height!==this.height){this.height=this.canvas.height;resize=true}if(this._hasInvalidDimensions())return;if(Object.keys(this.tiles).length===0)return;const context=this.map.painter.context;const gl=context.gl;if(!this.boundsBuffer){this.boundsBuffer=context.createVertexBuffer(this._boundsArray,rasterBoundsAttributes.members)}if(!this.boundsSegments){this.boundsSegments=performance$1.SegmentVector.simpleSegment(0,0,4,2)}if(!this.texture){this.texture=new Texture(context,this.canvas,gl.RGBA,{premultiply:true})}else if(resize||this._playing){this.texture.update(this.canvas,{premultiply:true})}let newTilesLoaded=false;for(const w in this.tiles){const tile=this.tiles[w];if(tile.state!=="loaded"){tile.state="loaded";tile.texture=this.texture;newTilesLoaded=true}}if(newTilesLoaded){this.fire(new performance$1.Event("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}))}}serialize(){return{type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const x of[this.canvas.width,this.canvas.height]){if(isNaN(x)||x<=0)return true}return false}}const registeredSources={};const create=(id,specification,dispatcher,eventedParent)=>{const Class=getSourceType(specification.type);const source=new Class(id,specification,dispatcher,eventedParent);if(source.id!==id){throw new Error(`Expected Source id to be ${id} instead of ${source.id}`)}return source};const getSourceType=name=>{switch(name){case"geojson":return GeoJSONSource;case"image":return ImageSource;case"raster":return RasterTileSource;case"raster-dem":return RasterDEMTileSource;case"vector":return VectorTileSource;case"video":return VideoSource;case"canvas":return CanvasSource}return registeredSources[name]};const setSourceType=(name,type)=>{registeredSources[name]=type};const addSourceType=(name,SourceType)=>performance$1.__awaiter(void 0,void 0,void 0,(function*(){if(getSourceType(name)){throw new Error(`A source type called "${name}" already exists.`)}setSourceType(name,SourceType)}));function deserialize(input,style){const output={};if(!style)return output;for(const bucket of input){const layers=bucket.layerIds.map((id=>style.getLayer(id))).filter(Boolean);if(layers.length===0){continue}bucket.layers=layers;if(bucket.stateDependentLayerIds){bucket.stateDependentLayers=bucket.stateDependentLayerIds.map((lId=>layers.filter((l=>l.id===lId))[0]))}for(const layer of layers){output[layer.id]=bucket}}return output}class RTLMainThreadPlugin extends performance$1.Evented{constructor(){super(...arguments);this.pluginStatus="unavailable";this.pluginURL=null;this.dispatcher=getGlobalDispatcher();this.queue=[]}_sendPluginStateToWorker(){return performance$1.__awaiter(this,void 0,void 0,(function*(){yield this.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:this.pluginStatus,pluginURL:this.pluginURL});this.fire(new performance$1.Event("pluginStateChange",{pluginStatus:this.pluginStatus,pluginURL:this.pluginURL}))}))}getRTLTextPluginStatus(){return this.pluginStatus}clearRTLTextPlugin(){this.pluginStatus="unavailable";this.pluginURL=null}setRTLTextPlugin(url,deferred=false){return performance$1.__awaiter(this,void 0,void 0,(function*(){if(this.pluginStatus==="deferred"||this.pluginStatus==="loading"||this.pluginStatus==="loaded"){throw new Error("setRTLTextPlugin cannot be called multiple times.")}this.pluginURL=browser.resolveURL(url);this.pluginStatus="deferred";yield this._sendPluginStateToWorker();if(!deferred){yield this._downloadRTLTextPlugin()}}))}_downloadRTLTextPlugin(){return performance$1.__awaiter(this,void 0,void 0,(function*(){if(this.pluginStatus!=="deferred"||!this.pluginURL){throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified")}try{this.pluginStatus="loading";yield this._sendPluginStateToWorker();yield performance$1.getArrayBuffer({url:this.pluginURL},new AbortController);this.pluginStatus="loaded"}catch(_a){this.pluginStatus="error"}yield this._sendPluginStateToWorker()}))}lazyLoadRTLTextPlugin(){return performance$1.__awaiter(this,void 0,void 0,(function*(){if(this.pluginStatus==="deferred"){yield this._downloadRTLTextPlugin()}}))}}let rtlMainThreadPlugin=null;function rtlMainThreadPluginFactory(){if(!rtlMainThreadPlugin){rtlMainThreadPlugin=new RTLMainThreadPlugin}return rtlMainThreadPlugin}const CLOCK_SKEW_RETRY_TIMEOUT=3e4;class Tile{constructor(tileID,size){this.timeAdded=0;this.fadeEndTime=0;this.tileID=tileID;this.uid=performance$1.uniqueId();this.uses=0;this.tileSize=size;this.buckets={};this.expirationTime=null;this.queryPadding=0;this.hasSymbolBuckets=false;this.hasRTLText=false;this.dependencies={};this.rtt=[];this.rttCoords={};this.expiredRequestCount=0;this.state="loading"}registerFadeDuration(duration){const fadeEndTime=duration+this.timeAdded;if(fadeEndTimenow){isExpired=false}else if(!prior){isExpired=true}else if(this.expirationTime{this.remove(tileID,dataWrapper)}),expiryTimeout)}this.data[key].push(dataWrapper);this.order.push(key);if(this.order.length>this.max){const removedData=this._getAndRemoveByKey(this.order[0]);if(removedData)this.onRemove(removedData)}return this}has(tileID){return tileID.wrapped().key in this.data}getAndRemove(tileID){if(!this.has(tileID)){return null}return this._getAndRemoveByKey(tileID.wrapped().key)}_getAndRemoveByKey(key){const data=this.data[key].shift();if(data.timeout)clearTimeout(data.timeout);if(this.data[key].length===0){delete this.data[key]}this.order.splice(this.order.indexOf(key),1);return data.value}getByKey(key){const data=this.data[key];return data?data[0].value:null}get(tileID){if(!this.has(tileID)){return null}const data=this.data[tileID.wrapped().key][0];return data.value}remove(tileID,value){if(!this.has(tileID)){return this}const key=tileID.wrapped().key;const dataIndex=value===undefined?0:this.data[key].indexOf(value);const data=this.data[key][dataIndex];this.data[key].splice(dataIndex,1);if(data.timeout)clearTimeout(data.timeout);if(this.data[key].length===0){delete this.data[key]}this.onRemove(data.value);this.order.splice(this.order.indexOf(key),1);return this}setMaxSize(max){this.max=max;while(this.order.length>this.max){const removedData=this._getAndRemoveByKey(this.order[0]);if(removedData)this.onRemove(removedData)}return this}filter(filterFn){const removed=[];for(const key in this.data){for(const entry of this.data[key]){if(!filterFn(entry.value)){removed.push(entry)}}}for(const r of removed){this.remove(r.value.tileID,r)}}}class SourceFeatureState{constructor(){this.state={};this.stateChanges={};this.deletedStates={}}updateState(sourceLayer,featureId,newState){const feature=String(featureId);this.stateChanges[sourceLayer]=this.stateChanges[sourceLayer]||{};this.stateChanges[sourceLayer][feature]=this.stateChanges[sourceLayer][feature]||{};performance$1.extend(this.stateChanges[sourceLayer][feature],newState);if(this.deletedStates[sourceLayer]===null){this.deletedStates[sourceLayer]={};for(const ft in this.state[sourceLayer]){if(ft!==feature)this.deletedStates[sourceLayer][ft]=null}}else{const featureDeletionQueued=this.deletedStates[sourceLayer]&&this.deletedStates[sourceLayer][feature]===null;if(featureDeletionQueued){this.deletedStates[sourceLayer][feature]={};for(const prop in this.state[sourceLayer][feature]){if(!newState[prop])this.deletedStates[sourceLayer][feature][prop]=null}}else{for(const key in newState){const deletionInQueue=this.deletedStates[sourceLayer]&&this.deletedStates[sourceLayer][feature]&&this.deletedStates[sourceLayer][feature][key]===null;if(deletionInQueue)delete this.deletedStates[sourceLayer][feature][key]}}}}removeFeatureState(sourceLayer,featureId,key){const sourceLayerDeleted=this.deletedStates[sourceLayer]===null;if(sourceLayerDeleted)return;const feature=String(featureId);this.deletedStates[sourceLayer]=this.deletedStates[sourceLayer]||{};if(key&&featureId!==undefined){if(this.deletedStates[sourceLayer][feature]!==null){this.deletedStates[sourceLayer][feature]=this.deletedStates[sourceLayer][feature]||{};this.deletedStates[sourceLayer][feature][key]=null}}else if(featureId!==undefined){const updateInQueue=this.stateChanges[sourceLayer]&&this.stateChanges[sourceLayer][feature];if(updateInQueue){this.deletedStates[sourceLayer][feature]={};for(key in this.stateChanges[sourceLayer][feature])this.deletedStates[sourceLayer][feature][key]=null}else{this.deletedStates[sourceLayer][feature]=null}}else{this.deletedStates[sourceLayer]=null}}getState(sourceLayer,featureId){const feature=String(featureId);const base=this.state[sourceLayer]||{};const changes=this.stateChanges[sourceLayer]||{};const reconciledState=performance$1.extend({},base[feature],changes[feature]);if(this.deletedStates[sourceLayer]===null)return{};else if(this.deletedStates[sourceLayer]){const featureDeletions=this.deletedStates[sourceLayer][featureId];if(featureDeletions===null)return{};for(const prop in featureDeletions)delete reconciledState[prop]}return reconciledState}initializeTileState(tile,painter){tile.setFeatureState(this.state,painter)}coalesceChanges(tiles,painter){const featuresChanged={};for(const sourceLayer in this.stateChanges){this.state[sourceLayer]=this.state[sourceLayer]||{};const layerStates={};for(const feature in this.stateChanges[sourceLayer]){if(!this.state[sourceLayer][feature])this.state[sourceLayer][feature]={};performance$1.extend(this.state[sourceLayer][feature],this.stateChanges[sourceLayer][feature]);layerStates[feature]=this.state[sourceLayer][feature]}featuresChanged[sourceLayer]=layerStates}for(const sourceLayer in this.deletedStates){this.state[sourceLayer]=this.state[sourceLayer]||{};const layerStates={};if(this.deletedStates[sourceLayer]===null){for(const ft in this.state[sourceLayer]){layerStates[ft]={};this.state[sourceLayer][ft]={}}}else{for(const feature in this.deletedStates[sourceLayer]){const deleteWholeFeatureState=this.deletedStates[sourceLayer][feature]===null;if(deleteWholeFeatureState)this.state[sourceLayer][feature]={};else{for(const key of Object.keys(this.deletedStates[sourceLayer][feature])){delete this.state[sourceLayer][feature][key]}}layerStates[feature]=this.state[sourceLayer][feature]}}featuresChanged[sourceLayer]=featuresChanged[sourceLayer]||{};performance$1.extend(featuresChanged[sourceLayer],layerStates)}this.stateChanges={};this.deletedStates={};if(Object.keys(featuresChanged).length===0)return;for(const id in tiles){const tile=tiles[id];tile.setFeatureState(featuresChanged,painter)}}}class SourceCache extends performance$1.Evented{constructor(id,options,dispatcher){super();this.id=id;this.dispatcher=dispatcher;this.on("data",(e=>{if(e.dataType==="source"&&e.sourceDataType==="metadata")this._sourceLoaded=true;if(this._sourceLoaded&&!this._paused&&e.dataType==="source"&&e.sourceDataType==="content"){this.reload();if(this.transform){this.update(this.transform,this.terrain)}this._didEmitContent=true}}));this.on("dataloading",(()=>{this._sourceErrored=false}));this.on("error",(()=>{this._sourceErrored=this._source.loaded()}));this._source=create(id,options,dispatcher,this);this._tiles={};this._cache=new TileCache(0,(tile=>this._unloadTile(tile)));this._timers={};this._cacheTimers={};this._maxTileCacheSize=null;this._maxTileCacheZoomLevels=null;this._loadedParentTiles={};this._coveredTiles={};this._state=new SourceFeatureState;this._didEmitContent=false;this._updated=false}onAdd(map){this.map=map;this._maxTileCacheSize=map?map._maxTileCacheSize:null;this._maxTileCacheZoomLevels=map?map._maxTileCacheZoomLevels:null;if(this._source&&this._source.onAdd){this._source.onAdd(map)}}onRemove(map){this.clearTiles();if(this._source&&this._source.onRemove){this._source.onRemove(map)}}loaded(){if(this._sourceErrored){return true}if(!this._sourceLoaded){return false}if(!this._source.loaded()){return false}if((this.used!==undefined||this.usedForTerrain!==undefined)&&!this.used&&!this.usedForTerrain){return true}if(!this._updated){return false}for(const t in this._tiles){const tile=this._tiles[t];if(tile.state!=="loaded"&&tile.state!=="errored")return false}return true}getSource(){return this._source}pause(){this._paused=true}resume(){if(!this._paused)return;const shouldReload=this._shouldReloadOnResume;this._paused=false;this._shouldReloadOnResume=false;if(shouldReload)this.reload();if(this.transform)this.update(this.transform,this.terrain)}_loadTile(tile,id,state){return performance$1.__awaiter(this,void 0,void 0,(function*(){try{yield this._source.loadTile(tile);this._tileLoaded(tile,id,state)}catch(err){tile.state="errored";if(err.status!==404){this._source.fire(new performance$1.ErrorEvent(err,{tile:tile}))}else{this.update(this.transform,this.terrain)}}}))}_unloadTile(tile){if(this._source.unloadTile)this._source.unloadTile(tile)}_abortTile(tile){if(this._source.abortTile)this._source.abortTile(tile);this._source.fire(new performance$1.Event("dataabort",{tile:tile,coord:tile.tileID,dataType:"source"}))}serialize(){return this._source.serialize()}prepare(context){if(this._source.prepare){this._source.prepare()}this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const i in this._tiles){const tile=this._tiles[i];tile.upload(context);tile.prepare(this.map.style.imageManager)}}getIds(){return Object.values(this._tiles).map((tile=>tile.tileID)).sort(compareTileId).map((id=>id.key))}getRenderableIds(symbolLayer){const renderables=[];for(const id in this._tiles){if(this._isIdRenderable(id,symbolLayer))renderables.push(this._tiles[id])}if(symbolLayer){return renderables.sort(((a_,b_)=>{const a=a_.tileID;const b=b_.tileID;const rotatedA=new performance$1.Point(a.canonical.x,a.canonical.y)._rotate(this.transform.angle);const rotatedB=new performance$1.Point(b.canonical.x,b.canonical.y)._rotate(this.transform.angle);return a.overscaledZ-b.overscaledZ||rotatedB.y-rotatedA.y||rotatedB.x-rotatedA.x})).map((tile=>tile.tileID.key))}return renderables.map((tile=>tile.tileID)).sort(compareTileId).map((id=>id.key))}hasRenderableParent(tileID){const parentTile=this.findLoadedParent(tileID,0);if(parentTile){return this._isIdRenderable(parentTile.tileID.key)}return false}_isIdRenderable(id,symbolLayer){return this._tiles[id]&&this._tiles[id].hasData()&&!this._coveredTiles[id]&&(symbolLayer||!this._tiles[id].holdingForFade())}reload(){if(this._paused){this._shouldReloadOnResume=true;return}this._cache.reset();for(const i in this._tiles){if(this._tiles[i].state!=="errored")this._reloadTile(i,"reloading")}}_reloadTile(id,state){return performance$1.__awaiter(this,void 0,void 0,(function*(){const tile=this._tiles[id];if(!tile)return;if(tile.state!=="loading"){tile.state=state}yield this._loadTile(tile,id,state)}))}_tileLoaded(tile,id,previousState){tile.timeAdded=browser.now();if(previousState==="expired")tile.refreshedUponExpiration=true;this._setTileReloadTimer(id,tile);if(this.getSource().type==="raster-dem"&&tile.dem)this._backfillDEM(tile);this._state.initializeTileState(tile,this.map?this.map.painter:null);if(!tile.aborted){this._source.fire(new performance$1.Event("data",{dataType:"source",tile:tile,coord:tile.tileID}))}}_backfillDEM(tile){const renderables=this.getRenderableIds();for(let i=0;i1){return}if(Math.abs(dx)>1){if(Math.abs(dx+dim)===1){dx+=dim}else if(Math.abs(dx-dim)===1){dx-=dim}}if(!borderTile.dem||!tile.dem)return;tile.dem.backfillBorder(borderTile.dem,dx,dy);if(tile.neighboringTiles&&tile.neighboringTiles[borderId])tile.neighboringTiles[borderId].backfilled=true}}getTile(tileID){return this.getTileByID(tileID.key)}getTileByID(id){return this._tiles[id]}_retainLoadedChildren(idealTiles,zoom,maxCoveringZoom,retain){for(const id in this._tiles){let tile=this._tiles[id];if(retain[id]||!tile.hasData()||tile.tileID.overscaledZ<=zoom||tile.tileID.overscaledZ>maxCoveringZoom)continue;let topmostLoadedID=tile.tileID;while(tile&&tile.tileID.overscaledZ>zoom+1){const parentID=tile.tileID.scaledTo(tile.tileID.overscaledZ-1);tile=this._tiles[parentID.key];if(tile&&tile.hasData()){topmostLoadedID=parentID}}let tileID=topmostLoadedID;while(tileID.overscaledZ>zoom){tileID=tileID.scaledTo(tileID.overscaledZ-1);if(idealTiles[tileID.key]){retain[topmostLoadedID.key]=topmostLoadedID;break}}}}findLoadedParent(tileID,minCoveringZoom){if(tileID.key in this._loadedParentTiles){const parent=this._loadedParentTiles[tileID.key];if(parent&&parent.tileID.overscaledZ>=minCoveringZoom){return parent}else{return null}}for(let z=tileID.overscaledZ-1;z>=minCoveringZoom;z--){const parentTileID=tileID.scaledTo(z);const tile=this._getLoadedTile(parentTileID);if(tile){return tile}}}_getLoadedTile(tileID){const tile=this._tiles[tileID.key];if(tile&&tile.hasData()){return tile}const cachedTile=this._cache.getByKey(tileID.wrapped().key);return cachedTile}updateCacheSize(transform){const widthInTiles=Math.ceil(transform.width/this._source.tileSize)+1;const heightInTiles=Math.ceil(transform.height/this._source.tileSize)+1;const approxTilesInView=widthInTiles*heightInTiles;const commonZoomRange=this._maxTileCacheZoomLevels===null?performance$1.config.MAX_TILE_CACHE_ZOOM_LEVELS:this._maxTileCacheZoomLevels;const viewDependentMaxSize=Math.floor(approxTilesInView*commonZoomRange);const maxSize=typeof this._maxTileCacheSize==="number"?Math.min(this._maxTileCacheSize,viewDependentMaxSize):viewDependentMaxSize;this._cache.setMaxSize(maxSize)}handleWrapJump(lng){const prevLng=this._prevLng===undefined?lng:this._prevLng;const lngDifference=lng-prevLng;const worldDifference=lngDifference/360;const wrapDelta=Math.round(worldDifference);this._prevLng=lng;if(wrapDelta){const tiles={};for(const key in this._tiles){const tile=this._tiles[key];tile.tileID=tile.tileID.unwrapTo(tile.tileID.wrap+wrapDelta);tiles[tile.tileID.key]=tile}this._tiles=tiles;for(const id in this._timers){clearTimeout(this._timers[id]);delete this._timers[id]}for(const id in this._tiles){const tile=this._tiles[id];this._setTileReloadTimer(id,tile)}}}update(transform,terrain){this.transform=transform;this.terrain=terrain;if(!this._sourceLoaded||this._paused){return}this.updateCacheSize(transform);this.handleWrapJump(this.transform.center.lng);this._coveredTiles={};let idealTileIDs;if(!this.used&&!this.usedForTerrain){idealTileIDs=[]}else if(this._source.tileID){idealTileIDs=transform.getVisibleUnwrappedCoordinates(this._source.tileID).map((unwrapped=>new performance$1.OverscaledTileID(unwrapped.canonical.z,unwrapped.wrap,unwrapped.canonical.z,unwrapped.canonical.x,unwrapped.canonical.y)))}else{idealTileIDs=transform.coveringTiles({tileSize:this.usedForTerrain?this.tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this.usedForTerrain?false:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled,terrain:terrain});if(this._source.hasTile){idealTileIDs=idealTileIDs.filter((coord=>this._source.hasTile(coord)))}}const zoom=transform.coveringZoomLevel(this._source);const minCoveringZoom=Math.max(zoom-SourceCache.maxOverzooming,this._source.minzoom);const maxCoveringZoom=Math.max(zoom+SourceCache.maxUnderzooming,this._source.minzoom);if(this.usedForTerrain){const parents={};for(const tileID of idealTileIDs){if(tileID.canonical.z>this._source.minzoom){const parent=tileID.scaledTo(tileID.canonical.z-1);parents[parent.key]=parent;const parent2=tileID.scaledTo(Math.max(this._source.minzoom,Math.min(tileID.canonical.z,5)));parents[parent2.key]=parent2}}idealTileIDs=idealTileIDs.concat(Object.values(parents))}const noPendingDataEmissions=idealTileIDs.length===0&&!this._updated&&this._didEmitContent;this._updated=true;if(noPendingDataEmissions){this.fire(new performance$1.Event("data",{sourceDataType:"idle",dataType:"source",sourceId:this.id}))}const retain=this._updateRetainedTiles(idealTileIDs,zoom);if(isRasterType(this._source.type)){const parentsForFading={};const fadingTiles={};const ids=Object.keys(retain);const now=browser.now();for(const id of ids){const tileID=retain[id];const tile=this._tiles[id];if(!tile||tile.fadeEndTime!==0&&tile.fadeEndTime<=now){continue}const parentTile=this.findLoadedParent(tileID,minCoveringZoom);if(parentTile){this._addTile(parentTile.tileID);parentsForFading[parentTile.tileID.key]=parentTile.tileID}fadingTiles[id]=tileID}this._retainLoadedChildren(fadingTiles,zoom,maxCoveringZoom,retain);for(const id in parentsForFading){if(!retain[id]){this._coveredTiles[id]=true;retain[id]=parentsForFading[id]}}if(terrain){const idealRasterTileIDs={};const missingTileIDs={};for(const tileID of idealTileIDs){if(this._tiles[tileID.key].hasData())idealRasterTileIDs[tileID.key]=tileID;else missingTileIDs[tileID.key]=tileID}for(const key in missingTileIDs){const children=missingTileIDs[key].children(this._source.maxzoom);if(this._tiles[children[0].key]&&this._tiles[children[1].key]&&this._tiles[children[2].key]&&this._tiles[children[3].key]){idealRasterTileIDs[children[0].key]=retain[children[0].key]=children[0];idealRasterTileIDs[children[1].key]=retain[children[1].key]=children[1];idealRasterTileIDs[children[2].key]=retain[children[2].key]=children[2];idealRasterTileIDs[children[3].key]=retain[children[3].key]=children[3];delete missingTileIDs[key]}}for(const key in missingTileIDs){const parent=this.findLoadedParent(missingTileIDs[key],this._source.minzoom);if(parent){idealRasterTileIDs[parent.tileID.key]=retain[parent.tileID.key]=parent.tileID;for(const key in idealRasterTileIDs){if(idealRasterTileIDs[key].isChildOf(parent.tileID))delete idealRasterTileIDs[key]}}}for(const key in this._tiles){if(!idealRasterTileIDs[key])this._coveredTiles[key]=true}}}for(const retainedId in retain){this._tiles[retainedId].clearFadeHold()}const remove=performance$1.keysDifference(this._tiles,retain);for(const tileID of remove){const tile=this._tiles[tileID];if(tile.hasSymbolBuckets&&!tile.holdingForFade()){tile.setHoldDuration(this.map._fadeDuration)}else if(!tile.hasSymbolBuckets||tile.symbolFadeFinished()){this._removeTile(tileID)}}this._updateLoadedParentTileCache()}releaseSymbolFadeTiles(){for(const id in this._tiles){if(this._tiles[id].holdingForFade()){this._removeTile(id)}}}_updateRetainedTiles(idealTileIDs,zoom){const retain={};const checked={};const minCoveringZoom=Math.max(zoom-SourceCache.maxOverzooming,this._source.minzoom);const maxCoveringZoom=Math.max(zoom+SourceCache.maxUnderzooming,this._source.minzoom);const missingTiles={};for(const tileID of idealTileIDs){const tile=this._addTile(tileID);retain[tileID.key]=tileID;if(tile.hasData())continue;if(zoomthis._source.maxzoom){const childCoord=tileID.children(this._source.maxzoom)[0];const childTile=this.getTile(childCoord);if(!!childTile&&childTile.hasData()){retain[childCoord.key]=childCoord;continue}}else{const children=tileID.children(this._source.maxzoom);if(retain[children[0].key]&&retain[children[1].key]&&retain[children[2].key]&&retain[children[3].key])continue}let parentWasRequested=tile.wasRequested();for(let overscaledZ=tileID.overscaledZ-1;overscaledZ>=minCoveringZoom;--overscaledZ){const parentId=tileID.scaledTo(overscaledZ);if(checked[parentId.key])break;checked[parentId.key]=true;tile=this.getTile(parentId);if(!tile&&parentWasRequested){tile=this._addTile(parentId)}if(tile){const hasData=tile.hasData();if(parentWasRequested||hasData){retain[parentId.key]=parentId}parentWasRequested=tile.wasRequested();if(hasData)break}}}return retain}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const tileKey in this._tiles){const path=[];let parentTile;let currentId=this._tiles[tileKey].tileID;while(currentId.overscaledZ>0){if(currentId.key in this._loadedParentTiles){parentTile=this._loadedParentTiles[currentId.key];break}path.push(currentId.key);const parentId=currentId.scaledTo(currentId.overscaledZ-1);parentTile=this._getLoadedTile(parentId);if(parentTile){break}currentId=parentId}for(const key of path){this._loadedParentTiles[key]=parentTile}}}_addTile(tileID){let tile=this._tiles[tileID.key];if(tile)return tile;tile=this._cache.getAndRemove(tileID);if(tile){this._setTileReloadTimer(tileID.key,tile);tile.tileID=tileID;this._state.initializeTileState(tile,this.map?this.map.painter:null);if(this._cacheTimers[tileID.key]){clearTimeout(this._cacheTimers[tileID.key]);delete this._cacheTimers[tileID.key];this._setTileReloadTimer(tileID.key,tile)}}const cached=tile;if(!tile){tile=new Tile(tileID,this._source.tileSize*tileID.overscaleFactor());this._loadTile(tile,tileID.key,tile.state)}tile.uses++;this._tiles[tileID.key]=tile;if(!cached){this._source.fire(new performance$1.Event("dataloading",{tile:tile,coord:tile.tileID,dataType:"source"}))}return tile}_setTileReloadTimer(id,tile){if(id in this._timers){clearTimeout(this._timers[id]);delete this._timers[id]}const expiryTimeout=tile.getExpiryTimeout();if(expiryTimeout){this._timers[id]=setTimeout((()=>{this._reloadTile(id,"expired");delete this._timers[id]}),expiryTimeout)}}_removeTile(id){const tile=this._tiles[id];if(!tile)return;tile.uses--;delete this._tiles[id];if(this._timers[id]){clearTimeout(this._timers[id]);delete this._timers[id]}if(tile.uses>0)return;if(tile.hasData()&&tile.state!=="reloading"){this._cache.add(tile.tileID,tile,tile.getExpiryTimeout())}else{tile.aborted=true;this._abortTile(tile);this._unloadTile(tile)}}clearTiles(){this._shouldReloadOnResume=false;this._paused=false;for(const id in this._tiles)this._removeTile(id);this._cache.reset()}tilesIn(pointQueryGeometry,maxPitchScaleFactor,has3DLayer){const tileResults=[];const transform=this.transform;if(!transform)return tileResults;const cameraPointQueryGeometry=has3DLayer?transform.getCameraQueryGeometry(pointQueryGeometry):pointQueryGeometry;const queryGeometry=pointQueryGeometry.map((p=>transform.pointCoordinate(p,this.terrain)));const cameraQueryGeometry=cameraPointQueryGeometry.map((p=>transform.pointCoordinate(p,this.terrain)));const ids=this.getIds();let minX=Infinity;let minY=Infinity;let maxX=-Infinity;let maxY=-Infinity;for(const p of cameraQueryGeometry){minX=Math.min(minX,p.x);minY=Math.min(minY,p.y);maxX=Math.max(maxX,p.x);maxY=Math.max(maxY,p.y)}for(let i=0;i=0&&tileSpaceBounds[1].y+queryPadding>=0){const tileSpaceQueryGeometry=queryGeometry.map((c=>tileID.getTilePoint(c)));const tileSpaceCameraQueryGeometry=cameraQueryGeometry.map((c=>tileID.getTilePoint(c)));tileResults.push({tile:tile,tileID:tileID,queryGeometry:tileSpaceQueryGeometry,cameraQueryGeometry:tileSpaceCameraQueryGeometry,scale:scale})}}return tileResults}getVisibleCoordinates(symbolLayer){const coords=this.getRenderableIds(symbolLayer).map((id=>this._tiles[id].tileID));for(const coord of coords){coord.posMatrix=this.transform.calculatePosMatrix(coord.toUnwrapped())}return coords}hasTransition(){if(this._source.hasTransition()){return true}if(isRasterType(this._source.type)){const now=browser.now();for(const id in this._tiles){const tile=this._tiles[id];if(tile.fadeEndTime>=now){return true}}}return false}setFeatureState(sourceLayer,featureId,state){sourceLayer=sourceLayer||"_geojsonTileLayer";this._state.updateState(sourceLayer,featureId,state)}removeFeatureState(sourceLayer,featureId,key){sourceLayer=sourceLayer||"_geojsonTileLayer";this._state.removeFeatureState(sourceLayer,featureId,key)}getFeatureState(sourceLayer,featureId){sourceLayer=sourceLayer||"_geojsonTileLayer";return this._state.getState(sourceLayer,featureId)}setDependencies(tileKey,namespace,dependencies){const tile=this._tiles[tileKey];if(tile){tile.setDependencies(namespace,dependencies)}}reloadTilesForDependencies(namespaces,keys){for(const id in this._tiles){const tile=this._tiles[id];if(tile.hasDependency(namespaces,keys)){this._reloadTile(id,"reloading")}}this._cache.filter((tile=>!tile.hasDependency(namespaces,keys)))}}SourceCache.maxOverzooming=10;SourceCache.maxUnderzooming=3;function compareTileId(a,b){const aWrap=Math.abs(a.wrap*2)-+(a.wrap<0);const bWrap=Math.abs(b.wrap*2)-+(b.wrap<0);return a.overscaledZ-b.overscaledZ||bWrap-aWrap||b.canonical.y-a.canonical.y||b.canonical.x-a.canonical.x}function isRasterType(type){return type==="raster"||type==="image"||type==="video"}class PathInterpolator{constructor(points_,padding_){this.reset(points_,padding_)}reset(points_,padding_){this.points=points_||[];this._distances=[0];for(let i=1;i0?(distToTarget-distOfPrevIdx)/segmentLength:0;return this.points[idxOfPrevPoint].mult(1-segmentT).add(this.points[currentIndex].mult(segmentT))}}function overlapAllowed(overlapA,overlapB){let allowed=true;if(overlapA==="always"){}else if(overlapA==="never"||overlapB==="never"){allowed=false}return allowed}class GridIndex{constructor(width,height,cellSize){const boxCells=this.boxCells=[];const circleCells=this.circleCells=[];this.xCellCount=Math.ceil(width/cellSize);this.yCellCount=Math.ceil(height/cellSize);for(let i=0;ithis.width||y2<0||y1>this.height){return[]}const result=[];if(x1<=0&&y1<=0&&this.width<=x2&&this.height<=y2){if(hitTest){return[{key:null,x1:x1,y1:y1,x2:x2,y2:y2}]}for(let boxUid=0;boxUid0}hitTestCircle(x,y,radius,overlapMode,predicate){const x1=x-radius;const x2=x+radius;const y1=y-radius;const y2=y+radius;if(x2<0||x1>this.width||y2<0||y1>this.height){return false}const result=[];const queryArgs={hitTest:true,overlapMode:overlapMode,circle:{x:x,y:y,radius:radius},seenUids:{box:{},circle:{}}};this._forEachCell(x1,y1,x2,y2,this._queryCellCircle,result,queryArgs,predicate);return result.length>0}_queryCell(x1,y1,x2,y2,cellIndex,result,queryArgs,predicate){const{seenUids:seenUids,hitTest:hitTest,overlapMode:overlapMode}=queryArgs;const boxCell=this.boxCells[cellIndex];if(boxCell!==null){const bboxes=this.bboxes;for(const boxUid of boxCell){if(!seenUids.box[boxUid]){seenUids.box[boxUid]=true;const offset=boxUid*4;const key=this.boxKeys[boxUid];if(x1<=bboxes[offset+2]&&y1<=bboxes[offset+3]&&x2>=bboxes[offset+0]&&y2>=bboxes[offset+1]&&(!predicate||predicate(key))){if(!hitTest||!overlapAllowed(overlapMode,key.overlapMode)){result.push({key:key,x1:bboxes[offset],y1:bboxes[offset+1],x2:bboxes[offset+2],y2:bboxes[offset+3]});if(hitTest){return true}}}}}}const circleCell=this.circleCells[cellIndex];if(circleCell!==null){const circles=this.circles;for(const circleUid of circleCell){if(!seenUids.circle[circleUid]){seenUids.circle[circleUid]=true;const offset=circleUid*3;const key=this.circleKeys[circleUid];if(this._circleAndRectCollide(circles[offset],circles[offset+1],circles[offset+2],x1,y1,x2,y2)&&(!predicate||predicate(key))){if(!hitTest||!overlapAllowed(overlapMode,key.overlapMode)){const x=circles[offset];const y=circles[offset+1];const radius=circles[offset+2];result.push({key:key,x1:x-radius,y1:y-radius,x2:x+radius,y2:y+radius});if(hitTest){return true}}}}}}return false}_queryCellCircle(x1,y1,x2,y2,cellIndex,result,queryArgs,predicate){const{circle:circle,seenUids:seenUids,overlapMode:overlapMode}=queryArgs;const boxCell=this.boxCells[cellIndex];if(boxCell!==null){const bboxes=this.bboxes;for(const boxUid of boxCell){if(!seenUids.box[boxUid]){seenUids.box[boxUid]=true;const offset=boxUid*4;const key=this.boxKeys[boxUid];if(this._circleAndRectCollide(circle.x,circle.y,circle.radius,bboxes[offset+0],bboxes[offset+1],bboxes[offset+2],bboxes[offset+3])&&(!predicate||predicate(key))&&!overlapAllowed(overlapMode,key.overlapMode)){result.push(true);return true}}}}const circleCell=this.circleCells[cellIndex];if(circleCell!==null){const circles=this.circles;for(const circleUid of circleCell){if(!seenUids.circle[circleUid]){seenUids.circle[circleUid]=true;const offset=circleUid*3;const key=this.circleKeys[circleUid];if(this._circlesCollide(circles[offset],circles[offset+1],circles[offset+2],circle.x,circle.y,circle.radius)&&(!predicate||predicate(key))&&!overlapAllowed(overlapMode,key.overlapMode)){result.push(true);return true}}}}}_forEachCell(x1,y1,x2,y2,fn,arg1,arg2,predicate){const cx1=this._convertToXCellCoord(x1);const cy1=this._convertToYCellCoord(y1);const cx2=this._convertToXCellCoord(x2);const cy2=this._convertToYCellCoord(y2);for(let x=cx1;x<=cx2;x++){for(let y=cy1;y<=cy2;y++){const cellIndex=this.xCellCount*y+x;if(fn.call(this,x1,y1,x2,y2,cellIndex,arg1,arg2,predicate))return}}}_convertToXCellCoord(x){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(x*this.xScale)))}_convertToYCellCoord(y){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(y*this.yScale)))}_circlesCollide(x1,y1,r1,x2,y2,r2){const dx=x2-x1;const dy=y2-y1;const bothRadii=r1+r2;return bothRadii*bothRadii>dx*dx+dy*dy}_circleAndRectCollide(circleX,circleY,radius,x1,y1,x2,y2){const halfRectWidth=(x2-x1)/2;const distX=Math.abs(circleX-(x1+halfRectWidth));if(distX>halfRectWidth+radius){return false}const halfRectHeight=(y2-y1)/2;const distY=Math.abs(circleY-(y1+halfRectHeight));if(distY>halfRectHeight+radius){return false}if(distX<=halfRectWidth||distY<=halfRectHeight){return true}const dx=distX-halfRectWidth;const dy=distY-halfRectHeight;return dx*dx+dy*dy<=radius*radius}}function getLabelPlaneMatrix(posMatrix,pitchWithMap,rotateWithMap,transform,pixelsToTileUnits){const m=performance$1.create();if(pitchWithMap){performance$1.scale(m,m,[1/pixelsToTileUnits,1/pixelsToTileUnits,1]);if(!rotateWithMap){performance$1.rotateZ(m,m,transform.angle)}}else{performance$1.multiply(m,transform.labelPlaneMatrix,posMatrix)}return m}function getGlCoordMatrix(posMatrix,pitchWithMap,rotateWithMap,transform,pixelsToTileUnits){if(pitchWithMap){const m=performance$1.clone(posMatrix);performance$1.scale(m,m,[pixelsToTileUnits,pixelsToTileUnits,1]);if(!rotateWithMap){performance$1.rotateZ(m,m,-transform.angle)}return m}else{return transform.glCoordMatrix}}function project(point,matrix,getElevation){let pos;if(getElevation){pos=[point.x,point.y,getElevation(point.x,point.y),1];performance$1.transformMat4(pos,pos,matrix)}else{pos=[point.x,point.y,0,1];xyTransformMat4(pos,pos,matrix)}const w=pos[3];return{point:new performance$1.Point(pos[0]/w,pos[1]/w),signedDistanceFromCamera:w}}function getPerspectiveRatio(cameraToCenterDistance,signedDistanceFromCamera){return.5+.5*(cameraToCenterDistance/signedDistanceFromCamera)}function isVisible(anchorPos,clippingBuffer){const x=anchorPos[0]/anchorPos[3];const y=anchorPos[1]/anchorPos[3];const inPaddedViewport=x>=-clippingBuffer[0]&&x<=clippingBuffer[0]&&y>=-clippingBuffer[1]&&y<=clippingBuffer[1];return inPaddedViewport}function updateLineLabels(bucket,posMatrix,painter,isText,labelPlaneMatrix,glCoordMatrix,pitchWithMap,keepUpright,rotateToLine,getElevation){const sizeData=isText?bucket.textSizeData:bucket.iconSizeData;const partiallyEvaluatedSize=performance$1.evaluateSizeForZoom(sizeData,painter.transform.zoom);const clippingBuffer=[256/painter.width*2+1,256/painter.height*2+1];const dynamicLayoutVertexArray=isText?bucket.text.dynamicLayoutVertexArray:bucket.icon.dynamicLayoutVertexArray;dynamicLayoutVertexArray.clear();const lineVertexArray=bucket.lineVertexArray;const placedSymbols=isText?bucket.text.placedSymbolArray:bucket.icon.placedSymbolArray;const aspectRatio=painter.transform.width/painter.transform.height;let useVertical=false;for(let s=0;srun){return{useVertical:true}}}if(writingMode===performance$1.WritingMode.vertical?firstPoint.ylastPoint.x){return{needsFlipping:true}}return null}function placeGlyphsAlongLine(symbol,fontSize,flip,keepUpright,posMatrix,labelPlaneMatrix,glCoordMatrix,glyphOffsetArray,lineVertexArray,dynamicLayoutVertexArray,anchorPoint,tileAnchorPoint,projectionCache,aspectRatio,rotateToLine,getElevation){const fontScale=fontSize/24;const lineOffsetX=symbol.lineOffsetX*fontScale;const lineOffsetY=symbol.lineOffsetY*fontScale;let placedGlyphs;if(symbol.numGlyphs>1){const glyphEndIndex=symbol.glyphStartIndex+symbol.numGlyphs;const lineStartIndex=symbol.lineStartIndex;const lineEndIndex=symbol.lineStartIndex+symbol.lineLength;const firstAndLastGlyph=placeFirstAndLastGlyph(fontScale,glyphOffsetArray,lineOffsetX,lineOffsetY,flip,anchorPoint,tileAnchorPoint,symbol,lineVertexArray,labelPlaneMatrix,projectionCache,rotateToLine,getElevation);if(!firstAndLastGlyph){return{notEnoughRoom:true}}const firstPoint=project(firstAndLastGlyph.first.point,glCoordMatrix,getElevation).point;const lastPoint=project(firstAndLastGlyph.last.point,glCoordMatrix,getElevation).point;if(keepUpright&&!flip){const orientationChange=requiresOrientationChange(symbol.writingMode,firstPoint,lastPoint,aspectRatio);if(orientationChange){return orientationChange}}placedGlyphs=[firstAndLastGlyph.first];for(let glyphIndex=symbol.glyphStartIndex+1;glyphIndex0?projectedVertex.point:projectTruncatedLineSegment(tileAnchorPoint,tileSegmentEnd,a,1,posMatrix,getElevation);const orientationChange=requiresOrientationChange(symbol.writingMode,a,b,aspectRatio);if(orientationChange){return orientationChange}}const singleGlyph=placeGlyphAlongLine(fontScale*glyphOffsetArray.getoffsetX(symbol.glyphStartIndex),lineOffsetX,lineOffsetY,flip,anchorPoint,tileAnchorPoint,symbol.segment,symbol.lineStartIndex,symbol.lineStartIndex+symbol.lineLength,lineVertexArray,labelPlaneMatrix,projectionCache,rotateToLine,getElevation);if(!singleGlyph)return{notEnoughRoom:true};placedGlyphs=[singleGlyph]}for(const glyph of placedGlyphs){performance$1.addDynamicAttributes(dynamicLayoutVertexArray,glyph.point,glyph.angle)}return{}}function projectTruncatedLineSegment(previousTilePoint,currentTilePoint,previousProjectedPoint,minimumLength,projectionMatrix,getElevation){const projectedUnitVertex=project(previousTilePoint.add(previousTilePoint.sub(currentTilePoint)._unit()),projectionMatrix,getElevation).point;const projectedUnitSegment=previousProjectedPoint.sub(projectedUnitVertex);return previousProjectedPoint.add(projectedUnitSegment._mult(minimumLength/projectedUnitSegment.mag()))}function projectVertexToViewport(index,projectionArgs){const{projectionCache:projectionCache,lineVertexArray:lineVertexArray,labelPlaneMatrix:labelPlaneMatrix,tileAnchorPoint:tileAnchorPoint,distanceFromAnchor:distanceFromAnchor,getElevation:getElevation,previousVertex:previousVertex,direction:direction,absOffsetX:absOffsetX}=projectionArgs;if(projectionCache.projections[index]){return projectionCache.projections[index]}const currentVertex=new performance$1.Point(lineVertexArray.getx(index),lineVertexArray.gety(index));const projection=project(currentVertex,labelPlaneMatrix,getElevation);if(projection.signedDistanceFromCamera>0){projectionCache.projections[index]=projection.point;return projection.point}const previousLineVertexIndex=index-direction;const previousTilePoint=distanceFromAnchor===0?tileAnchorPoint:new performance$1.Point(lineVertexArray.getx(previousLineVertexIndex),lineVertexArray.gety(previousLineVertexIndex));return projectTruncatedLineSegment(previousTilePoint,currentVertex,previousVertex,absOffsetX-distanceFromAnchor+1,labelPlaneMatrix,getElevation)}function transformToOffsetNormal(segmentVector,offset,direction){return segmentVector._unit()._perp()._mult(offset*direction)}function findOffsetIntersectionPoint(index,prevToCurrentOffsetNormal,currentVertex,lineStartIndex,lineEndIndex,offsetPreviousVertex,lineOffsetY,projectionArgs){const{projectionCache:projectionCache,direction:direction}=projectionArgs;if(projectionCache.offsets[index]){return projectionCache.offsets[index]}const offsetCurrentVertex=currentVertex.add(prevToCurrentOffsetNormal);if(index+direction=lineEndIndex){projectionCache.offsets[index]=offsetCurrentVertex;return offsetCurrentVertex}const nextVertex=projectVertexToViewport(index+direction,projectionArgs);const currentToNextOffsetNormal=transformToOffsetNormal(nextVertex.sub(currentVertex),lineOffsetY,direction);const offsetNextSegmentBegin=currentVertex.add(currentToNextOffsetNormal);const offsetNextSegmentEnd=nextVertex.add(currentToNextOffsetNormal);projectionCache.offsets[index]=performance$1.findLineIntersection(offsetPreviousVertex,offsetCurrentVertex,offsetNextSegmentBegin,offsetNextSegmentEnd)||offsetCurrentVertex;return projectionCache.offsets[index]}function placeGlyphAlongLine(offsetX,lineOffsetX,lineOffsetY,flip,anchorPoint,tileAnchorPoint,anchorSegment,lineStartIndex,lineEndIndex,lineVertexArray,labelPlaneMatrix,projectionCache,rotateToLine,getElevation){const combinedOffsetX=flip?offsetX-lineOffsetX:offsetX+lineOffsetX;let direction=combinedOffsetX>0?1:-1;let angle=0;if(flip){direction*=-1;angle=Math.PI}if(direction<0)angle+=Math.PI;let currentIndex=direction>0?lineStartIndex+anchorSegment:lineStartIndex+anchorSegment+1;let currentVertex=anchorPoint;let previousVertex=anchorPoint;let offsetIntersectionPoint;let offsetPreviousVertex;let distanceFromAnchor=0;let currentSegmentDistance=0;const absOffsetX=Math.abs(combinedOffsetX);const pathVertices=[];let currentLineSegment;while(distanceFromAnchor+currentSegmentDistance<=absOffsetX){currentIndex+=direction;if(currentIndex=lineEndIndex)return null;distanceFromAnchor+=currentSegmentDistance;previousVertex=currentVertex;offsetPreviousVertex=offsetIntersectionPoint;const projectionArgs={projectionCache:projectionCache,lineVertexArray:lineVertexArray,labelPlaneMatrix:labelPlaneMatrix,tileAnchorPoint:tileAnchorPoint,distanceFromAnchor:distanceFromAnchor,getElevation:getElevation,previousVertex:previousVertex,direction:direction,absOffsetX:absOffsetX};currentVertex=projectVertexToViewport(currentIndex,projectionArgs);if(lineOffsetY===0){pathVertices.push(previousVertex);currentLineSegment=currentVertex.sub(previousVertex)}else{let prevToCurrentOffsetNormal;const prevToCurrent=currentVertex.sub(previousVertex);if(prevToCurrent.mag()===0){const nextVertex=projectVertexToViewport(currentIndex+direction,projectionArgs);prevToCurrentOffsetNormal=transformToOffsetNormal(nextVertex.sub(currentVertex),lineOffsetY,direction)}else{prevToCurrentOffsetNormal=transformToOffsetNormal(prevToCurrent,lineOffsetY,direction)}if(!offsetPreviousVertex)offsetPreviousVertex=previousVertex.add(prevToCurrentOffsetNormal);offsetIntersectionPoint=findOffsetIntersectionPoint(currentIndex,prevToCurrentOffsetNormal,currentVertex,lineStartIndex,lineEndIndex,offsetPreviousVertex,lineOffsetY,projectionArgs);pathVertices.push(offsetPreviousVertex);currentLineSegment=offsetIntersectionPoint.sub(offsetPreviousVertex)}currentSegmentDistance=currentLineSegment.mag()}const segmentInterpolationT=(absOffsetX-distanceFromAnchor)/currentSegmentDistance;const p=currentLineSegment._mult(segmentInterpolationT)._add(offsetPreviousVertex||previousVertex);const segmentAngle=angle+Math.atan2(currentVertex.y-previousVertex.y,currentVertex.x-previousVertex.x);pathVertices.push(p);return{point:p,angle:rotateToLine?segmentAngle:0,path:pathVertices}}const hiddenGlyphAttributes=new Float32Array([-Infinity,-Infinity,0,-Infinity,-Infinity,0,-Infinity,-Infinity,0,-Infinity,-Infinity,0]);function hideGlyphs(num,dynamicLayoutVertexArray){for(let i=0;i=1;i--){projectedPath.push(first.path[i])}for(let i=1;iproject(p,labelToScreenMatrix,getElevation)));if(screenSpacePath.some((point=>point.signedDistanceFromCamera<=0))){projectedPath=[]}else{projectedPath=screenSpacePath.map((p=>p.point))}}let segments=[];if(projectedPath.length>0){const minPoint=projectedPath[0].clone();const maxPoint=projectedPath[0].clone();for(let i=1;i=screenPlaneMin.x&&maxPoint.x<=screenPlaneMax.x&&minPoint.y>=screenPlaneMin.y&&maxPoint.y<=screenPlaneMax.y){segments=[projectedPath]}else if(maxPoint.xscreenPlaneMax.x||maxPoint.yscreenPlaneMax.y){segments=[]}else{segments=performance$1.clipLine([projectedPath],screenPlaneMin.x,screenPlaneMin.y,screenPlaneMax.x,screenPlaneMax.y)}}for(const seg of segments){interpolator.reset(seg,radius*.25);let numCircles=0;if(interpolator.length<=.5*radius){numCircles=1}else{numCircles=Math.ceil(interpolator.paddedLength/circleDist)+1}for(let i=0;i=this.screenRightBoundary||y2this.screenBottomBoundary}isInsideGrid(x1,y1,x2,y2){return x2>=0&&x1=0&&y1key.collisionGroupID===nextGroupID}}return this.collisionGroups[sourceID]}else{return{ID:0,predicate:null}}}}function calculateVariableLayoutShift(anchor,width,height,textOffset,textBoxScale){const{horizontalAlign:horizontalAlign,verticalAlign:verticalAlign}=performance$1.getAnchorAlignment(anchor);const shiftX=-(horizontalAlign-.5)*width;const shiftY=-(verticalAlign-.5)*height;return new performance$1.Point(shiftX+textOffset[0]*textBoxScale,shiftY+textOffset[1]*textBoxScale)}function shiftVariableCollisionBox(collisionBox,shiftX,shiftY,rotateWithMap,pitchWithMap,angle){const{x1:x1,x2:x2,y1:y1,y2:y2,anchorPointX:anchorPointX,anchorPointY:anchorPointY}=collisionBox;const rotatedOffset=new performance$1.Point(shiftX,shiftY);if(rotateWithMap){rotatedOffset._rotate(pitchWithMap?angle:-angle)}return{x1:x1+rotatedOffset.x,y1:y1+rotatedOffset.y,x2:x2+rotatedOffset.x,y2:y2+rotatedOffset.y,anchorPointX:anchorPointX,anchorPointY:anchorPointY}}class Placement{constructor(transform,terrain,fadeDuration,crossSourceCollisions,prevPlacement){this.transform=transform.clone();this.terrain=terrain;this.collisionIndex=new CollisionIndex(this.transform);this.placements={};this.opacities={};this.variableOffsets={};this.stale=false;this.commitTime=0;this.fadeDuration=fadeDuration;this.retainedQueryData={};this.collisionGroups=new CollisionGroups(crossSourceCollisions);this.collisionCircleArrays={};this.prevPlacement=prevPlacement;if(prevPlacement){prevPlacement.prevPlacement=undefined}this.placedOrientations={}}getBucketParts(results,styleLayer,tile,sortAcrossTiles){const symbolBucket=tile.getBucket(styleLayer);const bucketFeatureIndex=tile.latestFeatureIndex;if(!symbolBucket||!bucketFeatureIndex||styleLayer.id!==symbolBucket.layerIds[0])return;const collisionBoxArray=tile.collisionBoxArray;const layout=symbolBucket.layers[0].layout;const scale=Math.pow(2,this.transform.zoom-tile.tileID.overscaledZ);const textPixelRatio=tile.tileSize/performance$1.EXTENT;const posMatrix=this.transform.calculatePosMatrix(tile.tileID.toUnwrapped());const pitchWithMap=layout.get("text-pitch-alignment")==="map";const rotateWithMap=layout.get("text-rotation-alignment")==="map";const pixelsToTiles=pixelsToTileUnits(tile,1,this.transform.zoom);const textLabelPlaneMatrix=getLabelPlaneMatrix(posMatrix,pitchWithMap,rotateWithMap,this.transform,pixelsToTiles);let labelToScreenMatrix=null;if(pitchWithMap){const glMatrix=getGlCoordMatrix(posMatrix,pitchWithMap,rotateWithMap,this.transform,pixelsToTiles);labelToScreenMatrix=performance$1.multiply([],this.transform.labelPlaneMatrix,glMatrix)}this.retainedQueryData[symbolBucket.bucketInstanceId]=new RetainedQueryData(symbolBucket.bucketInstanceId,bucketFeatureIndex,symbolBucket.sourceLayerIndex,symbolBucket.index,tile.tileID);const parameters={bucket:symbolBucket,layout:layout,posMatrix:posMatrix,textLabelPlaneMatrix:textLabelPlaneMatrix,labelToScreenMatrix:labelToScreenMatrix,scale:scale,textPixelRatio:textPixelRatio,holdingForFade:tile.holdingForFade(),collisionBoxArray:collisionBoxArray,partiallyEvaluatedTextSize:performance$1.evaluateSizeForZoom(symbolBucket.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(symbolBucket.sourceID)};if(sortAcrossTiles){for(const range of symbolBucket.sortKeyRanges){const{sortKey:sortKey,symbolInstanceStart:symbolInstanceStart,symbolInstanceEnd:symbolInstanceEnd}=range;results.push({sortKey:sortKey,symbolInstanceStart:symbolInstanceStart,symbolInstanceEnd:symbolInstanceEnd,parameters:parameters})}}else{results.push({symbolInstanceStart:0,symbolInstanceEnd:symbolBucket.symbolInstances.length,parameters:parameters})}}attemptAnchorPlacement(textAnchorOffset,textBox,width,height,textBoxScale,rotateWithMap,pitchWithMap,textPixelRatio,posMatrix,collisionGroup,textOverlapMode,symbolInstance,bucket,orientation,iconBox,getElevation){const anchor=performance$1.TextAnchorEnum[textAnchorOffset.textAnchor];const textOffset=[textAnchorOffset.textOffset0,textAnchorOffset.textOffset1];const shift=calculateVariableLayoutShift(anchor,width,height,textOffset,textBoxScale);const placedGlyphBoxes=this.collisionIndex.placeCollisionBox(shiftVariableCollisionBox(textBox,shift.x,shift.y,rotateWithMap,pitchWithMap,this.transform.angle),textOverlapMode,textPixelRatio,posMatrix,collisionGroup.predicate,getElevation);if(iconBox){const placedIconBoxes=this.collisionIndex.placeCollisionBox(shiftVariableCollisionBox(iconBox,shift.x,shift.y,rotateWithMap,pitchWithMap,this.transform.angle),textOverlapMode,textPixelRatio,posMatrix,collisionGroup.predicate,getElevation);if(placedIconBoxes.box.length===0)return}if(placedGlyphBoxes.box.length>0){let prevAnchor;if(this.prevPlacement&&this.prevPlacement.variableOffsets[symbolInstance.crossTileID]&&this.prevPlacement.placements[symbolInstance.crossTileID]&&this.prevPlacement.placements[symbolInstance.crossTileID].text){prevAnchor=this.prevPlacement.variableOffsets[symbolInstance.crossTileID].anchor}if(symbolInstance.crossTileID===0)throw new Error("symbolInstance.crossTileID can't be 0");this.variableOffsets[symbolInstance.crossTileID]={textOffset:textOffset,width:width,height:height,anchor:anchor,textBoxScale:textBoxScale,prevAnchor:prevAnchor};this.markUsedJustification(bucket,anchor,symbolInstance,orientation);if(bucket.allowVerticalPlacement){this.markUsedOrientation(bucket,orientation,symbolInstance);this.placedOrientations[symbolInstance.crossTileID]=orientation}return{shift:shift,placedGlyphBoxes:placedGlyphBoxes}}}placeLayerBucketPart(bucketPart,seenCrossTileIDs,showCollisionBoxes){const{bucket:bucket,layout:layout,posMatrix:posMatrix,textLabelPlaneMatrix:textLabelPlaneMatrix,labelToScreenMatrix:labelToScreenMatrix,textPixelRatio:textPixelRatio,holdingForFade:holdingForFade,collisionBoxArray:collisionBoxArray,partiallyEvaluatedTextSize:partiallyEvaluatedTextSize,collisionGroup:collisionGroup}=bucketPart.parameters;const textOptional=layout.get("text-optional");const iconOptional=layout.get("icon-optional");const textOverlapMode=performance$1.getOverlapMode(layout,"text-overlap","text-allow-overlap");const textAlwaysOverlap=textOverlapMode==="always";const iconOverlapMode=performance$1.getOverlapMode(layout,"icon-overlap","icon-allow-overlap");const iconAlwaysOverlap=iconOverlapMode==="always";const rotateWithMap=layout.get("text-rotation-alignment")==="map";const pitchWithMap=layout.get("text-pitch-alignment")==="map";const hasIconTextFit=layout.get("icon-text-fit")!=="none";const zOrderByViewportY=layout.get("symbol-z-order")==="viewport-y";const alwaysShowText=textAlwaysOverlap&&(iconAlwaysOverlap||!bucket.hasIconData()||iconOptional);const alwaysShowIcon=iconAlwaysOverlap&&(textAlwaysOverlap||!bucket.hasTextData()||textOptional);if(!bucket.collisionArrays&&collisionBoxArray){bucket.deserializeCollisionBoxes(collisionBoxArray)}const tileID=this.retainedQueryData[bucket.bucketInstanceId].tileID;const getElevation=this.terrain?(x,y)=>this.terrain.getElevation(tileID,x,y):null;const placeSymbol=(symbolInstance,collisionArrays)=>{var _a,_b;if(seenCrossTileIDs[symbolInstance.crossTileID])return;if(holdingForFade){this.placements[symbolInstance.crossTileID]=new JointPlacement(false,false,false);return}let placeText=false;let placeIcon=false;let offscreen=true;let shift=null;let placed={box:null,offscreen:null};let placedVerticalText={box:null,offscreen:null};let placedGlyphBoxes=null;let placedGlyphCircles=null;let placedIconBoxes=null;let textFeatureIndex=0;let verticalTextFeatureIndex=0;let iconFeatureIndex=0;if(collisionArrays.textFeatureIndex){textFeatureIndex=collisionArrays.textFeatureIndex}else if(symbolInstance.useRuntimeCollisionCircles){textFeatureIndex=symbolInstance.featureIndex}if(collisionArrays.verticalTextFeatureIndex){verticalTextFeatureIndex=collisionArrays.verticalTextFeatureIndex}const textBox=collisionArrays.textBox;if(textBox){const updatePreviousOrientationIfNotPlaced=isPlaced=>{let previousOrientation=performance$1.WritingMode.horizontal;if(bucket.allowVerticalPlacement&&!isPlaced&&this.prevPlacement){const prevPlacedOrientation=this.prevPlacement.placedOrientations[symbolInstance.crossTileID];if(prevPlacedOrientation){this.placedOrientations[symbolInstance.crossTileID]=prevPlacedOrientation;previousOrientation=prevPlacedOrientation;this.markUsedOrientation(bucket,previousOrientation,symbolInstance)}}return previousOrientation};const placeTextForPlacementModes=(placeHorizontalFn,placeVerticalFn)=>{if(bucket.allowVerticalPlacement&&symbolInstance.numVerticalGlyphVertices>0&&collisionArrays.verticalTextBox){for(const placementMode of bucket.writingModes){if(placementMode===performance$1.WritingMode.vertical){placed=placeVerticalFn();placedVerticalText=placed}else{placed=placeHorizontalFn()}if(placed&&placed.box&&placed.box.length)break}}else{placed=placeHorizontalFn()}};const textAnchorOffsetStart=symbolInstance.textAnchorOffsetStartIndex;const textAnchorOffsetEnd=symbolInstance.textAnchorOffsetEndIndex;if(textAnchorOffsetEnd===textAnchorOffsetStart){const placeBox=(collisionTextBox,orientation)=>{const placedFeature=this.collisionIndex.placeCollisionBox(collisionTextBox,textOverlapMode,textPixelRatio,posMatrix,collisionGroup.predicate,getElevation);if(placedFeature&&placedFeature.box&&placedFeature.box.length){this.markUsedOrientation(bucket,orientation,symbolInstance);this.placedOrientations[symbolInstance.crossTileID]=orientation}return placedFeature};const placeHorizontal=()=>placeBox(textBox,performance$1.WritingMode.horizontal);const placeVertical=()=>{const verticalTextBox=collisionArrays.verticalTextBox;if(bucket.allowVerticalPlacement&&symbolInstance.numVerticalGlyphVertices>0&&verticalTextBox){return placeBox(verticalTextBox,performance$1.WritingMode.vertical)}return{box:null,offscreen:null}};placeTextForPlacementModes(placeHorizontal,placeVertical);updatePreviousOrientationIfNotPlaced(placed&&placed.box&&placed.box.length)}else{let prevAnchor=performance$1.TextAnchorEnum[(_b=(_a=this.prevPlacement)===null||_a===void 0?void 0:_a.variableOffsets[symbolInstance.crossTileID])===null||_b===void 0?void 0:_b.anchor];const placeBoxForVariableAnchors=(collisionTextBox,collisionIconBox,orientation)=>{const width=collisionTextBox.x2-collisionTextBox.x1;const height=collisionTextBox.y2-collisionTextBox.y1;const textBoxScale=symbolInstance.textBoxScale;const variableIconBox=hasIconTextFit&&iconOverlapMode==="never"?collisionIconBox:null;let placedBox={box:[],offscreen:false};let placementPasses=textOverlapMode==="never"?1:2;let overlapMode="never";if(prevAnchor){placementPasses++}for(let pass=0;passplaceBoxForVariableAnchors(textBox,collisionArrays.iconBox,performance$1.WritingMode.horizontal);const placeVertical=()=>{const verticalTextBox=collisionArrays.verticalTextBox;const wasPlaced=placed&&placed.box&&placed.box.length;if(bucket.allowVerticalPlacement&&!wasPlaced&&symbolInstance.numVerticalGlyphVertices>0&&verticalTextBox){return placeBoxForVariableAnchors(verticalTextBox,collisionArrays.verticalIconBox,performance$1.WritingMode.vertical)}return{box:null,offscreen:null}};placeTextForPlacementModes(placeHorizontal,placeVertical);if(placed){placeText=placed.box;offscreen=placed.offscreen}const prevOrientation=updatePreviousOrientationIfNotPlaced(placed&&placed.box);if(!placeText&&this.prevPlacement){const prevOffset=this.prevPlacement.variableOffsets[symbolInstance.crossTileID];if(prevOffset){this.variableOffsets[symbolInstance.crossTileID]=prevOffset;this.markUsedJustification(bucket,prevOffset.anchor,symbolInstance,prevOrientation)}}}}placedGlyphBoxes=placed;placeText=placedGlyphBoxes&&placedGlyphBoxes.box&&placedGlyphBoxes.box.length>0;offscreen=placedGlyphBoxes&&placedGlyphBoxes.offscreen;if(symbolInstance.useRuntimeCollisionCircles){const placedSymbol=bucket.text.placedSymbolArray.get(symbolInstance.centerJustifiedTextSymbolIndex);const fontSize=performance$1.evaluateSizeForFeature(bucket.textSizeData,partiallyEvaluatedTextSize,placedSymbol);const textPixelPadding=layout.get("text-padding");const circlePixelDiameter=symbolInstance.collisionCircleDiameter;placedGlyphCircles=this.collisionIndex.placeCollisionCircles(textOverlapMode,placedSymbol,bucket.lineVertexArray,bucket.glyphOffsetArray,fontSize,posMatrix,textLabelPlaneMatrix,labelToScreenMatrix,showCollisionBoxes,pitchWithMap,collisionGroup.predicate,circlePixelDiameter,textPixelPadding,getElevation);if(placedGlyphCircles.circles.length&&placedGlyphCircles.collisionDetected&&!showCollisionBoxes){performance$1.warnOnce("Collisions detected, but collision boxes are not shown")}placeText=textAlwaysOverlap||placedGlyphCircles.circles.length>0&&!placedGlyphCircles.collisionDetected;offscreen=offscreen&&placedGlyphCircles.offscreen}if(collisionArrays.iconFeatureIndex){iconFeatureIndex=collisionArrays.iconFeatureIndex}if(collisionArrays.iconBox){const placeIconFeature=iconBox=>{const shiftedIconBox=hasIconTextFit&&shift?shiftVariableCollisionBox(iconBox,shift.x,shift.y,rotateWithMap,pitchWithMap,this.transform.angle):iconBox;return this.collisionIndex.placeCollisionBox(shiftedIconBox,iconOverlapMode,textPixelRatio,posMatrix,collisionGroup.predicate,getElevation)};if(placedVerticalText&&placedVerticalText.box&&placedVerticalText.box.length&&collisionArrays.verticalIconBox){placedIconBoxes=placeIconFeature(collisionArrays.verticalIconBox);placeIcon=placedIconBoxes.box.length>0}else{placedIconBoxes=placeIconFeature(collisionArrays.iconBox);placeIcon=placedIconBoxes.box.length>0}offscreen=offscreen&&placedIconBoxes.offscreen}const iconWithoutText=textOptional||symbolInstance.numHorizontalGlyphVertices===0&&symbolInstance.numVerticalGlyphVertices===0;const textWithoutIcon=iconOptional||symbolInstance.numIconVertices===0;if(!iconWithoutText&&!textWithoutIcon){placeIcon=placeText=placeIcon&&placeText}else if(!textWithoutIcon){placeText=placeIcon&&placeText}else if(!iconWithoutText){placeIcon=placeIcon&&placeText}if(placeText&&placedGlyphBoxes&&placedGlyphBoxes.box){if(placedVerticalText&&placedVerticalText.box&&verticalTextFeatureIndex){this.collisionIndex.insertCollisionBox(placedGlyphBoxes.box,textOverlapMode,layout.get("text-ignore-placement"),bucket.bucketInstanceId,verticalTextFeatureIndex,collisionGroup.ID)}else{this.collisionIndex.insertCollisionBox(placedGlyphBoxes.box,textOverlapMode,layout.get("text-ignore-placement"),bucket.bucketInstanceId,textFeatureIndex,collisionGroup.ID)}}if(placeIcon&&placedIconBoxes){this.collisionIndex.insertCollisionBox(placedIconBoxes.box,iconOverlapMode,layout.get("icon-ignore-placement"),bucket.bucketInstanceId,iconFeatureIndex,collisionGroup.ID)}if(placedGlyphCircles){if(placeText){this.collisionIndex.insertCollisionCircles(placedGlyphCircles.circles,textOverlapMode,layout.get("text-ignore-placement"),bucket.bucketInstanceId,textFeatureIndex,collisionGroup.ID)}if(showCollisionBoxes){const id=bucket.bucketInstanceId;let circleArray=this.collisionCircleArrays[id];if(circleArray===undefined)circleArray=this.collisionCircleArrays[id]=new CollisionCircleArray;for(let i=0;i=0;--i){const symbolIndex=symbolIndexes[i];placeSymbol(bucket.symbolInstances.get(symbolIndex),bucket.collisionArrays[symbolIndex])}}else{for(let i=bucketPart.symbolInstanceStart;i=0){if(autoIndex>=0&&index!==autoIndex){bucket.text.placedSymbolArray.get(index).crossTileID=0}else{bucket.text.placedSymbolArray.get(index).crossTileID=symbolInstance.crossTileID}}}}markUsedOrientation(bucket,orientation,symbolInstance){const horizontal=orientation===performance$1.WritingMode.horizontal||orientation===performance$1.WritingMode.horizontalOnly?orientation:0;const vertical=orientation===performance$1.WritingMode.vertical?orientation:0;const horizontalIndexes=[symbolInstance.leftJustifiedTextSymbolIndex,symbolInstance.centerJustifiedTextSymbolIndex,symbolInstance.rightJustifiedTextSymbolIndex];for(const index of horizontalIndexes){bucket.text.placedSymbolArray.get(index).placedOrientation=horizontal}if(symbolInstance.verticalPlacedTextSymbolIndex){bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).placedOrientation=vertical}}commit(now){this.commitTime=now;this.zoomAtLastRecencyCheck=this.transform.zoom;const prevPlacement=this.prevPlacement;let placementChanged=false;this.prevZoomAdjustment=prevPlacement?prevPlacement.zoomAdjustment(this.transform.zoom):0;const increment=prevPlacement?prevPlacement.symbolFadeChange(now):1;const prevOpacities=prevPlacement?prevPlacement.opacities:{};const prevOffsets=prevPlacement?prevPlacement.variableOffsets:{};const prevOrientations=prevPlacement?prevPlacement.placedOrientations:{};for(const crossTileID in this.placements){const jointPlacement=this.placements[crossTileID];const prevOpacity=prevOpacities[crossTileID];if(prevOpacity){this.opacities[crossTileID]=new JointOpacityState(prevOpacity,increment,jointPlacement.text,jointPlacement.icon);placementChanged=placementChanged||jointPlacement.text!==prevOpacity.text.placed||jointPlacement.icon!==prevOpacity.icon.placed}else{this.opacities[crossTileID]=new JointOpacityState(null,increment,jointPlacement.text,jointPlacement.icon,jointPlacement.skipFade);placementChanged=placementChanged||jointPlacement.text||jointPlacement.icon}}for(const crossTileID in prevOpacities){const prevOpacity=prevOpacities[crossTileID];if(!this.opacities[crossTileID]){const jointOpacity=new JointOpacityState(prevOpacity,increment,false,false);if(!jointOpacity.isHidden()){this.opacities[crossTileID]=jointOpacity;placementChanged=placementChanged||prevOpacity.text.placed||prevOpacity.icon.placed}}}for(const crossTileID in prevOffsets){if(!this.variableOffsets[crossTileID]&&this.opacities[crossTileID]&&!this.opacities[crossTileID].isHidden()){this.variableOffsets[crossTileID]=prevOffsets[crossTileID]}}for(const crossTileID in prevOrientations){if(!this.placedOrientations[crossTileID]&&this.opacities[crossTileID]&&!this.opacities[crossTileID].isHidden()){this.placedOrientations[crossTileID]=prevOrientations[crossTileID]}}if(prevPlacement&&prevPlacement.lastPlacementChangeTime===undefined){throw new Error("Last placement time for previous placement is not defined")}if(placementChanged){this.lastPlacementChangeTime=now}else if(typeof this.lastPlacementChangeTime!=="number"){this.lastPlacementChangeTime=prevPlacement?prevPlacement.lastPlacementChangeTime:now}}updateLayerOpacities(styleLayer,tiles){const seenCrossTileIDs={};for(const tile of tiles){const symbolBucket=tile.getBucket(styleLayer);if(symbolBucket&&tile.latestFeatureIndex&&styleLayer.id===symbolBucket.layerIds[0]){this.updateBucketOpacities(symbolBucket,seenCrossTileIDs,tile.collisionBoxArray)}}}updateBucketOpacities(bucket,seenCrossTileIDs,collisionBoxArray){if(bucket.hasTextData()){bucket.text.opacityVertexArray.clear();bucket.text.hasVisibleVertices=false}if(bucket.hasIconData()){bucket.icon.opacityVertexArray.clear();bucket.icon.hasVisibleVertices=false}if(bucket.hasIconCollisionBoxData())bucket.iconCollisionBox.collisionVertexArray.clear();if(bucket.hasTextCollisionBoxData())bucket.textCollisionBox.collisionVertexArray.clear();const layer=bucket.layers[0];const layout=layer.layout;const duplicateOpacityState=new JointOpacityState(null,0,false,false,true);const textAllowOverlap=layout.get("text-allow-overlap");const iconAllowOverlap=layout.get("icon-allow-overlap");const hasVariablePlacement=layer._unevaluatedLayout.hasValue("text-variable-anchor")||layer._unevaluatedLayout.hasValue("text-variable-anchor-offset");const rotateWithMap=layout.get("text-rotation-alignment")==="map";const pitchWithMap=layout.get("text-pitch-alignment")==="map";const hasIconTextFit=layout.get("icon-text-fit")!=="none";const defaultOpacityState=new JointOpacityState(null,0,textAllowOverlap&&(iconAllowOverlap||!bucket.hasIconData()||layout.get("icon-optional")),iconAllowOverlap&&(textAllowOverlap||!bucket.hasTextData()||layout.get("text-optional")),true);if(!bucket.collisionArrays&&collisionBoxArray&&(bucket.hasIconCollisionBoxData()||bucket.hasTextCollisionBoxData())){bucket.deserializeCollisionBoxes(collisionBoxArray)}const addOpacities=(iconOrText,numVertices,opacity)=>{for(let i=0;i0||numVerticalGlyphVertices>0;const hasIcon=symbolInstance.numIconVertices>0;const placedOrientation=this.placedOrientations[symbolInstance.crossTileID];const horizontalHidden=placedOrientation===performance$1.WritingMode.vertical;const verticalHidden=placedOrientation===performance$1.WritingMode.horizontal||placedOrientation===performance$1.WritingMode.horizontalOnly;if(hasText){const packedOpacity=packOpacity(opacityState.text);const horizontalOpacity=horizontalHidden?PACKED_HIDDEN_OPACITY:packedOpacity;addOpacities(bucket.text,numHorizontalGlyphVertices,horizontalOpacity);const verticalOpacity=verticalHidden?PACKED_HIDDEN_OPACITY:packedOpacity;addOpacities(bucket.text,numVerticalGlyphVertices,verticalOpacity);const symbolHidden=opacityState.text.isHidden();[symbolInstance.rightJustifiedTextSymbolIndex,symbolInstance.centerJustifiedTextSymbolIndex,symbolInstance.leftJustifiedTextSymbolIndex].forEach((index=>{if(index>=0){bucket.text.placedSymbolArray.get(index).hidden=symbolHidden||horizontalHidden?1:0}}));if(symbolInstance.verticalPlacedTextSymbolIndex>=0){bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).hidden=symbolHidden||verticalHidden?1:0}const prevOffset=this.variableOffsets[symbolInstance.crossTileID];if(prevOffset){this.markUsedJustification(bucket,prevOffset.anchor,symbolInstance,placedOrientation)}const prevOrientation=this.placedOrientations[symbolInstance.crossTileID];if(prevOrientation){this.markUsedJustification(bucket,"left",symbolInstance,prevOrientation);this.markUsedOrientation(bucket,prevOrientation,symbolInstance)}}if(hasIcon){const packedOpacity=packOpacity(opacityState.icon);const useHorizontal=!(hasIconTextFit&&symbolInstance.verticalPlacedIconSymbolIndex&&horizontalHidden);if(symbolInstance.placedIconSymbolIndex>=0){const horizontalOpacity=useHorizontal?packedOpacity:PACKED_HIDDEN_OPACITY;addOpacities(bucket.icon,symbolInstance.numIconVertices,horizontalOpacity);bucket.icon.placedSymbolArray.get(symbolInstance.placedIconSymbolIndex).hidden=opacityState.icon.isHidden()}if(symbolInstance.verticalPlacedIconSymbolIndex>=0){const verticalOpacity=!useHorizontal?packedOpacity:PACKED_HIDDEN_OPACITY;addOpacities(bucket.icon,symbolInstance.numVerticalIconVertices,verticalOpacity);bucket.icon.placedSymbolArray.get(symbolInstance.verticalPlacedIconSymbolIndex).hidden=opacityState.icon.isHidden()}}if(bucket.hasIconCollisionBoxData()||bucket.hasTextCollisionBoxData()){const collisionArrays=bucket.collisionArrays[s];if(collisionArrays){let shift=new performance$1.Point(0,0);if(collisionArrays.textBox||collisionArrays.verticalTextBox){let used=true;if(hasVariablePlacement){const variableOffset=this.variableOffsets[crossTileID];if(variableOffset){shift=calculateVariableLayoutShift(variableOffset.anchor,variableOffset.width,variableOffset.height,variableOffset.textOffset,variableOffset.textBoxScale);if(rotateWithMap){shift._rotate(pitchWithMap?this.transform.angle:-this.transform.angle)}}else{used=false}}if(collisionArrays.textBox){updateCollisionVertices(bucket.textCollisionBox.collisionVertexArray,opacityState.text.placed,!used||horizontalHidden,shift.x,shift.y)}if(collisionArrays.verticalTextBox){updateCollisionVertices(bucket.textCollisionBox.collisionVertexArray,opacityState.text.placed,!used||verticalHidden,shift.x,shift.y)}}const verticalIconUsed=Boolean(!verticalHidden&&collisionArrays.verticalIconBox);if(collisionArrays.iconBox){updateCollisionVertices(bucket.iconCollisionBox.collisionVertexArray,opacityState.icon.placed,verticalIconUsed,hasIconTextFit?shift.x:0,hasIconTextFit?shift.y:0)}if(collisionArrays.verticalIconBox){updateCollisionVertices(bucket.iconCollisionBox.collisionVertexArray,opacityState.icon.placed,!verticalIconUsed,hasIconTextFit?shift.x:0,hasIconTextFit?shift.y:0)}}}}bucket.sortFeatures(this.transform.angle);if(this.retainedQueryData[bucket.bucketInstanceId]){this.retainedQueryData[bucket.bucketInstanceId].featureSortOrder=bucket.featureSortOrder}if(bucket.hasTextData()&&bucket.text.opacityVertexBuffer){bucket.text.opacityVertexBuffer.updateData(bucket.text.opacityVertexArray)}if(bucket.hasIconData()&&bucket.icon.opacityVertexBuffer){bucket.icon.opacityVertexBuffer.updateData(bucket.icon.opacityVertexArray)}if(bucket.hasIconCollisionBoxData()&&bucket.iconCollisionBox.collisionVertexBuffer){bucket.iconCollisionBox.collisionVertexBuffer.updateData(bucket.iconCollisionBox.collisionVertexArray)}if(bucket.hasTextCollisionBoxData()&&bucket.textCollisionBox.collisionVertexBuffer){bucket.textCollisionBox.collisionVertexBuffer.updateData(bucket.textCollisionBox.collisionVertexArray)}if(bucket.text.opacityVertexArray.length!==bucket.text.layoutVertexArray.length/4)throw new Error(`bucket.text.opacityVertexArray.length (= ${bucket.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${bucket.text.layoutVertexArray.length}) / 4`);if(bucket.icon.opacityVertexArray.length!==bucket.icon.layoutVertexArray.length/4)throw new Error(`bucket.icon.opacityVertexArray.length (= ${bucket.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${bucket.icon.layoutVertexArray.length}) / 4`);if(bucket.bucketInstanceId in this.collisionCircleArrays){const instance=this.collisionCircleArrays[bucket.bucketInstanceId];bucket.placementInvProjMatrix=instance.invProjMatrix;bucket.placementViewportMatrix=instance.viewportMatrix;bucket.collisionCircleArray=instance.circles;delete this.collisionCircleArrays[bucket.bucketInstanceId]}}symbolFadeChange(now){return this.fadeDuration===0?1:(now-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(zoom){return Math.max(0,(this.transform.zoom-zoom)/1.5)}hasTransitions(now){return this.stale||now-this.lastPlacementChangeTimenow}setStale(){this.stale=true}}function updateCollisionVertices(collisionVertexArray,placed,notUsed,shiftX,shiftY){collisionVertexArray.emplaceBack(placed?1:0,notUsed?1:0,shiftX||0,shiftY||0);collisionVertexArray.emplaceBack(placed?1:0,notUsed?1:0,shiftX||0,shiftY||0);collisionVertexArray.emplaceBack(placed?1:0,notUsed?1:0,shiftX||0,shiftY||0);collisionVertexArray.emplaceBack(placed?1:0,notUsed?1:0,shiftX||0,shiftY||0)}const shift25=Math.pow(2,25);const shift24=Math.pow(2,24);const shift17=Math.pow(2,17);const shift16=Math.pow(2,16);const shift9=Math.pow(2,9);const shift8=Math.pow(2,8);const shift1=Math.pow(2,1);function packOpacity(opacityState){if(opacityState.opacity===0&&!opacityState.placed){return 0}else if(opacityState.opacity===1&&opacityState.placed){return 4294967295}const targetBit=opacityState.placed?1:0;const opacityBits=Math.floor(opacityState.opacity*127);return opacityBits*shift25+targetBit*shift24+opacityBits*shift17+targetBit*shift16+opacityBits*shift9+targetBit*shift8+opacityBits*shift1+targetBit}const PACKED_HIDDEN_OPACITY=0;class LayerPlacement{constructor(styleLayer){this._sortAcrossTiles=styleLayer.layout.get("symbol-z-order")!=="viewport-y"&&!styleLayer.layout.get("symbol-sort-key").isConstant();this._currentTileIndex=0;this._currentPartIndex=0;this._seenCrossTileIDs={};this._bucketParts=[]}continuePlacement(tiles,placement,showCollisionBoxes,styleLayer,shouldPausePlacement){const bucketParts=this._bucketParts;while(this._currentTileIndexa.sortKey-b.sortKey))}while(this._currentPartIndexthis._forceFullPlacement?false:browser.now()-startTime>2;while(this._currentPlacementIndex>=0){const layerId=order[this._currentPlacementIndex];const layer=layers[layerId];const placementZoom=this.placement.collisionIndex.transform.zoom;if(layer.type==="symbol"&&(!layer.minzoom||layer.minzoom<=placementZoom)&&(!layer.maxzoom||layer.maxzoom>placementZoom)){if(!this._inProgressLayer){this._inProgressLayer=new LayerPlacement(layer)}const pausePlacement=this._inProgressLayer.continuePlacement(layerTiles[layer.source],this.placement,this._showCollisionBoxes,layer,shouldPausePlacement);if(pausePlacement){return}delete this._inProgressLayer}this._currentPlacementIndex--}this._done=true}commit(now){this.placement.commit(now);return this.placement}}const roundingFactor=512/performance$1.EXTENT/2;const KDBUSH_THRESHHOLD=128;class TileLayerIndex{constructor(tileID,symbolInstances,bucketInstanceId){this.tileID=tileID;this.bucketInstanceId=bucketInstanceId;this._symbolsByKey={};const symbolInstancesByKey=new Map;for(let i=0;i({x:Math.floor(symbolInstance.anchorX*roundingFactor),y:Math.floor(symbolInstance.anchorY*roundingFactor)})));const crossTileIDs=symbols.map((v=>v.crossTileID));const entry={positions:positions,crossTileIDs:crossTileIDs};if(entry.positions.length>KDBUSH_THRESHHOLD){const index=new performance$1.KDBush(entry.positions.length,16,Uint16Array);for(const{x:x,y:y}of entry.positions)index.add(x,y);index.finish();delete entry.positions;entry.index=index}this._symbolsByKey[key]=entry}}getScaledCoordinates(symbolInstance,childTileID){const{x:localX,y:localY,z:localZ}=this.tileID.canonical;const{x:x,y:y,z:z}=childTileID.canonical;const zDifference=z-localZ;const scale=roundingFactor/Math.pow(2,zDifference);const xWorld=(x*performance$1.EXTENT+symbolInstance.anchorX)*scale;const yWorld=(y*performance$1.EXTENT+symbolInstance.anchorY)*scale;const xOffset=localX*performance$1.EXTENT*roundingFactor;const yOffset=localY*performance$1.EXTENT*roundingFactor;const result={x:Math.floor(xWorld-xOffset),y:Math.floor(yWorld-yOffset)};return result}findMatches(symbolInstances,newTileID,zoomCrossTileIDs){const tolerance=this.tileID.canonical.zcrossTileIDs))}}class CrossTileIDs{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class CrossTileSymbolLayerIndex{constructor(){this.indexes={};this.usedCrossTileIDs={};this.lng=0}handleWrapJump(lng){const wrapDelta=Math.round((lng-this.lng)/360);if(wrapDelta!==0){for(const zoom in this.indexes){const zoomIndexes=this.indexes[zoom];const newZoomIndex={};for(const key in zoomIndexes){const index=zoomIndexes[key];index.tileID=index.tileID.unwrapTo(index.tileID.wrap+wrapDelta);newZoomIndex[index.tileID.key]=index}this.indexes[zoom]=newZoomIndex}}this.lng=lng}addBucket(tileID,bucket,crossTileIDs){if(this.indexes[tileID.overscaledZ]&&this.indexes[tileID.overscaledZ][tileID.key]){if(this.indexes[tileID.overscaledZ][tileID.key].bucketInstanceId===bucket.bucketInstanceId){return false}else{this.removeBucketCrossTileIDs(tileID.overscaledZ,this.indexes[tileID.overscaledZ][tileID.key])}}for(let i=0;itileID.overscaledZ){for(const id in zoomIndexes){const childIndex=zoomIndexes[id];if(childIndex.tileID.isChildOf(tileID)){childIndex.findMatches(bucket.symbolInstances,tileID,zoomCrossTileIDs)}}}else{const parentCoord=tileID.scaledTo(Number(zoom));const parentIndex=zoomIndexes[parentCoord.key];if(parentIndex){parentIndex.findMatches(bucket.symbolInstances,tileID,zoomCrossTileIDs)}}}for(let i=0;i{usedLayerMap[usedLayer]=true}));for(const layerId in this.layerIndexes){if(!usedLayerMap[layerId]){delete this.layerIndexes[layerId]}}}}const emitValidationErrors=(evented,errors)=>performance$1.emitValidationErrors(evented,errors&&errors.filter((error=>error.identifier!=="source.canvas")));const empty=performance$1.emptyStyle();class Style extends performance$1.Evented{constructor(map,options={}){super();this._rtlTextPluginStateChange=()=>{for(const id in this.sourceCaches){const sourceType=this.sourceCaches[id].getSource().type;if(sourceType==="vector"||sourceType==="geojson"){this.sourceCaches[id].reload()}}};this.map=map;this.dispatcher=new Dispatcher(getGlobalWorkerPool(),map._getMapId());this.dispatcher.registerMessageHandler("getGlyphs",((mapId,params)=>this.getGlyphs(mapId,params)));this.dispatcher.registerMessageHandler("getImages",((mapId,params)=>this.getImages(mapId,params)));this.imageManager=new ImageManager;this.imageManager.setEventedParent(this);this.glyphManager=new GlyphManager(map._requestManager,options.localIdeographFontFamily);this.lineAtlas=new LineAtlas(256,512);this.crossTileSymbolIndex=new CrossTileSymbolIndex;this._spritesImagesIds={};this._layers={};this._order=[];this.sourceCaches={};this.zoomHistory=new performance$1.ZoomHistory;this._loaded=false;this._availableImages=[];this._resetUpdates();this.dispatcher.broadcast("setReferrer",performance$1.getReferrer());rtlMainThreadPluginFactory().on("pluginStateChange",this._rtlTextPluginStateChange);this.on("data",(event=>{if(event.dataType!=="source"||event.sourceDataType!=="metadata"){return}const sourceCache=this.sourceCaches[event.sourceId];if(!sourceCache){return}const source=sourceCache.getSource();if(!source||!source.vectorLayerIds){return}for(const layerId in this._layers){const layer=this._layers[layerId];if(layer.source===source.id){this._validateLayer(layer)}}}))}loadURL(url,options={},previousStyle){this.fire(new performance$1.Event("dataloading",{dataType:"style"}));options.validate=typeof options.validate==="boolean"?options.validate:true;const request=this.map._requestManager.transformRequest(url,ResourceType.Style);this._loadStyleRequest=new AbortController;performance$1.getJSON(request,this._loadStyleRequest).then((response=>{this._loadStyleRequest=null;this._load(response.data,options,previousStyle)})).catch((error=>{this._loadStyleRequest=null;if(error){this.fire(new performance$1.ErrorEvent(error))}}))}loadJSON(json,options={},previousStyle){this.fire(new performance$1.Event("dataloading",{dataType:"style"}));this._frameRequest=new AbortController;browser.frameAsync(this._frameRequest).then((()=>{this._frameRequest=null;options.validate=options.validate!==false;this._load(json,options,previousStyle)})).catch((()=>{}))}loadEmpty(){this.fire(new performance$1.Event("dataloading",{dataType:"style"}));this._load(empty,{validate:false})}_load(json,options,previousStyle){var _a;const nextState=options.transformStyle?options.transformStyle(previousStyle,json):json;if(options.validate&&emitValidationErrors(this,performance$1.validateStyle(nextState))){return}this._loaded=true;this.stylesheet=nextState;for(const id in nextState.sources){this.addSource(id,nextState.sources[id],{validate:false})}if(nextState.sprite){this._loadSprite(nextState.sprite)}else{this.imageManager.setLoaded(true)}this.glyphManager.setURL(nextState.glyphs);this._createLayers();this.light=new Light(this.stylesheet.light);this.map.setTerrain((_a=this.stylesheet.terrain)!==null&&_a!==void 0?_a:null);this.fire(new performance$1.Event("data",{dataType:"style"}));this.fire(new performance$1.Event("style.load"))}_createLayers(){const dereferencedLayers=performance$1.derefLayers(this.stylesheet.layers);this.dispatcher.broadcast("setLayers",dereferencedLayers);this._order=dereferencedLayers.map((layer=>layer.id));this._layers={};this._serializedLayers=null;for(const layer of dereferencedLayers){const styledLayer=performance$1.createStyleLayer(layer);styledLayer.setEventedParent(this,{layer:{id:layer.id}});this._layers[layer.id]=styledLayer}}_loadSprite(sprite,isUpdate=false,completion=undefined){this.imageManager.setLoaded(false);this._spriteRequest=new AbortController;let err;loadSprite(sprite,this.map._requestManager,this.map.getPixelRatio(),this._spriteRequest).then((images=>{this._spriteRequest=null;if(images){for(const spriteId in images){this._spritesImagesIds[spriteId]=[];const imagesToRemove=this._spritesImagesIds[spriteId]?this._spritesImagesIds[spriteId].filter((id=>!(id in images))):[];for(const id of imagesToRemove){this.imageManager.removeImage(id);this._changedImages[id]=true}for(const id in images[spriteId]){const imageId=spriteId==="default"?id:`${spriteId}:${id}`;this._spritesImagesIds[spriteId].push(imageId);if(imageId in this.imageManager.images){this.imageManager.updateImage(imageId,images[spriteId][id],false)}else{this.imageManager.addImage(imageId,images[spriteId][id])}if(isUpdate){this._changedImages[imageId]=true}}}}})).catch((error=>{this._spriteRequest=null;err=error;this.fire(new performance$1.ErrorEvent(err))})).finally((()=>{this.imageManager.setLoaded(true);this._availableImages=this.imageManager.listImages();if(isUpdate){this._changed=true}this.dispatcher.broadcast("setImages",this._availableImages);this.fire(new performance$1.Event("data",{dataType:"style"}));if(completion){completion(err)}}))}_unloadSprite(){for(const id of Object.values(this._spritesImagesIds).flat()){this.imageManager.removeImage(id);this._changedImages[id]=true}this._spritesImagesIds={};this._availableImages=this.imageManager.listImages();this._changed=true;this.dispatcher.broadcast("setImages",this._availableImages);this.fire(new performance$1.Event("data",{dataType:"style"}))}_validateLayer(layer){const sourceCache=this.sourceCaches[layer.source];if(!sourceCache){return}const sourceLayer=layer.sourceLayer;if(!sourceLayer){return}const source=sourceCache.getSource();if(source.type==="geojson"||source.vectorLayerIds&&source.vectorLayerIds.indexOf(sourceLayer)===-1){this.fire(new performance$1.ErrorEvent(new Error(`Source layer "${sourceLayer}" `+`does not exist on source "${source.id}" `+`as specified by style layer "${layer.id}".`)))}}loaded(){if(!this._loaded)return false;if(Object.keys(this._updatedSources).length)return false;for(const id in this.sourceCaches)if(!this.sourceCaches[id].loaded())return false;if(!this.imageManager.isLoaded())return false;return true}_serializeByIds(ids){const serializedLayersDictionary=this._serializedAllLayers();if(!ids||ids.length===0){return Object.values(serializedLayersDictionary)}const serializedLayers=[];for(const id of ids){if(serializedLayersDictionary[id]){serializedLayers.push(serializedLayersDictionary[id])}}return serializedLayers}_serializedAllLayers(){let serializedLayers=this._serializedLayers;if(serializedLayers){return serializedLayers}serializedLayers=this._serializedLayers={};const allLayerIds=Object.keys(this._layers);for(const layerId of allLayerIds){const layer=this._layers[layerId];if(layer.type!=="custom"){serializedLayers[layerId]=layer.serialize()}}return serializedLayers}hasTransitions(){if(this.light&&this.light.hasTransition()){return true}for(const id in this.sourceCaches){if(this.sourceCaches[id].hasTransition()){return true}}for(const id in this._layers){if(this._layers[id].hasTransition()){return true}}return false}_checkLoaded(){if(!this._loaded){throw new Error("Style is not done loading.")}}update(parameters){if(!this._loaded){return}const changed=this._changed;if(this._changed){const updatedIds=Object.keys(this._updatedLayers);const removedIds=Object.keys(this._removedLayers);if(updatedIds.length||removedIds.length){this._updateWorkerLayers(updatedIds,removedIds)}for(const id in this._updatedSources){const action=this._updatedSources[id];if(action==="reload"){this._reloadSource(id)}else if(action==="clear"){this._clearSource(id)}else{throw new Error(`Invalid action ${action}`)}}this._updateTilesForChangedImages();this._updateTilesForChangedGlyphs();for(const id in this._updatedPaintProps){this._layers[id].updateTransitions(parameters)}this.light.updateTransitions(parameters);this._resetUpdates()}const sourcesUsedBefore={};for(const sourceId in this.sourceCaches){const sourceCache=this.sourceCaches[sourceId];sourcesUsedBefore[sourceId]=sourceCache.used;sourceCache.used=false}for(const layerId of this._order){const layer=this._layers[layerId];layer.recalculate(parameters,this._availableImages);if(!layer.isHidden(parameters.zoom)&&layer.source){this.sourceCaches[layer.source].used=true}}for(const sourceId in sourcesUsedBefore){const sourceCache=this.sourceCaches[sourceId];if(sourcesUsedBefore[sourceId]!==sourceCache.used){sourceCache.fire(new performance$1.Event("data",{sourceDataType:"visibility",dataType:"source",sourceId:sourceId}))}}this.light.recalculate(parameters);this.z=parameters.zoom;if(changed){this.fire(new performance$1.Event("data",{dataType:"style"}))}}_updateTilesForChangedImages(){const changedImages=Object.keys(this._changedImages);if(changedImages.length){for(const name in this.sourceCaches){this.sourceCaches[name].reloadTilesForDependencies(["icons","patterns"],changedImages)}this._changedImages={}}}_updateTilesForChangedGlyphs(){if(this._glyphsDidChange){for(const name in this.sourceCaches){this.sourceCaches[name].reloadTilesForDependencies(["glyphs"],[""])}this._glyphsDidChange=false}}_updateWorkerLayers(updatedIds,removedIds){this.dispatcher.broadcast("updateLayers",{layers:this._serializeByIds(updatedIds),removedIds:removedIds})}_resetUpdates(){this._changed=false;this._updatedLayers={};this._removedLayers={};this._updatedSources={};this._updatedPaintProps={};this._changedImages={};this._glyphsDidChange=false}setState(nextState,options={}){var _a;this._checkLoaded();const serializedStyle=this.serialize();nextState=options.transformStyle?options.transformStyle(serializedStyle,nextState):nextState;const validate=(_a=options.validate)!==null&&_a!==void 0?_a:true;if(validate&&emitValidationErrors(this,performance$1.validateStyle(nextState)))return false;nextState=performance$1.clone$1(nextState);nextState.layers=performance$1.derefLayers(nextState.layers);const changes=performance$1.diffStyles(serializedStyle,nextState);const operations=this._getOperationsToPerform(changes);if(operations.unimplemented.length>0){throw new Error(`Unimplemented: ${operations.unimplemented.join(", ")}.`)}if(operations.operations.length===0){return false}for(const styleChangeOperation of operations.operations){styleChangeOperation()}this.stylesheet=nextState;this._serializedLayers=null;return true}_getOperationsToPerform(diff){const operations=[];const unimplemented=[];for(const op of diff){switch(op.command){case"setCenter":case"setZoom":case"setBearing":case"setPitch":continue;case"addLayer":operations.push((()=>this.addLayer.apply(this,op.args)));break;case"removeLayer":operations.push((()=>this.removeLayer.apply(this,op.args)));break;case"setPaintProperty":operations.push((()=>this.setPaintProperty.apply(this,op.args)));break;case"setLayoutProperty":operations.push((()=>this.setLayoutProperty.apply(this,op.args)));break;case"setFilter":operations.push((()=>this.setFilter.apply(this,op.args)));break;case"addSource":operations.push((()=>this.addSource.apply(this,op.args)));break;case"removeSource":operations.push((()=>this.removeSource.apply(this,op.args)));break;case"setLayerZoomRange":operations.push((()=>this.setLayerZoomRange.apply(this,op.args)));break;case"setLight":operations.push((()=>this.setLight.apply(this,op.args)));break;case"setGeoJSONSourceData":operations.push((()=>this.setGeoJSONSourceData.apply(this,op.args)));break;case"setGlyphs":operations.push((()=>this.setGlyphs.apply(this,op.args)));break;case"setSprite":operations.push((()=>this.setSprite.apply(this,op.args)));break;case"setTerrain":operations.push((()=>this.map.setTerrain.apply(this,op.args)));break;case"setTransition":operations.push((()=>{}));break;default:unimplemented.push(op.command);break}}return{operations:operations,unimplemented:unimplemented}}addImage(id,image){if(this.getImage(id)){return this.fire(new performance$1.ErrorEvent(new Error(`An image named "${id}" already exists.`)))}this.imageManager.addImage(id,image);this._afterImageUpdated(id)}updateImage(id,image){this.imageManager.updateImage(id,image)}getImage(id){return this.imageManager.getImage(id)}removeImage(id){if(!this.getImage(id)){return this.fire(new performance$1.ErrorEvent(new Error(`An image named "${id}" does not exist.`)))}this.imageManager.removeImage(id);this._afterImageUpdated(id)}_afterImageUpdated(id){this._availableImages=this.imageManager.listImages();this._changedImages[id]=true;this._changed=true;this.dispatcher.broadcast("setImages",this._availableImages);this.fire(new performance$1.Event("data",{dataType:"style"}))}listImages(){this._checkLoaded();return this.imageManager.listImages()}addSource(id,source,options={}){this._checkLoaded();if(this.sourceCaches[id]!==undefined){throw new Error(`Source "${id}" already exists.`)}if(!source.type){throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(source).join(", ")}.`)}const builtIns=["vector","raster","geojson","video","image"];const shouldValidate=builtIns.indexOf(source.type)>=0;if(shouldValidate&&this._validate(performance$1.validateStyle.source,`sources.${id}`,source,null,options))return;if(this.map&&this.map._collectResourceTiming)source.collectResourceTiming=true;const sourceCache=this.sourceCaches[id]=new SourceCache(id,source,this.dispatcher);sourceCache.style=this;sourceCache.setEventedParent(this,(()=>({isSourceLoaded:sourceCache.loaded(),source:sourceCache.serialize(),sourceId:id})));sourceCache.onAdd(this.map);this._changed=true}removeSource(id){this._checkLoaded();if(this.sourceCaches[id]===undefined){throw new Error("There is no source with this ID")}for(const layerId in this._layers){if(this._layers[layerId].source===id){return this.fire(new performance$1.ErrorEvent(new Error(`Source "${id}" cannot be removed while layer "${layerId}" is using it.`)))}}const sourceCache=this.sourceCaches[id];delete this.sourceCaches[id];delete this._updatedSources[id];sourceCache.fire(new performance$1.Event("data",{sourceDataType:"metadata",dataType:"source",sourceId:id}));sourceCache.setEventedParent(null);sourceCache.onRemove(this.map);this._changed=true}setGeoJSONSourceData(id,data){this._checkLoaded();if(this.sourceCaches[id]===undefined)throw new Error(`There is no source with this ID=${id}`);const geojsonSource=this.sourceCaches[id].getSource();if(geojsonSource.type!=="geojson")throw new Error(`geojsonSource.type is ${geojsonSource.type}, which is !== 'geojson`);geojsonSource.setData(data);this._changed=true}getSource(id){return this.sourceCaches[id]&&this.sourceCaches[id].getSource()}addLayer(layerObject,before,options={}){this._checkLoaded();const id=layerObject.id;if(this.getLayer(id)){this.fire(new performance$1.ErrorEvent(new Error(`Layer "${id}" already exists on this map.`)));return}let layer;if(layerObject.type==="custom"){if(emitValidationErrors(this,performance$1.validateCustomStyleLayer(layerObject)))return;layer=performance$1.createStyleLayer(layerObject)}else{if("source"in layerObject&&typeof layerObject.source==="object"){this.addSource(id,layerObject.source);layerObject=performance$1.clone$1(layerObject);layerObject=performance$1.extend(layerObject,{source:id})}if(this._validate(performance$1.validateStyle.layer,`layers.${id}`,layerObject,{arrayIndex:-1},options))return;layer=performance$1.createStyleLayer(layerObject);this._validateLayer(layer);layer.setEventedParent(this,{layer:{id:id}})}const index=before?this._order.indexOf(before):this._order.length;if(before&&index===-1){this.fire(new performance$1.ErrorEvent(new Error(`Cannot add layer "${id}" before non-existing layer "${before}".`)));return}this._order.splice(index,0,id);this._layerOrderChanged=true;this._layers[id]=layer;if(this._removedLayers[id]&&layer.source&&layer.type!=="custom"){const removed=this._removedLayers[id];delete this._removedLayers[id];if(removed.type!==layer.type){this._updatedSources[layer.source]="clear"}else{this._updatedSources[layer.source]="reload";this.sourceCaches[layer.source].pause()}}this._updateLayer(layer);if(layer.onAdd){layer.onAdd(this.map)}}moveLayer(id,before){this._checkLoaded();this._changed=true;const layer=this._layers[id];if(!layer){this.fire(new performance$1.ErrorEvent(new Error(`The layer '${id}' does not exist in the map's style and cannot be moved.`)));return}if(id===before){return}const index=this._order.indexOf(id);this._order.splice(index,1);const newIndex=before?this._order.indexOf(before):this._order.length;if(before&&newIndex===-1){this.fire(new performance$1.ErrorEvent(new Error(`Cannot move layer "${id}" before non-existing layer "${before}".`)));return}this._order.splice(newIndex,0,id);this._layerOrderChanged=true}removeLayer(id){this._checkLoaded();const layer=this._layers[id];if(!layer){this.fire(new performance$1.ErrorEvent(new Error(`Cannot remove non-existing layer "${id}".`)));return}layer.setEventedParent(null);const index=this._order.indexOf(id);this._order.splice(index,1);this._layerOrderChanged=true;this._changed=true;this._removedLayers[id]=layer;delete this._layers[id];if(this._serializedLayers){delete this._serializedLayers[id]}delete this._updatedLayers[id];delete this._updatedPaintProps[id];if(layer.onRemove){layer.onRemove(this.map)}}getLayer(id){return this._layers[id]}getLayersOrder(){return[...this._order]}hasLayer(id){return id in this._layers}setLayerZoomRange(layerId,minzoom,maxzoom){this._checkLoaded();const layer=this.getLayer(layerId);if(!layer){this.fire(new performance$1.ErrorEvent(new Error(`Cannot set the zoom range of non-existing layer "${layerId}".`)));return}if(layer.minzoom===minzoom&&layer.maxzoom===maxzoom)return;if(minzoom!=null){layer.minzoom=minzoom}if(maxzoom!=null){layer.maxzoom=maxzoom}this._updateLayer(layer)}setFilter(layerId,filter,options={}){this._checkLoaded();const layer=this.getLayer(layerId);if(!layer){this.fire(new performance$1.ErrorEvent(new Error(`Cannot filter non-existing layer "${layerId}".`)));return}if(performance$1.deepEqual(layer.filter,filter)){return}if(filter===null||filter===undefined){layer.filter=undefined;this._updateLayer(layer);return}if(this._validate(performance$1.validateStyle.filter,`layers.${layer.id}.filter`,filter,null,options)){return}layer.filter=performance$1.clone$1(filter);this._updateLayer(layer)}getFilter(layer){return performance$1.clone$1(this.getLayer(layer).filter)}setLayoutProperty(layerId,name,value,options={}){this._checkLoaded();const layer=this.getLayer(layerId);if(!layer){this.fire(new performance$1.ErrorEvent(new Error(`Cannot style non-existing layer "${layerId}".`)));return}if(performance$1.deepEqual(layer.getLayoutProperty(name),value))return;layer.setLayoutProperty(name,value,options);this._updateLayer(layer)}getLayoutProperty(layerId,name){const layer=this.getLayer(layerId);if(!layer){this.fire(new performance$1.ErrorEvent(new Error(`Cannot get style of non-existing layer "${layerId}".`)));return}return layer.getLayoutProperty(name)}setPaintProperty(layerId,name,value,options={}){this._checkLoaded();const layer=this.getLayer(layerId);if(!layer){this.fire(new performance$1.ErrorEvent(new Error(`Cannot style non-existing layer "${layerId}".`)));return}if(performance$1.deepEqual(layer.getPaintProperty(name),value))return;const requiresRelayout=layer.setPaintProperty(name,value,options);if(requiresRelayout){this._updateLayer(layer)}this._changed=true;this._updatedPaintProps[layerId]=true}getPaintProperty(layer,name){return this.getLayer(layer).getPaintProperty(name)}setFeatureState(target,state){this._checkLoaded();const sourceId=target.source;const sourceLayer=target.sourceLayer;const sourceCache=this.sourceCaches[sourceId];if(sourceCache===undefined){this.fire(new performance$1.ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`)));return}const sourceType=sourceCache.getSource().type;if(sourceType==="geojson"&&sourceLayer){this.fire(new performance$1.ErrorEvent(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));return}if(sourceType==="vector"&&!sourceLayer){this.fire(new performance$1.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));return}if(target.id===undefined){this.fire(new performance$1.ErrorEvent(new Error("The feature id parameter must be provided.")))}sourceCache.setFeatureState(sourceLayer,target.id,state)}removeFeatureState(target,key){this._checkLoaded();const sourceId=target.source;const sourceCache=this.sourceCaches[sourceId];if(sourceCache===undefined){this.fire(new performance$1.ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`)));return}const sourceType=sourceCache.getSource().type;const sourceLayer=sourceType==="vector"?target.sourceLayer:undefined;if(sourceType==="vector"&&!sourceLayer){this.fire(new performance$1.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));return}if(key&&(typeof target.id!=="string"&&typeof target.id!=="number")){this.fire(new performance$1.ErrorEvent(new Error("A feature id is required to remove its specific state property.")));return}sourceCache.removeFeatureState(sourceLayer,target.id,key)}getFeatureState(target){this._checkLoaded();const sourceId=target.source;const sourceLayer=target.sourceLayer;const sourceCache=this.sourceCaches[sourceId];if(sourceCache===undefined){this.fire(new performance$1.ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`)));return}const sourceType=sourceCache.getSource().type;if(sourceType==="vector"&&!sourceLayer){this.fire(new performance$1.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));return}if(target.id===undefined){this.fire(new performance$1.ErrorEvent(new Error("The feature id parameter must be provided.")))}return sourceCache.getFeatureState(sourceLayer,target.id)}getTransition(){return performance$1.extend({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)}serialize(){if(!this._loaded)return;const sources=performance$1.mapObject(this.sourceCaches,(source=>source.serialize()));const layers=this._serializeByIds(this._order);const terrain=this.map.getTerrain()||undefined;const myStyleSheet=this.stylesheet;return performance$1.filterObject({version:myStyleSheet.version,name:myStyleSheet.name,metadata:myStyleSheet.metadata,light:myStyleSheet.light,center:myStyleSheet.center,zoom:myStyleSheet.zoom,bearing:myStyleSheet.bearing,pitch:myStyleSheet.pitch,sprite:myStyleSheet.sprite,glyphs:myStyleSheet.glyphs,transition:myStyleSheet.transition,sources:sources,layers:layers,terrain:terrain},(value=>value!==undefined))}_updateLayer(layer){this._updatedLayers[layer.id]=true;if(layer.source&&!this._updatedSources[layer.source]&&this.sourceCaches[layer.source].getSource().type!=="raster"){this._updatedSources[layer.source]="reload";this.sourceCaches[layer.source].pause()}this._serializedLayers=null;this._changed=true}_flattenAndSortRenderedFeatures(sourceResults){const isLayer3D=layerId=>this._layers[layerId].type==="fill-extrusion";const layerIndex={};const features3D=[];for(let l=this._order.length-1;l>=0;l--){const layerId=this._order[l];if(isLayer3D(layerId)){layerIndex[layerId]=l;for(const sourceResult of sourceResults){const layerFeatures=sourceResult[layerId];if(layerFeatures){for(const featureWrapper of layerFeatures){features3D.push(featureWrapper)}}}}}features3D.sort(((a,b)=>b.intersectionZ-a.intersectionZ));const features=[];for(let l=this._order.length-1;l>=0;l--){const layerId=this._order[l];if(isLayer3D(layerId)){for(let i=features3D.length-1;i>=0;i--){const topmost3D=features3D[i].feature;if(layerIndex[topmost3D.layer.id]sourceCache.getTileByID(id))).sort(((a,b)=>b.tileID.overscaledZ-a.tileID.overscaledZ||(a.tileID.isLessThan(b.tileID)?-1:1)))}const layerBucketsChanged=this.crossTileSymbolIndex.addLayer(styleLayer,layerTiles[styleLayer.source],transform.center.lng);symbolBucketsChanged=symbolBucketsChanged||layerBucketsChanged}this.crossTileSymbolIndex.pruneUnusedLayers(this._order);forceFullPlacement=forceFullPlacement||this._layerOrderChanged||fadeDuration===0;if(forceFullPlacement||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(browser.now(),transform.zoom)){this.pauseablePlacement=new PauseablePlacement(transform,this.map.terrain,this._order,forceFullPlacement,showCollisionBoxes,fadeDuration,crossSourceCollisions,this.placement);this._layerOrderChanged=false}if(this.pauseablePlacement.isDone()){this.placement.setStale()}else{this.pauseablePlacement.continuePlacement(this._order,this._layers,layerTiles);if(this.pauseablePlacement.isDone()){this.placement=this.pauseablePlacement.commit(browser.now());placementCommitted=true}if(symbolBucketsChanged){this.pauseablePlacement.placement.setStale()}}if(placementCommitted||symbolBucketsChanged){for(const layerID of this._order){const styleLayer=this._layers[layerID];if(styleLayer.type!=="symbol")continue;this.placement.updateLayerOpacities(styleLayer,layerTiles[styleLayer.source])}}const needsRerender=!this.pauseablePlacement.isDone()||this.placement.hasTransitions(browser.now());return needsRerender}_releaseSymbolFadeTiles(){for(const id in this.sourceCaches){this.sourceCaches[id].releaseSymbolFadeTiles()}}getImages(mapId,params){return performance$1.__awaiter(this,void 0,void 0,(function*(){const images=yield this.imageManager.getImages(params.icons);this._updateTilesForChangedImages();const sourceCache=this.sourceCaches[params.source];if(sourceCache){sourceCache.setDependencies(params.tileID.key,params.type,params.icons)}return images}))}getGlyphs(mapId,params){return performance$1.__awaiter(this,void 0,void 0,(function*(){const glypgs=yield this.glyphManager.getGlyphs(params.stacks);const sourceCache=this.sourceCaches[params.source];if(sourceCache){sourceCache.setDependencies(params.tileID.key,params.type,[""])}return glypgs}))}getGlyphsUrl(){return this.stylesheet.glyphs||null}setGlyphs(glyphsUrl,options={}){this._checkLoaded();if(glyphsUrl&&this._validate(performance$1.validateStyle.glyphs,"glyphs",glyphsUrl,null,options)){return}this._glyphsDidChange=true;this.stylesheet.glyphs=glyphsUrl;this.glyphManager.entries={};this.glyphManager.setURL(glyphsUrl)}addSprite(id,url,options={},completion){this._checkLoaded();const spriteToAdd=[{id:id,url:url}];const updatedSprite=[...coerceSpriteToArray(this.stylesheet.sprite),...spriteToAdd];if(this._validate(performance$1.validateStyle.sprite,"sprite",updatedSprite,null,options))return;this.stylesheet.sprite=updatedSprite;this._loadSprite(spriteToAdd,true,completion)}removeSprite(id){this._checkLoaded();const internalSpriteRepresentation=coerceSpriteToArray(this.stylesheet.sprite);if(!internalSpriteRepresentation.find((sprite=>sprite.id===id))){this.fire(new performance$1.ErrorEvent(new Error(`Sprite "${id}" doesn't exists on this map.`)));return}if(this._spritesImagesIds[id]){for(const imageId of this._spritesImagesIds[id]){this.imageManager.removeImage(imageId);this._changedImages[imageId]=true}}internalSpriteRepresentation.splice(internalSpriteRepresentation.findIndex((sprite=>sprite.id===id)),1);this.stylesheet.sprite=internalSpriteRepresentation.length>0?internalSpriteRepresentation:undefined;delete this._spritesImagesIds[id];this._availableImages=this.imageManager.listImages();this._changed=true;this.dispatcher.broadcast("setImages",this._availableImages);this.fire(new performance$1.Event("data",{dataType:"style"}))}getSprite(){return coerceSpriteToArray(this.stylesheet.sprite)}setSprite(sprite,options={},completion){this._checkLoaded();if(sprite&&this._validate(performance$1.validateStyle.sprite,"sprite",sprite,null,options)){return}this.stylesheet.sprite=sprite;if(sprite){this._loadSprite(sprite,true,completion)}else{this._unloadSprite();if(completion){completion(null)}}}}var posAttributes=performance$1.createLayout([{name:"a_pos",type:"Int16",components:2}]);var preludeFrag="#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\n";var preludeVert="#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}\n#ifdef TERRAIN3D\nuniform sampler2D u_terrain;uniform float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\n#endif\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\n#ifdef TERRAIN3D\nhighp float d=unpack(texture2D(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\n#else\nreturn 1.0;\n#endif\n}float calculate_visibility(vec4 pos) {\n#ifdef TERRAIN3D\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\n#else\nreturn 1.0;\n#endif\n}float ele(vec2 pos) {\n#ifdef TERRAIN3D\nvec4 rgb=(texture2D(u_terrain,pos)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\n#else\nreturn 0.0;\n#endif\n}float get_elevation(vec2 pos) {\n#ifdef TERRAIN3D\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.0;vec2 f=fract(coord);vec2 c=(floor(coord)+0.5)/(u_terrain_dim+2.0);float d=1.0/(u_terrain_dim+2.0);float tl=ele(c);float tr=ele(c+vec2(d,0.0));float bl=ele(c+vec2(0.0,d));float br=ele(c+vec2(d,d));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\n#else\nreturn 0.0;\n#endif\n}";var backgroundFrag="uniform vec4 u_color;uniform float u_opacity;void main() {gl_FragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var backgroundVert="attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}";var backgroundPatternFrag="uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var backgroundPatternVert="uniform mat4 u_matrix;uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}";var circleFrag="varying vec3 v_data;varying float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);lowp float antialiasblur=v_data.z;float antialiased_blur=-max(blur,antialiasblur);float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));gl_FragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var circleVert="uniform mat4 u_matrix;uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;attribute vec2 a_pos;varying vec3 v_data;varying float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=vec2(mod(a_pos,2.0)*2.0-1.0);vec2 circle_center=floor(a_pos*0.5);float ele=get_elevation(circle_center);v_visibility=calculate_visibility(u_matrix*vec4(circle_center,ele,1.0));if (u_pitch_with_map) {vec2 corner_position=circle_center;if (u_scale_with_map) {corner_position+=extrude*(radius+stroke_width)*u_extrude_scale;} else {vec4 projected_center=u_matrix*vec4(circle_center,0,1);corner_position+=extrude*(radius+stroke_width)*u_extrude_scale*(projected_center.w/u_camera_to_center_distance);}gl_Position=u_matrix*vec4(corner_position,ele,1);} else {gl_Position=u_matrix*vec4(circle_center,ele,1);if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}lowp float antialiasblur=1.0/u_device_pixel_ratio/(radius+stroke_width);v_data=vec3(extrude.x,extrude.y,antialiasblur);}";var clippingMaskFrag="void main() {gl_FragColor=vec4(1.0);}";var clippingMaskVert="attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}";var heatmapFrag="uniform highp float u_intensity;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);gl_FragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var heatmapVert="uniform mat4 u_matrix;uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;attribute vec2 a_pos;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 unscaled_extrude=vec2(mod(a_pos,2.0)*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec4 pos=vec4(floor(a_pos*0.5)+extrude,0,1);gl_Position=u_matrix*pos;}";var heatmapTextureFrag="uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;varying vec2 v_pos;void main() {float t=texture2D(u_image,v_pos).r;vec4 color=texture2D(u_color_ramp,vec2(t,0.5));gl_FragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(0.0);\n#endif\n}";var heatmapTextureVert="uniform mat4 u_matrix;uniform vec2 u_world;attribute vec2 a_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}";var collisionBoxFrag="varying float v_placed;varying float v_notUsed;void main() {float alpha=0.5;gl_FragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {gl_FragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {gl_FragColor*=.1;}}";var collisionBoxVert="attribute vec2 a_pos;attribute vec2 a_anchor_pos;attribute vec2 a_extrude;attribute vec2 a_placed;attribute vec2 a_shift;uniform mat4 u_matrix;uniform vec2 u_extrude_scale;uniform float u_camera_to_center_distance;varying float v_placed;varying float v_notUsed;void main() {vec4 projectedPoint=u_matrix*vec4(a_anchor_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float collision_perspective_ratio=clamp(0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);gl_Position=u_matrix*vec4(a_pos,get_elevation(a_pos),1.0);gl_Position.xy+=(a_extrude+a_shift)*u_extrude_scale*gl_Position.w*collision_perspective_ratio;v_placed=a_placed.x;v_notUsed=a_placed.y;}";var collisionCircleFrag="varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;void main() {float alpha=0.5*min(v_perspective_ratio,1.0);float stroke_radius=0.9*max(v_perspective_ratio,1.0);float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);gl_FragColor=color*alpha*opacity_t;}";var collisionCircleVert="attribute vec2 a_pos;attribute float a_radius;attribute vec2 a_flags;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform vec2 u_viewport_size;uniform float u_camera_to_center_distance;varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;vec3 toTilePosition(vec2 screenPos) {vec4 rayStart=u_inv_matrix*vec4(screenPos,-1.0,1.0);vec4 rayEnd =u_inv_matrix*vec4(screenPos, 1.0,1.0);rayStart.xyz/=rayStart.w;rayEnd.xyz /=rayEnd.w;highp float t=(0.0-rayStart.z)/(rayEnd.z-rayStart.z);return mix(rayStart.xyz,rayEnd.xyz,t);}void main() {vec2 quadCenterPos=a_pos;float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;vec3 tilePos=toTilePosition(quadCenterPos);vec4 clipPos=u_matrix*vec4(tilePos,1.0);highp float camera_to_anchor_distance=clipPos.w;highp float collision_perspective_ratio=clamp(0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_perspective_ratio=collision_perspective_ratio;v_collision=collision;gl_Position=vec4(clipPos.xyz/clipPos.w,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}";var debugFrag="uniform highp vec4 u_color;uniform sampler2D u_overlay;varying vec2 v_uv;void main() {vec4 overlay_color=texture2D(u_overlay,v_uv);gl_FragColor=mix(u_color,overlay_color,overlay_color.a);}";var debugVert="attribute vec2 a_pos;varying vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=u_matrix*vec4(a_pos*u_overlay_scale,get_elevation(a_pos),1);}";var fillFrag="#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_FragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var fillVert="attribute vec2 a_pos;uniform mat4 u_matrix;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);}";var fillOutlineFrag="varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=outline_color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var fillOutlineVert="attribute vec2 a_pos;uniform mat4 u_matrix;uniform vec2 u_world;varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}";var fillOutlinePatternFrag="uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var fillOutlinePatternVert="uniform mat4 u_matrix;uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=u_matrix*vec4(a_pos,0,1);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}";var fillPatternFrag="#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var fillPatternVert="uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}";var fillExtrusionFrag="varying vec4 v_color;void main() {gl_FragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var fillExtrusionVert="uniform mat4 u_matrix;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;attribute vec2 a_pos;attribute vec4 a_normal_ed;\n#ifdef TERRAIN3D\nattribute vec2 a_centroid;\n#endif\nvarying vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);gl_Position=u_matrix*vec4(a_pos,t > 0.0 ? height : base,1);float colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;float directional=clamp(dot(normal/16384.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}";var fillExtrusionPatternFrag="uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);gl_FragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var fillExtrusionPatternVert="uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;attribute vec2 a_pos;attribute vec4 a_normal_ed;\n#ifdef TERRAIN3D\nattribute vec2 a_centroid;\n#endif\nvarying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float z=t > 0.0 ? height : base;gl_Position=u_matrix*vec4(a_pos,z,1);vec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,z*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}";var hillshadePrepareFrag="#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture2D(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack)/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))/pow(2.0,exaggeration+(19.2562-u_zoom));gl_FragColor=clamp(vec4(deriv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var hillshadePrepareVert="uniform mat4 u_matrix;uniform vec2 u_dimension;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}";var hillshadeFrag="uniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;\n#define PI 3.141592653589793\nvoid main() {vec4 pixel=texture2D(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);gl_FragColor=accent_color*(1.0-shade_color.a)+shade_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var hillshadeVert="uniform mat4 u_matrix;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=a_texture_pos/8192.0;}";var lineFrag="uniform lowp float u_device_pixel_ratio;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var lineVert="\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp float v_linesofar;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}";var lineGradientFrag="uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;varying highp vec2 v_uv;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture2D(u_image,v_uv);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var lineGradientVert="\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;attribute float a_uv_x;attribute float a_split_index;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp vec2 v_uv;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}";var linePatternFrag="#ifdef GL_ES\nprecision highp float;\n#endif\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture2D(u_image,pos_a),texture2D(u_image,pos_b),u_fade);gl_FragColor=color*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var linePatternVert="\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}";var lineSDFFrag="uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture2D(u_image,v_tex_a).a;float sdfdist_b=texture2D(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var lineSDFVert="\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}";var rasterFrag="uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;varying vec2 v_pos0;varying vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture2D(u_image0,v_pos0);vec4 color1=texture2D(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);gl_FragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var rasterVert="uniform mat4 u_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos0;varying vec2 v_pos1;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos0=(((a_texture_pos/8192.0)-0.5)/u_buffer_scale )+0.5;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}";var symbolIconFrag="uniform sampler2D u_texture;varying vec2 v_tex;varying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;gl_FragColor=texture2D(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var symbolIconVert="const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;varying vec2 v_tex;varying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,ele,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),ele,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,ele,1.0);float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0),z,1.0);v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float visibility=calculate_visibility(projectedPoint);v_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));}";var symbolSDFFrag="#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;varying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);inner_edge=inner_edge+gamma*gamma_scale;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);if (u_is_halo) {lowp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha=min(smoothstep(halo_edge-gamma_scaled,halo_edge+gamma_scaled,dist),1.0-alpha);}gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var symbolSDFVert="const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;varying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,ele,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),ele,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,ele,1.0);float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset),z,1.0);float gamma_scale=gl_Position.w;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}";var symbolTextAndIconFrag="#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;varying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;gl_FragColor=texture2D(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";var symbolTextAndIconVert="const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;varying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,ele,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),ele,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,ele,1.0);float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale),z,1.0);float gamma_scale=gl_Position.w;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}";var terrainDepthFrag="varying float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {gl_FragColor=pack(v_depth);}";var terrainCoordsFrag="precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;varying vec2 v_texture_pos;void main() {vec4 rgba=texture2D(u_texture,v_texture_pos);gl_FragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}";var terrainFrag="uniform sampler2D u_texture;varying vec2 v_texture_pos;void main() {gl_FragColor=texture2D(u_texture,v_texture_pos);}";var terrainVert="attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform float u_ele_delta;varying vec2 v_texture_pos;varying float v_depth;void main() {float extent=8192.0;float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/extent;gl_Position=u_matrix*vec4(a_pos3d.xy,get_elevation(a_pos3d.xy)-ele_delta,1.0);v_depth=gl_Position.z/gl_Position.w;}";const shaders={prelude:compile(preludeFrag,preludeVert),background:compile(backgroundFrag,backgroundVert),backgroundPattern:compile(backgroundPatternFrag,backgroundPatternVert),circle:compile(circleFrag,circleVert),clippingMask:compile(clippingMaskFrag,clippingMaskVert),heatmap:compile(heatmapFrag,heatmapVert),heatmapTexture:compile(heatmapTextureFrag,heatmapTextureVert),collisionBox:compile(collisionBoxFrag,collisionBoxVert),collisionCircle:compile(collisionCircleFrag,collisionCircleVert),debug:compile(debugFrag,debugVert),fill:compile(fillFrag,fillVert),fillOutline:compile(fillOutlineFrag,fillOutlineVert),fillOutlinePattern:compile(fillOutlinePatternFrag,fillOutlinePatternVert),fillPattern:compile(fillPatternFrag,fillPatternVert),fillExtrusion:compile(fillExtrusionFrag,fillExtrusionVert),fillExtrusionPattern:compile(fillExtrusionPatternFrag,fillExtrusionPatternVert),hillshadePrepare:compile(hillshadePrepareFrag,hillshadePrepareVert),hillshade:compile(hillshadeFrag,hillshadeVert),line:compile(lineFrag,lineVert),lineGradient:compile(lineGradientFrag,lineGradientVert),linePattern:compile(linePatternFrag,linePatternVert),lineSDF:compile(lineSDFFrag,lineSDFVert),raster:compile(rasterFrag,rasterVert),symbolIcon:compile(symbolIconFrag,symbolIconVert),symbolSDF:compile(symbolSDFFrag,symbolSDFVert),symbolTextAndIcon:compile(symbolTextAndIconFrag,symbolTextAndIconVert),terrain:compile(terrainFrag,terrainVert),terrainDepth:compile(terrainDepthFrag,terrainVert),terrainCoords:compile(terrainCoordsFrag,terrainVert)};function compile(fragmentSource,vertexSource){const re=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g;const staticAttributes=vertexSource.match(/attribute ([\w]+) ([\w]+)/g);const fragmentUniforms=fragmentSource.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g);const vertexUniforms=vertexSource.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g);const staticUniforms=vertexUniforms?vertexUniforms.concat(fragmentUniforms):fragmentUniforms;const fragmentPragmas={};fragmentSource=fragmentSource.replace(re,((match,operation,precision,type,name)=>{fragmentPragmas[name]=true;if(operation==="define"){return`\n#ifndef HAS_UNIFORM_u_${name}\nvarying ${precision} ${type} ${name};\n#else\nuniform ${precision} ${type} u_${name};\n#endif\n`}else{return`\n#ifdef HAS_UNIFORM_u_${name}\n ${precision} ${type} ${name} = u_${name};\n#endif\n`}}));vertexSource=vertexSource.replace(re,((match,operation,precision,type,name)=>{const attrType=type==="float"?"vec2":"vec4";const unpackType=name.match(/color/)?"color":attrType;if(fragmentPragmas[name]){if(operation==="define"){return`\n#ifndef HAS_UNIFORM_u_${name}\nuniform lowp float u_${name}_t;\nattribute ${precision} ${attrType} a_${name};\nvarying ${precision} ${type} ${name};\n#else\nuniform ${precision} ${type} u_${name};\n#endif\n`}else{if(unpackType==="vec4"){return`\n#ifndef HAS_UNIFORM_u_${name}\n ${name} = a_${name};\n#else\n ${precision} ${type} ${name} = u_${name};\n#endif\n`}else{return`\n#ifndef HAS_UNIFORM_u_${name}\n ${name} = unpack_mix_${unpackType}(a_${name}, u_${name}_t);\n#else\n ${precision} ${type} ${name} = u_${name};\n#endif\n`}}}else{if(operation==="define"){return`\n#ifndef HAS_UNIFORM_u_${name}\nuniform lowp float u_${name}_t;\nattribute ${precision} ${attrType} a_${name};\n#else\nuniform ${precision} ${type} u_${name};\n#endif\n`}else{if(unpackType==="vec4"){return`\n#ifndef HAS_UNIFORM_u_${name}\n ${precision} ${type} ${name} = a_${name};\n#else\n ${precision} ${type} ${name} = u_${name};\n#endif\n`}else{return`\n#ifndef HAS_UNIFORM_u_${name}\n ${precision} ${type} ${name} = unpack_mix_${unpackType}(a_${name}, u_${name}_t);\n#else\n ${precision} ${type} ${name} = u_${name};\n#endif\n`}}}}));return{fragmentSource:fragmentSource,vertexSource:vertexSource,staticAttributes:staticAttributes,staticUniforms:staticUniforms}}class VertexArrayObject{constructor(){this.boundProgram=null;this.boundLayoutVertexBuffer=null;this.boundPaintVertexBuffers=[];this.boundIndexBuffer=null;this.boundVertexOffset=null;this.boundDynamicVertexBuffer=null;this.vao=null}bind(context,program,layoutVertexBuffer,paintVertexBuffers,indexBuffer,vertexOffset,dynamicVertexBuffer,dynamicVertexBuffer2,dynamicVertexBuffer3){this.context=context;let paintBuffersDiffer=this.boundPaintVertexBuffers.length!==paintVertexBuffers.length;for(let i=0;!paintBuffersDiffer&&i({u_depth:new performance$1.Uniform1i(context,locations.u_depth),u_terrain:new performance$1.Uniform1i(context,locations.u_terrain),u_terrain_dim:new performance$1.Uniform1f(context,locations.u_terrain_dim),u_terrain_matrix:new performance$1.UniformMatrix4f(context,locations.u_terrain_matrix),u_terrain_unpack:new performance$1.Uniform4f(context,locations.u_terrain_unpack),u_terrain_exaggeration:new performance$1.Uniform1f(context,locations.u_terrain_exaggeration)});const terrainUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_texture:new performance$1.Uniform1i(context,locations.u_texture),u_ele_delta:new performance$1.Uniform1f(context,locations.u_ele_delta)});const terrainDepthUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_ele_delta:new performance$1.Uniform1f(context,locations.u_ele_delta)});const terrainCoordsUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_texture:new performance$1.Uniform1i(context,locations.u_texture),u_terrain_coords_id:new performance$1.Uniform1f(context,locations.u_terrain_coords_id),u_ele_delta:new performance$1.Uniform1f(context,locations.u_ele_delta)});const terrainUniformValues=(matrix,eleDelta)=>({u_matrix:matrix,u_texture:0,u_ele_delta:eleDelta});const terrainDepthUniformValues=(matrix,eleDelta)=>({u_matrix:matrix,u_ele_delta:eleDelta});const terrainCoordsUniformValues=(matrix,coordsId,eleDelta)=>({u_matrix:matrix,u_terrain_coords_id:coordsId/255,u_texture:0,u_ele_delta:eleDelta});function getTokenizedAttributesAndUniforms(array){const result=[];for(let i=0;i>16,pixelY>>16],u_pixel_coord_lower:[pixelX&65535,pixelY&65535]}}function bgPatternUniformValues(image,crossfade,painter,tile){const imagePosA=painter.imageManager.getPattern(image.from.toString());const imagePosB=painter.imageManager.getPattern(image.to.toString());const{width:width,height:height}=painter.imageManager.getPixelSize();const numTiles=Math.pow(2,tile.tileID.overscaledZ);const tileSizeAtNearestZoom=tile.tileSize*Math.pow(2,painter.transform.tileZoom)/numTiles;const pixelX=tileSizeAtNearestZoom*(tile.tileID.canonical.x+tile.tileID.wrap*numTiles);const pixelY=tileSizeAtNearestZoom*tile.tileID.canonical.y;return{u_image:0,u_pattern_tl_a:imagePosA.tl,u_pattern_br_a:imagePosA.br,u_pattern_tl_b:imagePosB.tl,u_pattern_br_b:imagePosB.br,u_texsize:[width,height],u_mix:crossfade.t,u_pattern_size_a:imagePosA.displaySize,u_pattern_size_b:imagePosB.displaySize,u_scale_a:crossfade.fromScale,u_scale_b:crossfade.toScale,u_tile_units_to_pixels:1/pixelsToTileUnits(tile,1,painter.transform.tileZoom),u_pixel_coord_upper:[pixelX>>16,pixelY>>16],u_pixel_coord_lower:[pixelX&65535,pixelY&65535]}}const fillExtrusionUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_lightpos:new performance$1.Uniform3f(context,locations.u_lightpos),u_lightintensity:new performance$1.Uniform1f(context,locations.u_lightintensity),u_lightcolor:new performance$1.Uniform3f(context,locations.u_lightcolor),u_vertical_gradient:new performance$1.Uniform1f(context,locations.u_vertical_gradient),u_opacity:new performance$1.Uniform1f(context,locations.u_opacity)});const fillExtrusionPatternUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_lightpos:new performance$1.Uniform3f(context,locations.u_lightpos),u_lightintensity:new performance$1.Uniform1f(context,locations.u_lightintensity),u_lightcolor:new performance$1.Uniform3f(context,locations.u_lightcolor),u_vertical_gradient:new performance$1.Uniform1f(context,locations.u_vertical_gradient),u_height_factor:new performance$1.Uniform1f(context,locations.u_height_factor),u_image:new performance$1.Uniform1i(context,locations.u_image),u_texsize:new performance$1.Uniform2f(context,locations.u_texsize),u_pixel_coord_upper:new performance$1.Uniform2f(context,locations.u_pixel_coord_upper),u_pixel_coord_lower:new performance$1.Uniform2f(context,locations.u_pixel_coord_lower),u_scale:new performance$1.Uniform3f(context,locations.u_scale),u_fade:new performance$1.Uniform1f(context,locations.u_fade),u_opacity:new performance$1.Uniform1f(context,locations.u_opacity)});const fillExtrusionUniformValues=(matrix,painter,shouldUseVerticalGradient,opacity)=>{const light=painter.style.light;const _lp=light.properties.get("position");const lightPos=[_lp.x,_lp.y,_lp.z];const lightMat=performance$1.create$1();if(light.properties.get("anchor")==="viewport"){performance$1.fromRotation(lightMat,-painter.transform.angle)}performance$1.transformMat3(lightPos,lightPos,lightMat);const lightColor=light.properties.get("color");return{u_matrix:matrix,u_lightpos:lightPos,u_lightintensity:light.properties.get("intensity"),u_lightcolor:[lightColor.r,lightColor.g,lightColor.b],u_vertical_gradient:+shouldUseVerticalGradient,u_opacity:opacity}};const fillExtrusionPatternUniformValues=(matrix,painter,shouldUseVerticalGradient,opacity,coord,crossfade,tile)=>performance$1.extend(fillExtrusionUniformValues(matrix,painter,shouldUseVerticalGradient,opacity),patternUniformValues(crossfade,painter,tile),{u_height_factor:-Math.pow(2,coord.overscaledZ)/tile.tileSize/8});const fillUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix)});const fillPatternUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_image:new performance$1.Uniform1i(context,locations.u_image),u_texsize:new performance$1.Uniform2f(context,locations.u_texsize),u_pixel_coord_upper:new performance$1.Uniform2f(context,locations.u_pixel_coord_upper),u_pixel_coord_lower:new performance$1.Uniform2f(context,locations.u_pixel_coord_lower),u_scale:new performance$1.Uniform3f(context,locations.u_scale),u_fade:new performance$1.Uniform1f(context,locations.u_fade)});const fillOutlineUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_world:new performance$1.Uniform2f(context,locations.u_world)});const fillOutlinePatternUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_world:new performance$1.Uniform2f(context,locations.u_world),u_image:new performance$1.Uniform1i(context,locations.u_image),u_texsize:new performance$1.Uniform2f(context,locations.u_texsize),u_pixel_coord_upper:new performance$1.Uniform2f(context,locations.u_pixel_coord_upper),u_pixel_coord_lower:new performance$1.Uniform2f(context,locations.u_pixel_coord_lower),u_scale:new performance$1.Uniform3f(context,locations.u_scale),u_fade:new performance$1.Uniform1f(context,locations.u_fade)});const fillUniformValues=matrix=>({u_matrix:matrix});const fillPatternUniformValues=(matrix,painter,crossfade,tile)=>performance$1.extend(fillUniformValues(matrix),patternUniformValues(crossfade,painter,tile));const fillOutlineUniformValues=(matrix,drawingBufferSize)=>({u_matrix:matrix,u_world:drawingBufferSize});const fillOutlinePatternUniformValues=(matrix,painter,crossfade,tile,drawingBufferSize)=>performance$1.extend(fillPatternUniformValues(matrix,painter,crossfade,tile),{u_world:drawingBufferSize});const circleUniforms=(context,locations)=>({u_camera_to_center_distance:new performance$1.Uniform1f(context,locations.u_camera_to_center_distance),u_scale_with_map:new performance$1.Uniform1i(context,locations.u_scale_with_map),u_pitch_with_map:new performance$1.Uniform1i(context,locations.u_pitch_with_map),u_extrude_scale:new performance$1.Uniform2f(context,locations.u_extrude_scale),u_device_pixel_ratio:new performance$1.Uniform1f(context,locations.u_device_pixel_ratio),u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix)});const circleUniformValues=(painter,coord,tile,layer)=>{const transform=painter.transform;let pitchWithMap,extrudeScale;if(layer.paint.get("circle-pitch-alignment")==="map"){const pixelRatio=pixelsToTileUnits(tile,1,transform.zoom);pitchWithMap=true;extrudeScale=[pixelRatio,pixelRatio]}else{pitchWithMap=false;extrudeScale=transform.pixelsToGLUnits}return{u_camera_to_center_distance:transform.cameraToCenterDistance,u_scale_with_map:+(layer.paint.get("circle-pitch-scale")==="map"),u_matrix:painter.translatePosMatrix(coord.posMatrix,tile,layer.paint.get("circle-translate"),layer.paint.get("circle-translate-anchor")),u_pitch_with_map:+pitchWithMap,u_device_pixel_ratio:painter.pixelRatio,u_extrude_scale:extrudeScale}};const collisionUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_camera_to_center_distance:new performance$1.Uniform1f(context,locations.u_camera_to_center_distance),u_pixels_to_tile_units:new performance$1.Uniform1f(context,locations.u_pixels_to_tile_units),u_extrude_scale:new performance$1.Uniform2f(context,locations.u_extrude_scale),u_overscale_factor:new performance$1.Uniform1f(context,locations.u_overscale_factor)});const collisionCircleUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_inv_matrix:new performance$1.UniformMatrix4f(context,locations.u_inv_matrix),u_camera_to_center_distance:new performance$1.Uniform1f(context,locations.u_camera_to_center_distance),u_viewport_size:new performance$1.Uniform2f(context,locations.u_viewport_size)});const collisionUniformValues=(matrix,transform,tile)=>{const pixelRatio=pixelsToTileUnits(tile,1,transform.zoom);const scale=Math.pow(2,transform.zoom-tile.tileID.overscaledZ);const overscaleFactor=tile.tileID.overscaleFactor();return{u_matrix:matrix,u_camera_to_center_distance:transform.cameraToCenterDistance,u_pixels_to_tile_units:pixelRatio,u_extrude_scale:[transform.pixelsToGLUnits[0]/(pixelRatio*scale),transform.pixelsToGLUnits[1]/(pixelRatio*scale)],u_overscale_factor:overscaleFactor}};const collisionCircleUniformValues=(matrix,invMatrix,transform)=>({u_matrix:matrix,u_inv_matrix:invMatrix,u_camera_to_center_distance:transform.cameraToCenterDistance,u_viewport_size:[transform.width,transform.height]});const debugUniforms=(context,locations)=>({u_color:new performance$1.UniformColor(context,locations.u_color),u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_overlay:new performance$1.Uniform1i(context,locations.u_overlay),u_overlay_scale:new performance$1.Uniform1f(context,locations.u_overlay_scale)});const debugUniformValues=(matrix,color,scaleRatio=1)=>({u_matrix:matrix,u_color:color,u_overlay:0,u_overlay_scale:scaleRatio});const clippingMaskUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix)});const clippingMaskUniformValues=matrix=>({u_matrix:matrix});const heatmapUniforms=(context,locations)=>({u_extrude_scale:new performance$1.Uniform1f(context,locations.u_extrude_scale),u_intensity:new performance$1.Uniform1f(context,locations.u_intensity),u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix)});const heatmapTextureUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_world:new performance$1.Uniform2f(context,locations.u_world),u_image:new performance$1.Uniform1i(context,locations.u_image),u_color_ramp:new performance$1.Uniform1i(context,locations.u_color_ramp),u_opacity:new performance$1.Uniform1f(context,locations.u_opacity)});const heatmapUniformValues=(matrix,tile,zoom,intensity)=>({u_matrix:matrix,u_extrude_scale:pixelsToTileUnits(tile,1,zoom),u_intensity:intensity});const heatmapTextureUniformValues=(painter,layer,textureUnit,colorRampUnit)=>{const matrix=performance$1.create();performance$1.ortho(matrix,0,painter.width,painter.height,0,0,1);const gl=painter.context.gl;return{u_matrix:matrix,u_world:[gl.drawingBufferWidth,gl.drawingBufferHeight],u_image:textureUnit,u_color_ramp:colorRampUnit,u_opacity:layer.paint.get("heatmap-opacity")}};const hillshadeUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_image:new performance$1.Uniform1i(context,locations.u_image),u_latrange:new performance$1.Uniform2f(context,locations.u_latrange),u_light:new performance$1.Uniform2f(context,locations.u_light),u_shadow:new performance$1.UniformColor(context,locations.u_shadow),u_highlight:new performance$1.UniformColor(context,locations.u_highlight),u_accent:new performance$1.UniformColor(context,locations.u_accent)});const hillshadePrepareUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_image:new performance$1.Uniform1i(context,locations.u_image),u_dimension:new performance$1.Uniform2f(context,locations.u_dimension),u_zoom:new performance$1.Uniform1f(context,locations.u_zoom),u_unpack:new performance$1.Uniform4f(context,locations.u_unpack)});const hillshadeUniformValues=(painter,tile,layer,coord)=>{const shadow=layer.paint.get("hillshade-shadow-color");const highlight=layer.paint.get("hillshade-highlight-color");const accent=layer.paint.get("hillshade-accent-color");let azimuthal=layer.paint.get("hillshade-illumination-direction")*(Math.PI/180);if(layer.paint.get("hillshade-illumination-anchor")==="viewport"){azimuthal-=painter.transform.angle}const align=!painter.options.moving;return{u_matrix:coord?coord.posMatrix:painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped(),align),u_image:0,u_latrange:getTileLatRange(painter,tile.tileID),u_light:[layer.paint.get("hillshade-exaggeration"),azimuthal],u_shadow:shadow,u_highlight:highlight,u_accent:accent}};const hillshadeUniformPrepareValues=(tileID,dem)=>{const stride=dem.stride;const matrix=performance$1.create();performance$1.ortho(matrix,0,performance$1.EXTENT,-performance$1.EXTENT,0,0,1);performance$1.translate(matrix,matrix,[0,-performance$1.EXTENT,0]);return{u_matrix:matrix,u_image:1,u_dimension:[stride,stride],u_zoom:tileID.overscaledZ,u_unpack:dem.getUnpackVector()}};function getTileLatRange(painter,tileID){const tilesAtZoom=Math.pow(2,tileID.canonical.z);const y=tileID.canonical.y;return[new performance$1.MercatorCoordinate(0,y/tilesAtZoom).toLngLat().lat,new performance$1.MercatorCoordinate(0,(y+1)/tilesAtZoom).toLngLat().lat]}const lineUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_ratio:new performance$1.Uniform1f(context,locations.u_ratio),u_device_pixel_ratio:new performance$1.Uniform1f(context,locations.u_device_pixel_ratio),u_units_to_pixels:new performance$1.Uniform2f(context,locations.u_units_to_pixels)});const lineGradientUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_ratio:new performance$1.Uniform1f(context,locations.u_ratio),u_device_pixel_ratio:new performance$1.Uniform1f(context,locations.u_device_pixel_ratio),u_units_to_pixels:new performance$1.Uniform2f(context,locations.u_units_to_pixels),u_image:new performance$1.Uniform1i(context,locations.u_image),u_image_height:new performance$1.Uniform1f(context,locations.u_image_height)});const linePatternUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_texsize:new performance$1.Uniform2f(context,locations.u_texsize),u_ratio:new performance$1.Uniform1f(context,locations.u_ratio),u_device_pixel_ratio:new performance$1.Uniform1f(context,locations.u_device_pixel_ratio),u_image:new performance$1.Uniform1i(context,locations.u_image),u_units_to_pixels:new performance$1.Uniform2f(context,locations.u_units_to_pixels),u_scale:new performance$1.Uniform3f(context,locations.u_scale),u_fade:new performance$1.Uniform1f(context,locations.u_fade)});const lineSDFUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_ratio:new performance$1.Uniform1f(context,locations.u_ratio),u_device_pixel_ratio:new performance$1.Uniform1f(context,locations.u_device_pixel_ratio),u_units_to_pixels:new performance$1.Uniform2f(context,locations.u_units_to_pixels),u_patternscale_a:new performance$1.Uniform2f(context,locations.u_patternscale_a),u_patternscale_b:new performance$1.Uniform2f(context,locations.u_patternscale_b),u_sdfgamma:new performance$1.Uniform1f(context,locations.u_sdfgamma),u_image:new performance$1.Uniform1i(context,locations.u_image),u_tex_y_a:new performance$1.Uniform1f(context,locations.u_tex_y_a),u_tex_y_b:new performance$1.Uniform1f(context,locations.u_tex_y_b),u_mix:new performance$1.Uniform1f(context,locations.u_mix)});const lineUniformValues=(painter,tile,layer,coord)=>{const transform=painter.transform;return{u_matrix:calculateMatrix(painter,tile,layer,coord),u_ratio:1/pixelsToTileUnits(tile,1,transform.zoom),u_device_pixel_ratio:painter.pixelRatio,u_units_to_pixels:[1/transform.pixelsToGLUnits[0],1/transform.pixelsToGLUnits[1]]}};const lineGradientUniformValues=(painter,tile,layer,imageHeight,coord)=>performance$1.extend(lineUniformValues(painter,tile,layer,coord),{u_image:0,u_image_height:imageHeight});const linePatternUniformValues=(painter,tile,layer,crossfade,coord)=>{const transform=painter.transform;const tileZoomRatio=calculateTileRatio(tile,transform);return{u_matrix:calculateMatrix(painter,tile,layer,coord),u_texsize:tile.imageAtlasTexture.size,u_ratio:1/pixelsToTileUnits(tile,1,transform.zoom),u_device_pixel_ratio:painter.pixelRatio,u_image:0,u_scale:[tileZoomRatio,crossfade.fromScale,crossfade.toScale],u_fade:crossfade.t,u_units_to_pixels:[1/transform.pixelsToGLUnits[0],1/transform.pixelsToGLUnits[1]]}};const lineSDFUniformValues=(painter,tile,layer,dasharray,crossfade,coord)=>{const transform=painter.transform;const lineAtlas=painter.lineAtlas;const tileRatio=calculateTileRatio(tile,transform);const round=layer.layout.get("line-cap")==="round";const posA=lineAtlas.getDash(dasharray.from,round);const posB=lineAtlas.getDash(dasharray.to,round);const widthA=posA.width*crossfade.fromScale;const widthB=posB.width*crossfade.toScale;return performance$1.extend(lineUniformValues(painter,tile,layer,coord),{u_patternscale_a:[tileRatio/widthA,-posA.height/2],u_patternscale_b:[tileRatio/widthB,-posB.height/2],u_sdfgamma:lineAtlas.width/(Math.min(widthA,widthB)*256*painter.pixelRatio)/2,u_image:0,u_tex_y_a:posA.y,u_tex_y_b:posB.y,u_mix:crossfade.t})};function calculateTileRatio(tile,transform){return 1/pixelsToTileUnits(tile,1,transform.tileZoom)}function calculateMatrix(painter,tile,layer,coord){return painter.translatePosMatrix(coord?coord.posMatrix:tile.tileID.posMatrix,tile,layer.paint.get("line-translate"),layer.paint.get("line-translate-anchor"))}const rasterUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_tl_parent:new performance$1.Uniform2f(context,locations.u_tl_parent),u_scale_parent:new performance$1.Uniform1f(context,locations.u_scale_parent),u_buffer_scale:new performance$1.Uniform1f(context,locations.u_buffer_scale),u_fade_t:new performance$1.Uniform1f(context,locations.u_fade_t),u_opacity:new performance$1.Uniform1f(context,locations.u_opacity),u_image0:new performance$1.Uniform1i(context,locations.u_image0),u_image1:new performance$1.Uniform1i(context,locations.u_image1),u_brightness_low:new performance$1.Uniform1f(context,locations.u_brightness_low),u_brightness_high:new performance$1.Uniform1f(context,locations.u_brightness_high),u_saturation_factor:new performance$1.Uniform1f(context,locations.u_saturation_factor),u_contrast_factor:new performance$1.Uniform1f(context,locations.u_contrast_factor),u_spin_weights:new performance$1.Uniform3f(context,locations.u_spin_weights)});const rasterUniformValues=(matrix,parentTL,parentScaleBy,fade,layer)=>({u_matrix:matrix,u_tl_parent:parentTL,u_scale_parent:parentScaleBy,u_buffer_scale:1,u_fade_t:fade.mix,u_opacity:fade.opacity*layer.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:layer.paint.get("raster-brightness-min"),u_brightness_high:layer.paint.get("raster-brightness-max"),u_saturation_factor:saturationFactor(layer.paint.get("raster-saturation")),u_contrast_factor:contrastFactor(layer.paint.get("raster-contrast")),u_spin_weights:spinWeights(layer.paint.get("raster-hue-rotate"))});function spinWeights(angle){angle*=Math.PI/180;const s=Math.sin(angle);const c=Math.cos(angle);return[(2*c+1)/3,(-Math.sqrt(3)*s-c+1)/3,(Math.sqrt(3)*s-c+1)/3]}function contrastFactor(contrast){return contrast>0?1/(1-contrast):1+contrast}function saturationFactor(saturation){return saturation>0?1-1/(1.001-saturation):-saturation}const symbolIconUniforms=(context,locations)=>({u_is_size_zoom_constant:new performance$1.Uniform1i(context,locations.u_is_size_zoom_constant),u_is_size_feature_constant:new performance$1.Uniform1i(context,locations.u_is_size_feature_constant),u_size_t:new performance$1.Uniform1f(context,locations.u_size_t),u_size:new performance$1.Uniform1f(context,locations.u_size),u_camera_to_center_distance:new performance$1.Uniform1f(context,locations.u_camera_to_center_distance),u_pitch:new performance$1.Uniform1f(context,locations.u_pitch),u_rotate_symbol:new performance$1.Uniform1i(context,locations.u_rotate_symbol),u_aspect_ratio:new performance$1.Uniform1f(context,locations.u_aspect_ratio),u_fade_change:new performance$1.Uniform1f(context,locations.u_fade_change),u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_label_plane_matrix:new performance$1.UniformMatrix4f(context,locations.u_label_plane_matrix),u_coord_matrix:new performance$1.UniformMatrix4f(context,locations.u_coord_matrix),u_is_text:new performance$1.Uniform1i(context,locations.u_is_text),u_pitch_with_map:new performance$1.Uniform1i(context,locations.u_pitch_with_map),u_texsize:new performance$1.Uniform2f(context,locations.u_texsize),u_texture:new performance$1.Uniform1i(context,locations.u_texture)});const symbolSDFUniforms=(context,locations)=>({u_is_size_zoom_constant:new performance$1.Uniform1i(context,locations.u_is_size_zoom_constant),u_is_size_feature_constant:new performance$1.Uniform1i(context,locations.u_is_size_feature_constant),u_size_t:new performance$1.Uniform1f(context,locations.u_size_t),u_size:new performance$1.Uniform1f(context,locations.u_size),u_camera_to_center_distance:new performance$1.Uniform1f(context,locations.u_camera_to_center_distance),u_pitch:new performance$1.Uniform1f(context,locations.u_pitch),u_rotate_symbol:new performance$1.Uniform1i(context,locations.u_rotate_symbol),u_aspect_ratio:new performance$1.Uniform1f(context,locations.u_aspect_ratio),u_fade_change:new performance$1.Uniform1f(context,locations.u_fade_change),u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_label_plane_matrix:new performance$1.UniformMatrix4f(context,locations.u_label_plane_matrix),u_coord_matrix:new performance$1.UniformMatrix4f(context,locations.u_coord_matrix),u_is_text:new performance$1.Uniform1i(context,locations.u_is_text),u_pitch_with_map:new performance$1.Uniform1i(context,locations.u_pitch_with_map),u_texsize:new performance$1.Uniform2f(context,locations.u_texsize),u_texture:new performance$1.Uniform1i(context,locations.u_texture),u_gamma_scale:new performance$1.Uniform1f(context,locations.u_gamma_scale),u_device_pixel_ratio:new performance$1.Uniform1f(context,locations.u_device_pixel_ratio),u_is_halo:new performance$1.Uniform1i(context,locations.u_is_halo)});const symbolTextAndIconUniforms=(context,locations)=>({u_is_size_zoom_constant:new performance$1.Uniform1i(context,locations.u_is_size_zoom_constant),u_is_size_feature_constant:new performance$1.Uniform1i(context,locations.u_is_size_feature_constant),u_size_t:new performance$1.Uniform1f(context,locations.u_size_t),u_size:new performance$1.Uniform1f(context,locations.u_size),u_camera_to_center_distance:new performance$1.Uniform1f(context,locations.u_camera_to_center_distance),u_pitch:new performance$1.Uniform1f(context,locations.u_pitch),u_rotate_symbol:new performance$1.Uniform1i(context,locations.u_rotate_symbol),u_aspect_ratio:new performance$1.Uniform1f(context,locations.u_aspect_ratio),u_fade_change:new performance$1.Uniform1f(context,locations.u_fade_change),u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_label_plane_matrix:new performance$1.UniformMatrix4f(context,locations.u_label_plane_matrix),u_coord_matrix:new performance$1.UniformMatrix4f(context,locations.u_coord_matrix),u_is_text:new performance$1.Uniform1i(context,locations.u_is_text),u_pitch_with_map:new performance$1.Uniform1i(context,locations.u_pitch_with_map),u_texsize:new performance$1.Uniform2f(context,locations.u_texsize),u_texsize_icon:new performance$1.Uniform2f(context,locations.u_texsize_icon),u_texture:new performance$1.Uniform1i(context,locations.u_texture),u_texture_icon:new performance$1.Uniform1i(context,locations.u_texture_icon),u_gamma_scale:new performance$1.Uniform1f(context,locations.u_gamma_scale),u_device_pixel_ratio:new performance$1.Uniform1f(context,locations.u_device_pixel_ratio),u_is_halo:new performance$1.Uniform1i(context,locations.u_is_halo)});const symbolIconUniformValues=(functionType,size,rotateInShader,pitchWithMap,painter,matrix,labelPlaneMatrix,glCoordMatrix,isText,texSize)=>{const transform=painter.transform;return{u_is_size_zoom_constant:+(functionType==="constant"||functionType==="source"),u_is_size_feature_constant:+(functionType==="constant"||functionType==="camera"),u_size_t:size?size.uSizeT:0,u_size:size?size.uSize:0,u_camera_to_center_distance:transform.cameraToCenterDistance,u_pitch:transform.pitch/360*2*Math.PI,u_rotate_symbol:+rotateInShader,u_aspect_ratio:transform.width/transform.height,u_fade_change:painter.options.fadeDuration?painter.symbolFadeChange:1,u_matrix:matrix,u_label_plane_matrix:labelPlaneMatrix,u_coord_matrix:glCoordMatrix,u_is_text:+isText,u_pitch_with_map:+pitchWithMap,u_texsize:texSize,u_texture:0}};const symbolSDFUniformValues=(functionType,size,rotateInShader,pitchWithMap,painter,matrix,labelPlaneMatrix,glCoordMatrix,isText,texSize,isHalo)=>{const transform=painter.transform;return performance$1.extend(symbolIconUniformValues(functionType,size,rotateInShader,pitchWithMap,painter,matrix,labelPlaneMatrix,glCoordMatrix,isText,texSize),{u_gamma_scale:pitchWithMap?Math.cos(transform._pitch)*transform.cameraToCenterDistance:1,u_device_pixel_ratio:painter.pixelRatio,u_is_halo:+isHalo})};const symbolTextAndIconUniformValues=(functionType,size,rotateInShader,pitchWithMap,painter,matrix,labelPlaneMatrix,glCoordMatrix,texSizeSDF,texSizeIcon)=>performance$1.extend(symbolSDFUniformValues(functionType,size,rotateInShader,pitchWithMap,painter,matrix,labelPlaneMatrix,glCoordMatrix,true,texSizeSDF,true),{u_texsize_icon:texSizeIcon,u_texture_icon:1});const backgroundUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_opacity:new performance$1.Uniform1f(context,locations.u_opacity),u_color:new performance$1.UniformColor(context,locations.u_color)});const backgroundPatternUniforms=(context,locations)=>({u_matrix:new performance$1.UniformMatrix4f(context,locations.u_matrix),u_opacity:new performance$1.Uniform1f(context,locations.u_opacity),u_image:new performance$1.Uniform1i(context,locations.u_image),u_pattern_tl_a:new performance$1.Uniform2f(context,locations.u_pattern_tl_a),u_pattern_br_a:new performance$1.Uniform2f(context,locations.u_pattern_br_a),u_pattern_tl_b:new performance$1.Uniform2f(context,locations.u_pattern_tl_b),u_pattern_br_b:new performance$1.Uniform2f(context,locations.u_pattern_br_b),u_texsize:new performance$1.Uniform2f(context,locations.u_texsize),u_mix:new performance$1.Uniform1f(context,locations.u_mix),u_pattern_size_a:new performance$1.Uniform2f(context,locations.u_pattern_size_a),u_pattern_size_b:new performance$1.Uniform2f(context,locations.u_pattern_size_b),u_scale_a:new performance$1.Uniform1f(context,locations.u_scale_a),u_scale_b:new performance$1.Uniform1f(context,locations.u_scale_b),u_pixel_coord_upper:new performance$1.Uniform2f(context,locations.u_pixel_coord_upper),u_pixel_coord_lower:new performance$1.Uniform2f(context,locations.u_pixel_coord_lower),u_tile_units_to_pixels:new performance$1.Uniform1f(context,locations.u_tile_units_to_pixels)});const backgroundUniformValues=(matrix,opacity,color)=>({u_matrix:matrix,u_opacity:opacity,u_color:color});const backgroundPatternUniformValues=(matrix,opacity,painter,image,tile,crossfade)=>performance$1.extend(bgPatternUniformValues(image,crossfade,painter,tile),{u_matrix:matrix,u_opacity:opacity});const programUniforms={fillExtrusion:fillExtrusionUniforms,fillExtrusionPattern:fillExtrusionPatternUniforms,fill:fillUniforms,fillPattern:fillPatternUniforms,fillOutline:fillOutlineUniforms,fillOutlinePattern:fillOutlinePatternUniforms,circle:circleUniforms,collisionBox:collisionUniforms,collisionCircle:collisionCircleUniforms,debug:debugUniforms,clippingMask:clippingMaskUniforms,heatmap:heatmapUniforms,heatmapTexture:heatmapTextureUniforms,hillshade:hillshadeUniforms,hillshadePrepare:hillshadePrepareUniforms,line:lineUniforms,lineGradient:lineGradientUniforms,linePattern:linePatternUniforms,lineSDF:lineSDFUniforms,raster:rasterUniforms,symbolIcon:symbolIconUniforms,symbolSDF:symbolSDFUniforms,symbolTextAndIcon:symbolTextAndIconUniforms,background:backgroundUniforms,backgroundPattern:backgroundPatternUniforms,terrain:terrainUniforms,terrainDepth:terrainDepthUniforms,terrainCoords:terrainCoordsUniforms};class IndexBuffer{constructor(context,array,dynamicDraw){this.context=context;const gl=context.gl;this.buffer=gl.createBuffer();this.dynamicDraw=Boolean(dynamicDraw);this.context.unbindVAO();context.bindElementBuffer.set(this.buffer);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,array.arrayBuffer,this.dynamicDraw?gl.DYNAMIC_DRAW:gl.STATIC_DRAW);if(!this.dynamicDraw){delete array.arrayBuffer}}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(array){const gl=this.context.gl;if(!this.dynamicDraw)throw new Error("Attempted to update data while not in dynamic mode.");this.context.unbindVAO();this.bind();gl.bufferSubData(gl.ELEMENT_ARRAY_BUFFER,0,array.arrayBuffer)}destroy(){const gl=this.context.gl;if(this.buffer){gl.deleteBuffer(this.buffer);delete this.buffer}}}const AttributeType={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class VertexBuffer{constructor(context,array,attributes,dynamicDraw){this.length=array.length;this.attributes=attributes;this.itemSize=array.bytesPerElement;this.dynamicDraw=dynamicDraw;this.context=context;const gl=context.gl;this.buffer=gl.createBuffer();context.bindVertexBuffer.set(this.buffer);gl.bufferData(gl.ARRAY_BUFFER,array.arrayBuffer,this.dynamicDraw?gl.DYNAMIC_DRAW:gl.STATIC_DRAW);if(!this.dynamicDraw){delete array.arrayBuffer}}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(array){if(array.length!==this.length)throw new Error(`Length of new data is ${array.length}, which doesn't match current length of ${this.length}`);const gl=this.context.gl;this.bind();gl.bufferSubData(gl.ARRAY_BUFFER,0,array.arrayBuffer)}enableAttributes(gl,program){for(let j=0;j0){const invTransform=performance$1.create();const transform=posMatrix;performance$1.mul(invTransform,bucket.placementInvProjMatrix,painter.transform.glCoordMatrix);performance$1.mul(invTransform,invTransform,bucket.placementViewportMatrix);tileBatches.push({circleArray:circleArray,circleOffset:circleOffset,transform:transform,invTransform:invTransform,coord:coord});circleCount+=circleArray.length/4;circleOffset=circleCount}if(!buffers)continue;program.draw(context,gl.LINES,DepthMode.disabled,StencilMode.disabled,painter.colorModeForRenderPass(),CullFaceMode.disabled,collisionUniformValues(posMatrix,painter.transform,tile),painter.style.map.terrain&&painter.style.map.terrain.getTerrainData(coord),layer.id,buffers.layoutVertexBuffer,buffers.indexBuffer,buffers.segments,null,painter.transform.zoom,null,null,buffers.collisionVertexBuffer)}if(!isText||!tileBatches.length){return}const circleProgram=painter.useProgram("collisionCircle");const vertexData=new performance$1.CollisionCircleLayoutArray;vertexData.resize(circleCount*4);vertexData._trim();let vertexOffset=0;for(const batch of tileBatches){for(let i=0;ipainter.style.map.terrain.getElevation(coord,x,y):null;updateVariableAnchorsForBucket(bucket,rotateWithMap,pitchWithMap,variableOffsets,tr,labelPlaneMatrix,coord.posMatrix,tileScale,size,updateTextFitIcon,getElevation)}}}function updateVariableAnchorsForBucket(bucket,rotateWithMap,pitchWithMap,variableOffsets,transform,labelPlaneMatrix,posMatrix,tileScale,size,updateTextFitIcon,getElevation){const placedSymbols=bucket.text.placedSymbolArray;const dynamicTextLayoutVertexArray=bucket.text.dynamicLayoutVertexArray;const dynamicIconLayoutVertexArray=bucket.icon.dynamicLayoutVertexArray;const placedTextShifts={};dynamicTextLayoutVertexArray.clear();for(let s=0;s=0){placedTextShifts[symbol.associatedIconIndex]={shiftedAnchor:shiftedAnchor,angle:angle}}}}if(updateTextFitIcon){dynamicIconLayoutVertexArray.clear();const placedIcons=bucket.icon.placedSymbolArray;for(let i=0;ipainter.style.map.terrain.getElevation(coord,x,y):null;const rotateToLine=layer.layout.get("text-rotation-alignment")==="map";updateLineLabels(bucket,coord.posMatrix,painter,isText,labelPlaneMatrix,glCoordMatrix,pitchWithMap,keepUpright,rotateToLine,getElevation)}const matrix=painter.translatePosMatrix(coord.posMatrix,tile,translate,translateAnchor),uLabelPlaneMatrix=alongLine||isText&&hasVariablePlacement||updateTextFitIcon?identityMat4:labelPlaneMatrix,uglCoordMatrix=painter.translatePosMatrix(glCoordMatrix,tile,translate,translateAnchor,true);const hasHalo=isSDF&&layer.paint.get(isText?"text-halo-width":"icon-halo-width").constantOr(1)!==0;let uniformValues;if(isSDF){if(!bucket.iconsInText){uniformValues=symbolSDFUniformValues(sizeData.kind,size,rotateInShader,pitchWithMap,painter,matrix,uLabelPlaneMatrix,uglCoordMatrix,isText,texSize,true)}else{uniformValues=symbolTextAndIconUniformValues(sizeData.kind,size,rotateInShader,pitchWithMap,painter,matrix,uLabelPlaneMatrix,uglCoordMatrix,texSize,texSizeIcon)}}else{uniformValues=symbolIconUniformValues(sizeData.kind,size,rotateInShader,pitchWithMap,painter,matrix,uLabelPlaneMatrix,uglCoordMatrix,isText,texSize)}const state={program:program,buffers:buffers,uniformValues:uniformValues,atlasTexture:atlasTexture,atlasTextureIcon:atlasTextureIcon,atlasInterpolation:atlasInterpolation,atlasInterpolationIcon:atlasInterpolationIcon,isSDF:isSDF,hasHalo:hasHalo};if(hasSortKey&&bucket.canOverlap){sortFeaturesByKey=true;const oldSegments=buffers.segments.get();for(const segment of oldSegments){tileRenderState.push({segments:new performance$1.SegmentVector([segment]),sortKey:segment.sortKey,state:state,terrainData:terrainData})}}else{tileRenderState.push({segments:buffers.segments,sortKey:0,state:state,terrainData:terrainData})}}if(sortFeaturesByKey){tileRenderState.sort(((a,b)=>a.sortKey-b.sortKey))}for(const segmentState of tileRenderState){const state=segmentState.state;context.activeTexture.set(gl.TEXTURE0);state.atlasTexture.bind(state.atlasInterpolation,gl.CLAMP_TO_EDGE);if(state.atlasTextureIcon){context.activeTexture.set(gl.TEXTURE1);if(state.atlasTextureIcon){state.atlasTextureIcon.bind(state.atlasInterpolationIcon,gl.CLAMP_TO_EDGE)}}if(state.isSDF){const uniformValues=state.uniformValues;if(state.hasHalo){uniformValues["u_is_halo"]=1;drawSymbolElements(state.buffers,segmentState.segments,layer,painter,state.program,depthMode,stencilMode,colorMode,uniformValues,segmentState.terrainData)}uniformValues["u_is_halo"]=0}drawSymbolElements(state.buffers,segmentState.segments,layer,painter,state.program,depthMode,stencilMode,colorMode,state.uniformValues,segmentState.terrainData)}}function drawSymbolElements(buffers,segments,layer,painter,program,depthMode,stencilMode,colorMode,uniformValues,terrainData){const context=painter.context;const gl=context.gl;program.draw(context,gl.TRIANGLES,depthMode,stencilMode,colorMode,CullFaceMode.disabled,uniformValues,terrainData,layer.id,buffers.layoutVertexBuffer,buffers.indexBuffer,segments,layer.paint,painter.transform.zoom,buffers.programConfigurations.get(layer.id),buffers.dynamicLayoutVertexBuffer,buffers.opacityVertexBuffer)}function drawCircles(painter,sourceCache,layer,coords){if(painter.renderPass!=="translucent")return;const opacity=layer.paint.get("circle-opacity");const strokeWidth=layer.paint.get("circle-stroke-width");const strokeOpacity=layer.paint.get("circle-stroke-opacity");const sortFeaturesByKey=!layer.layout.get("circle-sort-key").isConstant();if(opacity.constantOr(1)===0&&(strokeWidth.constantOr(1)===0||strokeOpacity.constantOr(1)===0)){return}const context=painter.context;const gl=context.gl;const depthMode=painter.depthModeForSublayer(0,DepthMode.ReadOnly);const stencilMode=StencilMode.disabled;const colorMode=painter.colorModeForRenderPass();const segmentsRenderStates=[];for(let i=0;ia.sortKey-b.sortKey))}for(const segmentsState of segmentsRenderStates){const{programConfiguration:programConfiguration,program:program,layoutVertexBuffer:layoutVertexBuffer,indexBuffer:indexBuffer,uniformValues:uniformValues,terrainData:terrainData}=segmentsState.state;const segments=segmentsState.segments;program.draw(context,gl.TRIANGLES,depthMode,stencilMode,colorMode,CullFaceMode.disabled,uniformValues,terrainData,layer.id,layoutVertexBuffer,indexBuffer,segments,layer.paint,painter.transform.zoom,programConfiguration)}}function drawHeatmap(painter,sourceCache,layer,coords){if(layer.paint.get("heatmap-opacity")===0){return}if(painter.renderPass==="offscreen"){const context=painter.context;const gl=context.gl;const stencilMode=StencilMode.disabled;const colorMode=new ColorMode([gl.ONE,gl.ONE],performance$1.Color.transparent,[true,true,true,true]);bindFramebuffer(context,painter,layer);context.clear({color:performance$1.Color.transparent});for(let i=0;i0){const now=browser.now();const sinceTile=(now-tile.timeAdded)/fadeDuration;const sinceParent=parentTile?(now-parentTile.timeAdded)/fadeDuration:-1;const source=sourceCache.getSource();const idealZ=transform.coveringZoomLevel({tileSize:source.tileSize,roundZoom:source.roundZoom});const fadeIn=!parentTile||Math.abs(parentTile.tileID.overscaledZ-idealZ)>Math.abs(tile.tileID.overscaledZ-idealZ);const childOpacity=fadeIn&&tile.refreshedUponExpiration?1:performance$1.clamp(fadeIn?sinceTile:1-sinceParent,0,1);if(tile.refreshedUponExpiration&&sinceTile>=1)tile.refreshedUponExpiration=false;if(parentTile){return{opacity:1,mix:1-childOpacity}}else{return{opacity:childOpacity,mix:0}}}else{return{opacity:1,mix:0}}}function drawBackground(painter,sourceCache,layer,coords){const color=layer.paint.get("background-color");const opacity=layer.paint.get("background-opacity");if(opacity===0)return;const context=painter.context;const gl=context.gl;const transform=painter.transform;const tileSize=transform.tileSize;const image=layer.paint.get("background-pattern");if(painter.isPatternMissing(image))return;const pass=!image&&color.a===1&&opacity===1&&painter.opaquePassEnabledForLayer()?"opaque":"translucent";if(painter.renderPass!==pass)return;const stencilMode=StencilMode.disabled;const depthMode=painter.depthModeForSublayer(0,pass==="opaque"?DepthMode.ReadWrite:DepthMode.ReadOnly);const colorMode=painter.colorModeForRenderPass();const program=painter.useProgram(image?"backgroundPattern":"background");const tileIDs=coords?coords:transform.coveringTiles({tileSize:tileSize,terrain:painter.style.map.terrain});if(image){context.activeTexture.set(gl.TEXTURE0);painter.imageManager.bind(painter.context)}const crossfade=layer.getCrossfadeParameters();for(const tileID of tileIDs){const matrix=coords?tileID.posMatrix:painter.transform.calculatePosMatrix(tileID.toUnwrapped());const uniformValues=image?backgroundPatternUniformValues(matrix,opacity,painter,image,{tileID:tileID,tileSize:tileSize},crossfade):backgroundUniformValues(matrix,opacity,color);const terrainData=painter.style.map.terrain&&painter.style.map.terrain.getTerrainData(tileID);program.draw(context,gl.TRIANGLES,depthMode,stencilMode,colorMode,CullFaceMode.disabled,uniformValues,terrainData,layer.id,painter.tileExtentBuffer,painter.quadTriangleIndexBuffer,painter.tileExtentSegments)}}const topColor=new performance$1.Color(1,0,0,1);const btmColor=new performance$1.Color(0,1,0,1);const leftColor=new performance$1.Color(0,0,1,1);const rightColor=new performance$1.Color(1,0,1,1);const centerColor=new performance$1.Color(0,1,1,1);function drawDebugPadding(painter){const padding=painter.transform.padding;const lineWidth=3;drawHorizontalLine(painter,painter.transform.height-(padding.top||0),lineWidth,topColor);drawHorizontalLine(painter,padding.bottom||0,lineWidth,btmColor);drawVerticalLine(painter,padding.left||0,lineWidth,leftColor);drawVerticalLine(painter,painter.transform.width-(padding.right||0),lineWidth,rightColor);const center=painter.transform.centerPoint;drawCrosshair(painter,center.x,painter.transform.height-center.y,centerColor)}function drawCrosshair(painter,x,y,color){const size=20;const lineWidth=2;drawDebugSSRect(painter,x-lineWidth/2,y-size/2,lineWidth,size,color);drawDebugSSRect(painter,x-size/2,y-lineWidth/2,size,lineWidth,color)}function drawHorizontalLine(painter,y,lineWidth,color){drawDebugSSRect(painter,0,y+lineWidth/2,painter.transform.width,lineWidth,color)}function drawVerticalLine(painter,x,lineWidth,color){drawDebugSSRect(painter,x-lineWidth/2,0,lineWidth,painter.transform.height,color)}function drawDebugSSRect(painter,x,y,width,height,color){const context=painter.context;const gl=context.gl;gl.enable(gl.SCISSOR_TEST);gl.scissor(x*painter.pixelRatio,y*painter.pixelRatio,width*painter.pixelRatio,height*painter.pixelRatio);context.clear({color:color});gl.disable(gl.SCISSOR_TEST)}function drawDebug(painter,sourceCache,coords){for(let i=0;i ${coord.overscaledZ}`}const tileLabel=`${tileIdText} ${tileSizeKb}kB`;drawTextToOverlay(painter,tileLabel);program.draw(context,gl.TRIANGLES,depthMode,stencilMode,ColorMode.alphaBlended,CullFaceMode.disabled,debugUniformValues(posMatrix,performance$1.Color.transparent,scaleRatio),null,id,painter.debugBuffer,painter.quadTriangleIndexBuffer,painter.debugSegments);program.draw(context,gl.LINE_STRIP,depthMode,stencilMode,colorMode,CullFaceMode.disabled,debugUniformValues(posMatrix,performance$1.Color.red),terrainData,id,painter.debugBuffer,painter.tileBorderIndexBuffer,painter.debugSegments)}function drawTextToOverlay(painter,text){painter.initDebugOverlayCanvas();const canvas=painter.debugOverlayCanvas;const gl=painter.context.gl;const ctx2d=painter.debugOverlayCanvas.getContext("2d");ctx2d.clearRect(0,0,canvas.width,canvas.height);ctx2d.shadowColor="white";ctx2d.shadowBlur=2;ctx2d.lineWidth=1.5;ctx2d.strokeStyle="white";ctx2d.textBaseline="top";ctx2d.font=`bold ${36}px Open Sans, sans-serif`;ctx2d.fillText(text,5,5);ctx2d.strokeText(text,5,5);painter.debugOverlayTexture.update(canvas);painter.debugOverlayTexture.bind(gl.LINEAR,gl.CLAMP_TO_EDGE)}function selectDebugSource(style,zoom){let selectedSource=null;const layers=Object.values(style._layers);const sources=layers.flatMap((layer=>{if(layer.source&&!layer.isHidden(zoom)){const sourceCache=style.sourceCaches[layer.source];return[sourceCache]}else{return[]}}));const vectorSources=sources.filter((source=>source.getSource().type==="vector"));const otherSources=sources.filter((source=>source.getSource().type!=="vector"));const considerSource=source=>{if(!selectedSource||selectedSource.getSource().maxzoomconsiderSource(source)));if(!selectedSource){otherSources.forEach((source=>considerSource(source)))}return selectedSource}function drawCustom(painter,sourceCache,layer){const context=painter.context;const implementation=layer.implementation;if(painter.renderPass==="offscreen"){const prerender=implementation.prerender;if(prerender){painter.setCustomLayerDefaults();context.setColorMode(painter.colorModeForRenderPass());prerender.call(implementation,context.gl,painter.transform.customLayerMatrix());context.setDirty();painter.setBaseState()}}else if(painter.renderPass==="translucent"){painter.setCustomLayerDefaults();context.setColorMode(painter.colorModeForRenderPass());context.setStencilMode(StencilMode.disabled);const depthMode=implementation.renderingMode==="3d"?new DepthMode(painter.context.gl.LEQUAL,DepthMode.ReadWrite,painter.depthRangeFor3D):painter.depthModeForSublayer(0,DepthMode.ReadOnly);context.setDepthMode(depthMode);implementation.render(context.gl,painter.transform.customLayerMatrix());context.setDirty();painter.setBaseState();context.bindFramebuffer.set(null)}}function drawDepth(painter,terrain){const context=painter.context;const gl=context.gl;const colorMode=ColorMode.unblended;const depthMode=new DepthMode(gl.LEQUAL,DepthMode.ReadWrite,[0,1]);const mesh=terrain.getTerrainMesh();const tiles=terrain.sourceCache.getRenderableTiles();const program=painter.useProgram("terrainDepth");context.bindFramebuffer.set(terrain.getFramebuffer("depth").framebuffer);context.viewport.set([0,0,painter.width/devicePixelRatio,painter.height/devicePixelRatio]);context.clear({color:performance$1.Color.transparent,depth:1});for(const tile of tiles){const terrainData=terrain.getTerrainData(tile.tileID);const posMatrix=painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped());const uniformValues=terrainDepthUniformValues(posMatrix,terrain.getMeshFrameDelta(painter.transform.zoom));program.draw(context,gl.TRIANGLES,depthMode,StencilMode.disabled,colorMode,CullFaceMode.backCCW,uniformValues,terrainData,"terrain",mesh.vertexBuffer,mesh.indexBuffer,mesh.segments)}context.bindFramebuffer.set(null);context.viewport.set([0,0,painter.width,painter.height])}function drawCoords(painter,terrain){const context=painter.context;const gl=context.gl;const colorMode=ColorMode.unblended;const depthMode=new DepthMode(gl.LEQUAL,DepthMode.ReadWrite,[0,1]);const mesh=terrain.getTerrainMesh();const coords=terrain.getCoordsTexture();const tiles=terrain.sourceCache.getRenderableTiles();const program=painter.useProgram("terrainCoords");context.bindFramebuffer.set(terrain.getFramebuffer("coords").framebuffer);context.viewport.set([0,0,painter.width/devicePixelRatio,painter.height/devicePixelRatio]);context.clear({color:performance$1.Color.transparent,depth:1});terrain.coordsIndex=[];for(const tile of tiles){const terrainData=terrain.getTerrainData(tile.tileID);context.activeTexture.set(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,coords.texture);const posMatrix=painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped());const uniformValues=terrainCoordsUniformValues(posMatrix,255-terrain.coordsIndex.length,terrain.getMeshFrameDelta(painter.transform.zoom));program.draw(context,gl.TRIANGLES,depthMode,StencilMode.disabled,colorMode,CullFaceMode.backCCW,uniformValues,terrainData,"terrain",mesh.vertexBuffer,mesh.indexBuffer,mesh.segments);terrain.coordsIndex.push(tile.tileID.key)}context.bindFramebuffer.set(null);context.viewport.set([0,0,painter.width,painter.height])}function drawTerrain(painter,terrain,tiles){const context=painter.context;const gl=context.gl;const colorMode=painter.colorModeForRenderPass();const depthMode=new DepthMode(gl.LEQUAL,DepthMode.ReadWrite,painter.depthRangeFor3D);const program=painter.useProgram("terrain");const mesh=terrain.getTerrainMesh();context.bindFramebuffer.set(null);context.viewport.set([0,0,painter.width,painter.height]);for(const tile of tiles){const texture=painter.renderToTexture.getTexture(tile);const terrainData=terrain.getTerrainData(tile.tileID);context.activeTexture.set(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,texture.texture);const posMatrix=painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped());const uniformValues=terrainUniformValues(posMatrix,terrain.getMeshFrameDelta(painter.transform.zoom));program.draw(context,gl.TRIANGLES,depthMode,StencilMode.disabled,colorMode,CullFaceMode.backCCW,uniformValues,terrainData,"terrain",mesh.vertexBuffer,mesh.indexBuffer,mesh.segments)}}class Painter{constructor(gl,transform){this.context=new Context(gl);this.transform=transform;this._tileTextures={};this.terrainFacilitator={dirty:true,matrix:performance$1.create(),renderTime:0};this.setup();this.numSublayers=SourceCache.maxUnderzooming+SourceCache.maxOverzooming+1;this.depthEpsilon=1/Math.pow(2,16);this.crossTileSymbolIndex=new CrossTileSymbolIndex}resize(width,height,pixelRatio){this.width=Math.floor(width*pixelRatio);this.height=Math.floor(height*pixelRatio);this.pixelRatio=pixelRatio;this.context.viewport.set([0,0,this.width,this.height]);if(this.style){for(const layerId of this.style._order){this.style._layers[layerId].resize()}}}setup(){const context=this.context;const tileExtentArray=new performance$1.PosArray;tileExtentArray.emplaceBack(0,0);tileExtentArray.emplaceBack(performance$1.EXTENT,0);tileExtentArray.emplaceBack(0,performance$1.EXTENT);tileExtentArray.emplaceBack(performance$1.EXTENT,performance$1.EXTENT);this.tileExtentBuffer=context.createVertexBuffer(tileExtentArray,posAttributes.members);this.tileExtentSegments=performance$1.SegmentVector.simpleSegment(0,0,4,2);const debugArray=new performance$1.PosArray;debugArray.emplaceBack(0,0);debugArray.emplaceBack(performance$1.EXTENT,0);debugArray.emplaceBack(0,performance$1.EXTENT);debugArray.emplaceBack(performance$1.EXTENT,performance$1.EXTENT);this.debugBuffer=context.createVertexBuffer(debugArray,posAttributes.members);this.debugSegments=performance$1.SegmentVector.simpleSegment(0,0,4,5);const rasterBoundsArray=new performance$1.RasterBoundsArray;rasterBoundsArray.emplaceBack(0,0,0,0);rasterBoundsArray.emplaceBack(performance$1.EXTENT,0,performance$1.EXTENT,0);rasterBoundsArray.emplaceBack(0,performance$1.EXTENT,0,performance$1.EXTENT);rasterBoundsArray.emplaceBack(performance$1.EXTENT,performance$1.EXTENT,performance$1.EXTENT,performance$1.EXTENT);this.rasterBoundsBuffer=context.createVertexBuffer(rasterBoundsArray,rasterBoundsAttributes.members);this.rasterBoundsSegments=performance$1.SegmentVector.simpleSegment(0,0,4,2);const viewportArray=new performance$1.PosArray;viewportArray.emplaceBack(0,0);viewportArray.emplaceBack(1,0);viewportArray.emplaceBack(0,1);viewportArray.emplaceBack(1,1);this.viewportBuffer=context.createVertexBuffer(viewportArray,posAttributes.members);this.viewportSegments=performance$1.SegmentVector.simpleSegment(0,0,4,2);const tileLineStripIndices=new performance$1.LineStripIndexArray;tileLineStripIndices.emplaceBack(0);tileLineStripIndices.emplaceBack(1);tileLineStripIndices.emplaceBack(3);tileLineStripIndices.emplaceBack(2);tileLineStripIndices.emplaceBack(0);this.tileBorderIndexBuffer=context.createIndexBuffer(tileLineStripIndices);const quadTriangleIndices=new performance$1.TriangleIndexArray;quadTriangleIndices.emplaceBack(0,1,2);quadTriangleIndices.emplaceBack(2,1,3);this.quadTriangleIndexBuffer=context.createIndexBuffer(quadTriangleIndices);const gl=this.context.gl;this.stencilClearMode=new StencilMode({func:gl.ALWAYS,mask:0},0,255,gl.ZERO,gl.ZERO,gl.ZERO)}clearStencil(){const context=this.context;const gl=context.gl;this.nextStencilID=1;this.currentStencilSource=undefined;const matrix=performance$1.create();performance$1.ortho(matrix,0,this.width,this.height,0,0,1);performance$1.scale(matrix,matrix,[gl.drawingBufferWidth,gl.drawingBufferHeight,0]);this.useProgram("clippingMask").draw(context,gl.TRIANGLES,DepthMode.disabled,this.stencilClearMode,ColorMode.disabled,CullFaceMode.disabled,clippingMaskUniformValues(matrix),null,"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}_renderTileClippingMasks(layer,tileIDs){if(this.currentStencilSource===layer.source||!layer.isTileClipped()||!tileIDs||!tileIDs.length)return;this.currentStencilSource=layer.source;const context=this.context;const gl=context.gl;if(this.nextStencilID+tileIDs.length>256){this.clearStencil()}context.setColorMode(ColorMode.disabled);context.setDepthMode(DepthMode.disabled);const program=this.useProgram("clippingMask");this._tileClippingMaskIDs={};for(const tileID of tileIDs){const id=this._tileClippingMaskIDs[tileID.key]=this.nextStencilID++;const terrainData=this.style.map.terrain&&this.style.map.terrain.getTerrainData(tileID);program.draw(context,gl.TRIANGLES,DepthMode.disabled,new StencilMode({func:gl.ALWAYS,mask:0},id,255,gl.KEEP,gl.KEEP,gl.REPLACE),ColorMode.disabled,CullFaceMode.disabled,clippingMaskUniformValues(tileID.posMatrix),terrainData,"$clipping",this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments)}}stencilModeFor3D(){this.currentStencilSource=undefined;if(this.nextStencilID+1>256){this.clearStencil()}const id=this.nextStencilID++;const gl=this.context.gl;return new StencilMode({func:gl.NOTEQUAL,mask:255},id,255,gl.KEEP,gl.KEEP,gl.REPLACE)}stencilModeForClipping(tileID){const gl=this.context.gl;return new StencilMode({func:gl.EQUAL,mask:255},this._tileClippingMaskIDs[tileID.key],0,gl.KEEP,gl.KEEP,gl.REPLACE)}stencilConfigForOverlap(tileIDs){const gl=this.context.gl;const coords=tileIDs.sort(((a,b)=>b.overscaledZ-a.overscaledZ));const minTileZ=coords[coords.length-1].overscaledZ;const stencilValues=coords[0].overscaledZ-minTileZ+1;if(stencilValues>1){this.currentStencilSource=undefined;if(this.nextStencilID+stencilValues>256){this.clearStencil()}const zToStencilMode={};for(let i=0;i=0;this.currentLayer--){const layer=this.style._layers[layerIds[this.currentLayer]];const sourceCache=sourceCaches[layer.source];const coords=coordsAscending[layer.source];this._renderTileClippingMasks(layer,coords);this.renderLayer(this,sourceCache,layer,coords)}}this.renderPass="translucent";for(this.currentLayer=0;this.currentLayer0?textures.pop():null}isPatternMissing(image){if(!image)return false;if(!image.from||!image.to)return true;const imagePosA=this.imageManager.getPattern(image.from.toString());const imagePosB=this.imageManager.getPattern(image.to.toString());return!imagePosA||!imagePosB}useProgram(name,programConfiguration){this.cache=this.cache||{};const key=name+(programConfiguration?programConfiguration.cacheKey:"")+(this._showOverdrawInspector?"/overdraw":"")+(this.style.map.terrain?"/terrain":"");if(!this.cache[key]){this.cache[key]=new Program(this.context,shaders[name],programConfiguration,programUniforms[name],this._showOverdrawInspector,this.style.map.terrain)}return this.cache[key]}setCustomLayerDefaults(){this.context.unbindVAO();this.context.cullFace.setDefault();this.context.activeTexture.setDefault();this.context.pixelStoreUnpack.setDefault();this.context.pixelStoreUnpackPremultiplyAlpha.setDefault();this.context.pixelStoreUnpackFlipY.setDefault()}setBaseState(){const gl=this.context.gl;this.context.cullFace.set(false);this.context.viewport.set([0,0,this.width,this.height]);this.context.blendEquation.set(gl.FUNC_ADD)}initDebugOverlayCanvas(){if(this.debugOverlayCanvas==null){this.debugOverlayCanvas=document.createElement("canvas");this.debugOverlayCanvas.width=512;this.debugOverlayCanvas.height=512;const gl=this.context.gl;this.debugOverlayTexture=new Texture(this.context,this.debugOverlayCanvas,gl.RGBA)}}destroy(){if(this.debugOverlayTexture){this.debugOverlayTexture.destroy()}}overLimit(){const{drawingBufferWidth:drawingBufferWidth,drawingBufferHeight:drawingBufferHeight}=this.context.gl;return this.width!==drawingBufferWidth||this.height!==drawingBufferHeight}}class Frustum{constructor(points,planes){this.points=points;this.planes=planes}static fromInvProjectionMatrix(invProj,worldSize,zoom){const clipSpaceCorners=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]];const scale=Math.pow(2,zoom);const frustumCoords=clipSpaceCorners.map((v=>{v=performance$1.transformMat4([],v,invProj);const s=1/v[3]/worldSize*scale;return performance$1.mul$1(v,v,[s,s,1/v[3],s])}));const frustumPlanePointIndices=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]];const frustumPlanes=frustumPlanePointIndices.map((p=>{const a=performance$1.sub([],frustumCoords[p[0]],frustumCoords[p[1]]);const b=performance$1.sub([],frustumCoords[p[2]],frustumCoords[p[1]]);const n=performance$1.normalize([],performance$1.cross([],a,b));const d=-performance$1.dot(n,frustumCoords[p[1]]);return n.concat(d)}));return new Frustum(frustumCoords,frustumPlanes)}}class Aabb{constructor(min_,max_){this.min=min_;this.max=max_;this.center=performance$1.scale$1([],performance$1.add([],this.min,this.max),.5)}quadrant(index){const split=[index%2===0,index<2];const qMin=performance$1.clone$2(this.min);const qMax=performance$1.clone$2(this.max);for(let axis=0;axis=0){pointsInside++}}if(pointsInside===0)return 0;if(pointsInside!==aabbPoints.length)fullyInside=false}if(fullyInside)return 2;for(let axis=0;axis<3;axis++){let projMin=Number.MAX_VALUE;let projMax=-Number.MAX_VALUE;for(let p=0;pthis.max[axis]-this.min[axis])return 0}return 1}}class EdgeInsets{constructor(top=0,bottom=0,left=0,right=0){if(isNaN(top)||top<0||isNaN(bottom)||bottom<0||isNaN(left)||left<0||isNaN(right)||right<0){throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers")}this.top=top;this.bottom=bottom;this.left=left;this.right=right}interpolate(start,target,t){if(target.top!=null&&start.top!=null)this.top=performance$1.interpolate.number(start.top,target.top,t);if(target.bottom!=null&&start.bottom!=null)this.bottom=performance$1.interpolate.number(start.bottom,target.bottom,t);if(target.left!=null&&start.left!=null)this.left=performance$1.interpolate.number(start.left,target.left,t);if(target.right!=null&&start.right!=null)this.right=performance$1.interpolate.number(start.right,target.right,t);return this}getCenter(width,height){const x=performance$1.clamp((this.left+width-this.right)/2,0,width);const y=performance$1.clamp((this.top+height-this.bottom)/2,0,height);return new performance$1.Point(x,y)}equals(other){return this.top===other.top&&this.bottom===other.bottom&&this.left===other.left&&this.right===other.right}clone(){return new EdgeInsets(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}class Transform{constructor(minZoom,maxZoom,minPitch,maxPitch,renderWorldCopies){this.tileSize=512;this.maxValidLatitude=85.051129;this._renderWorldCopies=renderWorldCopies===undefined?true:!!renderWorldCopies;this._minZoom=minZoom||0;this._maxZoom=maxZoom||22;this._minPitch=minPitch===undefined||minPitch===null?0:minPitch;this._maxPitch=maxPitch===undefined||maxPitch===null?60:maxPitch;this.setMaxBounds();this.width=0;this.height=0;this._center=new performance$1.LngLat(0,0);this._elevation=0;this.zoom=0;this.angle=0;this._fov=.6435011087932844;this._pitch=0;this._unmodified=true;this._edgeInsets=new EdgeInsets;this._posMatrixCache={};this._alignedPosMatrixCache={};this.minElevationForCurrentTile=0}clone(){const clone=new Transform(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies);clone.apply(this);return clone}apply(that){this.tileSize=that.tileSize;this.latRange=that.latRange;this.width=that.width;this.height=that.height;this._center=that._center;this._elevation=that._elevation;this.minElevationForCurrentTile=that.minElevationForCurrentTile;this.zoom=that.zoom;this.angle=that.angle;this._fov=that._fov;this._pitch=that._pitch;this._unmodified=that._unmodified;this._edgeInsets=that._edgeInsets.clone();this._calcMatrices()}get minZoom(){return this._minZoom}set minZoom(zoom){if(this._minZoom===zoom)return;this._minZoom=zoom;this.zoom=Math.max(this.zoom,zoom)}get maxZoom(){return this._maxZoom}set maxZoom(zoom){if(this._maxZoom===zoom)return;this._maxZoom=zoom;this.zoom=Math.min(this.zoom,zoom)}get minPitch(){return this._minPitch}set minPitch(pitch){if(this._minPitch===pitch)return;this._minPitch=pitch;this.pitch=Math.max(this.pitch,pitch)}get maxPitch(){return this._maxPitch}set maxPitch(pitch){if(this._maxPitch===pitch)return;this._maxPitch=pitch;this.pitch=Math.min(this.pitch,pitch)}get renderWorldCopies(){return this._renderWorldCopies}set renderWorldCopies(renderWorldCopies){if(renderWorldCopies===undefined){renderWorldCopies=true}else if(renderWorldCopies===null){renderWorldCopies=false}this._renderWorldCopies=renderWorldCopies}get worldSize(){return this.tileSize*this.scale}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new performance$1.Point(this.width,this.height)}get bearing(){return-this.angle/Math.PI*180}set bearing(bearing){const b=-performance$1.wrap(bearing,-180,180)*Math.PI/180;if(this.angle===b)return;this._unmodified=false;this.angle=b;this._calcMatrices();this.rotationMatrix=performance$1.create$2();performance$1.rotate(this.rotationMatrix,this.rotationMatrix,this.angle)}get pitch(){return this._pitch/Math.PI*180}set pitch(pitch){const p=performance$1.clamp(pitch,this.minPitch,this.maxPitch)/180*Math.PI;if(this._pitch===p)return;this._unmodified=false;this._pitch=p;this._calcMatrices()}get fov(){return this._fov/Math.PI*180}set fov(fov){fov=Math.max(.01,Math.min(60,fov));if(this._fov===fov)return;this._unmodified=false;this._fov=fov/180*Math.PI;this._calcMatrices()}get zoom(){return this._zoom}set zoom(zoom){const constrainedZoom=Math.min(Math.max(zoom,this.minZoom),this.maxZoom);if(this._zoom===constrainedZoom)return;this._unmodified=false;this._zoom=constrainedZoom;this.tileZoom=Math.max(0,Math.floor(constrainedZoom));this.scale=this.zoomScale(constrainedZoom);this._constrain();this._calcMatrices()}get center(){return this._center}set center(center){if(center.lat===this._center.lat&¢er.lng===this._center.lng)return;this._unmodified=false;this._center=center;this._constrain();this._calcMatrices()}get elevation(){return this._elevation}set elevation(elevation){if(elevation===this._elevation)return;this._elevation=elevation;this._constrain();this._calcMatrices()}get padding(){return this._edgeInsets.toJSON()}set padding(padding){if(this._edgeInsets.equals(padding))return;this._unmodified=false;this._edgeInsets.interpolate(this._edgeInsets,padding,1);this._calcMatrices()}get centerPoint(){return this._edgeInsets.getCenter(this.width,this.height)}isPaddingEqual(padding){return this._edgeInsets.equals(padding)}interpolatePadding(start,target,t){this._unmodified=false;this._edgeInsets.interpolate(start,target,t);this._constrain();this._calcMatrices()}coveringZoomLevel(options){const z=(options.roundZoom?Math.round:Math.floor)(this.zoom+this.scaleZoom(this.tileSize/options.tileSize));return Math.max(0,z)}getVisibleUnwrappedCoordinates(tileID){const result=[new performance$1.UnwrappedTileID(0,tileID)];if(this._renderWorldCopies){const utl=this.pointCoordinate(new performance$1.Point(0,0));const utr=this.pointCoordinate(new performance$1.Point(this.width,0));const ubl=this.pointCoordinate(new performance$1.Point(this.width,this.height));const ubr=this.pointCoordinate(new performance$1.Point(0,this.height));const w0=Math.floor(Math.min(utl.x,utr.x,ubl.x,ubr.x));const w1=Math.floor(Math.max(utl.x,utr.x,ubl.x,ubr.x));const extraWorldCopy=1;for(let w=w0-extraWorldCopy;w<=w1+extraWorldCopy;w++){if(w===0)continue;result.push(new performance$1.UnwrappedTileID(w,tileID))}}return result}coveringTiles(options){var _a,_b;let z=this.coveringZoomLevel(options);const actualZ=z;if(options.minzoom!==undefined&&zoptions.maxzoom)z=options.maxzoom;const cameraCoord=this.pointCoordinate(this.getCameraPoint());const centerCoord=performance$1.MercatorCoordinate.fromLngLat(this.center);const numTiles=Math.pow(2,z);const cameraPoint=[numTiles*cameraCoord.x,numTiles*cameraCoord.y,0];const centerPoint=[numTiles*centerCoord.x,numTiles*centerCoord.y,0];const cameraFrustum=Frustum.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,z);let minZoom=options.minzoom||0;if(!options.terrain&&this.pitch<=60&&this._edgeInsets.top<.1)minZoom=z;const radiusOfMaxLvlLodInTiles=options.terrain?2/Math.min(this.tileSize,options.tileSize)*this.tileSize:3;const newRootTile=wrap=>({aabb:new Aabb([wrap*numTiles,0,0],[(wrap+1)*numTiles,numTiles,0]),zoom:0,x:0,y:0,wrap:wrap,fullyVisible:false});const stack=[];const result=[];const maxZoom=z;const overscaledZ=options.reparseOverscaled?actualZ:z;if(this._renderWorldCopies){for(let i=1;i<=3;i++){stack.push(newRootTile(-i));stack.push(newRootTile(i))}}stack.push(newRootTile(0));while(stack.length>0){const it=stack.pop();const x=it.x;const y=it.y;let fullyVisible=it.fullyVisible;if(!fullyVisible){const intersectResult=it.aabb.intersects(cameraFrustum);if(intersectResult===0)continue;fullyVisible=intersectResult===2}const refPoint=options.terrain?cameraPoint:centerPoint;const distanceX=it.aabb.distanceX(refPoint);const distanceY=it.aabb.distanceY(refPoint);const longestDim=Math.max(Math.abs(distanceX),Math.abs(distanceY));const distToSplit=radiusOfMaxLvlLodInTiles+(1<distToSplit&&it.zoom>=minZoom){const dz=maxZoom-it.zoom,dx=cameraPoint[0]-.5-(x<>1);const childZ=it.zoom+1;let quadrant=it.aabb.quadrant(i);if(options.terrain){const tileID=new performance$1.OverscaledTileID(childZ,it.wrap,childZ,childX,childY);const minMax=options.terrain.getMinMaxElevation(tileID);const minElevation=(_a=minMax.minElevation)!==null&&_a!==void 0?_a:this.elevation;const maxElevation=(_b=minMax.maxElevation)!==null&&_b!==void 0?_b:this.elevation;quadrant=new Aabb([quadrant.min[0],quadrant.min[1],minElevation],[quadrant.max[0],quadrant.max[1],maxElevation])}stack.push({aabb:quadrant,zoom:childZ,x:childX,y:childY,wrap:it.wrap,fullyVisible:fullyVisible})}}return result.sort(((a,b)=>a.distanceSq-b.distanceSq)).map((a=>a.tileID))}resize(width,height){this.width=width;this.height=height;this.pixelsToGLUnits=[2/width,-2/height];this._constrain();this._calcMatrices()}get unmodified(){return this._unmodified}zoomScale(zoom){return Math.pow(2,zoom)}scaleZoom(scale){return Math.log(scale)/Math.LN2}project(lnglat){const lat=performance$1.clamp(lnglat.lat,-this.maxValidLatitude,this.maxValidLatitude);return new performance$1.Point(performance$1.mercatorXfromLng(lnglat.lng)*this.worldSize,performance$1.mercatorYfromLat(lat)*this.worldSize)}unproject(point){return new performance$1.MercatorCoordinate(point.x/this.worldSize,point.y/this.worldSize).toLngLat()}get point(){return this.project(this.center)}getCameraPosition(){const lngLat=this.pointLocation(this.getCameraPoint());const altitude=Math.cos(this._pitch)*this.cameraToCenterDistance/this._pixelPerMeter;return{lngLat:lngLat,altitude:altitude+this.elevation}}recalculateZoom(terrain){const center=this.pointLocation(this.centerPoint,terrain);const elevation=terrain.getElevationForLngLatZoom(center,this.tileZoom);const deltaElevation=this.elevation-elevation;if(!deltaElevation)return;const cameraPosition=this.getCameraPosition();const camera=performance$1.MercatorCoordinate.fromLngLat(cameraPosition.lngLat,cameraPosition.altitude);const target=performance$1.MercatorCoordinate.fromLngLat(center,elevation);const dx=camera.x-target.x,dy=camera.y-target.y,dz=camera.z-target.z;const distance=Math.sqrt(dx*dx+dy*dy+dz*dz);const zoom=this.scaleZoom(this.cameraToCenterDistance/distance/this.tileSize);this._elevation=elevation;this._center=center;this.zoom=zoom}setLocationAtPoint(lnglat,point){const a=this.pointCoordinate(point);const b=this.pointCoordinate(this.centerPoint);const loc=this.locationCoordinate(lnglat);const newCenter=new performance$1.MercatorCoordinate(loc.x-(a.x-b.x),loc.y-(a.y-b.y));this.center=this.coordinateLocation(newCenter);if(this._renderWorldCopies){this.center=this.center.wrap()}}locationPoint(lnglat,terrain){return terrain?this.coordinatePoint(this.locationCoordinate(lnglat),terrain.getElevationForLngLatZoom(lnglat,this.tileZoom),this.pixelMatrix3D):this.coordinatePoint(this.locationCoordinate(lnglat))}pointLocation(p,terrain){return this.coordinateLocation(this.pointCoordinate(p,terrain))}locationCoordinate(lnglat){return performance$1.MercatorCoordinate.fromLngLat(lnglat)}coordinateLocation(coord){return coord&&coord.toLngLat()}pointCoordinate(p,terrain){if(terrain){const coordinate=terrain.pointCoordinate(p);if(coordinate!=null){return coordinate}}const targetZ=0;const coord0=[p.x,p.y,0,1];const coord1=[p.x,p.y,1,1];performance$1.transformMat4(coord0,coord0,this.pixelMatrixInverse);performance$1.transformMat4(coord1,coord1,this.pixelMatrixInverse);const w0=coord0[3];const w1=coord1[3];const x0=coord0[0]/w0;const x1=coord1[0]/w1;const y0=coord0[1]/w0;const y1=coord1[1]/w1;const z0=coord0[2]/w0;const z1=coord1[2]/w1;const t=z0===z1?0:(targetZ-z0)/(z1-z0);return new performance$1.MercatorCoordinate(performance$1.interpolate.number(x0,x1,t)/this.worldSize,performance$1.interpolate.number(y0,y1,t)/this.worldSize)}coordinatePoint(coord,elevation=0,pixelMatrix=this.pixelMatrix){const p=[coord.x*this.worldSize,coord.y*this.worldSize,elevation,1];performance$1.transformMat4(p,p,pixelMatrix);return new performance$1.Point(p[0]/p[3],p[1]/p[3])}getBounds(){const top=Math.max(0,this.height/2-this.getHorizon());return(new LngLatBounds).extend(this.pointLocation(new performance$1.Point(0,top))).extend(this.pointLocation(new performance$1.Point(this.width,top))).extend(this.pointLocation(new performance$1.Point(this.width,this.height))).extend(this.pointLocation(new performance$1.Point(0,this.height)))}getMaxBounds(){if(!this.latRange||this.latRange.length!==2||!this.lngRange||this.lngRange.length!==2)return null;return new LngLatBounds([this.lngRange[0],this.latRange[0]],[this.lngRange[1],this.latRange[1]])}getHorizon(){return Math.tan(Math.PI/2-this._pitch)*this.cameraToCenterDistance*.85}setMaxBounds(bounds){if(bounds){this.lngRange=[bounds.getWest(),bounds.getEast()];this.latRange=[bounds.getSouth(),bounds.getNorth()];this._constrain()}else{this.lngRange=null;this.latRange=[-this.maxValidLatitude,this.maxValidLatitude]}}calculatePosMatrix(unwrappedTileID,aligned=false){const posMatrixKey=unwrappedTileID.key;const cache=aligned?this._alignedPosMatrixCache:this._posMatrixCache;if(cache[posMatrixKey]){return cache[posMatrixKey]}const canonical=unwrappedTileID.canonical;const scale=this.worldSize/this.zoomScale(canonical.z);const unwrappedX=canonical.x+Math.pow(2,canonical.z)*unwrappedTileID.wrap;const posMatrix=performance$1.identity(new Float64Array(16));performance$1.translate(posMatrix,posMatrix,[unwrappedX*scale,canonical.y*scale,0]);performance$1.scale(posMatrix,posMatrix,[scale/performance$1.EXTENT,scale/performance$1.EXTENT,1]);performance$1.multiply(posMatrix,aligned?this.alignedProjMatrix:this.projMatrix,posMatrix);cache[posMatrixKey]=new Float32Array(posMatrix);return cache[posMatrixKey]}customLayerMatrix(){return this.mercatorMatrix.slice()}_constrain(){if(!this.center||!this.width||!this.height||this._constraining)return;this._constraining=true;let minY=-90;let maxY=90;let minX=-180;let maxX=180;let sy,sx,x2,y2;const size=this.size,unmodified=this._unmodified;if(this.latRange){const latRange=this.latRange;minY=performance$1.mercatorYfromLat(latRange[1])*this.worldSize;maxY=performance$1.mercatorYfromLat(latRange[0])*this.worldSize;sy=maxY-minYmaxY)y2=maxY-h2}if(this.lngRange){const centerX=(minX+maxX)/2;const x=performance$1.wrap(point.x,centerX-this.worldSize/2,centerX+this.worldSize/2);const w2=size.x/2;if(x-w2maxX)x2=maxX-w2}if(x2!==undefined||y2!==undefined){this.center=this.unproject(new performance$1.Point(x2!==undefined?x2:point.x,y2!==undefined?y2:point.y)).wrap()}this._unmodified=unmodified;this._constraining=false}_calcMatrices(){if(!this.height)return;const halfFov=this._fov/2;const offset=this.centerOffset;const x=this.point.x,y=this.point.y;this.cameraToCenterDistance=.5/Math.tan(halfFov)*this.height;this._pixelPerMeter=performance$1.mercatorZfromAltitude(1,this.center.lat)*this.worldSize;let m=performance$1.identity(new Float64Array(16));performance$1.scale(m,m,[this.width/2,-this.height/2,1]);performance$1.translate(m,m,[1,-1,0]);this.labelPlaneMatrix=m;m=performance$1.identity(new Float64Array(16));performance$1.scale(m,m,[1,-1,1]);performance$1.translate(m,m,[-1,-1,0]);performance$1.scale(m,m,[2/this.width,2/this.height,1]);this.glCoordMatrix=m;const cameraToSeaLevelDistance=this.cameraToCenterDistance+this._elevation*this._pixelPerMeter/Math.cos(this._pitch);const minElevation=Math.min(this.elevation,this.minElevationForCurrentTile);const cameraToLowestPointDistance=cameraToSeaLevelDistance-minElevation*this._pixelPerMeter/Math.cos(this._pitch);const lowestPlane=minElevation<0?cameraToLowestPointDistance:cameraToSeaLevelDistance;const groundAngle=Math.PI/2+this._pitch;const fovAboveCenter=this._fov*(.5+offset.y/this.height);const topHalfSurfaceDistance=Math.sin(fovAboveCenter)*lowestPlane/Math.sin(performance$1.clamp(Math.PI-groundAngle-fovAboveCenter,.01,Math.PI-.01));const horizon=this.getHorizon();const horizonAngle=Math.atan(horizon/this.cameraToCenterDistance);const fovCenterToHorizon=2*horizonAngle*(.5+offset.y/(horizon*2));const topHalfSurfaceDistanceHorizon=Math.sin(fovCenterToHorizon)*lowestPlane/Math.sin(performance$1.clamp(Math.PI-groundAngle-fovCenterToHorizon,.01,Math.PI-.01));const topHalfMinDistance=Math.min(topHalfSurfaceDistance,topHalfSurfaceDistanceHorizon);const farZ=(Math.cos(Math.PI/2-this._pitch)*topHalfMinDistance+lowestPlane)*1.01;const nearZ=this.height/50;m=new Float64Array(16);performance$1.perspective(m,this._fov,this.width/this.height,nearZ,farZ);m[8]=-offset.x*2/this.width;m[9]=offset.y*2/this.height;performance$1.scale(m,m,[1,-1,1]);performance$1.translate(m,m,[0,0,-this.cameraToCenterDistance]);performance$1.rotateX(m,m,this._pitch);performance$1.rotateZ(m,m,this.angle);performance$1.translate(m,m,[-x,-y,0]);this.mercatorMatrix=performance$1.scale([],m,[this.worldSize,this.worldSize,this.worldSize]);performance$1.scale(m,m,[1,1,this._pixelPerMeter]);this.pixelMatrix=performance$1.multiply(new Float64Array(16),this.labelPlaneMatrix,m);performance$1.translate(m,m,[0,0,-this.elevation]);this.projMatrix=m;this.invProjMatrix=performance$1.invert([],m);this.pixelMatrix3D=performance$1.multiply(new Float64Array(16),this.labelPlaneMatrix,m);const xShift=this.width%2/2,yShift=this.height%2/2,angleCos=Math.cos(this.angle),angleSin=Math.sin(this.angle),dx=x-Math.round(x)+angleCos*xShift+angleSin*yShift,dy=y-Math.round(y)+angleCos*yShift+angleSin*xShift;const alignedM=new Float64Array(m);performance$1.translate(alignedM,alignedM,[dx>.5?dx-1:dx,dy>.5?dy-1:dy,0]);this.alignedProjMatrix=alignedM;m=performance$1.invert(new Float64Array(16),this.pixelMatrix);if(!m)throw new Error("failed to invert matrix");this.pixelMatrixInverse=m;this._posMatrixCache={};this._alignedPosMatrixCache={}}maxPitchScaleFactor(){if(!this.pixelMatrixInverse)return 1;const coord=this.pointCoordinate(new performance$1.Point(0,0));const p=[coord.x*this.worldSize,coord.y*this.worldSize,0,1];const topPoint=performance$1.transformMat4(p,p,this.pixelMatrix);return topPoint[3]/this.cameraToCenterDistance}getCameraPoint(){const pitch=this._pitch;const yOffset=Math.tan(pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new performance$1.Point(0,yOffset))}getCameraQueryGeometry(queryGeometry){const c=this.getCameraPoint();if(queryGeometry.length===1){return[queryGeometry[0],c]}else{let minX=c.x;let minY=c.y;let maxX=c.x;let maxY=c.y;for(const p of queryGeometry){minX=Math.min(minX,p.x);minY=Math.min(minY,p.y);maxX=Math.max(maxX,p.x);maxY=Math.max(maxY,p.y)}return[new performance$1.Point(minX,minY),new performance$1.Point(maxX,minY),new performance$1.Point(maxX,maxY),new performance$1.Point(minX,maxY),new performance$1.Point(minX,minY)]}}lngLatToCameraDepth(lngLat,elevation){const coord=this.locationCoordinate(lngLat);const p=[coord.x*this.worldSize,coord.y*this.worldSize,elevation,1];performance$1.transformMat4(p,p,this.projMatrix);return p[2]/p[3]}}function throttle(fn,time){let pending=false;let timerId=null;let lastCallContext=null;let lastCallArgs;const later=()=>{timerId=null;if(pending){fn.apply(lastCallContext,lastCallArgs);timerId=setTimeout(later,time);pending=false}};return(...args)=>{pending=true;lastCallContext=this;lastCallArgs=args;if(!timerId){later()}return timerId}}class Hash{constructor(hashName){this._getCurrentHash=()=>{const hash=window.location.hash.replace("#","");if(this._hashName){let keyval;hash.split("&").map((part=>part.split("="))).forEach((part=>{if(part[0]===this._hashName){keyval=part}}));return(keyval?keyval[1]||"":"").split("/")}return hash.split("/")};this._onHashChange=()=>{const loc=this._getCurrentHash();if(loc.length>=3&&!loc.some((v=>isNaN(v)))){const bearing=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(loc[3]||0):this._map.getBearing();this._map.jumpTo({center:[+loc[2],+loc[1]],zoom:+loc[0],bearing:bearing,pitch:+(loc[4]||0)});return true}return false};this._updateHashUnthrottled=()=>{const location=window.location.href.replace(/(#.+)?$/,this.getHashString());try{window.history.replaceState(window.history.state,null,location)}catch(SecurityError){}};this._updateHash=throttle(this._updateHashUnthrottled,30*1e3/100);this._hashName=hashName&&encodeURIComponent(hashName)}addTo(map){this._map=map;addEventListener("hashchange",this._onHashChange,false);this._map.on("moveend",this._updateHash);return this}remove(){removeEventListener("hashchange",this._onHashChange,false);this._map.off("moveend",this._updateHash);clearTimeout(this._updateHash());delete this._map;return this}getHashString(mapFeedback){const center=this._map.getCenter(),zoom=Math.round(this._map.getZoom()*100)/100,precision=Math.ceil((zoom*Math.LN2+Math.log(512/360/.5))/Math.LN10),m=Math.pow(10,precision),lng=Math.round(center.lng*m)/m,lat=Math.round(center.lat*m)/m,bearing=this._map.getBearing(),pitch=this._map.getPitch();let hash="";if(mapFeedback){hash+=`/${lng}/${lat}/${zoom}`}else{hash+=`${zoom}/${lat}/${lng}`}if(bearing||pitch)hash+=`/${Math.round(bearing*10)/10}`;if(pitch)hash+=`/${Math.round(pitch)}`;if(this._hashName){const hashName=this._hashName;let found=false;const parts=window.location.hash.slice(1).split("&").map((part=>{const key=part.split("=")[0];if(key===hashName){found=true;return`${key}=${hash}`}return part})).filter((a=>a));if(!found){parts.push(`${hashName}=${hash}`)}return`#${parts.join("&")}`}return`#${hash}`}}const defaultInertiaOptions={linearity:.3,easing:performance$1.bezier(0,0,.3,1)};const defaultPanInertiaOptions=performance$1.extend({deceleration:2500,maxSpeed:1400},defaultInertiaOptions);const defaultZoomInertiaOptions=performance$1.extend({deceleration:20,maxSpeed:1400},defaultInertiaOptions);const defaultBearingInertiaOptions=performance$1.extend({deceleration:1e3,maxSpeed:360},defaultInertiaOptions);const defaultPitchInertiaOptions=performance$1.extend({deceleration:1e3,maxSpeed:90},defaultInertiaOptions);class HandlerInertia{constructor(map){this._map=map;this.clear()}clear(){this._inertiaBuffer=[]}record(settings){this._drainInertiaBuffer();this._inertiaBuffer.push({time:browser.now(),settings:settings})}_drainInertiaBuffer(){const inertia=this._inertiaBuffer,now=browser.now(),cutoff=160;while(inertia.length>0&&now-inertia[0].time>cutoff)inertia.shift()}_onMoveEnd(panInertiaOptions){this._drainInertiaBuffer();if(this._inertiaBuffer.length<2){return}const deltas={zoom:0,bearing:0,pitch:0,pan:new performance$1.Point(0,0),pinchAround:undefined,around:undefined};for(const{settings:settings}of this._inertiaBuffer){deltas.zoom+=settings.zoomDelta||0;deltas.bearing+=settings.bearingDelta||0;deltas.pitch+=settings.pitchDelta||0;if(settings.panDelta)deltas.pan._add(settings.panDelta);if(settings.around)deltas.around=settings.around;if(settings.pinchAround)deltas.pinchAround=settings.pinchAround}const lastEntry=this._inertiaBuffer[this._inertiaBuffer.length-1];const duration=lastEntry.time-this._inertiaBuffer[0].time;const easeOptions={};if(deltas.pan.mag()){const result=calculateEasing(deltas.pan.mag(),duration,performance$1.extend({},defaultPanInertiaOptions,panInertiaOptions||{}));easeOptions.offset=deltas.pan.mult(result.amount/deltas.pan.mag());easeOptions.center=this._map.transform.center;extendDuration(easeOptions,result)}if(deltas.zoom){const result=calculateEasing(deltas.zoom,duration,defaultZoomInertiaOptions);easeOptions.zoom=this._map.transform.zoom+result.amount;extendDuration(easeOptions,result)}if(deltas.bearing){const result=calculateEasing(deltas.bearing,duration,defaultBearingInertiaOptions);easeOptions.bearing=this._map.transform.bearing+performance$1.clamp(result.amount,-179,179);extendDuration(easeOptions,result)}if(deltas.pitch){const result=calculateEasing(deltas.pitch,duration,defaultPitchInertiaOptions);easeOptions.pitch=this._map.transform.pitch+result.amount;extendDuration(easeOptions,result)}if(easeOptions.zoom||easeOptions.bearing){const last=deltas.pinchAround===undefined?deltas.around:deltas.pinchAround;easeOptions.around=last?this._map.unproject(last):this._map.getCenter()}this.clear();return performance$1.extend(easeOptions,{noMoveStart:true})}}function extendDuration(easeOptions,result){if(!easeOptions.duration||easeOptions.durationmap.unproject(t)));const point=points.reduce(((prev,curr,i,arr)=>prev.add(curr.div(arr.length))),new performance$1.Point(0,0));const lngLat=map.unproject(point);super(type,{points:points,point:point,lngLats:lngLats,lngLat:lngLat,originalEvent:originalEvent});this._defaultPrevented=false}}class MapWheelEvent extends performance$1.Event{preventDefault(){this._defaultPrevented=true}get defaultPrevented(){return this._defaultPrevented}constructor(type,map,originalEvent){super(type,{originalEvent:originalEvent});this._defaultPrevented=false}}class MapEventHandler{constructor(map,options){this._map=map;this._clickTolerance=options.clickTolerance}reset(){delete this._mousedownPos}wheel(e){return this._firePreventable(new MapWheelEvent(e.type,this._map,e))}mousedown(e,point){this._mousedownPos=point;return this._firePreventable(new MapMouseEvent(e.type,this._map,e))}mouseup(e){this._map.fire(new MapMouseEvent(e.type,this._map,e))}click(e,point){if(this._mousedownPos&&this._mousedownPos.dist(point)>=this._clickTolerance)return;this._map.fire(new MapMouseEvent(e.type,this._map,e))}dblclick(e){return this._firePreventable(new MapMouseEvent(e.type,this._map,e))}mouseover(e){this._map.fire(new MapMouseEvent(e.type,this._map,e))}mouseout(e){this._map.fire(new MapMouseEvent(e.type,this._map,e))}touchstart(e){return this._firePreventable(new MapTouchEvent(e.type,this._map,e))}touchmove(e){this._map.fire(new MapTouchEvent(e.type,this._map,e))}touchend(e){this._map.fire(new MapTouchEvent(e.type,this._map,e))}touchcancel(e){this._map.fire(new MapTouchEvent(e.type,this._map,e))}_firePreventable(mapEvent){this._map.fire(mapEvent);if(mapEvent.defaultPrevented){return{}}}isEnabled(){return true}isActive(){return false}enable(){}disable(){}}class BlockableMapEventHandler{constructor(map){this._map=map}reset(){this._delayContextMenu=false;this._ignoreContextMenu=true;delete this._contextMenuEvent}mousemove(e){this._map.fire(new MapMouseEvent(e.type,this._map,e))}mousedown(){this._delayContextMenu=true;this._ignoreContextMenu=false}mouseup(){this._delayContextMenu=false;if(this._contextMenuEvent){this._map.fire(new MapMouseEvent("contextmenu",this._map,this._contextMenuEvent));delete this._contextMenuEvent}}contextmenu(e){if(this._delayContextMenu){this._contextMenuEvent=e}else if(!this._ignoreContextMenu){this._map.fire(new MapMouseEvent(e.type,this._map,e))}if(this._map.listens("contextmenu")){e.preventDefault()}}isEnabled(){return true}isActive(){return false}enable(){}disable(){}}class TransformProvider{constructor(map){this._map=map}get transform(){return this._map._requestedCameraState||this._map.transform}get center(){return{lng:this.transform.center.lng,lat:this.transform.center.lat}}get zoom(){return this.transform.zoom}get pitch(){return this.transform.pitch}get bearing(){return this.transform.bearing}unproject(point){return this.transform.pointLocation(performance$1.Point.convert(point),this._map.terrain)}}class BoxZoomHandler{constructor(map,options){this._map=map;this._tr=new TransformProvider(map);this._el=map.getCanvasContainer();this._container=map.getContainer();this._clickTolerance=options.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){if(this.isEnabled())return;this._enabled=true}disable(){if(!this.isEnabled())return;this._enabled=false}mousedown(e,point){if(!this.isEnabled())return;if(!(e.shiftKey&&e.button===0))return;DOM.disableDrag();this._startPos=this._lastPos=point;this._active=true}mousemoveWindow(e,point){if(!this._active)return;const pos=point;if(this._lastPos.equals(pos)||!this._box&&pos.dist(this._startPos)map.fitScreenCoordinates(p0,p1,this._tr.bearing,{linear:true})}}}keydown(e){if(!this._active)return;if(e.keyCode===27){this.reset();this._fireEvent("boxzoomcancel",e)}}reset(){this._active=false;this._container.classList.remove("maplibregl-crosshair");if(this._box){DOM.remove(this._box);this._box=null}DOM.enableDrag();delete this._startPos;delete this._lastPos}_fireEvent(type,e){return this._map.fire(new performance$1.Event(type,{originalEvent:e}))}}function indexTouches(touches,points){if(touches.length!==points.length)throw new Error(`The number of touches and points are not equal - touches ${touches.length}, points ${points.length}`);const obj={};for(let i=0;ithis.numTouches){this.aborted=true}if(this.aborted){return}if(this.startTime===undefined){this.startTime=e.timeStamp}if(mapTouches.length===this.numTouches){this.centroid=getCentroid(points);this.touches=indexTouches(mapTouches,points)}}touchmove(e,points,mapTouches){if(this.aborted||!this.centroid)return;const newTouches=indexTouches(mapTouches,points);for(const id in this.touches){const prevPos=this.touches[id];const pos=newTouches[id];if(!pos||pos.dist(prevPos)>MAX_DIST){this.aborted=true}}}touchend(e,points,mapTouches){if(!this.centroid||e.timeStamp-this.startTime>MAX_TOUCH_TIME){this.aborted=true}if(mapTouches.length===0){const centroid=!this.aborted&&this.centroid;this.reset();if(centroid)return centroid}}}class TapRecognizer{constructor(options){this.singleTap=new SingleTapRecognizer(options);this.numTaps=options.numTaps;this.reset()}reset(){this.lastTime=Infinity;delete this.lastTap;this.count=0;this.singleTap.reset()}touchstart(e,points,mapTouches){this.singleTap.touchstart(e,points,mapTouches)}touchmove(e,points,mapTouches){this.singleTap.touchmove(e,points,mapTouches)}touchend(e,points,mapTouches){const tap=this.singleTap.touchend(e,points,mapTouches);if(tap){const soonEnough=e.timeStamp-this.lastTimethis.reset()),0);return{cameraAnimation:map=>map.easeTo({duration:300,zoom:tr.zoom+1,around:tr.unproject(zoomInPoint)},{originalEvent:e})}}else if(zoomOutPoint){this._active=true;e.preventDefault();setTimeout((()=>this.reset()),0);return{cameraAnimation:map=>map.easeTo({duration:300,zoom:tr.zoom-1,around:tr.unproject(zoomOutPoint)},{originalEvent:e})}}}touchcancel(){this.reset()}enable(){this._enabled=true}disable(){this._enabled=false;this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class DragHandler{constructor(options){this._enabled=!!options.enable;this._moveStateManager=options.moveStateManager;this._clickTolerance=options.clickTolerance||1;this._moveFunction=options.move;this._activateOnStart=!!options.activateOnStart;options.assignEvents(this);this.reset()}reset(e){this._active=false;this._moved=false;delete this._lastPoint;this._moveStateManager.endMove(e)}_move(...params){const move=this._moveFunction(...params);if(move.bearingDelta||move.pitchDelta||move.around||move.panDelta){this._active=true;return move}}dragStart(e,point){if(!this.isEnabled()||this._lastPoint)return;if(!this._moveStateManager.isValidStartEvent(e))return;this._moveStateManager.startMove(e);this._lastPoint=point["length"]?point[0]:point;if(this._activateOnStart&&this._lastPoint)this._active=true}dragMove(e,point){if(!this.isEnabled())return;const lastPoint=this._lastPoint;if(!lastPoint)return;e.preventDefault();if(!this._moveStateManager.isValidMoveEvent(e)){this.reset(e);return}const movePoint=point["length"]?point[0]:point;if(!this._moved&&movePoint.dist(lastPoint){handler.mousedown=handler.dragStart;handler.mousemoveWindow=handler.dragMove;handler.mouseup=handler.dragEnd;handler.contextmenu=function(e){e.preventDefault()}};const generateMousePanHandler=({enable:enable,clickTolerance:clickTolerance})=>{const mouseMoveStateManager=new MouseMoveStateManager({checkCorrectEvent:e=>DOM.mouseButton(e)===LEFT_BUTTON&&!e.ctrlKey});return new DragHandler({clickTolerance:clickTolerance,move:(lastPoint,point)=>({around:point,panDelta:point.sub(lastPoint)}),activateOnStart:true,moveStateManager:mouseMoveStateManager,enable:enable,assignEvents:assignEvents$1})};const generateMouseRotationHandler=({enable:enable,clickTolerance:clickTolerance,bearingDegreesPerPixelMoved:bearingDegreesPerPixelMoved=.8})=>{const mouseMoveStateManager=new MouseMoveStateManager({checkCorrectEvent:e=>DOM.mouseButton(e)===LEFT_BUTTON&&e.ctrlKey||DOM.mouseButton(e)===RIGHT_BUTTON});return new DragHandler({clickTolerance:clickTolerance,move:(lastPoint,point)=>({bearingDelta:(point.x-lastPoint.x)*bearingDegreesPerPixelMoved}),moveStateManager:mouseMoveStateManager,enable:enable,assignEvents:assignEvents$1})};const generateMousePitchHandler=({enable:enable,clickTolerance:clickTolerance,pitchDegreesPerPixelMoved:pitchDegreesPerPixelMoved=-.5})=>{const mouseMoveStateManager=new MouseMoveStateManager({checkCorrectEvent:e=>DOM.mouseButton(e)===LEFT_BUTTON&&e.ctrlKey||DOM.mouseButton(e)===RIGHT_BUTTON});return new DragHandler({clickTolerance:clickTolerance,move:(lastPoint,point)=>({pitchDelta:(point.y-lastPoint.y)*pitchDegreesPerPixelMoved}),moveStateManager:mouseMoveStateManager,enable:enable,assignEvents:assignEvents$1})};class TouchPanHandler{constructor(options,map){this._clickTolerance=options.clickTolerance||1;this._map=map;this.reset()}reset(){this._active=false;this._touches={};this._sum=new performance$1.Point(0,0)}minTouchs(){return this._map.cooperativeGestures.isEnabled()?2:1}touchstart(e,points,mapTouches){return this._calculateTransform(e,points,mapTouches)}touchmove(e,points,mapTouches){if(!this._active||mapTouches.length0)this._active=true;const touches=indexTouches(mapTouches,points);const touchPointSum=new performance$1.Point(0,0);const touchDeltaSum=new performance$1.Point(0,0);let touchDeltaCount=0;for(const identifier in touches){const point=touches[identifier];const prevPoint=this._touches[identifier];if(prevPoint){touchPointSum._add(point);touchDeltaSum._add(point.sub(prevPoint));touchDeltaCount++;touches[identifier]=point}}this._touches=touches;if(touchDeltaCountMath.abs(vector.x)}const ALLOWED_SINGLE_TOUCH_TIME=100;class TwoFingersTouchPitchHandler extends TwoFingersTouchHandler{constructor(map){super();this._currentTouchCount=0;this._map=map}reset(){super.reset();this._valid=undefined;delete this._firstMove;delete this._lastPoints}touchstart(e,points,mapTouches){super.touchstart(e,points,mapTouches);this._currentTouchCount=mapTouches.length}_start(points){this._lastPoints=points;if(isVertical(points[0].sub(points[1]))){this._valid=false}}_move(points,center,e){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3){return}const vectorA=points[0].sub(this._lastPoints[0]);const vectorB=points[1].sub(this._lastPoints[1]);this._valid=this.gestureBeginsVertically(vectorA,vectorB,e.timeStamp);if(!this._valid)return;this._lastPoints=points;this._active=true;const yDeltaAverage=(vectorA.y+vectorB.y)/2;const degreesPerPixelMoved=-.5;return{pitchDelta:yDeltaAverage*degreesPerPixelMoved}}gestureBeginsVertically(vectorA,vectorB,timeStamp){if(this._valid!==undefined)return this._valid;const threshold=2;const movedA=vectorA.mag()>=threshold;const movedB=vectorB.mag()>=threshold;if(!movedA&&!movedB)return;if(!movedA||!movedB){if(this._firstMove===undefined){this._firstMove=timeStamp}if(timeStamp-this._firstMove0===vectorB.y>0;return isVertical(vectorA)&&isVertical(vectorB)&&isSameDirection}}const defaultOptions$5={panStep:100,bearingStep:15,pitchStep:10};class KeyboardHandler{constructor(map){this._tr=new TransformProvider(map);const stepOptions=defaultOptions$5;this._panStep=stepOptions.panStep;this._bearingStep=stepOptions.bearingStep;this._pitchStep=stepOptions.pitchStep;this._rotationDisabled=false}reset(){this._active=false}keydown(e){if(e.altKey||e.ctrlKey||e.metaKey)return;let zoomDir=0;let bearingDir=0;let pitchDir=0;let xDir=0;let yDir=0;switch(e.keyCode){case 61:case 107:case 171:case 187:zoomDir=1;break;case 189:case 109:case 173:zoomDir=-1;break;case 37:if(e.shiftKey){bearingDir=-1}else{e.preventDefault();xDir=-1}break;case 39:if(e.shiftKey){bearingDir=1}else{e.preventDefault();xDir=1}break;case 38:if(e.shiftKey){pitchDir=1}else{e.preventDefault();yDir=-1}break;case 40:if(e.shiftKey){pitchDir=-1}else{e.preventDefault();yDir=1}break;default:return}if(this._rotationDisabled){bearingDir=0;pitchDir=0}return{cameraAnimation:map=>{const tr=this._tr;map.easeTo({duration:300,easeId:"keyboardHandler",easing:easeOut,zoom:zoomDir?Math.round(tr.zoom)+zoomDir*(e.shiftKey?2:1):tr.zoom,bearing:tr.bearing+bearingDir*this._bearingStep,pitch:tr.pitch+pitchDir*this._pitchStep,offset:[-xDir*this._panStep,-yDir*this._panStep],center:tr.center},{originalEvent:e})}}}enable(){this._enabled=true}disable(){this._enabled=false;this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=true}enableRotation(){this._rotationDisabled=false}}function easeOut(t){return t*(2-t)}const wheelZoomDelta=4.000244140625;const defaultZoomRate=1/100;const wheelZoomRate=1/450;const maxScalePerFrame=2;class ScrollZoomHandler{constructor(map,triggerRenderFrame){this._onTimeout=initialEvent=>{this._type="wheel";this._delta-=this._lastValue;if(!this._active){this._start(initialEvent)}};this._map=map;this._tr=new TransformProvider(map);this._triggerRenderFrame=triggerRenderFrame;this._delta=0;this._defaultZoomRate=defaultZoomRate;this._wheelZoomRate=wheelZoomRate}setZoomRate(zoomRate){this._defaultZoomRate=zoomRate}setWheelZoomRate(wheelZoomRate){this._wheelZoomRate=wheelZoomRate}isEnabled(){return!!this._enabled}isActive(){return!!this._active||this._finishTimeout!==undefined}isZooming(){return!!this._zooming}enable(options){if(this.isEnabled())return;this._enabled=true;this._aroundCenter=!!options&&options.around==="center"}disable(){if(!this.isEnabled())return;this._enabled=false}wheel(e){if(!this.isEnabled())return;if(this._map.cooperativeGestures.isEnabled()&&!e[this._map.cooperativeGestures._bypassKey]){return}let value=e.deltaMode===WheelEvent.DOM_DELTA_LINE?e.deltaY*40:e.deltaY;const now=browser.now(),timeDelta=now-(this._lastWheelEventTime||0);this._lastWheelEventTime=now;if(value!==0&&value%wheelZoomDelta===0){this._type="wheel"}else if(value!==0&&Math.abs(value)<4){this._type="trackpad"}else if(timeDelta>400){this._type=null;this._lastValue=value;this._timeout=setTimeout(this._onTimeout,40,e)}else if(!this._type){this._type=Math.abs(timeDelta*value)<200?"trackpad":"wheel";if(this._timeout){clearTimeout(this._timeout);this._timeout=null;value+=this._lastValue}}if(e.shiftKey&&value)value=value/4;if(this._type){this._lastWheelEvent=e;this._delta-=value;if(!this._active){this._start(e)}}e.preventDefault()}_start(e){if(!this._delta)return;if(this._frameId){this._frameId=null}this._active=true;if(!this.isZooming()){this._zooming=true}if(this._finishTimeout){clearTimeout(this._finishTimeout);delete this._finishTimeout}const pos=DOM.mousePos(this._map.getCanvas(),e);const tr=this._tr;if(pos.y>tr.transform.height/2-tr.transform.getHorizon()){this._around=performance$1.LngLat.convert(this._aroundCenter?tr.center:tr.unproject(pos))}else{this._around=performance$1.LngLat.convert(tr.center)}this._aroundPoint=tr.transform.locationPoint(this._around);if(!this._frameId){this._frameId=true;this._triggerRenderFrame()}}renderFrame(){if(!this._frameId)return;this._frameId=null;if(!this.isActive())return;const tr=this._tr.transform;if(this._delta!==0){const zoomRate=this._type==="wheel"&&Math.abs(this._delta)>wheelZoomDelta?this._wheelZoomRate:this._defaultZoomRate;let scale=maxScalePerFrame/(1+Math.exp(-Math.abs(this._delta*zoomRate)));if(this._delta<0&&scale!==0){scale=1/scale}const fromScale=typeof this._targetZoom==="number"?tr.zoomScale(this._targetZoom):tr.scale;this._targetZoom=Math.min(tr.maxZoom,Math.max(tr.minZoom,tr.scaleZoom(fromScale*scale)));if(this._type==="wheel"){this._startZoom=tr.zoom;this._easing=this._smoothOutEasing(200)}this._delta=0}const targetZoom=typeof this._targetZoom==="number"?this._targetZoom:tr.zoom;const startZoom=this._startZoom;const easing=this._easing;let finished=false;let zoom;if(this._type==="wheel"&&startZoom&&easing){const t=Math.min((browser.now()-this._lastWheelEventTime)/200,1);const k=easing(t);zoom=performance$1.interpolate.number(startZoom,targetZoom,k);if(t<1){if(!this._frameId){this._frameId=true}}else{finished=true}}else{zoom=targetZoom;finished=true}this._active=true;if(finished){this._active=false;this._finishTimeout=setTimeout((()=>{this._zooming=false;this._triggerRenderFrame();delete this._targetZoom;delete this._finishTimeout}),200)}return{noInertia:true,needsRenderFrame:!finished,zoomDelta:zoom-tr.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(duration){let easing=performance$1.defaultEasing;if(this._prevEase){const currentEase=this._prevEase;const t=(browser.now()-currentEase.start)/currentEase.duration;const speed=currentEase.easing(t+.01)-currentEase.easing(t);const x=.27/Math.sqrt(speed*speed+1e-4)*.01;const y=Math.sqrt(.27*.27-x*x);easing=performance$1.bezier(x,y,.25,1)}this._prevEase={start:browser.now(),duration:duration,easing:easing};return easing}reset(){this._active=false;this._zooming=false;delete this._targetZoom;if(this._finishTimeout){clearTimeout(this._finishTimeout);delete this._finishTimeout}}}class DoubleClickZoomHandler{constructor(clickZoom,TapZoom){this._clickZoom=clickZoom;this._tapZoom=TapZoom}enable(){this._clickZoom.enable();this._tapZoom.enable()}disable(){this._clickZoom.disable();this._tapZoom.disable()}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class ClickZoomHandler{constructor(map){this._tr=new TransformProvider(map);this.reset()}reset(){this._active=false}dblclick(e,point){e.preventDefault();return{cameraAnimation:map=>{map.easeTo({duration:300,zoom:this._tr.zoom+(e.shiftKey?-1:1),around:this._tr.unproject(point)},{originalEvent:e})}}}enable(){this._enabled=true}disable(){this._enabled=false;this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class TapDragZoomHandler{constructor(){this._tap=new TapRecognizer({numTouches:1,numTaps:1});this.reset()}reset(){this._active=false;delete this._swipePoint;delete this._swipeTouch;delete this._tapTime;delete this._tapPoint;this._tap.reset()}touchstart(e,points,mapTouches){if(this._swipePoint)return;if(!this._tapTime){this._tap.touchstart(e,points,mapTouches)}else{const swipePoint=points[0];const soonEnough=e.timeStamp-this._tapTime0){this._swipePoint=swipePoint;this._swipeTouch=mapTouches[0].identifier}}}touchmove(e,points,mapTouches){if(!this._tapTime){this._tap.touchmove(e,points,mapTouches)}else if(this._swipePoint){if(mapTouches[0].identifier!==this._swipeTouch){return}const newSwipePoint=points[0];const dist=newSwipePoint.y-this._swipePoint.y;this._swipePoint=newSwipePoint;e.preventDefault();this._active=true;return{zoomDelta:dist/128}}}touchend(e,points,mapTouches){if(!this._tapTime){const point=this._tap.touchend(e,points,mapTouches);if(point){this._tapTime=e.timeStamp;this._tapPoint=point}}else if(this._swipePoint){if(mapTouches.length===0){this.reset()}}}touchcancel(){this.reset()}enable(){this._enabled=true}disable(){this._enabled=false;this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class DragPanHandler{constructor(el,mousePan,touchPan){this._el=el;this._mousePan=mousePan;this._touchPan=touchPan}enable(options){this._inertiaOptions=options||{};this._mousePan.enable();this._touchPan.enable();this._el.classList.add("maplibregl-touch-drag-pan")}disable(){this._mousePan.disable();this._touchPan.disable();this._el.classList.remove("maplibregl-touch-drag-pan")}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class DragRotateHandler{constructor(options,mouseRotate,mousePitch){this._pitchWithRotate=options.pitchWithRotate;this._mouseRotate=mouseRotate;this._mousePitch=mousePitch}enable(){this._mouseRotate.enable();if(this._pitchWithRotate)this._mousePitch.enable()}disable(){this._mouseRotate.disable();this._mousePitch.disable()}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()}}class TwoFingersTouchZoomRotateHandler{constructor(el,touchZoom,touchRotate,tapDragZoom){this._el=el;this._touchZoom=touchZoom;this._touchRotate=touchRotate;this._tapDragZoom=tapDragZoom;this._rotationDisabled=false;this._enabled=true}enable(options){this._touchZoom.enable(options);if(!this._rotationDisabled)this._touchRotate.enable(options);this._tapDragZoom.enable();this._el.classList.add("maplibregl-touch-zoom-rotate")}disable(){this._touchZoom.disable();this._touchRotate.disable();this._tapDragZoom.disable();this._el.classList.remove("maplibregl-touch-zoom-rotate")}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=true;this._touchRotate.disable()}enableRotation(){this._rotationDisabled=false;if(this._touchZoom.isEnabled())this._touchRotate.enable()}}class CooperativeGesturesHandler{constructor(map,options){this._bypassKey=navigator.userAgent.indexOf("Mac")!==-1?"metaKey":"ctrlKey";this._map=map;this._options=options;this._enabled=false}isActive(){return false}reset(){}_setupUI(){if(this._container)return;const mapCanvasContainer=this._map.getCanvasContainer();mapCanvasContainer.classList.add("maplibregl-cooperative-gestures");this._container=DOM.create("div","maplibregl-cooperative-gesture-screen",mapCanvasContainer);let desktopMessage=this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");if(this._bypassKey==="metaKey"){desktopMessage=this._map._getUIString("CooperativeGesturesHandler.MacHelpText")}const mobileMessage=this._map._getUIString("CooperativeGesturesHandler.MobileHelpText");const desktopDiv=document.createElement("div");desktopDiv.className="maplibregl-desktop-message";desktopDiv.textContent=desktopMessage;this._container.appendChild(desktopDiv);const mobileDiv=document.createElement("div");mobileDiv.className="maplibregl-mobile-message";mobileDiv.textContent=mobileMessage;this._container.appendChild(mobileDiv);this._container.setAttribute("aria-hidden","true")}_destoryUI(){if(this._container){DOM.remove(this._container);const mapCanvasContainer=this._map.getCanvasContainer();mapCanvasContainer.classList.remove("maplibregl-cooperative-gestures")}delete this._container}enable(){this._setupUI();this._enabled=true}disable(){this._enabled=false;this._destoryUI()}isEnabled(){return this._enabled}touchmove(e){this._onCooperativeGesture(e.touches.length===1)}wheel(e){if(!this._map.scrollZoom.isEnabled()){return}this._onCooperativeGesture(!e[this._bypassKey])}_onCooperativeGesture(showNotification){if(!this._enabled||!showNotification)return;this._container.classList.add("maplibregl-show");setTimeout((()=>{this._container.classList.remove("maplibregl-show")}),100)}}const isMoving=p=>p.zoom||p.drag||p.pitch||p.rotate;class RenderFrameEvent extends performance$1.Event{}function hasChange(result){return result.panDelta&&result.panDelta.mag()||result.zoomDelta||result.bearingDelta||result.pitchDelta}class HandlerManager{constructor(map,options){this.handleWindowEvent=e=>{this.handleEvent(e,`${e.type}Window`)};this.handleEvent=(e,eventName)=>{if(e.type==="blur"){this.stop(true);return}this._updatingCamera=true;const inputEvent=e.type==="renderFrame"?undefined:e;const mergedHandlerResult={needsRenderFrame:false};const eventsInProgress={};const activeHandlers={};const eventTouches=e.touches;const mapTouches=eventTouches?this._getMapTouches(eventTouches):undefined;const points=mapTouches?DOM.touchPos(this._map.getCanvas(),mapTouches):DOM.mousePos(this._map.getCanvas(),e);for(const{handlerName:handlerName,handler:handler,allowed:allowed}of this._handlers){if(!handler.isEnabled())continue;let data;if(this._blockedByActive(activeHandlers,allowed,handlerName)){handler.reset()}else{if(handler[eventName||e.type]){data=handler[eventName||e.type](e,points,mapTouches);this.mergeHandlerResult(mergedHandlerResult,eventsInProgress,data,handlerName,inputEvent);if(data&&data.needsRenderFrame){this._triggerRenderFrame()}}}if(data||handler.isActive()){activeHandlers[handlerName]=handler}}const deactivatedHandlers={};for(const name in this._previousActiveHandlers){if(!activeHandlers[name]){deactivatedHandlers[name]=inputEvent}}this._previousActiveHandlers=activeHandlers;if(Object.keys(deactivatedHandlers).length||hasChange(mergedHandlerResult)){this._changes.push([mergedHandlerResult,eventsInProgress,deactivatedHandlers]);this._triggerRenderFrame()}if(Object.keys(activeHandlers).length||hasChange(mergedHandlerResult)){this._map._stop(true)}this._updatingCamera=false;const{cameraAnimation:cameraAnimation}=mergedHandlerResult;if(cameraAnimation){this._inertia.clear();this._fireEvents({},{},true);this._changes=[];cameraAnimation(this._map)}};this._map=map;this._el=this._map.getCanvasContainer();this._handlers=[];this._handlersById={};this._changes=[];this._inertia=new HandlerInertia(map);this._bearingSnap=options.bearingSnap;this._previousActiveHandlers={};this._eventsInProgress={};this._addDefaultHandlers(options);const el=this._el;this._listeners=[[el,"touchstart",{passive:true}],[el,"touchmove",{passive:false}],[el,"touchend",undefined],[el,"touchcancel",undefined],[el,"mousedown",undefined],[el,"mousemove",undefined],[el,"mouseup",undefined],[document,"mousemove",{capture:true}],[document,"mouseup",undefined],[el,"mouseover",undefined],[el,"mouseout",undefined],[el,"dblclick",undefined],[el,"click",undefined],[el,"keydown",{capture:false}],[el,"keyup",undefined],[el,"wheel",{passive:false}],[el,"contextmenu",undefined],[window,"blur",undefined]];for(const[target,type,listenerOptions]of this._listeners){DOM.addEventListener(target,type,target===document?this.handleWindowEvent:this.handleEvent,listenerOptions)}}destroy(){for(const[target,type,listenerOptions]of this._listeners){DOM.removeEventListener(target,type,target===document?this.handleWindowEvent:this.handleEvent,listenerOptions)}}_addDefaultHandlers(options){const map=this._map;const el=map.getCanvasContainer();this._add("mapEvent",new MapEventHandler(map,options));const boxZoom=map.boxZoom=new BoxZoomHandler(map,options);this._add("boxZoom",boxZoom);if(options.interactive&&options.boxZoom){boxZoom.enable()}const cooperativeGestures=map.cooperativeGestures=new CooperativeGesturesHandler(map,options.cooperativeGestures);this._add("cooperativeGestures",cooperativeGestures);if(options.cooperativeGestures){cooperativeGestures.enable()}const tapZoom=new TapZoomHandler(map);const clickZoom=new ClickZoomHandler(map);map.doubleClickZoom=new DoubleClickZoomHandler(clickZoom,tapZoom);this._add("tapZoom",tapZoom);this._add("clickZoom",clickZoom);if(options.interactive&&options.doubleClickZoom){map.doubleClickZoom.enable()}const tapDragZoom=new TapDragZoomHandler;this._add("tapDragZoom",tapDragZoom);const touchPitch=map.touchPitch=new TwoFingersTouchPitchHandler(map);this._add("touchPitch",touchPitch);if(options.interactive&&options.touchPitch){map.touchPitch.enable(options.touchPitch)}const mouseRotate=generateMouseRotationHandler(options);const mousePitch=generateMousePitchHandler(options);map.dragRotate=new DragRotateHandler(options,mouseRotate,mousePitch);this._add("mouseRotate",mouseRotate,["mousePitch"]);this._add("mousePitch",mousePitch,["mouseRotate"]);if(options.interactive&&options.dragRotate){map.dragRotate.enable()}const mousePan=generateMousePanHandler(options);const touchPan=new TouchPanHandler(options,map);map.dragPan=new DragPanHandler(el,mousePan,touchPan);this._add("mousePan",mousePan);this._add("touchPan",touchPan,["touchZoom","touchRotate"]);if(options.interactive&&options.dragPan){map.dragPan.enable(options.dragPan)}const touchRotate=new TwoFingersTouchRotateHandler;const touchZoom=new TwoFingersTouchZoomHandler;map.touchZoomRotate=new TwoFingersTouchZoomRotateHandler(el,touchZoom,touchRotate,tapDragZoom);this._add("touchRotate",touchRotate,["touchPan","touchZoom"]);this._add("touchZoom",touchZoom,["touchPan","touchRotate"]);if(options.interactive&&options.touchZoomRotate){map.touchZoomRotate.enable(options.touchZoomRotate)}const scrollZoom=map.scrollZoom=new ScrollZoomHandler(map,(()=>this._triggerRenderFrame()));this._add("scrollZoom",scrollZoom,["mousePan"]);if(options.interactive&&options.scrollZoom){map.scrollZoom.enable(options.scrollZoom)}const keyboard=map.keyboard=new KeyboardHandler(map);this._add("keyboard",keyboard);if(options.interactive&&options.keyboard){map.keyboard.enable()}this._add("blockableMapEvent",new BlockableMapEventHandler(map))}_add(handlerName,handler,allowed){this._handlers.push({handlerName:handlerName,handler:handler,allowed:allowed});this._handlersById[handlerName]=handler}stop(allowEndAnimation){if(this._updatingCamera)return;for(const{handler:handler}of this._handlers){handler.reset()}this._inertia.clear();this._fireEvents({},{},allowEndAnimation);this._changes=[]}isActive(){for(const{handler:handler}of this._handlers){if(handler.isActive())return true}return false}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return Boolean(isMoving(this._eventsInProgress))||this.isZooming()}_blockedByActive(activeHandlers,allowed,myName){for(const name in activeHandlers){if(name===myName)continue;if(!allowed||allowed.indexOf(name)<0){return true}}return false}_getMapTouches(touches){const mapTouches=[];for(const t of touches){const target=t.target;if(this._el.contains(target)){mapTouches.push(t)}}return mapTouches}mergeHandlerResult(mergedHandlerResult,eventsInProgress,handlerResult,name,e){if(!handlerResult)return;performance$1.extend(mergedHandlerResult,handlerResult);const eventData={handlerName:name,originalEvent:handlerResult.originalEvent||e};if(handlerResult.zoomDelta!==undefined){eventsInProgress.zoom=eventData}if(handlerResult.panDelta!==undefined){eventsInProgress.drag=eventData}if(handlerResult.pitchDelta!==undefined){eventsInProgress.pitch=eventData}if(handlerResult.bearingDelta!==undefined){eventsInProgress.rotate=eventData}}_applyChanges(){const combined={};const combinedEventsInProgress={};const combinedDeactivatedHandlers={};for(const[change,eventsInProgress,deactivatedHandlers]of this._changes){if(change.panDelta)combined.panDelta=(combined.panDelta||new performance$1.Point(0,0))._add(change.panDelta);if(change.zoomDelta)combined.zoomDelta=(combined.zoomDelta||0)+change.zoomDelta;if(change.bearingDelta)combined.bearingDelta=(combined.bearingDelta||0)+change.bearingDelta;if(change.pitchDelta)combined.pitchDelta=(combined.pitchDelta||0)+change.pitchDelta;if(change.around!==undefined)combined.around=change.around;if(change.pinchAround!==undefined)combined.pinchAround=change.pinchAround;if(change.noInertia)combined.noInertia=change.noInertia;performance$1.extend(combinedEventsInProgress,eventsInProgress);performance$1.extend(combinedDeactivatedHandlers,deactivatedHandlers)}this._updateMapTransform(combined,combinedEventsInProgress,combinedDeactivatedHandlers);this._changes=[]}_updateMapTransform(combinedResult,combinedEventsInProgress,deactivatedHandlers){const map=this._map;const tr=map._getTransformForUpdate();const terrain=map.terrain;if(!hasChange(combinedResult)&&!(terrain&&this._terrainMovement)){return this._fireEvents(combinedEventsInProgress,deactivatedHandlers,true)}let{panDelta:panDelta,zoomDelta:zoomDelta,bearingDelta:bearingDelta,pitchDelta:pitchDelta,around:around,pinchAround:pinchAround}=combinedResult;if(pinchAround!==undefined){around=pinchAround}map._stop(true);around=around||map.transform.centerPoint;const loc=tr.pointLocation(panDelta?around.sub(panDelta):around);if(bearingDelta)tr.bearing+=bearingDelta;if(pitchDelta)tr.pitch+=pitchDelta;if(zoomDelta)tr.zoom+=zoomDelta;if(!terrain){tr.setLocationAtPoint(loc,around)}else{if(!this._terrainMovement&&(combinedEventsInProgress.drag||combinedEventsInProgress.zoom)){this._terrainMovement=true;this._map._elevationFreeze=true;tr.setLocationAtPoint(loc,around);this._map.once("moveend",(()=>{this._map._elevationFreeze=false;this._terrainMovement=false;tr.recalculateZoom(map.terrain)}))}else if(combinedEventsInProgress.drag&&this._terrainMovement){tr.center=tr.pointLocation(tr.centerPoint.sub(panDelta))}else{tr.setLocationAtPoint(loc,around)}}map._applyUpdatedTransform(tr);this._map._update();if(!combinedResult.noInertia)this._inertia.record(combinedResult);this._fireEvents(combinedEventsInProgress,deactivatedHandlers,true)}_fireEvents(newEventsInProgress,deactivatedHandlers,allowEndAnimation){const wasMoving=isMoving(this._eventsInProgress);const nowMoving=isMoving(newEventsInProgress);const startEvents={};for(const eventName in newEventsInProgress){const{originalEvent:originalEvent}=newEventsInProgress[eventName];if(!this._eventsInProgress[eventName]){startEvents[`${eventName}start`]=originalEvent}this._eventsInProgress[eventName]=newEventsInProgress[eventName]}if(!wasMoving&&nowMoving){this._fireEvent("movestart",nowMoving.originalEvent)}for(const name in startEvents){this._fireEvent(name,startEvents[name])}if(nowMoving){this._fireEvent("move",nowMoving.originalEvent)}for(const eventName in newEventsInProgress){const{originalEvent:originalEvent}=newEventsInProgress[eventName];this._fireEvent(eventName,originalEvent)}const endEvents={};let originalEndEvent;for(const eventName in this._eventsInProgress){const{handlerName:handlerName,originalEvent:originalEvent}=this._eventsInProgress[eventName];if(!this._handlersById[handlerName].isActive()){delete this._eventsInProgress[eventName];originalEndEvent=deactivatedHandlers[handlerName]||originalEvent;endEvents[`${eventName}end`]=originalEndEvent}}for(const name in endEvents){this._fireEvent(name,endEvents[name])}const stillMoving=isMoving(this._eventsInProgress);if(allowEndAnimation&&(wasMoving||nowMoving)&&!stillMoving){this._updatingCamera=true;const inertialEase=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions);const shouldSnapToNorth=bearing=>bearing!==0&&-this._bearingSnap{delete this._frameId;this.handleEvent(new RenderFrameEvent("renderFrame",{timeStamp:timeStamp}));this._applyChanges()}))}_triggerRenderFrame(){if(this._frameId===undefined){this._frameId=this._requestFrame()}}}class Camera extends performance$1.Evented{constructor(transform,options){super();this._renderFrameCallback=()=>{const t=Math.min((browser.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(t));if(t<1&&this._easeFrameId){this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback)}else{this.stop()}};this._moving=false;this._zooming=false;this.transform=transform;this._bearingSnap=options.bearingSnap;this.on("moveend",(()=>{delete this._requestedCameraState}))}getCenter(){return new performance$1.LngLat(this.transform.center.lng,this.transform.center.lat)}setCenter(center,eventData){return this.jumpTo({center:center},eventData)}panBy(offset,options,eventData){offset=performance$1.Point.convert(offset).mult(-1);return this.panTo(this.transform.center,performance$1.extend({offset:offset},options),eventData)}panTo(lnglat,options,eventData){return this.easeTo(performance$1.extend({center:lnglat},options),eventData)}getZoom(){return this.transform.zoom}setZoom(zoom,eventData){this.jumpTo({zoom:zoom},eventData);return this}zoomTo(zoom,options,eventData){return this.easeTo(performance$1.extend({zoom:zoom},options),eventData)}zoomIn(options,eventData){this.zoomTo(this.getZoom()+1,options,eventData);return this}zoomOut(options,eventData){this.zoomTo(this.getZoom()-1,options,eventData);return this}getBearing(){return this.transform.bearing}setBearing(bearing,eventData){this.jumpTo({bearing:bearing},eventData);return this}getPadding(){return this.transform.padding}setPadding(padding,eventData){this.jumpTo({padding:padding},eventData);return this}rotateTo(bearing,options,eventData){return this.easeTo(performance$1.extend({bearing:bearing},options),eventData)}resetNorth(options,eventData){this.rotateTo(0,performance$1.extend({duration:1e3},options),eventData);return this}resetNorthPitch(options,eventData){this.easeTo(performance$1.extend({bearing:0,pitch:0,duration:1e3},options),eventData);return this}snapToNorth(options,eventData){if(Math.abs(this.getBearing()){if(this._zooming){tr.zoom=performance$1.interpolate.number(startZoom,zoom,k)}if(this._rotating){tr.bearing=performance$1.interpolate.number(startBearing,bearing,k)}if(this._pitching){tr.pitch=performance$1.interpolate.number(startPitch,pitch,k)}if(this._padding){tr.interpolatePadding(startPadding,padding,k);pointAtOffset=tr.centerPoint.add(offsetAsPoint)}if(this.terrain&&!options.freezeElevation)this._updateElevation(k);if(around){tr.setLocationAtPoint(around,aroundPoint)}else{const scale=tr.zoomScale(tr.zoom-startZoom);const base=zoom>startZoom?Math.min(2,finalScale):Math.max(.5,finalScale);const speedup=Math.pow(base,1-k);const newCenter=tr.unproject(from.add(delta.mult(k*speedup)).mult(scale));tr.setLocationAtPoint(tr.renderWorldCopies?newCenter.wrap():newCenter,pointAtOffset)}this._applyUpdatedTransform(tr);this._fireMoveEvents(eventData)}),(interruptingEaseId=>{if(this.terrain)this._finalizeElevation();this._afterEase(eventData,interruptingEaseId)}),options);return this}_prepareEase(eventData,noMoveStart,currently={}){this._moving=true;if(!noMoveStart&&!currently.moving){this.fire(new performance$1.Event("movestart",eventData))}if(this._zooming&&!currently.zooming){this.fire(new performance$1.Event("zoomstart",eventData))}if(this._rotating&&!currently.rotating){this.fire(new performance$1.Event("rotatestart",eventData))}if(this._pitching&&!currently.pitching){this.fire(new performance$1.Event("pitchstart",eventData))}}_prepareElevation(center){this._elevationCenter=center;this._elevationStart=this.transform.elevation;this._elevationTarget=this.terrain.getElevationForLngLatZoom(center,this.transform.tileZoom);this._elevationFreeze=true}_updateElevation(k){this.transform.minElevationForCurrentTile=this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);const elevation=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(k<1&&elevation!==this._elevationTarget){const pitch1=this._elevationTarget-this._elevationStart;const pitch2=(elevation-(pitch1*k+this._elevationStart))/(1-k);this._elevationStart+=k*(pitch1-pitch2);this._elevationTarget=elevation}this.transform.elevation=performance$1.interpolate.number(this._elevationStart,this._elevationTarget,k)}_finalizeElevation(){this._elevationFreeze=false;this.transform.recalculateZoom(this.terrain)}_getTransformForUpdate(){if(!this.transformCameraUpdate)return this.transform;if(!this._requestedCameraState){this._requestedCameraState=this.transform.clone()}return this._requestedCameraState}_applyUpdatedTransform(tr){if(!this.transformCameraUpdate)return;const nextTransform=tr.clone();const{center:center,zoom:zoom,pitch:pitch,bearing:bearing,elevation:elevation}=this.transformCameraUpdate(nextTransform);if(center)nextTransform.center=center;if(zoom!==undefined)nextTransform.zoom=zoom;if(pitch!==undefined)nextTransform.pitch=pitch;if(bearing!==undefined)nextTransform.bearing=bearing;if(elevation!==undefined)nextTransform.elevation=elevation;this.transform.apply(nextTransform)}_fireMoveEvents(eventData){this.fire(new performance$1.Event("move",eventData));if(this._zooming){this.fire(new performance$1.Event("zoom",eventData))}if(this._rotating){this.fire(new performance$1.Event("rotate",eventData))}if(this._pitching){this.fire(new performance$1.Event("pitch",eventData))}}_afterEase(eventData,easeId){if(this._easeId&&easeId&&this._easeId===easeId){return}delete this._easeId;const wasZooming=this._zooming;const wasRotating=this._rotating;const wasPitching=this._pitching;this._moving=false;this._zooming=false;this._rotating=false;this._pitching=false;this._padding=false;if(wasZooming){this.fire(new performance$1.Event("zoomend",eventData))}if(wasRotating){this.fire(new performance$1.Event("rotateend",eventData))}if(wasPitching){this.fire(new performance$1.Event("pitchend",eventData))}this.fire(new performance$1.Event("moveend",eventData))}flyTo(options,eventData){if(!options.essential&&browser.prefersReducedMotion){const coercedOptions=performance$1.pick(options,["center","zoom","bearing","pitch","around"]);return this.jumpTo(coercedOptions,eventData)}this.stop();options=performance$1.extend({offset:[0,0],speed:1.2,curve:1.42,easing:performance$1.defaultEasing},options);const tr=this._getTransformForUpdate(),startZoom=this.getZoom(),startBearing=this.getBearing(),startPitch=this.getPitch(),startPadding=this.getPadding();const zoom="zoom"in options?performance$1.clamp(+options.zoom,tr.minZoom,tr.maxZoom):startZoom;const bearing="bearing"in options?this._normalizeBearing(options.bearing,startBearing):startBearing;const pitch="pitch"in options?+options.pitch:startPitch;const padding="padding"in options?options.padding:tr.padding;const scale=tr.zoomScale(zoom-startZoom);const offsetAsPoint=performance$1.Point.convert(options.offset);let pointAtOffset=tr.centerPoint.add(offsetAsPoint);const locationAtOffset=tr.pointLocation(pointAtOffset);const center=performance$1.LngLat.convert(options.center||locationAtOffset);this._normalizeCenter(center);const from=tr.project(locationAtOffset);const delta=tr.project(center).sub(from);let rho=options.curve;const w0=Math.max(tr.width,tr.height),w1=w0/scale,u1=delta.mag();if("minZoom"in options){const minZoom=performance$1.clamp(Math.min(options.minZoom,startZoom,zoom),tr.minZoom,tr.maxZoom);const wMax=w0/tr.zoomScale(minZoom-startZoom);rho=Math.sqrt(wMax/u1*2)}const rho2=rho*rho;function zoomOutFactor(descent){const b=(w1*w1-w0*w0+(descent?-1:1)*rho2*rho2*u1*u1)/(2*(descent?w1:w0)*rho2*u1);return Math.log(Math.sqrt(b*b+1)-b)}function sinh(n){return(Math.exp(n)-Math.exp(-n))/2}function cosh(n){return(Math.exp(n)+Math.exp(-n))/2}function tanh(n){return sinh(n)/cosh(n)}const r0=zoomOutFactor(false);let w=function(s){return cosh(r0)/cosh(r0+rho*s)};let u=function(s){return w0*((cosh(r0)*tanh(r0+rho*s)-sinh(r0))/rho2)/u1};let S=(zoomOutFactor(true)-r0)/rho;if(Math.abs(u1)<1e-6||!isFinite(S)){if(Math.abs(w0-w1)<1e-6)return this.easeTo(options,eventData);const k=w1options.maxDuration){options.duration=0}this._zooming=true;this._rotating=startBearing!==bearing;this._pitching=pitch!==startPitch;this._padding=!tr.isPaddingEqual(padding);this._prepareEase(eventData,false);if(this.terrain)this._prepareElevation(center);this._ease((k=>{const s=k*S;const scale=1/w(s);tr.zoom=k===1?zoom:startZoom+tr.scaleZoom(scale);if(this._rotating){tr.bearing=performance$1.interpolate.number(startBearing,bearing,k)}if(this._pitching){tr.pitch=performance$1.interpolate.number(startPitch,pitch,k)}if(this._padding){tr.interpolatePadding(startPadding,padding,k);pointAtOffset=tr.centerPoint.add(offsetAsPoint)}if(this.terrain&&!options.freezeElevation)this._updateElevation(k);const newCenter=k===1?center:tr.unproject(from.add(delta.mult(u(s))).mult(scale));tr.setLocationAtPoint(tr.renderWorldCopies?newCenter.wrap():newCenter,pointAtOffset);this._applyUpdatedTransform(tr);this._fireMoveEvents(eventData)}),(()=>{if(this.terrain)this._finalizeElevation();this._afterEase(eventData)}),options);return this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_stop(allowGestures,easeId){if(this._easeFrameId){this._cancelRenderFrame(this._easeFrameId);delete this._easeFrameId;delete this._onEaseFrame}if(this._onEaseEnd){const onEaseEnd=this._onEaseEnd;delete this._onEaseEnd;onEaseEnd.call(this,easeId)}if(!allowGestures){const handlers=this.handlers;if(handlers)handlers.stop(false)}return this}_ease(frame,finish,options){if(options.animate===false||options.duration===0){frame(1);finish()}else{this._easeStart=browser.now();this._easeOptions=options;this._onEaseFrame=frame;this._onEaseEnd=finish;this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback)}}_normalizeBearing(bearing,currentBearing){bearing=performance$1.wrap(bearing,-180,180);const diff=Math.abs(bearing-currentBearing);if(Math.abs(bearing-360-currentBearing)180?-360:delta<-180?360:0}queryTerrainElevation(lngLatLike){if(!this.terrain){return null}const elevation=this.terrain.getElevationForLngLatZoom(performance$1.LngLat.convert(lngLatLike),this.transform.tileZoom);return elevation-this.transform.elevation}}const defaultAtributionControlOptions={compact:true,customAttribution:'MapLibre'};class AttributionControl{constructor(options=defaultAtributionControlOptions){this._toggleAttribution=()=>{if(this._container.classList.contains("maplibregl-compact")){if(this._container.classList.contains("maplibregl-compact-show")){this._container.setAttribute("open","");this._container.classList.remove("maplibregl-compact-show")}else{this._container.classList.add("maplibregl-compact-show");this._container.removeAttribute("open")}}};this._updateData=e=>{if(e&&(e.sourceDataType==="metadata"||e.sourceDataType==="visibility"||e.dataType==="style"||e.type==="terrain")){this._updateAttributions()}};this._updateCompact=()=>{if(this._map.getCanvasContainer().offsetWidth<=640||this._compact){if(this._compact===false){this._container.setAttribute("open","")}else if(!this._container.classList.contains("maplibregl-compact")&&!this._container.classList.contains("maplibregl-attrib-empty")){this._container.setAttribute("open","");this._container.classList.add("maplibregl-compact","maplibregl-compact-show")}}else{this._container.setAttribute("open","");if(this._container.classList.contains("maplibregl-compact")){this._container.classList.remove("maplibregl-compact","maplibregl-compact-show")}}};this._updateCompactMinimize=()=>{if(this._container.classList.contains("maplibregl-compact")){if(this._container.classList.contains("maplibregl-compact-show")){this._container.classList.remove("maplibregl-compact-show")}}};this.options=options}getDefaultPosition(){return"bottom-right"}onAdd(map){this._map=map;this._compact=this.options.compact;this._container=DOM.create("details","maplibregl-ctrl maplibregl-ctrl-attrib");this._compactButton=DOM.create("summary","maplibregl-ctrl-attrib-button",this._container);this._compactButton.addEventListener("click",this._toggleAttribution);this._setElementTitle(this._compactButton,"ToggleAttribution");this._innerContainer=DOM.create("div","maplibregl-ctrl-attrib-inner",this._container);this._updateAttributions();this._updateCompact();this._map.on("styledata",this._updateData);this._map.on("sourcedata",this._updateData);this._map.on("terrain",this._updateData);this._map.on("resize",this._updateCompact);this._map.on("drag",this._updateCompactMinimize);return this._container}onRemove(){DOM.remove(this._container);this._map.off("styledata",this._updateData);this._map.off("sourcedata",this._updateData);this._map.off("terrain",this._updateData);this._map.off("resize",this._updateCompact);this._map.off("drag",this._updateCompactMinimize);this._map=undefined;this._compact=undefined;this._attribHTML=undefined}_setElementTitle(element,title){const str=this._map._getUIString(`AttributionControl.${title}`);element.title=str;element.setAttribute("aria-label",str)}_updateAttributions(){if(!this._map.style)return;let attributions=[];if(this.options.customAttribution){if(Array.isArray(this.options.customAttribution)){attributions=attributions.concat(this.options.customAttribution.map((attribution=>{if(typeof attribution!=="string")return"";return attribution})))}else if(typeof this.options.customAttribution==="string"){attributions.push(this.options.customAttribution)}}if(this._map.style.stylesheet){const stylesheet=this._map.style.stylesheet;this.styleOwner=stylesheet.owner;this.styleId=stylesheet.id}const sourceCaches=this._map.style.sourceCaches;for(const id in sourceCaches){const sourceCache=sourceCaches[id];if(sourceCache.used||sourceCache.usedForTerrain){const source=sourceCache.getSource();if(source.attribution&&attributions.indexOf(source.attribution)<0){attributions.push(source.attribution)}}}attributions=attributions.filter((e=>String(e).trim()));attributions.sort(((a,b)=>a.length-b.length));attributions=attributions.filter(((attrib,i)=>{for(let j=i+1;j=0){return false}}return true}));const attribHTML=attributions.join(" | ");if(attribHTML===this._attribHTML)return;this._attribHTML=attribHTML;if(attributions.length){this._innerContainer.innerHTML=attribHTML;this._container.classList.remove("maplibregl-attrib-empty")}else{this._container.classList.add("maplibregl-attrib-empty")}this._updateCompact();this._editLink=null}}class LogoControl{constructor(options={}){this._updateCompact=()=>{const containerChildren=this._container.children;if(containerChildren.length){const anchor=containerChildren[0];if(this._map.getCanvasContainer().offsetWidth<=640||this._compact){if(this._compact!==false){anchor.classList.add("maplibregl-compact")}}else{anchor.classList.remove("maplibregl-compact")}}};this.options=options}getDefaultPosition(){return"bottom-left"}onAdd(map){this._map=map;this._compact=this.options&&this.options.compact;this._container=DOM.create("div","maplibregl-ctrl");const anchor=DOM.create("a","maplibregl-ctrl-logo");anchor.target="_blank";anchor.rel="noopener nofollow";anchor.href="https://maplibre.org/";anchor.setAttribute("aria-label",this._map._getUIString("LogoControl.Title"));anchor.setAttribute("rel","noopener nofollow");this._container.appendChild(anchor);this._container.style.display="block";this._map.on("resize",this._updateCompact);this._updateCompact();return this._container}onRemove(){DOM.remove(this._container);this._map.off("resize",this._updateCompact);this._map=undefined;this._compact=undefined}}class TaskQueue{constructor(){this._queue=[];this._id=0;this._cleared=false;this._currentlyRunning=false}add(callback){const id=++this._id;const queue=this._queue;queue.push({callback:callback,id:id,cancelled:false});return id}remove(id){const running=this._currentlyRunning;const queue=running?this._queue.concat(running):this._queue;for(const task of queue){if(task.id===id){task.cancelled=true;return}}}run(timeStamp=0){if(this._currentlyRunning)throw new Error("Attempting to run(), but is already running.");const queue=this._currentlyRunning=this._queue;this._queue=[];for(const task of queue){if(task.cancelled)continue;task.callback(timeStamp);if(this._cleared)break}this._cleared=false;this._currentlyRunning=false}clear(){if(this._currentlyRunning){this._cleared=true}this._queue=[]}}var pos3dAttributes=performance$1.createLayout([{name:"a_pos3d",type:"Int16",components:3}]);class TerrainSourceCache extends performance$1.Evented{constructor(sourceCache){super();this.sourceCache=sourceCache;this._tiles={};this._renderableTilesKeys=[];this._sourceTileCache={};this.minzoom=0;this.maxzoom=22;this.tileSize=512;this.deltaZoom=1;sourceCache.usedForTerrain=true;sourceCache.tileSize=this.tileSize*2**this.deltaZoom}destruct(){this.sourceCache.usedForTerrain=false;this.sourceCache.tileSize=null}update(transform,terrain){this.sourceCache.update(transform,terrain);this._renderableTilesKeys=[];const keys={};for(const tileID of transform.coveringTiles({tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:false,terrain:terrain})){keys[tileID.key]=true;this._renderableTilesKeys.push(tileID.key);if(!this._tiles[tileID.key]){tileID.posMatrix=new Float64Array(16);performance$1.ortho(tileID.posMatrix,0,performance$1.EXTENT,0,performance$1.EXTENT,0,1);this._tiles[tileID.key]=new Tile(tileID,this.tileSize)}}for(const key in this._tiles){if(!keys[key])delete this._tiles[key]}}freeRtt(tileID){for(const key in this._tiles){const tile=this._tiles[key];if(!tileID||tile.tileID.equals(tileID)||tile.tileID.isChildOf(tileID)||tileID.isChildOf(tile.tileID))tile.rtt=[]}}getRenderableTiles(){return this._renderableTilesKeys.map((key=>this.getTileByID(key)))}getTileByID(id){return this._tiles[id]}getTerrainCoords(tileID){const coords={};for(const key of this._renderableTilesKeys){const _tileID=this._tiles[key].tileID;if(_tileID.canonical.equals(tileID.canonical)){const coord=tileID.clone();coord.posMatrix=new Float64Array(16);performance$1.ortho(coord.posMatrix,0,performance$1.EXTENT,0,performance$1.EXTENT,0,1);coords[key]=coord}else if(_tileID.canonical.isChildOf(tileID.canonical)){const coord=tileID.clone();coord.posMatrix=new Float64Array(16);const dz=_tileID.canonical.z-tileID.canonical.z;const dx=_tileID.canonical.x-(_tileID.canonical.x>>dz<>dz<>dz;performance$1.ortho(coord.posMatrix,0,size,0,size,0,1);performance$1.translate(coord.posMatrix,coord.posMatrix,[-dx*size,-dy*size,0]);coords[key]=coord}else if(tileID.canonical.isChildOf(_tileID.canonical)){const coord=tileID.clone();coord.posMatrix=new Float64Array(16);const dz=tileID.canonical.z-_tileID.canonical.z;const dx=tileID.canonical.x-(tileID.canonical.x>>dz<>dz<>dz;performance$1.ortho(coord.posMatrix,0,performance$1.EXTENT,0,performance$1.EXTENT,0,1);performance$1.translate(coord.posMatrix,coord.posMatrix,[dx*size,dy*size,0]);performance$1.scale(coord.posMatrix,coord.posMatrix,[1/2**dz,1/2**dz,0]);coords[key]=coord}}return coords}getSourceTile(tileID,searchForDEM){const source=this.sourceCache._source;let z=tileID.overscaledZ-this.deltaZoom;if(z>source.maxzoom)z=source.maxzoom;if(z=source.minzoom&&!(tile&&tile.dem))tile=this.sourceCache.getTileByID(tileID.scaledTo(z--).key);return tile}tilesAfterTime(time=Date.now()){return Object.values(this._tiles).filter((t=>t.timeAdded>=time))}}class Terrain{constructor(painter,sourceCache,options){this.painter=painter;this.sourceCache=new TerrainSourceCache(sourceCache);this.options=options;this.exaggeration=typeof options.exaggeration==="number"?options.exaggeration:1;this.qualityFactor=2;this.meshSize=128;this._demMatrixCache={};this.coordsIndex=[];this._coordsTextureSize=1024}getDEMElevation(tileID,x,y,extent=performance$1.EXTENT){var _a;if(!(x>=0&&x=0&&ytileID.canonical.z){if(tileID.canonical.z>=maxzoom)dz=tileID.canonical.z-maxzoom;else performance$1.warnOnce("cannot calculate elevation if elevation maxzoom > source.maxzoom")}const dx=tileID.canonical.x-(tileID.canonical.x>>dz<>dz<>8<<4|y>>8;data[i+3]=0}const image=new performance$1.RGBAImage({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(data.buffer));const texture=new Texture(context,image,context.gl.RGBA,{premultiply:false});texture.bind(context.gl.NEAREST,context.gl.CLAMP_TO_EDGE);this._coordsTexture=texture;return texture}pointCoordinate(p){const rgba=new Uint8Array(4);const context=this.painter.context,gl=context.gl;context.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer);gl.readPixels(p.x,this.painter.height/devicePixelRatio-p.y-1,1,1,gl.RGBA,gl.UNSIGNED_BYTE,rgba);context.bindFramebuffer.set(null);const x=rgba[0]+(rgba[2]>>4<<8);const y=rgba[1]+((rgba[2]&15)<<8);const tileID=this.coordsIndex[255-rgba[3]];const tile=tileID&&this.sourceCache.getTileByID(tileID);if(!tile)return null;const coordsSize=this._coordsTextureSize;const worldSize=(1<obj.id!==id));this._recentlyUsed.push(obj.id)}stampObject(obj){obj.stamp=++this._stamp}getOrCreateFreeObject(){for(const id of this._recentlyUsed){if(!this._objects[id].inUse)return this._objects[id]}if(this._objects.length>=this._size)throw new Error("No free RenderPool available, call freeAllObjects() required!");const obj=this._createObject(this._objects.length);this._objects.push(obj);return obj}freeObject(obj){obj.inUse=false}freeAllObjects(){for(const obj of this._objects)this.freeObject(obj)}isFull(){if(this._objects.length!o.inUse))===false}}const LAYERS={background:true,fill:true,line:true,raster:true,hillshade:true};class RenderToTexture{constructor(painter,terrain){this.painter=painter;this.terrain=terrain;this.pool=new RenderPool(painter.context,30,terrain.sourceCache.tileSize*terrain.qualityFactor)}destruct(){this.pool.destruct()}getTexture(tile){return this.pool.getObjectForId(tile.rtt[this._stacks.length-1].id).texture}prepareForRender(style,zoom){this._stacks=[];this._prevType=null;this._rttTiles=[];this._renderableTiles=this.terrain.sourceCache.getRenderableTiles();this._renderableLayerIds=style._order.filter((id=>!style._layers[id].isHidden(zoom)));this._coordsDescendingInv={};for(const id in style.sourceCaches){this._coordsDescendingInv[id]={};const tileIDs=style.sourceCaches[id].getVisibleCoordinates();for(const tileID of tileIDs){const keys=this.terrain.sourceCache.getTerrainCoords(tileID);for(const key in keys){if(!this._coordsDescendingInv[id][key])this._coordsDescendingInv[id][key]=[];this._coordsDescendingInv[id][key].push(keys[key])}}}this._coordsDescendingInvStr={};for(const id of style._order){const layer=style._layers[id],source=layer.source;if(LAYERS[layer.type]){if(!this._coordsDescendingInvStr[source]){this._coordsDescendingInvStr[source]={};for(const key in this._coordsDescendingInv[source])this._coordsDescendingInvStr[source][key]=this._coordsDescendingInv[source][key].map((c=>c.key)).sort().join()}}}for(const tile of this._renderableTiles){for(const source in this._coordsDescendingInvStr){const coords=this._coordsDescendingInvStr[source][tile.tileID.key];if(coords&&coords!==tile.rttCoords[source])tile.rtt=[]}}}renderLayer(layer){if(layer.isHidden(this.painter.transform.zoom))return false;const type=layer.type;const painter=this.painter;const isLastLayer=this._renderableLayerIds[this._renderableLayerIds.length-1]===layer.id;if(LAYERS[type]){if(!this._prevType||!LAYERS[this._prevType])this._stacks.push([]);this._prevType=type;this._stacks[this._stacks.length-1].push(layer.id);if(!isLastLayer)return true}if(LAYERS[this._prevType]||LAYERS[type]&&isLastLayer){this._prevType=type;const stack=this._stacks.length-1,layers=this._stacks[stack]||[];for(const tile of this._renderableTiles){if(this.pool.isFull()){drawTerrain(this.painter,this.terrain,this._rttTiles);this._rttTiles=[];this.pool.freeAllObjects()}this._rttTiles.push(tile);if(tile.rtt[stack]){const obj=this.pool.getObjectForId(tile.rtt[stack].id);if(obj.stamp===tile.rtt[stack].stamp){this.pool.useObject(obj);continue}}const obj=this.pool.getOrCreateFreeObject();this.pool.useObject(obj);this.pool.stampObject(obj);tile.rtt[stack]={id:obj.id,stamp:obj.stamp};painter.context.bindFramebuffer.set(obj.fbo.framebuffer);painter.context.clear({color:performance$1.Color.transparent,stencil:0});painter.currentStencilSource=undefined;for(let l=0;loptions.maxZoom){throw new Error("maxZoom must be greater than or equal to minZoom")}if(options.minPitch!=null&&options.maxPitch!=null&&options.minPitch>options.maxPitch){throw new Error("maxPitch must be greater than or equal to minPitch")}if(options.minPitch!=null&&options.minPitchmaxPitchThreshold){throw new Error(`maxPitch must be less than or equal to ${maxPitchThreshold}`)}const transform=new Transform(options.minZoom,options.maxZoom,options.minPitch,options.maxPitch,options.renderWorldCopies);super(transform,{bearingSnap:options.bearingSnap});this._contextLost=event=>{event.preventDefault();if(this._frameRequest){this._frameRequest.abort();this._frameRequest=null}this.fire(new performance$1.Event("webglcontextlost",{originalEvent:event}))};this._contextRestored=event=>{this._setupPainter();this.resize();this._update();this.fire(new performance$1.Event("webglcontextrestored",{originalEvent:event}))};this._onMapScroll=event=>{if(event.target!==this._container)return;this._container.scrollTop=0;this._container.scrollLeft=0;return false};this._onWindowOnline=()=>{this._update()};this._interactive=options.interactive;this._maxTileCacheSize=options.maxTileCacheSize;this._maxTileCacheZoomLevels=options.maxTileCacheZoomLevels;this._failIfMajorPerformanceCaveat=options.failIfMajorPerformanceCaveat;this._preserveDrawingBuffer=options.preserveDrawingBuffer;this._antialias=options.antialias;this._trackResize=options.trackResize;this._bearingSnap=options.bearingSnap;this._refreshExpiredTiles=options.refreshExpiredTiles;this._fadeDuration=options.fadeDuration;this._crossSourceCollisions=options.crossSourceCollisions;this._crossFadingFactor=1;this._collectResourceTiming=options.collectResourceTiming;this._renderTaskQueue=new TaskQueue;this._controls=[];this._mapId=performance$1.uniqueId();this._locale=performance$1.extend({},defaultLocale,options.locale);this._clickTolerance=options.clickTolerance;this._overridePixelRatio=options.pixelRatio;this._maxCanvasSize=options.maxCanvasSize;this.transformCameraUpdate=options.transformCameraUpdate;this._imageQueueHandle=ImageRequest.addThrottleControl((()=>this.isMoving()));this._requestManager=new RequestManager(options.transformRequest);if(typeof options.container==="string"){this._container=document.getElementById(options.container);if(!this._container){throw new Error(`Container '${options.container}' not found.`)}}else if(options.container instanceof HTMLElement){this._container=options.container}else{throw new Error("Invalid type: 'container' must be a String or HTMLElement.")}if(options.maxBounds){this.setMaxBounds(options.maxBounds)}this._setupContainer();this._setupPainter();this.on("move",(()=>this._update(false)));this.on("moveend",(()=>this._update(false)));this.on("zoom",(()=>this._update(true)));this.on("terrain",(()=>{this.painter.terrainFacilitator.dirty=true;this._update(true)}));this.once("idle",(()=>{this._idleTriggered=true}));if(typeof window!=="undefined"){addEventListener("online",this._onWindowOnline,false);let initialResizeEventCaptured=false;const throttledResizeCallback=throttle((entries=>{if(this._trackResize&&!this._removed){this.resize(entries)._update()}}),50);this._resizeObserver=new ResizeObserver((entries=>{if(!initialResizeEventCaptured){initialResizeEventCaptured=true;return}throttledResizeCallback(entries)}));this._resizeObserver.observe(this._container)}this.handlers=new HandlerManager(this,options);const hashName=typeof options.hash==="string"&&options.hash||undefined;this._hash=options.hash&&new Hash(hashName).addTo(this);if(!this._hash||!this._hash._onHashChange()){this.jumpTo({center:options.center,zoom:options.zoom,bearing:options.bearing,pitch:options.pitch});if(options.bounds){this.resize();this.fitBounds(options.bounds,performance$1.extend({},options.fitBoundsOptions,{duration:0}))}}this.resize();this._localIdeographFontFamily=options.localIdeographFontFamily;this._validateStyle=options.validateStyle;if(options.style)this.setStyle(options.style,{localIdeographFontFamily:options.localIdeographFontFamily});if(options.attributionControl)this.addControl(new AttributionControl(typeof options.attributionControl==="boolean"?undefined:options.attributionControl));if(options.maplibreLogo)this.addControl(new LogoControl,options.logoPosition);this.on("style.load",(()=>{if(this.transform.unmodified){this.jumpTo(this.style.stylesheet)}}));this.on("data",(event=>{this._update(event.dataType==="style");this.fire(new performance$1.Event(`${event.dataType}data`,event))}));this.on("dataloading",(event=>{this.fire(new performance$1.Event(`${event.dataType}dataloading`,event))}));this.on("dataabort",(event=>{this.fire(new performance$1.Event("sourcedataabort",event))}))}_getMapId(){return this._mapId}addControl(control,position){if(position===undefined){if(control.getDefaultPosition){position=control.getDefaultPosition()}else{position="top-right"}}if(!control||!control.onAdd){return this.fire(new performance$1.ErrorEvent(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")))}const controlElement=control.onAdd(this);this._controls.push(control);const positionContainer=this._controlPositions[position];if(position.indexOf("bottom")!==-1){positionContainer.insertBefore(controlElement,positionContainer.firstChild)}else{positionContainer.appendChild(controlElement)}return this}removeControl(control){if(!control||!control.onRemove){return this.fire(new performance$1.ErrorEvent(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")))}const ci=this._controls.indexOf(control);if(ci>-1)this._controls.splice(ci,1);control.onRemove(this);return this}hasControl(control){return this._controls.indexOf(control)>-1}calculateCameraOptionsFromTo(from,altitudeFrom,to,altitudeTo){if(altitudeTo==null&&this.terrain){altitudeTo=this.terrain.getElevationForLngLatZoom(to,this.transform.tileZoom)}return super.calculateCameraOptionsFromTo(from,altitudeFrom,to,altitudeTo)}resize(eventData){var _a;const dimensions=this._containerDimensions();const width=dimensions[0];const height=dimensions[1];const clampedPixelRatio=this._getClampedPixelRatio(width,height);this._resizeCanvas(width,height,clampedPixelRatio);this.painter.resize(width,height,clampedPixelRatio);if(this.painter.overLimit()){const gl=this.painter.context.gl;this._maxCanvasSize=[gl.drawingBufferWidth,gl.drawingBufferHeight];const clampedPixelRatio=this._getClampedPixelRatio(width,height);this._resizeCanvas(width,height,clampedPixelRatio);this.painter.resize(width,height,clampedPixelRatio)}this.transform.resize(width,height);(_a=this._requestedCameraState)===null||_a===void 0?void 0:_a.resize(width,height);const fireMoving=!this._moving;if(fireMoving){this.stop();this.fire(new performance$1.Event("movestart",eventData)).fire(new performance$1.Event("move",eventData))}this.fire(new performance$1.Event("resize",eventData));if(fireMoving)this.fire(new performance$1.Event("moveend",eventData));return this}_getClampedPixelRatio(width,height){const{0:maxCanvasWidth,1:maxCanvasHeight}=this._maxCanvasSize;const pixelRatio=this.getPixelRatio();const canvasWidth=width*pixelRatio;const canvasHeight=height*pixelRatio;const widthScaleFactor=canvasWidth>maxCanvasWidth?maxCanvasWidth/canvasWidth:1;const heightScaleFactor=canvasHeight>maxCanvasHeight?maxCanvasHeight/canvasHeight:1;return Math.min(widthScaleFactor,heightScaleFactor)*pixelRatio}getPixelRatio(){var _a;return(_a=this._overridePixelRatio)!==null&&_a!==void 0?_a:devicePixelRatio}setPixelRatio(pixelRatio){this._overridePixelRatio=pixelRatio;this.resize()}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(bounds){this.transform.setMaxBounds(LngLatBounds.convert(bounds));return this._update()}setMinZoom(minZoom){minZoom=minZoom===null||minZoom===undefined?defaultMinZoom:minZoom;if(minZoom>=defaultMinZoom&&minZoom<=this.transform.maxZoom){this.transform.minZoom=minZoom;this._update();if(this.getZoom()=this.transform.minZoom){this.transform.maxZoom=maxZoom;this._update();if(this.getZoom()>maxZoom)this.setZoom(maxZoom);return this}else throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(minPitch){minPitch=minPitch===null||minPitch===undefined?defaultMinPitch:minPitch;if(minPitch=defaultMinPitch&&minPitch<=this.transform.maxPitch){this.transform.minPitch=minPitch;this._update();if(this.getPitch()maxPitchThreshold){throw new Error(`maxPitch must be less than or equal to ${maxPitchThreshold}`)}if(maxPitch>=this.transform.minPitch){this.transform.maxPitch=maxPitch;this._update();if(this.getPitch()>maxPitch)this.setPitch(maxPitch);return this}else throw new Error("maxPitch must be greater than the current minPitch")}getMaxPitch(){return this.transform.maxPitch}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(renderWorldCopies){this.transform.renderWorldCopies=renderWorldCopies;return this._update()}project(lnglat){return this.transform.locationPoint(performance$1.LngLat.convert(lnglat),this.style&&this.terrain)}unproject(point){return this.transform.pointLocation(performance$1.Point.convert(point),this.terrain)}isMoving(){var _a;return this._moving||((_a=this.handlers)===null||_a===void 0?void 0:_a.isMoving())}isZooming(){var _a;return this._zooming||((_a=this.handlers)===null||_a===void 0?void 0:_a.isZooming())}isRotating(){var _a;return this._rotating||((_a=this.handlers)===null||_a===void 0?void 0:_a.isRotating())}_createDelegatedListener(type,layerId,listener){if(type==="mouseenter"||type==="mouseover"){let mousein=false;const mousemove=e=>{const features=this.getLayer(layerId)?this.queryRenderedFeatures(e.point,{layers:[layerId]}):[];if(!features.length){mousein=false}else if(!mousein){mousein=true;listener.call(this,new MapMouseEvent(type,this,e.originalEvent,{features:features}))}};const mouseout=()=>{mousein=false};return{layer:layerId,listener:listener,delegates:{mousemove:mousemove,mouseout:mouseout}}}else if(type==="mouseleave"||type==="mouseout"){let mousein=false;const mousemove=e=>{const features=this.getLayer(layerId)?this.queryRenderedFeatures(e.point,{layers:[layerId]}):[];if(features.length){mousein=true}else if(mousein){mousein=false;listener.call(this,new MapMouseEvent(type,this,e.originalEvent))}};const mouseout=e=>{if(mousein){mousein=false;listener.call(this,new MapMouseEvent(type,this,e.originalEvent))}};return{layer:layerId,listener:listener,delegates:{mousemove:mousemove,mouseout:mouseout}}}else{const delegate=e=>{const features=this.getLayer(layerId)?this.queryRenderedFeatures(e.point,{layers:[layerId]}):[];if(features.length){e.features=features;listener.call(this,e);delete e.features}};return{layer:layerId,listener:listener,delegates:{[type]:delegate}}}}on(type,layerIdOrListener,listener){if(listener===undefined){return super.on(type,layerIdOrListener)}const delegatedListener=this._createDelegatedListener(type,layerIdOrListener,listener);this._delegatedListeners=this._delegatedListeners||{};this._delegatedListeners[type]=this._delegatedListeners[type]||[];this._delegatedListeners[type].push(delegatedListener);for(const event in delegatedListener.delegates){this.on(event,delegatedListener.delegates[event])}return this}once(type,layerIdOrListener,listener){if(listener===undefined){return super.once(type,layerIdOrListener)}const delegatedListener=this._createDelegatedListener(type,layerIdOrListener,listener);for(const event in delegatedListener.delegates){this.once(event,delegatedListener.delegates[event])}return this}off(type,layerIdOrListener,listener){if(listener===undefined){return super.off(type,layerIdOrListener)}const removeDelegatedListener=delegatedListeners=>{const listeners=delegatedListeners[type];for(let i=0;ithis._updateStyle(style,options)));return}const previousStyle=this.style&&options.transformStyle?this.style.serialize():undefined;if(this.style){this.style.setEventedParent(null);this.style._remove(!style)}if(!style){delete this.style;return this}else{this.style=new Style(this,options||{})}this.style.setEventedParent(this,{style:this.style});if(typeof style==="string"){this.style.loadURL(style,options,previousStyle)}else{this.style.loadJSON(style,options,previousStyle)}return this}_lazyInitEmptyStyle(){if(!this.style){this.style=new Style(this,{});this.style.setEventedParent(this,{style:this.style});this.style.loadEmpty()}}_diffStyle(style,options){if(typeof style==="string"){const url=style;const request=this._requestManager.transformRequest(url,ResourceType.Style);performance$1.getJSON(request,new AbortController).then((response=>{this._updateDiff(response.data,options)})).catch((error=>{if(error){this.fire(new performance$1.ErrorEvent(error))}}))}else if(typeof style==="object"){this._updateDiff(style,options)}}_updateDiff(style,options){try{if(this.style.setState(style,options)){this._update(true)}}catch(e){performance$1.warnOnce(`Unable to perform style diff: ${e.message||e.error||e}. Rebuilding the style from scratch.`);this._updateStyle(style,options)}}getStyle(){if(this.style){return this.style.serialize()}}isStyleLoaded(){if(!this.style)return performance$1.warnOnce("There is no style added to the map.");return this.style.loaded()}addSource(id,source){this._lazyInitEmptyStyle();this.style.addSource(id,source);return this._update(true)}isSourceLoaded(id){const source=this.style&&this.style.sourceCaches[id];if(source===undefined){this.fire(new performance$1.ErrorEvent(new Error(`There is no source with ID '${id}'`)));return}return source.loaded()}setTerrain(options){this.style._checkLoaded();if(this._terrainDataCallback)this.style.off("data",this._terrainDataCallback);if(!options){if(this.terrain)this.terrain.sourceCache.destruct();this.terrain=null;if(this.painter.renderToTexture)this.painter.renderToTexture.destruct();this.painter.renderToTexture=null;this.transform.minElevationForCurrentTile=0;this.transform.elevation=0}else{const sourceCache=this.style.sourceCaches[options.source];if(!sourceCache)throw new Error(`cannot load terrain, because there exists no source with ID: ${options.source}`);if(this.terrain===null)sourceCache.reload();for(const index in this.style._layers){const thisLayer=this.style._layers[index];if(thisLayer.type==="hillshade"&&thisLayer.source===options.source){performance$1.warnOnce("You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.")}}this.terrain=new Terrain(this.painter,sourceCache,options);this.painter.renderToTexture=new RenderToTexture(this.painter,this.terrain);this.transform.minElevationForCurrentTile=this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom);this.transform.elevation=this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom);this._terrainDataCallback=e=>{if(e.dataType==="style"){this.terrain.sourceCache.freeRtt()}else if(e.dataType==="source"&&e.tile){if(e.sourceId===options.source&&!this._elevationFreeze){this.transform.minElevationForCurrentTile=this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom);this.transform.elevation=this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)}this.terrain.sourceCache.freeRtt(e.tile.tileID)}};this.style.on("data",this._terrainDataCallback)}this.fire(new performance$1.Event("terrain",{terrain:options}));return this}getTerrain(){var _a,_b;return(_b=(_a=this.terrain)===null||_a===void 0?void 0:_a.options)!==null&&_b!==void 0?_b:null}areTilesLoaded(){const sources=this.style&&this.style.sourceCaches;for(const id in sources){const source=sources[id];const tiles=source._tiles;for(const t in tiles){const tile=tiles[t];if(!(tile.state==="loaded"||tile.state==="errored"))return false}}return true}removeSource(id){this.style.removeSource(id);return this._update(true)}getSource(id){return this.style.getSource(id)}addImage(id,image,options={}){const{pixelRatio:pixelRatio=1,sdf:sdf=false,stretchX:stretchX,stretchY:stretchY,content:content}=options;this._lazyInitEmptyStyle();const version=0;if(image instanceof HTMLImageElement||performance$1.isImageBitmap(image)){const{width:width,height:height,data:data}=browser.getImageData(image);this.style.addImage(id,{data:new performance$1.RGBAImage({width:width,height:height},data),pixelRatio:pixelRatio,stretchX:stretchX,stretchY:stretchY,content:content,sdf:sdf,version:version})}else if(image.width===undefined||image.height===undefined){return this.fire(new performance$1.ErrorEvent(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, "+"or object with `width`, `height`, and `data` properties with the same format as `ImageData`")))}else{const{width:width,height:height,data:data}=image;const userImage=image;this.style.addImage(id,{data:new performance$1.RGBAImage({width:width,height:height},new Uint8Array(data)),pixelRatio:pixelRatio,stretchX:stretchX,stretchY:stretchY,content:content,sdf:sdf,version:version,userImage:userImage});if(userImage.onAdd){userImage.onAdd(this,id)}return this}}updateImage(id,image){const existingImage=this.style.getImage(id);if(!existingImage){return this.fire(new performance$1.ErrorEvent(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")))}const imageData=image instanceof HTMLImageElement||performance$1.isImageBitmap(image)?browser.getImageData(image):image;const{width:width,height:height,data:data}=imageData;if(width===undefined||height===undefined){return this.fire(new performance$1.ErrorEvent(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, "+"or object with `width`, `height`, and `data` properties with the same format as `ImageData`")))}if(width!==existingImage.data.width||height!==existingImage.data.height){return this.fire(new performance$1.ErrorEvent(new Error("The width and height of the updated image must be that same as the previous version of the image")))}const copy=!(image instanceof HTMLImageElement||performance$1.isImageBitmap(image));existingImage.data.replace(data,copy);this.style.updateImage(id,existingImage);return this}getImage(id){return this.style.getImage(id)}hasImage(id){if(!id){this.fire(new performance$1.ErrorEvent(new Error("Missing required image id")));return false}return!!this.style.getImage(id)}removeImage(id){this.style.removeImage(id)}loadImage(url){return ImageRequest.getImage(this._requestManager.transformRequest(url,ResourceType.Image),new AbortController)}listImages(){return this.style.listImages()}addLayer(layer,beforeId){this._lazyInitEmptyStyle();this.style.addLayer(layer,beforeId);return this._update(true)}moveLayer(id,beforeId){this.style.moveLayer(id,beforeId);return this._update(true)}removeLayer(id){this.style.removeLayer(id);return this._update(true)}getLayer(id){return this.style.getLayer(id)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(layerId,minzoom,maxzoom){this.style.setLayerZoomRange(layerId,minzoom,maxzoom);return this._update(true)}setFilter(layerId,filter,options={}){this.style.setFilter(layerId,filter,options);return this._update(true)}getFilter(layerId){return this.style.getFilter(layerId)}setPaintProperty(layerId,name,value,options={}){this.style.setPaintProperty(layerId,name,value,options);return this._update(true)}getPaintProperty(layerId,name){return this.style.getPaintProperty(layerId,name)}setLayoutProperty(layerId,name,value,options={}){this.style.setLayoutProperty(layerId,name,value,options);return this._update(true)}getLayoutProperty(layerId,name){return this.style.getLayoutProperty(layerId,name)}setGlyphs(glyphsUrl,options={}){this._lazyInitEmptyStyle();this.style.setGlyphs(glyphsUrl,options);return this._update(true)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(id,url,options={}){this._lazyInitEmptyStyle();this.style.addSprite(id,url,options,(err=>{if(!err){this._update(true)}}));return this}removeSprite(id){this._lazyInitEmptyStyle();this.style.removeSprite(id);return this._update(true)}getSprite(){return this.style.getSprite()}setSprite(spriteUrl,options={}){this._lazyInitEmptyStyle();this.style.setSprite(spriteUrl,options,(err=>{if(!err){this._update(true)}}));return this}setLight(light,options={}){this._lazyInitEmptyStyle();this.style.setLight(light,options);return this._update(true)}getLight(){return this.style.getLight()}setFeatureState(feature,state){this.style.setFeatureState(feature,state);return this._update()}removeFeatureState(target,key){this.style.removeFeatureState(target,key);return this._update()}getFeatureState(feature){return this.style.getFeatureState(feature)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let width=0;let height=0;if(this._container){width=this._container.clientWidth||400;height=this._container.clientHeight||300}return[width,height]}_setupContainer(){const container=this._container;container.classList.add("maplibregl-map");const canvasContainer=this._canvasContainer=DOM.create("div","maplibregl-canvas-container",container);if(this._interactive){canvasContainer.classList.add("maplibregl-interactive")}this._canvas=DOM.create("canvas","maplibregl-canvas",canvasContainer);this._canvas.addEventListener("webglcontextlost",this._contextLost,false);this._canvas.addEventListener("webglcontextrestored",this._contextRestored,false);this._canvas.setAttribute("tabindex","0");this._canvas.setAttribute("aria-label","Map");this._canvas.setAttribute("role","region");const dimensions=this._containerDimensions();const clampedPixelRatio=this._getClampedPixelRatio(dimensions[0],dimensions[1]);this._resizeCanvas(dimensions[0],dimensions[1],clampedPixelRatio);const controlContainer=this._controlContainer=DOM.create("div","maplibregl-control-container",container);const positions=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach((positionName=>{positions[positionName]=DOM.create("div",`maplibregl-ctrl-${positionName} `,controlContainer)}));this._container.addEventListener("scroll",this._onMapScroll,false)}_resizeCanvas(width,height,pixelRatio){this._canvas.width=Math.floor(pixelRatio*width);this._canvas.height=Math.floor(pixelRatio*height);this._canvas.style.width=`${width}px`;this._canvas.style.height=`${height}px`}_setupPainter(){const attributes={alpha:true,stencil:true,depth:true,failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||false};let webglcontextcreationerrorDetailObject=null;this._canvas.addEventListener("webglcontextcreationerror",(args=>{webglcontextcreationerrorDetailObject={requestedAttributes:attributes};if(args){webglcontextcreationerrorDetailObject.statusMessage=args.statusMessage;webglcontextcreationerrorDetailObject.type=args.type}}),{once:true});const gl=this._canvas.getContext("webgl2",attributes)||this._canvas.getContext("webgl",attributes);if(!gl){const msg="Failed to initialize WebGL";if(webglcontextcreationerrorDetailObject){webglcontextcreationerrorDetailObject.message=msg;throw new Error(JSON.stringify(webglcontextcreationerrorDetailObject))}else{throw new Error(msg)}}this.painter=new Painter(gl,this.transform);webpSupported.testSupport(gl)}loaded(){return!this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(updateStyle){if(!this.style||!this.style._loaded)return this;this._styleDirty=this._styleDirty||updateStyle;this._sourcesDirty=true;this.triggerRepaint();return this}_requestRenderFrame(callback){this._update();return this._renderTaskQueue.add(callback)}_cancelRenderFrame(id){this._renderTaskQueue.remove(id)}_render(paintStartTimeStamp){const fadeDuration=this._idleTriggered?this._fadeDuration:0;this.painter.context.setDirty();this.painter.setBaseState();this._renderTaskQueue.run(paintStartTimeStamp);if(this._removed)return;let crossFading=false;if(this.style&&this._styleDirty){this._styleDirty=false;const zoom=this.transform.zoom;const now=browser.now();this.style.zoomHistory.update(zoom,now);const parameters=new performance$1.EvaluationParameters(zoom,{now:now,fadeDuration:fadeDuration,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()});const factor=parameters.crossFadingFactor();if(factor!==1||factor!==this._crossFadingFactor){crossFading=true;this._crossFadingFactor=factor}this.style.update(parameters)}if(this.style&&this._sourcesDirty){this._sourcesDirty=false;this.style._updateSources(this.transform)}if(this.terrain){this.terrain.sourceCache.update(this.transform,this.terrain);this.transform.minElevationForCurrentTile=this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom);if(!this._elevationFreeze){this.transform.elevation=this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)}}else{this.transform.minElevationForCurrentTile=0;this.transform.elevation=0}this._placementDirty=this.style&&this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,fadeDuration,this._crossSourceCollisions);this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:fadeDuration,showPadding:this.showPadding});this.fire(new performance$1.Event("render"));if(this.loaded()&&!this._loaded){this._loaded=true;performance$1.PerformanceUtils.mark(performance$1.PerformanceMarkers.load);this.fire(new performance$1.Event("load"))}if(this.style&&(this.style.hasTransitions()||crossFading)){this._styleDirty=true}if(this.style&&!this._placementDirty){this.style._releaseSymbolFadeTiles()}const somethingDirty=this._sourcesDirty||this._styleDirty||this._placementDirty;if(somethingDirty||this._repaint){this.triggerRepaint()}else if(!this.isMoving()&&this.loaded()){this.fire(new performance$1.Event("idle"))}if(this._loaded&&!this._fullyLoaded&&!somethingDirty){this._fullyLoaded=true;performance$1.PerformanceUtils.mark(performance$1.PerformanceMarkers.fullLoad)}return this}redraw(){if(this.style){if(this._frameRequest){this._frameRequest.abort();this._frameRequest=null}this._render(0)}return this}remove(){var _a;if(this._hash)this._hash.remove();for(const control of this._controls)control.onRemove(this);this._controls=[];if(this._frameRequest){this._frameRequest.abort();this._frameRequest=null}this._renderTaskQueue.clear();this.painter.destroy();this.handlers.destroy();delete this.handlers;this.setStyle(null);if(typeof window!=="undefined"){removeEventListener("online",this._onWindowOnline,false)}ImageRequest.removeThrottleControl(this._imageQueueHandle);(_a=this._resizeObserver)===null||_a===void 0?void 0:_a.disconnect();const extension=this.painter.context.gl.getExtension("WEBGL_lose_context");if(extension)extension.loseContext();this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,false);this._canvas.removeEventListener("webglcontextlost",this._contextLost,false);DOM.remove(this._canvasContainer);DOM.remove(this._controlContainer);this._container.classList.remove("maplibregl-map");performance$1.PerformanceUtils.clearMetrics();this._removed=true;this.fire(new performance$1.Event("remove"))}triggerRepaint(){if(this.style&&!this._frameRequest){this._frameRequest=new AbortController;browser.frameAsync(this._frameRequest).then((paintStartTimeStamp=>{performance$1.PerformanceUtils.frame(paintStartTimeStamp);this._frameRequest=null;this._render(paintStartTimeStamp)})).catch((()=>{}))}}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(value){if(this._showTileBoundaries===value)return;this._showTileBoundaries=value;this._update()}get showPadding(){return!!this._showPadding}set showPadding(value){if(this._showPadding===value)return;this._showPadding=value;this._update()}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(value){if(this._showCollisionBoxes===value)return;this._showCollisionBoxes=value;if(value){this.style._generateCollisionBoxes()}else{this._update()}}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(value){if(this._showOverdrawInspector===value)return;this._showOverdrawInspector=value;this._update()}get repaint(){return!!this._repaint}set repaint(value){if(this._repaint!==value){this._repaint=value;this.triggerRepaint()}}get vertices(){return!!this._vertices}set vertices(value){this._vertices=value;this._update()}get version(){return version$1}getCameraTargetElevation(){return this.transform.elevation}};const assignEvents=handler=>{handler.touchstart=handler.dragStart;handler.touchmoveWindow=handler.dragMove;handler.touchend=handler.dragEnd};const generateOneFingerTouchRotationHandler=({enable:enable,clickTolerance:clickTolerance,bearingDegreesPerPixelMoved:bearingDegreesPerPixelMoved=.8})=>{const touchMoveStateManager=new OneFingerTouchMoveStateManager;return new DragHandler({clickTolerance:clickTolerance,move:(lastPoint,point)=>({bearingDelta:(point.x-lastPoint.x)*bearingDegreesPerPixelMoved}),moveStateManager:touchMoveStateManager,enable:enable,assignEvents:assignEvents})};const generateOneFingerTouchPitchHandler=({enable:enable,clickTolerance:clickTolerance,pitchDegreesPerPixelMoved:pitchDegreesPerPixelMoved=-.5})=>{const touchMoveStateManager=new OneFingerTouchMoveStateManager;return new DragHandler({clickTolerance:clickTolerance,move:(lastPoint,point)=>({pitchDelta:(point.y-lastPoint.y)*pitchDegreesPerPixelMoved}),moveStateManager:touchMoveStateManager,enable:enable,assignEvents:assignEvents})};const defaultOptions$3={showCompass:true,showZoom:true,visualizePitch:false};class NavigationControl{constructor(options){this._updateZoomButtons=()=>{const zoom=this._map.getZoom();const isMax=zoom===this._map.getMaxZoom();const isMin=zoom===this._map.getMinZoom();this._zoomInButton.disabled=isMax;this._zoomOutButton.disabled=isMin;this._zoomInButton.setAttribute("aria-disabled",isMax.toString());this._zoomOutButton.setAttribute("aria-disabled",isMin.toString())};this._rotateCompassArrow=()=>{const rotate=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(this._map.transform.pitch*(Math.PI/180)),.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${this._map.transform.angle*(180/Math.PI)}deg)`:`rotate(${this._map.transform.angle*(180/Math.PI)}deg)`;this._compassIcon.style.transform=rotate};this._setButtonTitle=(button,title)=>{const str=this._map._getUIString(`NavigationControl.${title}`);button.title=str;button.setAttribute("aria-label",str)};this.options=performance$1.extend({},defaultOptions$3,options);this._container=DOM.create("div","maplibregl-ctrl maplibregl-ctrl-group");this._container.addEventListener("contextmenu",(e=>e.preventDefault()));if(this.options.showZoom){this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(e=>this._map.zoomIn({},{originalEvent:e})));DOM.create("span","maplibregl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true");this._zoomOutButton=this._createButton("maplibregl-ctrl-zoom-out",(e=>this._map.zoomOut({},{originalEvent:e})));DOM.create("span","maplibregl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")}if(this.options.showCompass){this._compass=this._createButton("maplibregl-ctrl-compass",(e=>{if(this.options.visualizePitch){this._map.resetNorthPitch({},{originalEvent:e})}else{this._map.resetNorth({},{originalEvent:e})}}));this._compassIcon=DOM.create("span","maplibregl-ctrl-icon",this._compass);this._compassIcon.setAttribute("aria-hidden","true")}}onAdd(map){this._map=map;if(this.options.showZoom){this._setButtonTitle(this._zoomInButton,"ZoomIn");this._setButtonTitle(this._zoomOutButton,"ZoomOut");this._map.on("zoom",this._updateZoomButtons);this._updateZoomButtons()}if(this.options.showCompass){this._setButtonTitle(this._compass,"ResetBearing");if(this.options.visualizePitch){this._map.on("pitch",this._rotateCompassArrow)}this._map.on("rotate",this._rotateCompassArrow);this._rotateCompassArrow();this._handler=new MouseRotateWrapper(this._map,this._compass,this.options.visualizePitch)}return this._container}onRemove(){DOM.remove(this._container);if(this.options.showZoom){this._map.off("zoom",this._updateZoomButtons)}if(this.options.showCompass){if(this.options.visualizePitch){this._map.off("pitch",this._rotateCompassArrow)}this._map.off("rotate",this._rotateCompassArrow);this._handler.off();delete this._handler}delete this._map}_createButton(className,fn){const a=DOM.create("button",className,this._container);a.type="button";a.addEventListener("click",fn);return a}}class MouseRotateWrapper{constructor(map,element,pitch=false){this.mousedown=e=>{this.startMouse(performance$1.extend({},e,{ctrlKey:true,preventDefault:()=>e.preventDefault()}),DOM.mousePos(this.element,e));DOM.addEventListener(window,"mousemove",this.mousemove);DOM.addEventListener(window,"mouseup",this.mouseup)};this.mousemove=e=>{this.moveMouse(e,DOM.mousePos(this.element,e))};this.mouseup=e=>{this.mouseRotate.dragEnd(e);if(this.mousePitch)this.mousePitch.dragEnd(e);this.offTemp()};this.touchstart=e=>{if(e.targetTouches.length!==1){this.reset()}else{this._startPos=this._lastPos=DOM.touchPos(this.element,e.targetTouches)[0];this.startTouch(e,this._startPos);DOM.addEventListener(window,"touchmove",this.touchmove,{passive:false});DOM.addEventListener(window,"touchend",this.touchend)}};this.touchmove=e=>{if(e.targetTouches.length!==1){this.reset()}else{this._lastPos=DOM.touchPos(this.element,e.targetTouches)[0];this.moveTouch(e,this._lastPos)}};this.touchend=e=>{if(e.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos){this.mouseRotate.reset();if(this.mousePitch)this.mousePitch.reset();this.touchRotate.reset();if(this.touchPitch)this.touchPitch.reset();delete this._startPos;delete this._lastPos;this.offTemp()};this._clickTolerance=10;const mapRotateTolerance=map.dragRotate._mouseRotate.getClickTolerance();const mapPitchTolerance=map.dragRotate._mousePitch.getClickTolerance();this.element=element;this.mouseRotate=generateMouseRotationHandler({clickTolerance:mapRotateTolerance,enable:true});this.touchRotate=generateOneFingerTouchRotationHandler({clickTolerance:mapRotateTolerance,enable:true});this.map=map;if(pitch){this.mousePitch=generateMousePitchHandler({clickTolerance:mapPitchTolerance,enable:true});this.touchPitch=generateOneFingerTouchPitchHandler({clickTolerance:mapPitchTolerance,enable:true})}DOM.addEventListener(element,"mousedown",this.mousedown);DOM.addEventListener(element,"touchstart",this.touchstart,{passive:false});DOM.addEventListener(element,"touchcancel",this.reset)}startMouse(e,point){this.mouseRotate.dragStart(e,point);if(this.mousePitch)this.mousePitch.dragStart(e,point);DOM.disableDrag()}startTouch(e,point){this.touchRotate.dragStart(e,point);if(this.touchPitch)this.touchPitch.dragStart(e,point);DOM.disableDrag()}moveMouse(e,point){const map=this.map;const{bearingDelta:bearingDelta}=this.mouseRotate.dragMove(e,point)||{};if(bearingDelta)map.setBearing(map.getBearing()+bearingDelta);if(this.mousePitch){const{pitchDelta:pitchDelta}=this.mousePitch.dragMove(e,point)||{};if(pitchDelta)map.setPitch(map.getPitch()+pitchDelta)}}moveTouch(e,point){const map=this.map;const{bearingDelta:bearingDelta}=this.touchRotate.dragMove(e,point)||{};if(bearingDelta)map.setBearing(map.getBearing()+bearingDelta);if(this.touchPitch){const{pitchDelta:pitchDelta}=this.touchPitch.dragMove(e,point)||{};if(pitchDelta)map.setPitch(map.getPitch()+pitchDelta)}}off(){const element=this.element;DOM.removeEventListener(element,"mousedown",this.mousedown);DOM.removeEventListener(element,"touchstart",this.touchstart,{passive:false});DOM.removeEventListener(window,"touchmove",this.touchmove,{passive:false});DOM.removeEventListener(window,"touchend",this.touchend);DOM.removeEventListener(element,"touchcancel",this.reset);this.offTemp()}offTemp(){DOM.enableDrag();DOM.removeEventListener(window,"mousemove",this.mousemove);DOM.removeEventListener(window,"mouseup",this.mouseup);DOM.removeEventListener(window,"touchmove",this.touchmove,{passive:false});DOM.removeEventListener(window,"touchend",this.touchend)}}let supportsGeolocation;function checkGeolocationSupport(forceRecalculation=false){return performance$1.__awaiter(this,void 0,void 0,(function*(){if(supportsGeolocation!==undefined&&!forceRecalculation){return supportsGeolocation}if(window.navigator.permissions===undefined){supportsGeolocation=!!window.navigator.geolocation;return supportsGeolocation}try{const permissions=yield window.navigator.permissions.query({name:"geolocation"});supportsGeolocation=permissions.state!=="denied"}catch(_a){supportsGeolocation=!!window.navigator.geolocation}return supportsGeolocation}))}function smartWrap(lngLat,priorPos,transform){const originalLngLat=new performance$1.LngLat(lngLat.lng,lngLat.lat);lngLat=new performance$1.LngLat(lngLat.lng,lngLat.lat);if(priorPos){const left=new performance$1.LngLat(lngLat.lng-360,lngLat.lat);const right=new performance$1.LngLat(lngLat.lng+360,lngLat.lat);const delta=transform.locationPoint(lngLat).distSqr(priorPos);if(transform.locationPoint(left).distSqr(priorPos)180){const pos=transform.locationPoint(lngLat);if(pos.x>=0&&pos.y>=0&&pos.x<=transform.width&&pos.y<=transform.height){break}if(lngLat.lng>transform.center.lng){lngLat.lng-=360}else{lngLat.lng+=360}}if(lngLat.lng!==originalLngLat.lng&&transform.locationPoint(lngLat).y>transform.height/2-transform.getHorizon()){return lngLat}return originalLngLat}const anchorTranslate={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function applyAnchorClass(element,anchor,prefix){const classList=element.classList;for(const key in anchorTranslate){classList.remove(`maplibregl-${prefix}-anchor-${key}`)}classList.add(`maplibregl-${prefix}-anchor-${anchor}`)}class Marker extends performance$1.Evented{constructor(options){super();this._onKeyPress=e=>{const code=e.code;const legacyCode=e.charCode||e.keyCode;if(code==="Space"||code==="Enter"||legacyCode===32||legacyCode===13){this.togglePopup()}};this._onMapClick=e=>{const targetElement=e.originalEvent.target;const element=this._element;if(this._popup&&(targetElement===element||element.contains(targetElement))){this.togglePopup()}};this._update=e=>{if(!this._map)return;const isFullyLoaded=this._map.loaded()&&!this._map.isMoving();if((e===null||e===void 0?void 0:e.type)==="terrain"||(e===null||e===void 0?void 0:e.type)==="render"&&!isFullyLoaded){this._map.once("render",this._update)}if(this._map.transform.renderWorldCopies){this._lngLat=smartWrap(this._lngLat,this._flatPos,this._map.transform)}this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset);if(this._map.terrain){this._flatPos=this._map.transform.locationPoint(this._lngLat)._add(this._offset)}let rotation="";if(this._rotationAlignment==="viewport"||this._rotationAlignment==="auto"){rotation=`rotateZ(${this._rotation}deg)`}else if(this._rotationAlignment==="map"){rotation=`rotateZ(${this._rotation-this._map.getBearing()}deg)`}let pitch="";if(this._pitchAlignment==="viewport"||this._pitchAlignment==="auto"){pitch="rotateX(0deg)"}else if(this._pitchAlignment==="map"){pitch=`rotateX(${this._map.getPitch()}deg)`}if(!e||e.type==="moveend"){this._pos=this._pos.round()}DOM.setTransform(this._element,`${anchorTranslate[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${pitch} ${rotation}`);browser.frameAsync(new AbortController).then((()=>{this._updateOpacity(e&&e.type==="moveend")})).catch((()=>{}))};this._onMove=e=>{if(!this._isDragging){const clickTolerance=this._clickTolerance||this._map._clickTolerance;this._isDragging=e.point.dist(this._pointerdownPos)>=clickTolerance}if(!this._isDragging)return;this._pos=e.point.sub(this._positionDelta);this._lngLat=this._map.unproject(this._pos);this.setLngLat(this._lngLat);this._element.style.pointerEvents="none";if(this._state==="pending"){this._state="active";this.fire(new performance$1.Event("dragstart"))}this.fire(new performance$1.Event("drag"))};this._onUp=()=>{this._element.style.pointerEvents="auto";this._positionDelta=null;this._pointerdownPos=null;this._isDragging=false;this._map.off("mousemove",this._onMove);this._map.off("touchmove",this._onMove);if(this._state==="active"){this.fire(new performance$1.Event("dragend"))}this._state="inactive"};this._addDragHandler=e=>{if(this._element.contains(e.originalEvent.target)){e.preventDefault();this._positionDelta=e.point.sub(this._pos).add(this._offset);this._pointerdownPos=e.point;this._state="pending";this._map.on("mousemove",this._onMove);this._map.on("touchmove",this._onMove);this._map.once("mouseup",this._onUp);this._map.once("touchend",this._onUp)}};this._anchor=options&&options.anchor||"center";this._color=options&&options.color||"#3FB1CE";this._scale=options&&options.scale||1;this._draggable=options&&options.draggable||false;this._clickTolerance=options&&options.clickTolerance||0;this._isDragging=false;this._state="inactive";this._rotation=options&&options.rotation||0;this._rotationAlignment=options&&options.rotationAlignment||"auto";this._pitchAlignment=options&&options.pitchAlignment&&options.pitchAlignment!=="auto"?options.pitchAlignment:this._rotationAlignment;this.setOpacity();this.setOpacity(options===null||options===void 0?void 0:options.opacity,options===null||options===void 0?void 0:options.opacityWhenCovered);if(!options||!options.element){this._defaultMarker=true;this._element=DOM.create("div");this._element.setAttribute("aria-label","Map marker");const svg=DOM.createNS("http://www.w3.org/2000/svg","svg");const defaultHeight=41;const defaultWidth=27;svg.setAttributeNS(null,"display","block");svg.setAttributeNS(null,"height",`${defaultHeight}px`);svg.setAttributeNS(null,"width",`${defaultWidth}px`);svg.setAttributeNS(null,"viewBox",`0 0 ${defaultWidth} ${defaultHeight}`);const markerLarge=DOM.createNS("http://www.w3.org/2000/svg","g");markerLarge.setAttributeNS(null,"stroke","none");markerLarge.setAttributeNS(null,"stroke-width","1");markerLarge.setAttributeNS(null,"fill","none");markerLarge.setAttributeNS(null,"fill-rule","evenodd");const page1=DOM.createNS("http://www.w3.org/2000/svg","g");page1.setAttributeNS(null,"fill-rule","nonzero");const shadow=DOM.createNS("http://www.w3.org/2000/svg","g");shadow.setAttributeNS(null,"transform","translate(3.0, 29.0)");shadow.setAttributeNS(null,"fill","#000000");const ellipses=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];for(const data of ellipses){const ellipse=DOM.createNS("http://www.w3.org/2000/svg","ellipse");ellipse.setAttributeNS(null,"opacity","0.04");ellipse.setAttributeNS(null,"cx","10.5");ellipse.setAttributeNS(null,"cy","5.80029008");ellipse.setAttributeNS(null,"rx",data["rx"]);ellipse.setAttributeNS(null,"ry",data["ry"]);shadow.appendChild(ellipse)}const background=DOM.createNS("http://www.w3.org/2000/svg","g");background.setAttributeNS(null,"fill",this._color);const bgPath=DOM.createNS("http://www.w3.org/2000/svg","path");bgPath.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z");background.appendChild(bgPath);const border=DOM.createNS("http://www.w3.org/2000/svg","g");border.setAttributeNS(null,"opacity","0.25");border.setAttributeNS(null,"fill","#000000");const borderPath=DOM.createNS("http://www.w3.org/2000/svg","path");borderPath.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z");border.appendChild(borderPath);const maki=DOM.createNS("http://www.w3.org/2000/svg","g");maki.setAttributeNS(null,"transform","translate(6.0, 7.0)");maki.setAttributeNS(null,"fill","#FFFFFF");const circleContainer=DOM.createNS("http://www.w3.org/2000/svg","g");circleContainer.setAttributeNS(null,"transform","translate(8.0, 8.0)");const circle1=DOM.createNS("http://www.w3.org/2000/svg","circle");circle1.setAttributeNS(null,"fill","#000000");circle1.setAttributeNS(null,"opacity","0.25");circle1.setAttributeNS(null,"cx","5.5");circle1.setAttributeNS(null,"cy","5.5");circle1.setAttributeNS(null,"r","5.4999962");const circle2=DOM.createNS("http://www.w3.org/2000/svg","circle");circle2.setAttributeNS(null,"fill","#FFFFFF");circle2.setAttributeNS(null,"cx","5.5");circle2.setAttributeNS(null,"cy","5.5");circle2.setAttributeNS(null,"r","5.4999962");circleContainer.appendChild(circle1);circleContainer.appendChild(circle2);page1.appendChild(shadow);page1.appendChild(background);page1.appendChild(border);page1.appendChild(maki);page1.appendChild(circleContainer);svg.appendChild(page1);svg.setAttributeNS(null,"height",`${defaultHeight*this._scale}px`);svg.setAttributeNS(null,"width",`${defaultWidth*this._scale}px`);this._element.appendChild(svg);this._offset=performance$1.Point.convert(options&&options.offset||[0,-14])}else{this._element=options.element;this._offset=performance$1.Point.convert(options&&options.offset||[0,0])}this._element.classList.add("maplibregl-marker");this._element.addEventListener("dragstart",(e=>{e.preventDefault()}));this._element.addEventListener("mousedown",(e=>{e.preventDefault()}));applyAnchorClass(this._element,this._anchor,"marker");if(options&&options.className){for(const name of options.className.split(" ")){this._element.classList.add(name)}}this._popup=null}addTo(map){this.remove();this._map=map;map.getCanvasContainer().appendChild(this._element);map.on("move",this._update);map.on("moveend",this._update);map.on("terrain",this._update);this.setDraggable(this._draggable);this._update();this._map.on("click",this._onMapClick);return this}remove(){if(this._opacityTimeout){clearTimeout(this._opacityTimeout);delete this._opacityTimeout}if(this._map){this._map.off("click",this._onMapClick);this._map.off("move",this._update);this._map.off("moveend",this._update);this._map.off("mousedown",this._addDragHandler);this._map.off("touchstart",this._addDragHandler);this._map.off("mouseup",this._onUp);this._map.off("touchend",this._onUp);this._map.off("mousemove",this._onMove);this._map.off("touchmove",this._onMove);delete this._map}DOM.remove(this._element);if(this._popup)this._popup.remove();return this}getLngLat(){return this._lngLat}setLngLat(lnglat){this._lngLat=performance$1.LngLat.convert(lnglat);this._pos=null;if(this._popup)this._popup.setLngLat(this._lngLat);this._update();return this}getElement(){return this._element}setPopup(popup){if(this._popup){this._popup.remove();this._popup=null;this._element.removeEventListener("keypress",this._onKeyPress);if(!this._originalTabIndex){this._element.removeAttribute("tabindex")}}if(popup){if(!("offset"in popup.options)){const markerHeight=41-5.8/2;const markerRadius=13.5;const linearOffset=Math.abs(markerRadius)/Math.SQRT2;popup.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-markerHeight],"bottom-left":[linearOffset,(markerHeight-markerRadius+linearOffset)*-1],"bottom-right":[-linearOffset,(markerHeight-markerRadius+linearOffset)*-1],left:[markerRadius,(markerHeight-markerRadius)*-1],right:[-markerRadius,(markerHeight-markerRadius)*-1]}:this._offset}this._popup=popup;if(this._lngLat)this._popup.setLngLat(this._lngLat);this._originalTabIndex=this._element.getAttribute("tabindex");if(!this._originalTabIndex){this._element.setAttribute("tabindex","0")}this._element.addEventListener("keypress",this._onKeyPress)}return this}getPopup(){return this._popup}togglePopup(){const popup=this._popup;if(!popup)return this;else if(popup.isOpen())popup.remove();else popup.addTo(this._map);return this}_updateOpacity(force=false){var _a;const terrain=(_a=this._map)===null||_a===void 0?void 0:_a.terrain;if(!terrain){if(this._element.style.opacity!==this._opacity){this._element.style.opacity=this._opacity}return}if(force){this._opacityTimeout=null}else{if(this._opacityTimeout){return}this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null}),100)}const map=this._map;const terrainDistance=map.terrain.depthAtPoint(this._pos);const elevation=map.terrain.getElevationForLngLatZoom(this._lngLat,map.transform.tileZoom);const markerDistance=map.transform.lngLatToCameraDepth(this._lngLat,elevation);const forgiveness=.006;if(markerDistance-terrainDistanceforgiveness;this._element.style.opacity=centerIsInvisible?this._opacityWhenCovered:this._opacity}getOffset(){return this._offset}setOffset(offset){this._offset=performance$1.Point.convert(offset);this._update();return this}addClassName(className){this._element.classList.add(className)}removeClassName(className){this._element.classList.remove(className)}toggleClassName(className){return this._element.classList.toggle(className)}setDraggable(shouldBeDraggable){this._draggable=!!shouldBeDraggable;if(this._map){if(shouldBeDraggable){this._map.on("mousedown",this._addDragHandler);this._map.on("touchstart",this._addDragHandler)}else{this._map.off("mousedown",this._addDragHandler);this._map.off("touchstart",this._addDragHandler)}}return this}isDraggable(){return this._draggable}setRotation(rotation){this._rotation=rotation||0;this._update();return this}getRotation(){return this._rotation}setRotationAlignment(alignment){this._rotationAlignment=alignment||"auto";this._update();return this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(alignment){this._pitchAlignment=alignment&&alignment!=="auto"?alignment:this._rotationAlignment;this._update();return this}getPitchAlignment(){return this._pitchAlignment}setOpacity(opacity,opacityWhenCovered){if(opacity===undefined&&opacityWhenCovered===undefined){this._opacity="1";this._opacityWhenCovered="0.2"}if(opacity!==undefined){this._opacity=opacity}if(opacityWhenCovered!==undefined){this._opacityWhenCovered=opacityWhenCovered}if(this._map){this._updateOpacity(true)}return this}}const defaultOptions$2={positionOptions:{enableHighAccuracy:false,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:false,showAccuracyCircle:true,showUserLocation:true};let numberOfWatches=0;let noTimeout=false;class GeolocateControl extends performance$1.Evented{constructor(options){super();this._onSuccess=position=>{if(!this._map){return}if(this._isOutOfMapMaxBounds(position)){this._setErrorState();this.fire(new performance$1.Event("outofmaxbounds",position));this._updateMarker();this._finish();return}if(this.options.trackUserLocation){this._lastKnownPosition=position;switch(this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK";this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting");this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error");this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND";this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting");this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error");this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}}if(this.options.showUserLocation&&this._watchState!=="OFF"){this._updateMarker(position)}if(!this.options.trackUserLocation||this._watchState==="ACTIVE_LOCK"){this._updateCamera(position)}if(this.options.showUserLocation){this._dotElement.classList.remove("maplibregl-user-location-dot-stale")}this.fire(new performance$1.Event("geolocate",position));this._finish()};this._updateCamera=position=>{const center=new performance$1.LngLat(position.coords.longitude,position.coords.latitude);const radius=position.coords.accuracy;const bearing=this._map.getBearing();const options=performance$1.extend({bearing:bearing},this.options.fitBoundsOptions);const newBounds=LngLatBounds.fromLngLat(center,radius);this._map.fitBounds(newBounds,options,{geolocateSource:true})};this._updateMarker=position=>{if(position){const center=new performance$1.LngLat(position.coords.longitude,position.coords.latitude);this._accuracyCircleMarker.setLngLat(center).addTo(this._map);this._userLocationDotMarker.setLngLat(center).addTo(this._map);this._accuracy=position.coords.accuracy;if(this.options.showUserLocation&&this.options.showAccuracyCircle){this._updateCircleRadius()}}else{this._userLocationDotMarker.remove();this._accuracyCircleMarker.remove()}};this._onZoom=()=>{if(this.options.showUserLocation&&this.options.showAccuracyCircle){this._updateCircleRadius()}};this._onError=error=>{if(!this._map){return}if(this.options.trackUserLocation){if(error.code===1){this._watchState="OFF";this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting");this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active");this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error");this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background");this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error");this._geolocateButton.disabled=true;const title=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=title;this._geolocateButton.setAttribute("aria-label",title);if(this._geolocationWatchID!==undefined){this._clearWatch()}}else if(error.code===3&&noTimeout){return}else{this._setErrorState()}}if(this._watchState!=="OFF"&&this.options.showUserLocation){this._dotElement.classList.add("maplibregl-user-location-dot-stale")}this.fire(new performance$1.Event("error",error));this._finish()};this._finish=()=>{if(this._timeoutId){clearTimeout(this._timeoutId)}this._timeoutId=undefined};this._setupUI=supported=>{if(!this._map){return}this._container.addEventListener("contextmenu",(e=>e.preventDefault()));this._geolocateButton=DOM.create("button","maplibregl-ctrl-geolocate",this._container);DOM.create("span","maplibregl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true");this._geolocateButton.type="button";if(supported===false){performance$1.warnOnce("Geolocation support is not available so the GeolocateControl will be disabled.");const title=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=true;this._geolocateButton.title=title;this._geolocateButton.setAttribute("aria-label",title)}else{const title=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.title=title;this._geolocateButton.setAttribute("aria-label",title)}if(this.options.trackUserLocation){this._geolocateButton.setAttribute("aria-pressed","false");this._watchState="OFF"}if(this.options.showUserLocation){this._dotElement=DOM.create("div","maplibregl-user-location-dot");this._userLocationDotMarker=new Marker({element:this._dotElement});this._circleElement=DOM.create("div","maplibregl-user-location-accuracy-circle");this._accuracyCircleMarker=new Marker({element:this._circleElement,pitchAlignment:"map"});if(this.options.trackUserLocation)this._watchState="OFF";this._map.on("zoom",this._onZoom)}this._geolocateButton.addEventListener("click",(()=>this.trigger()));this._setup=true;if(this.options.trackUserLocation){this._map.on("movestart",(event=>{const fromResize=event.originalEvent&&event.originalEvent.type==="resize";if(!event.geolocateSource&&this._watchState==="ACTIVE_LOCK"&&!fromResize){this._watchState="BACKGROUND";this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active");this.fire(new performance$1.Event("trackuserlocationend"))}}))}};this.options=performance$1.extend({},defaultOptions$2,options)}onAdd(map){this._map=map;this._container=DOM.create("div","maplibregl-ctrl maplibregl-ctrl-group");checkGeolocationSupport().then((supported=>this._setupUI(supported)));return this._container}onRemove(){if(this._geolocationWatchID!==undefined){window.navigator.geolocation.clearWatch(this._geolocationWatchID);this._geolocationWatchID=undefined}if(this.options.showUserLocation&&this._userLocationDotMarker){this._userLocationDotMarker.remove()}if(this.options.showAccuracyCircle&&this._accuracyCircleMarker){this._accuracyCircleMarker.remove()}DOM.remove(this._container);this._map.off("zoom",this._onZoom);this._map=undefined;numberOfWatches=0;noTimeout=false}_isOutOfMapMaxBounds(position){const bounds=this._map.getMaxBounds();const coordinates=position.coords;return bounds&&(coordinates.longitudebounds.getEast()||coordinates.latitudebounds.getNorth())}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR";this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active");this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR";this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active");this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR";this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background");this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background-error");this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case"ACTIVE_ERROR":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}}_updateCircleRadius(){const bounds=this._map.getBounds();const southEastPoint=bounds.getSouthEast();const northEastPoint=bounds.getNorthEast();const mapHeightInMeters=southEastPoint.distanceTo(northEastPoint);const mapHeightInPixels=this._map._container.clientHeight;const circleDiameter=Math.ceil(2*(this._accuracy/(mapHeightInMeters/mapHeightInPixels)));this._circleElement.style.width=`${circleDiameter}px`;this._circleElement.style.height=`${circleDiameter}px`}trigger(){if(!this._setup){performance$1.warnOnce("Geolocate control triggered before added to a map");return false}if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE";this.fire(new performance$1.Event("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":numberOfWatches--;noTimeout=false;this._watchState="OFF";this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting");this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active");this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error");this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background");this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error");this.fire(new performance$1.Event("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK";this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background");if(this._lastKnownPosition)this._updateCamera(this._lastKnownPosition);this.fire(new performance$1.Event("trackuserlocationstart"));break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"OFF":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}if(this._watchState==="OFF"&&this._geolocationWatchID!==undefined){this._clearWatch()}else if(this._geolocationWatchID===undefined){this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");this._geolocateButton.setAttribute("aria-pressed","true");numberOfWatches++;let positionOptions;if(numberOfWatches>1){positionOptions={maximumAge:6e5,timeout:0};noTimeout=true}else{positionOptions=this.options.positionOptions;noTimeout=false}this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,positionOptions)}}else{window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions);this._timeoutId=setTimeout(this._finish,1e4)}return true}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID);this._geolocationWatchID=undefined;this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting");this._geolocateButton.setAttribute("aria-pressed","false");if(this.options.showUserLocation){this._updateMarker(null)}}}const defaultOptions$1={maxWidth:100,unit:"metric"};class ScaleControl{constructor(options){this._onMove=()=>{updateScale(this._map,this._container,this.options)};this.setUnit=unit=>{this.options.unit=unit;updateScale(this._map,this._container,this.options)};this.options=performance$1.extend({},defaultOptions$1,options)}getDefaultPosition(){return"bottom-left"}onAdd(map){this._map=map;this._container=DOM.create("div","maplibregl-ctrl maplibregl-ctrl-scale",map.getContainer());this._map.on("move",this._onMove);this._onMove();return this._container}onRemove(){DOM.remove(this._container);this._map.off("move",this._onMove);this._map=undefined}}function updateScale(map,container,options){const maxWidth=options&&options.maxWidth||100;const y=map._container.clientHeight/2;const left=map.unproject([0,y]);const right=map.unproject([maxWidth,y]);const maxMeters=left.distanceTo(right);if(options&&options.unit==="imperial"){const maxFeet=3.2808*maxMeters;if(maxFeet>5280){const maxMiles=maxFeet/5280;setScale(container,maxWidth,maxMiles,map._getUIString("ScaleControl.Miles"))}else{setScale(container,maxWidth,maxFeet,map._getUIString("ScaleControl.Feet"))}}else if(options&&options.unit==="nautical"){const maxNauticals=maxMeters/1852;setScale(container,maxWidth,maxNauticals,map._getUIString("ScaleControl.NauticalMiles"))}else if(maxMeters>=1e3){setScale(container,maxWidth,maxMeters/1e3,map._getUIString("ScaleControl.Kilometers"))}else{setScale(container,maxWidth,maxMeters,map._getUIString("ScaleControl.Meters"))}}function setScale(container,maxWidth,maxDistance,unit){const distance=getRoundNum(maxDistance);const ratio=distance/maxDistance;container.style.width=`${maxWidth*ratio}px`;container.innerHTML=`${distance} ${unit}`}function getDecimalRoundNum(d){const multiplier=Math.pow(10,Math.ceil(-Math.log(d)/Math.LN10));return Math.round(d*multiplier)/multiplier}function getRoundNum(num){const pow10=Math.pow(10,`${Math.floor(num)}`.length-1);let d=num/pow10;d=d>=10?10:d>=5?5:d>=3?3:d>=2?2:d>=1?1:getDecimalRoundNum(d);return pow10*d}class FullscreenControl extends performance$1.Evented{constructor(options={}){super();this._onFullscreenChange=()=>{const fullscreenElement=window.document.fullscreenElement||window.document.mozFullScreenElement||window.document.webkitFullscreenElement||window.document.msFullscreenElement;if(fullscreenElement===this._container!==this._fullscreen){this._handleFullscreenChange()}};this._onClickFullscreen=()=>{if(this._isFullscreen()){this._exitFullscreen()}else{this._requestFullscreen()}};this._fullscreen=false;if(options&&options.container){if(options.container instanceof HTMLElement){this._container=options.container}else{performance$1.warnOnce("Full screen control 'container' must be a DOM element.")}}if("onfullscreenchange"in document){this._fullscreenchange="fullscreenchange"}else if("onmozfullscreenchange"in document){this._fullscreenchange="mozfullscreenchange"}else if("onwebkitfullscreenchange"in document){this._fullscreenchange="webkitfullscreenchange"}else if("onmsfullscreenchange"in document){this._fullscreenchange="MSFullscreenChange"}}onAdd(map){this._map=map;if(!this._container)this._container=this._map.getContainer();this._controlContainer=DOM.create("div","maplibregl-ctrl maplibregl-ctrl-group");this._setupUI();return this._controlContainer}onRemove(){DOM.remove(this._controlContainer);this._map=null;window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange)}_setupUI(){const button=this._fullscreenButton=DOM.create("button","maplibregl-ctrl-fullscreen",this._controlContainer);DOM.create("span","maplibregl-ctrl-icon",button).setAttribute("aria-hidden","true");button.type="button";this._updateTitle();this._fullscreenButton.addEventListener("click",this._onClickFullscreen);window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange)}_updateTitle(){const title=this._getTitle();this._fullscreenButton.setAttribute("aria-label",title);this._fullscreenButton.title=title}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_handleFullscreenChange(){this._fullscreen=!this._fullscreen;this._fullscreenButton.classList.toggle("maplibregl-ctrl-shrink");this._fullscreenButton.classList.toggle("maplibregl-ctrl-fullscreen");this._updateTitle();if(this._fullscreen){this.fire(new performance$1.Event("fullscreenstart"));this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled();this._map.cooperativeGestures.disable()}else{this.fire(new performance$1.Event("fullscreenend"));if(this._prevCooperativeGesturesEnabled){this._map.cooperativeGestures.enable()}}}_exitFullscreen(){if(window.document.exitFullscreen){window.document.exitFullscreen()}else if(window.document.mozCancelFullScreen){window.document.mozCancelFullScreen()}else if(window.document.msExitFullscreen){window.document.msExitFullscreen()}else if(window.document.webkitCancelFullScreen){window.document.webkitCancelFullScreen()}else{this._togglePseudoFullScreen()}}_requestFullscreen(){if(this._container.requestFullscreen){this._container.requestFullscreen()}else if(this._container.mozRequestFullScreen){this._container.mozRequestFullScreen()}else if(this._container.msRequestFullscreen){this._container.msRequestFullscreen()}else if(this._container.webkitRequestFullscreen){this._container.webkitRequestFullscreen()}else{this._togglePseudoFullScreen()}}_togglePseudoFullScreen(){this._container.classList.toggle("maplibregl-pseudo-fullscreen");this._handleFullscreenChange();this._map.resize()}}class TerrainControl{constructor(options){this._toggleTerrain=()=>{if(this._map.getTerrain()){this._map.setTerrain(null)}else{this._map.setTerrain(this.options)}this._updateTerrainIcon()};this._updateTerrainIcon=()=>{this._terrainButton.classList.remove("maplibregl-ctrl-terrain");this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled");if(this._map.terrain){this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled");this._terrainButton.title=this._map._getUIString("TerrainControl.Disable")}else{this._terrainButton.classList.add("maplibregl-ctrl-terrain");this._terrainButton.title=this._map._getUIString("TerrainControl.Enable")}};this.options=options}onAdd(map){this._map=map;this._container=DOM.create("div","maplibregl-ctrl maplibregl-ctrl-group");this._terrainButton=DOM.create("button","maplibregl-ctrl-terrain",this._container);DOM.create("span","maplibregl-ctrl-icon",this._terrainButton).setAttribute("aria-hidden","true");this._terrainButton.type="button";this._terrainButton.addEventListener("click",this._toggleTerrain);this._updateTerrainIcon();this._map.on("terrain",this._updateTerrainIcon);return this._container}onRemove(){DOM.remove(this._container);this._map.off("terrain",this._updateTerrainIcon);this._map=undefined}}const defaultOptions={closeButton:true,closeOnClick:true,focusAfterOpen:true,className:"",maxWidth:"240px"};const focusQuerySelector=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");class Popup extends performance$1.Evented{constructor(options){super();this.remove=()=>{if(this._content){DOM.remove(this._content)}if(this._container){DOM.remove(this._container);delete this._container}if(this._map){this._map.off("move",this._update);this._map.off("move",this._onClose);this._map.off("click",this._onClose);this._map.off("remove",this.remove);this._map.off("mousemove",this._onMouseMove);this._map.off("mouseup",this._onMouseUp);this._map.off("drag",this._onDrag);this._map._canvasContainer.classList.remove("maplibregl-track-pointer");delete this._map}this.fire(new performance$1.Event("close"));return this};this._onMouseUp=event=>{this._update(event.point)};this._onMouseMove=event=>{this._update(event.point)};this._onDrag=event=>{this._update(event.point)};this._update=cursor=>{const hasPosition=this._lngLat||this._trackPointer;if(!this._map||!hasPosition||!this._content){return}if(!this._container){this._container=DOM.create("div","maplibregl-popup",this._map.getContainer());this._tip=DOM.create("div","maplibregl-popup-tip",this._container);this._container.appendChild(this._content);if(this.options.className){for(const name of this.options.className.split(" ")){this._container.classList.add(name)}}if(this._trackPointer){this._container.classList.add("maplibregl-popup-track-pointer")}}if(this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth){this._container.style.maxWidth=this.options.maxWidth}if(this._map.transform.renderWorldCopies&&!this._trackPointer){this._lngLat=smartWrap(this._lngLat,this._flatPos,this._map.transform)}if(this._trackPointer&&!cursor)return;const pos=this._flatPos=this._pos=this._trackPointer&&cursor?cursor:this._map.project(this._lngLat);if(this._map.terrain){this._flatPos=this._trackPointer&&cursor?cursor:this._map.transform.locationPoint(this._lngLat)}let anchor=this.options.anchor;const offset=normalizeOffset(this.options.offset);if(!anchor){const width=this._container.offsetWidth;const height=this._container.offsetHeight;let anchorComponents;if(pos.y+offset.bottom.ythis._map.transform.height-height){anchorComponents=["bottom"]}else{anchorComponents=[]}if(pos.xthis._map.transform.width-width/2){anchorComponents.push("right")}if(anchorComponents.length===0){anchor="bottom"}else{anchor=anchorComponents.join("-")}}const offsetedPos=pos.add(offset[anchor]).round();DOM.setTransform(this._container,`${anchorTranslate[anchor]} translate(${offsetedPos.x}px,${offsetedPos.y}px)`);applyAnchorClass(this._container,anchor,"popup")};this._onClose=()=>{this.remove()};this.options=performance$1.extend(Object.create(defaultOptions),options)}addTo(map){if(this._map)this.remove();this._map=map;if(this.options.closeOnClick){this._map.on("click",this._onClose)}if(this.options.closeOnMove){this._map.on("move",this._onClose)}this._map.on("remove",this.remove);this._update();this._focusFirstElement();if(this._trackPointer){this._map.on("mousemove",this._onMouseMove);this._map.on("mouseup",this._onMouseUp);if(this._container){this._container.classList.add("maplibregl-popup-track-pointer")}this._map._canvasContainer.classList.add("maplibregl-track-pointer")}else{this._map.on("move",this._update)}this.fire(new performance$1.Event("open"));return this}isOpen(){return!!this._map}getLngLat(){return this._lngLat}setLngLat(lnglat){this._lngLat=performance$1.LngLat.convert(lnglat);this._pos=null;this._trackPointer=false;this._update();if(this._map){this._map.on("move",this._update);this._map.off("mousemove",this._onMouseMove);if(this._container){this._container.classList.remove("maplibregl-popup-track-pointer")}this._map._canvasContainer.classList.remove("maplibregl-track-pointer")}return this}trackPointer(){this._trackPointer=true;this._pos=null;this._update();if(this._map){this._map.off("move",this._update);this._map.on("mousemove",this._onMouseMove);this._map.on("drag",this._onDrag);if(this._container){this._container.classList.add("maplibregl-popup-track-pointer")}this._map._canvasContainer.classList.add("maplibregl-track-pointer")}return this}getElement(){return this._container}setText(text){return this.setDOMContent(document.createTextNode(text))}setHTML(html){const frag=document.createDocumentFragment();const temp=document.createElement("body");let child;temp.innerHTML=html;while(true){child=temp.firstChild;if(!child)break;frag.appendChild(child)}return this.setDOMContent(frag)}getMaxWidth(){var _a;return(_a=this._container)===null||_a===void 0?void 0:_a.style.maxWidth}setMaxWidth(maxWidth){this.options.maxWidth=maxWidth;this._update();return this}setDOMContent(htmlNode){if(this._content){while(this._content.hasChildNodes()){if(this._content.firstChild){this._content.removeChild(this._content.firstChild)}}}else{this._content=DOM.create("div","maplibregl-popup-content",this._container)}this._content.appendChild(htmlNode);this._createCloseButton();this._update();this._focusFirstElement();return this}addClassName(className){if(this._container){this._container.classList.add(className)}}removeClassName(className){if(this._container){this._container.classList.remove(className)}}setOffset(offset){this.options.offset=offset;this._update();return this}toggleClassName(className){if(this._container){return this._container.classList.toggle(className)}}_createCloseButton(){if(this.options.closeButton){this._closeButton=DOM.create("button","maplibregl-popup-close-button",this._content);this._closeButton.type="button";this._closeButton.setAttribute("aria-label","Close popup");this._closeButton.innerHTML="×";this._closeButton.addEventListener("click",this._onClose)}}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const firstFocusable=this._container.querySelector(focusQuerySelector);if(firstFocusable)firstFocusable.focus()}}function normalizeOffset(offset){if(!offset){return normalizeOffset(new performance$1.Point(0,0))}else if(typeof offset==="number"){const cornerOffset=Math.round(Math.abs(offset)/Math.SQRT2);return{center:new performance$1.Point(0,0),top:new performance$1.Point(0,offset),"top-left":new performance$1.Point(cornerOffset,cornerOffset),"top-right":new performance$1.Point(-cornerOffset,cornerOffset),bottom:new performance$1.Point(0,-offset),"bottom-left":new performance$1.Point(cornerOffset,-cornerOffset),"bottom-right":new performance$1.Point(-cornerOffset,-cornerOffset),left:new performance$1.Point(offset,0),right:new performance$1.Point(-offset,0)}}else if(offset instanceof performance$1.Point||Array.isArray(offset)){const convertedOffset=performance$1.Point.convert(offset);return{center:convertedOffset,top:convertedOffset,"top-left":convertedOffset,"top-right":convertedOffset,bottom:convertedOffset,"bottom-left":convertedOffset,"bottom-right":convertedOffset,left:convertedOffset,right:convertedOffset}}else{return{center:performance$1.Point.convert(offset["center"]||[0,0]),top:performance$1.Point.convert(offset["top"]||[0,0]),"top-left":performance$1.Point.convert(offset["top-left"]||[0,0]),"top-right":performance$1.Point.convert(offset["top-right"]||[0,0]),bottom:performance$1.Point.convert(offset["bottom"]||[0,0]),"bottom-left":performance$1.Point.convert(offset["bottom-left"]||[0,0]),"bottom-right":performance$1.Point.convert(offset["bottom-right"]||[0,0]),left:performance$1.Point.convert(offset["left"]||[0,0]),right:performance$1.Point.convert(offset["right"]||[0,0])}}}const version=packageJSON.version;function setRTLTextPlugin(pluginURL,lazy){return rtlMainThreadPluginFactory().setRTLTextPlugin(pluginURL,lazy)}function getRTLTextPluginStatus(){return rtlMainThreadPluginFactory().getRTLTextPluginStatus()}function getVersion(){return version}function getWorkerCount(){return WorkerPool.workerCount}function setWorkerCount(count){WorkerPool.workerCount=count}function getMaxParallelImageRequests(){return performance$1.config.MAX_PARALLEL_IMAGE_REQUESTS}function setMaxParallelImageRequests(numRequests){performance$1.config.MAX_PARALLEL_IMAGE_REQUESTS=numRequests}function getWorkerUrl(){return performance$1.config.WORKER_URL}function setWorkerUrl(value){performance$1.config.WORKER_URL=value}function importScriptInWorkers(workerUrl){return getGlobalDispatcher().broadcast("importScript",workerUrl)}exports.AJAXError=performance$1.AJAXError;exports.Evented=performance$1.Evented;exports.LngLat=performance$1.LngLat;exports.MercatorCoordinate=performance$1.MercatorCoordinate;exports.Point=performance$1.Point;exports.addProtocol=performance$1.addProtocol;exports.config=performance$1.config;exports.removeProtocol=performance$1.removeProtocol;exports.AttributionControl=AttributionControl;exports.BoxZoomHandler=BoxZoomHandler;exports.CanvasSource=CanvasSource;exports.CooperativeGesturesHandler=CooperativeGesturesHandler;exports.DoubleClickZoomHandler=DoubleClickZoomHandler;exports.DragPanHandler=DragPanHandler;exports.DragRotateHandler=DragRotateHandler;exports.EdgeInsets=EdgeInsets;exports.FullscreenControl=FullscreenControl;exports.GeoJSONSource=GeoJSONSource;exports.GeolocateControl=GeolocateControl;exports.Hash=Hash;exports.ImageSource=ImageSource;exports.KeyboardHandler=KeyboardHandler;exports.LngLatBounds=LngLatBounds;exports.LogoControl=LogoControl;exports.Map=Map$1;exports.MapMouseEvent=MapMouseEvent;exports.MapTouchEvent=MapTouchEvent;exports.MapWheelEvent=MapWheelEvent;exports.Marker=Marker;exports.NavigationControl=NavigationControl;exports.Popup=Popup;exports.RasterDEMTileSource=RasterDEMTileSource;exports.RasterTileSource=RasterTileSource;exports.ScaleControl=ScaleControl;exports.ScrollZoomHandler=ScrollZoomHandler;exports.Style=Style;exports.TerrainControl=TerrainControl;exports.TwoFingersTouchPitchHandler=TwoFingersTouchPitchHandler;exports.TwoFingersTouchRotateHandler=TwoFingersTouchRotateHandler;exports.TwoFingersTouchZoomHandler=TwoFingersTouchZoomHandler;exports.TwoFingersTouchZoomRotateHandler=TwoFingersTouchZoomRotateHandler;exports.VectorTileSource=VectorTileSource;exports.VideoSource=VideoSource;exports.addSourceType=addSourceType;exports.clearPrewarmedResources=clearPrewarmedResources;exports.getMaxParallelImageRequests=getMaxParallelImageRequests;exports.getRTLTextPluginStatus=getRTLTextPluginStatus;exports.getVersion=getVersion;exports.getWorkerCount=getWorkerCount;exports.getWorkerUrl=getWorkerUrl;exports.importScriptInWorkers=importScriptInWorkers;exports.prewarm=prewarm;exports.setMaxParallelImageRequests=setMaxParallelImageRequests;exports.setRTLTextPlugin=setRTLTextPlugin;exports.setWorkerCount=setWorkerCount;exports.setWorkerUrl=setWorkerUrl}));var maplibregl$1=maplibregl;return maplibregl$1}));"use strict";var hortis=fluid.registerNamespace("hortis");hortis.taxonDisplayLookup={iNaturalistTaxonName:"Taxon Name:",observationCount:"Observation Count:",iNaturalistObsLink:"Observation:",taxonLink:"iNaturalist Taxon:",commonName:"",reportingStatus:"Status:",hulqName:"Hul'qumi'num name:",wikipediaSummary:"Wikipedia Summary",media:"Media",observationData:"Observation Data",iNaturalistTaxonImage:"iNaturalist Taxon Image:",phyloPic:"Taxon Icon:",taxonPic:"Taxon Picture:",taxonPicDescription:"Taxon Picture Description:"};hortis.friendlyDisplayLookup={...hortis.taxonDisplayLookup,iNaturalistTaxonName:"Species:"};hortis.commonFields=["commonName","wikipediaSummary"];hortis.dumpRow=function(key,value,markup,extraClazz,valueClazz,options){if(value){const toLook=options?.friendlyNames?hortis.friendlyDisplayLookup:hortis.taxonDisplayLookup;const keyName=key?toLook[key]||hortis.capitalize(key):"";valueClazz=valueClazz||"";const openPanel=options?.openTaxonPanels[key];const isRemainder=extraClazz&&extraClazz.includes("taxonDisplay-expandable-remainder");const clazz="taxonDisplay-row "+(extraClazz||"")+(openPanel?" taxonDisplay-expanded":" taxonDisplay-unexpanded");return fluid.stringTemplate(markup.taxonDisplayRow,{key:isRemainder?"":keyName,value:value,rootAttrs:'class="'+clazz+'"',valueClazz:valueClazz})}else{return""}};hortis.renderDate=function(date){return new Date(date).toISOString().substring(0,10)};hortis.expandButtonMarkup='';hortis.expandableBlock='
    %blockName'+hortis.expandButtonMarkup+"
    "+'
    %block
    ';hortis.sourceTable={iNat:"iNaturalist",PMLS:"Pacific Marine Life Surveys",RBCM:"Royal British Columbia Museum",CMN:"Canadian Museum of Nature",BCCSN:"British Columbia Cetacean Sightings Network","Gal-Salm":"Erickson",CHU2010:"Chu and Leys (2010)",CHU2012:"Chu and Leys (2012)",Hunterston:"Hunterston Farms BioBlitz 2010"};hortis.sourceFromId=function(obsId){const colpos=obsId?obsId.indexOf(":"):-1;return colpos===-1?null:obsId.substring(0,colpos)};hortis.datasetIdFromObs=function(obsId){const colpos=obsId.indexOf(":");return obsId.substring(0,colpos)};hortis.localIdFromObs=function(obsId){const colpos=obsId.indexOf(":");return obsId.substring(colpos+1)};hortis.renderObsId=function(obsId){const dataset=hortis.datasetIdFromObs(obsId);if(dataset==="iNat"){const localId=hortis.localIdFromObs(obsId);return fluid.stringTemplate(' (%obsId)',{obsId:localId})}else{return obsId}};hortis.renderObsBound=function(row,prefix,markup,options){const date=row[prefix+"Timestamp"];if(date){const capPrefix=prefix==="since"?"":hortis.capitalize(prefix);const recordedBy=row[prefix+"RecordedBy"];const catalogueNumber=row[prefix+"CatalogueNumber"];const value=hortis.renderDate(row[prefix+"Timestamp"])+(recordedBy&&!options.suppressObsAuthors?" by "+recordedBy:"");const row1=hortis.dumpRow(capPrefix+(prefix==="since"?"First Observed:":" Reported:"),value,markup);const obsId=row[prefix+"ObservationId"];const collection=row[prefix+"Collection"];const institutionCode=row[prefix+"InstitutionCode"];const obsIdCollection=hortis.sourceFromId(row[prefix+"ObservationId"]);const renderedCollection=institutionCode||hortis.sourceTable[obsIdCollection||collection]||collection;let source=renderedCollection+(catalogueNumber&&institutionCode!=="iNaturalist"?" ("+catalogueNumber+")":"");if(obsId&&obsIdCollection==="iNat"){source+=hortis.renderObsId(obsId)}if(catalogueNumber&&institutionCode==="iNaturalist"){source+=hortis.renderObsId("iNat:"+catalogueNumber)}const row2=hortis.dumpRow("Source:",source,markup);return row1+row2}else{return""}};hortis.mediaBlock='
    %mediaName
    '+'
    '+'
    %mediaText
    ';hortis.renderOneMedium=function(medium){return fluid.stringTemplate(hortis.mediaBlock,{mediaName:medium.Name,mediaTarget:medium.URL,mediaImage:medium.Thumbnail,mediaText:medium.Description})};hortis.renderExpandable=function(terms,expanded){const allTerms={...terms,state:expanded?"taxonDisplay-expanded":"taxonDisplay-unexpanded"};return fluid.stringTemplate(hortis.expandableBlock,allTerms)};hortis.renderMedia=function(media){const mediaBlocks=media.map((oneMedium=>hortis.renderOneMedium(oneMedium)));return mediaBlocks.join("\n")};hortis.hulqValues=["Food","Medicinal","Spiritual","Material","Trade","Indicator"];hortis.hulqValueItem=`\n
    \n \n
    %label
    \n
    `;hortis.hulqValueBlock=`
    %valueBlocks
    `;hortis.drivePlayerTemplate=``;hortis.audioPlayerTemplate=``;hortis.driveToPreview=function(url){const lastSlash=url.lastIndexOf("/");return url.substring(0,lastSlash)+"/preview"};hortis.renderAudioLink=function(audioLink){return audioLink?fluid.stringTemplate(hortis.audioPlayerTemplate,{url:audioLink}):""};hortis.dumpHulqName=function(row,hulqName,markup){const player=hortis.renderAudioLink(row.audioLink);const nameRow=hortis.dumpRow("hulqName",`
    ${hulqName}
    `+player,markup);return nameRow};hortis.dumpHulqValues=function(row,markup){const valueBlocks=hortis.hulqValues.map((function(value){return row[value.toLowerCase()+"Value"]==="1"?value:"missing"})).map((function(img,index){return img==="missing"?"":fluid.stringTemplate(hortis.hulqValueItem,{img:img.toLowerCase(),label:hortis.hulqValues[index]})}));const valueBlock=fluid.stringTemplate(hortis.hulqValueBlock,{valueBlocks:valueBlocks.join("\n")});const valueRow1=hortis.dumpRow("Cultural values"," ",markup,"taxonDisplay-empty-header");const valueRow2=hortis.dumpRow("",valueBlock,markup,"taxonDisplay-empty-row");return valueRow1+valueRow2};hortis.iNatExtern=`iNaturalist`;hortis.imageTemplate=`\n
    \n
    \n %iNatExtern\n
    \n
    \n %photoCaption\n
    \n
    `;hortis.idToTaxonLink=function(taxonId){return"https://www.inaturalist.org/taxa/"+taxonId};hortis.renderTaxonDisplay=function(row,accessRow,markup,options){if(!row){return null}let togo=markup.taxonDisplayHeader;const dumpRow=function(keyName,value,extraClazz,options){if(keyName==="wikipediaSummary"&&value){const row1=hortis.dumpRow("Wikipedia Summary",hortis.expandButtonMarkup,markup,"taxonDisplay-expandable-header taxonDisplay-unexpanded taxonDisplay-runon-header");const row2=hortis.dumpRow("",value,markup,"taxonDisplay-expandable-remainder taxonDisplay-unexpanded taxonDisplay-runon-remainder","taxonDisplay-wikipediaSummary");togo+=row1+row2}else{togo+=hortis.dumpRow(keyName,value,markup,extraClazz,undefined,options)}};const dumpImage=function(keyName,url,taxonId,photoCaption){const imageMarkup=fluid.stringTemplate(markup.imageTemplate,{imgUrl:url,photoCaption:photoCaption,iNatExtern:taxonId?fluid.stringTemplate(hortis.iNatExtern,{iNatLink:hortis.idToTaxonLink(taxonId)}):""});togo+=imageMarkup};const dumpPhyloPic=function(keyName,url){togo+=hortis.dumpRow(keyName,`
    Taxon photo
    `,markup)};const photoCaption=`
    ${accessRow.featuredName}
    `+hortis.renderAudioLink(row.audioLink);if(!row.taxonName){if(row.iNaturalistTaxonImage&&!row.taxonPic){dumpImage("iNaturalistTaxonImage",row.iNaturalistTaxonImage,row.id,photoCaption)}else if(row.taxonPic){dumpImage("taxonPic",row.taxonPic)}if(row.phyloPicUrl){dumpPhyloPic("phyloPic",row.phyloPicUrl)}dumpRow(row.rank,accessRow.scientificName,"taxonDisplay-rank");hortis.commonFields.forEach((function(field){dumpRow(field,row[field])}));dumpRow("taxonPicDescription",row.taxonPicDescription);dumpRow("Species:",row.childCount);dumpRow("observationCount",row.observationCount)}else{if(row.iNaturalistTaxonImage&&!row.obsPhotoLink){dumpImage("iNaturalistTaxonImage",row.iNaturalistTaxonImage,row.id,photoCaption)}if(row.species){dumpRow("iNaturalistTaxonName",(row.taxonName||row.iNaturalistTaxonName)+(row.authority?" "+row.authority:""),"taxonDisplay-rank",options)}if(accessRow.commonName!==accessRow.featuredName){dumpRow("commonName",row.commonName&&hortis.capitalize(row.commonName))}if(accessRow.nativeName&&options.culturalValues){togo+=hortis.dumpHulqValues(row,markup)}if(row.media){const mediaPanel=hortis.renderMedia(row.media,"");togo+=hortis.dumpRow("media",hortis.expandButtonMarkup,markup,"taxonDisplay-expandable-header",null,options);togo+=hortis.dumpRow("media",mediaPanel,markup,"taxonDisplay-expandable-remainder taxonDisplay-runon-remainder",null,options)}dumpRow("wikipediaSummary",row.wikipediaSummary);let obsPanel="";obsPanel+=hortis.dumpRow("reportingStatus",row.reportingStatus&&hortis.capitalize(row.reportingStatus),markup);obsPanel+=hortis.renderObsBound(row,"first",markup,options);obsPanel+=hortis.renderObsBound(row,"last",markup,options);obsPanel+=hortis.renderObsBound(row,"since",markup,options);if(row.iNaturalistObsLink){obsPanel+=hortis.dumpRow("iNaturalistObsLink",`${row.iNaturalistObsLink}`,markup)}obsPanel+=hortis.dumpRow("observationCount",row.observationCount,markup);togo+=hortis.dumpRow("observationData",hortis.expandButtonMarkup,markup,"taxonDisplay-expandable-header",null,options);togo+=hortis.dumpRow("observationData",obsPanel,markup,"taxonDisplay-expandable-remainder taxonDisplay-runon-remainder",null,options);if(row.obsPhotoLink){dumpImage("Observation photo",row.obsPhotoLink)}}togo+=markup.taxonDisplayFooter;return togo};hortis.bindRowExpander=function(that){that.container.on("click",".taxonDisplay-expand",(function(e){const target=$(e.target);const header=target.closest(".taxonDisplay-expandable-header");header.toggleClass("taxonDisplay-expanded");header.toggleClass("taxonDisplay-unexpanded");const showing=header.hasClass("taxonDisplay-expanded");const siblings=header.parent().children();const ownIndex=header.index();const next=$(siblings[ownIndex+1]);if(next.hasClass("taxonDisplay-expandable-remainder")){next.toggleClass("taxonDisplay-expanded",showing);next.toggleClass("taxonDisplay-unexpanded",!showing)}}))};hortis.updateTaxonDisplay=function(that,taxonRow){const content=taxonRow?hortis.renderTaxonDisplay(taxonRow,that.accessRow(taxonRow),that.options.markup,that.options):null;const taxonDisplay=that.container[0];taxonDisplay.innerHTML=content||""};fluid.defaults("hortis.taxonDisplay",{gradeNames:"fluid.viewComponent",listeners:{"onCreate.bindRowExpander":{funcName:"hortis.bindRowExpander",args:["{that}"]}},invokers:{accessRow:{funcName:"hortis.accessRowHulq"}},markup:{taxonDisplayHeader:"",taxonDisplayRow:'
    %key%value
    ',taxonDisplayFooter:"",imageTemplate:hortis.imageTemplate},members:{selectedTaxonId:"@expand:signal()",obsRows:"@expand:signal()",taxaById:"@expand:signal()",obsForTaxonId:"@expand:fluid.computed(hortis.obsForTaxon, {that}.obsRows, {that}.selectedTaxonId)",taxonRow:"@expand:fluid.computed(hortis.computeTaxonDisplayRow, {that}.obsForTaxonId, {that}.taxaById, {that}.selectedTaxonId)",updateDisplay:"@expand:fluid.effect(hortis.updateTaxonDisplay, {that}, {that}.taxonRow)"},openTaxonPanels:{observationData:true,media:true}});hortis.byField=function(fieldName){return(a,b)=>a[fieldName]>b[fieldName]?1:-1};hortis.obsForTaxon=function(obsRows,taxonId){return obsRows.filter((row=>row["iNaturalist taxon ID"]===taxonId)).sort(hortis.byField("Date observed"))};hortis.obsToSummaryFields={RecordedBy:"Recorded by",ObservationId:"observationId",Timestamp:"Date observed"};hortis.computeTaxonDisplayRow=function(taxonObs,taxaById,taxonId){if(taxonId){const togo=Object.assign({},taxaById[taxonId]);const obsToFields=function(target,prefix,row){Object.entries(hortis.obsToSummaryFields).forEach((([key,value])=>{target[prefix+key]=row[value]}))};if(taxonObs.length>0){obsToFields(togo,"first",taxonObs[0]);obsToFields(togo,"last",fluid.peek(taxonObs))}return togo}else{return null}};"use strict";var hortis=fluid.registerNamespace("hortis");var{effect:effect,batch:batch}=preactSignalsCore;fluid.defaults("hortis.bareResourceLoader",{gradeNames:"fluid.component",members:{completionPromise:"@expand:fluid.promise()"}});fluid.defaults("hortis.csvReader",{gradeNames:"hortis.bareResourceLoader",csvOptions:{header:true,skipEmptyLines:true},members:{rows:"@expand:signal()"},events:{},listeners:{"onCreate.parse":"hortis.csvReader.parse({that}, {that}.options.csvOptions, {that}.options.url)"}});Object.defineProperty(fluid,"log",{get:function(){return fluid.isLogging()?console.log.bind(window.console,fluid.renderTimestamp(new Date)+": "):function(){}}});hortis.toggleClass=function(container,clazz,value,inverse){container.classList[value^inverse?"add":"remove"](clazz)};hortis.csvReader.parse=function(that,csvOptions,url){const options={...csvOptions,complete:function(results){that.parsed=results;that.data=results.data;that.headers=results.meta.fields;that.completionPromise.resolve(that.data);that.rows.value=that.data},error:function(err){that.completionPromise.reject();fluid.fail("Error parsing CSV file ",url,": ",err)}};Papa.parse(url,options)};fluid.defaults("hortis.urlCsvReader",{gradeNames:"hortis.csvReader",csvOptions:{download:true}});fluid.defaults("hortis.vizLoader",{gradeNames:["fluid.component"],components:{taxaLoader:{type:"hortis.urlCsvReader",options:{url:"{vizLoader}.options.taxaFile"}},obsLoader:{type:"hortis.urlCsvReader",options:{url:"{vizLoader}.options.obsFile"}},taxa:{type:"hortis.taxa",options:{members:{rows:"{vizLoader}.taxaRows"}}}},events:{onResourcesLoaded:null},members:{resourcesLoaded:"@expand:signal()",taxaRows:"@expand:signal()",obsRows:"@expand:signal()",filteredObs:"{that}.obsRows",finalFilteredObs:"@expand:fluid.computed({that}.filterObsByTaxa, {that}.filteredObs)"},invokers:{filterObs:fluid.identity,filterObsByTaxa:fluid.identity},listeners:{"onCreate.bindResources":"hortis.vizLoader.bindResources"}});hortis.vizLoader.bindResources=async function(that){const resourceLoaders=fluid.queryIoCSelector(that,"hortis.bareResourceLoader",true);const promises=resourceLoaders.map((resourceLoader=>resourceLoader.completionPromise));const[taxa,obs]=await Promise.all(promises);batch((()=>{that.taxaRows.value=taxa;that.obsRows.value=obs;that.resourcesLoaded.value=true;that.events.onResourcesLoaded.fire()}))};hortis.taxonTooltipTemplate=`
    \n
    \n
    %taxonRank: %taxonNames
    \n
    `;hortis.capitalize=function(string){return string.charAt(0).toUpperCase()+string.slice(1)};hortis.renderTaxonTooltip=function(that,hoverId){const row=that.rowById.value[hoverId];const terms={imgUrl:row.iNaturalistTaxonImage||""};if(row.rank){terms.taxonRank=hortis.capitalize(row.rank)}else{terms.taxonRank="Species"}const names=[row.taxonName||row.iNaturalistTaxonName,row.commonName,row.hulqName].filter((name=>name));terms.taxonNames=names.join(" / ");return fluid.stringTemplate(hortis.taxonTooltipTemplate,terms)};hortis.isInDocument=function(node){const dokkument=fluid.getDocument(node),container=node[0];return $.contains(dokkument,container)||dokkument===container};hortis.clearAllTooltips=function(that){hortis.clearTooltip(that);$(".ui-tooltip").remove();that[that.options.tooltipKey].value=null};hortis.clearTooltip=function(that){const tooltipTarget=that.tooltipTarget;if(tooltipTarget){that.tooltipTarget=null;if(hortis.isInDocument(tooltipTarget)){tooltipTarget.tooltip("destroy")}else{hortis.clearAllTooltips(that)}}};hortis.updateTooltip=function(that,id){const content=id?that.renderTooltip(id):null;hortis.clearTooltip(that);if(content){const target=$(that.hoverEvent.target);target.tooltip({items:target});target.tooltip("option","content",content||"");target.tooltip("option","track",true);target.tooltip("open",that.hoverEvent);that.tooltipTarget=target}else{that.hoverEvent=null}};hortis.subscribeHover=function(that){const tooltipKey=that.options.tooltipKey;return effect((()=>{hortis.updateTooltip(that,that[tooltipKey].value)}))};fluid.defaults("hortis.withTooltip",{invokers:{renderTooltip:"fluid.notImplemented"},members:{subscribeHover:"@expand:hortis.subscribeHover({that})"}});fluid.defaults("hortis.checkbox",{gradeNames:"fluid.stringTemplateRenderingView",members:{value:"@expand:signal()",valueToDom:"@expand:fluid.effect(hortis.checkbox.valueToDom, {that}.value, {that}.dom.control.0)"},selectors:{control:"input"},elideParent:false,markup:{container:`\n \n \n \n \n \n \n `},listeners:{"onCreate.listenCheck":"hortis.checkbox.listenCheck"}});hortis.checkbox.valueToDom=function(value,node){const state=value?"selected":"unselected";node.checked=state==="selected";node.setAttribute("indeterminate",state==="indeterminate");const holder=node.closest(".p-icon");const ui=holder.querySelector(".icon");$(ui).toggleClass("mdi-check",state!=="indeterminate")};hortis.checkbox.listenCheck=function(that){that.dom.locate("control").on("click",(function(){that.value.value=this.checked}))};hortis.closeParentTaxa=function(rowFocus,rowById){Object.keys(rowFocus).forEach((function(id){let row=rowById[id];while(row){rowFocus[row.id]=true;row=row.parent}}));return rowFocus};hortis.taxaFromObs=function(filteredObs,rowById){const taxonIds={};filteredObs.forEach((row=>{taxonIds[row["iNaturalist taxon ID"]]=true}));return hortis.closeParentTaxa(taxonIds,rowById)};hortis.bindTaxonHover=function(that,layoutHolder){const hoverable=that.options.selectors.hoverable;that.container.on("mouseenter",hoverable,(function(e){const id=this.dataset.rowId;layoutHolder.hoverEvent=e;layoutHolder.hoverId.value=id}));that.container.on("mouseleave",hoverable,(function(){layoutHolder.hoverId.value=null}));that.container.on("click",hoverable,(function(){const id=this.dataset.rowId;layoutHolder.events.taxonSelect.fire(id)}))};fluid.defaults("hortis.taxa",{gradeNames:"fluid.component",members:{rowByIdPre:"@expand:fluid.computed(hortis.indexTree, {that}.rows)",rowById:"@expand:fluid.computed(hortis.taxa.map, {that}.rows, {that}.rowByIdPre)",entries:"@expand:fluid.computed(hortis.computeEntries, {that}.rows, {that}.acceptRow)",entryById:"@expand:fluid.computed(hortis.indexEntries, {that}.entries)"},invokers:{acceptRow:"hortis.acceptRow({that}, {arguments}.0)"}});hortis.acceptRow=function(){return true};hortis.computeEntries=function(rows,acceptRow){const togo=[];fluid.each(rows,(function(row){if(acceptRow(row)){togo.push({row:row,children:hortis.computeEntries(row.children,acceptRow)})}else{const dChildren=hortis.computeEntries(row.children,acceptRow);Array.prototype.push.apply(togo,dChildren)}}));return hortis.sortChecklistLevel(togo)};hortis.indexEntries=function(entries){const index={};entries.forEach((function(entry){index[entry.row.id]=entry}));return index};hortis.indexTree=function(flatTree){const index={};flatTree.forEach((function(row){index[row.id]=row}));return index};hortis.taxa.map=function(rows,byId){rows.forEach(((row,i)=>{row.flatIndex=i;if(!row.children){row.children=[]}if(row.parentId){const parent=byId[row.parentId];row.parent=parent;fluid.pushArray(parent,"children",row)}}));const assignDepth=function(node,depth){node.depth=depth;node.children.forEach((child=>assignDepth(child,depth+1)))};if(rows.length>0){assignDepth(rows[0],0)}return byId};fluid.defaults("hortis.layoutHolder",{gradeNames:["fluid.modelComponent","hortis.withTooltip"],tooltipKey:"hoverId",events:{taxonSelect:null},members:{taxonHistory:"@expand:signal([])",historyIndex:"@expand:signal(0)",rootId:"@expand:signal({that}.options.rootId)",rowFocus:"@expand:signal({})",rowSelection:"@expand:signal({})",selectedId:"@expand:signal(null)",hoverId:"@expand:signal(null)"},modelRelay:{isAtRoot:{target:"isAtRoot",args:["{that}.model.layoutId","{that}.options.rootId"],func:(x,y)=>x===y}},invokers:{renderTooltip:"hortis.renderTaxonTooltip({that}, {arguments}.0)"}});fluid.defaults("hortis.vizLoaderWithMap",{gradeNames:["fluid.viewComponent","hortis.vizLoader"],selectors:{map:".imerss-map"},components:{map:{type:"hortis.libreMap",container:"{that}.dom.map",options:{gradeNames:"{vizLoader}.options.mapGrades"}}}});hortis.projectBounds={Galiano:[[48.855,-123.65],[49.005,-123.25]],Valdes:[[49,-123.798],[49.144,-123.504]],Xetthecum:[[48.93713,-123.511],[48.9511,-123.498]],Pepiowelh:[[48.565,-123.1575],[48.598,-123.1266]],HoweSound:[[49.16,-124.281],[50.17,-122.05]],SalishSea:[[47.568,-124.2],[49.134,-122.059]]};hortis.initBounds=function(){const bounds=[[90,180],[-90,-180]];return bounds};hortis.updateBounds=function(bounds,lat,long){bounds[0][0]=Math.min(bounds[0][0],lat);bounds[0][1]=Math.min(bounds[0][1],long);bounds[1][0]=Math.max(bounds[1][0],lat);bounds[1][1]=Math.max(bounds[1][1],long)};hortis.expandBounds=function(bounds,factor,latMin,longMin){const longSpan=bounds[1][1]-bounds[0][1];const latSpan=bounds[1][0]-bounds[0][0];const longD=Math.max(longSpan*factor,longMin/2);const latD=Math.max(latSpan*factor,latMin/2);if(longSpan<360){bounds[1][1]+=longD;bounds[0][1]-=longD;bounds[1][0]+=latD;bounds[0][0]-=latD}};fluid.defaults("hortis.libreMap",{gradeNames:"fluid.viewComponent",zoomDuration:1e3,mapOptions:{style:{version:8,layers:[],sources:{}}},members:{map:"@expand:hortis.libreMap.make({that}.container.0, {that}.options.mapOptions, {that}.options.zoomDuration, {that}.mapLoaded)",mapLoaded:"@expand:signal()"}});const initNavigationControl=function(options){this.options=options;this._container=fluid.h("div",{class:"maplibregl-ctrl maplibregl-ctrl-group"});this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(e=>this._map.zoomIn({duration:options.zoomDuration,essential:true},{originalEvent:e})));this._zoomInButton.appendChild(fluid.h("span",{class:"maplibregl-ctrl-icon","aria-hidden":true}));this._zoomOutButton=this._createButton("maplibregl-ctrl-zoom-out",(e=>this._map.zoomOut({duration:options.zoomDuration,essential:true},{originalEvent:e})));this._zoomOutButton.appendChild(fluid.h("span",{class:"maplibregl-ctrl-icon","aria-hidden":true}));this._updateZoomButtons=()=>{const zoom=this._map.getZoom();const isMax=zoom===this._map.getMaxZoom();const isMin=zoom===this._map.getMinZoom();this._zoomInButton.disabled=isMax;this._zoomOutButton.disabled=isMin;this._zoomInButton.setAttribute("aria-disabled",isMax.toString());this._zoomOutButton.setAttribute("aria-disabled",isMin.toString())};this._setButtonTitle=(button,title)=>{const str=this._map._getUIString(`NavigationControl.${title}`);button.title=str;button.setAttribute("aria-label",str)}};const makeNavigationControl=function(options){const inst=Object.create(maplibregl.NavigationControl.prototype);initNavigationControl.bind(inst)(options);return inst};hortis.libreMap.zoomControls=function(map,zoomDuration){map.addControl(makeNavigationControl({showCompass:false,showZoom:true,zoomDuration:zoomDuration}));map.dragRotate.disable();map.touchZoomRotate.disableRotation()};hortis.libreMap.make=function(container,mapOptions,zoomDuration,mapLoaded){const map=new maplibregl.Map({container:container,...mapOptions});map.on("load",(function(){console.log("Map loaded");mapLoaded.value=1}));hortis.libreMap.zoomControls(map,zoomDuration);return map};fluid.defaults("hortis.libreMap.withTiles",{addTiles:"@expand:fluid.effect(hortis.libreMap.addTileLayers, {that}.map, {that}.options.tileSets, {that}.mapLoaded)"});fluid.defaults("hortis.libreMap.streetmapTiles",{tileSets:{baseMap:{tiles:["https://tile.openstreetmap.org/{z}/{x}/{y}.png"],attribution:'© OpenStreetMap contributors',tileSize:256}}});fluid.defaults("hortis.libreMap.usEcoL3Tiles",{tileSets:{ecoL3:{tiles:["https://usda-nifa-b-team.github.io/b-team/tiles/us_eco_l3_tiles/{z}/{x}/{y}.png"],tileSize:512,maxzoom:8,paint:{"raster-opacity":.3}}}});hortis.libreMap.addTileLayers=function(map,tileSets){const tileKeys=Object.keys(tileSets);tileKeys.reverse().forEach((function(key){const tileSet=tileSets[key];const paint=tileSet.paint||{};map.addSource(key,{type:"raster",...fluid.censorKeys(tileSet,["paint"])});map.addLayer({id:key,type:"raster",source:key,paint:paint})}))};hortis.libreMap.viridisStops=[[0,"#440154"],[.2,"#414487"],[.4,"#2a788e"],[.6,"#22a884"],[.8,"#7ad151"],[1,"#fde725"]];hortis.libreMap.natureStops=[[0,"#ffffff"],[1,"#09326d"]];fluid.defaults("hortis.libreMap.withObsGrid",{gradeNames:["hortis.withTooltip"],tooltipKey:"hoverCell",fillStops:hortis.libreMap.viridisStops,fillOpacity:.5,outlineColour:"black",legendStops:5,members:{gridBounds:"@expand:fluid.derefSignal({obsQuantiser}.grid, bounds)",updateObsGrid:"@expand:fluid.effect(hortis.libreMap.updateObsGrid, {that}, {obsQuantiser}, {obsQuantiser}.grid, {that}.mapLoaded)",fitBounds:"@expand:fluid.effect(hortis.libreMap.fitBounds, {that}, {that}.gridBounds, {that}.mapLoaded)",memoStops:"@expand:fluid.colour.memoStops({that}.options.fillStops, 256)",control:"@expand:hortis.libreMap.withObsGrid.addLegendControl({map}, {obsQuantiser}.grid, {that}.gridVisible)",hoverCell:"@expand:signal(null)",gridVisible:"@expand:signal(true)"},invokers:{drawObsGridLegend:"hortis.libreMap.withObsGrid.drawLegend({map}, {obsQuantiser}.grid, {that}.gridVisible)"},listeners:{"onCreate.bindGridSelect":"hortis.libreMap.bindGridSelect({that})"}});fluid.registerNamespace("hortis.legend");hortis.legend.rowTemplate=`\n
    \n \n \n %keyLabel\n
    `;hortis.libreMap.withObsGrid.addLegendControl=function(map){const control=map.drawObsGridLegend();control.onAdd=()=>control.container;control.onRemove=()=>{console.log("Cleaning up legend attached to ",control.container);control.cleanup()};map.map.addControl(control,"bottom-right");return control};hortis.libreMap.withObsGrid.drawLegend=function(map,gridSignal,gridVisibleSignal){const quant=map.obsQuantiser;const container=document.createElement("div");container.classList.add("imerss-legend");const cstops=map.options.legendStops;const stops=fluid.iota(cstops);const legendStopProps=fluid.iota(cstops+1).map((stop=>stop/cstops));const renderLegend=function(grid){const propToLevel=prop=>Math.floor(prop*grid.maxObsCount);const regionMarkupRows=stops.map((function(stop){const midProp=(legendStopProps[stop]+legendStopProps[stop+1])/2;const colour=fluid.colour.lookupStop(map.memoStops,midProp);const label=propToLevel(legendStopProps[stop])+" - "+propToLevel(legendStopProps[stop+1]);return fluid.stringTemplate(hortis.legend.rowTemplate,{previewStyle:"background-color: "+colour,keyLabel:label})}));const longRes=quant.longResolution.value;const baseLat=quant.baseLatitude.value;const longLen=Math.floor(longRes*hortis.longitudeLength(baseLat));const markup=`
    Observation count
    `+regionMarkupRows.join("\n")+`
    Cell size: ${longLen}m
    `;container.innerHTML=markup};fluid.effect(renderLegend,gridSignal);fluid.effect((isVisible=>hortis.toggleClass(container,"imerss-hidden",!isVisible)),gridVisibleSignal);return{container:container}};hortis.capitalize=function(string){return string.charAt(0).toUpperCase()+string.slice(1)};hortis.renderTaxonTooltip=function(that,hoverId){const row=that.rowById.value[hoverId];const terms={imgUrl:row.iNaturalistTaxonImage||""};if(row.rank){terms.taxonRank=hortis.capitalize(row.rank)}else{terms.taxonRank="Species"}const names=[row.taxonName||row.iNaturalistTaxonName,row.commonName,row.hulqName].filter((name=>name));terms.taxonNames=names.join(" / ");return fluid.stringTemplate(hortis.taxonTooltipTemplate,terms)};hortis.libreMap.bindGridSelect=function(that){const map=that.map;map.on("mousemove",(e=>{const features=map.queryRenderedFeatures(e.point);const visibleFeatures=features.filter((feature=>feature.properties.cellId));that.hoverEvent=e.originalEvent;const cellId=visibleFeatures[0]?.properties.cellId||null;that.hoverCell.value=cellId;map.getCanvas().style.cursor=cellId?"default":""}));map.getCanvas().addEventListener("mouseleave",(()=>hortis.clearAllTooltips(that)))};hortis.libreMap.rectFromCorner=function(lat,long,latres,longres){return[[long,lat],[long+longres,lat],[long+longres,lat+latres],[long,lat+latres],[long,lat]]};hortis.libreMap.obsGridFeature=function(map,obsQuantiser,grid){const buckets=grid.buckets,latres=obsQuantiser.latResolution.value,longres=obsQuantiser.longResolution.value;return{type:"FeatureCollection",features:Object.entries(buckets).map((function([key,bucket]){const[lat,long]=hortis.obsQuantiser.indexToCoord(key,latres,longres);return{type:"Feature",geometry:{type:"Polygon",coordinates:[hortis.libreMap.rectFromCorner(lat,long,latres,longres)]},properties:{cellId:key,obsprop:bucket.obsCount/grid.maxObsCount}}}))}};hortis.libreMap.updateObsGrid=function(map,obsQuantiser,grid){const geojson=hortis.libreMap.obsGridFeature(map,obsQuantiser,grid);let source=map.map.getSource("obsgrid-source");if(source){source.setData(geojson)}else{map.map.addSource("obsgrid-source",{type:"geojson",data:geojson})}const layer=map.map.getLayer("obsgrid-layer");if(!layer){const layer={id:"obsgrid-layer",type:"fill",source:"obsgrid-source",paint:{"fill-color":{property:"obsprop",stops:map.options.fillStops},"fill-opacity":map.options.fillOpacity,"fill-outline-color":map.options.outlineColour}};map.map.addLayer(layer)}};hortis.libreMap.swapCoords=function(coords){return[coords[1],coords[0]]};hortis.libreMap.swapBounds=function(bounds){return bounds.map(hortis.libreMap.swapCoords)};hortis.libreMap.fitBounds=function(that,fitBounds){const swapped=hortis.libreMap.swapBounds(fitBounds);that.map.fitBounds(swapped,{duration:that.options.zoomDuration,essential:true})};hortis.WGS84a=6378137;hortis.WGS84b=6356752.3142;hortis.WGS84e2=(hortis.WGS84a*hortis.WGS84a-hortis.WGS84b*hortis.WGS84b)/(hortis.WGS84a*hortis.WGS84a);hortis.longitudeLength=function(latitude){const latrad=Math.PI*latitude/180;const sinrad=Math.sin(latrad);return Math.PI*hortis.WGS84a*Math.cos(latrad)/(180*Math.sqrt(1-hortis.WGS84e2*sinrad*sinrad))};hortis.latitudeLength=function(latitude){const latrad=Math.PI*latitude/180;const sinrad=Math.sin(latrad);return Math.PI*hortis.WGS84a*(1-hortis.WGS84e2)/(180*Math.pow(1-hortis.WGS84e2*sinrad*sinrad,1.5))};hortis.longToLat=function(lng,lat){const longLength=hortis.longitudeLength(lat);const latLength=hortis.latitudeLength(lat);return lng*longLength/latLength};fluid.registerNamespace("hortis.obsQuantiser");hortis.obsQuantiser.initGrid=function(){const grid={};grid.bounds=hortis.initBounds();grid.maxObsCount=0;grid.buckets={};return grid};hortis.gridBucket=()=>({obsCount:0,byTaxonId:{}});hortis.indexObs=function(bucket,row,index){fluid.pushArray(bucket.byTaxonId,row.iNatTaxonId,index)};fluid.defaults("hortis.obsQuantiser",{gradeNames:"fluid.modelComponent",members:{newBucket:hortis.gridBucket,indexObs:hortis.indexObs,baseLatitude:"@expand:signal(37.5)",longResolution:"@expand:signal(0.005)",latResolution:"@expand:fluid.computed(hortis.longToLat, {that}.longResolution, {that}.baseLatitude)",maxBounds:"@expand:fluid.computed(hortis.obsBounds, {vizLoader}.obsRows)",grid:{expander:{funcName:"fluid.computed",args:["hortis.obsQuantiser.indexObs","{that}","{vizLoader}.finalFilteredObs","{that}.latResolution","{that}.longResolution"]}}}});hortis.obsQuantiser.indexToCoord=function(index,latres,longres){const coords=index.split("|");return[coords[0]*latres,coords[1]*longres]};hortis.obsQuantiser.coordToIndex=function(lat,long,latres,longres){const latq=Math.floor(lat/latres);const longq=Math.floor(long/longres);return latq+"|"+longq};hortis.obsBounds=function(rows){const bounds=hortis.initBounds();rows.forEach((function(row){hortis.updateBounds(bounds,row.decimalLatitude,row.decimalLongitude)}));return bounds};hortis.obsQuantiser.indexObs=function(that,rows,latRes,longRes){const grid=hortis.obsQuantiser.initGrid();const now=Date.now();rows.forEach((function(row,index){const coordIndex=hortis.obsQuantiser.coordToIndex(row.decimalLatitude,row.decimalLongitude,latRes,longRes);hortis.updateBounds(grid.bounds,row.decimalLatitude,row.decimalLongitude);let bucket=grid.buckets[coordIndex];if(!bucket){bucket=grid.buckets[coordIndex]=that.newBucket()}bucket.obsCount++;grid.maxObsCount=Math.max(grid.maxObsCount,bucket.obsCount);that.indexObs(bucket,row,index)}));if(rows.length===0){grid.bounds=[...that.maxBounds.value]}hortis.expandBounds(grid.bounds,.1,latRes*6,longRes*6);const delay=Date.now()-now;fluid.log("Gridded "+rows.length+" rows in "+delay+" ms: "+1e3*(delay/rows.length)+" us/row");return grid};fluid.defaults("hortis.libreObsMap",{gradeNames:["hortis.libreMap","hortis.libreMap.withObsGrid"],components:{obsQuantiser:{type:"hortis.obsQuantiser",options:{members:{longResolution:"@expand:signal(0.075)"}}}}});"use strict";var hortis=fluid.registerNamespace("hortis");var{signal:signal,effect:effect,batch:batch}=preactSignalsCore;hortis.sppAnnotations=["agg.","aff.","s.lat.","cf","sp.nov.","var.","sp.","ssp.","spp.","complex"];hortis.annoteRegex=new RegExp("("+hortis.sppAnnotations.map((annot=>annot.replace(".","\\."))).join("|")+")","g");hortis.renderSpeciesName=function(name){return name.replace(hortis.annoteRegex,`$1`)};hortis.encodeHTML=function(str){return str.replace(/[&<>'"]/g,(function(tag){return{"&":"&","<":"<",">":">","'":"'",'"':"""}[tag]}))};hortis.rowToScientific=function(row){return row.taxonName||row.iNaturalistTaxonName};hortis.accessRowHulq=function(row){const togo={nativeName:row.hulquminumName,scientificName:hortis.rowToScientific(row),commonName:row.commonName};togo.featuredName=togo.nativeName||togo.commonName;return togo};hortis.rowFold=function(rowid,folded){const foldChar=folded==="folded"?"chevron-right":folded==="unfolded"?"chevron-down":"none";const active=foldChar==="none"?"":" active";return`\n \n \n \n \n \n `};hortis.rowCheckbox=function(id,state){const checked=state==="selected"?"checked":"";const indeterminate=`indeterminate="${state==="indeterminate"}"`;const rowid=` data-row-id="${id}"`;return`\n \n \n \n \n \n \n `};hortis.resetChecks=function(parent){[...parent.querySelectorAll(".pretty input")].forEach((input=>input.checked=false))};hortis.checklistItem=function(entry,options,state){const record=entry.row,id=record.id;const rowid=`data-row-id="${id}"`;const rank=record.rank&&!(options.simple&&record.taxonName)?record.rank:"species";const selectedClass=rank==="species"&&record.id===state.selectedId?" checklist-selected":"";const header=`
  • `;const accessed=options.accessRow(record);const render=rank==="species"?hortis.renderSpeciesName:fluid.identity;const names={};if(accessed.nativeName){names.nativeName=`

    ${accessed.nativeName}

    `}if(accessed.scientificName){names.scientificName=`

    ${render(hortis.encodeHTML(accessed.scientificName))}

    `}if(accessed.commonName){names.commonName=`

    ${accessed.commonName}

    `}const name=Object.values(names).join(" - ");const rowState=state.idToState[id];const subList=hortis.checklistList(rowState.folded==="folded"?[]:entry.children,options,state);const footer="
  • ";const fold=options.unfoldable?hortis.rowFold(rowid,rowState.folded):"";const check=options.selectable?hortis.rowCheckbox(id,rowState.selected):"";return header+fold+check+name+subList+footer};hortis.checklistList=function(entries,options,state){return entries.length?"
      "+entries.map((function(entry){return hortis.checklistItem(entry,options,state)})).join("")+"
    ":""};hortis.checklistRowForId=function(container,id){return container.find(`[data-row-id=${id}]`).closest("li")};hortis.updateChecklistSelection=function(container,newSelectedId,oldSelectedId,rowById){if(newSelectedId===null){return}const oldSelected=hortis.checklistRowForId(container,oldSelectedId);oldSelected.removeClass("checklist-selected");const row=rowById[newSelectedId];if(row&&row.species){const newSelected=hortis.checklistRowForId(container,newSelectedId);newSelected.addClass("checklist-selected")}};hortis.alwaysRejectRanks=[];hortis.acceptChecklistRowAS=function(row,filterRanks,rowFocus){const acceptBasic=!filterRanks||filterRanks.includes(row.rank)||row.species;const alwaysReject=hortis.alwaysRejectRanks.includes(row.rank);const rejectSpecies=row.rank==="species"&&row.children.length>0;const acceptChecklist=row.taxonName;return rowFocus[row.id]&&(acceptBasic&&!rejectSpecies&&!alwaysReject||acceptChecklist)};hortis.acceptChecklistRowOBA=function(row,filterRanks,idToState,rowFocus){const acceptBasic=!filterRanks||filterRanks.includes(row.rank);const alwaysReject=hortis.alwaysRejectRanks.includes(row.rank);return rowFocus[row.id]&&acceptBasic&&!alwaysReject};hortis.scientificComparator=function(entrya,entryb){return hortis.rowToScientific(entrya.row)>hortis.rowToScientific(entryb.row)?1:-1};hortis.sortChecklistLevel=function(entries){return entries.sort(hortis.scientificComparator)};hortis.filterTaxonomy=function(rows,depth,acceptChecklistRow,filterTaxonomy,showRoot){const togo=[];fluid.each(rows,(function(row){if(acceptChecklistRow(row)||depth===0&&showRoot){togo.push({row:row,children:filterTaxonomy(row.children,depth+1)})}else{const dChildren=filterTaxonomy(row.children,depth+1);Array.prototype.push.apply(togo,dChildren)}}));return hortis.sortChecklistLevel(togo)};fluid.defaults("hortis.checklist",{gradeNames:["hortis.withPanelLabel","fluid.viewComponent"],filterRanks:false,showRoot:false,selectable:false,unfoldable:false,selectors:{hoverable:"p",checklist:".imerss-checklist"},invokers:{accessRow:{funcName:"hortis.accessRowHulq"},foldByDefault:{args:["{that}.options.disclosableRanks","{arguments}.0"],func:(disclosableRanks,row)=>disclosableRanks&&disclosableRanks.includes(row.rank)},acceptChecklistRow:{funcName:"hortis.acceptChecklistRowAS",args:["{arguments}.0","{that}.options.filterRanks","{that}.rowFocus.value"]},filterTaxonomy:{funcName:"hortis.filterTaxonomy",args:["{arguments}.0","{arguments}.1","{that}.acceptChecklistRow","{that}.filterTaxonomy","{that}.options.showRoot"]},generate:{funcName:"hortis.checklist.generate",args:["{that}","{that}.dom.checklist","{that}.idToState.value","{that}.rootEntry.value","{that}.selectedId.value"]},check:"hortis.checklist.check({that}, {arguments}.0, {arguments}.1)",toggleFold:"hortis.checklist.toggleFold({that}, {arguments}.0)",reset:"hortis.checklist.reset({that})"},members:{idToEntry:{},rootEntry:"@expand:fluid.computed(hortis.checklist.computeRootEntry, {that}, {that}.rowById, {that}.rootId, {that}.filterTaxonomy)",idToStateUIOld:null,idToStateUI:"@expand:signal(null)",scheduleRender:"@expand:signal()",subscribeScheduleRender:"@expand:fluid.effect({that}.generate, {that}.scheduleRender)",idToStateOld:null,idToState:"@expand:fluid.computed(hortis.checklist.idToState, {that}, {that}.idToStateUI, {that}.rootEntry, {that}.rowFocus)",rowSelection:"@expand:fluid.computed(hortis.checklist.checksToSelection, {that}.idToState)",subscribeChecks:"@expand:fluid.effect(hortis.checklist.subscribeChecks, {that}, {that}.idToStateUI)",subscribeSelected:"@expand:hortis.checklist.subscribeSelected({that}, {that}.selectedId, {that}.rowById)",allLeaves:"@expand:fluid.computed(hortis.checklist.computeLeaves, {that}.idToEntry, {that}.rowSelection)",renderEffect:"@expand:fluid.effect(fluid.identity, {that}.idToState)"},listeners:{"onCreate.bindTaxonHover":"hortis.bindTaxonHover({that}, {layoutHolder})","onCreate.bindCheckboxClick":"hortis.checklist.bindCheckboxClick({that}, {that}.dom.checklist)"}});fluid.defaults("hortis.checklist.withOBA",{invokers:{acceptChecklistRow:{funcName:"hortis.acceptChecklistRowOBA",args:["{arguments}.0","{that}.options.filterRanks","{that}.oldIdToState","{that}.rowFocus.value"]}}});fluid.defaults("hortis.checklist.withCopy",{selectors:{copyButton:".imerss-copy-checklist"},components:{copyButton:{type:"fluid.viewComponent",container:"{that}.dom.copyButton",options:{gradeNames:"hortis.withTooltip",tooltipKey:"tooltipKey",members:{hovered:"@expand:signal(null)",inCopy:"@expand:signal(null)",tooltipKey:"@expand:fluid.computed(hortis.checklist.withCopy.deriveTooltipKey, {that}.hovered, {that}.inCopy)",inCopyEffect:"@expand:fluid.effect(hortis.checklist.withCopy.inCopyEffect, {that}.container.0, {that}.inCopy)"},invokers:{renderTooltip:"hortis.checklist.withCopy.renderTooltip({copyButton}, {hortis.checklist})",copyToClipboard:"hortis.checklist.withCopy.copyToClipboard({copyButton},{hortis.checklist})"},listeners:{"onCreate.bindHover":"hortis.checklist.withCopy.bindHover"}}}}});hortis.checklist.withCopy.bindHover=function(that){that.container.on("mouseenter",(function(e){that.hoverEvent=e;that.hovered.value=true}));that.container.on("mouseleave",(function(){that.hovered.value=null}));that.container.on("click",that.copyToClipboard)};hortis.checklist.withCopy.deriveTooltipKey=function(hovered,inCopy){return inCopy?"inCopy":hovered};hortis.checklist.withCopy.inCopyEffect=function(container,inCopy){const node=container.querySelector("use");if(inCopy){node.setAttribute("href","#copy-check");container.classList.add("imerss-copy-checklist-copied")}else{node.setAttribute("href","#copy-clipboard");container.classList.remove("imerss-copy-checklist-copied")}};hortis.checklist.withCopy.renderTooltip=function(copyButton,checklist){if(copyButton.inCopy.value){return"Copied!"}else{const leaves=checklist.allLeaves.value;const limit=5;const truncate=leaves.length>limit;const message=fluid.stringTemplate(checklist.options.copyButtonMessage,{rows:leaves.length})+":\n"+(truncate?[...leaves.slice(0,limit),"..."].join("\n"):leaves.join("\n"));return message.replaceAll("\n","
    ")}};hortis.checklist.withCopy.copyToClipboard=function(copyButton,checklist){copyButton.inCopy.value=true;window.setTimeout((()=>copyButton.inCopy.value=null),2e3);const leaves=checklist.allLeaves.value.join("\n");navigator.clipboard.writeText(leaves).then((function(){console.log("Copying to clipboard was successful!")}),(function(err){console.error("Could not copy text: ",err)}))};hortis.checklist.bindCheckboxClick=function(checklist,checklistContainer){checklistContainer.on("click",".pretty input",(function(){const id=this.dataset.rowId;fluid.log("Checkbox clicked with row "+id);checklist.check(id,this.checked)}));checklistContainer.on("click",".checklist-fold-control.active",(function(){const id=this.dataset.rowId;fluid.log("Fold clicked with row "+id);checklist.toggleFold(id)}))};hortis.checklist.stateToCheck=function(checklist,state,id){const node=checklist.idToNode?.[id];if(node){node.checked=state.selected==="selected";node.setAttribute("indeterminate",state.selected==="indeterminate");const holder=node.closest(".p-icon");const ui=holder.querySelector(".icon");$(ui).toggleClass("mdi-check",state.selected!=="indeterminate")}};hortis.checklist.subscribeChecks=function(checklist,idToStateUI){const oldIdToState=checklist.idToStateUIOld;fluid.each(idToStateUI,((newState,id)=>{const oldState=oldIdToState[id];if(newState!==oldState){hortis.checklist.stateToCheck(checklist,newState,id)}}));checklist.idToStateUIOld=idToStateUI};hortis.checklist.allChildrenState=function(idToState,entry,state){return entry.children.find((child=>idToState[child.row.id].selected!==state))===undefined};hortis.checklist.check=function(checklist,id,checked){const idToStateUp=fluid.copy(checklist.idToStateUI.value);const upState=checked?"selected":"unselected";const entry=checklist.idToEntry[id];const setChildState=function(entry,state){idToStateUp[entry.row.id].selected=state;entry.children.forEach((child=>setChildState(child,state)))};setChildState(entry,upState);let parent=entry.parent;while(parent.row){const allChildrenState=hortis.checklist.allChildrenState(idToStateUp,parent,upState);idToStateUp[parent.row.id].selected=allChildrenState?upState:"indeterminate";parent=parent.parent}batch((()=>{checklist.idToStateUI.value=idToStateUp;if(upState==="selected"&&idToStateUp[id].folded==="folded"){hortis.checklist.toggleFold(checklist,id)}}))};hortis.checklist.reset=function(checklist){const rootId=checklist.rootEntry.value.children[0].row.id;hortis.checklist.check(checklist,rootId,false)};hortis.checklist.toggleFold=function(checklist,id){const idToStateUp=fluid.copy(checklist.idToStateUI.value);const state=idToStateUp[id];const newFolded=state.folded==="folded"?"unfolded":"folded";state.folded=newFolded;const entry=checklist.idToEntry[id];const defaultNewFold=entry=>entry.children.length===0?"fixed":"folded";entry.children.forEach((child=>idToStateUp[child.row.id].folded=newFolded==="folded"?"hidden":defaultNewFold(child)));checklist.idToStateUI.value=idToStateUp;checklist.scheduleRender.value=true};hortis.checklist.subscribeSelected=function(that,selectedIdSignal,rowByIdSignal){let oldSelectedId=undefined;return fluid.effect((function(newSelectedId,rowById){hortis.updateChecklistSelection(that.container,newSelectedId,oldSelectedId,rowById);oldSelectedId=newSelectedId}),selectedIdSignal,rowByIdSignal)};hortis.checklist.computeRootEntry=function(that,rowById,rootId,filterTaxonomy){const rootRow=rowById[rootId];fluid.log("Generating checklist for id "+rootId);const filteredEntries=filterTaxonomy([rootRow],0);const idToEntry=that.idToEntry;fluid.clear(idToEntry);let entryIndex=0;const indexEntry=function(entry,parent){idToEntry[entry.row.id]=entry;entry.index=entryIndex++;entry.parent=parent;entry.children.forEach((child=>indexEntry(child,entry)))};filteredEntries.forEach(indexEntry);return{children:filteredEntries}};hortis.checklist.idToState=function(that,idToStateUI,rootEntry,rowFocus){const idToStateOld=that.idToStateOld;let togo;if(idToStateOld===idToStateUI){togo=hortis.checklist.computeInitialModel(rootEntry,rowFocus,idToStateOld,that.options.unfoldable,that.foldByDefault);fluid.invokeLater((()=>that.scheduleRender.value=true))}else{togo=idToStateUI;that.idToStateOld=togo}return togo};hortis.checklist.generate=function(that,element,idToState,rootEntry,selectedId){const selectable=that.options.selectable,unfoldable=that.options.unfoldable,simple=!!that.options.filterRanks;const rootEntries=rootEntry.children;const options={simple:simple,selectable:selectable,unfoldable:unfoldable,accessRow:that.accessRow};const state={selectedId:selectedId,idToState:idToState};const markup=hortis.checklistList(rootEntries,options,state);element[0].innerHTML=markup;if(selectable){const checks=element[0].querySelectorAll(".checklist-check");const idToNode={};checks.forEach((check=>idToNode[check.dataset.rowId]=check));that.idToNode=idToNode}that.scheduleRender.value=undefined;that.idToStateUIOld=idToState;that.idToStateUI.value=idToState};hortis.checklist.ROOT_ID=Number.NEGATIVE_INFINITY;hortis.checklist.defaultFold=function(entry,unfoldable,foldByDefault){return entry.children.length===0||!unfoldable?"fixed":entry.children.every((child=>foldByDefault(child.row)))?"folded":"unfolded"};hortis.checklist.computeInitialModel=function(rootEntry,rowFocus,oldIdToState,unfoldable,foldByDefault){const idToState={};const indexEntry=function(entry,parentFolded){const id=entry.row.id;if(!id){fluid.log("Warning, discarding row ",entry.row," without id set")}else if(rowFocus[id]){const defaultFolded=parentFolded==="folded"||parentFolded==="hidden"?"hidden":parentFolded==="root"?"fixed":hortis.checklist.defaultFold(entry,unfoldable,foldByDefault);idToState[id]=oldIdToState?.[id]||{selected:"unselected",folded:defaultFolded}}const folded=idToState[id].folded;entry.children.forEach((childEntry=>indexEntry(childEntry,folded)))};rootEntry.children.forEach((childEntry=>indexEntry(childEntry,"root")));return idToState};fluid.defaults("hortis.checklist.withHolder",{gradeNames:["hortis.layoutHolder","hortis.checklist"]});hortis.checklist.checksToSelection=function(idToState){const selection={};const selectAll={};let selected=0;fluid.each(idToState,((state,key)=>{if(state.folded!=="hidden"){if(state.selected==="selected"){++selected;selection[key]=true}selectAll[key]=true}}));return selected===0?selectAll:selection};hortis.checklist.computeLeaves=function(idToEntry,selection){const leaves=[];const appendLeaves=function(id){const entry=idToEntry[id];if(entry.children.length===0){leaves.push(entry.row.iNaturalistTaxonName)}else{entry.children.forEach((child=>appendLeaves(child.row.id)))}};Object.keys(selection).forEach((id=>appendLeaves(id)));return leaves}; //# sourceMappingURL=imerss-viz-new-core.js.map \ No newline at end of file diff --git a/docs/js/imerss-viz-new.js b/docs/js/imerss-viz-new.js index b1c7638a..69160626 100644 --- a/docs/js/imerss-viz-new.js +++ b/docs/js/imerss-viz-new.js @@ -1,4 +1,11 @@ -(function webpackUniversalModuleDefinition(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports["accessibleAutocomplete"]=t():e["accessibleAutocomplete"]=t()})(window,(function(){return function(n){var r={};function o(e){if(r[e])return r[e].exports;var t=r[e]={i:e,l:!1,exports:{}};return n[e].call(t.exports,t,t.exports,o),t.l=!0,t.exports}return o.m=n,o.c=r,o.d=function(e,t,n){o.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},o.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},o.t=function(t,e){if(1&e&&(t=o(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(o.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)o.d(n,r,function(e){return t[e]}.bind(null,r));return n},o.n=function(e){var t=e&&e.__esModule?function(){return e["default"]}:function(){return e};return o.d(t,"a",t),t},o.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},o.p="/",o(o.s=37)}([function(e,t,n){var m=n(1),v=n(6),y=n(7),g=n(16),_=n(18),b="prototype",w=function(e,t,n){var r,o,i,u,a=e&w.F,s=e&w.G,l=e&w.S,c=e&w.P,p=e&w.B,f=s?m:l?m[t]||(m[t]={}):(m[t]||{})[b],d=s?v:v[t]||(v[t]={}),h=d[b]||(d[b]={});for(r in s&&(n=t),n)i=((o=!a&&f&&f[r]!==undefined)?f:n)[r],u=p&&o?_(i,m):c&&"function"==typeof i?_(Function.call,i):i,f&&g(f,r,i,e&w.U),d[r]!=i&&y(d,r,u),c&&h[r]!=i&&(h[r]=i)};m.core=v,w.F=1,w.G=2,w.S=4,w.P=8,w.B=16,w.W=32,w.U=64,w.R=128,e.exports=w},function(e,t){var n=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t,n){e.exports=!n(4)((function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}))},function(e,t){e.exports=function(e){try{return!!e()}catch(t){return!0}}},function(e,t,n){"use strict";n.r(t),n.d(t,"h",(function(){return r})),n.d(t,"createElement",(function(){return r})),n.d(t,"cloneElement",(function(){return i})),n.d(t,"Component",(function(){return g})),n.d(t,"render",(function(){return _})),n.d(t,"rerender",(function(){return f})),n.d(t,"options",(function(){return E}));var s=function s(){},E={},l=[],c=[];function r(e,t){var n,r,o,i,u=c;for(i=arguments.length;2o;)u(r,n=t[o++])&&(~s(i,n)||i.push(n));return i}},function(e,t,n){var r=n(25),o=Math.max,i=Math.min;e.exports=function(e,t){return(e=r(e))<0?o(e+t,0):i(e,t)}},function(e,t){e.exports=!1},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t){t.f={}.propertyIsEnumerable},function(e,t,n){var r=n(48);e.exports=function(e,t){return new(r(e))(t)}},function(e,t,n){var r=n(2),o=n(33),i=n(34)("species");e.exports=function(e){var t;return o(e)&&("function"!=typeof(t=e.constructor)||t!==Array&&!o(t.prototype)||(t=undefined),r(t)&&null===(t=t[i])&&(t=undefined)),t===undefined?Array:t}},function(e,t,n){"use strict";var r=n(0),o=n(32)(2);r(r.P+r.F*!n(13)([].filter,!0),"Array",{filter:function(e){return o(this,e,arguments[1])}})},function(e,t,n){var r=n(0);r(r.S,"Array",{isArray:n(33)})},function(e,t,n){"use strict";t.__esModule=!0,t["default"]=void 0,n(14),n(36),n(30),n(31),n(35),n(55),n(58);var $=n(5),J=o(n(60)),r=o(n(61));function o(e){return e&&e.__esModule?e:{default:e}}function X(){return(X=Object.assign||function(e){for(var t=1;t=r;this.setState({query:a,ariaHint:s}),i||!s&&l&&c?o(a,(function(e){var t=0=i&&0=o,P=this.props.showNoOptionsFound&&N&&I&&k&&A,j=n+"__wrapper",L=n+"__input",T=null!==_?" "+L+"--focused":"",B=this.props.showAllValues?" "+L+"--show-all-values":" "+L+"--default",D=n+"__dropdown-arrow-down",F=-1!==_&&null!==_,R=n+"__menu",U=R+"--"+r,V=R+"--"+(w||P?"visible":"hidden"),q=n+"__option",W=n+"__hint",H=this.templateInputValue(x[C]),K=H&&0===H.toLowerCase().indexOf(O.toLowerCase())&&M?O+H.substr(O.length):"",Q=u+"__assistiveHint",z=S?{"aria-describedby":Q}:null;return c&&"string"==typeof(e=y({className:D}))&&(e=(0,$.createElement)("div",{className:n+"__dropdown-arrow-down-wrapper",dangerouslySetInnerHTML:{__html:e}})),(0,$.createElement)("div",{className:j,onKeyDown:this.handleKeyDown},(0,$.createElement)(J["default"],{id:u,length:x.length,queryLength:O.length,minQueryLength:o,selectedOption:this.templateInputValue(x[C]),selectedOptionIndex:C,validChoiceMade:E,isInFocus:null!==this.state.focused,tQueryTooShort:f,tNoResults:d,tSelectedOption:h,tResults:m}),K&&(0,$.createElement)("span",null,(0,$.createElement)("input",{className:W,readonly:!0,tabIndex:"-1",value:K})),(0,$.createElement)("input",X({"aria-expanded":w?"true":"false","aria-activedescendant":!!F&&u+"__option--"+_,"aria-owns":u+"__listbox","aria-autocomplete":this.hasAutoselect()?"both":"list"},z,{autoComplete:"off",className:""+L+T+B,id:u,onClick:function(e){return i.handleInputClick(e)},onBlur:this.handleInputBlur},function G(e){return{onInput:e}}(this.handleInputChange),{onFocus:this.handleInputFocus,name:a,placeholder:s,ref:function(e){i.elementReferences[-1]=e},type:"text",role:"combobox",required:l,value:O})),e,(0,$.createElement)("ul",{className:R+" "+U+" "+V,onMouseLeave:function(e){return i.handleListMouseLeave(e)},id:u+"__listbox",role:"listbox"},x.map((function(e,t){var n=(-1===_?C===t:_===t)&&null===b?" "+q+"--focused":"",r=t%2?" "+q+"--odd":"",o=Y()?" '+(t+1)+" of "+x.length+"":"";return(0,$.createElement)("li",{"aria-selected":_===t?"true":"false",className:""+q+n+r,dangerouslySetInnerHTML:{__html:i.templateSuggestion(e)+o},id:u+"__option--"+t,key:t,onBlur:function(e){return i.handleOptionBlur(e,t)},onClick:function(e){return i.handleOptionClick(e,t)},onMouseDown:i.handleOptionMouseDown,onMouseEnter:function(e){return i.handleOptionMouseEnter(e,t)},ref:function(e){i.elementReferences[t]=e},role:"option",tabIndex:"-1","aria-posinset":t+1,"aria-setsize":x.length})})),P&&(0,$.createElement)("li",{className:q+" "+q+"--no-results"},p())),(0,$.createElement)("span",{id:Q,style:{display:"none"}},v()))},e}($.Component);(t["default"]=a).defaultProps={autoselect:!1,cssNamespace:"autocomplete",defaultValue:"",displayMenu:"inline",minLength:0,name:"input-autocomplete",placeholder:"",onConfirm:function(){},confirmOnBlur:!0,showNoOptionsFound:!0,showAllValues:!1,required:!1,tNoResults:function(){return"No results found"},tAssistiveHint:function(){return"When autocomplete results are available use up and down arrows to review and enter to select. Touch device users, explore by touch or with swipe gestures."},dropdownArrow:r["default"]}},function(e,t,r){var o=r(9),i=r(53),u=r(28),a=r(26)("IE_PROTO"),s=function(){},l="prototype",c=function(){var e,t=r(15)("iframe"),n=u.length;for(t.style.display="none",r(54).appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write(" - diff --git a/src/client/css/imerss-core.css b/src/client/css/imerss-core.css index 0434cc74..eb8906ab 100644 --- a/src/client/css/imerss-core.css +++ b/src/client/css/imerss-core.css @@ -421,6 +421,12 @@ cursor: pointer; width: 20px; height: 20px; + border-radius: 6px; +} + +.imerss-filter-clear:hover { + /** TODO consolidate these, e.g. imerss-reset-filter */ + background: #d0d7de33; } .imerss-filter-clear.imerss-hidden { diff --git a/src/client/js/new/polygon-draw.js b/src/client/js/new/polygon-draw.js index ae13c427..7beee371 100644 --- a/src/client/js/new/polygon-draw.js +++ b/src/client/js/new/polygon-draw.js @@ -7,7 +7,7 @@ You may obtain a copy of the ECL 2.0 License and BSD License at https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt */ -/* global MapboxDraw */ +/* global MapboxDraw, hortis */ "use strict"; diff --git a/src/copyBeasOut.js b/src/copyBeasOut.js new file mode 100644 index 00000000..3de30a67 --- /dev/null +++ b/src/copyBeasOut.js @@ -0,0 +1,68 @@ +/* eslint-env node */ + +"use strict"; + +const fs = require("fs-extra"), + path = require("path"), + fluid = require("infusion"); + +require("../index.js"); + +const config = { + target: "%b-team/docs/", + copyJobs: [ + { + source: "%imerss-bioinfo/docs/indexBeasOBA.html", + target: "%b-team/docs/index.html" + }, + "%imerss-bioinfo/docs/js/vizjs.js", + "%imerss-bioinfo/docs/js/bipartitePP.js", + + "%imerss-bioinfo/docs/css/imerss-viz-lib.css", + "%imerss-bioinfo/docs/css/imerss-viz-new-core.css", + "%imerss-bioinfo/docs/css/imerss-viz-new.css", + "%imerss-bioinfo/docs/css/imerss-bbea.css", + + "%imerss-bioinfo/docs/js/jquery.js", + "%imerss-bioinfo/docs/js/imerss-viz-lib.js", + "%imerss-bioinfo/docs/js/imerss-viz-new-core.js", + "%imerss-bioinfo/docs/js/imerss-viz-new.js", + "%imerss-bioinfo/docs/js/imerss-bbea.js", + + "%imerss-bioinfo/docs/img/x-circle-close.svg", + + "%imerss-bioinfo/docs/data/b-team/plant-pollinators-OBA-2-assigned-subset-labels.csv", + "%imerss-bioinfo/docs/data/b-team/plant-pollinators-OBA-2-assigned-taxa.csv", + "%imerss-bioinfo/docs/data/b-team/us-eco-l3-regions.csv" + ] +}; + +console.log(fluid.module.resolvePath("%imerss-bioinfo/")); + +const b_team = path.join(fluid.module.resolvePath("%imerss-bioinfo/"), "../b-team/"); + + +fluid.module.register("b-team", b_team, require); + +const copyOut = function () { + const defTarget = fluid.module.resolvePath(config.target); + const computeTarget = function (source) { + const dp = source.indexOf("/docs/"); + const stem = source.substring(dp + "/docs/".length); + return path.join(defTarget, stem); + }; + + config.copyJobs.forEach(oneJob => { + const job = typeof(oneJob) === "string" ? {source: oneJob} : oneJob; + const source = fluid.module.resolvePath(job.source); + const target = job.target ? fluid.module.resolvePath(job.target) : computeTarget(job.source); + + fs.ensureDirSync(path.dirname(target)); + fs.copySync(source, target); + + console.log("Copied ", source, " to ", target); + }); + +}; + +copyOut(); \ No newline at end of file